xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision 85bb5f1d)
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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 const char tcp_version[] = "%Z%%M%	%I%	%E% SMI";
30 
31 
32 #include <sys/types.h>
33 #include <sys/stream.h>
34 #include <sys/strsun.h>
35 #include <sys/strsubr.h>
36 #include <sys/stropts.h>
37 #include <sys/strlog.h>
38 #include <sys/strsun.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/timod.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/suntpi.h>
45 #include <sys/xti_inet.h>
46 #include <sys/cmn_err.h>
47 #include <sys/debug.h>
48 #include <sys/sdt.h>
49 #include <sys/vtrace.h>
50 #include <sys/kmem.h>
51 #include <sys/ethernet.h>
52 #include <sys/cpuvar.h>
53 #include <sys/dlpi.h>
54 #include <sys/multidata.h>
55 #include <sys/multidata_impl.h>
56 #include <sys/pattr.h>
57 #include <sys/policy.h>
58 #include <sys/priv.h>
59 #include <sys/zone.h>
60 #include <sys/sunldi.h>
61 
62 #include <sys/errno.h>
63 #include <sys/signal.h>
64 #include <sys/socket.h>
65 #include <sys/sockio.h>
66 #include <sys/isa_defs.h>
67 #include <sys/md5.h>
68 #include <sys/random.h>
69 #include <sys/sodirect.h>
70 #include <sys/uio.h>
71 #include <netinet/in.h>
72 #include <netinet/tcp.h>
73 #include <netinet/ip6.h>
74 #include <netinet/icmp6.h>
75 #include <net/if.h>
76 #include <net/route.h>
77 #include <inet/ipsec_impl.h>
78 
79 #include <inet/common.h>
80 #include <inet/ip.h>
81 #include <inet/ip_impl.h>
82 #include <inet/ip6.h>
83 #include <inet/ip_ndp.h>
84 #include <inet/mi.h>
85 #include <inet/mib2.h>
86 #include <inet/nd.h>
87 #include <inet/optcom.h>
88 #include <inet/snmpcom.h>
89 #include <inet/kstatcom.h>
90 #include <inet/tcp.h>
91 #include <inet/tcp_impl.h>
92 #include <net/pfkeyv2.h>
93 #include <inet/ipsec_info.h>
94 #include <inet/ipdrop.h>
95 #include <inet/tcp_trace.h>
96 
97 #include <inet/ipclassifier.h>
98 #include <inet/ip_ire.h>
99 #include <inet/ip_ftable.h>
100 #include <inet/ip_if.h>
101 #include <inet/ipp_common.h>
102 #include <inet/ip_netinfo.h>
103 #include <sys/squeue.h>
104 #include <inet/kssl/ksslapi.h>
105 #include <sys/tsol/label.h>
106 #include <sys/tsol/tnet.h>
107 #include <rpc/pmap_prot.h>
108 
109 /*
110  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
111  *
112  * (Read the detailed design doc in PSARC case directory)
113  *
114  * The entire tcp state is contained in tcp_t and conn_t structure
115  * which are allocated in tandem using ipcl_conn_create() and passing
116  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
117  * the references on the tcp_t. The tcp_t structure is never compressed
118  * and packets always land on the correct TCP perimeter from the time
119  * eager is created till the time tcp_t dies (as such the old mentat
120  * TCP global queue is not used for detached state and no IPSEC checking
121  * is required). The global queue is still allocated to send out resets
122  * for connection which have no listeners and IP directly calls
123  * tcp_xmit_listeners_reset() which does any policy check.
124  *
125  * Protection and Synchronisation mechanism:
126  *
127  * The tcp data structure does not use any kind of lock for protecting
128  * its state but instead uses 'squeues' for mutual exclusion from various
129  * read and write side threads. To access a tcp member, the thread should
130  * always be behind squeue (via squeue_enter, squeue_enter_nodrain, or
131  * squeue_fill). Since the squeues allow a direct function call, caller
132  * can pass any tcp function having prototype of edesc_t as argument
133  * (different from traditional STREAMs model where packets come in only
134  * designated entry points). The list of functions that can be directly
135  * called via squeue are listed before the usual function prototype.
136  *
137  * Referencing:
138  *
139  * TCP is MT-Hot and we use a reference based scheme to make sure that the
140  * tcp structure doesn't disappear when its needed. When the application
141  * creates an outgoing connection or accepts an incoming connection, we
142  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
143  * The IP reference is just a symbolic reference since ip_tcpclose()
144  * looks at tcp structure after tcp_close_output() returns which could
145  * have dropped the last TCP reference. So as long as the connection is
146  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
147  * conn_t. The classifier puts its own reference when the connection is
148  * inserted in listen or connected hash. Anytime a thread needs to enter
149  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
150  * on write side or by doing a classify on read side and then puts a
151  * reference on the conn before doing squeue_enter/tryenter/fill. For
152  * read side, the classifier itself puts the reference under fanout lock
153  * to make sure that tcp can't disappear before it gets processed. The
154  * squeue will drop this reference automatically so the called function
155  * doesn't have to do a DEC_REF.
156  *
157  * Opening a new connection:
158  *
159  * The outgoing connection open is pretty simple. tcp_open() does the
160  * work in creating the conn/tcp structure and initializing it. The
161  * squeue assignment is done based on the CPU the application
162  * is running on. So for outbound connections, processing is always done
163  * on application CPU which might be different from the incoming CPU
164  * being interrupted by the NIC. An optimal way would be to figure out
165  * the NIC <-> CPU binding at listen time, and assign the outgoing
166  * connection to the squeue attached to the CPU that will be interrupted
167  * for incoming packets (we know the NIC based on the bind IP address).
168  * This might seem like a problem if more data is going out but the
169  * fact is that in most cases the transmit is ACK driven transmit where
170  * the outgoing data normally sits on TCP's xmit queue waiting to be
171  * transmitted.
172  *
173  * Accepting a connection:
174  *
175  * This is a more interesting case because of various races involved in
176  * establishing a eager in its own perimeter. Read the meta comment on
177  * top of tcp_conn_request(). But briefly, the squeue is picked by
178  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
179  *
180  * Closing a connection:
181  *
182  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
183  * via squeue to do the close and mark the tcp as detached if the connection
184  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
185  * reference but tcp_close() drop IP's reference always. So if tcp was
186  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
187  * and 1 because it is in classifier's connected hash. This is the condition
188  * we use to determine that its OK to clean up the tcp outside of squeue
189  * when time wait expires (check the ref under fanout and conn_lock and
190  * if it is 2, remove it from fanout hash and kill it).
191  *
192  * Although close just drops the necessary references and marks the
193  * tcp_detached state, tcp_close needs to know the tcp_detached has been
194  * set (under squeue) before letting the STREAM go away (because a
195  * inbound packet might attempt to go up the STREAM while the close
196  * has happened and tcp_detached is not set). So a special lock and
197  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
198  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
199  * tcp_detached.
200  *
201  * Special provisions and fast paths:
202  *
203  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
204  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
205  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
206  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
207  * check to send packets directly to tcp_rput_data via squeue. Everyone
208  * else comes through tcp_input() on the read side.
209  *
210  * We also make special provisions for sockfs by marking tcp_issocket
211  * whenever we have only sockfs on top of TCP. This allows us to skip
212  * putting the tcp in acceptor hash since a sockfs listener can never
213  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
214  * since eager has already been allocated and the accept now happens
215  * on acceptor STREAM. There is a big blob of comment on top of
216  * tcp_conn_request explaining the new accept. When socket is POP'd,
217  * sockfs sends us an ioctl to mark the fact and we go back to old
218  * behaviour. Once tcp_issocket is unset, its never set for the
219  * life of that connection.
220  *
221  * In support of on-board asynchronous DMA hardware (e.g. Intel I/OAT)
222  * two consoldiation private KAPIs are used to enqueue M_DATA mblk_t's
223  * directly to the socket (sodirect) and start an asynchronous copyout
224  * to a user-land receive-side buffer (uioa) when a blocking socket read
225  * (e.g. read, recv, ...) is pending.
226  *
227  * This is accomplished when tcp_issocket is set and tcp_sodirect is not
228  * NULL so points to an sodirect_t and if marked enabled then we enqueue
229  * all mblk_t's directly to the socket.
230  *
231  * Further, if the sodirect_t sod_uioa and if marked enabled (due to a
232  * blocking socket read, e.g. user-land read, recv, ...) then an asynchronous
233  * copyout will be started directly to the user-land uio buffer. Also, as we
234  * have a pending read, TCP's push logic can take into account the number of
235  * bytes to be received and only awake the blocked read()er when the uioa_t
236  * byte count has been satisfied.
237  *
238  * IPsec notes :
239  *
240  * Since a packet is always executed on the correct TCP perimeter
241  * all IPsec processing is defered to IP including checking new
242  * connections and setting IPSEC policies for new connection. The
243  * only exception is tcp_xmit_listeners_reset() which is called
244  * directly from IP and needs to policy check to see if TH_RST
245  * can be sent out.
246  *
247  * PFHooks notes :
248  *
249  * For mdt case, one meta buffer contains multiple packets. Mblks for every
250  * packet are assembled and passed to the hooks. When packets are blocked,
251  * or boundary of any packet is changed, the mdt processing is stopped, and
252  * packets of the meta buffer are send to the IP path one by one.
253  */
254 
255 /*
256  * Values for squeue switch:
257  * 1: squeue_enter_nodrain
258  * 2: squeue_enter
259  * 3: squeue_fill
260  */
261 int tcp_squeue_close = 2;	/* Setable in /etc/system */
262 int tcp_squeue_wput = 2;
263 
264 squeue_func_t tcp_squeue_close_proc;
265 squeue_func_t tcp_squeue_wput_proc;
266 
267 /*
268  * Macros for sodirect:
269  *
270  * SOD_PTR_ENTER(tcp, sodp) - for the tcp_t pointer "tcp" set the
271  * sodirect_t pointer "sodp" to the socket/tcp shared sodirect_t
272  * if it exists and is enabled, else to NULL. Note, in the current
273  * sodirect implementation the sod_lock must not be held across any
274  * STREAMS call (e.g. putnext) else a "recursive mutex_enter" PANIC
275  * will result as sod_lock is the streamhead stdata.sd_lock.
276  *
277  * SOD_NOT_ENABLED(tcp) - return true if not a sodirect tcp_t or the
278  * sodirect_t isn't enabled, usefull for ASSERT()ing that a recieve
279  * side tcp code path dealing with a tcp_rcv_list or putnext() isn't
280  * being used when sodirect code paths should be.
281  */
282 
283 #define	SOD_PTR_ENTER(tcp, sodp)					\
284 	(sodp) = (tcp)->tcp_sodirect;					\
285 									\
286 	if ((sodp) != NULL) {						\
287 		mutex_enter((sodp)->sod_lock);				\
288 		if (!((sodp)->sod_state & SOD_ENABLED)) {		\
289 			mutex_exit((sodp)->sod_lock);			\
290 			(sodp) = NULL;					\
291 		}							\
292 	}
293 
294 #define	SOD_NOT_ENABLED(tcp)						\
295 	((tcp)->tcp_sodirect == NULL ||					\
296 	    !((tcp)->tcp_sodirect->sod_state & SOD_ENABLED))
297 
298 /*
299  * This controls how tiny a write must be before we try to copy it
300  * into the the mblk on the tail of the transmit queue.  Not much
301  * speedup is observed for values larger than sixteen.  Zero will
302  * disable the optimisation.
303  */
304 int tcp_tx_pull_len = 16;
305 
306 /*
307  * TCP Statistics.
308  *
309  * How TCP statistics work.
310  *
311  * There are two types of statistics invoked by two macros.
312  *
313  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
314  * supposed to be used in non MT-hot paths of the code.
315  *
316  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
317  * supposed to be used for DEBUG purposes and may be used on a hot path.
318  *
319  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
320  * (use "kstat tcp" to get them).
321  *
322  * There is also additional debugging facility that marks tcp_clean_death()
323  * instances and saves them in tcp_t structure. It is triggered by
324  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
325  * tcp_clean_death() calls that counts the number of times each tag was hit. It
326  * is triggered by TCP_CLD_COUNTERS define.
327  *
328  * How to add new counters.
329  *
330  * 1) Add a field in the tcp_stat structure describing your counter.
331  * 2) Add a line in the template in tcp_kstat2_init() with the name
332  *    of the counter.
333  *
334  *    IMPORTANT!! - make sure that both are in sync !!
335  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
336  *
337  * Please avoid using private counters which are not kstat-exported.
338  *
339  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
340  * in tcp_t structure.
341  *
342  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
343  */
344 
345 #ifndef TCP_DEBUG_COUNTER
346 #ifdef DEBUG
347 #define	TCP_DEBUG_COUNTER 1
348 #else
349 #define	TCP_DEBUG_COUNTER 0
350 #endif
351 #endif
352 
353 #define	TCP_CLD_COUNTERS 0
354 
355 #define	TCP_TAG_CLEAN_DEATH 1
356 #define	TCP_MAX_CLEAN_DEATH_TAG 32
357 
358 #ifdef lint
359 static int _lint_dummy_;
360 #endif
361 
362 #if TCP_CLD_COUNTERS
363 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
364 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
365 #elif defined(lint)
366 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
367 #else
368 #define	TCP_CLD_STAT(x)
369 #endif
370 
371 #if TCP_DEBUG_COUNTER
372 #define	TCP_DBGSTAT(tcps, x)	\
373 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
374 #define	TCP_G_DBGSTAT(x)	\
375 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
376 #elif defined(lint)
377 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
378 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
379 #else
380 #define	TCP_DBGSTAT(tcps, x)
381 #define	TCP_G_DBGSTAT(x)
382 #endif
383 
384 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
385 
386 tcp_g_stat_t	tcp_g_statistics;
387 kstat_t		*tcp_g_kstat;
388 
389 /*
390  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
391  * tcp write side.
392  */
393 #define	CALL_IP_WPUT(connp, q, mp) {					\
394 	tcp_stack_t	*tcps;						\
395 									\
396 	tcps = connp->conn_netstack->netstack_tcp;			\
397 	ASSERT(((q)->q_flag & QREADR) == 0);				\
398 	TCP_DBGSTAT(tcps, tcp_ip_output);				\
399 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
400 }
401 
402 /* Macros for timestamp comparisons */
403 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
404 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
405 
406 /*
407  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
408  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
409  * by adding three components: a time component which grows by 1 every 4096
410  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
411  * a per-connection component which grows by 125000 for every new connection;
412  * and an "extra" component that grows by a random amount centered
413  * approximately on 64000.  This causes the the ISS generator to cycle every
414  * 4.89 hours if no TCP connections are made, and faster if connections are
415  * made.
416  *
417  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
418  * components: a time component which grows by 250000 every second; and
419  * a per-connection component which grows by 125000 for every new connections.
420  *
421  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
422  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
423  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
424  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
425  * password.
426  */
427 #define	ISS_INCR	250000
428 #define	ISS_NSEC_SHT	12
429 
430 static sin_t	sin_null;	/* Zero address for quick clears */
431 static sin6_t	sin6_null;	/* Zero address for quick clears */
432 
433 /*
434  * This implementation follows the 4.3BSD interpretation of the urgent
435  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
436  * incompatible changes in protocols like telnet and rlogin.
437  */
438 #define	TCP_OLD_URP_INTERPRETATION	1
439 
440 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
441 	(TCP_IS_DETACHED(tcp) && \
442 	    (!(tcp)->tcp_hard_binding))
443 
444 /*
445  * TCP reassembly macros.  We hide starting and ending sequence numbers in
446  * b_next and b_prev of messages on the reassembly queue.  The messages are
447  * chained using b_cont.  These macros are used in tcp_reass() so we don't
448  * have to see the ugly casts and assignments.
449  */
450 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
451 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
452 					(mblk_t *)(uintptr_t)(u))
453 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
454 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
455 					(mblk_t *)(uintptr_t)(u))
456 
457 /*
458  * Implementation of TCP Timers.
459  * =============================
460  *
461  * INTERFACE:
462  *
463  * There are two basic functions dealing with tcp timers:
464  *
465  *	timeout_id_t	tcp_timeout(connp, func, time)
466  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
467  *	TCP_TIMER_RESTART(tcp, intvl)
468  *
469  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
470  * after 'time' ticks passed. The function called by timeout() must adhere to
471  * the same restrictions as a driver soft interrupt handler - it must not sleep
472  * or call other functions that might sleep. The value returned is the opaque
473  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
474  * cancel the request. The call to tcp_timeout() may fail in which case it
475  * returns zero. This is different from the timeout(9F) function which never
476  * fails.
477  *
478  * The call-back function 'func' always receives 'connp' as its single
479  * argument. It is always executed in the squeue corresponding to the tcp
480  * structure. The tcp structure is guaranteed to be present at the time the
481  * call-back is called.
482  *
483  * NOTE: The call-back function 'func' is never called if tcp is in
484  * 	the TCPS_CLOSED state.
485  *
486  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
487  * request. locks acquired by the call-back routine should not be held across
488  * the call to tcp_timeout_cancel() or a deadlock may result.
489  *
490  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
491  * Otherwise, it returns an integer value greater than or equal to 0. In
492  * particular, if the call-back function is already placed on the squeue, it can
493  * not be canceled.
494  *
495  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
496  * 	within squeue context corresponding to the tcp instance. Since the
497  *	call-back is also called via the same squeue, there are no race
498  *	conditions described in untimeout(9F) manual page since all calls are
499  *	strictly serialized.
500  *
501  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
502  *	stored in tcp_timer_tid and starts a new one using
503  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
504  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
505  *	field.
506  *
507  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
508  *	call-back may still be called, so it is possible tcp_timer() will be
509  *	called several times. This should not be a problem since tcp_timer()
510  *	should always check the tcp instance state.
511  *
512  *
513  * IMPLEMENTATION:
514  *
515  * TCP timers are implemented using three-stage process. The call to
516  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
517  * when the timer expires. The tcp_timer_callback() arranges the call of the
518  * tcp_timer_handler() function via squeue corresponding to the tcp
519  * instance. The tcp_timer_handler() calls actual requested timeout call-back
520  * and passes tcp instance as an argument to it. Information is passed between
521  * stages using the tcp_timer_t structure which contains the connp pointer, the
522  * tcp call-back to call and the timeout id returned by the timeout(9F).
523  *
524  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
525  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
526  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
527  * returns the pointer to this mblk.
528  *
529  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
530  * looks like a normal mblk without actual dblk attached to it.
531  *
532  * To optimize performance each tcp instance holds a small cache of timer
533  * mblocks. In the current implementation it caches up to two timer mblocks per
534  * tcp instance. The cache is preserved over tcp frees and is only freed when
535  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
536  * timer processing happens on a corresponding squeue, the cache manipulation
537  * does not require any locks. Experiments show that majority of timer mblocks
538  * allocations are satisfied from the tcp cache and do not involve kmem calls.
539  *
540  * The tcp_timeout() places a refhold on the connp instance which guarantees
541  * that it will be present at the time the call-back function fires. The
542  * tcp_timer_handler() drops the reference after calling the call-back, so the
543  * call-back function does not need to manipulate the references explicitly.
544  */
545 
546 typedef struct tcp_timer_s {
547 	conn_t	*connp;
548 	void 	(*tcpt_proc)(void *);
549 	timeout_id_t   tcpt_tid;
550 } tcp_timer_t;
551 
552 static kmem_cache_t *tcp_timercache;
553 kmem_cache_t	*tcp_sack_info_cache;
554 kmem_cache_t	*tcp_iphc_cache;
555 
556 /*
557  * For scalability, we must not run a timer for every TCP connection
558  * in TIME_WAIT state.  To see why, consider (for time wait interval of
559  * 4 minutes):
560  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
561  *
562  * This list is ordered by time, so you need only delete from the head
563  * until you get to entries which aren't old enough to delete yet.
564  * The list consists of only the detached TIME_WAIT connections.
565  *
566  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
567  * becomes detached TIME_WAIT (either by changing the state and already
568  * being detached or the other way around). This means that the TIME_WAIT
569  * state can be extended (up to doubled) if the connection doesn't become
570  * detached for a long time.
571  *
572  * The list manipulations (including tcp_time_wait_next/prev)
573  * are protected by the tcp_time_wait_lock. The content of the
574  * detached TIME_WAIT connections is protected by the normal perimeters.
575  *
576  * This list is per squeue and squeues are shared across the tcp_stack_t's.
577  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
578  * and conn_netstack.
579  * The tcp_t's that are added to tcp_free_list are disassociated and
580  * have NULL tcp_tcps and conn_netstack pointers.
581  */
582 typedef struct tcp_squeue_priv_s {
583 	kmutex_t	tcp_time_wait_lock;
584 	timeout_id_t	tcp_time_wait_tid;
585 	tcp_t		*tcp_time_wait_head;
586 	tcp_t		*tcp_time_wait_tail;
587 	tcp_t		*tcp_free_list;
588 	uint_t		tcp_free_list_cnt;
589 } tcp_squeue_priv_t;
590 
591 /*
592  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
593  * Running it every 5 seconds seems to give the best results.
594  */
595 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
596 
597 /*
598  * To prevent memory hog, limit the number of entries in tcp_free_list
599  * to 1% of available memory / number of cpus
600  */
601 uint_t tcp_free_list_max_cnt = 0;
602 
603 #define	TCP_XMIT_LOWATER	4096
604 #define	TCP_XMIT_HIWATER	49152
605 #define	TCP_RECV_LOWATER	2048
606 #define	TCP_RECV_HIWATER	49152
607 
608 /*
609  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
610  */
611 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
612 
613 #define	TIDUSZ	4096	/* transport interface data unit size */
614 
615 /*
616  * Bind hash list size and has function.  It has to be a power of 2 for
617  * hashing.
618  */
619 #define	TCP_BIND_FANOUT_SIZE	512
620 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
621 /*
622  * Size of listen and acceptor hash list.  It has to be a power of 2 for
623  * hashing.
624  */
625 #define	TCP_FANOUT_SIZE		256
626 
627 #ifdef	_ILP32
628 #define	TCP_ACCEPTOR_HASH(accid)					\
629 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
630 #else
631 #define	TCP_ACCEPTOR_HASH(accid)					\
632 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
633 #endif	/* _ILP32 */
634 
635 #define	IP_ADDR_CACHE_SIZE	2048
636 #define	IP_ADDR_CACHE_HASH(faddr)					\
637 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
638 
639 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
640 #define	TCP_HSP_HASH_SIZE 256
641 
642 #define	TCP_HSP_HASH(addr)					\
643 	(((addr>>24) ^ (addr >>16) ^			\
644 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
645 
646 /*
647  * TCP options struct returned from tcp_parse_options.
648  */
649 typedef struct tcp_opt_s {
650 	uint32_t	tcp_opt_mss;
651 	uint32_t	tcp_opt_wscale;
652 	uint32_t	tcp_opt_ts_val;
653 	uint32_t	tcp_opt_ts_ecr;
654 	tcp_t		*tcp;
655 } tcp_opt_t;
656 
657 /*
658  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
659  */
660 
661 #ifdef _BIG_ENDIAN
662 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
663 	(TCPOPT_TSTAMP << 8) | 10)
664 #else
665 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
666 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
667 #endif
668 
669 /*
670  * Flags returned from tcp_parse_options.
671  */
672 #define	TCP_OPT_MSS_PRESENT	1
673 #define	TCP_OPT_WSCALE_PRESENT	2
674 #define	TCP_OPT_TSTAMP_PRESENT	4
675 #define	TCP_OPT_SACK_OK_PRESENT	8
676 #define	TCP_OPT_SACK_PRESENT	16
677 
678 /* TCP option length */
679 #define	TCPOPT_NOP_LEN		1
680 #define	TCPOPT_MAXSEG_LEN	4
681 #define	TCPOPT_WS_LEN		3
682 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
683 #define	TCPOPT_TSTAMP_LEN	10
684 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
685 #define	TCPOPT_SACK_OK_LEN	2
686 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
687 #define	TCPOPT_REAL_SACK_LEN	4
688 #define	TCPOPT_MAX_SACK_LEN	36
689 #define	TCPOPT_HEADER_LEN	2
690 
691 /* TCP cwnd burst factor. */
692 #define	TCP_CWND_INFINITE	65535
693 #define	TCP_CWND_SS		3
694 #define	TCP_CWND_NORMAL		5
695 
696 /* Maximum TCP initial cwin (start/restart). */
697 #define	TCP_MAX_INIT_CWND	8
698 
699 /*
700  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
701  * either tcp_slow_start_initial or tcp_slow_start_after idle
702  * depending on the caller.  If the upper layer has not used the
703  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
704  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
705  * If the upper layer has changed set the tcp_init_cwnd, just use
706  * it to calculate the tcp_cwnd.
707  */
708 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
709 {									\
710 	if ((tcp)->tcp_init_cwnd == 0) {				\
711 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
712 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
713 	} else {							\
714 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
715 	}								\
716 	tcp->tcp_cwnd_cnt = 0;						\
717 }
718 
719 /* TCP Timer control structure */
720 typedef struct tcpt_s {
721 	pfv_t	tcpt_pfv;	/* The routine we are to call */
722 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
723 } tcpt_t;
724 
725 /* Host Specific Parameter structure */
726 typedef struct tcp_hsp {
727 	struct tcp_hsp	*tcp_hsp_next;
728 	in6_addr_t	tcp_hsp_addr_v6;
729 	in6_addr_t	tcp_hsp_subnet_v6;
730 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
731 	int32_t		tcp_hsp_sendspace;
732 	int32_t		tcp_hsp_recvspace;
733 	int32_t		tcp_hsp_tstamp;
734 } tcp_hsp_t;
735 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
736 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
737 
738 /*
739  * Functions called directly via squeue having a prototype of edesc_t.
740  */
741 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
742 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
743 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
744 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
745 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
746 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
747 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
748 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
749 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
750 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
751 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
752 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
753 
754 
755 /* Prototype for TCP functions */
756 static void	tcp_random_init(void);
757 int		tcp_random(void);
758 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
759 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
760 		    tcp_t *eager);
761 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
762 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
763     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
764     boolean_t user_specified);
765 static void	tcp_closei_local(tcp_t *tcp);
766 static void	tcp_close_detached(tcp_t *tcp);
767 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
768 			mblk_t *idmp, mblk_t **defermp);
769 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
770 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
771 		    in_port_t dstport, uint_t srcid);
772 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
773 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
774 		    uint32_t scope_id);
775 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
776 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
777 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
778 static char	*tcp_display(tcp_t *tcp, char *, char);
779 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
780 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
781 static void	tcp_eager_unlink(tcp_t *tcp);
782 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
783 		    int unixerr);
784 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
785 		    int tlierr, int unixerr);
786 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
787 		    cred_t *cr);
788 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
789 		    char *value, caddr_t cp, cred_t *cr);
790 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
791 		    char *value, caddr_t cp, cred_t *cr);
792 static int	tcp_tpistate(tcp_t *tcp);
793 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
794     int caller_holds_lock);
795 static void	tcp_bind_hash_remove(tcp_t *tcp);
796 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
797 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
798 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
799 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
800 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
801 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
802 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
803 void		tcp_g_q_setup(tcp_stack_t *);
804 void		tcp_g_q_create(tcp_stack_t *);
805 void		tcp_g_q_destroy(tcp_stack_t *);
806 static int	tcp_header_init_ipv4(tcp_t *tcp);
807 static int	tcp_header_init_ipv6(tcp_t *tcp);
808 int		tcp_init(tcp_t *tcp, queue_t *q);
809 static int	tcp_init_values(tcp_t *tcp);
810 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
811 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
812 		    t_scalar_t addr_length);
813 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
814 static void	tcp_ip_notify(tcp_t *tcp);
815 static mblk_t	*tcp_ire_mp(mblk_t *mp);
816 static void	tcp_iss_init(tcp_t *tcp);
817 static void	tcp_keepalive_killer(void *arg);
818 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
819 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
820 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
821 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
822 static boolean_t tcp_allow_connopt_set(int level, int name);
823 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
824 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
825 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
826 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
827 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
828 		    mblk_t *mblk);
829 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
830 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
831 		    uchar_t *ptr, uint_t len);
832 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
833 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
834     tcp_stack_t *);
835 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
836 		    caddr_t cp, cred_t *cr);
837 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
838 		    caddr_t cp, cred_t *cr);
839 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
840 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
841 		    caddr_t cp, cred_t *cr);
842 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
843 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
844 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
845 static void	tcp_reinit(tcp_t *tcp);
846 static void	tcp_reinit_values(tcp_t *tcp);
847 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
848 		    tcp_t *thisstream, cred_t *cr);
849 
850 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
851 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
852 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
853 static void	tcp_ss_rexmit(tcp_t *tcp);
854 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
855 static void	tcp_process_options(tcp_t *, tcph_t *);
856 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
857 static void	tcp_rsrv(queue_t *q);
858 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
859 static int	tcp_snmp_state(tcp_t *tcp);
860 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
861 		    cred_t *cr);
862 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
863 		    cred_t *cr);
864 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
865 		    cred_t *cr);
866 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
867 		    cred_t *cr);
868 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
869 		    cred_t *cr);
870 static int	tcp_host_param_set(queue_t *q, mblk_t *mp, char *value,
871 		    caddr_t cp, cred_t *cr);
872 static int	tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value,
873 		    caddr_t cp, cred_t *cr);
874 static int	tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp,
875 		    cred_t *cr);
876 static void	tcp_timer(void *arg);
877 static void	tcp_timer_callback(void *);
878 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
879     boolean_t random);
880 static in_port_t tcp_get_next_priv_port(const tcp_t *);
881 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
882 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
883 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
884 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
885 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
886 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
887 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
888 		    const int num_sack_blk, int *usable, uint_t *snxt,
889 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
890 		    const int mdt_thres);
891 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
892 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
893 		    const int num_sack_blk, int *usable, uint_t *snxt,
894 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
895 		    const int mdt_thres);
896 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
897 		    int num_sack_blk);
898 static void	tcp_wsrv(queue_t *q);
899 static int	tcp_xmit_end(tcp_t *tcp);
900 static void	tcp_ack_timer(void *arg);
901 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
902 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
903 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
904 		    zoneid_t zoneid, tcp_stack_t *, conn_t *connp);
905 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
906 		    uint32_t ack, int ctl);
907 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *);
908 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr, tcp_stack_t *);
909 static int	setmaxps(queue_t *q, int maxpsz);
910 static void	tcp_set_rto(tcp_t *, time_t);
911 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
912 		    boolean_t, boolean_t);
913 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
914 		    boolean_t ipsec_mctl);
915 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
916 		    char *opt, int optlen);
917 static int	tcp_build_hdrs(queue_t *, tcp_t *);
918 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
919 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
920 		    tcph_t *tcph);
921 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
922 boolean_t	tcp_reserved_port_add(int, in_port_t *, in_port_t *);
923 boolean_t	tcp_reserved_port_del(in_port_t, in_port_t);
924 boolean_t	tcp_reserved_port_check(in_port_t, tcp_stack_t *);
925 static tcp_t	*tcp_alloc_temp_tcp(in_port_t, tcp_stack_t *);
926 static int	tcp_reserved_port_list(queue_t *, mblk_t *, caddr_t, cred_t *);
927 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
928 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
929 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
930 		    const boolean_t, const uint32_t, const uint32_t,
931 		    const uint32_t, const uint32_t, tcp_stack_t *);
932 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
933 		    const uint_t, const uint_t, boolean_t *);
934 static mblk_t	*tcp_lso_info_mp(mblk_t *);
935 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
936 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
937 extern mblk_t	*tcp_timermp_alloc(int);
938 extern void	tcp_timermp_free(tcp_t *);
939 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
940 static void	tcp_stop_lingering(tcp_t *tcp);
941 static void	tcp_close_linger_timeout(void *arg);
942 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
943 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
944 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
945 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
946 static void	tcp_g_kstat_fini(kstat_t *);
947 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
948 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
949 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
950 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
951 static int	tcp_kstat_update(kstat_t *kp, int rw);
952 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
953 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
954 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
955 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
956 			tcph_t *tcph, mblk_t *idmp);
957 static squeue_func_t tcp_squeue_switch(int);
958 
959 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
960 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
961 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
962 static int	tcp_close(queue_t *, int);
963 static int	tcpclose_accept(queue_t *);
964 
965 static void	tcp_squeue_add(squeue_t *);
966 static boolean_t tcp_zcopy_check(tcp_t *);
967 static void	tcp_zcopy_notify(tcp_t *);
968 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
969 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
970 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
971 
972 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
973 
974 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
975 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
976 
977 /*
978  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
979  *
980  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
981  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
982  * (defined in tcp.h) needs to be filled in and passed into the kernel
983  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
984  * structure contains the four-tuple of a TCP connection and a range of TCP
985  * states (specified by ac_start and ac_end). The use of wildcard addresses
986  * and ports is allowed. Connections with a matching four tuple and a state
987  * within the specified range will be aborted. The valid states for the
988  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
989  * inclusive.
990  *
991  * An application which has its connection aborted by this ioctl will receive
992  * an error that is dependent on the connection state at the time of the abort.
993  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
994  * though a RST packet has been received.  If the connection state is equal to
995  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
996  * and all resources associated with the connection will be freed.
997  */
998 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
999 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
1000 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
1001 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
1002 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
1003 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
1004     boolean_t, tcp_stack_t *);
1005 
1006 static struct module_info tcp_rinfo =  {
1007 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
1008 };
1009 
1010 static struct module_info tcp_winfo =  {
1011 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
1012 };
1013 
1014 /*
1015  * Entry points for TCP as a device. The normal case which supports
1016  * the TCP functionality.
1017  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
1018  */
1019 struct qinit tcp_rinitv4 = {
1020 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_close, NULL, &tcp_rinfo
1021 };
1022 
1023 struct qinit tcp_rinitv6 = {
1024 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_close, NULL, &tcp_rinfo
1025 };
1026 
1027 struct qinit tcp_winit = {
1028 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1029 };
1030 
1031 /* Initial entry point for TCP in socket mode. */
1032 struct qinit tcp_sock_winit = {
1033 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1034 };
1035 
1036 /*
1037  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1038  * an accept. Avoid allocating data structures since eager has already
1039  * been created.
1040  */
1041 struct qinit tcp_acceptor_rinit = {
1042 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1043 };
1044 
1045 struct qinit tcp_acceptor_winit = {
1046 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1047 };
1048 
1049 /*
1050  * Entry points for TCP loopback (read side only)
1051  * The open routine is only used for reopens, thus no need to
1052  * have a separate one for tcp_openv6.
1053  */
1054 struct qinit tcp_loopback_rinit = {
1055 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_openv4, tcp_close, (pfi_t)0,
1056 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1057 };
1058 
1059 /* For AF_INET aka /dev/tcp */
1060 struct streamtab tcpinfov4 = {
1061 	&tcp_rinitv4, &tcp_winit
1062 };
1063 
1064 /* For AF_INET6 aka /dev/tcp6 */
1065 struct streamtab tcpinfov6 = {
1066 	&tcp_rinitv6, &tcp_winit
1067 };
1068 
1069 /*
1070  * Have to ensure that tcp_g_q_close is not done by an
1071  * interrupt thread.
1072  */
1073 static taskq_t *tcp_taskq;
1074 
1075 /*
1076  * TCP has a private interface for other kernel modules to reserve a
1077  * port range for them to use.  Once reserved, TCP will not use any ports
1078  * in the range.  This interface relies on the TCP_EXCLBIND feature.  If
1079  * the semantics of TCP_EXCLBIND is changed, implementation of this interface
1080  * has to be verified.
1081  *
1082  * There can be TCP_RESERVED_PORTS_ARRAY_MAX_SIZE port ranges.  Each port
1083  * range can cover at most TCP_RESERVED_PORTS_RANGE_MAX ports.  A port
1084  * range is [port a, port b] inclusive.  And each port range is between
1085  * TCP_LOWESET_RESERVED_PORT and TCP_LARGEST_RESERVED_PORT inclusive.
1086  *
1087  * Note that the default anonymous port range starts from 32768.  There is
1088  * no port "collision" between that and the reserved port range.  If there
1089  * is port collision (because the default smallest anonymous port is lowered
1090  * or some apps specifically bind to ports in the reserved port range), the
1091  * system may not be able to reserve a port range even there are enough
1092  * unbound ports as a reserved port range contains consecutive ports .
1093  */
1094 #define	TCP_RESERVED_PORTS_ARRAY_MAX_SIZE	5
1095 #define	TCP_RESERVED_PORTS_RANGE_MAX		1000
1096 #define	TCP_SMALLEST_RESERVED_PORT		10240
1097 #define	TCP_LARGEST_RESERVED_PORT		20480
1098 
1099 /* Structure to represent those reserved port ranges. */
1100 typedef struct tcp_rport_s {
1101 	in_port_t	lo_port;
1102 	in_port_t	hi_port;
1103 	tcp_t		**temp_tcp_array;
1104 } tcp_rport_t;
1105 
1106 /* Setable only in /etc/system. Move to ndd? */
1107 boolean_t tcp_icmp_source_quench = B_FALSE;
1108 
1109 /*
1110  * Following assumes TPI alignment requirements stay along 32 bit
1111  * boundaries
1112  */
1113 #define	ROUNDUP32(x) \
1114 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1115 
1116 /* Template for response to info request. */
1117 static struct T_info_ack tcp_g_t_info_ack = {
1118 	T_INFO_ACK,		/* PRIM_type */
1119 	0,			/* TSDU_size */
1120 	T_INFINITE,		/* ETSDU_size */
1121 	T_INVALID,		/* CDATA_size */
1122 	T_INVALID,		/* DDATA_size */
1123 	sizeof (sin_t),		/* ADDR_size */
1124 	0,			/* OPT_size - not initialized here */
1125 	TIDUSZ,			/* TIDU_size */
1126 	T_COTS_ORD,		/* SERV_type */
1127 	TCPS_IDLE,		/* CURRENT_state */
1128 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1129 };
1130 
1131 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1132 	T_INFO_ACK,		/* PRIM_type */
1133 	0,			/* TSDU_size */
1134 	T_INFINITE,		/* ETSDU_size */
1135 	T_INVALID,		/* CDATA_size */
1136 	T_INVALID,		/* DDATA_size */
1137 	sizeof (sin6_t),	/* ADDR_size */
1138 	0,			/* OPT_size - not initialized here */
1139 	TIDUSZ,		/* TIDU_size */
1140 	T_COTS_ORD,		/* SERV_type */
1141 	TCPS_IDLE,		/* CURRENT_state */
1142 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1143 };
1144 
1145 #define	MS	1L
1146 #define	SECONDS	(1000 * MS)
1147 #define	MINUTES	(60 * SECONDS)
1148 #define	HOURS	(60 * MINUTES)
1149 #define	DAYS	(24 * HOURS)
1150 
1151 #define	PARAM_MAX (~(uint32_t)0)
1152 
1153 /* Max size IP datagram is 64k - 1 */
1154 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1155 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1156 /* Max of the above */
1157 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1158 
1159 /* Largest TCP port number */
1160 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1161 
1162 /*
1163  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1164  * layer header.  It has to be a multiple of 4.
1165  */
1166 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1167 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1168 
1169 /*
1170  * All of these are alterable, within the min/max values given, at run time.
1171  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1172  * per the TCP spec.
1173  */
1174 /* BEGIN CSTYLED */
1175 static tcpparam_t	lcl_tcp_param_arr[] = {
1176  /*min		max		value		name */
1177  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1178  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1179  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1180  { 1,		1024,		1,		"tcp_conn_req_min" },
1181  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1182  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1183  { 0,		10,		0,		"tcp_debug" },
1184  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1185  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1186  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1187  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1188  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1189  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1190  { 1,		255,		64,		"tcp_ipv4_ttl"},
1191  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1192  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1193  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1194  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1195  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1196  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1197  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1198  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1199  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1200  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1201  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1202  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1203  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1204  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1205  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1206  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1207  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1208  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1209  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1210  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1211  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1212  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1213  { 0,		TCP_MSS_MAX,	64,		"tcp_co_min"},
1214  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1215 /*
1216  * Question:  What default value should I set for tcp_strong_iss?
1217  */
1218  { 0,		2,		1,		"tcp_strong_iss"},
1219  { 0,		65536,		20,		"tcp_rtt_updates"},
1220  { 0,		1,		1,		"tcp_wscale_always"},
1221  { 0,		1,		0,		"tcp_tstamp_always"},
1222  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1223  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1224  { 0,		16,		2,		"tcp_deferred_acks_max"},
1225  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1226  { 1,		4,		4,		"tcp_slow_start_initial"},
1227  { 10*MS,	50*MS,		20*MS,		"tcp_co_timer_interval"},
1228  { 0,		2,		2,		"tcp_sack_permitted"},
1229  { 0,		1,		0,		"tcp_trace"},
1230  { 0,		1,		1,		"tcp_compression_enabled"},
1231  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1232  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1233  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1234  { 0,		1,		0,		"tcp_rev_src_routes"},
1235  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1236  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1237  { 0,		16,		8,		"tcp_local_dacks_max"},
1238  { 0,		2,		1,		"tcp_ecn_permitted"},
1239  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1240  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1241  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1242  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1243  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1244 };
1245 /* END CSTYLED */
1246 
1247 /*
1248  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1249  * each header fragment in the header buffer.  Each parameter value has
1250  * to be a multiple of 4 (32-bit aligned).
1251  */
1252 static tcpparam_t lcl_tcp_mdt_head_param =
1253 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1254 static tcpparam_t lcl_tcp_mdt_tail_param =
1255 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1256 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1257 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1258 
1259 /*
1260  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1261  * the maximum number of payload buffers associated per Multidata.
1262  */
1263 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1264 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1265 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1266 
1267 /* Round up the value to the nearest mss. */
1268 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1269 
1270 /*
1271  * Set ECN capable transport (ECT) code point in IP header.
1272  *
1273  * Note that there are 2 ECT code points '01' and '10', which are called
1274  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1275  * point ECT(0) for TCP as described in RFC 2481.
1276  */
1277 #define	SET_ECT(tcp, iph) \
1278 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1279 		/* We need to clear the code point first. */ \
1280 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1281 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1282 	} else { \
1283 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1284 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1285 	}
1286 
1287 /*
1288  * The format argument to pass to tcp_display().
1289  * DISP_PORT_ONLY means that the returned string has only port info.
1290  * DISP_ADDR_AND_PORT means that the returned string also contains the
1291  * remote and local IP address.
1292  */
1293 #define	DISP_PORT_ONLY		1
1294 #define	DISP_ADDR_AND_PORT	2
1295 
1296 #define	NDD_TOO_QUICK_MSG \
1297 	"ndd get info rate too high for non-privileged users, try again " \
1298 	"later.\n"
1299 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1300 
1301 #define	IS_VMLOANED_MBLK(mp) \
1302 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1303 
1304 
1305 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1306 boolean_t tcp_mdt_chain = B_TRUE;
1307 
1308 /*
1309  * MDT threshold in the form of effective send MSS multiplier; we take
1310  * the MDT path if the amount of unsent data exceeds the threshold value
1311  * (default threshold is 1*SMSS).
1312  */
1313 uint_t tcp_mdt_smss_threshold = 1;
1314 
1315 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1316 
1317 /*
1318  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1319  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1320  * determined dynamically during tcp_adapt_ire(), which is the default.
1321  */
1322 boolean_t tcp_static_maxpsz = B_FALSE;
1323 
1324 /* Setable in /etc/system */
1325 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1326 uint32_t tcp_random_anon_port = 1;
1327 
1328 /*
1329  * To reach to an eager in Q0 which can be dropped due to an incoming
1330  * new SYN request when Q0 is full, a new doubly linked list is
1331  * introduced. This list allows to select an eager from Q0 in O(1) time.
1332  * This is needed to avoid spending too much time walking through the
1333  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1334  * this new list has to be a member of Q0.
1335  * This list is headed by listener's tcp_t. When the list is empty,
1336  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1337  * of listener's tcp_t point to listener's tcp_t itself.
1338  *
1339  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1340  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1341  * These macros do not affect the eager's membership to Q0.
1342  */
1343 
1344 
1345 #define	MAKE_DROPPABLE(listener, eager)					\
1346 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1347 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1348 		    = (eager);						\
1349 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1350 		(eager)->tcp_eager_next_drop_q0 =			\
1351 		    (listener)->tcp_eager_next_drop_q0;			\
1352 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1353 	}
1354 
1355 #define	MAKE_UNDROPPABLE(eager)						\
1356 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1357 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1358 		    = (eager)->tcp_eager_prev_drop_q0;			\
1359 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1360 		    = (eager)->tcp_eager_next_drop_q0;			\
1361 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1362 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1363 	}
1364 
1365 /*
1366  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1367  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1368  * data, TCP will not respond with an ACK.  RFC 793 requires that
1369  * TCP responds with an ACK for such a bogus ACK.  By not following
1370  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1371  * an attacker successfully spoofs an acceptable segment to our
1372  * peer; or when our peer is "confused."
1373  */
1374 uint32_t tcp_drop_ack_unsent_cnt = 10;
1375 
1376 /*
1377  * Hook functions to enable cluster networking
1378  * On non-clustered systems these vectors must always be NULL.
1379  */
1380 
1381 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1382 			    uint8_t *laddrp, in_port_t lport) = NULL;
1383 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1384 			    uint8_t *laddrp, in_port_t lport) = NULL;
1385 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1386 			    uint8_t *laddrp, in_port_t lport,
1387 			    uint8_t *faddrp, in_port_t fport) = NULL;
1388 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1389 			    uint8_t *laddrp, in_port_t lport,
1390 			    uint8_t *faddrp, in_port_t fport) = NULL;
1391 
1392 /*
1393  * The following are defined in ip.c
1394  */
1395 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1396 				uint8_t *laddrp);
1397 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1398 				uint8_t *laddrp, uint8_t *faddrp);
1399 
1400 #define	CL_INET_CONNECT(tcp)		{			\
1401 	if (cl_inet_connect != NULL) {				\
1402 		/*						\
1403 		 * Running in cluster mode - register active connection	\
1404 		 * information						\
1405 		 */							\
1406 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1407 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1408 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1409 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1410 				    (in_port_t)(tcp)->tcp_lport,	\
1411 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1412 				    (in_port_t)(tcp)->tcp_fport);	\
1413 			}						\
1414 		} else {						\
1415 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1416 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1417 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1418 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1419 				    (in_port_t)(tcp)->tcp_lport,	\
1420 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1421 				    (in_port_t)(tcp)->tcp_fport);	\
1422 			}						\
1423 		}							\
1424 	}								\
1425 }
1426 
1427 #define	CL_INET_DISCONNECT(tcp)	{				\
1428 	if (cl_inet_disconnect != NULL) {				\
1429 		/*							\
1430 		 * Running in cluster mode - deregister active		\
1431 		 * connection information				\
1432 		 */							\
1433 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1434 			if ((tcp)->tcp_ip_src != 0) {			\
1435 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1436 				    AF_INET,				\
1437 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1438 				    (in_port_t)(tcp)->tcp_lport,	\
1439 				    (uint8_t *)				\
1440 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1441 				    (in_port_t)(tcp)->tcp_fport);	\
1442 			}						\
1443 		} else {						\
1444 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1445 			    &(tcp)->tcp_ip_src_v6)) {			\
1446 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1447 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1448 				    (in_port_t)(tcp)->tcp_lport,	\
1449 				    (uint8_t *)				\
1450 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1451 				    (in_port_t)(tcp)->tcp_fport);	\
1452 			}						\
1453 		}							\
1454 	}								\
1455 }
1456 
1457 /*
1458  * Cluster networking hook for traversing current connection list.
1459  * This routine is used to extract the current list of live connections
1460  * which must continue to to be dispatched to this node.
1461  */
1462 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1463 
1464 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1465     void *arg, tcp_stack_t *tcps);
1466 
1467 #define	DTRACE_IP_FASTPATH(mp, iph, ill, ipha, ip6h) 			\
1468 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,	\
1469 	    iph, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha,		\
1470 	    ip6_t *, ip6h, int, 0);
1471 
1472 /*
1473  * Figure out the value of window scale opton.  Note that the rwnd is
1474  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1475  * We cannot find the scale value and then do a round up of tcp_rwnd
1476  * because the scale value may not be correct after that.
1477  *
1478  * Set the compiler flag to make this function inline.
1479  */
1480 static void
1481 tcp_set_ws_value(tcp_t *tcp)
1482 {
1483 	int i;
1484 	uint32_t rwnd = tcp->tcp_rwnd;
1485 
1486 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1487 	    i++, rwnd >>= 1)
1488 		;
1489 	tcp->tcp_rcv_ws = i;
1490 }
1491 
1492 /*
1493  * Remove a connection from the list of detached TIME_WAIT connections.
1494  * It returns B_FALSE if it can't remove the connection from the list
1495  * as the connection has already been removed from the list due to an
1496  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1497  */
1498 static boolean_t
1499 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1500 {
1501 	boolean_t	locked = B_FALSE;
1502 
1503 	if (tcp_time_wait == NULL) {
1504 		tcp_time_wait = *((tcp_squeue_priv_t **)
1505 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1506 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1507 		locked = B_TRUE;
1508 	} else {
1509 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1510 	}
1511 
1512 	if (tcp->tcp_time_wait_expire == 0) {
1513 		ASSERT(tcp->tcp_time_wait_next == NULL);
1514 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1515 		if (locked)
1516 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1517 		return (B_FALSE);
1518 	}
1519 	ASSERT(TCP_IS_DETACHED(tcp));
1520 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1521 
1522 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1523 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1524 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1525 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1526 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1527 			    NULL;
1528 		} else {
1529 			tcp_time_wait->tcp_time_wait_tail = NULL;
1530 		}
1531 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1532 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1533 		ASSERT(tcp->tcp_time_wait_next == NULL);
1534 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1535 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1536 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1537 	} else {
1538 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1539 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1540 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1541 		    tcp->tcp_time_wait_next;
1542 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1543 		    tcp->tcp_time_wait_prev;
1544 	}
1545 	tcp->tcp_time_wait_next = NULL;
1546 	tcp->tcp_time_wait_prev = NULL;
1547 	tcp->tcp_time_wait_expire = 0;
1548 
1549 	if (locked)
1550 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1551 	return (B_TRUE);
1552 }
1553 
1554 /*
1555  * Add a connection to the list of detached TIME_WAIT connections
1556  * and set its time to expire.
1557  */
1558 static void
1559 tcp_time_wait_append(tcp_t *tcp)
1560 {
1561 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1562 	tcp_squeue_priv_t *tcp_time_wait =
1563 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1564 	    SQPRIVATE_TCP));
1565 
1566 	tcp_timers_stop(tcp);
1567 
1568 	/* Freed above */
1569 	ASSERT(tcp->tcp_timer_tid == 0);
1570 	ASSERT(tcp->tcp_ack_tid == 0);
1571 
1572 	/* must have happened at the time of detaching the tcp */
1573 	ASSERT(tcp->tcp_ptpahn == NULL);
1574 	ASSERT(tcp->tcp_flow_stopped == 0);
1575 	ASSERT(tcp->tcp_time_wait_next == NULL);
1576 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1577 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1578 	ASSERT(tcp->tcp_listener == NULL);
1579 
1580 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1581 	/*
1582 	 * The value computed below in tcp->tcp_time_wait_expire may
1583 	 * appear negative or wrap around. That is ok since our
1584 	 * interest is only in the difference between the current lbolt
1585 	 * value and tcp->tcp_time_wait_expire. But the value should not
1586 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1587 	 * The corresponding comparison in tcp_time_wait_collector() uses
1588 	 * modular arithmetic.
1589 	 */
1590 	tcp->tcp_time_wait_expire +=
1591 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1592 	if (tcp->tcp_time_wait_expire == 0)
1593 		tcp->tcp_time_wait_expire = 1;
1594 
1595 	ASSERT(TCP_IS_DETACHED(tcp));
1596 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1597 	ASSERT(tcp->tcp_time_wait_next == NULL);
1598 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1599 	TCP_DBGSTAT(tcps, tcp_time_wait);
1600 
1601 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1602 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1603 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1604 		tcp_time_wait->tcp_time_wait_head = tcp;
1605 	} else {
1606 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1607 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1608 		    TCPS_TIME_WAIT);
1609 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1610 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1611 	}
1612 	tcp_time_wait->tcp_time_wait_tail = tcp;
1613 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1614 }
1615 
1616 /* ARGSUSED */
1617 void
1618 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1619 {
1620 	conn_t	*connp = (conn_t *)arg;
1621 	tcp_t	*tcp = connp->conn_tcp;
1622 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1623 
1624 	ASSERT(tcp != NULL);
1625 	if (tcp->tcp_state == TCPS_CLOSED) {
1626 		return;
1627 	}
1628 
1629 	ASSERT((tcp->tcp_family == AF_INET &&
1630 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1631 	    (tcp->tcp_family == AF_INET6 &&
1632 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1633 	    tcp->tcp_ipversion == IPV6_VERSION)));
1634 	ASSERT(!tcp->tcp_listener);
1635 
1636 	TCP_STAT(tcps, tcp_time_wait_reap);
1637 	ASSERT(TCP_IS_DETACHED(tcp));
1638 
1639 	/*
1640 	 * Because they have no upstream client to rebind or tcp_close()
1641 	 * them later, we axe the connection here and now.
1642 	 */
1643 	tcp_close_detached(tcp);
1644 }
1645 
1646 /*
1647  * Remove cached/latched IPsec references.
1648  */
1649 void
1650 tcp_ipsec_cleanup(tcp_t *tcp)
1651 {
1652 	conn_t		*connp = tcp->tcp_connp;
1653 
1654 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1655 
1656 	if (connp->conn_latch != NULL) {
1657 		IPLATCH_REFRELE(connp->conn_latch,
1658 		    connp->conn_netstack);
1659 		connp->conn_latch = NULL;
1660 	}
1661 	if (connp->conn_policy != NULL) {
1662 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1663 		connp->conn_policy = NULL;
1664 	}
1665 }
1666 
1667 /*
1668  * Cleaup before placing on free list.
1669  * Disassociate from the netstack/tcp_stack_t since the freelist
1670  * is per squeue and not per netstack.
1671  */
1672 void
1673 tcp_cleanup(tcp_t *tcp)
1674 {
1675 	mblk_t		*mp;
1676 	char		*tcp_iphc;
1677 	int		tcp_iphc_len;
1678 	int		tcp_hdr_grown;
1679 	tcp_sack_info_t	*tcp_sack_info;
1680 	conn_t		*connp = tcp->tcp_connp;
1681 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1682 	netstack_t	*ns = tcps->tcps_netstack;
1683 
1684 	tcp_bind_hash_remove(tcp);
1685 
1686 	/* Cleanup that which needs the netstack first */
1687 	tcp_ipsec_cleanup(tcp);
1688 
1689 	tcp_free(tcp);
1690 
1691 	/* Release any SSL context */
1692 	if (tcp->tcp_kssl_ent != NULL) {
1693 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1694 		tcp->tcp_kssl_ent = NULL;
1695 	}
1696 
1697 	if (tcp->tcp_kssl_ctx != NULL) {
1698 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1699 		tcp->tcp_kssl_ctx = NULL;
1700 	}
1701 	tcp->tcp_kssl_pending = B_FALSE;
1702 
1703 	conn_delete_ire(connp, NULL);
1704 
1705 	/*
1706 	 * Since we will bzero the entire structure, we need to
1707 	 * remove it and reinsert it in global hash list. We
1708 	 * know the walkers can't get to this conn because we
1709 	 * had set CONDEMNED flag earlier and checked reference
1710 	 * under conn_lock so walker won't pick it and when we
1711 	 * go the ipcl_globalhash_remove() below, no walker
1712 	 * can get to it.
1713 	 */
1714 	ipcl_globalhash_remove(connp);
1715 
1716 	/*
1717 	 * Now it is safe to decrement the reference counts.
1718 	 * This might be the last reference on the netstack and TCPS
1719 	 * in which case it will cause the tcp_g_q_close and
1720 	 * the freeing of the IP Instance.
1721 	 */
1722 	connp->conn_netstack = NULL;
1723 	netstack_rele(ns);
1724 	ASSERT(tcps != NULL);
1725 	tcp->tcp_tcps = NULL;
1726 	TCPS_REFRELE(tcps);
1727 
1728 	/* Save some state */
1729 	mp = tcp->tcp_timercache;
1730 
1731 	tcp_sack_info = tcp->tcp_sack_info;
1732 	tcp_iphc = tcp->tcp_iphc;
1733 	tcp_iphc_len = tcp->tcp_iphc_len;
1734 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1735 
1736 	if (connp->conn_cred != NULL) {
1737 		crfree(connp->conn_cred);
1738 		connp->conn_cred = NULL;
1739 	}
1740 	if (connp->conn_peercred != NULL) {
1741 		crfree(connp->conn_peercred);
1742 		connp->conn_peercred = NULL;
1743 	}
1744 	ipcl_conn_cleanup(connp);
1745 	connp->conn_flags = IPCL_TCPCONN;
1746 	bzero(tcp, sizeof (tcp_t));
1747 
1748 	/* restore the state */
1749 	tcp->tcp_timercache = mp;
1750 
1751 	tcp->tcp_sack_info = tcp_sack_info;
1752 	tcp->tcp_iphc = tcp_iphc;
1753 	tcp->tcp_iphc_len = tcp_iphc_len;
1754 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1755 
1756 	tcp->tcp_connp = connp;
1757 
1758 	ASSERT(connp->conn_tcp == tcp);
1759 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1760 	connp->conn_state_flags = CONN_INCIPIENT;
1761 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1762 	ASSERT(connp->conn_ref == 1);
1763 }
1764 
1765 /*
1766  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1767  * is done forwards from the head.
1768  * This walks all stack instances since
1769  * tcp_time_wait remains global across all stacks.
1770  */
1771 /* ARGSUSED */
1772 void
1773 tcp_time_wait_collector(void *arg)
1774 {
1775 	tcp_t *tcp;
1776 	clock_t now;
1777 	mblk_t *mp;
1778 	conn_t *connp;
1779 	kmutex_t *lock;
1780 	boolean_t removed;
1781 
1782 	squeue_t *sqp = (squeue_t *)arg;
1783 	tcp_squeue_priv_t *tcp_time_wait =
1784 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1785 
1786 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1787 	tcp_time_wait->tcp_time_wait_tid = 0;
1788 
1789 	if (tcp_time_wait->tcp_free_list != NULL &&
1790 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1791 		TCP_G_STAT(tcp_freelist_cleanup);
1792 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1793 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1794 			tcp->tcp_time_wait_next = NULL;
1795 			tcp_time_wait->tcp_free_list_cnt--;
1796 			ASSERT(tcp->tcp_tcps == NULL);
1797 			CONN_DEC_REF(tcp->tcp_connp);
1798 		}
1799 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1800 	}
1801 
1802 	/*
1803 	 * In order to reap time waits reliably, we should use a
1804 	 * source of time that is not adjustable by the user -- hence
1805 	 * the call to ddi_get_lbolt().
1806 	 */
1807 	now = ddi_get_lbolt();
1808 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1809 		/*
1810 		 * Compare times using modular arithmetic, since
1811 		 * lbolt can wrapover.
1812 		 */
1813 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1814 			break;
1815 		}
1816 
1817 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1818 		ASSERT(removed);
1819 
1820 		connp = tcp->tcp_connp;
1821 		ASSERT(connp->conn_fanout != NULL);
1822 		lock = &connp->conn_fanout->connf_lock;
1823 		/*
1824 		 * This is essentially a TW reclaim fast path optimization for
1825 		 * performance where the timewait collector checks under the
1826 		 * fanout lock (so that no one else can get access to the
1827 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1828 		 * the classifier hash list. If ref count is indeed 2, we can
1829 		 * just remove the conn under the fanout lock and avoid
1830 		 * cleaning up the conn under the squeue, provided that
1831 		 * clustering callbacks are not enabled. If clustering is
1832 		 * enabled, we need to make the clustering callback before
1833 		 * setting the CONDEMNED flag and after dropping all locks and
1834 		 * so we forego this optimization and fall back to the slow
1835 		 * path. Also please see the comments in tcp_closei_local
1836 		 * regarding the refcnt logic.
1837 		 *
1838 		 * Since we are holding the tcp_time_wait_lock, its better
1839 		 * not to block on the fanout_lock because other connections
1840 		 * can't add themselves to time_wait list. So we do a
1841 		 * tryenter instead of mutex_enter.
1842 		 */
1843 		if (mutex_tryenter(lock)) {
1844 			mutex_enter(&connp->conn_lock);
1845 			if ((connp->conn_ref == 2) &&
1846 			    (cl_inet_disconnect == NULL)) {
1847 				ipcl_hash_remove_locked(connp,
1848 				    connp->conn_fanout);
1849 				/*
1850 				 * Set the CONDEMNED flag now itself so that
1851 				 * the refcnt cannot increase due to any
1852 				 * walker. But we have still not cleaned up
1853 				 * conn_ire_cache. This is still ok since
1854 				 * we are going to clean it up in tcp_cleanup
1855 				 * immediately and any interface unplumb
1856 				 * thread will wait till the ire is blown away
1857 				 */
1858 				connp->conn_state_flags |= CONN_CONDEMNED;
1859 				mutex_exit(lock);
1860 				mutex_exit(&connp->conn_lock);
1861 				if (tcp_time_wait->tcp_free_list_cnt <
1862 				    tcp_free_list_max_cnt) {
1863 					/* Add to head of tcp_free_list */
1864 					mutex_exit(
1865 					    &tcp_time_wait->tcp_time_wait_lock);
1866 					tcp_cleanup(tcp);
1867 					ASSERT(connp->conn_latch == NULL);
1868 					ASSERT(connp->conn_policy == NULL);
1869 					ASSERT(tcp->tcp_tcps == NULL);
1870 					ASSERT(connp->conn_netstack == NULL);
1871 
1872 					mutex_enter(
1873 					    &tcp_time_wait->tcp_time_wait_lock);
1874 					tcp->tcp_time_wait_next =
1875 					    tcp_time_wait->tcp_free_list;
1876 					tcp_time_wait->tcp_free_list = tcp;
1877 					tcp_time_wait->tcp_free_list_cnt++;
1878 					continue;
1879 				} else {
1880 					/* Do not add to tcp_free_list */
1881 					mutex_exit(
1882 					    &tcp_time_wait->tcp_time_wait_lock);
1883 					tcp_bind_hash_remove(tcp);
1884 					conn_delete_ire(tcp->tcp_connp, NULL);
1885 					tcp_ipsec_cleanup(tcp);
1886 					CONN_DEC_REF(tcp->tcp_connp);
1887 				}
1888 			} else {
1889 				CONN_INC_REF_LOCKED(connp);
1890 				mutex_exit(lock);
1891 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1892 				mutex_exit(&connp->conn_lock);
1893 				/*
1894 				 * We can reuse the closemp here since conn has
1895 				 * detached (otherwise we wouldn't even be in
1896 				 * time_wait list). tcp_closemp_used can safely
1897 				 * be changed without taking a lock as no other
1898 				 * thread can concurrently access it at this
1899 				 * point in the connection lifecycle.
1900 				 */
1901 
1902 				if (tcp->tcp_closemp.b_prev == NULL)
1903 					tcp->tcp_closemp_used = B_TRUE;
1904 				else
1905 					cmn_err(CE_PANIC,
1906 					    "tcp_timewait_collector: "
1907 					    "concurrent use of tcp_closemp: "
1908 					    "connp %p tcp %p\n", (void *)connp,
1909 					    (void *)tcp);
1910 
1911 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1912 				mp = &tcp->tcp_closemp;
1913 				squeue_fill(connp->conn_sqp, mp,
1914 				    tcp_timewait_output, connp,
1915 				    SQTAG_TCP_TIMEWAIT);
1916 			}
1917 		} else {
1918 			mutex_enter(&connp->conn_lock);
1919 			CONN_INC_REF_LOCKED(connp);
1920 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1921 			mutex_exit(&connp->conn_lock);
1922 			/*
1923 			 * We can reuse the closemp here since conn has
1924 			 * detached (otherwise we wouldn't even be in
1925 			 * time_wait list). tcp_closemp_used can safely
1926 			 * be changed without taking a lock as no other
1927 			 * thread can concurrently access it at this
1928 			 * point in the connection lifecycle.
1929 			 */
1930 
1931 			if (tcp->tcp_closemp.b_prev == NULL)
1932 				tcp->tcp_closemp_used = B_TRUE;
1933 			else
1934 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1935 				    "concurrent use of tcp_closemp: "
1936 				    "connp %p tcp %p\n", (void *)connp,
1937 				    (void *)tcp);
1938 
1939 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1940 			mp = &tcp->tcp_closemp;
1941 			squeue_fill(connp->conn_sqp, mp,
1942 			    tcp_timewait_output, connp, 0);
1943 		}
1944 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1945 	}
1946 
1947 	if (tcp_time_wait->tcp_free_list != NULL)
1948 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1949 
1950 	tcp_time_wait->tcp_time_wait_tid =
1951 	    timeout(tcp_time_wait_collector, sqp, TCP_TIME_WAIT_DELAY);
1952 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1953 }
1954 /*
1955  * Reply to a clients T_CONN_RES TPI message. This function
1956  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1957  * on the acceptor STREAM and processed in tcp_wput_accept().
1958  * Read the block comment on top of tcp_conn_request().
1959  */
1960 static void
1961 tcp_accept(tcp_t *listener, mblk_t *mp)
1962 {
1963 	tcp_t	*acceptor;
1964 	tcp_t	*eager;
1965 	tcp_t   *tcp;
1966 	struct T_conn_res	*tcr;
1967 	t_uscalar_t	acceptor_id;
1968 	t_scalar_t	seqnum;
1969 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1970 	mblk_t	*ok_mp;
1971 	mblk_t	*mp1;
1972 	tcp_stack_t	*tcps = listener->tcp_tcps;
1973 
1974 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1975 		tcp_err_ack(listener, mp, TPROTO, 0);
1976 		return;
1977 	}
1978 	tcr = (struct T_conn_res *)mp->b_rptr;
1979 
1980 	/*
1981 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1982 	 * read side queue of the streams device underneath us i.e. the
1983 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1984 	 * look it up in the queue_hash.  Under LP64 it sends down the
1985 	 * minor_t of the accepting endpoint.
1986 	 *
1987 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1988 	 * fanout hash lock is held.
1989 	 * This prevents any thread from entering the acceptor queue from
1990 	 * below (since it has not been hard bound yet i.e. any inbound
1991 	 * packets will arrive on the listener or default tcp queue and
1992 	 * go through tcp_lookup).
1993 	 * The CONN_INC_REF will prevent the acceptor from closing.
1994 	 *
1995 	 * XXX It is still possible for a tli application to send down data
1996 	 * on the accepting stream while another thread calls t_accept.
1997 	 * This should not be a problem for well-behaved applications since
1998 	 * the T_OK_ACK is sent after the queue swapping is completed.
1999 	 *
2000 	 * If the accepting fd is the same as the listening fd, avoid
2001 	 * queue hash lookup since that will return an eager listener in a
2002 	 * already established state.
2003 	 */
2004 	acceptor_id = tcr->ACCEPTOR_id;
2005 	mutex_enter(&listener->tcp_eager_lock);
2006 	if (listener->tcp_acceptor_id == acceptor_id) {
2007 		eager = listener->tcp_eager_next_q;
2008 		/* only count how many T_CONN_INDs so don't count q0 */
2009 		if ((listener->tcp_conn_req_cnt_q != 1) ||
2010 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
2011 			mutex_exit(&listener->tcp_eager_lock);
2012 			tcp_err_ack(listener, mp, TBADF, 0);
2013 			return;
2014 		}
2015 		if (listener->tcp_conn_req_cnt_q0 != 0) {
2016 			/* Throw away all the eagers on q0. */
2017 			tcp_eager_cleanup(listener, 1);
2018 		}
2019 		if (listener->tcp_syn_defense) {
2020 			listener->tcp_syn_defense = B_FALSE;
2021 			if (listener->tcp_ip_addr_cache != NULL) {
2022 				kmem_free(listener->tcp_ip_addr_cache,
2023 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
2024 				listener->tcp_ip_addr_cache = NULL;
2025 			}
2026 		}
2027 		/*
2028 		 * Transfer tcp_conn_req_max to the eager so that when
2029 		 * a disconnect occurs we can revert the endpoint to the
2030 		 * listen state.
2031 		 */
2032 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
2033 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
2034 		/*
2035 		 * Get a reference on the acceptor just like the
2036 		 * tcp_acceptor_hash_lookup below.
2037 		 */
2038 		acceptor = listener;
2039 		CONN_INC_REF(acceptor->tcp_connp);
2040 	} else {
2041 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
2042 		if (acceptor == NULL) {
2043 			if (listener->tcp_debug) {
2044 				(void) strlog(TCP_MOD_ID, 0, 1,
2045 				    SL_ERROR|SL_TRACE,
2046 				    "tcp_accept: did not find acceptor 0x%x\n",
2047 				    acceptor_id);
2048 			}
2049 			mutex_exit(&listener->tcp_eager_lock);
2050 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2051 			return;
2052 		}
2053 		/*
2054 		 * Verify acceptor state. The acceptable states for an acceptor
2055 		 * include TCPS_IDLE and TCPS_BOUND.
2056 		 */
2057 		switch (acceptor->tcp_state) {
2058 		case TCPS_IDLE:
2059 			/* FALLTHRU */
2060 		case TCPS_BOUND:
2061 			break;
2062 		default:
2063 			CONN_DEC_REF(acceptor->tcp_connp);
2064 			mutex_exit(&listener->tcp_eager_lock);
2065 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2066 			return;
2067 		}
2068 	}
2069 
2070 	/* The listener must be in TCPS_LISTEN */
2071 	if (listener->tcp_state != TCPS_LISTEN) {
2072 		CONN_DEC_REF(acceptor->tcp_connp);
2073 		mutex_exit(&listener->tcp_eager_lock);
2074 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2075 		return;
2076 	}
2077 
2078 	/*
2079 	 * Rendezvous with an eager connection request packet hanging off
2080 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2081 	 * tcp structure when the connection packet arrived in
2082 	 * tcp_conn_request().
2083 	 */
2084 	seqnum = tcr->SEQ_number;
2085 	eager = listener;
2086 	do {
2087 		eager = eager->tcp_eager_next_q;
2088 		if (eager == NULL) {
2089 			CONN_DEC_REF(acceptor->tcp_connp);
2090 			mutex_exit(&listener->tcp_eager_lock);
2091 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2092 			return;
2093 		}
2094 	} while (eager->tcp_conn_req_seqnum != seqnum);
2095 	mutex_exit(&listener->tcp_eager_lock);
2096 
2097 	/*
2098 	 * At this point, both acceptor and listener have 2 ref
2099 	 * that they begin with. Acceptor has one additional ref
2100 	 * we placed in lookup while listener has 3 additional
2101 	 * ref for being behind the squeue (tcp_accept() is
2102 	 * done on listener's squeue); being in classifier hash;
2103 	 * and eager's ref on listener.
2104 	 */
2105 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2106 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2107 
2108 	/*
2109 	 * The eager at this point is set in its own squeue and
2110 	 * could easily have been killed (tcp_accept_finish will
2111 	 * deal with that) because of a TH_RST so we can only
2112 	 * ASSERT for a single ref.
2113 	 */
2114 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2115 
2116 	/* Pre allocate the stroptions mblk also */
2117 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2118 	if (opt_mp == NULL) {
2119 		CONN_DEC_REF(acceptor->tcp_connp);
2120 		CONN_DEC_REF(eager->tcp_connp);
2121 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2122 		return;
2123 	}
2124 	DB_TYPE(opt_mp) = M_SETOPTS;
2125 	opt_mp->b_wptr += sizeof (struct stroptions);
2126 
2127 	/*
2128 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2129 	 * from listener to acceptor. The message is chained on opt_mp
2130 	 * which will be sent onto eager's squeue.
2131 	 */
2132 	if (listener->tcp_bound_if != 0) {
2133 		/* allocate optmgmt req */
2134 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2135 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2136 		    sizeof (int));
2137 		if (mp1 != NULL)
2138 			linkb(opt_mp, mp1);
2139 	}
2140 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2141 		uint_t on = 1;
2142 
2143 		/* allocate optmgmt req */
2144 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2145 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2146 		if (mp1 != NULL)
2147 			linkb(opt_mp, mp1);
2148 	}
2149 
2150 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2151 	if ((mp1 = copymsg(mp)) == NULL) {
2152 		CONN_DEC_REF(acceptor->tcp_connp);
2153 		CONN_DEC_REF(eager->tcp_connp);
2154 		freemsg(opt_mp);
2155 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2156 		return;
2157 	}
2158 
2159 	tcr = (struct T_conn_res *)mp1->b_rptr;
2160 
2161 	/*
2162 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2163 	 * which allocates a larger mblk and appends the new
2164 	 * local address to the ok_ack.  The address is copied by
2165 	 * soaccept() for getsockname().
2166 	 */
2167 	{
2168 		int extra;
2169 
2170 		extra = (eager->tcp_family == AF_INET) ?
2171 		    sizeof (sin_t) : sizeof (sin6_t);
2172 
2173 		/*
2174 		 * Try to re-use mp, if possible.  Otherwise, allocate
2175 		 * an mblk and return it as ok_mp.  In any case, mp
2176 		 * is no longer usable upon return.
2177 		 */
2178 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2179 			CONN_DEC_REF(acceptor->tcp_connp);
2180 			CONN_DEC_REF(eager->tcp_connp);
2181 			freemsg(opt_mp);
2182 			/* Original mp has been freed by now, so use mp1 */
2183 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2184 			return;
2185 		}
2186 
2187 		mp = NULL;	/* We should never use mp after this point */
2188 
2189 		switch (extra) {
2190 		case sizeof (sin_t): {
2191 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2192 
2193 				ok_mp->b_wptr += extra;
2194 				sin->sin_family = AF_INET;
2195 				sin->sin_port = eager->tcp_lport;
2196 				sin->sin_addr.s_addr =
2197 				    eager->tcp_ipha->ipha_src;
2198 				break;
2199 			}
2200 		case sizeof (sin6_t): {
2201 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2202 
2203 				ok_mp->b_wptr += extra;
2204 				sin6->sin6_family = AF_INET6;
2205 				sin6->sin6_port = eager->tcp_lport;
2206 				if (eager->tcp_ipversion == IPV4_VERSION) {
2207 					sin6->sin6_flowinfo = 0;
2208 					IN6_IPADDR_TO_V4MAPPED(
2209 					    eager->tcp_ipha->ipha_src,
2210 					    &sin6->sin6_addr);
2211 				} else {
2212 					ASSERT(eager->tcp_ip6h != NULL);
2213 					sin6->sin6_flowinfo =
2214 					    eager->tcp_ip6h->ip6_vcf &
2215 					    ~IPV6_VERS_AND_FLOW_MASK;
2216 					sin6->sin6_addr =
2217 					    eager->tcp_ip6h->ip6_src;
2218 				}
2219 				sin6->sin6_scope_id = 0;
2220 				sin6->__sin6_src_id = 0;
2221 				break;
2222 			}
2223 		default:
2224 			break;
2225 		}
2226 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2227 	}
2228 
2229 	/*
2230 	 * If there are no options we know that the T_CONN_RES will
2231 	 * succeed. However, we can't send the T_OK_ACK upstream until
2232 	 * the tcp_accept_swap is done since it would be dangerous to
2233 	 * let the application start using the new fd prior to the swap.
2234 	 */
2235 	tcp_accept_swap(listener, acceptor, eager);
2236 
2237 	/*
2238 	 * tcp_accept_swap unlinks eager from listener but does not drop
2239 	 * the eager's reference on the listener.
2240 	 */
2241 	ASSERT(eager->tcp_listener == NULL);
2242 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2243 
2244 	/*
2245 	 * The eager is now associated with its own queue. Insert in
2246 	 * the hash so that the connection can be reused for a future
2247 	 * T_CONN_RES.
2248 	 */
2249 	tcp_acceptor_hash_insert(acceptor_id, eager);
2250 
2251 	/*
2252 	 * We now do the processing of options with T_CONN_RES.
2253 	 * We delay till now since we wanted to have queue to pass to
2254 	 * option processing routines that points back to the right
2255 	 * instance structure which does not happen until after
2256 	 * tcp_accept_swap().
2257 	 *
2258 	 * Note:
2259 	 * The sanity of the logic here assumes that whatever options
2260 	 * are appropriate to inherit from listner=>eager are done
2261 	 * before this point, and whatever were to be overridden (or not)
2262 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2263 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2264 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2265 	 * This may not be true at this point in time but can be fixed
2266 	 * independently. This option processing code starts with
2267 	 * the instantiated acceptor instance and the final queue at
2268 	 * this point.
2269 	 */
2270 
2271 	if (tcr->OPT_length != 0) {
2272 		/* Options to process */
2273 		int t_error = 0;
2274 		int sys_error = 0;
2275 		int do_disconnect = 0;
2276 
2277 		if (tcp_conprim_opt_process(eager, mp1,
2278 		    &do_disconnect, &t_error, &sys_error) < 0) {
2279 			eager->tcp_accept_error = 1;
2280 			if (do_disconnect) {
2281 				/*
2282 				 * An option failed which does not allow
2283 				 * connection to be accepted.
2284 				 *
2285 				 * We allow T_CONN_RES to succeed and
2286 				 * put a T_DISCON_IND on the eager queue.
2287 				 */
2288 				ASSERT(t_error == 0 && sys_error == 0);
2289 				eager->tcp_send_discon_ind = 1;
2290 			} else {
2291 				ASSERT(t_error != 0);
2292 				freemsg(ok_mp);
2293 				/*
2294 				 * Original mp was either freed or set
2295 				 * to ok_mp above, so use mp1 instead.
2296 				 */
2297 				tcp_err_ack(listener, mp1, t_error, sys_error);
2298 				goto finish;
2299 			}
2300 		}
2301 		/*
2302 		 * Most likely success in setting options (except if
2303 		 * eager->tcp_send_discon_ind set).
2304 		 * mp1 option buffer represented by OPT_length/offset
2305 		 * potentially modified and contains results of setting
2306 		 * options at this point
2307 		 */
2308 	}
2309 
2310 	/* We no longer need mp1, since all options processing has passed */
2311 	freemsg(mp1);
2312 
2313 	putnext(listener->tcp_rq, ok_mp);
2314 
2315 	mutex_enter(&listener->tcp_eager_lock);
2316 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2317 		tcp_t	*tail;
2318 		mblk_t	*conn_ind;
2319 
2320 		/*
2321 		 * This path should not be executed if listener and
2322 		 * acceptor streams are the same.
2323 		 */
2324 		ASSERT(listener != acceptor);
2325 
2326 		tcp = listener->tcp_eager_prev_q0;
2327 		/*
2328 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2329 		 * deferred T_conn_ind queue. We need to get to the head of
2330 		 * the queue in order to send up T_conn_ind the same order as
2331 		 * how the 3WHS is completed.
2332 		 */
2333 		while (tcp != listener) {
2334 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2335 				break;
2336 			else
2337 				tcp = tcp->tcp_eager_prev_q0;
2338 		}
2339 		ASSERT(tcp != listener);
2340 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2341 		ASSERT(conn_ind != NULL);
2342 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2343 
2344 		/* Move from q0 to q */
2345 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2346 		listener->tcp_conn_req_cnt_q0--;
2347 		listener->tcp_conn_req_cnt_q++;
2348 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2349 		    tcp->tcp_eager_prev_q0;
2350 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2351 		    tcp->tcp_eager_next_q0;
2352 		tcp->tcp_eager_prev_q0 = NULL;
2353 		tcp->tcp_eager_next_q0 = NULL;
2354 		tcp->tcp_conn_def_q0 = B_FALSE;
2355 
2356 		/* Make sure the tcp isn't in the list of droppables */
2357 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2358 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2359 
2360 		/*
2361 		 * Insert at end of the queue because sockfs sends
2362 		 * down T_CONN_RES in chronological order. Leaving
2363 		 * the older conn indications at front of the queue
2364 		 * helps reducing search time.
2365 		 */
2366 		tail = listener->tcp_eager_last_q;
2367 		if (tail != NULL)
2368 			tail->tcp_eager_next_q = tcp;
2369 		else
2370 			listener->tcp_eager_next_q = tcp;
2371 		listener->tcp_eager_last_q = tcp;
2372 		tcp->tcp_eager_next_q = NULL;
2373 		mutex_exit(&listener->tcp_eager_lock);
2374 		putnext(tcp->tcp_rq, conn_ind);
2375 	} else {
2376 		mutex_exit(&listener->tcp_eager_lock);
2377 	}
2378 
2379 	/*
2380 	 * Done with the acceptor - free it
2381 	 *
2382 	 * Note: from this point on, no access to listener should be made
2383 	 * as listener can be equal to acceptor.
2384 	 */
2385 finish:
2386 	ASSERT(acceptor->tcp_detached);
2387 	ASSERT(tcps->tcps_g_q != NULL);
2388 	acceptor->tcp_rq = tcps->tcps_g_q;
2389 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2390 	(void) tcp_clean_death(acceptor, 0, 2);
2391 	CONN_DEC_REF(acceptor->tcp_connp);
2392 
2393 	/*
2394 	 * In case we already received a FIN we have to make tcp_rput send
2395 	 * the ordrel_ind. This will also send up a window update if the window
2396 	 * has opened up.
2397 	 *
2398 	 * In the normal case of a successful connection acceptance
2399 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2400 	 * indication that this was just accepted. This tells tcp_rput to
2401 	 * pass up any data queued in tcp_rcv_list.
2402 	 *
2403 	 * In the fringe case where options sent with T_CONN_RES failed and
2404 	 * we required, we would be indicating a T_DISCON_IND to blow
2405 	 * away this connection.
2406 	 */
2407 
2408 	/*
2409 	 * XXX: we currently have a problem if XTI application closes the
2410 	 * acceptor stream in between. This problem exists in on10-gate also
2411 	 * and is well know but nothing can be done short of major rewrite
2412 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2413 	 * eager same squeue as listener (we can distinguish non socket
2414 	 * listeners at the time of handling a SYN in tcp_conn_request)
2415 	 * and do most of the work that tcp_accept_finish does here itself
2416 	 * and then get behind the acceptor squeue to access the acceptor
2417 	 * queue.
2418 	 */
2419 	/*
2420 	 * We already have a ref on tcp so no need to do one before squeue_fill
2421 	 */
2422 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
2423 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
2424 }
2425 
2426 /*
2427  * Swap information between the eager and acceptor for a TLI/XTI client.
2428  * The sockfs accept is done on the acceptor stream and control goes
2429  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2430  * called. In either case, both the eager and listener are in their own
2431  * perimeter (squeue) and the code has to deal with potential race.
2432  *
2433  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2434  */
2435 static void
2436 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2437 {
2438 	conn_t	*econnp, *aconnp;
2439 
2440 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2441 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2442 	ASSERT(!eager->tcp_hard_bound);
2443 	ASSERT(!TCP_IS_SOCKET(acceptor));
2444 	ASSERT(!TCP_IS_SOCKET(eager));
2445 	ASSERT(!TCP_IS_SOCKET(listener));
2446 
2447 	acceptor->tcp_detached = B_TRUE;
2448 	/*
2449 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2450 	 * the acceptor id.
2451 	 */
2452 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2453 
2454 	/* remove eager from listen list... */
2455 	mutex_enter(&listener->tcp_eager_lock);
2456 	tcp_eager_unlink(eager);
2457 	ASSERT(eager->tcp_eager_next_q == NULL &&
2458 	    eager->tcp_eager_last_q == NULL);
2459 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2460 	    eager->tcp_eager_prev_q0 == NULL);
2461 	mutex_exit(&listener->tcp_eager_lock);
2462 	eager->tcp_rq = acceptor->tcp_rq;
2463 	eager->tcp_wq = acceptor->tcp_wq;
2464 
2465 	econnp = eager->tcp_connp;
2466 	aconnp = acceptor->tcp_connp;
2467 
2468 	eager->tcp_rq->q_ptr = econnp;
2469 	eager->tcp_wq->q_ptr = econnp;
2470 
2471 	/*
2472 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2473 	 * which might be a different squeue from our peer TCP instance.
2474 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2475 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2476 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2477 	 * above reach global visibility prior to the clearing of tcp_detached.
2478 	 */
2479 	membar_producer();
2480 	eager->tcp_detached = B_FALSE;
2481 
2482 	ASSERT(eager->tcp_ack_tid == 0);
2483 
2484 	econnp->conn_dev = aconnp->conn_dev;
2485 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2486 	ASSERT(econnp->conn_minor_arena != NULL);
2487 	if (eager->tcp_cred != NULL)
2488 		crfree(eager->tcp_cred);
2489 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2490 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2491 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2492 
2493 	aconnp->conn_cred = NULL;
2494 
2495 	econnp->conn_zoneid = aconnp->conn_zoneid;
2496 	econnp->conn_allzones = aconnp->conn_allzones;
2497 
2498 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2499 	aconnp->conn_mac_exempt = B_FALSE;
2500 
2501 	ASSERT(aconnp->conn_peercred == NULL);
2502 
2503 	/* Do the IPC initialization */
2504 	CONN_INC_REF(econnp);
2505 
2506 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2507 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2508 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2509 
2510 	/* Done with old IPC. Drop its ref on its connp */
2511 	CONN_DEC_REF(aconnp);
2512 }
2513 
2514 
2515 /*
2516  * Adapt to the information, such as rtt and rtt_sd, provided from the
2517  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2518  *
2519  * Checks for multicast and broadcast destination address.
2520  * Returns zero on failure; non-zero if ok.
2521  *
2522  * Note that the MSS calculation here is based on the info given in
2523  * the IRE.  We do not do any calculation based on TCP options.  They
2524  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2525  * knows which options to use.
2526  *
2527  * Note on how TCP gets its parameters for a connection.
2528  *
2529  * When a tcp_t structure is allocated, it gets all the default parameters.
2530  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2531  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2532  * default.  But if there is an associated tcp_host_param, it will override
2533  * the metrics.
2534  *
2535  * An incoming SYN with a multicast or broadcast destination address, is dropped
2536  * in 1 of 2 places.
2537  *
2538  * 1. If the packet was received over the wire it is dropped in
2539  * ip_rput_process_broadcast()
2540  *
2541  * 2. If the packet was received through internal IP loopback, i.e. the packet
2542  * was generated and received on the same machine, it is dropped in
2543  * ip_wput_local()
2544  *
2545  * An incoming SYN with a multicast or broadcast source address is always
2546  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2547  * reject an attempt to connect to a broadcast or multicast (destination)
2548  * address.
2549  */
2550 static int
2551 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2552 {
2553 	tcp_hsp_t	*hsp;
2554 	ire_t		*ire;
2555 	ire_t		*sire = NULL;
2556 	iulp_t		*ire_uinfo = NULL;
2557 	uint32_t	mss_max;
2558 	uint32_t	mss;
2559 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2560 	conn_t		*connp = tcp->tcp_connp;
2561 	boolean_t	ire_cacheable = B_FALSE;
2562 	zoneid_t	zoneid = connp->conn_zoneid;
2563 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2564 	    MATCH_IRE_SECATTR;
2565 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2566 	ill_t		*ill = NULL;
2567 	boolean_t	incoming = (ire_mp == NULL);
2568 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2569 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2570 
2571 	ASSERT(connp->conn_ire_cache == NULL);
2572 
2573 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2574 
2575 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2576 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2577 			return (0);
2578 		}
2579 		/*
2580 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2581 		 * for the destination with the nexthop as gateway.
2582 		 * ire_ctable_lookup() is used because this particular
2583 		 * ire, if it exists, will be marked private.
2584 		 * If that is not available, use the interface ire
2585 		 * for the nexthop.
2586 		 *
2587 		 * TSol: tcp_update_label will detect label mismatches based
2588 		 * only on the destination's label, but that would not
2589 		 * detect label mismatches based on the security attributes
2590 		 * of routes or next hop gateway. Hence we need to pass the
2591 		 * label to ire_ftable_lookup below in order to locate the
2592 		 * right prefix (and/or) ire cache. Similarly we also need
2593 		 * pass the label to the ire_cache_lookup below to locate
2594 		 * the right ire that also matches on the label.
2595 		 */
2596 		if (tcp->tcp_connp->conn_nexthop_set) {
2597 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2598 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2599 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2600 			    ipst);
2601 			if (ire == NULL) {
2602 				ire = ire_ftable_lookup(
2603 				    tcp->tcp_connp->conn_nexthop_v4,
2604 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2605 				    tsl, match_flags, ipst);
2606 				if (ire == NULL)
2607 					return (0);
2608 			} else {
2609 				ire_uinfo = &ire->ire_uinfo;
2610 			}
2611 		} else {
2612 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2613 			    zoneid, tsl, ipst);
2614 			if (ire != NULL) {
2615 				ire_cacheable = B_TRUE;
2616 				ire_uinfo = (ire_mp != NULL) ?
2617 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2618 				    &ire->ire_uinfo;
2619 
2620 			} else {
2621 				if (ire_mp == NULL) {
2622 					ire = ire_ftable_lookup(
2623 					    tcp->tcp_connp->conn_rem,
2624 					    0, 0, 0, NULL, &sire, zoneid, 0,
2625 					    tsl, (MATCH_IRE_RECURSIVE |
2626 					    MATCH_IRE_DEFAULT), ipst);
2627 					if (ire == NULL)
2628 						return (0);
2629 					ire_uinfo = (sire != NULL) ?
2630 					    &sire->ire_uinfo :
2631 					    &ire->ire_uinfo;
2632 				} else {
2633 					ire = (ire_t *)ire_mp->b_rptr;
2634 					ire_uinfo =
2635 					    &((ire_t *)
2636 					    ire_mp->b_rptr)->ire_uinfo;
2637 				}
2638 			}
2639 		}
2640 		ASSERT(ire != NULL);
2641 
2642 		if ((ire->ire_src_addr == INADDR_ANY) ||
2643 		    (ire->ire_type & IRE_BROADCAST)) {
2644 			/*
2645 			 * ire->ire_mp is non null when ire_mp passed in is used
2646 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2647 			 */
2648 			if (ire->ire_mp == NULL)
2649 				ire_refrele(ire);
2650 			if (sire != NULL)
2651 				ire_refrele(sire);
2652 			return (0);
2653 		}
2654 
2655 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2656 			ipaddr_t src_addr;
2657 
2658 			/*
2659 			 * ip_bind_connected() has stored the correct source
2660 			 * address in conn_src.
2661 			 */
2662 			src_addr = tcp->tcp_connp->conn_src;
2663 			tcp->tcp_ipha->ipha_src = src_addr;
2664 			/*
2665 			 * Copy of the src addr. in tcp_t is needed
2666 			 * for the lookup funcs.
2667 			 */
2668 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2669 		}
2670 		/*
2671 		 * Set the fragment bit so that IP will tell us if the MTU
2672 		 * should change. IP tells us the latest setting of
2673 		 * ip_path_mtu_discovery through ire_frag_flag.
2674 		 */
2675 		if (ipst->ips_ip_path_mtu_discovery) {
2676 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2677 			    htons(IPH_DF);
2678 		}
2679 		/*
2680 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2681 		 * for IP_NEXTHOP. No cache ire has been found for the
2682 		 * destination and we are working with the nexthop's
2683 		 * interface ire. Since we need to forward all packets
2684 		 * to the nexthop first, we "blindly" set tcp_localnet
2685 		 * to false, eventhough the destination may also be
2686 		 * onlink.
2687 		 */
2688 		if (ire_uinfo == NULL)
2689 			tcp->tcp_localnet = 0;
2690 		else
2691 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2692 	} else {
2693 		/*
2694 		 * For incoming connection ire_mp = NULL
2695 		 * For outgoing connection ire_mp != NULL
2696 		 * Technically we should check conn_incoming_ill
2697 		 * when ire_mp is NULL and conn_outgoing_ill when
2698 		 * ire_mp is non-NULL. But this is performance
2699 		 * critical path and for IPV*_BOUND_IF, outgoing
2700 		 * and incoming ill are always set to the same value.
2701 		 */
2702 		ill_t	*dst_ill = NULL;
2703 		ipif_t  *dst_ipif = NULL;
2704 
2705 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2706 
2707 		if (connp->conn_outgoing_ill != NULL) {
2708 			/* Outgoing or incoming path */
2709 			int   err;
2710 
2711 			dst_ill = conn_get_held_ill(connp,
2712 			    &connp->conn_outgoing_ill, &err);
2713 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2714 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2715 				return (0);
2716 			}
2717 			match_flags |= MATCH_IRE_ILL;
2718 			dst_ipif = dst_ill->ill_ipif;
2719 		}
2720 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2721 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2722 
2723 		if (ire != NULL) {
2724 			ire_cacheable = B_TRUE;
2725 			ire_uinfo = (ire_mp != NULL) ?
2726 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2727 			    &ire->ire_uinfo;
2728 		} else {
2729 			if (ire_mp == NULL) {
2730 				ire = ire_ftable_lookup_v6(
2731 				    &tcp->tcp_connp->conn_remv6,
2732 				    0, 0, 0, dst_ipif, &sire, zoneid,
2733 				    0, tsl, match_flags, ipst);
2734 				if (ire == NULL) {
2735 					if (dst_ill != NULL)
2736 						ill_refrele(dst_ill);
2737 					return (0);
2738 				}
2739 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2740 				    &ire->ire_uinfo;
2741 			} else {
2742 				ire = (ire_t *)ire_mp->b_rptr;
2743 				ire_uinfo =
2744 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2745 			}
2746 		}
2747 		if (dst_ill != NULL)
2748 			ill_refrele(dst_ill);
2749 
2750 		ASSERT(ire != NULL);
2751 		ASSERT(ire_uinfo != NULL);
2752 
2753 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2754 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2755 			/*
2756 			 * ire->ire_mp is non null when ire_mp passed in is used
2757 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2758 			 */
2759 			if (ire->ire_mp == NULL)
2760 				ire_refrele(ire);
2761 			if (sire != NULL)
2762 				ire_refrele(sire);
2763 			return (0);
2764 		}
2765 
2766 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2767 			in6_addr_t	src_addr;
2768 
2769 			/*
2770 			 * ip_bind_connected_v6() has stored the correct source
2771 			 * address per IPv6 addr. selection policy in
2772 			 * conn_src_v6.
2773 			 */
2774 			src_addr = tcp->tcp_connp->conn_srcv6;
2775 
2776 			tcp->tcp_ip6h->ip6_src = src_addr;
2777 			/*
2778 			 * Copy of the src addr. in tcp_t is needed
2779 			 * for the lookup funcs.
2780 			 */
2781 			tcp->tcp_ip_src_v6 = src_addr;
2782 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2783 			    &connp->conn_srcv6));
2784 		}
2785 		tcp->tcp_localnet =
2786 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2787 	}
2788 
2789 	/*
2790 	 * This allows applications to fail quickly when connections are made
2791 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2792 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2793 	 */
2794 	if ((ire->ire_flags & RTF_REJECT) &&
2795 	    (ire->ire_flags & RTF_PRIVATE))
2796 		goto error;
2797 
2798 	/*
2799 	 * Make use of the cached rtt and rtt_sd values to calculate the
2800 	 * initial RTO.  Note that they are already initialized in
2801 	 * tcp_init_values().
2802 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2803 	 * IP_NEXTHOP, but instead are using the interface ire for the
2804 	 * nexthop, then we do not use the ire_uinfo from that ire to
2805 	 * do any initializations.
2806 	 */
2807 	if (ire_uinfo != NULL) {
2808 		if (ire_uinfo->iulp_rtt != 0) {
2809 			clock_t	rto;
2810 
2811 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2812 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2813 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2814 			    tcps->tcps_rexmit_interval_extra +
2815 			    (tcp->tcp_rtt_sa >> 5);
2816 
2817 			if (rto > tcps->tcps_rexmit_interval_max) {
2818 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2819 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2820 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2821 			} else {
2822 				tcp->tcp_rto = rto;
2823 			}
2824 		}
2825 		if (ire_uinfo->iulp_ssthresh != 0)
2826 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2827 		else
2828 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2829 		if (ire_uinfo->iulp_spipe > 0) {
2830 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2831 			    tcps->tcps_max_buf);
2832 			if (tcps->tcps_snd_lowat_fraction != 0)
2833 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2834 				    tcps->tcps_snd_lowat_fraction;
2835 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2836 		}
2837 		/*
2838 		 * Note that up till now, acceptor always inherits receive
2839 		 * window from the listener.  But if there is a metrics
2840 		 * associated with a host, we should use that instead of
2841 		 * inheriting it from listener. Thus we need to pass this
2842 		 * info back to the caller.
2843 		 */
2844 		if (ire_uinfo->iulp_rpipe > 0) {
2845 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2846 			    tcps->tcps_max_buf);
2847 		}
2848 
2849 		if (ire_uinfo->iulp_rtomax > 0) {
2850 			tcp->tcp_second_timer_threshold =
2851 			    ire_uinfo->iulp_rtomax;
2852 		}
2853 
2854 		/*
2855 		 * Use the metric option settings, iulp_tstamp_ok and
2856 		 * iulp_wscale_ok, only for active open. What this means
2857 		 * is that if the other side uses timestamp or window
2858 		 * scale option, TCP will also use those options. That
2859 		 * is for passive open.  If the application sets a
2860 		 * large window, window scale is enabled regardless of
2861 		 * the value in iulp_wscale_ok.  This is the behavior
2862 		 * since 2.6.  So we keep it.
2863 		 * The only case left in passive open processing is the
2864 		 * check for SACK.
2865 		 * For ECN, it should probably be like SACK.  But the
2866 		 * current value is binary, so we treat it like the other
2867 		 * cases.  The metric only controls active open.For passive
2868 		 * open, the ndd param, tcp_ecn_permitted, controls the
2869 		 * behavior.
2870 		 */
2871 		if (!tcp_detached) {
2872 			/*
2873 			 * The if check means that the following can only
2874 			 * be turned on by the metrics only IRE, but not off.
2875 			 */
2876 			if (ire_uinfo->iulp_tstamp_ok)
2877 				tcp->tcp_snd_ts_ok = B_TRUE;
2878 			if (ire_uinfo->iulp_wscale_ok)
2879 				tcp->tcp_snd_ws_ok = B_TRUE;
2880 			if (ire_uinfo->iulp_sack == 2)
2881 				tcp->tcp_snd_sack_ok = B_TRUE;
2882 			if (ire_uinfo->iulp_ecn_ok)
2883 				tcp->tcp_ecn_ok = B_TRUE;
2884 		} else {
2885 			/*
2886 			 * Passive open.
2887 			 *
2888 			 * As above, the if check means that SACK can only be
2889 			 * turned on by the metric only IRE.
2890 			 */
2891 			if (ire_uinfo->iulp_sack > 0) {
2892 				tcp->tcp_snd_sack_ok = B_TRUE;
2893 			}
2894 		}
2895 	}
2896 
2897 
2898 	/*
2899 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2900 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2901 	 * length of all those options exceeds 28 bytes.  But because
2902 	 * of the tcp_mss_min check below, we may not have a problem if
2903 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2904 	 * the negative problem still exists.  And the check defeats PMTUd.
2905 	 * In fact, if PMTUd finds that the MSS should be smaller than
2906 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2907 	 * value.
2908 	 *
2909 	 * We do not deal with that now.  All those problems related to
2910 	 * PMTUd will be fixed later.
2911 	 */
2912 	ASSERT(ire->ire_max_frag != 0);
2913 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2914 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2915 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2916 			mss = MIN(mss, IPV6_MIN_MTU);
2917 		}
2918 	}
2919 
2920 	/* Sanity check for MSS value. */
2921 	if (tcp->tcp_ipversion == IPV4_VERSION)
2922 		mss_max = tcps->tcps_mss_max_ipv4;
2923 	else
2924 		mss_max = tcps->tcps_mss_max_ipv6;
2925 
2926 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2927 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2928 		/*
2929 		 * After receiving an ICMPv6 "packet too big" message with a
2930 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2931 		 * will insert a 8-byte fragment header in every packet; we
2932 		 * reduce the MSS by that amount here.
2933 		 */
2934 		mss -= sizeof (ip6_frag_t);
2935 	}
2936 
2937 	if (tcp->tcp_ipsec_overhead == 0)
2938 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2939 
2940 	mss -= tcp->tcp_ipsec_overhead;
2941 
2942 	if (mss < tcps->tcps_mss_min)
2943 		mss = tcps->tcps_mss_min;
2944 	if (mss > mss_max)
2945 		mss = mss_max;
2946 
2947 	/* Note that this is the maximum MSS, excluding all options. */
2948 	tcp->tcp_mss = mss;
2949 
2950 	/*
2951 	 * Initialize the ISS here now that we have the full connection ID.
2952 	 * The RFC 1948 method of initial sequence number generation requires
2953 	 * knowledge of the full connection ID before setting the ISS.
2954 	 */
2955 
2956 	tcp_iss_init(tcp);
2957 
2958 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2959 		tcp->tcp_loopback = B_TRUE;
2960 
2961 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2962 		hsp = tcp_hsp_lookup(tcp->tcp_remote, tcps);
2963 	} else {
2964 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6, tcps);
2965 	}
2966 
2967 	if (hsp != NULL) {
2968 		/* Only modify if we're going to make them bigger */
2969 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2970 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2971 			if (tcps->tcps_snd_lowat_fraction != 0)
2972 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2973 				    tcps->tcps_snd_lowat_fraction;
2974 		}
2975 
2976 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2977 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2978 		}
2979 
2980 		/* Copy timestamp flag only for active open */
2981 		if (!tcp_detached)
2982 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2983 	}
2984 
2985 	if (sire != NULL)
2986 		IRE_REFRELE(sire);
2987 
2988 	/*
2989 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2990 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2991 	 */
2992 	if (tcp->tcp_loopback ||
2993 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2994 		/*
2995 		 * For incoming, see if this tcp may be MDT-capable.  For
2996 		 * outgoing, this process has been taken care of through
2997 		 * tcp_rput_other.
2998 		 */
2999 		tcp_ire_ill_check(tcp, ire, ill, incoming);
3000 		tcp->tcp_ire_ill_check_done = B_TRUE;
3001 	}
3002 
3003 	mutex_enter(&connp->conn_lock);
3004 	/*
3005 	 * Make sure that conn is not marked incipient
3006 	 * for incoming connections. A blind
3007 	 * removal of incipient flag is cheaper than
3008 	 * check and removal.
3009 	 */
3010 	connp->conn_state_flags &= ~CONN_INCIPIENT;
3011 
3012 	/*
3013 	 * Must not cache forwarding table routes
3014 	 * or recache an IRE after the conn_t has
3015 	 * had conn_ire_cache cleared and is flagged
3016 	 * unusable, (see the CONN_CACHE_IRE() macro).
3017 	 */
3018 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
3019 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
3020 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
3021 			connp->conn_ire_cache = ire;
3022 			IRE_UNTRACE_REF(ire);
3023 			rw_exit(&ire->ire_bucket->irb_lock);
3024 			mutex_exit(&connp->conn_lock);
3025 			return (1);
3026 		}
3027 		rw_exit(&ire->ire_bucket->irb_lock);
3028 	}
3029 	mutex_exit(&connp->conn_lock);
3030 
3031 	if (ire->ire_mp == NULL)
3032 		ire_refrele(ire);
3033 	return (1);
3034 
3035 error:
3036 	if (ire->ire_mp == NULL)
3037 		ire_refrele(ire);
3038 	if (sire != NULL)
3039 		ire_refrele(sire);
3040 	return (0);
3041 }
3042 
3043 /*
3044  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
3045  * O_T_BIND_REQ/T_BIND_REQ message.
3046  */
3047 static void
3048 tcp_bind(tcp_t *tcp, mblk_t *mp)
3049 {
3050 	sin_t	*sin;
3051 	sin6_t	*sin6;
3052 	mblk_t	*mp1;
3053 	in_port_t requested_port;
3054 	in_port_t allocated_port;
3055 	struct T_bind_req *tbr;
3056 	boolean_t	bind_to_req_port_only;
3057 	boolean_t	backlog_update = B_FALSE;
3058 	boolean_t	user_specified;
3059 	in6_addr_t	v6addr;
3060 	ipaddr_t	v4addr;
3061 	uint_t	origipversion;
3062 	int	err;
3063 	queue_t *q = tcp->tcp_wq;
3064 	conn_t	*connp = tcp->tcp_connp;
3065 	mlp_type_t addrtype, mlptype;
3066 	zone_t	*zone;
3067 	cred_t	*cr;
3068 	in_port_t mlp_port;
3069 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3070 
3071 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3072 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3073 		if (tcp->tcp_debug) {
3074 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3075 			    "tcp_bind: bad req, len %u",
3076 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3077 		}
3078 		tcp_err_ack(tcp, mp, TPROTO, 0);
3079 		return;
3080 	}
3081 	/* Make sure the largest address fits */
3082 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3083 	if (mp1 == NULL) {
3084 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3085 		return;
3086 	}
3087 	mp = mp1;
3088 	tbr = (struct T_bind_req *)mp->b_rptr;
3089 	if (tcp->tcp_state >= TCPS_BOUND) {
3090 		if ((tcp->tcp_state == TCPS_BOUND ||
3091 		    tcp->tcp_state == TCPS_LISTEN) &&
3092 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
3093 		    tbr->CONIND_number > 0) {
3094 			/*
3095 			 * Handle listen() increasing CONIND_number.
3096 			 * This is more "liberal" then what the TPI spec
3097 			 * requires but is needed to avoid a t_unbind
3098 			 * when handling listen() since the port number
3099 			 * might be "stolen" between the unbind and bind.
3100 			 */
3101 			backlog_update = B_TRUE;
3102 			goto do_bind;
3103 		}
3104 		if (tcp->tcp_debug) {
3105 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3106 			    "tcp_bind: bad state, %d", tcp->tcp_state);
3107 		}
3108 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
3109 		return;
3110 	}
3111 	origipversion = tcp->tcp_ipversion;
3112 
3113 	switch (tbr->ADDR_length) {
3114 	case 0:			/* request for a generic port */
3115 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3116 		if (tcp->tcp_family == AF_INET) {
3117 			tbr->ADDR_length = sizeof (sin_t);
3118 			sin = (sin_t *)&tbr[1];
3119 			*sin = sin_null;
3120 			sin->sin_family = AF_INET;
3121 			mp->b_wptr = (uchar_t *)&sin[1];
3122 			tcp->tcp_ipversion = IPV4_VERSION;
3123 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
3124 		} else {
3125 			ASSERT(tcp->tcp_family == AF_INET6);
3126 			tbr->ADDR_length = sizeof (sin6_t);
3127 			sin6 = (sin6_t *)&tbr[1];
3128 			*sin6 = sin6_null;
3129 			sin6->sin6_family = AF_INET6;
3130 			mp->b_wptr = (uchar_t *)&sin6[1];
3131 			tcp->tcp_ipversion = IPV6_VERSION;
3132 			V6_SET_ZERO(v6addr);
3133 		}
3134 		requested_port = 0;
3135 		break;
3136 
3137 	case sizeof (sin_t):	/* Complete IPv4 address */
3138 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
3139 		    sizeof (sin_t));
3140 		if (sin == NULL || !OK_32PTR((char *)sin)) {
3141 			if (tcp->tcp_debug) {
3142 				(void) strlog(TCP_MOD_ID, 0, 1,
3143 				    SL_ERROR|SL_TRACE,
3144 				    "tcp_bind: bad address parameter, "
3145 				    "offset %d, len %d",
3146 				    tbr->ADDR_offset, tbr->ADDR_length);
3147 			}
3148 			tcp_err_ack(tcp, mp, TPROTO, 0);
3149 			return;
3150 		}
3151 		/*
3152 		 * With sockets sockfs will accept bogus sin_family in
3153 		 * bind() and replace it with the family used in the socket
3154 		 * call.
3155 		 */
3156 		if (sin->sin_family != AF_INET ||
3157 		    tcp->tcp_family != AF_INET) {
3158 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3159 			return;
3160 		}
3161 		requested_port = ntohs(sin->sin_port);
3162 		tcp->tcp_ipversion = IPV4_VERSION;
3163 		v4addr = sin->sin_addr.s_addr;
3164 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3165 		break;
3166 
3167 	case sizeof (sin6_t): /* Complete IPv6 address */
3168 		sin6 = (sin6_t *)mi_offset_param(mp,
3169 		    tbr->ADDR_offset, sizeof (sin6_t));
3170 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3171 			if (tcp->tcp_debug) {
3172 				(void) strlog(TCP_MOD_ID, 0, 1,
3173 				    SL_ERROR|SL_TRACE,
3174 				    "tcp_bind: bad IPv6 address parameter, "
3175 				    "offset %d, len %d", tbr->ADDR_offset,
3176 				    tbr->ADDR_length);
3177 			}
3178 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3179 			return;
3180 		}
3181 		if (sin6->sin6_family != AF_INET6 ||
3182 		    tcp->tcp_family != AF_INET6) {
3183 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3184 			return;
3185 		}
3186 		requested_port = ntohs(sin6->sin6_port);
3187 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3188 		    IPV4_VERSION : IPV6_VERSION;
3189 		v6addr = sin6->sin6_addr;
3190 		break;
3191 
3192 	default:
3193 		if (tcp->tcp_debug) {
3194 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3195 			    "tcp_bind: bad address length, %d",
3196 			    tbr->ADDR_length);
3197 		}
3198 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3199 		return;
3200 	}
3201 	tcp->tcp_bound_source_v6 = v6addr;
3202 
3203 	/* Check for change in ipversion */
3204 	if (origipversion != tcp->tcp_ipversion) {
3205 		ASSERT(tcp->tcp_family == AF_INET6);
3206 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3207 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3208 		if (err) {
3209 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3210 			return;
3211 		}
3212 	}
3213 
3214 	/*
3215 	 * Initialize family specific fields. Copy of the src addr.
3216 	 * in tcp_t is needed for the lookup funcs.
3217 	 */
3218 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3219 		tcp->tcp_ip6h->ip6_src = v6addr;
3220 	} else {
3221 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3222 	}
3223 	tcp->tcp_ip_src_v6 = v6addr;
3224 
3225 	/*
3226 	 * For O_T_BIND_REQ:
3227 	 * Verify that the target port/addr is available, or choose
3228 	 * another.
3229 	 * For  T_BIND_REQ:
3230 	 * Verify that the target port/addr is available or fail.
3231 	 * In both cases when it succeeds the tcp is inserted in the
3232 	 * bind hash table. This ensures that the operation is atomic
3233 	 * under the lock on the hash bucket.
3234 	 */
3235 	bind_to_req_port_only = requested_port != 0 &&
3236 	    tbr->PRIM_type != O_T_BIND_REQ;
3237 	/*
3238 	 * Get a valid port (within the anonymous range and should not
3239 	 * be a privileged one) to use if the user has not given a port.
3240 	 * If multiple threads are here, they may all start with
3241 	 * with the same initial port. But, it should be fine as long as
3242 	 * tcp_bindi will ensure that no two threads will be assigned
3243 	 * the same port.
3244 	 *
3245 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3246 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3247 	 * unless TCP_ANONPRIVBIND option is set.
3248 	 */
3249 	mlptype = mlptSingle;
3250 	mlp_port = requested_port;
3251 	if (requested_port == 0) {
3252 		requested_port = tcp->tcp_anon_priv_bind ?
3253 		    tcp_get_next_priv_port(tcp) :
3254 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
3255 		    tcp, B_TRUE);
3256 		if (requested_port == 0) {
3257 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3258 			return;
3259 		}
3260 		user_specified = B_FALSE;
3261 
3262 		/*
3263 		 * If the user went through one of the RPC interfaces to create
3264 		 * this socket and RPC is MLP in this zone, then give him an
3265 		 * anonymous MLP.
3266 		 */
3267 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3268 		if (connp->conn_anon_mlp && is_system_labeled()) {
3269 			zone = crgetzone(cr);
3270 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3271 			    IPV6_VERSION, &v6addr,
3272 			    tcps->tcps_netstack->netstack_ip);
3273 			if (addrtype == mlptSingle) {
3274 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3275 				return;
3276 			}
3277 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3278 			    PMAPPORT, addrtype);
3279 			mlp_port = PMAPPORT;
3280 		}
3281 	} else {
3282 		int i;
3283 		boolean_t priv = B_FALSE;
3284 
3285 		/*
3286 		 * If the requested_port is in the well-known privileged range,
3287 		 * verify that the stream was opened by a privileged user.
3288 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3289 		 * but instead the code relies on:
3290 		 * - the fact that the address of the array and its size never
3291 		 *   changes
3292 		 * - the atomic assignment of the elements of the array
3293 		 */
3294 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3295 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
3296 			priv = B_TRUE;
3297 		} else {
3298 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
3299 				if (requested_port ==
3300 				    tcps->tcps_g_epriv_ports[i]) {
3301 					priv = B_TRUE;
3302 					break;
3303 				}
3304 			}
3305 		}
3306 		if (priv) {
3307 			if (secpolicy_net_privaddr(cr, requested_port,
3308 			    IPPROTO_TCP) != 0) {
3309 				if (tcp->tcp_debug) {
3310 					(void) strlog(TCP_MOD_ID, 0, 1,
3311 					    SL_ERROR|SL_TRACE,
3312 					    "tcp_bind: no priv for port %d",
3313 					    requested_port);
3314 				}
3315 				tcp_err_ack(tcp, mp, TACCES, 0);
3316 				return;
3317 			}
3318 		}
3319 		user_specified = B_TRUE;
3320 
3321 		if (is_system_labeled()) {
3322 			zone = crgetzone(cr);
3323 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3324 			    IPV6_VERSION, &v6addr,
3325 			    tcps->tcps_netstack->netstack_ip);
3326 			if (addrtype == mlptSingle) {
3327 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3328 				return;
3329 			}
3330 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3331 			    requested_port, addrtype);
3332 		}
3333 	}
3334 
3335 	if (mlptype != mlptSingle) {
3336 		if (secpolicy_net_bindmlp(cr) != 0) {
3337 			if (tcp->tcp_debug) {
3338 				(void) strlog(TCP_MOD_ID, 0, 1,
3339 				    SL_ERROR|SL_TRACE,
3340 				    "tcp_bind: no priv for multilevel port %d",
3341 				    requested_port);
3342 			}
3343 			tcp_err_ack(tcp, mp, TACCES, 0);
3344 			return;
3345 		}
3346 
3347 		/*
3348 		 * If we're specifically binding a shared IP address and the
3349 		 * port is MLP on shared addresses, then check to see if this
3350 		 * zone actually owns the MLP.  Reject if not.
3351 		 */
3352 		if (mlptype == mlptShared && addrtype == mlptShared) {
3353 			/*
3354 			 * No need to handle exclusive-stack zones since
3355 			 * ALL_ZONES only applies to the shared stack.
3356 			 */
3357 			zoneid_t mlpzone;
3358 
3359 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
3360 			    htons(mlp_port));
3361 			if (connp->conn_zoneid != mlpzone) {
3362 				if (tcp->tcp_debug) {
3363 					(void) strlog(TCP_MOD_ID, 0, 1,
3364 					    SL_ERROR|SL_TRACE,
3365 					    "tcp_bind: attempt to bind port "
3366 					    "%d on shared addr in zone %d "
3367 					    "(should be %d)",
3368 					    mlp_port, connp->conn_zoneid,
3369 					    mlpzone);
3370 				}
3371 				tcp_err_ack(tcp, mp, TACCES, 0);
3372 				return;
3373 			}
3374 		}
3375 
3376 		if (!user_specified) {
3377 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3378 			    requested_port, B_TRUE);
3379 			if (err != 0) {
3380 				if (tcp->tcp_debug) {
3381 					(void) strlog(TCP_MOD_ID, 0, 1,
3382 					    SL_ERROR|SL_TRACE,
3383 					    "tcp_bind: cannot establish anon "
3384 					    "MLP for port %d",
3385 					    requested_port);
3386 				}
3387 				tcp_err_ack(tcp, mp, TSYSERR, err);
3388 				return;
3389 			}
3390 			connp->conn_anon_port = B_TRUE;
3391 		}
3392 		connp->conn_mlp_type = mlptype;
3393 	}
3394 
3395 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3396 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3397 
3398 	if (allocated_port == 0) {
3399 		connp->conn_mlp_type = mlptSingle;
3400 		if (connp->conn_anon_port) {
3401 			connp->conn_anon_port = B_FALSE;
3402 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3403 			    requested_port, B_FALSE);
3404 		}
3405 		if (bind_to_req_port_only) {
3406 			if (tcp->tcp_debug) {
3407 				(void) strlog(TCP_MOD_ID, 0, 1,
3408 				    SL_ERROR|SL_TRACE,
3409 				    "tcp_bind: requested addr busy");
3410 			}
3411 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3412 		} else {
3413 			/* If we are out of ports, fail the bind. */
3414 			if (tcp->tcp_debug) {
3415 				(void) strlog(TCP_MOD_ID, 0, 1,
3416 				    SL_ERROR|SL_TRACE,
3417 				    "tcp_bind: out of ports?");
3418 			}
3419 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3420 		}
3421 		return;
3422 	}
3423 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3424 do_bind:
3425 	if (!backlog_update) {
3426 		if (tcp->tcp_family == AF_INET)
3427 			sin->sin_port = htons(allocated_port);
3428 		else
3429 			sin6->sin6_port = htons(allocated_port);
3430 	}
3431 	if (tcp->tcp_family == AF_INET) {
3432 		if (tbr->CONIND_number != 0) {
3433 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3434 			    sizeof (sin_t));
3435 		} else {
3436 			/* Just verify the local IP address */
3437 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3438 		}
3439 	} else {
3440 		if (tbr->CONIND_number != 0) {
3441 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3442 			    sizeof (sin6_t));
3443 		} else {
3444 			/* Just verify the local IP address */
3445 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3446 			    IPV6_ADDR_LEN);
3447 		}
3448 	}
3449 	if (mp1 == NULL) {
3450 		if (connp->conn_anon_port) {
3451 			connp->conn_anon_port = B_FALSE;
3452 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3453 			    requested_port, B_FALSE);
3454 		}
3455 		connp->conn_mlp_type = mlptSingle;
3456 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3457 		return;
3458 	}
3459 
3460 	tbr->PRIM_type = T_BIND_ACK;
3461 	mp->b_datap->db_type = M_PCPROTO;
3462 
3463 	/* Chain in the reply mp for tcp_rput() */
3464 	mp1->b_cont = mp;
3465 	mp = mp1;
3466 
3467 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3468 	if (tcp->tcp_conn_req_max) {
3469 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
3470 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
3471 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
3472 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
3473 		/*
3474 		 * If this is a listener, do not reset the eager list
3475 		 * and other stuffs.  Note that we don't check if the
3476 		 * existing eager list meets the new tcp_conn_req_max
3477 		 * requirement.
3478 		 */
3479 		if (tcp->tcp_state != TCPS_LISTEN) {
3480 			tcp->tcp_state = TCPS_LISTEN;
3481 			/* Initialize the chain. Don't need the eager_lock */
3482 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3483 			tcp->tcp_eager_next_drop_q0 = tcp;
3484 			tcp->tcp_eager_prev_drop_q0 = tcp;
3485 			tcp->tcp_second_ctimer_threshold =
3486 			    tcps->tcps_ip_abort_linterval;
3487 		}
3488 	}
3489 
3490 	/*
3491 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3492 	 * processing continues in tcp_rput_other().
3493 	 *
3494 	 * We need to make sure that the conn_recv is set to a non-null
3495 	 * value before we insert the conn into the classifier table.
3496 	 * This is to avoid a race with an incoming packet which does an
3497 	 * ipcl_classify().
3498 	 */
3499 	connp->conn_recv = tcp_conn_request;
3500 	if (tcp->tcp_family == AF_INET6) {
3501 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3502 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3503 	} else {
3504 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3505 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3506 	}
3507 	/*
3508 	 * If the bind cannot complete immediately
3509 	 * IP will arrange to call tcp_rput_other
3510 	 * when the bind completes.
3511 	 */
3512 	if (mp != NULL) {
3513 		tcp_rput_other(tcp, mp);
3514 	} else {
3515 		/*
3516 		 * Bind will be resumed later. Need to ensure
3517 		 * that conn doesn't disappear when that happens.
3518 		 * This will be decremented in ip_resume_tcp_bind().
3519 		 */
3520 		CONN_INC_REF(tcp->tcp_connp);
3521 	}
3522 }
3523 
3524 
3525 /*
3526  * If the "bind_to_req_port_only" parameter is set, if the requested port
3527  * number is available, return it, If not return 0
3528  *
3529  * If "bind_to_req_port_only" parameter is not set and
3530  * If the requested port number is available, return it.  If not, return
3531  * the first anonymous port we happen across.  If no anonymous ports are
3532  * available, return 0. addr is the requested local address, if any.
3533  *
3534  * In either case, when succeeding update the tcp_t to record the port number
3535  * and insert it in the bind hash table.
3536  *
3537  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3538  * without setting SO_REUSEADDR. This is needed so that they
3539  * can be viewed as two independent transport protocols.
3540  */
3541 static in_port_t
3542 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3543     int reuseaddr, boolean_t quick_connect,
3544     boolean_t bind_to_req_port_only, boolean_t user_specified)
3545 {
3546 	/* number of times we have run around the loop */
3547 	int count = 0;
3548 	/* maximum number of times to run around the loop */
3549 	int loopmax;
3550 	conn_t *connp = tcp->tcp_connp;
3551 	zoneid_t zoneid = connp->conn_zoneid;
3552 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3553 
3554 	/*
3555 	 * Lookup for free addresses is done in a loop and "loopmax"
3556 	 * influences how long we spin in the loop
3557 	 */
3558 	if (bind_to_req_port_only) {
3559 		/*
3560 		 * If the requested port is busy, don't bother to look
3561 		 * for a new one. Setting loop maximum count to 1 has
3562 		 * that effect.
3563 		 */
3564 		loopmax = 1;
3565 	} else {
3566 		/*
3567 		 * If the requested port is busy, look for a free one
3568 		 * in the anonymous port range.
3569 		 * Set loopmax appropriately so that one does not look
3570 		 * forever in the case all of the anonymous ports are in use.
3571 		 */
3572 		if (tcp->tcp_anon_priv_bind) {
3573 			/*
3574 			 * loopmax =
3575 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3576 			 */
3577 			loopmax = IPPORT_RESERVED -
3578 			    tcps->tcps_min_anonpriv_port;
3579 		} else {
3580 			loopmax = (tcps->tcps_largest_anon_port -
3581 			    tcps->tcps_smallest_anon_port + 1);
3582 		}
3583 	}
3584 	do {
3585 		uint16_t	lport;
3586 		tf_t		*tbf;
3587 		tcp_t		*ltcp;
3588 		conn_t		*lconnp;
3589 
3590 		lport = htons(port);
3591 
3592 		/*
3593 		 * Ensure that the tcp_t is not currently in the bind hash.
3594 		 * Hold the lock on the hash bucket to ensure that
3595 		 * the duplicate check plus the insertion is an atomic
3596 		 * operation.
3597 		 *
3598 		 * This function does an inline lookup on the bind hash list
3599 		 * Make sure that we access only members of tcp_t
3600 		 * and that we don't look at tcp_tcp, since we are not
3601 		 * doing a CONN_INC_REF.
3602 		 */
3603 		tcp_bind_hash_remove(tcp);
3604 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3605 		mutex_enter(&tbf->tf_lock);
3606 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3607 		    ltcp = ltcp->tcp_bind_hash) {
3608 			boolean_t not_socket;
3609 			boolean_t exclbind;
3610 
3611 			if (lport != ltcp->tcp_lport)
3612 				continue;
3613 
3614 			lconnp = ltcp->tcp_connp;
3615 
3616 			/*
3617 			 * On a labeled system, we must treat bindings to ports
3618 			 * on shared IP addresses by sockets with MAC exemption
3619 			 * privilege as being in all zones, as there's
3620 			 * otherwise no way to identify the right receiver.
3621 			 */
3622 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3623 			    IPCL_ZONE_MATCH(connp,
3624 			    ltcp->tcp_connp->conn_zoneid)) &&
3625 			    !lconnp->conn_mac_exempt &&
3626 			    !connp->conn_mac_exempt)
3627 				continue;
3628 
3629 			/*
3630 			 * If TCP_EXCLBIND is set for either the bound or
3631 			 * binding endpoint, the semantics of bind
3632 			 * is changed according to the following.
3633 			 *
3634 			 * spec = specified address (v4 or v6)
3635 			 * unspec = unspecified address (v4 or v6)
3636 			 * A = specified addresses are different for endpoints
3637 			 *
3638 			 * bound	bind to		allowed
3639 			 * -------------------------------------
3640 			 * unspec	unspec		no
3641 			 * unspec	spec		no
3642 			 * spec		unspec		no
3643 			 * spec		spec		yes if A
3644 			 *
3645 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3646 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3647 			 *
3648 			 * Note:
3649 			 *
3650 			 * 1. Because of TLI semantics, an endpoint can go
3651 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3652 			 * TCPS_BOUND, depending on whether it is originally
3653 			 * a listener or not.  That is why we need to check
3654 			 * for states greater than or equal to TCPS_BOUND
3655 			 * here.
3656 			 *
3657 			 * 2. Ideally, we should only check for state equals
3658 			 * to TCPS_LISTEN. And the following check should be
3659 			 * added.
3660 			 *
3661 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3662 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3663 			 *		...
3664 			 * }
3665 			 *
3666 			 * The semantics will be changed to this.  If the
3667 			 * endpoint on the list is in state not equal to
3668 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3669 			 * set, let the bind succeed.
3670 			 *
3671 			 * Because of (1), we cannot do that for TLI
3672 			 * endpoints.  But we can do that for socket endpoints.
3673 			 * If in future, we can change this going back
3674 			 * semantics, we can use the above check for TLI also.
3675 			 */
3676 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3677 			    TCP_IS_SOCKET(tcp));
3678 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3679 
3680 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3681 			    (exclbind && (not_socket ||
3682 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3683 				if (V6_OR_V4_INADDR_ANY(
3684 				    ltcp->tcp_bound_source_v6) ||
3685 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3686 				    IN6_ARE_ADDR_EQUAL(laddr,
3687 				    &ltcp->tcp_bound_source_v6)) {
3688 					break;
3689 				}
3690 				continue;
3691 			}
3692 
3693 			/*
3694 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3695 			 * have disjoint port number spaces, if *_EXCLBIND
3696 			 * is not set and only if the application binds to a
3697 			 * specific port. We use the same autoassigned port
3698 			 * number space for IPv4 and IPv6 sockets.
3699 			 */
3700 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3701 			    bind_to_req_port_only)
3702 				continue;
3703 
3704 			/*
3705 			 * Ideally, we should make sure that the source
3706 			 * address, remote address, and remote port in the
3707 			 * four tuple for this tcp-connection is unique.
3708 			 * However, trying to find out the local source
3709 			 * address would require too much code duplication
3710 			 * with IP, since IP needs needs to have that code
3711 			 * to support userland TCP implementations.
3712 			 */
3713 			if (quick_connect &&
3714 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3715 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3716 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3717 			    &ltcp->tcp_remote_v6)))
3718 				continue;
3719 
3720 			if (!reuseaddr) {
3721 				/*
3722 				 * No socket option SO_REUSEADDR.
3723 				 * If existing port is bound to
3724 				 * a non-wildcard IP address
3725 				 * and the requesting stream is
3726 				 * bound to a distinct
3727 				 * different IP addresses
3728 				 * (non-wildcard, also), keep
3729 				 * going.
3730 				 */
3731 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3732 				    !V6_OR_V4_INADDR_ANY(
3733 				    ltcp->tcp_bound_source_v6) &&
3734 				    !IN6_ARE_ADDR_EQUAL(laddr,
3735 				    &ltcp->tcp_bound_source_v6))
3736 					continue;
3737 				if (ltcp->tcp_state >= TCPS_BOUND) {
3738 					/*
3739 					 * This port is being used and
3740 					 * its state is >= TCPS_BOUND,
3741 					 * so we can't bind to it.
3742 					 */
3743 					break;
3744 				}
3745 			} else {
3746 				/*
3747 				 * socket option SO_REUSEADDR is set on the
3748 				 * binding tcp_t.
3749 				 *
3750 				 * If two streams are bound to
3751 				 * same IP address or both addr
3752 				 * and bound source are wildcards
3753 				 * (INADDR_ANY), we want to stop
3754 				 * searching.
3755 				 * We have found a match of IP source
3756 				 * address and source port, which is
3757 				 * refused regardless of the
3758 				 * SO_REUSEADDR setting, so we break.
3759 				 */
3760 				if (IN6_ARE_ADDR_EQUAL(laddr,
3761 				    &ltcp->tcp_bound_source_v6) &&
3762 				    (ltcp->tcp_state == TCPS_LISTEN ||
3763 				    ltcp->tcp_state == TCPS_BOUND))
3764 					break;
3765 			}
3766 		}
3767 		if (ltcp != NULL) {
3768 			/* The port number is busy */
3769 			mutex_exit(&tbf->tf_lock);
3770 		} else {
3771 			/*
3772 			 * This port is ours. Insert in fanout and mark as
3773 			 * bound to prevent others from getting the port
3774 			 * number.
3775 			 */
3776 			tcp->tcp_state = TCPS_BOUND;
3777 			tcp->tcp_lport = htons(port);
3778 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3779 
3780 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3781 			    tcp->tcp_lport)] == tbf);
3782 			tcp_bind_hash_insert(tbf, tcp, 1);
3783 
3784 			mutex_exit(&tbf->tf_lock);
3785 
3786 			/*
3787 			 * We don't want tcp_next_port_to_try to "inherit"
3788 			 * a port number supplied by the user in a bind.
3789 			 */
3790 			if (user_specified)
3791 				return (port);
3792 
3793 			/*
3794 			 * This is the only place where tcp_next_port_to_try
3795 			 * is updated. After the update, it may or may not
3796 			 * be in the valid range.
3797 			 */
3798 			if (!tcp->tcp_anon_priv_bind)
3799 				tcps->tcps_next_port_to_try = port + 1;
3800 			return (port);
3801 		}
3802 
3803 		if (tcp->tcp_anon_priv_bind) {
3804 			port = tcp_get_next_priv_port(tcp);
3805 		} else {
3806 			if (count == 0 && user_specified) {
3807 				/*
3808 				 * We may have to return an anonymous port. So
3809 				 * get one to start with.
3810 				 */
3811 				port =
3812 				    tcp_update_next_port(
3813 				    tcps->tcps_next_port_to_try,
3814 				    tcp, B_TRUE);
3815 				user_specified = B_FALSE;
3816 			} else {
3817 				port = tcp_update_next_port(port + 1, tcp,
3818 				    B_FALSE);
3819 			}
3820 		}
3821 		if (port == 0)
3822 			break;
3823 
3824 		/*
3825 		 * Don't let this loop run forever in the case where
3826 		 * all of the anonymous ports are in use.
3827 		 */
3828 	} while (++count < loopmax);
3829 	return (0);
3830 }
3831 
3832 /*
3833  * tcp_clean_death / tcp_close_detached must not be called more than once
3834  * on a tcp. Thus every function that potentially calls tcp_clean_death
3835  * must check for the tcp state before calling tcp_clean_death.
3836  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3837  * tcp_timer_handler, all check for the tcp state.
3838  */
3839 /* ARGSUSED */
3840 void
3841 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3842 {
3843 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3844 
3845 	freemsg(mp);
3846 	if (tcp->tcp_state > TCPS_BOUND)
3847 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3848 		    ETIMEDOUT, 5);
3849 }
3850 
3851 /*
3852  * We are dying for some reason.  Try to do it gracefully.  (May be called
3853  * as writer.)
3854  *
3855  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3856  * done by a service procedure).
3857  * TBD - Should the return value distinguish between the tcp_t being
3858  * freed and it being reinitialized?
3859  */
3860 static int
3861 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3862 {
3863 	mblk_t	*mp;
3864 	queue_t	*q;
3865 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3866 	sodirect_t	*sodp;
3867 
3868 	TCP_CLD_STAT(tag);
3869 
3870 #if TCP_TAG_CLEAN_DEATH
3871 	tcp->tcp_cleandeathtag = tag;
3872 #endif
3873 
3874 	if (tcp->tcp_fused)
3875 		tcp_unfuse(tcp);
3876 
3877 	if (tcp->tcp_linger_tid != 0 &&
3878 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3879 		tcp_stop_lingering(tcp);
3880 	}
3881 
3882 	ASSERT(tcp != NULL);
3883 	ASSERT((tcp->tcp_family == AF_INET &&
3884 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3885 	    (tcp->tcp_family == AF_INET6 &&
3886 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3887 	    tcp->tcp_ipversion == IPV6_VERSION)));
3888 
3889 	if (TCP_IS_DETACHED(tcp)) {
3890 		if (tcp->tcp_hard_binding) {
3891 			/*
3892 			 * Its an eager that we are dealing with. We close the
3893 			 * eager but in case a conn_ind has already gone to the
3894 			 * listener, let tcp_accept_finish() send a discon_ind
3895 			 * to the listener and drop the last reference. If the
3896 			 * listener doesn't even know about the eager i.e. the
3897 			 * conn_ind hasn't gone up, blow away the eager and drop
3898 			 * the last reference as well. If the conn_ind has gone
3899 			 * up, state should be BOUND. tcp_accept_finish
3900 			 * will figure out that the connection has received a
3901 			 * RST and will send a DISCON_IND to the application.
3902 			 */
3903 			tcp_closei_local(tcp);
3904 			if (!tcp->tcp_tconnind_started) {
3905 				CONN_DEC_REF(tcp->tcp_connp);
3906 			} else {
3907 				tcp->tcp_state = TCPS_BOUND;
3908 			}
3909 		} else {
3910 			tcp_close_detached(tcp);
3911 		}
3912 		return (0);
3913 	}
3914 
3915 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3916 
3917 	/*
3918 	 * If T_ORDREL_IND has not been sent yet (done when service routine
3919 	 * is run) postpone cleaning up the endpoint until service routine
3920 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
3921 	 * client_errno since tcp_close uses the client_errno field.
3922 	 */
3923 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
3924 		if (err != 0)
3925 			tcp->tcp_client_errno = err;
3926 
3927 		tcp->tcp_deferred_clean_death = B_TRUE;
3928 		return (-1);
3929 	}
3930 
3931 	/* If sodirect, not anymore */
3932 	SOD_PTR_ENTER(tcp, sodp);
3933 	if (sodp != NULL) {
3934 		tcp->tcp_sodirect = NULL;
3935 		mutex_exit(sodp->sod_lock);
3936 	}
3937 
3938 	q = tcp->tcp_rq;
3939 
3940 	/* Trash all inbound data */
3941 	flushq(q, FLUSHALL);
3942 
3943 	/*
3944 	 * If we are at least part way open and there is error
3945 	 * (err==0 implies no error)
3946 	 * notify our client by a T_DISCON_IND.
3947 	 */
3948 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3949 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3950 		    !TCP_IS_SOCKET(tcp)) {
3951 			/*
3952 			 * Send M_FLUSH according to TPI. Because sockets will
3953 			 * (and must) ignore FLUSHR we do that only for TPI
3954 			 * endpoints and sockets in STREAMS mode.
3955 			 */
3956 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3957 		}
3958 		if (tcp->tcp_debug) {
3959 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3960 			    "tcp_clean_death: discon err %d", err);
3961 		}
3962 		mp = mi_tpi_discon_ind(NULL, err, 0);
3963 		if (mp != NULL) {
3964 			putnext(q, mp);
3965 		} else {
3966 			if (tcp->tcp_debug) {
3967 				(void) strlog(TCP_MOD_ID, 0, 1,
3968 				    SL_ERROR|SL_TRACE,
3969 				    "tcp_clean_death, sending M_ERROR");
3970 			}
3971 			(void) putnextctl1(q, M_ERROR, EPROTO);
3972 		}
3973 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3974 			/* SYN_SENT or SYN_RCVD */
3975 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3976 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3977 			/* ESTABLISHED or CLOSE_WAIT */
3978 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3979 		}
3980 	}
3981 
3982 	tcp_reinit(tcp);
3983 	return (-1);
3984 }
3985 
3986 /*
3987  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3988  * to expire, stop the wait and finish the close.
3989  */
3990 static void
3991 tcp_stop_lingering(tcp_t *tcp)
3992 {
3993 	clock_t	delta = 0;
3994 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3995 
3996 	tcp->tcp_linger_tid = 0;
3997 	if (tcp->tcp_state > TCPS_LISTEN) {
3998 		tcp_acceptor_hash_remove(tcp);
3999 		mutex_enter(&tcp->tcp_non_sq_lock);
4000 		if (tcp->tcp_flow_stopped) {
4001 			tcp_clrqfull(tcp);
4002 		}
4003 		mutex_exit(&tcp->tcp_non_sq_lock);
4004 
4005 		if (tcp->tcp_timer_tid != 0) {
4006 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4007 			tcp->tcp_timer_tid = 0;
4008 		}
4009 		/*
4010 		 * Need to cancel those timers which will not be used when
4011 		 * TCP is detached.  This has to be done before the tcp_wq
4012 		 * is set to the global queue.
4013 		 */
4014 		tcp_timers_stop(tcp);
4015 
4016 
4017 		tcp->tcp_detached = B_TRUE;
4018 		ASSERT(tcps->tcps_g_q != NULL);
4019 		tcp->tcp_rq = tcps->tcps_g_q;
4020 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4021 
4022 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4023 			tcp_time_wait_append(tcp);
4024 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
4025 			goto finish;
4026 		}
4027 
4028 		/*
4029 		 * If delta is zero the timer event wasn't executed and was
4030 		 * successfully canceled. In this case we need to restart it
4031 		 * with the minimal delta possible.
4032 		 */
4033 		if (delta >= 0) {
4034 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4035 			    delta ? delta : 1);
4036 		}
4037 	} else {
4038 		tcp_closei_local(tcp);
4039 		CONN_DEC_REF(tcp->tcp_connp);
4040 	}
4041 finish:
4042 	/* Signal closing thread that it can complete close */
4043 	mutex_enter(&tcp->tcp_closelock);
4044 	tcp->tcp_detached = B_TRUE;
4045 	ASSERT(tcps->tcps_g_q != NULL);
4046 	tcp->tcp_rq = tcps->tcps_g_q;
4047 	tcp->tcp_wq = WR(tcps->tcps_g_q);
4048 	tcp->tcp_closed = 1;
4049 	cv_signal(&tcp->tcp_closecv);
4050 	mutex_exit(&tcp->tcp_closelock);
4051 }
4052 
4053 /*
4054  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
4055  * expires.
4056  */
4057 static void
4058 tcp_close_linger_timeout(void *arg)
4059 {
4060 	conn_t	*connp = (conn_t *)arg;
4061 	tcp_t 	*tcp = connp->conn_tcp;
4062 
4063 	tcp->tcp_client_errno = ETIMEDOUT;
4064 	tcp_stop_lingering(tcp);
4065 }
4066 
4067 static int
4068 tcp_close(queue_t *q, int flags)
4069 {
4070 	conn_t		*connp = Q_TO_CONN(q);
4071 	tcp_t		*tcp = connp->conn_tcp;
4072 	mblk_t 		*mp = &tcp->tcp_closemp;
4073 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4074 	mblk_t		*bp;
4075 
4076 	ASSERT(WR(q)->q_next == NULL);
4077 	ASSERT(connp->conn_ref >= 2);
4078 
4079 	/*
4080 	 * We are being closed as /dev/tcp or /dev/tcp6.
4081 	 *
4082 	 * Mark the conn as closing. ill_pending_mp_add will not
4083 	 * add any mp to the pending mp list, after this conn has
4084 	 * started closing. Same for sq_pending_mp_add
4085 	 */
4086 	mutex_enter(&connp->conn_lock);
4087 	connp->conn_state_flags |= CONN_CLOSING;
4088 	if (connp->conn_oper_pending_ill != NULL)
4089 		conn_ioctl_cleanup_reqd = B_TRUE;
4090 	CONN_INC_REF_LOCKED(connp);
4091 	mutex_exit(&connp->conn_lock);
4092 	tcp->tcp_closeflags = (uint8_t)flags;
4093 	ASSERT(connp->conn_ref >= 3);
4094 
4095 	/*
4096 	 * tcp_closemp_used is used below without any protection of a lock
4097 	 * as we don't expect any one else to use it concurrently at this
4098 	 * point otherwise it would be a major defect.
4099 	 */
4100 
4101 	if (mp->b_prev == NULL)
4102 		tcp->tcp_closemp_used = B_TRUE;
4103 	else
4104 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
4105 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
4106 
4107 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
4108 
4109 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
4110 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
4111 
4112 	mutex_enter(&tcp->tcp_closelock);
4113 	while (!tcp->tcp_closed) {
4114 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
4115 			/*
4116 			 * The cv_wait_sig() was interrupted. We now do the
4117 			 * following:
4118 			 *
4119 			 * 1) If the endpoint was lingering, we allow this
4120 			 * to be interrupted by cancelling the linger timeout
4121 			 * and closing normally.
4122 			 *
4123 			 * 2) Revert to calling cv_wait()
4124 			 *
4125 			 * We revert to using cv_wait() to avoid an
4126 			 * infinite loop which can occur if the calling
4127 			 * thread is higher priority than the squeue worker
4128 			 * thread and is bound to the same cpu.
4129 			 */
4130 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
4131 				mutex_exit(&tcp->tcp_closelock);
4132 				/* Entering squeue, bump ref count. */
4133 				CONN_INC_REF(connp);
4134 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
4135 				squeue_enter(connp->conn_sqp, bp,
4136 				    tcp_linger_interrupted, connp,
4137 				    SQTAG_IP_TCP_CLOSE);
4138 				mutex_enter(&tcp->tcp_closelock);
4139 			}
4140 			break;
4141 		}
4142 	}
4143 	while (!tcp->tcp_closed)
4144 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
4145 	mutex_exit(&tcp->tcp_closelock);
4146 
4147 	/*
4148 	 * In the case of listener streams that have eagers in the q or q0
4149 	 * we wait for the eagers to drop their reference to us. tcp_rq and
4150 	 * tcp_wq of the eagers point to our queues. By waiting for the
4151 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
4152 	 * up their queue pointers and also dropped their references to us.
4153 	 */
4154 	if (tcp->tcp_wait_for_eagers) {
4155 		mutex_enter(&connp->conn_lock);
4156 		while (connp->conn_ref != 1) {
4157 			cv_wait(&connp->conn_cv, &connp->conn_lock);
4158 		}
4159 		mutex_exit(&connp->conn_lock);
4160 	}
4161 	/*
4162 	 * ioctl cleanup. The mp is queued in the
4163 	 * ill_pending_mp or in the sq_pending_mp.
4164 	 */
4165 	if (conn_ioctl_cleanup_reqd)
4166 		conn_ioctl_cleanup(connp);
4167 
4168 	qprocsoff(q);
4169 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4170 
4171 	tcp->tcp_cpid = -1;
4172 
4173 	/*
4174 	 * Drop IP's reference on the conn. This is the last reference
4175 	 * on the connp if the state was less than established. If the
4176 	 * connection has gone into timewait state, then we will have
4177 	 * one ref for the TCP and one more ref (total of two) for the
4178 	 * classifier connected hash list (a timewait connections stays
4179 	 * in connected hash till closed).
4180 	 *
4181 	 * We can't assert the references because there might be other
4182 	 * transient reference places because of some walkers or queued
4183 	 * packets in squeue for the timewait state.
4184 	 */
4185 	CONN_DEC_REF(connp);
4186 	q->q_ptr = WR(q)->q_ptr = NULL;
4187 	return (0);
4188 }
4189 
4190 static int
4191 tcpclose_accept(queue_t *q)
4192 {
4193 	vmem_t	*minor_arena;
4194 	dev_t	conn_dev;
4195 
4196 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
4197 
4198 	/*
4199 	 * We had opened an acceptor STREAM for sockfs which is
4200 	 * now being closed due to some error.
4201 	 */
4202 	qprocsoff(q);
4203 
4204 	minor_arena = (vmem_t *)WR(q)->q_ptr;
4205 	conn_dev = (dev_t)RD(q)->q_ptr;
4206 	ASSERT(minor_arena != NULL);
4207 	ASSERT(conn_dev != 0);
4208 	inet_minor_free(minor_arena, conn_dev);
4209 	q->q_ptr = WR(q)->q_ptr = NULL;
4210 	return (0);
4211 }
4212 
4213 /*
4214  * Called by tcp_close() routine via squeue when lingering is
4215  * interrupted by a signal.
4216  */
4217 
4218 /* ARGSUSED */
4219 static void
4220 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
4221 {
4222 	conn_t	*connp = (conn_t *)arg;
4223 	tcp_t	*tcp = connp->conn_tcp;
4224 
4225 	freeb(mp);
4226 	if (tcp->tcp_linger_tid != 0 &&
4227 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
4228 		tcp_stop_lingering(tcp);
4229 		tcp->tcp_client_errno = EINTR;
4230 	}
4231 }
4232 
4233 /*
4234  * Called by streams close routine via squeues when our client blows off her
4235  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
4236  * connection politely" When SO_LINGER is set (with a non-zero linger time and
4237  * it is not a nonblocking socket) then this routine sleeps until the FIN is
4238  * acked.
4239  *
4240  * NOTE: tcp_close potentially returns error when lingering.
4241  * However, the stream head currently does not pass these errors
4242  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
4243  * errors to the application (from tsleep()) and not errors
4244  * like ECONNRESET caused by receiving a reset packet.
4245  */
4246 
4247 /* ARGSUSED */
4248 static void
4249 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
4250 {
4251 	char	*msg;
4252 	conn_t	*connp = (conn_t *)arg;
4253 	tcp_t	*tcp = connp->conn_tcp;
4254 	clock_t	delta = 0;
4255 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4256 
4257 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
4258 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
4259 
4260 	/* Cancel any pending timeout */
4261 	if (tcp->tcp_ordrelid != 0) {
4262 		if (tcp->tcp_timeout) {
4263 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
4264 		}
4265 		tcp->tcp_ordrelid = 0;
4266 		tcp->tcp_timeout = B_FALSE;
4267 	}
4268 
4269 	mutex_enter(&tcp->tcp_eager_lock);
4270 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
4271 		/* Cleanup for listener */
4272 		tcp_eager_cleanup(tcp, 0);
4273 		tcp->tcp_wait_for_eagers = 1;
4274 	}
4275 	mutex_exit(&tcp->tcp_eager_lock);
4276 
4277 	connp->conn_mdt_ok = B_FALSE;
4278 	tcp->tcp_mdt = B_FALSE;
4279 
4280 	connp->conn_lso_ok = B_FALSE;
4281 	tcp->tcp_lso = B_FALSE;
4282 
4283 	msg = NULL;
4284 	switch (tcp->tcp_state) {
4285 	case TCPS_CLOSED:
4286 	case TCPS_IDLE:
4287 	case TCPS_BOUND:
4288 	case TCPS_LISTEN:
4289 		break;
4290 	case TCPS_SYN_SENT:
4291 		msg = "tcp_close, during connect";
4292 		break;
4293 	case TCPS_SYN_RCVD:
4294 		/*
4295 		 * Close during the connect 3-way handshake
4296 		 * but here there may or may not be pending data
4297 		 * already on queue. Process almost same as in
4298 		 * the ESTABLISHED state.
4299 		 */
4300 		/* FALLTHRU */
4301 	default:
4302 		if (tcp->tcp_sodirect != NULL) {
4303 			/* Ok, no more sodirect */
4304 			tcp->tcp_sodirect = NULL;
4305 		}
4306 
4307 		if (tcp->tcp_fused)
4308 			tcp_unfuse(tcp);
4309 
4310 		/*
4311 		 * If SO_LINGER has set a zero linger time, abort the
4312 		 * connection with a reset.
4313 		 */
4314 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
4315 			msg = "tcp_close, zero lingertime";
4316 			break;
4317 		}
4318 
4319 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
4320 		/*
4321 		 * Abort connection if there is unread data queued.
4322 		 */
4323 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
4324 			msg = "tcp_close, unread data";
4325 			break;
4326 		}
4327 		/*
4328 		 * tcp_hard_bound is now cleared thus all packets go through
4329 		 * tcp_lookup. This fact is used by tcp_detach below.
4330 		 *
4331 		 * We have done a qwait() above which could have possibly
4332 		 * drained more messages in turn causing transition to a
4333 		 * different state. Check whether we have to do the rest
4334 		 * of the processing or not.
4335 		 */
4336 		if (tcp->tcp_state <= TCPS_LISTEN)
4337 			break;
4338 
4339 		/*
4340 		 * Transmit the FIN before detaching the tcp_t.
4341 		 * After tcp_detach returns this queue/perimeter
4342 		 * no longer owns the tcp_t thus others can modify it.
4343 		 */
4344 		(void) tcp_xmit_end(tcp);
4345 
4346 		/*
4347 		 * If lingering on close then wait until the fin is acked,
4348 		 * the SO_LINGER time passes, or a reset is sent/received.
4349 		 */
4350 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
4351 		    !(tcp->tcp_fin_acked) &&
4352 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
4353 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
4354 				tcp->tcp_client_errno = EWOULDBLOCK;
4355 			} else if (tcp->tcp_client_errno == 0) {
4356 
4357 				ASSERT(tcp->tcp_linger_tid == 0);
4358 
4359 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
4360 				    tcp_close_linger_timeout,
4361 				    tcp->tcp_lingertime * hz);
4362 
4363 				/* tcp_close_linger_timeout will finish close */
4364 				if (tcp->tcp_linger_tid == 0)
4365 					tcp->tcp_client_errno = ENOSR;
4366 				else
4367 					return;
4368 			}
4369 
4370 			/*
4371 			 * Check if we need to detach or just close
4372 			 * the instance.
4373 			 */
4374 			if (tcp->tcp_state <= TCPS_LISTEN)
4375 				break;
4376 		}
4377 
4378 		/*
4379 		 * Make sure that no other thread will access the tcp_rq of
4380 		 * this instance (through lookups etc.) as tcp_rq will go
4381 		 * away shortly.
4382 		 */
4383 		tcp_acceptor_hash_remove(tcp);
4384 
4385 		mutex_enter(&tcp->tcp_non_sq_lock);
4386 		if (tcp->tcp_flow_stopped) {
4387 			tcp_clrqfull(tcp);
4388 		}
4389 		mutex_exit(&tcp->tcp_non_sq_lock);
4390 
4391 		if (tcp->tcp_timer_tid != 0) {
4392 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4393 			tcp->tcp_timer_tid = 0;
4394 		}
4395 		/*
4396 		 * Need to cancel those timers which will not be used when
4397 		 * TCP is detached.  This has to be done before the tcp_wq
4398 		 * is set to the global queue.
4399 		 */
4400 		tcp_timers_stop(tcp);
4401 
4402 		tcp->tcp_detached = B_TRUE;
4403 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4404 			tcp_time_wait_append(tcp);
4405 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
4406 			ASSERT(connp->conn_ref >= 3);
4407 			goto finish;
4408 		}
4409 
4410 		/*
4411 		 * If delta is zero the timer event wasn't executed and was
4412 		 * successfully canceled. In this case we need to restart it
4413 		 * with the minimal delta possible.
4414 		 */
4415 		if (delta >= 0)
4416 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4417 			    delta ? delta : 1);
4418 
4419 		ASSERT(connp->conn_ref >= 3);
4420 		goto finish;
4421 	}
4422 
4423 	/* Detach did not complete. Still need to remove q from stream. */
4424 	if (msg) {
4425 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4426 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4427 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4428 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4429 		    tcp->tcp_state == TCPS_SYN_RCVD)
4430 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4431 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4432 	}
4433 
4434 	tcp_closei_local(tcp);
4435 	CONN_DEC_REF(connp);
4436 	ASSERT(connp->conn_ref >= 2);
4437 
4438 finish:
4439 	/*
4440 	 * Although packets are always processed on the correct
4441 	 * tcp's perimeter and access is serialized via squeue's,
4442 	 * IP still needs a queue when sending packets in time_wait
4443 	 * state so use WR(tcps_g_q) till ip_output() can be
4444 	 * changed to deal with just connp. For read side, we
4445 	 * could have set tcp_rq to NULL but there are some cases
4446 	 * in tcp_rput_data() from early days of this code which
4447 	 * do a putnext without checking if tcp is closed. Those
4448 	 * need to be identified before both tcp_rq and tcp_wq
4449 	 * can be set to NULL and tcps_g_q can disappear forever.
4450 	 */
4451 	mutex_enter(&tcp->tcp_closelock);
4452 	/*
4453 	 * Don't change the queues in the case of a listener that has
4454 	 * eagers in its q or q0. It could surprise the eagers.
4455 	 * Instead wait for the eagers outside the squeue.
4456 	 */
4457 	if (!tcp->tcp_wait_for_eagers) {
4458 		tcp->tcp_detached = B_TRUE;
4459 		/*
4460 		 * When default queue is closing we set tcps_g_q to NULL
4461 		 * after the close is done.
4462 		 */
4463 		ASSERT(tcps->tcps_g_q != NULL);
4464 		tcp->tcp_rq = tcps->tcps_g_q;
4465 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4466 	}
4467 
4468 	/* Signal tcp_close() to finish closing. */
4469 	tcp->tcp_closed = 1;
4470 	cv_signal(&tcp->tcp_closecv);
4471 	mutex_exit(&tcp->tcp_closelock);
4472 }
4473 
4474 
4475 /*
4476  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4477  * Some stream heads get upset if they see these later on as anything but NULL.
4478  */
4479 static void
4480 tcp_close_mpp(mblk_t **mpp)
4481 {
4482 	mblk_t	*mp;
4483 
4484 	if ((mp = *mpp) != NULL) {
4485 		do {
4486 			mp->b_next = NULL;
4487 			mp->b_prev = NULL;
4488 		} while ((mp = mp->b_cont) != NULL);
4489 
4490 		mp = *mpp;
4491 		*mpp = NULL;
4492 		freemsg(mp);
4493 	}
4494 }
4495 
4496 /* Do detached close. */
4497 static void
4498 tcp_close_detached(tcp_t *tcp)
4499 {
4500 	if (tcp->tcp_fused)
4501 		tcp_unfuse(tcp);
4502 
4503 	/*
4504 	 * Clustering code serializes TCP disconnect callbacks and
4505 	 * cluster tcp list walks by blocking a TCP disconnect callback
4506 	 * if a cluster tcp list walk is in progress. This ensures
4507 	 * accurate accounting of TCPs in the cluster code even though
4508 	 * the TCP list walk itself is not atomic.
4509 	 */
4510 	tcp_closei_local(tcp);
4511 	CONN_DEC_REF(tcp->tcp_connp);
4512 }
4513 
4514 /*
4515  * Stop all TCP timers, and free the timer mblks if requested.
4516  */
4517 void
4518 tcp_timers_stop(tcp_t *tcp)
4519 {
4520 	if (tcp->tcp_timer_tid != 0) {
4521 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4522 		tcp->tcp_timer_tid = 0;
4523 	}
4524 	if (tcp->tcp_ka_tid != 0) {
4525 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4526 		tcp->tcp_ka_tid = 0;
4527 	}
4528 	if (tcp->tcp_ack_tid != 0) {
4529 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4530 		tcp->tcp_ack_tid = 0;
4531 	}
4532 	if (tcp->tcp_push_tid != 0) {
4533 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4534 		tcp->tcp_push_tid = 0;
4535 	}
4536 }
4537 
4538 /*
4539  * The tcp_t is going away. Remove it from all lists and set it
4540  * to TCPS_CLOSED. The freeing up of memory is deferred until
4541  * tcp_inactive. This is needed since a thread in tcp_rput might have
4542  * done a CONN_INC_REF on this structure before it was removed from the
4543  * hashes.
4544  */
4545 static void
4546 tcp_closei_local(tcp_t *tcp)
4547 {
4548 	ire_t 	*ire;
4549 	conn_t	*connp = tcp->tcp_connp;
4550 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4551 
4552 	if (!TCP_IS_SOCKET(tcp))
4553 		tcp_acceptor_hash_remove(tcp);
4554 
4555 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4556 	tcp->tcp_ibsegs = 0;
4557 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4558 	tcp->tcp_obsegs = 0;
4559 
4560 	/*
4561 	 * If we are an eager connection hanging off a listener that
4562 	 * hasn't formally accepted the connection yet, get off his
4563 	 * list and blow off any data that we have accumulated.
4564 	 */
4565 	if (tcp->tcp_listener != NULL) {
4566 		tcp_t	*listener = tcp->tcp_listener;
4567 		mutex_enter(&listener->tcp_eager_lock);
4568 		/*
4569 		 * tcp_tconnind_started == B_TRUE means that the
4570 		 * conn_ind has already gone to listener. At
4571 		 * this point, eager will be closed but we
4572 		 * leave it in listeners eager list so that
4573 		 * if listener decides to close without doing
4574 		 * accept, we can clean this up. In tcp_wput_accept
4575 		 * we take care of the case of accept on closed
4576 		 * eager.
4577 		 */
4578 		if (!tcp->tcp_tconnind_started) {
4579 			tcp_eager_unlink(tcp);
4580 			mutex_exit(&listener->tcp_eager_lock);
4581 			/*
4582 			 * We don't want to have any pointers to the
4583 			 * listener queue, after we have released our
4584 			 * reference on the listener
4585 			 */
4586 			ASSERT(tcps->tcps_g_q != NULL);
4587 			tcp->tcp_rq = tcps->tcps_g_q;
4588 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4589 			CONN_DEC_REF(listener->tcp_connp);
4590 		} else {
4591 			mutex_exit(&listener->tcp_eager_lock);
4592 		}
4593 	}
4594 
4595 	/* Stop all the timers */
4596 	tcp_timers_stop(tcp);
4597 
4598 	if (tcp->tcp_state == TCPS_LISTEN) {
4599 		if (tcp->tcp_ip_addr_cache) {
4600 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4601 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4602 			tcp->tcp_ip_addr_cache = NULL;
4603 		}
4604 	}
4605 	mutex_enter(&tcp->tcp_non_sq_lock);
4606 	if (tcp->tcp_flow_stopped)
4607 		tcp_clrqfull(tcp);
4608 	mutex_exit(&tcp->tcp_non_sq_lock);
4609 
4610 	tcp_bind_hash_remove(tcp);
4611 	/*
4612 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4613 	 * is trying to remove this tcp from the time wait list, we will
4614 	 * block in tcp_time_wait_remove while trying to acquire the
4615 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4616 	 * requires the ipcl_hash_remove to be ordered after the
4617 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4618 	 */
4619 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4620 		(void) tcp_time_wait_remove(tcp, NULL);
4621 	CL_INET_DISCONNECT(tcp);
4622 	ipcl_hash_remove(connp);
4623 
4624 	/*
4625 	 * Delete the cached ire in conn_ire_cache and also mark
4626 	 * the conn as CONDEMNED
4627 	 */
4628 	mutex_enter(&connp->conn_lock);
4629 	connp->conn_state_flags |= CONN_CONDEMNED;
4630 	ire = connp->conn_ire_cache;
4631 	connp->conn_ire_cache = NULL;
4632 	mutex_exit(&connp->conn_lock);
4633 	if (ire != NULL)
4634 		IRE_REFRELE_NOTR(ire);
4635 
4636 	/* Need to cleanup any pending ioctls */
4637 	ASSERT(tcp->tcp_time_wait_next == NULL);
4638 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4639 	ASSERT(tcp->tcp_time_wait_expire == 0);
4640 	tcp->tcp_state = TCPS_CLOSED;
4641 
4642 	/* Release any SSL context */
4643 	if (tcp->tcp_kssl_ent != NULL) {
4644 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4645 		tcp->tcp_kssl_ent = NULL;
4646 	}
4647 	if (tcp->tcp_kssl_ctx != NULL) {
4648 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4649 		tcp->tcp_kssl_ctx = NULL;
4650 	}
4651 	tcp->tcp_kssl_pending = B_FALSE;
4652 
4653 	tcp_ipsec_cleanup(tcp);
4654 }
4655 
4656 /*
4657  * tcp is dying (called from ipcl_conn_destroy and error cases).
4658  * Free the tcp_t in either case.
4659  */
4660 void
4661 tcp_free(tcp_t *tcp)
4662 {
4663 	mblk_t	*mp;
4664 	ip6_pkt_t	*ipp;
4665 
4666 	ASSERT(tcp != NULL);
4667 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4668 
4669 	tcp->tcp_rq = NULL;
4670 	tcp->tcp_wq = NULL;
4671 
4672 	tcp_close_mpp(&tcp->tcp_xmit_head);
4673 	tcp_close_mpp(&tcp->tcp_reass_head);
4674 	if (tcp->tcp_rcv_list != NULL) {
4675 		/* Free b_next chain */
4676 		tcp_close_mpp(&tcp->tcp_rcv_list);
4677 	}
4678 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4679 		freemsg(mp);
4680 	}
4681 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4682 		freemsg(mp);
4683 	}
4684 
4685 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4686 		freeb(tcp->tcp_fused_sigurg_mp);
4687 		tcp->tcp_fused_sigurg_mp = NULL;
4688 	}
4689 
4690 	if (tcp->tcp_sack_info != NULL) {
4691 		if (tcp->tcp_notsack_list != NULL) {
4692 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4693 		}
4694 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4695 	}
4696 
4697 	if (tcp->tcp_hopopts != NULL) {
4698 		mi_free(tcp->tcp_hopopts);
4699 		tcp->tcp_hopopts = NULL;
4700 		tcp->tcp_hopoptslen = 0;
4701 	}
4702 	ASSERT(tcp->tcp_hopoptslen == 0);
4703 	if (tcp->tcp_dstopts != NULL) {
4704 		mi_free(tcp->tcp_dstopts);
4705 		tcp->tcp_dstopts = NULL;
4706 		tcp->tcp_dstoptslen = 0;
4707 	}
4708 	ASSERT(tcp->tcp_dstoptslen == 0);
4709 	if (tcp->tcp_rtdstopts != NULL) {
4710 		mi_free(tcp->tcp_rtdstopts);
4711 		tcp->tcp_rtdstopts = NULL;
4712 		tcp->tcp_rtdstoptslen = 0;
4713 	}
4714 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4715 	if (tcp->tcp_rthdr != NULL) {
4716 		mi_free(tcp->tcp_rthdr);
4717 		tcp->tcp_rthdr = NULL;
4718 		tcp->tcp_rthdrlen = 0;
4719 	}
4720 	ASSERT(tcp->tcp_rthdrlen == 0);
4721 
4722 	ipp = &tcp->tcp_sticky_ipp;
4723 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4724 	    IPPF_RTHDR))
4725 		ip6_pkt_free(ipp);
4726 
4727 	/*
4728 	 * Free memory associated with the tcp/ip header template.
4729 	 */
4730 
4731 	if (tcp->tcp_iphc != NULL)
4732 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4733 
4734 	/*
4735 	 * Following is really a blowing away a union.
4736 	 * It happens to have exactly two members of identical size
4737 	 * the following code is enough.
4738 	 */
4739 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4740 
4741 	if (tcp->tcp_tracebuf != NULL) {
4742 		kmem_free(tcp->tcp_tracebuf, sizeof (tcptrch_t));
4743 		tcp->tcp_tracebuf = NULL;
4744 	}
4745 }
4746 
4747 
4748 /*
4749  * Put a connection confirmation message upstream built from the
4750  * address information within 'iph' and 'tcph'.  Report our success or failure.
4751  */
4752 static boolean_t
4753 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4754     mblk_t **defermp)
4755 {
4756 	sin_t	sin;
4757 	sin6_t	sin6;
4758 	mblk_t	*mp;
4759 	char	*optp = NULL;
4760 	int	optlen = 0;
4761 	cred_t	*cr;
4762 
4763 	if (defermp != NULL)
4764 		*defermp = NULL;
4765 
4766 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4767 		/*
4768 		 * Return in T_CONN_CON results of option negotiation through
4769 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4770 		 * negotiation, then what is received from remote end needs
4771 		 * to be taken into account but there is no such thing (yet?)
4772 		 * in our TCP/IP.
4773 		 * Note: We do not use mi_offset_param() here as
4774 		 * tcp_opts_conn_req contents do not directly come from
4775 		 * an application and are either generated in kernel or
4776 		 * from user input that was already verified.
4777 		 */
4778 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4779 		optp = (char *)(mp->b_rptr +
4780 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4781 		optlen = (int)
4782 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4783 	}
4784 
4785 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4786 		ipha_t *ipha = (ipha_t *)iphdr;
4787 
4788 		/* packet is IPv4 */
4789 		if (tcp->tcp_family == AF_INET) {
4790 			sin = sin_null;
4791 			sin.sin_addr.s_addr = ipha->ipha_src;
4792 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4793 			sin.sin_family = AF_INET;
4794 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4795 			    (int)sizeof (sin_t), optp, optlen);
4796 		} else {
4797 			sin6 = sin6_null;
4798 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4799 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4800 			sin6.sin6_family = AF_INET6;
4801 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4802 			    (int)sizeof (sin6_t), optp, optlen);
4803 
4804 		}
4805 	} else {
4806 		ip6_t	*ip6h = (ip6_t *)iphdr;
4807 
4808 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4809 		ASSERT(tcp->tcp_family == AF_INET6);
4810 		sin6 = sin6_null;
4811 		sin6.sin6_addr = ip6h->ip6_src;
4812 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4813 		sin6.sin6_family = AF_INET6;
4814 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4815 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4816 		    (int)sizeof (sin6_t), optp, optlen);
4817 	}
4818 
4819 	if (!mp)
4820 		return (B_FALSE);
4821 
4822 	if ((cr = DB_CRED(idmp)) != NULL) {
4823 		mblk_setcred(mp, cr);
4824 		DB_CPID(mp) = DB_CPID(idmp);
4825 	}
4826 
4827 	if (defermp == NULL)
4828 		putnext(tcp->tcp_rq, mp);
4829 	else
4830 		*defermp = mp;
4831 
4832 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4833 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4834 	return (B_TRUE);
4835 }
4836 
4837 /*
4838  * Defense for the SYN attack -
4839  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4840  *    one from the list of droppable eagers. This list is a subset of q0.
4841  *    see comments before the definition of MAKE_DROPPABLE().
4842  * 2. Don't drop a SYN request before its first timeout. This gives every
4843  *    request at least til the first timeout to complete its 3-way handshake.
4844  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4845  *    requests currently on the queue that has timed out. This will be used
4846  *    as an indicator of whether an attack is under way, so that appropriate
4847  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4848  *    either when eager goes into ESTABLISHED, or gets freed up.)
4849  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4850  *    # of timeout drops back to <= q0len/32 => SYN alert off
4851  */
4852 static boolean_t
4853 tcp_drop_q0(tcp_t *tcp)
4854 {
4855 	tcp_t	*eager;
4856 	mblk_t	*mp;
4857 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4858 
4859 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4860 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4861 
4862 	/* Pick oldest eager from the list of droppable eagers */
4863 	eager = tcp->tcp_eager_prev_drop_q0;
4864 
4865 	/* If list is empty. return B_FALSE */
4866 	if (eager == tcp) {
4867 		return (B_FALSE);
4868 	}
4869 
4870 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4871 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4872 		return (B_FALSE);
4873 
4874 	/*
4875 	 * Take this eager out from the list of droppable eagers since we are
4876 	 * going to drop it.
4877 	 */
4878 	MAKE_UNDROPPABLE(eager);
4879 
4880 	if (tcp->tcp_debug) {
4881 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4882 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4883 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4884 		    tcp->tcp_conn_req_cnt_q0,
4885 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4886 	}
4887 
4888 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4889 
4890 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4891 	CONN_INC_REF(eager->tcp_connp);
4892 
4893 	/* Mark the IRE created for this SYN request temporary */
4894 	tcp_ip_ire_mark_advice(eager);
4895 	squeue_fill(eager->tcp_connp->conn_sqp, mp,
4896 	    tcp_clean_death_wrapper, eager->tcp_connp, SQTAG_TCP_DROP_Q0);
4897 
4898 	return (B_TRUE);
4899 }
4900 
4901 int
4902 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4903     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4904 {
4905 	tcp_t 		*ltcp = lconnp->conn_tcp;
4906 	tcp_t		*tcp = connp->conn_tcp;
4907 	mblk_t		*tpi_mp;
4908 	ipha_t		*ipha;
4909 	ip6_t		*ip6h;
4910 	sin6_t 		sin6;
4911 	in6_addr_t 	v6dst;
4912 	int		err;
4913 	int		ifindex = 0;
4914 	cred_t		*cr;
4915 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4916 
4917 	if (ipvers == IPV4_VERSION) {
4918 		ipha = (ipha_t *)mp->b_rptr;
4919 
4920 		connp->conn_send = ip_output;
4921 		connp->conn_recv = tcp_input;
4922 
4923 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4924 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4925 
4926 		sin6 = sin6_null;
4927 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4928 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4929 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4930 		sin6.sin6_family = AF_INET6;
4931 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4932 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4933 		if (tcp->tcp_recvdstaddr) {
4934 			sin6_t	sin6d;
4935 
4936 			sin6d = sin6_null;
4937 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4938 			    &sin6d.sin6_addr);
4939 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4940 			sin6d.sin6_family = AF_INET;
4941 			tpi_mp = mi_tpi_extconn_ind(NULL,
4942 			    (char *)&sin6d, sizeof (sin6_t),
4943 			    (char *)&tcp,
4944 			    (t_scalar_t)sizeof (intptr_t),
4945 			    (char *)&sin6d, sizeof (sin6_t),
4946 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4947 		} else {
4948 			tpi_mp = mi_tpi_conn_ind(NULL,
4949 			    (char *)&sin6, sizeof (sin6_t),
4950 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4951 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4952 		}
4953 	} else {
4954 		ip6h = (ip6_t *)mp->b_rptr;
4955 
4956 		connp->conn_send = ip_output_v6;
4957 		connp->conn_recv = tcp_input;
4958 
4959 		connp->conn_srcv6 = ip6h->ip6_dst;
4960 		connp->conn_remv6 = ip6h->ip6_src;
4961 
4962 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4963 		ifindex = (int)DB_CKSUMSTUFF(mp);
4964 		DB_CKSUMSTUFF(mp) = 0;
4965 
4966 		sin6 = sin6_null;
4967 		sin6.sin6_addr = ip6h->ip6_src;
4968 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4969 		sin6.sin6_family = AF_INET6;
4970 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4971 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4972 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4973 
4974 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4975 			/* Pass up the scope_id of remote addr */
4976 			sin6.sin6_scope_id = ifindex;
4977 		} else {
4978 			sin6.sin6_scope_id = 0;
4979 		}
4980 		if (tcp->tcp_recvdstaddr) {
4981 			sin6_t	sin6d;
4982 
4983 			sin6d = sin6_null;
4984 			sin6.sin6_addr = ip6h->ip6_dst;
4985 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4986 			sin6d.sin6_family = AF_INET;
4987 			tpi_mp = mi_tpi_extconn_ind(NULL,
4988 			    (char *)&sin6d, sizeof (sin6_t),
4989 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4990 			    (char *)&sin6d, sizeof (sin6_t),
4991 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4992 		} else {
4993 			tpi_mp = mi_tpi_conn_ind(NULL,
4994 			    (char *)&sin6, sizeof (sin6_t),
4995 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4996 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4997 		}
4998 	}
4999 
5000 	if (tpi_mp == NULL)
5001 		return (ENOMEM);
5002 
5003 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
5004 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
5005 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
5006 	connp->conn_fully_bound = B_FALSE;
5007 
5008 	if (tcps->tcps_trace)
5009 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
5010 
5011 	/* Inherit information from the "parent" */
5012 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
5013 	tcp->tcp_family = ltcp->tcp_family;
5014 	tcp->tcp_wq = ltcp->tcp_wq;
5015 	tcp->tcp_rq = ltcp->tcp_rq;
5016 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
5017 	tcp->tcp_detached = B_TRUE;
5018 	if ((err = tcp_init_values(tcp)) != 0) {
5019 		freemsg(tpi_mp);
5020 		return (err);
5021 	}
5022 
5023 	if (ipvers == IPV4_VERSION) {
5024 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
5025 			freemsg(tpi_mp);
5026 			return (err);
5027 		}
5028 		ASSERT(tcp->tcp_ipha != NULL);
5029 	} else {
5030 		/* ifindex must be already set */
5031 		ASSERT(ifindex != 0);
5032 
5033 		if (ltcp->tcp_bound_if != 0) {
5034 			/*
5035 			 * Set newtcp's bound_if equal to
5036 			 * listener's value. If ifindex is
5037 			 * not the same as ltcp->tcp_bound_if,
5038 			 * it must be a packet for the ipmp group
5039 			 * of interfaces
5040 			 */
5041 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
5042 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
5043 			tcp->tcp_bound_if = ifindex;
5044 		}
5045 
5046 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
5047 		tcp->tcp_recvifindex = 0;
5048 		tcp->tcp_recvhops = 0xffffffffU;
5049 		ASSERT(tcp->tcp_ip6h != NULL);
5050 	}
5051 
5052 	tcp->tcp_lport = ltcp->tcp_lport;
5053 
5054 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
5055 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
5056 			/*
5057 			 * Listener had options of some sort; eager inherits.
5058 			 * Free up the eager template and allocate one
5059 			 * of the right size.
5060 			 */
5061 			if (tcp->tcp_hdr_grown) {
5062 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
5063 			} else {
5064 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
5065 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
5066 			}
5067 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
5068 			    KM_NOSLEEP);
5069 			if (tcp->tcp_iphc == NULL) {
5070 				tcp->tcp_iphc_len = 0;
5071 				freemsg(tpi_mp);
5072 				return (ENOMEM);
5073 			}
5074 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
5075 			tcp->tcp_hdr_grown = B_TRUE;
5076 		}
5077 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5078 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5079 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5080 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
5081 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
5082 
5083 		/*
5084 		 * Copy the IP+TCP header template from listener to eager
5085 		 */
5086 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5087 		if (tcp->tcp_ipversion == IPV6_VERSION) {
5088 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
5089 			    IPPROTO_RAW) {
5090 				tcp->tcp_ip6h =
5091 				    (ip6_t *)(tcp->tcp_iphc +
5092 				    sizeof (ip6i_t));
5093 			} else {
5094 				tcp->tcp_ip6h =
5095 				    (ip6_t *)(tcp->tcp_iphc);
5096 			}
5097 			tcp->tcp_ipha = NULL;
5098 		} else {
5099 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5100 			tcp->tcp_ip6h = NULL;
5101 		}
5102 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5103 		    tcp->tcp_ip_hdr_len);
5104 	} else {
5105 		/*
5106 		 * only valid case when ipversion of listener and
5107 		 * eager differ is when listener is IPv6 and
5108 		 * eager is IPv4.
5109 		 * Eager header template has been initialized to the
5110 		 * maximum v4 header sizes, which includes space for
5111 		 * TCP and IP options.
5112 		 */
5113 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
5114 		    (tcp->tcp_ipversion == IPV4_VERSION));
5115 		ASSERT(tcp->tcp_iphc_len >=
5116 		    TCP_MAX_COMBINED_HEADER_LENGTH);
5117 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5118 		/* copy IP header fields individually */
5119 		tcp->tcp_ipha->ipha_ttl =
5120 		    ltcp->tcp_ip6h->ip6_hops;
5121 		bcopy(ltcp->tcp_tcph->th_lport,
5122 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
5123 	}
5124 
5125 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5126 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
5127 	    sizeof (in_port_t));
5128 
5129 	if (ltcp->tcp_lport == 0) {
5130 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
5131 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
5132 		    sizeof (in_port_t));
5133 	}
5134 
5135 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5136 		ASSERT(ipha != NULL);
5137 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5138 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5139 
5140 		/* Source routing option copyover (reverse it) */
5141 		if (tcps->tcps_rev_src_routes)
5142 			tcp_opt_reverse(tcp, ipha);
5143 	} else {
5144 		ASSERT(ip6h != NULL);
5145 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
5146 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
5147 	}
5148 
5149 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5150 	ASSERT(!tcp->tcp_tconnind_started);
5151 	/*
5152 	 * If the SYN contains a credential, it's a loopback packet; attach
5153 	 * the credential to the TPI message.
5154 	 */
5155 	if ((cr = DB_CRED(idmp)) != NULL) {
5156 		mblk_setcred(tpi_mp, cr);
5157 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5158 	}
5159 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5160 
5161 	/* Inherit the listener's SSL protection state */
5162 
5163 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5164 		kssl_hold_ent(tcp->tcp_kssl_ent);
5165 		tcp->tcp_kssl_pending = B_TRUE;
5166 	}
5167 
5168 	return (0);
5169 }
5170 
5171 
5172 int
5173 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
5174     tcph_t *tcph, mblk_t *idmp)
5175 {
5176 	tcp_t 		*ltcp = lconnp->conn_tcp;
5177 	tcp_t		*tcp = connp->conn_tcp;
5178 	sin_t		sin;
5179 	mblk_t		*tpi_mp = NULL;
5180 	int		err;
5181 	cred_t		*cr;
5182 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5183 
5184 	sin = sin_null;
5185 	sin.sin_addr.s_addr = ipha->ipha_src;
5186 	sin.sin_port = *(uint16_t *)tcph->th_lport;
5187 	sin.sin_family = AF_INET;
5188 	if (ltcp->tcp_recvdstaddr) {
5189 		sin_t	sind;
5190 
5191 		sind = sin_null;
5192 		sind.sin_addr.s_addr = ipha->ipha_dst;
5193 		sind.sin_port = *(uint16_t *)tcph->th_fport;
5194 		sind.sin_family = AF_INET;
5195 		tpi_mp = mi_tpi_extconn_ind(NULL,
5196 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
5197 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
5198 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5199 	} else {
5200 		tpi_mp = mi_tpi_conn_ind(NULL,
5201 		    (char *)&sin, sizeof (sin_t),
5202 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5203 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5204 	}
5205 
5206 	if (tpi_mp == NULL) {
5207 		return (ENOMEM);
5208 	}
5209 
5210 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
5211 	connp->conn_send = ip_output;
5212 	connp->conn_recv = tcp_input;
5213 	connp->conn_fully_bound = B_FALSE;
5214 
5215 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
5216 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
5217 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
5218 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
5219 
5220 	if (tcps->tcps_trace) {
5221 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
5222 	}
5223 
5224 	/* Inherit information from the "parent" */
5225 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
5226 	tcp->tcp_family = ltcp->tcp_family;
5227 	tcp->tcp_wq = ltcp->tcp_wq;
5228 	tcp->tcp_rq = ltcp->tcp_rq;
5229 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
5230 	tcp->tcp_detached = B_TRUE;
5231 	if ((err = tcp_init_values(tcp)) != 0) {
5232 		freemsg(tpi_mp);
5233 		return (err);
5234 	}
5235 
5236 	/*
5237 	 * Let's make sure that eager tcp template has enough space to
5238 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
5239 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
5240 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
5241 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
5242 	 * extension headers or with ip6i_t struct). Note that bcopy() below
5243 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
5244 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
5245 	 */
5246 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
5247 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
5248 
5249 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5250 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5251 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5252 	tcp->tcp_ttl = ltcp->tcp_ttl;
5253 	tcp->tcp_tos = ltcp->tcp_tos;
5254 
5255 	/* Copy the IP+TCP header template from listener to eager */
5256 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5257 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5258 	tcp->tcp_ip6h = NULL;
5259 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5260 	    tcp->tcp_ip_hdr_len);
5261 
5262 	/* Initialize the IP addresses and Ports */
5263 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5264 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5265 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5266 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
5267 
5268 	/* Source routing option copyover (reverse it) */
5269 	if (tcps->tcps_rev_src_routes)
5270 		tcp_opt_reverse(tcp, ipha);
5271 
5272 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5273 	ASSERT(!tcp->tcp_tconnind_started);
5274 
5275 	/*
5276 	 * If the SYN contains a credential, it's a loopback packet; attach
5277 	 * the credential to the TPI message.
5278 	 */
5279 	if ((cr = DB_CRED(idmp)) != NULL) {
5280 		mblk_setcred(tpi_mp, cr);
5281 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5282 	}
5283 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5284 
5285 	/* Inherit the listener's SSL protection state */
5286 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5287 		kssl_hold_ent(tcp->tcp_kssl_ent);
5288 		tcp->tcp_kssl_pending = B_TRUE;
5289 	}
5290 
5291 	return (0);
5292 }
5293 
5294 /*
5295  * sets up conn for ipsec.
5296  * if the first mblk is M_CTL it is consumed and mpp is updated.
5297  * in case of error mpp is freed.
5298  */
5299 conn_t *
5300 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
5301 {
5302 	conn_t 		*connp = tcp->tcp_connp;
5303 	conn_t 		*econnp;
5304 	squeue_t 	*new_sqp;
5305 	mblk_t 		*first_mp = *mpp;
5306 	mblk_t		*mp = *mpp;
5307 	boolean_t	mctl_present = B_FALSE;
5308 	uint_t		ipvers;
5309 
5310 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
5311 	if (econnp == NULL) {
5312 		freemsg(first_mp);
5313 		return (NULL);
5314 	}
5315 	if (DB_TYPE(mp) == M_CTL) {
5316 		if (mp->b_cont == NULL ||
5317 		    mp->b_cont->b_datap->db_type != M_DATA) {
5318 			freemsg(first_mp);
5319 			return (NULL);
5320 		}
5321 		mp = mp->b_cont;
5322 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
5323 			freemsg(first_mp);
5324 			return (NULL);
5325 		}
5326 
5327 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5328 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5329 		mctl_present = B_TRUE;
5330 	} else {
5331 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
5332 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5333 	}
5334 
5335 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5336 	DB_CKSUMSTART(mp) = 0;
5337 
5338 	ASSERT(OK_32PTR(mp->b_rptr));
5339 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5340 	if (ipvers == IPV4_VERSION) {
5341 		uint16_t  	*up;
5342 		uint32_t	ports;
5343 		ipha_t		*ipha;
5344 
5345 		ipha = (ipha_t *)mp->b_rptr;
5346 		up = (uint16_t *)((uchar_t *)ipha +
5347 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5348 		ports = *(uint32_t *)up;
5349 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5350 		    ipha->ipha_dst, ipha->ipha_src, ports);
5351 	} else {
5352 		uint16_t  	*up;
5353 		uint32_t	ports;
5354 		uint16_t	ip_hdr_len;
5355 		uint8_t		*nexthdrp;
5356 		ip6_t 		*ip6h;
5357 		tcph_t		*tcph;
5358 
5359 		ip6h = (ip6_t *)mp->b_rptr;
5360 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5361 			ip_hdr_len = IPV6_HDR_LEN;
5362 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5363 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5364 			CONN_DEC_REF(econnp);
5365 			freemsg(first_mp);
5366 			return (NULL);
5367 		}
5368 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5369 		up = (uint16_t *)tcph->th_lport;
5370 		ports = *(uint32_t *)up;
5371 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5372 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5373 	}
5374 
5375 	/*
5376 	 * The caller already ensured that there is a sqp present.
5377 	 */
5378 	econnp->conn_sqp = new_sqp;
5379 
5380 	if (connp->conn_policy != NULL) {
5381 		ipsec_in_t *ii;
5382 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5383 		ASSERT(ii->ipsec_in_policy == NULL);
5384 		IPPH_REFHOLD(connp->conn_policy);
5385 		ii->ipsec_in_policy = connp->conn_policy;
5386 
5387 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5388 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5389 			CONN_DEC_REF(econnp);
5390 			freemsg(first_mp);
5391 			return (NULL);
5392 		}
5393 	}
5394 
5395 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5396 		CONN_DEC_REF(econnp);
5397 		freemsg(first_mp);
5398 		return (NULL);
5399 	}
5400 
5401 	/*
5402 	 * If we know we have some policy, pass the "IPSEC"
5403 	 * options size TCP uses this adjust the MSS.
5404 	 */
5405 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5406 	if (mctl_present) {
5407 		freeb(first_mp);
5408 		*mpp = mp;
5409 	}
5410 
5411 	return (econnp);
5412 }
5413 
5414 /*
5415  * tcp_get_conn/tcp_free_conn
5416  *
5417  * tcp_get_conn is used to get a clean tcp connection structure.
5418  * It tries to reuse the connections put on the freelist by the
5419  * time_wait_collector failing which it goes to kmem_cache. This
5420  * way has two benefits compared to just allocating from and
5421  * freeing to kmem_cache.
5422  * 1) The time_wait_collector can free (which includes the cleanup)
5423  * outside the squeue. So when the interrupt comes, we have a clean
5424  * connection sitting in the freelist. Obviously, this buys us
5425  * performance.
5426  *
5427  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5428  * has multiple disadvantages - tying up the squeue during alloc, and the
5429  * fact that IPSec policy initialization has to happen here which
5430  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5431  * But allocating the conn/tcp in IP land is also not the best since
5432  * we can't check the 'q' and 'q0' which are protected by squeue and
5433  * blindly allocate memory which might have to be freed here if we are
5434  * not allowed to accept the connection. By using the freelist and
5435  * putting the conn/tcp back in freelist, we don't pay a penalty for
5436  * allocating memory without checking 'q/q0' and freeing it if we can't
5437  * accept the connection.
5438  *
5439  * Care should be taken to put the conn back in the same squeue's freelist
5440  * from which it was allocated. Best results are obtained if conn is
5441  * allocated from listener's squeue and freed to the same. Time wait
5442  * collector will free up the freelist is the connection ends up sitting
5443  * there for too long.
5444  */
5445 void *
5446 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5447 {
5448 	tcp_t			*tcp = NULL;
5449 	conn_t			*connp = NULL;
5450 	squeue_t		*sqp = (squeue_t *)arg;
5451 	tcp_squeue_priv_t 	*tcp_time_wait;
5452 	netstack_t		*ns;
5453 
5454 	tcp_time_wait =
5455 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5456 
5457 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5458 	tcp = tcp_time_wait->tcp_free_list;
5459 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5460 	if (tcp != NULL) {
5461 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5462 		tcp_time_wait->tcp_free_list_cnt--;
5463 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5464 		tcp->tcp_time_wait_next = NULL;
5465 		connp = tcp->tcp_connp;
5466 		connp->conn_flags |= IPCL_REUSED;
5467 
5468 		ASSERT(tcp->tcp_tcps == NULL);
5469 		ASSERT(connp->conn_netstack == NULL);
5470 		ns = tcps->tcps_netstack;
5471 		netstack_hold(ns);
5472 		connp->conn_netstack = ns;
5473 		tcp->tcp_tcps = tcps;
5474 		TCPS_REFHOLD(tcps);
5475 		ipcl_globalhash_insert(connp);
5476 		return ((void *)connp);
5477 	}
5478 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5479 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5480 	    tcps->tcps_netstack)) == NULL)
5481 		return (NULL);
5482 	tcp = connp->conn_tcp;
5483 	tcp->tcp_tcps = tcps;
5484 	TCPS_REFHOLD(tcps);
5485 	return ((void *)connp);
5486 }
5487 
5488 /*
5489  * Update the cached label for the given tcp_t.  This should be called once per
5490  * connection, and before any packets are sent or tcp_process_options is
5491  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5492  */
5493 static boolean_t
5494 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5495 {
5496 	conn_t *connp = tcp->tcp_connp;
5497 
5498 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5499 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5500 		int added;
5501 
5502 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5503 		    connp->conn_mac_exempt,
5504 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5505 			return (B_FALSE);
5506 
5507 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5508 		if (added == -1)
5509 			return (B_FALSE);
5510 		tcp->tcp_hdr_len += added;
5511 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5512 		tcp->tcp_ip_hdr_len += added;
5513 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5514 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5515 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5516 			    tcp->tcp_hdr_len);
5517 			if (added == -1)
5518 				return (B_FALSE);
5519 			tcp->tcp_hdr_len += added;
5520 			tcp->tcp_tcph = (tcph_t *)
5521 			    ((uchar_t *)tcp->tcp_tcph + added);
5522 			tcp->tcp_ip_hdr_len += added;
5523 		}
5524 	} else {
5525 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5526 
5527 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5528 		    connp->conn_mac_exempt,
5529 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5530 			return (B_FALSE);
5531 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5532 		    &tcp->tcp_label_len, optbuf) != 0)
5533 			return (B_FALSE);
5534 		if (tcp_build_hdrs(tcp->tcp_rq, tcp) != 0)
5535 			return (B_FALSE);
5536 	}
5537 
5538 	connp->conn_ulp_labeled = 1;
5539 
5540 	return (B_TRUE);
5541 }
5542 
5543 /* BEGIN CSTYLED */
5544 /*
5545  *
5546  * The sockfs ACCEPT path:
5547  * =======================
5548  *
5549  * The eager is now established in its own perimeter as soon as SYN is
5550  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5551  * completes the accept processing on the acceptor STREAM. The sending
5552  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5553  * listener but a TLI/XTI listener completes the accept processing
5554  * on the listener perimeter.
5555  *
5556  * Common control flow for 3 way handshake:
5557  * ----------------------------------------
5558  *
5559  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5560  *					-> tcp_conn_request()
5561  *
5562  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5563  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5564  *
5565  * Sockfs ACCEPT Path:
5566  * -------------------
5567  *
5568  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5569  * as STREAM entry point)
5570  *
5571  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5572  *
5573  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5574  * association (we are not behind eager's squeue but sockfs is protecting us
5575  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5576  * is changed to point at tcp_wput().
5577  *
5578  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5579  * listener (done on listener's perimeter).
5580  *
5581  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5582  * accept.
5583  *
5584  * TLI/XTI client ACCEPT path:
5585  * ---------------------------
5586  *
5587  * soaccept() sends T_CONN_RES on the listener STREAM.
5588  *
5589  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5590  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5591  *
5592  * Locks:
5593  * ======
5594  *
5595  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5596  * and listeners->tcp_eager_next_q.
5597  *
5598  * Referencing:
5599  * ============
5600  *
5601  * 1) We start out in tcp_conn_request by eager placing a ref on
5602  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5603  *
5604  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5605  * doing so we place a ref on the eager. This ref is finally dropped at the
5606  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5607  * reference is dropped by the squeue framework.
5608  *
5609  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5610  *
5611  * The reference must be released by the same entity that added the reference
5612  * In the above scheme, the eager is the entity that adds and releases the
5613  * references. Note that tcp_accept_finish executes in the squeue of the eager
5614  * (albeit after it is attached to the acceptor stream). Though 1. executes
5615  * in the listener's squeue, the eager is nascent at this point and the
5616  * reference can be considered to have been added on behalf of the eager.
5617  *
5618  * Eager getting a Reset or listener closing:
5619  * ==========================================
5620  *
5621  * Once the listener and eager are linked, the listener never does the unlink.
5622  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5623  * a message on all eager perimeter. The eager then does the unlink, clears
5624  * any pointers to the listener's queue and drops the reference to the
5625  * listener. The listener waits in tcp_close outside the squeue until its
5626  * refcount has dropped to 1. This ensures that the listener has waited for
5627  * all eagers to clear their association with the listener.
5628  *
5629  * Similarly, if eager decides to go away, it can unlink itself and close.
5630  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5631  * the reference to eager is still valid because of the extra ref we put
5632  * in tcp_send_conn_ind.
5633  *
5634  * Listener can always locate the eager under the protection
5635  * of the listener->tcp_eager_lock, and then do a refhold
5636  * on the eager during the accept processing.
5637  *
5638  * The acceptor stream accesses the eager in the accept processing
5639  * based on the ref placed on eager before sending T_conn_ind.
5640  * The only entity that can negate this refhold is a listener close
5641  * which is mutually exclusive with an active acceptor stream.
5642  *
5643  * Eager's reference on the listener
5644  * ===================================
5645  *
5646  * If the accept happens (even on a closed eager) the eager drops its
5647  * reference on the listener at the start of tcp_accept_finish. If the
5648  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5649  * the reference is dropped in tcp_closei_local. If the listener closes,
5650  * the reference is dropped in tcp_eager_kill. In all cases the reference
5651  * is dropped while executing in the eager's context (squeue).
5652  */
5653 /* END CSTYLED */
5654 
5655 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5656 
5657 /*
5658  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5659  * tcp_rput_data will not see any SYN packets.
5660  */
5661 /* ARGSUSED */
5662 void
5663 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5664 {
5665 	tcph_t		*tcph;
5666 	uint32_t	seg_seq;
5667 	tcp_t		*eager;
5668 	uint_t		ipvers;
5669 	ipha_t		*ipha;
5670 	ip6_t		*ip6h;
5671 	int		err;
5672 	conn_t		*econnp = NULL;
5673 	squeue_t	*new_sqp;
5674 	mblk_t		*mp1;
5675 	uint_t 		ip_hdr_len;
5676 	conn_t		*connp = (conn_t *)arg;
5677 	tcp_t		*tcp = connp->conn_tcp;
5678 	cred_t		*credp;
5679 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5680 	ip_stack_t	*ipst;
5681 
5682 	if (tcp->tcp_state != TCPS_LISTEN)
5683 		goto error2;
5684 
5685 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5686 
5687 	mutex_enter(&tcp->tcp_eager_lock);
5688 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5689 		mutex_exit(&tcp->tcp_eager_lock);
5690 		TCP_STAT(tcps, tcp_listendrop);
5691 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5692 		if (tcp->tcp_debug) {
5693 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5694 			    "tcp_conn_request: listen backlog (max=%d) "
5695 			    "overflow (%d pending) on %s",
5696 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5697 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5698 		}
5699 		goto error2;
5700 	}
5701 
5702 	if (tcp->tcp_conn_req_cnt_q0 >=
5703 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5704 		/*
5705 		 * Q0 is full. Drop a pending half-open req from the queue
5706 		 * to make room for the new SYN req. Also mark the time we
5707 		 * drop a SYN.
5708 		 *
5709 		 * A more aggressive defense against SYN attack will
5710 		 * be to set the "tcp_syn_defense" flag now.
5711 		 */
5712 		TCP_STAT(tcps, tcp_listendropq0);
5713 		tcp->tcp_last_rcv_lbolt = lbolt64;
5714 		if (!tcp_drop_q0(tcp)) {
5715 			mutex_exit(&tcp->tcp_eager_lock);
5716 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5717 			if (tcp->tcp_debug) {
5718 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5719 				    "tcp_conn_request: listen half-open queue "
5720 				    "(max=%d) full (%d pending) on %s",
5721 				    tcps->tcps_conn_req_max_q0,
5722 				    tcp->tcp_conn_req_cnt_q0,
5723 				    tcp_display(tcp, NULL,
5724 				    DISP_PORT_ONLY));
5725 			}
5726 			goto error2;
5727 		}
5728 	}
5729 	mutex_exit(&tcp->tcp_eager_lock);
5730 
5731 	/*
5732 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5733 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5734 	 * link local address.  If IPSec is enabled, db_struioflag has
5735 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5736 	 * otherwise an error case if neither of them is set.
5737 	 */
5738 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5739 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5740 		DB_CKSUMSTART(mp) = 0;
5741 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5742 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5743 		if (econnp == NULL)
5744 			goto error2;
5745 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5746 		econnp->conn_sqp = new_sqp;
5747 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5748 		/*
5749 		 * mp is updated in tcp_get_ipsec_conn().
5750 		 */
5751 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5752 		if (econnp == NULL) {
5753 			/*
5754 			 * mp freed by tcp_get_ipsec_conn.
5755 			 */
5756 			return;
5757 		}
5758 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5759 	} else {
5760 		goto error2;
5761 	}
5762 
5763 	ASSERT(DB_TYPE(mp) == M_DATA);
5764 
5765 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5766 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5767 	ASSERT(OK_32PTR(mp->b_rptr));
5768 	if (ipvers == IPV4_VERSION) {
5769 		ipha = (ipha_t *)mp->b_rptr;
5770 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5771 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5772 	} else {
5773 		ip6h = (ip6_t *)mp->b_rptr;
5774 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5775 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5776 	}
5777 
5778 	if (tcp->tcp_family == AF_INET) {
5779 		ASSERT(ipvers == IPV4_VERSION);
5780 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5781 	} else {
5782 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5783 	}
5784 
5785 	if (err)
5786 		goto error3;
5787 
5788 	eager = econnp->conn_tcp;
5789 
5790 	/* Inherit various TCP parameters from the listener */
5791 	eager->tcp_naglim = tcp->tcp_naglim;
5792 	eager->tcp_first_timer_threshold =
5793 	    tcp->tcp_first_timer_threshold;
5794 	eager->tcp_second_timer_threshold =
5795 	    tcp->tcp_second_timer_threshold;
5796 
5797 	eager->tcp_first_ctimer_threshold =
5798 	    tcp->tcp_first_ctimer_threshold;
5799 	eager->tcp_second_ctimer_threshold =
5800 	    tcp->tcp_second_ctimer_threshold;
5801 
5802 	/*
5803 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5804 	 * If it does not, the eager's receive window will be set to the
5805 	 * listener's receive window later in this function.
5806 	 */
5807 	eager->tcp_rwnd = 0;
5808 
5809 	/*
5810 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5811 	 * calling tcp_process_options() where tcp_mss_set() is called
5812 	 * to set the initial cwnd.
5813 	 */
5814 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5815 
5816 	/*
5817 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5818 	 * zone id before the accept is completed in tcp_wput_accept().
5819 	 */
5820 	econnp->conn_zoneid = connp->conn_zoneid;
5821 	econnp->conn_allzones = connp->conn_allzones;
5822 
5823 	/* Copy nexthop information from listener to eager */
5824 	if (connp->conn_nexthop_set) {
5825 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5826 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5827 	}
5828 
5829 	/*
5830 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5831 	 * eager is accepted
5832 	 */
5833 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5834 	crhold(credp);
5835 
5836 	/*
5837 	 * If the caller has the process-wide flag set, then default to MAC
5838 	 * exempt mode.  This allows read-down to unlabeled hosts.
5839 	 */
5840 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5841 		econnp->conn_mac_exempt = B_TRUE;
5842 
5843 	if (is_system_labeled()) {
5844 		cred_t *cr;
5845 
5846 		if (connp->conn_mlp_type != mlptSingle) {
5847 			cr = econnp->conn_peercred = DB_CRED(mp);
5848 			if (cr != NULL)
5849 				crhold(cr);
5850 			else
5851 				cr = econnp->conn_cred;
5852 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5853 			    econnp, cred_t *, cr)
5854 		} else {
5855 			cr = econnp->conn_cred;
5856 			DTRACE_PROBE2(syn_accept, conn_t *,
5857 			    econnp, cred_t *, cr)
5858 		}
5859 
5860 		if (!tcp_update_label(eager, cr)) {
5861 			DTRACE_PROBE3(
5862 			    tx__ip__log__error__connrequest__tcp,
5863 			    char *, "eager connp(1) label on SYN mp(2) failed",
5864 			    conn_t *, econnp, mblk_t *, mp);
5865 			goto error3;
5866 		}
5867 	}
5868 
5869 	eager->tcp_hard_binding = B_TRUE;
5870 
5871 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5872 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5873 
5874 	CL_INET_CONNECT(eager);
5875 
5876 	/*
5877 	 * No need to check for multicast destination since ip will only pass
5878 	 * up multicasts to those that have expressed interest
5879 	 * TODO: what about rejecting broadcasts?
5880 	 * Also check that source is not a multicast or broadcast address.
5881 	 */
5882 	eager->tcp_state = TCPS_SYN_RCVD;
5883 
5884 
5885 	/*
5886 	 * There should be no ire in the mp as we are being called after
5887 	 * receiving the SYN.
5888 	 */
5889 	ASSERT(tcp_ire_mp(mp) == NULL);
5890 
5891 	/*
5892 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5893 	 */
5894 
5895 	if (tcp_adapt_ire(eager, NULL) == 0) {
5896 		/* Undo the bind_hash_insert */
5897 		tcp_bind_hash_remove(eager);
5898 		goto error3;
5899 	}
5900 
5901 	/* Process all TCP options. */
5902 	tcp_process_options(eager, tcph);
5903 
5904 	/* Is the other end ECN capable? */
5905 	if (tcps->tcps_ecn_permitted >= 1 &&
5906 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5907 		eager->tcp_ecn_ok = B_TRUE;
5908 	}
5909 
5910 	/*
5911 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5912 	 * window size changed via SO_RCVBUF option.  First round up the
5913 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5914 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5915 	 * setting.
5916 	 *
5917 	 * Note if there is a rpipe metric associated with the remote host,
5918 	 * we should not inherit receive window size from listener.
5919 	 */
5920 	eager->tcp_rwnd = MSS_ROUNDUP(
5921 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5922 	    eager->tcp_rwnd), eager->tcp_mss);
5923 	if (eager->tcp_snd_ws_ok)
5924 		tcp_set_ws_value(eager);
5925 	/*
5926 	 * Note that this is the only place tcp_rwnd_set() is called for
5927 	 * accepting a connection.  We need to call it here instead of
5928 	 * after the 3-way handshake because we need to tell the other
5929 	 * side our rwnd in the SYN-ACK segment.
5930 	 */
5931 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5932 
5933 	/*
5934 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5935 	 * via soaccept()->soinheritoptions() which essentially applies
5936 	 * all the listener options to the new STREAM. The options that we
5937 	 * need to take care of are:
5938 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5939 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5940 	 * SO_SNDBUF, SO_RCVBUF.
5941 	 *
5942 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5943 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5944 	 *		tcp_maxpsz_set() gets called later from
5945 	 *		tcp_accept_finish(), the option takes effect.
5946 	 *
5947 	 */
5948 	/* Set the TCP options */
5949 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5950 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5951 	eager->tcp_oobinline = tcp->tcp_oobinline;
5952 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5953 	eager->tcp_broadcast = tcp->tcp_broadcast;
5954 	eager->tcp_useloopback = tcp->tcp_useloopback;
5955 	eager->tcp_dontroute = tcp->tcp_dontroute;
5956 	eager->tcp_linger = tcp->tcp_linger;
5957 	eager->tcp_lingertime = tcp->tcp_lingertime;
5958 	if (tcp->tcp_ka_enabled)
5959 		eager->tcp_ka_enabled = 1;
5960 
5961 	/* Set the IP options */
5962 	econnp->conn_broadcast = connp->conn_broadcast;
5963 	econnp->conn_loopback = connp->conn_loopback;
5964 	econnp->conn_dontroute = connp->conn_dontroute;
5965 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5966 
5967 	/* Put a ref on the listener for the eager. */
5968 	CONN_INC_REF(connp);
5969 	mutex_enter(&tcp->tcp_eager_lock);
5970 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5971 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5972 	tcp->tcp_eager_next_q0 = eager;
5973 	eager->tcp_eager_prev_q0 = tcp;
5974 
5975 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5976 	eager->tcp_listener = tcp;
5977 	eager->tcp_saved_listener = tcp;
5978 
5979 	/*
5980 	 * Tag this detached tcp vector for later retrieval
5981 	 * by our listener client in tcp_accept().
5982 	 */
5983 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5984 	tcp->tcp_conn_req_cnt_q0++;
5985 	if (++tcp->tcp_conn_req_seqnum == -1) {
5986 		/*
5987 		 * -1 is "special" and defined in TPI as something
5988 		 * that should never be used in T_CONN_IND
5989 		 */
5990 		++tcp->tcp_conn_req_seqnum;
5991 	}
5992 	mutex_exit(&tcp->tcp_eager_lock);
5993 
5994 	if (tcp->tcp_syn_defense) {
5995 		/* Don't drop the SYN that comes from a good IP source */
5996 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5997 		if (addr_cache != NULL && eager->tcp_remote ==
5998 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5999 			eager->tcp_dontdrop = B_TRUE;
6000 		}
6001 	}
6002 
6003 	/*
6004 	 * We need to insert the eager in its own perimeter but as soon
6005 	 * as we do that, we expose the eager to the classifier and
6006 	 * should not touch any field outside the eager's perimeter.
6007 	 * So do all the work necessary before inserting the eager
6008 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
6009 	 * will succeed but undo everything if it fails.
6010 	 */
6011 	seg_seq = ABE32_TO_U32(tcph->th_seq);
6012 	eager->tcp_irs = seg_seq;
6013 	eager->tcp_rack = seg_seq;
6014 	eager->tcp_rnxt = seg_seq + 1;
6015 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
6016 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
6017 	eager->tcp_state = TCPS_SYN_RCVD;
6018 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
6019 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
6020 	if (mp1 == NULL) {
6021 		/*
6022 		 * Increment the ref count as we are going to
6023 		 * enqueueing an mp in squeue
6024 		 */
6025 		CONN_INC_REF(econnp);
6026 		goto error;
6027 	}
6028 	DB_CPID(mp1) = tcp->tcp_cpid;
6029 	eager->tcp_cpid = tcp->tcp_cpid;
6030 	eager->tcp_open_time = lbolt64;
6031 
6032 	/*
6033 	 * We need to start the rto timer. In normal case, we start
6034 	 * the timer after sending the packet on the wire (or at
6035 	 * least believing that packet was sent by waiting for
6036 	 * CALL_IP_WPUT() to return). Since this is the first packet
6037 	 * being sent on the wire for the eager, our initial tcp_rto
6038 	 * is at least tcp_rexmit_interval_min which is a fairly
6039 	 * large value to allow the algorithm to adjust slowly to large
6040 	 * fluctuations of RTT during first few transmissions.
6041 	 *
6042 	 * Starting the timer first and then sending the packet in this
6043 	 * case shouldn't make much difference since tcp_rexmit_interval_min
6044 	 * is of the order of several 100ms and starting the timer
6045 	 * first and then sending the packet will result in difference
6046 	 * of few micro seconds.
6047 	 *
6048 	 * Without this optimization, we are forced to hold the fanout
6049 	 * lock across the ipcl_bind_insert() and sending the packet
6050 	 * so that we don't race against an incoming packet (maybe RST)
6051 	 * for this eager.
6052 	 *
6053 	 * It is necessary to acquire an extra reference on the eager
6054 	 * at this point and hold it until after tcp_send_data() to
6055 	 * ensure against an eager close race.
6056 	 */
6057 
6058 	CONN_INC_REF(eager->tcp_connp);
6059 
6060 	TCP_RECORD_TRACE(eager, mp1, TCP_TRACE_SEND_PKT);
6061 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
6062 
6063 
6064 	/*
6065 	 * Insert the eager in its own perimeter now. We are ready to deal
6066 	 * with any packets on eager.
6067 	 */
6068 	if (eager->tcp_ipversion == IPV4_VERSION) {
6069 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
6070 			goto error;
6071 		}
6072 	} else {
6073 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
6074 			goto error;
6075 		}
6076 	}
6077 
6078 	/* mark conn as fully-bound */
6079 	econnp->conn_fully_bound = B_TRUE;
6080 
6081 	/* Send the SYN-ACK */
6082 	tcp_send_data(eager, eager->tcp_wq, mp1);
6083 	CONN_DEC_REF(eager->tcp_connp);
6084 	freemsg(mp);
6085 
6086 	return;
6087 error:
6088 	freemsg(mp1);
6089 	eager->tcp_closemp_used = B_TRUE;
6090 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6091 	squeue_fill(econnp->conn_sqp, &eager->tcp_closemp, tcp_eager_kill,
6092 	    econnp, SQTAG_TCP_CONN_REQ_2);
6093 
6094 	/*
6095 	 * If a connection already exists, send the mp to that connections so
6096 	 * that it can be appropriately dealt with.
6097 	 */
6098 	ipst = tcps->tcps_netstack->netstack_ip;
6099 
6100 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
6101 		if (!IPCL_IS_CONNECTED(econnp)) {
6102 			/*
6103 			 * Something bad happened. ipcl_conn_insert()
6104 			 * failed because a connection already existed
6105 			 * in connected hash but we can't find it
6106 			 * anymore (someone blew it away). Just
6107 			 * free this message and hopefully remote
6108 			 * will retransmit at which time the SYN can be
6109 			 * treated as a new connection or dealth with
6110 			 * a TH_RST if a connection already exists.
6111 			 */
6112 			CONN_DEC_REF(econnp);
6113 			freemsg(mp);
6114 		} else {
6115 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
6116 			    econnp, SQTAG_TCP_CONN_REQ_1);
6117 		}
6118 	} else {
6119 		/* Nobody wants this packet */
6120 		freemsg(mp);
6121 	}
6122 	return;
6123 error3:
6124 	CONN_DEC_REF(econnp);
6125 error2:
6126 	freemsg(mp);
6127 }
6128 
6129 /*
6130  * In an ideal case of vertical partition in NUMA architecture, its
6131  * beneficial to have the listener and all the incoming connections
6132  * tied to the same squeue. The other constraint is that incoming
6133  * connections should be tied to the squeue attached to interrupted
6134  * CPU for obvious locality reason so this leaves the listener to
6135  * be tied to the same squeue. Our only problem is that when listener
6136  * is binding, the CPU that will get interrupted by the NIC whose
6137  * IP address the listener is binding to is not even known. So
6138  * the code below allows us to change that binding at the time the
6139  * CPU is interrupted by virtue of incoming connection's squeue.
6140  *
6141  * This is usefull only in case of a listener bound to a specific IP
6142  * address. For other kind of listeners, they get bound the
6143  * very first time and there is no attempt to rebind them.
6144  */
6145 void
6146 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
6147 {
6148 	conn_t		*connp = (conn_t *)arg;
6149 	squeue_t	*sqp = (squeue_t *)arg2;
6150 	squeue_t	*new_sqp;
6151 	uint32_t	conn_flags;
6152 
6153 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
6154 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
6155 	} else {
6156 		goto done;
6157 	}
6158 
6159 	if (connp->conn_fanout == NULL)
6160 		goto done;
6161 
6162 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
6163 		mutex_enter(&connp->conn_fanout->connf_lock);
6164 		mutex_enter(&connp->conn_lock);
6165 		/*
6166 		 * No one from read or write side can access us now
6167 		 * except for already queued packets on this squeue.
6168 		 * But since we haven't changed the squeue yet, they
6169 		 * can't execute. If they are processed after we have
6170 		 * changed the squeue, they are sent back to the
6171 		 * correct squeue down below.
6172 		 * But a listner close can race with processing of
6173 		 * incoming SYN. If incoming SYN processing changes
6174 		 * the squeue then the listener close which is waiting
6175 		 * to enter the squeue would operate on the wrong
6176 		 * squeue. Hence we don't change the squeue here unless
6177 		 * the refcount is exactly the minimum refcount. The
6178 		 * minimum refcount of 4 is counted as - 1 each for
6179 		 * TCP and IP, 1 for being in the classifier hash, and
6180 		 * 1 for the mblk being processed.
6181 		 */
6182 
6183 		if (connp->conn_ref != 4 ||
6184 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
6185 			mutex_exit(&connp->conn_lock);
6186 			mutex_exit(&connp->conn_fanout->connf_lock);
6187 			goto done;
6188 		}
6189 		if (connp->conn_sqp != new_sqp) {
6190 			while (connp->conn_sqp != new_sqp)
6191 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
6192 		}
6193 
6194 		do {
6195 			conn_flags = connp->conn_flags;
6196 			conn_flags |= IPCL_FULLY_BOUND;
6197 			(void) cas32(&connp->conn_flags, connp->conn_flags,
6198 			    conn_flags);
6199 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
6200 
6201 		mutex_exit(&connp->conn_fanout->connf_lock);
6202 		mutex_exit(&connp->conn_lock);
6203 	}
6204 
6205 done:
6206 	if (connp->conn_sqp != sqp) {
6207 		CONN_INC_REF(connp);
6208 		squeue_fill(connp->conn_sqp, mp,
6209 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
6210 	} else {
6211 		tcp_conn_request(connp, mp, sqp);
6212 	}
6213 }
6214 
6215 /*
6216  * Successful connect request processing begins when our client passes
6217  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
6218  * our T_OK_ACK reply message upstream.  The control flow looks like this:
6219  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
6220  *   upstream <- tcp_rput()                <- IP
6221  * After various error checks are completed, tcp_connect() lays
6222  * the target address and port into the composite header template,
6223  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
6224  * request followed by an IRE request, and passes the three mblk message
6225  * down to IP looking like this:
6226  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
6227  * Processing continues in tcp_rput() when we receive the following message:
6228  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
6229  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
6230  * to fire off the connection request, and then passes the T_OK_ACK mblk
6231  * upstream that we filled in below.  There are, of course, numerous
6232  * error conditions along the way which truncate the processing described
6233  * above.
6234  */
6235 static void
6236 tcp_connect(tcp_t *tcp, mblk_t *mp)
6237 {
6238 	sin_t		*sin;
6239 	sin6_t		*sin6;
6240 	queue_t		*q = tcp->tcp_wq;
6241 	struct T_conn_req	*tcr;
6242 	ipaddr_t	*dstaddrp;
6243 	in_port_t	dstport;
6244 	uint_t		srcid;
6245 
6246 	tcr = (struct T_conn_req *)mp->b_rptr;
6247 
6248 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6249 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
6250 		tcp_err_ack(tcp, mp, TPROTO, 0);
6251 		return;
6252 	}
6253 
6254 	/*
6255 	 * Determine packet type based on type of address passed in
6256 	 * the request should contain an IPv4 or IPv6 address.
6257 	 * Make sure that address family matches the type of
6258 	 * family of the the address passed down
6259 	 */
6260 	switch (tcr->DEST_length) {
6261 	default:
6262 		tcp_err_ack(tcp, mp, TBADADDR, 0);
6263 		return;
6264 
6265 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
6266 		/*
6267 		 * XXX: The check for valid DEST_length was not there
6268 		 * in earlier releases and some buggy
6269 		 * TLI apps (e.g Sybase) got away with not feeding
6270 		 * in sin_zero part of address.
6271 		 * We allow that bug to keep those buggy apps humming.
6272 		 * Test suites require the check on DEST_length.
6273 		 * We construct a new mblk with valid DEST_length
6274 		 * free the original so the rest of the code does
6275 		 * not have to keep track of this special shorter
6276 		 * length address case.
6277 		 */
6278 		mblk_t *nmp;
6279 		struct T_conn_req *ntcr;
6280 		sin_t *nsin;
6281 
6282 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
6283 		    tcr->OPT_length, BPRI_HI);
6284 		if (nmp == NULL) {
6285 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6286 			return;
6287 		}
6288 		ntcr = (struct T_conn_req *)nmp->b_rptr;
6289 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
6290 		ntcr->PRIM_type = T_CONN_REQ;
6291 		ntcr->DEST_length = sizeof (sin_t);
6292 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6293 
6294 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6295 		*nsin = sin_null;
6296 		/* Get pointer to shorter address to copy from original mp */
6297 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6298 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6299 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6300 			freemsg(nmp);
6301 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6302 			return;
6303 		}
6304 		nsin->sin_family = sin->sin_family;
6305 		nsin->sin_port = sin->sin_port;
6306 		nsin->sin_addr = sin->sin_addr;
6307 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6308 		nmp->b_wptr = (uchar_t *)&nsin[1];
6309 		if (tcr->OPT_length != 0) {
6310 			ntcr->OPT_length = tcr->OPT_length;
6311 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6312 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6313 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6314 			    tcr->OPT_length);
6315 			nmp->b_wptr += tcr->OPT_length;
6316 		}
6317 		freemsg(mp);	/* original mp freed */
6318 		mp = nmp;	/* re-initialize original variables */
6319 		tcr = ntcr;
6320 	}
6321 	/* FALLTHRU */
6322 
6323 	case sizeof (sin_t):
6324 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6325 		    sizeof (sin_t));
6326 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6327 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6328 			return;
6329 		}
6330 		if (tcp->tcp_family != AF_INET ||
6331 		    sin->sin_family != AF_INET) {
6332 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6333 			return;
6334 		}
6335 		if (sin->sin_port == 0) {
6336 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6337 			return;
6338 		}
6339 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
6340 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6341 			return;
6342 		}
6343 
6344 		break;
6345 
6346 	case sizeof (sin6_t):
6347 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
6348 		    sizeof (sin6_t));
6349 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
6350 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6351 			return;
6352 		}
6353 		if (tcp->tcp_family != AF_INET6 ||
6354 		    sin6->sin6_family != AF_INET6) {
6355 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6356 			return;
6357 		}
6358 		if (sin6->sin6_port == 0) {
6359 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6360 			return;
6361 		}
6362 		break;
6363 	}
6364 	/*
6365 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6366 	 * should key on their sequence number and cut them loose.
6367 	 */
6368 
6369 	/*
6370 	 * If options passed in, feed it for verification and handling
6371 	 */
6372 	if (tcr->OPT_length != 0) {
6373 		mblk_t	*ok_mp;
6374 		mblk_t	*discon_mp;
6375 		mblk_t  *conn_opts_mp;
6376 		int t_error, sys_error, do_disconnect;
6377 
6378 		conn_opts_mp = NULL;
6379 
6380 		if (tcp_conprim_opt_process(tcp, mp,
6381 		    &do_disconnect, &t_error, &sys_error) < 0) {
6382 			if (do_disconnect) {
6383 				ASSERT(t_error == 0 && sys_error == 0);
6384 				discon_mp = mi_tpi_discon_ind(NULL,
6385 				    ECONNREFUSED, 0);
6386 				if (!discon_mp) {
6387 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6388 					    TSYSERR, ENOMEM);
6389 					return;
6390 				}
6391 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6392 				if (!ok_mp) {
6393 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6394 					    TSYSERR, ENOMEM);
6395 					return;
6396 				}
6397 				qreply(q, ok_mp);
6398 				qreply(q, discon_mp); /* no flush! */
6399 			} else {
6400 				ASSERT(t_error != 0);
6401 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6402 				    sys_error);
6403 			}
6404 			return;
6405 		}
6406 		/*
6407 		 * Success in setting options, the mp option buffer represented
6408 		 * by OPT_length/offset has been potentially modified and
6409 		 * contains results of option processing. We copy it in
6410 		 * another mp to save it for potentially influencing returning
6411 		 * it in T_CONN_CONN.
6412 		 */
6413 		if (tcr->OPT_length != 0) { /* there are resulting options */
6414 			conn_opts_mp = copyb(mp);
6415 			if (!conn_opts_mp) {
6416 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6417 				    TSYSERR, ENOMEM);
6418 				return;
6419 			}
6420 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6421 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6422 			/*
6423 			 * Note:
6424 			 * These resulting option negotiation can include any
6425 			 * end-to-end negotiation options but there no such
6426 			 * thing (yet?) in our TCP/IP.
6427 			 */
6428 		}
6429 	}
6430 
6431 	/*
6432 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
6433 	 * make sure that the template IP header in the tcp structure is an
6434 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
6435 	 * need to this before we call tcp_bindi() so that the port lookup
6436 	 * code will look for ports in the correct port space (IPv4 and
6437 	 * IPv6 have separate port spaces).
6438 	 */
6439 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
6440 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6441 		int err = 0;
6442 
6443 		err = tcp_header_init_ipv4(tcp);
6444 		if (err != 0) {
6445 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6446 			goto connect_failed;
6447 		}
6448 		if (tcp->tcp_lport != 0)
6449 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
6450 	}
6451 
6452 	if (tcp->tcp_issocket) {
6453 		/*
6454 		 * TCP is _D_SODIRECT and sockfs is directly above so save
6455 		 * the shared sonode sodirect_t pointer (if any) to enable
6456 		 * TCP sodirect.
6457 		 */
6458 		tcp->tcp_sodirect = SOD_QTOSODP(tcp->tcp_rq);
6459 	}
6460 
6461 	switch (tcp->tcp_state) {
6462 	case TCPS_IDLE:
6463 		/*
6464 		 * We support quick connect, refer to comments in
6465 		 * tcp_connect_*()
6466 		 */
6467 		/* FALLTHRU */
6468 	case TCPS_BOUND:
6469 	case TCPS_LISTEN:
6470 		if (tcp->tcp_family == AF_INET6) {
6471 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6472 				tcp_connect_ipv6(tcp, mp,
6473 				    &sin6->sin6_addr,
6474 				    sin6->sin6_port, sin6->sin6_flowinfo,
6475 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
6476 				return;
6477 			}
6478 			/*
6479 			 * Destination adress is mapped IPv6 address.
6480 			 * Source bound address should be unspecified or
6481 			 * IPv6 mapped address as well.
6482 			 */
6483 			if (!IN6_IS_ADDR_UNSPECIFIED(
6484 			    &tcp->tcp_bound_source_v6) &&
6485 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
6486 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
6487 				    EADDRNOTAVAIL);
6488 				break;
6489 			}
6490 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
6491 			dstport = sin6->sin6_port;
6492 			srcid = sin6->__sin6_src_id;
6493 		} else {
6494 			dstaddrp = &sin->sin_addr.s_addr;
6495 			dstport = sin->sin_port;
6496 			srcid = 0;
6497 		}
6498 
6499 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
6500 		return;
6501 	default:
6502 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
6503 		break;
6504 	}
6505 	/*
6506 	 * Note: Code below is the "failure" case
6507 	 */
6508 	/* return error ack and blow away saved option results if any */
6509 connect_failed:
6510 	if (mp != NULL)
6511 		putnext(tcp->tcp_rq, mp);
6512 	else {
6513 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6514 		    TSYSERR, ENOMEM);
6515 	}
6516 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6517 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6518 }
6519 
6520 /*
6521  * Handle connect to IPv4 destinations, including connections for AF_INET6
6522  * sockets connecting to IPv4 mapped IPv6 destinations.
6523  */
6524 static void
6525 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
6526     uint_t srcid)
6527 {
6528 	tcph_t	*tcph;
6529 	mblk_t	*mp1;
6530 	ipaddr_t dstaddr = *dstaddrp;
6531 	int32_t	oldstate;
6532 	uint16_t lport;
6533 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6534 
6535 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6536 
6537 	/* Check for attempt to connect to INADDR_ANY */
6538 	if (dstaddr == INADDR_ANY)  {
6539 		/*
6540 		 * SunOS 4.x and 4.3 BSD allow an application
6541 		 * to connect a TCP socket to INADDR_ANY.
6542 		 * When they do this, the kernel picks the
6543 		 * address of one interface and uses it
6544 		 * instead.  The kernel usually ends up
6545 		 * picking the address of the loopback
6546 		 * interface.  This is an undocumented feature.
6547 		 * However, we provide the same thing here
6548 		 * in order to have source and binary
6549 		 * compatibility with SunOS 4.x.
6550 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6551 		 * generate the T_CONN_CON.
6552 		 */
6553 		dstaddr = htonl(INADDR_LOOPBACK);
6554 		*dstaddrp = dstaddr;
6555 	}
6556 
6557 	/* Handle __sin6_src_id if socket not bound to an IP address */
6558 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6559 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6560 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6561 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6562 		    tcp->tcp_ipha->ipha_src);
6563 	}
6564 
6565 	/*
6566 	 * Don't let an endpoint connect to itself.  Note that
6567 	 * the test here does not catch the case where the
6568 	 * source IP addr was left unspecified by the user. In
6569 	 * this case, the source addr is set in tcp_adapt_ire()
6570 	 * using the reply to the T_BIND message that we send
6571 	 * down to IP here and the check is repeated in tcp_rput_other.
6572 	 */
6573 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6574 	    dstport == tcp->tcp_lport) {
6575 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6576 		goto failed;
6577 	}
6578 
6579 	tcp->tcp_ipha->ipha_dst = dstaddr;
6580 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6581 
6582 	/*
6583 	 * Massage a source route if any putting the first hop
6584 	 * in iph_dst. Compute a starting value for the checksum which
6585 	 * takes into account that the original iph_dst should be
6586 	 * included in the checksum but that ip will include the
6587 	 * first hop in the source route in the tcp checksum.
6588 	 */
6589 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6590 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6591 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6592 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6593 	if ((int)tcp->tcp_sum < 0)
6594 		tcp->tcp_sum--;
6595 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6596 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6597 	    (tcp->tcp_sum >> 16));
6598 	tcph = tcp->tcp_tcph;
6599 	*(uint16_t *)tcph->th_fport = dstport;
6600 	tcp->tcp_fport = dstport;
6601 
6602 	oldstate = tcp->tcp_state;
6603 	/*
6604 	 * At this point the remote destination address and remote port fields
6605 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6606 	 * have to see which state tcp was in so we can take apropriate action.
6607 	 */
6608 	if (oldstate == TCPS_IDLE) {
6609 		/*
6610 		 * We support a quick connect capability here, allowing
6611 		 * clients to transition directly from IDLE to SYN_SENT
6612 		 * tcp_bindi will pick an unused port, insert the connection
6613 		 * in the bind hash and transition to BOUND state.
6614 		 */
6615 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6616 		    tcp, B_TRUE);
6617 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6618 		    B_FALSE, B_FALSE);
6619 		if (lport == 0) {
6620 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6621 			goto failed;
6622 		}
6623 	}
6624 	tcp->tcp_state = TCPS_SYN_SENT;
6625 
6626 	/*
6627 	 * TODO: allow data with connect requests
6628 	 * by unlinking M_DATA trailers here and
6629 	 * linking them in behind the T_OK_ACK mblk.
6630 	 * The tcp_rput() bind ack handler would then
6631 	 * feed them to tcp_wput_data() rather than call
6632 	 * tcp_timer().
6633 	 */
6634 	mp = mi_tpi_ok_ack_alloc(mp);
6635 	if (!mp) {
6636 		tcp->tcp_state = oldstate;
6637 		goto failed;
6638 	}
6639 	if (tcp->tcp_family == AF_INET) {
6640 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6641 		    sizeof (ipa_conn_t));
6642 	} else {
6643 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6644 		    sizeof (ipa6_conn_t));
6645 	}
6646 	if (mp1) {
6647 		/*
6648 		 * We need to make sure that the conn_recv is set to a non-null
6649 		 * value before we insert the conn_t into the classifier table.
6650 		 * This is to avoid a race with an incoming packet which does
6651 		 * an ipcl_classify().
6652 		 */
6653 		tcp->tcp_connp->conn_recv = tcp_input;
6654 
6655 		/* Hang onto the T_OK_ACK for later. */
6656 		linkb(mp1, mp);
6657 		mblk_setcred(mp1, tcp->tcp_cred);
6658 		if (tcp->tcp_family == AF_INET)
6659 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6660 		else {
6661 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6662 			    &tcp->tcp_sticky_ipp);
6663 		}
6664 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6665 		tcp->tcp_active_open = 1;
6666 		/*
6667 		 * If the bind cannot complete immediately
6668 		 * IP will arrange to call tcp_rput_other
6669 		 * when the bind completes.
6670 		 */
6671 		if (mp1 != NULL)
6672 			tcp_rput_other(tcp, mp1);
6673 		return;
6674 	}
6675 	/* Error case */
6676 	tcp->tcp_state = oldstate;
6677 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6678 
6679 failed:
6680 	/* return error ack and blow away saved option results if any */
6681 	if (mp != NULL)
6682 		putnext(tcp->tcp_rq, mp);
6683 	else {
6684 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6685 		    TSYSERR, ENOMEM);
6686 	}
6687 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6688 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6689 
6690 }
6691 
6692 /*
6693  * Handle connect to IPv6 destinations.
6694  */
6695 static void
6696 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6697     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6698 {
6699 	tcph_t	*tcph;
6700 	mblk_t	*mp1;
6701 	ip6_rthdr_t *rth;
6702 	int32_t  oldstate;
6703 	uint16_t lport;
6704 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6705 
6706 	ASSERT(tcp->tcp_family == AF_INET6);
6707 
6708 	/*
6709 	 * If we're here, it means that the destination address is a native
6710 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6711 	 * reason why it might not be IPv6 is if the socket was bound to an
6712 	 * IPv4-mapped IPv6 address.
6713 	 */
6714 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6715 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6716 		goto failed;
6717 	}
6718 
6719 	/*
6720 	 * Interpret a zero destination to mean loopback.
6721 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6722 	 * generate the T_CONN_CON.
6723 	 */
6724 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6725 		*dstaddrp = ipv6_loopback;
6726 	}
6727 
6728 	/* Handle __sin6_src_id if socket not bound to an IP address */
6729 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6730 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6731 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6732 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6733 	}
6734 
6735 	/*
6736 	 * Take care of the scope_id now and add ip6i_t
6737 	 * if ip6i_t is not already allocated through TCP
6738 	 * sticky options. At this point tcp_ip6h does not
6739 	 * have dst info, thus use dstaddrp.
6740 	 */
6741 	if (scope_id != 0 &&
6742 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6743 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6744 		ip6i_t  *ip6i;
6745 
6746 		ipp->ipp_ifindex = scope_id;
6747 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6748 
6749 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6750 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6751 			/* Already allocated */
6752 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6753 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6754 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6755 		} else {
6756 			int reterr;
6757 
6758 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6759 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6760 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6761 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6762 			if (reterr != 0)
6763 				goto failed;
6764 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6765 		}
6766 	}
6767 
6768 	/*
6769 	 * Don't let an endpoint connect to itself.  Note that
6770 	 * the test here does not catch the case where the
6771 	 * source IP addr was left unspecified by the user. In
6772 	 * this case, the source addr is set in tcp_adapt_ire()
6773 	 * using the reply to the T_BIND message that we send
6774 	 * down to IP here and the check is repeated in tcp_rput_other.
6775 	 */
6776 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6777 	    (dstport == tcp->tcp_lport)) {
6778 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6779 		goto failed;
6780 	}
6781 
6782 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6783 	tcp->tcp_remote_v6 = *dstaddrp;
6784 	tcp->tcp_ip6h->ip6_vcf =
6785 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6786 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6787 
6788 
6789 	/*
6790 	 * Massage a routing header (if present) putting the first hop
6791 	 * in ip6_dst. Compute a starting value for the checksum which
6792 	 * takes into account that the original ip6_dst should be
6793 	 * included in the checksum but that ip will include the
6794 	 * first hop in the source route in the tcp checksum.
6795 	 */
6796 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6797 	if (rth != NULL) {
6798 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6799 		    tcps->tcps_netstack);
6800 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6801 		    (tcp->tcp_sum >> 16));
6802 	} else {
6803 		tcp->tcp_sum = 0;
6804 	}
6805 
6806 	tcph = tcp->tcp_tcph;
6807 	*(uint16_t *)tcph->th_fport = dstport;
6808 	tcp->tcp_fport = dstport;
6809 
6810 	oldstate = tcp->tcp_state;
6811 	/*
6812 	 * At this point the remote destination address and remote port fields
6813 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6814 	 * have to see which state tcp was in so we can take apropriate action.
6815 	 */
6816 	if (oldstate == TCPS_IDLE) {
6817 		/*
6818 		 * We support a quick connect capability here, allowing
6819 		 * clients to transition directly from IDLE to SYN_SENT
6820 		 * tcp_bindi will pick an unused port, insert the connection
6821 		 * in the bind hash and transition to BOUND state.
6822 		 */
6823 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6824 		    tcp, B_TRUE);
6825 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6826 		    B_FALSE, B_FALSE);
6827 		if (lport == 0) {
6828 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6829 			goto failed;
6830 		}
6831 	}
6832 	tcp->tcp_state = TCPS_SYN_SENT;
6833 	/*
6834 	 * TODO: allow data with connect requests
6835 	 * by unlinking M_DATA trailers here and
6836 	 * linking them in behind the T_OK_ACK mblk.
6837 	 * The tcp_rput() bind ack handler would then
6838 	 * feed them to tcp_wput_data() rather than call
6839 	 * tcp_timer().
6840 	 */
6841 	mp = mi_tpi_ok_ack_alloc(mp);
6842 	if (!mp) {
6843 		tcp->tcp_state = oldstate;
6844 		goto failed;
6845 	}
6846 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6847 	if (mp1) {
6848 		/*
6849 		 * We need to make sure that the conn_recv is set to a non-null
6850 		 * value before we insert the conn_t into the classifier table.
6851 		 * This is to avoid a race with an incoming packet which does
6852 		 * an ipcl_classify().
6853 		 */
6854 		tcp->tcp_connp->conn_recv = tcp_input;
6855 
6856 		/* Hang onto the T_OK_ACK for later. */
6857 		linkb(mp1, mp);
6858 		mblk_setcred(mp1, tcp->tcp_cred);
6859 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6860 		    &tcp->tcp_sticky_ipp);
6861 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6862 		tcp->tcp_active_open = 1;
6863 		/* ip_bind_v6() may return ACK or ERROR */
6864 		if (mp1 != NULL)
6865 			tcp_rput_other(tcp, mp1);
6866 		return;
6867 	}
6868 	/* Error case */
6869 	tcp->tcp_state = oldstate;
6870 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6871 
6872 failed:
6873 	/* return error ack and blow away saved option results if any */
6874 	if (mp != NULL)
6875 		putnext(tcp->tcp_rq, mp);
6876 	else {
6877 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6878 		    TSYSERR, ENOMEM);
6879 	}
6880 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6881 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6882 }
6883 
6884 /*
6885  * We need a stream q for detached closing tcp connections
6886  * to use.  Our client hereby indicates that this q is the
6887  * one to use.
6888  */
6889 static void
6890 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6891 {
6892 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6893 	queue_t	*q = tcp->tcp_wq;
6894 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6895 
6896 #ifdef NS_DEBUG
6897 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6898 	    tcps->tcps_netstack->netstack_stackid);
6899 #endif
6900 	mp->b_datap->db_type = M_IOCACK;
6901 	iocp->ioc_count = 0;
6902 	mutex_enter(&tcps->tcps_g_q_lock);
6903 	if (tcps->tcps_g_q != NULL) {
6904 		mutex_exit(&tcps->tcps_g_q_lock);
6905 		iocp->ioc_error = EALREADY;
6906 	} else {
6907 		mblk_t *mp1;
6908 
6909 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6910 		if (mp1 == NULL) {
6911 			mutex_exit(&tcps->tcps_g_q_lock);
6912 			iocp->ioc_error = ENOMEM;
6913 		} else {
6914 			tcps->tcps_g_q = tcp->tcp_rq;
6915 			mutex_exit(&tcps->tcps_g_q_lock);
6916 			iocp->ioc_error = 0;
6917 			iocp->ioc_rval = 0;
6918 			/*
6919 			 * We are passing tcp_sticky_ipp as NULL
6920 			 * as it is not useful for tcp_default queue
6921 			 *
6922 			 * Set conn_recv just in case.
6923 			 */
6924 			tcp->tcp_connp->conn_recv = tcp_conn_request;
6925 
6926 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6927 			if (mp1 != NULL)
6928 				tcp_rput_other(tcp, mp1);
6929 		}
6930 	}
6931 	qreply(q, mp);
6932 }
6933 
6934 /*
6935  * Our client hereby directs us to reject the connection request
6936  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6937  * of sending the appropriate RST, not an ICMP error.
6938  */
6939 static void
6940 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6941 {
6942 	tcp_t	*ltcp = NULL;
6943 	t_scalar_t seqnum;
6944 	conn_t	*connp;
6945 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6946 
6947 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6948 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6949 		tcp_err_ack(tcp, mp, TPROTO, 0);
6950 		return;
6951 	}
6952 
6953 	/*
6954 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6955 	 * when the stream is in BOUND state. Do not send a reset,
6956 	 * since the destination IP address is not valid, and it can
6957 	 * be the initialized value of all zeros (broadcast address).
6958 	 *
6959 	 * If TCP has sent down a bind request to IP and has not
6960 	 * received the reply, reject the request.  Otherwise, TCP
6961 	 * will be confused.
6962 	 */
6963 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6964 		if (tcp->tcp_debug) {
6965 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6966 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6967 		}
6968 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6969 		return;
6970 	}
6971 
6972 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6973 
6974 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6975 
6976 		/*
6977 		 * According to TPI, for non-listeners, ignore seqnum
6978 		 * and disconnect.
6979 		 * Following interpretation of -1 seqnum is historical
6980 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6981 		 * a valid seqnum should not be -1).
6982 		 *
6983 		 *	-1 means disconnect everything
6984 		 *	regardless even on a listener.
6985 		 */
6986 
6987 		int old_state = tcp->tcp_state;
6988 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6989 
6990 		/*
6991 		 * The connection can't be on the tcp_time_wait_head list
6992 		 * since it is not detached.
6993 		 */
6994 		ASSERT(tcp->tcp_time_wait_next == NULL);
6995 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6996 		ASSERT(tcp->tcp_time_wait_expire == 0);
6997 		ltcp = NULL;
6998 		/*
6999 		 * If it used to be a listener, check to make sure no one else
7000 		 * has taken the port before switching back to LISTEN state.
7001 		 */
7002 		if (tcp->tcp_ipversion == IPV4_VERSION) {
7003 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
7004 			    tcp->tcp_ipha->ipha_src,
7005 			    tcp->tcp_connp->conn_zoneid, ipst);
7006 			if (connp != NULL)
7007 				ltcp = connp->conn_tcp;
7008 		} else {
7009 			/* Allow tcp_bound_if listeners? */
7010 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
7011 			    &tcp->tcp_ip6h->ip6_src, 0,
7012 			    tcp->tcp_connp->conn_zoneid, ipst);
7013 			if (connp != NULL)
7014 				ltcp = connp->conn_tcp;
7015 		}
7016 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
7017 			tcp->tcp_state = TCPS_LISTEN;
7018 		} else if (old_state > TCPS_BOUND) {
7019 			tcp->tcp_conn_req_max = 0;
7020 			tcp->tcp_state = TCPS_BOUND;
7021 		}
7022 		if (ltcp != NULL)
7023 			CONN_DEC_REF(ltcp->tcp_connp);
7024 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
7025 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
7026 		} else if (old_state == TCPS_ESTABLISHED ||
7027 		    old_state == TCPS_CLOSE_WAIT) {
7028 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
7029 		}
7030 
7031 		if (tcp->tcp_fused)
7032 			tcp_unfuse(tcp);
7033 
7034 		mutex_enter(&tcp->tcp_eager_lock);
7035 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
7036 		    (tcp->tcp_conn_req_cnt_q != 0)) {
7037 			tcp_eager_cleanup(tcp, 0);
7038 		}
7039 		mutex_exit(&tcp->tcp_eager_lock);
7040 
7041 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
7042 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
7043 
7044 		tcp_reinit(tcp);
7045 
7046 		if (old_state >= TCPS_ESTABLISHED) {
7047 			/* Send M_FLUSH according to TPI */
7048 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
7049 		}
7050 		mp = mi_tpi_ok_ack_alloc(mp);
7051 		if (mp)
7052 			putnext(tcp->tcp_rq, mp);
7053 		return;
7054 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
7055 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
7056 		return;
7057 	}
7058 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
7059 		/* Send M_FLUSH according to TPI */
7060 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
7061 	}
7062 	mp = mi_tpi_ok_ack_alloc(mp);
7063 	if (mp)
7064 		putnext(tcp->tcp_rq, mp);
7065 }
7066 
7067 /*
7068  * Diagnostic routine used to return a string associated with the tcp state.
7069  * Note that if the caller does not supply a buffer, it will use an internal
7070  * static string.  This means that if multiple threads call this function at
7071  * the same time, output can be corrupted...  Note also that this function
7072  * does not check the size of the supplied buffer.  The caller has to make
7073  * sure that it is big enough.
7074  */
7075 static char *
7076 tcp_display(tcp_t *tcp, char *sup_buf, char format)
7077 {
7078 	char		buf1[30];
7079 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
7080 	char		*buf;
7081 	char		*cp;
7082 	in6_addr_t	local, remote;
7083 	char		local_addrbuf[INET6_ADDRSTRLEN];
7084 	char		remote_addrbuf[INET6_ADDRSTRLEN];
7085 
7086 	if (sup_buf != NULL)
7087 		buf = sup_buf;
7088 	else
7089 		buf = priv_buf;
7090 
7091 	if (tcp == NULL)
7092 		return ("NULL_TCP");
7093 	switch (tcp->tcp_state) {
7094 	case TCPS_CLOSED:
7095 		cp = "TCP_CLOSED";
7096 		break;
7097 	case TCPS_IDLE:
7098 		cp = "TCP_IDLE";
7099 		break;
7100 	case TCPS_BOUND:
7101 		cp = "TCP_BOUND";
7102 		break;
7103 	case TCPS_LISTEN:
7104 		cp = "TCP_LISTEN";
7105 		break;
7106 	case TCPS_SYN_SENT:
7107 		cp = "TCP_SYN_SENT";
7108 		break;
7109 	case TCPS_SYN_RCVD:
7110 		cp = "TCP_SYN_RCVD";
7111 		break;
7112 	case TCPS_ESTABLISHED:
7113 		cp = "TCP_ESTABLISHED";
7114 		break;
7115 	case TCPS_CLOSE_WAIT:
7116 		cp = "TCP_CLOSE_WAIT";
7117 		break;
7118 	case TCPS_FIN_WAIT_1:
7119 		cp = "TCP_FIN_WAIT_1";
7120 		break;
7121 	case TCPS_CLOSING:
7122 		cp = "TCP_CLOSING";
7123 		break;
7124 	case TCPS_LAST_ACK:
7125 		cp = "TCP_LAST_ACK";
7126 		break;
7127 	case TCPS_FIN_WAIT_2:
7128 		cp = "TCP_FIN_WAIT_2";
7129 		break;
7130 	case TCPS_TIME_WAIT:
7131 		cp = "TCP_TIME_WAIT";
7132 		break;
7133 	default:
7134 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
7135 		cp = buf1;
7136 		break;
7137 	}
7138 	switch (format) {
7139 	case DISP_ADDR_AND_PORT:
7140 		if (tcp->tcp_ipversion == IPV4_VERSION) {
7141 			/*
7142 			 * Note that we use the remote address in the tcp_b
7143 			 * structure.  This means that it will print out
7144 			 * the real destination address, not the next hop's
7145 			 * address if source routing is used.
7146 			 */
7147 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
7148 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
7149 
7150 		} else {
7151 			local = tcp->tcp_ip_src_v6;
7152 			remote = tcp->tcp_remote_v6;
7153 		}
7154 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
7155 		    sizeof (local_addrbuf));
7156 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
7157 		    sizeof (remote_addrbuf));
7158 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
7159 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
7160 		    ntohs(tcp->tcp_fport), cp);
7161 		break;
7162 	case DISP_PORT_ONLY:
7163 	default:
7164 		(void) mi_sprintf(buf, "[%u, %u] %s",
7165 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
7166 		break;
7167 	}
7168 
7169 	return (buf);
7170 }
7171 
7172 /*
7173  * Called via squeue to get on to eager's perimeter. It sends a
7174  * TH_RST if eager is in the fanout table. The listener wants the
7175  * eager to disappear either by means of tcp_eager_blowoff() or
7176  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
7177  * called (via squeue) if the eager cannot be inserted in the
7178  * fanout table in tcp_conn_request().
7179  */
7180 /* ARGSUSED */
7181 void
7182 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
7183 {
7184 	conn_t	*econnp = (conn_t *)arg;
7185 	tcp_t	*eager = econnp->conn_tcp;
7186 	tcp_t	*listener = eager->tcp_listener;
7187 	tcp_stack_t	*tcps = eager->tcp_tcps;
7188 
7189 	/*
7190 	 * We could be called because listener is closing. Since
7191 	 * the eager is using listener's queue's, its not safe.
7192 	 * Better use the default queue just to send the TH_RST
7193 	 * out.
7194 	 */
7195 	ASSERT(tcps->tcps_g_q != NULL);
7196 	eager->tcp_rq = tcps->tcps_g_q;
7197 	eager->tcp_wq = WR(tcps->tcps_g_q);
7198 
7199 	/*
7200 	 * An eager's conn_fanout will be NULL if it's a duplicate
7201 	 * for an existing 4-tuples in the conn fanout table.
7202 	 * We don't want to send an RST out in such case.
7203 	 */
7204 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
7205 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
7206 		    eager, eager->tcp_snxt, 0, TH_RST);
7207 	}
7208 
7209 	/* We are here because listener wants this eager gone */
7210 	if (listener != NULL) {
7211 		mutex_enter(&listener->tcp_eager_lock);
7212 		tcp_eager_unlink(eager);
7213 		if (eager->tcp_tconnind_started) {
7214 			/*
7215 			 * The eager has sent a conn_ind up to the
7216 			 * listener but listener decides to close
7217 			 * instead. We need to drop the extra ref
7218 			 * placed on eager in tcp_rput_data() before
7219 			 * sending the conn_ind to listener.
7220 			 */
7221 			CONN_DEC_REF(econnp);
7222 		}
7223 		mutex_exit(&listener->tcp_eager_lock);
7224 		CONN_DEC_REF(listener->tcp_connp);
7225 	}
7226 
7227 	if (eager->tcp_state > TCPS_BOUND)
7228 		tcp_close_detached(eager);
7229 }
7230 
7231 /*
7232  * Reset any eager connection hanging off this listener marked
7233  * with 'seqnum' and then reclaim it's resources.
7234  */
7235 static boolean_t
7236 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
7237 {
7238 	tcp_t	*eager;
7239 	mblk_t 	*mp;
7240 	tcp_stack_t	*tcps = listener->tcp_tcps;
7241 
7242 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
7243 	eager = listener;
7244 	mutex_enter(&listener->tcp_eager_lock);
7245 	do {
7246 		eager = eager->tcp_eager_next_q;
7247 		if (eager == NULL) {
7248 			mutex_exit(&listener->tcp_eager_lock);
7249 			return (B_FALSE);
7250 		}
7251 	} while (eager->tcp_conn_req_seqnum != seqnum);
7252 
7253 	if (eager->tcp_closemp_used) {
7254 		mutex_exit(&listener->tcp_eager_lock);
7255 		return (B_TRUE);
7256 	}
7257 	eager->tcp_closemp_used = B_TRUE;
7258 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7259 	CONN_INC_REF(eager->tcp_connp);
7260 	mutex_exit(&listener->tcp_eager_lock);
7261 	mp = &eager->tcp_closemp;
7262 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
7263 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
7264 	return (B_TRUE);
7265 }
7266 
7267 /*
7268  * Reset any eager connection hanging off this listener
7269  * and then reclaim it's resources.
7270  */
7271 static void
7272 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
7273 {
7274 	tcp_t	*eager;
7275 	mblk_t	*mp;
7276 	tcp_stack_t	*tcps = listener->tcp_tcps;
7277 
7278 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7279 
7280 	if (!q0_only) {
7281 		/* First cleanup q */
7282 		TCP_STAT(tcps, tcp_eager_blowoff_q);
7283 		eager = listener->tcp_eager_next_q;
7284 		while (eager != NULL) {
7285 			if (!eager->tcp_closemp_used) {
7286 				eager->tcp_closemp_used = B_TRUE;
7287 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7288 				CONN_INC_REF(eager->tcp_connp);
7289 				mp = &eager->tcp_closemp;
7290 				squeue_fill(eager->tcp_connp->conn_sqp, mp,
7291 				    tcp_eager_kill, eager->tcp_connp,
7292 				    SQTAG_TCP_EAGER_CLEANUP);
7293 			}
7294 			eager = eager->tcp_eager_next_q;
7295 		}
7296 	}
7297 	/* Then cleanup q0 */
7298 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
7299 	eager = listener->tcp_eager_next_q0;
7300 	while (eager != listener) {
7301 		if (!eager->tcp_closemp_used) {
7302 			eager->tcp_closemp_used = B_TRUE;
7303 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7304 			CONN_INC_REF(eager->tcp_connp);
7305 			mp = &eager->tcp_closemp;
7306 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
7307 			    tcp_eager_kill, eager->tcp_connp,
7308 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
7309 		}
7310 		eager = eager->tcp_eager_next_q0;
7311 	}
7312 }
7313 
7314 /*
7315  * If we are an eager connection hanging off a listener that hasn't
7316  * formally accepted the connection yet, get off his list and blow off
7317  * any data that we have accumulated.
7318  */
7319 static void
7320 tcp_eager_unlink(tcp_t *tcp)
7321 {
7322 	tcp_t	*listener = tcp->tcp_listener;
7323 
7324 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7325 	ASSERT(listener != NULL);
7326 	if (tcp->tcp_eager_next_q0 != NULL) {
7327 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
7328 
7329 		/* Remove the eager tcp from q0 */
7330 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
7331 		    tcp->tcp_eager_prev_q0;
7332 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
7333 		    tcp->tcp_eager_next_q0;
7334 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
7335 		listener->tcp_conn_req_cnt_q0--;
7336 
7337 		tcp->tcp_eager_next_q0 = NULL;
7338 		tcp->tcp_eager_prev_q0 = NULL;
7339 
7340 		/*
7341 		 * Take the eager out, if it is in the list of droppable
7342 		 * eagers.
7343 		 */
7344 		MAKE_UNDROPPABLE(tcp);
7345 
7346 		if (tcp->tcp_syn_rcvd_timeout != 0) {
7347 			/* we have timed out before */
7348 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
7349 			listener->tcp_syn_rcvd_timeout--;
7350 		}
7351 	} else {
7352 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
7353 		tcp_t	*prev = NULL;
7354 
7355 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
7356 			if (tcpp[0] == tcp) {
7357 				if (listener->tcp_eager_last_q == tcp) {
7358 					/*
7359 					 * If we are unlinking the last
7360 					 * element on the list, adjust
7361 					 * tail pointer. Set tail pointer
7362 					 * to nil when list is empty.
7363 					 */
7364 					ASSERT(tcp->tcp_eager_next_q == NULL);
7365 					if (listener->tcp_eager_last_q ==
7366 					    listener->tcp_eager_next_q) {
7367 						listener->tcp_eager_last_q =
7368 						    NULL;
7369 					} else {
7370 						/*
7371 						 * We won't get here if there
7372 						 * is only one eager in the
7373 						 * list.
7374 						 */
7375 						ASSERT(prev != NULL);
7376 						listener->tcp_eager_last_q =
7377 						    prev;
7378 					}
7379 				}
7380 				tcpp[0] = tcp->tcp_eager_next_q;
7381 				tcp->tcp_eager_next_q = NULL;
7382 				tcp->tcp_eager_last_q = NULL;
7383 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7384 				listener->tcp_conn_req_cnt_q--;
7385 				break;
7386 			}
7387 			prev = tcpp[0];
7388 		}
7389 	}
7390 	tcp->tcp_listener = NULL;
7391 }
7392 
7393 /* Shorthand to generate and send TPI error acks to our client */
7394 static void
7395 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7396 {
7397 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7398 		putnext(tcp->tcp_rq, mp);
7399 }
7400 
7401 /* Shorthand to generate and send TPI error acks to our client */
7402 static void
7403 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7404     int t_error, int sys_error)
7405 {
7406 	struct T_error_ack	*teackp;
7407 
7408 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7409 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7410 		teackp = (struct T_error_ack *)mp->b_rptr;
7411 		teackp->ERROR_prim = primitive;
7412 		teackp->TLI_error = t_error;
7413 		teackp->UNIX_error = sys_error;
7414 		putnext(tcp->tcp_rq, mp);
7415 	}
7416 }
7417 
7418 /*
7419  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7420  * but instead the code relies on:
7421  * - the fact that the address of the array and its size never changes
7422  * - the atomic assignment of the elements of the array
7423  */
7424 /* ARGSUSED */
7425 static int
7426 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7427 {
7428 	int i;
7429 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7430 
7431 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7432 		if (tcps->tcps_g_epriv_ports[i] != 0)
7433 			(void) mi_mpprintf(mp, "%d ",
7434 			    tcps->tcps_g_epriv_ports[i]);
7435 	}
7436 	return (0);
7437 }
7438 
7439 /*
7440  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7441  * threads from changing it at the same time.
7442  */
7443 /* ARGSUSED */
7444 static int
7445 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7446     cred_t *cr)
7447 {
7448 	long	new_value;
7449 	int	i;
7450 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7451 
7452 	/*
7453 	 * Fail the request if the new value does not lie within the
7454 	 * port number limits.
7455 	 */
7456 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7457 	    new_value <= 0 || new_value >= 65536) {
7458 		return (EINVAL);
7459 	}
7460 
7461 	mutex_enter(&tcps->tcps_epriv_port_lock);
7462 	/* Check if the value is already in the list */
7463 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7464 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7465 			mutex_exit(&tcps->tcps_epriv_port_lock);
7466 			return (EEXIST);
7467 		}
7468 	}
7469 	/* Find an empty slot */
7470 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7471 		if (tcps->tcps_g_epriv_ports[i] == 0)
7472 			break;
7473 	}
7474 	if (i == tcps->tcps_g_num_epriv_ports) {
7475 		mutex_exit(&tcps->tcps_epriv_port_lock);
7476 		return (EOVERFLOW);
7477 	}
7478 	/* Set the new value */
7479 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7480 	mutex_exit(&tcps->tcps_epriv_port_lock);
7481 	return (0);
7482 }
7483 
7484 /*
7485  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7486  * threads from changing it at the same time.
7487  */
7488 /* ARGSUSED */
7489 static int
7490 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7491     cred_t *cr)
7492 {
7493 	long	new_value;
7494 	int	i;
7495 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7496 
7497 	/*
7498 	 * Fail the request if the new value does not lie within the
7499 	 * port number limits.
7500 	 */
7501 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7502 	    new_value >= 65536) {
7503 		return (EINVAL);
7504 	}
7505 
7506 	mutex_enter(&tcps->tcps_epriv_port_lock);
7507 	/* Check that the value is already in the list */
7508 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7509 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7510 			break;
7511 	}
7512 	if (i == tcps->tcps_g_num_epriv_ports) {
7513 		mutex_exit(&tcps->tcps_epriv_port_lock);
7514 		return (ESRCH);
7515 	}
7516 	/* Clear the value */
7517 	tcps->tcps_g_epriv_ports[i] = 0;
7518 	mutex_exit(&tcps->tcps_epriv_port_lock);
7519 	return (0);
7520 }
7521 
7522 /* Return the TPI/TLI equivalent of our current tcp_state */
7523 static int
7524 tcp_tpistate(tcp_t *tcp)
7525 {
7526 	switch (tcp->tcp_state) {
7527 	case TCPS_IDLE:
7528 		return (TS_UNBND);
7529 	case TCPS_LISTEN:
7530 		/*
7531 		 * Return whether there are outstanding T_CONN_IND waiting
7532 		 * for the matching T_CONN_RES. Therefore don't count q0.
7533 		 */
7534 		if (tcp->tcp_conn_req_cnt_q > 0)
7535 			return (TS_WRES_CIND);
7536 		else
7537 			return (TS_IDLE);
7538 	case TCPS_BOUND:
7539 		return (TS_IDLE);
7540 	case TCPS_SYN_SENT:
7541 		return (TS_WCON_CREQ);
7542 	case TCPS_SYN_RCVD:
7543 		/*
7544 		 * Note: assumption: this has to the active open SYN_RCVD.
7545 		 * The passive instance is detached in SYN_RCVD stage of
7546 		 * incoming connection processing so we cannot get request
7547 		 * for T_info_ack on it.
7548 		 */
7549 		return (TS_WACK_CRES);
7550 	case TCPS_ESTABLISHED:
7551 		return (TS_DATA_XFER);
7552 	case TCPS_CLOSE_WAIT:
7553 		return (TS_WREQ_ORDREL);
7554 	case TCPS_FIN_WAIT_1:
7555 		return (TS_WIND_ORDREL);
7556 	case TCPS_FIN_WAIT_2:
7557 		return (TS_WIND_ORDREL);
7558 
7559 	case TCPS_CLOSING:
7560 	case TCPS_LAST_ACK:
7561 	case TCPS_TIME_WAIT:
7562 	case TCPS_CLOSED:
7563 		/*
7564 		 * Following TS_WACK_DREQ7 is a rendition of "not
7565 		 * yet TS_IDLE" TPI state. There is no best match to any
7566 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7567 		 * choose a value chosen that will map to TLI/XTI level
7568 		 * state of TSTATECHNG (state is process of changing) which
7569 		 * captures what this dummy state represents.
7570 		 */
7571 		return (TS_WACK_DREQ7);
7572 	default:
7573 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7574 		    tcp->tcp_state, tcp_display(tcp, NULL,
7575 		    DISP_PORT_ONLY));
7576 		return (TS_UNBND);
7577 	}
7578 }
7579 
7580 static void
7581 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7582 {
7583 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7584 
7585 	if (tcp->tcp_family == AF_INET6)
7586 		*tia = tcp_g_t_info_ack_v6;
7587 	else
7588 		*tia = tcp_g_t_info_ack;
7589 	tia->CURRENT_state = tcp_tpistate(tcp);
7590 	tia->OPT_size = tcp_max_optsize;
7591 	if (tcp->tcp_mss == 0) {
7592 		/* Not yet set - tcp_open does not set mss */
7593 		if (tcp->tcp_ipversion == IPV4_VERSION)
7594 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7595 		else
7596 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7597 	} else {
7598 		tia->TIDU_size = tcp->tcp_mss;
7599 	}
7600 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7601 }
7602 
7603 /*
7604  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7605  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7606  * tcp_g_t_info_ack.  The current state of the stream is copied from
7607  * tcp_state.
7608  */
7609 static void
7610 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7611 {
7612 	t_uscalar_t		cap_bits1;
7613 	struct T_capability_ack	*tcap;
7614 
7615 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7616 		freemsg(mp);
7617 		return;
7618 	}
7619 
7620 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7621 
7622 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7623 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7624 	if (mp == NULL)
7625 		return;
7626 
7627 	tcap = (struct T_capability_ack *)mp->b_rptr;
7628 	tcap->CAP_bits1 = 0;
7629 
7630 	if (cap_bits1 & TC1_INFO) {
7631 		tcp_copy_info(&tcap->INFO_ack, tcp);
7632 		tcap->CAP_bits1 |= TC1_INFO;
7633 	}
7634 
7635 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7636 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7637 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7638 	}
7639 
7640 	putnext(tcp->tcp_rq, mp);
7641 }
7642 
7643 /*
7644  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7645  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7646  * The current state of the stream is copied from tcp_state.
7647  */
7648 static void
7649 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7650 {
7651 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7652 	    T_INFO_ACK);
7653 	if (!mp) {
7654 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7655 		return;
7656 	}
7657 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7658 	putnext(tcp->tcp_rq, mp);
7659 }
7660 
7661 /* Respond to the TPI addr request */
7662 static void
7663 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7664 {
7665 	sin_t	*sin;
7666 	mblk_t	*ackmp;
7667 	struct T_addr_ack *taa;
7668 
7669 	/* Make it large enough for worst case */
7670 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7671 	    2 * sizeof (sin6_t), 1);
7672 	if (ackmp == NULL) {
7673 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7674 		return;
7675 	}
7676 
7677 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7678 		tcp_addr_req_ipv6(tcp, ackmp);
7679 		return;
7680 	}
7681 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7682 
7683 	bzero(taa, sizeof (struct T_addr_ack));
7684 	ackmp->b_wptr = (uchar_t *)&taa[1];
7685 
7686 	taa->PRIM_type = T_ADDR_ACK;
7687 	ackmp->b_datap->db_type = M_PCPROTO;
7688 
7689 	/*
7690 	 * Note: Following code assumes 32 bit alignment of basic
7691 	 * data structures like sin_t and struct T_addr_ack.
7692 	 */
7693 	if (tcp->tcp_state >= TCPS_BOUND) {
7694 		/*
7695 		 * Fill in local address
7696 		 */
7697 		taa->LOCADDR_length = sizeof (sin_t);
7698 		taa->LOCADDR_offset = sizeof (*taa);
7699 
7700 		sin = (sin_t *)&taa[1];
7701 
7702 		/* Fill zeroes and then intialize non-zero fields */
7703 		*sin = sin_null;
7704 
7705 		sin->sin_family = AF_INET;
7706 
7707 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7708 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7709 
7710 		ackmp->b_wptr = (uchar_t *)&sin[1];
7711 
7712 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7713 			/*
7714 			 * Fill in Remote address
7715 			 */
7716 			taa->REMADDR_length = sizeof (sin_t);
7717 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7718 			    taa->LOCADDR_length);
7719 
7720 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7721 			*sin = sin_null;
7722 			sin->sin_family = AF_INET;
7723 			sin->sin_addr.s_addr = tcp->tcp_remote;
7724 			sin->sin_port = tcp->tcp_fport;
7725 
7726 			ackmp->b_wptr = (uchar_t *)&sin[1];
7727 		}
7728 	}
7729 	putnext(tcp->tcp_rq, ackmp);
7730 }
7731 
7732 /* Assumes that tcp_addr_req gets enough space and alignment */
7733 static void
7734 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7735 {
7736 	sin6_t	*sin6;
7737 	struct T_addr_ack *taa;
7738 
7739 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7740 	ASSERT(OK_32PTR(ackmp->b_rptr));
7741 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7742 	    2 * sizeof (sin6_t));
7743 
7744 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7745 
7746 	bzero(taa, sizeof (struct T_addr_ack));
7747 	ackmp->b_wptr = (uchar_t *)&taa[1];
7748 
7749 	taa->PRIM_type = T_ADDR_ACK;
7750 	ackmp->b_datap->db_type = M_PCPROTO;
7751 
7752 	/*
7753 	 * Note: Following code assumes 32 bit alignment of basic
7754 	 * data structures like sin6_t and struct T_addr_ack.
7755 	 */
7756 	if (tcp->tcp_state >= TCPS_BOUND) {
7757 		/*
7758 		 * Fill in local address
7759 		 */
7760 		taa->LOCADDR_length = sizeof (sin6_t);
7761 		taa->LOCADDR_offset = sizeof (*taa);
7762 
7763 		sin6 = (sin6_t *)&taa[1];
7764 		*sin6 = sin6_null;
7765 
7766 		sin6->sin6_family = AF_INET6;
7767 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7768 		sin6->sin6_port = tcp->tcp_lport;
7769 
7770 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7771 
7772 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7773 			/*
7774 			 * Fill in Remote address
7775 			 */
7776 			taa->REMADDR_length = sizeof (sin6_t);
7777 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7778 			    taa->LOCADDR_length);
7779 
7780 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7781 			*sin6 = sin6_null;
7782 			sin6->sin6_family = AF_INET6;
7783 			sin6->sin6_flowinfo =
7784 			    tcp->tcp_ip6h->ip6_vcf &
7785 			    ~IPV6_VERS_AND_FLOW_MASK;
7786 			sin6->sin6_addr = tcp->tcp_remote_v6;
7787 			sin6->sin6_port = tcp->tcp_fport;
7788 
7789 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7790 		}
7791 	}
7792 	putnext(tcp->tcp_rq, ackmp);
7793 }
7794 
7795 /*
7796  * Handle reinitialization of a tcp structure.
7797  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7798  */
7799 static void
7800 tcp_reinit(tcp_t *tcp)
7801 {
7802 	mblk_t	*mp;
7803 	int 	err;
7804 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7805 
7806 	TCP_STAT(tcps, tcp_reinit_calls);
7807 
7808 	/* tcp_reinit should never be called for detached tcp_t's */
7809 	ASSERT(tcp->tcp_listener == NULL);
7810 	ASSERT((tcp->tcp_family == AF_INET &&
7811 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7812 	    (tcp->tcp_family == AF_INET6 &&
7813 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7814 	    tcp->tcp_ipversion == IPV6_VERSION)));
7815 
7816 	/* Cancel outstanding timers */
7817 	tcp_timers_stop(tcp);
7818 
7819 	/*
7820 	 * Reset everything in the state vector, after updating global
7821 	 * MIB data from instance counters.
7822 	 */
7823 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7824 	tcp->tcp_ibsegs = 0;
7825 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7826 	tcp->tcp_obsegs = 0;
7827 
7828 	tcp_close_mpp(&tcp->tcp_xmit_head);
7829 	if (tcp->tcp_snd_zcopy_aware)
7830 		tcp_zcopy_notify(tcp);
7831 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7832 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7833 	mutex_enter(&tcp->tcp_non_sq_lock);
7834 	if (tcp->tcp_flow_stopped &&
7835 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7836 		tcp_clrqfull(tcp);
7837 	}
7838 	mutex_exit(&tcp->tcp_non_sq_lock);
7839 	tcp_close_mpp(&tcp->tcp_reass_head);
7840 	tcp->tcp_reass_tail = NULL;
7841 	if (tcp->tcp_rcv_list != NULL) {
7842 		/* Free b_next chain */
7843 		tcp_close_mpp(&tcp->tcp_rcv_list);
7844 		tcp->tcp_rcv_last_head = NULL;
7845 		tcp->tcp_rcv_last_tail = NULL;
7846 		tcp->tcp_rcv_cnt = 0;
7847 	}
7848 	tcp->tcp_rcv_last_tail = NULL;
7849 
7850 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7851 		freemsg(mp);
7852 		tcp->tcp_urp_mp = NULL;
7853 	}
7854 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7855 		freemsg(mp);
7856 		tcp->tcp_urp_mark_mp = NULL;
7857 	}
7858 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7859 		freeb(tcp->tcp_fused_sigurg_mp);
7860 		tcp->tcp_fused_sigurg_mp = NULL;
7861 	}
7862 
7863 	/*
7864 	 * Following is a union with two members which are
7865 	 * identical types and size so the following cleanup
7866 	 * is enough.
7867 	 */
7868 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7869 
7870 	CL_INET_DISCONNECT(tcp);
7871 
7872 	/*
7873 	 * The connection can't be on the tcp_time_wait_head list
7874 	 * since it is not detached.
7875 	 */
7876 	ASSERT(tcp->tcp_time_wait_next == NULL);
7877 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7878 	ASSERT(tcp->tcp_time_wait_expire == 0);
7879 
7880 	if (tcp->tcp_kssl_pending) {
7881 		tcp->tcp_kssl_pending = B_FALSE;
7882 
7883 		/* Don't reset if the initialized by bind. */
7884 		if (tcp->tcp_kssl_ent != NULL) {
7885 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7886 			    KSSL_NO_PROXY);
7887 		}
7888 	}
7889 	if (tcp->tcp_kssl_ctx != NULL) {
7890 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7891 		tcp->tcp_kssl_ctx = NULL;
7892 	}
7893 
7894 	/*
7895 	 * Reset/preserve other values
7896 	 */
7897 	tcp_reinit_values(tcp);
7898 	ipcl_hash_remove(tcp->tcp_connp);
7899 	conn_delete_ire(tcp->tcp_connp, NULL);
7900 	tcp_ipsec_cleanup(tcp);
7901 
7902 	if (tcp->tcp_conn_req_max != 0) {
7903 		/*
7904 		 * This is the case when a TLI program uses the same
7905 		 * transport end point to accept a connection.  This
7906 		 * makes the TCP both a listener and acceptor.  When
7907 		 * this connection is closed, we need to set the state
7908 		 * back to TCPS_LISTEN.  Make sure that the eager list
7909 		 * is reinitialized.
7910 		 *
7911 		 * Note that this stream is still bound to the four
7912 		 * tuples of the previous connection in IP.  If a new
7913 		 * SYN with different foreign address comes in, IP will
7914 		 * not find it and will send it to the global queue.  In
7915 		 * the global queue, TCP will do a tcp_lookup_listener()
7916 		 * to find this stream.  This works because this stream
7917 		 * is only removed from connected hash.
7918 		 *
7919 		 */
7920 		tcp->tcp_state = TCPS_LISTEN;
7921 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7922 		tcp->tcp_eager_next_drop_q0 = tcp;
7923 		tcp->tcp_eager_prev_drop_q0 = tcp;
7924 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7925 		if (tcp->tcp_family == AF_INET6) {
7926 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7927 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7928 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7929 		} else {
7930 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7931 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7932 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7933 		}
7934 	} else {
7935 		tcp->tcp_state = TCPS_BOUND;
7936 	}
7937 
7938 	/*
7939 	 * Initialize to default values
7940 	 * Can't fail since enough header template space already allocated
7941 	 * at open().
7942 	 */
7943 	err = tcp_init_values(tcp);
7944 	ASSERT(err == 0);
7945 	/* Restore state in tcp_tcph */
7946 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7947 	if (tcp->tcp_ipversion == IPV4_VERSION)
7948 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7949 	else
7950 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7951 	/*
7952 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7953 	 * since the lookup funcs can only lookup on tcp_t
7954 	 */
7955 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7956 
7957 	ASSERT(tcp->tcp_ptpbhn != NULL);
7958 	tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7959 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7960 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7961 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7962 }
7963 
7964 /*
7965  * Force values to zero that need be zero.
7966  * Do not touch values asociated with the BOUND or LISTEN state
7967  * since the connection will end up in that state after the reinit.
7968  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7969  * structure!
7970  */
7971 static void
7972 tcp_reinit_values(tcp)
7973 	tcp_t *tcp;
7974 {
7975 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7976 
7977 #ifndef	lint
7978 #define	DONTCARE(x)
7979 #define	PRESERVE(x)
7980 #else
7981 #define	DONTCARE(x)	((x) = (x))
7982 #define	PRESERVE(x)	((x) = (x))
7983 #endif	/* lint */
7984 
7985 	PRESERVE(tcp->tcp_bind_hash);
7986 	PRESERVE(tcp->tcp_ptpbhn);
7987 	PRESERVE(tcp->tcp_acceptor_hash);
7988 	PRESERVE(tcp->tcp_ptpahn);
7989 
7990 	/* Should be ASSERT NULL on these with new code! */
7991 	ASSERT(tcp->tcp_time_wait_next == NULL);
7992 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7993 	ASSERT(tcp->tcp_time_wait_expire == 0);
7994 	PRESERVE(tcp->tcp_state);
7995 	PRESERVE(tcp->tcp_rq);
7996 	PRESERVE(tcp->tcp_wq);
7997 
7998 	ASSERT(tcp->tcp_xmit_head == NULL);
7999 	ASSERT(tcp->tcp_xmit_last == NULL);
8000 	ASSERT(tcp->tcp_unsent == 0);
8001 	ASSERT(tcp->tcp_xmit_tail == NULL);
8002 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
8003 
8004 	tcp->tcp_snxt = 0;			/* Displayed in mib */
8005 	tcp->tcp_suna = 0;			/* Displayed in mib */
8006 	tcp->tcp_swnd = 0;
8007 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
8008 
8009 	ASSERT(tcp->tcp_ibsegs == 0);
8010 	ASSERT(tcp->tcp_obsegs == 0);
8011 
8012 	if (tcp->tcp_iphc != NULL) {
8013 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8014 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
8015 	}
8016 
8017 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
8018 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
8019 	DONTCARE(tcp->tcp_ipha);
8020 	DONTCARE(tcp->tcp_ip6h);
8021 	DONTCARE(tcp->tcp_ip_hdr_len);
8022 	DONTCARE(tcp->tcp_tcph);
8023 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
8024 	tcp->tcp_valid_bits = 0;
8025 
8026 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
8027 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
8028 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
8029 	tcp->tcp_last_rcv_lbolt = 0;
8030 
8031 	tcp->tcp_init_cwnd = 0;
8032 
8033 	tcp->tcp_urp_last_valid = 0;
8034 	tcp->tcp_hard_binding = 0;
8035 	tcp->tcp_hard_bound = 0;
8036 	PRESERVE(tcp->tcp_cred);
8037 	PRESERVE(tcp->tcp_cpid);
8038 	PRESERVE(tcp->tcp_open_time);
8039 	PRESERVE(tcp->tcp_exclbind);
8040 
8041 	tcp->tcp_fin_acked = 0;
8042 	tcp->tcp_fin_rcvd = 0;
8043 	tcp->tcp_fin_sent = 0;
8044 	tcp->tcp_ordrel_done = 0;
8045 
8046 	tcp->tcp_debug = 0;
8047 	tcp->tcp_dontroute = 0;
8048 	tcp->tcp_broadcast = 0;
8049 
8050 	tcp->tcp_useloopback = 0;
8051 	tcp->tcp_reuseaddr = 0;
8052 	tcp->tcp_oobinline = 0;
8053 	tcp->tcp_dgram_errind = 0;
8054 
8055 	tcp->tcp_detached = 0;
8056 	tcp->tcp_bind_pending = 0;
8057 	tcp->tcp_unbind_pending = 0;
8058 	tcp->tcp_deferred_clean_death = 0;
8059 
8060 	tcp->tcp_snd_ws_ok = B_FALSE;
8061 	tcp->tcp_snd_ts_ok = B_FALSE;
8062 	tcp->tcp_linger = 0;
8063 	tcp->tcp_ka_enabled = 0;
8064 	tcp->tcp_zero_win_probe = 0;
8065 
8066 	tcp->tcp_loopback = 0;
8067 	tcp->tcp_localnet = 0;
8068 	tcp->tcp_syn_defense = 0;
8069 	tcp->tcp_set_timer = 0;
8070 
8071 	tcp->tcp_active_open = 0;
8072 	ASSERT(tcp->tcp_timeout == B_FALSE);
8073 	tcp->tcp_rexmit = B_FALSE;
8074 	tcp->tcp_xmit_zc_clean = B_FALSE;
8075 
8076 	tcp->tcp_snd_sack_ok = B_FALSE;
8077 	PRESERVE(tcp->tcp_recvdstaddr);
8078 	tcp->tcp_hwcksum = B_FALSE;
8079 
8080 	tcp->tcp_ire_ill_check_done = B_FALSE;
8081 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
8082 
8083 	tcp->tcp_mdt = B_FALSE;
8084 	tcp->tcp_mdt_hdr_head = 0;
8085 	tcp->tcp_mdt_hdr_tail = 0;
8086 
8087 	tcp->tcp_conn_def_q0 = 0;
8088 	tcp->tcp_ip_forward_progress = B_FALSE;
8089 	tcp->tcp_anon_priv_bind = 0;
8090 	tcp->tcp_ecn_ok = B_FALSE;
8091 
8092 	tcp->tcp_cwr = B_FALSE;
8093 	tcp->tcp_ecn_echo_on = B_FALSE;
8094 
8095 	if (tcp->tcp_sack_info != NULL) {
8096 		if (tcp->tcp_notsack_list != NULL) {
8097 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
8098 		}
8099 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
8100 		tcp->tcp_sack_info = NULL;
8101 	}
8102 
8103 	tcp->tcp_rcv_ws = 0;
8104 	tcp->tcp_snd_ws = 0;
8105 	tcp->tcp_ts_recent = 0;
8106 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
8107 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
8108 	tcp->tcp_if_mtu = 0;
8109 
8110 	ASSERT(tcp->tcp_reass_head == NULL);
8111 	ASSERT(tcp->tcp_reass_tail == NULL);
8112 
8113 	tcp->tcp_cwnd_cnt = 0;
8114 
8115 	ASSERT(tcp->tcp_rcv_list == NULL);
8116 	ASSERT(tcp->tcp_rcv_last_head == NULL);
8117 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
8118 	ASSERT(tcp->tcp_rcv_cnt == 0);
8119 
8120 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
8121 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
8122 	tcp->tcp_csuna = 0;
8123 
8124 	tcp->tcp_rto = 0;			/* Displayed in MIB */
8125 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
8126 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
8127 	tcp->tcp_rtt_update = 0;
8128 
8129 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8130 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8131 
8132 	tcp->tcp_rack = 0;			/* Displayed in mib */
8133 	tcp->tcp_rack_cnt = 0;
8134 	tcp->tcp_rack_cur_max = 0;
8135 	tcp->tcp_rack_abs_max = 0;
8136 
8137 	tcp->tcp_max_swnd = 0;
8138 
8139 	ASSERT(tcp->tcp_listener == NULL);
8140 
8141 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
8142 
8143 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
8144 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
8145 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
8146 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
8147 
8148 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
8149 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
8150 	PRESERVE(tcp->tcp_conn_req_max);
8151 	PRESERVE(tcp->tcp_conn_req_seqnum);
8152 
8153 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
8154 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
8155 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
8156 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
8157 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
8158 
8159 	tcp->tcp_lingertime = 0;
8160 
8161 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
8162 	ASSERT(tcp->tcp_urp_mp == NULL);
8163 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
8164 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
8165 
8166 	ASSERT(tcp->tcp_eager_next_q == NULL);
8167 	ASSERT(tcp->tcp_eager_last_q == NULL);
8168 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
8169 	    tcp->tcp_eager_prev_q0 == NULL) ||
8170 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
8171 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
8172 
8173 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
8174 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
8175 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
8176 
8177 	tcp->tcp_client_errno = 0;
8178 
8179 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
8180 
8181 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
8182 
8183 	PRESERVE(tcp->tcp_bound_source_v6);
8184 	tcp->tcp_last_sent_len = 0;
8185 	tcp->tcp_dupack_cnt = 0;
8186 
8187 	tcp->tcp_fport = 0;			/* Displayed in MIB */
8188 	PRESERVE(tcp->tcp_lport);
8189 
8190 	PRESERVE(tcp->tcp_acceptor_lockp);
8191 
8192 	ASSERT(tcp->tcp_ordrelid == 0);
8193 	PRESERVE(tcp->tcp_acceptor_id);
8194 	DONTCARE(tcp->tcp_ipsec_overhead);
8195 
8196 	/*
8197 	 * If tcp_tracing flag is ON (i.e. We have a trace buffer
8198 	 * in tcp structure and now tracing), Re-initialize all
8199 	 * members of tcp_traceinfo.
8200 	 */
8201 	if (tcp->tcp_tracebuf != NULL) {
8202 		bzero(tcp->tcp_tracebuf, sizeof (tcptrch_t));
8203 	}
8204 
8205 	PRESERVE(tcp->tcp_family);
8206 	if (tcp->tcp_family == AF_INET6) {
8207 		tcp->tcp_ipversion = IPV6_VERSION;
8208 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
8209 	} else {
8210 		tcp->tcp_ipversion = IPV4_VERSION;
8211 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
8212 	}
8213 
8214 	tcp->tcp_bound_if = 0;
8215 	tcp->tcp_ipv6_recvancillary = 0;
8216 	tcp->tcp_recvifindex = 0;
8217 	tcp->tcp_recvhops = 0;
8218 	tcp->tcp_closed = 0;
8219 	tcp->tcp_cleandeathtag = 0;
8220 	if (tcp->tcp_hopopts != NULL) {
8221 		mi_free(tcp->tcp_hopopts);
8222 		tcp->tcp_hopopts = NULL;
8223 		tcp->tcp_hopoptslen = 0;
8224 	}
8225 	ASSERT(tcp->tcp_hopoptslen == 0);
8226 	if (tcp->tcp_dstopts != NULL) {
8227 		mi_free(tcp->tcp_dstopts);
8228 		tcp->tcp_dstopts = NULL;
8229 		tcp->tcp_dstoptslen = 0;
8230 	}
8231 	ASSERT(tcp->tcp_dstoptslen == 0);
8232 	if (tcp->tcp_rtdstopts != NULL) {
8233 		mi_free(tcp->tcp_rtdstopts);
8234 		tcp->tcp_rtdstopts = NULL;
8235 		tcp->tcp_rtdstoptslen = 0;
8236 	}
8237 	ASSERT(tcp->tcp_rtdstoptslen == 0);
8238 	if (tcp->tcp_rthdr != NULL) {
8239 		mi_free(tcp->tcp_rthdr);
8240 		tcp->tcp_rthdr = NULL;
8241 		tcp->tcp_rthdrlen = 0;
8242 	}
8243 	ASSERT(tcp->tcp_rthdrlen == 0);
8244 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
8245 
8246 	/* Reset fusion-related fields */
8247 	tcp->tcp_fused = B_FALSE;
8248 	tcp->tcp_unfusable = B_FALSE;
8249 	tcp->tcp_fused_sigurg = B_FALSE;
8250 	tcp->tcp_direct_sockfs = B_FALSE;
8251 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8252 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8253 	tcp->tcp_loopback_peer = NULL;
8254 	tcp->tcp_fuse_rcv_hiwater = 0;
8255 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8256 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8257 
8258 	tcp->tcp_lso = B_FALSE;
8259 
8260 	tcp->tcp_in_ack_unsent = 0;
8261 	tcp->tcp_cork = B_FALSE;
8262 	tcp->tcp_tconnind_started = B_FALSE;
8263 
8264 	PRESERVE(tcp->tcp_squeue_bytes);
8265 
8266 	ASSERT(tcp->tcp_kssl_ctx == NULL);
8267 	ASSERT(!tcp->tcp_kssl_pending);
8268 	PRESERVE(tcp->tcp_kssl_ent);
8269 
8270 	/* Sodirect */
8271 	tcp->tcp_sodirect = NULL;
8272 
8273 	tcp->tcp_closemp_used = B_FALSE;
8274 
8275 #ifdef DEBUG
8276 	DONTCARE(tcp->tcmp_stk[0]);
8277 #endif
8278 
8279 
8280 #undef	DONTCARE
8281 #undef	PRESERVE
8282 }
8283 
8284 /*
8285  * Allocate necessary resources and initialize state vector.
8286  * Guaranteed not to fail so that when an error is returned,
8287  * the caller doesn't need to do any additional cleanup.
8288  */
8289 int
8290 tcp_init(tcp_t *tcp, queue_t *q)
8291 {
8292 	int	err;
8293 
8294 	tcp->tcp_rq = q;
8295 	tcp->tcp_wq = WR(q);
8296 	tcp->tcp_state = TCPS_IDLE;
8297 	if ((err = tcp_init_values(tcp)) != 0)
8298 		tcp_timers_stop(tcp);
8299 	return (err);
8300 }
8301 
8302 static int
8303 tcp_init_values(tcp_t *tcp)
8304 {
8305 	int	err;
8306 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8307 
8308 	ASSERT((tcp->tcp_family == AF_INET &&
8309 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8310 	    (tcp->tcp_family == AF_INET6 &&
8311 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8312 	    tcp->tcp_ipversion == IPV6_VERSION)));
8313 
8314 	/*
8315 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
8316 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
8317 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
8318 	 * during first few transmissions of a connection as seen in slow
8319 	 * links.
8320 	 */
8321 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
8322 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
8323 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
8324 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
8325 	    tcps->tcps_conn_grace_period;
8326 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
8327 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
8328 	tcp->tcp_timer_backoff = 0;
8329 	tcp->tcp_ms_we_have_waited = 0;
8330 	tcp->tcp_last_recv_time = lbolt;
8331 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
8332 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
8333 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
8334 
8335 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
8336 
8337 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
8338 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
8339 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
8340 	/*
8341 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
8342 	 * passive open.
8343 	 */
8344 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
8345 
8346 	tcp->tcp_naglim = tcps->tcps_naglim_def;
8347 
8348 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
8349 
8350 	tcp->tcp_mdt_hdr_head = 0;
8351 	tcp->tcp_mdt_hdr_tail = 0;
8352 
8353 	/* Reset fusion-related fields */
8354 	tcp->tcp_fused = B_FALSE;
8355 	tcp->tcp_unfusable = B_FALSE;
8356 	tcp->tcp_fused_sigurg = B_FALSE;
8357 	tcp->tcp_direct_sockfs = B_FALSE;
8358 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8359 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8360 	tcp->tcp_loopback_peer = NULL;
8361 	tcp->tcp_fuse_rcv_hiwater = 0;
8362 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8363 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8364 
8365 	/* Sodirect */
8366 	tcp->tcp_sodirect = NULL;
8367 
8368 	/* Initialize the header template */
8369 	if (tcp->tcp_ipversion == IPV4_VERSION) {
8370 		err = tcp_header_init_ipv4(tcp);
8371 	} else {
8372 		err = tcp_header_init_ipv6(tcp);
8373 	}
8374 	if (err)
8375 		return (err);
8376 
8377 	/*
8378 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
8379 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
8380 	 */
8381 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
8382 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
8383 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
8384 
8385 	tcp->tcp_cork = B_FALSE;
8386 	/*
8387 	 * Init the tcp_debug option.  This value determines whether TCP
8388 	 * calls strlog() to print out debug messages.  Doing this
8389 	 * initialization here means that this value is not inherited thru
8390 	 * tcp_reinit().
8391 	 */
8392 	tcp->tcp_debug = tcps->tcps_dbg;
8393 
8394 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8395 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8396 
8397 	return (0);
8398 }
8399 
8400 /*
8401  * Initialize the IPv4 header. Loses any record of any IP options.
8402  */
8403 static int
8404 tcp_header_init_ipv4(tcp_t *tcp)
8405 {
8406 	tcph_t		*tcph;
8407 	uint32_t	sum;
8408 	conn_t		*connp;
8409 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8410 
8411 	/*
8412 	 * This is a simple initialization. If there's
8413 	 * already a template, it should never be too small,
8414 	 * so reuse it.  Otherwise, allocate space for the new one.
8415 	 */
8416 	if (tcp->tcp_iphc == NULL) {
8417 		ASSERT(tcp->tcp_iphc_len == 0);
8418 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8419 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8420 		if (tcp->tcp_iphc == NULL) {
8421 			tcp->tcp_iphc_len = 0;
8422 			return (ENOMEM);
8423 		}
8424 	}
8425 
8426 	/* options are gone; may need a new label */
8427 	connp = tcp->tcp_connp;
8428 	connp->conn_mlp_type = mlptSingle;
8429 	connp->conn_ulp_labeled = !is_system_labeled();
8430 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8431 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8432 	tcp->tcp_ip6h = NULL;
8433 	tcp->tcp_ipversion = IPV4_VERSION;
8434 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8435 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8436 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8437 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8438 	tcp->tcp_ipha->ipha_version_and_hdr_length
8439 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8440 	tcp->tcp_ipha->ipha_ident = 0;
8441 
8442 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8443 	tcp->tcp_tos = 0;
8444 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8445 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8446 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8447 
8448 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8449 	tcp->tcp_tcph = tcph;
8450 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8451 	/*
8452 	 * IP wants our header length in the checksum field to
8453 	 * allow it to perform a single pseudo-header+checksum
8454 	 * calculation on behalf of TCP.
8455 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8456 	 */
8457 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8458 	sum = (sum >> 16) + (sum & 0xFFFF);
8459 	U16_TO_ABE16(sum, tcph->th_sum);
8460 	return (0);
8461 }
8462 
8463 /*
8464  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8465  */
8466 static int
8467 tcp_header_init_ipv6(tcp_t *tcp)
8468 {
8469 	tcph_t	*tcph;
8470 	uint32_t	sum;
8471 	conn_t	*connp;
8472 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8473 
8474 	/*
8475 	 * This is a simple initialization. If there's
8476 	 * already a template, it should never be too small,
8477 	 * so reuse it. Otherwise, allocate space for the new one.
8478 	 * Ensure that there is enough space to "downgrade" the tcp_t
8479 	 * to an IPv4 tcp_t. This requires having space for a full load
8480 	 * of IPv4 options, as well as a full load of TCP options
8481 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8482 	 * than a v6 header and a TCP header with a full load of TCP options
8483 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8484 	 * We want to avoid reallocation in the "downgraded" case when
8485 	 * processing outbound IPv4 options.
8486 	 */
8487 	if (tcp->tcp_iphc == NULL) {
8488 		ASSERT(tcp->tcp_iphc_len == 0);
8489 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8490 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8491 		if (tcp->tcp_iphc == NULL) {
8492 			tcp->tcp_iphc_len = 0;
8493 			return (ENOMEM);
8494 		}
8495 	}
8496 
8497 	/* options are gone; may need a new label */
8498 	connp = tcp->tcp_connp;
8499 	connp->conn_mlp_type = mlptSingle;
8500 	connp->conn_ulp_labeled = !is_system_labeled();
8501 
8502 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8503 	tcp->tcp_ipversion = IPV6_VERSION;
8504 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8505 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8506 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8507 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8508 	tcp->tcp_ipha = NULL;
8509 
8510 	/* Initialize the header template */
8511 
8512 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8513 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8514 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8515 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8516 
8517 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8518 	tcp->tcp_tcph = tcph;
8519 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8520 	/*
8521 	 * IP wants our header length in the checksum field to
8522 	 * allow it to perform a single psuedo-header+checksum
8523 	 * calculation on behalf of TCP.
8524 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8525 	 */
8526 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8527 	sum = (sum >> 16) + (sum & 0xFFFF);
8528 	U16_TO_ABE16(sum, tcph->th_sum);
8529 	return (0);
8530 }
8531 
8532 /* At minimum we need 8 bytes in the TCP header for the lookup */
8533 #define	ICMP_MIN_TCP_HDR	8
8534 
8535 /*
8536  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8537  * passed up by IP. The message is always received on the correct tcp_t.
8538  * Assumes that IP has pulled up everything up to and including the ICMP header.
8539  */
8540 void
8541 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8542 {
8543 	icmph_t *icmph;
8544 	ipha_t	*ipha;
8545 	int	iph_hdr_length;
8546 	tcph_t	*tcph;
8547 	boolean_t ipsec_mctl = B_FALSE;
8548 	boolean_t secure;
8549 	mblk_t *first_mp = mp;
8550 	uint32_t new_mss;
8551 	uint32_t ratio;
8552 	size_t mp_size = MBLKL(mp);
8553 	uint32_t seg_seq;
8554 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8555 
8556 	/* Assume IP provides aligned packets - otherwise toss */
8557 	if (!OK_32PTR(mp->b_rptr)) {
8558 		freemsg(mp);
8559 		return;
8560 	}
8561 
8562 	/*
8563 	 * Since ICMP errors are normal data marked with M_CTL when sent
8564 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8565 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8566 	 */
8567 	if ((mp_size == sizeof (ipsec_info_t)) &&
8568 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8569 		ASSERT(mp->b_cont != NULL);
8570 		mp = mp->b_cont;
8571 		/* IP should have done this */
8572 		ASSERT(OK_32PTR(mp->b_rptr));
8573 		mp_size = MBLKL(mp);
8574 		ipsec_mctl = B_TRUE;
8575 	}
8576 
8577 	/*
8578 	 * Verify that we have a complete outer IP header. If not, drop it.
8579 	 */
8580 	if (mp_size < sizeof (ipha_t)) {
8581 noticmpv4:
8582 		freemsg(first_mp);
8583 		return;
8584 	}
8585 
8586 	ipha = (ipha_t *)mp->b_rptr;
8587 	/*
8588 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8589 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8590 	 */
8591 	switch (IPH_HDR_VERSION(ipha)) {
8592 	case IPV6_VERSION:
8593 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8594 		return;
8595 	case IPV4_VERSION:
8596 		break;
8597 	default:
8598 		goto noticmpv4;
8599 	}
8600 
8601 	/* Skip past the outer IP and ICMP headers */
8602 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8603 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8604 	/*
8605 	 * If we don't have the correct outer IP header length or if the ULP
8606 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8607 	 * send it upstream.
8608 	 */
8609 	if (iph_hdr_length < sizeof (ipha_t) ||
8610 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8611 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8612 		goto noticmpv4;
8613 	}
8614 	ipha = (ipha_t *)&icmph[1];
8615 
8616 	/* Skip past the inner IP and find the ULP header */
8617 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8618 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8619 	/*
8620 	 * If we don't have the correct inner IP header length or if the ULP
8621 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8622 	 * bytes of TCP header, drop it.
8623 	 */
8624 	if (iph_hdr_length < sizeof (ipha_t) ||
8625 	    ipha->ipha_protocol != IPPROTO_TCP ||
8626 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8627 		goto noticmpv4;
8628 	}
8629 
8630 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8631 		if (ipsec_mctl) {
8632 			secure = ipsec_in_is_secure(first_mp);
8633 		} else {
8634 			secure = B_FALSE;
8635 		}
8636 		if (secure) {
8637 			/*
8638 			 * If we are willing to accept this in clear
8639 			 * we don't have to verify policy.
8640 			 */
8641 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8642 				if (!tcp_check_policy(tcp, first_mp,
8643 				    ipha, NULL, secure, ipsec_mctl)) {
8644 					/*
8645 					 * tcp_check_policy called
8646 					 * ip_drop_packet() on failure.
8647 					 */
8648 					return;
8649 				}
8650 			}
8651 		}
8652 	} else if (ipsec_mctl) {
8653 		/*
8654 		 * This is a hard_bound connection. IP has already
8655 		 * verified policy. We don't have to do it again.
8656 		 */
8657 		freeb(first_mp);
8658 		first_mp = mp;
8659 		ipsec_mctl = B_FALSE;
8660 	}
8661 
8662 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8663 	/*
8664 	 * TCP SHOULD check that the TCP sequence number contained in
8665 	 * payload of the ICMP error message is within the range
8666 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8667 	 */
8668 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8669 		/*
8670 		 * If the ICMP message is bogus, should we kill the
8671 		 * connection, or should we just drop the bogus ICMP
8672 		 * message? It would probably make more sense to just
8673 		 * drop the message so that if this one managed to get
8674 		 * in, the real connection should not suffer.
8675 		 */
8676 		goto noticmpv4;
8677 	}
8678 
8679 	switch (icmph->icmph_type) {
8680 	case ICMP_DEST_UNREACHABLE:
8681 		switch (icmph->icmph_code) {
8682 		case ICMP_FRAGMENTATION_NEEDED:
8683 			/*
8684 			 * Reduce the MSS based on the new MTU.  This will
8685 			 * eliminate any fragmentation locally.
8686 			 * N.B.  There may well be some funny side-effects on
8687 			 * the local send policy and the remote receive policy.
8688 			 * Pending further research, we provide
8689 			 * tcp_ignore_path_mtu just in case this proves
8690 			 * disastrous somewhere.
8691 			 *
8692 			 * After updating the MSS, retransmit part of the
8693 			 * dropped segment using the new mss by calling
8694 			 * tcp_wput_data().  Need to adjust all those
8695 			 * params to make sure tcp_wput_data() work properly.
8696 			 */
8697 			if (tcps->tcps_ignore_path_mtu)
8698 				break;
8699 
8700 			/*
8701 			 * Decrease the MSS by time stamp options
8702 			 * IP options and IPSEC options. tcp_hdr_len
8703 			 * includes time stamp option and IP option
8704 			 * length.
8705 			 */
8706 
8707 			new_mss = ntohs(icmph->icmph_du_mtu) -
8708 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8709 
8710 			/*
8711 			 * Only update the MSS if the new one is
8712 			 * smaller than the previous one.  This is
8713 			 * to avoid problems when getting multiple
8714 			 * ICMP errors for the same MTU.
8715 			 */
8716 			if (new_mss >= tcp->tcp_mss)
8717 				break;
8718 
8719 			/*
8720 			 * Stop doing PMTU if new_mss is less than 68
8721 			 * or less than tcp_mss_min.
8722 			 * The value 68 comes from rfc 1191.
8723 			 */
8724 			if (new_mss < MAX(68, tcps->tcps_mss_min))
8725 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8726 				    0;
8727 
8728 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8729 			ASSERT(ratio >= 1);
8730 			tcp_mss_set(tcp, new_mss, B_TRUE);
8731 
8732 			/*
8733 			 * Make sure we have something to
8734 			 * send.
8735 			 */
8736 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8737 			    (tcp->tcp_xmit_head != NULL)) {
8738 				/*
8739 				 * Shrink tcp_cwnd in
8740 				 * proportion to the old MSS/new MSS.
8741 				 */
8742 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8743 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8744 				    (tcp->tcp_unsent == 0)) {
8745 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8746 				} else {
8747 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8748 				}
8749 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8750 				tcp->tcp_rexmit = B_TRUE;
8751 				tcp->tcp_dupack_cnt = 0;
8752 				tcp->tcp_snd_burst = TCP_CWND_SS;
8753 				tcp_ss_rexmit(tcp);
8754 			}
8755 			break;
8756 		case ICMP_PORT_UNREACHABLE:
8757 		case ICMP_PROTOCOL_UNREACHABLE:
8758 			switch (tcp->tcp_state) {
8759 			case TCPS_SYN_SENT:
8760 			case TCPS_SYN_RCVD:
8761 				/*
8762 				 * ICMP can snipe away incipient
8763 				 * TCP connections as long as
8764 				 * seq number is same as initial
8765 				 * send seq number.
8766 				 */
8767 				if (seg_seq == tcp->tcp_iss) {
8768 					(void) tcp_clean_death(tcp,
8769 					    ECONNREFUSED, 6);
8770 				}
8771 				break;
8772 			}
8773 			break;
8774 		case ICMP_HOST_UNREACHABLE:
8775 		case ICMP_NET_UNREACHABLE:
8776 			/* Record the error in case we finally time out. */
8777 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8778 				tcp->tcp_client_errno = EHOSTUNREACH;
8779 			else
8780 				tcp->tcp_client_errno = ENETUNREACH;
8781 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8782 				if (tcp->tcp_listener != NULL &&
8783 				    tcp->tcp_listener->tcp_syn_defense) {
8784 					/*
8785 					 * Ditch the half-open connection if we
8786 					 * suspect a SYN attack is under way.
8787 					 */
8788 					tcp_ip_ire_mark_advice(tcp);
8789 					(void) tcp_clean_death(tcp,
8790 					    tcp->tcp_client_errno, 7);
8791 				}
8792 			}
8793 			break;
8794 		default:
8795 			break;
8796 		}
8797 		break;
8798 	case ICMP_SOURCE_QUENCH: {
8799 		/*
8800 		 * use a global boolean to control
8801 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8802 		 * The default is false.
8803 		 */
8804 		if (tcp_icmp_source_quench) {
8805 			/*
8806 			 * Reduce the sending rate as if we got a
8807 			 * retransmit timeout
8808 			 */
8809 			uint32_t npkt;
8810 
8811 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8812 			    tcp->tcp_mss;
8813 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8814 			tcp->tcp_cwnd = tcp->tcp_mss;
8815 			tcp->tcp_cwnd_cnt = 0;
8816 		}
8817 		break;
8818 	}
8819 	}
8820 	freemsg(first_mp);
8821 }
8822 
8823 /*
8824  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8825  * error messages passed up by IP.
8826  * Assumes that IP has pulled up all the extension headers as well
8827  * as the ICMPv6 header.
8828  */
8829 static void
8830 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8831 {
8832 	icmp6_t *icmp6;
8833 	ip6_t	*ip6h;
8834 	uint16_t	iph_hdr_length;
8835 	tcpha_t	*tcpha;
8836 	uint8_t	*nexthdrp;
8837 	uint32_t new_mss;
8838 	uint32_t ratio;
8839 	boolean_t secure;
8840 	mblk_t *first_mp = mp;
8841 	size_t mp_size;
8842 	uint32_t seg_seq;
8843 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8844 
8845 	/*
8846 	 * The caller has determined if this is an IPSEC_IN packet and
8847 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8848 	 */
8849 	if (ipsec_mctl)
8850 		mp = mp->b_cont;
8851 
8852 	mp_size = MBLKL(mp);
8853 
8854 	/*
8855 	 * Verify that we have a complete IP header. If not, send it upstream.
8856 	 */
8857 	if (mp_size < sizeof (ip6_t)) {
8858 noticmpv6:
8859 		freemsg(first_mp);
8860 		return;
8861 	}
8862 
8863 	/*
8864 	 * Verify this is an ICMPV6 packet, else send it upstream.
8865 	 */
8866 	ip6h = (ip6_t *)mp->b_rptr;
8867 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8868 		iph_hdr_length = IPV6_HDR_LEN;
8869 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8870 	    &nexthdrp) ||
8871 	    *nexthdrp != IPPROTO_ICMPV6) {
8872 		goto noticmpv6;
8873 	}
8874 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8875 	ip6h = (ip6_t *)&icmp6[1];
8876 	/*
8877 	 * Verify if we have a complete ICMP and inner IP header.
8878 	 */
8879 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8880 		goto noticmpv6;
8881 
8882 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8883 		goto noticmpv6;
8884 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8885 	/*
8886 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8887 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8888 	 * packet.
8889 	 */
8890 	if ((*nexthdrp != IPPROTO_TCP) ||
8891 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8892 		goto noticmpv6;
8893 	}
8894 
8895 	/*
8896 	 * ICMP errors come on the right queue or come on
8897 	 * listener/global queue for detached connections and
8898 	 * get switched to the right queue. If it comes on the
8899 	 * right queue, policy check has already been done by IP
8900 	 * and thus free the first_mp without verifying the policy.
8901 	 * If it has come for a non-hard bound connection, we need
8902 	 * to verify policy as IP may not have done it.
8903 	 */
8904 	if (!tcp->tcp_hard_bound) {
8905 		if (ipsec_mctl) {
8906 			secure = ipsec_in_is_secure(first_mp);
8907 		} else {
8908 			secure = B_FALSE;
8909 		}
8910 		if (secure) {
8911 			/*
8912 			 * If we are willing to accept this in clear
8913 			 * we don't have to verify policy.
8914 			 */
8915 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8916 				if (!tcp_check_policy(tcp, first_mp,
8917 				    NULL, ip6h, secure, ipsec_mctl)) {
8918 					/*
8919 					 * tcp_check_policy called
8920 					 * ip_drop_packet() on failure.
8921 					 */
8922 					return;
8923 				}
8924 			}
8925 		}
8926 	} else if (ipsec_mctl) {
8927 		/*
8928 		 * This is a hard_bound connection. IP has already
8929 		 * verified policy. We don't have to do it again.
8930 		 */
8931 		freeb(first_mp);
8932 		first_mp = mp;
8933 		ipsec_mctl = B_FALSE;
8934 	}
8935 
8936 	seg_seq = ntohl(tcpha->tha_seq);
8937 	/*
8938 	 * TCP SHOULD check that the TCP sequence number contained in
8939 	 * payload of the ICMP error message is within the range
8940 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8941 	 */
8942 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8943 		/*
8944 		 * If the ICMP message is bogus, should we kill the
8945 		 * connection, or should we just drop the bogus ICMP
8946 		 * message? It would probably make more sense to just
8947 		 * drop the message so that if this one managed to get
8948 		 * in, the real connection should not suffer.
8949 		 */
8950 		goto noticmpv6;
8951 	}
8952 
8953 	switch (icmp6->icmp6_type) {
8954 	case ICMP6_PACKET_TOO_BIG:
8955 		/*
8956 		 * Reduce the MSS based on the new MTU.  This will
8957 		 * eliminate any fragmentation locally.
8958 		 * N.B.  There may well be some funny side-effects on
8959 		 * the local send policy and the remote receive policy.
8960 		 * Pending further research, we provide
8961 		 * tcp_ignore_path_mtu just in case this proves
8962 		 * disastrous somewhere.
8963 		 *
8964 		 * After updating the MSS, retransmit part of the
8965 		 * dropped segment using the new mss by calling
8966 		 * tcp_wput_data().  Need to adjust all those
8967 		 * params to make sure tcp_wput_data() work properly.
8968 		 */
8969 		if (tcps->tcps_ignore_path_mtu)
8970 			break;
8971 
8972 		/*
8973 		 * Decrease the MSS by time stamp options
8974 		 * IP options and IPSEC options. tcp_hdr_len
8975 		 * includes time stamp option and IP option
8976 		 * length.
8977 		 */
8978 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8979 		    tcp->tcp_ipsec_overhead;
8980 
8981 		/*
8982 		 * Only update the MSS if the new one is
8983 		 * smaller than the previous one.  This is
8984 		 * to avoid problems when getting multiple
8985 		 * ICMP errors for the same MTU.
8986 		 */
8987 		if (new_mss >= tcp->tcp_mss)
8988 			break;
8989 
8990 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8991 		ASSERT(ratio >= 1);
8992 		tcp_mss_set(tcp, new_mss, B_TRUE);
8993 
8994 		/*
8995 		 * Make sure we have something to
8996 		 * send.
8997 		 */
8998 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8999 		    (tcp->tcp_xmit_head != NULL)) {
9000 			/*
9001 			 * Shrink tcp_cwnd in
9002 			 * proportion to the old MSS/new MSS.
9003 			 */
9004 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
9005 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
9006 			    (tcp->tcp_unsent == 0)) {
9007 				tcp->tcp_rexmit_max = tcp->tcp_fss;
9008 			} else {
9009 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
9010 			}
9011 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
9012 			tcp->tcp_rexmit = B_TRUE;
9013 			tcp->tcp_dupack_cnt = 0;
9014 			tcp->tcp_snd_burst = TCP_CWND_SS;
9015 			tcp_ss_rexmit(tcp);
9016 		}
9017 		break;
9018 
9019 	case ICMP6_DST_UNREACH:
9020 		switch (icmp6->icmp6_code) {
9021 		case ICMP6_DST_UNREACH_NOPORT:
9022 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
9023 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
9024 			    (seg_seq == tcp->tcp_iss)) {
9025 				(void) tcp_clean_death(tcp,
9026 				    ECONNREFUSED, 8);
9027 			}
9028 			break;
9029 
9030 		case ICMP6_DST_UNREACH_ADMIN:
9031 		case ICMP6_DST_UNREACH_NOROUTE:
9032 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
9033 		case ICMP6_DST_UNREACH_ADDR:
9034 			/* Record the error in case we finally time out. */
9035 			tcp->tcp_client_errno = EHOSTUNREACH;
9036 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
9037 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
9038 			    (seg_seq == tcp->tcp_iss)) {
9039 				if (tcp->tcp_listener != NULL &&
9040 				    tcp->tcp_listener->tcp_syn_defense) {
9041 					/*
9042 					 * Ditch the half-open connection if we
9043 					 * suspect a SYN attack is under way.
9044 					 */
9045 					tcp_ip_ire_mark_advice(tcp);
9046 					(void) tcp_clean_death(tcp,
9047 					    tcp->tcp_client_errno, 9);
9048 				}
9049 			}
9050 
9051 
9052 			break;
9053 		default:
9054 			break;
9055 		}
9056 		break;
9057 
9058 	case ICMP6_PARAM_PROB:
9059 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
9060 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
9061 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
9062 		    (uchar_t *)nexthdrp) {
9063 			if (tcp->tcp_state == TCPS_SYN_SENT ||
9064 			    tcp->tcp_state == TCPS_SYN_RCVD) {
9065 				(void) tcp_clean_death(tcp,
9066 				    ECONNREFUSED, 10);
9067 			}
9068 			break;
9069 		}
9070 		break;
9071 
9072 	case ICMP6_TIME_EXCEEDED:
9073 	default:
9074 		break;
9075 	}
9076 	freemsg(first_mp);
9077 }
9078 
9079 /*
9080  * IP recognizes seven kinds of bind requests:
9081  *
9082  * - A zero-length address binds only to the protocol number.
9083  *
9084  * - A 4-byte address is treated as a request to
9085  * validate that the address is a valid local IPv4
9086  * address, appropriate for an application to bind to.
9087  * IP does the verification, but does not make any note
9088  * of the address at this time.
9089  *
9090  * - A 16-byte address contains is treated as a request
9091  * to validate a local IPv6 address, as the 4-byte
9092  * address case above.
9093  *
9094  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
9095  * use it for the inbound fanout of packets.
9096  *
9097  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
9098  * use it for the inbound fanout of packets.
9099  *
9100  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
9101  * information consisting of local and remote addresses
9102  * and ports.  In this case, the addresses are both
9103  * validated as appropriate for this operation, and, if
9104  * so, the information is retained for use in the
9105  * inbound fanout.
9106  *
9107  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
9108  * fanout information, like the 12-byte case above.
9109  *
9110  * IP will also fill in the IRE request mblk with information
9111  * regarding our peer.  In all cases, we notify IP of our protocol
9112  * type by appending a single protocol byte to the bind request.
9113  */
9114 static mblk_t *
9115 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
9116 {
9117 	char	*cp;
9118 	mblk_t	*mp;
9119 	struct T_bind_req *tbr;
9120 	ipa_conn_t	*ac;
9121 	ipa6_conn_t	*ac6;
9122 	sin_t		*sin;
9123 	sin6_t		*sin6;
9124 
9125 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
9126 	ASSERT((tcp->tcp_family == AF_INET &&
9127 	    tcp->tcp_ipversion == IPV4_VERSION) ||
9128 	    (tcp->tcp_family == AF_INET6 &&
9129 	    (tcp->tcp_ipversion == IPV4_VERSION ||
9130 	    tcp->tcp_ipversion == IPV6_VERSION)));
9131 
9132 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
9133 	if (!mp)
9134 		return (mp);
9135 	mp->b_datap->db_type = M_PROTO;
9136 	tbr = (struct T_bind_req *)mp->b_rptr;
9137 	tbr->PRIM_type = bind_prim;
9138 	tbr->ADDR_offset = sizeof (*tbr);
9139 	tbr->CONIND_number = 0;
9140 	tbr->ADDR_length = addr_length;
9141 	cp = (char *)&tbr[1];
9142 	switch (addr_length) {
9143 	case sizeof (ipa_conn_t):
9144 		ASSERT(tcp->tcp_family == AF_INET);
9145 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9146 
9147 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9148 		if (mp->b_cont == NULL) {
9149 			freemsg(mp);
9150 			return (NULL);
9151 		}
9152 		mp->b_cont->b_wptr += sizeof (ire_t);
9153 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9154 
9155 		/* cp known to be 32 bit aligned */
9156 		ac = (ipa_conn_t *)cp;
9157 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
9158 		ac->ac_faddr = tcp->tcp_remote;
9159 		ac->ac_fport = tcp->tcp_fport;
9160 		ac->ac_lport = tcp->tcp_lport;
9161 		tcp->tcp_hard_binding = 1;
9162 		break;
9163 
9164 	case sizeof (ipa6_conn_t):
9165 		ASSERT(tcp->tcp_family == AF_INET6);
9166 
9167 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9168 		if (mp->b_cont == NULL) {
9169 			freemsg(mp);
9170 			return (NULL);
9171 		}
9172 		mp->b_cont->b_wptr += sizeof (ire_t);
9173 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9174 
9175 		/* cp known to be 32 bit aligned */
9176 		ac6 = (ipa6_conn_t *)cp;
9177 		if (tcp->tcp_ipversion == IPV4_VERSION) {
9178 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
9179 			    &ac6->ac6_laddr);
9180 		} else {
9181 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
9182 		}
9183 		ac6->ac6_faddr = tcp->tcp_remote_v6;
9184 		ac6->ac6_fport = tcp->tcp_fport;
9185 		ac6->ac6_lport = tcp->tcp_lport;
9186 		tcp->tcp_hard_binding = 1;
9187 		break;
9188 
9189 	case sizeof (sin_t):
9190 		/*
9191 		 * NOTE: IPV6_ADDR_LEN also has same size.
9192 		 * Use family to discriminate.
9193 		 */
9194 		if (tcp->tcp_family == AF_INET) {
9195 			sin = (sin_t *)cp;
9196 
9197 			*sin = sin_null;
9198 			sin->sin_family = AF_INET;
9199 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
9200 			sin->sin_port = tcp->tcp_lport;
9201 			break;
9202 		} else {
9203 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
9204 		}
9205 		break;
9206 
9207 	case sizeof (sin6_t):
9208 		ASSERT(tcp->tcp_family == AF_INET6);
9209 		sin6 = (sin6_t *)cp;
9210 
9211 		*sin6 = sin6_null;
9212 		sin6->sin6_family = AF_INET6;
9213 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
9214 		sin6->sin6_port = tcp->tcp_lport;
9215 		break;
9216 
9217 	case IP_ADDR_LEN:
9218 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9219 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
9220 		break;
9221 
9222 	}
9223 	/* Add protocol number to end */
9224 	cp[addr_length] = (char)IPPROTO_TCP;
9225 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
9226 	return (mp);
9227 }
9228 
9229 /*
9230  * Notify IP that we are having trouble with this connection.  IP should
9231  * blow the IRE away and start over.
9232  */
9233 static void
9234 tcp_ip_notify(tcp_t *tcp)
9235 {
9236 	struct iocblk	*iocp;
9237 	ipid_t	*ipid;
9238 	mblk_t	*mp;
9239 
9240 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
9241 	if (tcp->tcp_ipversion == IPV6_VERSION)
9242 		return;
9243 
9244 	mp = mkiocb(IP_IOCTL);
9245 	if (mp == NULL)
9246 		return;
9247 
9248 	iocp = (struct iocblk *)mp->b_rptr;
9249 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
9250 
9251 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
9252 	if (!mp->b_cont) {
9253 		freeb(mp);
9254 		return;
9255 	}
9256 
9257 	ipid = (ipid_t *)mp->b_cont->b_rptr;
9258 	mp->b_cont->b_wptr += iocp->ioc_count;
9259 	bzero(ipid, sizeof (*ipid));
9260 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
9261 	ipid->ipid_ire_type = IRE_CACHE;
9262 	ipid->ipid_addr_offset = sizeof (ipid_t);
9263 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
9264 	/*
9265 	 * Note: in the case of source routing we want to blow away the
9266 	 * route to the first source route hop.
9267 	 */
9268 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
9269 	    sizeof (tcp->tcp_ipha->ipha_dst));
9270 
9271 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
9272 }
9273 
9274 /* Unlink and return any mblk that looks like it contains an ire */
9275 static mblk_t *
9276 tcp_ire_mp(mblk_t *mp)
9277 {
9278 	mblk_t	*prev_mp;
9279 
9280 	for (;;) {
9281 		prev_mp = mp;
9282 		mp = mp->b_cont;
9283 		if (mp == NULL)
9284 			break;
9285 		switch (DB_TYPE(mp)) {
9286 		case IRE_DB_TYPE:
9287 		case IRE_DB_REQ_TYPE:
9288 			if (prev_mp != NULL)
9289 				prev_mp->b_cont = mp->b_cont;
9290 			mp->b_cont = NULL;
9291 			return (mp);
9292 		default:
9293 			break;
9294 		}
9295 	}
9296 	return (mp);
9297 }
9298 
9299 /*
9300  * Timer callback routine for keepalive probe.  We do a fake resend of
9301  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
9302  * check to see if we have heard anything from the other end for the last
9303  * RTO period.  If we have, set the timer to expire for another
9304  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
9305  * RTO << 1 and check again when it expires.  Keep exponentially increasing
9306  * the timeout if we have not heard from the other side.  If for more than
9307  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
9308  * kill the connection unless the keepalive abort threshold is 0.  In
9309  * that case, we will probe "forever."
9310  */
9311 static void
9312 tcp_keepalive_killer(void *arg)
9313 {
9314 	mblk_t	*mp;
9315 	conn_t	*connp = (conn_t *)arg;
9316 	tcp_t  	*tcp = connp->conn_tcp;
9317 	int32_t	firetime;
9318 	int32_t	idletime;
9319 	int32_t	ka_intrvl;
9320 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9321 
9322 	tcp->tcp_ka_tid = 0;
9323 
9324 	if (tcp->tcp_fused)
9325 		return;
9326 
9327 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
9328 	ka_intrvl = tcp->tcp_ka_interval;
9329 
9330 	/*
9331 	 * Keepalive probe should only be sent if the application has not
9332 	 * done a close on the connection.
9333 	 */
9334 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
9335 		return;
9336 	}
9337 	/* Timer fired too early, restart it. */
9338 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
9339 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9340 		    MSEC_TO_TICK(ka_intrvl));
9341 		return;
9342 	}
9343 
9344 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
9345 	/*
9346 	 * If we have not heard from the other side for a long
9347 	 * time, kill the connection unless the keepalive abort
9348 	 * threshold is 0.  In that case, we will probe "forever."
9349 	 */
9350 	if (tcp->tcp_ka_abort_thres != 0 &&
9351 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
9352 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
9353 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
9354 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
9355 		return;
9356 	}
9357 
9358 	if (tcp->tcp_snxt == tcp->tcp_suna &&
9359 	    idletime >= ka_intrvl) {
9360 		/* Fake resend of last ACKed byte. */
9361 		mblk_t	*mp1 = allocb(1, BPRI_LO);
9362 
9363 		if (mp1 != NULL) {
9364 			*mp1->b_wptr++ = '\0';
9365 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
9366 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
9367 			freeb(mp1);
9368 			/*
9369 			 * if allocation failed, fall through to start the
9370 			 * timer back.
9371 			 */
9372 			if (mp != NULL) {
9373 				TCP_RECORD_TRACE(tcp, mp,
9374 				    TCP_TRACE_SEND_PKT);
9375 				tcp_send_data(tcp, tcp->tcp_wq, mp);
9376 				BUMP_MIB(&tcps->tcps_mib,
9377 				    tcpTimKeepaliveProbe);
9378 				if (tcp->tcp_ka_last_intrvl != 0) {
9379 					int max;
9380 					/*
9381 					 * We should probe again at least
9382 					 * in ka_intrvl, but not more than
9383 					 * tcp_rexmit_interval_max.
9384 					 */
9385 					max = tcps->tcps_rexmit_interval_max;
9386 					firetime = MIN(ka_intrvl - 1,
9387 					    tcp->tcp_ka_last_intrvl << 1);
9388 					if (firetime > max)
9389 						firetime = max;
9390 				} else {
9391 					firetime = tcp->tcp_rto;
9392 				}
9393 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9394 				    tcp_keepalive_killer,
9395 				    MSEC_TO_TICK(firetime));
9396 				tcp->tcp_ka_last_intrvl = firetime;
9397 				return;
9398 			}
9399 		}
9400 	} else {
9401 		tcp->tcp_ka_last_intrvl = 0;
9402 	}
9403 
9404 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
9405 	if ((firetime = ka_intrvl - idletime) < 0) {
9406 		firetime = ka_intrvl;
9407 	}
9408 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9409 	    MSEC_TO_TICK(firetime));
9410 }
9411 
9412 int
9413 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
9414 {
9415 	queue_t	*q = tcp->tcp_rq;
9416 	int32_t	mss = tcp->tcp_mss;
9417 	int	maxpsz;
9418 
9419 	if (TCP_IS_DETACHED(tcp))
9420 		return (mss);
9421 
9422 	if (tcp->tcp_fused) {
9423 		maxpsz = tcp_fuse_maxpsz_set(tcp);
9424 		mss = INFPSZ;
9425 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
9426 		/*
9427 		 * Set the sd_qn_maxpsz according to the socket send buffer
9428 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
9429 		 * instruct the stream head to copyin user data into contiguous
9430 		 * kernel-allocated buffers without breaking it up into smaller
9431 		 * chunks.  We round up the buffer size to the nearest SMSS.
9432 		 */
9433 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
9434 		if (tcp->tcp_kssl_ctx == NULL)
9435 			mss = INFPSZ;
9436 		else
9437 			mss = SSL3_MAX_RECORD_LEN;
9438 	} else {
9439 		/*
9440 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
9441 		 * (and a multiple of the mss).  This instructs the stream
9442 		 * head to break down larger than SMSS writes into SMSS-
9443 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
9444 		 */
9445 		maxpsz = tcp->tcp_maxpsz * mss;
9446 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
9447 			maxpsz = tcp->tcp_xmit_hiwater/2;
9448 			/* Round up to nearest mss */
9449 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
9450 		}
9451 	}
9452 	(void) setmaxps(q, maxpsz);
9453 	tcp->tcp_wq->q_maxpsz = maxpsz;
9454 
9455 	if (set_maxblk)
9456 		(void) mi_set_sth_maxblk(q, mss);
9457 
9458 	return (mss);
9459 }
9460 
9461 /*
9462  * Extract option values from a tcp header.  We put any found values into the
9463  * tcpopt struct and return a bitmask saying which options were found.
9464  */
9465 static int
9466 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
9467 {
9468 	uchar_t		*endp;
9469 	int		len;
9470 	uint32_t	mss;
9471 	uchar_t		*up = (uchar_t *)tcph;
9472 	int		found = 0;
9473 	int32_t		sack_len;
9474 	tcp_seq		sack_begin, sack_end;
9475 	tcp_t		*tcp;
9476 
9477 	endp = up + TCP_HDR_LENGTH(tcph);
9478 	up += TCP_MIN_HEADER_LENGTH;
9479 	while (up < endp) {
9480 		len = endp - up;
9481 		switch (*up) {
9482 		case TCPOPT_EOL:
9483 			break;
9484 
9485 		case TCPOPT_NOP:
9486 			up++;
9487 			continue;
9488 
9489 		case TCPOPT_MAXSEG:
9490 			if (len < TCPOPT_MAXSEG_LEN ||
9491 			    up[1] != TCPOPT_MAXSEG_LEN)
9492 				break;
9493 
9494 			mss = BE16_TO_U16(up+2);
9495 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9496 			tcpopt->tcp_opt_mss = mss;
9497 			found |= TCP_OPT_MSS_PRESENT;
9498 
9499 			up += TCPOPT_MAXSEG_LEN;
9500 			continue;
9501 
9502 		case TCPOPT_WSCALE:
9503 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9504 				break;
9505 
9506 			if (up[2] > TCP_MAX_WINSHIFT)
9507 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9508 			else
9509 				tcpopt->tcp_opt_wscale = up[2];
9510 			found |= TCP_OPT_WSCALE_PRESENT;
9511 
9512 			up += TCPOPT_WS_LEN;
9513 			continue;
9514 
9515 		case TCPOPT_SACK_PERMITTED:
9516 			if (len < TCPOPT_SACK_OK_LEN ||
9517 			    up[1] != TCPOPT_SACK_OK_LEN)
9518 				break;
9519 			found |= TCP_OPT_SACK_OK_PRESENT;
9520 			up += TCPOPT_SACK_OK_LEN;
9521 			continue;
9522 
9523 		case TCPOPT_SACK:
9524 			if (len <= 2 || up[1] <= 2 || len < up[1])
9525 				break;
9526 
9527 			/* If TCP is not interested in SACK blks... */
9528 			if ((tcp = tcpopt->tcp) == NULL) {
9529 				up += up[1];
9530 				continue;
9531 			}
9532 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9533 			up += TCPOPT_HEADER_LEN;
9534 
9535 			/*
9536 			 * If the list is empty, allocate one and assume
9537 			 * nothing is sack'ed.
9538 			 */
9539 			ASSERT(tcp->tcp_sack_info != NULL);
9540 			if (tcp->tcp_notsack_list == NULL) {
9541 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9542 				    tcp->tcp_suna, tcp->tcp_snxt,
9543 				    &(tcp->tcp_num_notsack_blk),
9544 				    &(tcp->tcp_cnt_notsack_list));
9545 
9546 				/*
9547 				 * Make sure tcp_notsack_list is not NULL.
9548 				 * This happens when kmem_alloc(KM_NOSLEEP)
9549 				 * returns NULL.
9550 				 */
9551 				if (tcp->tcp_notsack_list == NULL) {
9552 					up += sack_len;
9553 					continue;
9554 				}
9555 				tcp->tcp_fack = tcp->tcp_suna;
9556 			}
9557 
9558 			while (sack_len > 0) {
9559 				if (up + 8 > endp) {
9560 					up = endp;
9561 					break;
9562 				}
9563 				sack_begin = BE32_TO_U32(up);
9564 				up += 4;
9565 				sack_end = BE32_TO_U32(up);
9566 				up += 4;
9567 				sack_len -= 8;
9568 				/*
9569 				 * Bounds checking.  Make sure the SACK
9570 				 * info is within tcp_suna and tcp_snxt.
9571 				 * If this SACK blk is out of bound, ignore
9572 				 * it but continue to parse the following
9573 				 * blks.
9574 				 */
9575 				if (SEQ_LEQ(sack_end, sack_begin) ||
9576 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9577 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9578 					continue;
9579 				}
9580 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9581 				    sack_begin, sack_end,
9582 				    &(tcp->tcp_num_notsack_blk),
9583 				    &(tcp->tcp_cnt_notsack_list));
9584 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9585 					tcp->tcp_fack = sack_end;
9586 				}
9587 			}
9588 			found |= TCP_OPT_SACK_PRESENT;
9589 			continue;
9590 
9591 		case TCPOPT_TSTAMP:
9592 			if (len < TCPOPT_TSTAMP_LEN ||
9593 			    up[1] != TCPOPT_TSTAMP_LEN)
9594 				break;
9595 
9596 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9597 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9598 
9599 			found |= TCP_OPT_TSTAMP_PRESENT;
9600 
9601 			up += TCPOPT_TSTAMP_LEN;
9602 			continue;
9603 
9604 		default:
9605 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9606 				break;
9607 			up += up[1];
9608 			continue;
9609 		}
9610 		break;
9611 	}
9612 	return (found);
9613 }
9614 
9615 /*
9616  * Set the mss associated with a particular tcp based on its current value,
9617  * and a new one passed in. Observe minimums and maximums, and reset
9618  * other state variables that we want to view as multiples of mss.
9619  *
9620  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9621  * highwater marks etc. need to be initialized or adjusted.
9622  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9623  *    packet arrives.
9624  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9625  *    ICMP6_PACKET_TOO_BIG arrives.
9626  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9627  *    to increase the MSS to use the extra bytes available.
9628  *
9629  * Callers except tcp_paws_check() ensure that they only reduce mss.
9630  */
9631 static void
9632 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9633 {
9634 	uint32_t	mss_max;
9635 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9636 
9637 	if (tcp->tcp_ipversion == IPV4_VERSION)
9638 		mss_max = tcps->tcps_mss_max_ipv4;
9639 	else
9640 		mss_max = tcps->tcps_mss_max_ipv6;
9641 
9642 	if (mss < tcps->tcps_mss_min)
9643 		mss = tcps->tcps_mss_min;
9644 	if (mss > mss_max)
9645 		mss = mss_max;
9646 	/*
9647 	 * Unless naglim has been set by our client to
9648 	 * a non-mss value, force naglim to track mss.
9649 	 * This can help to aggregate small writes.
9650 	 */
9651 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9652 		tcp->tcp_naglim = mss;
9653 	/*
9654 	 * TCP should be able to buffer at least 4 MSS data for obvious
9655 	 * performance reason.
9656 	 */
9657 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9658 		tcp->tcp_xmit_hiwater = mss << 2;
9659 
9660 	if (do_ss) {
9661 		/*
9662 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9663 		 * changing due to a reduction in MTU, presumably as a
9664 		 * result of a new path component, reset cwnd to its
9665 		 * "initial" value, as a multiple of the new mss.
9666 		 */
9667 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9668 	} else {
9669 		/*
9670 		 * Called by tcp_paws_check(), the mss increased
9671 		 * marginally to allow use of space previously taken
9672 		 * by the timestamp option. It would be inappropriate
9673 		 * to apply slow start or tcp_init_cwnd values to
9674 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9675 		 */
9676 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9677 		tcp->tcp_cwnd_cnt = 0;
9678 	}
9679 	tcp->tcp_mss = mss;
9680 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9681 }
9682 
9683 /* For /dev/tcp aka AF_INET open */
9684 static int
9685 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9686 {
9687 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9688 }
9689 
9690 /* For /dev/tcp6 aka AF_INET6 open */
9691 static int
9692 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9693 {
9694 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9695 }
9696 
9697 static int
9698 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9699     boolean_t isv6)
9700 {
9701 	tcp_t		*tcp = NULL;
9702 	conn_t		*connp;
9703 	int		err;
9704 	vmem_t		*minor_arena = NULL;
9705 	dev_t		conn_dev;
9706 	zoneid_t	zoneid;
9707 	tcp_stack_t	*tcps = NULL;
9708 
9709 	if (q->q_ptr != NULL)
9710 		return (0);
9711 
9712 	if (sflag == MODOPEN)
9713 		return (EINVAL);
9714 
9715 	if (!(flag & SO_ACCEPTOR)) {
9716 		/*
9717 		 * Special case for install: miniroot needs to be able to
9718 		 * access files via NFS as though it were always in the
9719 		 * global zone.
9720 		 */
9721 		if (credp == kcred && nfs_global_client_only != 0) {
9722 			zoneid = GLOBAL_ZONEID;
9723 			tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9724 			    netstack_tcp;
9725 			ASSERT(tcps != NULL);
9726 		} else {
9727 			netstack_t *ns;
9728 
9729 			ns = netstack_find_by_cred(credp);
9730 			ASSERT(ns != NULL);
9731 			tcps = ns->netstack_tcp;
9732 			ASSERT(tcps != NULL);
9733 
9734 			/*
9735 			 * For exclusive stacks we set the zoneid to zero
9736 			 * to make TCP operate as if in the global zone.
9737 			 */
9738 			if (tcps->tcps_netstack->netstack_stackid !=
9739 			    GLOBAL_NETSTACKID)
9740 				zoneid = GLOBAL_ZONEID;
9741 			else
9742 				zoneid = crgetzoneid(credp);
9743 		}
9744 		/*
9745 		 * For stackid zero this is done from strplumb.c, but
9746 		 * non-zero stackids are handled here.
9747 		 */
9748 		if (tcps->tcps_g_q == NULL &&
9749 		    tcps->tcps_netstack->netstack_stackid !=
9750 		    GLOBAL_NETSTACKID) {
9751 			tcp_g_q_setup(tcps);
9752 		}
9753 	}
9754 
9755 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9756 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9757 		minor_arena = ip_minor_arena_la;
9758 	} else {
9759 		/*
9760 		 * Either minor numbers in the large arena were exhausted
9761 		 * or a non socket application is doing the open.
9762 		 * Try to allocate from the small arena.
9763 		 */
9764 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9765 			if (tcps != NULL)
9766 				netstack_rele(tcps->tcps_netstack);
9767 			return (EBUSY);
9768 		}
9769 		minor_arena = ip_minor_arena_sa;
9770 	}
9771 	ASSERT(minor_arena != NULL);
9772 
9773 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9774 
9775 	if (flag & SO_ACCEPTOR) {
9776 		/* No netstack_find_by_cred, hence no netstack_rele needed */
9777 		ASSERT(tcps == NULL);
9778 		q->q_qinfo = &tcp_acceptor_rinit;
9779 		/*
9780 		 * the conn_dev and minor_arena will be subsequently used by
9781 		 * tcp_wput_accept() and tcpclose_accept() to figure out the
9782 		 * minor device number for this connection from the q_ptr.
9783 		 */
9784 		RD(q)->q_ptr = (void *)conn_dev;
9785 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9786 		WR(q)->q_ptr = (void *)minor_arena;
9787 		qprocson(q);
9788 		return (0);
9789 	}
9790 
9791 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt), tcps);
9792 	/*
9793 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9794 	 * so we drop it by one.
9795 	 */
9796 	netstack_rele(tcps->tcps_netstack);
9797 	if (connp == NULL) {
9798 		inet_minor_free(minor_arena, conn_dev);
9799 		q->q_ptr = NULL;
9800 		return (ENOSR);
9801 	}
9802 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9803 	tcp = connp->conn_tcp;
9804 
9805 	q->q_ptr = WR(q)->q_ptr = connp;
9806 	if (isv6) {
9807 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9808 		connp->conn_send = ip_output_v6;
9809 		connp->conn_af_isv6 = B_TRUE;
9810 		connp->conn_pkt_isv6 = B_TRUE;
9811 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9812 		tcp->tcp_ipversion = IPV6_VERSION;
9813 		tcp->tcp_family = AF_INET6;
9814 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9815 	} else {
9816 		connp->conn_flags |= IPCL_TCP4;
9817 		connp->conn_send = ip_output;
9818 		connp->conn_af_isv6 = B_FALSE;
9819 		connp->conn_pkt_isv6 = B_FALSE;
9820 		tcp->tcp_ipversion = IPV4_VERSION;
9821 		tcp->tcp_family = AF_INET;
9822 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9823 	}
9824 
9825 	/*
9826 	 * TCP keeps a copy of cred for cache locality reasons but
9827 	 * we put a reference only once. If connp->conn_cred
9828 	 * becomes invalid, tcp_cred should also be set to NULL.
9829 	 */
9830 	tcp->tcp_cred = connp->conn_cred = credp;
9831 	crhold(connp->conn_cred);
9832 	tcp->tcp_cpid = curproc->p_pid;
9833 	tcp->tcp_open_time = lbolt64;
9834 	connp->conn_zoneid = zoneid;
9835 	connp->conn_mlp_type = mlptSingle;
9836 	connp->conn_ulp_labeled = !is_system_labeled();
9837 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9838 	ASSERT(tcp->tcp_tcps == tcps);
9839 
9840 	/*
9841 	 * If the caller has the process-wide flag set, then default to MAC
9842 	 * exempt mode.  This allows read-down to unlabeled hosts.
9843 	 */
9844 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9845 		connp->conn_mac_exempt = B_TRUE;
9846 
9847 	connp->conn_dev = conn_dev;
9848 	connp->conn_minor_arena = minor_arena;
9849 
9850 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9851 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9852 
9853 	if (flag & SO_SOCKSTR) {
9854 		/*
9855 		 * No need to insert a socket in tcp acceptor hash.
9856 		 * If it was a socket acceptor stream, we dealt with
9857 		 * it above. A socket listener can never accept a
9858 		 * connection and doesn't need acceptor_id.
9859 		 */
9860 		connp->conn_flags |= IPCL_SOCKET;
9861 		tcp->tcp_issocket = 1;
9862 		WR(q)->q_qinfo = &tcp_sock_winit;
9863 	} else {
9864 #ifdef	_ILP32
9865 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9866 #else
9867 		tcp->tcp_acceptor_id = conn_dev;
9868 #endif	/* _ILP32 */
9869 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9870 	}
9871 
9872 	if (tcps->tcps_trace)
9873 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_SLEEP);
9874 
9875 	err = tcp_init(tcp, q);
9876 	if (err != 0) {
9877 		inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
9878 		tcp_acceptor_hash_remove(tcp);
9879 		CONN_DEC_REF(connp);
9880 		q->q_ptr = WR(q)->q_ptr = NULL;
9881 		return (err);
9882 	}
9883 
9884 	RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9885 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9886 
9887 	/* Non-zero default values */
9888 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9889 	/*
9890 	 * Put the ref for TCP. Ref for IP was already put
9891 	 * by ipcl_conn_create. Also Make the conn_t globally
9892 	 * visible to walkers
9893 	 */
9894 	mutex_enter(&connp->conn_lock);
9895 	CONN_INC_REF_LOCKED(connp);
9896 	ASSERT(connp->conn_ref == 2);
9897 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9898 	mutex_exit(&connp->conn_lock);
9899 
9900 	qprocson(q);
9901 	return (0);
9902 }
9903 
9904 /*
9905  * Some TCP options can be "set" by requesting them in the option
9906  * buffer. This is needed for XTI feature test though we do not
9907  * allow it in general. We interpret that this mechanism is more
9908  * applicable to OSI protocols and need not be allowed in general.
9909  * This routine filters out options for which it is not allowed (most)
9910  * and lets through those (few) for which it is. [ The XTI interface
9911  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9912  * ever implemented will have to be allowed here ].
9913  */
9914 static boolean_t
9915 tcp_allow_connopt_set(int level, int name)
9916 {
9917 
9918 	switch (level) {
9919 	case IPPROTO_TCP:
9920 		switch (name) {
9921 		case TCP_NODELAY:
9922 			return (B_TRUE);
9923 		default:
9924 			return (B_FALSE);
9925 		}
9926 		/*NOTREACHED*/
9927 	default:
9928 		return (B_FALSE);
9929 	}
9930 	/*NOTREACHED*/
9931 }
9932 
9933 /*
9934  * This routine gets default values of certain options whose default
9935  * values are maintained by protocol specific code
9936  */
9937 /* ARGSUSED */
9938 int
9939 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9940 {
9941 	int32_t	*i1 = (int32_t *)ptr;
9942 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9943 
9944 	switch (level) {
9945 	case IPPROTO_TCP:
9946 		switch (name) {
9947 		case TCP_NOTIFY_THRESHOLD:
9948 			*i1 = tcps->tcps_ip_notify_interval;
9949 			break;
9950 		case TCP_ABORT_THRESHOLD:
9951 			*i1 = tcps->tcps_ip_abort_interval;
9952 			break;
9953 		case TCP_CONN_NOTIFY_THRESHOLD:
9954 			*i1 = tcps->tcps_ip_notify_cinterval;
9955 			break;
9956 		case TCP_CONN_ABORT_THRESHOLD:
9957 			*i1 = tcps->tcps_ip_abort_cinterval;
9958 			break;
9959 		default:
9960 			return (-1);
9961 		}
9962 		break;
9963 	case IPPROTO_IP:
9964 		switch (name) {
9965 		case IP_TTL:
9966 			*i1 = tcps->tcps_ipv4_ttl;
9967 			break;
9968 		default:
9969 			return (-1);
9970 		}
9971 		break;
9972 	case IPPROTO_IPV6:
9973 		switch (name) {
9974 		case IPV6_UNICAST_HOPS:
9975 			*i1 = tcps->tcps_ipv6_hoplimit;
9976 			break;
9977 		default:
9978 			return (-1);
9979 		}
9980 		break;
9981 	default:
9982 		return (-1);
9983 	}
9984 	return (sizeof (int));
9985 }
9986 
9987 
9988 /*
9989  * TCP routine to get the values of options.
9990  */
9991 int
9992 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9993 {
9994 	int		*i1 = (int *)ptr;
9995 	conn_t		*connp = Q_TO_CONN(q);
9996 	tcp_t		*tcp = connp->conn_tcp;
9997 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9998 
9999 	switch (level) {
10000 	case SOL_SOCKET:
10001 		switch (name) {
10002 		case SO_LINGER:	{
10003 			struct linger *lgr = (struct linger *)ptr;
10004 
10005 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
10006 			lgr->l_linger = tcp->tcp_lingertime;
10007 			}
10008 			return (sizeof (struct linger));
10009 		case SO_DEBUG:
10010 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
10011 			break;
10012 		case SO_KEEPALIVE:
10013 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
10014 			break;
10015 		case SO_DONTROUTE:
10016 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
10017 			break;
10018 		case SO_USELOOPBACK:
10019 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
10020 			break;
10021 		case SO_BROADCAST:
10022 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
10023 			break;
10024 		case SO_REUSEADDR:
10025 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
10026 			break;
10027 		case SO_OOBINLINE:
10028 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
10029 			break;
10030 		case SO_DGRAM_ERRIND:
10031 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
10032 			break;
10033 		case SO_TYPE:
10034 			*i1 = SOCK_STREAM;
10035 			break;
10036 		case SO_SNDBUF:
10037 			*i1 = tcp->tcp_xmit_hiwater;
10038 			break;
10039 		case SO_RCVBUF:
10040 			*i1 = RD(q)->q_hiwat;
10041 			break;
10042 		case SO_SND_COPYAVOID:
10043 			*i1 = tcp->tcp_snd_zcopy_on ?
10044 			    SO_SND_COPYAVOID : 0;
10045 			break;
10046 		case SO_ALLZONES:
10047 			*i1 = connp->conn_allzones ? 1 : 0;
10048 			break;
10049 		case SO_ANON_MLP:
10050 			*i1 = connp->conn_anon_mlp;
10051 			break;
10052 		case SO_MAC_EXEMPT:
10053 			*i1 = connp->conn_mac_exempt;
10054 			break;
10055 		case SO_EXCLBIND:
10056 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
10057 			break;
10058 		case SO_PROTOTYPE:
10059 			*i1 = IPPROTO_TCP;
10060 			break;
10061 		case SO_DOMAIN:
10062 			*i1 = tcp->tcp_family;
10063 			break;
10064 		default:
10065 			return (-1);
10066 		}
10067 		break;
10068 	case IPPROTO_TCP:
10069 		switch (name) {
10070 		case TCP_NODELAY:
10071 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
10072 			break;
10073 		case TCP_MAXSEG:
10074 			*i1 = tcp->tcp_mss;
10075 			break;
10076 		case TCP_NOTIFY_THRESHOLD:
10077 			*i1 = (int)tcp->tcp_first_timer_threshold;
10078 			break;
10079 		case TCP_ABORT_THRESHOLD:
10080 			*i1 = tcp->tcp_second_timer_threshold;
10081 			break;
10082 		case TCP_CONN_NOTIFY_THRESHOLD:
10083 			*i1 = tcp->tcp_first_ctimer_threshold;
10084 			break;
10085 		case TCP_CONN_ABORT_THRESHOLD:
10086 			*i1 = tcp->tcp_second_ctimer_threshold;
10087 			break;
10088 		case TCP_RECVDSTADDR:
10089 			*i1 = tcp->tcp_recvdstaddr;
10090 			break;
10091 		case TCP_ANONPRIVBIND:
10092 			*i1 = tcp->tcp_anon_priv_bind;
10093 			break;
10094 		case TCP_EXCLBIND:
10095 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
10096 			break;
10097 		case TCP_INIT_CWND:
10098 			*i1 = tcp->tcp_init_cwnd;
10099 			break;
10100 		case TCP_KEEPALIVE_THRESHOLD:
10101 			*i1 = tcp->tcp_ka_interval;
10102 			break;
10103 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10104 			*i1 = tcp->tcp_ka_abort_thres;
10105 			break;
10106 		case TCP_CORK:
10107 			*i1 = tcp->tcp_cork;
10108 			break;
10109 		default:
10110 			return (-1);
10111 		}
10112 		break;
10113 	case IPPROTO_IP:
10114 		if (tcp->tcp_family != AF_INET)
10115 			return (-1);
10116 		switch (name) {
10117 		case IP_OPTIONS:
10118 		case T_IP_OPTIONS: {
10119 			/*
10120 			 * This is compatible with BSD in that in only return
10121 			 * the reverse source route with the final destination
10122 			 * as the last entry. The first 4 bytes of the option
10123 			 * will contain the final destination.
10124 			 */
10125 			int	opt_len;
10126 
10127 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
10128 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
10129 			ASSERT(opt_len >= 0);
10130 			/* Caller ensures enough space */
10131 			if (opt_len > 0) {
10132 				/*
10133 				 * TODO: Do we have to handle getsockopt on an
10134 				 * initiator as well?
10135 				 */
10136 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
10137 			}
10138 			return (0);
10139 			}
10140 		case IP_TOS:
10141 		case T_IP_TOS:
10142 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
10143 			break;
10144 		case IP_TTL:
10145 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
10146 			break;
10147 		case IP_NEXTHOP:
10148 			/* Handled at IP level */
10149 			return (-EINVAL);
10150 		default:
10151 			return (-1);
10152 		}
10153 		break;
10154 	case IPPROTO_IPV6:
10155 		/*
10156 		 * IPPROTO_IPV6 options are only supported for sockets
10157 		 * that are using IPv6 on the wire.
10158 		 */
10159 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10160 			return (-1);
10161 		}
10162 		switch (name) {
10163 		case IPV6_UNICAST_HOPS:
10164 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
10165 			break;	/* goto sizeof (int) option return */
10166 		case IPV6_BOUND_IF:
10167 			/* Zero if not set */
10168 			*i1 = tcp->tcp_bound_if;
10169 			break;	/* goto sizeof (int) option return */
10170 		case IPV6_RECVPKTINFO:
10171 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
10172 				*i1 = 1;
10173 			else
10174 				*i1 = 0;
10175 			break;	/* goto sizeof (int) option return */
10176 		case IPV6_RECVTCLASS:
10177 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
10178 				*i1 = 1;
10179 			else
10180 				*i1 = 0;
10181 			break;	/* goto sizeof (int) option return */
10182 		case IPV6_RECVHOPLIMIT:
10183 			if (tcp->tcp_ipv6_recvancillary &
10184 			    TCP_IPV6_RECVHOPLIMIT)
10185 				*i1 = 1;
10186 			else
10187 				*i1 = 0;
10188 			break;	/* goto sizeof (int) option return */
10189 		case IPV6_RECVHOPOPTS:
10190 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
10191 				*i1 = 1;
10192 			else
10193 				*i1 = 0;
10194 			break;	/* goto sizeof (int) option return */
10195 		case IPV6_RECVDSTOPTS:
10196 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
10197 				*i1 = 1;
10198 			else
10199 				*i1 = 0;
10200 			break;	/* goto sizeof (int) option return */
10201 		case _OLD_IPV6_RECVDSTOPTS:
10202 			if (tcp->tcp_ipv6_recvancillary &
10203 			    TCP_OLD_IPV6_RECVDSTOPTS)
10204 				*i1 = 1;
10205 			else
10206 				*i1 = 0;
10207 			break;	/* goto sizeof (int) option return */
10208 		case IPV6_RECVRTHDR:
10209 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
10210 				*i1 = 1;
10211 			else
10212 				*i1 = 0;
10213 			break;	/* goto sizeof (int) option return */
10214 		case IPV6_RECVRTHDRDSTOPTS:
10215 			if (tcp->tcp_ipv6_recvancillary &
10216 			    TCP_IPV6_RECVRTDSTOPTS)
10217 				*i1 = 1;
10218 			else
10219 				*i1 = 0;
10220 			break;	/* goto sizeof (int) option return */
10221 		case IPV6_PKTINFO: {
10222 			/* XXX assumes that caller has room for max size! */
10223 			struct in6_pktinfo *pkti;
10224 
10225 			pkti = (struct in6_pktinfo *)ptr;
10226 			if (ipp->ipp_fields & IPPF_IFINDEX)
10227 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
10228 			else
10229 				pkti->ipi6_ifindex = 0;
10230 			if (ipp->ipp_fields & IPPF_ADDR)
10231 				pkti->ipi6_addr = ipp->ipp_addr;
10232 			else
10233 				pkti->ipi6_addr = ipv6_all_zeros;
10234 			return (sizeof (struct in6_pktinfo));
10235 		}
10236 		case IPV6_TCLASS:
10237 			if (ipp->ipp_fields & IPPF_TCLASS)
10238 				*i1 = ipp->ipp_tclass;
10239 			else
10240 				*i1 = IPV6_FLOW_TCLASS(
10241 				    IPV6_DEFAULT_VERS_AND_FLOW);
10242 			break;	/* goto sizeof (int) option return */
10243 		case IPV6_NEXTHOP: {
10244 			sin6_t *sin6 = (sin6_t *)ptr;
10245 
10246 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
10247 				return (0);
10248 			*sin6 = sin6_null;
10249 			sin6->sin6_family = AF_INET6;
10250 			sin6->sin6_addr = ipp->ipp_nexthop;
10251 			return (sizeof (sin6_t));
10252 		}
10253 		case IPV6_HOPOPTS:
10254 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
10255 				return (0);
10256 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
10257 				return (0);
10258 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
10259 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
10260 			if (tcp->tcp_label_len > 0) {
10261 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
10262 				ptr[1] = (ipp->ipp_hopoptslen -
10263 				    tcp->tcp_label_len + 7) / 8 - 1;
10264 			}
10265 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
10266 		case IPV6_RTHDRDSTOPTS:
10267 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
10268 				return (0);
10269 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
10270 			return (ipp->ipp_rtdstoptslen);
10271 		case IPV6_RTHDR:
10272 			if (!(ipp->ipp_fields & IPPF_RTHDR))
10273 				return (0);
10274 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
10275 			return (ipp->ipp_rthdrlen);
10276 		case IPV6_DSTOPTS:
10277 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
10278 				return (0);
10279 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
10280 			return (ipp->ipp_dstoptslen);
10281 		case IPV6_SRC_PREFERENCES:
10282 			return (ip6_get_src_preferences(connp,
10283 			    (uint32_t *)ptr));
10284 		case IPV6_PATHMTU: {
10285 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
10286 
10287 			if (tcp->tcp_state < TCPS_ESTABLISHED)
10288 				return (-1);
10289 
10290 			return (ip_fill_mtuinfo(&connp->conn_remv6,
10291 			    connp->conn_fport, mtuinfo,
10292 			    connp->conn_netstack));
10293 		}
10294 		default:
10295 			return (-1);
10296 		}
10297 		break;
10298 	default:
10299 		return (-1);
10300 	}
10301 	return (sizeof (int));
10302 }
10303 
10304 /*
10305  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
10306  * Parameters are assumed to be verified by the caller.
10307  */
10308 /* ARGSUSED */
10309 int
10310 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10311     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10312     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10313 {
10314 	conn_t	*connp = Q_TO_CONN(q);
10315 	tcp_t	*tcp = connp->conn_tcp;
10316 	int	*i1 = (int *)invalp;
10317 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
10318 	boolean_t checkonly;
10319 	int	reterr;
10320 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
10321 
10322 	switch (optset_context) {
10323 	case SETFN_OPTCOM_CHECKONLY:
10324 		checkonly = B_TRUE;
10325 		/*
10326 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10327 		 * inlen != 0 implies value supplied and
10328 		 * 	we have to "pretend" to set it.
10329 		 * inlen == 0 implies that there is no
10330 		 * 	value part in T_CHECK request and just validation
10331 		 * done elsewhere should be enough, we just return here.
10332 		 */
10333 		if (inlen == 0) {
10334 			*outlenp = 0;
10335 			return (0);
10336 		}
10337 		break;
10338 	case SETFN_OPTCOM_NEGOTIATE:
10339 		checkonly = B_FALSE;
10340 		break;
10341 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
10342 	case SETFN_CONN_NEGOTIATE:
10343 		checkonly = B_FALSE;
10344 		/*
10345 		 * Negotiating local and "association-related" options
10346 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
10347 		 * primitives is allowed by XTI, but we choose
10348 		 * to not implement this style negotiation for Internet
10349 		 * protocols (We interpret it is a must for OSI world but
10350 		 * optional for Internet protocols) for all options.
10351 		 * [ Will do only for the few options that enable test
10352 		 * suites that our XTI implementation of this feature
10353 		 * works for transports that do allow it ]
10354 		 */
10355 		if (!tcp_allow_connopt_set(level, name)) {
10356 			*outlenp = 0;
10357 			return (EINVAL);
10358 		}
10359 		break;
10360 	default:
10361 		/*
10362 		 * We should never get here
10363 		 */
10364 		*outlenp = 0;
10365 		return (EINVAL);
10366 	}
10367 
10368 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10369 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10370 
10371 	/*
10372 	 * For TCP, we should have no ancillary data sent down
10373 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
10374 	 * has to be zero.
10375 	 */
10376 	ASSERT(thisdg_attrs == NULL);
10377 
10378 	/*
10379 	 * For fixed length options, no sanity check
10380 	 * of passed in length is done. It is assumed *_optcom_req()
10381 	 * routines do the right thing.
10382 	 */
10383 
10384 	switch (level) {
10385 	case SOL_SOCKET:
10386 		switch (name) {
10387 		case SO_LINGER: {
10388 			struct linger *lgr = (struct linger *)invalp;
10389 
10390 			if (!checkonly) {
10391 				if (lgr->l_onoff) {
10392 					tcp->tcp_linger = 1;
10393 					tcp->tcp_lingertime = lgr->l_linger;
10394 				} else {
10395 					tcp->tcp_linger = 0;
10396 					tcp->tcp_lingertime = 0;
10397 				}
10398 				/* struct copy */
10399 				*(struct linger *)outvalp = *lgr;
10400 			} else {
10401 				if (!lgr->l_onoff) {
10402 					((struct linger *)
10403 					    outvalp)->l_onoff = 0;
10404 					((struct linger *)
10405 					    outvalp)->l_linger = 0;
10406 				} else {
10407 					/* struct copy */
10408 					*(struct linger *)outvalp = *lgr;
10409 				}
10410 			}
10411 			*outlenp = sizeof (struct linger);
10412 			return (0);
10413 		}
10414 		case SO_DEBUG:
10415 			if (!checkonly)
10416 				tcp->tcp_debug = onoff;
10417 			break;
10418 		case SO_KEEPALIVE:
10419 			if (checkonly) {
10420 				/* T_CHECK case */
10421 				break;
10422 			}
10423 
10424 			if (!onoff) {
10425 				if (tcp->tcp_ka_enabled) {
10426 					if (tcp->tcp_ka_tid != 0) {
10427 						(void) TCP_TIMER_CANCEL(tcp,
10428 						    tcp->tcp_ka_tid);
10429 						tcp->tcp_ka_tid = 0;
10430 					}
10431 					tcp->tcp_ka_enabled = 0;
10432 				}
10433 				break;
10434 			}
10435 			if (!tcp->tcp_ka_enabled) {
10436 				/* Crank up the keepalive timer */
10437 				tcp->tcp_ka_last_intrvl = 0;
10438 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10439 				    tcp_keepalive_killer,
10440 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10441 				tcp->tcp_ka_enabled = 1;
10442 			}
10443 			break;
10444 		case SO_DONTROUTE:
10445 			/*
10446 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10447 			 * only of interest to IP.  We track them here only so
10448 			 * that we can report their current value.
10449 			 */
10450 			if (!checkonly) {
10451 				tcp->tcp_dontroute = onoff;
10452 				tcp->tcp_connp->conn_dontroute = onoff;
10453 			}
10454 			break;
10455 		case SO_USELOOPBACK:
10456 			if (!checkonly) {
10457 				tcp->tcp_useloopback = onoff;
10458 				tcp->tcp_connp->conn_loopback = onoff;
10459 			}
10460 			break;
10461 		case SO_BROADCAST:
10462 			if (!checkonly) {
10463 				tcp->tcp_broadcast = onoff;
10464 				tcp->tcp_connp->conn_broadcast = onoff;
10465 			}
10466 			break;
10467 		case SO_REUSEADDR:
10468 			if (!checkonly) {
10469 				tcp->tcp_reuseaddr = onoff;
10470 				tcp->tcp_connp->conn_reuseaddr = onoff;
10471 			}
10472 			break;
10473 		case SO_OOBINLINE:
10474 			if (!checkonly)
10475 				tcp->tcp_oobinline = onoff;
10476 			break;
10477 		case SO_DGRAM_ERRIND:
10478 			if (!checkonly)
10479 				tcp->tcp_dgram_errind = onoff;
10480 			break;
10481 		case SO_SNDBUF: {
10482 			if (*i1 > tcps->tcps_max_buf) {
10483 				*outlenp = 0;
10484 				return (ENOBUFS);
10485 			}
10486 			if (checkonly)
10487 				break;
10488 
10489 			tcp->tcp_xmit_hiwater = *i1;
10490 			if (tcps->tcps_snd_lowat_fraction != 0)
10491 				tcp->tcp_xmit_lowater =
10492 				    tcp->tcp_xmit_hiwater /
10493 				    tcps->tcps_snd_lowat_fraction;
10494 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10495 			/*
10496 			 * If we are flow-controlled, recheck the condition.
10497 			 * There are apps that increase SO_SNDBUF size when
10498 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10499 			 * control condition to be lifted right away.
10500 			 */
10501 			mutex_enter(&tcp->tcp_non_sq_lock);
10502 			if (tcp->tcp_flow_stopped &&
10503 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10504 				tcp_clrqfull(tcp);
10505 			}
10506 			mutex_exit(&tcp->tcp_non_sq_lock);
10507 			break;
10508 		}
10509 		case SO_RCVBUF:
10510 			if (*i1 > tcps->tcps_max_buf) {
10511 				*outlenp = 0;
10512 				return (ENOBUFS);
10513 			}
10514 			/* Silently ignore zero */
10515 			if (!checkonly && *i1 != 0) {
10516 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10517 				(void) tcp_rwnd_set(tcp, *i1);
10518 			}
10519 			/*
10520 			 * XXX should we return the rwnd here
10521 			 * and tcp_opt_get ?
10522 			 */
10523 			break;
10524 		case SO_SND_COPYAVOID:
10525 			if (!checkonly) {
10526 				/* we only allow enable at most once for now */
10527 				if (tcp->tcp_loopback ||
10528 				    (tcp->tcp_kssl_ctx != NULL) ||
10529 				    (!tcp->tcp_snd_zcopy_aware &&
10530 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10531 					*outlenp = 0;
10532 					return (EOPNOTSUPP);
10533 				}
10534 				tcp->tcp_snd_zcopy_aware = 1;
10535 			}
10536 			break;
10537 		case SO_ALLZONES:
10538 			/* Pass option along to IP level for handling */
10539 			return (-EINVAL);
10540 		case SO_ANON_MLP:
10541 			/* Pass option along to IP level for handling */
10542 			return (-EINVAL);
10543 		case SO_MAC_EXEMPT:
10544 			/* Pass option along to IP level for handling */
10545 			return (-EINVAL);
10546 		case SO_EXCLBIND:
10547 			if (!checkonly)
10548 				tcp->tcp_exclbind = onoff;
10549 			break;
10550 		default:
10551 			*outlenp = 0;
10552 			return (EINVAL);
10553 		}
10554 		break;
10555 	case IPPROTO_TCP:
10556 		switch (name) {
10557 		case TCP_NODELAY:
10558 			if (!checkonly)
10559 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10560 			break;
10561 		case TCP_NOTIFY_THRESHOLD:
10562 			if (!checkonly)
10563 				tcp->tcp_first_timer_threshold = *i1;
10564 			break;
10565 		case TCP_ABORT_THRESHOLD:
10566 			if (!checkonly)
10567 				tcp->tcp_second_timer_threshold = *i1;
10568 			break;
10569 		case TCP_CONN_NOTIFY_THRESHOLD:
10570 			if (!checkonly)
10571 				tcp->tcp_first_ctimer_threshold = *i1;
10572 			break;
10573 		case TCP_CONN_ABORT_THRESHOLD:
10574 			if (!checkonly)
10575 				tcp->tcp_second_ctimer_threshold = *i1;
10576 			break;
10577 		case TCP_RECVDSTADDR:
10578 			if (tcp->tcp_state > TCPS_LISTEN)
10579 				return (EOPNOTSUPP);
10580 			if (!checkonly)
10581 				tcp->tcp_recvdstaddr = onoff;
10582 			break;
10583 		case TCP_ANONPRIVBIND:
10584 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10585 			    IPPROTO_TCP)) != 0) {
10586 				*outlenp = 0;
10587 				return (reterr);
10588 			}
10589 			if (!checkonly) {
10590 				tcp->tcp_anon_priv_bind = onoff;
10591 			}
10592 			break;
10593 		case TCP_EXCLBIND:
10594 			if (!checkonly)
10595 				tcp->tcp_exclbind = onoff;
10596 			break;	/* goto sizeof (int) option return */
10597 		case TCP_INIT_CWND: {
10598 			uint32_t init_cwnd = *((uint32_t *)invalp);
10599 
10600 			if (checkonly)
10601 				break;
10602 
10603 			/*
10604 			 * Only allow socket with network configuration
10605 			 * privilege to set the initial cwnd to be larger
10606 			 * than allowed by RFC 3390.
10607 			 */
10608 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10609 				tcp->tcp_init_cwnd = init_cwnd;
10610 				break;
10611 			}
10612 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10613 				*outlenp = 0;
10614 				return (reterr);
10615 			}
10616 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10617 				*outlenp = 0;
10618 				return (EINVAL);
10619 			}
10620 			tcp->tcp_init_cwnd = init_cwnd;
10621 			break;
10622 		}
10623 		case TCP_KEEPALIVE_THRESHOLD:
10624 			if (checkonly)
10625 				break;
10626 
10627 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10628 			    *i1 > tcps->tcps_keepalive_interval_high) {
10629 				*outlenp = 0;
10630 				return (EINVAL);
10631 			}
10632 			if (*i1 != tcp->tcp_ka_interval) {
10633 				tcp->tcp_ka_interval = *i1;
10634 				/*
10635 				 * Check if we need to restart the
10636 				 * keepalive timer.
10637 				 */
10638 				if (tcp->tcp_ka_tid != 0) {
10639 					ASSERT(tcp->tcp_ka_enabled);
10640 					(void) TCP_TIMER_CANCEL(tcp,
10641 					    tcp->tcp_ka_tid);
10642 					tcp->tcp_ka_last_intrvl = 0;
10643 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10644 					    tcp_keepalive_killer,
10645 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10646 				}
10647 			}
10648 			break;
10649 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10650 			if (!checkonly) {
10651 				if (*i1 <
10652 				    tcps->tcps_keepalive_abort_interval_low ||
10653 				    *i1 >
10654 				    tcps->tcps_keepalive_abort_interval_high) {
10655 					*outlenp = 0;
10656 					return (EINVAL);
10657 				}
10658 				tcp->tcp_ka_abort_thres = *i1;
10659 			}
10660 			break;
10661 		case TCP_CORK:
10662 			if (!checkonly) {
10663 				/*
10664 				 * if tcp->tcp_cork was set and is now
10665 				 * being unset, we have to make sure that
10666 				 * the remaining data gets sent out. Also
10667 				 * unset tcp->tcp_cork so that tcp_wput_data()
10668 				 * can send data even if it is less than mss
10669 				 */
10670 				if (tcp->tcp_cork && onoff == 0 &&
10671 				    tcp->tcp_unsent > 0) {
10672 					tcp->tcp_cork = B_FALSE;
10673 					tcp_wput_data(tcp, NULL, B_FALSE);
10674 				}
10675 				tcp->tcp_cork = onoff;
10676 			}
10677 			break;
10678 		default:
10679 			*outlenp = 0;
10680 			return (EINVAL);
10681 		}
10682 		break;
10683 	case IPPROTO_IP:
10684 		if (tcp->tcp_family != AF_INET) {
10685 			*outlenp = 0;
10686 			return (ENOPROTOOPT);
10687 		}
10688 		switch (name) {
10689 		case IP_OPTIONS:
10690 		case T_IP_OPTIONS:
10691 			reterr = tcp_opt_set_header(tcp, checkonly,
10692 			    invalp, inlen);
10693 			if (reterr) {
10694 				*outlenp = 0;
10695 				return (reterr);
10696 			}
10697 			/* OK return - copy input buffer into output buffer */
10698 			if (invalp != outvalp) {
10699 				/* don't trust bcopy for identical src/dst */
10700 				bcopy(invalp, outvalp, inlen);
10701 			}
10702 			*outlenp = inlen;
10703 			return (0);
10704 		case IP_TOS:
10705 		case T_IP_TOS:
10706 			if (!checkonly) {
10707 				tcp->tcp_ipha->ipha_type_of_service =
10708 				    (uchar_t)*i1;
10709 				tcp->tcp_tos = (uchar_t)*i1;
10710 			}
10711 			break;
10712 		case IP_TTL:
10713 			if (!checkonly) {
10714 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10715 				tcp->tcp_ttl = (uchar_t)*i1;
10716 			}
10717 			break;
10718 		case IP_BOUND_IF:
10719 		case IP_NEXTHOP:
10720 			/* Handled at the IP level */
10721 			return (-EINVAL);
10722 		case IP_SEC_OPT:
10723 			/*
10724 			 * We should not allow policy setting after
10725 			 * we start listening for connections.
10726 			 */
10727 			if (tcp->tcp_state == TCPS_LISTEN) {
10728 				return (EINVAL);
10729 			} else {
10730 				/* Handled at the IP level */
10731 				return (-EINVAL);
10732 			}
10733 		default:
10734 			*outlenp = 0;
10735 			return (EINVAL);
10736 		}
10737 		break;
10738 	case IPPROTO_IPV6: {
10739 		ip6_pkt_t		*ipp;
10740 
10741 		/*
10742 		 * IPPROTO_IPV6 options are only supported for sockets
10743 		 * that are using IPv6 on the wire.
10744 		 */
10745 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10746 			*outlenp = 0;
10747 			return (ENOPROTOOPT);
10748 		}
10749 		/*
10750 		 * Only sticky options; no ancillary data
10751 		 */
10752 		ASSERT(thisdg_attrs == NULL);
10753 		ipp = &tcp->tcp_sticky_ipp;
10754 
10755 		switch (name) {
10756 		case IPV6_UNICAST_HOPS:
10757 			/* -1 means use default */
10758 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10759 				*outlenp = 0;
10760 				return (EINVAL);
10761 			}
10762 			if (!checkonly) {
10763 				if (*i1 == -1) {
10764 					tcp->tcp_ip6h->ip6_hops =
10765 					    ipp->ipp_unicast_hops =
10766 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10767 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10768 					/* Pass modified value to IP. */
10769 					*i1 = tcp->tcp_ip6h->ip6_hops;
10770 				} else {
10771 					tcp->tcp_ip6h->ip6_hops =
10772 					    ipp->ipp_unicast_hops =
10773 					    (uint8_t)*i1;
10774 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10775 				}
10776 				reterr = tcp_build_hdrs(q, tcp);
10777 				if (reterr != 0)
10778 					return (reterr);
10779 			}
10780 			break;
10781 		case IPV6_BOUND_IF:
10782 			if (!checkonly) {
10783 				int error = 0;
10784 
10785 				tcp->tcp_bound_if = *i1;
10786 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10787 				    B_TRUE, checkonly, level, name, mblk);
10788 				if (error != 0) {
10789 					*outlenp = 0;
10790 					return (error);
10791 				}
10792 			}
10793 			break;
10794 		/*
10795 		 * Set boolean switches for ancillary data delivery
10796 		 */
10797 		case IPV6_RECVPKTINFO:
10798 			if (!checkonly) {
10799 				if (onoff)
10800 					tcp->tcp_ipv6_recvancillary |=
10801 					    TCP_IPV6_RECVPKTINFO;
10802 				else
10803 					tcp->tcp_ipv6_recvancillary &=
10804 					    ~TCP_IPV6_RECVPKTINFO;
10805 				/* Force it to be sent up with the next msg */
10806 				tcp->tcp_recvifindex = 0;
10807 			}
10808 			break;
10809 		case IPV6_RECVTCLASS:
10810 			if (!checkonly) {
10811 				if (onoff)
10812 					tcp->tcp_ipv6_recvancillary |=
10813 					    TCP_IPV6_RECVTCLASS;
10814 				else
10815 					tcp->tcp_ipv6_recvancillary &=
10816 					    ~TCP_IPV6_RECVTCLASS;
10817 			}
10818 			break;
10819 		case IPV6_RECVHOPLIMIT:
10820 			if (!checkonly) {
10821 				if (onoff)
10822 					tcp->tcp_ipv6_recvancillary |=
10823 					    TCP_IPV6_RECVHOPLIMIT;
10824 				else
10825 					tcp->tcp_ipv6_recvancillary &=
10826 					    ~TCP_IPV6_RECVHOPLIMIT;
10827 				/* Force it to be sent up with the next msg */
10828 				tcp->tcp_recvhops = 0xffffffffU;
10829 			}
10830 			break;
10831 		case IPV6_RECVHOPOPTS:
10832 			if (!checkonly) {
10833 				if (onoff)
10834 					tcp->tcp_ipv6_recvancillary |=
10835 					    TCP_IPV6_RECVHOPOPTS;
10836 				else
10837 					tcp->tcp_ipv6_recvancillary &=
10838 					    ~TCP_IPV6_RECVHOPOPTS;
10839 			}
10840 			break;
10841 		case IPV6_RECVDSTOPTS:
10842 			if (!checkonly) {
10843 				if (onoff)
10844 					tcp->tcp_ipv6_recvancillary |=
10845 					    TCP_IPV6_RECVDSTOPTS;
10846 				else
10847 					tcp->tcp_ipv6_recvancillary &=
10848 					    ~TCP_IPV6_RECVDSTOPTS;
10849 			}
10850 			break;
10851 		case _OLD_IPV6_RECVDSTOPTS:
10852 			if (!checkonly) {
10853 				if (onoff)
10854 					tcp->tcp_ipv6_recvancillary |=
10855 					    TCP_OLD_IPV6_RECVDSTOPTS;
10856 				else
10857 					tcp->tcp_ipv6_recvancillary &=
10858 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10859 			}
10860 			break;
10861 		case IPV6_RECVRTHDR:
10862 			if (!checkonly) {
10863 				if (onoff)
10864 					tcp->tcp_ipv6_recvancillary |=
10865 					    TCP_IPV6_RECVRTHDR;
10866 				else
10867 					tcp->tcp_ipv6_recvancillary &=
10868 					    ~TCP_IPV6_RECVRTHDR;
10869 			}
10870 			break;
10871 		case IPV6_RECVRTHDRDSTOPTS:
10872 			if (!checkonly) {
10873 				if (onoff)
10874 					tcp->tcp_ipv6_recvancillary |=
10875 					    TCP_IPV6_RECVRTDSTOPTS;
10876 				else
10877 					tcp->tcp_ipv6_recvancillary &=
10878 					    ~TCP_IPV6_RECVRTDSTOPTS;
10879 			}
10880 			break;
10881 		case IPV6_PKTINFO:
10882 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10883 				return (EINVAL);
10884 			if (checkonly)
10885 				break;
10886 
10887 			if (inlen == 0) {
10888 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10889 			} else {
10890 				struct in6_pktinfo *pkti;
10891 
10892 				pkti = (struct in6_pktinfo *)invalp;
10893 				/*
10894 				 * RFC 3542 states that ipi6_addr must be
10895 				 * the unspecified address when setting the
10896 				 * IPV6_PKTINFO sticky socket option on a
10897 				 * TCP socket.
10898 				 */
10899 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10900 					return (EINVAL);
10901 				/*
10902 				 * ip6_set_pktinfo() validates the source
10903 				 * address and interface index.
10904 				 */
10905 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10906 				    pkti, mblk);
10907 				if (reterr != 0)
10908 					return (reterr);
10909 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10910 				ipp->ipp_addr = pkti->ipi6_addr;
10911 				if (ipp->ipp_ifindex != 0)
10912 					ipp->ipp_fields |= IPPF_IFINDEX;
10913 				else
10914 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10915 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10916 					ipp->ipp_fields |= IPPF_ADDR;
10917 				else
10918 					ipp->ipp_fields &= ~IPPF_ADDR;
10919 			}
10920 			reterr = tcp_build_hdrs(q, tcp);
10921 			if (reterr != 0)
10922 				return (reterr);
10923 			break;
10924 		case IPV6_TCLASS:
10925 			if (inlen != 0 && inlen != sizeof (int))
10926 				return (EINVAL);
10927 			if (checkonly)
10928 				break;
10929 
10930 			if (inlen == 0) {
10931 				ipp->ipp_fields &= ~IPPF_TCLASS;
10932 			} else {
10933 				if (*i1 > 255 || *i1 < -1)
10934 					return (EINVAL);
10935 				if (*i1 == -1) {
10936 					ipp->ipp_tclass = 0;
10937 					*i1 = 0;
10938 				} else {
10939 					ipp->ipp_tclass = *i1;
10940 				}
10941 				ipp->ipp_fields |= IPPF_TCLASS;
10942 			}
10943 			reterr = tcp_build_hdrs(q, tcp);
10944 			if (reterr != 0)
10945 				return (reterr);
10946 			break;
10947 		case IPV6_NEXTHOP:
10948 			/*
10949 			 * IP will verify that the nexthop is reachable
10950 			 * and fail for sticky options.
10951 			 */
10952 			if (inlen != 0 && inlen != sizeof (sin6_t))
10953 				return (EINVAL);
10954 			if (checkonly)
10955 				break;
10956 
10957 			if (inlen == 0) {
10958 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10959 			} else {
10960 				sin6_t *sin6 = (sin6_t *)invalp;
10961 
10962 				if (sin6->sin6_family != AF_INET6)
10963 					return (EAFNOSUPPORT);
10964 				if (IN6_IS_ADDR_V4MAPPED(
10965 				    &sin6->sin6_addr))
10966 					return (EADDRNOTAVAIL);
10967 				ipp->ipp_nexthop = sin6->sin6_addr;
10968 				if (!IN6_IS_ADDR_UNSPECIFIED(
10969 				    &ipp->ipp_nexthop))
10970 					ipp->ipp_fields |= IPPF_NEXTHOP;
10971 				else
10972 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10973 			}
10974 			reterr = tcp_build_hdrs(q, tcp);
10975 			if (reterr != 0)
10976 				return (reterr);
10977 			break;
10978 		case IPV6_HOPOPTS: {
10979 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10980 
10981 			/*
10982 			 * Sanity checks - minimum size, size a multiple of
10983 			 * eight bytes, and matching size passed in.
10984 			 */
10985 			if (inlen != 0 &&
10986 			    inlen != (8 * (hopts->ip6h_len + 1)))
10987 				return (EINVAL);
10988 
10989 			if (checkonly)
10990 				break;
10991 
10992 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10993 			    (uchar_t **)&ipp->ipp_hopopts,
10994 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10995 			if (reterr != 0)
10996 				return (reterr);
10997 			if (ipp->ipp_hopoptslen == 0)
10998 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10999 			else
11000 				ipp->ipp_fields |= IPPF_HOPOPTS;
11001 			reterr = tcp_build_hdrs(q, tcp);
11002 			if (reterr != 0)
11003 				return (reterr);
11004 			break;
11005 		}
11006 		case IPV6_RTHDRDSTOPTS: {
11007 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
11008 
11009 			/*
11010 			 * Sanity checks - minimum size, size a multiple of
11011 			 * eight bytes, and matching size passed in.
11012 			 */
11013 			if (inlen != 0 &&
11014 			    inlen != (8 * (dopts->ip6d_len + 1)))
11015 				return (EINVAL);
11016 
11017 			if (checkonly)
11018 				break;
11019 
11020 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
11021 			    (uchar_t **)&ipp->ipp_rtdstopts,
11022 			    &ipp->ipp_rtdstoptslen, 0);
11023 			if (reterr != 0)
11024 				return (reterr);
11025 			if (ipp->ipp_rtdstoptslen == 0)
11026 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
11027 			else
11028 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
11029 			reterr = tcp_build_hdrs(q, tcp);
11030 			if (reterr != 0)
11031 				return (reterr);
11032 			break;
11033 		}
11034 		case IPV6_DSTOPTS: {
11035 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
11036 
11037 			/*
11038 			 * Sanity checks - minimum size, size a multiple of
11039 			 * eight bytes, and matching size passed in.
11040 			 */
11041 			if (inlen != 0 &&
11042 			    inlen != (8 * (dopts->ip6d_len + 1)))
11043 				return (EINVAL);
11044 
11045 			if (checkonly)
11046 				break;
11047 
11048 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
11049 			    (uchar_t **)&ipp->ipp_dstopts,
11050 			    &ipp->ipp_dstoptslen, 0);
11051 			if (reterr != 0)
11052 				return (reterr);
11053 			if (ipp->ipp_dstoptslen == 0)
11054 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
11055 			else
11056 				ipp->ipp_fields |= IPPF_DSTOPTS;
11057 			reterr = tcp_build_hdrs(q, tcp);
11058 			if (reterr != 0)
11059 				return (reterr);
11060 			break;
11061 		}
11062 		case IPV6_RTHDR: {
11063 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
11064 
11065 			/*
11066 			 * Sanity checks - minimum size, size a multiple of
11067 			 * eight bytes, and matching size passed in.
11068 			 */
11069 			if (inlen != 0 &&
11070 			    inlen != (8 * (rt->ip6r_len + 1)))
11071 				return (EINVAL);
11072 
11073 			if (checkonly)
11074 				break;
11075 
11076 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
11077 			    (uchar_t **)&ipp->ipp_rthdr,
11078 			    &ipp->ipp_rthdrlen, 0);
11079 			if (reterr != 0)
11080 				return (reterr);
11081 			if (ipp->ipp_rthdrlen == 0)
11082 				ipp->ipp_fields &= ~IPPF_RTHDR;
11083 			else
11084 				ipp->ipp_fields |= IPPF_RTHDR;
11085 			reterr = tcp_build_hdrs(q, tcp);
11086 			if (reterr != 0)
11087 				return (reterr);
11088 			break;
11089 		}
11090 		case IPV6_V6ONLY:
11091 			if (!checkonly)
11092 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
11093 			break;
11094 		case IPV6_USE_MIN_MTU:
11095 			if (inlen != sizeof (int))
11096 				return (EINVAL);
11097 
11098 			if (*i1 < -1 || *i1 > 1)
11099 				return (EINVAL);
11100 
11101 			if (checkonly)
11102 				break;
11103 
11104 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
11105 			ipp->ipp_use_min_mtu = *i1;
11106 			break;
11107 		case IPV6_BOUND_PIF:
11108 			/* Handled at the IP level */
11109 			return (-EINVAL);
11110 		case IPV6_SEC_OPT:
11111 			/*
11112 			 * We should not allow policy setting after
11113 			 * we start listening for connections.
11114 			 */
11115 			if (tcp->tcp_state == TCPS_LISTEN) {
11116 				return (EINVAL);
11117 			} else {
11118 				/* Handled at the IP level */
11119 				return (-EINVAL);
11120 			}
11121 		case IPV6_SRC_PREFERENCES:
11122 			if (inlen != sizeof (uint32_t))
11123 				return (EINVAL);
11124 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
11125 			    *(uint32_t *)invalp);
11126 			if (reterr != 0) {
11127 				*outlenp = 0;
11128 				return (reterr);
11129 			}
11130 			break;
11131 		default:
11132 			*outlenp = 0;
11133 			return (EINVAL);
11134 		}
11135 		break;
11136 	}		/* end IPPROTO_IPV6 */
11137 	default:
11138 		*outlenp = 0;
11139 		return (EINVAL);
11140 	}
11141 	/*
11142 	 * Common case of OK return with outval same as inval
11143 	 */
11144 	if (invalp != outvalp) {
11145 		/* don't trust bcopy for identical src/dst */
11146 		(void) bcopy(invalp, outvalp, inlen);
11147 	}
11148 	*outlenp = inlen;
11149 	return (0);
11150 }
11151 
11152 /*
11153  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
11154  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
11155  * headers, and the maximum size tcp header (to avoid reallocation
11156  * on the fly for additional tcp options).
11157  * Returns failure if can't allocate memory.
11158  */
11159 static int
11160 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
11161 {
11162 	char	*hdrs;
11163 	uint_t	hdrs_len;
11164 	ip6i_t	*ip6i;
11165 	char	buf[TCP_MAX_HDR_LENGTH];
11166 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
11167 	in6_addr_t src, dst;
11168 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11169 
11170 	/*
11171 	 * save the existing tcp header and source/dest IP addresses
11172 	 */
11173 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
11174 	src = tcp->tcp_ip6h->ip6_src;
11175 	dst = tcp->tcp_ip6h->ip6_dst;
11176 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
11177 	ASSERT(hdrs_len != 0);
11178 	if (hdrs_len > tcp->tcp_iphc_len) {
11179 		/* Need to reallocate */
11180 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
11181 		if (hdrs == NULL)
11182 			return (ENOMEM);
11183 		if (tcp->tcp_iphc != NULL) {
11184 			if (tcp->tcp_hdr_grown) {
11185 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
11186 			} else {
11187 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
11188 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
11189 			}
11190 			tcp->tcp_iphc_len = 0;
11191 		}
11192 		ASSERT(tcp->tcp_iphc_len == 0);
11193 		tcp->tcp_iphc = hdrs;
11194 		tcp->tcp_iphc_len = hdrs_len;
11195 		tcp->tcp_hdr_grown = B_TRUE;
11196 	}
11197 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
11198 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
11199 
11200 	/* Set header fields not in ipp */
11201 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
11202 		ip6i = (ip6i_t *)tcp->tcp_iphc;
11203 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
11204 	} else {
11205 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
11206 	}
11207 	/*
11208 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
11209 	 *
11210 	 * tcp->tcp_tcp_hdr_len doesn't change here.
11211 	 */
11212 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
11213 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
11214 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
11215 
11216 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
11217 
11218 	tcp->tcp_ip6h->ip6_src = src;
11219 	tcp->tcp_ip6h->ip6_dst = dst;
11220 
11221 	/*
11222 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
11223 	 * the default value for TCP.
11224 	 */
11225 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
11226 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
11227 
11228 	/*
11229 	 * If we're setting extension headers after a connection
11230 	 * has been established, and if we have a routing header
11231 	 * among the extension headers, call ip_massage_options_v6 to
11232 	 * manipulate the routing header/ip6_dst set the checksum
11233 	 * difference in the tcp header template.
11234 	 * (This happens in tcp_connect_ipv6 if the routing header
11235 	 * is set prior to the connect.)
11236 	 * Set the tcp_sum to zero first in case we've cleared a
11237 	 * routing header or don't have one at all.
11238 	 */
11239 	tcp->tcp_sum = 0;
11240 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
11241 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
11242 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
11243 		    (uint8_t *)tcp->tcp_tcph);
11244 		if (rth != NULL) {
11245 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
11246 			    rth, tcps->tcps_netstack);
11247 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
11248 			    (tcp->tcp_sum >> 16));
11249 		}
11250 	}
11251 
11252 	/* Try to get everything in a single mblk */
11253 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcps->tcps_wroff_xtra);
11254 	return (0);
11255 }
11256 
11257 /*
11258  * Transfer any source route option from ipha to buf/dst in reversed form.
11259  */
11260 static int
11261 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
11262 {
11263 	ipoptp_t	opts;
11264 	uchar_t		*opt;
11265 	uint8_t		optval;
11266 	uint8_t		optlen;
11267 	uint32_t	len = 0;
11268 
11269 	for (optval = ipoptp_first(&opts, ipha);
11270 	    optval != IPOPT_EOL;
11271 	    optval = ipoptp_next(&opts)) {
11272 		opt = opts.ipoptp_cur;
11273 		optlen = opts.ipoptp_len;
11274 		switch (optval) {
11275 			int	off1, off2;
11276 		case IPOPT_SSRR:
11277 		case IPOPT_LSRR:
11278 
11279 			/* Reverse source route */
11280 			/*
11281 			 * First entry should be the next to last one in the
11282 			 * current source route (the last entry is our
11283 			 * address.)
11284 			 * The last entry should be the final destination.
11285 			 */
11286 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
11287 			buf[IPOPT_OLEN] = (uint8_t)optlen;
11288 			off1 = IPOPT_MINOFF_SR - 1;
11289 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
11290 			if (off2 < 0) {
11291 				/* No entries in source route */
11292 				break;
11293 			}
11294 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11295 			/*
11296 			 * Note: use src since ipha has not had its src
11297 			 * and dst reversed (it is in the state it was
11298 			 * received.
11299 			 */
11300 			bcopy(&ipha->ipha_src, buf + off2,
11301 			    IP_ADDR_LEN);
11302 			off2 -= IP_ADDR_LEN;
11303 
11304 			while (off2 > 0) {
11305 				bcopy(opt + off2, buf + off1,
11306 				    IP_ADDR_LEN);
11307 				off1 += IP_ADDR_LEN;
11308 				off2 -= IP_ADDR_LEN;
11309 			}
11310 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11311 			buf += optlen;
11312 			len += optlen;
11313 			break;
11314 		}
11315 	}
11316 done:
11317 	/* Pad the resulting options */
11318 	while (len & 0x3) {
11319 		*buf++ = IPOPT_EOL;
11320 		len++;
11321 	}
11322 	return (len);
11323 }
11324 
11325 
11326 /*
11327  * Extract and revert a source route from ipha (if any)
11328  * and then update the relevant fields in both tcp_t and the standard header.
11329  */
11330 static void
11331 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11332 {
11333 	char	buf[TCP_MAX_HDR_LENGTH];
11334 	uint_t	tcph_len;
11335 	int	len;
11336 
11337 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11338 	len = IPH_HDR_LENGTH(ipha);
11339 	if (len == IP_SIMPLE_HDR_LENGTH)
11340 		/* Nothing to do */
11341 		return;
11342 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11343 	    (len & 0x3))
11344 		return;
11345 
11346 	tcph_len = tcp->tcp_tcp_hdr_len;
11347 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11348 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11349 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11350 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11351 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11352 	len += IP_SIMPLE_HDR_LENGTH;
11353 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11354 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11355 	if ((int)tcp->tcp_sum < 0)
11356 		tcp->tcp_sum--;
11357 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11358 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11359 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11360 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11361 	tcp->tcp_ip_hdr_len = len;
11362 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11363 	    (IP_VERSION << 4) | (len >> 2);
11364 	len += tcph_len;
11365 	tcp->tcp_hdr_len = len;
11366 }
11367 
11368 /*
11369  * Copy the standard header into its new location,
11370  * lay in the new options and then update the relevant
11371  * fields in both tcp_t and the standard header.
11372  */
11373 static int
11374 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11375 {
11376 	uint_t	tcph_len;
11377 	uint8_t	*ip_optp;
11378 	tcph_t	*new_tcph;
11379 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11380 
11381 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11382 		return (EINVAL);
11383 
11384 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11385 		return (EINVAL);
11386 
11387 	if (checkonly) {
11388 		/*
11389 		 * do not really set, just pretend to - T_CHECK
11390 		 */
11391 		return (0);
11392 	}
11393 
11394 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11395 	if (tcp->tcp_label_len > 0) {
11396 		int padlen;
11397 		uint8_t opt;
11398 
11399 		/* convert list termination to no-ops */
11400 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11401 		ip_optp += ip_optp[IPOPT_OLEN];
11402 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11403 		while (--padlen >= 0)
11404 			*ip_optp++ = opt;
11405 	}
11406 	tcph_len = tcp->tcp_tcp_hdr_len;
11407 	new_tcph = (tcph_t *)(ip_optp + len);
11408 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11409 	tcp->tcp_tcph = new_tcph;
11410 	bcopy(ptr, ip_optp, len);
11411 
11412 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11413 
11414 	tcp->tcp_ip_hdr_len = len;
11415 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11416 	    (IP_VERSION << 4) | (len >> 2);
11417 	tcp->tcp_hdr_len = len + tcph_len;
11418 	if (!TCP_IS_DETACHED(tcp)) {
11419 		/* Always allocate room for all options. */
11420 		(void) mi_set_sth_wroff(tcp->tcp_rq,
11421 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11422 	}
11423 	return (0);
11424 }
11425 
11426 /* Get callback routine passed to nd_load by tcp_param_register */
11427 /* ARGSUSED */
11428 static int
11429 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11430 {
11431 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11432 
11433 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11434 	return (0);
11435 }
11436 
11437 /*
11438  * Walk through the param array specified registering each element with the
11439  * named dispatch handler.
11440  */
11441 static boolean_t
11442 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11443 {
11444 	for (; cnt-- > 0; tcppa++) {
11445 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11446 			if (!nd_load(ndp, tcppa->tcp_param_name,
11447 			    tcp_param_get, tcp_param_set,
11448 			    (caddr_t)tcppa)) {
11449 				nd_free(ndp);
11450 				return (B_FALSE);
11451 			}
11452 		}
11453 	}
11454 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11455 	    KM_SLEEP);
11456 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11457 	    sizeof (tcpparam_t));
11458 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11459 	    tcp_param_get, tcp_param_set_aligned,
11460 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11461 		nd_free(ndp);
11462 		return (B_FALSE);
11463 	}
11464 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11465 	    KM_SLEEP);
11466 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11467 	    sizeof (tcpparam_t));
11468 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11469 	    tcp_param_get, tcp_param_set_aligned,
11470 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11471 		nd_free(ndp);
11472 		return (B_FALSE);
11473 	}
11474 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11475 	    KM_SLEEP);
11476 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11477 	    sizeof (tcpparam_t));
11478 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11479 	    tcp_param_get, tcp_param_set_aligned,
11480 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11481 		nd_free(ndp);
11482 		return (B_FALSE);
11483 	}
11484 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11485 	    KM_SLEEP);
11486 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11487 	    sizeof (tcpparam_t));
11488 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11489 	    tcp_param_get, tcp_param_set_aligned,
11490 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11491 		nd_free(ndp);
11492 		return (B_FALSE);
11493 	}
11494 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11495 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11496 		nd_free(ndp);
11497 		return (B_FALSE);
11498 	}
11499 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11500 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11501 		nd_free(ndp);
11502 		return (B_FALSE);
11503 	}
11504 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11505 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11506 		nd_free(ndp);
11507 		return (B_FALSE);
11508 	}
11509 	if (!nd_load(ndp, "tcp_status", tcp_status_report, NULL,
11510 	    NULL)) {
11511 		nd_free(ndp);
11512 		return (B_FALSE);
11513 	}
11514 	if (!nd_load(ndp, "tcp_bind_hash", tcp_bind_hash_report,
11515 	    NULL, NULL)) {
11516 		nd_free(ndp);
11517 		return (B_FALSE);
11518 	}
11519 	if (!nd_load(ndp, "tcp_listen_hash",
11520 	    tcp_listen_hash_report, NULL, NULL)) {
11521 		nd_free(ndp);
11522 		return (B_FALSE);
11523 	}
11524 	if (!nd_load(ndp, "tcp_conn_hash", tcp_conn_hash_report,
11525 	    NULL, NULL)) {
11526 		nd_free(ndp);
11527 		return (B_FALSE);
11528 	}
11529 	if (!nd_load(ndp, "tcp_acceptor_hash",
11530 	    tcp_acceptor_hash_report, NULL, NULL)) {
11531 		nd_free(ndp);
11532 		return (B_FALSE);
11533 	}
11534 	if (!nd_load(ndp, "tcp_host_param", tcp_host_param_report,
11535 	    tcp_host_param_set, NULL)) {
11536 		nd_free(ndp);
11537 		return (B_FALSE);
11538 	}
11539 	if (!nd_load(ndp, "tcp_host_param_ipv6",
11540 	    tcp_host_param_report, tcp_host_param_set_ipv6, NULL)) {
11541 		nd_free(ndp);
11542 		return (B_FALSE);
11543 	}
11544 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11545 	    tcp_1948_phrase_set, NULL)) {
11546 		nd_free(ndp);
11547 		return (B_FALSE);
11548 	}
11549 	if (!nd_load(ndp, "tcp_reserved_port_list",
11550 	    tcp_reserved_port_list, NULL, NULL)) {
11551 		nd_free(ndp);
11552 		return (B_FALSE);
11553 	}
11554 	/*
11555 	 * Dummy ndd variables - only to convey obsolescence information
11556 	 * through printing of their name (no get or set routines)
11557 	 * XXX Remove in future releases ?
11558 	 */
11559 	if (!nd_load(ndp,
11560 	    "tcp_close_wait_interval(obsoleted - "
11561 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11562 		nd_free(ndp);
11563 		return (B_FALSE);
11564 	}
11565 	return (B_TRUE);
11566 }
11567 
11568 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11569 /* ARGSUSED */
11570 static int
11571 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11572     cred_t *cr)
11573 {
11574 	long new_value;
11575 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11576 
11577 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11578 	    new_value < tcppa->tcp_param_min ||
11579 	    new_value > tcppa->tcp_param_max) {
11580 		return (EINVAL);
11581 	}
11582 	/*
11583 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11584 	 * round it up.  For future 64 bit requirement, we actually make it
11585 	 * a multiple of 8.
11586 	 */
11587 	if (new_value & 0x7) {
11588 		new_value = (new_value & ~0x7) + 0x8;
11589 	}
11590 	tcppa->tcp_param_val = new_value;
11591 	return (0);
11592 }
11593 
11594 /* Set callback routine passed to nd_load by tcp_param_register */
11595 /* ARGSUSED */
11596 static int
11597 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11598 {
11599 	long	new_value;
11600 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11601 
11602 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11603 	    new_value < tcppa->tcp_param_min ||
11604 	    new_value > tcppa->tcp_param_max) {
11605 		return (EINVAL);
11606 	}
11607 	tcppa->tcp_param_val = new_value;
11608 	return (0);
11609 }
11610 
11611 /*
11612  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11613  * is filled, return as much as we can.  The message passed in may be
11614  * multi-part, chained using b_cont.  "start" is the starting sequence
11615  * number for this piece.
11616  */
11617 static mblk_t *
11618 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11619 {
11620 	uint32_t	end;
11621 	mblk_t		*mp1;
11622 	mblk_t		*mp2;
11623 	mblk_t		*next_mp;
11624 	uint32_t	u1;
11625 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11626 
11627 	/* Walk through all the new pieces. */
11628 	do {
11629 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11630 		    (uintptr_t)INT_MAX);
11631 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11632 		next_mp = mp->b_cont;
11633 		if (start == end) {
11634 			/* Empty.  Blast it. */
11635 			freeb(mp);
11636 			continue;
11637 		}
11638 		mp->b_cont = NULL;
11639 		TCP_REASS_SET_SEQ(mp, start);
11640 		TCP_REASS_SET_END(mp, end);
11641 		mp1 = tcp->tcp_reass_tail;
11642 		if (!mp1) {
11643 			tcp->tcp_reass_tail = mp;
11644 			tcp->tcp_reass_head = mp;
11645 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11646 			UPDATE_MIB(&tcps->tcps_mib,
11647 			    tcpInDataUnorderBytes, end - start);
11648 			continue;
11649 		}
11650 		/* New stuff completely beyond tail? */
11651 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11652 			/* Link it on end. */
11653 			mp1->b_cont = mp;
11654 			tcp->tcp_reass_tail = mp;
11655 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11656 			UPDATE_MIB(&tcps->tcps_mib,
11657 			    tcpInDataUnorderBytes, end - start);
11658 			continue;
11659 		}
11660 		mp1 = tcp->tcp_reass_head;
11661 		u1 = TCP_REASS_SEQ(mp1);
11662 		/* New stuff at the front? */
11663 		if (SEQ_LT(start, u1)) {
11664 			/* Yes... Check for overlap. */
11665 			mp->b_cont = mp1;
11666 			tcp->tcp_reass_head = mp;
11667 			tcp_reass_elim_overlap(tcp, mp);
11668 			continue;
11669 		}
11670 		/*
11671 		 * The new piece fits somewhere between the head and tail.
11672 		 * We find our slot, where mp1 precedes us and mp2 trails.
11673 		 */
11674 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11675 			u1 = TCP_REASS_SEQ(mp2);
11676 			if (SEQ_LEQ(start, u1))
11677 				break;
11678 		}
11679 		/* Link ourselves in */
11680 		mp->b_cont = mp2;
11681 		mp1->b_cont = mp;
11682 
11683 		/* Trim overlap with following mblk(s) first */
11684 		tcp_reass_elim_overlap(tcp, mp);
11685 
11686 		/* Trim overlap with preceding mblk */
11687 		tcp_reass_elim_overlap(tcp, mp1);
11688 
11689 	} while (start = end, mp = next_mp);
11690 	mp1 = tcp->tcp_reass_head;
11691 	/* Anything ready to go? */
11692 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11693 		return (NULL);
11694 	/* Eat what we can off the queue */
11695 	for (;;) {
11696 		mp = mp1->b_cont;
11697 		end = TCP_REASS_END(mp1);
11698 		TCP_REASS_SET_SEQ(mp1, 0);
11699 		TCP_REASS_SET_END(mp1, 0);
11700 		if (!mp) {
11701 			tcp->tcp_reass_tail = NULL;
11702 			break;
11703 		}
11704 		if (end != TCP_REASS_SEQ(mp)) {
11705 			mp1->b_cont = NULL;
11706 			break;
11707 		}
11708 		mp1 = mp;
11709 	}
11710 	mp1 = tcp->tcp_reass_head;
11711 	tcp->tcp_reass_head = mp;
11712 	return (mp1);
11713 }
11714 
11715 /* Eliminate any overlap that mp may have over later mblks */
11716 static void
11717 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11718 {
11719 	uint32_t	end;
11720 	mblk_t		*mp1;
11721 	uint32_t	u1;
11722 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11723 
11724 	end = TCP_REASS_END(mp);
11725 	while ((mp1 = mp->b_cont) != NULL) {
11726 		u1 = TCP_REASS_SEQ(mp1);
11727 		if (!SEQ_GT(end, u1))
11728 			break;
11729 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11730 			mp->b_wptr -= end - u1;
11731 			TCP_REASS_SET_END(mp, u1);
11732 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11733 			UPDATE_MIB(&tcps->tcps_mib,
11734 			    tcpInDataPartDupBytes, end - u1);
11735 			break;
11736 		}
11737 		mp->b_cont = mp1->b_cont;
11738 		TCP_REASS_SET_SEQ(mp1, 0);
11739 		TCP_REASS_SET_END(mp1, 0);
11740 		freeb(mp1);
11741 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11742 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11743 	}
11744 	if (!mp1)
11745 		tcp->tcp_reass_tail = mp;
11746 }
11747 
11748 /*
11749  * Send up all messages queued on tcp_rcv_list.
11750  */
11751 static uint_t
11752 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11753 {
11754 	mblk_t *mp;
11755 	uint_t ret = 0;
11756 	uint_t thwin;
11757 #ifdef DEBUG
11758 	uint_t cnt = 0;
11759 #endif
11760 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11761 
11762 	/* Can't drain on an eager connection */
11763 	if (tcp->tcp_listener != NULL)
11764 		return (ret);
11765 
11766 	/* Can't be sodirect enabled */
11767 	ASSERT(SOD_NOT_ENABLED(tcp));
11768 
11769 	/* No need for the push timer now. */
11770 	if (tcp->tcp_push_tid != 0) {
11771 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11772 		tcp->tcp_push_tid = 0;
11773 	}
11774 
11775 	/*
11776 	 * Handle two cases here: we are currently fused or we were
11777 	 * previously fused and have some urgent data to be delivered
11778 	 * upstream.  The latter happens because we either ran out of
11779 	 * memory or were detached and therefore sending the SIGURG was
11780 	 * deferred until this point.  In either case we pass control
11781 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11782 	 * some work.
11783 	 */
11784 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11785 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11786 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11787 		    &tcp->tcp_fused_sigurg_mp))
11788 			return (ret);
11789 	}
11790 
11791 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11792 		tcp->tcp_rcv_list = mp->b_next;
11793 		mp->b_next = NULL;
11794 #ifdef DEBUG
11795 		cnt += msgdsize(mp);
11796 #endif
11797 		/* Does this need SSL processing first? */
11798 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11799 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11800 			    mblk_t *, mp);
11801 			tcp_kssl_input(tcp, mp);
11802 			continue;
11803 		}
11804 		putnext(q, mp);
11805 	}
11806 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11807 	tcp->tcp_rcv_last_head = NULL;
11808 	tcp->tcp_rcv_last_tail = NULL;
11809 	tcp->tcp_rcv_cnt = 0;
11810 
11811 	/* Learn the latest rwnd information that we sent to the other side. */
11812 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11813 	    << tcp->tcp_rcv_ws;
11814 	/* This is peer's calculated send window (our receive window). */
11815 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11816 	/*
11817 	 * Increase the receive window to max.  But we need to do receiver
11818 	 * SWS avoidance.  This means that we need to check the increase of
11819 	 * of receive window is at least 1 MSS.
11820 	 */
11821 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11822 		/*
11823 		 * If the window that the other side knows is less than max
11824 		 * deferred acks segments, send an update immediately.
11825 		 */
11826 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11827 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11828 			ret = TH_ACK_NEEDED;
11829 		}
11830 		tcp->tcp_rwnd = q->q_hiwat;
11831 	}
11832 	return (ret);
11833 }
11834 
11835 /*
11836  * Queue data on tcp_rcv_list which is a b_next chain.
11837  * tcp_rcv_last_head/tail is the last element of this chain.
11838  * Each element of the chain is a b_cont chain.
11839  *
11840  * M_DATA messages are added to the current element.
11841  * Other messages are added as new (b_next) elements.
11842  */
11843 void
11844 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11845 {
11846 	ASSERT(seg_len == msgdsize(mp));
11847 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11848 
11849 	if (tcp->tcp_rcv_list == NULL) {
11850 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11851 		tcp->tcp_rcv_list = mp;
11852 		tcp->tcp_rcv_last_head = mp;
11853 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11854 		tcp->tcp_rcv_last_tail->b_cont = mp;
11855 	} else {
11856 		tcp->tcp_rcv_last_head->b_next = mp;
11857 		tcp->tcp_rcv_last_head = mp;
11858 	}
11859 
11860 	while (mp->b_cont)
11861 		mp = mp->b_cont;
11862 
11863 	tcp->tcp_rcv_last_tail = mp;
11864 	tcp->tcp_rcv_cnt += seg_len;
11865 	tcp->tcp_rwnd -= seg_len;
11866 }
11867 
11868 /*
11869  * The tcp_rcv_sod_XXX() functions enqueue data directly to the socket
11870  * above, in addition when uioa is enabled schedule an asynchronous uio
11871  * prior to enqueuing. They implement the combinhed semantics of the
11872  * tcp_rcv_XXX() functions, tcp_rcv_list push logic, and STREAMS putnext()
11873  * canputnext(), i.e. flow-control with backenable.
11874  *
11875  * tcp_sod_wakeup() is called where tcp_rcv_drain() would be called in the
11876  * non sodirect connection but as there are no tcp_tcv_list mblk_t's we deal
11877  * with the rcv_wnd and push timer and call the sodirect wakeup function.
11878  *
11879  * Must be called with sodp->sod_lock held and will return with the lock
11880  * released.
11881  */
11882 static uint_t
11883 tcp_rcv_sod_wakeup(tcp_t *tcp, sodirect_t *sodp)
11884 {
11885 	queue_t		*q = tcp->tcp_rq;
11886 	uint_t		thwin;
11887 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11888 	uint_t		ret = 0;
11889 
11890 	/* Can't be an eager connection */
11891 	ASSERT(tcp->tcp_listener == NULL);
11892 
11893 	/* Caller must have lock held */
11894 	ASSERT(MUTEX_HELD(sodp->sod_lock));
11895 
11896 	/* Sodirect mode so must not be a tcp_rcv_list */
11897 	ASSERT(tcp->tcp_rcv_list == NULL);
11898 
11899 	if (SOD_QFULL(sodp)) {
11900 		/* Q is full, mark Q for need backenable */
11901 		SOD_QSETBE(sodp);
11902 	}
11903 	/* Last advertised rwnd, i.e. rwnd last sent in a packet */
11904 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11905 	    << tcp->tcp_rcv_ws;
11906 	/* This is peer's calculated send window (our available rwnd). */
11907 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11908 	/*
11909 	 * Increase the receive window to max.  But we need to do receiver
11910 	 * SWS avoidance.  This means that we need to check the increase of
11911 	 * of receive window is at least 1 MSS.
11912 	 */
11913 	if (!SOD_QFULL(sodp) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11914 		/*
11915 		 * If the window that the other side knows is less than max
11916 		 * deferred acks segments, send an update immediately.
11917 		 */
11918 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11919 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11920 			ret = TH_ACK_NEEDED;
11921 		}
11922 		tcp->tcp_rwnd = q->q_hiwat;
11923 	}
11924 
11925 	if (!SOD_QEMPTY(sodp)) {
11926 		/* Wakeup to socket */
11927 		sodp->sod_state &= SOD_WAKE_CLR;
11928 		sodp->sod_state |= SOD_WAKE_DONE;
11929 		(sodp->sod_wakeup)(sodp);
11930 		/* wakeup() does the mutex_ext() */
11931 	} else {
11932 		/* Q is empty, no need to wake */
11933 		sodp->sod_state &= SOD_WAKE_CLR;
11934 		sodp->sod_state |= SOD_WAKE_NOT;
11935 		mutex_exit(sodp->sod_lock);
11936 	}
11937 
11938 	/* No need for the push timer now. */
11939 	if (tcp->tcp_push_tid != 0) {
11940 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11941 		tcp->tcp_push_tid = 0;
11942 	}
11943 
11944 	return (ret);
11945 }
11946 
11947 /*
11948  * Called where tcp_rcv_enqueue()/putnext(RD(q)) would be. For M_DATA
11949  * mblk_t's if uioa enabled then start a uioa asynchronous copy directly
11950  * to the user-land buffer and flag the mblk_t as such.
11951  *
11952  * Also, handle tcp_rwnd.
11953  */
11954 uint_t
11955 tcp_rcv_sod_enqueue(tcp_t *tcp, sodirect_t *sodp, mblk_t *mp, uint_t seg_len)
11956 {
11957 	uioa_t		*uioap = &sodp->sod_uioa;
11958 	boolean_t	qfull;
11959 	uint_t		thwin;
11960 
11961 	/* Can't be an eager connection */
11962 	ASSERT(tcp->tcp_listener == NULL);
11963 
11964 	/* Caller must have lock held */
11965 	ASSERT(MUTEX_HELD(sodp->sod_lock));
11966 
11967 	/* Sodirect mode so must not be a tcp_rcv_list */
11968 	ASSERT(tcp->tcp_rcv_list == NULL);
11969 
11970 	/* Passed in segment length must be equal to mblk_t chain data size */
11971 	ASSERT(seg_len == msgdsize(mp));
11972 
11973 	if (DB_TYPE(mp) != M_DATA) {
11974 		/* Only process M_DATA mblk_t's */
11975 		goto enq;
11976 	}
11977 	if (uioap->uioa_state & UIOA_ENABLED) {
11978 		/* Uioa is enabled */
11979 		mblk_t		*mp1 = mp;
11980 
11981 		if (seg_len > uioap->uio_resid) {
11982 			/*
11983 			 * There isn't enough uio space for the mblk_t chain
11984 			 * so disable uioa such that this and any additional
11985 			 * mblk_t data is handled by the socket and schedule
11986 			 * the socket for wakeup to finish this uioa.
11987 			 */
11988 			uioap->uioa_state &= UIOA_CLR;
11989 			uioap->uioa_state |= UIOA_FINI;
11990 			if (sodp->sod_state & SOD_WAKE_NOT) {
11991 				sodp->sod_state &= SOD_WAKE_CLR;
11992 				sodp->sod_state |= SOD_WAKE_NEED;
11993 			}
11994 			goto enq;
11995 		}
11996 		do {
11997 			uint32_t	len = MBLKL(mp1);
11998 
11999 			if (!uioamove(mp1->b_rptr, len, UIO_READ, uioap)) {
12000 				/* Scheduled, mark dblk_t as such */
12001 				DB_FLAGS(mp1) |= DBLK_UIOA;
12002 			} else {
12003 				/* Error, turn off async processing */
12004 				uioap->uioa_state &= UIOA_CLR;
12005 				uioap->uioa_state |= UIOA_FINI;
12006 				break;
12007 			}
12008 		} while ((mp1 = mp1->b_cont) != NULL);
12009 
12010 		if (mp1 != NULL || uioap->uio_resid == 0) {
12011 			/*
12012 			 * Not all mblk_t(s) uioamoved (error) or all uio
12013 			 * space has been consumed so schedule the socket
12014 			 * for wakeup to finish this uio.
12015 			 */
12016 			sodp->sod_state &= SOD_WAKE_CLR;
12017 			sodp->sod_state |= SOD_WAKE_NEED;
12018 		}
12019 	} else if (uioap->uioa_state & UIOA_FINI) {
12020 		/*
12021 		 * Post UIO_ENABLED waiting for socket to finish processing
12022 		 * so just enqueue and update tcp_rwnd.
12023 		 */
12024 		if (SOD_QFULL(sodp))
12025 			tcp->tcp_rwnd -= seg_len;
12026 	} else if (sodp->sod_want > 0) {
12027 		/*
12028 		 * Uioa isn't enabled but sodirect has a pending read().
12029 		 */
12030 		if (SOD_QCNT(sodp) + seg_len >= sodp->sod_want) {
12031 			if (sodp->sod_state & SOD_WAKE_NOT) {
12032 				/* Schedule socket for wakeup */
12033 				sodp->sod_state &= SOD_WAKE_CLR;
12034 				sodp->sod_state |= SOD_WAKE_NEED;
12035 			}
12036 			tcp->tcp_rwnd -= seg_len;
12037 		}
12038 	} else if (SOD_QCNT(sodp) + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
12039 		/*
12040 		 * No pending sodirect read() so used the default
12041 		 * TCP push logic to guess that a push is needed.
12042 		 */
12043 		if (sodp->sod_state & SOD_WAKE_NOT) {
12044 			/* Schedule socket for wakeup */
12045 			sodp->sod_state &= SOD_WAKE_CLR;
12046 			sodp->sod_state |= SOD_WAKE_NEED;
12047 		}
12048 		tcp->tcp_rwnd -= seg_len;
12049 	} else {
12050 		/* Just update tcp_rwnd */
12051 		tcp->tcp_rwnd -= seg_len;
12052 	}
12053 enq:
12054 	qfull = SOD_QFULL(sodp);
12055 
12056 	(sodp->sod_enqueue)(sodp, mp);
12057 
12058 	if (! qfull && SOD_QFULL(sodp)) {
12059 		/* Wasn't QFULL, now QFULL, need back-enable */
12060 		SOD_QSETBE(sodp);
12061 	}
12062 
12063 	/*
12064 	 * Check to see if remote avail swnd < mss due to delayed ACK,
12065 	 * first get advertised rwnd.
12066 	 */
12067 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win));
12068 	/* Minus delayed ACK count */
12069 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
12070 	if (thwin < tcp->tcp_mss) {
12071 		/* Remote avail swnd < mss, need ACK now */
12072 		return (TH_ACK_NEEDED);
12073 	}
12074 
12075 	return (0);
12076 }
12077 
12078 /*
12079  * DEFAULT TCP ENTRY POINT via squeue on READ side.
12080  *
12081  * This is the default entry function into TCP on the read side. TCP is
12082  * always entered via squeue i.e. using squeue's for mutual exclusion.
12083  * When classifier does a lookup to find the tcp, it also puts a reference
12084  * on the conn structure associated so the tcp is guaranteed to exist
12085  * when we come here. We still need to check the state because it might
12086  * as well has been closed. The squeue processing function i.e. squeue_enter,
12087  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
12088  * CONN_DEC_REF.
12089  *
12090  * Apart from the default entry point, IP also sends packets directly to
12091  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
12092  * connections.
12093  */
12094 void
12095 tcp_input(void *arg, mblk_t *mp, void *arg2)
12096 {
12097 	conn_t	*connp = (conn_t *)arg;
12098 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
12099 
12100 	/* arg2 is the sqp */
12101 	ASSERT(arg2 != NULL);
12102 	ASSERT(mp != NULL);
12103 
12104 	/*
12105 	 * Don't accept any input on a closed tcp as this TCP logically does
12106 	 * not exist on the system. Don't proceed further with this TCP.
12107 	 * For eg. this packet could trigger another close of this tcp
12108 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
12109 	 * tcp_clean_death / tcp_closei_local must be called at most once
12110 	 * on a TCP. In this case we need to refeed the packet into the
12111 	 * classifier and figure out where the packet should go. Need to
12112 	 * preserve the recv_ill somehow. Until we figure that out, for
12113 	 * now just drop the packet if we can't classify the packet.
12114 	 */
12115 	if (tcp->tcp_state == TCPS_CLOSED ||
12116 	    tcp->tcp_state == TCPS_BOUND) {
12117 		conn_t	*new_connp;
12118 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
12119 
12120 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
12121 		if (new_connp != NULL) {
12122 			tcp_reinput(new_connp, mp, arg2);
12123 			return;
12124 		}
12125 		/* We failed to classify. For now just drop the packet */
12126 		freemsg(mp);
12127 		return;
12128 	}
12129 
12130 	if (DB_TYPE(mp) == M_DATA)
12131 		tcp_rput_data(connp, mp, arg2);
12132 	else
12133 		tcp_rput_common(tcp, mp);
12134 }
12135 
12136 /*
12137  * The read side put procedure.
12138  * The packets passed up by ip are assume to be aligned according to
12139  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
12140  */
12141 static void
12142 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
12143 {
12144 	/*
12145 	 * tcp_rput_data() does not expect M_CTL except for the case
12146 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
12147 	 * type. Need to make sure that any other M_CTLs don't make
12148 	 * it to tcp_rput_data since it is not expecting any and doesn't
12149 	 * check for it.
12150 	 */
12151 	if (DB_TYPE(mp) == M_CTL) {
12152 		switch (*(uint32_t *)(mp->b_rptr)) {
12153 		case TCP_IOC_ABORT_CONN:
12154 			/*
12155 			 * Handle connection abort request.
12156 			 */
12157 			tcp_ioctl_abort_handler(tcp, mp);
12158 			return;
12159 		case IPSEC_IN:
12160 			/*
12161 			 * Only secure icmp arrive in TCP and they
12162 			 * don't go through data path.
12163 			 */
12164 			tcp_icmp_error(tcp, mp);
12165 			return;
12166 		case IN_PKTINFO:
12167 			/*
12168 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
12169 			 * sockets that are receiving IPv4 traffic. tcp
12170 			 */
12171 			ASSERT(tcp->tcp_family == AF_INET6);
12172 			ASSERT(tcp->tcp_ipv6_recvancillary &
12173 			    TCP_IPV6_RECVPKTINFO);
12174 			tcp_rput_data(tcp->tcp_connp, mp,
12175 			    tcp->tcp_connp->conn_sqp);
12176 			return;
12177 		case MDT_IOC_INFO_UPDATE:
12178 			/*
12179 			 * Handle Multidata information update; the
12180 			 * following routine will free the message.
12181 			 */
12182 			if (tcp->tcp_connp->conn_mdt_ok) {
12183 				tcp_mdt_update(tcp,
12184 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
12185 				    B_FALSE);
12186 			}
12187 			freemsg(mp);
12188 			return;
12189 		case LSO_IOC_INFO_UPDATE:
12190 			/*
12191 			 * Handle LSO information update; the following
12192 			 * routine will free the message.
12193 			 */
12194 			if (tcp->tcp_connp->conn_lso_ok) {
12195 				tcp_lso_update(tcp,
12196 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
12197 			}
12198 			freemsg(mp);
12199 			return;
12200 		default:
12201 			/*
12202 			 * tcp_icmp_err() will process the M_CTL packets.
12203 			 * Non-ICMP packets, if any, will be discarded in
12204 			 * tcp_icmp_err(). We will process the ICMP packet
12205 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
12206 			 * incoming ICMP packet may result in changing
12207 			 * the tcp_mss, which we would need if we have
12208 			 * packets to retransmit.
12209 			 */
12210 			tcp_icmp_error(tcp, mp);
12211 			return;
12212 		}
12213 	}
12214 
12215 	/* No point processing the message if tcp is already closed */
12216 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
12217 		freemsg(mp);
12218 		return;
12219 	}
12220 
12221 	tcp_rput_other(tcp, mp);
12222 }
12223 
12224 
12225 /* The minimum of smoothed mean deviation in RTO calculation. */
12226 #define	TCP_SD_MIN	400
12227 
12228 /*
12229  * Set RTO for this connection.  The formula is from Jacobson and Karels'
12230  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
12231  * are the same as those in Appendix A.2 of that paper.
12232  *
12233  * m = new measurement
12234  * sa = smoothed RTT average (8 * average estimates).
12235  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
12236  */
12237 static void
12238 tcp_set_rto(tcp_t *tcp, clock_t rtt)
12239 {
12240 	long m = TICK_TO_MSEC(rtt);
12241 	clock_t sa = tcp->tcp_rtt_sa;
12242 	clock_t sv = tcp->tcp_rtt_sd;
12243 	clock_t rto;
12244 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12245 
12246 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
12247 	tcp->tcp_rtt_update++;
12248 
12249 	/* tcp_rtt_sa is not 0 means this is a new sample. */
12250 	if (sa != 0) {
12251 		/*
12252 		 * Update average estimator:
12253 		 *	new rtt = 7/8 old rtt + 1/8 Error
12254 		 */
12255 
12256 		/* m is now Error in estimate. */
12257 		m -= sa >> 3;
12258 		if ((sa += m) <= 0) {
12259 			/*
12260 			 * Don't allow the smoothed average to be negative.
12261 			 * We use 0 to denote reinitialization of the
12262 			 * variables.
12263 			 */
12264 			sa = 1;
12265 		}
12266 
12267 		/*
12268 		 * Update deviation estimator:
12269 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
12270 		 */
12271 		if (m < 0)
12272 			m = -m;
12273 		m -= sv >> 2;
12274 		sv += m;
12275 	} else {
12276 		/*
12277 		 * This follows BSD's implementation.  So the reinitialized
12278 		 * RTO is 3 * m.  We cannot go less than 2 because if the
12279 		 * link is bandwidth dominated, doubling the window size
12280 		 * during slow start means doubling the RTT.  We want to be
12281 		 * more conservative when we reinitialize our estimates.  3
12282 		 * is just a convenient number.
12283 		 */
12284 		sa = m << 3;
12285 		sv = m << 1;
12286 	}
12287 	if (sv < TCP_SD_MIN) {
12288 		/*
12289 		 * We do not know that if sa captures the delay ACK
12290 		 * effect as in a long train of segments, a receiver
12291 		 * does not delay its ACKs.  So set the minimum of sv
12292 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
12293 		 * of BSD DATO.  That means the minimum of mean
12294 		 * deviation is 100 ms.
12295 		 *
12296 		 */
12297 		sv = TCP_SD_MIN;
12298 	}
12299 	tcp->tcp_rtt_sa = sa;
12300 	tcp->tcp_rtt_sd = sv;
12301 	/*
12302 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
12303 	 *
12304 	 * Add tcp_rexmit_interval extra in case of extreme environment
12305 	 * where the algorithm fails to work.  The default value of
12306 	 * tcp_rexmit_interval_extra should be 0.
12307 	 *
12308 	 * As we use a finer grained clock than BSD and update
12309 	 * RTO for every ACKs, add in another .25 of RTT to the
12310 	 * deviation of RTO to accomodate burstiness of 1/4 of
12311 	 * window size.
12312 	 */
12313 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
12314 
12315 	if (rto > tcps->tcps_rexmit_interval_max) {
12316 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
12317 	} else if (rto < tcps->tcps_rexmit_interval_min) {
12318 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
12319 	} else {
12320 		tcp->tcp_rto = rto;
12321 	}
12322 
12323 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12324 	tcp->tcp_timer_backoff = 0;
12325 }
12326 
12327 /*
12328  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12329  * send queue which starts at the given seq. no.
12330  *
12331  * Parameters:
12332  *	tcp_t *tcp: the tcp instance pointer.
12333  *	uint32_t seq: the starting seq. no of the requested segment.
12334  *	int32_t *off: after the execution, *off will be the offset to
12335  *		the returned mblk which points to the requested seq no.
12336  *		It is the caller's responsibility to send in a non-null off.
12337  *
12338  * Return:
12339  *	A mblk_t pointer pointing to the requested segment in send queue.
12340  */
12341 static mblk_t *
12342 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12343 {
12344 	int32_t	cnt;
12345 	mblk_t	*mp;
12346 
12347 	/* Defensive coding.  Make sure we don't send incorrect data. */
12348 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12349 		return (NULL);
12350 
12351 	cnt = seq - tcp->tcp_suna;
12352 	mp = tcp->tcp_xmit_head;
12353 	while (cnt > 0 && mp != NULL) {
12354 		cnt -= mp->b_wptr - mp->b_rptr;
12355 		if (cnt < 0) {
12356 			cnt += mp->b_wptr - mp->b_rptr;
12357 			break;
12358 		}
12359 		mp = mp->b_cont;
12360 	}
12361 	ASSERT(mp != NULL);
12362 	*off = cnt;
12363 	return (mp);
12364 }
12365 
12366 /*
12367  * This function handles all retransmissions if SACK is enabled for this
12368  * connection.  First it calculates how many segments can be retransmitted
12369  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12370  * segments.  A segment is eligible if sack_cnt for that segment is greater
12371  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12372  * all eligible segments, it checks to see if TCP can send some new segments
12373  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12374  *
12375  * Parameters:
12376  *	tcp_t *tcp: the tcp structure of the connection.
12377  *	uint_t *flags: in return, appropriate value will be set for
12378  *	tcp_rput_data().
12379  */
12380 static void
12381 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12382 {
12383 	notsack_blk_t	*notsack_blk;
12384 	int32_t		usable_swnd;
12385 	int32_t		mss;
12386 	uint32_t	seg_len;
12387 	mblk_t		*xmit_mp;
12388 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12389 
12390 	ASSERT(tcp->tcp_sack_info != NULL);
12391 	ASSERT(tcp->tcp_notsack_list != NULL);
12392 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12393 
12394 	/* Defensive coding in case there is a bug... */
12395 	if (tcp->tcp_notsack_list == NULL) {
12396 		return;
12397 	}
12398 	notsack_blk = tcp->tcp_notsack_list;
12399 	mss = tcp->tcp_mss;
12400 
12401 	/*
12402 	 * Limit the num of outstanding data in the network to be
12403 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12404 	 */
12405 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12406 
12407 	/* At least retransmit 1 MSS of data. */
12408 	if (usable_swnd <= 0) {
12409 		usable_swnd = mss;
12410 	}
12411 
12412 	/* Make sure no new RTT samples will be taken. */
12413 	tcp->tcp_csuna = tcp->tcp_snxt;
12414 
12415 	notsack_blk = tcp->tcp_notsack_list;
12416 	while (usable_swnd > 0) {
12417 		mblk_t		*snxt_mp, *tmp_mp;
12418 		tcp_seq		begin = tcp->tcp_sack_snxt;
12419 		tcp_seq		end;
12420 		int32_t		off;
12421 
12422 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12423 			if (SEQ_GT(notsack_blk->end, begin) &&
12424 			    (notsack_blk->sack_cnt >=
12425 			    tcps->tcps_dupack_fast_retransmit)) {
12426 				end = notsack_blk->end;
12427 				if (SEQ_LT(begin, notsack_blk->begin)) {
12428 					begin = notsack_blk->begin;
12429 				}
12430 				break;
12431 			}
12432 		}
12433 		/*
12434 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12435 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12436 		 * set to tcp_cwnd_ssthresh.
12437 		 */
12438 		if (notsack_blk == NULL) {
12439 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12440 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12441 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12442 				ASSERT(tcp->tcp_cwnd > 0);
12443 				return;
12444 			} else {
12445 				usable_swnd = usable_swnd / mss;
12446 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12447 				    MAX(usable_swnd * mss, mss);
12448 				*flags |= TH_XMIT_NEEDED;
12449 				return;
12450 			}
12451 		}
12452 
12453 		/*
12454 		 * Note that we may send more than usable_swnd allows here
12455 		 * because of round off, but no more than 1 MSS of data.
12456 		 */
12457 		seg_len = end - begin;
12458 		if (seg_len > mss)
12459 			seg_len = mss;
12460 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12461 		ASSERT(snxt_mp != NULL);
12462 		/* This should not happen.  Defensive coding again... */
12463 		if (snxt_mp == NULL) {
12464 			return;
12465 		}
12466 
12467 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12468 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12469 		if (xmit_mp == NULL)
12470 			return;
12471 
12472 		usable_swnd -= seg_len;
12473 		tcp->tcp_pipe += seg_len;
12474 		tcp->tcp_sack_snxt = begin + seg_len;
12475 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
12476 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12477 
12478 		/*
12479 		 * Update the send timestamp to avoid false retransmission.
12480 		 */
12481 		snxt_mp->b_prev = (mblk_t *)lbolt;
12482 
12483 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12484 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12485 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12486 		/*
12487 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12488 		 * This happens when new data sent during fast recovery is
12489 		 * also lost.  If TCP retransmits those new data, it needs
12490 		 * to extend SACK recover phase to avoid starting another
12491 		 * fast retransmit/recovery unnecessarily.
12492 		 */
12493 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12494 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12495 		}
12496 	}
12497 }
12498 
12499 /*
12500  * This function handles policy checking at TCP level for non-hard_bound/
12501  * detached connections.
12502  */
12503 static boolean_t
12504 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12505     boolean_t secure, boolean_t mctl_present)
12506 {
12507 	ipsec_latch_t *ipl = NULL;
12508 	ipsec_action_t *act = NULL;
12509 	mblk_t *data_mp;
12510 	ipsec_in_t *ii;
12511 	const char *reason;
12512 	kstat_named_t *counter;
12513 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12514 	ipsec_stack_t	*ipss;
12515 	ip_stack_t	*ipst;
12516 
12517 	ASSERT(mctl_present || !secure);
12518 
12519 	ASSERT((ipha == NULL && ip6h != NULL) ||
12520 	    (ip6h == NULL && ipha != NULL));
12521 
12522 	/*
12523 	 * We don't necessarily have an ipsec_in_act action to verify
12524 	 * policy because of assymetrical policy where we have only
12525 	 * outbound policy and no inbound policy (possible with global
12526 	 * policy).
12527 	 */
12528 	if (!secure) {
12529 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12530 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12531 			return (B_TRUE);
12532 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12533 		    "tcp_check_policy", ipha, ip6h, secure,
12534 		    tcps->tcps_netstack);
12535 		ipss = tcps->tcps_netstack->netstack_ipsec;
12536 
12537 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12538 		    DROPPER(ipss, ipds_tcp_clear),
12539 		    &tcps->tcps_dropper);
12540 		return (B_FALSE);
12541 	}
12542 
12543 	/*
12544 	 * We have a secure packet.
12545 	 */
12546 	if (act == NULL) {
12547 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12548 		    "tcp_check_policy", ipha, ip6h, secure,
12549 		    tcps->tcps_netstack);
12550 		ipss = tcps->tcps_netstack->netstack_ipsec;
12551 
12552 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12553 		    DROPPER(ipss, ipds_tcp_secure),
12554 		    &tcps->tcps_dropper);
12555 		return (B_FALSE);
12556 	}
12557 
12558 	/*
12559 	 * XXX This whole routine is currently incorrect.  ipl should
12560 	 * be set to the latch pointer, but is currently not set, so
12561 	 * we initialize it to NULL to avoid picking up random garbage.
12562 	 */
12563 	if (ipl == NULL)
12564 		return (B_TRUE);
12565 
12566 	data_mp = first_mp->b_cont;
12567 
12568 	ii = (ipsec_in_t *)first_mp->b_rptr;
12569 
12570 	ipst = tcps->tcps_netstack->netstack_ip;
12571 
12572 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12573 	    &counter, tcp->tcp_connp)) {
12574 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12575 		return (B_TRUE);
12576 	}
12577 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12578 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12579 	    reason);
12580 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12581 
12582 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12583 	    &tcps->tcps_dropper);
12584 	return (B_FALSE);
12585 }
12586 
12587 /*
12588  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12589  * retransmission after a timeout.
12590  *
12591  * To limit the number of duplicate segments, we limit the number of segment
12592  * to be sent in one time to tcp_snd_burst, the burst variable.
12593  */
12594 static void
12595 tcp_ss_rexmit(tcp_t *tcp)
12596 {
12597 	uint32_t	snxt;
12598 	uint32_t	smax;
12599 	int32_t		win;
12600 	int32_t		mss;
12601 	int32_t		off;
12602 	int32_t		burst = tcp->tcp_snd_burst;
12603 	mblk_t		*snxt_mp;
12604 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12605 
12606 	/*
12607 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12608 	 * all unack'ed segments.
12609 	 */
12610 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12611 		smax = tcp->tcp_rexmit_max;
12612 		snxt = tcp->tcp_rexmit_nxt;
12613 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12614 			snxt = tcp->tcp_suna;
12615 		}
12616 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12617 		win -= snxt - tcp->tcp_suna;
12618 		mss = tcp->tcp_mss;
12619 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12620 
12621 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12622 		    (burst > 0) && (snxt_mp != NULL)) {
12623 			mblk_t	*xmit_mp;
12624 			mblk_t	*old_snxt_mp = snxt_mp;
12625 			uint32_t cnt = mss;
12626 
12627 			if (win < cnt) {
12628 				cnt = win;
12629 			}
12630 			if (SEQ_GT(snxt + cnt, smax)) {
12631 				cnt = smax - snxt;
12632 			}
12633 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12634 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12635 			if (xmit_mp == NULL)
12636 				return;
12637 
12638 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12639 
12640 			snxt += cnt;
12641 			win -= cnt;
12642 			/*
12643 			 * Update the send timestamp to avoid false
12644 			 * retransmission.
12645 			 */
12646 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12647 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12648 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12649 
12650 			tcp->tcp_rexmit_nxt = snxt;
12651 			burst--;
12652 		}
12653 		/*
12654 		 * If we have transmitted all we have at the time
12655 		 * we started the retranmission, we can leave
12656 		 * the rest of the job to tcp_wput_data().  But we
12657 		 * need to check the send window first.  If the
12658 		 * win is not 0, go on with tcp_wput_data().
12659 		 */
12660 		if (SEQ_LT(snxt, smax) || win == 0) {
12661 			return;
12662 		}
12663 	}
12664 	/* Only call tcp_wput_data() if there is data to be sent. */
12665 	if (tcp->tcp_unsent) {
12666 		tcp_wput_data(tcp, NULL, B_FALSE);
12667 	}
12668 }
12669 
12670 /*
12671  * Process all TCP option in SYN segment.  Note that this function should
12672  * be called after tcp_adapt_ire() is called so that the necessary info
12673  * from IRE is already set in the tcp structure.
12674  *
12675  * This function sets up the correct tcp_mss value according to the
12676  * MSS option value and our header size.  It also sets up the window scale
12677  * and timestamp values, and initialize SACK info blocks.  But it does not
12678  * change receive window size after setting the tcp_mss value.  The caller
12679  * should do the appropriate change.
12680  */
12681 void
12682 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12683 {
12684 	int options;
12685 	tcp_opt_t tcpopt;
12686 	uint32_t mss_max;
12687 	char *tmp_tcph;
12688 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12689 
12690 	tcpopt.tcp = NULL;
12691 	options = tcp_parse_options(tcph, &tcpopt);
12692 
12693 	/*
12694 	 * Process MSS option.  Note that MSS option value does not account
12695 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12696 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12697 	 * IPv6.
12698 	 */
12699 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12700 		if (tcp->tcp_ipversion == IPV4_VERSION)
12701 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12702 		else
12703 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12704 	} else {
12705 		if (tcp->tcp_ipversion == IPV4_VERSION)
12706 			mss_max = tcps->tcps_mss_max_ipv4;
12707 		else
12708 			mss_max = tcps->tcps_mss_max_ipv6;
12709 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12710 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12711 		else if (tcpopt.tcp_opt_mss > mss_max)
12712 			tcpopt.tcp_opt_mss = mss_max;
12713 	}
12714 
12715 	/* Process Window Scale option. */
12716 	if (options & TCP_OPT_WSCALE_PRESENT) {
12717 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12718 		tcp->tcp_snd_ws_ok = B_TRUE;
12719 	} else {
12720 		tcp->tcp_snd_ws = B_FALSE;
12721 		tcp->tcp_snd_ws_ok = B_FALSE;
12722 		tcp->tcp_rcv_ws = B_FALSE;
12723 	}
12724 
12725 	/* Process Timestamp option. */
12726 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12727 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12728 		tmp_tcph = (char *)tcp->tcp_tcph;
12729 
12730 		tcp->tcp_snd_ts_ok = B_TRUE;
12731 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12732 		tcp->tcp_last_rcv_lbolt = lbolt64;
12733 		ASSERT(OK_32PTR(tmp_tcph));
12734 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12735 
12736 		/* Fill in our template header with basic timestamp option. */
12737 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12738 		tmp_tcph[0] = TCPOPT_NOP;
12739 		tmp_tcph[1] = TCPOPT_NOP;
12740 		tmp_tcph[2] = TCPOPT_TSTAMP;
12741 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12742 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12743 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12744 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12745 	} else {
12746 		tcp->tcp_snd_ts_ok = B_FALSE;
12747 	}
12748 
12749 	/*
12750 	 * Process SACK options.  If SACK is enabled for this connection,
12751 	 * then allocate the SACK info structure.  Note the following ways
12752 	 * when tcp_snd_sack_ok is set to true.
12753 	 *
12754 	 * For active connection: in tcp_adapt_ire() called in
12755 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12756 	 * is checked.
12757 	 *
12758 	 * For passive connection: in tcp_adapt_ire() called in
12759 	 * tcp_accept_comm().
12760 	 *
12761 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12762 	 * That check makes sure that if we did not send a SACK OK option,
12763 	 * we will not enable SACK for this connection even though the other
12764 	 * side sends us SACK OK option.  For active connection, the SACK
12765 	 * info structure has already been allocated.  So we need to free
12766 	 * it if SACK is disabled.
12767 	 */
12768 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12769 	    (tcp->tcp_snd_sack_ok ||
12770 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12771 		/* This should be true only in the passive case. */
12772 		if (tcp->tcp_sack_info == NULL) {
12773 			ASSERT(TCP_IS_DETACHED(tcp));
12774 			tcp->tcp_sack_info =
12775 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12776 		}
12777 		if (tcp->tcp_sack_info == NULL) {
12778 			tcp->tcp_snd_sack_ok = B_FALSE;
12779 		} else {
12780 			tcp->tcp_snd_sack_ok = B_TRUE;
12781 			if (tcp->tcp_snd_ts_ok) {
12782 				tcp->tcp_max_sack_blk = 3;
12783 			} else {
12784 				tcp->tcp_max_sack_blk = 4;
12785 			}
12786 		}
12787 	} else {
12788 		/*
12789 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12790 		 * no SACK info will be used for this
12791 		 * connection.  This assumes that SACK usage
12792 		 * permission is negotiated.  This may need
12793 		 * to be changed once this is clarified.
12794 		 */
12795 		if (tcp->tcp_sack_info != NULL) {
12796 			ASSERT(tcp->tcp_notsack_list == NULL);
12797 			kmem_cache_free(tcp_sack_info_cache,
12798 			    tcp->tcp_sack_info);
12799 			tcp->tcp_sack_info = NULL;
12800 		}
12801 		tcp->tcp_snd_sack_ok = B_FALSE;
12802 	}
12803 
12804 	/*
12805 	 * Now we know the exact TCP/IP header length, subtract
12806 	 * that from tcp_mss to get our side's MSS.
12807 	 */
12808 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12809 	/*
12810 	 * Here we assume that the other side's header size will be equal to
12811 	 * our header size.  We calculate the real MSS accordingly.  Need to
12812 	 * take into additional stuffs IPsec puts in.
12813 	 *
12814 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12815 	 */
12816 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12817 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12818 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12819 
12820 	/*
12821 	 * Set MSS to the smaller one of both ends of the connection.
12822 	 * We should not have called tcp_mss_set() before, but our
12823 	 * side of the MSS should have been set to a proper value
12824 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12825 	 * STREAM head parameters properly.
12826 	 *
12827 	 * If we have a larger-than-16-bit window but the other side
12828 	 * didn't want to do window scale, tcp_rwnd_set() will take
12829 	 * care of that.
12830 	 */
12831 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12832 }
12833 
12834 /*
12835  * Sends the T_CONN_IND to the listener. The caller calls this
12836  * functions via squeue to get inside the listener's perimeter
12837  * once the 3 way hand shake is done a T_CONN_IND needs to be
12838  * sent. As an optimization, the caller can call this directly
12839  * if listener's perimeter is same as eager's.
12840  */
12841 /* ARGSUSED */
12842 void
12843 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12844 {
12845 	conn_t			*lconnp = (conn_t *)arg;
12846 	tcp_t			*listener = lconnp->conn_tcp;
12847 	tcp_t			*tcp;
12848 	struct T_conn_ind	*conn_ind;
12849 	ipaddr_t 		*addr_cache;
12850 	boolean_t		need_send_conn_ind = B_FALSE;
12851 	tcp_stack_t		*tcps = listener->tcp_tcps;
12852 
12853 	/* retrieve the eager */
12854 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12855 	ASSERT(conn_ind->OPT_offset != 0 &&
12856 	    conn_ind->OPT_length == sizeof (intptr_t));
12857 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12858 	    conn_ind->OPT_length);
12859 
12860 	/*
12861 	 * TLI/XTI applications will get confused by
12862 	 * sending eager as an option since it violates
12863 	 * the option semantics. So remove the eager as
12864 	 * option since TLI/XTI app doesn't need it anyway.
12865 	 */
12866 	if (!TCP_IS_SOCKET(listener)) {
12867 		conn_ind->OPT_length = 0;
12868 		conn_ind->OPT_offset = 0;
12869 	}
12870 	if (listener->tcp_state == TCPS_CLOSED ||
12871 	    TCP_IS_DETACHED(listener)) {
12872 		/*
12873 		 * If listener has closed, it would have caused a
12874 		 * a cleanup/blowoff to happen for the eager. We
12875 		 * just need to return.
12876 		 */
12877 		freemsg(mp);
12878 		return;
12879 	}
12880 
12881 
12882 	/*
12883 	 * if the conn_req_q is full defer passing up the
12884 	 * T_CONN_IND until space is availabe after t_accept()
12885 	 * processing
12886 	 */
12887 	mutex_enter(&listener->tcp_eager_lock);
12888 
12889 	/*
12890 	 * Take the eager out, if it is in the list of droppable eagers
12891 	 * as we are here because the 3W handshake is over.
12892 	 */
12893 	MAKE_UNDROPPABLE(tcp);
12894 
12895 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12896 		tcp_t *tail;
12897 
12898 		/*
12899 		 * The eager already has an extra ref put in tcp_rput_data
12900 		 * so that it stays till accept comes back even though it
12901 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12902 		 */
12903 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12904 		listener->tcp_conn_req_cnt_q0--;
12905 		listener->tcp_conn_req_cnt_q++;
12906 
12907 		/* Move from SYN_RCVD to ESTABLISHED list  */
12908 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12909 		    tcp->tcp_eager_prev_q0;
12910 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12911 		    tcp->tcp_eager_next_q0;
12912 		tcp->tcp_eager_prev_q0 = NULL;
12913 		tcp->tcp_eager_next_q0 = NULL;
12914 
12915 		/*
12916 		 * Insert at end of the queue because sockfs
12917 		 * sends down T_CONN_RES in chronological
12918 		 * order. Leaving the older conn indications
12919 		 * at front of the queue helps reducing search
12920 		 * time.
12921 		 */
12922 		tail = listener->tcp_eager_last_q;
12923 		if (tail != NULL)
12924 			tail->tcp_eager_next_q = tcp;
12925 		else
12926 			listener->tcp_eager_next_q = tcp;
12927 		listener->tcp_eager_last_q = tcp;
12928 		tcp->tcp_eager_next_q = NULL;
12929 		/*
12930 		 * Delay sending up the T_conn_ind until we are
12931 		 * done with the eager. Once we have have sent up
12932 		 * the T_conn_ind, the accept can potentially complete
12933 		 * any time and release the refhold we have on the eager.
12934 		 */
12935 		need_send_conn_ind = B_TRUE;
12936 	} else {
12937 		/*
12938 		 * Defer connection on q0 and set deferred
12939 		 * connection bit true
12940 		 */
12941 		tcp->tcp_conn_def_q0 = B_TRUE;
12942 
12943 		/* take tcp out of q0 ... */
12944 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12945 		    tcp->tcp_eager_next_q0;
12946 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12947 		    tcp->tcp_eager_prev_q0;
12948 
12949 		/* ... and place it at the end of q0 */
12950 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12951 		tcp->tcp_eager_next_q0 = listener;
12952 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12953 		listener->tcp_eager_prev_q0 = tcp;
12954 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12955 	}
12956 
12957 	/* we have timed out before */
12958 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12959 		tcp->tcp_syn_rcvd_timeout = 0;
12960 		listener->tcp_syn_rcvd_timeout--;
12961 		if (listener->tcp_syn_defense &&
12962 		    listener->tcp_syn_rcvd_timeout <=
12963 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12964 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12965 		    listener->tcp_last_rcv_lbolt)) {
12966 			/*
12967 			 * Turn off the defense mode if we
12968 			 * believe the SYN attack is over.
12969 			 */
12970 			listener->tcp_syn_defense = B_FALSE;
12971 			if (listener->tcp_ip_addr_cache) {
12972 				kmem_free((void *)listener->tcp_ip_addr_cache,
12973 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12974 				listener->tcp_ip_addr_cache = NULL;
12975 			}
12976 		}
12977 	}
12978 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12979 	if (addr_cache != NULL) {
12980 		/*
12981 		 * We have finished a 3-way handshake with this
12982 		 * remote host. This proves the IP addr is good.
12983 		 * Cache it!
12984 		 */
12985 		addr_cache[IP_ADDR_CACHE_HASH(
12986 		    tcp->tcp_remote)] = tcp->tcp_remote;
12987 	}
12988 	mutex_exit(&listener->tcp_eager_lock);
12989 	if (need_send_conn_ind)
12990 		putnext(listener->tcp_rq, mp);
12991 }
12992 
12993 mblk_t *
12994 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12995     uint_t *ifindexp, ip6_pkt_t *ippp)
12996 {
12997 	ip_pktinfo_t	*pinfo;
12998 	ip6_t		*ip6h;
12999 	uchar_t		*rptr;
13000 	mblk_t		*first_mp = mp;
13001 	boolean_t	mctl_present = B_FALSE;
13002 	uint_t 		ifindex = 0;
13003 	ip6_pkt_t	ipp;
13004 	uint_t		ipvers;
13005 	uint_t		ip_hdr_len;
13006 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13007 
13008 	rptr = mp->b_rptr;
13009 	ASSERT(OK_32PTR(rptr));
13010 	ASSERT(tcp != NULL);
13011 	ipp.ipp_fields = 0;
13012 
13013 	switch DB_TYPE(mp) {
13014 	case M_CTL:
13015 		mp = mp->b_cont;
13016 		if (mp == NULL) {
13017 			freemsg(first_mp);
13018 			return (NULL);
13019 		}
13020 		if (DB_TYPE(mp) != M_DATA) {
13021 			freemsg(first_mp);
13022 			return (NULL);
13023 		}
13024 		mctl_present = B_TRUE;
13025 		break;
13026 	case M_DATA:
13027 		break;
13028 	default:
13029 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
13030 		freemsg(mp);
13031 		return (NULL);
13032 	}
13033 	ipvers = IPH_HDR_VERSION(rptr);
13034 	if (ipvers == IPV4_VERSION) {
13035 		if (tcp == NULL) {
13036 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
13037 			goto done;
13038 		}
13039 
13040 		ipp.ipp_fields |= IPPF_HOPLIMIT;
13041 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
13042 
13043 		/*
13044 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
13045 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
13046 		 */
13047 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
13048 		    mctl_present) {
13049 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
13050 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
13051 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
13052 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
13053 				ipp.ipp_fields |= IPPF_IFINDEX;
13054 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
13055 				ifindex = pinfo->ip_pkt_ifindex;
13056 			}
13057 			freeb(first_mp);
13058 			mctl_present = B_FALSE;
13059 		}
13060 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
13061 	} else {
13062 		ip6h = (ip6_t *)rptr;
13063 
13064 		ASSERT(ipvers == IPV6_VERSION);
13065 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
13066 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
13067 		ipp.ipp_hoplimit = ip6h->ip6_hops;
13068 
13069 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
13070 			uint8_t	nexthdrp;
13071 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13072 
13073 			/* Look for ifindex information */
13074 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
13075 				ip6i_t *ip6i = (ip6i_t *)ip6h;
13076 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
13077 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
13078 					freemsg(first_mp);
13079 					return (NULL);
13080 				}
13081 
13082 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
13083 					ASSERT(ip6i->ip6i_ifindex != 0);
13084 					ipp.ipp_fields |= IPPF_IFINDEX;
13085 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
13086 					ifindex = ip6i->ip6i_ifindex;
13087 				}
13088 				rptr = (uchar_t *)&ip6i[1];
13089 				mp->b_rptr = rptr;
13090 				if (rptr == mp->b_wptr) {
13091 					mblk_t *mp1;
13092 					mp1 = mp->b_cont;
13093 					freeb(mp);
13094 					mp = mp1;
13095 					rptr = mp->b_rptr;
13096 				}
13097 				if (MBLKL(mp) < IPV6_HDR_LEN +
13098 				    sizeof (tcph_t)) {
13099 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
13100 					freemsg(first_mp);
13101 					return (NULL);
13102 				}
13103 				ip6h = (ip6_t *)rptr;
13104 			}
13105 
13106 			/*
13107 			 * Find any potentially interesting extension headers
13108 			 * as well as the length of the IPv6 + extension
13109 			 * headers.
13110 			 */
13111 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
13112 			/* Verify if this is a TCP packet */
13113 			if (nexthdrp != IPPROTO_TCP) {
13114 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
13115 				freemsg(first_mp);
13116 				return (NULL);
13117 			}
13118 		} else {
13119 			ip_hdr_len = IPV6_HDR_LEN;
13120 		}
13121 	}
13122 
13123 done:
13124 	if (ipversp != NULL)
13125 		*ipversp = ipvers;
13126 	if (ip_hdr_lenp != NULL)
13127 		*ip_hdr_lenp = ip_hdr_len;
13128 	if (ippp != NULL)
13129 		*ippp = ipp;
13130 	if (ifindexp != NULL)
13131 		*ifindexp = ifindex;
13132 	if (mctl_present) {
13133 		freeb(first_mp);
13134 	}
13135 	return (mp);
13136 }
13137 
13138 /*
13139  * Handle M_DATA messages from IP. Its called directly from IP via
13140  * squeue for AF_INET type sockets fast path. No M_CTL are expected
13141  * in this path.
13142  *
13143  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
13144  * v4 and v6), we are called through tcp_input() and a M_CTL can
13145  * be present for options but tcp_find_pktinfo() deals with it. We
13146  * only expect M_DATA packets after tcp_find_pktinfo() is done.
13147  *
13148  * The first argument is always the connp/tcp to which the mp belongs.
13149  * There are no exceptions to this rule. The caller has already put
13150  * a reference on this connp/tcp and once tcp_rput_data() returns,
13151  * the squeue will do the refrele.
13152  *
13153  * The TH_SYN for the listener directly go to tcp_conn_request via
13154  * squeue.
13155  *
13156  * sqp: NULL = recursive, sqp != NULL means called from squeue
13157  */
13158 void
13159 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
13160 {
13161 	int32_t		bytes_acked;
13162 	int32_t		gap;
13163 	mblk_t		*mp1;
13164 	uint_t		flags;
13165 	uint32_t	new_swnd = 0;
13166 	uchar_t		*iphdr;
13167 	uchar_t		*rptr;
13168 	int32_t		rgap;
13169 	uint32_t	seg_ack;
13170 	int		seg_len;
13171 	uint_t		ip_hdr_len;
13172 	uint32_t	seg_seq;
13173 	tcph_t		*tcph;
13174 	int		urp;
13175 	tcp_opt_t	tcpopt;
13176 	uint_t		ipvers;
13177 	ip6_pkt_t	ipp;
13178 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
13179 	uint32_t	cwnd;
13180 	uint32_t	add;
13181 	int		npkt;
13182 	int		mss;
13183 	conn_t		*connp = (conn_t *)arg;
13184 	squeue_t	*sqp = (squeue_t *)arg2;
13185 	tcp_t		*tcp = connp->conn_tcp;
13186 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13187 
13188 	/*
13189 	 * RST from fused tcp loopback peer should trigger an unfuse.
13190 	 */
13191 	if (tcp->tcp_fused) {
13192 		TCP_STAT(tcps, tcp_fusion_aborted);
13193 		tcp_unfuse(tcp);
13194 	}
13195 
13196 	iphdr = mp->b_rptr;
13197 	rptr = mp->b_rptr;
13198 	ASSERT(OK_32PTR(rptr));
13199 
13200 	/*
13201 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
13202 	 * processing here. For rest call tcp_find_pktinfo to fill up the
13203 	 * necessary information.
13204 	 */
13205 	if (IPCL_IS_TCP4(connp)) {
13206 		ipvers = IPV4_VERSION;
13207 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
13208 	} else {
13209 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
13210 		    NULL, &ipp);
13211 		if (mp == NULL) {
13212 			TCP_STAT(tcps, tcp_rput_v6_error);
13213 			return;
13214 		}
13215 		iphdr = mp->b_rptr;
13216 		rptr = mp->b_rptr;
13217 	}
13218 	ASSERT(DB_TYPE(mp) == M_DATA);
13219 
13220 	tcph = (tcph_t *)&rptr[ip_hdr_len];
13221 	seg_seq = ABE32_TO_U32(tcph->th_seq);
13222 	seg_ack = ABE32_TO_U32(tcph->th_ack);
13223 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
13224 	seg_len = (int)(mp->b_wptr - rptr) -
13225 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
13226 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
13227 		do {
13228 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
13229 			    (uintptr_t)INT_MAX);
13230 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
13231 		} while ((mp1 = mp1->b_cont) != NULL &&
13232 		    mp1->b_datap->db_type == M_DATA);
13233 	}
13234 
13235 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
13236 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
13237 		    seg_len, tcph);
13238 		return;
13239 	}
13240 
13241 	if (sqp != NULL) {
13242 		/*
13243 		 * This is the correct place to update tcp_last_recv_time. Note
13244 		 * that it is also updated for tcp structure that belongs to
13245 		 * global and listener queues which do not really need updating.
13246 		 * But that should not cause any harm.  And it is updated for
13247 		 * all kinds of incoming segments, not only for data segments.
13248 		 */
13249 		tcp->tcp_last_recv_time = lbolt;
13250 	}
13251 
13252 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13253 
13254 	BUMP_LOCAL(tcp->tcp_ibsegs);
13255 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
13256 
13257 	if ((flags & TH_URG) && sqp != NULL) {
13258 		/*
13259 		 * TCP can't handle urgent pointers that arrive before
13260 		 * the connection has been accept()ed since it can't
13261 		 * buffer OOB data.  Discard segment if this happens.
13262 		 *
13263 		 * We can't just rely on a non-null tcp_listener to indicate
13264 		 * that the accept() has completed since unlinking of the
13265 		 * eager and completion of the accept are not atomic.
13266 		 * tcp_detached, when it is not set (B_FALSE) indicates
13267 		 * that the accept() has completed.
13268 		 *
13269 		 * Nor can it reassemble urgent pointers, so discard
13270 		 * if it's not the next segment expected.
13271 		 *
13272 		 * Otherwise, collapse chain into one mblk (discard if
13273 		 * that fails).  This makes sure the headers, retransmitted
13274 		 * data, and new data all are in the same mblk.
13275 		 */
13276 		ASSERT(mp != NULL);
13277 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
13278 			freemsg(mp);
13279 			return;
13280 		}
13281 		/* Update pointers into message */
13282 		iphdr = rptr = mp->b_rptr;
13283 		tcph = (tcph_t *)&rptr[ip_hdr_len];
13284 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
13285 			/*
13286 			 * Since we can't handle any data with this urgent
13287 			 * pointer that is out of sequence, we expunge
13288 			 * the data.  This allows us to still register
13289 			 * the urgent mark and generate the M_PCSIG,
13290 			 * which we can do.
13291 			 */
13292 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13293 			seg_len = 0;
13294 		}
13295 	}
13296 
13297 	switch (tcp->tcp_state) {
13298 	case TCPS_SYN_SENT:
13299 		if (flags & TH_ACK) {
13300 			/*
13301 			 * Note that our stack cannot send data before a
13302 			 * connection is established, therefore the
13303 			 * following check is valid.  Otherwise, it has
13304 			 * to be changed.
13305 			 */
13306 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13307 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13308 				freemsg(mp);
13309 				if (flags & TH_RST)
13310 					return;
13311 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13312 				    tcp, seg_ack, 0, TH_RST);
13313 				return;
13314 			}
13315 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13316 		}
13317 		if (flags & TH_RST) {
13318 			freemsg(mp);
13319 			if (flags & TH_ACK)
13320 				(void) tcp_clean_death(tcp,
13321 				    ECONNREFUSED, 13);
13322 			return;
13323 		}
13324 		if (!(flags & TH_SYN)) {
13325 			freemsg(mp);
13326 			return;
13327 		}
13328 
13329 		/* Process all TCP options. */
13330 		tcp_process_options(tcp, tcph);
13331 		/*
13332 		 * The following changes our rwnd to be a multiple of the
13333 		 * MIN(peer MSS, our MSS) for performance reason.
13334 		 */
13335 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
13336 		    tcp->tcp_mss));
13337 
13338 		/* Is the other end ECN capable? */
13339 		if (tcp->tcp_ecn_ok) {
13340 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13341 				tcp->tcp_ecn_ok = B_FALSE;
13342 			}
13343 		}
13344 		/*
13345 		 * Clear ECN flags because it may interfere with later
13346 		 * processing.
13347 		 */
13348 		flags &= ~(TH_ECE|TH_CWR);
13349 
13350 		tcp->tcp_irs = seg_seq;
13351 		tcp->tcp_rack = seg_seq;
13352 		tcp->tcp_rnxt = seg_seq + 1;
13353 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13354 		if (!TCP_IS_DETACHED(tcp)) {
13355 			/* Allocate room for SACK options if needed. */
13356 			if (tcp->tcp_snd_sack_ok) {
13357 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13358 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
13359 				    (tcp->tcp_loopback ? 0 :
13360 				    tcps->tcps_wroff_xtra));
13361 			} else {
13362 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13363 				    tcp->tcp_hdr_len +
13364 				    (tcp->tcp_loopback ? 0 :
13365 				    tcps->tcps_wroff_xtra));
13366 			}
13367 		}
13368 		if (flags & TH_ACK) {
13369 			/*
13370 			 * If we can't get the confirmation upstream, pretend
13371 			 * we didn't even see this one.
13372 			 *
13373 			 * XXX: how can we pretend we didn't see it if we
13374 			 * have updated rnxt et. al.
13375 			 *
13376 			 * For loopback we defer sending up the T_CONN_CON
13377 			 * until after some checks below.
13378 			 */
13379 			mp1 = NULL;
13380 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13381 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13382 				freemsg(mp);
13383 				return;
13384 			}
13385 			/* SYN was acked - making progress */
13386 			if (tcp->tcp_ipversion == IPV6_VERSION)
13387 				tcp->tcp_ip_forward_progress = B_TRUE;
13388 
13389 			/* One for the SYN */
13390 			tcp->tcp_suna = tcp->tcp_iss + 1;
13391 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13392 			tcp->tcp_state = TCPS_ESTABLISHED;
13393 
13394 			/*
13395 			 * If SYN was retransmitted, need to reset all
13396 			 * retransmission info.  This is because this
13397 			 * segment will be treated as a dup ACK.
13398 			 */
13399 			if (tcp->tcp_rexmit) {
13400 				tcp->tcp_rexmit = B_FALSE;
13401 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13402 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13403 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13404 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13405 				tcp->tcp_ms_we_have_waited = 0;
13406 
13407 				/*
13408 				 * Set tcp_cwnd back to 1 MSS, per
13409 				 * recommendation from
13410 				 * draft-floyd-incr-init-win-01.txt,
13411 				 * Increasing TCP's Initial Window.
13412 				 */
13413 				tcp->tcp_cwnd = tcp->tcp_mss;
13414 			}
13415 
13416 			tcp->tcp_swl1 = seg_seq;
13417 			tcp->tcp_swl2 = seg_ack;
13418 
13419 			new_swnd = BE16_TO_U16(tcph->th_win);
13420 			tcp->tcp_swnd = new_swnd;
13421 			if (new_swnd > tcp->tcp_max_swnd)
13422 				tcp->tcp_max_swnd = new_swnd;
13423 
13424 			/*
13425 			 * Always send the three-way handshake ack immediately
13426 			 * in order to make the connection complete as soon as
13427 			 * possible on the accepting host.
13428 			 */
13429 			flags |= TH_ACK_NEEDED;
13430 
13431 			/*
13432 			 * Special case for loopback.  At this point we have
13433 			 * received SYN-ACK from the remote endpoint.  In
13434 			 * order to ensure that both endpoints reach the
13435 			 * fused state prior to any data exchange, the final
13436 			 * ACK needs to be sent before we indicate T_CONN_CON
13437 			 * to the module upstream.
13438 			 */
13439 			if (tcp->tcp_loopback) {
13440 				mblk_t *ack_mp;
13441 
13442 				ASSERT(!tcp->tcp_unfusable);
13443 				ASSERT(mp1 != NULL);
13444 				/*
13445 				 * For loopback, we always get a pure SYN-ACK
13446 				 * and only need to send back the final ACK
13447 				 * with no data (this is because the other
13448 				 * tcp is ours and we don't do T/TCP).  This
13449 				 * final ACK triggers the passive side to
13450 				 * perform fusion in ESTABLISHED state.
13451 				 */
13452 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13453 					if (tcp->tcp_ack_tid != 0) {
13454 						(void) TCP_TIMER_CANCEL(tcp,
13455 						    tcp->tcp_ack_tid);
13456 						tcp->tcp_ack_tid = 0;
13457 					}
13458 					TCP_RECORD_TRACE(tcp, ack_mp,
13459 					    TCP_TRACE_SEND_PKT);
13460 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13461 					BUMP_LOCAL(tcp->tcp_obsegs);
13462 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13463 
13464 					/* Send up T_CONN_CON */
13465 					putnext(tcp->tcp_rq, mp1);
13466 
13467 					freemsg(mp);
13468 					return;
13469 				}
13470 				/*
13471 				 * Forget fusion; we need to handle more
13472 				 * complex cases below.  Send the deferred
13473 				 * T_CONN_CON message upstream and proceed
13474 				 * as usual.  Mark this tcp as not capable
13475 				 * of fusion.
13476 				 */
13477 				TCP_STAT(tcps, tcp_fusion_unfusable);
13478 				tcp->tcp_unfusable = B_TRUE;
13479 				putnext(tcp->tcp_rq, mp1);
13480 			}
13481 
13482 			/*
13483 			 * Check to see if there is data to be sent.  If
13484 			 * yes, set the transmit flag.  Then check to see
13485 			 * if received data processing needs to be done.
13486 			 * If not, go straight to xmit_check.  This short
13487 			 * cut is OK as we don't support T/TCP.
13488 			 */
13489 			if (tcp->tcp_unsent)
13490 				flags |= TH_XMIT_NEEDED;
13491 
13492 			if (seg_len == 0 && !(flags & TH_URG)) {
13493 				freemsg(mp);
13494 				goto xmit_check;
13495 			}
13496 
13497 			flags &= ~TH_SYN;
13498 			seg_seq++;
13499 			break;
13500 		}
13501 		tcp->tcp_state = TCPS_SYN_RCVD;
13502 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13503 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13504 		if (mp1) {
13505 			DB_CPID(mp1) = tcp->tcp_cpid;
13506 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
13507 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13508 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13509 		}
13510 		freemsg(mp);
13511 		return;
13512 	case TCPS_SYN_RCVD:
13513 		if (flags & TH_ACK) {
13514 			/*
13515 			 * In this state, a SYN|ACK packet is either bogus
13516 			 * because the other side must be ACKing our SYN which
13517 			 * indicates it has seen the ACK for their SYN and
13518 			 * shouldn't retransmit it or we're crossing SYNs
13519 			 * on active open.
13520 			 */
13521 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13522 				freemsg(mp);
13523 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13524 				    tcp, seg_ack, 0, TH_RST);
13525 				return;
13526 			}
13527 			/*
13528 			 * NOTE: RFC 793 pg. 72 says this should be
13529 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13530 			 * but that would mean we have an ack that ignored
13531 			 * our SYN.
13532 			 */
13533 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13534 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13535 				freemsg(mp);
13536 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13537 				    tcp, seg_ack, 0, TH_RST);
13538 				return;
13539 			}
13540 		}
13541 		break;
13542 	case TCPS_LISTEN:
13543 		/*
13544 		 * Only a TLI listener can come through this path when a
13545 		 * acceptor is going back to be a listener and a packet
13546 		 * for the acceptor hits the classifier. For a socket
13547 		 * listener, this can never happen because a listener
13548 		 * can never accept connection on itself and hence a
13549 		 * socket acceptor can not go back to being a listener.
13550 		 */
13551 		ASSERT(!TCP_IS_SOCKET(tcp));
13552 		/*FALLTHRU*/
13553 	case TCPS_CLOSED:
13554 	case TCPS_BOUND: {
13555 		conn_t	*new_connp;
13556 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13557 
13558 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13559 		if (new_connp != NULL) {
13560 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13561 			return;
13562 		}
13563 		/* We failed to classify. For now just drop the packet */
13564 		freemsg(mp);
13565 		return;
13566 	}
13567 	case TCPS_IDLE:
13568 		/*
13569 		 * Handle the case where the tcp_clean_death() has happened
13570 		 * on a connection (application hasn't closed yet) but a packet
13571 		 * was already queued on squeue before tcp_clean_death()
13572 		 * was processed. Calling tcp_clean_death() twice on same
13573 		 * connection can result in weird behaviour.
13574 		 */
13575 		freemsg(mp);
13576 		return;
13577 	default:
13578 		break;
13579 	}
13580 
13581 	/*
13582 	 * Already on the correct queue/perimeter.
13583 	 * If this is a detached connection and not an eager
13584 	 * connection hanging off a listener then new data
13585 	 * (past the FIN) will cause a reset.
13586 	 * We do a special check here where it
13587 	 * is out of the main line, rather than check
13588 	 * if we are detached every time we see new
13589 	 * data down below.
13590 	 */
13591 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13592 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13593 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13594 		TCP_RECORD_TRACE(tcp,
13595 		    mp, TCP_TRACE_RECV_PKT);
13596 
13597 		freemsg(mp);
13598 		/*
13599 		 * This could be an SSL closure alert. We're detached so just
13600 		 * acknowledge it this last time.
13601 		 */
13602 		if (tcp->tcp_kssl_ctx != NULL) {
13603 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13604 			tcp->tcp_kssl_ctx = NULL;
13605 
13606 			tcp->tcp_rnxt += seg_len;
13607 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13608 			flags |= TH_ACK_NEEDED;
13609 			goto ack_check;
13610 		}
13611 
13612 		tcp_xmit_ctl("new data when detached", tcp,
13613 		    tcp->tcp_snxt, 0, TH_RST);
13614 		(void) tcp_clean_death(tcp, EPROTO, 12);
13615 		return;
13616 	}
13617 
13618 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13619 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13620 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13621 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13622 
13623 	if (tcp->tcp_snd_ts_ok) {
13624 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13625 			/*
13626 			 * This segment is not acceptable.
13627 			 * Drop it and send back an ACK.
13628 			 */
13629 			freemsg(mp);
13630 			flags |= TH_ACK_NEEDED;
13631 			goto ack_check;
13632 		}
13633 	} else if (tcp->tcp_snd_sack_ok) {
13634 		ASSERT(tcp->tcp_sack_info != NULL);
13635 		tcpopt.tcp = tcp;
13636 		/*
13637 		 * SACK info in already updated in tcp_parse_options.  Ignore
13638 		 * all other TCP options...
13639 		 */
13640 		(void) tcp_parse_options(tcph, &tcpopt);
13641 	}
13642 try_again:;
13643 	mss = tcp->tcp_mss;
13644 	gap = seg_seq - tcp->tcp_rnxt;
13645 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13646 	/*
13647 	 * gap is the amount of sequence space between what we expect to see
13648 	 * and what we got for seg_seq.  A positive value for gap means
13649 	 * something got lost.  A negative value means we got some old stuff.
13650 	 */
13651 	if (gap < 0) {
13652 		/* Old stuff present.  Is the SYN in there? */
13653 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13654 		    (seg_len != 0)) {
13655 			flags &= ~TH_SYN;
13656 			seg_seq++;
13657 			urp--;
13658 			/* Recompute the gaps after noting the SYN. */
13659 			goto try_again;
13660 		}
13661 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13662 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13663 		    (seg_len > -gap ? -gap : seg_len));
13664 		/* Remove the old stuff from seg_len. */
13665 		seg_len += gap;
13666 		/*
13667 		 * Anything left?
13668 		 * Make sure to check for unack'd FIN when rest of data
13669 		 * has been previously ack'd.
13670 		 */
13671 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13672 			/*
13673 			 * Resets are only valid if they lie within our offered
13674 			 * window.  If the RST bit is set, we just ignore this
13675 			 * segment.
13676 			 */
13677 			if (flags & TH_RST) {
13678 				freemsg(mp);
13679 				return;
13680 			}
13681 
13682 			/*
13683 			 * The arriving of dup data packets indicate that we
13684 			 * may have postponed an ack for too long, or the other
13685 			 * side's RTT estimate is out of shape. Start acking
13686 			 * more often.
13687 			 */
13688 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13689 			    tcp->tcp_rack_cnt >= 1 &&
13690 			    tcp->tcp_rack_abs_max > 2) {
13691 				tcp->tcp_rack_abs_max--;
13692 			}
13693 			tcp->tcp_rack_cur_max = 1;
13694 
13695 			/*
13696 			 * This segment is "unacceptable".  None of its
13697 			 * sequence space lies within our advertized window.
13698 			 *
13699 			 * Adjust seg_len to the original value for tracing.
13700 			 */
13701 			seg_len -= gap;
13702 			if (tcp->tcp_debug) {
13703 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13704 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13705 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13706 				    "seg_len %d, rnxt %u, snxt %u, %s",
13707 				    gap, rgap, flags, seg_seq, seg_ack,
13708 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13709 				    tcp_display(tcp, NULL,
13710 				    DISP_ADDR_AND_PORT));
13711 			}
13712 
13713 			/*
13714 			 * Arrange to send an ACK in response to the
13715 			 * unacceptable segment per RFC 793 page 69. There
13716 			 * is only one small difference between ours and the
13717 			 * acceptability test in the RFC - we accept ACK-only
13718 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13719 			 * will be generated.
13720 			 *
13721 			 * Note that we have to ACK an ACK-only packet at least
13722 			 * for stacks that send 0-length keep-alives with
13723 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13724 			 * section 4.2.3.6. As long as we don't ever generate
13725 			 * an unacceptable packet in response to an incoming
13726 			 * packet that is unacceptable, it should not cause
13727 			 * "ACK wars".
13728 			 */
13729 			flags |=  TH_ACK_NEEDED;
13730 
13731 			/*
13732 			 * Continue processing this segment in order to use the
13733 			 * ACK information it contains, but skip all other
13734 			 * sequence-number processing.	Processing the ACK
13735 			 * information is necessary in order to
13736 			 * re-synchronize connections that may have lost
13737 			 * synchronization.
13738 			 *
13739 			 * We clear seg_len and flag fields related to
13740 			 * sequence number processing as they are not
13741 			 * to be trusted for an unacceptable segment.
13742 			 */
13743 			seg_len = 0;
13744 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13745 			goto process_ack;
13746 		}
13747 
13748 		/* Fix seg_seq, and chew the gap off the front. */
13749 		seg_seq = tcp->tcp_rnxt;
13750 		urp += gap;
13751 		do {
13752 			mblk_t	*mp2;
13753 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13754 			    (uintptr_t)UINT_MAX);
13755 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13756 			if (gap > 0) {
13757 				mp->b_rptr = mp->b_wptr - gap;
13758 				break;
13759 			}
13760 			mp2 = mp;
13761 			mp = mp->b_cont;
13762 			freeb(mp2);
13763 		} while (gap < 0);
13764 		/*
13765 		 * If the urgent data has already been acknowledged, we
13766 		 * should ignore TH_URG below
13767 		 */
13768 		if (urp < 0)
13769 			flags &= ~TH_URG;
13770 	}
13771 	/*
13772 	 * rgap is the amount of stuff received out of window.  A negative
13773 	 * value is the amount out of window.
13774 	 */
13775 	if (rgap < 0) {
13776 		mblk_t	*mp2;
13777 
13778 		if (tcp->tcp_rwnd == 0) {
13779 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13780 		} else {
13781 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13782 			UPDATE_MIB(&tcps->tcps_mib,
13783 			    tcpInDataPastWinBytes, -rgap);
13784 		}
13785 
13786 		/*
13787 		 * seg_len does not include the FIN, so if more than
13788 		 * just the FIN is out of window, we act like we don't
13789 		 * see it.  (If just the FIN is out of window, rgap
13790 		 * will be zero and we will go ahead and acknowledge
13791 		 * the FIN.)
13792 		 */
13793 		flags &= ~TH_FIN;
13794 
13795 		/* Fix seg_len and make sure there is something left. */
13796 		seg_len += rgap;
13797 		if (seg_len <= 0) {
13798 			/*
13799 			 * Resets are only valid if they lie within our offered
13800 			 * window.  If the RST bit is set, we just ignore this
13801 			 * segment.
13802 			 */
13803 			if (flags & TH_RST) {
13804 				freemsg(mp);
13805 				return;
13806 			}
13807 
13808 			/* Per RFC 793, we need to send back an ACK. */
13809 			flags |= TH_ACK_NEEDED;
13810 
13811 			/*
13812 			 * Send SIGURG as soon as possible i.e. even
13813 			 * if the TH_URG was delivered in a window probe
13814 			 * packet (which will be unacceptable).
13815 			 *
13816 			 * We generate a signal if none has been generated
13817 			 * for this connection or if this is a new urgent
13818 			 * byte. Also send a zero-length "unmarked" message
13819 			 * to inform SIOCATMARK that this is not the mark.
13820 			 *
13821 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13822 			 * is sent up. This plus the check for old data
13823 			 * (gap >= 0) handles the wraparound of the sequence
13824 			 * number space without having to always track the
13825 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13826 			 * this max in its rcv_up variable).
13827 			 *
13828 			 * This prevents duplicate SIGURGS due to a "late"
13829 			 * zero-window probe when the T_EXDATA_IND has already
13830 			 * been sent up.
13831 			 */
13832 			if ((flags & TH_URG) &&
13833 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13834 			    tcp->tcp_urp_last))) {
13835 				mp1 = allocb(0, BPRI_MED);
13836 				if (mp1 == NULL) {
13837 					freemsg(mp);
13838 					return;
13839 				}
13840 				if (!TCP_IS_DETACHED(tcp) &&
13841 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13842 				    SIGURG)) {
13843 					/* Try again on the rexmit. */
13844 					freemsg(mp1);
13845 					freemsg(mp);
13846 					return;
13847 				}
13848 				/*
13849 				 * If the next byte would be the mark
13850 				 * then mark with MARKNEXT else mark
13851 				 * with NOTMARKNEXT.
13852 				 */
13853 				if (gap == 0 && urp == 0)
13854 					mp1->b_flag |= MSGMARKNEXT;
13855 				else
13856 					mp1->b_flag |= MSGNOTMARKNEXT;
13857 				freemsg(tcp->tcp_urp_mark_mp);
13858 				tcp->tcp_urp_mark_mp = mp1;
13859 				flags |= TH_SEND_URP_MARK;
13860 				tcp->tcp_urp_last_valid = B_TRUE;
13861 				tcp->tcp_urp_last = urp + seg_seq;
13862 			}
13863 			/*
13864 			 * If this is a zero window probe, continue to
13865 			 * process the ACK part.  But we need to set seg_len
13866 			 * to 0 to avoid data processing.  Otherwise just
13867 			 * drop the segment and send back an ACK.
13868 			 */
13869 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13870 				flags &= ~(TH_SYN | TH_URG);
13871 				seg_len = 0;
13872 				goto process_ack;
13873 			} else {
13874 				freemsg(mp);
13875 				goto ack_check;
13876 			}
13877 		}
13878 		/* Pitch out of window stuff off the end. */
13879 		rgap = seg_len;
13880 		mp2 = mp;
13881 		do {
13882 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13883 			    (uintptr_t)INT_MAX);
13884 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13885 			if (rgap < 0) {
13886 				mp2->b_wptr += rgap;
13887 				if ((mp1 = mp2->b_cont) != NULL) {
13888 					mp2->b_cont = NULL;
13889 					freemsg(mp1);
13890 				}
13891 				break;
13892 			}
13893 		} while ((mp2 = mp2->b_cont) != NULL);
13894 	}
13895 ok:;
13896 	/*
13897 	 * TCP should check ECN info for segments inside the window only.
13898 	 * Therefore the check should be done here.
13899 	 */
13900 	if (tcp->tcp_ecn_ok) {
13901 		if (flags & TH_CWR) {
13902 			tcp->tcp_ecn_echo_on = B_FALSE;
13903 		}
13904 		/*
13905 		 * Note that both ECN_CE and CWR can be set in the
13906 		 * same segment.  In this case, we once again turn
13907 		 * on ECN_ECHO.
13908 		 */
13909 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13910 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13911 
13912 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13913 				tcp->tcp_ecn_echo_on = B_TRUE;
13914 			}
13915 		} else {
13916 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13917 
13918 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13919 			    htonl(IPH_ECN_CE << 20)) {
13920 				tcp->tcp_ecn_echo_on = B_TRUE;
13921 			}
13922 		}
13923 	}
13924 
13925 	/*
13926 	 * Check whether we can update tcp_ts_recent.  This test is
13927 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13928 	 * Extensions for High Performance: An Update", Internet Draft.
13929 	 */
13930 	if (tcp->tcp_snd_ts_ok &&
13931 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13932 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13933 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13934 		tcp->tcp_last_rcv_lbolt = lbolt64;
13935 	}
13936 
13937 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13938 		/*
13939 		 * FIN in an out of order segment.  We record this in
13940 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13941 		 * Clear the FIN so that any check on FIN flag will fail.
13942 		 * Remember that FIN also counts in the sequence number
13943 		 * space.  So we need to ack out of order FIN only segments.
13944 		 */
13945 		if (flags & TH_FIN) {
13946 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13947 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13948 			flags &= ~TH_FIN;
13949 			flags |= TH_ACK_NEEDED;
13950 		}
13951 		if (seg_len > 0) {
13952 			/* Fill in the SACK blk list. */
13953 			if (tcp->tcp_snd_sack_ok) {
13954 				ASSERT(tcp->tcp_sack_info != NULL);
13955 				tcp_sack_insert(tcp->tcp_sack_list,
13956 				    seg_seq, seg_seq + seg_len,
13957 				    &(tcp->tcp_num_sack_blk));
13958 			}
13959 
13960 			/*
13961 			 * Attempt reassembly and see if we have something
13962 			 * ready to go.
13963 			 */
13964 			mp = tcp_reass(tcp, mp, seg_seq);
13965 			/* Always ack out of order packets */
13966 			flags |= TH_ACK_NEEDED | TH_PUSH;
13967 			if (mp) {
13968 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13969 				    (uintptr_t)INT_MAX);
13970 				seg_len = mp->b_cont ? msgdsize(mp) :
13971 				    (int)(mp->b_wptr - mp->b_rptr);
13972 				seg_seq = tcp->tcp_rnxt;
13973 				/*
13974 				 * A gap is filled and the seq num and len
13975 				 * of the gap match that of a previously
13976 				 * received FIN, put the FIN flag back in.
13977 				 */
13978 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13979 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13980 					flags |= TH_FIN;
13981 					tcp->tcp_valid_bits &=
13982 					    ~TCP_OFO_FIN_VALID;
13983 				}
13984 			} else {
13985 				/*
13986 				 * Keep going even with NULL mp.
13987 				 * There may be a useful ACK or something else
13988 				 * we don't want to miss.
13989 				 *
13990 				 * But TCP should not perform fast retransmit
13991 				 * because of the ack number.  TCP uses
13992 				 * seg_len == 0 to determine if it is a pure
13993 				 * ACK.  And this is not a pure ACK.
13994 				 */
13995 				seg_len = 0;
13996 				ofo_seg = B_TRUE;
13997 			}
13998 		}
13999 	} else if (seg_len > 0) {
14000 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
14001 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
14002 		/*
14003 		 * If an out of order FIN was received before, and the seq
14004 		 * num and len of the new segment match that of the FIN,
14005 		 * put the FIN flag back in.
14006 		 */
14007 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
14008 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
14009 			flags |= TH_FIN;
14010 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
14011 		}
14012 	}
14013 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
14014 	if (flags & TH_RST) {
14015 		freemsg(mp);
14016 		switch (tcp->tcp_state) {
14017 		case TCPS_SYN_RCVD:
14018 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
14019 			break;
14020 		case TCPS_ESTABLISHED:
14021 		case TCPS_FIN_WAIT_1:
14022 		case TCPS_FIN_WAIT_2:
14023 		case TCPS_CLOSE_WAIT:
14024 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
14025 			break;
14026 		case TCPS_CLOSING:
14027 		case TCPS_LAST_ACK:
14028 			(void) tcp_clean_death(tcp, 0, 16);
14029 			break;
14030 		default:
14031 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14032 			(void) tcp_clean_death(tcp, ENXIO, 17);
14033 			break;
14034 		}
14035 		return;
14036 	}
14037 	if (flags & TH_SYN) {
14038 		/*
14039 		 * See RFC 793, Page 71
14040 		 *
14041 		 * The seq number must be in the window as it should
14042 		 * be "fixed" above.  If it is outside window, it should
14043 		 * be already rejected.  Note that we allow seg_seq to be
14044 		 * rnxt + rwnd because we want to accept 0 window probe.
14045 		 */
14046 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
14047 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
14048 		freemsg(mp);
14049 		/*
14050 		 * If the ACK flag is not set, just use our snxt as the
14051 		 * seq number of the RST segment.
14052 		 */
14053 		if (!(flags & TH_ACK)) {
14054 			seg_ack = tcp->tcp_snxt;
14055 		}
14056 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
14057 		    TH_RST|TH_ACK);
14058 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14059 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
14060 		return;
14061 	}
14062 	/*
14063 	 * urp could be -1 when the urp field in the packet is 0
14064 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
14065 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
14066 	 */
14067 	if (flags & TH_URG && urp >= 0) {
14068 		if (!tcp->tcp_urp_last_valid ||
14069 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
14070 			/*
14071 			 * If we haven't generated the signal yet for this
14072 			 * urgent pointer value, do it now.  Also, send up a
14073 			 * zero-length M_DATA indicating whether or not this is
14074 			 * the mark. The latter is not needed when a
14075 			 * T_EXDATA_IND is sent up. However, if there are
14076 			 * allocation failures this code relies on the sender
14077 			 * retransmitting and the socket code for determining
14078 			 * the mark should not block waiting for the peer to
14079 			 * transmit. Thus, for simplicity we always send up the
14080 			 * mark indication.
14081 			 */
14082 			mp1 = allocb(0, BPRI_MED);
14083 			if (mp1 == NULL) {
14084 				freemsg(mp);
14085 				return;
14086 			}
14087 			if (!TCP_IS_DETACHED(tcp) &&
14088 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
14089 				/* Try again on the rexmit. */
14090 				freemsg(mp1);
14091 				freemsg(mp);
14092 				return;
14093 			}
14094 			/*
14095 			 * Mark with NOTMARKNEXT for now.
14096 			 * The code below will change this to MARKNEXT
14097 			 * if we are at the mark.
14098 			 *
14099 			 * If there are allocation failures (e.g. in dupmsg
14100 			 * below) the next time tcp_rput_data sees the urgent
14101 			 * segment it will send up the MSG*MARKNEXT message.
14102 			 */
14103 			mp1->b_flag |= MSGNOTMARKNEXT;
14104 			freemsg(tcp->tcp_urp_mark_mp);
14105 			tcp->tcp_urp_mark_mp = mp1;
14106 			flags |= TH_SEND_URP_MARK;
14107 #ifdef DEBUG
14108 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14109 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
14110 			    "last %x, %s",
14111 			    seg_seq, urp, tcp->tcp_urp_last,
14112 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14113 #endif /* DEBUG */
14114 			tcp->tcp_urp_last_valid = B_TRUE;
14115 			tcp->tcp_urp_last = urp + seg_seq;
14116 		} else if (tcp->tcp_urp_mark_mp != NULL) {
14117 			/*
14118 			 * An allocation failure prevented the previous
14119 			 * tcp_rput_data from sending up the allocated
14120 			 * MSG*MARKNEXT message - send it up this time
14121 			 * around.
14122 			 */
14123 			flags |= TH_SEND_URP_MARK;
14124 		}
14125 
14126 		/*
14127 		 * If the urgent byte is in this segment, make sure that it is
14128 		 * all by itself.  This makes it much easier to deal with the
14129 		 * possibility of an allocation failure on the T_exdata_ind.
14130 		 * Note that seg_len is the number of bytes in the segment, and
14131 		 * urp is the offset into the segment of the urgent byte.
14132 		 * urp < seg_len means that the urgent byte is in this segment.
14133 		 */
14134 		if (urp < seg_len) {
14135 			if (seg_len != 1) {
14136 				uint32_t  tmp_rnxt;
14137 				/*
14138 				 * Break it up and feed it back in.
14139 				 * Re-attach the IP header.
14140 				 */
14141 				mp->b_rptr = iphdr;
14142 				if (urp > 0) {
14143 					/*
14144 					 * There is stuff before the urgent
14145 					 * byte.
14146 					 */
14147 					mp1 = dupmsg(mp);
14148 					if (!mp1) {
14149 						/*
14150 						 * Trim from urgent byte on.
14151 						 * The rest will come back.
14152 						 */
14153 						(void) adjmsg(mp,
14154 						    urp - seg_len);
14155 						tcp_rput_data(connp,
14156 						    mp, NULL);
14157 						return;
14158 					}
14159 					(void) adjmsg(mp1, urp - seg_len);
14160 					/* Feed this piece back in. */
14161 					tmp_rnxt = tcp->tcp_rnxt;
14162 					tcp_rput_data(connp, mp1, NULL);
14163 					/*
14164 					 * If the data passed back in was not
14165 					 * processed (ie: bad ACK) sending
14166 					 * the remainder back in will cause a
14167 					 * loop. In this case, drop the
14168 					 * packet and let the sender try
14169 					 * sending a good packet.
14170 					 */
14171 					if (tmp_rnxt == tcp->tcp_rnxt) {
14172 						freemsg(mp);
14173 						return;
14174 					}
14175 				}
14176 				if (urp != seg_len - 1) {
14177 					uint32_t  tmp_rnxt;
14178 					/*
14179 					 * There is stuff after the urgent
14180 					 * byte.
14181 					 */
14182 					mp1 = dupmsg(mp);
14183 					if (!mp1) {
14184 						/*
14185 						 * Trim everything beyond the
14186 						 * urgent byte.  The rest will
14187 						 * come back.
14188 						 */
14189 						(void) adjmsg(mp,
14190 						    urp + 1 - seg_len);
14191 						tcp_rput_data(connp,
14192 						    mp, NULL);
14193 						return;
14194 					}
14195 					(void) adjmsg(mp1, urp + 1 - seg_len);
14196 					tmp_rnxt = tcp->tcp_rnxt;
14197 					tcp_rput_data(connp, mp1, NULL);
14198 					/*
14199 					 * If the data passed back in was not
14200 					 * processed (ie: bad ACK) sending
14201 					 * the remainder back in will cause a
14202 					 * loop. In this case, drop the
14203 					 * packet and let the sender try
14204 					 * sending a good packet.
14205 					 */
14206 					if (tmp_rnxt == tcp->tcp_rnxt) {
14207 						freemsg(mp);
14208 						return;
14209 					}
14210 				}
14211 				tcp_rput_data(connp, mp, NULL);
14212 				return;
14213 			}
14214 			/*
14215 			 * This segment contains only the urgent byte.  We
14216 			 * have to allocate the T_exdata_ind, if we can.
14217 			 */
14218 			if (!tcp->tcp_urp_mp) {
14219 				struct T_exdata_ind *tei;
14220 				mp1 = allocb(sizeof (struct T_exdata_ind),
14221 				    BPRI_MED);
14222 				if (!mp1) {
14223 					/*
14224 					 * Sigh... It'll be back.
14225 					 * Generate any MSG*MARK message now.
14226 					 */
14227 					freemsg(mp);
14228 					seg_len = 0;
14229 					if (flags & TH_SEND_URP_MARK) {
14230 
14231 
14232 						ASSERT(tcp->tcp_urp_mark_mp);
14233 						tcp->tcp_urp_mark_mp->b_flag &=
14234 						    ~MSGNOTMARKNEXT;
14235 						tcp->tcp_urp_mark_mp->b_flag |=
14236 						    MSGMARKNEXT;
14237 					}
14238 					goto ack_check;
14239 				}
14240 				mp1->b_datap->db_type = M_PROTO;
14241 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14242 				tei->PRIM_type = T_EXDATA_IND;
14243 				tei->MORE_flag = 0;
14244 				mp1->b_wptr = (uchar_t *)&tei[1];
14245 				tcp->tcp_urp_mp = mp1;
14246 #ifdef DEBUG
14247 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14248 				    "tcp_rput: allocated exdata_ind %s",
14249 				    tcp_display(tcp, NULL,
14250 				    DISP_PORT_ONLY));
14251 #endif /* DEBUG */
14252 				/*
14253 				 * There is no need to send a separate MSG*MARK
14254 				 * message since the T_EXDATA_IND will be sent
14255 				 * now.
14256 				 */
14257 				flags &= ~TH_SEND_URP_MARK;
14258 				freemsg(tcp->tcp_urp_mark_mp);
14259 				tcp->tcp_urp_mark_mp = NULL;
14260 			}
14261 			/*
14262 			 * Now we are all set.  On the next putnext upstream,
14263 			 * tcp_urp_mp will be non-NULL and will get prepended
14264 			 * to what has to be this piece containing the urgent
14265 			 * byte.  If for any reason we abort this segment below,
14266 			 * if it comes back, we will have this ready, or it
14267 			 * will get blown off in close.
14268 			 */
14269 		} else if (urp == seg_len) {
14270 			/*
14271 			 * The urgent byte is the next byte after this sequence
14272 			 * number. If there is data it is marked with
14273 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14274 			 * since it is not needed. Otherwise, if the code
14275 			 * above just allocated a zero-length tcp_urp_mark_mp
14276 			 * message, that message is tagged with MSGMARKNEXT.
14277 			 * Sending up these MSGMARKNEXT messages makes
14278 			 * SIOCATMARK work correctly even though
14279 			 * the T_EXDATA_IND will not be sent up until the
14280 			 * urgent byte arrives.
14281 			 */
14282 			if (seg_len != 0) {
14283 				flags |= TH_MARKNEXT_NEEDED;
14284 				freemsg(tcp->tcp_urp_mark_mp);
14285 				tcp->tcp_urp_mark_mp = NULL;
14286 				flags &= ~TH_SEND_URP_MARK;
14287 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14288 				flags |= TH_SEND_URP_MARK;
14289 				tcp->tcp_urp_mark_mp->b_flag &=
14290 				    ~MSGNOTMARKNEXT;
14291 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14292 			}
14293 #ifdef DEBUG
14294 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14295 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14296 			    seg_len, flags,
14297 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14298 #endif /* DEBUG */
14299 		} else {
14300 			/* Data left until we hit mark */
14301 #ifdef DEBUG
14302 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14303 			    "tcp_rput: URP %d bytes left, %s",
14304 			    urp - seg_len, tcp_display(tcp, NULL,
14305 			    DISP_PORT_ONLY));
14306 #endif /* DEBUG */
14307 		}
14308 	}
14309 
14310 process_ack:
14311 	if (!(flags & TH_ACK)) {
14312 		freemsg(mp);
14313 		goto xmit_check;
14314 	}
14315 	}
14316 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14317 
14318 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14319 		tcp->tcp_ip_forward_progress = B_TRUE;
14320 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14321 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
14322 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
14323 			/* 3-way handshake complete - pass up the T_CONN_IND */
14324 			tcp_t	*listener = tcp->tcp_listener;
14325 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14326 
14327 			tcp->tcp_tconnind_started = B_TRUE;
14328 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14329 			/*
14330 			 * We are here means eager is fine but it can
14331 			 * get a TH_RST at any point between now and till
14332 			 * accept completes and disappear. We need to
14333 			 * ensure that reference to eager is valid after
14334 			 * we get out of eager's perimeter. So we do
14335 			 * an extra refhold.
14336 			 */
14337 			CONN_INC_REF(connp);
14338 
14339 			/*
14340 			 * The listener also exists because of the refhold
14341 			 * done in tcp_conn_request. Its possible that it
14342 			 * might have closed. We will check that once we
14343 			 * get inside listeners context.
14344 			 */
14345 			CONN_INC_REF(listener->tcp_connp);
14346 			if (listener->tcp_connp->conn_sqp ==
14347 			    connp->conn_sqp) {
14348 				tcp_send_conn_ind(listener->tcp_connp, mp,
14349 				    listener->tcp_connp->conn_sqp);
14350 				CONN_DEC_REF(listener->tcp_connp);
14351 			} else if (!tcp->tcp_loopback) {
14352 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
14353 				    tcp_send_conn_ind,
14354 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
14355 			} else {
14356 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
14357 				    tcp_send_conn_ind, listener->tcp_connp,
14358 				    SQTAG_TCP_CONN_IND);
14359 			}
14360 		}
14361 
14362 		if (tcp->tcp_active_open) {
14363 			/*
14364 			 * We are seeing the final ack in the three way
14365 			 * hand shake of a active open'ed connection
14366 			 * so we must send up a T_CONN_CON
14367 			 */
14368 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14369 				freemsg(mp);
14370 				return;
14371 			}
14372 			/*
14373 			 * Don't fuse the loopback endpoints for
14374 			 * simultaneous active opens.
14375 			 */
14376 			if (tcp->tcp_loopback) {
14377 				TCP_STAT(tcps, tcp_fusion_unfusable);
14378 				tcp->tcp_unfusable = B_TRUE;
14379 			}
14380 		}
14381 
14382 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14383 		bytes_acked--;
14384 		/* SYN was acked - making progress */
14385 		if (tcp->tcp_ipversion == IPV6_VERSION)
14386 			tcp->tcp_ip_forward_progress = B_TRUE;
14387 
14388 		/*
14389 		 * If SYN was retransmitted, need to reset all
14390 		 * retransmission info as this segment will be
14391 		 * treated as a dup ACK.
14392 		 */
14393 		if (tcp->tcp_rexmit) {
14394 			tcp->tcp_rexmit = B_FALSE;
14395 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14396 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14397 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14398 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14399 			tcp->tcp_ms_we_have_waited = 0;
14400 			tcp->tcp_cwnd = mss;
14401 		}
14402 
14403 		/*
14404 		 * We set the send window to zero here.
14405 		 * This is needed if there is data to be
14406 		 * processed already on the queue.
14407 		 * Later (at swnd_update label), the
14408 		 * "new_swnd > tcp_swnd" condition is satisfied
14409 		 * the XMIT_NEEDED flag is set in the current
14410 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14411 		 * called if there is already data on queue in
14412 		 * this state.
14413 		 */
14414 		tcp->tcp_swnd = 0;
14415 
14416 		if (new_swnd > tcp->tcp_max_swnd)
14417 			tcp->tcp_max_swnd = new_swnd;
14418 		tcp->tcp_swl1 = seg_seq;
14419 		tcp->tcp_swl2 = seg_ack;
14420 		tcp->tcp_state = TCPS_ESTABLISHED;
14421 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14422 
14423 		/* Fuse when both sides are in ESTABLISHED state */
14424 		if (tcp->tcp_loopback && do_tcp_fusion)
14425 			tcp_fuse(tcp, iphdr, tcph);
14426 
14427 	}
14428 	/* This code follows 4.4BSD-Lite2 mostly. */
14429 	if (bytes_acked < 0)
14430 		goto est;
14431 
14432 	/*
14433 	 * If TCP is ECN capable and the congestion experience bit is
14434 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14435 	 * done once per window (or more loosely, per RTT).
14436 	 */
14437 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14438 		tcp->tcp_cwr = B_FALSE;
14439 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14440 		if (!tcp->tcp_cwr) {
14441 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14442 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14443 			tcp->tcp_cwnd = npkt * mss;
14444 			/*
14445 			 * If the cwnd is 0, use the timer to clock out
14446 			 * new segments.  This is required by the ECN spec.
14447 			 */
14448 			if (npkt == 0) {
14449 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14450 				/*
14451 				 * This makes sure that when the ACK comes
14452 				 * back, we will increase tcp_cwnd by 1 MSS.
14453 				 */
14454 				tcp->tcp_cwnd_cnt = 0;
14455 			}
14456 			tcp->tcp_cwr = B_TRUE;
14457 			/*
14458 			 * This marks the end of the current window of in
14459 			 * flight data.  That is why we don't use
14460 			 * tcp_suna + tcp_swnd.  Only data in flight can
14461 			 * provide ECN info.
14462 			 */
14463 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14464 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14465 		}
14466 	}
14467 
14468 	mp1 = tcp->tcp_xmit_head;
14469 	if (bytes_acked == 0) {
14470 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14471 			int dupack_cnt;
14472 
14473 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14474 			/*
14475 			 * Fast retransmit.  When we have seen exactly three
14476 			 * identical ACKs while we have unacked data
14477 			 * outstanding we take it as a hint that our peer
14478 			 * dropped something.
14479 			 *
14480 			 * If TCP is retransmitting, don't do fast retransmit.
14481 			 */
14482 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14483 			    ! tcp->tcp_rexmit) {
14484 				/* Do Limited Transmit */
14485 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14486 				    tcps->tcps_dupack_fast_retransmit) {
14487 					/*
14488 					 * RFC 3042
14489 					 *
14490 					 * What we need to do is temporarily
14491 					 * increase tcp_cwnd so that new
14492 					 * data can be sent if it is allowed
14493 					 * by the receive window (tcp_rwnd).
14494 					 * tcp_wput_data() will take care of
14495 					 * the rest.
14496 					 *
14497 					 * If the connection is SACK capable,
14498 					 * only do limited xmit when there
14499 					 * is SACK info.
14500 					 *
14501 					 * Note how tcp_cwnd is incremented.
14502 					 * The first dup ACK will increase
14503 					 * it by 1 MSS.  The second dup ACK
14504 					 * will increase it by 2 MSS.  This
14505 					 * means that only 1 new segment will
14506 					 * be sent for each dup ACK.
14507 					 */
14508 					if (tcp->tcp_unsent > 0 &&
14509 					    (!tcp->tcp_snd_sack_ok ||
14510 					    (tcp->tcp_snd_sack_ok &&
14511 					    tcp->tcp_notsack_list != NULL))) {
14512 						tcp->tcp_cwnd += mss <<
14513 						    (tcp->tcp_dupack_cnt - 1);
14514 						flags |= TH_LIMIT_XMIT;
14515 					}
14516 				} else if (dupack_cnt ==
14517 				    tcps->tcps_dupack_fast_retransmit) {
14518 
14519 				/*
14520 				 * If we have reduced tcp_ssthresh
14521 				 * because of ECN, do not reduce it again
14522 				 * unless it is already one window of data
14523 				 * away.  After one window of data, tcp_cwr
14524 				 * should then be cleared.  Note that
14525 				 * for non ECN capable connection, tcp_cwr
14526 				 * should always be false.
14527 				 *
14528 				 * Adjust cwnd since the duplicate
14529 				 * ack indicates that a packet was
14530 				 * dropped (due to congestion.)
14531 				 */
14532 				if (!tcp->tcp_cwr) {
14533 					npkt = ((tcp->tcp_snxt -
14534 					    tcp->tcp_suna) >> 1) / mss;
14535 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14536 					    mss;
14537 					tcp->tcp_cwnd = (npkt +
14538 					    tcp->tcp_dupack_cnt) * mss;
14539 				}
14540 				if (tcp->tcp_ecn_ok) {
14541 					tcp->tcp_cwr = B_TRUE;
14542 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14543 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14544 				}
14545 
14546 				/*
14547 				 * We do Hoe's algorithm.  Refer to her
14548 				 * paper "Improving the Start-up Behavior
14549 				 * of a Congestion Control Scheme for TCP,"
14550 				 * appeared in SIGCOMM'96.
14551 				 *
14552 				 * Save highest seq no we have sent so far.
14553 				 * Be careful about the invisible FIN byte.
14554 				 */
14555 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14556 				    (tcp->tcp_unsent == 0)) {
14557 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14558 				} else {
14559 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14560 				}
14561 
14562 				/*
14563 				 * Do not allow bursty traffic during.
14564 				 * fast recovery.  Refer to Fall and Floyd's
14565 				 * paper "Simulation-based Comparisons of
14566 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14567 				 * This is a best current practise.
14568 				 */
14569 				tcp->tcp_snd_burst = TCP_CWND_SS;
14570 
14571 				/*
14572 				 * For SACK:
14573 				 * Calculate tcp_pipe, which is the
14574 				 * estimated number of bytes in
14575 				 * network.
14576 				 *
14577 				 * tcp_fack is the highest sack'ed seq num
14578 				 * TCP has received.
14579 				 *
14580 				 * tcp_pipe is explained in the above quoted
14581 				 * Fall and Floyd's paper.  tcp_fack is
14582 				 * explained in Mathis and Mahdavi's
14583 				 * "Forward Acknowledgment: Refining TCP
14584 				 * Congestion Control" in SIGCOMM '96.
14585 				 */
14586 				if (tcp->tcp_snd_sack_ok) {
14587 					ASSERT(tcp->tcp_sack_info != NULL);
14588 					if (tcp->tcp_notsack_list != NULL) {
14589 						tcp->tcp_pipe = tcp->tcp_snxt -
14590 						    tcp->tcp_fack;
14591 						tcp->tcp_sack_snxt = seg_ack;
14592 						flags |= TH_NEED_SACK_REXMIT;
14593 					} else {
14594 						/*
14595 						 * Always initialize tcp_pipe
14596 						 * even though we don't have
14597 						 * any SACK info.  If later
14598 						 * we get SACK info and
14599 						 * tcp_pipe is not initialized,
14600 						 * funny things will happen.
14601 						 */
14602 						tcp->tcp_pipe =
14603 						    tcp->tcp_cwnd_ssthresh;
14604 					}
14605 				} else {
14606 					flags |= TH_REXMIT_NEEDED;
14607 				} /* tcp_snd_sack_ok */
14608 
14609 				} else {
14610 					/*
14611 					 * Here we perform congestion
14612 					 * avoidance, but NOT slow start.
14613 					 * This is known as the Fast
14614 					 * Recovery Algorithm.
14615 					 */
14616 					if (tcp->tcp_snd_sack_ok &&
14617 					    tcp->tcp_notsack_list != NULL) {
14618 						flags |= TH_NEED_SACK_REXMIT;
14619 						tcp->tcp_pipe -= mss;
14620 						if (tcp->tcp_pipe < 0)
14621 							tcp->tcp_pipe = 0;
14622 					} else {
14623 					/*
14624 					 * We know that one more packet has
14625 					 * left the pipe thus we can update
14626 					 * cwnd.
14627 					 */
14628 					cwnd = tcp->tcp_cwnd + mss;
14629 					if (cwnd > tcp->tcp_cwnd_max)
14630 						cwnd = tcp->tcp_cwnd_max;
14631 					tcp->tcp_cwnd = cwnd;
14632 					if (tcp->tcp_unsent > 0)
14633 						flags |= TH_XMIT_NEEDED;
14634 					}
14635 				}
14636 			}
14637 		} else if (tcp->tcp_zero_win_probe) {
14638 			/*
14639 			 * If the window has opened, need to arrange
14640 			 * to send additional data.
14641 			 */
14642 			if (new_swnd != 0) {
14643 				/* tcp_suna != tcp_snxt */
14644 				/* Packet contains a window update */
14645 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14646 				tcp->tcp_zero_win_probe = 0;
14647 				tcp->tcp_timer_backoff = 0;
14648 				tcp->tcp_ms_we_have_waited = 0;
14649 
14650 				/*
14651 				 * Transmit starting with tcp_suna since
14652 				 * the one byte probe is not ack'ed.
14653 				 * If TCP has sent more than one identical
14654 				 * probe, tcp_rexmit will be set.  That means
14655 				 * tcp_ss_rexmit() will send out the one
14656 				 * byte along with new data.  Otherwise,
14657 				 * fake the retransmission.
14658 				 */
14659 				flags |= TH_XMIT_NEEDED;
14660 				if (!tcp->tcp_rexmit) {
14661 					tcp->tcp_rexmit = B_TRUE;
14662 					tcp->tcp_dupack_cnt = 0;
14663 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14664 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14665 				}
14666 			}
14667 		}
14668 		goto swnd_update;
14669 	}
14670 
14671 	/*
14672 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14673 	 * If the ACK value acks something that we have not yet sent, it might
14674 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14675 	 * other side.
14676 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14677 	 * state is handled above, so we can always just drop the segment and
14678 	 * send an ACK here.
14679 	 *
14680 	 * Should we send ACKs in response to ACK only segments?
14681 	 */
14682 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14683 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14684 		/* drop the received segment */
14685 		freemsg(mp);
14686 
14687 		/*
14688 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14689 		 * greater than 0, check if the number of such
14690 		 * bogus ACks is greater than that count.  If yes,
14691 		 * don't send back any ACK.  This prevents TCP from
14692 		 * getting into an ACK storm if somehow an attacker
14693 		 * successfully spoofs an acceptable segment to our
14694 		 * peer.
14695 		 */
14696 		if (tcp_drop_ack_unsent_cnt > 0 &&
14697 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14698 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14699 			return;
14700 		}
14701 		mp = tcp_ack_mp(tcp);
14702 		if (mp != NULL) {
14703 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
14704 			BUMP_LOCAL(tcp->tcp_obsegs);
14705 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14706 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14707 		}
14708 		return;
14709 	}
14710 
14711 	/*
14712 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14713 	 * blocks that are covered by this ACK.
14714 	 */
14715 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14716 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14717 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14718 	}
14719 
14720 	/*
14721 	 * If we got an ACK after fast retransmit, check to see
14722 	 * if it is a partial ACK.  If it is not and the congestion
14723 	 * window was inflated to account for the other side's
14724 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14725 	 */
14726 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14727 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14728 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14729 			tcp->tcp_dupack_cnt = 0;
14730 			/*
14731 			 * Restore the orig tcp_cwnd_ssthresh after
14732 			 * fast retransmit phase.
14733 			 */
14734 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14735 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14736 			}
14737 			tcp->tcp_rexmit_max = seg_ack;
14738 			tcp->tcp_cwnd_cnt = 0;
14739 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14740 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14741 
14742 			/*
14743 			 * Remove all notsack info to avoid confusion with
14744 			 * the next fast retrasnmit/recovery phase.
14745 			 */
14746 			if (tcp->tcp_snd_sack_ok &&
14747 			    tcp->tcp_notsack_list != NULL) {
14748 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14749 			}
14750 		} else {
14751 			if (tcp->tcp_snd_sack_ok &&
14752 			    tcp->tcp_notsack_list != NULL) {
14753 				flags |= TH_NEED_SACK_REXMIT;
14754 				tcp->tcp_pipe -= mss;
14755 				if (tcp->tcp_pipe < 0)
14756 					tcp->tcp_pipe = 0;
14757 			} else {
14758 				/*
14759 				 * Hoe's algorithm:
14760 				 *
14761 				 * Retransmit the unack'ed segment and
14762 				 * restart fast recovery.  Note that we
14763 				 * need to scale back tcp_cwnd to the
14764 				 * original value when we started fast
14765 				 * recovery.  This is to prevent overly
14766 				 * aggressive behaviour in sending new
14767 				 * segments.
14768 				 */
14769 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14770 				    tcps->tcps_dupack_fast_retransmit * mss;
14771 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14772 				flags |= TH_REXMIT_NEEDED;
14773 			}
14774 		}
14775 	} else {
14776 		tcp->tcp_dupack_cnt = 0;
14777 		if (tcp->tcp_rexmit) {
14778 			/*
14779 			 * TCP is retranmitting.  If the ACK ack's all
14780 			 * outstanding data, update tcp_rexmit_max and
14781 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14782 			 * to the correct value.
14783 			 *
14784 			 * Note that SEQ_LEQ() is used.  This is to avoid
14785 			 * unnecessary fast retransmit caused by dup ACKs
14786 			 * received when TCP does slow start retransmission
14787 			 * after a time out.  During this phase, TCP may
14788 			 * send out segments which are already received.
14789 			 * This causes dup ACKs to be sent back.
14790 			 */
14791 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14792 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14793 					tcp->tcp_rexmit_nxt = seg_ack;
14794 				}
14795 				if (seg_ack != tcp->tcp_rexmit_max) {
14796 					flags |= TH_XMIT_NEEDED;
14797 				}
14798 			} else {
14799 				tcp->tcp_rexmit = B_FALSE;
14800 				tcp->tcp_xmit_zc_clean = B_FALSE;
14801 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14802 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14803 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14804 			}
14805 			tcp->tcp_ms_we_have_waited = 0;
14806 		}
14807 	}
14808 
14809 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14810 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14811 	tcp->tcp_suna = seg_ack;
14812 	if (tcp->tcp_zero_win_probe != 0) {
14813 		tcp->tcp_zero_win_probe = 0;
14814 		tcp->tcp_timer_backoff = 0;
14815 	}
14816 
14817 	/*
14818 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14819 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14820 	 * will not reach here.
14821 	 */
14822 	if (mp1 == NULL) {
14823 		goto fin_acked;
14824 	}
14825 
14826 	/*
14827 	 * Update the congestion window.
14828 	 *
14829 	 * If TCP is not ECN capable or TCP is ECN capable but the
14830 	 * congestion experience bit is not set, increase the tcp_cwnd as
14831 	 * usual.
14832 	 */
14833 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14834 		cwnd = tcp->tcp_cwnd;
14835 		add = mss;
14836 
14837 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14838 			/*
14839 			 * This is to prevent an increase of less than 1 MSS of
14840 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14841 			 * may send out tinygrams in order to preserve mblk
14842 			 * boundaries.
14843 			 *
14844 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14845 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14846 			 * increased by 1 MSS for every RTTs.
14847 			 */
14848 			if (tcp->tcp_cwnd_cnt <= 0) {
14849 				tcp->tcp_cwnd_cnt = cwnd + add;
14850 			} else {
14851 				tcp->tcp_cwnd_cnt -= add;
14852 				add = 0;
14853 			}
14854 		}
14855 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14856 	}
14857 
14858 	/* See if the latest urgent data has been acknowledged */
14859 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14860 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14861 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14862 
14863 	/* Can we update the RTT estimates? */
14864 	if (tcp->tcp_snd_ts_ok) {
14865 		/* Ignore zero timestamp echo-reply. */
14866 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14867 			tcp_set_rto(tcp, (int32_t)lbolt -
14868 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14869 		}
14870 
14871 		/* If needed, restart the timer. */
14872 		if (tcp->tcp_set_timer == 1) {
14873 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14874 			tcp->tcp_set_timer = 0;
14875 		}
14876 		/*
14877 		 * Update tcp_csuna in case the other side stops sending
14878 		 * us timestamps.
14879 		 */
14880 		tcp->tcp_csuna = tcp->tcp_snxt;
14881 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14882 		/*
14883 		 * An ACK sequence we haven't seen before, so get the RTT
14884 		 * and update the RTO. But first check if the timestamp is
14885 		 * valid to use.
14886 		 */
14887 		if ((mp1->b_next != NULL) &&
14888 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14889 			tcp_set_rto(tcp, (int32_t)lbolt -
14890 			    (int32_t)(intptr_t)mp1->b_prev);
14891 		else
14892 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14893 
14894 		/* Remeber the last sequence to be ACKed */
14895 		tcp->tcp_csuna = seg_ack;
14896 		if (tcp->tcp_set_timer == 1) {
14897 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14898 			tcp->tcp_set_timer = 0;
14899 		}
14900 	} else {
14901 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14902 	}
14903 
14904 	/* Eat acknowledged bytes off the xmit queue. */
14905 	for (;;) {
14906 		mblk_t	*mp2;
14907 		uchar_t	*wptr;
14908 
14909 		wptr = mp1->b_wptr;
14910 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14911 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14912 		if (bytes_acked < 0) {
14913 			mp1->b_rptr = wptr + bytes_acked;
14914 			/*
14915 			 * Set a new timestamp if all the bytes timed by the
14916 			 * old timestamp have been ack'ed.
14917 			 */
14918 			if (SEQ_GT(seg_ack,
14919 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14920 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14921 				mp1->b_next = NULL;
14922 			}
14923 			break;
14924 		}
14925 		mp1->b_next = NULL;
14926 		mp1->b_prev = NULL;
14927 		mp2 = mp1;
14928 		mp1 = mp1->b_cont;
14929 
14930 		/*
14931 		 * This notification is required for some zero-copy
14932 		 * clients to maintain a copy semantic. After the data
14933 		 * is ack'ed, client is safe to modify or reuse the buffer.
14934 		 */
14935 		if (tcp->tcp_snd_zcopy_aware &&
14936 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14937 			tcp_zcopy_notify(tcp);
14938 		freeb(mp2);
14939 		if (bytes_acked == 0) {
14940 			if (mp1 == NULL) {
14941 				/* Everything is ack'ed, clear the tail. */
14942 				tcp->tcp_xmit_tail = NULL;
14943 				/*
14944 				 * Cancel the timer unless we are still
14945 				 * waiting for an ACK for the FIN packet.
14946 				 */
14947 				if (tcp->tcp_timer_tid != 0 &&
14948 				    tcp->tcp_snxt == tcp->tcp_suna) {
14949 					(void) TCP_TIMER_CANCEL(tcp,
14950 					    tcp->tcp_timer_tid);
14951 					tcp->tcp_timer_tid = 0;
14952 				}
14953 				goto pre_swnd_update;
14954 			}
14955 			if (mp2 != tcp->tcp_xmit_tail)
14956 				break;
14957 			tcp->tcp_xmit_tail = mp1;
14958 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14959 			    (uintptr_t)INT_MAX);
14960 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14961 			    mp1->b_rptr);
14962 			break;
14963 		}
14964 		if (mp1 == NULL) {
14965 			/*
14966 			 * More was acked but there is nothing more
14967 			 * outstanding.  This means that the FIN was
14968 			 * just acked or that we're talking to a clown.
14969 			 */
14970 fin_acked:
14971 			ASSERT(tcp->tcp_fin_sent);
14972 			tcp->tcp_xmit_tail = NULL;
14973 			if (tcp->tcp_fin_sent) {
14974 				/* FIN was acked - making progress */
14975 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14976 				    !tcp->tcp_fin_acked)
14977 					tcp->tcp_ip_forward_progress = B_TRUE;
14978 				tcp->tcp_fin_acked = B_TRUE;
14979 				if (tcp->tcp_linger_tid != 0 &&
14980 				    TCP_TIMER_CANCEL(tcp,
14981 				    tcp->tcp_linger_tid) >= 0) {
14982 					tcp_stop_lingering(tcp);
14983 					freemsg(mp);
14984 					mp = NULL;
14985 				}
14986 			} else {
14987 				/*
14988 				 * We should never get here because
14989 				 * we have already checked that the
14990 				 * number of bytes ack'ed should be
14991 				 * smaller than or equal to what we
14992 				 * have sent so far (it is the
14993 				 * acceptability check of the ACK).
14994 				 * We can only get here if the send
14995 				 * queue is corrupted.
14996 				 *
14997 				 * Terminate the connection and
14998 				 * panic the system.  It is better
14999 				 * for us to panic instead of
15000 				 * continuing to avoid other disaster.
15001 				 */
15002 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
15003 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
15004 				panic("Memory corruption "
15005 				    "detected for connection %s.",
15006 				    tcp_display(tcp, NULL,
15007 				    DISP_ADDR_AND_PORT));
15008 				/*NOTREACHED*/
15009 			}
15010 			goto pre_swnd_update;
15011 		}
15012 		ASSERT(mp2 != tcp->tcp_xmit_tail);
15013 	}
15014 	if (tcp->tcp_unsent) {
15015 		flags |= TH_XMIT_NEEDED;
15016 	}
15017 pre_swnd_update:
15018 	tcp->tcp_xmit_head = mp1;
15019 swnd_update:
15020 	/*
15021 	 * The following check is different from most other implementations.
15022 	 * For bi-directional transfer, when segments are dropped, the
15023 	 * "normal" check will not accept a window update in those
15024 	 * retransmitted segemnts.  Failing to do that, TCP may send out
15025 	 * segments which are outside receiver's window.  As TCP accepts
15026 	 * the ack in those retransmitted segments, if the window update in
15027 	 * the same segment is not accepted, TCP will incorrectly calculates
15028 	 * that it can send more segments.  This can create a deadlock
15029 	 * with the receiver if its window becomes zero.
15030 	 */
15031 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
15032 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
15033 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
15034 		/*
15035 		 * The criteria for update is:
15036 		 *
15037 		 * 1. the segment acknowledges some data.  Or
15038 		 * 2. the segment is new, i.e. it has a higher seq num. Or
15039 		 * 3. the segment is not old and the advertised window is
15040 		 * larger than the previous advertised window.
15041 		 */
15042 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
15043 			flags |= TH_XMIT_NEEDED;
15044 		tcp->tcp_swnd = new_swnd;
15045 		if (new_swnd > tcp->tcp_max_swnd)
15046 			tcp->tcp_max_swnd = new_swnd;
15047 		tcp->tcp_swl1 = seg_seq;
15048 		tcp->tcp_swl2 = seg_ack;
15049 	}
15050 est:
15051 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
15052 
15053 		switch (tcp->tcp_state) {
15054 		case TCPS_FIN_WAIT_1:
15055 			if (tcp->tcp_fin_acked) {
15056 				tcp->tcp_state = TCPS_FIN_WAIT_2;
15057 				/*
15058 				 * We implement the non-standard BSD/SunOS
15059 				 * FIN_WAIT_2 flushing algorithm.
15060 				 * If there is no user attached to this
15061 				 * TCP endpoint, then this TCP struct
15062 				 * could hang around forever in FIN_WAIT_2
15063 				 * state if the peer forgets to send us
15064 				 * a FIN.  To prevent this, we wait only
15065 				 * 2*MSL (a convenient time value) for
15066 				 * the FIN to arrive.  If it doesn't show up,
15067 				 * we flush the TCP endpoint.  This algorithm,
15068 				 * though a violation of RFC-793, has worked
15069 				 * for over 10 years in BSD systems.
15070 				 * Note: SunOS 4.x waits 675 seconds before
15071 				 * flushing the FIN_WAIT_2 connection.
15072 				 */
15073 				TCP_TIMER_RESTART(tcp,
15074 				    tcps->tcps_fin_wait_2_flush_interval);
15075 			}
15076 			break;
15077 		case TCPS_FIN_WAIT_2:
15078 			break;	/* Shutdown hook? */
15079 		case TCPS_LAST_ACK:
15080 			freemsg(mp);
15081 			if (tcp->tcp_fin_acked) {
15082 				(void) tcp_clean_death(tcp, 0, 19);
15083 				return;
15084 			}
15085 			goto xmit_check;
15086 		case TCPS_CLOSING:
15087 			if (tcp->tcp_fin_acked) {
15088 				tcp->tcp_state = TCPS_TIME_WAIT;
15089 				/*
15090 				 * Unconditionally clear the exclusive binding
15091 				 * bit so this TIME-WAIT connection won't
15092 				 * interfere with new ones.
15093 				 */
15094 				tcp->tcp_exclbind = 0;
15095 				if (!TCP_IS_DETACHED(tcp)) {
15096 					TCP_TIMER_RESTART(tcp,
15097 					    tcps->tcps_time_wait_interval);
15098 				} else {
15099 					tcp_time_wait_append(tcp);
15100 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
15101 				}
15102 			}
15103 			/*FALLTHRU*/
15104 		case TCPS_CLOSE_WAIT:
15105 			freemsg(mp);
15106 			goto xmit_check;
15107 		default:
15108 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
15109 			break;
15110 		}
15111 	}
15112 	if (flags & TH_FIN) {
15113 		/* Make sure we ack the fin */
15114 		flags |= TH_ACK_NEEDED;
15115 		if (!tcp->tcp_fin_rcvd) {
15116 			tcp->tcp_fin_rcvd = B_TRUE;
15117 			tcp->tcp_rnxt++;
15118 			tcph = tcp->tcp_tcph;
15119 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15120 
15121 			/*
15122 			 * Generate the ordrel_ind at the end unless we
15123 			 * are an eager guy.
15124 			 * In the eager case tcp_rsrv will do this when run
15125 			 * after tcp_accept is done.
15126 			 */
15127 			if (tcp->tcp_listener == NULL &&
15128 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
15129 				flags |= TH_ORDREL_NEEDED;
15130 			switch (tcp->tcp_state) {
15131 			case TCPS_SYN_RCVD:
15132 			case TCPS_ESTABLISHED:
15133 				tcp->tcp_state = TCPS_CLOSE_WAIT;
15134 				/* Keepalive? */
15135 				break;
15136 			case TCPS_FIN_WAIT_1:
15137 				if (!tcp->tcp_fin_acked) {
15138 					tcp->tcp_state = TCPS_CLOSING;
15139 					break;
15140 				}
15141 				/* FALLTHRU */
15142 			case TCPS_FIN_WAIT_2:
15143 				tcp->tcp_state = TCPS_TIME_WAIT;
15144 				/*
15145 				 * Unconditionally clear the exclusive binding
15146 				 * bit so this TIME-WAIT connection won't
15147 				 * interfere with new ones.
15148 				 */
15149 				tcp->tcp_exclbind = 0;
15150 				if (!TCP_IS_DETACHED(tcp)) {
15151 					TCP_TIMER_RESTART(tcp,
15152 					    tcps->tcps_time_wait_interval);
15153 				} else {
15154 					tcp_time_wait_append(tcp);
15155 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
15156 				}
15157 				if (seg_len) {
15158 					/*
15159 					 * implies data piggybacked on FIN.
15160 					 * break to handle data.
15161 					 */
15162 					break;
15163 				}
15164 				freemsg(mp);
15165 				goto ack_check;
15166 			}
15167 		}
15168 	}
15169 	if (mp == NULL)
15170 		goto xmit_check;
15171 	if (seg_len == 0) {
15172 		freemsg(mp);
15173 		goto xmit_check;
15174 	}
15175 	if (mp->b_rptr == mp->b_wptr) {
15176 		/*
15177 		 * The header has been consumed, so we remove the
15178 		 * zero-length mblk here.
15179 		 */
15180 		mp1 = mp;
15181 		mp = mp->b_cont;
15182 		freeb(mp1);
15183 	}
15184 	tcph = tcp->tcp_tcph;
15185 	tcp->tcp_rack_cnt++;
15186 	{
15187 		uint32_t cur_max;
15188 
15189 		cur_max = tcp->tcp_rack_cur_max;
15190 		if (tcp->tcp_rack_cnt >= cur_max) {
15191 			/*
15192 			 * We have more unacked data than we should - send
15193 			 * an ACK now.
15194 			 */
15195 			flags |= TH_ACK_NEEDED;
15196 			cur_max++;
15197 			if (cur_max > tcp->tcp_rack_abs_max)
15198 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15199 			else
15200 				tcp->tcp_rack_cur_max = cur_max;
15201 		} else if (TCP_IS_DETACHED(tcp)) {
15202 			/* We don't have an ACK timer for detached TCP. */
15203 			flags |= TH_ACK_NEEDED;
15204 		} else if (seg_len < mss) {
15205 			/*
15206 			 * If we get a segment that is less than an mss, and we
15207 			 * already have unacknowledged data, and the amount
15208 			 * unacknowledged is not a multiple of mss, then we
15209 			 * better generate an ACK now.  Otherwise, this may be
15210 			 * the tail piece of a transaction, and we would rather
15211 			 * wait for the response.
15212 			 */
15213 			uint32_t udif;
15214 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
15215 			    (uintptr_t)INT_MAX);
15216 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
15217 			if (udif && (udif % mss))
15218 				flags |= TH_ACK_NEEDED;
15219 			else
15220 				flags |= TH_ACK_TIMER_NEEDED;
15221 		} else {
15222 			/* Start delayed ack timer */
15223 			flags |= TH_ACK_TIMER_NEEDED;
15224 		}
15225 	}
15226 	tcp->tcp_rnxt += seg_len;
15227 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15228 
15229 	/* Update SACK list */
15230 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15231 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15232 		    &(tcp->tcp_num_sack_blk));
15233 	}
15234 
15235 	if (tcp->tcp_urp_mp) {
15236 		tcp->tcp_urp_mp->b_cont = mp;
15237 		mp = tcp->tcp_urp_mp;
15238 		tcp->tcp_urp_mp = NULL;
15239 		/* Ready for a new signal. */
15240 		tcp->tcp_urp_last_valid = B_FALSE;
15241 #ifdef DEBUG
15242 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15243 		    "tcp_rput: sending exdata_ind %s",
15244 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15245 #endif /* DEBUG */
15246 	}
15247 
15248 	/*
15249 	 * Check for ancillary data changes compared to last segment.
15250 	 */
15251 	if (tcp->tcp_ipv6_recvancillary != 0) {
15252 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15253 		if (mp == NULL)
15254 			return;
15255 	}
15256 
15257 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15258 		/*
15259 		 * Side queue inbound data until the accept happens.
15260 		 * tcp_accept/tcp_rput drains this when the accept happens.
15261 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15262 		 * T_EXDATA_IND) it is queued on b_next.
15263 		 * XXX Make urgent data use this. Requires:
15264 		 *	Removing tcp_listener check for TH_URG
15265 		 *	Making M_PCPROTO and MARK messages skip the eager case
15266 		 */
15267 
15268 		if (tcp->tcp_kssl_pending) {
15269 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
15270 			    mblk_t *, mp);
15271 			tcp_kssl_input(tcp, mp);
15272 		} else {
15273 			tcp_rcv_enqueue(tcp, mp, seg_len);
15274 		}
15275 	} else {
15276 		sodirect_t	*sodp = tcp->tcp_sodirect;
15277 
15278 		/*
15279 		 * If an sodirect connection and an enabled sodirect_t then
15280 		 * sodp will be set to point to the tcp_t/sonode_t shared
15281 		 * sodirect_t and the sodirect_t's lock will be held.
15282 		 */
15283 		if (sodp != NULL) {
15284 			mutex_enter(sodp->sod_lock);
15285 			if (!(sodp->sod_state & SOD_ENABLED)) {
15286 				mutex_exit(sodp->sod_lock);
15287 				sodp = NULL;
15288 			} else if (tcp->tcp_kssl_ctx != NULL &&
15289 			    DB_TYPE(mp) == M_DATA) {
15290 				mutex_exit(sodp->sod_lock);
15291 				sodp = NULL;
15292 			}
15293 		}
15294 		if (mp->b_datap->db_type != M_DATA ||
15295 		    (flags & TH_MARKNEXT_NEEDED)) {
15296 			if (sodp != NULL) {
15297 				if (!SOD_QEMPTY(sodp) &&
15298 				    (sodp->sod_state & SOD_WAKE_NOT)) {
15299 					flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15300 					/* sod_wakeup() did the mutex_exit() */
15301 					mutex_enter(sodp->sod_lock);
15302 				}
15303 			} else if (tcp->tcp_rcv_list != NULL) {
15304 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15305 			}
15306 			ASSERT(tcp->tcp_rcv_list == NULL ||
15307 			    tcp->tcp_fused_sigurg);
15308 
15309 			if (flags & TH_MARKNEXT_NEEDED) {
15310 #ifdef DEBUG
15311 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15312 				    "tcp_rput: sending MSGMARKNEXT %s",
15313 				    tcp_display(tcp, NULL,
15314 				    DISP_PORT_ONLY));
15315 #endif /* DEBUG */
15316 				mp->b_flag |= MSGMARKNEXT;
15317 				flags &= ~TH_MARKNEXT_NEEDED;
15318 			}
15319 
15320 			/* Does this need SSL processing first? */
15321 			if ((tcp->tcp_kssl_ctx != NULL) &&
15322 			    (DB_TYPE(mp) == M_DATA)) {
15323 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15324 				    mblk_t *, mp);
15325 				tcp_kssl_input(tcp, mp);
15326 			} else {
15327 				if (sodp) {
15328 					/*
15329 					 * Done with sodirect, use putnext
15330 					 * to push this non M_DATA headed
15331 					 * mblk_t chain.
15332 					 */
15333 					mutex_exit(sodp->sod_lock);
15334 				}
15335 				putnext(tcp->tcp_rq, mp);
15336 				if (!canputnext(tcp->tcp_rq))
15337 					tcp->tcp_rwnd -= seg_len;
15338 			}
15339 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15340 		    (DB_TYPE(mp) == M_DATA)) {
15341 			/* Do SSL processing first */
15342 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2,
15343 			    mblk_t *, mp);
15344 			tcp_kssl_input(tcp, mp);
15345 		} else if (sodp != NULL) {
15346 			/*
15347 			 * Sodirect so all mblk_t's are queued on the
15348 			 * socket directly, check for wakeup of blocked
15349 			 * reader (if any), and last if flow-controled.
15350 			 */
15351 			flags |= tcp_rcv_sod_enqueue(tcp, sodp, mp, seg_len);
15352 			if ((sodp->sod_state & SOD_WAKE_NEED) ||
15353 			    (flags & (TH_PUSH|TH_FIN))) {
15354 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15355 				/* sod_wakeup() did the mutex_exit() */
15356 			} else {
15357 				if (SOD_QFULL(sodp)) {
15358 					/* Q is full, need backenable */
15359 					SOD_QSETBE(sodp);
15360 				}
15361 				mutex_exit(sodp->sod_lock);
15362 			}
15363 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15364 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
15365 			if (tcp->tcp_rcv_list != NULL) {
15366 				/*
15367 				 * Enqueue the new segment first and then
15368 				 * call tcp_rcv_drain() to send all data
15369 				 * up.  The other way to do this is to
15370 				 * send all queued data up and then call
15371 				 * putnext() to send the new segment up.
15372 				 * This way can remove the else part later
15373 				 * on.
15374 				 *
15375 				 * We don't this to avoid one more call to
15376 				 * canputnext() as tcp_rcv_drain() needs to
15377 				 * call canputnext().
15378 				 */
15379 				tcp_rcv_enqueue(tcp, mp, seg_len);
15380 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15381 			} else {
15382 				putnext(tcp->tcp_rq, mp);
15383 				if (!canputnext(tcp->tcp_rq))
15384 					tcp->tcp_rwnd -= seg_len;
15385 			}
15386 		} else {
15387 			/*
15388 			 * Enqueue all packets when processing an mblk
15389 			 * from the co queue and also enqueue normal packets.
15390 			 */
15391 			tcp_rcv_enqueue(tcp, mp, seg_len);
15392 		}
15393 		/*
15394 		 * Make sure the timer is running if we have data waiting
15395 		 * for a push bit. This provides resiliency against
15396 		 * implementations that do not correctly generate push bits.
15397 		 *
15398 		 * Note, for sodirect if Q isn't empty and there's not a
15399 		 * pending wakeup then we need a timer. Also note that sodp
15400 		 * is assumed to be still valid after exit()ing the sod_lock
15401 		 * above and while the SOD state can change it can only change
15402 		 * such that the Q is empty now even though data was added
15403 		 * above.
15404 		 */
15405 		if (((sodp != NULL && !SOD_QEMPTY(sodp) &&
15406 		    (sodp->sod_state & SOD_WAKE_NOT)) ||
15407 		    (sodp == NULL && tcp->tcp_rcv_list != NULL)) &&
15408 		    tcp->tcp_push_tid == 0) {
15409 			/*
15410 			 * The connection may be closed at this point, so don't
15411 			 * do anything for a detached tcp.
15412 			 */
15413 			if (!TCP_IS_DETACHED(tcp))
15414 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15415 				    tcp_push_timer,
15416 				    MSEC_TO_TICK(
15417 				    tcps->tcps_push_timer_interval));
15418 		}
15419 	}
15420 
15421 xmit_check:
15422 	/* Is there anything left to do? */
15423 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15424 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15425 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15426 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15427 		goto done;
15428 
15429 	/* Any transmit work to do and a non-zero window? */
15430 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15431 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15432 		if (flags & TH_REXMIT_NEEDED) {
15433 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15434 
15435 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15436 			if (snd_size > mss)
15437 				snd_size = mss;
15438 			if (snd_size > tcp->tcp_swnd)
15439 				snd_size = tcp->tcp_swnd;
15440 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15441 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15442 			    B_TRUE);
15443 
15444 			if (mp1 != NULL) {
15445 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15446 				tcp->tcp_csuna = tcp->tcp_snxt;
15447 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15448 				UPDATE_MIB(&tcps->tcps_mib,
15449 				    tcpRetransBytes, snd_size);
15450 				TCP_RECORD_TRACE(tcp, mp1,
15451 				    TCP_TRACE_SEND_PKT);
15452 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15453 			}
15454 		}
15455 		if (flags & TH_NEED_SACK_REXMIT) {
15456 			tcp_sack_rxmit(tcp, &flags);
15457 		}
15458 		/*
15459 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15460 		 * out new segment.  Note that tcp_rexmit should not be
15461 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15462 		 */
15463 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15464 			if (!tcp->tcp_rexmit) {
15465 				tcp_wput_data(tcp, NULL, B_FALSE);
15466 			} else {
15467 				tcp_ss_rexmit(tcp);
15468 			}
15469 		}
15470 		/*
15471 		 * Adjust tcp_cwnd back to normal value after sending
15472 		 * new data segments.
15473 		 */
15474 		if (flags & TH_LIMIT_XMIT) {
15475 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15476 			/*
15477 			 * This will restart the timer.  Restarting the
15478 			 * timer is used to avoid a timeout before the
15479 			 * limited transmitted segment's ACK gets back.
15480 			 */
15481 			if (tcp->tcp_xmit_head != NULL)
15482 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15483 		}
15484 
15485 		/* Anything more to do? */
15486 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15487 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15488 			goto done;
15489 	}
15490 ack_check:
15491 	if (flags & TH_SEND_URP_MARK) {
15492 		ASSERT(tcp->tcp_urp_mark_mp);
15493 		/*
15494 		 * Send up any queued data and then send the mark message
15495 		 */
15496 		sodirect_t *sodp;
15497 
15498 		SOD_PTR_ENTER(tcp, sodp);
15499 
15500 		mp1 = tcp->tcp_urp_mark_mp;
15501 		tcp->tcp_urp_mark_mp = NULL;
15502 		if (sodp != NULL) {
15503 
15504 			ASSERT(tcp->tcp_rcv_list == NULL);
15505 
15506 			flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15507 			/* sod_wakeup() does the mutex_exit() */
15508 		} else if (tcp->tcp_rcv_list != NULL) {
15509 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15510 
15511 			ASSERT(tcp->tcp_rcv_list == NULL ||
15512 			    tcp->tcp_fused_sigurg);
15513 
15514 		}
15515 		putnext(tcp->tcp_rq, mp1);
15516 #ifdef DEBUG
15517 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15518 		    "tcp_rput: sending zero-length %s %s",
15519 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15520 		    "MSGNOTMARKNEXT"),
15521 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15522 #endif /* DEBUG */
15523 		flags &= ~TH_SEND_URP_MARK;
15524 	}
15525 	if (flags & TH_ACK_NEEDED) {
15526 		/*
15527 		 * Time to send an ack for some reason.
15528 		 */
15529 		mp1 = tcp_ack_mp(tcp);
15530 
15531 		if (mp1 != NULL) {
15532 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
15533 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15534 			BUMP_LOCAL(tcp->tcp_obsegs);
15535 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15536 		}
15537 		if (tcp->tcp_ack_tid != 0) {
15538 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15539 			tcp->tcp_ack_tid = 0;
15540 		}
15541 	}
15542 	if (flags & TH_ACK_TIMER_NEEDED) {
15543 		/*
15544 		 * Arrange for deferred ACK or push wait timeout.
15545 		 * Start timer if it is not already running.
15546 		 */
15547 		if (tcp->tcp_ack_tid == 0) {
15548 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15549 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15550 			    (clock_t)tcps->tcps_local_dack_interval :
15551 			    (clock_t)tcps->tcps_deferred_ack_interval));
15552 		}
15553 	}
15554 	if (flags & TH_ORDREL_NEEDED) {
15555 		/*
15556 		 * Send up the ordrel_ind unless we are an eager guy.
15557 		 * In the eager case tcp_rsrv will do this when run
15558 		 * after tcp_accept is done.
15559 		 */
15560 		sodirect_t *sodp;
15561 
15562 		ASSERT(tcp->tcp_listener == NULL);
15563 
15564 		SOD_PTR_ENTER(tcp, sodp);
15565 		if (sodp != NULL) {
15566 			/* No more sodirect */
15567 			tcp->tcp_sodirect = NULL;
15568 			if (!SOD_QEMPTY(sodp)) {
15569 				/* Mblk(s) to process, notify */
15570 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15571 				/* sod_wakeup() does the mutex_exit() */
15572 			} else {
15573 				/* Nothing to process */
15574 				mutex_exit(sodp->sod_lock);
15575 			}
15576 		} else if (tcp->tcp_rcv_list != NULL) {
15577 			/*
15578 			 * Push any mblk(s) enqueued from co processing.
15579 			 */
15580 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15581 
15582 			ASSERT(tcp->tcp_rcv_list == NULL ||
15583 			    tcp->tcp_fused_sigurg);
15584 		}
15585 
15586 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
15587 			tcp->tcp_ordrel_done = B_TRUE;
15588 			putnext(tcp->tcp_rq, mp1);
15589 			if (tcp->tcp_deferred_clean_death) {
15590 				/*
15591 				 * tcp_clean_death was deferred
15592 				 * for T_ORDREL_IND - do it now
15593 				 */
15594 				(void) tcp_clean_death(tcp,
15595 				    tcp->tcp_client_errno, 20);
15596 				tcp->tcp_deferred_clean_death =	B_FALSE;
15597 			}
15598 		} else {
15599 			/*
15600 			 * Run the orderly release in the
15601 			 * service routine.
15602 			 */
15603 			qenable(tcp->tcp_rq);
15604 			/*
15605 			 * Caveat(XXX): The machine may be so
15606 			 * overloaded that tcp_rsrv() is not scheduled
15607 			 * until after the endpoint has transitioned
15608 			 * to TCPS_TIME_WAIT
15609 			 * and tcp_time_wait_interval expires. Then
15610 			 * tcp_timer() will blow away state in tcp_t
15611 			 * and T_ORDREL_IND will never be delivered
15612 			 * upstream. Unlikely but potentially
15613 			 * a problem.
15614 			 */
15615 		}
15616 	}
15617 done:
15618 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15619 }
15620 
15621 /*
15622  * This function does PAWS protection check. Returns B_TRUE if the
15623  * segment passes the PAWS test, else returns B_FALSE.
15624  */
15625 boolean_t
15626 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15627 {
15628 	uint8_t	flags;
15629 	int	options;
15630 	uint8_t *up;
15631 
15632 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15633 	/*
15634 	 * If timestamp option is aligned nicely, get values inline,
15635 	 * otherwise call general routine to parse.  Only do that
15636 	 * if timestamp is the only option.
15637 	 */
15638 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15639 	    TCPOPT_REAL_TS_LEN &&
15640 	    OK_32PTR((up = ((uint8_t *)tcph) +
15641 	    TCP_MIN_HEADER_LENGTH)) &&
15642 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15643 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15644 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15645 
15646 		options = TCP_OPT_TSTAMP_PRESENT;
15647 	} else {
15648 		if (tcp->tcp_snd_sack_ok) {
15649 			tcpoptp->tcp = tcp;
15650 		} else {
15651 			tcpoptp->tcp = NULL;
15652 		}
15653 		options = tcp_parse_options(tcph, tcpoptp);
15654 	}
15655 
15656 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15657 		/*
15658 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15659 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15660 		 */
15661 		if ((flags & TH_RST) == 0 &&
15662 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15663 		    tcp->tcp_ts_recent)) {
15664 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15665 			    PAWS_TIMEOUT)) {
15666 				/* This segment is not acceptable. */
15667 				return (B_FALSE);
15668 			} else {
15669 				/*
15670 				 * Connection has been idle for
15671 				 * too long.  Reset the timestamp
15672 				 * and assume the segment is valid.
15673 				 */
15674 				tcp->tcp_ts_recent =
15675 				    tcpoptp->tcp_opt_ts_val;
15676 			}
15677 		}
15678 	} else {
15679 		/*
15680 		 * If we don't get a timestamp on every packet, we
15681 		 * figure we can't really trust 'em, so we stop sending
15682 		 * and parsing them.
15683 		 */
15684 		tcp->tcp_snd_ts_ok = B_FALSE;
15685 
15686 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15687 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15688 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15689 		/*
15690 		 * Adjust the tcp_mss accordingly. We also need to
15691 		 * adjust tcp_cwnd here in accordance with the new mss.
15692 		 * But we avoid doing a slow start here so as to not
15693 		 * to lose on the transfer rate built up so far.
15694 		 */
15695 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15696 		if (tcp->tcp_snd_sack_ok) {
15697 			ASSERT(tcp->tcp_sack_info != NULL);
15698 			tcp->tcp_max_sack_blk = 4;
15699 		}
15700 	}
15701 	return (B_TRUE);
15702 }
15703 
15704 /*
15705  * Attach ancillary data to a received TCP segments for the
15706  * ancillary pieces requested by the application that are
15707  * different than they were in the previous data segment.
15708  *
15709  * Save the "current" values once memory allocation is ok so that
15710  * when memory allocation fails we can just wait for the next data segment.
15711  */
15712 static mblk_t *
15713 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15714 {
15715 	struct T_optdata_ind *todi;
15716 	int optlen;
15717 	uchar_t *optptr;
15718 	struct T_opthdr *toh;
15719 	uint_t addflag;	/* Which pieces to add */
15720 	mblk_t *mp1;
15721 
15722 	optlen = 0;
15723 	addflag = 0;
15724 	/* If app asked for pktinfo and the index has changed ... */
15725 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15726 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15727 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15728 		optlen += sizeof (struct T_opthdr) +
15729 		    sizeof (struct in6_pktinfo);
15730 		addflag |= TCP_IPV6_RECVPKTINFO;
15731 	}
15732 	/* If app asked for hoplimit and it has changed ... */
15733 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15734 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15735 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15736 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15737 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15738 	}
15739 	/* If app asked for tclass and it has changed ... */
15740 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15741 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15742 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15743 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15744 		addflag |= TCP_IPV6_RECVTCLASS;
15745 	}
15746 	/*
15747 	 * If app asked for hopbyhop headers and it has changed ...
15748 	 * For security labels, note that (1) security labels can't change on
15749 	 * a connected socket at all, (2) we're connected to at most one peer,
15750 	 * (3) if anything changes, then it must be some other extra option.
15751 	 */
15752 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15753 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15754 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15755 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15756 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15757 		    tcp->tcp_label_len;
15758 		addflag |= TCP_IPV6_RECVHOPOPTS;
15759 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15760 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15761 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15762 			return (mp);
15763 	}
15764 	/* If app asked for dst headers before routing headers ... */
15765 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15766 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15767 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15768 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15769 		optlen += sizeof (struct T_opthdr) +
15770 		    ipp->ipp_rtdstoptslen;
15771 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15772 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15773 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15774 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15775 			return (mp);
15776 	}
15777 	/* If app asked for routing headers and it has changed ... */
15778 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15779 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15780 	    (ipp->ipp_fields & IPPF_RTHDR),
15781 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15782 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15783 		addflag |= TCP_IPV6_RECVRTHDR;
15784 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15785 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15786 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15787 			return (mp);
15788 	}
15789 	/* If app asked for dest headers and it has changed ... */
15790 	if ((tcp->tcp_ipv6_recvancillary &
15791 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15792 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15793 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15794 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15795 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15796 		addflag |= TCP_IPV6_RECVDSTOPTS;
15797 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15798 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15799 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15800 			return (mp);
15801 	}
15802 
15803 	if (optlen == 0) {
15804 		/* Nothing to add */
15805 		return (mp);
15806 	}
15807 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15808 	if (mp1 == NULL) {
15809 		/*
15810 		 * Defer sending ancillary data until the next TCP segment
15811 		 * arrives.
15812 		 */
15813 		return (mp);
15814 	}
15815 	mp1->b_cont = mp;
15816 	mp = mp1;
15817 	mp->b_wptr += sizeof (*todi) + optlen;
15818 	mp->b_datap->db_type = M_PROTO;
15819 	todi = (struct T_optdata_ind *)mp->b_rptr;
15820 	todi->PRIM_type = T_OPTDATA_IND;
15821 	todi->DATA_flag = 1;	/* MORE data */
15822 	todi->OPT_length = optlen;
15823 	todi->OPT_offset = sizeof (*todi);
15824 	optptr = (uchar_t *)&todi[1];
15825 	/*
15826 	 * If app asked for pktinfo and the index has changed ...
15827 	 * Note that the local address never changes for the connection.
15828 	 */
15829 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15830 		struct in6_pktinfo *pkti;
15831 
15832 		toh = (struct T_opthdr *)optptr;
15833 		toh->level = IPPROTO_IPV6;
15834 		toh->name = IPV6_PKTINFO;
15835 		toh->len = sizeof (*toh) + sizeof (*pkti);
15836 		toh->status = 0;
15837 		optptr += sizeof (*toh);
15838 		pkti = (struct in6_pktinfo *)optptr;
15839 		if (tcp->tcp_ipversion == IPV6_VERSION)
15840 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15841 		else
15842 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15843 			    &pkti->ipi6_addr);
15844 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15845 		optptr += sizeof (*pkti);
15846 		ASSERT(OK_32PTR(optptr));
15847 		/* Save as "last" value */
15848 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15849 	}
15850 	/* If app asked for hoplimit and it has changed ... */
15851 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15852 		toh = (struct T_opthdr *)optptr;
15853 		toh->level = IPPROTO_IPV6;
15854 		toh->name = IPV6_HOPLIMIT;
15855 		toh->len = sizeof (*toh) + sizeof (uint_t);
15856 		toh->status = 0;
15857 		optptr += sizeof (*toh);
15858 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15859 		optptr += sizeof (uint_t);
15860 		ASSERT(OK_32PTR(optptr));
15861 		/* Save as "last" value */
15862 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15863 	}
15864 	/* If app asked for tclass and it has changed ... */
15865 	if (addflag & TCP_IPV6_RECVTCLASS) {
15866 		toh = (struct T_opthdr *)optptr;
15867 		toh->level = IPPROTO_IPV6;
15868 		toh->name = IPV6_TCLASS;
15869 		toh->len = sizeof (*toh) + sizeof (uint_t);
15870 		toh->status = 0;
15871 		optptr += sizeof (*toh);
15872 		*(uint_t *)optptr = ipp->ipp_tclass;
15873 		optptr += sizeof (uint_t);
15874 		ASSERT(OK_32PTR(optptr));
15875 		/* Save as "last" value */
15876 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15877 	}
15878 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15879 		toh = (struct T_opthdr *)optptr;
15880 		toh->level = IPPROTO_IPV6;
15881 		toh->name = IPV6_HOPOPTS;
15882 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15883 		    tcp->tcp_label_len;
15884 		toh->status = 0;
15885 		optptr += sizeof (*toh);
15886 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15887 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15888 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15889 		ASSERT(OK_32PTR(optptr));
15890 		/* Save as last value */
15891 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15892 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15893 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15894 	}
15895 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15896 		toh = (struct T_opthdr *)optptr;
15897 		toh->level = IPPROTO_IPV6;
15898 		toh->name = IPV6_RTHDRDSTOPTS;
15899 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15900 		toh->status = 0;
15901 		optptr += sizeof (*toh);
15902 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15903 		optptr += ipp->ipp_rtdstoptslen;
15904 		ASSERT(OK_32PTR(optptr));
15905 		/* Save as last value */
15906 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15907 		    &tcp->tcp_rtdstoptslen,
15908 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15909 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15910 	}
15911 	if (addflag & TCP_IPV6_RECVRTHDR) {
15912 		toh = (struct T_opthdr *)optptr;
15913 		toh->level = IPPROTO_IPV6;
15914 		toh->name = IPV6_RTHDR;
15915 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15916 		toh->status = 0;
15917 		optptr += sizeof (*toh);
15918 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15919 		optptr += ipp->ipp_rthdrlen;
15920 		ASSERT(OK_32PTR(optptr));
15921 		/* Save as last value */
15922 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15923 		    (ipp->ipp_fields & IPPF_RTHDR),
15924 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15925 	}
15926 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15927 		toh = (struct T_opthdr *)optptr;
15928 		toh->level = IPPROTO_IPV6;
15929 		toh->name = IPV6_DSTOPTS;
15930 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15931 		toh->status = 0;
15932 		optptr += sizeof (*toh);
15933 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15934 		optptr += ipp->ipp_dstoptslen;
15935 		ASSERT(OK_32PTR(optptr));
15936 		/* Save as last value */
15937 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15938 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15939 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15940 	}
15941 	ASSERT(optptr == mp->b_wptr);
15942 	return (mp);
15943 }
15944 
15945 
15946 /*
15947  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15948  * or a "bad" IRE detected by tcp_adapt_ire.
15949  * We can't tell if the failure was due to the laddr or the faddr
15950  * thus we clear out all addresses and ports.
15951  */
15952 static void
15953 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15954 {
15955 	queue_t	*q = tcp->tcp_rq;
15956 	tcph_t	*tcph;
15957 	struct T_error_ack *tea;
15958 	conn_t	*connp = tcp->tcp_connp;
15959 
15960 
15961 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15962 
15963 	if (mp->b_cont) {
15964 		freemsg(mp->b_cont);
15965 		mp->b_cont = NULL;
15966 	}
15967 	tea = (struct T_error_ack *)mp->b_rptr;
15968 	switch (tea->PRIM_type) {
15969 	case T_BIND_ACK:
15970 		/*
15971 		 * Need to unbind with classifier since we were just told that
15972 		 * our bind succeeded.
15973 		 */
15974 		tcp->tcp_hard_bound = B_FALSE;
15975 		tcp->tcp_hard_binding = B_FALSE;
15976 
15977 		ipcl_hash_remove(connp);
15978 		/* Reuse the mblk if possible */
15979 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15980 		    sizeof (*tea));
15981 		mp->b_rptr = mp->b_datap->db_base;
15982 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15983 		tea = (struct T_error_ack *)mp->b_rptr;
15984 		tea->PRIM_type = T_ERROR_ACK;
15985 		tea->TLI_error = TSYSERR;
15986 		tea->UNIX_error = error;
15987 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15988 			tea->ERROR_prim = T_CONN_REQ;
15989 		} else {
15990 			tea->ERROR_prim = O_T_BIND_REQ;
15991 		}
15992 		break;
15993 
15994 	case T_ERROR_ACK:
15995 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15996 			tea->ERROR_prim = T_CONN_REQ;
15997 		break;
15998 	default:
15999 		panic("tcp_bind_failed: unexpected TPI type");
16000 		/*NOTREACHED*/
16001 	}
16002 
16003 	tcp->tcp_state = TCPS_IDLE;
16004 	if (tcp->tcp_ipversion == IPV4_VERSION)
16005 		tcp->tcp_ipha->ipha_src = 0;
16006 	else
16007 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16008 	/*
16009 	 * Copy of the src addr. in tcp_t is needed since
16010 	 * the lookup funcs. can only look at tcp_t
16011 	 */
16012 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16013 
16014 	tcph = tcp->tcp_tcph;
16015 	tcph->th_lport[0] = 0;
16016 	tcph->th_lport[1] = 0;
16017 	tcp_bind_hash_remove(tcp);
16018 	bzero(&connp->u_port, sizeof (connp->u_port));
16019 	/* blow away saved option results if any */
16020 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
16021 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
16022 
16023 	conn_delete_ire(tcp->tcp_connp, NULL);
16024 	putnext(q, mp);
16025 }
16026 
16027 /*
16028  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
16029  * messages.
16030  */
16031 void
16032 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
16033 {
16034 	mblk_t	*mp1;
16035 	uchar_t	*rptr = mp->b_rptr;
16036 	queue_t	*q = tcp->tcp_rq;
16037 	struct T_error_ack *tea;
16038 	uint32_t mss;
16039 	mblk_t *syn_mp;
16040 	mblk_t *mdti;
16041 	mblk_t *lsoi;
16042 	int	retval;
16043 	mblk_t *ire_mp;
16044 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16045 
16046 	switch (mp->b_datap->db_type) {
16047 	case M_PROTO:
16048 	case M_PCPROTO:
16049 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
16050 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
16051 			break;
16052 		tea = (struct T_error_ack *)rptr;
16053 		switch (tea->PRIM_type) {
16054 		case T_BIND_ACK:
16055 			/*
16056 			 * Adapt Multidata information, if any.  The
16057 			 * following tcp_mdt_update routine will free
16058 			 * the message.
16059 			 */
16060 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
16061 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
16062 				    b_rptr)->mdt_capab, B_TRUE);
16063 				freemsg(mdti);
16064 			}
16065 
16066 			/*
16067 			 * Check to update LSO information with tcp, and
16068 			 * tcp_lso_update routine will free the message.
16069 			 */
16070 			if ((lsoi = tcp_lso_info_mp(mp)) != NULL) {
16071 				tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
16072 				    b_rptr)->lso_capab);
16073 				freemsg(lsoi);
16074 			}
16075 
16076 			/* Get the IRE, if we had requested for it */
16077 			ire_mp = tcp_ire_mp(mp);
16078 
16079 			if (tcp->tcp_hard_binding) {
16080 				tcp->tcp_hard_binding = B_FALSE;
16081 				tcp->tcp_hard_bound = B_TRUE;
16082 				CL_INET_CONNECT(tcp);
16083 			} else {
16084 				if (ire_mp != NULL)
16085 					freeb(ire_mp);
16086 				goto after_syn_sent;
16087 			}
16088 
16089 			retval = tcp_adapt_ire(tcp, ire_mp);
16090 			if (ire_mp != NULL)
16091 				freeb(ire_mp);
16092 			if (retval == 0) {
16093 				tcp_bind_failed(tcp, mp,
16094 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
16095 				    ENETUNREACH : EADDRNOTAVAIL));
16096 				return;
16097 			}
16098 			/*
16099 			 * Don't let an endpoint connect to itself.
16100 			 * Also checked in tcp_connect() but that
16101 			 * check can't handle the case when the
16102 			 * local IP address is INADDR_ANY.
16103 			 */
16104 			if (tcp->tcp_ipversion == IPV4_VERSION) {
16105 				if ((tcp->tcp_ipha->ipha_dst ==
16106 				    tcp->tcp_ipha->ipha_src) &&
16107 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
16108 				    tcp->tcp_tcph->th_fport))) {
16109 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
16110 					return;
16111 				}
16112 			} else {
16113 				if (IN6_ARE_ADDR_EQUAL(
16114 				    &tcp->tcp_ip6h->ip6_dst,
16115 				    &tcp->tcp_ip6h->ip6_src) &&
16116 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
16117 				    tcp->tcp_tcph->th_fport))) {
16118 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
16119 					return;
16120 				}
16121 			}
16122 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
16123 			/*
16124 			 * This should not be possible!  Just for
16125 			 * defensive coding...
16126 			 */
16127 			if (tcp->tcp_state != TCPS_SYN_SENT)
16128 				goto after_syn_sent;
16129 
16130 			if (is_system_labeled() &&
16131 			    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
16132 				tcp_bind_failed(tcp, mp, EHOSTUNREACH);
16133 				return;
16134 			}
16135 
16136 			ASSERT(q == tcp->tcp_rq);
16137 			/*
16138 			 * tcp_adapt_ire() does not adjust
16139 			 * for TCP/IP header length.
16140 			 */
16141 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
16142 
16143 			/*
16144 			 * Just make sure our rwnd is at
16145 			 * least tcp_recv_hiwat_mss * MSS
16146 			 * large, and round up to the nearest
16147 			 * MSS.
16148 			 *
16149 			 * We do the round up here because
16150 			 * we need to get the interface
16151 			 * MTU first before we can do the
16152 			 * round up.
16153 			 */
16154 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
16155 			    tcps->tcps_recv_hiwat_minmss * mss);
16156 			q->q_hiwat = tcp->tcp_rwnd;
16157 			tcp_set_ws_value(tcp);
16158 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
16159 			    tcp->tcp_tcph->th_win);
16160 			if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
16161 				tcp->tcp_snd_ws_ok = B_TRUE;
16162 
16163 			/*
16164 			 * Set tcp_snd_ts_ok to true
16165 			 * so that tcp_xmit_mp will
16166 			 * include the timestamp
16167 			 * option in the SYN segment.
16168 			 */
16169 			if (tcps->tcps_tstamp_always ||
16170 			    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
16171 				tcp->tcp_snd_ts_ok = B_TRUE;
16172 			}
16173 
16174 			/*
16175 			 * tcp_snd_sack_ok can be set in
16176 			 * tcp_adapt_ire() if the sack metric
16177 			 * is set.  So check it here also.
16178 			 */
16179 			if (tcps->tcps_sack_permitted == 2 ||
16180 			    tcp->tcp_snd_sack_ok) {
16181 				if (tcp->tcp_sack_info == NULL) {
16182 					tcp->tcp_sack_info =
16183 					    kmem_cache_alloc(
16184 					    tcp_sack_info_cache,
16185 					    KM_SLEEP);
16186 				}
16187 				tcp->tcp_snd_sack_ok = B_TRUE;
16188 			}
16189 
16190 			/*
16191 			 * Should we use ECN?  Note that the current
16192 			 * default value (SunOS 5.9) of tcp_ecn_permitted
16193 			 * is 1.  The reason for doing this is that there
16194 			 * are equipments out there that will drop ECN
16195 			 * enabled IP packets.  Setting it to 1 avoids
16196 			 * compatibility problems.
16197 			 */
16198 			if (tcps->tcps_ecn_permitted == 2)
16199 				tcp->tcp_ecn_ok = B_TRUE;
16200 
16201 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16202 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
16203 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
16204 			if (syn_mp) {
16205 				cred_t *cr;
16206 				pid_t pid;
16207 
16208 				/*
16209 				 * Obtain the credential from the
16210 				 * thread calling connect(); the credential
16211 				 * lives on in the second mblk which
16212 				 * originated from T_CONN_REQ and is echoed
16213 				 * with the T_BIND_ACK from ip.  If none
16214 				 * can be found, default to the creator
16215 				 * of the socket.
16216 				 */
16217 				if (mp->b_cont == NULL ||
16218 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
16219 					cr = tcp->tcp_cred;
16220 					pid = tcp->tcp_cpid;
16221 				} else {
16222 					pid = DB_CPID(mp->b_cont);
16223 				}
16224 
16225 				TCP_RECORD_TRACE(tcp, syn_mp,
16226 				    TCP_TRACE_SEND_PKT);
16227 				mblk_setcred(syn_mp, cr);
16228 				DB_CPID(syn_mp) = pid;
16229 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
16230 			}
16231 		after_syn_sent:
16232 			/*
16233 			 * A trailer mblk indicates a waiting client upstream.
16234 			 * We complete here the processing begun in
16235 			 * either tcp_bind() or tcp_connect() by passing
16236 			 * upstream the reply message they supplied.
16237 			 */
16238 			mp1 = mp;
16239 			mp = mp->b_cont;
16240 			freeb(mp1);
16241 			if (mp)
16242 				break;
16243 			return;
16244 		case T_ERROR_ACK:
16245 			if (tcp->tcp_debug) {
16246 				(void) strlog(TCP_MOD_ID, 0, 1,
16247 				    SL_TRACE|SL_ERROR,
16248 				    "tcp_rput_other: case T_ERROR_ACK, "
16249 				    "ERROR_prim == %d",
16250 				    tea->ERROR_prim);
16251 			}
16252 			switch (tea->ERROR_prim) {
16253 			case O_T_BIND_REQ:
16254 			case T_BIND_REQ:
16255 				tcp_bind_failed(tcp, mp,
16256 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
16257 				    ENETUNREACH : EADDRNOTAVAIL));
16258 				return;
16259 			case T_UNBIND_REQ:
16260 				tcp->tcp_hard_binding = B_FALSE;
16261 				tcp->tcp_hard_bound = B_FALSE;
16262 				if (mp->b_cont) {
16263 					freemsg(mp->b_cont);
16264 					mp->b_cont = NULL;
16265 				}
16266 				if (tcp->tcp_unbind_pending)
16267 					tcp->tcp_unbind_pending = 0;
16268 				else {
16269 					/* From tcp_ip_unbind() - free */
16270 					freemsg(mp);
16271 					return;
16272 				}
16273 				break;
16274 			case T_SVR4_OPTMGMT_REQ:
16275 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
16276 					/* T_OPTMGMT_REQ generated by TCP */
16277 					printf("T_SVR4_OPTMGMT_REQ failed "
16278 					    "%d/%d - dropped (cnt %d)\n",
16279 					    tea->TLI_error, tea->UNIX_error,
16280 					    tcp->tcp_drop_opt_ack_cnt);
16281 					freemsg(mp);
16282 					tcp->tcp_drop_opt_ack_cnt--;
16283 					return;
16284 				}
16285 				break;
16286 			}
16287 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
16288 			    tcp->tcp_drop_opt_ack_cnt > 0) {
16289 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
16290 				    "- dropped (cnt %d)\n",
16291 				    tea->TLI_error, tea->UNIX_error,
16292 				    tcp->tcp_drop_opt_ack_cnt);
16293 				freemsg(mp);
16294 				tcp->tcp_drop_opt_ack_cnt--;
16295 				return;
16296 			}
16297 			break;
16298 		case T_OPTMGMT_ACK:
16299 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
16300 				/* T_OPTMGMT_REQ generated by TCP */
16301 				freemsg(mp);
16302 				tcp->tcp_drop_opt_ack_cnt--;
16303 				return;
16304 			}
16305 			break;
16306 		default:
16307 			break;
16308 		}
16309 		break;
16310 	case M_FLUSH:
16311 		if (*rptr & FLUSHR)
16312 			flushq(q, FLUSHDATA);
16313 		break;
16314 	default:
16315 		/* M_CTL will be directly sent to tcp_icmp_error() */
16316 		ASSERT(DB_TYPE(mp) != M_CTL);
16317 		break;
16318 	}
16319 	/*
16320 	 * Make sure we set this bit before sending the ACK for
16321 	 * bind. Otherwise accept could possibly run and free
16322 	 * this tcp struct.
16323 	 */
16324 	putnext(q, mp);
16325 }
16326 
16327 /*
16328  * Called as the result of a qbufcall or a qtimeout to remedy a failure
16329  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
16330  * tcp_rsrv() try again.
16331  */
16332 static void
16333 tcp_ordrel_kick(void *arg)
16334 {
16335 	conn_t 	*connp = (conn_t *)arg;
16336 	tcp_t	*tcp = connp->conn_tcp;
16337 
16338 	tcp->tcp_ordrelid = 0;
16339 	tcp->tcp_timeout = B_FALSE;
16340 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
16341 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
16342 		qenable(tcp->tcp_rq);
16343 	}
16344 }
16345 
16346 /* ARGSUSED */
16347 static void
16348 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
16349 {
16350 	conn_t	*connp = (conn_t *)arg;
16351 	tcp_t	*tcp = connp->conn_tcp;
16352 	queue_t	*q = tcp->tcp_rq;
16353 	uint_t	thwin;
16354 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16355 	sodirect_t	*sodp;
16356 	boolean_t	fc;
16357 
16358 	freeb(mp);
16359 
16360 	TCP_STAT(tcps, tcp_rsrv_calls);
16361 
16362 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
16363 		return;
16364 	}
16365 
16366 	if (tcp->tcp_fused) {
16367 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16368 
16369 		ASSERT(tcp->tcp_fused);
16370 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
16371 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
16372 		ASSERT(!TCP_IS_DETACHED(tcp));
16373 		ASSERT(tcp->tcp_connp->conn_sqp ==
16374 		    peer_tcp->tcp_connp->conn_sqp);
16375 
16376 		/*
16377 		 * Normally we would not get backenabled in synchronous
16378 		 * streams mode, but in case this happens, we need to plug
16379 		 * synchronous streams during our drain to prevent a race
16380 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
16381 		 */
16382 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
16383 		if (tcp->tcp_rcv_list != NULL)
16384 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
16385 
16386 		if (peer_tcp > tcp) {
16387 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
16388 			mutex_enter(&tcp->tcp_non_sq_lock);
16389 		} else {
16390 			mutex_enter(&tcp->tcp_non_sq_lock);
16391 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
16392 		}
16393 
16394 		if (peer_tcp->tcp_flow_stopped &&
16395 		    (TCP_UNSENT_BYTES(peer_tcp) <=
16396 		    peer_tcp->tcp_xmit_lowater)) {
16397 			tcp_clrqfull(peer_tcp);
16398 		}
16399 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
16400 		mutex_exit(&tcp->tcp_non_sq_lock);
16401 
16402 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
16403 		TCP_STAT(tcps, tcp_fusion_backenabled);
16404 		return;
16405 	}
16406 
16407 	SOD_PTR_ENTER(tcp, sodp);
16408 	if (sodp != NULL) {
16409 		/* An sodirect connection */
16410 		if (SOD_QFULL(sodp)) {
16411 			/* Flow-controlled, need another back-enable */
16412 			fc = B_TRUE;
16413 			SOD_QSETBE(sodp);
16414 		} else {
16415 			/* Not flow-controlled */
16416 			fc = B_FALSE;
16417 		}
16418 		mutex_exit(sodp->sod_lock);
16419 	} else if (canputnext(q)) {
16420 		/* STREAMS, not flow-controlled */
16421 		fc = B_FALSE;
16422 	} else {
16423 		/* STREAMS, flow-controlled */
16424 		fc = B_TRUE;
16425 	}
16426 	if (!fc) {
16427 		/* Not flow-controlled, open rwnd */
16428 		tcp->tcp_rwnd = q->q_hiwat;
16429 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
16430 		    << tcp->tcp_rcv_ws;
16431 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
16432 		/*
16433 		 * Send back a window update immediately if TCP is above
16434 		 * ESTABLISHED state and the increase of the rcv window
16435 		 * that the other side knows is at least 1 MSS after flow
16436 		 * control is lifted.
16437 		 */
16438 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
16439 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
16440 			tcp_xmit_ctl(NULL, tcp,
16441 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
16442 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
16443 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
16444 		}
16445 	}
16446 
16447 	/* Handle a failure to allocate a T_ORDREL_IND here */
16448 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
16449 		ASSERT(tcp->tcp_listener == NULL);
16450 
16451 		SOD_PTR_ENTER(tcp, sodp);
16452 		if (sodp != NULL) {
16453 			/* No more sodirect */
16454 			tcp->tcp_sodirect = NULL;
16455 			if (!SOD_QEMPTY(sodp)) {
16456 				/* Notify mblk(s) to process */
16457 				(void) tcp_rcv_sod_wakeup(tcp, sodp);
16458 				/* sod_wakeup() does the mutex_exit() */
16459 			} else {
16460 				/* Nothing to process */
16461 				mutex_exit(sodp->sod_lock);
16462 			}
16463 		} else if (tcp->tcp_rcv_list != NULL) {
16464 			/*
16465 			 * Push any mblk(s) enqueued from co processing.
16466 			 */
16467 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
16468 			ASSERT(tcp->tcp_rcv_list == NULL ||
16469 			    tcp->tcp_fused_sigurg);
16470 		}
16471 
16472 		mp = mi_tpi_ordrel_ind();
16473 		if (mp) {
16474 			tcp->tcp_ordrel_done = B_TRUE;
16475 			putnext(q, mp);
16476 			if (tcp->tcp_deferred_clean_death) {
16477 				/*
16478 				 * tcp_clean_death was deferred for
16479 				 * T_ORDREL_IND - do it now
16480 				 */
16481 				tcp->tcp_deferred_clean_death = B_FALSE;
16482 				(void) tcp_clean_death(tcp,
16483 				    tcp->tcp_client_errno, 22);
16484 			}
16485 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16486 			/*
16487 			 * If there isn't already a timer running
16488 			 * start one.  Use a 4 second
16489 			 * timer as a fallback since it can't fail.
16490 			 */
16491 			tcp->tcp_timeout = B_TRUE;
16492 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16493 			    MSEC_TO_TICK(4000));
16494 		}
16495 	}
16496 }
16497 
16498 /*
16499  * The read side service routine is called mostly when we get back-enabled as a
16500  * result of flow control relief.  Since we don't actually queue anything in
16501  * TCP, we have no data to send out of here.  What we do is clear the receive
16502  * window, and send out a window update.
16503  * This routine is also called to drive an orderly release message upstream
16504  * if the attempt in tcp_rput failed.
16505  */
16506 static void
16507 tcp_rsrv(queue_t *q)
16508 {
16509 	conn_t *connp = Q_TO_CONN(q);
16510 	tcp_t	*tcp = connp->conn_tcp;
16511 	mblk_t	*mp;
16512 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16513 
16514 	/* No code does a putq on the read side */
16515 	ASSERT(q->q_first == NULL);
16516 
16517 	/* Nothing to do for the default queue */
16518 	if (q == tcps->tcps_g_q) {
16519 		return;
16520 	}
16521 
16522 	mp = allocb(0, BPRI_HI);
16523 	if (mp == NULL) {
16524 		/*
16525 		 * We are under memory pressure. Return for now and we
16526 		 * we will be called again later.
16527 		 */
16528 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16529 			/*
16530 			 * If there isn't already a timer running
16531 			 * start one.  Use a 4 second
16532 			 * timer as a fallback since it can't fail.
16533 			 */
16534 			tcp->tcp_timeout = B_TRUE;
16535 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16536 			    MSEC_TO_TICK(4000));
16537 		}
16538 		return;
16539 	}
16540 	CONN_INC_REF(connp);
16541 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16542 	    SQTAG_TCP_RSRV);
16543 }
16544 
16545 /*
16546  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16547  * We do not allow the receive window to shrink.  After setting rwnd,
16548  * set the flow control hiwat of the stream.
16549  *
16550  * This function is called in 2 cases:
16551  *
16552  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16553  *    connection (passive open) and in tcp_rput_data() for active connect.
16554  *    This is called after tcp_mss_set() when the desired MSS value is known.
16555  *    This makes sure that our window size is a mutiple of the other side's
16556  *    MSS.
16557  * 2) Handling SO_RCVBUF option.
16558  *
16559  * It is ASSUMED that the requested size is a multiple of the current MSS.
16560  *
16561  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16562  * user requests so.
16563  */
16564 static int
16565 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16566 {
16567 	uint32_t	mss = tcp->tcp_mss;
16568 	uint32_t	old_max_rwnd;
16569 	uint32_t	max_transmittable_rwnd;
16570 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16571 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16572 
16573 	if (tcp->tcp_fused) {
16574 		size_t sth_hiwat;
16575 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16576 
16577 		ASSERT(peer_tcp != NULL);
16578 		/*
16579 		 * Record the stream head's high water mark for
16580 		 * this endpoint; this is used for flow-control
16581 		 * purposes in tcp_fuse_output().
16582 		 */
16583 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16584 		if (!tcp_detached)
16585 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
16586 
16587 		/*
16588 		 * In the fusion case, the maxpsz stream head value of
16589 		 * our peer is set according to its send buffer size
16590 		 * and our receive buffer size; since the latter may
16591 		 * have changed we need to update the peer's maxpsz.
16592 		 */
16593 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16594 		return (rwnd);
16595 	}
16596 
16597 	if (tcp_detached)
16598 		old_max_rwnd = tcp->tcp_rwnd;
16599 	else
16600 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
16601 
16602 	/*
16603 	 * Insist on a receive window that is at least
16604 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16605 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16606 	 * and delayed acknowledgement.
16607 	 */
16608 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16609 
16610 	/*
16611 	 * If window size info has already been exchanged, TCP should not
16612 	 * shrink the window.  Shrinking window is doable if done carefully.
16613 	 * We may add that support later.  But so far there is not a real
16614 	 * need to do that.
16615 	 */
16616 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16617 		/* MSS may have changed, do a round up again. */
16618 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16619 	}
16620 
16621 	/*
16622 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16623 	 * can be applied even before the window scale option is decided.
16624 	 */
16625 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16626 	if (rwnd > max_transmittable_rwnd) {
16627 		rwnd = max_transmittable_rwnd -
16628 		    (max_transmittable_rwnd % mss);
16629 		if (rwnd < mss)
16630 			rwnd = max_transmittable_rwnd;
16631 		/*
16632 		 * If we're over the limit we may have to back down tcp_rwnd.
16633 		 * The increment below won't work for us. So we set all three
16634 		 * here and the increment below will have no effect.
16635 		 */
16636 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16637 	}
16638 	if (tcp->tcp_localnet) {
16639 		tcp->tcp_rack_abs_max =
16640 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16641 	} else {
16642 		/*
16643 		 * For a remote host on a different subnet (through a router),
16644 		 * we ack every other packet to be conforming to RFC1122.
16645 		 * tcp_deferred_acks_max is default to 2.
16646 		 */
16647 		tcp->tcp_rack_abs_max =
16648 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16649 	}
16650 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16651 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16652 	else
16653 		tcp->tcp_rack_cur_max = 0;
16654 	/*
16655 	 * Increment the current rwnd by the amount the maximum grew (we
16656 	 * can not overwrite it since we might be in the middle of a
16657 	 * connection.)
16658 	 */
16659 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16660 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16661 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16662 		tcp->tcp_cwnd_max = rwnd;
16663 
16664 	if (tcp_detached)
16665 		return (rwnd);
16666 	/*
16667 	 * We set the maximum receive window into rq->q_hiwat.
16668 	 * This is not actually used for flow control.
16669 	 */
16670 	tcp->tcp_rq->q_hiwat = rwnd;
16671 	/*
16672 	 * Set the Stream head high water mark. This doesn't have to be
16673 	 * here, since we are simply using default values, but we would
16674 	 * prefer to choose these values algorithmically, with a likely
16675 	 * relationship to rwnd.
16676 	 */
16677 	(void) mi_set_sth_hiwat(tcp->tcp_rq,
16678 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16679 	return (rwnd);
16680 }
16681 
16682 /*
16683  * Return SNMP stuff in buffer in mpdata.
16684  */
16685 mblk_t *
16686 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16687 {
16688 	mblk_t			*mpdata;
16689 	mblk_t			*mp_conn_ctl = NULL;
16690 	mblk_t			*mp_conn_tail;
16691 	mblk_t			*mp_attr_ctl = NULL;
16692 	mblk_t			*mp_attr_tail;
16693 	mblk_t			*mp6_conn_ctl = NULL;
16694 	mblk_t			*mp6_conn_tail;
16695 	mblk_t			*mp6_attr_ctl = NULL;
16696 	mblk_t			*mp6_attr_tail;
16697 	struct opthdr		*optp;
16698 	mib2_tcpConnEntry_t	tce;
16699 	mib2_tcp6ConnEntry_t	tce6;
16700 	mib2_transportMLPEntry_t mlp;
16701 	connf_t			*connfp;
16702 	int			i;
16703 	boolean_t 		ispriv;
16704 	zoneid_t 		zoneid;
16705 	int			v4_conn_idx;
16706 	int			v6_conn_idx;
16707 	conn_t			*connp = Q_TO_CONN(q);
16708 	tcp_stack_t		*tcps;
16709 	ip_stack_t		*ipst;
16710 	mblk_t			*mp2ctl;
16711 
16712 	/*
16713 	 * make a copy of the original message
16714 	 */
16715 	mp2ctl = copymsg(mpctl);
16716 
16717 	if (mpctl == NULL ||
16718 	    (mpdata = mpctl->b_cont) == NULL ||
16719 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16720 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16721 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16722 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16723 		freemsg(mp_conn_ctl);
16724 		freemsg(mp_attr_ctl);
16725 		freemsg(mp6_conn_ctl);
16726 		freemsg(mp6_attr_ctl);
16727 		freemsg(mpctl);
16728 		freemsg(mp2ctl);
16729 		return (NULL);
16730 	}
16731 
16732 	ipst = connp->conn_netstack->netstack_ip;
16733 	tcps = connp->conn_netstack->netstack_tcp;
16734 
16735 	/* build table of connections -- need count in fixed part */
16736 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16737 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16738 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16739 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16740 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16741 
16742 	ispriv =
16743 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16744 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16745 
16746 	v4_conn_idx = v6_conn_idx = 0;
16747 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16748 
16749 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16750 		ipst = tcps->tcps_netstack->netstack_ip;
16751 
16752 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16753 
16754 		connp = NULL;
16755 
16756 		while ((connp =
16757 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16758 			tcp_t *tcp;
16759 			boolean_t needattr;
16760 
16761 			if (connp->conn_zoneid != zoneid)
16762 				continue;	/* not in this zone */
16763 
16764 			tcp = connp->conn_tcp;
16765 			UPDATE_MIB(&tcps->tcps_mib,
16766 			    tcpHCInSegs, tcp->tcp_ibsegs);
16767 			tcp->tcp_ibsegs = 0;
16768 			UPDATE_MIB(&tcps->tcps_mib,
16769 			    tcpHCOutSegs, tcp->tcp_obsegs);
16770 			tcp->tcp_obsegs = 0;
16771 
16772 			tce6.tcp6ConnState = tce.tcpConnState =
16773 			    tcp_snmp_state(tcp);
16774 			if (tce.tcpConnState == MIB2_TCP_established ||
16775 			    tce.tcpConnState == MIB2_TCP_closeWait)
16776 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16777 
16778 			needattr = B_FALSE;
16779 			bzero(&mlp, sizeof (mlp));
16780 			if (connp->conn_mlp_type != mlptSingle) {
16781 				if (connp->conn_mlp_type == mlptShared ||
16782 				    connp->conn_mlp_type == mlptBoth)
16783 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16784 				if (connp->conn_mlp_type == mlptPrivate ||
16785 				    connp->conn_mlp_type == mlptBoth)
16786 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16787 				needattr = B_TRUE;
16788 			}
16789 			if (connp->conn_peercred != NULL) {
16790 				ts_label_t *tsl;
16791 
16792 				tsl = crgetlabel(connp->conn_peercred);
16793 				mlp.tme_doi = label2doi(tsl);
16794 				mlp.tme_label = *label2bslabel(tsl);
16795 				needattr = B_TRUE;
16796 			}
16797 
16798 			/* Create a message to report on IPv6 entries */
16799 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16800 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16801 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16802 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16803 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16804 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16805 			/* Don't want just anybody seeing these... */
16806 			if (ispriv) {
16807 				tce6.tcp6ConnEntryInfo.ce_snxt =
16808 				    tcp->tcp_snxt;
16809 				tce6.tcp6ConnEntryInfo.ce_suna =
16810 				    tcp->tcp_suna;
16811 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16812 				    tcp->tcp_rnxt;
16813 				tce6.tcp6ConnEntryInfo.ce_rack =
16814 				    tcp->tcp_rack;
16815 			} else {
16816 				/*
16817 				 * Netstat, unfortunately, uses this to
16818 				 * get send/receive queue sizes.  How to fix?
16819 				 * Why not compute the difference only?
16820 				 */
16821 				tce6.tcp6ConnEntryInfo.ce_snxt =
16822 				    tcp->tcp_snxt - tcp->tcp_suna;
16823 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16824 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16825 				    tcp->tcp_rnxt - tcp->tcp_rack;
16826 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16827 			}
16828 
16829 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16830 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16831 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16832 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16833 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16834 
16835 			tce6.tcp6ConnCreationProcess =
16836 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16837 			    tcp->tcp_cpid;
16838 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16839 
16840 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16841 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16842 
16843 			mlp.tme_connidx = v6_conn_idx++;
16844 			if (needattr)
16845 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16846 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16847 			}
16848 			/*
16849 			 * Create an IPv4 table entry for IPv4 entries and also
16850 			 * for IPv6 entries which are bound to in6addr_any
16851 			 * but don't have IPV6_V6ONLY set.
16852 			 * (i.e. anything an IPv4 peer could connect to)
16853 			 */
16854 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16855 			    (tcp->tcp_state <= TCPS_LISTEN &&
16856 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16857 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16858 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16859 					tce.tcpConnRemAddress = INADDR_ANY;
16860 					tce.tcpConnLocalAddress = INADDR_ANY;
16861 				} else {
16862 					tce.tcpConnRemAddress =
16863 					    tcp->tcp_remote;
16864 					tce.tcpConnLocalAddress =
16865 					    tcp->tcp_ip_src;
16866 				}
16867 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16868 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16869 				/* Don't want just anybody seeing these... */
16870 				if (ispriv) {
16871 					tce.tcpConnEntryInfo.ce_snxt =
16872 					    tcp->tcp_snxt;
16873 					tce.tcpConnEntryInfo.ce_suna =
16874 					    tcp->tcp_suna;
16875 					tce.tcpConnEntryInfo.ce_rnxt =
16876 					    tcp->tcp_rnxt;
16877 					tce.tcpConnEntryInfo.ce_rack =
16878 					    tcp->tcp_rack;
16879 				} else {
16880 					/*
16881 					 * Netstat, unfortunately, uses this to
16882 					 * get send/receive queue sizes.  How
16883 					 * to fix?
16884 					 * Why not compute the difference only?
16885 					 */
16886 					tce.tcpConnEntryInfo.ce_snxt =
16887 					    tcp->tcp_snxt - tcp->tcp_suna;
16888 					tce.tcpConnEntryInfo.ce_suna = 0;
16889 					tce.tcpConnEntryInfo.ce_rnxt =
16890 					    tcp->tcp_rnxt - tcp->tcp_rack;
16891 					tce.tcpConnEntryInfo.ce_rack = 0;
16892 				}
16893 
16894 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16895 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16896 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16897 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16898 				tce.tcpConnEntryInfo.ce_state =
16899 				    tcp->tcp_state;
16900 
16901 				tce.tcpConnCreationProcess =
16902 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16903 				    tcp->tcp_cpid;
16904 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16905 
16906 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16907 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16908 
16909 				mlp.tme_connidx = v4_conn_idx++;
16910 				if (needattr)
16911 					(void) snmp_append_data2(
16912 					    mp_attr_ctl->b_cont,
16913 					    &mp_attr_tail, (char *)&mlp,
16914 					    sizeof (mlp));
16915 			}
16916 		}
16917 	}
16918 
16919 	/* fixed length structure for IPv4 and IPv6 counters */
16920 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16921 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16922 	    sizeof (mib2_tcp6ConnEntry_t));
16923 	/* synchronize 32- and 64-bit counters */
16924 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16925 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16926 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16927 	optp->level = MIB2_TCP;
16928 	optp->name = 0;
16929 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16930 	    sizeof (tcps->tcps_mib));
16931 	optp->len = msgdsize(mpdata);
16932 	qreply(q, mpctl);
16933 
16934 	/* table of connections... */
16935 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16936 	    sizeof (struct T_optmgmt_ack)];
16937 	optp->level = MIB2_TCP;
16938 	optp->name = MIB2_TCP_CONN;
16939 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16940 	qreply(q, mp_conn_ctl);
16941 
16942 	/* table of MLP attributes... */
16943 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16944 	    sizeof (struct T_optmgmt_ack)];
16945 	optp->level = MIB2_TCP;
16946 	optp->name = EXPER_XPORT_MLP;
16947 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16948 	if (optp->len == 0)
16949 		freemsg(mp_attr_ctl);
16950 	else
16951 		qreply(q, mp_attr_ctl);
16952 
16953 	/* table of IPv6 connections... */
16954 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16955 	    sizeof (struct T_optmgmt_ack)];
16956 	optp->level = MIB2_TCP6;
16957 	optp->name = MIB2_TCP6_CONN;
16958 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16959 	qreply(q, mp6_conn_ctl);
16960 
16961 	/* table of IPv6 MLP attributes... */
16962 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16963 	    sizeof (struct T_optmgmt_ack)];
16964 	optp->level = MIB2_TCP6;
16965 	optp->name = EXPER_XPORT_MLP;
16966 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16967 	if (optp->len == 0)
16968 		freemsg(mp6_attr_ctl);
16969 	else
16970 		qreply(q, mp6_attr_ctl);
16971 	return (mp2ctl);
16972 }
16973 
16974 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16975 /* ARGSUSED */
16976 int
16977 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16978 {
16979 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16980 
16981 	switch (level) {
16982 	case MIB2_TCP:
16983 		switch (name) {
16984 		case 13:
16985 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16986 				return (0);
16987 			/* TODO: delete entry defined by tce */
16988 			return (1);
16989 		default:
16990 			return (0);
16991 		}
16992 	default:
16993 		return (1);
16994 	}
16995 }
16996 
16997 /* Translate TCP state to MIB2 TCP state. */
16998 static int
16999 tcp_snmp_state(tcp_t *tcp)
17000 {
17001 	if (tcp == NULL)
17002 		return (0);
17003 
17004 	switch (tcp->tcp_state) {
17005 	case TCPS_CLOSED:
17006 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
17007 	case TCPS_BOUND:
17008 		return (MIB2_TCP_closed);
17009 	case TCPS_LISTEN:
17010 		return (MIB2_TCP_listen);
17011 	case TCPS_SYN_SENT:
17012 		return (MIB2_TCP_synSent);
17013 	case TCPS_SYN_RCVD:
17014 		return (MIB2_TCP_synReceived);
17015 	case TCPS_ESTABLISHED:
17016 		return (MIB2_TCP_established);
17017 	case TCPS_CLOSE_WAIT:
17018 		return (MIB2_TCP_closeWait);
17019 	case TCPS_FIN_WAIT_1:
17020 		return (MIB2_TCP_finWait1);
17021 	case TCPS_CLOSING:
17022 		return (MIB2_TCP_closing);
17023 	case TCPS_LAST_ACK:
17024 		return (MIB2_TCP_lastAck);
17025 	case TCPS_FIN_WAIT_2:
17026 		return (MIB2_TCP_finWait2);
17027 	case TCPS_TIME_WAIT:
17028 		return (MIB2_TCP_timeWait);
17029 	default:
17030 		return (0);
17031 	}
17032 }
17033 
17034 static char tcp_report_header[] =
17035 	"TCP     " MI_COL_HDRPAD_STR
17036 	"zone dest            snxt     suna     "
17037 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
17038 	"recent   [lport,fport] state";
17039 
17040 /*
17041  * TCP status report triggered via the Named Dispatch mechanism.
17042  */
17043 /* ARGSUSED */
17044 static void
17045 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
17046     cred_t *cr)
17047 {
17048 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
17049 	boolean_t ispriv = secpolicy_ip_config(cr, B_TRUE) == 0;
17050 	char cflag;
17051 	in6_addr_t	v6dst;
17052 	char buf[80];
17053 	uint_t print_len, buf_len;
17054 
17055 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
17056 	if (buf_len <= 0)
17057 		return;
17058 
17059 	if (hashval >= 0)
17060 		(void) sprintf(hash, "%03d ", hashval);
17061 	else
17062 		hash[0] = '\0';
17063 
17064 	/*
17065 	 * Note that we use the remote address in the tcp_b  structure.
17066 	 * This means that it will print out the real destination address,
17067 	 * not the next hop's address if source routing is used.  This
17068 	 * avoid the confusion on the output because user may not
17069 	 * know that source routing is used for a connection.
17070 	 */
17071 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17072 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
17073 	} else {
17074 		v6dst = tcp->tcp_remote_v6;
17075 	}
17076 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
17077 	/*
17078 	 * the ispriv checks are so that normal users cannot determine
17079 	 * sequence number information using NDD.
17080 	 */
17081 
17082 	if (TCP_IS_DETACHED(tcp))
17083 		cflag = '*';
17084 	else
17085 		cflag = ' ';
17086 	print_len = snprintf((char *)mp->b_wptr, buf_len,
17087 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
17088 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
17089 	    hash,
17090 	    (void *)tcp,
17091 	    tcp->tcp_connp->conn_zoneid,
17092 	    addrbuf,
17093 	    (ispriv) ? tcp->tcp_snxt : 0,
17094 	    (ispriv) ? tcp->tcp_suna : 0,
17095 	    tcp->tcp_swnd,
17096 	    (ispriv) ? tcp->tcp_rnxt : 0,
17097 	    (ispriv) ? tcp->tcp_rack : 0,
17098 	    tcp->tcp_rwnd,
17099 	    tcp->tcp_rto,
17100 	    tcp->tcp_mss,
17101 	    tcp->tcp_snd_ws_ok,
17102 	    tcp->tcp_snd_ws,
17103 	    tcp->tcp_rcv_ws,
17104 	    tcp->tcp_snd_ts_ok,
17105 	    tcp->tcp_ts_recent,
17106 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
17107 	if (print_len < buf_len) {
17108 		((mblk_t *)mp)->b_wptr += print_len;
17109 	} else {
17110 		((mblk_t *)mp)->b_wptr += buf_len;
17111 	}
17112 }
17113 
17114 /*
17115  * TCP status report (for listeners only) triggered via the Named Dispatch
17116  * mechanism.
17117  */
17118 /* ARGSUSED */
17119 static void
17120 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
17121 {
17122 	char addrbuf[INET6_ADDRSTRLEN];
17123 	in6_addr_t	v6dst;
17124 	uint_t print_len, buf_len;
17125 
17126 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
17127 	if (buf_len <= 0)
17128 		return;
17129 
17130 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17131 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
17132 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
17133 	} else {
17134 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
17135 		    addrbuf, sizeof (addrbuf));
17136 	}
17137 	print_len = snprintf((char *)mp->b_wptr, buf_len,
17138 	    "%03d "
17139 	    MI_COL_PTRFMT_STR
17140 	    "%d %s %05u %08u %d/%d/%d%c\n",
17141 	    hashval, (void *)tcp,
17142 	    tcp->tcp_connp->conn_zoneid,
17143 	    addrbuf,
17144 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
17145 	    tcp->tcp_conn_req_seqnum,
17146 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
17147 	    tcp->tcp_conn_req_max,
17148 	    tcp->tcp_syn_defense ? '*' : ' ');
17149 	if (print_len < buf_len) {
17150 		((mblk_t *)mp)->b_wptr += print_len;
17151 	} else {
17152 		((mblk_t *)mp)->b_wptr += buf_len;
17153 	}
17154 }
17155 
17156 /* TCP status report triggered via the Named Dispatch mechanism. */
17157 /* ARGSUSED */
17158 static int
17159 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17160 {
17161 	tcp_t	*tcp;
17162 	int	i;
17163 	conn_t	*connp;
17164 	connf_t	*connfp;
17165 	zoneid_t zoneid;
17166 	tcp_stack_t *tcps;
17167 	ip_stack_t *ipst;
17168 
17169 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17170 	tcps = Q_TO_TCP(q)->tcp_tcps;
17171 
17172 	/*
17173 	 * Because of the ndd constraint, at most we can have 64K buffer
17174 	 * to put in all TCP info.  So to be more efficient, just
17175 	 * allocate a 64K buffer here, assuming we need that large buffer.
17176 	 * This may be a problem as any user can read tcp_status.  Therefore
17177 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
17178 	 * This should be OK as normal users should not do this too often.
17179 	 */
17180 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17181 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17182 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17183 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17184 			return (0);
17185 		}
17186 	}
17187 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17188 		/* The following may work even if we cannot get a large buf. */
17189 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17190 		return (0);
17191 	}
17192 
17193 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
17194 
17195 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
17196 
17197 		ipst = tcps->tcps_netstack->netstack_ip;
17198 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
17199 
17200 		connp = NULL;
17201 
17202 		while ((connp =
17203 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
17204 			tcp = connp->conn_tcp;
17205 			if (zoneid != GLOBAL_ZONEID &&
17206 			    zoneid != connp->conn_zoneid)
17207 				continue;
17208 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
17209 			    cr);
17210 		}
17211 
17212 	}
17213 
17214 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17215 	return (0);
17216 }
17217 
17218 /* TCP status report triggered via the Named Dispatch mechanism. */
17219 /* ARGSUSED */
17220 static int
17221 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17222 {
17223 	tf_t	*tbf;
17224 	tcp_t	*tcp;
17225 	int	i;
17226 	zoneid_t zoneid;
17227 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
17228 
17229 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17230 
17231 	/* Refer to comments in tcp_status_report(). */
17232 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17233 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17234 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17235 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17236 			return (0);
17237 		}
17238 	}
17239 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17240 		/* The following may work even if we cannot get a large buf. */
17241 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17242 		return (0);
17243 	}
17244 
17245 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
17246 
17247 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
17248 		tbf = &tcps->tcps_bind_fanout[i];
17249 		mutex_enter(&tbf->tf_lock);
17250 		for (tcp = tbf->tf_tcp; tcp != NULL;
17251 		    tcp = tcp->tcp_bind_hash) {
17252 			if (zoneid != GLOBAL_ZONEID &&
17253 			    zoneid != tcp->tcp_connp->conn_zoneid)
17254 				continue;
17255 			CONN_INC_REF(tcp->tcp_connp);
17256 			tcp_report_item(mp->b_cont, tcp, i,
17257 			    Q_TO_TCP(q), cr);
17258 			CONN_DEC_REF(tcp->tcp_connp);
17259 		}
17260 		mutex_exit(&tbf->tf_lock);
17261 	}
17262 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17263 	return (0);
17264 }
17265 
17266 /* TCP status report triggered via the Named Dispatch mechanism. */
17267 /* ARGSUSED */
17268 static int
17269 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17270 {
17271 	connf_t	*connfp;
17272 	conn_t	*connp;
17273 	tcp_t	*tcp;
17274 	int	i;
17275 	zoneid_t zoneid;
17276 	tcp_stack_t *tcps;
17277 	ip_stack_t	*ipst;
17278 
17279 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17280 	tcps = Q_TO_TCP(q)->tcp_tcps;
17281 
17282 	/* Refer to comments in tcp_status_report(). */
17283 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17284 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17285 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17286 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17287 			return (0);
17288 		}
17289 	}
17290 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17291 		/* The following may work even if we cannot get a large buf. */
17292 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17293 		return (0);
17294 	}
17295 
17296 	(void) mi_mpprintf(mp,
17297 	    "    TCP    " MI_COL_HDRPAD_STR
17298 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
17299 
17300 	ipst = tcps->tcps_netstack->netstack_ip;
17301 
17302 	for (i = 0; i < ipst->ips_ipcl_bind_fanout_size; i++) {
17303 		connfp = &ipst->ips_ipcl_bind_fanout[i];
17304 		connp = NULL;
17305 		while ((connp =
17306 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
17307 			tcp = connp->conn_tcp;
17308 			if (zoneid != GLOBAL_ZONEID &&
17309 			    zoneid != connp->conn_zoneid)
17310 				continue;
17311 			tcp_report_listener(mp->b_cont, tcp, i);
17312 		}
17313 	}
17314 
17315 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17316 	return (0);
17317 }
17318 
17319 /* TCP status report triggered via the Named Dispatch mechanism. */
17320 /* ARGSUSED */
17321 static int
17322 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17323 {
17324 	connf_t	*connfp;
17325 	conn_t	*connp;
17326 	tcp_t	*tcp;
17327 	int	i;
17328 	zoneid_t zoneid;
17329 	tcp_stack_t *tcps;
17330 	ip_stack_t *ipst;
17331 
17332 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17333 	tcps = Q_TO_TCP(q)->tcp_tcps;
17334 	ipst = tcps->tcps_netstack->netstack_ip;
17335 
17336 	/* Refer to comments in tcp_status_report(). */
17337 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17338 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17339 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17340 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17341 			return (0);
17342 		}
17343 	}
17344 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17345 		/* The following may work even if we cannot get a large buf. */
17346 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17347 		return (0);
17348 	}
17349 
17350 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
17351 	    ipst->ips_ipcl_conn_fanout_size);
17352 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
17353 
17354 	for (i = 0; i < ipst->ips_ipcl_conn_fanout_size; i++) {
17355 		connfp =  &ipst->ips_ipcl_conn_fanout[i];
17356 		connp = NULL;
17357 		while ((connp =
17358 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
17359 			tcp = connp->conn_tcp;
17360 			if (zoneid != GLOBAL_ZONEID &&
17361 			    zoneid != connp->conn_zoneid)
17362 				continue;
17363 			tcp_report_item(mp->b_cont, tcp, i,
17364 			    Q_TO_TCP(q), cr);
17365 		}
17366 	}
17367 
17368 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17369 	return (0);
17370 }
17371 
17372 /* TCP status report triggered via the Named Dispatch mechanism. */
17373 /* ARGSUSED */
17374 static int
17375 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17376 {
17377 	tf_t	*tf;
17378 	tcp_t	*tcp;
17379 	int	i;
17380 	zoneid_t zoneid;
17381 	tcp_stack_t	*tcps;
17382 
17383 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17384 	tcps = Q_TO_TCP(q)->tcp_tcps;
17385 
17386 	/* Refer to comments in tcp_status_report(). */
17387 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17388 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17389 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17390 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17391 			return (0);
17392 		}
17393 	}
17394 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17395 		/* The following may work even if we cannot get a large buf. */
17396 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17397 		return (0);
17398 	}
17399 
17400 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
17401 
17402 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
17403 		tf = &tcps->tcps_acceptor_fanout[i];
17404 		mutex_enter(&tf->tf_lock);
17405 		for (tcp = tf->tf_tcp; tcp != NULL;
17406 		    tcp = tcp->tcp_acceptor_hash) {
17407 			if (zoneid != GLOBAL_ZONEID &&
17408 			    zoneid != tcp->tcp_connp->conn_zoneid)
17409 				continue;
17410 			tcp_report_item(mp->b_cont, tcp, i,
17411 			    Q_TO_TCP(q), cr);
17412 		}
17413 		mutex_exit(&tf->tf_lock);
17414 	}
17415 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17416 	return (0);
17417 }
17418 
17419 /*
17420  * tcp_timer is the timer service routine.  It handles the retransmission,
17421  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
17422  * from the state of the tcp instance what kind of action needs to be done
17423  * at the time it is called.
17424  */
17425 static void
17426 tcp_timer(void *arg)
17427 {
17428 	mblk_t		*mp;
17429 	clock_t		first_threshold;
17430 	clock_t		second_threshold;
17431 	clock_t		ms;
17432 	uint32_t	mss;
17433 	conn_t		*connp = (conn_t *)arg;
17434 	tcp_t		*tcp = connp->conn_tcp;
17435 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17436 
17437 	tcp->tcp_timer_tid = 0;
17438 
17439 	if (tcp->tcp_fused)
17440 		return;
17441 
17442 	first_threshold =  tcp->tcp_first_timer_threshold;
17443 	second_threshold = tcp->tcp_second_timer_threshold;
17444 	switch (tcp->tcp_state) {
17445 	case TCPS_IDLE:
17446 	case TCPS_BOUND:
17447 	case TCPS_LISTEN:
17448 		return;
17449 	case TCPS_SYN_RCVD: {
17450 		tcp_t	*listener = tcp->tcp_listener;
17451 
17452 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
17453 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
17454 			/* it's our first timeout */
17455 			tcp->tcp_syn_rcvd_timeout = 1;
17456 			mutex_enter(&listener->tcp_eager_lock);
17457 			listener->tcp_syn_rcvd_timeout++;
17458 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
17459 				/*
17460 				 * Make this eager available for drop if we
17461 				 * need to drop one to accomodate a new
17462 				 * incoming SYN request.
17463 				 */
17464 				MAKE_DROPPABLE(listener, tcp);
17465 			}
17466 			if (!listener->tcp_syn_defense &&
17467 			    (listener->tcp_syn_rcvd_timeout >
17468 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
17469 			    (tcps->tcps_conn_req_max_q0 > 200)) {
17470 				/* We may be under attack. Put on a defense. */
17471 				listener->tcp_syn_defense = B_TRUE;
17472 				cmn_err(CE_WARN, "High TCP connect timeout "
17473 				    "rate! System (port %d) may be under a "
17474 				    "SYN flood attack!",
17475 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
17476 
17477 				listener->tcp_ip_addr_cache = kmem_zalloc(
17478 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
17479 				    KM_NOSLEEP);
17480 			}
17481 			mutex_exit(&listener->tcp_eager_lock);
17482 		} else if (listener != NULL) {
17483 			mutex_enter(&listener->tcp_eager_lock);
17484 			tcp->tcp_syn_rcvd_timeout++;
17485 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
17486 			    !tcp->tcp_closemp_used) {
17487 				/*
17488 				 * This is our second timeout. Put the tcp in
17489 				 * the list of droppable eagers to allow it to
17490 				 * be dropped, if needed. We don't check
17491 				 * whether tcp_dontdrop is set or not to
17492 				 * protect ourselve from a SYN attack where a
17493 				 * remote host can spoof itself as one of the
17494 				 * good IP source and continue to hold
17495 				 * resources too long.
17496 				 */
17497 				MAKE_DROPPABLE(listener, tcp);
17498 			}
17499 			mutex_exit(&listener->tcp_eager_lock);
17500 		}
17501 	}
17502 		/* FALLTHRU */
17503 	case TCPS_SYN_SENT:
17504 		first_threshold =  tcp->tcp_first_ctimer_threshold;
17505 		second_threshold = tcp->tcp_second_ctimer_threshold;
17506 		break;
17507 	case TCPS_ESTABLISHED:
17508 	case TCPS_FIN_WAIT_1:
17509 	case TCPS_CLOSING:
17510 	case TCPS_CLOSE_WAIT:
17511 	case TCPS_LAST_ACK:
17512 		/* If we have data to rexmit */
17513 		if (tcp->tcp_suna != tcp->tcp_snxt) {
17514 			clock_t	time_to_wait;
17515 
17516 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
17517 			if (!tcp->tcp_xmit_head)
17518 				break;
17519 			time_to_wait = lbolt -
17520 			    (clock_t)tcp->tcp_xmit_head->b_prev;
17521 			time_to_wait = tcp->tcp_rto -
17522 			    TICK_TO_MSEC(time_to_wait);
17523 			/*
17524 			 * If the timer fires too early, 1 clock tick earlier,
17525 			 * restart the timer.
17526 			 */
17527 			if (time_to_wait > msec_per_tick) {
17528 				TCP_STAT(tcps, tcp_timer_fire_early);
17529 				TCP_TIMER_RESTART(tcp, time_to_wait);
17530 				return;
17531 			}
17532 			/*
17533 			 * When we probe zero windows, we force the swnd open.
17534 			 * If our peer acks with a closed window swnd will be
17535 			 * set to zero by tcp_rput(). As long as we are
17536 			 * receiving acks tcp_rput will
17537 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
17538 			 * first and second interval actions.  NOTE: the timer
17539 			 * interval is allowed to continue its exponential
17540 			 * backoff.
17541 			 */
17542 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
17543 				if (tcp->tcp_debug) {
17544 					(void) strlog(TCP_MOD_ID, 0, 1,
17545 					    SL_TRACE, "tcp_timer: zero win");
17546 				}
17547 			} else {
17548 				/*
17549 				 * After retransmission, we need to do
17550 				 * slow start.  Set the ssthresh to one
17551 				 * half of current effective window and
17552 				 * cwnd to one MSS.  Also reset
17553 				 * tcp_cwnd_cnt.
17554 				 *
17555 				 * Note that if tcp_ssthresh is reduced because
17556 				 * of ECN, do not reduce it again unless it is
17557 				 * already one window of data away (tcp_cwr
17558 				 * should then be cleared) or this is a
17559 				 * timeout for a retransmitted segment.
17560 				 */
17561 				uint32_t npkt;
17562 
17563 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
17564 					npkt = ((tcp->tcp_timer_backoff ?
17565 					    tcp->tcp_cwnd_ssthresh :
17566 					    tcp->tcp_snxt -
17567 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
17568 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
17569 					    tcp->tcp_mss;
17570 				}
17571 				tcp->tcp_cwnd = tcp->tcp_mss;
17572 				tcp->tcp_cwnd_cnt = 0;
17573 				if (tcp->tcp_ecn_ok) {
17574 					tcp->tcp_cwr = B_TRUE;
17575 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17576 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17577 				}
17578 			}
17579 			break;
17580 		}
17581 		/*
17582 		 * We have something to send yet we cannot send.  The
17583 		 * reason can be:
17584 		 *
17585 		 * 1. Zero send window: we need to do zero window probe.
17586 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17587 		 * segments.
17588 		 * 3. SWS avoidance: receiver may have shrunk window,
17589 		 * reset our knowledge.
17590 		 *
17591 		 * Note that condition 2 can happen with either 1 or
17592 		 * 3.  But 1 and 3 are exclusive.
17593 		 */
17594 		if (tcp->tcp_unsent != 0) {
17595 			if (tcp->tcp_cwnd == 0) {
17596 				/*
17597 				 * Set tcp_cwnd to 1 MSS so that a
17598 				 * new segment can be sent out.  We
17599 				 * are "clocking out" new data when
17600 				 * the network is really congested.
17601 				 */
17602 				ASSERT(tcp->tcp_ecn_ok);
17603 				tcp->tcp_cwnd = tcp->tcp_mss;
17604 			}
17605 			if (tcp->tcp_swnd == 0) {
17606 				/* Extend window for zero window probe */
17607 				tcp->tcp_swnd++;
17608 				tcp->tcp_zero_win_probe = B_TRUE;
17609 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
17610 			} else {
17611 				/*
17612 				 * Handle timeout from sender SWS avoidance.
17613 				 * Reset our knowledge of the max send window
17614 				 * since the receiver might have reduced its
17615 				 * receive buffer.  Avoid setting tcp_max_swnd
17616 				 * to one since that will essentially disable
17617 				 * the SWS checks.
17618 				 *
17619 				 * Note that since we don't have a SWS
17620 				 * state variable, if the timeout is set
17621 				 * for ECN but not for SWS, this
17622 				 * code will also be executed.  This is
17623 				 * fine as tcp_max_swnd is updated
17624 				 * constantly and it will not affect
17625 				 * anything.
17626 				 */
17627 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17628 			}
17629 			tcp_wput_data(tcp, NULL, B_FALSE);
17630 			return;
17631 		}
17632 		/* Is there a FIN that needs to be to re retransmitted? */
17633 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17634 		    !tcp->tcp_fin_acked)
17635 			break;
17636 		/* Nothing to do, return without restarting timer. */
17637 		TCP_STAT(tcps, tcp_timer_fire_miss);
17638 		return;
17639 	case TCPS_FIN_WAIT_2:
17640 		/*
17641 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17642 		 * We waited some time for for peer's FIN, but it hasn't
17643 		 * arrived.  We flush the connection now to avoid
17644 		 * case where the peer has rebooted.
17645 		 */
17646 		if (TCP_IS_DETACHED(tcp)) {
17647 			(void) tcp_clean_death(tcp, 0, 23);
17648 		} else {
17649 			TCP_TIMER_RESTART(tcp,
17650 			    tcps->tcps_fin_wait_2_flush_interval);
17651 		}
17652 		return;
17653 	case TCPS_TIME_WAIT:
17654 		(void) tcp_clean_death(tcp, 0, 24);
17655 		return;
17656 	default:
17657 		if (tcp->tcp_debug) {
17658 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
17659 			    "tcp_timer: strange state (%d) %s",
17660 			    tcp->tcp_state, tcp_display(tcp, NULL,
17661 			    DISP_PORT_ONLY));
17662 		}
17663 		return;
17664 	}
17665 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17666 		/*
17667 		 * For zero window probe, we need to send indefinitely,
17668 		 * unless we have not heard from the other side for some
17669 		 * time...
17670 		 */
17671 		if ((tcp->tcp_zero_win_probe == 0) ||
17672 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17673 		    second_threshold)) {
17674 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
17675 			/*
17676 			 * If TCP is in SYN_RCVD state, send back a
17677 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17678 			 * should be zero in TCPS_SYN_RCVD state.
17679 			 */
17680 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17681 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17682 				    "in SYN_RCVD",
17683 				    tcp, tcp->tcp_snxt,
17684 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17685 			}
17686 			(void) tcp_clean_death(tcp,
17687 			    tcp->tcp_client_errno ?
17688 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17689 			return;
17690 		} else {
17691 			/*
17692 			 * Set tcp_ms_we_have_waited to second_threshold
17693 			 * so that in next timeout, we will do the above
17694 			 * check (lbolt - tcp_last_recv_time).  This is
17695 			 * also to avoid overflow.
17696 			 *
17697 			 * We don't need to decrement tcp_timer_backoff
17698 			 * to avoid overflow because it will be decremented
17699 			 * later if new timeout value is greater than
17700 			 * tcp_rexmit_interval_max.  In the case when
17701 			 * tcp_rexmit_interval_max is greater than
17702 			 * second_threshold, it means that we will wait
17703 			 * longer than second_threshold to send the next
17704 			 * window probe.
17705 			 */
17706 			tcp->tcp_ms_we_have_waited = second_threshold;
17707 		}
17708 	} else if (ms > first_threshold) {
17709 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17710 		    tcp->tcp_xmit_head != NULL) {
17711 			tcp->tcp_xmit_head =
17712 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17713 		}
17714 		/*
17715 		 * We have been retransmitting for too long...  The RTT
17716 		 * we calculated is probably incorrect.  Reinitialize it.
17717 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17718 		 * tcp_rtt_update so that we won't accidentally cache a
17719 		 * bad value.  But only do this if this is not a zero
17720 		 * window probe.
17721 		 */
17722 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17723 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17724 			    (tcp->tcp_rtt_sa >> 5);
17725 			tcp->tcp_rtt_sa = 0;
17726 			tcp_ip_notify(tcp);
17727 			tcp->tcp_rtt_update = 0;
17728 		}
17729 	}
17730 	tcp->tcp_timer_backoff++;
17731 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17732 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17733 	    tcps->tcps_rexmit_interval_min) {
17734 		/*
17735 		 * This means the original RTO is tcp_rexmit_interval_min.
17736 		 * So we will use tcp_rexmit_interval_min as the RTO value
17737 		 * and do the backoff.
17738 		 */
17739 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
17740 	} else {
17741 		ms <<= tcp->tcp_timer_backoff;
17742 	}
17743 	if (ms > tcps->tcps_rexmit_interval_max) {
17744 		ms = tcps->tcps_rexmit_interval_max;
17745 		/*
17746 		 * ms is at max, decrement tcp_timer_backoff to avoid
17747 		 * overflow.
17748 		 */
17749 		tcp->tcp_timer_backoff--;
17750 	}
17751 	tcp->tcp_ms_we_have_waited += ms;
17752 	if (tcp->tcp_zero_win_probe == 0) {
17753 		tcp->tcp_rto = ms;
17754 	}
17755 	TCP_TIMER_RESTART(tcp, ms);
17756 	/*
17757 	 * This is after a timeout and tcp_rto is backed off.  Set
17758 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17759 	 * restart the timer with a correct value.
17760 	 */
17761 	tcp->tcp_set_timer = 1;
17762 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17763 	if (mss > tcp->tcp_mss)
17764 		mss = tcp->tcp_mss;
17765 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17766 		mss = tcp->tcp_swnd;
17767 
17768 	if ((mp = tcp->tcp_xmit_head) != NULL)
17769 		mp->b_prev = (mblk_t *)lbolt;
17770 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17771 	    B_TRUE);
17772 
17773 	/*
17774 	 * When slow start after retransmission begins, start with
17775 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17776 	 * start phase.  tcp_snd_burst controls how many segments
17777 	 * can be sent because of an ack.
17778 	 */
17779 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17780 	tcp->tcp_snd_burst = TCP_CWND_SS;
17781 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17782 	    (tcp->tcp_unsent == 0)) {
17783 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17784 	} else {
17785 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17786 	}
17787 	tcp->tcp_rexmit = B_TRUE;
17788 	tcp->tcp_dupack_cnt = 0;
17789 
17790 	/*
17791 	 * Remove all rexmit SACK blk to start from fresh.
17792 	 */
17793 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17794 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17795 		tcp->tcp_num_notsack_blk = 0;
17796 		tcp->tcp_cnt_notsack_list = 0;
17797 	}
17798 	if (mp == NULL) {
17799 		return;
17800 	}
17801 	/* Attach credentials to retransmitted initial SYNs. */
17802 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17803 		mblk_setcred(mp, tcp->tcp_cred);
17804 		DB_CPID(mp) = tcp->tcp_cpid;
17805 	}
17806 
17807 	tcp->tcp_csuna = tcp->tcp_snxt;
17808 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17809 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17810 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
17811 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17812 
17813 }
17814 
17815 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17816 static void
17817 tcp_unbind(tcp_t *tcp, mblk_t *mp)
17818 {
17819 	conn_t	*connp;
17820 
17821 	switch (tcp->tcp_state) {
17822 	case TCPS_BOUND:
17823 	case TCPS_LISTEN:
17824 		break;
17825 	default:
17826 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
17827 		return;
17828 	}
17829 
17830 	/*
17831 	 * Need to clean up all the eagers since after the unbind, segments
17832 	 * will no longer be delivered to this listener stream.
17833 	 */
17834 	mutex_enter(&tcp->tcp_eager_lock);
17835 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17836 		tcp_eager_cleanup(tcp, 0);
17837 	}
17838 	mutex_exit(&tcp->tcp_eager_lock);
17839 
17840 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17841 		tcp->tcp_ipha->ipha_src = 0;
17842 	} else {
17843 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17844 	}
17845 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17846 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17847 	tcp_bind_hash_remove(tcp);
17848 	tcp->tcp_state = TCPS_IDLE;
17849 	tcp->tcp_mdt = B_FALSE;
17850 	/* Send M_FLUSH according to TPI */
17851 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17852 	connp = tcp->tcp_connp;
17853 	connp->conn_mdt_ok = B_FALSE;
17854 	ipcl_hash_remove(connp);
17855 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17856 	mp = mi_tpi_ok_ack_alloc(mp);
17857 	putnext(tcp->tcp_rq, mp);
17858 }
17859 
17860 /*
17861  * Don't let port fall into the privileged range.
17862  * Since the extra privileged ports can be arbitrary we also
17863  * ensure that we exclude those from consideration.
17864  * tcp_g_epriv_ports is not sorted thus we loop over it until
17865  * there are no changes.
17866  *
17867  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17868  * but instead the code relies on:
17869  * - the fact that the address of the array and its size never changes
17870  * - the atomic assignment of the elements of the array
17871  *
17872  * Returns 0 if there are no more ports available.
17873  *
17874  * TS note: skip multilevel ports.
17875  */
17876 static in_port_t
17877 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17878 {
17879 	int i;
17880 	boolean_t restart = B_FALSE;
17881 	tcp_stack_t *tcps = tcp->tcp_tcps;
17882 
17883 	if (random && tcp_random_anon_port != 0) {
17884 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17885 		    sizeof (in_port_t));
17886 		/*
17887 		 * Unless changed by a sys admin, the smallest anon port
17888 		 * is 32768 and the largest anon port is 65535.  It is
17889 		 * very likely (50%) for the random port to be smaller
17890 		 * than the smallest anon port.  When that happens,
17891 		 * add port % (anon port range) to the smallest anon
17892 		 * port to get the random port.  It should fall into the
17893 		 * valid anon port range.
17894 		 */
17895 		if (port < tcps->tcps_smallest_anon_port) {
17896 			port = tcps->tcps_smallest_anon_port +
17897 			    port % (tcps->tcps_largest_anon_port -
17898 			    tcps->tcps_smallest_anon_port);
17899 		}
17900 	}
17901 
17902 retry:
17903 	if (port < tcps->tcps_smallest_anon_port)
17904 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17905 
17906 	if (port > tcps->tcps_largest_anon_port) {
17907 		if (restart)
17908 			return (0);
17909 		restart = B_TRUE;
17910 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17911 	}
17912 
17913 	if (port < tcps->tcps_smallest_nonpriv_port)
17914 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17915 
17916 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17917 		if (port == tcps->tcps_g_epriv_ports[i]) {
17918 			port++;
17919 			/*
17920 			 * Make sure whether the port is in the
17921 			 * valid range.
17922 			 */
17923 			goto retry;
17924 		}
17925 	}
17926 	if (is_system_labeled() &&
17927 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17928 	    IPPROTO_TCP, B_TRUE)) != 0) {
17929 		port = i;
17930 		goto retry;
17931 	}
17932 	return (port);
17933 }
17934 
17935 /*
17936  * Return the next anonymous port in the privileged port range for
17937  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17938  * downwards.  This is the same behavior as documented in the userland
17939  * library call rresvport(3N).
17940  *
17941  * TS note: skip multilevel ports.
17942  */
17943 static in_port_t
17944 tcp_get_next_priv_port(const tcp_t *tcp)
17945 {
17946 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17947 	in_port_t nextport;
17948 	boolean_t restart = B_FALSE;
17949 	tcp_stack_t *tcps = tcp->tcp_tcps;
17950 retry:
17951 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17952 	    next_priv_port >= IPPORT_RESERVED) {
17953 		next_priv_port = IPPORT_RESERVED - 1;
17954 		if (restart)
17955 			return (0);
17956 		restart = B_TRUE;
17957 	}
17958 	if (is_system_labeled() &&
17959 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17960 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17961 		next_priv_port = nextport;
17962 		goto retry;
17963 	}
17964 	return (next_priv_port--);
17965 }
17966 
17967 /* The write side r/w procedure. */
17968 
17969 #if CCS_STATS
17970 struct {
17971 	struct {
17972 		int64_t count, bytes;
17973 	} tot, hit;
17974 } wrw_stats;
17975 #endif
17976 
17977 /*
17978  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17979  * messages.
17980  */
17981 /* ARGSUSED */
17982 static void
17983 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17984 {
17985 	conn_t	*connp = (conn_t *)arg;
17986 	tcp_t	*tcp = connp->conn_tcp;
17987 	queue_t	*q = tcp->tcp_wq;
17988 
17989 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17990 	/*
17991 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17992 	 * Once the close starts, streamhead and sockfs will not let any data
17993 	 * packets come down (close ensures that there are no threads using the
17994 	 * queue and no new threads will come down) but since qprocsoff()
17995 	 * hasn't happened yet, a M_FLUSH or some non data message might
17996 	 * get reflected back (in response to our own FLUSHRW) and get
17997 	 * processed after tcp_close() is done. The conn would still be valid
17998 	 * because a ref would have added but we need to check the state
17999 	 * before actually processing the packet.
18000 	 */
18001 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
18002 		freemsg(mp);
18003 		return;
18004 	}
18005 
18006 	switch (DB_TYPE(mp)) {
18007 	case M_IOCDATA:
18008 		tcp_wput_iocdata(tcp, mp);
18009 		break;
18010 	case M_FLUSH:
18011 		tcp_wput_flush(tcp, mp);
18012 		break;
18013 	default:
18014 		CALL_IP_WPUT(connp, q, mp);
18015 		break;
18016 	}
18017 }
18018 
18019 /*
18020  * The TCP fast path write put procedure.
18021  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
18022  */
18023 /* ARGSUSED */
18024 void
18025 tcp_output(void *arg, mblk_t *mp, void *arg2)
18026 {
18027 	int		len;
18028 	int		hdrlen;
18029 	int		plen;
18030 	mblk_t		*mp1;
18031 	uchar_t		*rptr;
18032 	uint32_t	snxt;
18033 	tcph_t		*tcph;
18034 	struct datab	*db;
18035 	uint32_t	suna;
18036 	uint32_t	mss;
18037 	ipaddr_t	*dst;
18038 	ipaddr_t	*src;
18039 	uint32_t	sum;
18040 	int		usable;
18041 	conn_t		*connp = (conn_t *)arg;
18042 	tcp_t		*tcp = connp->conn_tcp;
18043 	uint32_t	msize;
18044 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18045 
18046 	/*
18047 	 * Try and ASSERT the minimum possible references on the
18048 	 * conn early enough. Since we are executing on write side,
18049 	 * the connection is obviously not detached and that means
18050 	 * there is a ref each for TCP and IP. Since we are behind
18051 	 * the squeue, the minimum references needed are 3. If the
18052 	 * conn is in classifier hash list, there should be an
18053 	 * extra ref for that (we check both the possibilities).
18054 	 */
18055 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18056 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18057 
18058 	ASSERT(DB_TYPE(mp) == M_DATA);
18059 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
18060 
18061 	mutex_enter(&tcp->tcp_non_sq_lock);
18062 	tcp->tcp_squeue_bytes -= msize;
18063 	mutex_exit(&tcp->tcp_non_sq_lock);
18064 
18065 	/* Bypass tcp protocol for fused tcp loopback */
18066 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
18067 		return;
18068 
18069 	mss = tcp->tcp_mss;
18070 	if (tcp->tcp_xmit_zc_clean)
18071 		mp = tcp_zcopy_backoff(tcp, mp, 0);
18072 
18073 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18074 	len = (int)(mp->b_wptr - mp->b_rptr);
18075 
18076 	/*
18077 	 * Criteria for fast path:
18078 	 *
18079 	 *   1. no unsent data
18080 	 *   2. single mblk in request
18081 	 *   3. connection established
18082 	 *   4. data in mblk
18083 	 *   5. len <= mss
18084 	 *   6. no tcp_valid bits
18085 	 */
18086 	if ((tcp->tcp_unsent != 0) ||
18087 	    (tcp->tcp_cork) ||
18088 	    (mp->b_cont != NULL) ||
18089 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
18090 	    (len == 0) ||
18091 	    (len > mss) ||
18092 	    (tcp->tcp_valid_bits != 0)) {
18093 		tcp_wput_data(tcp, mp, B_FALSE);
18094 		return;
18095 	}
18096 
18097 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
18098 	ASSERT(tcp->tcp_fin_sent == 0);
18099 
18100 	/* queue new packet onto retransmission queue */
18101 	if (tcp->tcp_xmit_head == NULL) {
18102 		tcp->tcp_xmit_head = mp;
18103 	} else {
18104 		tcp->tcp_xmit_last->b_cont = mp;
18105 	}
18106 	tcp->tcp_xmit_last = mp;
18107 	tcp->tcp_xmit_tail = mp;
18108 
18109 	/* find out how much we can send */
18110 	/* BEGIN CSTYLED */
18111 	/*
18112 	 *    un-acked           usable
18113 	 *  |--------------|-----------------|
18114 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
18115 	 */
18116 	/* END CSTYLED */
18117 
18118 	/* start sending from tcp_snxt */
18119 	snxt = tcp->tcp_snxt;
18120 
18121 	/*
18122 	 * Check to see if this connection has been idled for some
18123 	 * time and no ACK is expected.  If it is, we need to slow
18124 	 * start again to get back the connection's "self-clock" as
18125 	 * described in VJ's paper.
18126 	 *
18127 	 * Refer to the comment in tcp_mss_set() for the calculation
18128 	 * of tcp_cwnd after idle.
18129 	 */
18130 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18131 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18132 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
18133 	}
18134 
18135 	usable = tcp->tcp_swnd;		/* tcp window size */
18136 	if (usable > tcp->tcp_cwnd)
18137 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
18138 	usable -= snxt;		/* subtract stuff already sent */
18139 	suna = tcp->tcp_suna;
18140 	usable += suna;
18141 	/* usable can be < 0 if the congestion window is smaller */
18142 	if (len > usable) {
18143 		/* Can't send complete M_DATA in one shot */
18144 		goto slow;
18145 	}
18146 
18147 	mutex_enter(&tcp->tcp_non_sq_lock);
18148 	if (tcp->tcp_flow_stopped &&
18149 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18150 		tcp_clrqfull(tcp);
18151 	}
18152 	mutex_exit(&tcp->tcp_non_sq_lock);
18153 
18154 	/*
18155 	 * determine if anything to send (Nagle).
18156 	 *
18157 	 *   1. len < tcp_mss (i.e. small)
18158 	 *   2. unacknowledged data present
18159 	 *   3. len < nagle limit
18160 	 *   4. last packet sent < nagle limit (previous packet sent)
18161 	 */
18162 	if ((len < mss) && (snxt != suna) &&
18163 	    (len < (int)tcp->tcp_naglim) &&
18164 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
18165 		/*
18166 		 * This was the first unsent packet and normally
18167 		 * mss < xmit_hiwater so there is no need to worry
18168 		 * about flow control. The next packet will go
18169 		 * through the flow control check in tcp_wput_data().
18170 		 */
18171 		/* leftover work from above */
18172 		tcp->tcp_unsent = len;
18173 		tcp->tcp_xmit_tail_unsent = len;
18174 
18175 		return;
18176 	}
18177 
18178 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
18179 
18180 	if (snxt == suna) {
18181 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18182 	}
18183 
18184 	/* we have always sent something */
18185 	tcp->tcp_rack_cnt = 0;
18186 
18187 	tcp->tcp_snxt = snxt + len;
18188 	tcp->tcp_rack = tcp->tcp_rnxt;
18189 
18190 	if ((mp1 = dupb(mp)) == 0)
18191 		goto no_memory;
18192 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
18193 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
18194 
18195 	/* adjust tcp header information */
18196 	tcph = tcp->tcp_tcph;
18197 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
18198 
18199 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
18200 	sum = (sum >> 16) + (sum & 0xFFFF);
18201 	U16_TO_ABE16(sum, tcph->th_sum);
18202 
18203 	U32_TO_ABE32(snxt, tcph->th_seq);
18204 
18205 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
18206 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
18207 	BUMP_LOCAL(tcp->tcp_obsegs);
18208 
18209 	/* Update the latest receive window size in TCP header. */
18210 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18211 	    tcph->th_win);
18212 
18213 	tcp->tcp_last_sent_len = (ushort_t)len;
18214 
18215 	plen = len + tcp->tcp_hdr_len;
18216 
18217 	if (tcp->tcp_ipversion == IPV4_VERSION) {
18218 		tcp->tcp_ipha->ipha_length = htons(plen);
18219 	} else {
18220 		tcp->tcp_ip6h->ip6_plen = htons(plen -
18221 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
18222 	}
18223 
18224 	/* see if we need to allocate a mblk for the headers */
18225 	hdrlen = tcp->tcp_hdr_len;
18226 	rptr = mp1->b_rptr - hdrlen;
18227 	db = mp1->b_datap;
18228 	if ((db->db_ref != 2) || rptr < db->db_base ||
18229 	    (!OK_32PTR(rptr))) {
18230 		/* NOTE: we assume allocb returns an OK_32PTR */
18231 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
18232 		    tcps->tcps_wroff_xtra, BPRI_MED);
18233 		if (!mp) {
18234 			freemsg(mp1);
18235 			goto no_memory;
18236 		}
18237 		mp->b_cont = mp1;
18238 		mp1 = mp;
18239 		/* Leave room for Link Level header */
18240 		/* hdrlen = tcp->tcp_hdr_len; */
18241 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
18242 		mp1->b_wptr = &rptr[hdrlen];
18243 	}
18244 	mp1->b_rptr = rptr;
18245 
18246 	/* Fill in the timestamp option. */
18247 	if (tcp->tcp_snd_ts_ok) {
18248 		U32_TO_BE32((uint32_t)lbolt,
18249 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
18250 		U32_TO_BE32(tcp->tcp_ts_recent,
18251 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
18252 	} else {
18253 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
18254 	}
18255 
18256 	/* copy header into outgoing packet */
18257 	dst = (ipaddr_t *)rptr;
18258 	src = (ipaddr_t *)tcp->tcp_iphc;
18259 	dst[0] = src[0];
18260 	dst[1] = src[1];
18261 	dst[2] = src[2];
18262 	dst[3] = src[3];
18263 	dst[4] = src[4];
18264 	dst[5] = src[5];
18265 	dst[6] = src[6];
18266 	dst[7] = src[7];
18267 	dst[8] = src[8];
18268 	dst[9] = src[9];
18269 	if (hdrlen -= 40) {
18270 		hdrlen >>= 2;
18271 		dst += 10;
18272 		src += 10;
18273 		do {
18274 			*dst++ = *src++;
18275 		} while (--hdrlen);
18276 	}
18277 
18278 	/*
18279 	 * Set the ECN info in the TCP header.  Note that this
18280 	 * is not the template header.
18281 	 */
18282 	if (tcp->tcp_ecn_ok) {
18283 		SET_ECT(tcp, rptr);
18284 
18285 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
18286 		if (tcp->tcp_ecn_echo_on)
18287 			tcph->th_flags[0] |= TH_ECE;
18288 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
18289 			tcph->th_flags[0] |= TH_CWR;
18290 			tcp->tcp_ecn_cwr_sent = B_TRUE;
18291 		}
18292 	}
18293 
18294 	if (tcp->tcp_ip_forward_progress) {
18295 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
18296 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
18297 		tcp->tcp_ip_forward_progress = B_FALSE;
18298 	}
18299 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
18300 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
18301 	return;
18302 
18303 	/*
18304 	 * If we ran out of memory, we pretend to have sent the packet
18305 	 * and that it was lost on the wire.
18306 	 */
18307 no_memory:
18308 	return;
18309 
18310 slow:
18311 	/* leftover work from above */
18312 	tcp->tcp_unsent = len;
18313 	tcp->tcp_xmit_tail_unsent = len;
18314 	tcp_wput_data(tcp, NULL, B_FALSE);
18315 }
18316 
18317 /*
18318  * The function called through squeue to get behind eager's perimeter to
18319  * finish the accept processing.
18320  */
18321 /* ARGSUSED */
18322 void
18323 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
18324 {
18325 	conn_t			*connp = (conn_t *)arg;
18326 	tcp_t			*tcp = connp->conn_tcp;
18327 	queue_t			*q = tcp->tcp_rq;
18328 	mblk_t			*mp1;
18329 	mblk_t			*stropt_mp = mp;
18330 	struct  stroptions	*stropt;
18331 	uint_t			thwin;
18332 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18333 
18334 	/*
18335 	 * Drop the eager's ref on the listener, that was placed when
18336 	 * this eager began life in tcp_conn_request.
18337 	 */
18338 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
18339 
18340 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
18341 		/*
18342 		 * Someone blewoff the eager before we could finish
18343 		 * the accept.
18344 		 *
18345 		 * The only reason eager exists it because we put in
18346 		 * a ref on it when conn ind went up. We need to send
18347 		 * a disconnect indication up while the last reference
18348 		 * on the eager will be dropped by the squeue when we
18349 		 * return.
18350 		 */
18351 		ASSERT(tcp->tcp_listener == NULL);
18352 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
18353 			struct	T_discon_ind	*tdi;
18354 
18355 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
18356 			/*
18357 			 * Let us reuse the incoming mblk to avoid memory
18358 			 * allocation failure problems. We know that the
18359 			 * size of the incoming mblk i.e. stroptions is greater
18360 			 * than sizeof T_discon_ind. So the reallocb below
18361 			 * can't fail.
18362 			 */
18363 			freemsg(mp->b_cont);
18364 			mp->b_cont = NULL;
18365 			ASSERT(DB_REF(mp) == 1);
18366 			mp = reallocb(mp, sizeof (struct T_discon_ind),
18367 			    B_FALSE);
18368 			ASSERT(mp != NULL);
18369 			DB_TYPE(mp) = M_PROTO;
18370 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
18371 			tdi = (struct T_discon_ind *)mp->b_rptr;
18372 			if (tcp->tcp_issocket) {
18373 				tdi->DISCON_reason = ECONNREFUSED;
18374 				tdi->SEQ_number = 0;
18375 			} else {
18376 				tdi->DISCON_reason = ENOPROTOOPT;
18377 				tdi->SEQ_number =
18378 				    tcp->tcp_conn_req_seqnum;
18379 			}
18380 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
18381 			putnext(q, mp);
18382 		} else {
18383 			freemsg(mp);
18384 		}
18385 		if (tcp->tcp_hard_binding) {
18386 			tcp->tcp_hard_binding = B_FALSE;
18387 			tcp->tcp_hard_bound = B_TRUE;
18388 		}
18389 		tcp->tcp_detached = B_FALSE;
18390 		return;
18391 	}
18392 
18393 	mp1 = stropt_mp->b_cont;
18394 	stropt_mp->b_cont = NULL;
18395 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
18396 	stropt = (struct stroptions *)stropt_mp->b_rptr;
18397 
18398 	while (mp1 != NULL) {
18399 		mp = mp1;
18400 		mp1 = mp1->b_cont;
18401 		mp->b_cont = NULL;
18402 		tcp->tcp_drop_opt_ack_cnt++;
18403 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
18404 	}
18405 	mp = NULL;
18406 
18407 	/*
18408 	 * For a loopback connection with tcp_direct_sockfs on, note that
18409 	 * we don't have to protect tcp_rcv_list yet because synchronous
18410 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
18411 	 * possibly race with us.
18412 	 */
18413 
18414 	/*
18415 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
18416 	 * properly.  This is the first time we know of the acceptor'
18417 	 * queue.  So we do it here.
18418 	 */
18419 	if (tcp->tcp_rcv_list == NULL) {
18420 		/*
18421 		 * Recv queue is empty, tcp_rwnd should not have changed.
18422 		 * That means it should be equal to the listener's tcp_rwnd.
18423 		 */
18424 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
18425 	} else {
18426 #ifdef DEBUG
18427 		uint_t cnt = 0;
18428 
18429 		mp1 = tcp->tcp_rcv_list;
18430 		while ((mp = mp1) != NULL) {
18431 			mp1 = mp->b_next;
18432 			cnt += msgdsize(mp);
18433 		}
18434 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
18435 #endif
18436 		/* There is some data, add them back to get the max. */
18437 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
18438 	}
18439 	/*
18440 	 * This is the first time we run on the correct
18441 	 * queue after tcp_accept. So fix all the q parameters
18442 	 * here.
18443 	 */
18444 	stropt->so_flags = SO_HIWAT | SO_MAXBLK | SO_WROFF;
18445 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
18446 
18447 	/*
18448 	 * Record the stream head's high water mark for this endpoint;
18449 	 * this is used for flow-control purposes.
18450 	 */
18451 	stropt->so_hiwat = tcp->tcp_fused ?
18452 	    tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat) :
18453 	    MAX(q->q_hiwat, tcps->tcps_sth_rcv_hiwat);
18454 
18455 	/*
18456 	 * Determine what write offset value to use depending on SACK and
18457 	 * whether the endpoint is fused or not.
18458 	 */
18459 	if (tcp->tcp_fused) {
18460 		ASSERT(tcp->tcp_loopback);
18461 		ASSERT(tcp->tcp_loopback_peer != NULL);
18462 		/*
18463 		 * For fused tcp loopback, set the stream head's write
18464 		 * offset value to zero since we won't be needing any room
18465 		 * for TCP/IP headers.  This would also improve performance
18466 		 * since it would reduce the amount of work done by kmem.
18467 		 * Non-fused tcp loopback case is handled separately below.
18468 		 */
18469 		stropt->so_wroff = 0;
18470 		/*
18471 		 * Update the peer's transmit parameters according to
18472 		 * our recently calculated high water mark value.
18473 		 */
18474 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
18475 	} else if (tcp->tcp_snd_sack_ok) {
18476 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
18477 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
18478 	} else {
18479 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
18480 		    tcps->tcps_wroff_xtra);
18481 	}
18482 
18483 	/*
18484 	 * If this is endpoint is handling SSL, then reserve extra
18485 	 * offset and space at the end.
18486 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
18487 	 * overriding the previous setting. The extra cost of signing and
18488 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
18489 	 * instead of a single contiguous one by the stream head
18490 	 * largely outweighs the statistical reduction of ACKs, when
18491 	 * applicable. The peer will also save on decryption and verification
18492 	 * costs.
18493 	 */
18494 	if (tcp->tcp_kssl_ctx != NULL) {
18495 		stropt->so_wroff += SSL3_WROFFSET;
18496 
18497 		stropt->so_flags |= SO_TAIL;
18498 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
18499 
18500 		stropt->so_flags |= SO_COPYOPT;
18501 		stropt->so_copyopt = ZCVMUNSAFE;
18502 
18503 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
18504 	}
18505 
18506 	/* Send the options up */
18507 	putnext(q, stropt_mp);
18508 
18509 	/*
18510 	 * Pass up any data and/or a fin that has been received.
18511 	 *
18512 	 * Adjust receive window in case it had decreased
18513 	 * (because there is data <=> tcp_rcv_list != NULL)
18514 	 * while the connection was detached. Note that
18515 	 * in case the eager was flow-controlled, w/o this
18516 	 * code, the rwnd may never open up again!
18517 	 */
18518 	if (tcp->tcp_rcv_list != NULL) {
18519 		/* We drain directly in case of fused tcp loopback */
18520 		sodirect_t *sodp;
18521 
18522 		if (!tcp->tcp_fused && canputnext(q)) {
18523 			tcp->tcp_rwnd = q->q_hiwat;
18524 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
18525 			    << tcp->tcp_rcv_ws;
18526 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
18527 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18528 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
18529 				tcp_xmit_ctl(NULL,
18530 				    tcp, (tcp->tcp_swnd == 0) ?
18531 				    tcp->tcp_suna : tcp->tcp_snxt,
18532 				    tcp->tcp_rnxt, TH_ACK);
18533 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
18534 			}
18535 
18536 		}
18537 
18538 		SOD_PTR_ENTER(tcp, sodp);
18539 		if (sodp != NULL) {
18540 			/* Sodirect, move from rcv_list */
18541 			ASSERT(!tcp->tcp_fused);
18542 			while ((mp = tcp->tcp_rcv_list) != NULL) {
18543 				tcp->tcp_rcv_list = mp->b_next;
18544 				mp->b_next = NULL;
18545 				(void) tcp_rcv_sod_enqueue(tcp, sodp, mp,
18546 				    msgdsize(mp));
18547 			}
18548 			tcp->tcp_rcv_last_head = NULL;
18549 			tcp->tcp_rcv_last_tail = NULL;
18550 			tcp->tcp_rcv_cnt = 0;
18551 			(void) tcp_rcv_sod_wakeup(tcp, sodp);
18552 			/* sod_wakeup() did the mutex_exit() */
18553 		} else {
18554 			/* Not sodirect, drain */
18555 			(void) tcp_rcv_drain(q, tcp);
18556 		}
18557 
18558 		/*
18559 		 * For fused tcp loopback, back-enable peer endpoint
18560 		 * if it's currently flow-controlled.
18561 		 */
18562 		if (tcp->tcp_fused) {
18563 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18564 
18565 			ASSERT(peer_tcp != NULL);
18566 			ASSERT(peer_tcp->tcp_fused);
18567 			/*
18568 			 * In order to change the peer's tcp_flow_stopped,
18569 			 * we need to take locks for both end points. The
18570 			 * highest address is taken first.
18571 			 */
18572 			if (peer_tcp > tcp) {
18573 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18574 				mutex_enter(&tcp->tcp_non_sq_lock);
18575 			} else {
18576 				mutex_enter(&tcp->tcp_non_sq_lock);
18577 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18578 			}
18579 			if (peer_tcp->tcp_flow_stopped) {
18580 				tcp_clrqfull(peer_tcp);
18581 				TCP_STAT(tcps, tcp_fusion_backenabled);
18582 			}
18583 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18584 			mutex_exit(&tcp->tcp_non_sq_lock);
18585 		}
18586 	}
18587 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18588 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18589 		mp = mi_tpi_ordrel_ind();
18590 		if (mp) {
18591 			tcp->tcp_ordrel_done = B_TRUE;
18592 			putnext(q, mp);
18593 			if (tcp->tcp_deferred_clean_death) {
18594 				/*
18595 				 * tcp_clean_death was deferred
18596 				 * for T_ORDREL_IND - do it now
18597 				 */
18598 				(void) tcp_clean_death(tcp,
18599 				    tcp->tcp_client_errno, 21);
18600 				tcp->tcp_deferred_clean_death = B_FALSE;
18601 			}
18602 		} else {
18603 			/*
18604 			 * Run the orderly release in the
18605 			 * service routine.
18606 			 */
18607 			qenable(q);
18608 		}
18609 	}
18610 	if (tcp->tcp_hard_binding) {
18611 		tcp->tcp_hard_binding = B_FALSE;
18612 		tcp->tcp_hard_bound = B_TRUE;
18613 	}
18614 
18615 	/* We can enable synchronous streams now */
18616 	if (tcp->tcp_fused) {
18617 		tcp_fuse_syncstr_enable_pair(tcp);
18618 	}
18619 
18620 	if (tcp->tcp_ka_enabled) {
18621 		tcp->tcp_ka_last_intrvl = 0;
18622 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18623 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18624 	}
18625 
18626 	/*
18627 	 * At this point, eager is fully established and will
18628 	 * have the following references -
18629 	 *
18630 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18631 	 * 1 reference for the squeue which will be dropped by the squeue as
18632 	 *	soon as this function returns.
18633 	 * There will be 1 additonal reference for being in classifier
18634 	 *	hash list provided something bad hasn't happened.
18635 	 */
18636 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18637 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18638 }
18639 
18640 /*
18641  * The function called through squeue to get behind listener's perimeter to
18642  * send a deffered conn_ind.
18643  */
18644 /* ARGSUSED */
18645 void
18646 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18647 {
18648 	conn_t	*connp = (conn_t *)arg;
18649 	tcp_t *listener = connp->conn_tcp;
18650 
18651 	if (listener->tcp_state == TCPS_CLOSED ||
18652 	    TCP_IS_DETACHED(listener)) {
18653 		/*
18654 		 * If listener has closed, it would have caused a
18655 		 * a cleanup/blowoff to happen for the eager.
18656 		 */
18657 		tcp_t *tcp;
18658 		struct T_conn_ind	*conn_ind;
18659 
18660 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18661 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18662 		    conn_ind->OPT_length);
18663 		/*
18664 		 * We need to drop the ref on eager that was put
18665 		 * tcp_rput_data() before trying to send the conn_ind
18666 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18667 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18668 		 * listener is closed so we drop the ref.
18669 		 */
18670 		CONN_DEC_REF(tcp->tcp_connp);
18671 		freemsg(mp);
18672 		return;
18673 	}
18674 	putnext(listener->tcp_rq, mp);
18675 }
18676 
18677 
18678 /*
18679  * This is the STREAMS entry point for T_CONN_RES coming down on
18680  * Acceptor STREAM when  sockfs listener does accept processing.
18681  * Read the block comment on top of tcp_conn_request().
18682  */
18683 void
18684 tcp_wput_accept(queue_t *q, mblk_t *mp)
18685 {
18686 	queue_t *rq = RD(q);
18687 	struct T_conn_res *conn_res;
18688 	tcp_t *eager;
18689 	tcp_t *listener;
18690 	struct T_ok_ack *ok;
18691 	t_scalar_t PRIM_type;
18692 	mblk_t *opt_mp;
18693 	conn_t *econnp;
18694 
18695 	ASSERT(DB_TYPE(mp) == M_PROTO);
18696 
18697 	conn_res = (struct T_conn_res *)mp->b_rptr;
18698 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18699 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18700 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18701 		if (mp != NULL)
18702 			putnext(rq, mp);
18703 		return;
18704 	}
18705 	switch (conn_res->PRIM_type) {
18706 	case O_T_CONN_RES:
18707 	case T_CONN_RES:
18708 		/*
18709 		 * We pass up an err ack if allocb fails. This will
18710 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18711 		 * tcp_eager_blowoff to be called. sockfs will then call
18712 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18713 		 * we need to do the allocb up here because we have to
18714 		 * make sure rq->q_qinfo->qi_qclose still points to the
18715 		 * correct function (tcpclose_accept) in case allocb
18716 		 * fails.
18717 		 */
18718 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18719 		if (opt_mp == NULL) {
18720 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18721 			if (mp != NULL)
18722 				putnext(rq, mp);
18723 			return;
18724 		}
18725 
18726 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18727 		    &eager, conn_res->OPT_length);
18728 		PRIM_type = conn_res->PRIM_type;
18729 		mp->b_datap->db_type = M_PCPROTO;
18730 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18731 		ok = (struct T_ok_ack *)mp->b_rptr;
18732 		ok->PRIM_type = T_OK_ACK;
18733 		ok->CORRECT_prim = PRIM_type;
18734 		econnp = eager->tcp_connp;
18735 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
18736 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
18737 		eager->tcp_rq = rq;
18738 		eager->tcp_wq = q;
18739 		rq->q_ptr = econnp;
18740 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
18741 		q->q_ptr = econnp;
18742 		q->q_qinfo = &tcp_winit;
18743 		listener = eager->tcp_listener;
18744 		eager->tcp_issocket = B_TRUE;
18745 
18746 		/*
18747 		 * TCP is _D_SODIRECT and sockfs is directly above so
18748 		 * save shared sodirect_t pointer (if any).
18749 		 *
18750 		 * If tcp_fused and sodirect enabled disable it.
18751 		 */
18752 		eager->tcp_sodirect = SOD_QTOSODP(eager->tcp_rq);
18753 		if (eager->tcp_fused && eager->tcp_sodirect != NULL) {
18754 			/* Fused, disable sodirect */
18755 			mutex_enter(eager->tcp_sodirect->sod_lock);
18756 			SOD_DISABLE(eager->tcp_sodirect);
18757 			mutex_exit(eager->tcp_sodirect->sod_lock);
18758 			eager->tcp_sodirect = NULL;
18759 		}
18760 
18761 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18762 		econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18763 		ASSERT(econnp->conn_netstack ==
18764 		    listener->tcp_connp->conn_netstack);
18765 		ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18766 
18767 		/* Put the ref for IP */
18768 		CONN_INC_REF(econnp);
18769 
18770 		/*
18771 		 * We should have minimum of 3 references on the conn
18772 		 * at this point. One each for TCP and IP and one for
18773 		 * the T_conn_ind that was sent up when the 3-way handshake
18774 		 * completed. In the normal case we would also have another
18775 		 * reference (making a total of 4) for the conn being in the
18776 		 * classifier hash list. However the eager could have received
18777 		 * an RST subsequently and tcp_closei_local could have removed
18778 		 * the eager from the classifier hash list, hence we can't
18779 		 * assert that reference.
18780 		 */
18781 		ASSERT(econnp->conn_ref >= 3);
18782 
18783 		/*
18784 		 * Send the new local address also up to sockfs. There
18785 		 * should already be enough space in the mp that came
18786 		 * down from soaccept().
18787 		 */
18788 		if (eager->tcp_family == AF_INET) {
18789 			sin_t *sin;
18790 
18791 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18792 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18793 			sin = (sin_t *)mp->b_wptr;
18794 			mp->b_wptr += sizeof (sin_t);
18795 			sin->sin_family = AF_INET;
18796 			sin->sin_port = eager->tcp_lport;
18797 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18798 		} else {
18799 			sin6_t *sin6;
18800 
18801 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18802 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18803 			sin6 = (sin6_t *)mp->b_wptr;
18804 			mp->b_wptr += sizeof (sin6_t);
18805 			sin6->sin6_family = AF_INET6;
18806 			sin6->sin6_port = eager->tcp_lport;
18807 			if (eager->tcp_ipversion == IPV4_VERSION) {
18808 				sin6->sin6_flowinfo = 0;
18809 				IN6_IPADDR_TO_V4MAPPED(
18810 				    eager->tcp_ipha->ipha_src,
18811 				    &sin6->sin6_addr);
18812 			} else {
18813 				ASSERT(eager->tcp_ip6h != NULL);
18814 				sin6->sin6_flowinfo =
18815 				    eager->tcp_ip6h->ip6_vcf &
18816 				    ~IPV6_VERS_AND_FLOW_MASK;
18817 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18818 			}
18819 			sin6->sin6_scope_id = 0;
18820 			sin6->__sin6_src_id = 0;
18821 		}
18822 
18823 		putnext(rq, mp);
18824 
18825 		opt_mp->b_datap->db_type = M_SETOPTS;
18826 		opt_mp->b_wptr += sizeof (struct stroptions);
18827 
18828 		/*
18829 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18830 		 * from listener to acceptor. The message is chained on the
18831 		 * bind_mp which tcp_rput_other will send down to IP.
18832 		 */
18833 		if (listener->tcp_bound_if != 0) {
18834 			/* allocate optmgmt req */
18835 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18836 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
18837 			    sizeof (int));
18838 			if (mp != NULL)
18839 				linkb(opt_mp, mp);
18840 		}
18841 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18842 			uint_t on = 1;
18843 
18844 			/* allocate optmgmt req */
18845 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18846 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
18847 			if (mp != NULL)
18848 				linkb(opt_mp, mp);
18849 		}
18850 
18851 
18852 		mutex_enter(&listener->tcp_eager_lock);
18853 
18854 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18855 
18856 			tcp_t *tail;
18857 			tcp_t *tcp;
18858 			mblk_t *mp1;
18859 
18860 			tcp = listener->tcp_eager_prev_q0;
18861 			/*
18862 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
18863 			 * deferred T_conn_ind queue. We need to get to the head
18864 			 * of the queue in order to send up T_conn_ind the same
18865 			 * order as how the 3WHS is completed.
18866 			 */
18867 			while (tcp != listener) {
18868 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18869 				    !tcp->tcp_kssl_pending)
18870 					break;
18871 				else
18872 					tcp = tcp->tcp_eager_prev_q0;
18873 			}
18874 			/* None of the pending eagers can be sent up now */
18875 			if (tcp == listener)
18876 				goto no_more_eagers;
18877 
18878 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18879 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18880 			/* Move from q0 to q */
18881 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18882 			listener->tcp_conn_req_cnt_q0--;
18883 			listener->tcp_conn_req_cnt_q++;
18884 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18885 			    tcp->tcp_eager_prev_q0;
18886 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18887 			    tcp->tcp_eager_next_q0;
18888 			tcp->tcp_eager_prev_q0 = NULL;
18889 			tcp->tcp_eager_next_q0 = NULL;
18890 			tcp->tcp_conn_def_q0 = B_FALSE;
18891 
18892 			/* Make sure the tcp isn't in the list of droppables */
18893 			ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18894 			    tcp->tcp_eager_prev_drop_q0 == NULL);
18895 
18896 			/*
18897 			 * Insert at end of the queue because sockfs sends
18898 			 * down T_CONN_RES in chronological order. Leaving
18899 			 * the older conn indications at front of the queue
18900 			 * helps reducing search time.
18901 			 */
18902 			tail = listener->tcp_eager_last_q;
18903 			if (tail != NULL) {
18904 				tail->tcp_eager_next_q = tcp;
18905 			} else {
18906 				listener->tcp_eager_next_q = tcp;
18907 			}
18908 			listener->tcp_eager_last_q = tcp;
18909 			tcp->tcp_eager_next_q = NULL;
18910 
18911 			/* Need to get inside the listener perimeter */
18912 			CONN_INC_REF(listener->tcp_connp);
18913 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
18914 			    tcp_send_pending, listener->tcp_connp,
18915 			    SQTAG_TCP_SEND_PENDING);
18916 		}
18917 no_more_eagers:
18918 		tcp_eager_unlink(eager);
18919 		mutex_exit(&listener->tcp_eager_lock);
18920 
18921 		/*
18922 		 * At this point, the eager is detached from the listener
18923 		 * but we still have an extra refs on eager (apart from the
18924 		 * usual tcp references). The ref was placed in tcp_rput_data
18925 		 * before sending the conn_ind in tcp_send_conn_ind.
18926 		 * The ref will be dropped in tcp_accept_finish(). As sockfs
18927 		 * has already established this tcp with it's own stream,
18928 		 * it's OK to set tcp_detached to B_FALSE.
18929 		 */
18930 		econnp->conn_tcp->tcp_detached = B_FALSE;
18931 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
18932 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
18933 		return;
18934 	default:
18935 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18936 		if (mp != NULL)
18937 			putnext(rq, mp);
18938 		return;
18939 	}
18940 }
18941 
18942 static int
18943 tcp_getmyname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18944 {
18945 	sin_t *sin = (sin_t *)sa;
18946 	sin6_t *sin6 = (sin6_t *)sa;
18947 
18948 	switch (tcp->tcp_family) {
18949 	case AF_INET:
18950 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18951 
18952 		if (*salenp < sizeof (sin_t))
18953 			return (EINVAL);
18954 
18955 		*sin = sin_null;
18956 		sin->sin_family = AF_INET;
18957 		sin->sin_port = tcp->tcp_lport;
18958 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
18959 		break;
18960 
18961 	case AF_INET6:
18962 		if (*salenp < sizeof (sin6_t))
18963 			return (EINVAL);
18964 
18965 		*sin6 = sin6_null;
18966 		sin6->sin6_family = AF_INET6;
18967 		sin6->sin6_port = tcp->tcp_lport;
18968 		if (tcp->tcp_ipversion == IPV4_VERSION) {
18969 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
18970 			    &sin6->sin6_addr);
18971 		} else {
18972 			sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
18973 		}
18974 		break;
18975 	}
18976 
18977 	return (0);
18978 }
18979 
18980 static int
18981 tcp_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18982 {
18983 	sin_t *sin = (sin_t *)sa;
18984 	sin6_t *sin6 = (sin6_t *)sa;
18985 
18986 	if (tcp->tcp_state < TCPS_SYN_RCVD)
18987 		return (ENOTCONN);
18988 
18989 	switch (tcp->tcp_family) {
18990 	case AF_INET:
18991 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18992 
18993 		if (*salenp < sizeof (sin_t))
18994 			return (EINVAL);
18995 
18996 		*sin = sin_null;
18997 		sin->sin_family = AF_INET;
18998 		sin->sin_port = tcp->tcp_fport;
18999 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
19000 		    sin->sin_addr.s_addr);
19001 		break;
19002 
19003 	case AF_INET6:
19004 		if (*salenp < sizeof (sin6_t))
19005 			return (EINVAL);
19006 
19007 		*sin6 = sin6_null;
19008 		sin6->sin6_family = AF_INET6;
19009 		sin6->sin6_port = tcp->tcp_fport;
19010 		sin6->sin6_addr = tcp->tcp_remote_v6;
19011 		if (tcp->tcp_ipversion == IPV6_VERSION) {
19012 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
19013 			    ~IPV6_VERS_AND_FLOW_MASK;
19014 		}
19015 		break;
19016 	}
19017 
19018 	return (0);
19019 }
19020 
19021 /*
19022  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
19023  */
19024 static void
19025 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
19026 {
19027 	void	*data;
19028 	mblk_t	*datamp = mp->b_cont;
19029 	tcp_t	*tcp = Q_TO_TCP(q);
19030 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
19031 
19032 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
19033 		cmdp->cb_error = EPROTO;
19034 		qreply(q, mp);
19035 		return;
19036 	}
19037 
19038 	data = datamp->b_rptr;
19039 
19040 	switch (cmdp->cb_cmd) {
19041 	case TI_GETPEERNAME:
19042 		cmdp->cb_error = tcp_getpeername(tcp, data, &cmdp->cb_len);
19043 		break;
19044 	case TI_GETMYNAME:
19045 		cmdp->cb_error = tcp_getmyname(tcp, data, &cmdp->cb_len);
19046 		break;
19047 	default:
19048 		cmdp->cb_error = EINVAL;
19049 		break;
19050 	}
19051 
19052 	qreply(q, mp);
19053 }
19054 
19055 void
19056 tcp_wput(queue_t *q, mblk_t *mp)
19057 {
19058 	conn_t	*connp = Q_TO_CONN(q);
19059 	tcp_t	*tcp;
19060 	void (*output_proc)();
19061 	t_scalar_t type;
19062 	uchar_t *rptr;
19063 	struct iocblk	*iocp;
19064 	uint32_t	msize;
19065 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
19066 
19067 	ASSERT(connp->conn_ref >= 2);
19068 
19069 	switch (DB_TYPE(mp)) {
19070 	case M_DATA:
19071 		tcp = connp->conn_tcp;
19072 		ASSERT(tcp != NULL);
19073 
19074 		msize = msgdsize(mp);
19075 
19076 		mutex_enter(&tcp->tcp_non_sq_lock);
19077 		tcp->tcp_squeue_bytes += msize;
19078 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
19079 			tcp_setqfull(tcp);
19080 		}
19081 		mutex_exit(&tcp->tcp_non_sq_lock);
19082 
19083 		CONN_INC_REF(connp);
19084 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
19085 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
19086 		return;
19087 
19088 	case M_CMD:
19089 		tcp_wput_cmdblk(q, mp);
19090 		return;
19091 
19092 	case M_PROTO:
19093 	case M_PCPROTO:
19094 		/*
19095 		 * if it is a snmp message, don't get behind the squeue
19096 		 */
19097 		tcp = connp->conn_tcp;
19098 		rptr = mp->b_rptr;
19099 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
19100 			type = ((union T_primitives *)rptr)->type;
19101 		} else {
19102 			if (tcp->tcp_debug) {
19103 				(void) strlog(TCP_MOD_ID, 0, 1,
19104 				    SL_ERROR|SL_TRACE,
19105 				    "tcp_wput_proto, dropping one...");
19106 			}
19107 			freemsg(mp);
19108 			return;
19109 		}
19110 		if (type == T_SVR4_OPTMGMT_REQ) {
19111 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
19112 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
19113 			    cr)) {
19114 				/*
19115 				 * This was a SNMP request
19116 				 */
19117 				return;
19118 			} else {
19119 				output_proc = tcp_wput_proto;
19120 			}
19121 		} else {
19122 			output_proc = tcp_wput_proto;
19123 		}
19124 		break;
19125 	case M_IOCTL:
19126 		/*
19127 		 * Most ioctls can be processed right away without going via
19128 		 * squeues - process them right here. Those that do require
19129 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
19130 		 * are processed by tcp_wput_ioctl().
19131 		 */
19132 		iocp = (struct iocblk *)mp->b_rptr;
19133 		tcp = connp->conn_tcp;
19134 
19135 		switch (iocp->ioc_cmd) {
19136 		case TCP_IOC_ABORT_CONN:
19137 			tcp_ioctl_abort_conn(q, mp);
19138 			return;
19139 		case TI_GETPEERNAME:
19140 		case TI_GETMYNAME:
19141 			mi_copyin(q, mp, NULL,
19142 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
19143 			return;
19144 		case ND_SET:
19145 			/* nd_getset does the necessary checks */
19146 		case ND_GET:
19147 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
19148 				CALL_IP_WPUT(connp, q, mp);
19149 				return;
19150 			}
19151 			qreply(q, mp);
19152 			return;
19153 		case TCP_IOC_DEFAULT_Q:
19154 			/*
19155 			 * Wants to be the default wq. Check the credentials
19156 			 * first, the rest is executed via squeue.
19157 			 */
19158 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
19159 				iocp->ioc_error = EPERM;
19160 				iocp->ioc_count = 0;
19161 				mp->b_datap->db_type = M_IOCACK;
19162 				qreply(q, mp);
19163 				return;
19164 			}
19165 			output_proc = tcp_wput_ioctl;
19166 			break;
19167 		default:
19168 			output_proc = tcp_wput_ioctl;
19169 			break;
19170 		}
19171 		break;
19172 	default:
19173 		output_proc = tcp_wput_nondata;
19174 		break;
19175 	}
19176 
19177 	CONN_INC_REF(connp);
19178 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
19179 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
19180 }
19181 
19182 /*
19183  * Initial STREAMS write side put() procedure for sockets. It tries to
19184  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
19185  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
19186  * are handled by tcp_wput() as usual.
19187  *
19188  * All further messages will also be handled by tcp_wput() because we cannot
19189  * be sure that the above short cut is safe later.
19190  */
19191 static void
19192 tcp_wput_sock(queue_t *wq, mblk_t *mp)
19193 {
19194 	conn_t			*connp = Q_TO_CONN(wq);
19195 	tcp_t			*tcp = connp->conn_tcp;
19196 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
19197 
19198 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
19199 	wq->q_qinfo = &tcp_winit;
19200 
19201 	ASSERT(IPCL_IS_TCP(connp));
19202 	ASSERT(TCP_IS_SOCKET(tcp));
19203 
19204 	if (DB_TYPE(mp) == M_PCPROTO &&
19205 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
19206 	    car->PRIM_type == T_CAPABILITY_REQ) {
19207 		tcp_capability_req(tcp, mp);
19208 		return;
19209 	}
19210 
19211 	tcp_wput(wq, mp);
19212 }
19213 
19214 static boolean_t
19215 tcp_zcopy_check(tcp_t *tcp)
19216 {
19217 	conn_t	*connp = tcp->tcp_connp;
19218 	ire_t	*ire;
19219 	boolean_t	zc_enabled = B_FALSE;
19220 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19221 
19222 	if (do_tcpzcopy == 2)
19223 		zc_enabled = B_TRUE;
19224 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
19225 	    IPCL_IS_CONNECTED(connp) &&
19226 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
19227 	    connp->conn_dontroute == 0 &&
19228 	    !connp->conn_nexthop_set &&
19229 	    connp->conn_outgoing_ill == NULL &&
19230 	    connp->conn_nofailover_ill == NULL &&
19231 	    do_tcpzcopy == 1) {
19232 		/*
19233 		 * the checks above  closely resemble the fast path checks
19234 		 * in tcp_send_data().
19235 		 */
19236 		mutex_enter(&connp->conn_lock);
19237 		ire = connp->conn_ire_cache;
19238 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19239 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19240 			IRE_REFHOLD(ire);
19241 			if (ire->ire_stq != NULL) {
19242 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
19243 
19244 				zc_enabled = ill && (ill->ill_capabilities &
19245 				    ILL_CAPAB_ZEROCOPY) &&
19246 				    (ill->ill_zerocopy_capab->
19247 				    ill_zerocopy_flags != 0);
19248 			}
19249 			IRE_REFRELE(ire);
19250 		}
19251 		mutex_exit(&connp->conn_lock);
19252 	}
19253 	tcp->tcp_snd_zcopy_on = zc_enabled;
19254 	if (!TCP_IS_DETACHED(tcp)) {
19255 		if (zc_enabled) {
19256 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
19257 			TCP_STAT(tcps, tcp_zcopy_on);
19258 		} else {
19259 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
19260 			TCP_STAT(tcps, tcp_zcopy_off);
19261 		}
19262 	}
19263 	return (zc_enabled);
19264 }
19265 
19266 static mblk_t *
19267 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
19268 {
19269 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19270 
19271 	if (do_tcpzcopy == 2)
19272 		return (bp);
19273 	else if (tcp->tcp_snd_zcopy_on) {
19274 		tcp->tcp_snd_zcopy_on = B_FALSE;
19275 		if (!TCP_IS_DETACHED(tcp)) {
19276 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
19277 			TCP_STAT(tcps, tcp_zcopy_disable);
19278 		}
19279 	}
19280 	return (tcp_zcopy_backoff(tcp, bp, 0));
19281 }
19282 
19283 /*
19284  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
19285  * the original desballoca'ed segmapped mblk.
19286  */
19287 static mblk_t *
19288 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
19289 {
19290 	mblk_t *head, *tail, *nbp;
19291 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19292 
19293 	if (IS_VMLOANED_MBLK(bp)) {
19294 		TCP_STAT(tcps, tcp_zcopy_backoff);
19295 		if ((head = copyb(bp)) == NULL) {
19296 			/* fail to backoff; leave it for the next backoff */
19297 			tcp->tcp_xmit_zc_clean = B_FALSE;
19298 			return (bp);
19299 		}
19300 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19301 			if (fix_xmitlist)
19302 				tcp_zcopy_notify(tcp);
19303 			else
19304 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19305 		}
19306 		nbp = bp->b_cont;
19307 		if (fix_xmitlist) {
19308 			head->b_prev = bp->b_prev;
19309 			head->b_next = bp->b_next;
19310 			if (tcp->tcp_xmit_tail == bp)
19311 				tcp->tcp_xmit_tail = head;
19312 		}
19313 		bp->b_next = NULL;
19314 		bp->b_prev = NULL;
19315 		freeb(bp);
19316 	} else {
19317 		head = bp;
19318 		nbp = bp->b_cont;
19319 	}
19320 	tail = head;
19321 	while (nbp) {
19322 		if (IS_VMLOANED_MBLK(nbp)) {
19323 			TCP_STAT(tcps, tcp_zcopy_backoff);
19324 			if ((tail->b_cont = copyb(nbp)) == NULL) {
19325 				tcp->tcp_xmit_zc_clean = B_FALSE;
19326 				tail->b_cont = nbp;
19327 				return (head);
19328 			}
19329 			tail = tail->b_cont;
19330 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19331 				if (fix_xmitlist)
19332 					tcp_zcopy_notify(tcp);
19333 				else
19334 					tail->b_datap->db_struioflag |=
19335 					    STRUIO_ZCNOTIFY;
19336 			}
19337 			bp = nbp;
19338 			nbp = nbp->b_cont;
19339 			if (fix_xmitlist) {
19340 				tail->b_prev = bp->b_prev;
19341 				tail->b_next = bp->b_next;
19342 				if (tcp->tcp_xmit_tail == bp)
19343 					tcp->tcp_xmit_tail = tail;
19344 			}
19345 			bp->b_next = NULL;
19346 			bp->b_prev = NULL;
19347 			freeb(bp);
19348 		} else {
19349 			tail->b_cont = nbp;
19350 			tail = nbp;
19351 			nbp = nbp->b_cont;
19352 		}
19353 	}
19354 	if (fix_xmitlist) {
19355 		tcp->tcp_xmit_last = tail;
19356 		tcp->tcp_xmit_zc_clean = B_TRUE;
19357 	}
19358 	return (head);
19359 }
19360 
19361 static void
19362 tcp_zcopy_notify(tcp_t *tcp)
19363 {
19364 	struct stdata	*stp;
19365 
19366 	if (tcp->tcp_detached)
19367 		return;
19368 	stp = STREAM(tcp->tcp_rq);
19369 	mutex_enter(&stp->sd_lock);
19370 	stp->sd_flag |= STZCNOTIFY;
19371 	cv_broadcast(&stp->sd_zcopy_wait);
19372 	mutex_exit(&stp->sd_lock);
19373 }
19374 
19375 static boolean_t
19376 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
19377 {
19378 	ire_t	*ire;
19379 	conn_t	*connp = tcp->tcp_connp;
19380 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19381 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19382 
19383 	mutex_enter(&connp->conn_lock);
19384 	ire = connp->conn_ire_cache;
19385 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19386 
19387 	if ((ire != NULL) &&
19388 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
19389 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
19390 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19391 		IRE_REFHOLD(ire);
19392 		mutex_exit(&connp->conn_lock);
19393 	} else {
19394 		boolean_t cached = B_FALSE;
19395 		ts_label_t *tsl;
19396 
19397 		/* force a recheck later on */
19398 		tcp->tcp_ire_ill_check_done = B_FALSE;
19399 
19400 		TCP_DBGSTAT(tcps, tcp_ire_null1);
19401 		connp->conn_ire_cache = NULL;
19402 		mutex_exit(&connp->conn_lock);
19403 
19404 		if (ire != NULL)
19405 			IRE_REFRELE_NOTR(ire);
19406 
19407 		tsl = crgetlabel(CONN_CRED(connp));
19408 		ire = (dst ?
19409 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
19410 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19411 		    connp->conn_zoneid, tsl, ipst));
19412 
19413 		if (ire == NULL) {
19414 			TCP_STAT(tcps, tcp_ire_null);
19415 			return (B_FALSE);
19416 		}
19417 
19418 		IRE_REFHOLD_NOTR(ire);
19419 		/*
19420 		 * Since we are inside the squeue, there cannot be another
19421 		 * thread in TCP trying to set the conn_ire_cache now.  The
19422 		 * check for IRE_MARK_CONDEMNED ensures that an interface
19423 		 * unplumb thread has not yet started cleaning up the conns.
19424 		 * Hence we don't need to grab the conn lock.
19425 		 */
19426 		if (CONN_CACHE_IRE(connp)) {
19427 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19428 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19429 				TCP_CHECK_IREINFO(tcp, ire);
19430 				connp->conn_ire_cache = ire;
19431 				cached = B_TRUE;
19432 			}
19433 			rw_exit(&ire->ire_bucket->irb_lock);
19434 		}
19435 
19436 		/*
19437 		 * We can continue to use the ire but since it was
19438 		 * not cached, we should drop the extra reference.
19439 		 */
19440 		if (!cached)
19441 			IRE_REFRELE_NOTR(ire);
19442 
19443 		/*
19444 		 * Rampart note: no need to select a new label here, since
19445 		 * labels are not allowed to change during the life of a TCP
19446 		 * connection.
19447 		 */
19448 	}
19449 
19450 	*irep = ire;
19451 
19452 	return (B_TRUE);
19453 }
19454 
19455 /*
19456  * Called from tcp_send() or tcp_send_data() to find workable IRE.
19457  *
19458  * 0 = success;
19459  * 1 = failed to find ire and ill.
19460  */
19461 static boolean_t
19462 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
19463 {
19464 	ipha_t		*ipha;
19465 	ipaddr_t	dst;
19466 	ire_t		*ire;
19467 	ill_t		*ill;
19468 	conn_t		*connp = tcp->tcp_connp;
19469 	mblk_t		*ire_fp_mp;
19470 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19471 
19472 	if (mp != NULL)
19473 		ipha = (ipha_t *)mp->b_rptr;
19474 	else
19475 		ipha = tcp->tcp_ipha;
19476 	dst = ipha->ipha_dst;
19477 
19478 	if (!tcp_send_find_ire(tcp, &dst, &ire))
19479 		return (B_FALSE);
19480 
19481 	if ((ire->ire_flags & RTF_MULTIRT) ||
19482 	    (ire->ire_stq == NULL) ||
19483 	    (ire->ire_nce == NULL) ||
19484 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
19485 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
19486 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
19487 		TCP_STAT(tcps, tcp_ip_ire_send);
19488 		IRE_REFRELE(ire);
19489 		return (B_FALSE);
19490 	}
19491 
19492 	ill = ire_to_ill(ire);
19493 	if (connp->conn_outgoing_ill != NULL) {
19494 		ill_t *conn_outgoing_ill = NULL;
19495 		/*
19496 		 * Choose a good ill in the group to send the packets on.
19497 		 */
19498 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
19499 		ill = ire_to_ill(ire);
19500 	}
19501 	ASSERT(ill != NULL);
19502 
19503 	if (!tcp->tcp_ire_ill_check_done) {
19504 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19505 		tcp->tcp_ire_ill_check_done = B_TRUE;
19506 	}
19507 
19508 	*irep = ire;
19509 	*illp = ill;
19510 
19511 	return (B_TRUE);
19512 }
19513 
19514 static void
19515 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
19516 {
19517 	ipha_t		*ipha;
19518 	ipaddr_t	src;
19519 	ipaddr_t	dst;
19520 	uint32_t	cksum;
19521 	ire_t		*ire;
19522 	uint16_t	*up;
19523 	ill_t		*ill;
19524 	conn_t		*connp = tcp->tcp_connp;
19525 	uint32_t	hcksum_txflags = 0;
19526 	mblk_t		*ire_fp_mp;
19527 	uint_t		ire_fp_mp_len;
19528 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19529 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19530 
19531 	ASSERT(DB_TYPE(mp) == M_DATA);
19532 
19533 	if (DB_CRED(mp) == NULL)
19534 		mblk_setcred(mp, CONN_CRED(connp));
19535 
19536 	ipha = (ipha_t *)mp->b_rptr;
19537 	src = ipha->ipha_src;
19538 	dst = ipha->ipha_dst;
19539 
19540 	/*
19541 	 * Drop off fast path for IPv6 and also if options are present or
19542 	 * we need to resolve a TS label.
19543 	 */
19544 	if (tcp->tcp_ipversion != IPV4_VERSION ||
19545 	    !IPCL_IS_CONNECTED(connp) ||
19546 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
19547 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
19548 	    !connp->conn_ulp_labeled ||
19549 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
19550 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
19551 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
19552 		if (tcp->tcp_snd_zcopy_aware)
19553 			mp = tcp_zcopy_disable(tcp, mp);
19554 		TCP_STAT(tcps, tcp_ip_send);
19555 		CALL_IP_WPUT(connp, q, mp);
19556 		return;
19557 	}
19558 
19559 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
19560 		if (tcp->tcp_snd_zcopy_aware)
19561 			mp = tcp_zcopy_backoff(tcp, mp, 0);
19562 		CALL_IP_WPUT(connp, q, mp);
19563 		return;
19564 	}
19565 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
19566 	ire_fp_mp_len = MBLKL(ire_fp_mp);
19567 
19568 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19569 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19570 #ifndef _BIG_ENDIAN
19571 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19572 #endif
19573 
19574 	/*
19575 	 * Check to see if we need to re-enable LSO/MDT for this connection
19576 	 * because it was previously disabled due to changes in the ill;
19577 	 * note that by doing it here, this re-enabling only applies when
19578 	 * the packet is not dispatched through CALL_IP_WPUT().
19579 	 *
19580 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
19581 	 * case, since that's how we ended up here.  For IPv6, we do the
19582 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
19583 	 */
19584 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
19585 		/*
19586 		 * Restore LSO for this connection, so that next time around
19587 		 * it is eligible to go through tcp_lsosend() path again.
19588 		 */
19589 		TCP_STAT(tcps, tcp_lso_enabled);
19590 		tcp->tcp_lso = B_TRUE;
19591 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
19592 		    "interface %s\n", (void *)connp, ill->ill_name));
19593 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
19594 		/*
19595 		 * Restore MDT for this connection, so that next time around
19596 		 * it is eligible to go through tcp_multisend() path again.
19597 		 */
19598 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
19599 		tcp->tcp_mdt = B_TRUE;
19600 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
19601 		    "interface %s\n", (void *)connp, ill->ill_name));
19602 	}
19603 
19604 	if (tcp->tcp_snd_zcopy_aware) {
19605 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
19606 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
19607 			mp = tcp_zcopy_disable(tcp, mp);
19608 		/*
19609 		 * we shouldn't need to reset ipha as the mp containing
19610 		 * ipha should never be a zero-copy mp.
19611 		 */
19612 	}
19613 
19614 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
19615 		ASSERT(ill->ill_hcksum_capab != NULL);
19616 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
19617 	}
19618 
19619 	/* pseudo-header checksum (do it in parts for IP header checksum) */
19620 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19621 
19622 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
19623 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
19624 
19625 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
19626 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
19627 
19628 	/* Software checksum? */
19629 	if (DB_CKSUMFLAGS(mp) == 0) {
19630 		TCP_STAT(tcps, tcp_out_sw_cksum);
19631 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
19632 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
19633 	}
19634 
19635 	ipha->ipha_fragment_offset_and_flags |=
19636 	    (uint32_t)htons(ire->ire_frag_flag);
19637 
19638 	/* Calculate IP header checksum if hardware isn't capable */
19639 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
19640 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
19641 		    ((uint16_t *)ipha)[4]);
19642 	}
19643 
19644 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
19645 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
19646 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
19647 
19648 	UPDATE_OB_PKT_COUNT(ire);
19649 	ire->ire_last_used_time = lbolt;
19650 
19651 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
19652 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
19653 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
19654 	    ntohs(ipha->ipha_length));
19655 
19656 	if (ILL_DLS_CAPABLE(ill)) {
19657 		/*
19658 		 * Send the packet directly to DLD, where it may be queued
19659 		 * depending on the availability of transmit resources at
19660 		 * the media layer.
19661 		 */
19662 		IP_DLS_ILL_TX(ill, ipha, mp, ipst);
19663 	} else {
19664 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
19665 		DTRACE_PROBE4(ip4__physical__out__start,
19666 		    ill_t *, NULL, ill_t *, out_ill,
19667 		    ipha_t *, ipha, mblk_t *, mp);
19668 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
19669 		    ipst->ips_ipv4firewall_physical_out,
19670 		    NULL, out_ill, ipha, mp, mp, 0, ipst);
19671 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19672 
19673 		if (mp != NULL) {
19674 			DTRACE_IP_FASTPATH(mp, ipha, out_ill, ipha, NULL);
19675 			putnext(ire->ire_stq, mp);
19676 		}
19677 	}
19678 	IRE_REFRELE(ire);
19679 }
19680 
19681 /*
19682  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19683  * if the receiver shrinks the window, i.e. moves the right window to the
19684  * left, the we should not send new data, but should retransmit normally the
19685  * old unacked data between suna and suna + swnd. We might has sent data
19686  * that is now outside the new window, pretend that we didn't send  it.
19687  */
19688 static void
19689 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19690 {
19691 	uint32_t	snxt = tcp->tcp_snxt;
19692 	mblk_t		*xmit_tail;
19693 	int32_t		offset;
19694 
19695 	ASSERT(shrunk_count > 0);
19696 
19697 	/* Pretend we didn't send the data outside the window */
19698 	snxt -= shrunk_count;
19699 
19700 	/* Get the mblk and the offset in it per the shrunk window */
19701 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19702 
19703 	ASSERT(xmit_tail != NULL);
19704 
19705 	/* Reset all the values per the now shrunk window */
19706 	tcp->tcp_snxt = snxt;
19707 	tcp->tcp_xmit_tail = xmit_tail;
19708 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19709 	    offset;
19710 	tcp->tcp_unsent += shrunk_count;
19711 
19712 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19713 		/*
19714 		 * Make sure the timer is running so that we will probe a zero
19715 		 * window.
19716 		 */
19717 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19718 }
19719 
19720 
19721 /*
19722  * The TCP normal data output path.
19723  * NOTE: the logic of the fast path is duplicated from this function.
19724  */
19725 static void
19726 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19727 {
19728 	int		len;
19729 	mblk_t		*local_time;
19730 	mblk_t		*mp1;
19731 	uint32_t	snxt;
19732 	int		tail_unsent;
19733 	int		tcpstate;
19734 	int		usable = 0;
19735 	mblk_t		*xmit_tail;
19736 	queue_t		*q = tcp->tcp_wq;
19737 	int32_t		mss;
19738 	int32_t		num_sack_blk = 0;
19739 	int32_t		tcp_hdr_len;
19740 	int32_t		tcp_tcp_hdr_len;
19741 	int		mdt_thres;
19742 	int		rc;
19743 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19744 	ip_stack_t	*ipst;
19745 
19746 	tcpstate = tcp->tcp_state;
19747 	if (mp == NULL) {
19748 		/*
19749 		 * tcp_wput_data() with NULL mp should only be called when
19750 		 * there is unsent data.
19751 		 */
19752 		ASSERT(tcp->tcp_unsent > 0);
19753 		/* Really tacky... but we need this for detached closes. */
19754 		len = tcp->tcp_unsent;
19755 		goto data_null;
19756 	}
19757 
19758 #if CCS_STATS
19759 	wrw_stats.tot.count++;
19760 	wrw_stats.tot.bytes += msgdsize(mp);
19761 #endif
19762 	ASSERT(mp->b_datap->db_type == M_DATA);
19763 	/*
19764 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19765 	 * or before a connection attempt has begun.
19766 	 */
19767 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19768 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19769 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19770 #ifdef DEBUG
19771 			cmn_err(CE_WARN,
19772 			    "tcp_wput_data: data after ordrel, %s",
19773 			    tcp_display(tcp, NULL,
19774 			    DISP_ADDR_AND_PORT));
19775 #else
19776 			if (tcp->tcp_debug) {
19777 				(void) strlog(TCP_MOD_ID, 0, 1,
19778 				    SL_TRACE|SL_ERROR,
19779 				    "tcp_wput_data: data after ordrel, %s\n",
19780 				    tcp_display(tcp, NULL,
19781 				    DISP_ADDR_AND_PORT));
19782 			}
19783 #endif /* DEBUG */
19784 		}
19785 		if (tcp->tcp_snd_zcopy_aware &&
19786 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19787 			tcp_zcopy_notify(tcp);
19788 		freemsg(mp);
19789 		mutex_enter(&tcp->tcp_non_sq_lock);
19790 		if (tcp->tcp_flow_stopped &&
19791 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19792 			tcp_clrqfull(tcp);
19793 		}
19794 		mutex_exit(&tcp->tcp_non_sq_lock);
19795 		return;
19796 	}
19797 
19798 	/* Strip empties */
19799 	for (;;) {
19800 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19801 		    (uintptr_t)INT_MAX);
19802 		len = (int)(mp->b_wptr - mp->b_rptr);
19803 		if (len > 0)
19804 			break;
19805 		mp1 = mp;
19806 		mp = mp->b_cont;
19807 		freeb(mp1);
19808 		if (!mp) {
19809 			return;
19810 		}
19811 	}
19812 
19813 	/* If we are the first on the list ... */
19814 	if (tcp->tcp_xmit_head == NULL) {
19815 		tcp->tcp_xmit_head = mp;
19816 		tcp->tcp_xmit_tail = mp;
19817 		tcp->tcp_xmit_tail_unsent = len;
19818 	} else {
19819 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19820 		struct datab *dp;
19821 
19822 		mp1 = tcp->tcp_xmit_last;
19823 		if (len < tcp_tx_pull_len &&
19824 		    (dp = mp1->b_datap)->db_ref == 1 &&
19825 		    dp->db_lim - mp1->b_wptr >= len) {
19826 			ASSERT(len > 0);
19827 			ASSERT(!mp1->b_cont);
19828 			if (len == 1) {
19829 				*mp1->b_wptr++ = *mp->b_rptr;
19830 			} else {
19831 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19832 				mp1->b_wptr += len;
19833 			}
19834 			if (mp1 == tcp->tcp_xmit_tail)
19835 				tcp->tcp_xmit_tail_unsent += len;
19836 			mp1->b_cont = mp->b_cont;
19837 			if (tcp->tcp_snd_zcopy_aware &&
19838 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19839 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19840 			freeb(mp);
19841 			mp = mp1;
19842 		} else {
19843 			tcp->tcp_xmit_last->b_cont = mp;
19844 		}
19845 		len += tcp->tcp_unsent;
19846 	}
19847 
19848 	/* Tack on however many more positive length mblks we have */
19849 	if ((mp1 = mp->b_cont) != NULL) {
19850 		do {
19851 			int tlen;
19852 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19853 			    (uintptr_t)INT_MAX);
19854 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19855 			if (tlen <= 0) {
19856 				mp->b_cont = mp1->b_cont;
19857 				freeb(mp1);
19858 			} else {
19859 				len += tlen;
19860 				mp = mp1;
19861 			}
19862 		} while ((mp1 = mp->b_cont) != NULL);
19863 	}
19864 	tcp->tcp_xmit_last = mp;
19865 	tcp->tcp_unsent = len;
19866 
19867 	if (urgent)
19868 		usable = 1;
19869 
19870 data_null:
19871 	snxt = tcp->tcp_snxt;
19872 	xmit_tail = tcp->tcp_xmit_tail;
19873 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19874 
19875 	/*
19876 	 * Note that tcp_mss has been adjusted to take into account the
19877 	 * timestamp option if applicable.  Because SACK options do not
19878 	 * appear in every TCP segments and they are of variable lengths,
19879 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19880 	 * the actual segment length when we need to send a segment which
19881 	 * includes SACK options.
19882 	 */
19883 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19884 		int32_t	opt_len;
19885 
19886 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19887 		    tcp->tcp_num_sack_blk);
19888 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19889 		    2 + TCPOPT_HEADER_LEN;
19890 		mss = tcp->tcp_mss - opt_len;
19891 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19892 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19893 	} else {
19894 		mss = tcp->tcp_mss;
19895 		tcp_hdr_len = tcp->tcp_hdr_len;
19896 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19897 	}
19898 
19899 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19900 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19901 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19902 	}
19903 	if (tcpstate == TCPS_SYN_RCVD) {
19904 		/*
19905 		 * The three-way connection establishment handshake is not
19906 		 * complete yet. We want to queue the data for transmission
19907 		 * after entering ESTABLISHED state (RFC793). A jump to
19908 		 * "done" label effectively leaves data on the queue.
19909 		 */
19910 		goto done;
19911 	} else {
19912 		int usable_r;
19913 
19914 		/*
19915 		 * In the special case when cwnd is zero, which can only
19916 		 * happen if the connection is ECN capable, return now.
19917 		 * New segments is sent using tcp_timer().  The timer
19918 		 * is set in tcp_rput_data().
19919 		 */
19920 		if (tcp->tcp_cwnd == 0) {
19921 			/*
19922 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19923 			 * finished.
19924 			 */
19925 			ASSERT(tcp->tcp_ecn_ok ||
19926 			    tcp->tcp_state < TCPS_ESTABLISHED);
19927 			return;
19928 		}
19929 
19930 		/* NOTE: trouble if xmitting while SYN not acked? */
19931 		usable_r = snxt - tcp->tcp_suna;
19932 		usable_r = tcp->tcp_swnd - usable_r;
19933 
19934 		/*
19935 		 * Check if the receiver has shrunk the window.  If
19936 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19937 		 * cannot be set as there is unsent data, so FIN cannot
19938 		 * be sent out.  Otherwise, we need to take into account
19939 		 * of FIN as it consumes an "invisible" sequence number.
19940 		 */
19941 		ASSERT(tcp->tcp_fin_sent == 0);
19942 		if (usable_r < 0) {
19943 			/*
19944 			 * The receiver has shrunk the window and we have sent
19945 			 * -usable_r date beyond the window, re-adjust.
19946 			 *
19947 			 * If TCP window scaling is enabled, there can be
19948 			 * round down error as the advertised receive window
19949 			 * is actually right shifted n bits.  This means that
19950 			 * the lower n bits info is wiped out.  It will look
19951 			 * like the window is shrunk.  Do a check here to
19952 			 * see if the shrunk amount is actually within the
19953 			 * error in window calculation.  If it is, just
19954 			 * return.  Note that this check is inside the
19955 			 * shrunk window check.  This makes sure that even
19956 			 * though tcp_process_shrunk_swnd() is not called,
19957 			 * we will stop further processing.
19958 			 */
19959 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19960 				tcp_process_shrunk_swnd(tcp, -usable_r);
19961 			}
19962 			return;
19963 		}
19964 
19965 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19966 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19967 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19968 
19969 		/* usable = MIN(usable, unsent) */
19970 		if (usable_r > len)
19971 			usable_r = len;
19972 
19973 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19974 		if (usable_r > 0) {
19975 			usable = usable_r;
19976 		} else {
19977 			/* Bypass all other unnecessary processing. */
19978 			goto done;
19979 		}
19980 	}
19981 
19982 	local_time = (mblk_t *)lbolt;
19983 
19984 	/*
19985 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19986 	 * BSD.  This is more in line with the true intent of Nagle.
19987 	 *
19988 	 * The conditions are:
19989 	 * 1. The amount of unsent data (or amount of data which can be
19990 	 *    sent, whichever is smaller) is less than Nagle limit.
19991 	 * 2. The last sent size is also less than Nagle limit.
19992 	 * 3. There is unack'ed data.
19993 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19994 	 *    Nagle algorithm.  This reduces the probability that urgent
19995 	 *    bytes get "merged" together.
19996 	 * 5. The app has not closed the connection.  This eliminates the
19997 	 *    wait time of the receiving side waiting for the last piece of
19998 	 *    (small) data.
19999 	 *
20000 	 * If all are satisified, exit without sending anything.  Note
20001 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
20002 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
20003 	 * 4095).
20004 	 */
20005 	if (usable < (int)tcp->tcp_naglim &&
20006 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
20007 	    snxt != tcp->tcp_suna &&
20008 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
20009 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
20010 		goto done;
20011 	}
20012 
20013 	if (tcp->tcp_cork) {
20014 		/*
20015 		 * if the tcp->tcp_cork option is set, then we have to force
20016 		 * TCP not to send partial segment (smaller than MSS bytes).
20017 		 * We are calculating the usable now based on full mss and
20018 		 * will save the rest of remaining data for later.
20019 		 */
20020 		if (usable < mss)
20021 			goto done;
20022 		usable = (usable / mss) * mss;
20023 	}
20024 
20025 	/* Update the latest receive window size in TCP header. */
20026 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
20027 	    tcp->tcp_tcph->th_win);
20028 
20029 	/*
20030 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
20031 	 *
20032 	 * 1. Simple TCP/IP{v4,v6} (no options).
20033 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
20034 	 * 3. If the TCP connection is in ESTABLISHED state.
20035 	 * 4. The TCP is not detached.
20036 	 *
20037 	 * If any of the above conditions have changed during the
20038 	 * connection, stop using LSO/MDT and restore the stream head
20039 	 * parameters accordingly.
20040 	 */
20041 	ipst = tcps->tcps_netstack->netstack_ip;
20042 
20043 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
20044 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
20045 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
20046 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20047 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
20048 	    tcp->tcp_state != TCPS_ESTABLISHED ||
20049 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
20050 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
20051 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
20052 		if (tcp->tcp_lso) {
20053 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
20054 			tcp->tcp_lso = B_FALSE;
20055 		} else {
20056 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
20057 			tcp->tcp_mdt = B_FALSE;
20058 		}
20059 
20060 		/* Anything other than detached is considered pathological */
20061 		if (!TCP_IS_DETACHED(tcp)) {
20062 			if (tcp->tcp_lso)
20063 				TCP_STAT(tcps, tcp_lso_disabled);
20064 			else
20065 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
20066 			(void) tcp_maxpsz_set(tcp, B_TRUE);
20067 		}
20068 	}
20069 
20070 	/* Use MDT if sendable amount is greater than the threshold */
20071 	if (tcp->tcp_mdt &&
20072 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
20073 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
20074 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
20075 	    (tcp->tcp_valid_bits == 0 ||
20076 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
20077 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
20078 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
20079 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
20080 		    local_time, mdt_thres);
20081 	} else {
20082 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
20083 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
20084 		    local_time, INT_MAX);
20085 	}
20086 
20087 	/* Pretend that all we were trying to send really got sent */
20088 	if (rc < 0 && tail_unsent < 0) {
20089 		do {
20090 			xmit_tail = xmit_tail->b_cont;
20091 			xmit_tail->b_prev = local_time;
20092 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
20093 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
20094 			tail_unsent += (int)(xmit_tail->b_wptr -
20095 			    xmit_tail->b_rptr);
20096 		} while (tail_unsent < 0);
20097 	}
20098 done:;
20099 	tcp->tcp_xmit_tail = xmit_tail;
20100 	tcp->tcp_xmit_tail_unsent = tail_unsent;
20101 	len = tcp->tcp_snxt - snxt;
20102 	if (len) {
20103 		/*
20104 		 * If new data was sent, need to update the notsack
20105 		 * list, which is, afterall, data blocks that have
20106 		 * not been sack'ed by the receiver.  New data is
20107 		 * not sack'ed.
20108 		 */
20109 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
20110 			/* len is a negative value. */
20111 			tcp->tcp_pipe -= len;
20112 			tcp_notsack_update(&(tcp->tcp_notsack_list),
20113 			    tcp->tcp_snxt, snxt,
20114 			    &(tcp->tcp_num_notsack_blk),
20115 			    &(tcp->tcp_cnt_notsack_list));
20116 		}
20117 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
20118 		tcp->tcp_rack = tcp->tcp_rnxt;
20119 		tcp->tcp_rack_cnt = 0;
20120 		if ((snxt + len) == tcp->tcp_suna) {
20121 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20122 		}
20123 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
20124 		/*
20125 		 * Didn't send anything. Make sure the timer is running
20126 		 * so that we will probe a zero window.
20127 		 */
20128 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20129 	}
20130 	/* Note that len is the amount we just sent but with a negative sign */
20131 	tcp->tcp_unsent += len;
20132 	mutex_enter(&tcp->tcp_non_sq_lock);
20133 	if (tcp->tcp_flow_stopped) {
20134 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
20135 			tcp_clrqfull(tcp);
20136 		}
20137 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
20138 		tcp_setqfull(tcp);
20139 	}
20140 	mutex_exit(&tcp->tcp_non_sq_lock);
20141 }
20142 
20143 /*
20144  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
20145  * outgoing TCP header with the template header, as well as other
20146  * options such as time-stamp, ECN and/or SACK.
20147  */
20148 static void
20149 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
20150 {
20151 	tcph_t *tcp_tmpl, *tcp_h;
20152 	uint32_t *dst, *src;
20153 	int hdrlen;
20154 
20155 	ASSERT(OK_32PTR(rptr));
20156 
20157 	/* Template header */
20158 	tcp_tmpl = tcp->tcp_tcph;
20159 
20160 	/* Header of outgoing packet */
20161 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
20162 
20163 	/* dst and src are opaque 32-bit fields, used for copying */
20164 	dst = (uint32_t *)rptr;
20165 	src = (uint32_t *)tcp->tcp_iphc;
20166 	hdrlen = tcp->tcp_hdr_len;
20167 
20168 	/* Fill time-stamp option if needed */
20169 	if (tcp->tcp_snd_ts_ok) {
20170 		U32_TO_BE32((uint32_t)now,
20171 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
20172 		U32_TO_BE32(tcp->tcp_ts_recent,
20173 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
20174 	} else {
20175 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
20176 	}
20177 
20178 	/*
20179 	 * Copy the template header; is this really more efficient than
20180 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
20181 	 * but perhaps not for other scenarios.
20182 	 */
20183 	dst[0] = src[0];
20184 	dst[1] = src[1];
20185 	dst[2] = src[2];
20186 	dst[3] = src[3];
20187 	dst[4] = src[4];
20188 	dst[5] = src[5];
20189 	dst[6] = src[6];
20190 	dst[7] = src[7];
20191 	dst[8] = src[8];
20192 	dst[9] = src[9];
20193 	if (hdrlen -= 40) {
20194 		hdrlen >>= 2;
20195 		dst += 10;
20196 		src += 10;
20197 		do {
20198 			*dst++ = *src++;
20199 		} while (--hdrlen);
20200 	}
20201 
20202 	/*
20203 	 * Set the ECN info in the TCP header if it is not a zero
20204 	 * window probe.  Zero window probe is only sent in
20205 	 * tcp_wput_data() and tcp_timer().
20206 	 */
20207 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
20208 		SET_ECT(tcp, rptr);
20209 
20210 		if (tcp->tcp_ecn_echo_on)
20211 			tcp_h->th_flags[0] |= TH_ECE;
20212 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
20213 			tcp_h->th_flags[0] |= TH_CWR;
20214 			tcp->tcp_ecn_cwr_sent = B_TRUE;
20215 		}
20216 	}
20217 
20218 	/* Fill in SACK options */
20219 	if (num_sack_blk > 0) {
20220 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
20221 		sack_blk_t *tmp;
20222 		int32_t	i;
20223 
20224 		wptr[0] = TCPOPT_NOP;
20225 		wptr[1] = TCPOPT_NOP;
20226 		wptr[2] = TCPOPT_SACK;
20227 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
20228 		    sizeof (sack_blk_t);
20229 		wptr += TCPOPT_REAL_SACK_LEN;
20230 
20231 		tmp = tcp->tcp_sack_list;
20232 		for (i = 0; i < num_sack_blk; i++) {
20233 			U32_TO_BE32(tmp[i].begin, wptr);
20234 			wptr += sizeof (tcp_seq);
20235 			U32_TO_BE32(tmp[i].end, wptr);
20236 			wptr += sizeof (tcp_seq);
20237 		}
20238 		tcp_h->th_offset_and_rsrvd[0] +=
20239 		    ((num_sack_blk * 2 + 1) << 4);
20240 	}
20241 }
20242 
20243 /*
20244  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
20245  * the destination address and SAP attribute, and if necessary, the
20246  * hardware checksum offload attribute to a Multidata message.
20247  */
20248 static int
20249 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
20250     const uint32_t start, const uint32_t stuff, const uint32_t end,
20251     const uint32_t flags, tcp_stack_t *tcps)
20252 {
20253 	/* Add global destination address & SAP attribute */
20254 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
20255 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
20256 		    "destination address+SAP\n"));
20257 
20258 		if (dlmp != NULL)
20259 			TCP_STAT(tcps, tcp_mdt_allocfail);
20260 		return (-1);
20261 	}
20262 
20263 	/* Add global hwcksum attribute */
20264 	if (hwcksum &&
20265 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
20266 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
20267 		    "checksum attribute\n"));
20268 
20269 		TCP_STAT(tcps, tcp_mdt_allocfail);
20270 		return (-1);
20271 	}
20272 
20273 	return (0);
20274 }
20275 
20276 /*
20277  * Smaller and private version of pdescinfo_t used specifically for TCP,
20278  * which allows for only two payload spans per packet.
20279  */
20280 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
20281 
20282 /*
20283  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
20284  * scheme, and returns one the following:
20285  *
20286  * -1 = failed allocation.
20287  *  0 = success; burst count reached, or usable send window is too small,
20288  *      and that we'd rather wait until later before sending again.
20289  */
20290 static int
20291 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20292     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20293     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20294     const int mdt_thres)
20295 {
20296 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
20297 	multidata_t	*mmd;
20298 	uint_t		obsegs, obbytes, hdr_frag_sz;
20299 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
20300 	int		num_burst_seg, max_pld;
20301 	pdesc_t		*pkt;
20302 	tcp_pdescinfo_t	tcp_pkt_info;
20303 	pdescinfo_t	*pkt_info;
20304 	int		pbuf_idx, pbuf_idx_nxt;
20305 	int		seg_len, len, spill, af;
20306 	boolean_t	add_buffer, zcopy, clusterwide;
20307 	boolean_t	buf_trunked = B_FALSE;
20308 	boolean_t	rconfirm = B_FALSE;
20309 	boolean_t	done = B_FALSE;
20310 	uint32_t	cksum;
20311 	uint32_t	hwcksum_flags;
20312 	ire_t		*ire = NULL;
20313 	ill_t		*ill;
20314 	ipha_t		*ipha;
20315 	ip6_t		*ip6h;
20316 	ipaddr_t	src, dst;
20317 	ill_zerocopy_capab_t *zc_cap = NULL;
20318 	uint16_t	*up;
20319 	int		err;
20320 	conn_t		*connp;
20321 	mblk_t		*mp, *mp1, *fw_mp_head = NULL;
20322 	uchar_t		*pld_start;
20323 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20324 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
20325 
20326 #ifdef	_BIG_ENDIAN
20327 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
20328 #else
20329 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
20330 #endif
20331 
20332 #define	PREP_NEW_MULTIDATA() {			\
20333 	mmd = NULL;				\
20334 	md_mp = md_hbuf = NULL;			\
20335 	cur_hdr_off = 0;			\
20336 	max_pld = tcp->tcp_mdt_max_pld;		\
20337 	pbuf_idx = pbuf_idx_nxt = -1;		\
20338 	add_buffer = B_TRUE;			\
20339 	zcopy = B_FALSE;			\
20340 }
20341 
20342 #define	PREP_NEW_PBUF() {			\
20343 	md_pbuf = md_pbuf_nxt = NULL;		\
20344 	pbuf_idx = pbuf_idx_nxt = -1;		\
20345 	cur_pld_off = 0;			\
20346 	first_snxt = *snxt;			\
20347 	ASSERT(*tail_unsent > 0);		\
20348 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
20349 }
20350 
20351 	ASSERT(mdt_thres >= mss);
20352 	ASSERT(*usable > 0 && *usable > mdt_thres);
20353 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20354 	ASSERT(!TCP_IS_DETACHED(tcp));
20355 	ASSERT(tcp->tcp_valid_bits == 0 ||
20356 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
20357 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
20358 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
20359 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20360 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
20361 
20362 	connp = tcp->tcp_connp;
20363 	ASSERT(connp != NULL);
20364 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
20365 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
20366 
20367 	/*
20368 	 * Note that tcp will only declare at most 2 payload spans per
20369 	 * packet, which is much lower than the maximum allowable number
20370 	 * of packet spans per Multidata.  For this reason, we use the
20371 	 * privately declared and smaller descriptor info structure, in
20372 	 * order to save some stack space.
20373 	 */
20374 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
20375 
20376 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
20377 	if (af == AF_INET) {
20378 		dst = tcp->tcp_ipha->ipha_dst;
20379 		src = tcp->tcp_ipha->ipha_src;
20380 		ASSERT(!CLASSD(dst));
20381 	}
20382 	ASSERT(af == AF_INET ||
20383 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
20384 
20385 	obsegs = obbytes = 0;
20386 	num_burst_seg = tcp->tcp_snd_burst;
20387 	md_mp_head = NULL;
20388 	PREP_NEW_MULTIDATA();
20389 
20390 	/*
20391 	 * Before we go on further, make sure there is an IRE that we can
20392 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
20393 	 * in proceeding any further, and we should just hand everything
20394 	 * off to the legacy path.
20395 	 */
20396 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
20397 		goto legacy_send_no_md;
20398 
20399 	ASSERT(ire != NULL);
20400 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
20401 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
20402 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
20403 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
20404 	/*
20405 	 * If we do support loopback for MDT (which requires modifications
20406 	 * to the receiving paths), the following assertions should go away,
20407 	 * and we would be sending the Multidata to loopback conn later on.
20408 	 */
20409 	ASSERT(!IRE_IS_LOCAL(ire));
20410 	ASSERT(ire->ire_stq != NULL);
20411 
20412 	ill = ire_to_ill(ire);
20413 	ASSERT(ill != NULL);
20414 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
20415 
20416 	if (!tcp->tcp_ire_ill_check_done) {
20417 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
20418 		tcp->tcp_ire_ill_check_done = B_TRUE;
20419 	}
20420 
20421 	/*
20422 	 * If the underlying interface conditions have changed, or if the
20423 	 * new interface does not support MDT, go back to legacy path.
20424 	 */
20425 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
20426 		/* don't go through this path anymore for this connection */
20427 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
20428 		tcp->tcp_mdt = B_FALSE;
20429 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
20430 		    "interface %s\n", (void *)connp, ill->ill_name));
20431 		/* IRE will be released prior to returning */
20432 		goto legacy_send_no_md;
20433 	}
20434 
20435 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
20436 		zc_cap = ill->ill_zerocopy_capab;
20437 
20438 	/*
20439 	 * Check if we can take tcp fast-path. Note that "incomplete"
20440 	 * ire's (where the link-layer for next hop is not resolved
20441 	 * or where the fast-path header in nce_fp_mp is not available
20442 	 * yet) are sent down the legacy (slow) path.
20443 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
20444 	 */
20445 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
20446 		/* IRE will be released prior to returning */
20447 		goto legacy_send_no_md;
20448 	}
20449 
20450 	/* go to legacy path if interface doesn't support zerocopy */
20451 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
20452 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
20453 		/* IRE will be released prior to returning */
20454 		goto legacy_send_no_md;
20455 	}
20456 
20457 	/* does the interface support hardware checksum offload? */
20458 	hwcksum_flags = 0;
20459 	if (ILL_HCKSUM_CAPABLE(ill) &&
20460 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
20461 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
20462 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
20463 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20464 		    HCKSUM_IPHDRCKSUM)
20465 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
20466 
20467 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20468 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
20469 			hwcksum_flags |= HCK_FULLCKSUM;
20470 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20471 		    HCKSUM_INET_PARTIAL)
20472 			hwcksum_flags |= HCK_PARTIALCKSUM;
20473 	}
20474 
20475 	/*
20476 	 * Each header fragment consists of the leading extra space,
20477 	 * followed by the TCP/IP header, and the trailing extra space.
20478 	 * We make sure that each header fragment begins on a 32-bit
20479 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
20480 	 * aligned in tcp_mdt_update).
20481 	 */
20482 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
20483 	    tcp->tcp_mdt_hdr_tail), 4);
20484 
20485 	/* are we starting from the beginning of data block? */
20486 	if (*tail_unsent == 0) {
20487 		*xmit_tail = (*xmit_tail)->b_cont;
20488 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
20489 		*tail_unsent = (int)MBLKL(*xmit_tail);
20490 	}
20491 
20492 	/*
20493 	 * Here we create one or more Multidata messages, each made up of
20494 	 * one header buffer and up to N payload buffers.  This entire
20495 	 * operation is done within two loops:
20496 	 *
20497 	 * The outer loop mostly deals with creating the Multidata message,
20498 	 * as well as the header buffer that gets added to it.  It also
20499 	 * links the Multidata messages together such that all of them can
20500 	 * be sent down to the lower layer in a single putnext call; this
20501 	 * linking behavior depends on the tcp_mdt_chain tunable.
20502 	 *
20503 	 * The inner loop takes an existing Multidata message, and adds
20504 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
20505 	 * packetizes those buffers by filling up the corresponding header
20506 	 * buffer fragments with the proper IP and TCP headers, and by
20507 	 * describing the layout of each packet in the packet descriptors
20508 	 * that get added to the Multidata.
20509 	 */
20510 	do {
20511 		/*
20512 		 * If usable send window is too small, or data blocks in
20513 		 * transmit list are smaller than our threshold (i.e. app
20514 		 * performs large writes followed by small ones), we hand
20515 		 * off the control over to the legacy path.  Note that we'll
20516 		 * get back the control once it encounters a large block.
20517 		 */
20518 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
20519 		    (*xmit_tail)->b_cont != NULL &&
20520 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
20521 			/* send down what we've got so far */
20522 			if (md_mp_head != NULL) {
20523 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
20524 				    obsegs, obbytes, &rconfirm);
20525 			}
20526 			/*
20527 			 * Pass control over to tcp_send(), but tell it to
20528 			 * return to us once a large-size transmission is
20529 			 * possible.
20530 			 */
20531 			TCP_STAT(tcps, tcp_mdt_legacy_small);
20532 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
20533 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
20534 			    tail_unsent, xmit_tail, local_time,
20535 			    mdt_thres)) <= 0) {
20536 				/* burst count reached, or alloc failed */
20537 				IRE_REFRELE(ire);
20538 				return (err);
20539 			}
20540 
20541 			/* tcp_send() may have sent everything, so check */
20542 			if (*usable <= 0) {
20543 				IRE_REFRELE(ire);
20544 				return (0);
20545 			}
20546 
20547 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
20548 			/*
20549 			 * We may have delivered the Multidata, so make sure
20550 			 * to re-initialize before the next round.
20551 			 */
20552 			md_mp_head = NULL;
20553 			obsegs = obbytes = 0;
20554 			num_burst_seg = tcp->tcp_snd_burst;
20555 			PREP_NEW_MULTIDATA();
20556 
20557 			/* are we starting from the beginning of data block? */
20558 			if (*tail_unsent == 0) {
20559 				*xmit_tail = (*xmit_tail)->b_cont;
20560 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20561 				    (uintptr_t)INT_MAX);
20562 				*tail_unsent = (int)MBLKL(*xmit_tail);
20563 			}
20564 		}
20565 
20566 		/*
20567 		 * max_pld limits the number of mblks in tcp's transmit
20568 		 * queue that can be added to a Multidata message.  Once
20569 		 * this counter reaches zero, no more additional mblks
20570 		 * can be added to it.  What happens afterwards depends
20571 		 * on whether or not we are set to chain the Multidata
20572 		 * messages.  If we are to link them together, reset
20573 		 * max_pld to its original value (tcp_mdt_max_pld) and
20574 		 * prepare to create a new Multidata message which will
20575 		 * get linked to md_mp_head.  Else, leave it alone and
20576 		 * let the inner loop break on its own.
20577 		 */
20578 		if (tcp_mdt_chain && max_pld == 0)
20579 			PREP_NEW_MULTIDATA();
20580 
20581 		/* adding a payload buffer; re-initialize values */
20582 		if (add_buffer)
20583 			PREP_NEW_PBUF();
20584 
20585 		/*
20586 		 * If we don't have a Multidata, either because we just
20587 		 * (re)entered this outer loop, or after we branched off
20588 		 * to tcp_send above, setup the Multidata and header
20589 		 * buffer to be used.
20590 		 */
20591 		if (md_mp == NULL) {
20592 			int md_hbuflen;
20593 			uint32_t start, stuff;
20594 
20595 			/*
20596 			 * Calculate Multidata header buffer size large enough
20597 			 * to hold all of the headers that can possibly be
20598 			 * sent at this moment.  We'd rather over-estimate
20599 			 * the size than running out of space; this is okay
20600 			 * since this buffer is small anyway.
20601 			 */
20602 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
20603 
20604 			/*
20605 			 * Start and stuff offset for partial hardware
20606 			 * checksum offload; these are currently for IPv4.
20607 			 * For full checksum offload, they are set to zero.
20608 			 */
20609 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
20610 				if (af == AF_INET) {
20611 					start = IP_SIMPLE_HDR_LENGTH;
20612 					stuff = IP_SIMPLE_HDR_LENGTH +
20613 					    TCP_CHECKSUM_OFFSET;
20614 				} else {
20615 					start = IPV6_HDR_LEN;
20616 					stuff = IPV6_HDR_LEN +
20617 					    TCP_CHECKSUM_OFFSET;
20618 				}
20619 			} else {
20620 				start = stuff = 0;
20621 			}
20622 
20623 			/*
20624 			 * Create the header buffer, Multidata, as well as
20625 			 * any necessary attributes (destination address,
20626 			 * SAP and hardware checksum offload) that should
20627 			 * be associated with the Multidata message.
20628 			 */
20629 			ASSERT(cur_hdr_off == 0);
20630 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
20631 			    ((md_hbuf->b_wptr += md_hbuflen),
20632 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
20633 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
20634 			    /* fastpath mblk */
20635 			    ire->ire_nce->nce_res_mp,
20636 			    /* hardware checksum enabled */
20637 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
20638 			    /* hardware checksum offsets */
20639 			    start, stuff, 0,
20640 			    /* hardware checksum flag */
20641 			    hwcksum_flags, tcps) != 0)) {
20642 legacy_send:
20643 				if (md_mp != NULL) {
20644 					/* Unlink message from the chain */
20645 					if (md_mp_head != NULL) {
20646 						err = (intptr_t)rmvb(md_mp_head,
20647 						    md_mp);
20648 						/*
20649 						 * We can't assert that rmvb
20650 						 * did not return -1, since we
20651 						 * may get here before linkb
20652 						 * happens.  We do, however,
20653 						 * check if we just removed the
20654 						 * only element in the list.
20655 						 */
20656 						if (err == 0)
20657 							md_mp_head = NULL;
20658 					}
20659 					/* md_hbuf gets freed automatically */
20660 					TCP_STAT(tcps, tcp_mdt_discarded);
20661 					freeb(md_mp);
20662 				} else {
20663 					/* Either allocb or mmd_alloc failed */
20664 					TCP_STAT(tcps, tcp_mdt_allocfail);
20665 					if (md_hbuf != NULL)
20666 						freeb(md_hbuf);
20667 				}
20668 
20669 				/* send down what we've got so far */
20670 				if (md_mp_head != NULL) {
20671 					tcp_multisend_data(tcp, ire, ill,
20672 					    md_mp_head, obsegs, obbytes,
20673 					    &rconfirm);
20674 				}
20675 legacy_send_no_md:
20676 				if (ire != NULL)
20677 					IRE_REFRELE(ire);
20678 				/*
20679 				 * Too bad; let the legacy path handle this.
20680 				 * We specify INT_MAX for the threshold, since
20681 				 * we gave up with the Multidata processings
20682 				 * and let the old path have it all.
20683 				 */
20684 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20685 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20686 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20687 				    snxt, tail_unsent, xmit_tail, local_time,
20688 				    INT_MAX));
20689 			}
20690 
20691 			/* link to any existing ones, if applicable */
20692 			TCP_STAT(tcps, tcp_mdt_allocd);
20693 			if (md_mp_head == NULL) {
20694 				md_mp_head = md_mp;
20695 			} else if (tcp_mdt_chain) {
20696 				TCP_STAT(tcps, tcp_mdt_linked);
20697 				linkb(md_mp_head, md_mp);
20698 			}
20699 		}
20700 
20701 		ASSERT(md_mp_head != NULL);
20702 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20703 		ASSERT(md_mp != NULL && mmd != NULL);
20704 		ASSERT(md_hbuf != NULL);
20705 
20706 		/*
20707 		 * Packetize the transmittable portion of the data block;
20708 		 * each data block is essentially added to the Multidata
20709 		 * as a payload buffer.  We also deal with adding more
20710 		 * than one payload buffers, which happens when the remaining
20711 		 * packetized portion of the current payload buffer is less
20712 		 * than MSS, while the next data block in transmit queue
20713 		 * has enough data to make up for one.  This "spillover"
20714 		 * case essentially creates a split-packet, where portions
20715 		 * of the packet's payload fragments may span across two
20716 		 * virtually discontiguous address blocks.
20717 		 */
20718 		seg_len = mss;
20719 		do {
20720 			len = seg_len;
20721 
20722 			/* one must remain NULL for DTRACE_IP_FASTPATH */
20723 			ipha = NULL;
20724 			ip6h = NULL;
20725 
20726 			ASSERT(len > 0);
20727 			ASSERT(max_pld >= 0);
20728 			ASSERT(!add_buffer || cur_pld_off == 0);
20729 
20730 			/*
20731 			 * First time around for this payload buffer; note
20732 			 * in the case of a spillover, the following has
20733 			 * been done prior to adding the split-packet
20734 			 * descriptor to Multidata, and we don't want to
20735 			 * repeat the process.
20736 			 */
20737 			if (add_buffer) {
20738 				ASSERT(mmd != NULL);
20739 				ASSERT(md_pbuf == NULL);
20740 				ASSERT(md_pbuf_nxt == NULL);
20741 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20742 
20743 				/*
20744 				 * Have we reached the limit?  We'd get to
20745 				 * this case when we're not chaining the
20746 				 * Multidata messages together, and since
20747 				 * we're done, terminate this loop.
20748 				 */
20749 				if (max_pld == 0)
20750 					break; /* done */
20751 
20752 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20753 					TCP_STAT(tcps, tcp_mdt_allocfail);
20754 					goto legacy_send; /* out_of_mem */
20755 				}
20756 
20757 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20758 				    zc_cap != NULL) {
20759 					if (!ip_md_zcopy_attr(mmd, NULL,
20760 					    zc_cap->ill_zerocopy_flags)) {
20761 						freeb(md_pbuf);
20762 						TCP_STAT(tcps,
20763 						    tcp_mdt_allocfail);
20764 						/* out_of_mem */
20765 						goto legacy_send;
20766 					}
20767 					zcopy = B_TRUE;
20768 				}
20769 
20770 				md_pbuf->b_rptr += base_pld_off;
20771 
20772 				/*
20773 				 * Add a payload buffer to the Multidata; this
20774 				 * operation must not fail, or otherwise our
20775 				 * logic in this routine is broken.  There
20776 				 * is no memory allocation done by the
20777 				 * routine, so any returned failure simply
20778 				 * tells us that we've done something wrong.
20779 				 *
20780 				 * A failure tells us that either we're adding
20781 				 * the same payload buffer more than once, or
20782 				 * we're trying to add more buffers than
20783 				 * allowed (max_pld calculation is wrong).
20784 				 * None of the above cases should happen, and
20785 				 * we panic because either there's horrible
20786 				 * heap corruption, and/or programming mistake.
20787 				 */
20788 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20789 				if (pbuf_idx < 0) {
20790 					cmn_err(CE_PANIC, "tcp_multisend: "
20791 					    "payload buffer logic error "
20792 					    "detected for tcp %p mmd %p "
20793 					    "pbuf %p (%d)\n",
20794 					    (void *)tcp, (void *)mmd,
20795 					    (void *)md_pbuf, pbuf_idx);
20796 				}
20797 
20798 				ASSERT(max_pld > 0);
20799 				--max_pld;
20800 				add_buffer = B_FALSE;
20801 			}
20802 
20803 			ASSERT(md_mp_head != NULL);
20804 			ASSERT(md_pbuf != NULL);
20805 			ASSERT(md_pbuf_nxt == NULL);
20806 			ASSERT(pbuf_idx != -1);
20807 			ASSERT(pbuf_idx_nxt == -1);
20808 			ASSERT(*usable > 0);
20809 
20810 			/*
20811 			 * We spillover to the next payload buffer only
20812 			 * if all of the following is true:
20813 			 *
20814 			 *   1. There is not enough data on the current
20815 			 *	payload buffer to make up `len',
20816 			 *   2. We are allowed to send `len',
20817 			 *   3. The next payload buffer length is large
20818 			 *	enough to accomodate `spill'.
20819 			 */
20820 			if ((spill = len - *tail_unsent) > 0 &&
20821 			    *usable >= len &&
20822 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20823 			    max_pld > 0) {
20824 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20825 				if (md_pbuf_nxt == NULL) {
20826 					TCP_STAT(tcps, tcp_mdt_allocfail);
20827 					goto legacy_send; /* out_of_mem */
20828 				}
20829 
20830 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20831 				    zc_cap != NULL) {
20832 					if (!ip_md_zcopy_attr(mmd, NULL,
20833 					    zc_cap->ill_zerocopy_flags)) {
20834 						freeb(md_pbuf_nxt);
20835 						TCP_STAT(tcps,
20836 						    tcp_mdt_allocfail);
20837 						/* out_of_mem */
20838 						goto legacy_send;
20839 					}
20840 					zcopy = B_TRUE;
20841 				}
20842 
20843 				/*
20844 				 * See comments above on the first call to
20845 				 * mmd_addpldbuf for explanation on the panic.
20846 				 */
20847 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20848 				if (pbuf_idx_nxt < 0) {
20849 					panic("tcp_multisend: "
20850 					    "next payload buffer logic error "
20851 					    "detected for tcp %p mmd %p "
20852 					    "pbuf %p (%d)\n",
20853 					    (void *)tcp, (void *)mmd,
20854 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20855 				}
20856 
20857 				ASSERT(max_pld > 0);
20858 				--max_pld;
20859 			} else if (spill > 0) {
20860 				/*
20861 				 * If there's a spillover, but the following
20862 				 * xmit_tail couldn't give us enough octets
20863 				 * to reach "len", then stop the current
20864 				 * Multidata creation and let the legacy
20865 				 * tcp_send() path take over.  We don't want
20866 				 * to send the tiny segment as part of this
20867 				 * Multidata for performance reasons; instead,
20868 				 * we let the legacy path deal with grouping
20869 				 * it with the subsequent small mblks.
20870 				 */
20871 				if (*usable >= len &&
20872 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20873 					max_pld = 0;
20874 					break;	/* done */
20875 				}
20876 
20877 				/*
20878 				 * We can't spillover, and we are near
20879 				 * the end of the current payload buffer,
20880 				 * so send what's left.
20881 				 */
20882 				ASSERT(*tail_unsent > 0);
20883 				len = *tail_unsent;
20884 			}
20885 
20886 			/* tail_unsent is negated if there is a spillover */
20887 			*tail_unsent -= len;
20888 			*usable -= len;
20889 			ASSERT(*usable >= 0);
20890 
20891 			if (*usable < mss)
20892 				seg_len = *usable;
20893 			/*
20894 			 * Sender SWS avoidance; see comments in tcp_send();
20895 			 * everything else is the same, except that we only
20896 			 * do this here if there is no more data to be sent
20897 			 * following the current xmit_tail.  We don't check
20898 			 * for 1-byte urgent data because we shouldn't get
20899 			 * here if TCP_URG_VALID is set.
20900 			 */
20901 			if (*usable > 0 && *usable < mss &&
20902 			    ((md_pbuf_nxt == NULL &&
20903 			    (*xmit_tail)->b_cont == NULL) ||
20904 			    (md_pbuf_nxt != NULL &&
20905 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20906 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20907 			    (tcp->tcp_unsent -
20908 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20909 			    !tcp->tcp_zero_win_probe) {
20910 				if ((*snxt + len) == tcp->tcp_snxt &&
20911 				    (*snxt + len) == tcp->tcp_suna) {
20912 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20913 				}
20914 				done = B_TRUE;
20915 			}
20916 
20917 			/*
20918 			 * Prime pump for IP's checksumming on our behalf;
20919 			 * include the adjustment for a source route if any.
20920 			 * Do this only for software/partial hardware checksum
20921 			 * offload, as this field gets zeroed out later for
20922 			 * the full hardware checksum offload case.
20923 			 */
20924 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20925 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20926 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20927 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20928 			}
20929 
20930 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20931 			*snxt += len;
20932 
20933 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20934 			/*
20935 			 * We set the PUSH bit only if TCP has no more buffered
20936 			 * data to be transmitted (or if sender SWS avoidance
20937 			 * takes place), as opposed to setting it for every
20938 			 * last packet in the burst.
20939 			 */
20940 			if (done ||
20941 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20942 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20943 
20944 			/*
20945 			 * Set FIN bit if this is our last segment; snxt
20946 			 * already includes its length, and it will not
20947 			 * be adjusted after this point.
20948 			 */
20949 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20950 			    *snxt == tcp->tcp_fss) {
20951 				if (!tcp->tcp_fin_acked) {
20952 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20953 					BUMP_MIB(&tcps->tcps_mib,
20954 					    tcpOutControl);
20955 				}
20956 				if (!tcp->tcp_fin_sent) {
20957 					tcp->tcp_fin_sent = B_TRUE;
20958 					/*
20959 					 * tcp state must be ESTABLISHED
20960 					 * in order for us to get here in
20961 					 * the first place.
20962 					 */
20963 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20964 
20965 					/*
20966 					 * Upon returning from this routine,
20967 					 * tcp_wput_data() will set tcp_snxt
20968 					 * to be equal to snxt + tcp_fin_sent.
20969 					 * This is essentially the same as
20970 					 * setting it to tcp_fss + 1.
20971 					 */
20972 				}
20973 			}
20974 
20975 			tcp->tcp_last_sent_len = (ushort_t)len;
20976 
20977 			len += tcp_hdr_len;
20978 			if (tcp->tcp_ipversion == IPV4_VERSION)
20979 				tcp->tcp_ipha->ipha_length = htons(len);
20980 			else
20981 				tcp->tcp_ip6h->ip6_plen = htons(len -
20982 				    ((char *)&tcp->tcp_ip6h[1] -
20983 				    tcp->tcp_iphc));
20984 
20985 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20986 
20987 			/* setup header fragment */
20988 			PDESC_HDR_ADD(pkt_info,
20989 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20990 			    tcp->tcp_mdt_hdr_head,		/* head room */
20991 			    tcp_hdr_len,			/* len */
20992 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20993 
20994 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20995 			    hdr_frag_sz);
20996 			ASSERT(MBLKIN(md_hbuf,
20997 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20998 			    PDESC_HDRSIZE(pkt_info)));
20999 
21000 			/* setup first payload fragment */
21001 			PDESC_PLD_INIT(pkt_info);
21002 			PDESC_PLD_SPAN_ADD(pkt_info,
21003 			    pbuf_idx,				/* index */
21004 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
21005 			    tcp->tcp_last_sent_len);		/* len */
21006 
21007 			/* create a split-packet in case of a spillover */
21008 			if (md_pbuf_nxt != NULL) {
21009 				ASSERT(spill > 0);
21010 				ASSERT(pbuf_idx_nxt > pbuf_idx);
21011 				ASSERT(!add_buffer);
21012 
21013 				md_pbuf = md_pbuf_nxt;
21014 				md_pbuf_nxt = NULL;
21015 				pbuf_idx = pbuf_idx_nxt;
21016 				pbuf_idx_nxt = -1;
21017 				cur_pld_off = spill;
21018 
21019 				/* trim out first payload fragment */
21020 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
21021 
21022 				/* setup second payload fragment */
21023 				PDESC_PLD_SPAN_ADD(pkt_info,
21024 				    pbuf_idx,			/* index */
21025 				    md_pbuf->b_rptr,		/* start */
21026 				    spill);			/* len */
21027 
21028 				if ((*xmit_tail)->b_next == NULL) {
21029 					/*
21030 					 * Store the lbolt used for RTT
21031 					 * estimation. We can only record one
21032 					 * timestamp per mblk so we do it when
21033 					 * we reach the end of the payload
21034 					 * buffer.  Also we only take a new
21035 					 * timestamp sample when the previous
21036 					 * timed data from the same mblk has
21037 					 * been ack'ed.
21038 					 */
21039 					(*xmit_tail)->b_prev = local_time;
21040 					(*xmit_tail)->b_next =
21041 					    (mblk_t *)(uintptr_t)first_snxt;
21042 				}
21043 
21044 				first_snxt = *snxt - spill;
21045 
21046 				/*
21047 				 * Advance xmit_tail; usable could be 0 by
21048 				 * the time we got here, but we made sure
21049 				 * above that we would only spillover to
21050 				 * the next data block if usable includes
21051 				 * the spilled-over amount prior to the
21052 				 * subtraction.  Therefore, we are sure
21053 				 * that xmit_tail->b_cont can't be NULL.
21054 				 */
21055 				ASSERT((*xmit_tail)->b_cont != NULL);
21056 				*xmit_tail = (*xmit_tail)->b_cont;
21057 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
21058 				    (uintptr_t)INT_MAX);
21059 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
21060 			} else {
21061 				cur_pld_off += tcp->tcp_last_sent_len;
21062 			}
21063 
21064 			/*
21065 			 * Fill in the header using the template header, and
21066 			 * add options such as time-stamp, ECN and/or SACK,
21067 			 * as needed.
21068 			 */
21069 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
21070 			    (clock_t)local_time, num_sack_blk);
21071 
21072 			/* take care of some IP header businesses */
21073 			if (af == AF_INET) {
21074 				ipha = (ipha_t *)pkt_info->hdr_rptr;
21075 
21076 				ASSERT(OK_32PTR((uchar_t *)ipha));
21077 				ASSERT(PDESC_HDRL(pkt_info) >=
21078 				    IP_SIMPLE_HDR_LENGTH);
21079 				ASSERT(ipha->ipha_version_and_hdr_length ==
21080 				    IP_SIMPLE_HDR_VERSION);
21081 
21082 				/*
21083 				 * Assign ident value for current packet; see
21084 				 * related comments in ip_wput_ire() about the
21085 				 * contract private interface with clustering
21086 				 * group.
21087 				 */
21088 				clusterwide = B_FALSE;
21089 				if (cl_inet_ipident != NULL) {
21090 					ASSERT(cl_inet_isclusterwide != NULL);
21091 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
21092 					    AF_INET,
21093 					    (uint8_t *)(uintptr_t)src)) {
21094 						ipha->ipha_ident =
21095 						    (*cl_inet_ipident)
21096 						    (IPPROTO_IP, AF_INET,
21097 						    (uint8_t *)(uintptr_t)src,
21098 						    (uint8_t *)(uintptr_t)dst);
21099 						clusterwide = B_TRUE;
21100 					}
21101 				}
21102 
21103 				if (!clusterwide) {
21104 					ipha->ipha_ident = (uint16_t)
21105 					    atomic_add_32_nv(
21106 						&ire->ire_ident, 1);
21107 				}
21108 #ifndef _BIG_ENDIAN
21109 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
21110 				    (ipha->ipha_ident >> 8);
21111 #endif
21112 			} else {
21113 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
21114 
21115 				ASSERT(OK_32PTR((uchar_t *)ip6h));
21116 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
21117 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
21118 				ASSERT(PDESC_HDRL(pkt_info) >=
21119 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
21120 				    TCP_CHECKSUM_SIZE));
21121 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21122 
21123 				if (tcp->tcp_ip_forward_progress) {
21124 					rconfirm = B_TRUE;
21125 					tcp->tcp_ip_forward_progress = B_FALSE;
21126 				}
21127 			}
21128 
21129 			/* at least one payload span, and at most two */
21130 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
21131 
21132 			/* add the packet descriptor to Multidata */
21133 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
21134 			    KM_NOSLEEP)) == NULL) {
21135 				/*
21136 				 * Any failure other than ENOMEM indicates
21137 				 * that we have passed in invalid pkt_info
21138 				 * or parameters to mmd_addpdesc, which must
21139 				 * not happen.
21140 				 *
21141 				 * EINVAL is a result of failure on boundary
21142 				 * checks against the pkt_info contents.  It
21143 				 * should not happen, and we panic because
21144 				 * either there's horrible heap corruption,
21145 				 * and/or programming mistake.
21146 				 */
21147 				if (err != ENOMEM) {
21148 					cmn_err(CE_PANIC, "tcp_multisend: "
21149 					    "pdesc logic error detected for "
21150 					    "tcp %p mmd %p pinfo %p (%d)\n",
21151 					    (void *)tcp, (void *)mmd,
21152 					    (void *)pkt_info, err);
21153 				}
21154 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
21155 				goto legacy_send; /* out_of_mem */
21156 			}
21157 			ASSERT(pkt != NULL);
21158 
21159 			/* calculate IP header and TCP checksums */
21160 			if (af == AF_INET) {
21161 				/* calculate pseudo-header checksum */
21162 				cksum = (dst >> 16) + (dst & 0xFFFF) +
21163 				    (src >> 16) + (src & 0xFFFF);
21164 
21165 				/* offset for TCP header checksum */
21166 				up = IPH_TCPH_CHECKSUMP(ipha,
21167 				    IP_SIMPLE_HDR_LENGTH);
21168 			} else {
21169 				up = (uint16_t *)&ip6h->ip6_src;
21170 
21171 				/* calculate pseudo-header checksum */
21172 				cksum = up[0] + up[1] + up[2] + up[3] +
21173 				    up[4] + up[5] + up[6] + up[7] +
21174 				    up[8] + up[9] + up[10] + up[11] +
21175 				    up[12] + up[13] + up[14] + up[15];
21176 
21177 				/* Fold the initial sum */
21178 				cksum = (cksum & 0xffff) + (cksum >> 16);
21179 
21180 				up = (uint16_t *)(((uchar_t *)ip6h) +
21181 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
21182 			}
21183 
21184 			if (hwcksum_flags & HCK_FULLCKSUM) {
21185 				/* clear checksum field for hardware */
21186 				*up = 0;
21187 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
21188 				uint32_t sum;
21189 
21190 				/* pseudo-header checksumming */
21191 				sum = *up + cksum + IP_TCP_CSUM_COMP;
21192 				sum = (sum & 0xFFFF) + (sum >> 16);
21193 				*up = (sum & 0xFFFF) + (sum >> 16);
21194 			} else {
21195 				/* software checksumming */
21196 				TCP_STAT(tcps, tcp_out_sw_cksum);
21197 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
21198 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
21199 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
21200 				    cksum + IP_TCP_CSUM_COMP);
21201 				if (*up == 0)
21202 					*up = 0xFFFF;
21203 			}
21204 
21205 			/* IPv4 header checksum */
21206 			if (af == AF_INET) {
21207 				ipha->ipha_fragment_offset_and_flags |=
21208 				    (uint32_t)htons(ire->ire_frag_flag);
21209 
21210 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
21211 					ipha->ipha_hdr_checksum = 0;
21212 				} else {
21213 					IP_HDR_CKSUM(ipha, cksum,
21214 					    ((uint32_t *)ipha)[0],
21215 					    ((uint16_t *)ipha)[4]);
21216 				}
21217 			}
21218 
21219 			if (af == AF_INET &&
21220 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
21221 			    af == AF_INET6 &&
21222 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
21223 				/* build header(IP/TCP) mblk for this segment */
21224 				if ((mp = dupb(md_hbuf)) == NULL)
21225 					goto legacy_send;
21226 
21227 				mp->b_rptr = pkt_info->hdr_rptr;
21228 				mp->b_wptr = pkt_info->hdr_wptr;
21229 
21230 				/* build payload mblk for this segment */
21231 				if ((mp1 = dupb(*xmit_tail)) == NULL) {
21232 					freemsg(mp);
21233 					goto legacy_send;
21234 				}
21235 				mp1->b_wptr = md_pbuf->b_rptr + cur_pld_off;
21236 				mp1->b_rptr = mp1->b_wptr -
21237 				    tcp->tcp_last_sent_len;
21238 				linkb(mp, mp1);
21239 
21240 				pld_start = mp1->b_rptr;
21241 
21242 				if (af == AF_INET) {
21243 					DTRACE_PROBE4(
21244 					    ip4__physical__out__start,
21245 					    ill_t *, NULL,
21246 					    ill_t *, ill,
21247 					    ipha_t *, ipha,
21248 					    mblk_t *, mp);
21249 					FW_HOOKS(
21250 					    ipst->ips_ip4_physical_out_event,
21251 					    ipst->ips_ipv4firewall_physical_out,
21252 					    NULL, ill, ipha, mp, mp, 0, ipst);
21253 					DTRACE_PROBE1(
21254 					    ip4__physical__out__end,
21255 					    mblk_t *, mp);
21256 				} else {
21257 					DTRACE_PROBE4(
21258 					    ip6__physical__out_start,
21259 					    ill_t *, NULL,
21260 					    ill_t *, ill,
21261 					    ip6_t *, ip6h,
21262 					    mblk_t *, mp);
21263 					FW_HOOKS6(
21264 					    ipst->ips_ip6_physical_out_event,
21265 					    ipst->ips_ipv6firewall_physical_out,
21266 					    NULL, ill, ip6h, mp, mp, 0, ipst);
21267 					DTRACE_PROBE1(
21268 					    ip6__physical__out__end,
21269 					    mblk_t *, mp);
21270 				}
21271 
21272 				if (buf_trunked && mp != NULL) {
21273 					/*
21274 					 * Need to pass it to normal path.
21275 					 */
21276 					CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21277 					mp = NULL;
21278 				} else if (mp == NULL ||
21279 				    mp->b_rptr != pkt_info->hdr_rptr ||
21280 				    mp->b_wptr != pkt_info->hdr_wptr ||
21281 				    (mp1 = mp->b_cont) == NULL ||
21282 				    mp1->b_rptr != pld_start ||
21283 				    mp1->b_wptr != pld_start +
21284 				    tcp->tcp_last_sent_len ||
21285 				    mp1->b_cont != NULL) {
21286 					/*
21287 					 * Need to pass all packets of this
21288 					 * buffer to normal path, either when
21289 					 * packet is blocked, or when boundary
21290 					 * of header buffer or payload buffer
21291 					 * has been changed by FW_HOOKS[6].
21292 					 */
21293 					buf_trunked = B_TRUE;
21294 					if (md_mp_head != NULL) {
21295 						err = (intptr_t)rmvb(md_mp_head,
21296 						    md_mp);
21297 						if (err == 0)
21298 							md_mp_head = NULL;
21299 					}
21300 
21301 					/* send down what we've got so far */
21302 					if (md_mp_head != NULL) {
21303 						tcp_multisend_data(tcp, ire,
21304 						    ill, md_mp_head, obsegs,
21305 						    obbytes, &rconfirm);
21306 					}
21307 					md_mp_head = NULL;
21308 
21309 					if (mp != NULL)
21310 						CALL_IP_WPUT(tcp->tcp_connp,
21311 						    q, mp);
21312 
21313 					mp1 = fw_mp_head;
21314 					do {
21315 						mp = mp1;
21316 						mp1 = mp1->b_next;
21317 						mp->b_next = NULL;
21318 						mp->b_prev = NULL;
21319 						CALL_IP_WPUT(tcp->tcp_connp,
21320 						    q, mp);
21321 					} while (mp1 != NULL);
21322 
21323 					fw_mp_head = mp = NULL;
21324 				} else {
21325 					if (fw_mp_head == NULL)
21326 						fw_mp_head = mp;
21327 					else
21328 						fw_mp_head->b_prev->b_next = mp;
21329 					fw_mp_head->b_prev = mp;
21330 				}
21331 			}
21332 
21333 			if (mp != NULL) {
21334 				DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
21335 				    ill, ipha, ip6h);
21336 			}
21337 
21338 			/* advance header offset */
21339 			cur_hdr_off += hdr_frag_sz;
21340 
21341 			obbytes += tcp->tcp_last_sent_len;
21342 			++obsegs;
21343 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
21344 		    *tail_unsent > 0);
21345 
21346 		if ((*xmit_tail)->b_next == NULL) {
21347 			/*
21348 			 * Store the lbolt used for RTT estimation. We can only
21349 			 * record one timestamp per mblk so we do it when we
21350 			 * reach the end of the payload buffer. Also we only
21351 			 * take a new timestamp sample when the previous timed
21352 			 * data from the same mblk has been ack'ed.
21353 			 */
21354 			(*xmit_tail)->b_prev = local_time;
21355 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
21356 		}
21357 
21358 		ASSERT(*tail_unsent >= 0);
21359 		if (*tail_unsent > 0) {
21360 			/*
21361 			 * We got here because we broke out of the above
21362 			 * loop due to of one of the following cases:
21363 			 *
21364 			 *   1. len < adjusted MSS (i.e. small),
21365 			 *   2. Sender SWS avoidance,
21366 			 *   3. max_pld is zero.
21367 			 *
21368 			 * We are done for this Multidata, so trim our
21369 			 * last payload buffer (if any) accordingly.
21370 			 */
21371 			if (md_pbuf != NULL)
21372 				md_pbuf->b_wptr -= *tail_unsent;
21373 		} else if (*usable > 0) {
21374 			*xmit_tail = (*xmit_tail)->b_cont;
21375 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
21376 			    (uintptr_t)INT_MAX);
21377 			*tail_unsent = (int)MBLKL(*xmit_tail);
21378 			add_buffer = B_TRUE;
21379 		}
21380 
21381 		while (fw_mp_head) {
21382 			mp = fw_mp_head;
21383 			fw_mp_head = fw_mp_head->b_next;
21384 			mp->b_prev = mp->b_next = NULL;
21385 			freemsg(mp);
21386 		}
21387 		if (buf_trunked) {
21388 			TCP_STAT(tcps, tcp_mdt_discarded);
21389 			freeb(md_mp);
21390 			buf_trunked = B_FALSE;
21391 		}
21392 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
21393 	    (tcp_mdt_chain || max_pld > 0));
21394 
21395 	if (md_mp_head != NULL) {
21396 		/* send everything down */
21397 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
21398 		    &rconfirm);
21399 	}
21400 
21401 #undef PREP_NEW_MULTIDATA
21402 #undef PREP_NEW_PBUF
21403 #undef IPVER
21404 
21405 	IRE_REFRELE(ire);
21406 	return (0);
21407 }
21408 
21409 /*
21410  * A wrapper function for sending one or more Multidata messages down to
21411  * the module below ip; this routine does not release the reference of the
21412  * IRE (caller does that).  This routine is analogous to tcp_send_data().
21413  */
21414 static void
21415 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
21416     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
21417 {
21418 	uint64_t delta;
21419 	nce_t *nce;
21420 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21421 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21422 
21423 	ASSERT(ire != NULL && ill != NULL);
21424 	ASSERT(ire->ire_stq != NULL);
21425 	ASSERT(md_mp_head != NULL);
21426 	ASSERT(rconfirm != NULL);
21427 
21428 	/* adjust MIBs and IRE timestamp */
21429 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
21430 	tcp->tcp_obsegs += obsegs;
21431 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
21432 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
21433 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
21434 
21435 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21436 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
21437 	} else {
21438 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
21439 	}
21440 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
21441 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
21442 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
21443 
21444 	ire->ire_ob_pkt_count += obsegs;
21445 	if (ire->ire_ipif != NULL)
21446 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
21447 	ire->ire_last_used_time = lbolt;
21448 
21449 	/* send it down */
21450 	if (ILL_DLS_CAPABLE(ill)) {
21451 		ill_dls_capab_t *ill_dls = ill->ill_dls_capab;
21452 		ill_dls->ill_tx(ill_dls->ill_tx_handle, md_mp_head);
21453 	} else {
21454 		putnext(ire->ire_stq, md_mp_head);
21455 	}
21456 
21457 	/* we're done for TCP/IPv4 */
21458 	if (tcp->tcp_ipversion == IPV4_VERSION)
21459 		return;
21460 
21461 	nce = ire->ire_nce;
21462 
21463 	ASSERT(nce != NULL);
21464 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
21465 	ASSERT(nce->nce_state != ND_INCOMPLETE);
21466 
21467 	/* reachability confirmation? */
21468 	if (*rconfirm) {
21469 		nce->nce_last = TICK_TO_MSEC(lbolt64);
21470 		if (nce->nce_state != ND_REACHABLE) {
21471 			mutex_enter(&nce->nce_lock);
21472 			nce->nce_state = ND_REACHABLE;
21473 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
21474 			mutex_exit(&nce->nce_lock);
21475 			(void) untimeout(nce->nce_timeout_id);
21476 			if (ip_debug > 2) {
21477 				/* ip1dbg */
21478 				pr_addr_dbg("tcp_multisend_data: state "
21479 				    "for %s changed to REACHABLE\n",
21480 				    AF_INET6, &ire->ire_addr_v6);
21481 			}
21482 		}
21483 		/* reset transport reachability confirmation */
21484 		*rconfirm = B_FALSE;
21485 	}
21486 
21487 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
21488 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
21489 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
21490 
21491 	if (delta > (uint64_t)ill->ill_reachable_time) {
21492 		mutex_enter(&nce->nce_lock);
21493 		switch (nce->nce_state) {
21494 		case ND_REACHABLE:
21495 		case ND_STALE:
21496 			/*
21497 			 * ND_REACHABLE is identical to ND_STALE in this
21498 			 * specific case. If reachable time has expired for
21499 			 * this neighbor (delta is greater than reachable
21500 			 * time), conceptually, the neighbor cache is no
21501 			 * longer in REACHABLE state, but already in STALE
21502 			 * state.  So the correct transition here is to
21503 			 * ND_DELAY.
21504 			 */
21505 			nce->nce_state = ND_DELAY;
21506 			mutex_exit(&nce->nce_lock);
21507 			NDP_RESTART_TIMER(nce,
21508 			    ipst->ips_delay_first_probe_time);
21509 			if (ip_debug > 3) {
21510 				/* ip2dbg */
21511 				pr_addr_dbg("tcp_multisend_data: state "
21512 				    "for %s changed to DELAY\n",
21513 				    AF_INET6, &ire->ire_addr_v6);
21514 			}
21515 			break;
21516 		case ND_DELAY:
21517 		case ND_PROBE:
21518 			mutex_exit(&nce->nce_lock);
21519 			/* Timers have already started */
21520 			break;
21521 		case ND_UNREACHABLE:
21522 			/*
21523 			 * ndp timer has detected that this nce is
21524 			 * unreachable and initiated deleting this nce
21525 			 * and all its associated IREs. This is a race
21526 			 * where we found the ire before it was deleted
21527 			 * and have just sent out a packet using this
21528 			 * unreachable nce.
21529 			 */
21530 			mutex_exit(&nce->nce_lock);
21531 			break;
21532 		default:
21533 			ASSERT(0);
21534 		}
21535 	}
21536 }
21537 
21538 /*
21539  * Derived from tcp_send_data().
21540  */
21541 static void
21542 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
21543     int num_lso_seg)
21544 {
21545 	ipha_t		*ipha;
21546 	mblk_t		*ire_fp_mp;
21547 	uint_t		ire_fp_mp_len;
21548 	uint32_t	hcksum_txflags = 0;
21549 	ipaddr_t	src;
21550 	ipaddr_t	dst;
21551 	uint32_t	cksum;
21552 	uint16_t	*up;
21553 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21554 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21555 
21556 	ASSERT(DB_TYPE(mp) == M_DATA);
21557 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
21558 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
21559 	ASSERT(tcp->tcp_connp != NULL);
21560 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
21561 
21562 	ipha = (ipha_t *)mp->b_rptr;
21563 	src = ipha->ipha_src;
21564 	dst = ipha->ipha_dst;
21565 
21566 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21567 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
21568 	    num_lso_seg);
21569 #ifndef _BIG_ENDIAN
21570 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21571 #endif
21572 	if (tcp->tcp_snd_zcopy_aware) {
21573 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
21574 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
21575 			mp = tcp_zcopy_disable(tcp, mp);
21576 	}
21577 
21578 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
21579 		ASSERT(ill->ill_hcksum_capab != NULL);
21580 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
21581 	}
21582 
21583 	/*
21584 	 * Since the TCP checksum should be recalculated by h/w, we can just
21585 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
21586 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
21587 	 * The partial pseudo-header excludes TCP length, that was calculated
21588 	 * in tcp_send(), so to zero *up before further processing.
21589 	 */
21590 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21591 
21592 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
21593 	*up = 0;
21594 
21595 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
21596 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
21597 
21598 	/*
21599 	 * Append LSO flag to DB_LSOFLAGS(mp) and set the mss to DB_LSOMSS(mp).
21600 	 */
21601 	DB_LSOFLAGS(mp) |= HW_LSO;
21602 	DB_LSOMSS(mp) = mss;
21603 
21604 	ipha->ipha_fragment_offset_and_flags |=
21605 	    (uint32_t)htons(ire->ire_frag_flag);
21606 
21607 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
21608 	ire_fp_mp_len = MBLKL(ire_fp_mp);
21609 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
21610 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
21611 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
21612 
21613 	UPDATE_OB_PKT_COUNT(ire);
21614 	ire->ire_last_used_time = lbolt;
21615 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
21616 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
21617 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
21618 	    ntohs(ipha->ipha_length));
21619 
21620 	if (ILL_DLS_CAPABLE(ill)) {
21621 		/*
21622 		 * Send the packet directly to DLD, where it may be queued
21623 		 * depending on the availability of transmit resources at
21624 		 * the media layer.
21625 		 */
21626 		IP_DLS_ILL_TX(ill, ipha, mp, ipst);
21627 	} else {
21628 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
21629 		DTRACE_PROBE4(ip4__physical__out__start,
21630 		    ill_t *, NULL, ill_t *, out_ill,
21631 		    ipha_t *, ipha, mblk_t *, mp);
21632 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
21633 		    ipst->ips_ipv4firewall_physical_out,
21634 		    NULL, out_ill, ipha, mp, mp, 0, ipst);
21635 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21636 
21637 		if (mp != NULL) {
21638 			DTRACE_IP_FASTPATH(mp, ipha, out_ill, ipha, NULL);
21639 			putnext(ire->ire_stq, mp);
21640 		}
21641 	}
21642 }
21643 
21644 /*
21645  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
21646  * scheme, and returns one of the following:
21647  *
21648  * -1 = failed allocation.
21649  *  0 = success; burst count reached, or usable send window is too small,
21650  *      and that we'd rather wait until later before sending again.
21651  *  1 = success; we are called from tcp_multisend(), and both usable send
21652  *      window and tail_unsent are greater than the MDT threshold, and thus
21653  *      Multidata Transmit should be used instead.
21654  */
21655 static int
21656 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
21657     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
21658     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
21659     const int mdt_thres)
21660 {
21661 	int num_burst_seg = tcp->tcp_snd_burst;
21662 	ire_t		*ire = NULL;
21663 	ill_t		*ill = NULL;
21664 	mblk_t		*ire_fp_mp = NULL;
21665 	uint_t		ire_fp_mp_len = 0;
21666 	int		num_lso_seg = 1;
21667 	uint_t		lso_usable;
21668 	boolean_t	do_lso_send = B_FALSE;
21669 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21670 
21671 	/*
21672 	 * Check LSO capability before any further work. And the similar check
21673 	 * need to be done in for(;;) loop.
21674 	 * LSO will be deployed when therer is more than one mss of available
21675 	 * data and a burst transmission is allowed.
21676 	 */
21677 	if (tcp->tcp_lso &&
21678 	    (tcp->tcp_valid_bits == 0 ||
21679 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21680 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21681 		/*
21682 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21683 		 */
21684 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
21685 			/*
21686 			 * Enable LSO with this transmission.
21687 			 * Since IRE has been hold in
21688 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
21689 			 * should be called before return.
21690 			 */
21691 			do_lso_send = B_TRUE;
21692 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21693 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21694 			/* Round up to multiple of 4 */
21695 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21696 		} else {
21697 			do_lso_send = B_FALSE;
21698 			ill = NULL;
21699 		}
21700 	}
21701 
21702 	for (;;) {
21703 		struct datab	*db;
21704 		tcph_t		*tcph;
21705 		uint32_t	sum;
21706 		mblk_t		*mp, *mp1;
21707 		uchar_t		*rptr;
21708 		int		len;
21709 
21710 		/*
21711 		 * If we're called by tcp_multisend(), and the amount of
21712 		 * sendable data as well as the size of current xmit_tail
21713 		 * is beyond the MDT threshold, return to the caller and
21714 		 * let the large data transmit be done using MDT.
21715 		 */
21716 		if (*usable > 0 && *usable > mdt_thres &&
21717 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21718 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21719 			ASSERT(tcp->tcp_mdt);
21720 			return (1);	/* success; do large send */
21721 		}
21722 
21723 		if (num_burst_seg == 0)
21724 			break;		/* success; burst count reached */
21725 
21726 		/*
21727 		 * Calculate the maximum payload length we can send in *one*
21728 		 * time.
21729 		 */
21730 		if (do_lso_send) {
21731 			/*
21732 			 * Check whether need to do LSO any more.
21733 			 */
21734 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21735 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21736 				lso_usable = MIN(lso_usable,
21737 				    num_burst_seg * mss);
21738 
21739 				num_lso_seg = lso_usable / mss;
21740 				if (lso_usable % mss) {
21741 					num_lso_seg++;
21742 					tcp->tcp_last_sent_len = (ushort_t)
21743 					    (lso_usable % mss);
21744 				} else {
21745 					tcp->tcp_last_sent_len = (ushort_t)mss;
21746 				}
21747 			} else {
21748 				do_lso_send = B_FALSE;
21749 				num_lso_seg = 1;
21750 				lso_usable = mss;
21751 			}
21752 		}
21753 
21754 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21755 
21756 		/*
21757 		 * Adjust num_burst_seg here.
21758 		 */
21759 		num_burst_seg -= num_lso_seg;
21760 
21761 		len = mss;
21762 		if (len > *usable) {
21763 			ASSERT(do_lso_send == B_FALSE);
21764 
21765 			len = *usable;
21766 			if (len <= 0) {
21767 				/* Terminate the loop */
21768 				break;	/* success; too small */
21769 			}
21770 			/*
21771 			 * Sender silly-window avoidance.
21772 			 * Ignore this if we are going to send a
21773 			 * zero window probe out.
21774 			 *
21775 			 * TODO: force data into microscopic window?
21776 			 *	==> (!pushed || (unsent > usable))
21777 			 */
21778 			if (len < (tcp->tcp_max_swnd >> 1) &&
21779 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21780 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21781 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21782 				/*
21783 				 * If the retransmit timer is not running
21784 				 * we start it so that we will retransmit
21785 				 * in the case when the the receiver has
21786 				 * decremented the window.
21787 				 */
21788 				if (*snxt == tcp->tcp_snxt &&
21789 				    *snxt == tcp->tcp_suna) {
21790 					/*
21791 					 * We are not supposed to send
21792 					 * anything.  So let's wait a little
21793 					 * bit longer before breaking SWS
21794 					 * avoidance.
21795 					 *
21796 					 * What should the value be?
21797 					 * Suggestion: MAX(init rexmit time,
21798 					 * tcp->tcp_rto)
21799 					 */
21800 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21801 				}
21802 				break;	/* success; too small */
21803 			}
21804 		}
21805 
21806 		tcph = tcp->tcp_tcph;
21807 
21808 		/*
21809 		 * The reason to adjust len here is that we need to set flags
21810 		 * and calculate checksum.
21811 		 */
21812 		if (do_lso_send)
21813 			len = lso_usable;
21814 
21815 		*usable -= len; /* Approximate - can be adjusted later */
21816 		if (*usable > 0)
21817 			tcph->th_flags[0] = TH_ACK;
21818 		else
21819 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21820 
21821 		/*
21822 		 * Prime pump for IP's checksumming on our behalf
21823 		 * Include the adjustment for a source route if any.
21824 		 */
21825 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21826 		sum = (sum >> 16) + (sum & 0xFFFF);
21827 		U16_TO_ABE16(sum, tcph->th_sum);
21828 
21829 		U32_TO_ABE32(*snxt, tcph->th_seq);
21830 
21831 		/*
21832 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21833 		 * set.  For the case when TCP_FSS_VALID is the only valid
21834 		 * bit (normal active close), branch off only when we think
21835 		 * that the FIN flag needs to be set.  Note for this case,
21836 		 * that (snxt + len) may not reflect the actual seg_len,
21837 		 * as len may be further reduced in tcp_xmit_mp().  If len
21838 		 * gets modified, we will end up here again.
21839 		 */
21840 		if (tcp->tcp_valid_bits != 0 &&
21841 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21842 		    ((*snxt + len) == tcp->tcp_fss))) {
21843 			uchar_t		*prev_rptr;
21844 			uint32_t	prev_snxt = tcp->tcp_snxt;
21845 
21846 			if (*tail_unsent == 0) {
21847 				ASSERT((*xmit_tail)->b_cont != NULL);
21848 				*xmit_tail = (*xmit_tail)->b_cont;
21849 				prev_rptr = (*xmit_tail)->b_rptr;
21850 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21851 				    (*xmit_tail)->b_rptr);
21852 			} else {
21853 				prev_rptr = (*xmit_tail)->b_rptr;
21854 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21855 				    *tail_unsent;
21856 			}
21857 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21858 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21859 			/* Restore tcp_snxt so we get amount sent right. */
21860 			tcp->tcp_snxt = prev_snxt;
21861 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21862 				/*
21863 				 * If the previous timestamp is still in use,
21864 				 * don't stomp on it.
21865 				 */
21866 				if ((*xmit_tail)->b_next == NULL) {
21867 					(*xmit_tail)->b_prev = local_time;
21868 					(*xmit_tail)->b_next =
21869 					    (mblk_t *)(uintptr_t)(*snxt);
21870 				}
21871 			} else
21872 				(*xmit_tail)->b_rptr = prev_rptr;
21873 
21874 			if (mp == NULL) {
21875 				if (ire != NULL)
21876 					IRE_REFRELE(ire);
21877 				return (-1);
21878 			}
21879 			mp1 = mp->b_cont;
21880 
21881 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21882 				tcp->tcp_last_sent_len = (ushort_t)len;
21883 			while (mp1->b_cont) {
21884 				*xmit_tail = (*xmit_tail)->b_cont;
21885 				(*xmit_tail)->b_prev = local_time;
21886 				(*xmit_tail)->b_next =
21887 				    (mblk_t *)(uintptr_t)(*snxt);
21888 				mp1 = mp1->b_cont;
21889 			}
21890 			*snxt += len;
21891 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21892 			BUMP_LOCAL(tcp->tcp_obsegs);
21893 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21894 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21895 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21896 			tcp_send_data(tcp, q, mp);
21897 			continue;
21898 		}
21899 
21900 		*snxt += len;	/* Adjust later if we don't send all of len */
21901 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21902 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21903 
21904 		if (*tail_unsent) {
21905 			/* Are the bytes above us in flight? */
21906 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21907 			if (rptr != (*xmit_tail)->b_rptr) {
21908 				*tail_unsent -= len;
21909 				if (len <= mss) /* LSO is unusable */
21910 					tcp->tcp_last_sent_len = (ushort_t)len;
21911 				len += tcp_hdr_len;
21912 				if (tcp->tcp_ipversion == IPV4_VERSION)
21913 					tcp->tcp_ipha->ipha_length = htons(len);
21914 				else
21915 					tcp->tcp_ip6h->ip6_plen =
21916 					    htons(len -
21917 					    ((char *)&tcp->tcp_ip6h[1] -
21918 					    tcp->tcp_iphc));
21919 				mp = dupb(*xmit_tail);
21920 				if (mp == NULL) {
21921 					if (ire != NULL)
21922 						IRE_REFRELE(ire);
21923 					return (-1);	/* out_of_mem */
21924 				}
21925 				mp->b_rptr = rptr;
21926 				/*
21927 				 * If the old timestamp is no longer in use,
21928 				 * sample a new timestamp now.
21929 				 */
21930 				if ((*xmit_tail)->b_next == NULL) {
21931 					(*xmit_tail)->b_prev = local_time;
21932 					(*xmit_tail)->b_next =
21933 					    (mblk_t *)(uintptr_t)(*snxt-len);
21934 				}
21935 				goto must_alloc;
21936 			}
21937 		} else {
21938 			*xmit_tail = (*xmit_tail)->b_cont;
21939 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21940 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21941 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21942 			    (*xmit_tail)->b_rptr);
21943 		}
21944 
21945 		(*xmit_tail)->b_prev = local_time;
21946 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21947 
21948 		*tail_unsent -= len;
21949 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21950 			tcp->tcp_last_sent_len = (ushort_t)len;
21951 
21952 		len += tcp_hdr_len;
21953 		if (tcp->tcp_ipversion == IPV4_VERSION)
21954 			tcp->tcp_ipha->ipha_length = htons(len);
21955 		else
21956 			tcp->tcp_ip6h->ip6_plen = htons(len -
21957 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21958 
21959 		mp = dupb(*xmit_tail);
21960 		if (mp == NULL) {
21961 			if (ire != NULL)
21962 				IRE_REFRELE(ire);
21963 			return (-1);	/* out_of_mem */
21964 		}
21965 
21966 		len = tcp_hdr_len;
21967 		/*
21968 		 * There are four reasons to allocate a new hdr mblk:
21969 		 *  1) The bytes above us are in use by another packet
21970 		 *  2) We don't have good alignment
21971 		 *  3) The mblk is being shared
21972 		 *  4) We don't have enough room for a header
21973 		 */
21974 		rptr = mp->b_rptr - len;
21975 		if (!OK_32PTR(rptr) ||
21976 		    ((db = mp->b_datap), db->db_ref != 2) ||
21977 		    rptr < db->db_base + ire_fp_mp_len) {
21978 			/* NOTE: we assume allocb returns an OK_32PTR */
21979 
21980 		must_alloc:;
21981 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21982 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21983 			if (mp1 == NULL) {
21984 				freemsg(mp);
21985 				if (ire != NULL)
21986 					IRE_REFRELE(ire);
21987 				return (-1);	/* out_of_mem */
21988 			}
21989 			mp1->b_cont = mp;
21990 			mp = mp1;
21991 			/* Leave room for Link Level header */
21992 			len = tcp_hdr_len;
21993 			rptr =
21994 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21995 			mp->b_wptr = &rptr[len];
21996 		}
21997 
21998 		/*
21999 		 * Fill in the header using the template header, and add
22000 		 * options such as time-stamp, ECN and/or SACK, as needed.
22001 		 */
22002 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
22003 
22004 		mp->b_rptr = rptr;
22005 
22006 		if (*tail_unsent) {
22007 			int spill = *tail_unsent;
22008 
22009 			mp1 = mp->b_cont;
22010 			if (mp1 == NULL)
22011 				mp1 = mp;
22012 
22013 			/*
22014 			 * If we're a little short, tack on more mblks until
22015 			 * there is no more spillover.
22016 			 */
22017 			while (spill < 0) {
22018 				mblk_t *nmp;
22019 				int nmpsz;
22020 
22021 				nmp = (*xmit_tail)->b_cont;
22022 				nmpsz = MBLKL(nmp);
22023 
22024 				/*
22025 				 * Excess data in mblk; can we split it?
22026 				 * If MDT is enabled for the connection,
22027 				 * keep on splitting as this is a transient
22028 				 * send path.
22029 				 */
22030 				if (!do_lso_send && !tcp->tcp_mdt &&
22031 				    (spill + nmpsz > 0)) {
22032 					/*
22033 					 * Don't split if stream head was
22034 					 * told to break up larger writes
22035 					 * into smaller ones.
22036 					 */
22037 					if (tcp->tcp_maxpsz > 0)
22038 						break;
22039 
22040 					/*
22041 					 * Next mblk is less than SMSS/2
22042 					 * rounded up to nearest 64-byte;
22043 					 * let it get sent as part of the
22044 					 * next segment.
22045 					 */
22046 					if (tcp->tcp_localnet &&
22047 					    !tcp->tcp_cork &&
22048 					    (nmpsz < roundup((mss >> 1), 64)))
22049 						break;
22050 				}
22051 
22052 				*xmit_tail = nmp;
22053 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
22054 				/* Stash for rtt use later */
22055 				(*xmit_tail)->b_prev = local_time;
22056 				(*xmit_tail)->b_next =
22057 				    (mblk_t *)(uintptr_t)(*snxt - len);
22058 				mp1->b_cont = dupb(*xmit_tail);
22059 				mp1 = mp1->b_cont;
22060 
22061 				spill += nmpsz;
22062 				if (mp1 == NULL) {
22063 					*tail_unsent = spill;
22064 					freemsg(mp);
22065 					if (ire != NULL)
22066 						IRE_REFRELE(ire);
22067 					return (-1);	/* out_of_mem */
22068 				}
22069 			}
22070 
22071 			/* Trim back any surplus on the last mblk */
22072 			if (spill >= 0) {
22073 				mp1->b_wptr -= spill;
22074 				*tail_unsent = spill;
22075 			} else {
22076 				/*
22077 				 * We did not send everything we could in
22078 				 * order to remain within the b_cont limit.
22079 				 */
22080 				*usable -= spill;
22081 				*snxt += spill;
22082 				tcp->tcp_last_sent_len += spill;
22083 				UPDATE_MIB(&tcps->tcps_mib,
22084 				    tcpOutDataBytes, spill);
22085 				/*
22086 				 * Adjust the checksum
22087 				 */
22088 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
22089 				sum += spill;
22090 				sum = (sum >> 16) + (sum & 0xFFFF);
22091 				U16_TO_ABE16(sum, tcph->th_sum);
22092 				if (tcp->tcp_ipversion == IPV4_VERSION) {
22093 					sum = ntohs(
22094 					    ((ipha_t *)rptr)->ipha_length) +
22095 					    spill;
22096 					((ipha_t *)rptr)->ipha_length =
22097 					    htons(sum);
22098 				} else {
22099 					sum = ntohs(
22100 					    ((ip6_t *)rptr)->ip6_plen) +
22101 					    spill;
22102 					((ip6_t *)rptr)->ip6_plen =
22103 					    htons(sum);
22104 				}
22105 				*tail_unsent = 0;
22106 			}
22107 		}
22108 		if (tcp->tcp_ip_forward_progress) {
22109 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22110 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
22111 			tcp->tcp_ip_forward_progress = B_FALSE;
22112 		}
22113 
22114 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22115 		if (do_lso_send) {
22116 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
22117 			    num_lso_seg);
22118 			tcp->tcp_obsegs += num_lso_seg;
22119 
22120 			TCP_STAT(tcps, tcp_lso_times);
22121 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
22122 		} else {
22123 			tcp_send_data(tcp, q, mp);
22124 			BUMP_LOCAL(tcp->tcp_obsegs);
22125 		}
22126 	}
22127 
22128 	if (ire != NULL)
22129 		IRE_REFRELE(ire);
22130 	return (0);
22131 }
22132 
22133 /* Unlink and return any mblk that looks like it contains a MDT info */
22134 static mblk_t *
22135 tcp_mdt_info_mp(mblk_t *mp)
22136 {
22137 	mblk_t	*prev_mp;
22138 
22139 	for (;;) {
22140 		prev_mp = mp;
22141 		/* no more to process? */
22142 		if ((mp = mp->b_cont) == NULL)
22143 			break;
22144 
22145 		switch (DB_TYPE(mp)) {
22146 		case M_CTL:
22147 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
22148 				continue;
22149 			ASSERT(prev_mp != NULL);
22150 			prev_mp->b_cont = mp->b_cont;
22151 			mp->b_cont = NULL;
22152 			return (mp);
22153 		default:
22154 			break;
22155 		}
22156 	}
22157 	return (mp);
22158 }
22159 
22160 /* MDT info update routine, called when IP notifies us about MDT */
22161 static void
22162 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
22163 {
22164 	boolean_t prev_state;
22165 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22166 
22167 	/*
22168 	 * IP is telling us to abort MDT on this connection?  We know
22169 	 * this because the capability is only turned off when IP
22170 	 * encounters some pathological cases, e.g. link-layer change
22171 	 * where the new driver doesn't support MDT, or in situation
22172 	 * where MDT usage on the link-layer has been switched off.
22173 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
22174 	 * if the link-layer doesn't support MDT, and if it does, it
22175 	 * will indicate that the feature is to be turned on.
22176 	 */
22177 	prev_state = tcp->tcp_mdt;
22178 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
22179 	if (!tcp->tcp_mdt && !first) {
22180 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
22181 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
22182 		    (void *)tcp->tcp_connp));
22183 	}
22184 
22185 	/*
22186 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
22187 	 * so disable MDT otherwise.  The checks are done here
22188 	 * and in tcp_wput_data().
22189 	 */
22190 	if (tcp->tcp_mdt &&
22191 	    (tcp->tcp_ipversion == IPV4_VERSION &&
22192 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
22193 	    (tcp->tcp_ipversion == IPV6_VERSION &&
22194 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
22195 		tcp->tcp_mdt = B_FALSE;
22196 
22197 	if (tcp->tcp_mdt) {
22198 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
22199 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
22200 			    "version (%d), expected version is %d",
22201 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
22202 			tcp->tcp_mdt = B_FALSE;
22203 			return;
22204 		}
22205 
22206 		/*
22207 		 * We need the driver to be able to handle at least three
22208 		 * spans per packet in order for tcp MDT to be utilized.
22209 		 * The first is for the header portion, while the rest are
22210 		 * needed to handle a packet that straddles across two
22211 		 * virtually non-contiguous buffers; a typical tcp packet
22212 		 * therefore consists of only two spans.  Note that we take
22213 		 * a zero as "don't care".
22214 		 */
22215 		if (mdt_capab->ill_mdt_span_limit > 0 &&
22216 		    mdt_capab->ill_mdt_span_limit < 3) {
22217 			tcp->tcp_mdt = B_FALSE;
22218 			return;
22219 		}
22220 
22221 		/* a zero means driver wants default value */
22222 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
22223 		    tcps->tcps_mdt_max_pbufs);
22224 		if (tcp->tcp_mdt_max_pld == 0)
22225 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
22226 
22227 		/* ensure 32-bit alignment */
22228 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
22229 		    mdt_capab->ill_mdt_hdr_head), 4);
22230 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
22231 		    mdt_capab->ill_mdt_hdr_tail), 4);
22232 
22233 		if (!first && !prev_state) {
22234 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
22235 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
22236 			    (void *)tcp->tcp_connp));
22237 		}
22238 	}
22239 }
22240 
22241 /* Unlink and return any mblk that looks like it contains a LSO info */
22242 static mblk_t *
22243 tcp_lso_info_mp(mblk_t *mp)
22244 {
22245 	mblk_t	*prev_mp;
22246 
22247 	for (;;) {
22248 		prev_mp = mp;
22249 		/* no more to process? */
22250 		if ((mp = mp->b_cont) == NULL)
22251 			break;
22252 
22253 		switch (DB_TYPE(mp)) {
22254 		case M_CTL:
22255 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
22256 				continue;
22257 			ASSERT(prev_mp != NULL);
22258 			prev_mp->b_cont = mp->b_cont;
22259 			mp->b_cont = NULL;
22260 			return (mp);
22261 		default:
22262 			break;
22263 		}
22264 	}
22265 
22266 	return (mp);
22267 }
22268 
22269 /* LSO info update routine, called when IP notifies us about LSO */
22270 static void
22271 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
22272 {
22273 	tcp_stack_t *tcps = tcp->tcp_tcps;
22274 
22275 	/*
22276 	 * IP is telling us to abort LSO on this connection?  We know
22277 	 * this because the capability is only turned off when IP
22278 	 * encounters some pathological cases, e.g. link-layer change
22279 	 * where the new NIC/driver doesn't support LSO, or in situation
22280 	 * where LSO usage on the link-layer has been switched off.
22281 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
22282 	 * if the link-layer doesn't support LSO, and if it does, it
22283 	 * will indicate that the feature is to be turned on.
22284 	 */
22285 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
22286 	TCP_STAT(tcps, tcp_lso_enabled);
22287 
22288 	/*
22289 	 * We currently only support LSO on simple TCP/IPv4,
22290 	 * so disable LSO otherwise.  The checks are done here
22291 	 * and in tcp_wput_data().
22292 	 */
22293 	if (tcp->tcp_lso &&
22294 	    (tcp->tcp_ipversion == IPV4_VERSION &&
22295 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
22296 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
22297 		tcp->tcp_lso = B_FALSE;
22298 		TCP_STAT(tcps, tcp_lso_disabled);
22299 	} else {
22300 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
22301 		    lso_capab->ill_lso_max);
22302 	}
22303 }
22304 
22305 static void
22306 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
22307 {
22308 	conn_t *connp = tcp->tcp_connp;
22309 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22310 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22311 
22312 	ASSERT(ire != NULL);
22313 
22314 	/*
22315 	 * We may be in the fastpath here, and although we essentially do
22316 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
22317 	 * we try to keep things as brief as possible.  After all, these
22318 	 * are only best-effort checks, and we do more thorough ones prior
22319 	 * to calling tcp_send()/tcp_multisend().
22320 	 */
22321 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
22322 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
22323 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
22324 	    !(ire->ire_flags & RTF_MULTIRT) &&
22325 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
22326 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
22327 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
22328 			/* Cache the result */
22329 			connp->conn_lso_ok = B_TRUE;
22330 
22331 			ASSERT(ill->ill_lso_capab != NULL);
22332 			if (!ill->ill_lso_capab->ill_lso_on) {
22333 				ill->ill_lso_capab->ill_lso_on = 1;
22334 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22335 				    "LSO for interface %s\n", (void *)connp,
22336 				    ill->ill_name));
22337 			}
22338 			tcp_lso_update(tcp, ill->ill_lso_capab);
22339 		} else if (ipst->ips_ip_multidata_outbound &&
22340 		    ILL_MDT_CAPABLE(ill)) {
22341 			/* Cache the result */
22342 			connp->conn_mdt_ok = B_TRUE;
22343 
22344 			ASSERT(ill->ill_mdt_capab != NULL);
22345 			if (!ill->ill_mdt_capab->ill_mdt_on) {
22346 				ill->ill_mdt_capab->ill_mdt_on = 1;
22347 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22348 				    "MDT for interface %s\n", (void *)connp,
22349 				    ill->ill_name));
22350 			}
22351 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
22352 		}
22353 	}
22354 
22355 	/*
22356 	 * The goal is to reduce the number of generated tcp segments by
22357 	 * setting the maxpsz multiplier to 0; this will have an affect on
22358 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
22359 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
22360 	 * of outbound segments and incoming ACKs, thus allowing for better
22361 	 * network and system performance.  In contrast the legacy behavior
22362 	 * may result in sending less than SMSS size, because the last mblk
22363 	 * for some packets may have more data than needed to make up SMSS,
22364 	 * and the legacy code refused to "split" it.
22365 	 *
22366 	 * We apply the new behavior on following situations:
22367 	 *
22368 	 *   1) Loopback connections,
22369 	 *   2) Connections in which the remote peer is not on local subnet,
22370 	 *   3) Local subnet connections over the bge interface (see below).
22371 	 *
22372 	 * Ideally, we would like this behavior to apply for interfaces other
22373 	 * than bge.  However, doing so would negatively impact drivers which
22374 	 * perform dynamic mapping and unmapping of DMA resources, which are
22375 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
22376 	 * packet will be generated by tcp).  The bge driver does not suffer
22377 	 * from this, as it copies the mblks into pre-mapped buffers, and
22378 	 * therefore does not require more I/O resources than before.
22379 	 *
22380 	 * Otherwise, this behavior is present on all network interfaces when
22381 	 * the destination endpoint is non-local, since reducing the number
22382 	 * of packets in general is good for the network.
22383 	 *
22384 	 * TODO We need to remove this hard-coded conditional for bge once
22385 	 *	a better "self-tuning" mechanism, or a way to comprehend
22386 	 *	the driver transmit strategy is devised.  Until the solution
22387 	 *	is found and well understood, we live with this hack.
22388 	 */
22389 	if (!tcp_static_maxpsz &&
22390 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
22391 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
22392 		/* override the default value */
22393 		tcp->tcp_maxpsz = 0;
22394 
22395 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
22396 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
22397 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
22398 	}
22399 
22400 	/* set the stream head parameters accordingly */
22401 	(void) tcp_maxpsz_set(tcp, B_TRUE);
22402 }
22403 
22404 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
22405 static void
22406 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
22407 {
22408 	uchar_t	fval = *mp->b_rptr;
22409 	mblk_t	*tail;
22410 	queue_t	*q = tcp->tcp_wq;
22411 
22412 	/* TODO: How should flush interact with urgent data? */
22413 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
22414 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
22415 		/*
22416 		 * Flush only data that has not yet been put on the wire.  If
22417 		 * we flush data that we have already transmitted, life, as we
22418 		 * know it, may come to an end.
22419 		 */
22420 		tail = tcp->tcp_xmit_tail;
22421 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
22422 		tcp->tcp_xmit_tail_unsent = 0;
22423 		tcp->tcp_unsent = 0;
22424 		if (tail->b_wptr != tail->b_rptr)
22425 			tail = tail->b_cont;
22426 		if (tail) {
22427 			mblk_t **excess = &tcp->tcp_xmit_head;
22428 			for (;;) {
22429 				mblk_t *mp1 = *excess;
22430 				if (mp1 == tail)
22431 					break;
22432 				tcp->tcp_xmit_tail = mp1;
22433 				tcp->tcp_xmit_last = mp1;
22434 				excess = &mp1->b_cont;
22435 			}
22436 			*excess = NULL;
22437 			tcp_close_mpp(&tail);
22438 			if (tcp->tcp_snd_zcopy_aware)
22439 				tcp_zcopy_notify(tcp);
22440 		}
22441 		/*
22442 		 * We have no unsent data, so unsent must be less than
22443 		 * tcp_xmit_lowater, so re-enable flow.
22444 		 */
22445 		mutex_enter(&tcp->tcp_non_sq_lock);
22446 		if (tcp->tcp_flow_stopped) {
22447 			tcp_clrqfull(tcp);
22448 		}
22449 		mutex_exit(&tcp->tcp_non_sq_lock);
22450 	}
22451 	/*
22452 	 * TODO: you can't just flush these, you have to increase rwnd for one
22453 	 * thing.  For another, how should urgent data interact?
22454 	 */
22455 	if (fval & FLUSHR) {
22456 		*mp->b_rptr = fval & ~FLUSHW;
22457 		/* XXX */
22458 		qreply(q, mp);
22459 		return;
22460 	}
22461 	freemsg(mp);
22462 }
22463 
22464 /*
22465  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
22466  * messages.
22467  */
22468 static void
22469 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
22470 {
22471 	mblk_t	*mp1;
22472 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
22473 	STRUCT_HANDLE(strbuf, sb);
22474 	queue_t *q = tcp->tcp_wq;
22475 	int	error;
22476 	uint_t	addrlen;
22477 
22478 	/* Make sure it is one of ours. */
22479 	switch (iocp->ioc_cmd) {
22480 	case TI_GETMYNAME:
22481 	case TI_GETPEERNAME:
22482 		break;
22483 	default:
22484 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
22485 		return;
22486 	}
22487 	switch (mi_copy_state(q, mp, &mp1)) {
22488 	case -1:
22489 		return;
22490 	case MI_COPY_CASE(MI_COPY_IN, 1):
22491 		break;
22492 	case MI_COPY_CASE(MI_COPY_OUT, 1):
22493 		/* Copy out the strbuf. */
22494 		mi_copyout(q, mp);
22495 		return;
22496 	case MI_COPY_CASE(MI_COPY_OUT, 2):
22497 		/* All done. */
22498 		mi_copy_done(q, mp, 0);
22499 		return;
22500 	default:
22501 		mi_copy_done(q, mp, EPROTO);
22502 		return;
22503 	}
22504 	/* Check alignment of the strbuf */
22505 	if (!OK_32PTR(mp1->b_rptr)) {
22506 		mi_copy_done(q, mp, EINVAL);
22507 		return;
22508 	}
22509 
22510 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
22511 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
22512 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
22513 		mi_copy_done(q, mp, EINVAL);
22514 		return;
22515 	}
22516 
22517 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
22518 	if (mp1 == NULL)
22519 		return;
22520 
22521 	switch (iocp->ioc_cmd) {
22522 	case TI_GETMYNAME:
22523 		error = tcp_getmyname(tcp, (void *)mp1->b_rptr, &addrlen);
22524 		break;
22525 	case TI_GETPEERNAME:
22526 		error = tcp_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
22527 		break;
22528 	}
22529 
22530 	if (error != 0) {
22531 		mi_copy_done(q, mp, error);
22532 	} else {
22533 		mp1->b_wptr += addrlen;
22534 		STRUCT_FSET(sb, len, addrlen);
22535 
22536 		/* Copy out the address */
22537 		mi_copyout(q, mp);
22538 	}
22539 }
22540 
22541 /*
22542  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
22543  * messages.
22544  */
22545 /* ARGSUSED */
22546 static void
22547 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
22548 {
22549 	conn_t 	*connp = (conn_t *)arg;
22550 	tcp_t	*tcp = connp->conn_tcp;
22551 	queue_t	*q = tcp->tcp_wq;
22552 	struct iocblk	*iocp;
22553 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22554 
22555 	ASSERT(DB_TYPE(mp) == M_IOCTL);
22556 	/*
22557 	 * Try and ASSERT the minimum possible references on the
22558 	 * conn early enough. Since we are executing on write side,
22559 	 * the connection is obviously not detached and that means
22560 	 * there is a ref each for TCP and IP. Since we are behind
22561 	 * the squeue, the minimum references needed are 3. If the
22562 	 * conn is in classifier hash list, there should be an
22563 	 * extra ref for that (we check both the possibilities).
22564 	 */
22565 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22566 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22567 
22568 	iocp = (struct iocblk *)mp->b_rptr;
22569 	switch (iocp->ioc_cmd) {
22570 	case TCP_IOC_DEFAULT_Q:
22571 		/* Wants to be the default wq. */
22572 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
22573 			iocp->ioc_error = EPERM;
22574 			iocp->ioc_count = 0;
22575 			mp->b_datap->db_type = M_IOCACK;
22576 			qreply(q, mp);
22577 			return;
22578 		}
22579 		tcp_def_q_set(tcp, mp);
22580 		return;
22581 	case _SIOCSOCKFALLBACK:
22582 		/*
22583 		 * Either sockmod is about to be popped and the socket
22584 		 * would now be treated as a plain stream, or a module
22585 		 * is about to be pushed so we could no longer use read-
22586 		 * side synchronous streams for fused loopback tcp.
22587 		 * Drain any queued data and disable direct sockfs
22588 		 * interface from now on.
22589 		 */
22590 		if (!tcp->tcp_issocket) {
22591 			DB_TYPE(mp) = M_IOCNAK;
22592 			iocp->ioc_error = EINVAL;
22593 		} else {
22594 #ifdef	_ILP32
22595 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
22596 #else
22597 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
22598 #endif
22599 			/*
22600 			 * Insert this socket into the acceptor hash.
22601 			 * We might need it for T_CONN_RES message
22602 			 */
22603 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
22604 
22605 			if (tcp->tcp_fused) {
22606 				/*
22607 				 * This is a fused loopback tcp; disable
22608 				 * read-side synchronous streams interface
22609 				 * and drain any queued data.  It is okay
22610 				 * to do this for non-synchronous streams
22611 				 * fused tcp as well.
22612 				 */
22613 				tcp_fuse_disable_pair(tcp, B_FALSE);
22614 			}
22615 			tcp->tcp_issocket = B_FALSE;
22616 			tcp->tcp_sodirect = NULL;
22617 			TCP_STAT(tcps, tcp_sock_fallback);
22618 
22619 			DB_TYPE(mp) = M_IOCACK;
22620 			iocp->ioc_error = 0;
22621 		}
22622 		iocp->ioc_count = 0;
22623 		iocp->ioc_rval = 0;
22624 		qreply(q, mp);
22625 		return;
22626 	}
22627 	CALL_IP_WPUT(connp, q, mp);
22628 }
22629 
22630 /*
22631  * This routine is called by tcp_wput() to handle all TPI requests.
22632  */
22633 /* ARGSUSED */
22634 static void
22635 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22636 {
22637 	conn_t 	*connp = (conn_t *)arg;
22638 	tcp_t	*tcp = connp->conn_tcp;
22639 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22640 	uchar_t *rptr;
22641 	t_scalar_t type;
22642 	int len;
22643 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
22644 
22645 	/*
22646 	 * Try and ASSERT the minimum possible references on the
22647 	 * conn early enough. Since we are executing on write side,
22648 	 * the connection is obviously not detached and that means
22649 	 * there is a ref each for TCP and IP. Since we are behind
22650 	 * the squeue, the minimum references needed are 3. If the
22651 	 * conn is in classifier hash list, there should be an
22652 	 * extra ref for that (we check both the possibilities).
22653 	 */
22654 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22655 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22656 
22657 	rptr = mp->b_rptr;
22658 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22659 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22660 		type = ((union T_primitives *)rptr)->type;
22661 		if (type == T_EXDATA_REQ) {
22662 			uint32_t msize = msgdsize(mp->b_cont);
22663 
22664 			len = msize - 1;
22665 			if (len < 0) {
22666 				freemsg(mp);
22667 				return;
22668 			}
22669 			/*
22670 			 * Try to force urgent data out on the wire.
22671 			 * Even if we have unsent data this will
22672 			 * at least send the urgent flag.
22673 			 * XXX does not handle more flag correctly.
22674 			 */
22675 			len += tcp->tcp_unsent;
22676 			len += tcp->tcp_snxt;
22677 			tcp->tcp_urg = len;
22678 			tcp->tcp_valid_bits |= TCP_URG_VALID;
22679 
22680 			/* Bypass tcp protocol for fused tcp loopback */
22681 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
22682 				return;
22683 		} else if (type != T_DATA_REQ) {
22684 			goto non_urgent_data;
22685 		}
22686 		/* TODO: options, flags, ... from user */
22687 		/* Set length to zero for reclamation below */
22688 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22689 		freeb(mp);
22690 		return;
22691 	} else {
22692 		if (tcp->tcp_debug) {
22693 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22694 			    "tcp_wput_proto, dropping one...");
22695 		}
22696 		freemsg(mp);
22697 		return;
22698 	}
22699 
22700 non_urgent_data:
22701 
22702 	switch ((int)tprim->type) {
22703 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22704 		/*
22705 		 * save the kssl_ent_t from the next block, and convert this
22706 		 * back to a normal bind_req.
22707 		 */
22708 		if (mp->b_cont != NULL) {
22709 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22710 
22711 			if (tcp->tcp_kssl_ent != NULL) {
22712 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22713 				    KSSL_NO_PROXY);
22714 				tcp->tcp_kssl_ent = NULL;
22715 			}
22716 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22717 			    sizeof (kssl_ent_t));
22718 			kssl_hold_ent(tcp->tcp_kssl_ent);
22719 			freemsg(mp->b_cont);
22720 			mp->b_cont = NULL;
22721 		}
22722 		tprim->type = T_BIND_REQ;
22723 
22724 	/* FALLTHROUGH */
22725 	case O_T_BIND_REQ:	/* bind request */
22726 	case T_BIND_REQ:	/* new semantics bind request */
22727 		tcp_bind(tcp, mp);
22728 		break;
22729 	case T_UNBIND_REQ:	/* unbind request */
22730 		tcp_unbind(tcp, mp);
22731 		break;
22732 	case O_T_CONN_RES:	/* old connection response XXX */
22733 	case T_CONN_RES:	/* connection response */
22734 		tcp_accept(tcp, mp);
22735 		break;
22736 	case T_CONN_REQ:	/* connection request */
22737 		tcp_connect(tcp, mp);
22738 		break;
22739 	case T_DISCON_REQ:	/* disconnect request */
22740 		tcp_disconnect(tcp, mp);
22741 		break;
22742 	case T_CAPABILITY_REQ:
22743 		tcp_capability_req(tcp, mp);	/* capability request */
22744 		break;
22745 	case T_INFO_REQ:	/* information request */
22746 		tcp_info_req(tcp, mp);
22747 		break;
22748 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22749 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr,
22750 		    &tcp_opt_obj, B_TRUE);
22751 		break;
22752 	case T_OPTMGMT_REQ:
22753 		/*
22754 		 * Note:  no support for snmpcom_req() through new
22755 		 * T_OPTMGMT_REQ. See comments in ip.c
22756 		 */
22757 		/* Only IP is allowed to return meaningful value */
22758 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22759 		    B_TRUE);
22760 		break;
22761 
22762 	case T_UNITDATA_REQ:	/* unitdata request */
22763 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22764 		break;
22765 	case T_ORDREL_REQ:	/* orderly release req */
22766 		freemsg(mp);
22767 
22768 		if (tcp->tcp_fused)
22769 			tcp_unfuse(tcp);
22770 
22771 		if (tcp_xmit_end(tcp) != 0) {
22772 			/*
22773 			 * We were crossing FINs and got a reset from
22774 			 * the other side. Just ignore it.
22775 			 */
22776 			if (tcp->tcp_debug) {
22777 				(void) strlog(TCP_MOD_ID, 0, 1,
22778 				    SL_ERROR|SL_TRACE,
22779 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22780 				    "state %s",
22781 				    tcp_display(tcp, NULL,
22782 				    DISP_ADDR_AND_PORT));
22783 			}
22784 		}
22785 		break;
22786 	case T_ADDR_REQ:
22787 		tcp_addr_req(tcp, mp);
22788 		break;
22789 	default:
22790 		if (tcp->tcp_debug) {
22791 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22792 			    "tcp_wput_proto, bogus TPI msg, type %d",
22793 			    tprim->type);
22794 		}
22795 		/*
22796 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22797 		 * to recover.
22798 		 */
22799 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22800 		break;
22801 	}
22802 }
22803 
22804 /*
22805  * The TCP write service routine should never be called...
22806  */
22807 /* ARGSUSED */
22808 static void
22809 tcp_wsrv(queue_t *q)
22810 {
22811 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22812 
22813 	TCP_STAT(tcps, tcp_wsrv_called);
22814 }
22815 
22816 /* Non overlapping byte exchanger */
22817 static void
22818 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22819 {
22820 	uchar_t	uch;
22821 
22822 	while (len-- > 0) {
22823 		uch = a[len];
22824 		a[len] = b[len];
22825 		b[len] = uch;
22826 	}
22827 }
22828 
22829 /*
22830  * Send out a control packet on the tcp connection specified.  This routine
22831  * is typically called where we need a simple ACK or RST generated.
22832  */
22833 static void
22834 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22835 {
22836 	uchar_t		*rptr;
22837 	tcph_t		*tcph;
22838 	ipha_t		*ipha = NULL;
22839 	ip6_t		*ip6h = NULL;
22840 	uint32_t	sum;
22841 	int		tcp_hdr_len;
22842 	int		tcp_ip_hdr_len;
22843 	mblk_t		*mp;
22844 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22845 
22846 	/*
22847 	 * Save sum for use in source route later.
22848 	 */
22849 	ASSERT(tcp != NULL);
22850 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22851 	tcp_hdr_len = tcp->tcp_hdr_len;
22852 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22853 
22854 	/* If a text string is passed in with the request, pass it to strlog. */
22855 	if (str != NULL && tcp->tcp_debug) {
22856 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22857 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22858 		    str, seq, ack, ctl);
22859 	}
22860 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22861 	    BPRI_MED);
22862 	if (mp == NULL) {
22863 		return;
22864 	}
22865 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22866 	mp->b_rptr = rptr;
22867 	mp->b_wptr = &rptr[tcp_hdr_len];
22868 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22869 
22870 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22871 		ipha = (ipha_t *)rptr;
22872 		ipha->ipha_length = htons(tcp_hdr_len);
22873 	} else {
22874 		ip6h = (ip6_t *)rptr;
22875 		ASSERT(tcp != NULL);
22876 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22877 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22878 	}
22879 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22880 	tcph->th_flags[0] = (uint8_t)ctl;
22881 	if (ctl & TH_RST) {
22882 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22883 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22884 		/*
22885 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22886 		 */
22887 		if (tcp->tcp_snd_ts_ok &&
22888 		    tcp->tcp_state > TCPS_SYN_SENT) {
22889 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22890 			*(mp->b_wptr) = TCPOPT_EOL;
22891 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22892 				ipha->ipha_length = htons(tcp_hdr_len -
22893 				    TCPOPT_REAL_TS_LEN);
22894 			} else {
22895 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22896 				    TCPOPT_REAL_TS_LEN);
22897 			}
22898 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22899 			sum -= TCPOPT_REAL_TS_LEN;
22900 		}
22901 	}
22902 	if (ctl & TH_ACK) {
22903 		if (tcp->tcp_snd_ts_ok) {
22904 			U32_TO_BE32(lbolt,
22905 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22906 			U32_TO_BE32(tcp->tcp_ts_recent,
22907 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22908 		}
22909 
22910 		/* Update the latest receive window size in TCP header. */
22911 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22912 		    tcph->th_win);
22913 		tcp->tcp_rack = ack;
22914 		tcp->tcp_rack_cnt = 0;
22915 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22916 	}
22917 	BUMP_LOCAL(tcp->tcp_obsegs);
22918 	U32_TO_BE32(seq, tcph->th_seq);
22919 	U32_TO_BE32(ack, tcph->th_ack);
22920 	/*
22921 	 * Include the adjustment for a source route if any.
22922 	 */
22923 	sum = (sum >> 16) + (sum & 0xFFFF);
22924 	U16_TO_BE16(sum, tcph->th_sum);
22925 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22926 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22927 }
22928 
22929 /*
22930  * If this routine returns B_TRUE, TCP can generate a RST in response
22931  * to a segment.  If it returns B_FALSE, TCP should not respond.
22932  */
22933 static boolean_t
22934 tcp_send_rst_chk(tcp_stack_t *tcps)
22935 {
22936 	clock_t	now;
22937 
22938 	/*
22939 	 * TCP needs to protect itself from generating too many RSTs.
22940 	 * This can be a DoS attack by sending us random segments
22941 	 * soliciting RSTs.
22942 	 *
22943 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22944 	 * in each 1 second interval.  In this way, TCP still generate
22945 	 * RSTs in normal cases but when under attack, the impact is
22946 	 * limited.
22947 	 */
22948 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22949 		now = lbolt;
22950 		/* lbolt can wrap around. */
22951 		if ((tcps->tcps_last_rst_intrvl > now) ||
22952 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22953 		    1*SECONDS)) {
22954 			tcps->tcps_last_rst_intrvl = now;
22955 			tcps->tcps_rst_cnt = 1;
22956 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22957 			return (B_FALSE);
22958 		}
22959 	}
22960 	return (B_TRUE);
22961 }
22962 
22963 /*
22964  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22965  */
22966 static void
22967 tcp_ip_ire_mark_advice(tcp_t *tcp)
22968 {
22969 	mblk_t *mp;
22970 	ipic_t *ipic;
22971 
22972 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22973 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22974 		    &ipic);
22975 	} else {
22976 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22977 		    &ipic);
22978 	}
22979 	if (mp == NULL)
22980 		return;
22981 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22982 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22983 }
22984 
22985 /*
22986  * Return an IP advice ioctl mblk and set ipic to be the pointer
22987  * to the advice structure.
22988  */
22989 static mblk_t *
22990 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22991 {
22992 	struct iocblk *ioc;
22993 	mblk_t *mp, *mp1;
22994 
22995 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22996 	if (mp == NULL)
22997 		return (NULL);
22998 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22999 	*ipic = (ipic_t *)mp->b_rptr;
23000 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
23001 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
23002 
23003 	bcopy(addr, *ipic + 1, addr_len);
23004 
23005 	(*ipic)->ipic_addr_length = addr_len;
23006 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
23007 
23008 	mp1 = mkiocb(IP_IOCTL);
23009 	if (mp1 == NULL) {
23010 		freemsg(mp);
23011 		return (NULL);
23012 	}
23013 	mp1->b_cont = mp;
23014 	ioc = (struct iocblk *)mp1->b_rptr;
23015 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
23016 
23017 	return (mp1);
23018 }
23019 
23020 /*
23021  * Generate a reset based on an inbound packet, connp is set by caller
23022  * when RST is in response to an unexpected inbound packet for which
23023  * there is active tcp state in the system.
23024  *
23025  * IPSEC NOTE : Try to send the reply with the same protection as it came
23026  * in.  We still have the ipsec_mp that the packet was attached to. Thus
23027  * the packet will go out at the same level of protection as it came in by
23028  * converting the IPSEC_IN to IPSEC_OUT.
23029  */
23030 static void
23031 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
23032     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
23033     tcp_stack_t *tcps, conn_t *connp)
23034 {
23035 	ipha_t		*ipha = NULL;
23036 	ip6_t		*ip6h = NULL;
23037 	ushort_t	len;
23038 	tcph_t		*tcph;
23039 	int		i;
23040 	mblk_t		*ipsec_mp;
23041 	boolean_t	mctl_present;
23042 	ipic_t		*ipic;
23043 	ipaddr_t	v4addr;
23044 	in6_addr_t	v6addr;
23045 	int		addr_len;
23046 	void		*addr;
23047 	queue_t		*q = tcps->tcps_g_q;
23048 	tcp_t		*tcp;
23049 	cred_t		*cr;
23050 	mblk_t		*nmp;
23051 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
23052 
23053 	if (tcps->tcps_g_q == NULL) {
23054 		/*
23055 		 * For non-zero stackids the default queue isn't created
23056 		 * until the first open, thus there can be a need to send
23057 		 * a reset before then. But we can't do that, hence we just
23058 		 * drop the packet. Later during boot, when the default queue
23059 		 * has been setup, a retransmitted packet from the peer
23060 		 * will result in a reset.
23061 		 */
23062 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
23063 		    GLOBAL_NETSTACKID);
23064 		freemsg(mp);
23065 		return;
23066 	}
23067 
23068 	if (connp != NULL)
23069 		tcp = connp->conn_tcp;
23070 	else
23071 		tcp = Q_TO_TCP(q);
23072 
23073 	if (!tcp_send_rst_chk(tcps)) {
23074 		tcps->tcps_rst_unsent++;
23075 		freemsg(mp);
23076 		return;
23077 	}
23078 
23079 	if (mp->b_datap->db_type == M_CTL) {
23080 		ipsec_mp = mp;
23081 		mp = mp->b_cont;
23082 		mctl_present = B_TRUE;
23083 	} else {
23084 		ipsec_mp = mp;
23085 		mctl_present = B_FALSE;
23086 	}
23087 
23088 	if (str && q && tcps->tcps_dbg) {
23089 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
23090 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
23091 		    "flags 0x%x",
23092 		    str, seq, ack, ctl);
23093 	}
23094 	if (mp->b_datap->db_ref != 1) {
23095 		mblk_t *mp1 = copyb(mp);
23096 		freemsg(mp);
23097 		mp = mp1;
23098 		if (!mp) {
23099 			if (mctl_present)
23100 				freeb(ipsec_mp);
23101 			return;
23102 		} else {
23103 			if (mctl_present) {
23104 				ipsec_mp->b_cont = mp;
23105 			} else {
23106 				ipsec_mp = mp;
23107 			}
23108 		}
23109 	} else if (mp->b_cont) {
23110 		freemsg(mp->b_cont);
23111 		mp->b_cont = NULL;
23112 	}
23113 	/*
23114 	 * We skip reversing source route here.
23115 	 * (for now we replace all IP options with EOL)
23116 	 */
23117 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23118 		ipha = (ipha_t *)mp->b_rptr;
23119 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
23120 			mp->b_rptr[i] = IPOPT_EOL;
23121 		/*
23122 		 * Make sure that src address isn't flagrantly invalid.
23123 		 * Not all broadcast address checking for the src address
23124 		 * is possible, since we don't know the netmask of the src
23125 		 * addr.  No check for destination address is done, since
23126 		 * IP will not pass up a packet with a broadcast dest
23127 		 * address to TCP.  Similar checks are done below for IPv6.
23128 		 */
23129 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
23130 		    CLASSD(ipha->ipha_src)) {
23131 			freemsg(ipsec_mp);
23132 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
23133 			return;
23134 		}
23135 	} else {
23136 		ip6h = (ip6_t *)mp->b_rptr;
23137 
23138 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
23139 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
23140 			freemsg(ipsec_mp);
23141 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
23142 			return;
23143 		}
23144 
23145 		/* Remove any extension headers assuming partial overlay */
23146 		if (ip_hdr_len > IPV6_HDR_LEN) {
23147 			uint8_t *to;
23148 
23149 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
23150 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
23151 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
23152 			ip_hdr_len = IPV6_HDR_LEN;
23153 			ip6h = (ip6_t *)mp->b_rptr;
23154 			ip6h->ip6_nxt = IPPROTO_TCP;
23155 		}
23156 	}
23157 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
23158 	if (tcph->th_flags[0] & TH_RST) {
23159 		freemsg(ipsec_mp);
23160 		return;
23161 	}
23162 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
23163 	len = ip_hdr_len + sizeof (tcph_t);
23164 	mp->b_wptr = &mp->b_rptr[len];
23165 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23166 		ipha->ipha_length = htons(len);
23167 		/* Swap addresses */
23168 		v4addr = ipha->ipha_src;
23169 		ipha->ipha_src = ipha->ipha_dst;
23170 		ipha->ipha_dst = v4addr;
23171 		ipha->ipha_ident = 0;
23172 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
23173 		addr_len = IP_ADDR_LEN;
23174 		addr = &v4addr;
23175 	} else {
23176 		/* No ip6i_t in this case */
23177 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
23178 		/* Swap addresses */
23179 		v6addr = ip6h->ip6_src;
23180 		ip6h->ip6_src = ip6h->ip6_dst;
23181 		ip6h->ip6_dst = v6addr;
23182 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
23183 		addr_len = IPV6_ADDR_LEN;
23184 		addr = &v6addr;
23185 	}
23186 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
23187 	U32_TO_BE32(ack, tcph->th_ack);
23188 	U32_TO_BE32(seq, tcph->th_seq);
23189 	U16_TO_BE16(0, tcph->th_win);
23190 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
23191 	tcph->th_flags[0] = (uint8_t)ctl;
23192 	if (ctl & TH_RST) {
23193 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
23194 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23195 	}
23196 
23197 	/* IP trusts us to set up labels when required. */
23198 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
23199 	    crgetlabel(cr) != NULL) {
23200 		int err;
23201 
23202 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
23203 			err = tsol_check_label(cr, &mp,
23204 			    tcp->tcp_connp->conn_mac_exempt,
23205 			    tcps->tcps_netstack->netstack_ip);
23206 		else
23207 			err = tsol_check_label_v6(cr, &mp,
23208 			    tcp->tcp_connp->conn_mac_exempt,
23209 			    tcps->tcps_netstack->netstack_ip);
23210 		if (mctl_present)
23211 			ipsec_mp->b_cont = mp;
23212 		else
23213 			ipsec_mp = mp;
23214 		if (err != 0) {
23215 			freemsg(ipsec_mp);
23216 			return;
23217 		}
23218 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23219 			ipha = (ipha_t *)mp->b_rptr;
23220 		} else {
23221 			ip6h = (ip6_t *)mp->b_rptr;
23222 		}
23223 	}
23224 
23225 	if (mctl_present) {
23226 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23227 
23228 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23229 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
23230 			return;
23231 		}
23232 	}
23233 	if (zoneid == ALL_ZONES)
23234 		zoneid = GLOBAL_ZONEID;
23235 
23236 	/* Add the zoneid so ip_output routes it properly */
23237 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
23238 		freemsg(ipsec_mp);
23239 		return;
23240 	}
23241 	ipsec_mp = nmp;
23242 
23243 	/*
23244 	 * NOTE:  one might consider tracing a TCP packet here, but
23245 	 * this function has no active TCP state and no tcp structure
23246 	 * that has a trace buffer.  If we traced here, we would have
23247 	 * to keep a local trace buffer in tcp_record_trace().
23248 	 *
23249 	 * TSol note: The mblk that contains the incoming packet was
23250 	 * reused by tcp_xmit_listener_reset, so it already contains
23251 	 * the right credentials and we don't need to call mblk_setcred.
23252 	 * Also the conn's cred is not right since it is associated
23253 	 * with tcps_g_q.
23254 	 */
23255 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
23256 
23257 	/*
23258 	 * Tell IP to mark the IRE used for this destination temporary.
23259 	 * This way, we can limit our exposure to DoS attack because IP
23260 	 * creates an IRE for each destination.  If there are too many,
23261 	 * the time to do any routing lookup will be extremely long.  And
23262 	 * the lookup can be in interrupt context.
23263 	 *
23264 	 * Note that in normal circumstances, this marking should not
23265 	 * affect anything.  It would be nice if only 1 message is
23266 	 * needed to inform IP that the IRE created for this RST should
23267 	 * not be added to the cache table.  But there is currently
23268 	 * not such communication mechanism between TCP and IP.  So
23269 	 * the best we can do now is to send the advice ioctl to IP
23270 	 * to mark the IRE temporary.
23271 	 */
23272 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
23273 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
23274 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23275 	}
23276 }
23277 
23278 /*
23279  * Initiate closedown sequence on an active connection.  (May be called as
23280  * writer.)  Return value zero for OK return, non-zero for error return.
23281  */
23282 static int
23283 tcp_xmit_end(tcp_t *tcp)
23284 {
23285 	ipic_t	*ipic;
23286 	mblk_t	*mp;
23287 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23288 
23289 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
23290 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
23291 		/*
23292 		 * Invalid state, only states TCPS_SYN_RCVD,
23293 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
23294 		 */
23295 		return (-1);
23296 	}
23297 
23298 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
23299 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
23300 	/*
23301 	 * If there is nothing more unsent, send the FIN now.
23302 	 * Otherwise, it will go out with the last segment.
23303 	 */
23304 	if (tcp->tcp_unsent == 0) {
23305 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
23306 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
23307 
23308 		if (mp) {
23309 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
23310 			tcp_send_data(tcp, tcp->tcp_wq, mp);
23311 		} else {
23312 			/*
23313 			 * Couldn't allocate msg.  Pretend we got it out.
23314 			 * Wait for rexmit timeout.
23315 			 */
23316 			tcp->tcp_snxt = tcp->tcp_fss + 1;
23317 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23318 		}
23319 
23320 		/*
23321 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
23322 		 * changed.
23323 		 */
23324 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
23325 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23326 		}
23327 	} else {
23328 		/*
23329 		 * If tcp->tcp_cork is set, then the data will not get sent,
23330 		 * so we have to check that and unset it first.
23331 		 */
23332 		if (tcp->tcp_cork)
23333 			tcp->tcp_cork = B_FALSE;
23334 		tcp_wput_data(tcp, NULL, B_FALSE);
23335 	}
23336 
23337 	/*
23338 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
23339 	 * is 0, don't update the cache.
23340 	 */
23341 	if (tcps->tcps_rtt_updates == 0 ||
23342 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
23343 		return (0);
23344 
23345 	/*
23346 	 * NOTE: should not update if source routes i.e. if tcp_remote if
23347 	 * different from the destination.
23348 	 */
23349 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23350 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
23351 			return (0);
23352 		}
23353 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
23354 		    &ipic);
23355 	} else {
23356 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
23357 		    &tcp->tcp_ip6h->ip6_dst))) {
23358 			return (0);
23359 		}
23360 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
23361 		    &ipic);
23362 	}
23363 
23364 	/* Record route attributes in the IRE for use by future connections. */
23365 	if (mp == NULL)
23366 		return (0);
23367 
23368 	/*
23369 	 * We do not have a good algorithm to update ssthresh at this time.
23370 	 * So don't do any update.
23371 	 */
23372 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
23373 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
23374 
23375 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23376 	return (0);
23377 }
23378 
23379 /*
23380  * Generate a "no listener here" RST in response to an "unknown" segment.
23381  * connp is set by caller when RST is in response to an unexpected
23382  * inbound packet for which there is active tcp state in the system.
23383  * Note that we are reusing the incoming mp to construct the outgoing RST.
23384  */
23385 void
23386 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
23387     tcp_stack_t *tcps, conn_t *connp)
23388 {
23389 	uchar_t		*rptr;
23390 	uint32_t	seg_len;
23391 	tcph_t		*tcph;
23392 	uint32_t	seg_seq;
23393 	uint32_t	seg_ack;
23394 	uint_t		flags;
23395 	mblk_t		*ipsec_mp;
23396 	ipha_t 		*ipha;
23397 	ip6_t 		*ip6h;
23398 	boolean_t	mctl_present = B_FALSE;
23399 	boolean_t	check = B_TRUE;
23400 	boolean_t	policy_present;
23401 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
23402 
23403 	TCP_STAT(tcps, tcp_no_listener);
23404 
23405 	ipsec_mp = mp;
23406 
23407 	if (mp->b_datap->db_type == M_CTL) {
23408 		ipsec_in_t *ii;
23409 
23410 		mctl_present = B_TRUE;
23411 		mp = mp->b_cont;
23412 
23413 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23414 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23415 		if (ii->ipsec_in_dont_check) {
23416 			check = B_FALSE;
23417 			if (!ii->ipsec_in_secure) {
23418 				freeb(ipsec_mp);
23419 				mctl_present = B_FALSE;
23420 				ipsec_mp = mp;
23421 			}
23422 		}
23423 	}
23424 
23425 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23426 		policy_present = ipss->ipsec_inbound_v4_policy_present;
23427 		ipha = (ipha_t *)mp->b_rptr;
23428 		ip6h = NULL;
23429 	} else {
23430 		policy_present = ipss->ipsec_inbound_v6_policy_present;
23431 		ipha = NULL;
23432 		ip6h = (ip6_t *)mp->b_rptr;
23433 	}
23434 
23435 	if (check && policy_present) {
23436 		/*
23437 		 * The conn_t parameter is NULL because we already know
23438 		 * nobody's home.
23439 		 */
23440 		ipsec_mp = ipsec_check_global_policy(
23441 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
23442 		    tcps->tcps_netstack);
23443 		if (ipsec_mp == NULL)
23444 			return;
23445 	}
23446 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
23447 		DTRACE_PROBE2(
23448 		    tx__ip__log__error__nolistener__tcp,
23449 		    char *, "Could not reply with RST to mp(1)",
23450 		    mblk_t *, mp);
23451 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
23452 		freemsg(ipsec_mp);
23453 		return;
23454 	}
23455 
23456 	rptr = mp->b_rptr;
23457 
23458 	tcph = (tcph_t *)&rptr[ip_hdr_len];
23459 	seg_seq = BE32_TO_U32(tcph->th_seq);
23460 	seg_ack = BE32_TO_U32(tcph->th_ack);
23461 	flags = tcph->th_flags[0];
23462 
23463 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
23464 	if (flags & TH_RST) {
23465 		freemsg(ipsec_mp);
23466 	} else if (flags & TH_ACK) {
23467 		tcp_xmit_early_reset("no tcp, reset",
23468 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
23469 		    connp);
23470 	} else {
23471 		if (flags & TH_SYN) {
23472 			seg_len++;
23473 		} else {
23474 			/*
23475 			 * Here we violate the RFC.  Note that a normal
23476 			 * TCP will never send a segment without the ACK
23477 			 * flag, except for RST or SYN segment.  This
23478 			 * segment is neither.  Just drop it on the
23479 			 * floor.
23480 			 */
23481 			freemsg(ipsec_mp);
23482 			tcps->tcps_rst_unsent++;
23483 			return;
23484 		}
23485 
23486 		tcp_xmit_early_reset("no tcp, reset/ack",
23487 		    ipsec_mp, 0, seg_seq + seg_len,
23488 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
23489 	}
23490 }
23491 
23492 /*
23493  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
23494  * ip and tcp header ready to pass down to IP.  If the mp passed in is
23495  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
23496  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
23497  * otherwise it will dup partial mblks.)
23498  * Otherwise, an appropriate ACK packet will be generated.  This
23499  * routine is not usually called to send new data for the first time.  It
23500  * is mostly called out of the timer for retransmits, and to generate ACKs.
23501  *
23502  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
23503  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
23504  * of the original mblk chain will be returned in *offset and *end_mp.
23505  */
23506 mblk_t *
23507 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
23508     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
23509     boolean_t rexmit)
23510 {
23511 	int	data_length;
23512 	int32_t	off = 0;
23513 	uint_t	flags;
23514 	mblk_t	*mp1;
23515 	mblk_t	*mp2;
23516 	uchar_t	*rptr;
23517 	tcph_t	*tcph;
23518 	int32_t	num_sack_blk = 0;
23519 	int32_t	sack_opt_len = 0;
23520 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23521 
23522 	/* Allocate for our maximum TCP header + link-level */
23523 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
23524 	    tcps->tcps_wroff_xtra, BPRI_MED);
23525 	if (!mp1)
23526 		return (NULL);
23527 	data_length = 0;
23528 
23529 	/*
23530 	 * Note that tcp_mss has been adjusted to take into account the
23531 	 * timestamp option if applicable.  Because SACK options do not
23532 	 * appear in every TCP segments and they are of variable lengths,
23533 	 * they cannot be included in tcp_mss.  Thus we need to calculate
23534 	 * the actual segment length when we need to send a segment which
23535 	 * includes SACK options.
23536 	 */
23537 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23538 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23539 		    tcp->tcp_num_sack_blk);
23540 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23541 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23542 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
23543 			max_to_send -= sack_opt_len;
23544 	}
23545 
23546 	if (offset != NULL) {
23547 		off = *offset;
23548 		/* We use offset as an indicator that end_mp is not NULL. */
23549 		*end_mp = NULL;
23550 	}
23551 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
23552 		/* This could be faster with cooperation from downstream */
23553 		if (mp2 != mp1 && !sendall &&
23554 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
23555 		    max_to_send)
23556 			/*
23557 			 * Don't send the next mblk since the whole mblk
23558 			 * does not fit.
23559 			 */
23560 			break;
23561 		mp2->b_cont = dupb(mp);
23562 		mp2 = mp2->b_cont;
23563 		if (!mp2) {
23564 			freemsg(mp1);
23565 			return (NULL);
23566 		}
23567 		mp2->b_rptr += off;
23568 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
23569 		    (uintptr_t)INT_MAX);
23570 
23571 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
23572 		if (data_length > max_to_send) {
23573 			mp2->b_wptr -= data_length - max_to_send;
23574 			data_length = max_to_send;
23575 			off = mp2->b_wptr - mp->b_rptr;
23576 			break;
23577 		} else {
23578 			off = 0;
23579 		}
23580 	}
23581 	if (offset != NULL) {
23582 		*offset = off;
23583 		*end_mp = mp;
23584 	}
23585 	if (seg_len != NULL) {
23586 		*seg_len = data_length;
23587 	}
23588 
23589 	/* Update the latest receive window size in TCP header. */
23590 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23591 	    tcp->tcp_tcph->th_win);
23592 
23593 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23594 	mp1->b_rptr = rptr;
23595 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
23596 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23597 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23598 	U32_TO_ABE32(seq, tcph->th_seq);
23599 
23600 	/*
23601 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
23602 	 * that this function was called from tcp_wput_data. Thus, when called
23603 	 * to retransmit data the setting of the PUSH bit may appear some
23604 	 * what random in that it might get set when it should not. This
23605 	 * should not pose any performance issues.
23606 	 */
23607 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
23608 	    tcp->tcp_unsent == data_length)) {
23609 		flags = TH_ACK | TH_PUSH;
23610 	} else {
23611 		flags = TH_ACK;
23612 	}
23613 
23614 	if (tcp->tcp_ecn_ok) {
23615 		if (tcp->tcp_ecn_echo_on)
23616 			flags |= TH_ECE;
23617 
23618 		/*
23619 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
23620 		 * There is no TCP flow control for non-data segments, and
23621 		 * only data segment is transmitted reliably.
23622 		 */
23623 		if (data_length > 0 && !rexmit) {
23624 			SET_ECT(tcp, rptr);
23625 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23626 				flags |= TH_CWR;
23627 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23628 			}
23629 		}
23630 	}
23631 
23632 	if (tcp->tcp_valid_bits) {
23633 		uint32_t u1;
23634 
23635 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23636 		    seq == tcp->tcp_iss) {
23637 			uchar_t	*wptr;
23638 
23639 			/*
23640 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23641 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23642 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23643 			 * our SYN is not ack'ed but the app closes this
23644 			 * TCP connection.
23645 			 */
23646 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23647 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23648 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23649 
23650 			/*
23651 			 * Tack on the MSS option.  It is always needed
23652 			 * for both active and passive open.
23653 			 *
23654 			 * MSS option value should be interface MTU - MIN
23655 			 * TCP/IP header according to RFC 793 as it means
23656 			 * the maximum segment size TCP can receive.  But
23657 			 * to get around some broken middle boxes/end hosts
23658 			 * out there, we allow the option value to be the
23659 			 * same as the MSS option size on the peer side.
23660 			 * In this way, the other side will not send
23661 			 * anything larger than they can receive.
23662 			 *
23663 			 * Note that for SYN_SENT state, the ndd param
23664 			 * tcp_use_smss_as_mss_opt has no effect as we
23665 			 * don't know the peer's MSS option value. So
23666 			 * the only case we need to take care of is in
23667 			 * SYN_RCVD state, which is done later.
23668 			 */
23669 			wptr = mp1->b_wptr;
23670 			wptr[0] = TCPOPT_MAXSEG;
23671 			wptr[1] = TCPOPT_MAXSEG_LEN;
23672 			wptr += 2;
23673 			u1 = tcp->tcp_if_mtu -
23674 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23675 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23676 			    TCP_MIN_HEADER_LENGTH;
23677 			U16_TO_BE16(u1, wptr);
23678 			mp1->b_wptr = wptr + 2;
23679 			/* Update the offset to cover the additional word */
23680 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23681 
23682 			/*
23683 			 * Note that the following way of filling in
23684 			 * TCP options are not optimal.  Some NOPs can
23685 			 * be saved.  But there is no need at this time
23686 			 * to optimize it.  When it is needed, we will
23687 			 * do it.
23688 			 */
23689 			switch (tcp->tcp_state) {
23690 			case TCPS_SYN_SENT:
23691 				flags = TH_SYN;
23692 
23693 				if (tcp->tcp_snd_ts_ok) {
23694 					uint32_t llbolt = (uint32_t)lbolt;
23695 
23696 					wptr = mp1->b_wptr;
23697 					wptr[0] = TCPOPT_NOP;
23698 					wptr[1] = TCPOPT_NOP;
23699 					wptr[2] = TCPOPT_TSTAMP;
23700 					wptr[3] = TCPOPT_TSTAMP_LEN;
23701 					wptr += 4;
23702 					U32_TO_BE32(llbolt, wptr);
23703 					wptr += 4;
23704 					ASSERT(tcp->tcp_ts_recent == 0);
23705 					U32_TO_BE32(0L, wptr);
23706 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23707 					tcph->th_offset_and_rsrvd[0] +=
23708 					    (3 << 4);
23709 				}
23710 
23711 				/*
23712 				 * Set up all the bits to tell other side
23713 				 * we are ECN capable.
23714 				 */
23715 				if (tcp->tcp_ecn_ok) {
23716 					flags |= (TH_ECE | TH_CWR);
23717 				}
23718 				break;
23719 			case TCPS_SYN_RCVD:
23720 				flags |= TH_SYN;
23721 
23722 				/*
23723 				 * Reset the MSS option value to be SMSS
23724 				 * We should probably add back the bytes
23725 				 * for timestamp option and IPsec.  We
23726 				 * don't do that as this is a workaround
23727 				 * for broken middle boxes/end hosts, it
23728 				 * is better for us to be more cautious.
23729 				 * They may not take these things into
23730 				 * account in their SMSS calculation.  Thus
23731 				 * the peer's calculated SMSS may be smaller
23732 				 * than what it can be.  This should be OK.
23733 				 */
23734 				if (tcps->tcps_use_smss_as_mss_opt) {
23735 					u1 = tcp->tcp_mss;
23736 					U16_TO_BE16(u1, wptr);
23737 				}
23738 
23739 				/*
23740 				 * If the other side is ECN capable, reply
23741 				 * that we are also ECN capable.
23742 				 */
23743 				if (tcp->tcp_ecn_ok)
23744 					flags |= TH_ECE;
23745 				break;
23746 			default:
23747 				/*
23748 				 * The above ASSERT() makes sure that this
23749 				 * must be FIN-WAIT-1 state.  Our SYN has
23750 				 * not been ack'ed so retransmit it.
23751 				 */
23752 				flags |= TH_SYN;
23753 				break;
23754 			}
23755 
23756 			if (tcp->tcp_snd_ws_ok) {
23757 				wptr = mp1->b_wptr;
23758 				wptr[0] =  TCPOPT_NOP;
23759 				wptr[1] =  TCPOPT_WSCALE;
23760 				wptr[2] =  TCPOPT_WS_LEN;
23761 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23762 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23763 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23764 			}
23765 
23766 			if (tcp->tcp_snd_sack_ok) {
23767 				wptr = mp1->b_wptr;
23768 				wptr[0] = TCPOPT_NOP;
23769 				wptr[1] = TCPOPT_NOP;
23770 				wptr[2] = TCPOPT_SACK_PERMITTED;
23771 				wptr[3] = TCPOPT_SACK_OK_LEN;
23772 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23773 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23774 			}
23775 
23776 			/* allocb() of adequate mblk assures space */
23777 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23778 			    (uintptr_t)INT_MAX);
23779 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23780 			/*
23781 			 * Get IP set to checksum on our behalf
23782 			 * Include the adjustment for a source route if any.
23783 			 */
23784 			u1 += tcp->tcp_sum;
23785 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23786 			U16_TO_BE16(u1, tcph->th_sum);
23787 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23788 		}
23789 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23790 		    (seq + data_length) == tcp->tcp_fss) {
23791 			if (!tcp->tcp_fin_acked) {
23792 				flags |= TH_FIN;
23793 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23794 			}
23795 			if (!tcp->tcp_fin_sent) {
23796 				tcp->tcp_fin_sent = B_TRUE;
23797 				switch (tcp->tcp_state) {
23798 				case TCPS_SYN_RCVD:
23799 				case TCPS_ESTABLISHED:
23800 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23801 					break;
23802 				case TCPS_CLOSE_WAIT:
23803 					tcp->tcp_state = TCPS_LAST_ACK;
23804 					break;
23805 				}
23806 				if (tcp->tcp_suna == tcp->tcp_snxt)
23807 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23808 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23809 			}
23810 		}
23811 		/*
23812 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23813 		 * is smaller than seq, u1 will become a very huge value.
23814 		 * So the comparison will fail.  Also note that tcp_urp
23815 		 * should be positive, see RFC 793 page 17.
23816 		 */
23817 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23818 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23819 		    u1 < (uint32_t)(64 * 1024)) {
23820 			flags |= TH_URG;
23821 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23822 			U32_TO_ABE16(u1, tcph->th_urp);
23823 		}
23824 	}
23825 	tcph->th_flags[0] = (uchar_t)flags;
23826 	tcp->tcp_rack = tcp->tcp_rnxt;
23827 	tcp->tcp_rack_cnt = 0;
23828 
23829 	if (tcp->tcp_snd_ts_ok) {
23830 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23831 			uint32_t llbolt = (uint32_t)lbolt;
23832 
23833 			U32_TO_BE32(llbolt,
23834 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23835 			U32_TO_BE32(tcp->tcp_ts_recent,
23836 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23837 		}
23838 	}
23839 
23840 	if (num_sack_blk > 0) {
23841 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23842 		sack_blk_t *tmp;
23843 		int32_t	i;
23844 
23845 		wptr[0] = TCPOPT_NOP;
23846 		wptr[1] = TCPOPT_NOP;
23847 		wptr[2] = TCPOPT_SACK;
23848 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23849 		    sizeof (sack_blk_t);
23850 		wptr += TCPOPT_REAL_SACK_LEN;
23851 
23852 		tmp = tcp->tcp_sack_list;
23853 		for (i = 0; i < num_sack_blk; i++) {
23854 			U32_TO_BE32(tmp[i].begin, wptr);
23855 			wptr += sizeof (tcp_seq);
23856 			U32_TO_BE32(tmp[i].end, wptr);
23857 			wptr += sizeof (tcp_seq);
23858 		}
23859 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23860 	}
23861 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23862 	data_length += (int)(mp1->b_wptr - rptr);
23863 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23864 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23865 	} else {
23866 		ip6_t *ip6 = (ip6_t *)(rptr +
23867 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23868 		    sizeof (ip6i_t) : 0));
23869 
23870 		ip6->ip6_plen = htons(data_length -
23871 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23872 	}
23873 
23874 	/*
23875 	 * Prime pump for IP
23876 	 * Include the adjustment for a source route if any.
23877 	 */
23878 	data_length -= tcp->tcp_ip_hdr_len;
23879 	data_length += tcp->tcp_sum;
23880 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23881 	U16_TO_ABE16(data_length, tcph->th_sum);
23882 	if (tcp->tcp_ip_forward_progress) {
23883 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23884 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23885 		tcp->tcp_ip_forward_progress = B_FALSE;
23886 	}
23887 	return (mp1);
23888 }
23889 
23890 /* This function handles the push timeout. */
23891 void
23892 tcp_push_timer(void *arg)
23893 {
23894 	conn_t	*connp = (conn_t *)arg;
23895 	tcp_t *tcp = connp->conn_tcp;
23896 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23897 	uint_t		flags;
23898 	sodirect_t	*sodp;
23899 
23900 	TCP_DBGSTAT(tcps, tcp_push_timer_cnt);
23901 
23902 	ASSERT(tcp->tcp_listener == NULL);
23903 
23904 	/*
23905 	 * We need to plug synchronous streams during our drain to prevent
23906 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23907 	 */
23908 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23909 	tcp->tcp_push_tid = 0;
23910 
23911 	SOD_PTR_ENTER(tcp, sodp);
23912 	if (sodp != NULL) {
23913 		flags = tcp_rcv_sod_wakeup(tcp, sodp);
23914 		/* sod_wakeup() does the mutex_exit() */
23915 	} else if (tcp->tcp_rcv_list != NULL) {
23916 		flags = tcp_rcv_drain(tcp->tcp_rq, tcp);
23917 	}
23918 	if (flags == TH_ACK_NEEDED)
23919 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23920 
23921 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23922 }
23923 
23924 /*
23925  * This function handles delayed ACK timeout.
23926  */
23927 static void
23928 tcp_ack_timer(void *arg)
23929 {
23930 	conn_t	*connp = (conn_t *)arg;
23931 	tcp_t *tcp = connp->conn_tcp;
23932 	mblk_t *mp;
23933 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23934 
23935 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23936 
23937 	tcp->tcp_ack_tid = 0;
23938 
23939 	if (tcp->tcp_fused)
23940 		return;
23941 
23942 	/*
23943 	 * Do not send ACK if there is no outstanding unack'ed data.
23944 	 */
23945 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23946 		return;
23947 	}
23948 
23949 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23950 		/*
23951 		 * Make sure we don't allow deferred ACKs to result in
23952 		 * timer-based ACKing.  If we have held off an ACK
23953 		 * when there was more than an mss here, and the timer
23954 		 * goes off, we have to worry about the possibility
23955 		 * that the sender isn't doing slow-start, or is out
23956 		 * of step with us for some other reason.  We fall
23957 		 * permanently back in the direction of
23958 		 * ACK-every-other-packet as suggested in RFC 1122.
23959 		 */
23960 		if (tcp->tcp_rack_abs_max > 2)
23961 			tcp->tcp_rack_abs_max--;
23962 		tcp->tcp_rack_cur_max = 2;
23963 	}
23964 	mp = tcp_ack_mp(tcp);
23965 
23966 	if (mp != NULL) {
23967 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
23968 		BUMP_LOCAL(tcp->tcp_obsegs);
23969 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23970 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23971 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23972 	}
23973 }
23974 
23975 
23976 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23977 static mblk_t *
23978 tcp_ack_mp(tcp_t *tcp)
23979 {
23980 	uint32_t	seq_no;
23981 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23982 
23983 	/*
23984 	 * There are a few cases to be considered while setting the sequence no.
23985 	 * Essentially, we can come here while processing an unacceptable pkt
23986 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23987 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23988 	 * If we are here for a zero window probe, stick with suna. In all
23989 	 * other cases, we check if suna + swnd encompasses snxt and set
23990 	 * the sequence number to snxt, if so. If snxt falls outside the
23991 	 * window (the receiver probably shrunk its window), we will go with
23992 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23993 	 * receiver.
23994 	 */
23995 	if (tcp->tcp_zero_win_probe) {
23996 		seq_no = tcp->tcp_suna;
23997 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23998 		ASSERT(tcp->tcp_swnd == 0);
23999 		seq_no = tcp->tcp_snxt;
24000 	} else {
24001 		seq_no = SEQ_GT(tcp->tcp_snxt,
24002 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
24003 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
24004 	}
24005 
24006 	if (tcp->tcp_valid_bits) {
24007 		/*
24008 		 * For the complex case where we have to send some
24009 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
24010 		 */
24011 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
24012 		    NULL, B_FALSE));
24013 	} else {
24014 		/* Generate a simple ACK */
24015 		int	data_length;
24016 		uchar_t	*rptr;
24017 		tcph_t	*tcph;
24018 		mblk_t	*mp1;
24019 		int32_t	tcp_hdr_len;
24020 		int32_t	tcp_tcp_hdr_len;
24021 		int32_t	num_sack_blk = 0;
24022 		int32_t sack_opt_len;
24023 
24024 		/*
24025 		 * Allocate space for TCP + IP headers
24026 		 * and link-level header
24027 		 */
24028 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
24029 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
24030 			    tcp->tcp_num_sack_blk);
24031 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
24032 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
24033 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
24034 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
24035 		} else {
24036 			tcp_hdr_len = tcp->tcp_hdr_len;
24037 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
24038 		}
24039 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
24040 		if (!mp1)
24041 			return (NULL);
24042 
24043 		/* Update the latest receive window size in TCP header. */
24044 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
24045 		    tcp->tcp_tcph->th_win);
24046 		/* copy in prototype TCP + IP header */
24047 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
24048 		mp1->b_rptr = rptr;
24049 		mp1->b_wptr = rptr + tcp_hdr_len;
24050 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
24051 
24052 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
24053 
24054 		/* Set the TCP sequence number. */
24055 		U32_TO_ABE32(seq_no, tcph->th_seq);
24056 
24057 		/* Set up the TCP flag field. */
24058 		tcph->th_flags[0] = (uchar_t)TH_ACK;
24059 		if (tcp->tcp_ecn_echo_on)
24060 			tcph->th_flags[0] |= TH_ECE;
24061 
24062 		tcp->tcp_rack = tcp->tcp_rnxt;
24063 		tcp->tcp_rack_cnt = 0;
24064 
24065 		/* fill in timestamp option if in use */
24066 		if (tcp->tcp_snd_ts_ok) {
24067 			uint32_t llbolt = (uint32_t)lbolt;
24068 
24069 			U32_TO_BE32(llbolt,
24070 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
24071 			U32_TO_BE32(tcp->tcp_ts_recent,
24072 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
24073 		}
24074 
24075 		/* Fill in SACK options */
24076 		if (num_sack_blk > 0) {
24077 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
24078 			sack_blk_t *tmp;
24079 			int32_t	i;
24080 
24081 			wptr[0] = TCPOPT_NOP;
24082 			wptr[1] = TCPOPT_NOP;
24083 			wptr[2] = TCPOPT_SACK;
24084 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
24085 			    sizeof (sack_blk_t);
24086 			wptr += TCPOPT_REAL_SACK_LEN;
24087 
24088 			tmp = tcp->tcp_sack_list;
24089 			for (i = 0; i < num_sack_blk; i++) {
24090 				U32_TO_BE32(tmp[i].begin, wptr);
24091 				wptr += sizeof (tcp_seq);
24092 				U32_TO_BE32(tmp[i].end, wptr);
24093 				wptr += sizeof (tcp_seq);
24094 			}
24095 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
24096 			    << 4);
24097 		}
24098 
24099 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24100 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
24101 		} else {
24102 			/* Check for ip6i_t header in sticky hdrs */
24103 			ip6_t *ip6 = (ip6_t *)(rptr +
24104 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
24105 			    sizeof (ip6i_t) : 0));
24106 
24107 			ip6->ip6_plen = htons(tcp_hdr_len -
24108 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
24109 		}
24110 
24111 		/*
24112 		 * Prime pump for checksum calculation in IP.  Include the
24113 		 * adjustment for a source route if any.
24114 		 */
24115 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
24116 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
24117 		U16_TO_ABE16(data_length, tcph->th_sum);
24118 
24119 		if (tcp->tcp_ip_forward_progress) {
24120 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
24121 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
24122 			tcp->tcp_ip_forward_progress = B_FALSE;
24123 		}
24124 		return (mp1);
24125 	}
24126 }
24127 
24128 /*
24129  * To create a temporary tcp structure for inserting into bind hash list.
24130  * The parameter is assumed to be in network byte order, ready for use.
24131  */
24132 /* ARGSUSED */
24133 static tcp_t *
24134 tcp_alloc_temp_tcp(in_port_t port, tcp_stack_t *tcps)
24135 {
24136 	conn_t	*connp;
24137 	tcp_t	*tcp;
24138 
24139 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP, tcps->tcps_netstack);
24140 	if (connp == NULL)
24141 		return (NULL);
24142 
24143 	tcp = connp->conn_tcp;
24144 	tcp->tcp_tcps = tcps;
24145 	TCPS_REFHOLD(tcps);
24146 
24147 	/*
24148 	 * Only initialize the necessary info in those structures.  Note
24149 	 * that since INADDR_ANY is all 0, we do not need to set
24150 	 * tcp_bound_source to INADDR_ANY here.
24151 	 */
24152 	tcp->tcp_state = TCPS_BOUND;
24153 	tcp->tcp_lport = port;
24154 	tcp->tcp_exclbind = 1;
24155 	tcp->tcp_reserved_port = 1;
24156 
24157 	/* Just for place holding... */
24158 	tcp->tcp_ipversion = IPV4_VERSION;
24159 
24160 	return (tcp);
24161 }
24162 
24163 /*
24164  * To remove a port range specified by lo_port and hi_port from the
24165  * reserved port ranges.  This is one of the three public functions of
24166  * the reserved port interface.  Note that a port range has to be removed
24167  * as a whole.  Ports in a range cannot be removed individually.
24168  *
24169  * Params:
24170  *	in_port_t lo_port: the beginning port of the reserved port range to
24171  *		be deleted.
24172  *	in_port_t hi_port: the ending port of the reserved port range to
24173  *		be deleted.
24174  *
24175  * Return:
24176  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
24177  *
24178  * Assumes that nca is only for zoneid=0
24179  */
24180 boolean_t
24181 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
24182 {
24183 	int	i, j;
24184 	int	size;
24185 	tcp_t	**temp_tcp_array;
24186 	tcp_t	*tcp;
24187 	tcp_stack_t	*tcps;
24188 
24189 	tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_tcp;
24190 	ASSERT(tcps != NULL);
24191 
24192 	rw_enter(&tcps->tcps_reserved_port_lock, RW_WRITER);
24193 
24194 	/* First make sure that the port ranage is indeed reserved. */
24195 	for (i = 0; i < tcps->tcps_reserved_port_array_size; i++) {
24196 		if (tcps->tcps_reserved_port[i].lo_port == lo_port) {
24197 			hi_port = tcps->tcps_reserved_port[i].hi_port;
24198 			temp_tcp_array =
24199 			    tcps->tcps_reserved_port[i].temp_tcp_array;
24200 			break;
24201 		}
24202 	}
24203 	if (i == tcps->tcps_reserved_port_array_size) {
24204 		rw_exit(&tcps->tcps_reserved_port_lock);
24205 		netstack_rele(tcps->tcps_netstack);
24206 		return (B_FALSE);
24207 	}
24208 
24209 	/*
24210 	 * Remove the range from the array.  This simple loop is possible
24211 	 * because port ranges are inserted in ascending order.
24212 	 */
24213 	for (j = i; j < tcps->tcps_reserved_port_array_size - 1; j++) {
24214 		tcps->tcps_reserved_port[j].lo_port =
24215 		    tcps->tcps_reserved_port[j+1].lo_port;
24216 		tcps->tcps_reserved_port[j].hi_port =
24217 		    tcps->tcps_reserved_port[j+1].hi_port;
24218 		tcps->tcps_reserved_port[j].temp_tcp_array =
24219 		    tcps->tcps_reserved_port[j+1].temp_tcp_array;
24220 	}
24221 
24222 	/* Remove all the temporary tcp structures. */
24223 	size = hi_port - lo_port + 1;
24224 	while (size > 0) {
24225 		tcp = temp_tcp_array[size - 1];
24226 		ASSERT(tcp != NULL);
24227 		tcp_bind_hash_remove(tcp);
24228 		CONN_DEC_REF(tcp->tcp_connp);
24229 		size--;
24230 	}
24231 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
24232 	tcps->tcps_reserved_port_array_size--;
24233 	rw_exit(&tcps->tcps_reserved_port_lock);
24234 	netstack_rele(tcps->tcps_netstack);
24235 	return (B_TRUE);
24236 }
24237 
24238 /*
24239  * Macro to remove temporary tcp structure from the bind hash list.  The
24240  * first parameter is the list of tcp to be removed.  The second parameter
24241  * is the number of tcps in the array.
24242  */
24243 #define	TCP_TMP_TCP_REMOVE(tcp_array, num, tcps) \
24244 { \
24245 	while ((num) > 0) { \
24246 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
24247 		tf_t *tbf; \
24248 		tcp_t *tcpnext; \
24249 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
24250 		mutex_enter(&tbf->tf_lock); \
24251 		tcpnext = tcp->tcp_bind_hash; \
24252 		if (tcpnext) { \
24253 			tcpnext->tcp_ptpbhn = \
24254 				tcp->tcp_ptpbhn; \
24255 		} \
24256 		*tcp->tcp_ptpbhn = tcpnext; \
24257 		mutex_exit(&tbf->tf_lock); \
24258 		kmem_free(tcp, sizeof (tcp_t)); \
24259 		(tcp_array)[(num) - 1] = NULL; \
24260 		(num)--; \
24261 	} \
24262 }
24263 
24264 /*
24265  * The public interface for other modules to call to reserve a port range
24266  * in TCP.  The caller passes in how large a port range it wants.  TCP
24267  * will try to find a range and return it via lo_port and hi_port.  This is
24268  * used by NCA's nca_conn_init.
24269  * NCA can only be used in the global zone so this only affects the global
24270  * zone's ports.
24271  *
24272  * Params:
24273  *	int size: the size of the port range to be reserved.
24274  *	in_port_t *lo_port (referenced): returns the beginning port of the
24275  *		reserved port range added.
24276  *	in_port_t *hi_port (referenced): returns the ending port of the
24277  *		reserved port range added.
24278  *
24279  * Return:
24280  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
24281  *
24282  * Assumes that nca is only for zoneid=0
24283  */
24284 boolean_t
24285 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
24286 {
24287 	tcp_t		*tcp;
24288 	tcp_t		*tmp_tcp;
24289 	tcp_t		**temp_tcp_array;
24290 	tf_t		*tbf;
24291 	in_port_t	net_port;
24292 	in_port_t	port;
24293 	int32_t		cur_size;
24294 	int		i, j;
24295 	boolean_t	used;
24296 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
24297 	zoneid_t	zoneid = GLOBAL_ZONEID;
24298 	tcp_stack_t	*tcps;
24299 
24300 	/* Sanity check. */
24301 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
24302 		return (B_FALSE);
24303 	}
24304 
24305 	tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_tcp;
24306 	ASSERT(tcps != NULL);
24307 
24308 	rw_enter(&tcps->tcps_reserved_port_lock, RW_WRITER);
24309 	if (tcps->tcps_reserved_port_array_size ==
24310 	    TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
24311 		rw_exit(&tcps->tcps_reserved_port_lock);
24312 		netstack_rele(tcps->tcps_netstack);
24313 		return (B_FALSE);
24314 	}
24315 
24316 	/*
24317 	 * Find the starting port to try.  Since the port ranges are ordered
24318 	 * in the reserved port array, we can do a simple search here.
24319 	 */
24320 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
24321 	*hi_port = TCP_LARGEST_RESERVED_PORT;
24322 	for (i = 0; i < tcps->tcps_reserved_port_array_size;
24323 	    *lo_port = tcps->tcps_reserved_port[i].hi_port + 1, i++) {
24324 		if (tcps->tcps_reserved_port[i].lo_port - *lo_port >= size) {
24325 			*hi_port = tcps->tcps_reserved_port[i].lo_port - 1;
24326 			break;
24327 		}
24328 	}
24329 	/* No available port range. */
24330 	if (i == tcps->tcps_reserved_port_array_size &&
24331 	    *hi_port - *lo_port < size) {
24332 		rw_exit(&tcps->tcps_reserved_port_lock);
24333 		netstack_rele(tcps->tcps_netstack);
24334 		return (B_FALSE);
24335 	}
24336 
24337 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
24338 	if (temp_tcp_array == NULL) {
24339 		rw_exit(&tcps->tcps_reserved_port_lock);
24340 		netstack_rele(tcps->tcps_netstack);
24341 		return (B_FALSE);
24342 	}
24343 
24344 	/* Go thru the port range to see if some ports are already bound. */
24345 	for (port = *lo_port, cur_size = 0;
24346 	    cur_size < size && port <= *hi_port;
24347 	    cur_size++, port++) {
24348 		used = B_FALSE;
24349 		net_port = htons(port);
24350 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(net_port)];
24351 		mutex_enter(&tbf->tf_lock);
24352 		for (tcp = tbf->tf_tcp; tcp != NULL;
24353 		    tcp = tcp->tcp_bind_hash) {
24354 			if (IPCL_ZONE_MATCH(tcp->tcp_connp, zoneid) &&
24355 			    net_port == tcp->tcp_lport) {
24356 				/*
24357 				 * A port is already bound.  Search again
24358 				 * starting from port + 1.  Release all
24359 				 * temporary tcps.
24360 				 */
24361 				mutex_exit(&tbf->tf_lock);
24362 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size,
24363 				    tcps);
24364 				*lo_port = port + 1;
24365 				cur_size = -1;
24366 				used = B_TRUE;
24367 				break;
24368 			}
24369 		}
24370 		if (!used) {
24371 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port, tcps)) ==
24372 			    NULL) {
24373 				/*
24374 				 * Allocation failure.  Just fail the request.
24375 				 * Need to remove all those temporary tcp
24376 				 * structures.
24377 				 */
24378 				mutex_exit(&tbf->tf_lock);
24379 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size,
24380 				    tcps);
24381 				rw_exit(&tcps->tcps_reserved_port_lock);
24382 				kmem_free(temp_tcp_array,
24383 				    (hi_port - lo_port + 1) *
24384 				    sizeof (tcp_t *));
24385 				netstack_rele(tcps->tcps_netstack);
24386 				return (B_FALSE);
24387 			}
24388 			temp_tcp_array[cur_size] = tmp_tcp;
24389 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
24390 			mutex_exit(&tbf->tf_lock);
24391 		}
24392 	}
24393 
24394 	/*
24395 	 * The current range is not large enough.  We can actually do another
24396 	 * search if this search is done between 2 reserved port ranges.  But
24397 	 * for first release, we just stop here and return saying that no port
24398 	 * range is available.
24399 	 */
24400 	if (cur_size < size) {
24401 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size, tcps);
24402 		rw_exit(&tcps->tcps_reserved_port_lock);
24403 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
24404 		netstack_rele(tcps->tcps_netstack);
24405 		return (B_FALSE);
24406 	}
24407 	*hi_port = port - 1;
24408 
24409 	/*
24410 	 * Insert range into array in ascending order.  Since this function
24411 	 * must not be called often, we choose to use the simplest method.
24412 	 * The above array should not consume excessive stack space as
24413 	 * the size must be very small.  If in future releases, we find
24414 	 * that we should provide more reserved port ranges, this function
24415 	 * has to be modified to be more efficient.
24416 	 */
24417 	if (tcps->tcps_reserved_port_array_size == 0) {
24418 		tcps->tcps_reserved_port[0].lo_port = *lo_port;
24419 		tcps->tcps_reserved_port[0].hi_port = *hi_port;
24420 		tcps->tcps_reserved_port[0].temp_tcp_array = temp_tcp_array;
24421 	} else {
24422 		for (i = 0, j = 0; i < tcps->tcps_reserved_port_array_size;
24423 		    i++, j++) {
24424 			if (*lo_port < tcps->tcps_reserved_port[i].lo_port &&
24425 			    i == j) {
24426 				tmp_ports[j].lo_port = *lo_port;
24427 				tmp_ports[j].hi_port = *hi_port;
24428 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
24429 				j++;
24430 			}
24431 			tmp_ports[j].lo_port =
24432 			    tcps->tcps_reserved_port[i].lo_port;
24433 			tmp_ports[j].hi_port =
24434 			    tcps->tcps_reserved_port[i].hi_port;
24435 			tmp_ports[j].temp_tcp_array =
24436 			    tcps->tcps_reserved_port[i].temp_tcp_array;
24437 		}
24438 		if (j == i) {
24439 			tmp_ports[j].lo_port = *lo_port;
24440 			tmp_ports[j].hi_port = *hi_port;
24441 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
24442 		}
24443 		bcopy(tmp_ports, tcps->tcps_reserved_port, sizeof (tmp_ports));
24444 	}
24445 	tcps->tcps_reserved_port_array_size++;
24446 	rw_exit(&tcps->tcps_reserved_port_lock);
24447 	netstack_rele(tcps->tcps_netstack);
24448 	return (B_TRUE);
24449 }
24450 
24451 /*
24452  * Check to see if a port is in any reserved port range.
24453  *
24454  * Params:
24455  *	in_port_t port: the port to be verified.
24456  *
24457  * Return:
24458  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
24459  */
24460 boolean_t
24461 tcp_reserved_port_check(in_port_t port, tcp_stack_t *tcps)
24462 {
24463 	int i;
24464 
24465 	rw_enter(&tcps->tcps_reserved_port_lock, RW_READER);
24466 	for (i = 0; i < tcps->tcps_reserved_port_array_size; i++) {
24467 		if (port >= tcps->tcps_reserved_port[i].lo_port ||
24468 		    port <= tcps->tcps_reserved_port[i].hi_port) {
24469 			rw_exit(&tcps->tcps_reserved_port_lock);
24470 			return (B_TRUE);
24471 		}
24472 	}
24473 	rw_exit(&tcps->tcps_reserved_port_lock);
24474 	return (B_FALSE);
24475 }
24476 
24477 /*
24478  * To list all reserved port ranges.  This is the function to handle
24479  * ndd tcp_reserved_port_list.
24480  */
24481 /* ARGSUSED */
24482 static int
24483 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
24484 {
24485 	int i;
24486 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24487 
24488 	rw_enter(&tcps->tcps_reserved_port_lock, RW_READER);
24489 	if (tcps->tcps_reserved_port_array_size > 0)
24490 		(void) mi_mpprintf(mp, "The following ports are reserved:");
24491 	else
24492 		(void) mi_mpprintf(mp, "No port is reserved.");
24493 	for (i = 0; i < tcps->tcps_reserved_port_array_size; i++) {
24494 		(void) mi_mpprintf(mp, "%d-%d",
24495 		    tcps->tcps_reserved_port[i].lo_port,
24496 		    tcps->tcps_reserved_port[i].hi_port);
24497 	}
24498 	rw_exit(&tcps->tcps_reserved_port_lock);
24499 	return (0);
24500 }
24501 
24502 /*
24503  * Hash list insertion routine for tcp_t structures.
24504  * Inserts entries with the ones bound to a specific IP address first
24505  * followed by those bound to INADDR_ANY.
24506  */
24507 static void
24508 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
24509 {
24510 	tcp_t	**tcpp;
24511 	tcp_t	*tcpnext;
24512 
24513 	if (tcp->tcp_ptpbhn != NULL) {
24514 		ASSERT(!caller_holds_lock);
24515 		tcp_bind_hash_remove(tcp);
24516 	}
24517 	tcpp = &tbf->tf_tcp;
24518 	if (!caller_holds_lock) {
24519 		mutex_enter(&tbf->tf_lock);
24520 	} else {
24521 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
24522 	}
24523 	tcpnext = tcpp[0];
24524 	if (tcpnext) {
24525 		/*
24526 		 * If the new tcp bound to the INADDR_ANY address
24527 		 * and the first one in the list is not bound to
24528 		 * INADDR_ANY we skip all entries until we find the
24529 		 * first one bound to INADDR_ANY.
24530 		 * This makes sure that applications binding to a
24531 		 * specific address get preference over those binding to
24532 		 * INADDR_ANY.
24533 		 */
24534 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
24535 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
24536 			while ((tcpnext = tcpp[0]) != NULL &&
24537 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
24538 				tcpp = &(tcpnext->tcp_bind_hash);
24539 			if (tcpnext)
24540 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
24541 		} else
24542 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
24543 	}
24544 	tcp->tcp_bind_hash = tcpnext;
24545 	tcp->tcp_ptpbhn = tcpp;
24546 	tcpp[0] = tcp;
24547 	if (!caller_holds_lock)
24548 		mutex_exit(&tbf->tf_lock);
24549 }
24550 
24551 /*
24552  * Hash list removal routine for tcp_t structures.
24553  */
24554 static void
24555 tcp_bind_hash_remove(tcp_t *tcp)
24556 {
24557 	tcp_t	*tcpnext;
24558 	kmutex_t *lockp;
24559 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24560 
24561 	if (tcp->tcp_ptpbhn == NULL)
24562 		return;
24563 
24564 	/*
24565 	 * Extract the lock pointer in case there are concurrent
24566 	 * hash_remove's for this instance.
24567 	 */
24568 	ASSERT(tcp->tcp_lport != 0);
24569 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
24570 
24571 	ASSERT(lockp != NULL);
24572 	mutex_enter(lockp);
24573 	if (tcp->tcp_ptpbhn) {
24574 		tcpnext = tcp->tcp_bind_hash;
24575 		if (tcpnext) {
24576 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
24577 			tcp->tcp_bind_hash = NULL;
24578 		}
24579 		*tcp->tcp_ptpbhn = tcpnext;
24580 		tcp->tcp_ptpbhn = NULL;
24581 	}
24582 	mutex_exit(lockp);
24583 }
24584 
24585 
24586 /*
24587  * Hash list lookup routine for tcp_t structures.
24588  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
24589  */
24590 static tcp_t *
24591 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
24592 {
24593 	tf_t	*tf;
24594 	tcp_t	*tcp;
24595 
24596 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24597 	mutex_enter(&tf->tf_lock);
24598 	for (tcp = tf->tf_tcp; tcp != NULL;
24599 	    tcp = tcp->tcp_acceptor_hash) {
24600 		if (tcp->tcp_acceptor_id == id) {
24601 			CONN_INC_REF(tcp->tcp_connp);
24602 			mutex_exit(&tf->tf_lock);
24603 			return (tcp);
24604 		}
24605 	}
24606 	mutex_exit(&tf->tf_lock);
24607 	return (NULL);
24608 }
24609 
24610 
24611 /*
24612  * Hash list insertion routine for tcp_t structures.
24613  */
24614 void
24615 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
24616 {
24617 	tf_t	*tf;
24618 	tcp_t	**tcpp;
24619 	tcp_t	*tcpnext;
24620 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24621 
24622 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24623 
24624 	if (tcp->tcp_ptpahn != NULL)
24625 		tcp_acceptor_hash_remove(tcp);
24626 	tcpp = &tf->tf_tcp;
24627 	mutex_enter(&tf->tf_lock);
24628 	tcpnext = tcpp[0];
24629 	if (tcpnext)
24630 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
24631 	tcp->tcp_acceptor_hash = tcpnext;
24632 	tcp->tcp_ptpahn = tcpp;
24633 	tcpp[0] = tcp;
24634 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
24635 	mutex_exit(&tf->tf_lock);
24636 }
24637 
24638 /*
24639  * Hash list removal routine for tcp_t structures.
24640  */
24641 static void
24642 tcp_acceptor_hash_remove(tcp_t *tcp)
24643 {
24644 	tcp_t	*tcpnext;
24645 	kmutex_t *lockp;
24646 
24647 	/*
24648 	 * Extract the lock pointer in case there are concurrent
24649 	 * hash_remove's for this instance.
24650 	 */
24651 	lockp = tcp->tcp_acceptor_lockp;
24652 
24653 	if (tcp->tcp_ptpahn == NULL)
24654 		return;
24655 
24656 	ASSERT(lockp != NULL);
24657 	mutex_enter(lockp);
24658 	if (tcp->tcp_ptpahn) {
24659 		tcpnext = tcp->tcp_acceptor_hash;
24660 		if (tcpnext) {
24661 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
24662 			tcp->tcp_acceptor_hash = NULL;
24663 		}
24664 		*tcp->tcp_ptpahn = tcpnext;
24665 		tcp->tcp_ptpahn = NULL;
24666 	}
24667 	mutex_exit(lockp);
24668 	tcp->tcp_acceptor_lockp = NULL;
24669 }
24670 
24671 /* ARGSUSED */
24672 static int
24673 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
24674 {
24675 	int error = 0;
24676 	int retval;
24677 	char *end;
24678 	tcp_hsp_t *hsp;
24679 	tcp_hsp_t *hspprev;
24680 	ipaddr_t addr = 0;		/* Address we're looking for */
24681 	in6_addr_t v6addr;		/* Address we're looking for */
24682 	uint32_t hash;			/* Hash of that address */
24683 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24684 
24685 	/*
24686 	 * If the following variables are still zero after parsing the input
24687 	 * string, the user didn't specify them and we don't change them in
24688 	 * the HSP.
24689 	 */
24690 
24691 	ipaddr_t mask = 0;		/* Subnet mask */
24692 	in6_addr_t v6mask;
24693 	long sendspace = 0;		/* Send buffer size */
24694 	long recvspace = 0;		/* Receive buffer size */
24695 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
24696 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
24697 
24698 	rw_enter(&tcps->tcps_hsp_lock, RW_WRITER);
24699 
24700 	/* Parse and validate address */
24701 	if (af == AF_INET) {
24702 		retval = inet_pton(af, value, &addr);
24703 		if (retval == 1)
24704 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
24705 	} else if (af == AF_INET6) {
24706 		retval = inet_pton(af, value, &v6addr);
24707 	} else {
24708 		error = EINVAL;
24709 		goto done;
24710 	}
24711 	if (retval == 0) {
24712 		error = EINVAL;
24713 		goto done;
24714 	}
24715 
24716 	while ((*value) && *value != ' ')
24717 		value++;
24718 
24719 	/* Parse individual keywords, set variables if found */
24720 	while (*value) {
24721 		/* Skip leading blanks */
24722 
24723 		while (*value == ' ' || *value == '\t')
24724 			value++;
24725 
24726 		/* If at end of string, we're done */
24727 
24728 		if (!*value)
24729 			break;
24730 
24731 		/* We have a word, figure out what it is */
24732 
24733 		if (strncmp("mask", value, 4) == 0) {
24734 			value += 4;
24735 			while (*value == ' ' || *value == '\t')
24736 				value++;
24737 			/* Parse subnet mask */
24738 			if (af == AF_INET) {
24739 				retval = inet_pton(af, value, &mask);
24740 				if (retval == 1) {
24741 					V4MASK_TO_V6(mask, v6mask);
24742 				}
24743 			} else if (af == AF_INET6) {
24744 				retval = inet_pton(af, value, &v6mask);
24745 			}
24746 			if (retval != 1) {
24747 				error = EINVAL;
24748 				goto done;
24749 			}
24750 			while ((*value) && *value != ' ')
24751 				value++;
24752 		} else if (strncmp("sendspace", value, 9) == 0) {
24753 			value += 9;
24754 
24755 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
24756 			    sendspace < TCP_XMIT_HIWATER ||
24757 			    sendspace >= (1L<<30)) {
24758 				error = EINVAL;
24759 				goto done;
24760 			}
24761 			value = end;
24762 		} else if (strncmp("recvspace", value, 9) == 0) {
24763 			value += 9;
24764 
24765 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
24766 			    recvspace < TCP_RECV_HIWATER ||
24767 			    recvspace >= (1L<<30)) {
24768 				error = EINVAL;
24769 				goto done;
24770 			}
24771 			value = end;
24772 		} else if (strncmp("timestamp", value, 9) == 0) {
24773 			value += 9;
24774 
24775 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
24776 			    timestamp < 0 || timestamp > 1) {
24777 				error = EINVAL;
24778 				goto done;
24779 			}
24780 
24781 			/*
24782 			 * We increment timestamp so we know it's been set;
24783 			 * this is undone when we put it in the HSP
24784 			 */
24785 			timestamp++;
24786 			value = end;
24787 		} else if (strncmp("delete", value, 6) == 0) {
24788 			value += 6;
24789 			delete = B_TRUE;
24790 		} else {
24791 			error = EINVAL;
24792 			goto done;
24793 		}
24794 	}
24795 
24796 	/* Hash address for lookup */
24797 
24798 	hash = TCP_HSP_HASH(addr);
24799 
24800 	if (delete) {
24801 		/*
24802 		 * Note that deletes don't return an error if the thing
24803 		 * we're trying to delete isn't there.
24804 		 */
24805 		if (tcps->tcps_hsp_hash == NULL)
24806 			goto done;
24807 		hsp = tcps->tcps_hsp_hash[hash];
24808 
24809 		if (hsp) {
24810 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24811 			    &v6addr)) {
24812 				tcps->tcps_hsp_hash[hash] = hsp->tcp_hsp_next;
24813 				mi_free((char *)hsp);
24814 			} else {
24815 				hspprev = hsp;
24816 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
24817 					if (IN6_ARE_ADDR_EQUAL(
24818 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
24819 						hspprev->tcp_hsp_next =
24820 						    hsp->tcp_hsp_next;
24821 						mi_free((char *)hsp);
24822 						break;
24823 					}
24824 					hspprev = hsp;
24825 				}
24826 			}
24827 		}
24828 	} else {
24829 		/*
24830 		 * We're adding/modifying an HSP.  If we haven't already done
24831 		 * so, allocate the hash table.
24832 		 */
24833 
24834 		if (!tcps->tcps_hsp_hash) {
24835 			tcps->tcps_hsp_hash = (tcp_hsp_t **)
24836 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
24837 			if (!tcps->tcps_hsp_hash) {
24838 				error = EINVAL;
24839 				goto done;
24840 			}
24841 		}
24842 
24843 		/* Get head of hash chain */
24844 
24845 		hsp = tcps->tcps_hsp_hash[hash];
24846 
24847 		/* Try to find pre-existing hsp on hash chain */
24848 		/* Doesn't handle CIDR prefixes. */
24849 		while (hsp) {
24850 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
24851 				break;
24852 			hsp = hsp->tcp_hsp_next;
24853 		}
24854 
24855 		/*
24856 		 * If we didn't, create one with default values and put it
24857 		 * at head of hash chain
24858 		 */
24859 
24860 		if (!hsp) {
24861 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
24862 			if (!hsp) {
24863 				error = EINVAL;
24864 				goto done;
24865 			}
24866 			hsp->tcp_hsp_next = tcps->tcps_hsp_hash[hash];
24867 			tcps->tcps_hsp_hash[hash] = hsp;
24868 		}
24869 
24870 		/* Set values that the user asked us to change */
24871 
24872 		hsp->tcp_hsp_addr_v6 = v6addr;
24873 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
24874 			hsp->tcp_hsp_vers = IPV4_VERSION;
24875 		else
24876 			hsp->tcp_hsp_vers = IPV6_VERSION;
24877 		hsp->tcp_hsp_subnet_v6 = v6mask;
24878 		if (sendspace > 0)
24879 			hsp->tcp_hsp_sendspace = sendspace;
24880 		if (recvspace > 0)
24881 			hsp->tcp_hsp_recvspace = recvspace;
24882 		if (timestamp > 0)
24883 			hsp->tcp_hsp_tstamp = timestamp - 1;
24884 	}
24885 
24886 done:
24887 	rw_exit(&tcps->tcps_hsp_lock);
24888 	return (error);
24889 }
24890 
24891 /* Set callback routine passed to nd_load by tcp_param_register. */
24892 /* ARGSUSED */
24893 static int
24894 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
24895 {
24896 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
24897 }
24898 /* ARGSUSED */
24899 static int
24900 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24901     cred_t *cr)
24902 {
24903 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
24904 }
24905 
24906 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
24907 /* ARGSUSED */
24908 static int
24909 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
24910 {
24911 	tcp_hsp_t *hsp;
24912 	int i;
24913 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
24914 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24915 
24916 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24917 	(void) mi_mpprintf(mp,
24918 	    "Hash HSP     " MI_COL_HDRPAD_STR
24919 	    "Address         Subnet Mask     Send       Receive    TStamp");
24920 	if (tcps->tcps_hsp_hash) {
24921 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
24922 			hsp = tcps->tcps_hsp_hash[i];
24923 			while (hsp) {
24924 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
24925 					(void) inet_ntop(AF_INET,
24926 					    &hsp->tcp_hsp_addr,
24927 					    addrbuf, sizeof (addrbuf));
24928 					(void) inet_ntop(AF_INET,
24929 					    &hsp->tcp_hsp_subnet,
24930 					    subnetbuf, sizeof (subnetbuf));
24931 				} else {
24932 					(void) inet_ntop(AF_INET6,
24933 					    &hsp->tcp_hsp_addr_v6,
24934 					    addrbuf, sizeof (addrbuf));
24935 					(void) inet_ntop(AF_INET6,
24936 					    &hsp->tcp_hsp_subnet_v6,
24937 					    subnetbuf, sizeof (subnetbuf));
24938 				}
24939 				(void) mi_mpprintf(mp,
24940 				    " %03d " MI_COL_PTRFMT_STR
24941 				    "%s %s %010d %010d      %d",
24942 				    i,
24943 				    (void *)hsp,
24944 				    addrbuf,
24945 				    subnetbuf,
24946 				    hsp->tcp_hsp_sendspace,
24947 				    hsp->tcp_hsp_recvspace,
24948 				    hsp->tcp_hsp_tstamp);
24949 
24950 				hsp = hsp->tcp_hsp_next;
24951 			}
24952 		}
24953 	}
24954 	rw_exit(&tcps->tcps_hsp_lock);
24955 	return (0);
24956 }
24957 
24958 
24959 /* Data for fast netmask macro used by tcp_hsp_lookup */
24960 
24961 static ipaddr_t netmasks[] = {
24962 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24963 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24964 };
24965 
24966 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24967 
24968 /*
24969  * XXX This routine should go away and instead we should use the metrics
24970  * associated with the routes to determine the default sndspace and rcvspace.
24971  */
24972 static tcp_hsp_t *
24973 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24974 {
24975 	tcp_hsp_t *hsp = NULL;
24976 
24977 	/* Quick check without acquiring the lock. */
24978 	if (tcps->tcps_hsp_hash == NULL)
24979 		return (NULL);
24980 
24981 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24982 
24983 	/* This routine finds the best-matching HSP for address addr. */
24984 
24985 	if (tcps->tcps_hsp_hash) {
24986 		int i;
24987 		ipaddr_t srchaddr;
24988 		tcp_hsp_t *hsp_net;
24989 
24990 		/* We do three passes: host, network, and subnet. */
24991 
24992 		srchaddr = addr;
24993 
24994 		for (i = 1; i <= 3; i++) {
24995 			/* Look for exact match on srchaddr */
24996 
24997 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24998 			while (hsp) {
24999 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
25000 				    hsp->tcp_hsp_addr == srchaddr)
25001 					break;
25002 				hsp = hsp->tcp_hsp_next;
25003 			}
25004 			ASSERT(hsp == NULL ||
25005 			    hsp->tcp_hsp_vers == IPV4_VERSION);
25006 
25007 			/*
25008 			 * If this is the first pass:
25009 			 *   If we found a match, great, return it.
25010 			 *   If not, search for the network on the second pass.
25011 			 */
25012 
25013 			if (i == 1)
25014 				if (hsp)
25015 					break;
25016 				else
25017 				{
25018 					srchaddr = addr & netmask(addr);
25019 					continue;
25020 				}
25021 
25022 			/*
25023 			 * If this is the second pass:
25024 			 *   If we found a match, but there's a subnet mask,
25025 			 *    save the match but try again using the subnet
25026 			 *    mask on the third pass.
25027 			 *   Otherwise, return whatever we found.
25028 			 */
25029 
25030 			if (i == 2) {
25031 				if (hsp && hsp->tcp_hsp_subnet) {
25032 					hsp_net = hsp;
25033 					srchaddr = addr & hsp->tcp_hsp_subnet;
25034 					continue;
25035 				} else {
25036 					break;
25037 				}
25038 			}
25039 
25040 			/*
25041 			 * This must be the third pass.  If we didn't find
25042 			 * anything, return the saved network HSP instead.
25043 			 */
25044 
25045 			if (!hsp)
25046 				hsp = hsp_net;
25047 		}
25048 	}
25049 
25050 	rw_exit(&tcps->tcps_hsp_lock);
25051 	return (hsp);
25052 }
25053 
25054 /*
25055  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
25056  * match lookup.
25057  */
25058 static tcp_hsp_t *
25059 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
25060 {
25061 	tcp_hsp_t *hsp = NULL;
25062 
25063 	/* Quick check without acquiring the lock. */
25064 	if (tcps->tcps_hsp_hash == NULL)
25065 		return (NULL);
25066 
25067 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
25068 
25069 	/* This routine finds the best-matching HSP for address addr. */
25070 
25071 	if (tcps->tcps_hsp_hash) {
25072 		int i;
25073 		in6_addr_t v6srchaddr;
25074 		tcp_hsp_t *hsp_net;
25075 
25076 		/* We do three passes: host, network, and subnet. */
25077 
25078 		v6srchaddr = *v6addr;
25079 
25080 		for (i = 1; i <= 3; i++) {
25081 			/* Look for exact match on srchaddr */
25082 
25083 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
25084 			    V4_PART_OF_V6(v6srchaddr))];
25085 			while (hsp) {
25086 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
25087 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
25088 				    &v6srchaddr))
25089 					break;
25090 				hsp = hsp->tcp_hsp_next;
25091 			}
25092 
25093 			/*
25094 			 * If this is the first pass:
25095 			 *   If we found a match, great, return it.
25096 			 *   If not, search for the network on the second pass.
25097 			 */
25098 
25099 			if (i == 1)
25100 				if (hsp)
25101 					break;
25102 				else {
25103 					/* Assume a 64 bit mask */
25104 					v6srchaddr.s6_addr32[0] =
25105 					    v6addr->s6_addr32[0];
25106 					v6srchaddr.s6_addr32[1] =
25107 					    v6addr->s6_addr32[1];
25108 					v6srchaddr.s6_addr32[2] = 0;
25109 					v6srchaddr.s6_addr32[3] = 0;
25110 					continue;
25111 				}
25112 
25113 			/*
25114 			 * If this is the second pass:
25115 			 *   If we found a match, but there's a subnet mask,
25116 			 *    save the match but try again using the subnet
25117 			 *    mask on the third pass.
25118 			 *   Otherwise, return whatever we found.
25119 			 */
25120 
25121 			if (i == 2) {
25122 				ASSERT(hsp == NULL ||
25123 				    hsp->tcp_hsp_vers == IPV6_VERSION);
25124 				if (hsp &&
25125 				    !IN6_IS_ADDR_UNSPECIFIED(
25126 				    &hsp->tcp_hsp_subnet_v6)) {
25127 					hsp_net = hsp;
25128 					V6_MASK_COPY(*v6addr,
25129 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
25130 					continue;
25131 				} else {
25132 					break;
25133 				}
25134 			}
25135 
25136 			/*
25137 			 * This must be the third pass.  If we didn't find
25138 			 * anything, return the saved network HSP instead.
25139 			 */
25140 
25141 			if (!hsp)
25142 				hsp = hsp_net;
25143 		}
25144 	}
25145 
25146 	rw_exit(&tcps->tcps_hsp_lock);
25147 	return (hsp);
25148 }
25149 
25150 /*
25151  * Type three generator adapted from the random() function in 4.4 BSD:
25152  */
25153 
25154 /*
25155  * Copyright (c) 1983, 1993
25156  *	The Regents of the University of California.  All rights reserved.
25157  *
25158  * Redistribution and use in source and binary forms, with or without
25159  * modification, are permitted provided that the following conditions
25160  * are met:
25161  * 1. Redistributions of source code must retain the above copyright
25162  *    notice, this list of conditions and the following disclaimer.
25163  * 2. Redistributions in binary form must reproduce the above copyright
25164  *    notice, this list of conditions and the following disclaimer in the
25165  *    documentation and/or other materials provided with the distribution.
25166  * 3. All advertising materials mentioning features or use of this software
25167  *    must display the following acknowledgement:
25168  *	This product includes software developed by the University of
25169  *	California, Berkeley and its contributors.
25170  * 4. Neither the name of the University nor the names of its contributors
25171  *    may be used to endorse or promote products derived from this software
25172  *    without specific prior written permission.
25173  *
25174  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25175  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25176  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25177  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25178  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25179  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25180  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25181  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25182  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25183  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25184  * SUCH DAMAGE.
25185  */
25186 
25187 /* Type 3 -- x**31 + x**3 + 1 */
25188 #define	DEG_3		31
25189 #define	SEP_3		3
25190 
25191 
25192 /* Protected by tcp_random_lock */
25193 static int tcp_randtbl[DEG_3 + 1];
25194 
25195 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
25196 static int *tcp_random_rptr = &tcp_randtbl[1];
25197 
25198 static int *tcp_random_state = &tcp_randtbl[1];
25199 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
25200 
25201 kmutex_t tcp_random_lock;
25202 
25203 void
25204 tcp_random_init(void)
25205 {
25206 	int i;
25207 	hrtime_t hrt;
25208 	time_t wallclock;
25209 	uint64_t result;
25210 
25211 	/*
25212 	 * Use high-res timer and current time for seed.  Gethrtime() returns
25213 	 * a longlong, which may contain resolution down to nanoseconds.
25214 	 * The current time will either be a 32-bit or a 64-bit quantity.
25215 	 * XOR the two together in a 64-bit result variable.
25216 	 * Convert the result to a 32-bit value by multiplying the high-order
25217 	 * 32-bits by the low-order 32-bits.
25218 	 */
25219 
25220 	hrt = gethrtime();
25221 	(void) drv_getparm(TIME, &wallclock);
25222 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
25223 	mutex_enter(&tcp_random_lock);
25224 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
25225 	    (result & 0xffffffff);
25226 
25227 	for (i = 1; i < DEG_3; i++)
25228 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
25229 		    + 12345;
25230 	tcp_random_fptr = &tcp_random_state[SEP_3];
25231 	tcp_random_rptr = &tcp_random_state[0];
25232 	mutex_exit(&tcp_random_lock);
25233 	for (i = 0; i < 10 * DEG_3; i++)
25234 		(void) tcp_random();
25235 }
25236 
25237 /*
25238  * tcp_random: Return a random number in the range [1 - (128K + 1)].
25239  * This range is selected to be approximately centered on TCP_ISS / 2,
25240  * and easy to compute. We get this value by generating a 32-bit random
25241  * number, selecting out the high-order 17 bits, and then adding one so
25242  * that we never return zero.
25243  */
25244 int
25245 tcp_random(void)
25246 {
25247 	int i;
25248 
25249 	mutex_enter(&tcp_random_lock);
25250 	*tcp_random_fptr += *tcp_random_rptr;
25251 
25252 	/*
25253 	 * The high-order bits are more random than the low-order bits,
25254 	 * so we select out the high-order 17 bits and add one so that
25255 	 * we never return zero.
25256 	 */
25257 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
25258 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
25259 		tcp_random_fptr = tcp_random_state;
25260 		++tcp_random_rptr;
25261 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
25262 		tcp_random_rptr = tcp_random_state;
25263 
25264 	mutex_exit(&tcp_random_lock);
25265 	return (i);
25266 }
25267 
25268 /*
25269  * XXX This will go away when TPI is extended to send
25270  * info reqs to sockfs/timod .....
25271  * Given a queue, set the max packet size for the write
25272  * side of the queue below stream head.  This value is
25273  * cached on the stream head.
25274  * Returns 1 on success, 0 otherwise.
25275  */
25276 static int
25277 setmaxps(queue_t *q, int maxpsz)
25278 {
25279 	struct stdata	*stp;
25280 	queue_t		*wq;
25281 	stp = STREAM(q);
25282 
25283 	/*
25284 	 * At this point change of a queue parameter is not allowed
25285 	 * when a multiplexor is sitting on top.
25286 	 */
25287 	if (stp->sd_flag & STPLEX)
25288 		return (0);
25289 
25290 	claimstr(stp->sd_wrq);
25291 	wq = stp->sd_wrq->q_next;
25292 	ASSERT(wq != NULL);
25293 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
25294 	releasestr(stp->sd_wrq);
25295 	return (1);
25296 }
25297 
25298 static int
25299 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
25300     int *t_errorp, int *sys_errorp)
25301 {
25302 	int error;
25303 	int is_absreq_failure;
25304 	t_scalar_t *opt_lenp;
25305 	t_scalar_t opt_offset;
25306 	int prim_type;
25307 	struct T_conn_req *tcreqp;
25308 	struct T_conn_res *tcresp;
25309 	cred_t *cr;
25310 
25311 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
25312 
25313 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
25314 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
25315 	    prim_type == T_CONN_RES);
25316 
25317 	switch (prim_type) {
25318 	case T_CONN_REQ:
25319 		tcreqp = (struct T_conn_req *)mp->b_rptr;
25320 		opt_offset = tcreqp->OPT_offset;
25321 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
25322 		break;
25323 	case O_T_CONN_RES:
25324 	case T_CONN_RES:
25325 		tcresp = (struct T_conn_res *)mp->b_rptr;
25326 		opt_offset = tcresp->OPT_offset;
25327 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
25328 		break;
25329 	}
25330 
25331 	*t_errorp = 0;
25332 	*sys_errorp = 0;
25333 	*do_disconnectp = 0;
25334 
25335 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
25336 	    opt_offset, cr, &tcp_opt_obj,
25337 	    NULL, &is_absreq_failure);
25338 
25339 	switch (error) {
25340 	case  0:		/* no error */
25341 		ASSERT(is_absreq_failure == 0);
25342 		return (0);
25343 	case ENOPROTOOPT:
25344 		*t_errorp = TBADOPT;
25345 		break;
25346 	case EACCES:
25347 		*t_errorp = TACCES;
25348 		break;
25349 	default:
25350 		*t_errorp = TSYSERR; *sys_errorp = error;
25351 		break;
25352 	}
25353 	if (is_absreq_failure != 0) {
25354 		/*
25355 		 * The connection request should get the local ack
25356 		 * T_OK_ACK and then a T_DISCON_IND.
25357 		 */
25358 		*do_disconnectp = 1;
25359 	}
25360 	return (-1);
25361 }
25362 
25363 /*
25364  * Split this function out so that if the secret changes, I'm okay.
25365  *
25366  * Initialize the tcp_iss_cookie and tcp_iss_key.
25367  */
25368 
25369 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
25370 
25371 static void
25372 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
25373 {
25374 	struct {
25375 		int32_t current_time;
25376 		uint32_t randnum;
25377 		uint16_t pad;
25378 		uint8_t ether[6];
25379 		uint8_t passwd[PASSWD_SIZE];
25380 	} tcp_iss_cookie;
25381 	time_t t;
25382 
25383 	/*
25384 	 * Start with the current absolute time.
25385 	 */
25386 	(void) drv_getparm(TIME, &t);
25387 	tcp_iss_cookie.current_time = t;
25388 
25389 	/*
25390 	 * XXX - Need a more random number per RFC 1750, not this crap.
25391 	 * OTOH, if what follows is pretty random, then I'm in better shape.
25392 	 */
25393 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
25394 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
25395 
25396 	/*
25397 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
25398 	 * as a good template.
25399 	 */
25400 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
25401 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
25402 
25403 	/*
25404 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
25405 	 */
25406 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
25407 
25408 	/*
25409 	 * See 4010593 if this section becomes a problem again,
25410 	 * but the local ethernet address is useful here.
25411 	 */
25412 	(void) localetheraddr(NULL,
25413 	    (struct ether_addr *)&tcp_iss_cookie.ether);
25414 
25415 	/*
25416 	 * Hash 'em all together.  The MD5Final is called per-connection.
25417 	 */
25418 	mutex_enter(&tcps->tcps_iss_key_lock);
25419 	MD5Init(&tcps->tcps_iss_key);
25420 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
25421 	    sizeof (tcp_iss_cookie));
25422 	mutex_exit(&tcps->tcps_iss_key_lock);
25423 }
25424 
25425 /*
25426  * Set the RFC 1948 pass phrase
25427  */
25428 /* ARGSUSED */
25429 static int
25430 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
25431     cred_t *cr)
25432 {
25433 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
25434 
25435 	/*
25436 	 * Basically, value contains a new pass phrase.  Pass it along!
25437 	 */
25438 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
25439 	return (0);
25440 }
25441 
25442 /* ARGSUSED */
25443 static int
25444 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
25445 {
25446 	bzero(buf, sizeof (tcp_sack_info_t));
25447 	return (0);
25448 }
25449 
25450 /* ARGSUSED */
25451 static int
25452 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
25453 {
25454 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
25455 	return (0);
25456 }
25457 
25458 /*
25459  * Make sure we wait until the default queue is setup, yet allow
25460  * tcp_g_q_create() to open a TCP stream.
25461  * We need to allow tcp_g_q_create() do do an open
25462  * of tcp, hence we compare curhread.
25463  * All others have to wait until the tcps_g_q has been
25464  * setup.
25465  */
25466 void
25467 tcp_g_q_setup(tcp_stack_t *tcps)
25468 {
25469 	mutex_enter(&tcps->tcps_g_q_lock);
25470 	if (tcps->tcps_g_q != NULL) {
25471 		mutex_exit(&tcps->tcps_g_q_lock);
25472 		return;
25473 	}
25474 	if (tcps->tcps_g_q_creator == NULL) {
25475 		/* This thread will set it up */
25476 		tcps->tcps_g_q_creator = curthread;
25477 		mutex_exit(&tcps->tcps_g_q_lock);
25478 		tcp_g_q_create(tcps);
25479 		mutex_enter(&tcps->tcps_g_q_lock);
25480 		ASSERT(tcps->tcps_g_q_creator == curthread);
25481 		tcps->tcps_g_q_creator = NULL;
25482 		cv_signal(&tcps->tcps_g_q_cv);
25483 		ASSERT(tcps->tcps_g_q != NULL);
25484 		mutex_exit(&tcps->tcps_g_q_lock);
25485 		return;
25486 	}
25487 	/* Everybody but the creator has to wait */
25488 	if (tcps->tcps_g_q_creator != curthread) {
25489 		while (tcps->tcps_g_q == NULL)
25490 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
25491 	}
25492 	mutex_exit(&tcps->tcps_g_q_lock);
25493 }
25494 
25495 #define	IP	"ip"
25496 
25497 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
25498 
25499 /*
25500  * Create a default tcp queue here instead of in strplumb
25501  */
25502 void
25503 tcp_g_q_create(tcp_stack_t *tcps)
25504 {
25505 	int error;
25506 	ldi_handle_t	lh = NULL;
25507 	ldi_ident_t	li = NULL;
25508 	int		rval;
25509 	cred_t		*cr;
25510 	major_t IP_MAJ;
25511 
25512 #ifdef NS_DEBUG
25513 	(void) printf("tcp_g_q_create()\n");
25514 #endif
25515 
25516 	IP_MAJ = ddi_name_to_major(IP);
25517 
25518 	ASSERT(tcps->tcps_g_q_creator == curthread);
25519 
25520 	error = ldi_ident_from_major(IP_MAJ, &li);
25521 	if (error) {
25522 #ifdef DEBUG
25523 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
25524 		    error);
25525 #endif
25526 		return;
25527 	}
25528 
25529 	cr = zone_get_kcred(netstackid_to_zoneid(
25530 	    tcps->tcps_netstack->netstack_stackid));
25531 	ASSERT(cr != NULL);
25532 	/*
25533 	 * We set the tcp default queue to IPv6 because IPv4 falls
25534 	 * back to IPv6 when it can't find a client, but
25535 	 * IPv6 does not fall back to IPv4.
25536 	 */
25537 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
25538 	if (error) {
25539 #ifdef DEBUG
25540 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
25541 		    error);
25542 #endif
25543 		goto out;
25544 	}
25545 
25546 	/*
25547 	 * This ioctl causes the tcp framework to cache a pointer to
25548 	 * this stream, so we don't want to close the stream after
25549 	 * this operation.
25550 	 * Use the kernel credentials that are for the zone we're in.
25551 	 */
25552 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
25553 	    (intptr_t)0, FKIOCTL, cr, &rval);
25554 	if (error) {
25555 #ifdef DEBUG
25556 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
25557 		    "error %d\n", error);
25558 #endif
25559 		goto out;
25560 	}
25561 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
25562 	lh = NULL;
25563 out:
25564 	/* Close layered handles */
25565 	if (li)
25566 		ldi_ident_release(li);
25567 	/* Keep cred around until _inactive needs it */
25568 	tcps->tcps_g_q_cr = cr;
25569 }
25570 
25571 /*
25572  * We keep tcp_g_q set until all other tcp_t's in the zone
25573  * has gone away, and then when tcp_g_q_inactive() is called
25574  * we clear it.
25575  */
25576 void
25577 tcp_g_q_destroy(tcp_stack_t *tcps)
25578 {
25579 #ifdef NS_DEBUG
25580 	(void) printf("tcp_g_q_destroy()for stack %d\n",
25581 	    tcps->tcps_netstack->netstack_stackid);
25582 #endif
25583 
25584 	if (tcps->tcps_g_q == NULL) {
25585 		return;	/* Nothing to cleanup */
25586 	}
25587 	/*
25588 	 * Drop reference corresponding to the default queue.
25589 	 * This reference was added from tcp_open when the default queue
25590 	 * was created, hence we compensate for this extra drop in
25591 	 * tcp_g_q_close. If the refcnt drops to zero here it means
25592 	 * the default queue was the last one to be open, in which
25593 	 * case, then tcp_g_q_inactive will be
25594 	 * called as a result of the refrele.
25595 	 */
25596 	TCPS_REFRELE(tcps);
25597 }
25598 
25599 /*
25600  * Called when last tcp_t drops reference count using TCPS_REFRELE.
25601  * Run by tcp_q_q_inactive using a taskq.
25602  */
25603 static void
25604 tcp_g_q_close(void *arg)
25605 {
25606 	tcp_stack_t *tcps = arg;
25607 	int error;
25608 	ldi_handle_t	lh = NULL;
25609 	ldi_ident_t	li = NULL;
25610 	cred_t		*cr;
25611 	major_t IP_MAJ;
25612 
25613 	IP_MAJ = ddi_name_to_major(IP);
25614 
25615 #ifdef NS_DEBUG
25616 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
25617 	    tcps->tcps_netstack->netstack_stackid,
25618 	    tcps->tcps_netstack->netstack_refcnt);
25619 #endif
25620 	lh = tcps->tcps_g_q_lh;
25621 	if (lh == NULL)
25622 		return;	/* Nothing to cleanup */
25623 
25624 	ASSERT(tcps->tcps_refcnt == 1);
25625 	ASSERT(tcps->tcps_g_q != NULL);
25626 
25627 	error = ldi_ident_from_major(IP_MAJ, &li);
25628 	if (error) {
25629 #ifdef DEBUG
25630 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
25631 		    error);
25632 #endif
25633 		return;
25634 	}
25635 
25636 	cr = tcps->tcps_g_q_cr;
25637 	tcps->tcps_g_q_cr = NULL;
25638 	ASSERT(cr != NULL);
25639 
25640 	/*
25641 	 * Make sure we can break the recursion when tcp_close decrements
25642 	 * the reference count causing g_q_inactive to be called again.
25643 	 */
25644 	tcps->tcps_g_q_lh = NULL;
25645 
25646 	/* close the default queue */
25647 	(void) ldi_close(lh, FREAD|FWRITE, cr);
25648 	/*
25649 	 * At this point in time tcps and the rest of netstack_t might
25650 	 * have been deleted.
25651 	 */
25652 	tcps = NULL;
25653 
25654 	/* Close layered handles */
25655 	ldi_ident_release(li);
25656 	crfree(cr);
25657 }
25658 
25659 /*
25660  * Called when last tcp_t drops reference count using TCPS_REFRELE.
25661  *
25662  * Have to ensure that the ldi routines are not used by an
25663  * interrupt thread by using a taskq.
25664  */
25665 void
25666 tcp_g_q_inactive(tcp_stack_t *tcps)
25667 {
25668 	if (tcps->tcps_g_q_lh == NULL)
25669 		return;	/* Nothing to cleanup */
25670 
25671 	ASSERT(tcps->tcps_refcnt == 0);
25672 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
25673 
25674 	if (servicing_interrupt()) {
25675 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
25676 		    (void *) tcps, TQ_SLEEP);
25677 	} else {
25678 		tcp_g_q_close(tcps);
25679 	}
25680 }
25681 
25682 /*
25683  * Called by IP when IP is loaded into the kernel
25684  */
25685 void
25686 tcp_ddi_g_init(void)
25687 {
25688 	tcp_timercache = kmem_cache_create("tcp_timercache",
25689 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
25690 	    NULL, NULL, NULL, NULL, NULL, 0);
25691 
25692 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
25693 	    sizeof (tcp_sack_info_t), 0,
25694 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
25695 
25696 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
25697 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
25698 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
25699 
25700 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
25701 
25702 	/* Initialize the random number generator */
25703 	tcp_random_init();
25704 
25705 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
25706 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
25707 
25708 	/* A single callback independently of how many netstacks we have */
25709 	ip_squeue_init(tcp_squeue_add);
25710 
25711 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
25712 
25713 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
25714 	    TASKQ_PREPOPULATE);
25715 
25716 	/*
25717 	 * We want to be informed each time a stack is created or
25718 	 * destroyed in the kernel, so we can maintain the
25719 	 * set of tcp_stack_t's.
25720 	 */
25721 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
25722 	    tcp_stack_fini);
25723 }
25724 
25725 
25726 /*
25727  * Initialize the TCP stack instance.
25728  */
25729 static void *
25730 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
25731 {
25732 	tcp_stack_t	*tcps;
25733 	tcpparam_t	*pa;
25734 	int		i;
25735 
25736 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
25737 	tcps->tcps_netstack = ns;
25738 
25739 	/* Initialize locks */
25740 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
25741 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
25742 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
25743 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
25744 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
25745 	rw_init(&tcps->tcps_reserved_port_lock, NULL, RW_DEFAULT, NULL);
25746 
25747 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
25748 	tcps->tcps_g_epriv_ports[0] = 2049;
25749 	tcps->tcps_g_epriv_ports[1] = 4045;
25750 	tcps->tcps_min_anonpriv_port = 512;
25751 
25752 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
25753 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
25754 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
25755 	    TCP_FANOUT_SIZE, KM_SLEEP);
25756 	tcps->tcps_reserved_port = kmem_zalloc(sizeof (tcp_rport_t) *
25757 	    TCP_RESERVED_PORTS_ARRAY_MAX_SIZE, KM_SLEEP);
25758 
25759 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
25760 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
25761 		    MUTEX_DEFAULT, NULL);
25762 	}
25763 
25764 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25765 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
25766 		    MUTEX_DEFAULT, NULL);
25767 	}
25768 
25769 	/* TCP's IPsec code calls the packet dropper. */
25770 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
25771 
25772 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
25773 	tcps->tcps_params = pa;
25774 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25775 
25776 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
25777 	    A_CNT(lcl_tcp_param_arr), tcps);
25778 
25779 	/*
25780 	 * Note: To really walk the device tree you need the devinfo
25781 	 * pointer to your device which is only available after probe/attach.
25782 	 * The following is safe only because it uses ddi_root_node()
25783 	 */
25784 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
25785 	    tcp_opt_obj.odb_opt_arr_cnt);
25786 
25787 	/*
25788 	 * Initialize RFC 1948 secret values.  This will probably be reset once
25789 	 * by the boot scripts.
25790 	 *
25791 	 * Use NULL name, as the name is caught by the new lockstats.
25792 	 *
25793 	 * Initialize with some random, non-guessable string, like the global
25794 	 * T_INFO_ACK.
25795 	 */
25796 
25797 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
25798 	    sizeof (tcp_g_t_info_ack), tcps);
25799 
25800 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
25801 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
25802 
25803 	return (tcps);
25804 }
25805 
25806 /*
25807  * Called when the IP module is about to be unloaded.
25808  */
25809 void
25810 tcp_ddi_g_destroy(void)
25811 {
25812 	tcp_g_kstat_fini(tcp_g_kstat);
25813 	tcp_g_kstat = NULL;
25814 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
25815 
25816 	mutex_destroy(&tcp_random_lock);
25817 
25818 	kmem_cache_destroy(tcp_timercache);
25819 	kmem_cache_destroy(tcp_sack_info_cache);
25820 	kmem_cache_destroy(tcp_iphc_cache);
25821 
25822 	netstack_unregister(NS_TCP);
25823 	taskq_destroy(tcp_taskq);
25824 }
25825 
25826 /*
25827  * Shut down the TCP stack instance.
25828  */
25829 /* ARGSUSED */
25830 static void
25831 tcp_stack_shutdown(netstackid_t stackid, void *arg)
25832 {
25833 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25834 
25835 	tcp_g_q_destroy(tcps);
25836 }
25837 
25838 /*
25839  * Free the TCP stack instance.
25840  */
25841 static void
25842 tcp_stack_fini(netstackid_t stackid, void *arg)
25843 {
25844 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25845 	int i;
25846 
25847 	nd_free(&tcps->tcps_g_nd);
25848 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25849 	tcps->tcps_params = NULL;
25850 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
25851 	tcps->tcps_wroff_xtra_param = NULL;
25852 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
25853 	tcps->tcps_mdt_head_param = NULL;
25854 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
25855 	tcps->tcps_mdt_tail_param = NULL;
25856 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
25857 	tcps->tcps_mdt_max_pbufs_param = NULL;
25858 
25859 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
25860 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
25861 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
25862 	}
25863 
25864 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25865 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
25866 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
25867 	}
25868 
25869 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
25870 	tcps->tcps_bind_fanout = NULL;
25871 
25872 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
25873 	tcps->tcps_acceptor_fanout = NULL;
25874 
25875 	kmem_free(tcps->tcps_reserved_port, sizeof (tcp_rport_t) *
25876 	    TCP_RESERVED_PORTS_ARRAY_MAX_SIZE);
25877 	tcps->tcps_reserved_port = NULL;
25878 
25879 	mutex_destroy(&tcps->tcps_iss_key_lock);
25880 	rw_destroy(&tcps->tcps_hsp_lock);
25881 	mutex_destroy(&tcps->tcps_g_q_lock);
25882 	cv_destroy(&tcps->tcps_g_q_cv);
25883 	mutex_destroy(&tcps->tcps_epriv_port_lock);
25884 	rw_destroy(&tcps->tcps_reserved_port_lock);
25885 
25886 	ip_drop_unregister(&tcps->tcps_dropper);
25887 
25888 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
25889 	tcps->tcps_kstat = NULL;
25890 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
25891 
25892 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
25893 	tcps->tcps_mibkp = NULL;
25894 
25895 	kmem_free(tcps, sizeof (*tcps));
25896 }
25897 
25898 /*
25899  * Generate ISS, taking into account NDD changes may happen halfway through.
25900  * (If the iss is not zero, set it.)
25901  */
25902 
25903 static void
25904 tcp_iss_init(tcp_t *tcp)
25905 {
25906 	MD5_CTX context;
25907 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
25908 	uint32_t answer[4];
25909 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25910 
25911 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
25912 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
25913 	switch (tcps->tcps_strong_iss) {
25914 	case 2:
25915 		mutex_enter(&tcps->tcps_iss_key_lock);
25916 		context = tcps->tcps_iss_key;
25917 		mutex_exit(&tcps->tcps_iss_key_lock);
25918 		arg.ports = tcp->tcp_ports;
25919 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25920 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
25921 			    &arg.src);
25922 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
25923 			    &arg.dst);
25924 		} else {
25925 			arg.src = tcp->tcp_ip6h->ip6_src;
25926 			arg.dst = tcp->tcp_ip6h->ip6_dst;
25927 		}
25928 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
25929 		MD5Final((uchar_t *)answer, &context);
25930 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
25931 		/*
25932 		 * Now that we've hashed into a unique per-connection sequence
25933 		 * space, add a random increment per strong_iss == 1.  So I
25934 		 * guess we'll have to...
25935 		 */
25936 		/* FALLTHRU */
25937 	case 1:
25938 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
25939 		break;
25940 	default:
25941 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25942 		break;
25943 	}
25944 	tcp->tcp_valid_bits = TCP_ISS_VALID;
25945 	tcp->tcp_fss = tcp->tcp_iss - 1;
25946 	tcp->tcp_suna = tcp->tcp_iss;
25947 	tcp->tcp_snxt = tcp->tcp_iss + 1;
25948 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
25949 	tcp->tcp_csuna = tcp->tcp_snxt;
25950 }
25951 
25952 /*
25953  * Exported routine for extracting active tcp connection status.
25954  *
25955  * This is used by the Solaris Cluster Networking software to
25956  * gather a list of connections that need to be forwarded to
25957  * specific nodes in the cluster when configuration changes occur.
25958  *
25959  * The callback is invoked for each tcp_t structure. Returning
25960  * non-zero from the callback routine terminates the search.
25961  */
25962 int
25963 cl_tcp_walk_list(int (*cl_callback)(cl_tcp_info_t *, void *),
25964     void *arg)
25965 {
25966 	netstack_handle_t nh;
25967 	netstack_t *ns;
25968 	int ret = 0;
25969 
25970 	netstack_next_init(&nh);
25971 	while ((ns = netstack_next(&nh)) != NULL) {
25972 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25973 		    ns->netstack_tcp);
25974 		netstack_rele(ns);
25975 	}
25976 	netstack_next_fini(&nh);
25977 	return (ret);
25978 }
25979 
25980 static int
25981 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25982     tcp_stack_t *tcps)
25983 {
25984 	tcp_t *tcp;
25985 	cl_tcp_info_t	cl_tcpi;
25986 	connf_t	*connfp;
25987 	conn_t	*connp;
25988 	int	i;
25989 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25990 
25991 	ASSERT(callback != NULL);
25992 
25993 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25994 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25995 		connp = NULL;
25996 
25997 		while ((connp =
25998 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25999 
26000 			tcp = connp->conn_tcp;
26001 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
26002 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
26003 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
26004 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
26005 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
26006 			/*
26007 			 * The macros tcp_laddr and tcp_faddr give the IPv4
26008 			 * addresses. They are copied implicitly below as
26009 			 * mapped addresses.
26010 			 */
26011 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
26012 			if (tcp->tcp_ipversion == IPV4_VERSION) {
26013 				cl_tcpi.cl_tcpi_faddr =
26014 				    tcp->tcp_ipha->ipha_dst;
26015 			} else {
26016 				cl_tcpi.cl_tcpi_faddr_v6 =
26017 				    tcp->tcp_ip6h->ip6_dst;
26018 			}
26019 
26020 			/*
26021 			 * If the callback returns non-zero
26022 			 * we terminate the traversal.
26023 			 */
26024 			if ((*callback)(&cl_tcpi, arg) != 0) {
26025 				CONN_DEC_REF(tcp->tcp_connp);
26026 				return (1);
26027 			}
26028 		}
26029 	}
26030 
26031 	return (0);
26032 }
26033 
26034 /*
26035  * Macros used for accessing the different types of sockaddr
26036  * structures inside a tcp_ioc_abort_conn_t.
26037  */
26038 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
26039 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
26040 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
26041 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
26042 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
26043 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
26044 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
26045 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
26046 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
26047 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
26048 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
26049 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
26050 
26051 /*
26052  * Return the correct error code to mimic the behavior
26053  * of a connection reset.
26054  */
26055 #define	TCP_AC_GET_ERRCODE(state, err) {	\
26056 		switch ((state)) {		\
26057 		case TCPS_SYN_SENT:		\
26058 		case TCPS_SYN_RCVD:		\
26059 			(err) = ECONNREFUSED;	\
26060 			break;			\
26061 		case TCPS_ESTABLISHED:		\
26062 		case TCPS_FIN_WAIT_1:		\
26063 		case TCPS_FIN_WAIT_2:		\
26064 		case TCPS_CLOSE_WAIT:		\
26065 			(err) = ECONNRESET;	\
26066 			break;			\
26067 		case TCPS_CLOSING:		\
26068 		case TCPS_LAST_ACK:		\
26069 		case TCPS_TIME_WAIT:		\
26070 			(err) = 0;		\
26071 			break;			\
26072 		default:			\
26073 			(err) = ENXIO;		\
26074 		}				\
26075 	}
26076 
26077 /*
26078  * Check if a tcp structure matches the info in acp.
26079  */
26080 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
26081 	(((acp)->ac_local.ss_family == AF_INET) ?		\
26082 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
26083 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
26084 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
26085 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
26086 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
26087 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
26088 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
26089 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
26090 	(acp)->ac_start <= (tcp)->tcp_state &&	\
26091 	(acp)->ac_end >= (tcp)->tcp_state) :		\
26092 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
26093 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
26094 	&(tcp)->tcp_ip_src_v6)) &&				\
26095 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
26096 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
26097 	&(tcp)->tcp_remote_v6)) &&				\
26098 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
26099 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
26100 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
26101 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
26102 	(acp)->ac_start <= (tcp)->tcp_state &&	\
26103 	(acp)->ac_end >= (tcp)->tcp_state))
26104 
26105 #define	TCP_AC_MATCH(acp, tcp)					\
26106 	(((acp)->ac_zoneid == ALL_ZONES ||			\
26107 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
26108 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
26109 
26110 /*
26111  * Build a message containing a tcp_ioc_abort_conn_t structure
26112  * which is filled in with information from acp and tp.
26113  */
26114 static mblk_t *
26115 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
26116 {
26117 	mblk_t *mp;
26118 	tcp_ioc_abort_conn_t *tacp;
26119 
26120 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
26121 	if (mp == NULL)
26122 		return (NULL);
26123 
26124 	mp->b_datap->db_type = M_CTL;
26125 
26126 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
26127 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
26128 	    sizeof (uint32_t));
26129 
26130 	tacp->ac_start = acp->ac_start;
26131 	tacp->ac_end = acp->ac_end;
26132 	tacp->ac_zoneid = acp->ac_zoneid;
26133 
26134 	if (acp->ac_local.ss_family == AF_INET) {
26135 		tacp->ac_local.ss_family = AF_INET;
26136 		tacp->ac_remote.ss_family = AF_INET;
26137 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
26138 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
26139 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
26140 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
26141 	} else {
26142 		tacp->ac_local.ss_family = AF_INET6;
26143 		tacp->ac_remote.ss_family = AF_INET6;
26144 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
26145 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
26146 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
26147 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
26148 	}
26149 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
26150 	return (mp);
26151 }
26152 
26153 /*
26154  * Print a tcp_ioc_abort_conn_t structure.
26155  */
26156 static void
26157 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
26158 {
26159 	char lbuf[128];
26160 	char rbuf[128];
26161 	sa_family_t af;
26162 	in_port_t lport, rport;
26163 	ushort_t logflags;
26164 
26165 	af = acp->ac_local.ss_family;
26166 
26167 	if (af == AF_INET) {
26168 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
26169 		    lbuf, 128);
26170 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
26171 		    rbuf, 128);
26172 		lport = ntohs(TCP_AC_V4LPORT(acp));
26173 		rport = ntohs(TCP_AC_V4RPORT(acp));
26174 	} else {
26175 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
26176 		    lbuf, 128);
26177 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
26178 		    rbuf, 128);
26179 		lport = ntohs(TCP_AC_V6LPORT(acp));
26180 		rport = ntohs(TCP_AC_V6RPORT(acp));
26181 	}
26182 
26183 	logflags = SL_TRACE | SL_NOTE;
26184 	/*
26185 	 * Don't print this message to the console if the operation was done
26186 	 * to a non-global zone.
26187 	 */
26188 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
26189 		logflags |= SL_CONSOLE;
26190 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
26191 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
26192 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
26193 	    acp->ac_start, acp->ac_end);
26194 }
26195 
26196 /*
26197  * Called inside tcp_rput when a message built using
26198  * tcp_ioctl_abort_build_msg is put into a queue.
26199  * Note that when we get here there is no wildcard in acp any more.
26200  */
26201 static void
26202 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
26203 {
26204 	tcp_ioc_abort_conn_t *acp;
26205 
26206 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
26207 	if (tcp->tcp_state <= acp->ac_end) {
26208 		/*
26209 		 * If we get here, we are already on the correct
26210 		 * squeue. This ioctl follows the following path
26211 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
26212 		 * ->tcp_ioctl_abort->squeue_fill (if on a
26213 		 * different squeue)
26214 		 */
26215 		int errcode;
26216 
26217 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
26218 		(void) tcp_clean_death(tcp, errcode, 26);
26219 	}
26220 	freemsg(mp);
26221 }
26222 
26223 /*
26224  * Abort all matching connections on a hash chain.
26225  */
26226 static int
26227 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
26228     boolean_t exact, tcp_stack_t *tcps)
26229 {
26230 	int nmatch, err = 0;
26231 	tcp_t *tcp;
26232 	MBLKP mp, last, listhead = NULL;
26233 	conn_t	*tconnp;
26234 	connf_t	*connfp;
26235 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
26236 
26237 	connfp = &ipst->ips_ipcl_conn_fanout[index];
26238 
26239 startover:
26240 	nmatch = 0;
26241 
26242 	mutex_enter(&connfp->connf_lock);
26243 	for (tconnp = connfp->connf_head; tconnp != NULL;
26244 	    tconnp = tconnp->conn_next) {
26245 		tcp = tconnp->conn_tcp;
26246 		if (TCP_AC_MATCH(acp, tcp)) {
26247 			CONN_INC_REF(tcp->tcp_connp);
26248 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
26249 			if (mp == NULL) {
26250 				err = ENOMEM;
26251 				CONN_DEC_REF(tcp->tcp_connp);
26252 				break;
26253 			}
26254 			mp->b_prev = (mblk_t *)tcp;
26255 
26256 			if (listhead == NULL) {
26257 				listhead = mp;
26258 				last = mp;
26259 			} else {
26260 				last->b_next = mp;
26261 				last = mp;
26262 			}
26263 			nmatch++;
26264 			if (exact)
26265 				break;
26266 		}
26267 
26268 		/* Avoid holding lock for too long. */
26269 		if (nmatch >= 500)
26270 			break;
26271 	}
26272 	mutex_exit(&connfp->connf_lock);
26273 
26274 	/* Pass mp into the correct tcp */
26275 	while ((mp = listhead) != NULL) {
26276 		listhead = listhead->b_next;
26277 		tcp = (tcp_t *)mp->b_prev;
26278 		mp->b_next = mp->b_prev = NULL;
26279 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
26280 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
26281 	}
26282 
26283 	*count += nmatch;
26284 	if (nmatch >= 500 && err == 0)
26285 		goto startover;
26286 	return (err);
26287 }
26288 
26289 /*
26290  * Abort all connections that matches the attributes specified in acp.
26291  */
26292 static int
26293 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
26294 {
26295 	sa_family_t af;
26296 	uint32_t  ports;
26297 	uint16_t *pports;
26298 	int err = 0, count = 0;
26299 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
26300 	int index = -1;
26301 	ushort_t logflags;
26302 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
26303 
26304 	af = acp->ac_local.ss_family;
26305 
26306 	if (af == AF_INET) {
26307 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
26308 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
26309 			pports = (uint16_t *)&ports;
26310 			pports[1] = TCP_AC_V4LPORT(acp);
26311 			pports[0] = TCP_AC_V4RPORT(acp);
26312 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
26313 		}
26314 	} else {
26315 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
26316 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
26317 			pports = (uint16_t *)&ports;
26318 			pports[1] = TCP_AC_V6LPORT(acp);
26319 			pports[0] = TCP_AC_V6RPORT(acp);
26320 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
26321 		}
26322 	}
26323 
26324 	/*
26325 	 * For cases where remote addr, local port, and remote port are non-
26326 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
26327 	 */
26328 	if (index != -1) {
26329 		err = tcp_ioctl_abort_bucket(acp, index,
26330 		    &count, exact, tcps);
26331 	} else {
26332 		/*
26333 		 * loop through all entries for wildcard case
26334 		 */
26335 		for (index = 0;
26336 		    index < ipst->ips_ipcl_conn_fanout_size;
26337 		    index++) {
26338 			err = tcp_ioctl_abort_bucket(acp, index,
26339 			    &count, exact, tcps);
26340 			if (err != 0)
26341 				break;
26342 		}
26343 	}
26344 
26345 	logflags = SL_TRACE | SL_NOTE;
26346 	/*
26347 	 * Don't print this message to the console if the operation was done
26348 	 * to a non-global zone.
26349 	 */
26350 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
26351 		logflags |= SL_CONSOLE;
26352 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
26353 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
26354 	if (err == 0 && count == 0)
26355 		err = ENOENT;
26356 	return (err);
26357 }
26358 
26359 /*
26360  * Process the TCP_IOC_ABORT_CONN ioctl request.
26361  */
26362 static void
26363 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
26364 {
26365 	int	err;
26366 	IOCP    iocp;
26367 	MBLKP   mp1;
26368 	sa_family_t laf, raf;
26369 	tcp_ioc_abort_conn_t *acp;
26370 	zone_t		*zptr;
26371 	conn_t		*connp = Q_TO_CONN(q);
26372 	zoneid_t	zoneid = connp->conn_zoneid;
26373 	tcp_t		*tcp = connp->conn_tcp;
26374 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26375 
26376 	iocp = (IOCP)mp->b_rptr;
26377 
26378 	if ((mp1 = mp->b_cont) == NULL ||
26379 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
26380 		err = EINVAL;
26381 		goto out;
26382 	}
26383 
26384 	/* check permissions */
26385 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
26386 		err = EPERM;
26387 		goto out;
26388 	}
26389 
26390 	if (mp1->b_cont != NULL) {
26391 		freemsg(mp1->b_cont);
26392 		mp1->b_cont = NULL;
26393 	}
26394 
26395 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
26396 	laf = acp->ac_local.ss_family;
26397 	raf = acp->ac_remote.ss_family;
26398 
26399 	/* check that a zone with the supplied zoneid exists */
26400 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
26401 		zptr = zone_find_by_id(zoneid);
26402 		if (zptr != NULL) {
26403 			zone_rele(zptr);
26404 		} else {
26405 			err = EINVAL;
26406 			goto out;
26407 		}
26408 	}
26409 
26410 	/*
26411 	 * For exclusive stacks we set the zoneid to zero
26412 	 * to make TCP operate as if in the global zone.
26413 	 */
26414 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
26415 		acp->ac_zoneid = GLOBAL_ZONEID;
26416 
26417 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
26418 	    acp->ac_start > acp->ac_end || laf != raf ||
26419 	    (laf != AF_INET && laf != AF_INET6)) {
26420 		err = EINVAL;
26421 		goto out;
26422 	}
26423 
26424 	tcp_ioctl_abort_dump(acp);
26425 	err = tcp_ioctl_abort(acp, tcps);
26426 
26427 out:
26428 	if (mp1 != NULL) {
26429 		freemsg(mp1);
26430 		mp->b_cont = NULL;
26431 	}
26432 
26433 	if (err != 0)
26434 		miocnak(q, mp, 0, err);
26435 	else
26436 		miocack(q, mp, 0, 0);
26437 }
26438 
26439 /*
26440  * tcp_time_wait_processing() handles processing of incoming packets when
26441  * the tcp is in the TIME_WAIT state.
26442  * A TIME_WAIT tcp that has an associated open TCP stream is never put
26443  * on the time wait list.
26444  */
26445 void
26446 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
26447     uint32_t seg_ack, int seg_len, tcph_t *tcph)
26448 {
26449 	int32_t		bytes_acked;
26450 	int32_t		gap;
26451 	int32_t		rgap;
26452 	tcp_opt_t	tcpopt;
26453 	uint_t		flags;
26454 	uint32_t	new_swnd = 0;
26455 	conn_t		*connp;
26456 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26457 
26458 	BUMP_LOCAL(tcp->tcp_ibsegs);
26459 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
26460 
26461 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
26462 	new_swnd = BE16_TO_U16(tcph->th_win) <<
26463 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
26464 	if (tcp->tcp_snd_ts_ok) {
26465 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
26466 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
26467 			    tcp->tcp_rnxt, TH_ACK);
26468 			goto done;
26469 		}
26470 	}
26471 	gap = seg_seq - tcp->tcp_rnxt;
26472 	rgap = tcp->tcp_rwnd - (gap + seg_len);
26473 	if (gap < 0) {
26474 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
26475 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
26476 		    (seg_len > -gap ? -gap : seg_len));
26477 		seg_len += gap;
26478 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
26479 			if (flags & TH_RST) {
26480 				goto done;
26481 			}
26482 			if ((flags & TH_FIN) && seg_len == -1) {
26483 				/*
26484 				 * When TCP receives a duplicate FIN in
26485 				 * TIME_WAIT state, restart the 2 MSL timer.
26486 				 * See page 73 in RFC 793. Make sure this TCP
26487 				 * is already on the TIME_WAIT list. If not,
26488 				 * just restart the timer.
26489 				 */
26490 				if (TCP_IS_DETACHED(tcp)) {
26491 					if (tcp_time_wait_remove(tcp, NULL) ==
26492 					    B_TRUE) {
26493 						tcp_time_wait_append(tcp);
26494 						TCP_DBGSTAT(tcps,
26495 						    tcp_rput_time_wait);
26496 					}
26497 				} else {
26498 					ASSERT(tcp != NULL);
26499 					TCP_TIMER_RESTART(tcp,
26500 					    tcps->tcps_time_wait_interval);
26501 				}
26502 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
26503 				    tcp->tcp_rnxt, TH_ACK);
26504 				goto done;
26505 			}
26506 			flags |=  TH_ACK_NEEDED;
26507 			seg_len = 0;
26508 			goto process_ack;
26509 		}
26510 
26511 		/* Fix seg_seq, and chew the gap off the front. */
26512 		seg_seq = tcp->tcp_rnxt;
26513 	}
26514 
26515 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
26516 		/*
26517 		 * Make sure that when we accept the connection, pick
26518 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
26519 		 * old connection.
26520 		 *
26521 		 * The next ISS generated is equal to tcp_iss_incr_extra
26522 		 * + ISS_INCR/2 + other components depending on the
26523 		 * value of tcp_strong_iss.  We pre-calculate the new
26524 		 * ISS here and compare with tcp_snxt to determine if
26525 		 * we need to make adjustment to tcp_iss_incr_extra.
26526 		 *
26527 		 * The above calculation is ugly and is a
26528 		 * waste of CPU cycles...
26529 		 */
26530 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
26531 		int32_t adj;
26532 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
26533 
26534 		switch (tcps->tcps_strong_iss) {
26535 		case 2: {
26536 			/* Add time and MD5 components. */
26537 			uint32_t answer[4];
26538 			struct {
26539 				uint32_t ports;
26540 				in6_addr_t src;
26541 				in6_addr_t dst;
26542 			} arg;
26543 			MD5_CTX context;
26544 
26545 			mutex_enter(&tcps->tcps_iss_key_lock);
26546 			context = tcps->tcps_iss_key;
26547 			mutex_exit(&tcps->tcps_iss_key_lock);
26548 			arg.ports = tcp->tcp_ports;
26549 			/* We use MAPPED addresses in tcp_iss_init */
26550 			arg.src = tcp->tcp_ip_src_v6;
26551 			if (tcp->tcp_ipversion == IPV4_VERSION) {
26552 				IN6_IPADDR_TO_V4MAPPED(
26553 				    tcp->tcp_ipha->ipha_dst,
26554 				    &arg.dst);
26555 			} else {
26556 				arg.dst =
26557 				    tcp->tcp_ip6h->ip6_dst;
26558 			}
26559 			MD5Update(&context, (uchar_t *)&arg,
26560 			    sizeof (arg));
26561 			MD5Final((uchar_t *)answer, &context);
26562 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
26563 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
26564 			break;
26565 		}
26566 		case 1:
26567 			/* Add time component and min random (i.e. 1). */
26568 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
26569 			break;
26570 		default:
26571 			/* Add only time component. */
26572 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
26573 			break;
26574 		}
26575 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
26576 			/*
26577 			 * New ISS not guaranteed to be ISS_INCR/2
26578 			 * ahead of the current tcp_snxt, so add the
26579 			 * difference to tcp_iss_incr_extra.
26580 			 */
26581 			tcps->tcps_iss_incr_extra += adj;
26582 		}
26583 		/*
26584 		 * If tcp_clean_death() can not perform the task now,
26585 		 * drop the SYN packet and let the other side re-xmit.
26586 		 * Otherwise pass the SYN packet back in, since the
26587 		 * old tcp state has been cleaned up or freed.
26588 		 */
26589 		if (tcp_clean_death(tcp, 0, 27) == -1)
26590 			goto done;
26591 		/*
26592 		 * We will come back to tcp_rput_data
26593 		 * on the global queue. Packets destined
26594 		 * for the global queue will be checked
26595 		 * with global policy. But the policy for
26596 		 * this packet has already been checked as
26597 		 * this was destined for the detached
26598 		 * connection. We need to bypass policy
26599 		 * check this time by attaching a dummy
26600 		 * ipsec_in with ipsec_in_dont_check set.
26601 		 */
26602 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
26603 		if (connp != NULL) {
26604 			TCP_STAT(tcps, tcp_time_wait_syn_success);
26605 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
26606 			return;
26607 		}
26608 		goto done;
26609 	}
26610 
26611 	/*
26612 	 * rgap is the amount of stuff received out of window.  A negative
26613 	 * value is the amount out of window.
26614 	 */
26615 	if (rgap < 0) {
26616 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
26617 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
26618 		/* Fix seg_len and make sure there is something left. */
26619 		seg_len += rgap;
26620 		if (seg_len <= 0) {
26621 			if (flags & TH_RST) {
26622 				goto done;
26623 			}
26624 			flags |=  TH_ACK_NEEDED;
26625 			seg_len = 0;
26626 			goto process_ack;
26627 		}
26628 	}
26629 	/*
26630 	 * Check whether we can update tcp_ts_recent.  This test is
26631 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
26632 	 * Extensions for High Performance: An Update", Internet Draft.
26633 	 */
26634 	if (tcp->tcp_snd_ts_ok &&
26635 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
26636 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
26637 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
26638 		tcp->tcp_last_rcv_lbolt = lbolt64;
26639 	}
26640 
26641 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
26642 		/* Always ack out of order packets */
26643 		flags |= TH_ACK_NEEDED;
26644 		seg_len = 0;
26645 	} else if (seg_len > 0) {
26646 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
26647 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
26648 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
26649 	}
26650 	if (flags & TH_RST) {
26651 		(void) tcp_clean_death(tcp, 0, 28);
26652 		goto done;
26653 	}
26654 	if (flags & TH_SYN) {
26655 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
26656 		    TH_RST|TH_ACK);
26657 		/*
26658 		 * Do not delete the TCP structure if it is in
26659 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
26660 		 */
26661 		goto done;
26662 	}
26663 process_ack:
26664 	if (flags & TH_ACK) {
26665 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
26666 		if (bytes_acked <= 0) {
26667 			if (bytes_acked == 0 && seg_len == 0 &&
26668 			    new_swnd == tcp->tcp_swnd)
26669 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
26670 		} else {
26671 			/* Acks something not sent */
26672 			flags |= TH_ACK_NEEDED;
26673 		}
26674 	}
26675 	if (flags & TH_ACK_NEEDED) {
26676 		/*
26677 		 * Time to send an ack for some reason.
26678 		 */
26679 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
26680 		    tcp->tcp_rnxt, TH_ACK);
26681 	}
26682 done:
26683 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26684 		DB_CKSUMSTART(mp) = 0;
26685 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
26686 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
26687 	}
26688 	freemsg(mp);
26689 }
26690 
26691 /*
26692  * Allocate a T_SVR4_OPTMGMT_REQ.
26693  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
26694  * that tcp_rput_other can drop the acks.
26695  */
26696 static mblk_t *
26697 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
26698 {
26699 	mblk_t *mp;
26700 	struct T_optmgmt_req *tor;
26701 	struct opthdr *oh;
26702 	uint_t size;
26703 	char *optptr;
26704 
26705 	size = sizeof (*tor) + sizeof (*oh) + optlen;
26706 	mp = allocb(size, BPRI_MED);
26707 	if (mp == NULL)
26708 		return (NULL);
26709 
26710 	mp->b_wptr += size;
26711 	mp->b_datap->db_type = M_PROTO;
26712 	tor = (struct T_optmgmt_req *)mp->b_rptr;
26713 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
26714 	tor->MGMT_flags = T_NEGOTIATE;
26715 	tor->OPT_length = sizeof (*oh) + optlen;
26716 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
26717 
26718 	oh = (struct opthdr *)&tor[1];
26719 	oh->level = level;
26720 	oh->name = cmd;
26721 	oh->len = optlen;
26722 	if (optlen != 0) {
26723 		optptr = (char *)&oh[1];
26724 		bcopy(opt, optptr, optlen);
26725 	}
26726 	return (mp);
26727 }
26728 
26729 /*
26730  * TCP Timers Implementation.
26731  */
26732 timeout_id_t
26733 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
26734 {
26735 	mblk_t *mp;
26736 	tcp_timer_t *tcpt;
26737 	tcp_t *tcp = connp->conn_tcp;
26738 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26739 
26740 	ASSERT(connp->conn_sqp != NULL);
26741 
26742 	TCP_DBGSTAT(tcps, tcp_timeout_calls);
26743 
26744 	if (tcp->tcp_timercache == NULL) {
26745 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
26746 	} else {
26747 		TCP_DBGSTAT(tcps, tcp_timeout_cached_alloc);
26748 		mp = tcp->tcp_timercache;
26749 		tcp->tcp_timercache = mp->b_next;
26750 		mp->b_next = NULL;
26751 		ASSERT(mp->b_wptr == NULL);
26752 	}
26753 
26754 	CONN_INC_REF(connp);
26755 	tcpt = (tcp_timer_t *)mp->b_rptr;
26756 	tcpt->connp = connp;
26757 	tcpt->tcpt_proc = f;
26758 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
26759 	return ((timeout_id_t)mp);
26760 }
26761 
26762 static void
26763 tcp_timer_callback(void *arg)
26764 {
26765 	mblk_t *mp = (mblk_t *)arg;
26766 	tcp_timer_t *tcpt;
26767 	conn_t	*connp;
26768 
26769 	tcpt = (tcp_timer_t *)mp->b_rptr;
26770 	connp = tcpt->connp;
26771 	squeue_fill(connp->conn_sqp, mp,
26772 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
26773 }
26774 
26775 static void
26776 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
26777 {
26778 	tcp_timer_t *tcpt;
26779 	conn_t *connp = (conn_t *)arg;
26780 	tcp_t *tcp = connp->conn_tcp;
26781 
26782 	tcpt = (tcp_timer_t *)mp->b_rptr;
26783 	ASSERT(connp == tcpt->connp);
26784 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
26785 
26786 	/*
26787 	 * If the TCP has reached the closed state, don't proceed any
26788 	 * further. This TCP logically does not exist on the system.
26789 	 * tcpt_proc could for example access queues, that have already
26790 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
26791 	 */
26792 	if (tcp->tcp_state != TCPS_CLOSED) {
26793 		(*tcpt->tcpt_proc)(connp);
26794 	} else {
26795 		tcp->tcp_timer_tid = 0;
26796 	}
26797 	tcp_timer_free(connp->conn_tcp, mp);
26798 }
26799 
26800 /*
26801  * There is potential race with untimeout and the handler firing at the same
26802  * time. The mblock may be freed by the handler while we are trying to use
26803  * it. But since both should execute on the same squeue, this race should not
26804  * occur.
26805  */
26806 clock_t
26807 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
26808 {
26809 	mblk_t	*mp = (mblk_t *)id;
26810 	tcp_timer_t *tcpt;
26811 	clock_t delta;
26812 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26813 
26814 	TCP_DBGSTAT(tcps, tcp_timeout_cancel_reqs);
26815 
26816 	if (mp == NULL)
26817 		return (-1);
26818 
26819 	tcpt = (tcp_timer_t *)mp->b_rptr;
26820 	ASSERT(tcpt->connp == connp);
26821 
26822 	delta = untimeout(tcpt->tcpt_tid);
26823 
26824 	if (delta >= 0) {
26825 		TCP_DBGSTAT(tcps, tcp_timeout_canceled);
26826 		tcp_timer_free(connp->conn_tcp, mp);
26827 		CONN_DEC_REF(connp);
26828 	}
26829 
26830 	return (delta);
26831 }
26832 
26833 /*
26834  * Allocate space for the timer event. The allocation looks like mblk, but it is
26835  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
26836  *
26837  * Dealing with failures: If we can't allocate from the timer cache we try
26838  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
26839  * points to b_rptr.
26840  * If we can't allocate anything using allocb_tryhard(), we perform a last
26841  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
26842  * save the actual allocation size in b_datap.
26843  */
26844 mblk_t *
26845 tcp_timermp_alloc(int kmflags)
26846 {
26847 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
26848 	    kmflags & ~KM_PANIC);
26849 
26850 	if (mp != NULL) {
26851 		mp->b_next = mp->b_prev = NULL;
26852 		mp->b_rptr = (uchar_t *)(&mp[1]);
26853 		mp->b_wptr = NULL;
26854 		mp->b_datap = NULL;
26855 		mp->b_queue = NULL;
26856 		mp->b_cont = NULL;
26857 	} else if (kmflags & KM_PANIC) {
26858 		/*
26859 		 * Failed to allocate memory for the timer. Try allocating from
26860 		 * dblock caches.
26861 		 */
26862 		/* ipclassifier calls this from a constructor - hence no tcps */
26863 		TCP_G_STAT(tcp_timermp_allocfail);
26864 		mp = allocb_tryhard(sizeof (tcp_timer_t));
26865 		if (mp == NULL) {
26866 			size_t size = 0;
26867 			/*
26868 			 * Memory is really low. Try tryhard allocation.
26869 			 *
26870 			 * ipclassifier calls this from a constructor -
26871 			 * hence no tcps
26872 			 */
26873 			TCP_G_STAT(tcp_timermp_allocdblfail);
26874 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
26875 			    sizeof (tcp_timer_t), &size, kmflags);
26876 			mp->b_rptr = (uchar_t *)(&mp[1]);
26877 			mp->b_next = mp->b_prev = NULL;
26878 			mp->b_wptr = (uchar_t *)-1;
26879 			mp->b_datap = (dblk_t *)size;
26880 			mp->b_queue = NULL;
26881 			mp->b_cont = NULL;
26882 		}
26883 		ASSERT(mp->b_wptr != NULL);
26884 	}
26885 	/* ipclassifier calls this from a constructor - hence no tcps */
26886 	TCP_G_DBGSTAT(tcp_timermp_alloced);
26887 
26888 	return (mp);
26889 }
26890 
26891 /*
26892  * Free per-tcp timer cache.
26893  * It can only contain entries from tcp_timercache.
26894  */
26895 void
26896 tcp_timermp_free(tcp_t *tcp)
26897 {
26898 	mblk_t *mp;
26899 
26900 	while ((mp = tcp->tcp_timercache) != NULL) {
26901 		ASSERT(mp->b_wptr == NULL);
26902 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
26903 		kmem_cache_free(tcp_timercache, mp);
26904 	}
26905 }
26906 
26907 /*
26908  * Free timer event. Put it on the per-tcp timer cache if there is not too many
26909  * events there already (currently at most two events are cached).
26910  * If the event is not allocated from the timer cache, free it right away.
26911  */
26912 static void
26913 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
26914 {
26915 	mblk_t *mp1 = tcp->tcp_timercache;
26916 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26917 
26918 	if (mp->b_wptr != NULL) {
26919 		/*
26920 		 * This allocation is not from a timer cache, free it right
26921 		 * away.
26922 		 */
26923 		if (mp->b_wptr != (uchar_t *)-1)
26924 			freeb(mp);
26925 		else
26926 			kmem_free(mp, (size_t)mp->b_datap);
26927 	} else if (mp1 == NULL || mp1->b_next == NULL) {
26928 		/* Cache this timer block for future allocations */
26929 		mp->b_rptr = (uchar_t *)(&mp[1]);
26930 		mp->b_next = mp1;
26931 		tcp->tcp_timercache = mp;
26932 	} else {
26933 		kmem_cache_free(tcp_timercache, mp);
26934 		TCP_DBGSTAT(tcps, tcp_timermp_freed);
26935 	}
26936 }
26937 
26938 /*
26939  * End of TCP Timers implementation.
26940  */
26941 
26942 /*
26943  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
26944  * on the specified backing STREAMS q. Note, the caller may make the
26945  * decision to call based on the tcp_t.tcp_flow_stopped value which
26946  * when check outside the q's lock is only an advisory check ...
26947  */
26948 
26949 void
26950 tcp_setqfull(tcp_t *tcp)
26951 {
26952 	queue_t *q = tcp->tcp_wq;
26953 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26954 
26955 	if (!(q->q_flag & QFULL)) {
26956 		mutex_enter(QLOCK(q));
26957 		if (!(q->q_flag & QFULL)) {
26958 			/* still need to set QFULL */
26959 			q->q_flag |= QFULL;
26960 			tcp->tcp_flow_stopped = B_TRUE;
26961 			mutex_exit(QLOCK(q));
26962 			TCP_STAT(tcps, tcp_flwctl_on);
26963 		} else {
26964 			mutex_exit(QLOCK(q));
26965 		}
26966 	}
26967 }
26968 
26969 void
26970 tcp_clrqfull(tcp_t *tcp)
26971 {
26972 	queue_t *q = tcp->tcp_wq;
26973 
26974 	if (q->q_flag & QFULL) {
26975 		mutex_enter(QLOCK(q));
26976 		if (q->q_flag & QFULL) {
26977 			q->q_flag &= ~QFULL;
26978 			tcp->tcp_flow_stopped = B_FALSE;
26979 			mutex_exit(QLOCK(q));
26980 			if (q->q_flag & QWANTW)
26981 				qbackenable(q, 0);
26982 		} else {
26983 			mutex_exit(QLOCK(q));
26984 		}
26985 	}
26986 }
26987 
26988 
26989 /*
26990  * kstats related to squeues i.e. not per IP instance
26991  */
26992 static void *
26993 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26994 {
26995 	kstat_t *ksp;
26996 
26997 	tcp_g_stat_t template = {
26998 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26999 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
27000 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
27001 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
27002 	};
27003 
27004 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
27005 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
27006 	    KSTAT_FLAG_VIRTUAL);
27007 
27008 	if (ksp == NULL)
27009 		return (NULL);
27010 
27011 	bcopy(&template, tcp_g_statp, sizeof (template));
27012 	ksp->ks_data = (void *)tcp_g_statp;
27013 
27014 	kstat_install(ksp);
27015 	return (ksp);
27016 }
27017 
27018 static void
27019 tcp_g_kstat_fini(kstat_t *ksp)
27020 {
27021 	if (ksp != NULL) {
27022 		kstat_delete(ksp);
27023 	}
27024 }
27025 
27026 
27027 static void *
27028 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
27029 {
27030 	kstat_t *ksp;
27031 
27032 	tcp_stat_t template = {
27033 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
27034 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
27035 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
27036 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
27037 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
27038 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
27039 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
27040 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
27041 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
27042 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
27043 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
27044 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
27045 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
27046 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
27047 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
27048 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
27049 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
27050 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
27051 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
27052 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
27053 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
27054 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
27055 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
27056 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
27057 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
27058 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
27059 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
27060 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
27061 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
27062 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
27063 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
27064 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
27065 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
27066 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
27067 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
27068 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
27069 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
27070 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
27071 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
27072 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
27073 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
27074 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
27075 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
27076 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
27077 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
27078 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
27079 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
27080 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
27081 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
27082 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
27083 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
27084 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
27085 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
27086 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
27087 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
27088 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
27089 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
27090 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
27091 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
27092 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
27093 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
27094 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
27095 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
27096 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
27097 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
27098 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
27099 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
27100 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
27101 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
27102 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
27103 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
27104 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
27105 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
27106 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
27107 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
27108 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
27109 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
27110 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
27111 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
27112 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
27113 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
27114 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
27115 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
27116 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
27117 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
27118 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
27119 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
27120 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
27121 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
27122 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
27123 	};
27124 
27125 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
27126 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
27127 	    KSTAT_FLAG_VIRTUAL, stackid);
27128 
27129 	if (ksp == NULL)
27130 		return (NULL);
27131 
27132 	bcopy(&template, tcps_statisticsp, sizeof (template));
27133 	ksp->ks_data = (void *)tcps_statisticsp;
27134 	ksp->ks_private = (void *)(uintptr_t)stackid;
27135 
27136 	kstat_install(ksp);
27137 	return (ksp);
27138 }
27139 
27140 static void
27141 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
27142 {
27143 	if (ksp != NULL) {
27144 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
27145 		kstat_delete_netstack(ksp, stackid);
27146 	}
27147 }
27148 
27149 /*
27150  * TCP Kstats implementation
27151  */
27152 static void *
27153 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
27154 {
27155 	kstat_t	*ksp;
27156 
27157 	tcp_named_kstat_t template = {
27158 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
27159 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
27160 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
27161 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
27162 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
27163 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
27164 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
27165 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
27166 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
27167 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
27168 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
27169 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
27170 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
27171 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
27172 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
27173 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
27174 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
27175 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
27176 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
27177 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
27178 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
27179 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
27180 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
27181 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
27182 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
27183 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
27184 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
27185 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
27186 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
27187 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
27188 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
27189 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
27190 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
27191 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
27192 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
27193 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
27194 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
27195 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
27196 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
27197 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
27198 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
27199 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
27200 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
27201 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
27202 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
27203 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
27204 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
27205 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
27206 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
27207 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
27208 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
27209 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
27210 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
27211 	};
27212 
27213 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
27214 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
27215 
27216 	if (ksp == NULL)
27217 		return (NULL);
27218 
27219 	template.rtoAlgorithm.value.ui32 = 4;
27220 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
27221 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
27222 	template.maxConn.value.i32 = -1;
27223 
27224 	bcopy(&template, ksp->ks_data, sizeof (template));
27225 	ksp->ks_update = tcp_kstat_update;
27226 	ksp->ks_private = (void *)(uintptr_t)stackid;
27227 
27228 	kstat_install(ksp);
27229 	return (ksp);
27230 }
27231 
27232 static void
27233 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
27234 {
27235 	if (ksp != NULL) {
27236 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
27237 		kstat_delete_netstack(ksp, stackid);
27238 	}
27239 }
27240 
27241 static int
27242 tcp_kstat_update(kstat_t *kp, int rw)
27243 {
27244 	tcp_named_kstat_t *tcpkp;
27245 	tcp_t		*tcp;
27246 	connf_t		*connfp;
27247 	conn_t		*connp;
27248 	int 		i;
27249 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
27250 	netstack_t	*ns;
27251 	tcp_stack_t	*tcps;
27252 	ip_stack_t	*ipst;
27253 
27254 	if ((kp == NULL) || (kp->ks_data == NULL))
27255 		return (EIO);
27256 
27257 	if (rw == KSTAT_WRITE)
27258 		return (EACCES);
27259 
27260 	ns = netstack_find_by_stackid(stackid);
27261 	if (ns == NULL)
27262 		return (-1);
27263 	tcps = ns->netstack_tcp;
27264 	if (tcps == NULL) {
27265 		netstack_rele(ns);
27266 		return (-1);
27267 	}
27268 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
27269 
27270 	tcpkp->currEstab.value.ui32 = 0;
27271 
27272 	ipst = ns->netstack_ip;
27273 
27274 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
27275 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
27276 		connp = NULL;
27277 		while ((connp =
27278 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
27279 			tcp = connp->conn_tcp;
27280 			switch (tcp_snmp_state(tcp)) {
27281 			case MIB2_TCP_established:
27282 			case MIB2_TCP_closeWait:
27283 				tcpkp->currEstab.value.ui32++;
27284 				break;
27285 			}
27286 		}
27287 	}
27288 
27289 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
27290 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
27291 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
27292 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
27293 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
27294 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
27295 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
27296 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
27297 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
27298 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
27299 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
27300 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
27301 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
27302 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
27303 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
27304 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
27305 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
27306 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
27307 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
27308 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
27309 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
27310 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
27311 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
27312 	tcpkp->inDataInorderSegs.value.ui32 =
27313 	    tcps->tcps_mib.tcpInDataInorderSegs;
27314 	tcpkp->inDataInorderBytes.value.ui32 =
27315 	    tcps->tcps_mib.tcpInDataInorderBytes;
27316 	tcpkp->inDataUnorderSegs.value.ui32 =
27317 	    tcps->tcps_mib.tcpInDataUnorderSegs;
27318 	tcpkp->inDataUnorderBytes.value.ui32 =
27319 	    tcps->tcps_mib.tcpInDataUnorderBytes;
27320 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
27321 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
27322 	tcpkp->inDataPartDupSegs.value.ui32 =
27323 	    tcps->tcps_mib.tcpInDataPartDupSegs;
27324 	tcpkp->inDataPartDupBytes.value.ui32 =
27325 	    tcps->tcps_mib.tcpInDataPartDupBytes;
27326 	tcpkp->inDataPastWinSegs.value.ui32 =
27327 	    tcps->tcps_mib.tcpInDataPastWinSegs;
27328 	tcpkp->inDataPastWinBytes.value.ui32 =
27329 	    tcps->tcps_mib.tcpInDataPastWinBytes;
27330 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
27331 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
27332 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
27333 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
27334 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
27335 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
27336 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
27337 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
27338 	tcpkp->timKeepaliveProbe.value.ui32 =
27339 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
27340 	tcpkp->timKeepaliveDrop.value.ui32 =
27341 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
27342 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
27343 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
27344 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
27345 	tcpkp->outSackRetransSegs.value.ui32 =
27346 	    tcps->tcps_mib.tcpOutSackRetransSegs;
27347 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
27348 
27349 	netstack_rele(ns);
27350 	return (0);
27351 }
27352 
27353 void
27354 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
27355 {
27356 	uint16_t	hdr_len;
27357 	ipha_t		*ipha;
27358 	uint8_t		*nexthdrp;
27359 	tcph_t		*tcph;
27360 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
27361 
27362 	/* Already has an eager */
27363 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
27364 		TCP_STAT(tcps, tcp_reinput_syn);
27365 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
27366 		    connp, SQTAG_TCP_REINPUT_EAGER);
27367 		return;
27368 	}
27369 
27370 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
27371 	case IPV4_VERSION:
27372 		ipha = (ipha_t *)mp->b_rptr;
27373 		hdr_len = IPH_HDR_LENGTH(ipha);
27374 		break;
27375 	case IPV6_VERSION:
27376 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
27377 		    &hdr_len, &nexthdrp)) {
27378 			CONN_DEC_REF(connp);
27379 			freemsg(mp);
27380 			return;
27381 		}
27382 		break;
27383 	}
27384 
27385 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
27386 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
27387 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
27388 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
27389 	}
27390 
27391 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
27392 	    SQTAG_TCP_REINPUT);
27393 }
27394 
27395 static squeue_func_t
27396 tcp_squeue_switch(int val)
27397 {
27398 	squeue_func_t rval = squeue_fill;
27399 
27400 	switch (val) {
27401 	case 1:
27402 		rval = squeue_enter_nodrain;
27403 		break;
27404 	case 2:
27405 		rval = squeue_enter;
27406 		break;
27407 	default:
27408 		break;
27409 	}
27410 	return (rval);
27411 }
27412 
27413 /*
27414  * This is called once for each squeue - globally for all stack
27415  * instances.
27416  */
27417 static void
27418 tcp_squeue_add(squeue_t *sqp)
27419 {
27420 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
27421 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
27422 
27423 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
27424 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
27425 	    sqp, TCP_TIME_WAIT_DELAY);
27426 	if (tcp_free_list_max_cnt == 0) {
27427 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
27428 		    max_ncpus : boot_max_ncpus);
27429 
27430 		/*
27431 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
27432 		 */
27433 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
27434 		    (tcp_ncpus * sizeof (tcp_t) * 100);
27435 	}
27436 	tcp_time_wait->tcp_free_list_cnt = 0;
27437 }
27438