xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision 7b79d84636ec82b45f00c982cf6810db81852d17)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/strsun.h>
31 #include <sys/strsubr.h>
32 #include <sys/stropts.h>
33 #include <sys/strlog.h>
34 #define	_SUN_TPI_VERSION 2
35 #include <sys/tihdr.h>
36 #include <sys/timod.h>
37 #include <sys/ddi.h>
38 #include <sys/sunddi.h>
39 #include <sys/suntpi.h>
40 #include <sys/xti_inet.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/sdt.h>
44 #include <sys/vtrace.h>
45 #include <sys/kmem.h>
46 #include <sys/ethernet.h>
47 #include <sys/cpuvar.h>
48 #include <sys/dlpi.h>
49 #include <sys/multidata.h>
50 #include <sys/multidata_impl.h>
51 #include <sys/pattr.h>
52 #include <sys/policy.h>
53 #include <sys/priv.h>
54 #include <sys/zone.h>
55 #include <sys/sunldi.h>
56 
57 #include <sys/errno.h>
58 #include <sys/signal.h>
59 #include <sys/socket.h>
60 #include <sys/socketvar.h>
61 #include <sys/sockio.h>
62 #include <sys/isa_defs.h>
63 #include <sys/md5.h>
64 #include <sys/random.h>
65 #include <sys/sodirect.h>
66 #include <sys/uio.h>
67 #include <sys/systm.h>
68 #include <netinet/in.h>
69 #include <netinet/tcp.h>
70 #include <netinet/ip6.h>
71 #include <netinet/icmp6.h>
72 #include <net/if.h>
73 #include <net/route.h>
74 #include <inet/ipsec_impl.h>
75 
76 #include <inet/common.h>
77 #include <inet/ip.h>
78 #include <inet/ip_impl.h>
79 #include <inet/ip6.h>
80 #include <inet/ip_ndp.h>
81 #include <inet/proto_set.h>
82 #include <inet/mib2.h>
83 #include <inet/nd.h>
84 #include <inet/optcom.h>
85 #include <inet/snmpcom.h>
86 #include <inet/kstatcom.h>
87 #include <inet/tcp.h>
88 #include <inet/tcp_impl.h>
89 #include <inet/udp_impl.h>
90 #include <net/pfkeyv2.h>
91 #include <inet/ipsec_info.h>
92 #include <inet/ipdrop.h>
93 
94 #include <inet/ipclassifier.h>
95 #include <inet/ip_ire.h>
96 #include <inet/ip_ftable.h>
97 #include <inet/ip_if.h>
98 #include <inet/ipp_common.h>
99 #include <inet/ip_netinfo.h>
100 #include <sys/squeue_impl.h>
101 #include <sys/squeue.h>
102 #include <inet/kssl/ksslapi.h>
103 #include <sys/tsol/label.h>
104 #include <sys/tsol/tnet.h>
105 #include <rpc/pmap_prot.h>
106 #include <sys/callo.h>
107 
108 /*
109  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
110  *
111  * (Read the detailed design doc in PSARC case directory)
112  *
113  * The entire tcp state is contained in tcp_t and conn_t structure
114  * which are allocated in tandem using ipcl_conn_create() and passing
115  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
116  * the references on the tcp_t. The tcp_t structure is never compressed
117  * and packets always land on the correct TCP perimeter from the time
118  * eager is created till the time tcp_t dies (as such the old mentat
119  * TCP global queue is not used for detached state and no IPSEC checking
120  * is required). The global queue is still allocated to send out resets
121  * for connection which have no listeners and IP directly calls
122  * tcp_xmit_listeners_reset() which does any policy check.
123  *
124  * Protection and Synchronisation mechanism:
125  *
126  * The tcp data structure does not use any kind of lock for protecting
127  * its state but instead uses 'squeues' for mutual exclusion from various
128  * read and write side threads. To access a tcp member, the thread should
129  * always be behind squeue (via squeue_enter with flags as SQ_FILL, SQ_PROCESS,
130  * or SQ_NODRAIN). Since the squeues allow a direct function call, caller
131  * can pass any tcp function having prototype of edesc_t as argument
132  * (different from traditional STREAMs model where packets come in only
133  * designated entry points). The list of functions that can be directly
134  * called via squeue are listed before the usual function prototype.
135  *
136  * Referencing:
137  *
138  * TCP is MT-Hot and we use a reference based scheme to make sure that the
139  * tcp structure doesn't disappear when its needed. When the application
140  * creates an outgoing connection or accepts an incoming connection, we
141  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
142  * The IP reference is just a symbolic reference since ip_tcpclose()
143  * looks at tcp structure after tcp_close_output() returns which could
144  * have dropped the last TCP reference. So as long as the connection is
145  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
146  * conn_t. The classifier puts its own reference when the connection is
147  * inserted in listen or connected hash. Anytime a thread needs to enter
148  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
149  * on write side or by doing a classify on read side and then puts a
150  * reference on the conn before doing squeue_enter/tryenter/fill. For
151  * read side, the classifier itself puts the reference under fanout lock
152  * to make sure that tcp can't disappear before it gets processed. The
153  * squeue will drop this reference automatically so the called function
154  * doesn't have to do a DEC_REF.
155  *
156  * Opening a new connection:
157  *
158  * The outgoing connection open is pretty simple. tcp_open() does the
159  * work in creating the conn/tcp structure and initializing it. The
160  * squeue assignment is done based on the CPU the application
161  * is running on. So for outbound connections, processing is always done
162  * on application CPU which might be different from the incoming CPU
163  * being interrupted by the NIC. An optimal way would be to figure out
164  * the NIC <-> CPU binding at listen time, and assign the outgoing
165  * connection to the squeue attached to the CPU that will be interrupted
166  * for incoming packets (we know the NIC based on the bind IP address).
167  * This might seem like a problem if more data is going out but the
168  * fact is that in most cases the transmit is ACK driven transmit where
169  * the outgoing data normally sits on TCP's xmit queue waiting to be
170  * transmitted.
171  *
172  * Accepting a connection:
173  *
174  * This is a more interesting case because of various races involved in
175  * establishing a eager in its own perimeter. Read the meta comment on
176  * top of tcp_conn_request(). But briefly, the squeue is picked by
177  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
178  *
179  * Closing a connection:
180  *
181  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
182  * via squeue to do the close and mark the tcp as detached if the connection
183  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
184  * reference but tcp_close() drop IP's reference always. So if tcp was
185  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
186  * and 1 because it is in classifier's connected hash. This is the condition
187  * we use to determine that its OK to clean up the tcp outside of squeue
188  * when time wait expires (check the ref under fanout and conn_lock and
189  * if it is 2, remove it from fanout hash and kill it).
190  *
191  * Although close just drops the necessary references and marks the
192  * tcp_detached state, tcp_close needs to know the tcp_detached has been
193  * set (under squeue) before letting the STREAM go away (because a
194  * inbound packet might attempt to go up the STREAM while the close
195  * has happened and tcp_detached is not set). So a special lock and
196  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
197  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
198  * tcp_detached.
199  *
200  * Special provisions and fast paths:
201  *
202  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
203  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
204  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
205  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
206  * check to send packets directly to tcp_rput_data via squeue. Everyone
207  * else comes through tcp_input() on the read side.
208  *
209  * We also make special provisions for sockfs by marking tcp_issocket
210  * whenever we have only sockfs on top of TCP. This allows us to skip
211  * putting the tcp in acceptor hash since a sockfs listener can never
212  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
213  * since eager has already been allocated and the accept now happens
214  * on acceptor STREAM. There is a big blob of comment on top of
215  * tcp_conn_request explaining the new accept. When socket is POP'd,
216  * sockfs sends us an ioctl to mark the fact and we go back to old
217  * behaviour. Once tcp_issocket is unset, its never set for the
218  * life of that connection.
219  *
220  * In support of on-board asynchronous DMA hardware (e.g. Intel I/OAT)
221  * two consoldiation private KAPIs are used to enqueue M_DATA mblk_t's
222  * directly to the socket (sodirect) and start an asynchronous copyout
223  * to a user-land receive-side buffer (uioa) when a blocking socket read
224  * (e.g. read, recv, ...) is pending.
225  *
226  * This is accomplished when tcp_issocket is set and tcp_sodirect is not
227  * NULL so points to an sodirect_t and if marked enabled then we enqueue
228  * all mblk_t's directly to the socket.
229  *
230  * Further, if the sodirect_t sod_uioa and if marked enabled (due to a
231  * blocking socket read, e.g. user-land read, recv, ...) then an asynchronous
232  * copyout will be started directly to the user-land uio buffer. Also, as we
233  * have a pending read, TCP's push logic can take into account the number of
234  * bytes to be received and only awake the blocked read()er when the uioa_t
235  * byte count has been satisfied.
236  *
237  * IPsec notes :
238  *
239  * Since a packet is always executed on the correct TCP perimeter
240  * all IPsec processing is defered to IP including checking new
241  * connections and setting IPSEC policies for new connection. The
242  * only exception is tcp_xmit_listeners_reset() which is called
243  * directly from IP and needs to policy check to see if TH_RST
244  * can be sent out.
245  *
246  * PFHooks notes :
247  *
248  * For mdt case, one meta buffer contains multiple packets. Mblks for every
249  * packet are assembled and passed to the hooks. When packets are blocked,
250  * or boundary of any packet is changed, the mdt processing is stopped, and
251  * packets of the meta buffer are send to the IP path one by one.
252  */
253 
254 /*
255  * Values for squeue switch:
256  * 1: SQ_NODRAIN
257  * 2: SQ_PROCESS
258  * 3: SQ_FILL
259  */
260 int tcp_squeue_wput = 2;	/* /etc/systems */
261 int tcp_squeue_flag;
262 
263 /*
264  * Macros for sodirect:
265  *
266  * SOD_PTR_ENTER(tcp, sodp) - for the tcp_t pointer "tcp" set the
267  * sodirect_t pointer "sodp" to the socket/tcp shared sodirect_t
268  * if it exists and is enabled, else to NULL. Note, in the current
269  * sodirect implementation the sod_lockp must not be held across any
270  * STREAMS call (e.g. putnext) else a "recursive mutex_enter" PANIC
271  * will result as sod_lockp is the streamhead stdata.sd_lock.
272  *
273  * SOD_NOT_ENABLED(tcp) - return true if not a sodirect tcp_t or the
274  * sodirect_t isn't enabled, usefull for ASSERT()ing that a recieve
275  * side tcp code path dealing with a tcp_rcv_list or putnext() isn't
276  * being used when sodirect code paths should be.
277  */
278 
279 #define	SOD_PTR_ENTER(tcp, sodp)					\
280 	(sodp) = (tcp)->tcp_sodirect;					\
281 									\
282 	if ((sodp) != NULL) {						\
283 		mutex_enter((sodp)->sod_lockp);				\
284 		if (!((sodp)->sod_state & SOD_ENABLED)) {		\
285 			mutex_exit((sodp)->sod_lockp);			\
286 			(sodp) = NULL;					\
287 		}							\
288 	}
289 
290 #define	SOD_NOT_ENABLED(tcp)						\
291 	((tcp)->tcp_sodirect == NULL ||					\
292 	    !((tcp)->tcp_sodirect->sod_state & SOD_ENABLED))
293 
294 /*
295  * This controls how tiny a write must be before we try to copy it
296  * into the the mblk on the tail of the transmit queue.  Not much
297  * speedup is observed for values larger than sixteen.  Zero will
298  * disable the optimisation.
299  */
300 int tcp_tx_pull_len = 16;
301 
302 /*
303  * TCP Statistics.
304  *
305  * How TCP statistics work.
306  *
307  * There are two types of statistics invoked by two macros.
308  *
309  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
310  * supposed to be used in non MT-hot paths of the code.
311  *
312  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
313  * supposed to be used for DEBUG purposes and may be used on a hot path.
314  *
315  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
316  * (use "kstat tcp" to get them).
317  *
318  * There is also additional debugging facility that marks tcp_clean_death()
319  * instances and saves them in tcp_t structure. It is triggered by
320  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
321  * tcp_clean_death() calls that counts the number of times each tag was hit. It
322  * is triggered by TCP_CLD_COUNTERS define.
323  *
324  * How to add new counters.
325  *
326  * 1) Add a field in the tcp_stat structure describing your counter.
327  * 2) Add a line in the template in tcp_kstat2_init() with the name
328  *    of the counter.
329  *
330  *    IMPORTANT!! - make sure that both are in sync !!
331  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
332  *
333  * Please avoid using private counters which are not kstat-exported.
334  *
335  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
336  * in tcp_t structure.
337  *
338  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
339  */
340 
341 #ifndef TCP_DEBUG_COUNTER
342 #ifdef DEBUG
343 #define	TCP_DEBUG_COUNTER 1
344 #else
345 #define	TCP_DEBUG_COUNTER 0
346 #endif
347 #endif
348 
349 #define	TCP_CLD_COUNTERS 0
350 
351 #define	TCP_TAG_CLEAN_DEATH 1
352 #define	TCP_MAX_CLEAN_DEATH_TAG 32
353 
354 #ifdef lint
355 static int _lint_dummy_;
356 #endif
357 
358 #if TCP_CLD_COUNTERS
359 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
360 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
361 #elif defined(lint)
362 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
363 #else
364 #define	TCP_CLD_STAT(x)
365 #endif
366 
367 #if TCP_DEBUG_COUNTER
368 #define	TCP_DBGSTAT(tcps, x)	\
369 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
370 #define	TCP_G_DBGSTAT(x)	\
371 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
372 #elif defined(lint)
373 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
374 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
375 #else
376 #define	TCP_DBGSTAT(tcps, x)
377 #define	TCP_G_DBGSTAT(x)
378 #endif
379 
380 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
381 
382 tcp_g_stat_t	tcp_g_statistics;
383 kstat_t		*tcp_g_kstat;
384 
385 /*
386  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
387  * tcp write side.
388  */
389 #define	CALL_IP_WPUT(connp, q, mp) {					\
390 	ASSERT(((q)->q_flag & QREADR) == 0);				\
391 	TCP_DBGSTAT(connp->conn_netstack->netstack_tcp, tcp_ip_output);	\
392 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
393 }
394 
395 /* Macros for timestamp comparisons */
396 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
397 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
398 
399 /*
400  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
401  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
402  * by adding three components: a time component which grows by 1 every 4096
403  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
404  * a per-connection component which grows by 125000 for every new connection;
405  * and an "extra" component that grows by a random amount centered
406  * approximately on 64000.  This causes the the ISS generator to cycle every
407  * 4.89 hours if no TCP connections are made, and faster if connections are
408  * made.
409  *
410  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
411  * components: a time component which grows by 250000 every second; and
412  * a per-connection component which grows by 125000 for every new connections.
413  *
414  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
415  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
416  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
417  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
418  * password.
419  */
420 #define	ISS_INCR	250000
421 #define	ISS_NSEC_SHT	12
422 
423 static sin_t	sin_null;	/* Zero address for quick clears */
424 static sin6_t	sin6_null;	/* Zero address for quick clears */
425 
426 /*
427  * This implementation follows the 4.3BSD interpretation of the urgent
428  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
429  * incompatible changes in protocols like telnet and rlogin.
430  */
431 #define	TCP_OLD_URP_INTERPRETATION	1
432 
433 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
434 	(TCP_IS_DETACHED(tcp) && \
435 	    (!(tcp)->tcp_hard_binding))
436 
437 /*
438  * TCP reassembly macros.  We hide starting and ending sequence numbers in
439  * b_next and b_prev of messages on the reassembly queue.  The messages are
440  * chained using b_cont.  These macros are used in tcp_reass() so we don't
441  * have to see the ugly casts and assignments.
442  */
443 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
444 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
445 					(mblk_t *)(uintptr_t)(u))
446 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
447 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
448 					(mblk_t *)(uintptr_t)(u))
449 
450 /*
451  * Implementation of TCP Timers.
452  * =============================
453  *
454  * INTERFACE:
455  *
456  * There are two basic functions dealing with tcp timers:
457  *
458  *	timeout_id_t	tcp_timeout(connp, func, time)
459  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
460  *	TCP_TIMER_RESTART(tcp, intvl)
461  *
462  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
463  * after 'time' ticks passed. The function called by timeout() must adhere to
464  * the same restrictions as a driver soft interrupt handler - it must not sleep
465  * or call other functions that might sleep. The value returned is the opaque
466  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
467  * cancel the request. The call to tcp_timeout() may fail in which case it
468  * returns zero. This is different from the timeout(9F) function which never
469  * fails.
470  *
471  * The call-back function 'func' always receives 'connp' as its single
472  * argument. It is always executed in the squeue corresponding to the tcp
473  * structure. The tcp structure is guaranteed to be present at the time the
474  * call-back is called.
475  *
476  * NOTE: The call-back function 'func' is never called if tcp is in
477  * 	the TCPS_CLOSED state.
478  *
479  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
480  * request. locks acquired by the call-back routine should not be held across
481  * the call to tcp_timeout_cancel() or a deadlock may result.
482  *
483  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
484  * Otherwise, it returns an integer value greater than or equal to 0. In
485  * particular, if the call-back function is already placed on the squeue, it can
486  * not be canceled.
487  *
488  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
489  * 	within squeue context corresponding to the tcp instance. Since the
490  *	call-back is also called via the same squeue, there are no race
491  *	conditions described in untimeout(9F) manual page since all calls are
492  *	strictly serialized.
493  *
494  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
495  *	stored in tcp_timer_tid and starts a new one using
496  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
497  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
498  *	field.
499  *
500  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
501  *	call-back may still be called, so it is possible tcp_timer() will be
502  *	called several times. This should not be a problem since tcp_timer()
503  *	should always check the tcp instance state.
504  *
505  *
506  * IMPLEMENTATION:
507  *
508  * TCP timers are implemented using three-stage process. The call to
509  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
510  * when the timer expires. The tcp_timer_callback() arranges the call of the
511  * tcp_timer_handler() function via squeue corresponding to the tcp
512  * instance. The tcp_timer_handler() calls actual requested timeout call-back
513  * and passes tcp instance as an argument to it. Information is passed between
514  * stages using the tcp_timer_t structure which contains the connp pointer, the
515  * tcp call-back to call and the timeout id returned by the timeout(9F).
516  *
517  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
518  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
519  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
520  * returns the pointer to this mblk.
521  *
522  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
523  * looks like a normal mblk without actual dblk attached to it.
524  *
525  * To optimize performance each tcp instance holds a small cache of timer
526  * mblocks. In the current implementation it caches up to two timer mblocks per
527  * tcp instance. The cache is preserved over tcp frees and is only freed when
528  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
529  * timer processing happens on a corresponding squeue, the cache manipulation
530  * does not require any locks. Experiments show that majority of timer mblocks
531  * allocations are satisfied from the tcp cache and do not involve kmem calls.
532  *
533  * The tcp_timeout() places a refhold on the connp instance which guarantees
534  * that it will be present at the time the call-back function fires. The
535  * tcp_timer_handler() drops the reference after calling the call-back, so the
536  * call-back function does not need to manipulate the references explicitly.
537  */
538 
539 typedef struct tcp_timer_s {
540 	conn_t	*connp;
541 	void 	(*tcpt_proc)(void *);
542 	callout_id_t   tcpt_tid;
543 } tcp_timer_t;
544 
545 static kmem_cache_t *tcp_timercache;
546 kmem_cache_t	*tcp_sack_info_cache;
547 kmem_cache_t	*tcp_iphc_cache;
548 
549 /*
550  * For scalability, we must not run a timer for every TCP connection
551  * in TIME_WAIT state.  To see why, consider (for time wait interval of
552  * 4 minutes):
553  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
554  *
555  * This list is ordered by time, so you need only delete from the head
556  * until you get to entries which aren't old enough to delete yet.
557  * The list consists of only the detached TIME_WAIT connections.
558  *
559  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
560  * becomes detached TIME_WAIT (either by changing the state and already
561  * being detached or the other way around). This means that the TIME_WAIT
562  * state can be extended (up to doubled) if the connection doesn't become
563  * detached for a long time.
564  *
565  * The list manipulations (including tcp_time_wait_next/prev)
566  * are protected by the tcp_time_wait_lock. The content of the
567  * detached TIME_WAIT connections is protected by the normal perimeters.
568  *
569  * This list is per squeue and squeues are shared across the tcp_stack_t's.
570  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
571  * and conn_netstack.
572  * The tcp_t's that are added to tcp_free_list are disassociated and
573  * have NULL tcp_tcps and conn_netstack pointers.
574  */
575 typedef struct tcp_squeue_priv_s {
576 	kmutex_t	tcp_time_wait_lock;
577 	callout_id_t	tcp_time_wait_tid;
578 	tcp_t		*tcp_time_wait_head;
579 	tcp_t		*tcp_time_wait_tail;
580 	tcp_t		*tcp_free_list;
581 	uint_t		tcp_free_list_cnt;
582 } tcp_squeue_priv_t;
583 
584 /*
585  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
586  * Running it every 5 seconds seems to give the best results.
587  */
588 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
589 
590 /*
591  * To prevent memory hog, limit the number of entries in tcp_free_list
592  * to 1% of available memory / number of cpus
593  */
594 uint_t tcp_free_list_max_cnt = 0;
595 
596 #define	TCP_XMIT_LOWATER	4096
597 #define	TCP_XMIT_HIWATER	49152
598 #define	TCP_RECV_LOWATER	2048
599 #define	TCP_RECV_HIWATER	49152
600 
601 /*
602  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
603  */
604 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
605 
606 #define	TIDUSZ	4096	/* transport interface data unit size */
607 
608 /*
609  * Bind hash list size and has function.  It has to be a power of 2 for
610  * hashing.
611  */
612 #define	TCP_BIND_FANOUT_SIZE	512
613 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
614 /*
615  * Size of listen and acceptor hash list.  It has to be a power of 2 for
616  * hashing.
617  */
618 #define	TCP_FANOUT_SIZE		256
619 
620 #ifdef	_ILP32
621 #define	TCP_ACCEPTOR_HASH(accid)					\
622 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
623 #else
624 #define	TCP_ACCEPTOR_HASH(accid)					\
625 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
626 #endif	/* _ILP32 */
627 
628 #define	IP_ADDR_CACHE_SIZE	2048
629 #define	IP_ADDR_CACHE_HASH(faddr)					\
630 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
631 
632 /*
633  * TCP options struct returned from tcp_parse_options.
634  */
635 typedef struct tcp_opt_s {
636 	uint32_t	tcp_opt_mss;
637 	uint32_t	tcp_opt_wscale;
638 	uint32_t	tcp_opt_ts_val;
639 	uint32_t	tcp_opt_ts_ecr;
640 	tcp_t		*tcp;
641 } tcp_opt_t;
642 
643 /*
644  * TCP option struct passing information b/w lisenter and eager.
645  */
646 struct tcp_options {
647 	uint_t			to_flags;
648 	ssize_t			to_boundif;	/* IPV6_BOUND_IF */
649 };
650 
651 #define	TCPOPT_BOUNDIF		0x00000001	/* set IPV6_BOUND_IF */
652 #define	TCPOPT_RECVPKTINFO	0x00000002	/* set IPV6_RECVPKTINFO */
653 
654 /*
655  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
656  */
657 
658 #ifdef _BIG_ENDIAN
659 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
660 	(TCPOPT_TSTAMP << 8) | 10)
661 #else
662 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
663 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
664 #endif
665 
666 /*
667  * Flags returned from tcp_parse_options.
668  */
669 #define	TCP_OPT_MSS_PRESENT	1
670 #define	TCP_OPT_WSCALE_PRESENT	2
671 #define	TCP_OPT_TSTAMP_PRESENT	4
672 #define	TCP_OPT_SACK_OK_PRESENT	8
673 #define	TCP_OPT_SACK_PRESENT	16
674 
675 /* TCP option length */
676 #define	TCPOPT_NOP_LEN		1
677 #define	TCPOPT_MAXSEG_LEN	4
678 #define	TCPOPT_WS_LEN		3
679 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
680 #define	TCPOPT_TSTAMP_LEN	10
681 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
682 #define	TCPOPT_SACK_OK_LEN	2
683 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
684 #define	TCPOPT_REAL_SACK_LEN	4
685 #define	TCPOPT_MAX_SACK_LEN	36
686 #define	TCPOPT_HEADER_LEN	2
687 
688 /* TCP cwnd burst factor. */
689 #define	TCP_CWND_INFINITE	65535
690 #define	TCP_CWND_SS		3
691 #define	TCP_CWND_NORMAL		5
692 
693 /* Maximum TCP initial cwin (start/restart). */
694 #define	TCP_MAX_INIT_CWND	8
695 
696 /*
697  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
698  * either tcp_slow_start_initial or tcp_slow_start_after idle
699  * depending on the caller.  If the upper layer has not used the
700  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
701  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
702  * If the upper layer has changed set the tcp_init_cwnd, just use
703  * it to calculate the tcp_cwnd.
704  */
705 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
706 {									\
707 	if ((tcp)->tcp_init_cwnd == 0) {				\
708 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
709 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
710 	} else {							\
711 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
712 	}								\
713 	tcp->tcp_cwnd_cnt = 0;						\
714 }
715 
716 /* TCP Timer control structure */
717 typedef struct tcpt_s {
718 	pfv_t	tcpt_pfv;	/* The routine we are to call */
719 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
720 } tcpt_t;
721 
722 /*
723  * Functions called directly via squeue having a prototype of edesc_t.
724  */
725 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
726 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
727 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
728 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
729 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
730 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
731 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
732 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
733 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
734 void		tcp_output_urgent(void *arg, mblk_t *mp, void *arg2);
735 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
736 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
737 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
738 
739 
740 /* Prototype for TCP functions */
741 static void	tcp_random_init(void);
742 int		tcp_random(void);
743 static void	tcp_tli_accept(tcp_t *tcp, mblk_t *mp);
744 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
745 		    tcp_t *eager);
746 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
747 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
748     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
749     boolean_t user_specified);
750 static void	tcp_closei_local(tcp_t *tcp);
751 static void	tcp_close_detached(tcp_t *tcp);
752 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
753 			mblk_t *idmp, mblk_t **defermp);
754 static void	tcp_tpi_connect(tcp_t *tcp, mblk_t *mp);
755 static int	tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
756 		    in_port_t dstport, uint_t srcid, cred_t *cr, pid_t pid);
757 static int 	tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
758 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
759 		    uint32_t scope_id, cred_t *cr, pid_t pid);
760 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
761 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
762 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
763 static char	*tcp_display(tcp_t *tcp, char *, char);
764 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
765 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
766 static void	tcp_eager_unlink(tcp_t *tcp);
767 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
768 		    int unixerr);
769 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
770 		    int tlierr, int unixerr);
771 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
772 		    cred_t *cr);
773 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
774 		    char *value, caddr_t cp, cred_t *cr);
775 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
776 		    char *value, caddr_t cp, cred_t *cr);
777 static int	tcp_tpistate(tcp_t *tcp);
778 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
779     int caller_holds_lock);
780 static void	tcp_bind_hash_remove(tcp_t *tcp);
781 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
782 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
783 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
784 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
785 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
786 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
787 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
788 void		tcp_g_q_setup(tcp_stack_t *);
789 void		tcp_g_q_create(tcp_stack_t *);
790 void		tcp_g_q_destroy(tcp_stack_t *);
791 static int	tcp_header_init_ipv4(tcp_t *tcp);
792 static int	tcp_header_init_ipv6(tcp_t *tcp);
793 int		tcp_init(tcp_t *tcp, queue_t *q);
794 static int	tcp_init_values(tcp_t *tcp);
795 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
796 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
797 static void	tcp_ip_notify(tcp_t *tcp);
798 static mblk_t	*tcp_ire_mp(mblk_t **mpp);
799 static void	tcp_iss_init(tcp_t *tcp);
800 static void	tcp_keepalive_killer(void *arg);
801 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
802 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
803 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
804 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
805 static boolean_t tcp_allow_connopt_set(int level, int name);
806 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
807 int		tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
808 int		tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level,
809 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
810 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
811 		    mblk_t *mblk);
812 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
813 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
814 		    uchar_t *ptr, uint_t len);
815 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
816 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
817     tcp_stack_t *);
818 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
819 		    caddr_t cp, cred_t *cr);
820 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
821 		    caddr_t cp, cred_t *cr);
822 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
823 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
824 		    caddr_t cp, cred_t *cr);
825 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
826 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
827 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
828 static void	tcp_reinit(tcp_t *tcp);
829 static void	tcp_reinit_values(tcp_t *tcp);
830 
831 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
832 static uint_t	tcp_rcv_drain(tcp_t *tcp);
833 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
834 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
835 static void	tcp_ss_rexmit(tcp_t *tcp);
836 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
837 static void	tcp_process_options(tcp_t *, tcph_t *);
838 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
839 static void	tcp_rsrv(queue_t *q);
840 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
841 static int	tcp_snmp_state(tcp_t *tcp);
842 static void	tcp_timer(void *arg);
843 static void	tcp_timer_callback(void *);
844 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
845     boolean_t random);
846 static in_port_t tcp_get_next_priv_port(const tcp_t *);
847 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
848 static void	tcp_wput_fallback(queue_t *q, mblk_t *mp);
849 void		tcp_tpi_accept(queue_t *q, mblk_t *mp);
850 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
851 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
852 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
853 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
854 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
855 		    const int num_sack_blk, int *usable, uint_t *snxt,
856 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
857 		    const int mdt_thres);
858 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
859 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
860 		    const int num_sack_blk, int *usable, uint_t *snxt,
861 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
862 		    const int mdt_thres);
863 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
864 		    int num_sack_blk);
865 static void	tcp_wsrv(queue_t *q);
866 static int	tcp_xmit_end(tcp_t *tcp);
867 static void	tcp_ack_timer(void *arg);
868 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
869 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
870 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
871 		    zoneid_t zoneid, tcp_stack_t *, conn_t *connp);
872 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
873 		    uint32_t ack, int ctl);
874 static int	setmaxps(queue_t *q, int maxpsz);
875 static void	tcp_set_rto(tcp_t *, time_t);
876 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
877 		    boolean_t, boolean_t);
878 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
879 		    boolean_t ipsec_mctl);
880 static int	tcp_build_hdrs(tcp_t *);
881 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
882 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
883 		    tcph_t *tcph);
884 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
885 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
886 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
887 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
888 		    const boolean_t, const uint32_t, const uint32_t,
889 		    const uint32_t, const uint32_t, tcp_stack_t *);
890 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
891 		    const uint_t, const uint_t, boolean_t *);
892 static mblk_t	*tcp_lso_info_mp(mblk_t *);
893 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
894 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
895 extern mblk_t	*tcp_timermp_alloc(int);
896 extern void	tcp_timermp_free(tcp_t *);
897 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
898 static void	tcp_stop_lingering(tcp_t *tcp);
899 static void	tcp_close_linger_timeout(void *arg);
900 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
901 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
902 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
903 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
904 static void	tcp_g_kstat_fini(kstat_t *);
905 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
906 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
907 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
908 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
909 static int	tcp_kstat_update(kstat_t *kp, int rw);
910 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
911 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
912 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
913 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
914 			tcph_t *tcph, mblk_t *idmp);
915 static int	tcp_squeue_switch(int);
916 
917 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
918 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
919 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
920 static int	tcp_tpi_close(queue_t *, int);
921 static int	tcpclose_accept(queue_t *);
922 
923 static void	tcp_squeue_add(squeue_t *);
924 static boolean_t tcp_zcopy_check(tcp_t *);
925 static void	tcp_zcopy_notify(tcp_t *);
926 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
927 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
928 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
929 
930 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
931 
932 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
933 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
934 
935 static int tcp_accept(sock_lower_handle_t, sock_lower_handle_t,
936 	    sock_upper_handle_t, cred_t *);
937 static int tcp_listen(sock_lower_handle_t, int, cred_t *);
938 static int tcp_post_ip_bind(tcp_t *, mblk_t *, int, cred_t *, pid_t);
939 static int tcp_do_listen(conn_t *, int, cred_t *);
940 static int tcp_do_connect(conn_t *, const struct sockaddr *, socklen_t,
941     cred_t *, pid_t);
942 static int tcp_do_bind(conn_t *, struct sockaddr *, socklen_t, cred_t *,
943     boolean_t);
944 static int tcp_do_unbind(conn_t *);
945 static int tcp_bind_check(conn_t *, struct sockaddr *, socklen_t, cred_t *,
946     boolean_t);
947 
948 static void tcp_ulp_newconn(conn_t *, conn_t *, mblk_t *);
949 
950 /*
951  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
952  *
953  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
954  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
955  * (defined in tcp.h) needs to be filled in and passed into the kernel
956  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
957  * structure contains the four-tuple of a TCP connection and a range of TCP
958  * states (specified by ac_start and ac_end). The use of wildcard addresses
959  * and ports is allowed. Connections with a matching four tuple and a state
960  * within the specified range will be aborted. The valid states for the
961  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
962  * inclusive.
963  *
964  * An application which has its connection aborted by this ioctl will receive
965  * an error that is dependent on the connection state at the time of the abort.
966  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
967  * though a RST packet has been received.  If the connection state is equal to
968  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
969  * and all resources associated with the connection will be freed.
970  */
971 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
972 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
973 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
974 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
975 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
976 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
977     boolean_t, tcp_stack_t *);
978 
979 static struct module_info tcp_rinfo =  {
980 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
981 };
982 
983 static struct module_info tcp_winfo =  {
984 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
985 };
986 
987 /*
988  * Entry points for TCP as a device. The normal case which supports
989  * the TCP functionality.
990  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
991  */
992 struct qinit tcp_rinitv4 = {
993 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, NULL, &tcp_rinfo
994 };
995 
996 struct qinit tcp_rinitv6 = {
997 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_tpi_close, NULL, &tcp_rinfo
998 };
999 
1000 struct qinit tcp_winit = {
1001 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1002 };
1003 
1004 /* Initial entry point for TCP in socket mode. */
1005 struct qinit tcp_sock_winit = {
1006 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1007 };
1008 
1009 /* TCP entry point during fallback */
1010 struct qinit tcp_fallback_sock_winit = {
1011 	(pfi_t)tcp_wput_fallback, NULL, NULL, NULL, NULL, &tcp_winfo
1012 };
1013 
1014 /*
1015  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1016  * an accept. Avoid allocating data structures since eager has already
1017  * been created.
1018  */
1019 struct qinit tcp_acceptor_rinit = {
1020 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1021 };
1022 
1023 struct qinit tcp_acceptor_winit = {
1024 	(pfi_t)tcp_tpi_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1025 };
1026 
1027 /*
1028  * Entry points for TCP loopback (read side only)
1029  * The open routine is only used for reopens, thus no need to
1030  * have a separate one for tcp_openv6.
1031  */
1032 struct qinit tcp_loopback_rinit = {
1033 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, (pfi_t)0,
1034 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1035 };
1036 
1037 /* For AF_INET aka /dev/tcp */
1038 struct streamtab tcpinfov4 = {
1039 	&tcp_rinitv4, &tcp_winit
1040 };
1041 
1042 /* For AF_INET6 aka /dev/tcp6 */
1043 struct streamtab tcpinfov6 = {
1044 	&tcp_rinitv6, &tcp_winit
1045 };
1046 
1047 sock_downcalls_t sock_tcp_downcalls;
1048 
1049 /*
1050  * Have to ensure that tcp_g_q_close is not done by an
1051  * interrupt thread.
1052  */
1053 static taskq_t *tcp_taskq;
1054 
1055 /* Setable only in /etc/system. Move to ndd? */
1056 boolean_t tcp_icmp_source_quench = B_FALSE;
1057 
1058 /*
1059  * Following assumes TPI alignment requirements stay along 32 bit
1060  * boundaries
1061  */
1062 #define	ROUNDUP32(x) \
1063 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1064 
1065 /* Template for response to info request. */
1066 static struct T_info_ack tcp_g_t_info_ack = {
1067 	T_INFO_ACK,		/* PRIM_type */
1068 	0,			/* TSDU_size */
1069 	T_INFINITE,		/* ETSDU_size */
1070 	T_INVALID,		/* CDATA_size */
1071 	T_INVALID,		/* DDATA_size */
1072 	sizeof (sin_t),		/* ADDR_size */
1073 	0,			/* OPT_size - not initialized here */
1074 	TIDUSZ,			/* TIDU_size */
1075 	T_COTS_ORD,		/* SERV_type */
1076 	TCPS_IDLE,		/* CURRENT_state */
1077 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1078 };
1079 
1080 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1081 	T_INFO_ACK,		/* PRIM_type */
1082 	0,			/* TSDU_size */
1083 	T_INFINITE,		/* ETSDU_size */
1084 	T_INVALID,		/* CDATA_size */
1085 	T_INVALID,		/* DDATA_size */
1086 	sizeof (sin6_t),	/* ADDR_size */
1087 	0,			/* OPT_size - not initialized here */
1088 	TIDUSZ,		/* TIDU_size */
1089 	T_COTS_ORD,		/* SERV_type */
1090 	TCPS_IDLE,		/* CURRENT_state */
1091 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1092 };
1093 
1094 #define	MS	1L
1095 #define	SECONDS	(1000 * MS)
1096 #define	MINUTES	(60 * SECONDS)
1097 #define	HOURS	(60 * MINUTES)
1098 #define	DAYS	(24 * HOURS)
1099 
1100 #define	PARAM_MAX (~(uint32_t)0)
1101 
1102 /* Max size IP datagram is 64k - 1 */
1103 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1104 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1105 /* Max of the above */
1106 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1107 
1108 /* Largest TCP port number */
1109 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1110 
1111 /*
1112  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1113  * layer header.  It has to be a multiple of 4.
1114  */
1115 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1116 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1117 
1118 /*
1119  * All of these are alterable, within the min/max values given, at run time.
1120  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1121  * per the TCP spec.
1122  */
1123 /* BEGIN CSTYLED */
1124 static tcpparam_t	lcl_tcp_param_arr[] = {
1125  /*min		max		value		name */
1126  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1127  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1128  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1129  { 1,		1024,		1,		"tcp_conn_req_min" },
1130  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1131  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1132  { 0,		10,		0,		"tcp_debug" },
1133  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1134  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1135  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1136  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1137  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1138  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1139  { 1,		255,		64,		"tcp_ipv4_ttl"},
1140  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1141  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1142  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1143  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1144  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1145  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1146  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1147  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1148  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1149  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1150  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1151  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1152  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1153  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1154  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1155  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1156  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1157  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1158  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1159  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1160  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1161  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1162  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1163 /*
1164  * Question:  What default value should I set for tcp_strong_iss?
1165  */
1166  { 0,		2,		1,		"tcp_strong_iss"},
1167  { 0,		65536,		20,		"tcp_rtt_updates"},
1168  { 0,		1,		1,		"tcp_wscale_always"},
1169  { 0,		1,		0,		"tcp_tstamp_always"},
1170  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1171  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1172  { 0,		16,		2,		"tcp_deferred_acks_max"},
1173  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1174  { 1,		4,		4,		"tcp_slow_start_initial"},
1175  { 0,		2,		2,		"tcp_sack_permitted"},
1176  { 0,		1,		1,		"tcp_compression_enabled"},
1177  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1178  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1179  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1180  { 0,		1,		0,		"tcp_rev_src_routes"},
1181  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1182  { 0,		16,		8,		"tcp_local_dacks_max"},
1183  { 0,		2,		1,		"tcp_ecn_permitted"},
1184  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1185  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1186  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1187  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1188  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1189 };
1190 /* END CSTYLED */
1191 
1192 /*
1193  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1194  * each header fragment in the header buffer.  Each parameter value has
1195  * to be a multiple of 4 (32-bit aligned).
1196  */
1197 static tcpparam_t lcl_tcp_mdt_head_param =
1198 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1199 static tcpparam_t lcl_tcp_mdt_tail_param =
1200 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1201 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1202 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1203 
1204 /*
1205  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1206  * the maximum number of payload buffers associated per Multidata.
1207  */
1208 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1209 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1210 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1211 
1212 /* Round up the value to the nearest mss. */
1213 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1214 
1215 /*
1216  * Set ECN capable transport (ECT) code point in IP header.
1217  *
1218  * Note that there are 2 ECT code points '01' and '10', which are called
1219  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1220  * point ECT(0) for TCP as described in RFC 2481.
1221  */
1222 #define	SET_ECT(tcp, iph) \
1223 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1224 		/* We need to clear the code point first. */ \
1225 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1226 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1227 	} else { \
1228 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1229 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1230 	}
1231 
1232 /*
1233  * The format argument to pass to tcp_display().
1234  * DISP_PORT_ONLY means that the returned string has only port info.
1235  * DISP_ADDR_AND_PORT means that the returned string also contains the
1236  * remote and local IP address.
1237  */
1238 #define	DISP_PORT_ONLY		1
1239 #define	DISP_ADDR_AND_PORT	2
1240 
1241 #define	IS_VMLOANED_MBLK(mp) \
1242 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1243 
1244 
1245 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1246 boolean_t tcp_mdt_chain = B_TRUE;
1247 
1248 /*
1249  * MDT threshold in the form of effective send MSS multiplier; we take
1250  * the MDT path if the amount of unsent data exceeds the threshold value
1251  * (default threshold is 1*SMSS).
1252  */
1253 uint_t tcp_mdt_smss_threshold = 1;
1254 
1255 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1256 
1257 /*
1258  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1259  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1260  * determined dynamically during tcp_adapt_ire(), which is the default.
1261  */
1262 boolean_t tcp_static_maxpsz = B_FALSE;
1263 
1264 /* Setable in /etc/system */
1265 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1266 uint32_t tcp_random_anon_port = 1;
1267 
1268 /*
1269  * To reach to an eager in Q0 which can be dropped due to an incoming
1270  * new SYN request when Q0 is full, a new doubly linked list is
1271  * introduced. This list allows to select an eager from Q0 in O(1) time.
1272  * This is needed to avoid spending too much time walking through the
1273  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1274  * this new list has to be a member of Q0.
1275  * This list is headed by listener's tcp_t. When the list is empty,
1276  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1277  * of listener's tcp_t point to listener's tcp_t itself.
1278  *
1279  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1280  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1281  * These macros do not affect the eager's membership to Q0.
1282  */
1283 
1284 
1285 #define	MAKE_DROPPABLE(listener, eager)					\
1286 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1287 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1288 		    = (eager);						\
1289 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1290 		(eager)->tcp_eager_next_drop_q0 =			\
1291 		    (listener)->tcp_eager_next_drop_q0;			\
1292 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1293 	}
1294 
1295 #define	MAKE_UNDROPPABLE(eager)						\
1296 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1297 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1298 		    = (eager)->tcp_eager_prev_drop_q0;			\
1299 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1300 		    = (eager)->tcp_eager_next_drop_q0;			\
1301 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1302 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1303 	}
1304 
1305 /*
1306  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1307  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1308  * data, TCP will not respond with an ACK.  RFC 793 requires that
1309  * TCP responds with an ACK for such a bogus ACK.  By not following
1310  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1311  * an attacker successfully spoofs an acceptable segment to our
1312  * peer; or when our peer is "confused."
1313  */
1314 uint32_t tcp_drop_ack_unsent_cnt = 10;
1315 
1316 /*
1317  * Hook functions to enable cluster networking
1318  * On non-clustered systems these vectors must always be NULL.
1319  */
1320 
1321 void (*cl_inet_listen)(netstackid_t stack_id, uint8_t protocol,
1322 			    sa_family_t addr_family, uint8_t *laddrp,
1323 			    in_port_t lport, void *args) = NULL;
1324 void (*cl_inet_unlisten)(netstackid_t stack_id, uint8_t protocol,
1325 			    sa_family_t addr_family, uint8_t *laddrp,
1326 			    in_port_t lport, void *args) = NULL;
1327 
1328 int (*cl_inet_connect2)(netstackid_t stack_id, uint8_t protocol,
1329 			    boolean_t is_outgoing,
1330 			    sa_family_t addr_family,
1331 			    uint8_t *laddrp, in_port_t lport,
1332 			    uint8_t *faddrp, in_port_t fport,
1333 			    void *args) = NULL;
1334 
1335 void (*cl_inet_disconnect)(netstackid_t stack_id, uint8_t protocol,
1336 			    sa_family_t addr_family, uint8_t *laddrp,
1337 			    in_port_t lport, uint8_t *faddrp,
1338 			    in_port_t fport, void *args) = NULL;
1339 
1340 /*
1341  * The following are defined in ip.c
1342  */
1343 extern int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
1344 			    sa_family_t addr_family, uint8_t *laddrp,
1345 			    void *args);
1346 extern uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
1347 			    sa_family_t addr_family, uint8_t *laddrp,
1348 			    uint8_t *faddrp, void *args);
1349 
1350 
1351 /*
1352  * int CL_INET_CONNECT(conn_t *cp, tcp_t *tcp, boolean_t is_outgoing, int err)
1353  */
1354 #define	CL_INET_CONNECT(connp, tcp, is_outgoing, err) {		\
1355 	(err) = 0;						\
1356 	if (cl_inet_connect2 != NULL) {				\
1357 		/*						\
1358 		 * Running in cluster mode - register active connection	\
1359 		 * information						\
1360 		 */							\
1361 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1362 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1363 				(err) = (*cl_inet_connect2)(		\
1364 				    (connp)->conn_netstack->netstack_stackid,\
1365 				    IPPROTO_TCP, is_outgoing, AF_INET,	\
1366 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1367 				    (in_port_t)(tcp)->tcp_lport,	\
1368 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1369 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1370 			}						\
1371 		} else {						\
1372 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1373 			    &(tcp)->tcp_ip6h->ip6_src)) {		\
1374 				(err) = (*cl_inet_connect2)(		\
1375 				    (connp)->conn_netstack->netstack_stackid,\
1376 				    IPPROTO_TCP, is_outgoing, AF_INET6,	\
1377 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1378 				    (in_port_t)(tcp)->tcp_lport,	\
1379 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1380 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1381 			}						\
1382 		}							\
1383 	}								\
1384 }
1385 
1386 #define	CL_INET_DISCONNECT(connp, tcp)	{				\
1387 	if (cl_inet_disconnect != NULL) {				\
1388 		/*							\
1389 		 * Running in cluster mode - deregister active		\
1390 		 * connection information				\
1391 		 */							\
1392 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1393 			if ((tcp)->tcp_ip_src != 0) {			\
1394 				(*cl_inet_disconnect)(			\
1395 				    (connp)->conn_netstack->netstack_stackid,\
1396 				    IPPROTO_TCP, AF_INET,		\
1397 				    (uint8_t *)(&((tcp)->tcp_ip_src)),	\
1398 				    (in_port_t)(tcp)->tcp_lport,	\
1399 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1400 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1401 			}						\
1402 		} else {						\
1403 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1404 			    &(tcp)->tcp_ip_src_v6)) {			\
1405 				(*cl_inet_disconnect)(			\
1406 				    (connp)->conn_netstack->netstack_stackid,\
1407 				    IPPROTO_TCP, AF_INET6,		\
1408 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1409 				    (in_port_t)(tcp)->tcp_lport,	\
1410 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1411 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1412 			}						\
1413 		}							\
1414 	}								\
1415 }
1416 
1417 /*
1418  * Cluster networking hook for traversing current connection list.
1419  * This routine is used to extract the current list of live connections
1420  * which must continue to to be dispatched to this node.
1421  */
1422 int cl_tcp_walk_list(netstackid_t stack_id,
1423     int (*callback)(cl_tcp_info_t *, void *), void *arg);
1424 
1425 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1426     void *arg, tcp_stack_t *tcps);
1427 
1428 #define	DTRACE_IP_FASTPATH(mp, iph, ill, ipha, ip6h) 			\
1429 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,	\
1430 	    iph, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha,		\
1431 	    ip6_t *, ip6h, int, 0);
1432 
1433 /*
1434  * Figure out the value of window scale opton.  Note that the rwnd is
1435  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1436  * We cannot find the scale value and then do a round up of tcp_rwnd
1437  * because the scale value may not be correct after that.
1438  *
1439  * Set the compiler flag to make this function inline.
1440  */
1441 static void
1442 tcp_set_ws_value(tcp_t *tcp)
1443 {
1444 	int i;
1445 	uint32_t rwnd = tcp->tcp_rwnd;
1446 
1447 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1448 	    i++, rwnd >>= 1)
1449 		;
1450 	tcp->tcp_rcv_ws = i;
1451 }
1452 
1453 /*
1454  * Remove a connection from the list of detached TIME_WAIT connections.
1455  * It returns B_FALSE if it can't remove the connection from the list
1456  * as the connection has already been removed from the list due to an
1457  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1458  */
1459 static boolean_t
1460 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1461 {
1462 	boolean_t	locked = B_FALSE;
1463 
1464 	if (tcp_time_wait == NULL) {
1465 		tcp_time_wait = *((tcp_squeue_priv_t **)
1466 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1467 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1468 		locked = B_TRUE;
1469 	} else {
1470 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1471 	}
1472 
1473 	if (tcp->tcp_time_wait_expire == 0) {
1474 		ASSERT(tcp->tcp_time_wait_next == NULL);
1475 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1476 		if (locked)
1477 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1478 		return (B_FALSE);
1479 	}
1480 	ASSERT(TCP_IS_DETACHED(tcp));
1481 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1482 
1483 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1484 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1485 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1486 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1487 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1488 			    NULL;
1489 		} else {
1490 			tcp_time_wait->tcp_time_wait_tail = NULL;
1491 		}
1492 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1493 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1494 		ASSERT(tcp->tcp_time_wait_next == NULL);
1495 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1496 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1497 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1498 	} else {
1499 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1500 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1501 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1502 		    tcp->tcp_time_wait_next;
1503 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1504 		    tcp->tcp_time_wait_prev;
1505 	}
1506 	tcp->tcp_time_wait_next = NULL;
1507 	tcp->tcp_time_wait_prev = NULL;
1508 	tcp->tcp_time_wait_expire = 0;
1509 
1510 	if (locked)
1511 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1512 	return (B_TRUE);
1513 }
1514 
1515 /*
1516  * Add a connection to the list of detached TIME_WAIT connections
1517  * and set its time to expire.
1518  */
1519 static void
1520 tcp_time_wait_append(tcp_t *tcp)
1521 {
1522 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1523 	tcp_squeue_priv_t *tcp_time_wait =
1524 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1525 	    SQPRIVATE_TCP));
1526 
1527 	tcp_timers_stop(tcp);
1528 
1529 	/* Freed above */
1530 	ASSERT(tcp->tcp_timer_tid == 0);
1531 	ASSERT(tcp->tcp_ack_tid == 0);
1532 
1533 	/* must have happened at the time of detaching the tcp */
1534 	ASSERT(tcp->tcp_ptpahn == NULL);
1535 	ASSERT(tcp->tcp_flow_stopped == 0);
1536 	ASSERT(tcp->tcp_time_wait_next == NULL);
1537 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1538 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1539 	ASSERT(tcp->tcp_listener == NULL);
1540 
1541 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1542 	/*
1543 	 * The value computed below in tcp->tcp_time_wait_expire may
1544 	 * appear negative or wrap around. That is ok since our
1545 	 * interest is only in the difference between the current lbolt
1546 	 * value and tcp->tcp_time_wait_expire. But the value should not
1547 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1548 	 * The corresponding comparison in tcp_time_wait_collector() uses
1549 	 * modular arithmetic.
1550 	 */
1551 	tcp->tcp_time_wait_expire +=
1552 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1553 	if (tcp->tcp_time_wait_expire == 0)
1554 		tcp->tcp_time_wait_expire = 1;
1555 
1556 	ASSERT(TCP_IS_DETACHED(tcp));
1557 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1558 	ASSERT(tcp->tcp_time_wait_next == NULL);
1559 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1560 	TCP_DBGSTAT(tcps, tcp_time_wait);
1561 
1562 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1563 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1564 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1565 		tcp_time_wait->tcp_time_wait_head = tcp;
1566 	} else {
1567 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1568 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1569 		    TCPS_TIME_WAIT);
1570 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1571 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1572 	}
1573 	tcp_time_wait->tcp_time_wait_tail = tcp;
1574 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1575 }
1576 
1577 /* ARGSUSED */
1578 void
1579 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1580 {
1581 	conn_t	*connp = (conn_t *)arg;
1582 	tcp_t	*tcp = connp->conn_tcp;
1583 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1584 
1585 	ASSERT(tcp != NULL);
1586 	if (tcp->tcp_state == TCPS_CLOSED) {
1587 		return;
1588 	}
1589 
1590 	ASSERT((tcp->tcp_family == AF_INET &&
1591 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1592 	    (tcp->tcp_family == AF_INET6 &&
1593 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1594 	    tcp->tcp_ipversion == IPV6_VERSION)));
1595 	ASSERT(!tcp->tcp_listener);
1596 
1597 	TCP_STAT(tcps, tcp_time_wait_reap);
1598 	ASSERT(TCP_IS_DETACHED(tcp));
1599 
1600 	/*
1601 	 * Because they have no upstream client to rebind or tcp_close()
1602 	 * them later, we axe the connection here and now.
1603 	 */
1604 	tcp_close_detached(tcp);
1605 }
1606 
1607 /*
1608  * Remove cached/latched IPsec references.
1609  */
1610 void
1611 tcp_ipsec_cleanup(tcp_t *tcp)
1612 {
1613 	conn_t		*connp = tcp->tcp_connp;
1614 
1615 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1616 
1617 	if (connp->conn_latch != NULL) {
1618 		IPLATCH_REFRELE(connp->conn_latch,
1619 		    connp->conn_netstack);
1620 		connp->conn_latch = NULL;
1621 	}
1622 	if (connp->conn_policy != NULL) {
1623 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1624 		connp->conn_policy = NULL;
1625 	}
1626 }
1627 
1628 /*
1629  * Cleaup before placing on free list.
1630  * Disassociate from the netstack/tcp_stack_t since the freelist
1631  * is per squeue and not per netstack.
1632  */
1633 void
1634 tcp_cleanup(tcp_t *tcp)
1635 {
1636 	mblk_t		*mp;
1637 	char		*tcp_iphc;
1638 	int		tcp_iphc_len;
1639 	int		tcp_hdr_grown;
1640 	tcp_sack_info_t	*tcp_sack_info;
1641 	conn_t		*connp = tcp->tcp_connp;
1642 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1643 	netstack_t	*ns = tcps->tcps_netstack;
1644 	mblk_t		*tcp_rsrv_mp;
1645 
1646 	tcp_bind_hash_remove(tcp);
1647 
1648 	/* Cleanup that which needs the netstack first */
1649 	tcp_ipsec_cleanup(tcp);
1650 
1651 	tcp_free(tcp);
1652 
1653 	/* Release any SSL context */
1654 	if (tcp->tcp_kssl_ent != NULL) {
1655 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1656 		tcp->tcp_kssl_ent = NULL;
1657 	}
1658 
1659 	if (tcp->tcp_kssl_ctx != NULL) {
1660 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1661 		tcp->tcp_kssl_ctx = NULL;
1662 	}
1663 	tcp->tcp_kssl_pending = B_FALSE;
1664 
1665 	conn_delete_ire(connp, NULL);
1666 
1667 	/*
1668 	 * Since we will bzero the entire structure, we need to
1669 	 * remove it and reinsert it in global hash list. We
1670 	 * know the walkers can't get to this conn because we
1671 	 * had set CONDEMNED flag earlier and checked reference
1672 	 * under conn_lock so walker won't pick it and when we
1673 	 * go the ipcl_globalhash_remove() below, no walker
1674 	 * can get to it.
1675 	 */
1676 	ipcl_globalhash_remove(connp);
1677 
1678 	/*
1679 	 * Now it is safe to decrement the reference counts.
1680 	 * This might be the last reference on the netstack and TCPS
1681 	 * in which case it will cause the tcp_g_q_close and
1682 	 * the freeing of the IP Instance.
1683 	 */
1684 	connp->conn_netstack = NULL;
1685 	netstack_rele(ns);
1686 	ASSERT(tcps != NULL);
1687 	tcp->tcp_tcps = NULL;
1688 	TCPS_REFRELE(tcps);
1689 
1690 	/* Save some state */
1691 	mp = tcp->tcp_timercache;
1692 
1693 	tcp_sack_info = tcp->tcp_sack_info;
1694 	tcp_iphc = tcp->tcp_iphc;
1695 	tcp_iphc_len = tcp->tcp_iphc_len;
1696 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1697 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1698 
1699 	if (connp->conn_cred != NULL) {
1700 		crfree(connp->conn_cred);
1701 		connp->conn_cred = NULL;
1702 	}
1703 	if (connp->conn_peercred != NULL) {
1704 		crfree(connp->conn_peercred);
1705 		connp->conn_peercred = NULL;
1706 	}
1707 	ipcl_conn_cleanup(connp);
1708 	connp->conn_flags = IPCL_TCPCONN;
1709 	bzero(tcp, sizeof (tcp_t));
1710 
1711 	/* restore the state */
1712 	tcp->tcp_timercache = mp;
1713 
1714 	tcp->tcp_sack_info = tcp_sack_info;
1715 	tcp->tcp_iphc = tcp_iphc;
1716 	tcp->tcp_iphc_len = tcp_iphc_len;
1717 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1718 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1719 
1720 	tcp->tcp_connp = connp;
1721 
1722 	ASSERT(connp->conn_tcp == tcp);
1723 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1724 	connp->conn_state_flags = CONN_INCIPIENT;
1725 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1726 	ASSERT(connp->conn_ref == 1);
1727 }
1728 
1729 /*
1730  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1731  * is done forwards from the head.
1732  * This walks all stack instances since
1733  * tcp_time_wait remains global across all stacks.
1734  */
1735 /* ARGSUSED */
1736 void
1737 tcp_time_wait_collector(void *arg)
1738 {
1739 	tcp_t *tcp;
1740 	clock_t now;
1741 	mblk_t *mp;
1742 	conn_t *connp;
1743 	kmutex_t *lock;
1744 	boolean_t removed;
1745 
1746 	squeue_t *sqp = (squeue_t *)arg;
1747 	tcp_squeue_priv_t *tcp_time_wait =
1748 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1749 
1750 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1751 	tcp_time_wait->tcp_time_wait_tid = 0;
1752 
1753 	if (tcp_time_wait->tcp_free_list != NULL &&
1754 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1755 		TCP_G_STAT(tcp_freelist_cleanup);
1756 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1757 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1758 			tcp->tcp_time_wait_next = NULL;
1759 			tcp_time_wait->tcp_free_list_cnt--;
1760 			ASSERT(tcp->tcp_tcps == NULL);
1761 			CONN_DEC_REF(tcp->tcp_connp);
1762 		}
1763 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1764 	}
1765 
1766 	/*
1767 	 * In order to reap time waits reliably, we should use a
1768 	 * source of time that is not adjustable by the user -- hence
1769 	 * the call to ddi_get_lbolt().
1770 	 */
1771 	now = ddi_get_lbolt();
1772 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1773 		/*
1774 		 * Compare times using modular arithmetic, since
1775 		 * lbolt can wrapover.
1776 		 */
1777 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1778 			break;
1779 		}
1780 
1781 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1782 		ASSERT(removed);
1783 
1784 		connp = tcp->tcp_connp;
1785 		ASSERT(connp->conn_fanout != NULL);
1786 		lock = &connp->conn_fanout->connf_lock;
1787 		/*
1788 		 * This is essentially a TW reclaim fast path optimization for
1789 		 * performance where the timewait collector checks under the
1790 		 * fanout lock (so that no one else can get access to the
1791 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1792 		 * the classifier hash list. If ref count is indeed 2, we can
1793 		 * just remove the conn under the fanout lock and avoid
1794 		 * cleaning up the conn under the squeue, provided that
1795 		 * clustering callbacks are not enabled. If clustering is
1796 		 * enabled, we need to make the clustering callback before
1797 		 * setting the CONDEMNED flag and after dropping all locks and
1798 		 * so we forego this optimization and fall back to the slow
1799 		 * path. Also please see the comments in tcp_closei_local
1800 		 * regarding the refcnt logic.
1801 		 *
1802 		 * Since we are holding the tcp_time_wait_lock, its better
1803 		 * not to block on the fanout_lock because other connections
1804 		 * can't add themselves to time_wait list. So we do a
1805 		 * tryenter instead of mutex_enter.
1806 		 */
1807 		if (mutex_tryenter(lock)) {
1808 			mutex_enter(&connp->conn_lock);
1809 			if ((connp->conn_ref == 2) &&
1810 			    (cl_inet_disconnect == NULL)) {
1811 				ipcl_hash_remove_locked(connp,
1812 				    connp->conn_fanout);
1813 				/*
1814 				 * Set the CONDEMNED flag now itself so that
1815 				 * the refcnt cannot increase due to any
1816 				 * walker. But we have still not cleaned up
1817 				 * conn_ire_cache. This is still ok since
1818 				 * we are going to clean it up in tcp_cleanup
1819 				 * immediately and any interface unplumb
1820 				 * thread will wait till the ire is blown away
1821 				 */
1822 				connp->conn_state_flags |= CONN_CONDEMNED;
1823 				mutex_exit(lock);
1824 				mutex_exit(&connp->conn_lock);
1825 				if (tcp_time_wait->tcp_free_list_cnt <
1826 				    tcp_free_list_max_cnt) {
1827 					/* Add to head of tcp_free_list */
1828 					mutex_exit(
1829 					    &tcp_time_wait->tcp_time_wait_lock);
1830 					tcp_cleanup(tcp);
1831 					ASSERT(connp->conn_latch == NULL);
1832 					ASSERT(connp->conn_policy == NULL);
1833 					ASSERT(tcp->tcp_tcps == NULL);
1834 					ASSERT(connp->conn_netstack == NULL);
1835 
1836 					mutex_enter(
1837 					    &tcp_time_wait->tcp_time_wait_lock);
1838 					tcp->tcp_time_wait_next =
1839 					    tcp_time_wait->tcp_free_list;
1840 					tcp_time_wait->tcp_free_list = tcp;
1841 					tcp_time_wait->tcp_free_list_cnt++;
1842 					continue;
1843 				} else {
1844 					/* Do not add to tcp_free_list */
1845 					mutex_exit(
1846 					    &tcp_time_wait->tcp_time_wait_lock);
1847 					tcp_bind_hash_remove(tcp);
1848 					conn_delete_ire(tcp->tcp_connp, NULL);
1849 					tcp_ipsec_cleanup(tcp);
1850 					CONN_DEC_REF(tcp->tcp_connp);
1851 				}
1852 			} else {
1853 				CONN_INC_REF_LOCKED(connp);
1854 				mutex_exit(lock);
1855 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1856 				mutex_exit(&connp->conn_lock);
1857 				/*
1858 				 * We can reuse the closemp here since conn has
1859 				 * detached (otherwise we wouldn't even be in
1860 				 * time_wait list). tcp_closemp_used can safely
1861 				 * be changed without taking a lock as no other
1862 				 * thread can concurrently access it at this
1863 				 * point in the connection lifecycle.
1864 				 */
1865 
1866 				if (tcp->tcp_closemp.b_prev == NULL)
1867 					tcp->tcp_closemp_used = B_TRUE;
1868 				else
1869 					cmn_err(CE_PANIC,
1870 					    "tcp_timewait_collector: "
1871 					    "concurrent use of tcp_closemp: "
1872 					    "connp %p tcp %p\n", (void *)connp,
1873 					    (void *)tcp);
1874 
1875 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1876 				mp = &tcp->tcp_closemp;
1877 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1878 				    tcp_timewait_output, connp,
1879 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1880 			}
1881 		} else {
1882 			mutex_enter(&connp->conn_lock);
1883 			CONN_INC_REF_LOCKED(connp);
1884 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1885 			mutex_exit(&connp->conn_lock);
1886 			/*
1887 			 * We can reuse the closemp here since conn has
1888 			 * detached (otherwise we wouldn't even be in
1889 			 * time_wait list). tcp_closemp_used can safely
1890 			 * be changed without taking a lock as no other
1891 			 * thread can concurrently access it at this
1892 			 * point in the connection lifecycle.
1893 			 */
1894 
1895 			if (tcp->tcp_closemp.b_prev == NULL)
1896 				tcp->tcp_closemp_used = B_TRUE;
1897 			else
1898 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1899 				    "concurrent use of tcp_closemp: "
1900 				    "connp %p tcp %p\n", (void *)connp,
1901 				    (void *)tcp);
1902 
1903 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1904 			mp = &tcp->tcp_closemp;
1905 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1906 			    tcp_timewait_output, connp,
1907 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1908 		}
1909 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1910 	}
1911 
1912 	if (tcp_time_wait->tcp_free_list != NULL)
1913 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1914 
1915 	tcp_time_wait->tcp_time_wait_tid =
1916 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1917 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1918 	    CALLOUT_FLAG_ROUNDUP);
1919 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1920 }
1921 
1922 /*
1923  * Reply to a clients T_CONN_RES TPI message. This function
1924  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1925  * on the acceptor STREAM and processed in tcp_wput_accept().
1926  * Read the block comment on top of tcp_conn_request().
1927  */
1928 static void
1929 tcp_tli_accept(tcp_t *listener, mblk_t *mp)
1930 {
1931 	tcp_t	*acceptor;
1932 	tcp_t	*eager;
1933 	tcp_t   *tcp;
1934 	struct T_conn_res	*tcr;
1935 	t_uscalar_t	acceptor_id;
1936 	t_scalar_t	seqnum;
1937 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1938 	struct tcp_options *tcpopt;
1939 	mblk_t	*ok_mp;
1940 	mblk_t	*mp1;
1941 	tcp_stack_t	*tcps = listener->tcp_tcps;
1942 
1943 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1944 		tcp_err_ack(listener, mp, TPROTO, 0);
1945 		return;
1946 	}
1947 	tcr = (struct T_conn_res *)mp->b_rptr;
1948 
1949 	/*
1950 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1951 	 * read side queue of the streams device underneath us i.e. the
1952 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1953 	 * look it up in the queue_hash.  Under LP64 it sends down the
1954 	 * minor_t of the accepting endpoint.
1955 	 *
1956 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1957 	 * fanout hash lock is held.
1958 	 * This prevents any thread from entering the acceptor queue from
1959 	 * below (since it has not been hard bound yet i.e. any inbound
1960 	 * packets will arrive on the listener or default tcp queue and
1961 	 * go through tcp_lookup).
1962 	 * The CONN_INC_REF will prevent the acceptor from closing.
1963 	 *
1964 	 * XXX It is still possible for a tli application to send down data
1965 	 * on the accepting stream while another thread calls t_accept.
1966 	 * This should not be a problem for well-behaved applications since
1967 	 * the T_OK_ACK is sent after the queue swapping is completed.
1968 	 *
1969 	 * If the accepting fd is the same as the listening fd, avoid
1970 	 * queue hash lookup since that will return an eager listener in a
1971 	 * already established state.
1972 	 */
1973 	acceptor_id = tcr->ACCEPTOR_id;
1974 	mutex_enter(&listener->tcp_eager_lock);
1975 	if (listener->tcp_acceptor_id == acceptor_id) {
1976 		eager = listener->tcp_eager_next_q;
1977 		/* only count how many T_CONN_INDs so don't count q0 */
1978 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1979 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1980 			mutex_exit(&listener->tcp_eager_lock);
1981 			tcp_err_ack(listener, mp, TBADF, 0);
1982 			return;
1983 		}
1984 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1985 			/* Throw away all the eagers on q0. */
1986 			tcp_eager_cleanup(listener, 1);
1987 		}
1988 		if (listener->tcp_syn_defense) {
1989 			listener->tcp_syn_defense = B_FALSE;
1990 			if (listener->tcp_ip_addr_cache != NULL) {
1991 				kmem_free(listener->tcp_ip_addr_cache,
1992 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1993 				listener->tcp_ip_addr_cache = NULL;
1994 			}
1995 		}
1996 		/*
1997 		 * Transfer tcp_conn_req_max to the eager so that when
1998 		 * a disconnect occurs we can revert the endpoint to the
1999 		 * listen state.
2000 		 */
2001 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
2002 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
2003 		/*
2004 		 * Get a reference on the acceptor just like the
2005 		 * tcp_acceptor_hash_lookup below.
2006 		 */
2007 		acceptor = listener;
2008 		CONN_INC_REF(acceptor->tcp_connp);
2009 	} else {
2010 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
2011 		if (acceptor == NULL) {
2012 			if (listener->tcp_debug) {
2013 				(void) strlog(TCP_MOD_ID, 0, 1,
2014 				    SL_ERROR|SL_TRACE,
2015 				    "tcp_accept: did not find acceptor 0x%x\n",
2016 				    acceptor_id);
2017 			}
2018 			mutex_exit(&listener->tcp_eager_lock);
2019 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2020 			return;
2021 		}
2022 		/*
2023 		 * Verify acceptor state. The acceptable states for an acceptor
2024 		 * include TCPS_IDLE and TCPS_BOUND.
2025 		 */
2026 		switch (acceptor->tcp_state) {
2027 		case TCPS_IDLE:
2028 			/* FALLTHRU */
2029 		case TCPS_BOUND:
2030 			break;
2031 		default:
2032 			CONN_DEC_REF(acceptor->tcp_connp);
2033 			mutex_exit(&listener->tcp_eager_lock);
2034 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2035 			return;
2036 		}
2037 	}
2038 
2039 	/* The listener must be in TCPS_LISTEN */
2040 	if (listener->tcp_state != TCPS_LISTEN) {
2041 		CONN_DEC_REF(acceptor->tcp_connp);
2042 		mutex_exit(&listener->tcp_eager_lock);
2043 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2044 		return;
2045 	}
2046 
2047 	/*
2048 	 * Rendezvous with an eager connection request packet hanging off
2049 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2050 	 * tcp structure when the connection packet arrived in
2051 	 * tcp_conn_request().
2052 	 */
2053 	seqnum = tcr->SEQ_number;
2054 	eager = listener;
2055 	do {
2056 		eager = eager->tcp_eager_next_q;
2057 		if (eager == NULL) {
2058 			CONN_DEC_REF(acceptor->tcp_connp);
2059 			mutex_exit(&listener->tcp_eager_lock);
2060 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2061 			return;
2062 		}
2063 	} while (eager->tcp_conn_req_seqnum != seqnum);
2064 	mutex_exit(&listener->tcp_eager_lock);
2065 
2066 	/*
2067 	 * At this point, both acceptor and listener have 2 ref
2068 	 * that they begin with. Acceptor has one additional ref
2069 	 * we placed in lookup while listener has 3 additional
2070 	 * ref for being behind the squeue (tcp_accept() is
2071 	 * done on listener's squeue); being in classifier hash;
2072 	 * and eager's ref on listener.
2073 	 */
2074 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2075 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2076 
2077 	/*
2078 	 * The eager at this point is set in its own squeue and
2079 	 * could easily have been killed (tcp_accept_finish will
2080 	 * deal with that) because of a TH_RST so we can only
2081 	 * ASSERT for a single ref.
2082 	 */
2083 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2084 
2085 	/* Pre allocate the stroptions mblk also */
2086 	opt_mp = allocb(MAX(sizeof (struct tcp_options),
2087 	    sizeof (struct T_conn_res)), BPRI_HI);
2088 	if (opt_mp == NULL) {
2089 		CONN_DEC_REF(acceptor->tcp_connp);
2090 		CONN_DEC_REF(eager->tcp_connp);
2091 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2092 		return;
2093 	}
2094 	DB_TYPE(opt_mp) = M_SETOPTS;
2095 	opt_mp->b_wptr += sizeof (struct tcp_options);
2096 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
2097 	tcpopt->to_flags = 0;
2098 
2099 	/*
2100 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2101 	 * from listener to acceptor.
2102 	 */
2103 	if (listener->tcp_bound_if != 0) {
2104 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
2105 		tcpopt->to_boundif = listener->tcp_bound_if;
2106 	}
2107 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2108 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
2109 	}
2110 
2111 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2112 	if ((mp1 = copymsg(mp)) == NULL) {
2113 		CONN_DEC_REF(acceptor->tcp_connp);
2114 		CONN_DEC_REF(eager->tcp_connp);
2115 		freemsg(opt_mp);
2116 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2117 		return;
2118 	}
2119 
2120 	tcr = (struct T_conn_res *)mp1->b_rptr;
2121 
2122 	/*
2123 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2124 	 * which allocates a larger mblk and appends the new
2125 	 * local address to the ok_ack.  The address is copied by
2126 	 * soaccept() for getsockname().
2127 	 */
2128 	{
2129 		int extra;
2130 
2131 		extra = (eager->tcp_family == AF_INET) ?
2132 		    sizeof (sin_t) : sizeof (sin6_t);
2133 
2134 		/*
2135 		 * Try to re-use mp, if possible.  Otherwise, allocate
2136 		 * an mblk and return it as ok_mp.  In any case, mp
2137 		 * is no longer usable upon return.
2138 		 */
2139 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2140 			CONN_DEC_REF(acceptor->tcp_connp);
2141 			CONN_DEC_REF(eager->tcp_connp);
2142 			freemsg(opt_mp);
2143 			/* Original mp has been freed by now, so use mp1 */
2144 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2145 			return;
2146 		}
2147 
2148 		mp = NULL;	/* We should never use mp after this point */
2149 
2150 		switch (extra) {
2151 		case sizeof (sin_t): {
2152 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2153 
2154 				ok_mp->b_wptr += extra;
2155 				sin->sin_family = AF_INET;
2156 				sin->sin_port = eager->tcp_lport;
2157 				sin->sin_addr.s_addr =
2158 				    eager->tcp_ipha->ipha_src;
2159 				break;
2160 			}
2161 		case sizeof (sin6_t): {
2162 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2163 
2164 				ok_mp->b_wptr += extra;
2165 				sin6->sin6_family = AF_INET6;
2166 				sin6->sin6_port = eager->tcp_lport;
2167 				if (eager->tcp_ipversion == IPV4_VERSION) {
2168 					sin6->sin6_flowinfo = 0;
2169 					IN6_IPADDR_TO_V4MAPPED(
2170 					    eager->tcp_ipha->ipha_src,
2171 					    &sin6->sin6_addr);
2172 				} else {
2173 					ASSERT(eager->tcp_ip6h != NULL);
2174 					sin6->sin6_flowinfo =
2175 					    eager->tcp_ip6h->ip6_vcf &
2176 					    ~IPV6_VERS_AND_FLOW_MASK;
2177 					sin6->sin6_addr =
2178 					    eager->tcp_ip6h->ip6_src;
2179 				}
2180 				sin6->sin6_scope_id = 0;
2181 				sin6->__sin6_src_id = 0;
2182 				break;
2183 			}
2184 		default:
2185 			break;
2186 		}
2187 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2188 	}
2189 
2190 	/*
2191 	 * If there are no options we know that the T_CONN_RES will
2192 	 * succeed. However, we can't send the T_OK_ACK upstream until
2193 	 * the tcp_accept_swap is done since it would be dangerous to
2194 	 * let the application start using the new fd prior to the swap.
2195 	 */
2196 	tcp_accept_swap(listener, acceptor, eager);
2197 
2198 	/*
2199 	 * tcp_accept_swap unlinks eager from listener but does not drop
2200 	 * the eager's reference on the listener.
2201 	 */
2202 	ASSERT(eager->tcp_listener == NULL);
2203 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2204 
2205 	/*
2206 	 * The eager is now associated with its own queue. Insert in
2207 	 * the hash so that the connection can be reused for a future
2208 	 * T_CONN_RES.
2209 	 */
2210 	tcp_acceptor_hash_insert(acceptor_id, eager);
2211 
2212 	/*
2213 	 * We now do the processing of options with T_CONN_RES.
2214 	 * We delay till now since we wanted to have queue to pass to
2215 	 * option processing routines that points back to the right
2216 	 * instance structure which does not happen until after
2217 	 * tcp_accept_swap().
2218 	 *
2219 	 * Note:
2220 	 * The sanity of the logic here assumes that whatever options
2221 	 * are appropriate to inherit from listner=>eager are done
2222 	 * before this point, and whatever were to be overridden (or not)
2223 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2224 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2225 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2226 	 * This may not be true at this point in time but can be fixed
2227 	 * independently. This option processing code starts with
2228 	 * the instantiated acceptor instance and the final queue at
2229 	 * this point.
2230 	 */
2231 
2232 	if (tcr->OPT_length != 0) {
2233 		/* Options to process */
2234 		int t_error = 0;
2235 		int sys_error = 0;
2236 		int do_disconnect = 0;
2237 
2238 		if (tcp_conprim_opt_process(eager, mp1,
2239 		    &do_disconnect, &t_error, &sys_error) < 0) {
2240 			eager->tcp_accept_error = 1;
2241 			if (do_disconnect) {
2242 				/*
2243 				 * An option failed which does not allow
2244 				 * connection to be accepted.
2245 				 *
2246 				 * We allow T_CONN_RES to succeed and
2247 				 * put a T_DISCON_IND on the eager queue.
2248 				 */
2249 				ASSERT(t_error == 0 && sys_error == 0);
2250 				eager->tcp_send_discon_ind = 1;
2251 			} else {
2252 				ASSERT(t_error != 0);
2253 				freemsg(ok_mp);
2254 				/*
2255 				 * Original mp was either freed or set
2256 				 * to ok_mp above, so use mp1 instead.
2257 				 */
2258 				tcp_err_ack(listener, mp1, t_error, sys_error);
2259 				goto finish;
2260 			}
2261 		}
2262 		/*
2263 		 * Most likely success in setting options (except if
2264 		 * eager->tcp_send_discon_ind set).
2265 		 * mp1 option buffer represented by OPT_length/offset
2266 		 * potentially modified and contains results of setting
2267 		 * options at this point
2268 		 */
2269 	}
2270 
2271 	/* We no longer need mp1, since all options processing has passed */
2272 	freemsg(mp1);
2273 
2274 	putnext(listener->tcp_rq, ok_mp);
2275 
2276 	mutex_enter(&listener->tcp_eager_lock);
2277 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2278 		tcp_t	*tail;
2279 		mblk_t	*conn_ind;
2280 
2281 		/*
2282 		 * This path should not be executed if listener and
2283 		 * acceptor streams are the same.
2284 		 */
2285 		ASSERT(listener != acceptor);
2286 
2287 		tcp = listener->tcp_eager_prev_q0;
2288 		/*
2289 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2290 		 * deferred T_conn_ind queue. We need to get to the head of
2291 		 * the queue in order to send up T_conn_ind the same order as
2292 		 * how the 3WHS is completed.
2293 		 */
2294 		while (tcp != listener) {
2295 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2296 				break;
2297 			else
2298 				tcp = tcp->tcp_eager_prev_q0;
2299 		}
2300 		ASSERT(tcp != listener);
2301 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2302 		ASSERT(conn_ind != NULL);
2303 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2304 
2305 		/* Move from q0 to q */
2306 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2307 		listener->tcp_conn_req_cnt_q0--;
2308 		listener->tcp_conn_req_cnt_q++;
2309 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2310 		    tcp->tcp_eager_prev_q0;
2311 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2312 		    tcp->tcp_eager_next_q0;
2313 		tcp->tcp_eager_prev_q0 = NULL;
2314 		tcp->tcp_eager_next_q0 = NULL;
2315 		tcp->tcp_conn_def_q0 = B_FALSE;
2316 
2317 		/* Make sure the tcp isn't in the list of droppables */
2318 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2319 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2320 
2321 		/*
2322 		 * Insert at end of the queue because sockfs sends
2323 		 * down T_CONN_RES in chronological order. Leaving
2324 		 * the older conn indications at front of the queue
2325 		 * helps reducing search time.
2326 		 */
2327 		tail = listener->tcp_eager_last_q;
2328 		if (tail != NULL)
2329 			tail->tcp_eager_next_q = tcp;
2330 		else
2331 			listener->tcp_eager_next_q = tcp;
2332 		listener->tcp_eager_last_q = tcp;
2333 		tcp->tcp_eager_next_q = NULL;
2334 		mutex_exit(&listener->tcp_eager_lock);
2335 		putnext(tcp->tcp_rq, conn_ind);
2336 	} else {
2337 		mutex_exit(&listener->tcp_eager_lock);
2338 	}
2339 
2340 	/*
2341 	 * Done with the acceptor - free it
2342 	 *
2343 	 * Note: from this point on, no access to listener should be made
2344 	 * as listener can be equal to acceptor.
2345 	 */
2346 finish:
2347 	ASSERT(acceptor->tcp_detached);
2348 	ASSERT(tcps->tcps_g_q != NULL);
2349 	ASSERT(!IPCL_IS_NONSTR(acceptor->tcp_connp));
2350 	acceptor->tcp_rq = tcps->tcps_g_q;
2351 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2352 	(void) tcp_clean_death(acceptor, 0, 2);
2353 	CONN_DEC_REF(acceptor->tcp_connp);
2354 
2355 	/*
2356 	 * In case we already received a FIN we have to make tcp_rput send
2357 	 * the ordrel_ind. This will also send up a window update if the window
2358 	 * has opened up.
2359 	 *
2360 	 * In the normal case of a successful connection acceptance
2361 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2362 	 * indication that this was just accepted. This tells tcp_rput to
2363 	 * pass up any data queued in tcp_rcv_list.
2364 	 *
2365 	 * In the fringe case where options sent with T_CONN_RES failed and
2366 	 * we required, we would be indicating a T_DISCON_IND to blow
2367 	 * away this connection.
2368 	 */
2369 
2370 	/*
2371 	 * XXX: we currently have a problem if XTI application closes the
2372 	 * acceptor stream in between. This problem exists in on10-gate also
2373 	 * and is well know but nothing can be done short of major rewrite
2374 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2375 	 * eager same squeue as listener (we can distinguish non socket
2376 	 * listeners at the time of handling a SYN in tcp_conn_request)
2377 	 * and do most of the work that tcp_accept_finish does here itself
2378 	 * and then get behind the acceptor squeue to access the acceptor
2379 	 * queue.
2380 	 */
2381 	/*
2382 	 * We already have a ref on tcp so no need to do one before squeue_enter
2383 	 */
2384 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, opt_mp, tcp_accept_finish,
2385 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_ACCEPT_FINISH);
2386 }
2387 
2388 /*
2389  * Swap information between the eager and acceptor for a TLI/XTI client.
2390  * The sockfs accept is done on the acceptor stream and control goes
2391  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2392  * called. In either case, both the eager and listener are in their own
2393  * perimeter (squeue) and the code has to deal with potential race.
2394  *
2395  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2396  */
2397 static void
2398 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2399 {
2400 	conn_t	*econnp, *aconnp;
2401 
2402 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2403 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2404 	ASSERT(!eager->tcp_hard_bound);
2405 	ASSERT(!TCP_IS_SOCKET(acceptor));
2406 	ASSERT(!TCP_IS_SOCKET(eager));
2407 	ASSERT(!TCP_IS_SOCKET(listener));
2408 
2409 	acceptor->tcp_detached = B_TRUE;
2410 	/*
2411 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2412 	 * the acceptor id.
2413 	 */
2414 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2415 
2416 	/* remove eager from listen list... */
2417 	mutex_enter(&listener->tcp_eager_lock);
2418 	tcp_eager_unlink(eager);
2419 	ASSERT(eager->tcp_eager_next_q == NULL &&
2420 	    eager->tcp_eager_last_q == NULL);
2421 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2422 	    eager->tcp_eager_prev_q0 == NULL);
2423 	mutex_exit(&listener->tcp_eager_lock);
2424 	eager->tcp_rq = acceptor->tcp_rq;
2425 	eager->tcp_wq = acceptor->tcp_wq;
2426 
2427 	econnp = eager->tcp_connp;
2428 	aconnp = acceptor->tcp_connp;
2429 
2430 	eager->tcp_rq->q_ptr = econnp;
2431 	eager->tcp_wq->q_ptr = econnp;
2432 
2433 	/*
2434 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2435 	 * which might be a different squeue from our peer TCP instance.
2436 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2437 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2438 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2439 	 * above reach global visibility prior to the clearing of tcp_detached.
2440 	 */
2441 	membar_producer();
2442 	eager->tcp_detached = B_FALSE;
2443 
2444 	ASSERT(eager->tcp_ack_tid == 0);
2445 
2446 	econnp->conn_dev = aconnp->conn_dev;
2447 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2448 	ASSERT(econnp->conn_minor_arena != NULL);
2449 	if (eager->tcp_cred != NULL)
2450 		crfree(eager->tcp_cred);
2451 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2452 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2453 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2454 
2455 	aconnp->conn_cred = NULL;
2456 
2457 	econnp->conn_zoneid = aconnp->conn_zoneid;
2458 	econnp->conn_allzones = aconnp->conn_allzones;
2459 
2460 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2461 	aconnp->conn_mac_exempt = B_FALSE;
2462 
2463 	ASSERT(aconnp->conn_peercred == NULL);
2464 
2465 	/* Do the IPC initialization */
2466 	CONN_INC_REF(econnp);
2467 
2468 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2469 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2470 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2471 
2472 	/* Done with old IPC. Drop its ref on its connp */
2473 	CONN_DEC_REF(aconnp);
2474 }
2475 
2476 
2477 /*
2478  * Adapt to the information, such as rtt and rtt_sd, provided from the
2479  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2480  *
2481  * Checks for multicast and broadcast destination address.
2482  * Returns zero on failure; non-zero if ok.
2483  *
2484  * Note that the MSS calculation here is based on the info given in
2485  * the IRE.  We do not do any calculation based on TCP options.  They
2486  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2487  * knows which options to use.
2488  *
2489  * Note on how TCP gets its parameters for a connection.
2490  *
2491  * When a tcp_t structure is allocated, it gets all the default parameters.
2492  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2493  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2494  * default.
2495  *
2496  * An incoming SYN with a multicast or broadcast destination address, is dropped
2497  * in 1 of 2 places.
2498  *
2499  * 1. If the packet was received over the wire it is dropped in
2500  * ip_rput_process_broadcast()
2501  *
2502  * 2. If the packet was received through internal IP loopback, i.e. the packet
2503  * was generated and received on the same machine, it is dropped in
2504  * ip_wput_local()
2505  *
2506  * An incoming SYN with a multicast or broadcast source address is always
2507  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2508  * reject an attempt to connect to a broadcast or multicast (destination)
2509  * address.
2510  */
2511 static int
2512 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2513 {
2514 	ire_t		*ire;
2515 	ire_t		*sire = NULL;
2516 	iulp_t		*ire_uinfo = NULL;
2517 	uint32_t	mss_max;
2518 	uint32_t	mss;
2519 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2520 	conn_t		*connp = tcp->tcp_connp;
2521 	boolean_t	ire_cacheable = B_FALSE;
2522 	zoneid_t	zoneid = connp->conn_zoneid;
2523 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2524 	    MATCH_IRE_SECATTR;
2525 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2526 	ill_t		*ill = NULL;
2527 	boolean_t	incoming = (ire_mp == NULL);
2528 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2529 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2530 
2531 	ASSERT(connp->conn_ire_cache == NULL);
2532 
2533 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2534 
2535 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2536 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2537 			return (0);
2538 		}
2539 		/*
2540 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2541 		 * for the destination with the nexthop as gateway.
2542 		 * ire_ctable_lookup() is used because this particular
2543 		 * ire, if it exists, will be marked private.
2544 		 * If that is not available, use the interface ire
2545 		 * for the nexthop.
2546 		 *
2547 		 * TSol: tcp_update_label will detect label mismatches based
2548 		 * only on the destination's label, but that would not
2549 		 * detect label mismatches based on the security attributes
2550 		 * of routes or next hop gateway. Hence we need to pass the
2551 		 * label to ire_ftable_lookup below in order to locate the
2552 		 * right prefix (and/or) ire cache. Similarly we also need
2553 		 * pass the label to the ire_cache_lookup below to locate
2554 		 * the right ire that also matches on the label.
2555 		 */
2556 		if (tcp->tcp_connp->conn_nexthop_set) {
2557 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2558 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2559 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2560 			    ipst);
2561 			if (ire == NULL) {
2562 				ire = ire_ftable_lookup(
2563 				    tcp->tcp_connp->conn_nexthop_v4,
2564 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2565 				    tsl, match_flags, ipst);
2566 				if (ire == NULL)
2567 					return (0);
2568 			} else {
2569 				ire_uinfo = &ire->ire_uinfo;
2570 			}
2571 		} else {
2572 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2573 			    zoneid, tsl, ipst);
2574 			if (ire != NULL) {
2575 				ire_cacheable = B_TRUE;
2576 				ire_uinfo = (ire_mp != NULL) ?
2577 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2578 				    &ire->ire_uinfo;
2579 
2580 			} else {
2581 				if (ire_mp == NULL) {
2582 					ire = ire_ftable_lookup(
2583 					    tcp->tcp_connp->conn_rem,
2584 					    0, 0, 0, NULL, &sire, zoneid, 0,
2585 					    tsl, (MATCH_IRE_RECURSIVE |
2586 					    MATCH_IRE_DEFAULT), ipst);
2587 					if (ire == NULL)
2588 						return (0);
2589 					ire_uinfo = (sire != NULL) ?
2590 					    &sire->ire_uinfo :
2591 					    &ire->ire_uinfo;
2592 				} else {
2593 					ire = (ire_t *)ire_mp->b_rptr;
2594 					ire_uinfo =
2595 					    &((ire_t *)
2596 					    ire_mp->b_rptr)->ire_uinfo;
2597 				}
2598 			}
2599 		}
2600 		ASSERT(ire != NULL);
2601 
2602 		if ((ire->ire_src_addr == INADDR_ANY) ||
2603 		    (ire->ire_type & IRE_BROADCAST)) {
2604 			/*
2605 			 * ire->ire_mp is non null when ire_mp passed in is used
2606 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2607 			 */
2608 			if (ire->ire_mp == NULL)
2609 				ire_refrele(ire);
2610 			if (sire != NULL)
2611 				ire_refrele(sire);
2612 			return (0);
2613 		}
2614 
2615 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2616 			ipaddr_t src_addr;
2617 
2618 			/*
2619 			 * ip_bind_connected() has stored the correct source
2620 			 * address in conn_src.
2621 			 */
2622 			src_addr = tcp->tcp_connp->conn_src;
2623 			tcp->tcp_ipha->ipha_src = src_addr;
2624 			/*
2625 			 * Copy of the src addr. in tcp_t is needed
2626 			 * for the lookup funcs.
2627 			 */
2628 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2629 		}
2630 		/*
2631 		 * Set the fragment bit so that IP will tell us if the MTU
2632 		 * should change. IP tells us the latest setting of
2633 		 * ip_path_mtu_discovery through ire_frag_flag.
2634 		 */
2635 		if (ipst->ips_ip_path_mtu_discovery) {
2636 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2637 			    htons(IPH_DF);
2638 		}
2639 		/*
2640 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2641 		 * for IP_NEXTHOP. No cache ire has been found for the
2642 		 * destination and we are working with the nexthop's
2643 		 * interface ire. Since we need to forward all packets
2644 		 * to the nexthop first, we "blindly" set tcp_localnet
2645 		 * to false, eventhough the destination may also be
2646 		 * onlink.
2647 		 */
2648 		if (ire_uinfo == NULL)
2649 			tcp->tcp_localnet = 0;
2650 		else
2651 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2652 	} else {
2653 		/*
2654 		 * For incoming connection ire_mp = NULL
2655 		 * For outgoing connection ire_mp != NULL
2656 		 * Technically we should check conn_incoming_ill
2657 		 * when ire_mp is NULL and conn_outgoing_ill when
2658 		 * ire_mp is non-NULL. But this is performance
2659 		 * critical path and for IPV*_BOUND_IF, outgoing
2660 		 * and incoming ill are always set to the same value.
2661 		 */
2662 		ill_t	*dst_ill = NULL;
2663 		ipif_t  *dst_ipif = NULL;
2664 
2665 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2666 
2667 		if (connp->conn_outgoing_ill != NULL) {
2668 			/* Outgoing or incoming path */
2669 			int   err;
2670 
2671 			dst_ill = conn_get_held_ill(connp,
2672 			    &connp->conn_outgoing_ill, &err);
2673 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2674 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2675 				return (0);
2676 			}
2677 			match_flags |= MATCH_IRE_ILL;
2678 			dst_ipif = dst_ill->ill_ipif;
2679 		}
2680 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2681 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2682 
2683 		if (ire != NULL) {
2684 			ire_cacheable = B_TRUE;
2685 			ire_uinfo = (ire_mp != NULL) ?
2686 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2687 			    &ire->ire_uinfo;
2688 		} else {
2689 			if (ire_mp == NULL) {
2690 				ire = ire_ftable_lookup_v6(
2691 				    &tcp->tcp_connp->conn_remv6,
2692 				    0, 0, 0, dst_ipif, &sire, zoneid,
2693 				    0, tsl, match_flags, ipst);
2694 				if (ire == NULL) {
2695 					if (dst_ill != NULL)
2696 						ill_refrele(dst_ill);
2697 					return (0);
2698 				}
2699 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2700 				    &ire->ire_uinfo;
2701 			} else {
2702 				ire = (ire_t *)ire_mp->b_rptr;
2703 				ire_uinfo =
2704 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2705 			}
2706 		}
2707 		if (dst_ill != NULL)
2708 			ill_refrele(dst_ill);
2709 
2710 		ASSERT(ire != NULL);
2711 		ASSERT(ire_uinfo != NULL);
2712 
2713 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2714 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2715 			/*
2716 			 * ire->ire_mp is non null when ire_mp passed in is used
2717 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2718 			 */
2719 			if (ire->ire_mp == NULL)
2720 				ire_refrele(ire);
2721 			if (sire != NULL)
2722 				ire_refrele(sire);
2723 			return (0);
2724 		}
2725 
2726 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2727 			in6_addr_t	src_addr;
2728 
2729 			/*
2730 			 * ip_bind_connected_v6() has stored the correct source
2731 			 * address per IPv6 addr. selection policy in
2732 			 * conn_src_v6.
2733 			 */
2734 			src_addr = tcp->tcp_connp->conn_srcv6;
2735 
2736 			tcp->tcp_ip6h->ip6_src = src_addr;
2737 			/*
2738 			 * Copy of the src addr. in tcp_t is needed
2739 			 * for the lookup funcs.
2740 			 */
2741 			tcp->tcp_ip_src_v6 = src_addr;
2742 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2743 			    &connp->conn_srcv6));
2744 		}
2745 		tcp->tcp_localnet =
2746 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2747 	}
2748 
2749 	/*
2750 	 * This allows applications to fail quickly when connections are made
2751 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2752 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2753 	 */
2754 	if ((ire->ire_flags & RTF_REJECT) &&
2755 	    (ire->ire_flags & RTF_PRIVATE))
2756 		goto error;
2757 
2758 	/*
2759 	 * Make use of the cached rtt and rtt_sd values to calculate the
2760 	 * initial RTO.  Note that they are already initialized in
2761 	 * tcp_init_values().
2762 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2763 	 * IP_NEXTHOP, but instead are using the interface ire for the
2764 	 * nexthop, then we do not use the ire_uinfo from that ire to
2765 	 * do any initializations.
2766 	 */
2767 	if (ire_uinfo != NULL) {
2768 		if (ire_uinfo->iulp_rtt != 0) {
2769 			clock_t	rto;
2770 
2771 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2772 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2773 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2774 			    tcps->tcps_rexmit_interval_extra +
2775 			    (tcp->tcp_rtt_sa >> 5);
2776 
2777 			if (rto > tcps->tcps_rexmit_interval_max) {
2778 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2779 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2780 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2781 			} else {
2782 				tcp->tcp_rto = rto;
2783 			}
2784 		}
2785 		if (ire_uinfo->iulp_ssthresh != 0)
2786 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2787 		else
2788 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2789 		if (ire_uinfo->iulp_spipe > 0) {
2790 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2791 			    tcps->tcps_max_buf);
2792 			if (tcps->tcps_snd_lowat_fraction != 0)
2793 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2794 				    tcps->tcps_snd_lowat_fraction;
2795 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2796 		}
2797 		/*
2798 		 * Note that up till now, acceptor always inherits receive
2799 		 * window from the listener.  But if there is a metrics
2800 		 * associated with a host, we should use that instead of
2801 		 * inheriting it from listener. Thus we need to pass this
2802 		 * info back to the caller.
2803 		 */
2804 		if (ire_uinfo->iulp_rpipe > 0) {
2805 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2806 			    tcps->tcps_max_buf);
2807 		}
2808 
2809 		if (ire_uinfo->iulp_rtomax > 0) {
2810 			tcp->tcp_second_timer_threshold =
2811 			    ire_uinfo->iulp_rtomax;
2812 		}
2813 
2814 		/*
2815 		 * Use the metric option settings, iulp_tstamp_ok and
2816 		 * iulp_wscale_ok, only for active open. What this means
2817 		 * is that if the other side uses timestamp or window
2818 		 * scale option, TCP will also use those options. That
2819 		 * is for passive open.  If the application sets a
2820 		 * large window, window scale is enabled regardless of
2821 		 * the value in iulp_wscale_ok.  This is the behavior
2822 		 * since 2.6.  So we keep it.
2823 		 * The only case left in passive open processing is the
2824 		 * check for SACK.
2825 		 * For ECN, it should probably be like SACK.  But the
2826 		 * current value is binary, so we treat it like the other
2827 		 * cases.  The metric only controls active open.For passive
2828 		 * open, the ndd param, tcp_ecn_permitted, controls the
2829 		 * behavior.
2830 		 */
2831 		if (!tcp_detached) {
2832 			/*
2833 			 * The if check means that the following can only
2834 			 * be turned on by the metrics only IRE, but not off.
2835 			 */
2836 			if (ire_uinfo->iulp_tstamp_ok)
2837 				tcp->tcp_snd_ts_ok = B_TRUE;
2838 			if (ire_uinfo->iulp_wscale_ok)
2839 				tcp->tcp_snd_ws_ok = B_TRUE;
2840 			if (ire_uinfo->iulp_sack == 2)
2841 				tcp->tcp_snd_sack_ok = B_TRUE;
2842 			if (ire_uinfo->iulp_ecn_ok)
2843 				tcp->tcp_ecn_ok = B_TRUE;
2844 		} else {
2845 			/*
2846 			 * Passive open.
2847 			 *
2848 			 * As above, the if check means that SACK can only be
2849 			 * turned on by the metric only IRE.
2850 			 */
2851 			if (ire_uinfo->iulp_sack > 0) {
2852 				tcp->tcp_snd_sack_ok = B_TRUE;
2853 			}
2854 		}
2855 	}
2856 
2857 
2858 	/*
2859 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2860 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2861 	 * length of all those options exceeds 28 bytes.  But because
2862 	 * of the tcp_mss_min check below, we may not have a problem if
2863 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2864 	 * the negative problem still exists.  And the check defeats PMTUd.
2865 	 * In fact, if PMTUd finds that the MSS should be smaller than
2866 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2867 	 * value.
2868 	 *
2869 	 * We do not deal with that now.  All those problems related to
2870 	 * PMTUd will be fixed later.
2871 	 */
2872 	ASSERT(ire->ire_max_frag != 0);
2873 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2874 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2875 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2876 			mss = MIN(mss, IPV6_MIN_MTU);
2877 		}
2878 	}
2879 
2880 	/* Sanity check for MSS value. */
2881 	if (tcp->tcp_ipversion == IPV4_VERSION)
2882 		mss_max = tcps->tcps_mss_max_ipv4;
2883 	else
2884 		mss_max = tcps->tcps_mss_max_ipv6;
2885 
2886 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2887 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2888 		/*
2889 		 * After receiving an ICMPv6 "packet too big" message with a
2890 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2891 		 * will insert a 8-byte fragment header in every packet; we
2892 		 * reduce the MSS by that amount here.
2893 		 */
2894 		mss -= sizeof (ip6_frag_t);
2895 	}
2896 
2897 	if (tcp->tcp_ipsec_overhead == 0)
2898 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2899 
2900 	mss -= tcp->tcp_ipsec_overhead;
2901 
2902 	if (mss < tcps->tcps_mss_min)
2903 		mss = tcps->tcps_mss_min;
2904 	if (mss > mss_max)
2905 		mss = mss_max;
2906 
2907 	/* Note that this is the maximum MSS, excluding all options. */
2908 	tcp->tcp_mss = mss;
2909 
2910 	/*
2911 	 * Initialize the ISS here now that we have the full connection ID.
2912 	 * The RFC 1948 method of initial sequence number generation requires
2913 	 * knowledge of the full connection ID before setting the ISS.
2914 	 */
2915 
2916 	tcp_iss_init(tcp);
2917 
2918 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2919 		tcp->tcp_loopback = B_TRUE;
2920 
2921 	if (sire != NULL)
2922 		IRE_REFRELE(sire);
2923 
2924 	/*
2925 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2926 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2927 	 */
2928 	if (tcp->tcp_loopback ||
2929 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2930 		/*
2931 		 * For incoming, see if this tcp may be MDT-capable.  For
2932 		 * outgoing, this process has been taken care of through
2933 		 * tcp_rput_other.
2934 		 */
2935 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2936 		tcp->tcp_ire_ill_check_done = B_TRUE;
2937 	}
2938 
2939 	mutex_enter(&connp->conn_lock);
2940 	/*
2941 	 * Make sure that conn is not marked incipient
2942 	 * for incoming connections. A blind
2943 	 * removal of incipient flag is cheaper than
2944 	 * check and removal.
2945 	 */
2946 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2947 
2948 	/*
2949 	 * Must not cache forwarding table routes
2950 	 * or recache an IRE after the conn_t has
2951 	 * had conn_ire_cache cleared and is flagged
2952 	 * unusable, (see the CONN_CACHE_IRE() macro).
2953 	 */
2954 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
2955 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2956 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2957 			connp->conn_ire_cache = ire;
2958 			IRE_UNTRACE_REF(ire);
2959 			rw_exit(&ire->ire_bucket->irb_lock);
2960 			mutex_exit(&connp->conn_lock);
2961 			return (1);
2962 		}
2963 		rw_exit(&ire->ire_bucket->irb_lock);
2964 	}
2965 	mutex_exit(&connp->conn_lock);
2966 
2967 	if (ire->ire_mp == NULL)
2968 		ire_refrele(ire);
2969 	return (1);
2970 
2971 error:
2972 	if (ire->ire_mp == NULL)
2973 		ire_refrele(ire);
2974 	if (sire != NULL)
2975 		ire_refrele(sire);
2976 	return (0);
2977 }
2978 
2979 static void
2980 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
2981 {
2982 	int	error;
2983 	conn_t	*connp = tcp->tcp_connp;
2984 	struct sockaddr	*sa;
2985 	mblk_t  *mp1;
2986 	struct T_bind_req *tbr;
2987 	int	backlog;
2988 	socklen_t	len;
2989 	sin_t	*sin;
2990 	sin6_t	*sin6;
2991 	cred_t		*cr;
2992 
2993 	/*
2994 	 * All Solaris components should pass a db_credp
2995 	 * for this TPI message, hence we ASSERT.
2996 	 * But in case there is some other M_PROTO that looks
2997 	 * like a TPI message sent by some other kernel
2998 	 * component, we check and return an error.
2999 	 */
3000 	cr = msg_getcred(mp, NULL);
3001 	ASSERT(cr != NULL);
3002 	if (cr == NULL) {
3003 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3004 		return;
3005 	}
3006 
3007 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3008 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3009 		if (tcp->tcp_debug) {
3010 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3011 			    "tcp_tpi_bind: bad req, len %u",
3012 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3013 		}
3014 		tcp_err_ack(tcp, mp, TPROTO, 0);
3015 		return;
3016 	}
3017 	/* Make sure the largest address fits */
3018 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3019 	if (mp1 == NULL) {
3020 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3021 		return;
3022 	}
3023 	mp = mp1;
3024 	tbr = (struct T_bind_req *)mp->b_rptr;
3025 
3026 	backlog = tbr->CONIND_number;
3027 	len = tbr->ADDR_length;
3028 
3029 	switch (len) {
3030 	case 0:		/* request for a generic port */
3031 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3032 		if (tcp->tcp_family == AF_INET) {
3033 			tbr->ADDR_length = sizeof (sin_t);
3034 			sin = (sin_t *)&tbr[1];
3035 			*sin = sin_null;
3036 			sin->sin_family = AF_INET;
3037 			sa = (struct sockaddr *)sin;
3038 			len = sizeof (sin_t);
3039 			mp->b_wptr = (uchar_t *)&sin[1];
3040 		} else {
3041 			ASSERT(tcp->tcp_family == AF_INET6);
3042 			tbr->ADDR_length = sizeof (sin6_t);
3043 			sin6 = (sin6_t *)&tbr[1];
3044 			*sin6 = sin6_null;
3045 			sin6->sin6_family = AF_INET6;
3046 			sa = (struct sockaddr *)sin6;
3047 			len = sizeof (sin6_t);
3048 			mp->b_wptr = (uchar_t *)&sin6[1];
3049 		}
3050 		break;
3051 
3052 	case sizeof (sin_t):    /* Complete IPv4 address */
3053 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
3054 		    sizeof (sin_t));
3055 		break;
3056 
3057 	case sizeof (sin6_t): /* Complete IPv6 address */
3058 		sa = (struct sockaddr *)mi_offset_param(mp,
3059 		    tbr->ADDR_offset, sizeof (sin6_t));
3060 		break;
3061 
3062 	default:
3063 		if (tcp->tcp_debug) {
3064 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3065 			    "tcp_tpi_bind: bad address length, %d",
3066 			    tbr->ADDR_length);
3067 		}
3068 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3069 		return;
3070 	}
3071 
3072 	error = tcp_bind_check(connp, sa, len, cr,
3073 	    tbr->PRIM_type != O_T_BIND_REQ);
3074 	if (error == 0) {
3075 		if (tcp->tcp_family == AF_INET) {
3076 			sin = (sin_t *)sa;
3077 			sin->sin_port = tcp->tcp_lport;
3078 		} else {
3079 			sin6 = (sin6_t *)sa;
3080 			sin6->sin6_port = tcp->tcp_lport;
3081 		}
3082 
3083 		if (backlog > 0) {
3084 			error = tcp_do_listen(connp, backlog, cr);
3085 		}
3086 	}
3087 done:
3088 	if (error > 0) {
3089 		tcp_err_ack(tcp, mp, TSYSERR, error);
3090 	} else if (error < 0) {
3091 		tcp_err_ack(tcp, mp, -error, 0);
3092 	} else {
3093 		mp->b_datap->db_type = M_PCPROTO;
3094 		tbr->PRIM_type = T_BIND_ACK;
3095 		putnext(tcp->tcp_rq, mp);
3096 	}
3097 }
3098 
3099 /*
3100  * If the "bind_to_req_port_only" parameter is set, if the requested port
3101  * number is available, return it, If not return 0
3102  *
3103  * If "bind_to_req_port_only" parameter is not set and
3104  * If the requested port number is available, return it.  If not, return
3105  * the first anonymous port we happen across.  If no anonymous ports are
3106  * available, return 0. addr is the requested local address, if any.
3107  *
3108  * In either case, when succeeding update the tcp_t to record the port number
3109  * and insert it in the bind hash table.
3110  *
3111  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3112  * without setting SO_REUSEADDR. This is needed so that they
3113  * can be viewed as two independent transport protocols.
3114  */
3115 static in_port_t
3116 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3117     int reuseaddr, boolean_t quick_connect,
3118     boolean_t bind_to_req_port_only, boolean_t user_specified)
3119 {
3120 	/* number of times we have run around the loop */
3121 	int count = 0;
3122 	/* maximum number of times to run around the loop */
3123 	int loopmax;
3124 	conn_t *connp = tcp->tcp_connp;
3125 	zoneid_t zoneid = connp->conn_zoneid;
3126 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3127 
3128 	/*
3129 	 * Lookup for free addresses is done in a loop and "loopmax"
3130 	 * influences how long we spin in the loop
3131 	 */
3132 	if (bind_to_req_port_only) {
3133 		/*
3134 		 * If the requested port is busy, don't bother to look
3135 		 * for a new one. Setting loop maximum count to 1 has
3136 		 * that effect.
3137 		 */
3138 		loopmax = 1;
3139 	} else {
3140 		/*
3141 		 * If the requested port is busy, look for a free one
3142 		 * in the anonymous port range.
3143 		 * Set loopmax appropriately so that one does not look
3144 		 * forever in the case all of the anonymous ports are in use.
3145 		 */
3146 		if (tcp->tcp_anon_priv_bind) {
3147 			/*
3148 			 * loopmax =
3149 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3150 			 */
3151 			loopmax = IPPORT_RESERVED -
3152 			    tcps->tcps_min_anonpriv_port;
3153 		} else {
3154 			loopmax = (tcps->tcps_largest_anon_port -
3155 			    tcps->tcps_smallest_anon_port + 1);
3156 		}
3157 	}
3158 	do {
3159 		uint16_t	lport;
3160 		tf_t		*tbf;
3161 		tcp_t		*ltcp;
3162 		conn_t		*lconnp;
3163 
3164 		lport = htons(port);
3165 
3166 		/*
3167 		 * Ensure that the tcp_t is not currently in the bind hash.
3168 		 * Hold the lock on the hash bucket to ensure that
3169 		 * the duplicate check plus the insertion is an atomic
3170 		 * operation.
3171 		 *
3172 		 * This function does an inline lookup on the bind hash list
3173 		 * Make sure that we access only members of tcp_t
3174 		 * and that we don't look at tcp_tcp, since we are not
3175 		 * doing a CONN_INC_REF.
3176 		 */
3177 		tcp_bind_hash_remove(tcp);
3178 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3179 		mutex_enter(&tbf->tf_lock);
3180 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3181 		    ltcp = ltcp->tcp_bind_hash) {
3182 			if (lport == ltcp->tcp_lport)
3183 				break;
3184 		}
3185 
3186 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
3187 			boolean_t not_socket;
3188 			boolean_t exclbind;
3189 
3190 			lconnp = ltcp->tcp_connp;
3191 
3192 			/*
3193 			 * On a labeled system, we must treat bindings to ports
3194 			 * on shared IP addresses by sockets with MAC exemption
3195 			 * privilege as being in all zones, as there's
3196 			 * otherwise no way to identify the right receiver.
3197 			 */
3198 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3199 			    IPCL_ZONE_MATCH(connp,
3200 			    ltcp->tcp_connp->conn_zoneid)) &&
3201 			    !lconnp->conn_mac_exempt &&
3202 			    !connp->conn_mac_exempt)
3203 				continue;
3204 
3205 			/*
3206 			 * If TCP_EXCLBIND is set for either the bound or
3207 			 * binding endpoint, the semantics of bind
3208 			 * is changed according to the following.
3209 			 *
3210 			 * spec = specified address (v4 or v6)
3211 			 * unspec = unspecified address (v4 or v6)
3212 			 * A = specified addresses are different for endpoints
3213 			 *
3214 			 * bound	bind to		allowed
3215 			 * -------------------------------------
3216 			 * unspec	unspec		no
3217 			 * unspec	spec		no
3218 			 * spec		unspec		no
3219 			 * spec		spec		yes if A
3220 			 *
3221 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3222 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3223 			 *
3224 			 * Note:
3225 			 *
3226 			 * 1. Because of TLI semantics, an endpoint can go
3227 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3228 			 * TCPS_BOUND, depending on whether it is originally
3229 			 * a listener or not.  That is why we need to check
3230 			 * for states greater than or equal to TCPS_BOUND
3231 			 * here.
3232 			 *
3233 			 * 2. Ideally, we should only check for state equals
3234 			 * to TCPS_LISTEN. And the following check should be
3235 			 * added.
3236 			 *
3237 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3238 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3239 			 *		...
3240 			 * }
3241 			 *
3242 			 * The semantics will be changed to this.  If the
3243 			 * endpoint on the list is in state not equal to
3244 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3245 			 * set, let the bind succeed.
3246 			 *
3247 			 * Because of (1), we cannot do that for TLI
3248 			 * endpoints.  But we can do that for socket endpoints.
3249 			 * If in future, we can change this going back
3250 			 * semantics, we can use the above check for TLI also.
3251 			 */
3252 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3253 			    TCP_IS_SOCKET(tcp));
3254 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3255 
3256 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3257 			    (exclbind && (not_socket ||
3258 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3259 				if (V6_OR_V4_INADDR_ANY(
3260 				    ltcp->tcp_bound_source_v6) ||
3261 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3262 				    IN6_ARE_ADDR_EQUAL(laddr,
3263 				    &ltcp->tcp_bound_source_v6)) {
3264 					break;
3265 				}
3266 				continue;
3267 			}
3268 
3269 			/*
3270 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3271 			 * have disjoint port number spaces, if *_EXCLBIND
3272 			 * is not set and only if the application binds to a
3273 			 * specific port. We use the same autoassigned port
3274 			 * number space for IPv4 and IPv6 sockets.
3275 			 */
3276 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3277 			    bind_to_req_port_only)
3278 				continue;
3279 
3280 			/*
3281 			 * Ideally, we should make sure that the source
3282 			 * address, remote address, and remote port in the
3283 			 * four tuple for this tcp-connection is unique.
3284 			 * However, trying to find out the local source
3285 			 * address would require too much code duplication
3286 			 * with IP, since IP needs needs to have that code
3287 			 * to support userland TCP implementations.
3288 			 */
3289 			if (quick_connect &&
3290 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3291 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3292 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3293 			    &ltcp->tcp_remote_v6)))
3294 				continue;
3295 
3296 			if (!reuseaddr) {
3297 				/*
3298 				 * No socket option SO_REUSEADDR.
3299 				 * If existing port is bound to
3300 				 * a non-wildcard IP address
3301 				 * and the requesting stream is
3302 				 * bound to a distinct
3303 				 * different IP addresses
3304 				 * (non-wildcard, also), keep
3305 				 * going.
3306 				 */
3307 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3308 				    !V6_OR_V4_INADDR_ANY(
3309 				    ltcp->tcp_bound_source_v6) &&
3310 				    !IN6_ARE_ADDR_EQUAL(laddr,
3311 				    &ltcp->tcp_bound_source_v6))
3312 					continue;
3313 				if (ltcp->tcp_state >= TCPS_BOUND) {
3314 					/*
3315 					 * This port is being used and
3316 					 * its state is >= TCPS_BOUND,
3317 					 * so we can't bind to it.
3318 					 */
3319 					break;
3320 				}
3321 			} else {
3322 				/*
3323 				 * socket option SO_REUSEADDR is set on the
3324 				 * binding tcp_t.
3325 				 *
3326 				 * If two streams are bound to
3327 				 * same IP address or both addr
3328 				 * and bound source are wildcards
3329 				 * (INADDR_ANY), we want to stop
3330 				 * searching.
3331 				 * We have found a match of IP source
3332 				 * address and source port, which is
3333 				 * refused regardless of the
3334 				 * SO_REUSEADDR setting, so we break.
3335 				 */
3336 				if (IN6_ARE_ADDR_EQUAL(laddr,
3337 				    &ltcp->tcp_bound_source_v6) &&
3338 				    (ltcp->tcp_state == TCPS_LISTEN ||
3339 				    ltcp->tcp_state == TCPS_BOUND))
3340 					break;
3341 			}
3342 		}
3343 		if (ltcp != NULL) {
3344 			/* The port number is busy */
3345 			mutex_exit(&tbf->tf_lock);
3346 		} else {
3347 			/*
3348 			 * This port is ours. Insert in fanout and mark as
3349 			 * bound to prevent others from getting the port
3350 			 * number.
3351 			 */
3352 			tcp->tcp_state = TCPS_BOUND;
3353 			tcp->tcp_lport = htons(port);
3354 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3355 
3356 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3357 			    tcp->tcp_lport)] == tbf);
3358 			tcp_bind_hash_insert(tbf, tcp, 1);
3359 
3360 			mutex_exit(&tbf->tf_lock);
3361 
3362 			/*
3363 			 * We don't want tcp_next_port_to_try to "inherit"
3364 			 * a port number supplied by the user in a bind.
3365 			 */
3366 			if (user_specified)
3367 				return (port);
3368 
3369 			/*
3370 			 * This is the only place where tcp_next_port_to_try
3371 			 * is updated. After the update, it may or may not
3372 			 * be in the valid range.
3373 			 */
3374 			if (!tcp->tcp_anon_priv_bind)
3375 				tcps->tcps_next_port_to_try = port + 1;
3376 			return (port);
3377 		}
3378 
3379 		if (tcp->tcp_anon_priv_bind) {
3380 			port = tcp_get_next_priv_port(tcp);
3381 		} else {
3382 			if (count == 0 && user_specified) {
3383 				/*
3384 				 * We may have to return an anonymous port. So
3385 				 * get one to start with.
3386 				 */
3387 				port =
3388 				    tcp_update_next_port(
3389 				    tcps->tcps_next_port_to_try,
3390 				    tcp, B_TRUE);
3391 				user_specified = B_FALSE;
3392 			} else {
3393 				port = tcp_update_next_port(port + 1, tcp,
3394 				    B_FALSE);
3395 			}
3396 		}
3397 		if (port == 0)
3398 			break;
3399 
3400 		/*
3401 		 * Don't let this loop run forever in the case where
3402 		 * all of the anonymous ports are in use.
3403 		 */
3404 	} while (++count < loopmax);
3405 	return (0);
3406 }
3407 
3408 /*
3409  * tcp_clean_death / tcp_close_detached must not be called more than once
3410  * on a tcp. Thus every function that potentially calls tcp_clean_death
3411  * must check for the tcp state before calling tcp_clean_death.
3412  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3413  * tcp_timer_handler, all check for the tcp state.
3414  */
3415 /* ARGSUSED */
3416 void
3417 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3418 {
3419 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3420 
3421 	freemsg(mp);
3422 	if (tcp->tcp_state > TCPS_BOUND)
3423 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3424 		    ETIMEDOUT, 5);
3425 }
3426 
3427 /*
3428  * We are dying for some reason.  Try to do it gracefully.  (May be called
3429  * as writer.)
3430  *
3431  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3432  * done by a service procedure).
3433  * TBD - Should the return value distinguish between the tcp_t being
3434  * freed and it being reinitialized?
3435  */
3436 static int
3437 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3438 {
3439 	mblk_t	*mp;
3440 	queue_t	*q;
3441 	conn_t	*connp = tcp->tcp_connp;
3442 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3443 	sodirect_t	*sodp;
3444 
3445 	TCP_CLD_STAT(tag);
3446 
3447 #if TCP_TAG_CLEAN_DEATH
3448 	tcp->tcp_cleandeathtag = tag;
3449 #endif
3450 
3451 	if (tcp->tcp_fused)
3452 		tcp_unfuse(tcp);
3453 
3454 	if (tcp->tcp_linger_tid != 0 &&
3455 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3456 		tcp_stop_lingering(tcp);
3457 	}
3458 
3459 	ASSERT(tcp != NULL);
3460 	ASSERT((tcp->tcp_family == AF_INET &&
3461 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3462 	    (tcp->tcp_family == AF_INET6 &&
3463 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3464 	    tcp->tcp_ipversion == IPV6_VERSION)));
3465 
3466 	if (TCP_IS_DETACHED(tcp)) {
3467 		if (tcp->tcp_hard_binding) {
3468 			/*
3469 			 * Its an eager that we are dealing with. We close the
3470 			 * eager but in case a conn_ind has already gone to the
3471 			 * listener, let tcp_accept_finish() send a discon_ind
3472 			 * to the listener and drop the last reference. If the
3473 			 * listener doesn't even know about the eager i.e. the
3474 			 * conn_ind hasn't gone up, blow away the eager and drop
3475 			 * the last reference as well. If the conn_ind has gone
3476 			 * up, state should be BOUND. tcp_accept_finish
3477 			 * will figure out that the connection has received a
3478 			 * RST and will send a DISCON_IND to the application.
3479 			 */
3480 			tcp_closei_local(tcp);
3481 			if (!tcp->tcp_tconnind_started) {
3482 				CONN_DEC_REF(connp);
3483 			} else {
3484 				tcp->tcp_state = TCPS_BOUND;
3485 			}
3486 		} else {
3487 			tcp_close_detached(tcp);
3488 		}
3489 		return (0);
3490 	}
3491 
3492 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3493 
3494 	/* If sodirect, not anymore */
3495 	SOD_PTR_ENTER(tcp, sodp);
3496 	if (sodp != NULL) {
3497 		tcp->tcp_sodirect = NULL;
3498 		mutex_exit(sodp->sod_lockp);
3499 	}
3500 
3501 	q = tcp->tcp_rq;
3502 
3503 	/* Trash all inbound data */
3504 	if (!IPCL_IS_NONSTR(connp)) {
3505 		ASSERT(q != NULL);
3506 		flushq(q, FLUSHALL);
3507 	}
3508 
3509 	/*
3510 	 * If we are at least part way open and there is error
3511 	 * (err==0 implies no error)
3512 	 * notify our client by a T_DISCON_IND.
3513 	 */
3514 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3515 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3516 		    !TCP_IS_SOCKET(tcp)) {
3517 			/*
3518 			 * Send M_FLUSH according to TPI. Because sockets will
3519 			 * (and must) ignore FLUSHR we do that only for TPI
3520 			 * endpoints and sockets in STREAMS mode.
3521 			 */
3522 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3523 		}
3524 		if (tcp->tcp_debug) {
3525 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3526 			    "tcp_clean_death: discon err %d", err);
3527 		}
3528 		if (IPCL_IS_NONSTR(connp)) {
3529 			/* Direct socket, use upcall */
3530 			(*connp->conn_upcalls->su_disconnected)(
3531 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3532 		} else {
3533 			mp = mi_tpi_discon_ind(NULL, err, 0);
3534 			if (mp != NULL) {
3535 				putnext(q, mp);
3536 			} else {
3537 				if (tcp->tcp_debug) {
3538 					(void) strlog(TCP_MOD_ID, 0, 1,
3539 					    SL_ERROR|SL_TRACE,
3540 					    "tcp_clean_death, sending M_ERROR");
3541 				}
3542 				(void) putnextctl1(q, M_ERROR, EPROTO);
3543 			}
3544 		}
3545 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3546 			/* SYN_SENT or SYN_RCVD */
3547 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3548 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3549 			/* ESTABLISHED or CLOSE_WAIT */
3550 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3551 		}
3552 	}
3553 
3554 	tcp_reinit(tcp);
3555 	if (IPCL_IS_NONSTR(connp))
3556 		(void) tcp_do_unbind(connp);
3557 
3558 	return (-1);
3559 }
3560 
3561 /*
3562  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3563  * to expire, stop the wait and finish the close.
3564  */
3565 static void
3566 tcp_stop_lingering(tcp_t *tcp)
3567 {
3568 	clock_t	delta = 0;
3569 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3570 
3571 	tcp->tcp_linger_tid = 0;
3572 	if (tcp->tcp_state > TCPS_LISTEN) {
3573 		tcp_acceptor_hash_remove(tcp);
3574 		mutex_enter(&tcp->tcp_non_sq_lock);
3575 		if (tcp->tcp_flow_stopped) {
3576 			tcp_clrqfull(tcp);
3577 		}
3578 		mutex_exit(&tcp->tcp_non_sq_lock);
3579 
3580 		if (tcp->tcp_timer_tid != 0) {
3581 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3582 			tcp->tcp_timer_tid = 0;
3583 		}
3584 		/*
3585 		 * Need to cancel those timers which will not be used when
3586 		 * TCP is detached.  This has to be done before the tcp_wq
3587 		 * is set to the global queue.
3588 		 */
3589 		tcp_timers_stop(tcp);
3590 
3591 		tcp->tcp_detached = B_TRUE;
3592 		ASSERT(tcps->tcps_g_q != NULL);
3593 		tcp->tcp_rq = tcps->tcps_g_q;
3594 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3595 
3596 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3597 			tcp_time_wait_append(tcp);
3598 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3599 			goto finish;
3600 		}
3601 
3602 		/*
3603 		 * If delta is zero the timer event wasn't executed and was
3604 		 * successfully canceled. In this case we need to restart it
3605 		 * with the minimal delta possible.
3606 		 */
3607 		if (delta >= 0) {
3608 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3609 			    delta ? delta : 1);
3610 		}
3611 	} else {
3612 		tcp_closei_local(tcp);
3613 		CONN_DEC_REF(tcp->tcp_connp);
3614 	}
3615 finish:
3616 	/* Signal closing thread that it can complete close */
3617 	mutex_enter(&tcp->tcp_closelock);
3618 	tcp->tcp_detached = B_TRUE;
3619 	ASSERT(tcps->tcps_g_q != NULL);
3620 
3621 	tcp->tcp_rq = tcps->tcps_g_q;
3622 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3623 
3624 	tcp->tcp_closed = 1;
3625 	cv_signal(&tcp->tcp_closecv);
3626 	mutex_exit(&tcp->tcp_closelock);
3627 }
3628 
3629 /*
3630  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3631  * expires.
3632  */
3633 static void
3634 tcp_close_linger_timeout(void *arg)
3635 {
3636 	conn_t	*connp = (conn_t *)arg;
3637 	tcp_t 	*tcp = connp->conn_tcp;
3638 
3639 	tcp->tcp_client_errno = ETIMEDOUT;
3640 	tcp_stop_lingering(tcp);
3641 }
3642 
3643 static void
3644 tcp_close_common(conn_t *connp, int flags)
3645 {
3646 	tcp_t		*tcp = connp->conn_tcp;
3647 	mblk_t 		*mp = &tcp->tcp_closemp;
3648 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3649 	mblk_t		*bp;
3650 
3651 	ASSERT(connp->conn_ref >= 2);
3652 
3653 	/*
3654 	 * Mark the conn as closing. ill_pending_mp_add will not
3655 	 * add any mp to the pending mp list, after this conn has
3656 	 * started closing. Same for sq_pending_mp_add
3657 	 */
3658 	mutex_enter(&connp->conn_lock);
3659 	connp->conn_state_flags |= CONN_CLOSING;
3660 	if (connp->conn_oper_pending_ill != NULL)
3661 		conn_ioctl_cleanup_reqd = B_TRUE;
3662 	CONN_INC_REF_LOCKED(connp);
3663 	mutex_exit(&connp->conn_lock);
3664 	tcp->tcp_closeflags = (uint8_t)flags;
3665 	ASSERT(connp->conn_ref >= 3);
3666 
3667 	/*
3668 	 * tcp_closemp_used is used below without any protection of a lock
3669 	 * as we don't expect any one else to use it concurrently at this
3670 	 * point otherwise it would be a major defect.
3671 	 */
3672 
3673 	if (mp->b_prev == NULL)
3674 		tcp->tcp_closemp_used = B_TRUE;
3675 	else
3676 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3677 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3678 
3679 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3680 
3681 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3682 	    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3683 
3684 	mutex_enter(&tcp->tcp_closelock);
3685 	while (!tcp->tcp_closed) {
3686 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3687 			/*
3688 			 * The cv_wait_sig() was interrupted. We now do the
3689 			 * following:
3690 			 *
3691 			 * 1) If the endpoint was lingering, we allow this
3692 			 * to be interrupted by cancelling the linger timeout
3693 			 * and closing normally.
3694 			 *
3695 			 * 2) Revert to calling cv_wait()
3696 			 *
3697 			 * We revert to using cv_wait() to avoid an
3698 			 * infinite loop which can occur if the calling
3699 			 * thread is higher priority than the squeue worker
3700 			 * thread and is bound to the same cpu.
3701 			 */
3702 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
3703 				mutex_exit(&tcp->tcp_closelock);
3704 				/* Entering squeue, bump ref count. */
3705 				CONN_INC_REF(connp);
3706 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3707 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3708 				    tcp_linger_interrupted, connp,
3709 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3710 				mutex_enter(&tcp->tcp_closelock);
3711 			}
3712 			break;
3713 		}
3714 	}
3715 	while (!tcp->tcp_closed)
3716 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3717 	mutex_exit(&tcp->tcp_closelock);
3718 
3719 	/*
3720 	 * In the case of listener streams that have eagers in the q or q0
3721 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3722 	 * tcp_wq of the eagers point to our queues. By waiting for the
3723 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3724 	 * up their queue pointers and also dropped their references to us.
3725 	 */
3726 	if (tcp->tcp_wait_for_eagers) {
3727 		mutex_enter(&connp->conn_lock);
3728 		while (connp->conn_ref != 1) {
3729 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3730 		}
3731 		mutex_exit(&connp->conn_lock);
3732 	}
3733 	/*
3734 	 * ioctl cleanup. The mp is queued in the
3735 	 * ill_pending_mp or in the sq_pending_mp.
3736 	 */
3737 	if (conn_ioctl_cleanup_reqd)
3738 		conn_ioctl_cleanup(connp);
3739 
3740 	tcp->tcp_cpid = -1;
3741 }
3742 
3743 static int
3744 tcp_tpi_close(queue_t *q, int flags)
3745 {
3746 	conn_t		*connp;
3747 
3748 	ASSERT(WR(q)->q_next == NULL);
3749 
3750 	if (flags & SO_FALLBACK) {
3751 		/*
3752 		 * stream is being closed while in fallback
3753 		 * simply free the resources that were allocated
3754 		 */
3755 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3756 		qprocsoff(q);
3757 		goto done;
3758 	}
3759 
3760 	connp = Q_TO_CONN(q);
3761 	/*
3762 	 * We are being closed as /dev/tcp or /dev/tcp6.
3763 	 */
3764 	tcp_close_common(connp, flags);
3765 
3766 	qprocsoff(q);
3767 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3768 
3769 	/*
3770 	 * Drop IP's reference on the conn. This is the last reference
3771 	 * on the connp if the state was less than established. If the
3772 	 * connection has gone into timewait state, then we will have
3773 	 * one ref for the TCP and one more ref (total of two) for the
3774 	 * classifier connected hash list (a timewait connections stays
3775 	 * in connected hash till closed).
3776 	 *
3777 	 * We can't assert the references because there might be other
3778 	 * transient reference places because of some walkers or queued
3779 	 * packets in squeue for the timewait state.
3780 	 */
3781 	CONN_DEC_REF(connp);
3782 done:
3783 	q->q_ptr = WR(q)->q_ptr = NULL;
3784 	return (0);
3785 }
3786 
3787 static int
3788 tcpclose_accept(queue_t *q)
3789 {
3790 	vmem_t	*minor_arena;
3791 	dev_t	conn_dev;
3792 
3793 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3794 
3795 	/*
3796 	 * We had opened an acceptor STREAM for sockfs which is
3797 	 * now being closed due to some error.
3798 	 */
3799 	qprocsoff(q);
3800 
3801 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3802 	conn_dev = (dev_t)RD(q)->q_ptr;
3803 	ASSERT(minor_arena != NULL);
3804 	ASSERT(conn_dev != 0);
3805 	inet_minor_free(minor_arena, conn_dev);
3806 	q->q_ptr = WR(q)->q_ptr = NULL;
3807 	return (0);
3808 }
3809 
3810 /*
3811  * Called by tcp_close() routine via squeue when lingering is
3812  * interrupted by a signal.
3813  */
3814 
3815 /* ARGSUSED */
3816 static void
3817 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
3818 {
3819 	conn_t	*connp = (conn_t *)arg;
3820 	tcp_t	*tcp = connp->conn_tcp;
3821 
3822 	freeb(mp);
3823 	if (tcp->tcp_linger_tid != 0 &&
3824 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3825 		tcp_stop_lingering(tcp);
3826 		tcp->tcp_client_errno = EINTR;
3827 	}
3828 }
3829 
3830 /*
3831  * Called by streams close routine via squeues when our client blows off her
3832  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3833  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3834  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3835  * acked.
3836  *
3837  * NOTE: tcp_close potentially returns error when lingering.
3838  * However, the stream head currently does not pass these errors
3839  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3840  * errors to the application (from tsleep()) and not errors
3841  * like ECONNRESET caused by receiving a reset packet.
3842  */
3843 
3844 /* ARGSUSED */
3845 static void
3846 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3847 {
3848 	char	*msg;
3849 	conn_t	*connp = (conn_t *)arg;
3850 	tcp_t	*tcp = connp->conn_tcp;
3851 	clock_t	delta = 0;
3852 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3853 
3854 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3855 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3856 
3857 	mutex_enter(&tcp->tcp_eager_lock);
3858 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3859 		/* Cleanup for listener */
3860 		tcp_eager_cleanup(tcp, 0);
3861 		tcp->tcp_wait_for_eagers = 1;
3862 	}
3863 	mutex_exit(&tcp->tcp_eager_lock);
3864 
3865 	connp->conn_mdt_ok = B_FALSE;
3866 	tcp->tcp_mdt = B_FALSE;
3867 
3868 	connp->conn_lso_ok = B_FALSE;
3869 	tcp->tcp_lso = B_FALSE;
3870 
3871 	msg = NULL;
3872 	switch (tcp->tcp_state) {
3873 	case TCPS_CLOSED:
3874 	case TCPS_IDLE:
3875 	case TCPS_BOUND:
3876 	case TCPS_LISTEN:
3877 		break;
3878 	case TCPS_SYN_SENT:
3879 		msg = "tcp_close, during connect";
3880 		break;
3881 	case TCPS_SYN_RCVD:
3882 		/*
3883 		 * Close during the connect 3-way handshake
3884 		 * but here there may or may not be pending data
3885 		 * already on queue. Process almost same as in
3886 		 * the ESTABLISHED state.
3887 		 */
3888 		/* FALLTHRU */
3889 	default:
3890 		if (tcp->tcp_sodirect != NULL) {
3891 			/* Ok, no more sodirect */
3892 			tcp->tcp_sodirect = NULL;
3893 		}
3894 
3895 		if (tcp->tcp_fused)
3896 			tcp_unfuse(tcp);
3897 
3898 		/*
3899 		 * If SO_LINGER has set a zero linger time, abort the
3900 		 * connection with a reset.
3901 		 */
3902 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3903 			msg = "tcp_close, zero lingertime";
3904 			break;
3905 		}
3906 
3907 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3908 		/*
3909 		 * Abort connection if there is unread data queued.
3910 		 */
3911 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3912 			msg = "tcp_close, unread data";
3913 			break;
3914 		}
3915 		/*
3916 		 * tcp_hard_bound is now cleared thus all packets go through
3917 		 * tcp_lookup. This fact is used by tcp_detach below.
3918 		 *
3919 		 * We have done a qwait() above which could have possibly
3920 		 * drained more messages in turn causing transition to a
3921 		 * different state. Check whether we have to do the rest
3922 		 * of the processing or not.
3923 		 */
3924 		if (tcp->tcp_state <= TCPS_LISTEN)
3925 			break;
3926 
3927 		/*
3928 		 * Transmit the FIN before detaching the tcp_t.
3929 		 * After tcp_detach returns this queue/perimeter
3930 		 * no longer owns the tcp_t thus others can modify it.
3931 		 */
3932 		(void) tcp_xmit_end(tcp);
3933 
3934 		/*
3935 		 * If lingering on close then wait until the fin is acked,
3936 		 * the SO_LINGER time passes, or a reset is sent/received.
3937 		 */
3938 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
3939 		    !(tcp->tcp_fin_acked) &&
3940 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3941 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3942 				tcp->tcp_client_errno = EWOULDBLOCK;
3943 			} else if (tcp->tcp_client_errno == 0) {
3944 
3945 				ASSERT(tcp->tcp_linger_tid == 0);
3946 
3947 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3948 				    tcp_close_linger_timeout,
3949 				    tcp->tcp_lingertime * hz);
3950 
3951 				/* tcp_close_linger_timeout will finish close */
3952 				if (tcp->tcp_linger_tid == 0)
3953 					tcp->tcp_client_errno = ENOSR;
3954 				else
3955 					return;
3956 			}
3957 
3958 			/*
3959 			 * Check if we need to detach or just close
3960 			 * the instance.
3961 			 */
3962 			if (tcp->tcp_state <= TCPS_LISTEN)
3963 				break;
3964 		}
3965 
3966 		/*
3967 		 * Make sure that no other thread will access the tcp_rq of
3968 		 * this instance (through lookups etc.) as tcp_rq will go
3969 		 * away shortly.
3970 		 */
3971 		tcp_acceptor_hash_remove(tcp);
3972 
3973 		mutex_enter(&tcp->tcp_non_sq_lock);
3974 		if (tcp->tcp_flow_stopped) {
3975 			tcp_clrqfull(tcp);
3976 		}
3977 		mutex_exit(&tcp->tcp_non_sq_lock);
3978 
3979 		if (tcp->tcp_timer_tid != 0) {
3980 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3981 			tcp->tcp_timer_tid = 0;
3982 		}
3983 		/*
3984 		 * Need to cancel those timers which will not be used when
3985 		 * TCP is detached.  This has to be done before the tcp_wq
3986 		 * is set to the global queue.
3987 		 */
3988 		tcp_timers_stop(tcp);
3989 
3990 		tcp->tcp_detached = B_TRUE;
3991 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3992 			tcp_time_wait_append(tcp);
3993 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3994 			ASSERT(connp->conn_ref >= 3);
3995 			goto finish;
3996 		}
3997 
3998 		/*
3999 		 * If delta is zero the timer event wasn't executed and was
4000 		 * successfully canceled. In this case we need to restart it
4001 		 * with the minimal delta possible.
4002 		 */
4003 		if (delta >= 0)
4004 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4005 			    delta ? delta : 1);
4006 
4007 		ASSERT(connp->conn_ref >= 3);
4008 		goto finish;
4009 	}
4010 
4011 	/* Detach did not complete. Still need to remove q from stream. */
4012 	if (msg) {
4013 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4014 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4015 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4016 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4017 		    tcp->tcp_state == TCPS_SYN_RCVD)
4018 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4019 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4020 	}
4021 
4022 	tcp_closei_local(tcp);
4023 	CONN_DEC_REF(connp);
4024 	ASSERT(connp->conn_ref >= 2);
4025 
4026 finish:
4027 	/*
4028 	 * Although packets are always processed on the correct
4029 	 * tcp's perimeter and access is serialized via squeue's,
4030 	 * IP still needs a queue when sending packets in time_wait
4031 	 * state so use WR(tcps_g_q) till ip_output() can be
4032 	 * changed to deal with just connp. For read side, we
4033 	 * could have set tcp_rq to NULL but there are some cases
4034 	 * in tcp_rput_data() from early days of this code which
4035 	 * do a putnext without checking if tcp is closed. Those
4036 	 * need to be identified before both tcp_rq and tcp_wq
4037 	 * can be set to NULL and tcps_g_q can disappear forever.
4038 	 */
4039 	mutex_enter(&tcp->tcp_closelock);
4040 	/*
4041 	 * Don't change the queues in the case of a listener that has
4042 	 * eagers in its q or q0. It could surprise the eagers.
4043 	 * Instead wait for the eagers outside the squeue.
4044 	 */
4045 	if (!tcp->tcp_wait_for_eagers) {
4046 		tcp->tcp_detached = B_TRUE;
4047 		/*
4048 		 * When default queue is closing we set tcps_g_q to NULL
4049 		 * after the close is done.
4050 		 */
4051 		ASSERT(tcps->tcps_g_q != NULL);
4052 		tcp->tcp_rq = tcps->tcps_g_q;
4053 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4054 	}
4055 
4056 	/* Signal tcp_close() to finish closing. */
4057 	tcp->tcp_closed = 1;
4058 	cv_signal(&tcp->tcp_closecv);
4059 	mutex_exit(&tcp->tcp_closelock);
4060 }
4061 
4062 
4063 /*
4064  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4065  * Some stream heads get upset if they see these later on as anything but NULL.
4066  */
4067 static void
4068 tcp_close_mpp(mblk_t **mpp)
4069 {
4070 	mblk_t	*mp;
4071 
4072 	if ((mp = *mpp) != NULL) {
4073 		do {
4074 			mp->b_next = NULL;
4075 			mp->b_prev = NULL;
4076 		} while ((mp = mp->b_cont) != NULL);
4077 
4078 		mp = *mpp;
4079 		*mpp = NULL;
4080 		freemsg(mp);
4081 	}
4082 }
4083 
4084 /* Do detached close. */
4085 static void
4086 tcp_close_detached(tcp_t *tcp)
4087 {
4088 	if (tcp->tcp_fused)
4089 		tcp_unfuse(tcp);
4090 
4091 	/*
4092 	 * Clustering code serializes TCP disconnect callbacks and
4093 	 * cluster tcp list walks by blocking a TCP disconnect callback
4094 	 * if a cluster tcp list walk is in progress. This ensures
4095 	 * accurate accounting of TCPs in the cluster code even though
4096 	 * the TCP list walk itself is not atomic.
4097 	 */
4098 	tcp_closei_local(tcp);
4099 	CONN_DEC_REF(tcp->tcp_connp);
4100 }
4101 
4102 /*
4103  * Stop all TCP timers, and free the timer mblks if requested.
4104  */
4105 void
4106 tcp_timers_stop(tcp_t *tcp)
4107 {
4108 	if (tcp->tcp_timer_tid != 0) {
4109 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4110 		tcp->tcp_timer_tid = 0;
4111 	}
4112 	if (tcp->tcp_ka_tid != 0) {
4113 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4114 		tcp->tcp_ka_tid = 0;
4115 	}
4116 	if (tcp->tcp_ack_tid != 0) {
4117 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4118 		tcp->tcp_ack_tid = 0;
4119 	}
4120 	if (tcp->tcp_push_tid != 0) {
4121 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4122 		tcp->tcp_push_tid = 0;
4123 	}
4124 }
4125 
4126 /*
4127  * The tcp_t is going away. Remove it from all lists and set it
4128  * to TCPS_CLOSED. The freeing up of memory is deferred until
4129  * tcp_inactive. This is needed since a thread in tcp_rput might have
4130  * done a CONN_INC_REF on this structure before it was removed from the
4131  * hashes.
4132  */
4133 static void
4134 tcp_closei_local(tcp_t *tcp)
4135 {
4136 	ire_t 	*ire;
4137 	conn_t	*connp = tcp->tcp_connp;
4138 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4139 
4140 	if (!TCP_IS_SOCKET(tcp))
4141 		tcp_acceptor_hash_remove(tcp);
4142 
4143 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4144 	tcp->tcp_ibsegs = 0;
4145 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4146 	tcp->tcp_obsegs = 0;
4147 
4148 	/*
4149 	 * If we are an eager connection hanging off a listener that
4150 	 * hasn't formally accepted the connection yet, get off his
4151 	 * list and blow off any data that we have accumulated.
4152 	 */
4153 	if (tcp->tcp_listener != NULL) {
4154 		tcp_t	*listener = tcp->tcp_listener;
4155 		mutex_enter(&listener->tcp_eager_lock);
4156 		/*
4157 		 * tcp_tconnind_started == B_TRUE means that the
4158 		 * conn_ind has already gone to listener. At
4159 		 * this point, eager will be closed but we
4160 		 * leave it in listeners eager list so that
4161 		 * if listener decides to close without doing
4162 		 * accept, we can clean this up. In tcp_wput_accept
4163 		 * we take care of the case of accept on closed
4164 		 * eager.
4165 		 */
4166 		if (!tcp->tcp_tconnind_started) {
4167 			tcp_eager_unlink(tcp);
4168 			mutex_exit(&listener->tcp_eager_lock);
4169 			/*
4170 			 * We don't want to have any pointers to the
4171 			 * listener queue, after we have released our
4172 			 * reference on the listener
4173 			 */
4174 			ASSERT(tcps->tcps_g_q != NULL);
4175 			tcp->tcp_rq = tcps->tcps_g_q;
4176 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4177 			CONN_DEC_REF(listener->tcp_connp);
4178 		} else {
4179 			mutex_exit(&listener->tcp_eager_lock);
4180 		}
4181 	}
4182 
4183 	/* Stop all the timers */
4184 	tcp_timers_stop(tcp);
4185 
4186 	if (tcp->tcp_state == TCPS_LISTEN) {
4187 		if (tcp->tcp_ip_addr_cache) {
4188 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4189 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4190 			tcp->tcp_ip_addr_cache = NULL;
4191 		}
4192 	}
4193 	mutex_enter(&tcp->tcp_non_sq_lock);
4194 	if (tcp->tcp_flow_stopped)
4195 		tcp_clrqfull(tcp);
4196 	mutex_exit(&tcp->tcp_non_sq_lock);
4197 
4198 	tcp_bind_hash_remove(tcp);
4199 	/*
4200 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4201 	 * is trying to remove this tcp from the time wait list, we will
4202 	 * block in tcp_time_wait_remove while trying to acquire the
4203 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4204 	 * requires the ipcl_hash_remove to be ordered after the
4205 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4206 	 */
4207 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4208 		(void) tcp_time_wait_remove(tcp, NULL);
4209 	CL_INET_DISCONNECT(connp, tcp);
4210 	ipcl_hash_remove(connp);
4211 
4212 	/*
4213 	 * Delete the cached ire in conn_ire_cache and also mark
4214 	 * the conn as CONDEMNED
4215 	 */
4216 	mutex_enter(&connp->conn_lock);
4217 	connp->conn_state_flags |= CONN_CONDEMNED;
4218 	ire = connp->conn_ire_cache;
4219 	connp->conn_ire_cache = NULL;
4220 	mutex_exit(&connp->conn_lock);
4221 	if (ire != NULL)
4222 		IRE_REFRELE_NOTR(ire);
4223 
4224 	/* Need to cleanup any pending ioctls */
4225 	ASSERT(tcp->tcp_time_wait_next == NULL);
4226 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4227 	ASSERT(tcp->tcp_time_wait_expire == 0);
4228 	tcp->tcp_state = TCPS_CLOSED;
4229 
4230 	/* Release any SSL context */
4231 	if (tcp->tcp_kssl_ent != NULL) {
4232 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4233 		tcp->tcp_kssl_ent = NULL;
4234 	}
4235 	if (tcp->tcp_kssl_ctx != NULL) {
4236 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4237 		tcp->tcp_kssl_ctx = NULL;
4238 	}
4239 	tcp->tcp_kssl_pending = B_FALSE;
4240 
4241 	tcp_ipsec_cleanup(tcp);
4242 }
4243 
4244 /*
4245  * tcp is dying (called from ipcl_conn_destroy and error cases).
4246  * Free the tcp_t in either case.
4247  */
4248 void
4249 tcp_free(tcp_t *tcp)
4250 {
4251 	mblk_t	*mp;
4252 	ip6_pkt_t	*ipp;
4253 
4254 	ASSERT(tcp != NULL);
4255 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4256 
4257 	tcp->tcp_rq = NULL;
4258 	tcp->tcp_wq = NULL;
4259 
4260 	tcp_close_mpp(&tcp->tcp_xmit_head);
4261 	tcp_close_mpp(&tcp->tcp_reass_head);
4262 	if (tcp->tcp_rcv_list != NULL) {
4263 		/* Free b_next chain */
4264 		tcp_close_mpp(&tcp->tcp_rcv_list);
4265 	}
4266 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4267 		freemsg(mp);
4268 	}
4269 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4270 		freemsg(mp);
4271 	}
4272 
4273 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4274 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4275 		freeb(tcp->tcp_fused_sigurg_mp);
4276 		tcp->tcp_fused_sigurg_mp = NULL;
4277 	}
4278 
4279 	if (tcp->tcp_ordrel_mp != NULL) {
4280 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4281 		freeb(tcp->tcp_ordrel_mp);
4282 		tcp->tcp_ordrel_mp = NULL;
4283 	}
4284 
4285 	if (tcp->tcp_sack_info != NULL) {
4286 		if (tcp->tcp_notsack_list != NULL) {
4287 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4288 		}
4289 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4290 	}
4291 
4292 	if (tcp->tcp_hopopts != NULL) {
4293 		mi_free(tcp->tcp_hopopts);
4294 		tcp->tcp_hopopts = NULL;
4295 		tcp->tcp_hopoptslen = 0;
4296 	}
4297 	ASSERT(tcp->tcp_hopoptslen == 0);
4298 	if (tcp->tcp_dstopts != NULL) {
4299 		mi_free(tcp->tcp_dstopts);
4300 		tcp->tcp_dstopts = NULL;
4301 		tcp->tcp_dstoptslen = 0;
4302 	}
4303 	ASSERT(tcp->tcp_dstoptslen == 0);
4304 	if (tcp->tcp_rtdstopts != NULL) {
4305 		mi_free(tcp->tcp_rtdstopts);
4306 		tcp->tcp_rtdstopts = NULL;
4307 		tcp->tcp_rtdstoptslen = 0;
4308 	}
4309 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4310 	if (tcp->tcp_rthdr != NULL) {
4311 		mi_free(tcp->tcp_rthdr);
4312 		tcp->tcp_rthdr = NULL;
4313 		tcp->tcp_rthdrlen = 0;
4314 	}
4315 	ASSERT(tcp->tcp_rthdrlen == 0);
4316 
4317 	ipp = &tcp->tcp_sticky_ipp;
4318 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4319 	    IPPF_RTHDR))
4320 		ip6_pkt_free(ipp);
4321 
4322 	/*
4323 	 * Free memory associated with the tcp/ip header template.
4324 	 */
4325 
4326 	if (tcp->tcp_iphc != NULL)
4327 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4328 
4329 	/*
4330 	 * Following is really a blowing away a union.
4331 	 * It happens to have exactly two members of identical size
4332 	 * the following code is enough.
4333 	 */
4334 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4335 }
4336 
4337 
4338 /*
4339  * Put a connection confirmation message upstream built from the
4340  * address information within 'iph' and 'tcph'.  Report our success or failure.
4341  */
4342 static boolean_t
4343 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4344     mblk_t **defermp)
4345 {
4346 	sin_t	sin;
4347 	sin6_t	sin6;
4348 	mblk_t	*mp;
4349 	char	*optp = NULL;
4350 	int	optlen = 0;
4351 
4352 	if (defermp != NULL)
4353 		*defermp = NULL;
4354 
4355 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4356 		/*
4357 		 * Return in T_CONN_CON results of option negotiation through
4358 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4359 		 * negotiation, then what is received from remote end needs
4360 		 * to be taken into account but there is no such thing (yet?)
4361 		 * in our TCP/IP.
4362 		 * Note: We do not use mi_offset_param() here as
4363 		 * tcp_opts_conn_req contents do not directly come from
4364 		 * an application and are either generated in kernel or
4365 		 * from user input that was already verified.
4366 		 */
4367 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4368 		optp = (char *)(mp->b_rptr +
4369 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4370 		optlen = (int)
4371 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4372 	}
4373 
4374 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4375 		ipha_t *ipha = (ipha_t *)iphdr;
4376 
4377 		/* packet is IPv4 */
4378 		if (tcp->tcp_family == AF_INET) {
4379 			sin = sin_null;
4380 			sin.sin_addr.s_addr = ipha->ipha_src;
4381 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4382 			sin.sin_family = AF_INET;
4383 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4384 			    (int)sizeof (sin_t), optp, optlen);
4385 		} else {
4386 			sin6 = sin6_null;
4387 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4388 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4389 			sin6.sin6_family = AF_INET6;
4390 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4391 			    (int)sizeof (sin6_t), optp, optlen);
4392 
4393 		}
4394 	} else {
4395 		ip6_t	*ip6h = (ip6_t *)iphdr;
4396 
4397 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4398 		ASSERT(tcp->tcp_family == AF_INET6);
4399 		sin6 = sin6_null;
4400 		sin6.sin6_addr = ip6h->ip6_src;
4401 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4402 		sin6.sin6_family = AF_INET6;
4403 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4404 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4405 		    (int)sizeof (sin6_t), optp, optlen);
4406 	}
4407 
4408 	if (!mp)
4409 		return (B_FALSE);
4410 
4411 	mblk_copycred(mp, idmp);
4412 
4413 	if (defermp == NULL) {
4414 		conn_t *connp = tcp->tcp_connp;
4415 		if (IPCL_IS_NONSTR(connp)) {
4416 			cred_t *cr;
4417 			pid_t cpid;
4418 
4419 			cr = msg_getcred(mp, &cpid);
4420 			(*connp->conn_upcalls->su_connected)
4421 			    (connp->conn_upper_handle, tcp->tcp_connid, cr,
4422 			    cpid);
4423 			freemsg(mp);
4424 		} else {
4425 			putnext(tcp->tcp_rq, mp);
4426 		}
4427 	} else {
4428 		*defermp = mp;
4429 	}
4430 
4431 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4432 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4433 	return (B_TRUE);
4434 }
4435 
4436 /*
4437  * Defense for the SYN attack -
4438  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4439  *    one from the list of droppable eagers. This list is a subset of q0.
4440  *    see comments before the definition of MAKE_DROPPABLE().
4441  * 2. Don't drop a SYN request before its first timeout. This gives every
4442  *    request at least til the first timeout to complete its 3-way handshake.
4443  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4444  *    requests currently on the queue that has timed out. This will be used
4445  *    as an indicator of whether an attack is under way, so that appropriate
4446  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4447  *    either when eager goes into ESTABLISHED, or gets freed up.)
4448  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4449  *    # of timeout drops back to <= q0len/32 => SYN alert off
4450  */
4451 static boolean_t
4452 tcp_drop_q0(tcp_t *tcp)
4453 {
4454 	tcp_t	*eager;
4455 	mblk_t	*mp;
4456 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4457 
4458 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4459 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4460 
4461 	/* Pick oldest eager from the list of droppable eagers */
4462 	eager = tcp->tcp_eager_prev_drop_q0;
4463 
4464 	/* If list is empty. return B_FALSE */
4465 	if (eager == tcp) {
4466 		return (B_FALSE);
4467 	}
4468 
4469 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4470 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4471 		return (B_FALSE);
4472 
4473 	/*
4474 	 * Take this eager out from the list of droppable eagers since we are
4475 	 * going to drop it.
4476 	 */
4477 	MAKE_UNDROPPABLE(eager);
4478 
4479 	if (tcp->tcp_debug) {
4480 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4481 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4482 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4483 		    tcp->tcp_conn_req_cnt_q0,
4484 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4485 	}
4486 
4487 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4488 
4489 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4490 	CONN_INC_REF(eager->tcp_connp);
4491 
4492 	/* Mark the IRE created for this SYN request temporary */
4493 	tcp_ip_ire_mark_advice(eager);
4494 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4495 	    tcp_clean_death_wrapper, eager->tcp_connp,
4496 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4497 
4498 	return (B_TRUE);
4499 }
4500 
4501 int
4502 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4503     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4504 {
4505 	tcp_t 		*ltcp = lconnp->conn_tcp;
4506 	tcp_t		*tcp = connp->conn_tcp;
4507 	mblk_t		*tpi_mp;
4508 	ipha_t		*ipha;
4509 	ip6_t		*ip6h;
4510 	sin6_t 		sin6;
4511 	in6_addr_t 	v6dst;
4512 	int		err;
4513 	int		ifindex = 0;
4514 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4515 
4516 	if (ipvers == IPV4_VERSION) {
4517 		ipha = (ipha_t *)mp->b_rptr;
4518 
4519 		connp->conn_send = ip_output;
4520 		connp->conn_recv = tcp_input;
4521 
4522 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4523 		    &connp->conn_bound_source_v6);
4524 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4525 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4526 
4527 		sin6 = sin6_null;
4528 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4529 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4530 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4531 		sin6.sin6_family = AF_INET6;
4532 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4533 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4534 		if (tcp->tcp_recvdstaddr) {
4535 			sin6_t	sin6d;
4536 
4537 			sin6d = sin6_null;
4538 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4539 			    &sin6d.sin6_addr);
4540 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4541 			sin6d.sin6_family = AF_INET;
4542 			tpi_mp = mi_tpi_extconn_ind(NULL,
4543 			    (char *)&sin6d, sizeof (sin6_t),
4544 			    (char *)&tcp,
4545 			    (t_scalar_t)sizeof (intptr_t),
4546 			    (char *)&sin6d, sizeof (sin6_t),
4547 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4548 		} else {
4549 			tpi_mp = mi_tpi_conn_ind(NULL,
4550 			    (char *)&sin6, sizeof (sin6_t),
4551 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4552 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4553 		}
4554 	} else {
4555 		ip6h = (ip6_t *)mp->b_rptr;
4556 
4557 		connp->conn_send = ip_output_v6;
4558 		connp->conn_recv = tcp_input;
4559 
4560 		connp->conn_bound_source_v6 = ip6h->ip6_dst;
4561 		connp->conn_srcv6 = ip6h->ip6_dst;
4562 		connp->conn_remv6 = ip6h->ip6_src;
4563 
4564 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4565 		ifindex = (int)DB_CKSUMSTUFF(mp);
4566 		DB_CKSUMSTUFF(mp) = 0;
4567 
4568 		sin6 = sin6_null;
4569 		sin6.sin6_addr = ip6h->ip6_src;
4570 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4571 		sin6.sin6_family = AF_INET6;
4572 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4573 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4574 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4575 
4576 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4577 			/* Pass up the scope_id of remote addr */
4578 			sin6.sin6_scope_id = ifindex;
4579 		} else {
4580 			sin6.sin6_scope_id = 0;
4581 		}
4582 		if (tcp->tcp_recvdstaddr) {
4583 			sin6_t	sin6d;
4584 
4585 			sin6d = sin6_null;
4586 			sin6.sin6_addr = ip6h->ip6_dst;
4587 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4588 			sin6d.sin6_family = AF_INET;
4589 			tpi_mp = mi_tpi_extconn_ind(NULL,
4590 			    (char *)&sin6d, sizeof (sin6_t),
4591 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4592 			    (char *)&sin6d, sizeof (sin6_t),
4593 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4594 		} else {
4595 			tpi_mp = mi_tpi_conn_ind(NULL,
4596 			    (char *)&sin6, sizeof (sin6_t),
4597 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4598 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4599 		}
4600 	}
4601 
4602 	if (tpi_mp == NULL)
4603 		return (ENOMEM);
4604 
4605 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4606 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4607 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4608 	connp->conn_fully_bound = B_FALSE;
4609 
4610 	/* Inherit information from the "parent" */
4611 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4612 	tcp->tcp_family = ltcp->tcp_family;
4613 
4614 	tcp->tcp_wq = ltcp->tcp_wq;
4615 	tcp->tcp_rq = ltcp->tcp_rq;
4616 
4617 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4618 	tcp->tcp_detached = B_TRUE;
4619 	SOCK_CONNID_INIT(tcp->tcp_connid);
4620 	if ((err = tcp_init_values(tcp)) != 0) {
4621 		freemsg(tpi_mp);
4622 		return (err);
4623 	}
4624 
4625 	if (ipvers == IPV4_VERSION) {
4626 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4627 			freemsg(tpi_mp);
4628 			return (err);
4629 		}
4630 		ASSERT(tcp->tcp_ipha != NULL);
4631 	} else {
4632 		/* ifindex must be already set */
4633 		ASSERT(ifindex != 0);
4634 
4635 		if (ltcp->tcp_bound_if != 0)
4636 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4637 		else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src))
4638 			tcp->tcp_bound_if = ifindex;
4639 
4640 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4641 		tcp->tcp_recvifindex = 0;
4642 		tcp->tcp_recvhops = 0xffffffffU;
4643 		ASSERT(tcp->tcp_ip6h != NULL);
4644 	}
4645 
4646 	tcp->tcp_lport = ltcp->tcp_lport;
4647 
4648 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4649 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4650 			/*
4651 			 * Listener had options of some sort; eager inherits.
4652 			 * Free up the eager template and allocate one
4653 			 * of the right size.
4654 			 */
4655 			if (tcp->tcp_hdr_grown) {
4656 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4657 			} else {
4658 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4659 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4660 			}
4661 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4662 			    KM_NOSLEEP);
4663 			if (tcp->tcp_iphc == NULL) {
4664 				tcp->tcp_iphc_len = 0;
4665 				freemsg(tpi_mp);
4666 				return (ENOMEM);
4667 			}
4668 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4669 			tcp->tcp_hdr_grown = B_TRUE;
4670 		}
4671 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4672 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4673 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4674 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4675 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4676 
4677 		/*
4678 		 * Copy the IP+TCP header template from listener to eager
4679 		 */
4680 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4681 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4682 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4683 			    IPPROTO_RAW) {
4684 				tcp->tcp_ip6h =
4685 				    (ip6_t *)(tcp->tcp_iphc +
4686 				    sizeof (ip6i_t));
4687 			} else {
4688 				tcp->tcp_ip6h =
4689 				    (ip6_t *)(tcp->tcp_iphc);
4690 			}
4691 			tcp->tcp_ipha = NULL;
4692 		} else {
4693 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4694 			tcp->tcp_ip6h = NULL;
4695 		}
4696 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4697 		    tcp->tcp_ip_hdr_len);
4698 	} else {
4699 		/*
4700 		 * only valid case when ipversion of listener and
4701 		 * eager differ is when listener is IPv6 and
4702 		 * eager is IPv4.
4703 		 * Eager header template has been initialized to the
4704 		 * maximum v4 header sizes, which includes space for
4705 		 * TCP and IP options.
4706 		 */
4707 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4708 		    (tcp->tcp_ipversion == IPV4_VERSION));
4709 		ASSERT(tcp->tcp_iphc_len >=
4710 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4711 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4712 		/* copy IP header fields individually */
4713 		tcp->tcp_ipha->ipha_ttl =
4714 		    ltcp->tcp_ip6h->ip6_hops;
4715 		bcopy(ltcp->tcp_tcph->th_lport,
4716 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4717 	}
4718 
4719 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4720 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4721 	    sizeof (in_port_t));
4722 
4723 	if (ltcp->tcp_lport == 0) {
4724 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4725 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4726 		    sizeof (in_port_t));
4727 	}
4728 
4729 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4730 		ASSERT(ipha != NULL);
4731 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4732 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4733 
4734 		/* Source routing option copyover (reverse it) */
4735 		if (tcps->tcps_rev_src_routes)
4736 			tcp_opt_reverse(tcp, ipha);
4737 	} else {
4738 		ASSERT(ip6h != NULL);
4739 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4740 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4741 	}
4742 
4743 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4744 	ASSERT(!tcp->tcp_tconnind_started);
4745 	/*
4746 	 * If the SYN contains a credential, it's a loopback packet; attach
4747 	 * the credential to the TPI message.
4748 	 */
4749 	mblk_copycred(tpi_mp, idmp);
4750 
4751 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4752 
4753 	/* Inherit the listener's SSL protection state */
4754 
4755 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4756 		kssl_hold_ent(tcp->tcp_kssl_ent);
4757 		tcp->tcp_kssl_pending = B_TRUE;
4758 	}
4759 
4760 	/* Inherit the listener's non-STREAMS flag */
4761 	if (IPCL_IS_NONSTR(lconnp)) {
4762 		connp->conn_flags |= IPCL_NONSTR;
4763 	}
4764 
4765 	return (0);
4766 }
4767 
4768 
4769 int
4770 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4771     tcph_t *tcph, mblk_t *idmp)
4772 {
4773 	tcp_t 		*ltcp = lconnp->conn_tcp;
4774 	tcp_t		*tcp = connp->conn_tcp;
4775 	sin_t		sin;
4776 	mblk_t		*tpi_mp = NULL;
4777 	int		err;
4778 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4779 
4780 	sin = sin_null;
4781 	sin.sin_addr.s_addr = ipha->ipha_src;
4782 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4783 	sin.sin_family = AF_INET;
4784 	if (ltcp->tcp_recvdstaddr) {
4785 		sin_t	sind;
4786 
4787 		sind = sin_null;
4788 		sind.sin_addr.s_addr = ipha->ipha_dst;
4789 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4790 		sind.sin_family = AF_INET;
4791 		tpi_mp = mi_tpi_extconn_ind(NULL,
4792 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4793 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4794 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4795 	} else {
4796 		tpi_mp = mi_tpi_conn_ind(NULL,
4797 		    (char *)&sin, sizeof (sin_t),
4798 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4799 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4800 	}
4801 
4802 	if (tpi_mp == NULL) {
4803 		return (ENOMEM);
4804 	}
4805 
4806 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4807 	connp->conn_send = ip_output;
4808 	connp->conn_recv = tcp_input;
4809 	connp->conn_fully_bound = B_FALSE;
4810 
4811 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_bound_source_v6);
4812 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4813 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4814 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4815 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4816 
4817 	/* Inherit information from the "parent" */
4818 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4819 	tcp->tcp_family = ltcp->tcp_family;
4820 	tcp->tcp_wq = ltcp->tcp_wq;
4821 	tcp->tcp_rq = ltcp->tcp_rq;
4822 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4823 	tcp->tcp_detached = B_TRUE;
4824 	SOCK_CONNID_INIT(tcp->tcp_connid);
4825 	if ((err = tcp_init_values(tcp)) != 0) {
4826 		freemsg(tpi_mp);
4827 		return (err);
4828 	}
4829 
4830 	/*
4831 	 * Let's make sure that eager tcp template has enough space to
4832 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4833 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4834 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4835 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4836 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4837 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4838 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4839 	 */
4840 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4841 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4842 
4843 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4844 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4845 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4846 	tcp->tcp_ttl = ltcp->tcp_ttl;
4847 	tcp->tcp_tos = ltcp->tcp_tos;
4848 
4849 	/* Copy the IP+TCP header template from listener to eager */
4850 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4851 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4852 	tcp->tcp_ip6h = NULL;
4853 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4854 	    tcp->tcp_ip_hdr_len);
4855 
4856 	/* Initialize the IP addresses and Ports */
4857 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4858 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4859 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4860 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4861 
4862 	/* Source routing option copyover (reverse it) */
4863 	if (tcps->tcps_rev_src_routes)
4864 		tcp_opt_reverse(tcp, ipha);
4865 
4866 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4867 	ASSERT(!tcp->tcp_tconnind_started);
4868 
4869 	/*
4870 	 * If the SYN contains a credential, it's a loopback packet; attach
4871 	 * the credential to the TPI message.
4872 	 */
4873 	mblk_copycred(tpi_mp, idmp);
4874 
4875 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4876 
4877 	/* Inherit the listener's SSL protection state */
4878 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4879 		kssl_hold_ent(tcp->tcp_kssl_ent);
4880 		tcp->tcp_kssl_pending = B_TRUE;
4881 	}
4882 
4883 	/* Inherit the listener's non-STREAMS flag */
4884 	if (IPCL_IS_NONSTR(lconnp)) {
4885 		connp->conn_flags |= IPCL_NONSTR;
4886 	}
4887 
4888 	return (0);
4889 }
4890 
4891 /*
4892  * sets up conn for ipsec.
4893  * if the first mblk is M_CTL it is consumed and mpp is updated.
4894  * in case of error mpp is freed.
4895  */
4896 conn_t *
4897 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4898 {
4899 	conn_t 		*connp = tcp->tcp_connp;
4900 	conn_t 		*econnp;
4901 	squeue_t 	*new_sqp;
4902 	mblk_t 		*first_mp = *mpp;
4903 	mblk_t		*mp = *mpp;
4904 	boolean_t	mctl_present = B_FALSE;
4905 	uint_t		ipvers;
4906 
4907 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
4908 	if (econnp == NULL) {
4909 		freemsg(first_mp);
4910 		return (NULL);
4911 	}
4912 	if (DB_TYPE(mp) == M_CTL) {
4913 		if (mp->b_cont == NULL ||
4914 		    mp->b_cont->b_datap->db_type != M_DATA) {
4915 			freemsg(first_mp);
4916 			return (NULL);
4917 		}
4918 		mp = mp->b_cont;
4919 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4920 			freemsg(first_mp);
4921 			return (NULL);
4922 		}
4923 
4924 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4925 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4926 		mctl_present = B_TRUE;
4927 	} else {
4928 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4929 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4930 	}
4931 
4932 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4933 	DB_CKSUMSTART(mp) = 0;
4934 
4935 	ASSERT(OK_32PTR(mp->b_rptr));
4936 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
4937 	if (ipvers == IPV4_VERSION) {
4938 		uint16_t  	*up;
4939 		uint32_t	ports;
4940 		ipha_t		*ipha;
4941 
4942 		ipha = (ipha_t *)mp->b_rptr;
4943 		up = (uint16_t *)((uchar_t *)ipha +
4944 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
4945 		ports = *(uint32_t *)up;
4946 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
4947 		    ipha->ipha_dst, ipha->ipha_src, ports);
4948 	} else {
4949 		uint16_t  	*up;
4950 		uint32_t	ports;
4951 		uint16_t	ip_hdr_len;
4952 		uint8_t		*nexthdrp;
4953 		ip6_t 		*ip6h;
4954 		tcph_t		*tcph;
4955 
4956 		ip6h = (ip6_t *)mp->b_rptr;
4957 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
4958 			ip_hdr_len = IPV6_HDR_LEN;
4959 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
4960 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
4961 			CONN_DEC_REF(econnp);
4962 			freemsg(first_mp);
4963 			return (NULL);
4964 		}
4965 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
4966 		up = (uint16_t *)tcph->th_lport;
4967 		ports = *(uint32_t *)up;
4968 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
4969 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
4970 	}
4971 
4972 	/*
4973 	 * The caller already ensured that there is a sqp present.
4974 	 */
4975 	econnp->conn_sqp = new_sqp;
4976 	econnp->conn_initial_sqp = new_sqp;
4977 
4978 	if (connp->conn_policy != NULL) {
4979 		ipsec_in_t *ii;
4980 		ii = (ipsec_in_t *)(first_mp->b_rptr);
4981 		ASSERT(ii->ipsec_in_policy == NULL);
4982 		IPPH_REFHOLD(connp->conn_policy);
4983 		ii->ipsec_in_policy = connp->conn_policy;
4984 
4985 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
4986 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
4987 			CONN_DEC_REF(econnp);
4988 			freemsg(first_mp);
4989 			return (NULL);
4990 		}
4991 	}
4992 
4993 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
4994 		CONN_DEC_REF(econnp);
4995 		freemsg(first_mp);
4996 		return (NULL);
4997 	}
4998 
4999 	/*
5000 	 * If we know we have some policy, pass the "IPSEC"
5001 	 * options size TCP uses this adjust the MSS.
5002 	 */
5003 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5004 	if (mctl_present) {
5005 		freeb(first_mp);
5006 		*mpp = mp;
5007 	}
5008 
5009 	return (econnp);
5010 }
5011 
5012 /*
5013  * tcp_get_conn/tcp_free_conn
5014  *
5015  * tcp_get_conn is used to get a clean tcp connection structure.
5016  * It tries to reuse the connections put on the freelist by the
5017  * time_wait_collector failing which it goes to kmem_cache. This
5018  * way has two benefits compared to just allocating from and
5019  * freeing to kmem_cache.
5020  * 1) The time_wait_collector can free (which includes the cleanup)
5021  * outside the squeue. So when the interrupt comes, we have a clean
5022  * connection sitting in the freelist. Obviously, this buys us
5023  * performance.
5024  *
5025  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5026  * has multiple disadvantages - tying up the squeue during alloc, and the
5027  * fact that IPSec policy initialization has to happen here which
5028  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5029  * But allocating the conn/tcp in IP land is also not the best since
5030  * we can't check the 'q' and 'q0' which are protected by squeue and
5031  * blindly allocate memory which might have to be freed here if we are
5032  * not allowed to accept the connection. By using the freelist and
5033  * putting the conn/tcp back in freelist, we don't pay a penalty for
5034  * allocating memory without checking 'q/q0' and freeing it if we can't
5035  * accept the connection.
5036  *
5037  * Care should be taken to put the conn back in the same squeue's freelist
5038  * from which it was allocated. Best results are obtained if conn is
5039  * allocated from listener's squeue and freed to the same. Time wait
5040  * collector will free up the freelist is the connection ends up sitting
5041  * there for too long.
5042  */
5043 void *
5044 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5045 {
5046 	tcp_t			*tcp = NULL;
5047 	conn_t			*connp = NULL;
5048 	squeue_t		*sqp = (squeue_t *)arg;
5049 	tcp_squeue_priv_t 	*tcp_time_wait;
5050 	netstack_t		*ns;
5051 	mblk_t			*rsrv_mp;
5052 
5053 	tcp_time_wait =
5054 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5055 
5056 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5057 	tcp = tcp_time_wait->tcp_free_list;
5058 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5059 	if (tcp != NULL) {
5060 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5061 		tcp_time_wait->tcp_free_list_cnt--;
5062 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5063 		tcp->tcp_time_wait_next = NULL;
5064 		connp = tcp->tcp_connp;
5065 		connp->conn_flags |= IPCL_REUSED;
5066 
5067 		ASSERT(tcp->tcp_tcps == NULL);
5068 		ASSERT(connp->conn_netstack == NULL);
5069 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5070 		ns = tcps->tcps_netstack;
5071 		netstack_hold(ns);
5072 		connp->conn_netstack = ns;
5073 		tcp->tcp_tcps = tcps;
5074 		TCPS_REFHOLD(tcps);
5075 		ipcl_globalhash_insert(connp);
5076 		return ((void *)connp);
5077 	}
5078 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5079 	/*
5080 	 * Pre-allocate the tcp_rsrv_mp.  This mblk will not be freed
5081 	 * until this conn_t/tcp_t is freed at ipcl_conn_destroy().
5082 	 */
5083 	if ((rsrv_mp = allocb(0, BPRI_HI)) == NULL)
5084 		return (NULL);
5085 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5086 	    tcps->tcps_netstack)) == NULL) {
5087 		freeb(rsrv_mp);
5088 		return (NULL);
5089 	}
5090 	tcp = connp->conn_tcp;
5091 	tcp->tcp_rsrv_mp = rsrv_mp;
5092 
5093 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5094 	tcp->tcp_tcps = tcps;
5095 	TCPS_REFHOLD(tcps);
5096 
5097 	return ((void *)connp);
5098 }
5099 
5100 /*
5101  * Update the cached label for the given tcp_t.  This should be called once per
5102  * connection, and before any packets are sent or tcp_process_options is
5103  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5104  */
5105 static boolean_t
5106 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5107 {
5108 	conn_t *connp = tcp->tcp_connp;
5109 
5110 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5111 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5112 		int added;
5113 
5114 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5115 		    connp->conn_mac_exempt,
5116 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5117 			return (B_FALSE);
5118 
5119 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5120 		if (added == -1)
5121 			return (B_FALSE);
5122 		tcp->tcp_hdr_len += added;
5123 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5124 		tcp->tcp_ip_hdr_len += added;
5125 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5126 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5127 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5128 			    tcp->tcp_hdr_len);
5129 			if (added == -1)
5130 				return (B_FALSE);
5131 			tcp->tcp_hdr_len += added;
5132 			tcp->tcp_tcph = (tcph_t *)
5133 			    ((uchar_t *)tcp->tcp_tcph + added);
5134 			tcp->tcp_ip_hdr_len += added;
5135 		}
5136 	} else {
5137 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5138 
5139 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5140 		    connp->conn_mac_exempt,
5141 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5142 			return (B_FALSE);
5143 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5144 		    &tcp->tcp_label_len, optbuf) != 0)
5145 			return (B_FALSE);
5146 		if (tcp_build_hdrs(tcp) != 0)
5147 			return (B_FALSE);
5148 	}
5149 
5150 	connp->conn_ulp_labeled = 1;
5151 
5152 	return (B_TRUE);
5153 }
5154 
5155 /* BEGIN CSTYLED */
5156 /*
5157  *
5158  * The sockfs ACCEPT path:
5159  * =======================
5160  *
5161  * The eager is now established in its own perimeter as soon as SYN is
5162  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5163  * completes the accept processing on the acceptor STREAM. The sending
5164  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5165  * listener but a TLI/XTI listener completes the accept processing
5166  * on the listener perimeter.
5167  *
5168  * Common control flow for 3 way handshake:
5169  * ----------------------------------------
5170  *
5171  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5172  *					-> tcp_conn_request()
5173  *
5174  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5175  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5176  *
5177  * Sockfs ACCEPT Path:
5178  * -------------------
5179  *
5180  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5181  * as STREAM entry point)
5182  *
5183  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5184  *
5185  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5186  * association (we are not behind eager's squeue but sockfs is protecting us
5187  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5188  * is changed to point at tcp_wput().
5189  *
5190  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5191  * listener (done on listener's perimeter).
5192  *
5193  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5194  * accept.
5195  *
5196  * TLI/XTI client ACCEPT path:
5197  * ---------------------------
5198  *
5199  * soaccept() sends T_CONN_RES on the listener STREAM.
5200  *
5201  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5202  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5203  *
5204  * Locks:
5205  * ======
5206  *
5207  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5208  * and listeners->tcp_eager_next_q.
5209  *
5210  * Referencing:
5211  * ============
5212  *
5213  * 1) We start out in tcp_conn_request by eager placing a ref on
5214  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5215  *
5216  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5217  * doing so we place a ref on the eager. This ref is finally dropped at the
5218  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5219  * reference is dropped by the squeue framework.
5220  *
5221  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5222  *
5223  * The reference must be released by the same entity that added the reference
5224  * In the above scheme, the eager is the entity that adds and releases the
5225  * references. Note that tcp_accept_finish executes in the squeue of the eager
5226  * (albeit after it is attached to the acceptor stream). Though 1. executes
5227  * in the listener's squeue, the eager is nascent at this point and the
5228  * reference can be considered to have been added on behalf of the eager.
5229  *
5230  * Eager getting a Reset or listener closing:
5231  * ==========================================
5232  *
5233  * Once the listener and eager are linked, the listener never does the unlink.
5234  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5235  * a message on all eager perimeter. The eager then does the unlink, clears
5236  * any pointers to the listener's queue and drops the reference to the
5237  * listener. The listener waits in tcp_close outside the squeue until its
5238  * refcount has dropped to 1. This ensures that the listener has waited for
5239  * all eagers to clear their association with the listener.
5240  *
5241  * Similarly, if eager decides to go away, it can unlink itself and close.
5242  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5243  * the reference to eager is still valid because of the extra ref we put
5244  * in tcp_send_conn_ind.
5245  *
5246  * Listener can always locate the eager under the protection
5247  * of the listener->tcp_eager_lock, and then do a refhold
5248  * on the eager during the accept processing.
5249  *
5250  * The acceptor stream accesses the eager in the accept processing
5251  * based on the ref placed on eager before sending T_conn_ind.
5252  * The only entity that can negate this refhold is a listener close
5253  * which is mutually exclusive with an active acceptor stream.
5254  *
5255  * Eager's reference on the listener
5256  * ===================================
5257  *
5258  * If the accept happens (even on a closed eager) the eager drops its
5259  * reference on the listener at the start of tcp_accept_finish. If the
5260  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5261  * the reference is dropped in tcp_closei_local. If the listener closes,
5262  * the reference is dropped in tcp_eager_kill. In all cases the reference
5263  * is dropped while executing in the eager's context (squeue).
5264  */
5265 /* END CSTYLED */
5266 
5267 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5268 
5269 /*
5270  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5271  * tcp_rput_data will not see any SYN packets.
5272  */
5273 /* ARGSUSED */
5274 void
5275 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5276 {
5277 	tcph_t		*tcph;
5278 	uint32_t	seg_seq;
5279 	tcp_t		*eager;
5280 	uint_t		ipvers;
5281 	ipha_t		*ipha;
5282 	ip6_t		*ip6h;
5283 	int		err;
5284 	conn_t		*econnp = NULL;
5285 	squeue_t	*new_sqp;
5286 	mblk_t		*mp1;
5287 	uint_t 		ip_hdr_len;
5288 	conn_t		*connp = (conn_t *)arg;
5289 	tcp_t		*tcp = connp->conn_tcp;
5290 	cred_t		*credp;
5291 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5292 	ip_stack_t	*ipst;
5293 
5294 	if (tcp->tcp_state != TCPS_LISTEN)
5295 		goto error2;
5296 
5297 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5298 
5299 	mutex_enter(&tcp->tcp_eager_lock);
5300 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5301 		mutex_exit(&tcp->tcp_eager_lock);
5302 		TCP_STAT(tcps, tcp_listendrop);
5303 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5304 		if (tcp->tcp_debug) {
5305 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5306 			    "tcp_conn_request: listen backlog (max=%d) "
5307 			    "overflow (%d pending) on %s",
5308 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5309 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5310 		}
5311 		goto error2;
5312 	}
5313 
5314 	if (tcp->tcp_conn_req_cnt_q0 >=
5315 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5316 		/*
5317 		 * Q0 is full. Drop a pending half-open req from the queue
5318 		 * to make room for the new SYN req. Also mark the time we
5319 		 * drop a SYN.
5320 		 *
5321 		 * A more aggressive defense against SYN attack will
5322 		 * be to set the "tcp_syn_defense" flag now.
5323 		 */
5324 		TCP_STAT(tcps, tcp_listendropq0);
5325 		tcp->tcp_last_rcv_lbolt = lbolt64;
5326 		if (!tcp_drop_q0(tcp)) {
5327 			mutex_exit(&tcp->tcp_eager_lock);
5328 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5329 			if (tcp->tcp_debug) {
5330 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5331 				    "tcp_conn_request: listen half-open queue "
5332 				    "(max=%d) full (%d pending) on %s",
5333 				    tcps->tcps_conn_req_max_q0,
5334 				    tcp->tcp_conn_req_cnt_q0,
5335 				    tcp_display(tcp, NULL,
5336 				    DISP_PORT_ONLY));
5337 			}
5338 			goto error2;
5339 		}
5340 	}
5341 	mutex_exit(&tcp->tcp_eager_lock);
5342 
5343 	/*
5344 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5345 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5346 	 * link local address.  If IPSec is enabled, db_struioflag has
5347 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5348 	 * otherwise an error case if neither of them is set.
5349 	 */
5350 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5351 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5352 		DB_CKSUMSTART(mp) = 0;
5353 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5354 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5355 		if (econnp == NULL)
5356 			goto error2;
5357 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5358 		econnp->conn_sqp = new_sqp;
5359 		econnp->conn_initial_sqp = new_sqp;
5360 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5361 		/*
5362 		 * mp is updated in tcp_get_ipsec_conn().
5363 		 */
5364 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5365 		if (econnp == NULL) {
5366 			/*
5367 			 * mp freed by tcp_get_ipsec_conn.
5368 			 */
5369 			return;
5370 		}
5371 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5372 	} else {
5373 		goto error2;
5374 	}
5375 
5376 	ASSERT(DB_TYPE(mp) == M_DATA);
5377 
5378 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5379 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5380 	ASSERT(OK_32PTR(mp->b_rptr));
5381 	if (ipvers == IPV4_VERSION) {
5382 		ipha = (ipha_t *)mp->b_rptr;
5383 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5384 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5385 	} else {
5386 		ip6h = (ip6_t *)mp->b_rptr;
5387 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5388 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5389 	}
5390 
5391 	if (tcp->tcp_family == AF_INET) {
5392 		ASSERT(ipvers == IPV4_VERSION);
5393 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5394 	} else {
5395 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5396 	}
5397 
5398 	if (err)
5399 		goto error3;
5400 
5401 	eager = econnp->conn_tcp;
5402 
5403 	/*
5404 	 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that at close
5405 	 * time, we will always have that to send up.  Otherwise, we need to do
5406 	 * special handling in case the allocation fails at that time.
5407 	 */
5408 	ASSERT(eager->tcp_ordrel_mp == NULL);
5409 	if (!IPCL_IS_NONSTR(econnp) &&
5410 	    (eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5411 		goto error3;
5412 
5413 	/* Inherit various TCP parameters from the listener */
5414 	eager->tcp_naglim = tcp->tcp_naglim;
5415 	eager->tcp_first_timer_threshold =
5416 	    tcp->tcp_first_timer_threshold;
5417 	eager->tcp_second_timer_threshold =
5418 	    tcp->tcp_second_timer_threshold;
5419 
5420 	eager->tcp_first_ctimer_threshold =
5421 	    tcp->tcp_first_ctimer_threshold;
5422 	eager->tcp_second_ctimer_threshold =
5423 	    tcp->tcp_second_ctimer_threshold;
5424 
5425 	/*
5426 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5427 	 * If it does not, the eager's receive window will be set to the
5428 	 * listener's receive window later in this function.
5429 	 */
5430 	eager->tcp_rwnd = 0;
5431 
5432 	/*
5433 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5434 	 * calling tcp_process_options() where tcp_mss_set() is called
5435 	 * to set the initial cwnd.
5436 	 */
5437 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5438 
5439 	/*
5440 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5441 	 * zone id before the accept is completed in tcp_wput_accept().
5442 	 */
5443 	econnp->conn_zoneid = connp->conn_zoneid;
5444 	econnp->conn_allzones = connp->conn_allzones;
5445 
5446 	/* Copy nexthop information from listener to eager */
5447 	if (connp->conn_nexthop_set) {
5448 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5449 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5450 	}
5451 
5452 	/*
5453 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5454 	 * eager is accepted
5455 	 */
5456 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5457 	crhold(credp);
5458 
5459 	/*
5460 	 * If the caller has the process-wide flag set, then default to MAC
5461 	 * exempt mode.  This allows read-down to unlabeled hosts.
5462 	 */
5463 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5464 		econnp->conn_mac_exempt = B_TRUE;
5465 
5466 	if (is_system_labeled()) {
5467 		cred_t *cr;
5468 
5469 		if (connp->conn_mlp_type != mlptSingle) {
5470 			cr = econnp->conn_peercred = msg_getcred(mp, NULL);
5471 			if (cr != NULL)
5472 				crhold(cr);
5473 			else
5474 				cr = econnp->conn_cred;
5475 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5476 			    econnp, cred_t *, cr)
5477 		} else {
5478 			cr = econnp->conn_cred;
5479 			DTRACE_PROBE2(syn_accept, conn_t *,
5480 			    econnp, cred_t *, cr)
5481 		}
5482 
5483 		if (!tcp_update_label(eager, cr)) {
5484 			DTRACE_PROBE3(
5485 			    tx__ip__log__error__connrequest__tcp,
5486 			    char *, "eager connp(1) label on SYN mp(2) failed",
5487 			    conn_t *, econnp, mblk_t *, mp);
5488 			goto error3;
5489 		}
5490 	}
5491 
5492 	eager->tcp_hard_binding = B_TRUE;
5493 
5494 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5495 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5496 
5497 	CL_INET_CONNECT(connp, eager, B_FALSE, err);
5498 	if (err != 0) {
5499 		tcp_bind_hash_remove(eager);
5500 		goto error3;
5501 	}
5502 
5503 	/*
5504 	 * No need to check for multicast destination since ip will only pass
5505 	 * up multicasts to those that have expressed interest
5506 	 * TODO: what about rejecting broadcasts?
5507 	 * Also check that source is not a multicast or broadcast address.
5508 	 */
5509 	eager->tcp_state = TCPS_SYN_RCVD;
5510 
5511 
5512 	/*
5513 	 * There should be no ire in the mp as we are being called after
5514 	 * receiving the SYN.
5515 	 */
5516 	ASSERT(tcp_ire_mp(&mp) == NULL);
5517 
5518 	/*
5519 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5520 	 */
5521 
5522 	if (tcp_adapt_ire(eager, NULL) == 0) {
5523 		/* Undo the bind_hash_insert */
5524 		tcp_bind_hash_remove(eager);
5525 		goto error3;
5526 	}
5527 
5528 	/* Process all TCP options. */
5529 	tcp_process_options(eager, tcph);
5530 
5531 	/* Is the other end ECN capable? */
5532 	if (tcps->tcps_ecn_permitted >= 1 &&
5533 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5534 		eager->tcp_ecn_ok = B_TRUE;
5535 	}
5536 
5537 	/*
5538 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5539 	 * window size changed via SO_RCVBUF option.  First round up the
5540 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5541 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5542 	 * setting.
5543 	 *
5544 	 * Note if there is a rpipe metric associated with the remote host,
5545 	 * we should not inherit receive window size from listener.
5546 	 */
5547 	eager->tcp_rwnd = MSS_ROUNDUP(
5548 	    (eager->tcp_rwnd == 0 ? tcp->tcp_recv_hiwater:
5549 	    eager->tcp_rwnd), eager->tcp_mss);
5550 	if (eager->tcp_snd_ws_ok)
5551 		tcp_set_ws_value(eager);
5552 	/*
5553 	 * Note that this is the only place tcp_rwnd_set() is called for
5554 	 * accepting a connection.  We need to call it here instead of
5555 	 * after the 3-way handshake because we need to tell the other
5556 	 * side our rwnd in the SYN-ACK segment.
5557 	 */
5558 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5559 
5560 	/*
5561 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5562 	 * via soaccept()->soinheritoptions() which essentially applies
5563 	 * all the listener options to the new STREAM. The options that we
5564 	 * need to take care of are:
5565 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5566 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5567 	 * SO_SNDBUF, SO_RCVBUF.
5568 	 *
5569 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5570 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5571 	 *		tcp_maxpsz_set() gets called later from
5572 	 *		tcp_accept_finish(), the option takes effect.
5573 	 *
5574 	 */
5575 	/* Set the TCP options */
5576 	eager->tcp_recv_hiwater = tcp->tcp_recv_hiwater;
5577 	eager->tcp_recv_lowater = tcp->tcp_recv_lowater;
5578 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5579 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5580 	eager->tcp_oobinline = tcp->tcp_oobinline;
5581 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5582 	eager->tcp_broadcast = tcp->tcp_broadcast;
5583 	eager->tcp_useloopback = tcp->tcp_useloopback;
5584 	eager->tcp_dontroute = tcp->tcp_dontroute;
5585 	eager->tcp_debug = tcp->tcp_debug;
5586 	eager->tcp_linger = tcp->tcp_linger;
5587 	eager->tcp_lingertime = tcp->tcp_lingertime;
5588 	if (tcp->tcp_ka_enabled)
5589 		eager->tcp_ka_enabled = 1;
5590 
5591 	/* Set the IP options */
5592 	econnp->conn_broadcast = connp->conn_broadcast;
5593 	econnp->conn_loopback = connp->conn_loopback;
5594 	econnp->conn_dontroute = connp->conn_dontroute;
5595 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5596 
5597 	/* Put a ref on the listener for the eager. */
5598 	CONN_INC_REF(connp);
5599 	mutex_enter(&tcp->tcp_eager_lock);
5600 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5601 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5602 	tcp->tcp_eager_next_q0 = eager;
5603 	eager->tcp_eager_prev_q0 = tcp;
5604 
5605 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5606 	eager->tcp_listener = tcp;
5607 	eager->tcp_saved_listener = tcp;
5608 
5609 	/*
5610 	 * Tag this detached tcp vector for later retrieval
5611 	 * by our listener client in tcp_accept().
5612 	 */
5613 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5614 	tcp->tcp_conn_req_cnt_q0++;
5615 	if (++tcp->tcp_conn_req_seqnum == -1) {
5616 		/*
5617 		 * -1 is "special" and defined in TPI as something
5618 		 * that should never be used in T_CONN_IND
5619 		 */
5620 		++tcp->tcp_conn_req_seqnum;
5621 	}
5622 	mutex_exit(&tcp->tcp_eager_lock);
5623 
5624 	if (tcp->tcp_syn_defense) {
5625 		/* Don't drop the SYN that comes from a good IP source */
5626 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5627 		if (addr_cache != NULL && eager->tcp_remote ==
5628 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5629 			eager->tcp_dontdrop = B_TRUE;
5630 		}
5631 	}
5632 
5633 	/*
5634 	 * We need to insert the eager in its own perimeter but as soon
5635 	 * as we do that, we expose the eager to the classifier and
5636 	 * should not touch any field outside the eager's perimeter.
5637 	 * So do all the work necessary before inserting the eager
5638 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5639 	 * will succeed but undo everything if it fails.
5640 	 */
5641 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5642 	eager->tcp_irs = seg_seq;
5643 	eager->tcp_rack = seg_seq;
5644 	eager->tcp_rnxt = seg_seq + 1;
5645 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5646 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5647 	eager->tcp_state = TCPS_SYN_RCVD;
5648 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5649 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5650 	if (mp1 == NULL) {
5651 		/*
5652 		 * Increment the ref count as we are going to
5653 		 * enqueueing an mp in squeue
5654 		 */
5655 		CONN_INC_REF(econnp);
5656 		goto error;
5657 	}
5658 
5659 	/*
5660 	 * Note that in theory this should use the current pid
5661 	 * so that getpeerucred on the client returns the actual listener
5662 	 * that does accept. But accept() hasn't been called yet. We could use
5663 	 * the pid of the process that did bind/listen on the server.
5664 	 * However, with common usage like inetd() the bind/listen can be done
5665 	 * by a different process than the accept().
5666 	 * Hence we do the simple thing of using the open pid here.
5667 	 * Note that db_credp is set later in tcp_send_data().
5668 	 */
5669 	mblk_setcred(mp1, credp, tcp->tcp_cpid);
5670 	eager->tcp_cpid = tcp->tcp_cpid;
5671 	eager->tcp_open_time = lbolt64;
5672 
5673 	/*
5674 	 * We need to start the rto timer. In normal case, we start
5675 	 * the timer after sending the packet on the wire (or at
5676 	 * least believing that packet was sent by waiting for
5677 	 * CALL_IP_WPUT() to return). Since this is the first packet
5678 	 * being sent on the wire for the eager, our initial tcp_rto
5679 	 * is at least tcp_rexmit_interval_min which is a fairly
5680 	 * large value to allow the algorithm to adjust slowly to large
5681 	 * fluctuations of RTT during first few transmissions.
5682 	 *
5683 	 * Starting the timer first and then sending the packet in this
5684 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5685 	 * is of the order of several 100ms and starting the timer
5686 	 * first and then sending the packet will result in difference
5687 	 * of few micro seconds.
5688 	 *
5689 	 * Without this optimization, we are forced to hold the fanout
5690 	 * lock across the ipcl_bind_insert() and sending the packet
5691 	 * so that we don't race against an incoming packet (maybe RST)
5692 	 * for this eager.
5693 	 *
5694 	 * It is necessary to acquire an extra reference on the eager
5695 	 * at this point and hold it until after tcp_send_data() to
5696 	 * ensure against an eager close race.
5697 	 */
5698 
5699 	CONN_INC_REF(eager->tcp_connp);
5700 
5701 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5702 
5703 	/*
5704 	 * Insert the eager in its own perimeter now. We are ready to deal
5705 	 * with any packets on eager.
5706 	 */
5707 	if (eager->tcp_ipversion == IPV4_VERSION) {
5708 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5709 			goto error;
5710 		}
5711 	} else {
5712 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5713 			goto error;
5714 		}
5715 	}
5716 
5717 	/* mark conn as fully-bound */
5718 	econnp->conn_fully_bound = B_TRUE;
5719 
5720 	/* Send the SYN-ACK */
5721 	tcp_send_data(eager, eager->tcp_wq, mp1);
5722 	CONN_DEC_REF(eager->tcp_connp);
5723 	freemsg(mp);
5724 
5725 	return;
5726 error:
5727 	freemsg(mp1);
5728 	eager->tcp_closemp_used = B_TRUE;
5729 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5730 	mp1 = &eager->tcp_closemp;
5731 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5732 	    econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5733 
5734 	/*
5735 	 * If a connection already exists, send the mp to that connections so
5736 	 * that it can be appropriately dealt with.
5737 	 */
5738 	ipst = tcps->tcps_netstack->netstack_ip;
5739 
5740 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
5741 		if (!IPCL_IS_CONNECTED(econnp)) {
5742 			/*
5743 			 * Something bad happened. ipcl_conn_insert()
5744 			 * failed because a connection already existed
5745 			 * in connected hash but we can't find it
5746 			 * anymore (someone blew it away). Just
5747 			 * free this message and hopefully remote
5748 			 * will retransmit at which time the SYN can be
5749 			 * treated as a new connection or dealth with
5750 			 * a TH_RST if a connection already exists.
5751 			 */
5752 			CONN_DEC_REF(econnp);
5753 			freemsg(mp);
5754 		} else {
5755 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp,
5756 			    tcp_input, econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5757 		}
5758 	} else {
5759 		/* Nobody wants this packet */
5760 		freemsg(mp);
5761 	}
5762 	return;
5763 error3:
5764 	CONN_DEC_REF(econnp);
5765 error2:
5766 	freemsg(mp);
5767 }
5768 
5769 /*
5770  * In an ideal case of vertical partition in NUMA architecture, its
5771  * beneficial to have the listener and all the incoming connections
5772  * tied to the same squeue. The other constraint is that incoming
5773  * connections should be tied to the squeue attached to interrupted
5774  * CPU for obvious locality reason so this leaves the listener to
5775  * be tied to the same squeue. Our only problem is that when listener
5776  * is binding, the CPU that will get interrupted by the NIC whose
5777  * IP address the listener is binding to is not even known. So
5778  * the code below allows us to change that binding at the time the
5779  * CPU is interrupted by virtue of incoming connection's squeue.
5780  *
5781  * This is usefull only in case of a listener bound to a specific IP
5782  * address. For other kind of listeners, they get bound the
5783  * very first time and there is no attempt to rebind them.
5784  */
5785 void
5786 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5787 {
5788 	conn_t		*connp = (conn_t *)arg;
5789 	squeue_t	*sqp = (squeue_t *)arg2;
5790 	squeue_t	*new_sqp;
5791 	uint32_t	conn_flags;
5792 
5793 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5794 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5795 	} else {
5796 		goto done;
5797 	}
5798 
5799 	if (connp->conn_fanout == NULL)
5800 		goto done;
5801 
5802 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5803 		mutex_enter(&connp->conn_fanout->connf_lock);
5804 		mutex_enter(&connp->conn_lock);
5805 		/*
5806 		 * No one from read or write side can access us now
5807 		 * except for already queued packets on this squeue.
5808 		 * But since we haven't changed the squeue yet, they
5809 		 * can't execute. If they are processed after we have
5810 		 * changed the squeue, they are sent back to the
5811 		 * correct squeue down below.
5812 		 * But a listner close can race with processing of
5813 		 * incoming SYN. If incoming SYN processing changes
5814 		 * the squeue then the listener close which is waiting
5815 		 * to enter the squeue would operate on the wrong
5816 		 * squeue. Hence we don't change the squeue here unless
5817 		 * the refcount is exactly the minimum refcount. The
5818 		 * minimum refcount of 4 is counted as - 1 each for
5819 		 * TCP and IP, 1 for being in the classifier hash, and
5820 		 * 1 for the mblk being processed.
5821 		 */
5822 
5823 		if (connp->conn_ref != 4 ||
5824 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5825 			mutex_exit(&connp->conn_lock);
5826 			mutex_exit(&connp->conn_fanout->connf_lock);
5827 			goto done;
5828 		}
5829 		if (connp->conn_sqp != new_sqp) {
5830 			while (connp->conn_sqp != new_sqp)
5831 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5832 		}
5833 
5834 		do {
5835 			conn_flags = connp->conn_flags;
5836 			conn_flags |= IPCL_FULLY_BOUND;
5837 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5838 			    conn_flags);
5839 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5840 
5841 		mutex_exit(&connp->conn_fanout->connf_lock);
5842 		mutex_exit(&connp->conn_lock);
5843 	}
5844 
5845 done:
5846 	if (connp->conn_sqp != sqp) {
5847 		CONN_INC_REF(connp);
5848 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5849 		    SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5850 	} else {
5851 		tcp_conn_request(connp, mp, sqp);
5852 	}
5853 }
5854 
5855 /*
5856  * Successful connect request processing begins when our client passes
5857  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5858  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5859  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_tpi_connect() -> IP
5860  *   upstream <- tcp_rput()		<- IP
5861  * After various error checks are completed, tcp_tpi_connect() lays
5862  * the target address and port into the composite header template,
5863  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5864  * request followed by an IRE request, and passes the three mblk message
5865  * down to IP looking like this:
5866  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5867  * Processing continues in tcp_rput() when we receive the following message:
5868  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5869  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5870  * to fire off the connection request, and then passes the T_OK_ACK mblk
5871  * upstream that we filled in below.  There are, of course, numerous
5872  * error conditions along the way which truncate the processing described
5873  * above.
5874  */
5875 static void
5876 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5877 {
5878 	sin_t		*sin;
5879 	queue_t		*q = tcp->tcp_wq;
5880 	struct T_conn_req	*tcr;
5881 	struct sockaddr	*sa;
5882 	socklen_t	len;
5883 	int		error;
5884 	cred_t		*cr;
5885 	pid_t		cpid;
5886 
5887 	/*
5888 	 * All Solaris components should pass a db_credp
5889 	 * for this TPI message, hence we ASSERT.
5890 	 * But in case there is some other M_PROTO that looks
5891 	 * like a TPI message sent by some other kernel
5892 	 * component, we check and return an error.
5893 	 */
5894 	cr = msg_getcred(mp, &cpid);
5895 	ASSERT(cr != NULL);
5896 	if (cr == NULL) {
5897 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5898 		return;
5899 	}
5900 
5901 	tcr = (struct T_conn_req *)mp->b_rptr;
5902 
5903 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5904 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5905 		tcp_err_ack(tcp, mp, TPROTO, 0);
5906 		return;
5907 	}
5908 
5909 	/*
5910 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5911 	 * will always have that to send up.  Otherwise, we need to do
5912 	 * special handling in case the allocation fails at that time.
5913 	 * If the end point is TPI, the tcp_t can be reused and the
5914 	 * tcp_ordrel_mp may be allocated already.
5915 	 */
5916 	if (tcp->tcp_ordrel_mp == NULL) {
5917 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5918 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5919 			return;
5920 		}
5921 	}
5922 
5923 	/*
5924 	 * Determine packet type based on type of address passed in
5925 	 * the request should contain an IPv4 or IPv6 address.
5926 	 * Make sure that address family matches the type of
5927 	 * family of the the address passed down
5928 	 */
5929 	switch (tcr->DEST_length) {
5930 	default:
5931 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5932 		return;
5933 
5934 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5935 		/*
5936 		 * XXX: The check for valid DEST_length was not there
5937 		 * in earlier releases and some buggy
5938 		 * TLI apps (e.g Sybase) got away with not feeding
5939 		 * in sin_zero part of address.
5940 		 * We allow that bug to keep those buggy apps humming.
5941 		 * Test suites require the check on DEST_length.
5942 		 * We construct a new mblk with valid DEST_length
5943 		 * free the original so the rest of the code does
5944 		 * not have to keep track of this special shorter
5945 		 * length address case.
5946 		 */
5947 		mblk_t *nmp;
5948 		struct T_conn_req *ntcr;
5949 		sin_t *nsin;
5950 
5951 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5952 		    tcr->OPT_length, BPRI_HI);
5953 		if (nmp == NULL) {
5954 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5955 			return;
5956 		}
5957 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5958 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5959 		ntcr->PRIM_type = T_CONN_REQ;
5960 		ntcr->DEST_length = sizeof (sin_t);
5961 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5962 
5963 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5964 		*nsin = sin_null;
5965 		/* Get pointer to shorter address to copy from original mp */
5966 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5967 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5968 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5969 			freemsg(nmp);
5970 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5971 			return;
5972 		}
5973 		nsin->sin_family = sin->sin_family;
5974 		nsin->sin_port = sin->sin_port;
5975 		nsin->sin_addr = sin->sin_addr;
5976 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5977 		nmp->b_wptr = (uchar_t *)&nsin[1];
5978 		if (tcr->OPT_length != 0) {
5979 			ntcr->OPT_length = tcr->OPT_length;
5980 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5981 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5982 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5983 			    tcr->OPT_length);
5984 			nmp->b_wptr += tcr->OPT_length;
5985 		}
5986 		freemsg(mp);	/* original mp freed */
5987 		mp = nmp;	/* re-initialize original variables */
5988 		tcr = ntcr;
5989 	}
5990 	/* FALLTHRU */
5991 
5992 	case sizeof (sin_t):
5993 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5994 		    sizeof (sin_t));
5995 		len = sizeof (sin_t);
5996 		break;
5997 
5998 	case sizeof (sin6_t):
5999 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6000 		    sizeof (sin6_t));
6001 		len = sizeof (sin6_t);
6002 		break;
6003 	}
6004 
6005 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
6006 	if (error != 0) {
6007 		tcp_err_ack(tcp, mp, TSYSERR, error);
6008 		return;
6009 	}
6010 
6011 	/*
6012 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6013 	 * should key on their sequence number and cut them loose.
6014 	 */
6015 
6016 	/*
6017 	 * If options passed in, feed it for verification and handling
6018 	 */
6019 	if (tcr->OPT_length != 0) {
6020 		mblk_t	*ok_mp;
6021 		mblk_t	*discon_mp;
6022 		mblk_t  *conn_opts_mp;
6023 		int t_error, sys_error, do_disconnect;
6024 
6025 		conn_opts_mp = NULL;
6026 
6027 		if (tcp_conprim_opt_process(tcp, mp,
6028 		    &do_disconnect, &t_error, &sys_error) < 0) {
6029 			if (do_disconnect) {
6030 				ASSERT(t_error == 0 && sys_error == 0);
6031 				discon_mp = mi_tpi_discon_ind(NULL,
6032 				    ECONNREFUSED, 0);
6033 				if (!discon_mp) {
6034 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6035 					    TSYSERR, ENOMEM);
6036 					return;
6037 				}
6038 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6039 				if (!ok_mp) {
6040 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6041 					    TSYSERR, ENOMEM);
6042 					return;
6043 				}
6044 				qreply(q, ok_mp);
6045 				qreply(q, discon_mp); /* no flush! */
6046 			} else {
6047 				ASSERT(t_error != 0);
6048 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6049 				    sys_error);
6050 			}
6051 			return;
6052 		}
6053 		/*
6054 		 * Success in setting options, the mp option buffer represented
6055 		 * by OPT_length/offset has been potentially modified and
6056 		 * contains results of option processing. We copy it in
6057 		 * another mp to save it for potentially influencing returning
6058 		 * it in T_CONN_CONN.
6059 		 */
6060 		if (tcr->OPT_length != 0) { /* there are resulting options */
6061 			conn_opts_mp = copyb(mp);
6062 			if (!conn_opts_mp) {
6063 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6064 				    TSYSERR, ENOMEM);
6065 				return;
6066 			}
6067 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6068 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6069 			/*
6070 			 * Note:
6071 			 * These resulting option negotiation can include any
6072 			 * end-to-end negotiation options but there no such
6073 			 * thing (yet?) in our TCP/IP.
6074 			 */
6075 		}
6076 	}
6077 
6078 	/* call the non-TPI version */
6079 	error = tcp_do_connect(tcp->tcp_connp, sa, len, cr, cpid);
6080 	if (error < 0) {
6081 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
6082 	} else if (error > 0) {
6083 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
6084 	} else {
6085 		mp = mi_tpi_ok_ack_alloc(mp);
6086 	}
6087 
6088 	/*
6089 	 * Note: Code below is the "failure" case
6090 	 */
6091 	/* return error ack and blow away saved option results if any */
6092 connect_failed:
6093 	if (mp != NULL)
6094 		putnext(tcp->tcp_rq, mp);
6095 	else {
6096 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6097 		    TSYSERR, ENOMEM);
6098 	}
6099 }
6100 
6101 /*
6102  * Handle connect to IPv4 destinations, including connections for AF_INET6
6103  * sockets connecting to IPv4 mapped IPv6 destinations.
6104  */
6105 static int
6106 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
6107     uint_t srcid, cred_t *cr, pid_t pid)
6108 {
6109 	tcph_t	*tcph;
6110 	mblk_t	*mp;
6111 	ipaddr_t dstaddr = *dstaddrp;
6112 	int32_t	oldstate;
6113 	uint16_t lport;
6114 	int	error = 0;
6115 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6116 
6117 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6118 
6119 	/* Check for attempt to connect to INADDR_ANY */
6120 	if (dstaddr == INADDR_ANY)  {
6121 		/*
6122 		 * SunOS 4.x and 4.3 BSD allow an application
6123 		 * to connect a TCP socket to INADDR_ANY.
6124 		 * When they do this, the kernel picks the
6125 		 * address of one interface and uses it
6126 		 * instead.  The kernel usually ends up
6127 		 * picking the address of the loopback
6128 		 * interface.  This is an undocumented feature.
6129 		 * However, we provide the same thing here
6130 		 * in order to have source and binary
6131 		 * compatibility with SunOS 4.x.
6132 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6133 		 * generate the T_CONN_CON.
6134 		 */
6135 		dstaddr = htonl(INADDR_LOOPBACK);
6136 		*dstaddrp = dstaddr;
6137 	}
6138 
6139 	/* Handle __sin6_src_id if socket not bound to an IP address */
6140 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6141 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6142 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6143 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6144 		    tcp->tcp_ipha->ipha_src);
6145 	}
6146 
6147 	/*
6148 	 * Don't let an endpoint connect to itself.  Note that
6149 	 * the test here does not catch the case where the
6150 	 * source IP addr was left unspecified by the user. In
6151 	 * this case, the source addr is set in tcp_adapt_ire()
6152 	 * using the reply to the T_BIND message that we send
6153 	 * down to IP here and the check is repeated in tcp_rput_other.
6154 	 */
6155 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6156 	    dstport == tcp->tcp_lport) {
6157 		error = -TBADADDR;
6158 		goto failed;
6159 	}
6160 
6161 	tcp->tcp_ipha->ipha_dst = dstaddr;
6162 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6163 
6164 	/*
6165 	 * Massage a source route if any putting the first hop
6166 	 * in iph_dst. Compute a starting value for the checksum which
6167 	 * takes into account that the original iph_dst should be
6168 	 * included in the checksum but that ip will include the
6169 	 * first hop in the source route in the tcp checksum.
6170 	 */
6171 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6172 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6173 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6174 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6175 	if ((int)tcp->tcp_sum < 0)
6176 		tcp->tcp_sum--;
6177 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6178 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6179 	    (tcp->tcp_sum >> 16));
6180 	tcph = tcp->tcp_tcph;
6181 	*(uint16_t *)tcph->th_fport = dstport;
6182 	tcp->tcp_fport = dstport;
6183 
6184 	oldstate = tcp->tcp_state;
6185 	/*
6186 	 * At this point the remote destination address and remote port fields
6187 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6188 	 * have to see which state tcp was in so we can take apropriate action.
6189 	 */
6190 	if (oldstate == TCPS_IDLE) {
6191 		/*
6192 		 * We support a quick connect capability here, allowing
6193 		 * clients to transition directly from IDLE to SYN_SENT
6194 		 * tcp_bindi will pick an unused port, insert the connection
6195 		 * in the bind hash and transition to BOUND state.
6196 		 */
6197 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6198 		    tcp, B_TRUE);
6199 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6200 		    B_FALSE, B_FALSE);
6201 		if (lport == 0) {
6202 			error = -TNOADDR;
6203 			goto failed;
6204 		}
6205 	}
6206 	tcp->tcp_state = TCPS_SYN_SENT;
6207 
6208 	mp = allocb(sizeof (ire_t), BPRI_HI);
6209 	if (mp == NULL) {
6210 		tcp->tcp_state = oldstate;
6211 		error = ENOMEM;
6212 		goto failed;
6213 	}
6214 
6215 	mp->b_wptr += sizeof (ire_t);
6216 	mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6217 	tcp->tcp_hard_binding = 1;
6218 
6219 	/*
6220 	 * We need to make sure that the conn_recv is set to a non-null
6221 	 * value before we insert the conn_t into the classifier table.
6222 	 * This is to avoid a race with an incoming packet which does
6223 	 * an ipcl_classify().
6224 	 */
6225 	tcp->tcp_connp->conn_recv = tcp_input;
6226 
6227 	if (tcp->tcp_family == AF_INET) {
6228 		error = ip_proto_bind_connected_v4(tcp->tcp_connp, &mp,
6229 		    IPPROTO_TCP, &tcp->tcp_ipha->ipha_src, tcp->tcp_lport,
6230 		    tcp->tcp_remote, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6231 	} else {
6232 		in6_addr_t v6src;
6233 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6234 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6235 		} else {
6236 			v6src = tcp->tcp_ip6h->ip6_src;
6237 		}
6238 		error = ip_proto_bind_connected_v6(tcp->tcp_connp, &mp,
6239 		    IPPROTO_TCP, &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6240 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6241 	}
6242 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6243 	tcp->tcp_active_open = 1;
6244 
6245 
6246 	return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6247 failed:
6248 	/* return error ack and blow away saved option results if any */
6249 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6250 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6251 	return (error);
6252 }
6253 
6254 /*
6255  * Handle connect to IPv6 destinations.
6256  */
6257 static int
6258 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
6259     uint32_t flowinfo, uint_t srcid, uint32_t scope_id, cred_t *cr, pid_t pid)
6260 {
6261 	tcph_t	*tcph;
6262 	mblk_t	*mp;
6263 	ip6_rthdr_t *rth;
6264 	int32_t  oldstate;
6265 	uint16_t lport;
6266 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6267 	int	error = 0;
6268 	conn_t	*connp = tcp->tcp_connp;
6269 
6270 	ASSERT(tcp->tcp_family == AF_INET6);
6271 
6272 	/*
6273 	 * If we're here, it means that the destination address is a native
6274 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6275 	 * reason why it might not be IPv6 is if the socket was bound to an
6276 	 * IPv4-mapped IPv6 address.
6277 	 */
6278 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6279 		return (-TBADADDR);
6280 	}
6281 
6282 	/*
6283 	 * Interpret a zero destination to mean loopback.
6284 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6285 	 * generate the T_CONN_CON.
6286 	 */
6287 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6288 		*dstaddrp = ipv6_loopback;
6289 	}
6290 
6291 	/* Handle __sin6_src_id if socket not bound to an IP address */
6292 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6293 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6294 		    connp->conn_zoneid, tcps->tcps_netstack);
6295 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6296 	}
6297 
6298 	/*
6299 	 * Take care of the scope_id now and add ip6i_t
6300 	 * if ip6i_t is not already allocated through TCP
6301 	 * sticky options. At this point tcp_ip6h does not
6302 	 * have dst info, thus use dstaddrp.
6303 	 */
6304 	if (scope_id != 0 &&
6305 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6306 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6307 		ip6i_t  *ip6i;
6308 
6309 		ipp->ipp_ifindex = scope_id;
6310 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6311 
6312 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6313 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6314 			/* Already allocated */
6315 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6316 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6317 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6318 		} else {
6319 			int reterr;
6320 
6321 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6322 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6323 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6324 			reterr = tcp_build_hdrs(tcp);
6325 			if (reterr != 0)
6326 				goto failed;
6327 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6328 		}
6329 	}
6330 
6331 	/*
6332 	 * Don't let an endpoint connect to itself.  Note that
6333 	 * the test here does not catch the case where the
6334 	 * source IP addr was left unspecified by the user. In
6335 	 * this case, the source addr is set in tcp_adapt_ire()
6336 	 * using the reply to the T_BIND message that we send
6337 	 * down to IP here and the check is repeated in tcp_rput_other.
6338 	 */
6339 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6340 	    (dstport == tcp->tcp_lport)) {
6341 		error = -TBADADDR;
6342 		goto failed;
6343 	}
6344 
6345 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6346 	tcp->tcp_remote_v6 = *dstaddrp;
6347 	tcp->tcp_ip6h->ip6_vcf =
6348 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6349 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6350 
6351 	/*
6352 	 * Massage a routing header (if present) putting the first hop
6353 	 * in ip6_dst. Compute a starting value for the checksum which
6354 	 * takes into account that the original ip6_dst should be
6355 	 * included in the checksum but that ip will include the
6356 	 * first hop in the source route in the tcp checksum.
6357 	 */
6358 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6359 	if (rth != NULL) {
6360 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6361 		    tcps->tcps_netstack);
6362 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6363 		    (tcp->tcp_sum >> 16));
6364 	} else {
6365 		tcp->tcp_sum = 0;
6366 	}
6367 
6368 	tcph = tcp->tcp_tcph;
6369 	*(uint16_t *)tcph->th_fport = dstport;
6370 	tcp->tcp_fport = dstport;
6371 
6372 	oldstate = tcp->tcp_state;
6373 	/*
6374 	 * At this point the remote destination address and remote port fields
6375 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6376 	 * have to see which state tcp was in so we can take apropriate action.
6377 	 */
6378 	if (oldstate == TCPS_IDLE) {
6379 		/*
6380 		 * We support a quick connect capability here, allowing
6381 		 * clients to transition directly from IDLE to SYN_SENT
6382 		 * tcp_bindi will pick an unused port, insert the connection
6383 		 * in the bind hash and transition to BOUND state.
6384 		 */
6385 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6386 		    tcp, B_TRUE);
6387 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6388 		    B_FALSE, B_FALSE);
6389 		if (lport == 0) {
6390 			error = -TNOADDR;
6391 			goto failed;
6392 		}
6393 	}
6394 	tcp->tcp_state = TCPS_SYN_SENT;
6395 
6396 	mp = allocb(sizeof (ire_t), BPRI_HI);
6397 	if (mp != NULL) {
6398 		in6_addr_t v6src;
6399 
6400 		mp->b_wptr += sizeof (ire_t);
6401 		mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6402 
6403 		tcp->tcp_hard_binding = 1;
6404 
6405 		/*
6406 		 * We need to make sure that the conn_recv is set to a non-null
6407 		 * value before we insert the conn_t into the classifier table.
6408 		 * This is to avoid a race with an incoming packet which does
6409 		 * an ipcl_classify().
6410 		 */
6411 		tcp->tcp_connp->conn_recv = tcp_input;
6412 
6413 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6414 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6415 		} else {
6416 			v6src = tcp->tcp_ip6h->ip6_src;
6417 		}
6418 		error = ip_proto_bind_connected_v6(connp, &mp, IPPROTO_TCP,
6419 		    &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6420 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6421 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6422 		tcp->tcp_active_open = 1;
6423 
6424 		return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6425 	}
6426 	/* Error case */
6427 	tcp->tcp_state = oldstate;
6428 	error = ENOMEM;
6429 
6430 failed:
6431 	/* return error ack and blow away saved option results if any */
6432 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6433 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6434 	return (error);
6435 }
6436 
6437 /*
6438  * We need a stream q for detached closing tcp connections
6439  * to use.  Our client hereby indicates that this q is the
6440  * one to use.
6441  */
6442 static void
6443 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6444 {
6445 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6446 	queue_t	*q = tcp->tcp_wq;
6447 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6448 
6449 #ifdef NS_DEBUG
6450 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6451 	    tcps->tcps_netstack->netstack_stackid);
6452 #endif
6453 	mp->b_datap->db_type = M_IOCACK;
6454 	iocp->ioc_count = 0;
6455 	mutex_enter(&tcps->tcps_g_q_lock);
6456 	if (tcps->tcps_g_q != NULL) {
6457 		mutex_exit(&tcps->tcps_g_q_lock);
6458 		iocp->ioc_error = EALREADY;
6459 	} else {
6460 		int error = 0;
6461 		conn_t *connp = tcp->tcp_connp;
6462 		ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
6463 
6464 		tcps->tcps_g_q = tcp->tcp_rq;
6465 		mutex_exit(&tcps->tcps_g_q_lock);
6466 		iocp->ioc_error = 0;
6467 		iocp->ioc_rval = 0;
6468 		/*
6469 		 * We are passing tcp_sticky_ipp as NULL
6470 		 * as it is not useful for tcp_default queue
6471 		 *
6472 		 * Set conn_recv just in case.
6473 		 */
6474 		tcp->tcp_connp->conn_recv = tcp_conn_request;
6475 
6476 		ASSERT(connp->conn_af_isv6);
6477 		connp->conn_ulp = IPPROTO_TCP;
6478 
6479 		if (ipst->ips_ipcl_proto_fanout_v6[IPPROTO_TCP].connf_head !=
6480 		    NULL || connp->conn_mac_exempt) {
6481 			error = -TBADADDR;
6482 		} else {
6483 			connp->conn_srcv6 = ipv6_all_zeros;
6484 			ipcl_proto_insert_v6(connp, IPPROTO_TCP);
6485 		}
6486 
6487 		(void) tcp_post_ip_bind(tcp, NULL, error, NULL, 0);
6488 	}
6489 	qreply(q, mp);
6490 }
6491 
6492 static int
6493 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
6494 {
6495 	tcp_t	*ltcp = NULL;
6496 	conn_t	*connp;
6497 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6498 
6499 	/*
6500 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6501 	 * when the stream is in BOUND state. Do not send a reset,
6502 	 * since the destination IP address is not valid, and it can
6503 	 * be the initialized value of all zeros (broadcast address).
6504 	 *
6505 	 * XXX There won't be any pending bind request to IP.
6506 	 */
6507 	if (tcp->tcp_state <= TCPS_BOUND) {
6508 		if (tcp->tcp_debug) {
6509 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6510 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6511 		}
6512 		return (TOUTSTATE);
6513 	}
6514 
6515 
6516 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6517 
6518 		/*
6519 		 * According to TPI, for non-listeners, ignore seqnum
6520 		 * and disconnect.
6521 		 * Following interpretation of -1 seqnum is historical
6522 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6523 		 * a valid seqnum should not be -1).
6524 		 *
6525 		 *	-1 means disconnect everything
6526 		 *	regardless even on a listener.
6527 		 */
6528 
6529 		int old_state = tcp->tcp_state;
6530 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6531 
6532 		/*
6533 		 * The connection can't be on the tcp_time_wait_head list
6534 		 * since it is not detached.
6535 		 */
6536 		ASSERT(tcp->tcp_time_wait_next == NULL);
6537 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6538 		ASSERT(tcp->tcp_time_wait_expire == 0);
6539 		ltcp = NULL;
6540 		/*
6541 		 * If it used to be a listener, check to make sure no one else
6542 		 * has taken the port before switching back to LISTEN state.
6543 		 */
6544 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6545 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6546 			    tcp->tcp_ipha->ipha_src,
6547 			    tcp->tcp_connp->conn_zoneid, ipst);
6548 			if (connp != NULL)
6549 				ltcp = connp->conn_tcp;
6550 		} else {
6551 			/* Allow tcp_bound_if listeners? */
6552 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6553 			    &tcp->tcp_ip6h->ip6_src, 0,
6554 			    tcp->tcp_connp->conn_zoneid, ipst);
6555 			if (connp != NULL)
6556 				ltcp = connp->conn_tcp;
6557 		}
6558 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6559 			tcp->tcp_state = TCPS_LISTEN;
6560 		} else if (old_state > TCPS_BOUND) {
6561 			tcp->tcp_conn_req_max = 0;
6562 			tcp->tcp_state = TCPS_BOUND;
6563 		}
6564 		if (ltcp != NULL)
6565 			CONN_DEC_REF(ltcp->tcp_connp);
6566 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6567 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6568 		} else if (old_state == TCPS_ESTABLISHED ||
6569 		    old_state == TCPS_CLOSE_WAIT) {
6570 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6571 		}
6572 
6573 		if (tcp->tcp_fused)
6574 			tcp_unfuse(tcp);
6575 
6576 		mutex_enter(&tcp->tcp_eager_lock);
6577 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6578 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6579 			tcp_eager_cleanup(tcp, 0);
6580 		}
6581 		mutex_exit(&tcp->tcp_eager_lock);
6582 
6583 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6584 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6585 
6586 		tcp_reinit(tcp);
6587 
6588 		return (0);
6589 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6590 		return (TBADSEQ);
6591 	}
6592 	return (0);
6593 }
6594 
6595 /*
6596  * Our client hereby directs us to reject the connection request
6597  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6598  * of sending the appropriate RST, not an ICMP error.
6599  */
6600 static void
6601 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6602 {
6603 	t_scalar_t seqnum;
6604 	int	error;
6605 
6606 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6607 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6608 		tcp_err_ack(tcp, mp, TPROTO, 0);
6609 		return;
6610 	}
6611 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6612 	error = tcp_disconnect_common(tcp, seqnum);
6613 	if (error != 0)
6614 		tcp_err_ack(tcp, mp, error, 0);
6615 	else {
6616 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6617 			/* Send M_FLUSH according to TPI */
6618 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6619 		}
6620 		mp = mi_tpi_ok_ack_alloc(mp);
6621 		if (mp)
6622 			putnext(tcp->tcp_rq, mp);
6623 	}
6624 }
6625 
6626 /*
6627  * Diagnostic routine used to return a string associated with the tcp state.
6628  * Note that if the caller does not supply a buffer, it will use an internal
6629  * static string.  This means that if multiple threads call this function at
6630  * the same time, output can be corrupted...  Note also that this function
6631  * does not check the size of the supplied buffer.  The caller has to make
6632  * sure that it is big enough.
6633  */
6634 static char *
6635 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6636 {
6637 	char		buf1[30];
6638 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6639 	char		*buf;
6640 	char		*cp;
6641 	in6_addr_t	local, remote;
6642 	char		local_addrbuf[INET6_ADDRSTRLEN];
6643 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6644 
6645 	if (sup_buf != NULL)
6646 		buf = sup_buf;
6647 	else
6648 		buf = priv_buf;
6649 
6650 	if (tcp == NULL)
6651 		return ("NULL_TCP");
6652 	switch (tcp->tcp_state) {
6653 	case TCPS_CLOSED:
6654 		cp = "TCP_CLOSED";
6655 		break;
6656 	case TCPS_IDLE:
6657 		cp = "TCP_IDLE";
6658 		break;
6659 	case TCPS_BOUND:
6660 		cp = "TCP_BOUND";
6661 		break;
6662 	case TCPS_LISTEN:
6663 		cp = "TCP_LISTEN";
6664 		break;
6665 	case TCPS_SYN_SENT:
6666 		cp = "TCP_SYN_SENT";
6667 		break;
6668 	case TCPS_SYN_RCVD:
6669 		cp = "TCP_SYN_RCVD";
6670 		break;
6671 	case TCPS_ESTABLISHED:
6672 		cp = "TCP_ESTABLISHED";
6673 		break;
6674 	case TCPS_CLOSE_WAIT:
6675 		cp = "TCP_CLOSE_WAIT";
6676 		break;
6677 	case TCPS_FIN_WAIT_1:
6678 		cp = "TCP_FIN_WAIT_1";
6679 		break;
6680 	case TCPS_CLOSING:
6681 		cp = "TCP_CLOSING";
6682 		break;
6683 	case TCPS_LAST_ACK:
6684 		cp = "TCP_LAST_ACK";
6685 		break;
6686 	case TCPS_FIN_WAIT_2:
6687 		cp = "TCP_FIN_WAIT_2";
6688 		break;
6689 	case TCPS_TIME_WAIT:
6690 		cp = "TCP_TIME_WAIT";
6691 		break;
6692 	default:
6693 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6694 		cp = buf1;
6695 		break;
6696 	}
6697 	switch (format) {
6698 	case DISP_ADDR_AND_PORT:
6699 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6700 			/*
6701 			 * Note that we use the remote address in the tcp_b
6702 			 * structure.  This means that it will print out
6703 			 * the real destination address, not the next hop's
6704 			 * address if source routing is used.
6705 			 */
6706 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6707 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6708 
6709 		} else {
6710 			local = tcp->tcp_ip_src_v6;
6711 			remote = tcp->tcp_remote_v6;
6712 		}
6713 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6714 		    sizeof (local_addrbuf));
6715 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6716 		    sizeof (remote_addrbuf));
6717 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6718 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6719 		    ntohs(tcp->tcp_fport), cp);
6720 		break;
6721 	case DISP_PORT_ONLY:
6722 	default:
6723 		(void) mi_sprintf(buf, "[%u, %u] %s",
6724 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6725 		break;
6726 	}
6727 
6728 	return (buf);
6729 }
6730 
6731 /*
6732  * Called via squeue to get on to eager's perimeter. It sends a
6733  * TH_RST if eager is in the fanout table. The listener wants the
6734  * eager to disappear either by means of tcp_eager_blowoff() or
6735  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
6736  * called (via squeue) if the eager cannot be inserted in the
6737  * fanout table in tcp_conn_request().
6738  */
6739 /* ARGSUSED */
6740 void
6741 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6742 {
6743 	conn_t	*econnp = (conn_t *)arg;
6744 	tcp_t	*eager = econnp->conn_tcp;
6745 	tcp_t	*listener = eager->tcp_listener;
6746 	tcp_stack_t	*tcps = eager->tcp_tcps;
6747 
6748 	/*
6749 	 * We could be called because listener is closing. Since
6750 	 * the eager is using listener's queue's, its not safe.
6751 	 * Better use the default queue just to send the TH_RST
6752 	 * out.
6753 	 */
6754 	ASSERT(tcps->tcps_g_q != NULL);
6755 	eager->tcp_rq = tcps->tcps_g_q;
6756 	eager->tcp_wq = WR(tcps->tcps_g_q);
6757 
6758 	/*
6759 	 * An eager's conn_fanout will be NULL if it's a duplicate
6760 	 * for an existing 4-tuples in the conn fanout table.
6761 	 * We don't want to send an RST out in such case.
6762 	 */
6763 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
6764 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6765 		    eager, eager->tcp_snxt, 0, TH_RST);
6766 	}
6767 
6768 	/* We are here because listener wants this eager gone */
6769 	if (listener != NULL) {
6770 		mutex_enter(&listener->tcp_eager_lock);
6771 		tcp_eager_unlink(eager);
6772 		if (eager->tcp_tconnind_started) {
6773 			/*
6774 			 * The eager has sent a conn_ind up to the
6775 			 * listener but listener decides to close
6776 			 * instead. We need to drop the extra ref
6777 			 * placed on eager in tcp_rput_data() before
6778 			 * sending the conn_ind to listener.
6779 			 */
6780 			CONN_DEC_REF(econnp);
6781 		}
6782 		mutex_exit(&listener->tcp_eager_lock);
6783 		CONN_DEC_REF(listener->tcp_connp);
6784 	}
6785 
6786 	if (eager->tcp_state > TCPS_BOUND)
6787 		tcp_close_detached(eager);
6788 }
6789 
6790 /*
6791  * Reset any eager connection hanging off this listener marked
6792  * with 'seqnum' and then reclaim it's resources.
6793  */
6794 static boolean_t
6795 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6796 {
6797 	tcp_t	*eager;
6798 	mblk_t 	*mp;
6799 	tcp_stack_t	*tcps = listener->tcp_tcps;
6800 
6801 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
6802 	eager = listener;
6803 	mutex_enter(&listener->tcp_eager_lock);
6804 	do {
6805 		eager = eager->tcp_eager_next_q;
6806 		if (eager == NULL) {
6807 			mutex_exit(&listener->tcp_eager_lock);
6808 			return (B_FALSE);
6809 		}
6810 	} while (eager->tcp_conn_req_seqnum != seqnum);
6811 
6812 	if (eager->tcp_closemp_used) {
6813 		mutex_exit(&listener->tcp_eager_lock);
6814 		return (B_TRUE);
6815 	}
6816 	eager->tcp_closemp_used = B_TRUE;
6817 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6818 	CONN_INC_REF(eager->tcp_connp);
6819 	mutex_exit(&listener->tcp_eager_lock);
6820 	mp = &eager->tcp_closemp;
6821 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6822 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
6823 	return (B_TRUE);
6824 }
6825 
6826 /*
6827  * Reset any eager connection hanging off this listener
6828  * and then reclaim it's resources.
6829  */
6830 static void
6831 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6832 {
6833 	tcp_t	*eager;
6834 	mblk_t	*mp;
6835 	tcp_stack_t	*tcps = listener->tcp_tcps;
6836 
6837 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6838 
6839 	if (!q0_only) {
6840 		/* First cleanup q */
6841 		TCP_STAT(tcps, tcp_eager_blowoff_q);
6842 		eager = listener->tcp_eager_next_q;
6843 		while (eager != NULL) {
6844 			if (!eager->tcp_closemp_used) {
6845 				eager->tcp_closemp_used = B_TRUE;
6846 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6847 				CONN_INC_REF(eager->tcp_connp);
6848 				mp = &eager->tcp_closemp;
6849 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6850 				    tcp_eager_kill, eager->tcp_connp,
6851 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
6852 			}
6853 			eager = eager->tcp_eager_next_q;
6854 		}
6855 	}
6856 	/* Then cleanup q0 */
6857 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6858 	eager = listener->tcp_eager_next_q0;
6859 	while (eager != listener) {
6860 		if (!eager->tcp_closemp_used) {
6861 			eager->tcp_closemp_used = B_TRUE;
6862 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6863 			CONN_INC_REF(eager->tcp_connp);
6864 			mp = &eager->tcp_closemp;
6865 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6866 			    tcp_eager_kill, eager->tcp_connp, SQ_FILL,
6867 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6868 		}
6869 		eager = eager->tcp_eager_next_q0;
6870 	}
6871 }
6872 
6873 /*
6874  * If we are an eager connection hanging off a listener that hasn't
6875  * formally accepted the connection yet, get off his list and blow off
6876  * any data that we have accumulated.
6877  */
6878 static void
6879 tcp_eager_unlink(tcp_t *tcp)
6880 {
6881 	tcp_t	*listener = tcp->tcp_listener;
6882 
6883 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6884 	ASSERT(listener != NULL);
6885 	if (tcp->tcp_eager_next_q0 != NULL) {
6886 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6887 
6888 		/* Remove the eager tcp from q0 */
6889 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6890 		    tcp->tcp_eager_prev_q0;
6891 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6892 		    tcp->tcp_eager_next_q0;
6893 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6894 		listener->tcp_conn_req_cnt_q0--;
6895 
6896 		tcp->tcp_eager_next_q0 = NULL;
6897 		tcp->tcp_eager_prev_q0 = NULL;
6898 
6899 		/*
6900 		 * Take the eager out, if it is in the list of droppable
6901 		 * eagers.
6902 		 */
6903 		MAKE_UNDROPPABLE(tcp);
6904 
6905 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6906 			/* we have timed out before */
6907 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6908 			listener->tcp_syn_rcvd_timeout--;
6909 		}
6910 	} else {
6911 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6912 		tcp_t	*prev = NULL;
6913 
6914 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6915 			if (tcpp[0] == tcp) {
6916 				if (listener->tcp_eager_last_q == tcp) {
6917 					/*
6918 					 * If we are unlinking the last
6919 					 * element on the list, adjust
6920 					 * tail pointer. Set tail pointer
6921 					 * to nil when list is empty.
6922 					 */
6923 					ASSERT(tcp->tcp_eager_next_q == NULL);
6924 					if (listener->tcp_eager_last_q ==
6925 					    listener->tcp_eager_next_q) {
6926 						listener->tcp_eager_last_q =
6927 						    NULL;
6928 					} else {
6929 						/*
6930 						 * We won't get here if there
6931 						 * is only one eager in the
6932 						 * list.
6933 						 */
6934 						ASSERT(prev != NULL);
6935 						listener->tcp_eager_last_q =
6936 						    prev;
6937 					}
6938 				}
6939 				tcpp[0] = tcp->tcp_eager_next_q;
6940 				tcp->tcp_eager_next_q = NULL;
6941 				tcp->tcp_eager_last_q = NULL;
6942 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6943 				listener->tcp_conn_req_cnt_q--;
6944 				break;
6945 			}
6946 			prev = tcpp[0];
6947 		}
6948 	}
6949 	tcp->tcp_listener = NULL;
6950 }
6951 
6952 /* Shorthand to generate and send TPI error acks to our client */
6953 static void
6954 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6955 {
6956 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6957 		putnext(tcp->tcp_rq, mp);
6958 }
6959 
6960 /* Shorthand to generate and send TPI error acks to our client */
6961 static void
6962 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6963     int t_error, int sys_error)
6964 {
6965 	struct T_error_ack	*teackp;
6966 
6967 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
6968 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
6969 		teackp = (struct T_error_ack *)mp->b_rptr;
6970 		teackp->ERROR_prim = primitive;
6971 		teackp->TLI_error = t_error;
6972 		teackp->UNIX_error = sys_error;
6973 		putnext(tcp->tcp_rq, mp);
6974 	}
6975 }
6976 
6977 /*
6978  * Note: No locks are held when inspecting tcp_g_*epriv_ports
6979  * but instead the code relies on:
6980  * - the fact that the address of the array and its size never changes
6981  * - the atomic assignment of the elements of the array
6982  */
6983 /* ARGSUSED */
6984 static int
6985 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
6986 {
6987 	int i;
6988 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6989 
6990 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6991 		if (tcps->tcps_g_epriv_ports[i] != 0)
6992 			(void) mi_mpprintf(mp, "%d ",
6993 			    tcps->tcps_g_epriv_ports[i]);
6994 	}
6995 	return (0);
6996 }
6997 
6998 /*
6999  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7000  * threads from changing it at the same time.
7001  */
7002 /* ARGSUSED */
7003 static int
7004 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7005     cred_t *cr)
7006 {
7007 	long	new_value;
7008 	int	i;
7009 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7010 
7011 	/*
7012 	 * Fail the request if the new value does not lie within the
7013 	 * port number limits.
7014 	 */
7015 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7016 	    new_value <= 0 || new_value >= 65536) {
7017 		return (EINVAL);
7018 	}
7019 
7020 	mutex_enter(&tcps->tcps_epriv_port_lock);
7021 	/* Check if the value is already in the list */
7022 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7023 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7024 			mutex_exit(&tcps->tcps_epriv_port_lock);
7025 			return (EEXIST);
7026 		}
7027 	}
7028 	/* Find an empty slot */
7029 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7030 		if (tcps->tcps_g_epriv_ports[i] == 0)
7031 			break;
7032 	}
7033 	if (i == tcps->tcps_g_num_epriv_ports) {
7034 		mutex_exit(&tcps->tcps_epriv_port_lock);
7035 		return (EOVERFLOW);
7036 	}
7037 	/* Set the new value */
7038 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7039 	mutex_exit(&tcps->tcps_epriv_port_lock);
7040 	return (0);
7041 }
7042 
7043 /*
7044  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7045  * threads from changing it at the same time.
7046  */
7047 /* ARGSUSED */
7048 static int
7049 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7050     cred_t *cr)
7051 {
7052 	long	new_value;
7053 	int	i;
7054 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7055 
7056 	/*
7057 	 * Fail the request if the new value does not lie within the
7058 	 * port number limits.
7059 	 */
7060 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7061 	    new_value >= 65536) {
7062 		return (EINVAL);
7063 	}
7064 
7065 	mutex_enter(&tcps->tcps_epriv_port_lock);
7066 	/* Check that the value is already in the list */
7067 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7068 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7069 			break;
7070 	}
7071 	if (i == tcps->tcps_g_num_epriv_ports) {
7072 		mutex_exit(&tcps->tcps_epriv_port_lock);
7073 		return (ESRCH);
7074 	}
7075 	/* Clear the value */
7076 	tcps->tcps_g_epriv_ports[i] = 0;
7077 	mutex_exit(&tcps->tcps_epriv_port_lock);
7078 	return (0);
7079 }
7080 
7081 /* Return the TPI/TLI equivalent of our current tcp_state */
7082 static int
7083 tcp_tpistate(tcp_t *tcp)
7084 {
7085 	switch (tcp->tcp_state) {
7086 	case TCPS_IDLE:
7087 		return (TS_UNBND);
7088 	case TCPS_LISTEN:
7089 		/*
7090 		 * Return whether there are outstanding T_CONN_IND waiting
7091 		 * for the matching T_CONN_RES. Therefore don't count q0.
7092 		 */
7093 		if (tcp->tcp_conn_req_cnt_q > 0)
7094 			return (TS_WRES_CIND);
7095 		else
7096 			return (TS_IDLE);
7097 	case TCPS_BOUND:
7098 		return (TS_IDLE);
7099 	case TCPS_SYN_SENT:
7100 		return (TS_WCON_CREQ);
7101 	case TCPS_SYN_RCVD:
7102 		/*
7103 		 * Note: assumption: this has to the active open SYN_RCVD.
7104 		 * The passive instance is detached in SYN_RCVD stage of
7105 		 * incoming connection processing so we cannot get request
7106 		 * for T_info_ack on it.
7107 		 */
7108 		return (TS_WACK_CRES);
7109 	case TCPS_ESTABLISHED:
7110 		return (TS_DATA_XFER);
7111 	case TCPS_CLOSE_WAIT:
7112 		return (TS_WREQ_ORDREL);
7113 	case TCPS_FIN_WAIT_1:
7114 		return (TS_WIND_ORDREL);
7115 	case TCPS_FIN_WAIT_2:
7116 		return (TS_WIND_ORDREL);
7117 
7118 	case TCPS_CLOSING:
7119 	case TCPS_LAST_ACK:
7120 	case TCPS_TIME_WAIT:
7121 	case TCPS_CLOSED:
7122 		/*
7123 		 * Following TS_WACK_DREQ7 is a rendition of "not
7124 		 * yet TS_IDLE" TPI state. There is no best match to any
7125 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7126 		 * choose a value chosen that will map to TLI/XTI level
7127 		 * state of TSTATECHNG (state is process of changing) which
7128 		 * captures what this dummy state represents.
7129 		 */
7130 		return (TS_WACK_DREQ7);
7131 	default:
7132 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7133 		    tcp->tcp_state, tcp_display(tcp, NULL,
7134 		    DISP_PORT_ONLY));
7135 		return (TS_UNBND);
7136 	}
7137 }
7138 
7139 static void
7140 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7141 {
7142 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7143 
7144 	if (tcp->tcp_family == AF_INET6)
7145 		*tia = tcp_g_t_info_ack_v6;
7146 	else
7147 		*tia = tcp_g_t_info_ack;
7148 	tia->CURRENT_state = tcp_tpistate(tcp);
7149 	tia->OPT_size = tcp_max_optsize;
7150 	if (tcp->tcp_mss == 0) {
7151 		/* Not yet set - tcp_open does not set mss */
7152 		if (tcp->tcp_ipversion == IPV4_VERSION)
7153 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7154 		else
7155 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7156 	} else {
7157 		tia->TIDU_size = tcp->tcp_mss;
7158 	}
7159 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7160 }
7161 
7162 static void
7163 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
7164     t_uscalar_t cap_bits1)
7165 {
7166 	tcap->CAP_bits1 = 0;
7167 
7168 	if (cap_bits1 & TC1_INFO) {
7169 		tcp_copy_info(&tcap->INFO_ack, tcp);
7170 		tcap->CAP_bits1 |= TC1_INFO;
7171 	}
7172 
7173 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7174 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7175 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7176 	}
7177 
7178 }
7179 
7180 /*
7181  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7182  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7183  * tcp_g_t_info_ack.  The current state of the stream is copied from
7184  * tcp_state.
7185  */
7186 static void
7187 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7188 {
7189 	t_uscalar_t		cap_bits1;
7190 	struct T_capability_ack	*tcap;
7191 
7192 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7193 		freemsg(mp);
7194 		return;
7195 	}
7196 
7197 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7198 
7199 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7200 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7201 	if (mp == NULL)
7202 		return;
7203 
7204 	tcap = (struct T_capability_ack *)mp->b_rptr;
7205 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
7206 
7207 	putnext(tcp->tcp_rq, mp);
7208 }
7209 
7210 /*
7211  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7212  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7213  * The current state of the stream is copied from tcp_state.
7214  */
7215 static void
7216 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7217 {
7218 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7219 	    T_INFO_ACK);
7220 	if (!mp) {
7221 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7222 		return;
7223 	}
7224 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7225 	putnext(tcp->tcp_rq, mp);
7226 }
7227 
7228 /* Respond to the TPI addr request */
7229 static void
7230 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7231 {
7232 	sin_t	*sin;
7233 	mblk_t	*ackmp;
7234 	struct T_addr_ack *taa;
7235 
7236 	/* Make it large enough for worst case */
7237 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7238 	    2 * sizeof (sin6_t), 1);
7239 	if (ackmp == NULL) {
7240 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7241 		return;
7242 	}
7243 
7244 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7245 		tcp_addr_req_ipv6(tcp, ackmp);
7246 		return;
7247 	}
7248 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7249 
7250 	bzero(taa, sizeof (struct T_addr_ack));
7251 	ackmp->b_wptr = (uchar_t *)&taa[1];
7252 
7253 	taa->PRIM_type = T_ADDR_ACK;
7254 	ackmp->b_datap->db_type = M_PCPROTO;
7255 
7256 	/*
7257 	 * Note: Following code assumes 32 bit alignment of basic
7258 	 * data structures like sin_t and struct T_addr_ack.
7259 	 */
7260 	if (tcp->tcp_state >= TCPS_BOUND) {
7261 		/*
7262 		 * Fill in local address
7263 		 */
7264 		taa->LOCADDR_length = sizeof (sin_t);
7265 		taa->LOCADDR_offset = sizeof (*taa);
7266 
7267 		sin = (sin_t *)&taa[1];
7268 
7269 		/* Fill zeroes and then intialize non-zero fields */
7270 		*sin = sin_null;
7271 
7272 		sin->sin_family = AF_INET;
7273 
7274 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7275 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7276 
7277 		ackmp->b_wptr = (uchar_t *)&sin[1];
7278 
7279 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7280 			/*
7281 			 * Fill in Remote address
7282 			 */
7283 			taa->REMADDR_length = sizeof (sin_t);
7284 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7285 			    taa->LOCADDR_length);
7286 
7287 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7288 			*sin = sin_null;
7289 			sin->sin_family = AF_INET;
7290 			sin->sin_addr.s_addr = tcp->tcp_remote;
7291 			sin->sin_port = tcp->tcp_fport;
7292 
7293 			ackmp->b_wptr = (uchar_t *)&sin[1];
7294 		}
7295 	}
7296 	putnext(tcp->tcp_rq, ackmp);
7297 }
7298 
7299 /* Assumes that tcp_addr_req gets enough space and alignment */
7300 static void
7301 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7302 {
7303 	sin6_t	*sin6;
7304 	struct T_addr_ack *taa;
7305 
7306 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7307 	ASSERT(OK_32PTR(ackmp->b_rptr));
7308 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7309 	    2 * sizeof (sin6_t));
7310 
7311 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7312 
7313 	bzero(taa, sizeof (struct T_addr_ack));
7314 	ackmp->b_wptr = (uchar_t *)&taa[1];
7315 
7316 	taa->PRIM_type = T_ADDR_ACK;
7317 	ackmp->b_datap->db_type = M_PCPROTO;
7318 
7319 	/*
7320 	 * Note: Following code assumes 32 bit alignment of basic
7321 	 * data structures like sin6_t and struct T_addr_ack.
7322 	 */
7323 	if (tcp->tcp_state >= TCPS_BOUND) {
7324 		/*
7325 		 * Fill in local address
7326 		 */
7327 		taa->LOCADDR_length = sizeof (sin6_t);
7328 		taa->LOCADDR_offset = sizeof (*taa);
7329 
7330 		sin6 = (sin6_t *)&taa[1];
7331 		*sin6 = sin6_null;
7332 
7333 		sin6->sin6_family = AF_INET6;
7334 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7335 		sin6->sin6_port = tcp->tcp_lport;
7336 
7337 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7338 
7339 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7340 			/*
7341 			 * Fill in Remote address
7342 			 */
7343 			taa->REMADDR_length = sizeof (sin6_t);
7344 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7345 			    taa->LOCADDR_length);
7346 
7347 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7348 			*sin6 = sin6_null;
7349 			sin6->sin6_family = AF_INET6;
7350 			sin6->sin6_flowinfo =
7351 			    tcp->tcp_ip6h->ip6_vcf &
7352 			    ~IPV6_VERS_AND_FLOW_MASK;
7353 			sin6->sin6_addr = tcp->tcp_remote_v6;
7354 			sin6->sin6_port = tcp->tcp_fport;
7355 
7356 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7357 		}
7358 	}
7359 	putnext(tcp->tcp_rq, ackmp);
7360 }
7361 
7362 /*
7363  * Handle reinitialization of a tcp structure.
7364  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7365  */
7366 static void
7367 tcp_reinit(tcp_t *tcp)
7368 {
7369 	mblk_t	*mp;
7370 	int 	err;
7371 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7372 
7373 	TCP_STAT(tcps, tcp_reinit_calls);
7374 
7375 	/* tcp_reinit should never be called for detached tcp_t's */
7376 	ASSERT(tcp->tcp_listener == NULL);
7377 	ASSERT((tcp->tcp_family == AF_INET &&
7378 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7379 	    (tcp->tcp_family == AF_INET6 &&
7380 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7381 	    tcp->tcp_ipversion == IPV6_VERSION)));
7382 
7383 	/* Cancel outstanding timers */
7384 	tcp_timers_stop(tcp);
7385 
7386 	/*
7387 	 * Reset everything in the state vector, after updating global
7388 	 * MIB data from instance counters.
7389 	 */
7390 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7391 	tcp->tcp_ibsegs = 0;
7392 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7393 	tcp->tcp_obsegs = 0;
7394 
7395 	tcp_close_mpp(&tcp->tcp_xmit_head);
7396 	if (tcp->tcp_snd_zcopy_aware)
7397 		tcp_zcopy_notify(tcp);
7398 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7399 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7400 	mutex_enter(&tcp->tcp_non_sq_lock);
7401 	if (tcp->tcp_flow_stopped &&
7402 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7403 		tcp_clrqfull(tcp);
7404 	}
7405 	mutex_exit(&tcp->tcp_non_sq_lock);
7406 	tcp_close_mpp(&tcp->tcp_reass_head);
7407 	tcp->tcp_reass_tail = NULL;
7408 	if (tcp->tcp_rcv_list != NULL) {
7409 		/* Free b_next chain */
7410 		tcp_close_mpp(&tcp->tcp_rcv_list);
7411 		tcp->tcp_rcv_last_head = NULL;
7412 		tcp->tcp_rcv_last_tail = NULL;
7413 		tcp->tcp_rcv_cnt = 0;
7414 	}
7415 	tcp->tcp_rcv_last_tail = NULL;
7416 
7417 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7418 		freemsg(mp);
7419 		tcp->tcp_urp_mp = NULL;
7420 	}
7421 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7422 		freemsg(mp);
7423 		tcp->tcp_urp_mark_mp = NULL;
7424 	}
7425 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7426 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7427 		freeb(tcp->tcp_fused_sigurg_mp);
7428 		tcp->tcp_fused_sigurg_mp = NULL;
7429 	}
7430 	if (tcp->tcp_ordrel_mp != NULL) {
7431 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7432 		freeb(tcp->tcp_ordrel_mp);
7433 		tcp->tcp_ordrel_mp = NULL;
7434 	}
7435 
7436 	/*
7437 	 * Following is a union with two members which are
7438 	 * identical types and size so the following cleanup
7439 	 * is enough.
7440 	 */
7441 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7442 
7443 	CL_INET_DISCONNECT(tcp->tcp_connp, tcp);
7444 
7445 	/*
7446 	 * The connection can't be on the tcp_time_wait_head list
7447 	 * since it is not detached.
7448 	 */
7449 	ASSERT(tcp->tcp_time_wait_next == NULL);
7450 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7451 	ASSERT(tcp->tcp_time_wait_expire == 0);
7452 
7453 	if (tcp->tcp_kssl_pending) {
7454 		tcp->tcp_kssl_pending = B_FALSE;
7455 
7456 		/* Don't reset if the initialized by bind. */
7457 		if (tcp->tcp_kssl_ent != NULL) {
7458 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7459 			    KSSL_NO_PROXY);
7460 		}
7461 	}
7462 	if (tcp->tcp_kssl_ctx != NULL) {
7463 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7464 		tcp->tcp_kssl_ctx = NULL;
7465 	}
7466 
7467 	/*
7468 	 * Reset/preserve other values
7469 	 */
7470 	tcp_reinit_values(tcp);
7471 	ipcl_hash_remove(tcp->tcp_connp);
7472 	conn_delete_ire(tcp->tcp_connp, NULL);
7473 	tcp_ipsec_cleanup(tcp);
7474 
7475 	if (tcp->tcp_conn_req_max != 0) {
7476 		/*
7477 		 * This is the case when a TLI program uses the same
7478 		 * transport end point to accept a connection.  This
7479 		 * makes the TCP both a listener and acceptor.  When
7480 		 * this connection is closed, we need to set the state
7481 		 * back to TCPS_LISTEN.  Make sure that the eager list
7482 		 * is reinitialized.
7483 		 *
7484 		 * Note that this stream is still bound to the four
7485 		 * tuples of the previous connection in IP.  If a new
7486 		 * SYN with different foreign address comes in, IP will
7487 		 * not find it and will send it to the global queue.  In
7488 		 * the global queue, TCP will do a tcp_lookup_listener()
7489 		 * to find this stream.  This works because this stream
7490 		 * is only removed from connected hash.
7491 		 *
7492 		 */
7493 		tcp->tcp_state = TCPS_LISTEN;
7494 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7495 		tcp->tcp_eager_next_drop_q0 = tcp;
7496 		tcp->tcp_eager_prev_drop_q0 = tcp;
7497 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7498 		if (tcp->tcp_family == AF_INET6) {
7499 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7500 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7501 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7502 		} else {
7503 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7504 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7505 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7506 		}
7507 	} else {
7508 		tcp->tcp_state = TCPS_BOUND;
7509 	}
7510 
7511 	/*
7512 	 * Initialize to default values
7513 	 * Can't fail since enough header template space already allocated
7514 	 * at open().
7515 	 */
7516 	err = tcp_init_values(tcp);
7517 	ASSERT(err == 0);
7518 	/* Restore state in tcp_tcph */
7519 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7520 	if (tcp->tcp_ipversion == IPV4_VERSION)
7521 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7522 	else
7523 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7524 	/*
7525 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7526 	 * since the lookup funcs can only lookup on tcp_t
7527 	 */
7528 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7529 
7530 	ASSERT(tcp->tcp_ptpbhn != NULL);
7531 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
7532 		tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7533 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
7534 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
7535 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7536 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7537 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7538 }
7539 
7540 /*
7541  * Force values to zero that need be zero.
7542  * Do not touch values asociated with the BOUND or LISTEN state
7543  * since the connection will end up in that state after the reinit.
7544  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7545  * structure!
7546  */
7547 static void
7548 tcp_reinit_values(tcp)
7549 	tcp_t *tcp;
7550 {
7551 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7552 
7553 #ifndef	lint
7554 #define	DONTCARE(x)
7555 #define	PRESERVE(x)
7556 #else
7557 #define	DONTCARE(x)	((x) = (x))
7558 #define	PRESERVE(x)	((x) = (x))
7559 #endif	/* lint */
7560 
7561 	PRESERVE(tcp->tcp_bind_hash_port);
7562 	PRESERVE(tcp->tcp_bind_hash);
7563 	PRESERVE(tcp->tcp_ptpbhn);
7564 	PRESERVE(tcp->tcp_acceptor_hash);
7565 	PRESERVE(tcp->tcp_ptpahn);
7566 
7567 	/* Should be ASSERT NULL on these with new code! */
7568 	ASSERT(tcp->tcp_time_wait_next == NULL);
7569 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7570 	ASSERT(tcp->tcp_time_wait_expire == 0);
7571 	PRESERVE(tcp->tcp_state);
7572 	PRESERVE(tcp->tcp_rq);
7573 	PRESERVE(tcp->tcp_wq);
7574 
7575 	ASSERT(tcp->tcp_xmit_head == NULL);
7576 	ASSERT(tcp->tcp_xmit_last == NULL);
7577 	ASSERT(tcp->tcp_unsent == 0);
7578 	ASSERT(tcp->tcp_xmit_tail == NULL);
7579 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7580 
7581 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7582 	tcp->tcp_suna = 0;			/* Displayed in mib */
7583 	tcp->tcp_swnd = 0;
7584 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7585 
7586 	ASSERT(tcp->tcp_ibsegs == 0);
7587 	ASSERT(tcp->tcp_obsegs == 0);
7588 
7589 	if (tcp->tcp_iphc != NULL) {
7590 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7591 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7592 	}
7593 
7594 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7595 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7596 	DONTCARE(tcp->tcp_ipha);
7597 	DONTCARE(tcp->tcp_ip6h);
7598 	DONTCARE(tcp->tcp_ip_hdr_len);
7599 	DONTCARE(tcp->tcp_tcph);
7600 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7601 	tcp->tcp_valid_bits = 0;
7602 
7603 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7604 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7605 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7606 	tcp->tcp_last_rcv_lbolt = 0;
7607 
7608 	tcp->tcp_init_cwnd = 0;
7609 
7610 	tcp->tcp_urp_last_valid = 0;
7611 	tcp->tcp_hard_binding = 0;
7612 	tcp->tcp_hard_bound = 0;
7613 	PRESERVE(tcp->tcp_cred);
7614 	PRESERVE(tcp->tcp_cpid);
7615 	PRESERVE(tcp->tcp_open_time);
7616 	PRESERVE(tcp->tcp_exclbind);
7617 
7618 	tcp->tcp_fin_acked = 0;
7619 	tcp->tcp_fin_rcvd = 0;
7620 	tcp->tcp_fin_sent = 0;
7621 	tcp->tcp_ordrel_done = 0;
7622 
7623 	tcp->tcp_debug = 0;
7624 	tcp->tcp_dontroute = 0;
7625 	tcp->tcp_broadcast = 0;
7626 
7627 	tcp->tcp_useloopback = 0;
7628 	tcp->tcp_reuseaddr = 0;
7629 	tcp->tcp_oobinline = 0;
7630 	tcp->tcp_dgram_errind = 0;
7631 
7632 	tcp->tcp_detached = 0;
7633 	tcp->tcp_bind_pending = 0;
7634 	tcp->tcp_unbind_pending = 0;
7635 
7636 	tcp->tcp_snd_ws_ok = B_FALSE;
7637 	tcp->tcp_snd_ts_ok = B_FALSE;
7638 	tcp->tcp_linger = 0;
7639 	tcp->tcp_ka_enabled = 0;
7640 	tcp->tcp_zero_win_probe = 0;
7641 
7642 	tcp->tcp_loopback = 0;
7643 	tcp->tcp_refuse = 0;
7644 	tcp->tcp_localnet = 0;
7645 	tcp->tcp_syn_defense = 0;
7646 	tcp->tcp_set_timer = 0;
7647 
7648 	tcp->tcp_active_open = 0;
7649 	tcp->tcp_rexmit = B_FALSE;
7650 	tcp->tcp_xmit_zc_clean = B_FALSE;
7651 
7652 	tcp->tcp_snd_sack_ok = B_FALSE;
7653 	PRESERVE(tcp->tcp_recvdstaddr);
7654 	tcp->tcp_hwcksum = B_FALSE;
7655 
7656 	tcp->tcp_ire_ill_check_done = B_FALSE;
7657 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7658 
7659 	tcp->tcp_mdt = B_FALSE;
7660 	tcp->tcp_mdt_hdr_head = 0;
7661 	tcp->tcp_mdt_hdr_tail = 0;
7662 
7663 	tcp->tcp_conn_def_q0 = 0;
7664 	tcp->tcp_ip_forward_progress = B_FALSE;
7665 	tcp->tcp_anon_priv_bind = 0;
7666 	tcp->tcp_ecn_ok = B_FALSE;
7667 
7668 	tcp->tcp_cwr = B_FALSE;
7669 	tcp->tcp_ecn_echo_on = B_FALSE;
7670 
7671 	if (tcp->tcp_sack_info != NULL) {
7672 		if (tcp->tcp_notsack_list != NULL) {
7673 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7674 		}
7675 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7676 		tcp->tcp_sack_info = NULL;
7677 	}
7678 
7679 	tcp->tcp_rcv_ws = 0;
7680 	tcp->tcp_snd_ws = 0;
7681 	tcp->tcp_ts_recent = 0;
7682 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7683 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7684 	tcp->tcp_if_mtu = 0;
7685 
7686 	ASSERT(tcp->tcp_reass_head == NULL);
7687 	ASSERT(tcp->tcp_reass_tail == NULL);
7688 
7689 	tcp->tcp_cwnd_cnt = 0;
7690 
7691 	ASSERT(tcp->tcp_rcv_list == NULL);
7692 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7693 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7694 	ASSERT(tcp->tcp_rcv_cnt == 0);
7695 
7696 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7697 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7698 	tcp->tcp_csuna = 0;
7699 
7700 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7701 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7702 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7703 	tcp->tcp_rtt_update = 0;
7704 
7705 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7706 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7707 
7708 	tcp->tcp_rack = 0;			/* Displayed in mib */
7709 	tcp->tcp_rack_cnt = 0;
7710 	tcp->tcp_rack_cur_max = 0;
7711 	tcp->tcp_rack_abs_max = 0;
7712 
7713 	tcp->tcp_max_swnd = 0;
7714 
7715 	ASSERT(tcp->tcp_listener == NULL);
7716 
7717 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7718 
7719 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7720 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7721 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7722 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7723 
7724 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7725 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7726 	PRESERVE(tcp->tcp_conn_req_max);
7727 	PRESERVE(tcp->tcp_conn_req_seqnum);
7728 
7729 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7730 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7731 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7732 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7733 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7734 
7735 	tcp->tcp_lingertime = 0;
7736 
7737 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7738 	ASSERT(tcp->tcp_urp_mp == NULL);
7739 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7740 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7741 
7742 	ASSERT(tcp->tcp_eager_next_q == NULL);
7743 	ASSERT(tcp->tcp_eager_last_q == NULL);
7744 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7745 	    tcp->tcp_eager_prev_q0 == NULL) ||
7746 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7747 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7748 
7749 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
7750 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
7751 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
7752 
7753 	tcp->tcp_client_errno = 0;
7754 
7755 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7756 
7757 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7758 
7759 	PRESERVE(tcp->tcp_bound_source_v6);
7760 	tcp->tcp_last_sent_len = 0;
7761 	tcp->tcp_dupack_cnt = 0;
7762 
7763 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7764 	PRESERVE(tcp->tcp_lport);
7765 
7766 	PRESERVE(tcp->tcp_acceptor_lockp);
7767 
7768 	ASSERT(tcp->tcp_ordrel_mp == NULL);
7769 	PRESERVE(tcp->tcp_acceptor_id);
7770 	DONTCARE(tcp->tcp_ipsec_overhead);
7771 
7772 	PRESERVE(tcp->tcp_family);
7773 	if (tcp->tcp_family == AF_INET6) {
7774 		tcp->tcp_ipversion = IPV6_VERSION;
7775 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7776 	} else {
7777 		tcp->tcp_ipversion = IPV4_VERSION;
7778 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7779 	}
7780 
7781 	tcp->tcp_bound_if = 0;
7782 	tcp->tcp_ipv6_recvancillary = 0;
7783 	tcp->tcp_recvifindex = 0;
7784 	tcp->tcp_recvhops = 0;
7785 	tcp->tcp_closed = 0;
7786 	tcp->tcp_cleandeathtag = 0;
7787 	if (tcp->tcp_hopopts != NULL) {
7788 		mi_free(tcp->tcp_hopopts);
7789 		tcp->tcp_hopopts = NULL;
7790 		tcp->tcp_hopoptslen = 0;
7791 	}
7792 	ASSERT(tcp->tcp_hopoptslen == 0);
7793 	if (tcp->tcp_dstopts != NULL) {
7794 		mi_free(tcp->tcp_dstopts);
7795 		tcp->tcp_dstopts = NULL;
7796 		tcp->tcp_dstoptslen = 0;
7797 	}
7798 	ASSERT(tcp->tcp_dstoptslen == 0);
7799 	if (tcp->tcp_rtdstopts != NULL) {
7800 		mi_free(tcp->tcp_rtdstopts);
7801 		tcp->tcp_rtdstopts = NULL;
7802 		tcp->tcp_rtdstoptslen = 0;
7803 	}
7804 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7805 	if (tcp->tcp_rthdr != NULL) {
7806 		mi_free(tcp->tcp_rthdr);
7807 		tcp->tcp_rthdr = NULL;
7808 		tcp->tcp_rthdrlen = 0;
7809 	}
7810 	ASSERT(tcp->tcp_rthdrlen == 0);
7811 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7812 
7813 	/* Reset fusion-related fields */
7814 	tcp->tcp_fused = B_FALSE;
7815 	tcp->tcp_unfusable = B_FALSE;
7816 	tcp->tcp_fused_sigurg = B_FALSE;
7817 	tcp->tcp_direct_sockfs = B_FALSE;
7818 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7819 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7820 	tcp->tcp_loopback_peer = NULL;
7821 	tcp->tcp_fuse_rcv_hiwater = 0;
7822 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7823 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7824 
7825 	tcp->tcp_lso = B_FALSE;
7826 
7827 	tcp->tcp_in_ack_unsent = 0;
7828 	tcp->tcp_cork = B_FALSE;
7829 	tcp->tcp_tconnind_started = B_FALSE;
7830 
7831 	PRESERVE(tcp->tcp_squeue_bytes);
7832 
7833 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7834 	ASSERT(!tcp->tcp_kssl_pending);
7835 	PRESERVE(tcp->tcp_kssl_ent);
7836 
7837 	/* Sodirect */
7838 	tcp->tcp_sodirect = NULL;
7839 
7840 	tcp->tcp_closemp_used = B_FALSE;
7841 
7842 	PRESERVE(tcp->tcp_rsrv_mp);
7843 	PRESERVE(tcp->tcp_rsrv_mp_lock);
7844 
7845 #ifdef DEBUG
7846 	DONTCARE(tcp->tcmp_stk[0]);
7847 #endif
7848 
7849 	PRESERVE(tcp->tcp_connid);
7850 
7851 
7852 #undef	DONTCARE
7853 #undef	PRESERVE
7854 }
7855 
7856 /*
7857  * Allocate necessary resources and initialize state vector.
7858  * Guaranteed not to fail so that when an error is returned,
7859  * the caller doesn't need to do any additional cleanup.
7860  */
7861 int
7862 tcp_init(tcp_t *tcp, queue_t *q)
7863 {
7864 	int	err;
7865 
7866 	tcp->tcp_rq = q;
7867 	tcp->tcp_wq = WR(q);
7868 	tcp->tcp_state = TCPS_IDLE;
7869 	if ((err = tcp_init_values(tcp)) != 0)
7870 		tcp_timers_stop(tcp);
7871 	return (err);
7872 }
7873 
7874 static int
7875 tcp_init_values(tcp_t *tcp)
7876 {
7877 	int	err;
7878 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7879 
7880 	ASSERT((tcp->tcp_family == AF_INET &&
7881 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7882 	    (tcp->tcp_family == AF_INET6 &&
7883 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7884 	    tcp->tcp_ipversion == IPV6_VERSION)));
7885 
7886 	/*
7887 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7888 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7889 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7890 	 * during first few transmissions of a connection as seen in slow
7891 	 * links.
7892 	 */
7893 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
7894 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
7895 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7896 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7897 	    tcps->tcps_conn_grace_period;
7898 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
7899 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
7900 	tcp->tcp_timer_backoff = 0;
7901 	tcp->tcp_ms_we_have_waited = 0;
7902 	tcp->tcp_last_recv_time = lbolt;
7903 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
7904 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7905 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7906 
7907 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
7908 
7909 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
7910 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
7911 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
7912 	/*
7913 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7914 	 * passive open.
7915 	 */
7916 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
7917 
7918 	tcp->tcp_naglim = tcps->tcps_naglim_def;
7919 
7920 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7921 
7922 	tcp->tcp_mdt_hdr_head = 0;
7923 	tcp->tcp_mdt_hdr_tail = 0;
7924 
7925 	/* Reset fusion-related fields */
7926 	tcp->tcp_fused = B_FALSE;
7927 	tcp->tcp_unfusable = B_FALSE;
7928 	tcp->tcp_fused_sigurg = B_FALSE;
7929 	tcp->tcp_direct_sockfs = B_FALSE;
7930 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7931 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7932 	tcp->tcp_loopback_peer = NULL;
7933 	tcp->tcp_fuse_rcv_hiwater = 0;
7934 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7935 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7936 
7937 	/* Sodirect */
7938 	tcp->tcp_sodirect = NULL;
7939 
7940 	/* Initialize the header template */
7941 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7942 		err = tcp_header_init_ipv4(tcp);
7943 	} else {
7944 		err = tcp_header_init_ipv6(tcp);
7945 	}
7946 	if (err)
7947 		return (err);
7948 
7949 	/*
7950 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7951 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7952 	 */
7953 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7954 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
7955 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
7956 
7957 	tcp->tcp_cork = B_FALSE;
7958 	/*
7959 	 * Init the tcp_debug option.  This value determines whether TCP
7960 	 * calls strlog() to print out debug messages.  Doing this
7961 	 * initialization here means that this value is not inherited thru
7962 	 * tcp_reinit().
7963 	 */
7964 	tcp->tcp_debug = tcps->tcps_dbg;
7965 
7966 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
7967 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
7968 
7969 	return (0);
7970 }
7971 
7972 /*
7973  * Initialize the IPv4 header. Loses any record of any IP options.
7974  */
7975 static int
7976 tcp_header_init_ipv4(tcp_t *tcp)
7977 {
7978 	tcph_t		*tcph;
7979 	uint32_t	sum;
7980 	conn_t		*connp;
7981 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7982 
7983 	/*
7984 	 * This is a simple initialization. If there's
7985 	 * already a template, it should never be too small,
7986 	 * so reuse it.  Otherwise, allocate space for the new one.
7987 	 */
7988 	if (tcp->tcp_iphc == NULL) {
7989 		ASSERT(tcp->tcp_iphc_len == 0);
7990 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
7991 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
7992 		if (tcp->tcp_iphc == NULL) {
7993 			tcp->tcp_iphc_len = 0;
7994 			return (ENOMEM);
7995 		}
7996 	}
7997 
7998 	/* options are gone; may need a new label */
7999 	connp = tcp->tcp_connp;
8000 	connp->conn_mlp_type = mlptSingle;
8001 	connp->conn_ulp_labeled = !is_system_labeled();
8002 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8003 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8004 	tcp->tcp_ip6h = NULL;
8005 	tcp->tcp_ipversion = IPV4_VERSION;
8006 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8007 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8008 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8009 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8010 	tcp->tcp_ipha->ipha_version_and_hdr_length
8011 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8012 	tcp->tcp_ipha->ipha_ident = 0;
8013 
8014 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8015 	tcp->tcp_tos = 0;
8016 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8017 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8018 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8019 
8020 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8021 	tcp->tcp_tcph = tcph;
8022 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8023 	/*
8024 	 * IP wants our header length in the checksum field to
8025 	 * allow it to perform a single pseudo-header+checksum
8026 	 * calculation on behalf of TCP.
8027 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8028 	 */
8029 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8030 	sum = (sum >> 16) + (sum & 0xFFFF);
8031 	U16_TO_ABE16(sum, tcph->th_sum);
8032 	return (0);
8033 }
8034 
8035 /*
8036  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8037  */
8038 static int
8039 tcp_header_init_ipv6(tcp_t *tcp)
8040 {
8041 	tcph_t	*tcph;
8042 	uint32_t	sum;
8043 	conn_t	*connp;
8044 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8045 
8046 	/*
8047 	 * This is a simple initialization. If there's
8048 	 * already a template, it should never be too small,
8049 	 * so reuse it. Otherwise, allocate space for the new one.
8050 	 * Ensure that there is enough space to "downgrade" the tcp_t
8051 	 * to an IPv4 tcp_t. This requires having space for a full load
8052 	 * of IPv4 options, as well as a full load of TCP options
8053 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8054 	 * than a v6 header and a TCP header with a full load of TCP options
8055 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8056 	 * We want to avoid reallocation in the "downgraded" case when
8057 	 * processing outbound IPv4 options.
8058 	 */
8059 	if (tcp->tcp_iphc == NULL) {
8060 		ASSERT(tcp->tcp_iphc_len == 0);
8061 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8062 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8063 		if (tcp->tcp_iphc == NULL) {
8064 			tcp->tcp_iphc_len = 0;
8065 			return (ENOMEM);
8066 		}
8067 	}
8068 
8069 	/* options are gone; may need a new label */
8070 	connp = tcp->tcp_connp;
8071 	connp->conn_mlp_type = mlptSingle;
8072 	connp->conn_ulp_labeled = !is_system_labeled();
8073 
8074 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8075 	tcp->tcp_ipversion = IPV6_VERSION;
8076 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8077 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8078 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8079 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8080 	tcp->tcp_ipha = NULL;
8081 
8082 	/* Initialize the header template */
8083 
8084 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8085 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8086 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8087 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8088 
8089 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8090 	tcp->tcp_tcph = tcph;
8091 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8092 	/*
8093 	 * IP wants our header length in the checksum field to
8094 	 * allow it to perform a single psuedo-header+checksum
8095 	 * calculation on behalf of TCP.
8096 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8097 	 */
8098 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8099 	sum = (sum >> 16) + (sum & 0xFFFF);
8100 	U16_TO_ABE16(sum, tcph->th_sum);
8101 	return (0);
8102 }
8103 
8104 /* At minimum we need 8 bytes in the TCP header for the lookup */
8105 #define	ICMP_MIN_TCP_HDR	8
8106 
8107 /*
8108  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8109  * passed up by IP. The message is always received on the correct tcp_t.
8110  * Assumes that IP has pulled up everything up to and including the ICMP header.
8111  */
8112 void
8113 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8114 {
8115 	icmph_t *icmph;
8116 	ipha_t	*ipha;
8117 	int	iph_hdr_length;
8118 	tcph_t	*tcph;
8119 	boolean_t ipsec_mctl = B_FALSE;
8120 	boolean_t secure;
8121 	mblk_t *first_mp = mp;
8122 	int32_t new_mss;
8123 	uint32_t ratio;
8124 	size_t mp_size = MBLKL(mp);
8125 	uint32_t seg_seq;
8126 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8127 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8128 
8129 	/* Assume IP provides aligned packets - otherwise toss */
8130 	if (!OK_32PTR(mp->b_rptr)) {
8131 		freemsg(mp);
8132 		return;
8133 	}
8134 
8135 	/*
8136 	 * Since ICMP errors are normal data marked with M_CTL when sent
8137 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8138 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8139 	 */
8140 	if ((mp_size == sizeof (ipsec_info_t)) &&
8141 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8142 		ASSERT(mp->b_cont != NULL);
8143 		mp = mp->b_cont;
8144 		/* IP should have done this */
8145 		ASSERT(OK_32PTR(mp->b_rptr));
8146 		mp_size = MBLKL(mp);
8147 		ipsec_mctl = B_TRUE;
8148 	}
8149 
8150 	/*
8151 	 * Verify that we have a complete outer IP header. If not, drop it.
8152 	 */
8153 	if (mp_size < sizeof (ipha_t)) {
8154 noticmpv4:
8155 		freemsg(first_mp);
8156 		return;
8157 	}
8158 
8159 	ipha = (ipha_t *)mp->b_rptr;
8160 	/*
8161 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8162 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8163 	 */
8164 	switch (IPH_HDR_VERSION(ipha)) {
8165 	case IPV6_VERSION:
8166 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8167 		return;
8168 	case IPV4_VERSION:
8169 		break;
8170 	default:
8171 		goto noticmpv4;
8172 	}
8173 
8174 	/* Skip past the outer IP and ICMP headers */
8175 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8176 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8177 	/*
8178 	 * If we don't have the correct outer IP header length or if the ULP
8179 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8180 	 * send it upstream.
8181 	 */
8182 	if (iph_hdr_length < sizeof (ipha_t) ||
8183 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8184 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8185 		goto noticmpv4;
8186 	}
8187 	ipha = (ipha_t *)&icmph[1];
8188 
8189 	/* Skip past the inner IP and find the ULP header */
8190 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8191 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8192 	/*
8193 	 * If we don't have the correct inner IP header length or if the ULP
8194 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8195 	 * bytes of TCP header, drop it.
8196 	 */
8197 	if (iph_hdr_length < sizeof (ipha_t) ||
8198 	    ipha->ipha_protocol != IPPROTO_TCP ||
8199 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8200 		goto noticmpv4;
8201 	}
8202 
8203 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8204 		if (ipsec_mctl) {
8205 			secure = ipsec_in_is_secure(first_mp);
8206 		} else {
8207 			secure = B_FALSE;
8208 		}
8209 		if (secure) {
8210 			/*
8211 			 * If we are willing to accept this in clear
8212 			 * we don't have to verify policy.
8213 			 */
8214 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8215 				if (!tcp_check_policy(tcp, first_mp,
8216 				    ipha, NULL, secure, ipsec_mctl)) {
8217 					/*
8218 					 * tcp_check_policy called
8219 					 * ip_drop_packet() on failure.
8220 					 */
8221 					return;
8222 				}
8223 			}
8224 		}
8225 	} else if (ipsec_mctl) {
8226 		/*
8227 		 * This is a hard_bound connection. IP has already
8228 		 * verified policy. We don't have to do it again.
8229 		 */
8230 		freeb(first_mp);
8231 		first_mp = mp;
8232 		ipsec_mctl = B_FALSE;
8233 	}
8234 
8235 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8236 	/*
8237 	 * TCP SHOULD check that the TCP sequence number contained in
8238 	 * payload of the ICMP error message is within the range
8239 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8240 	 */
8241 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8242 		/*
8243 		 * The ICMP message is bogus, just drop it.  But if this is
8244 		 * an ICMP too big message, IP has already changed
8245 		 * the ire_max_frag to the bogus value.  We need to change
8246 		 * it back.
8247 		 */
8248 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8249 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8250 			conn_t *connp = tcp->tcp_connp;
8251 			ire_t *ire;
8252 			int flag;
8253 
8254 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8255 				flag = tcp->tcp_ipha->
8256 				    ipha_fragment_offset_and_flags;
8257 			} else {
8258 				flag = 0;
8259 			}
8260 			mutex_enter(&connp->conn_lock);
8261 			if ((ire = connp->conn_ire_cache) != NULL) {
8262 				mutex_enter(&ire->ire_lock);
8263 				mutex_exit(&connp->conn_lock);
8264 				ire->ire_max_frag = tcp->tcp_if_mtu;
8265 				ire->ire_frag_flag |= flag;
8266 				mutex_exit(&ire->ire_lock);
8267 			} else {
8268 				mutex_exit(&connp->conn_lock);
8269 			}
8270 		}
8271 		goto noticmpv4;
8272 	}
8273 
8274 	switch (icmph->icmph_type) {
8275 	case ICMP_DEST_UNREACHABLE:
8276 		switch (icmph->icmph_code) {
8277 		case ICMP_FRAGMENTATION_NEEDED:
8278 			/*
8279 			 * Reduce the MSS based on the new MTU.  This will
8280 			 * eliminate any fragmentation locally.
8281 			 * N.B.  There may well be some funny side-effects on
8282 			 * the local send policy and the remote receive policy.
8283 			 * Pending further research, we provide
8284 			 * tcp_ignore_path_mtu just in case this proves
8285 			 * disastrous somewhere.
8286 			 *
8287 			 * After updating the MSS, retransmit part of the
8288 			 * dropped segment using the new mss by calling
8289 			 * tcp_wput_data().  Need to adjust all those
8290 			 * params to make sure tcp_wput_data() work properly.
8291 			 */
8292 			if (tcps->tcps_ignore_path_mtu ||
8293 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8294 				break;
8295 
8296 			/*
8297 			 * Decrease the MSS by time stamp options
8298 			 * IP options and IPSEC options. tcp_hdr_len
8299 			 * includes time stamp option and IP option
8300 			 * length.  Note that new_mss may be negative
8301 			 * if tcp_ipsec_overhead is large and the
8302 			 * icmph_du_mtu is the minimum value, which is 68.
8303 			 */
8304 			new_mss = ntohs(icmph->icmph_du_mtu) -
8305 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8306 
8307 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8308 			    new_mss);
8309 
8310 			/*
8311 			 * Only update the MSS if the new one is
8312 			 * smaller than the previous one.  This is
8313 			 * to avoid problems when getting multiple
8314 			 * ICMP errors for the same MTU.
8315 			 */
8316 			if (new_mss >= tcp->tcp_mss)
8317 				break;
8318 
8319 			/*
8320 			 * Note that we are using the template header's DF
8321 			 * bit in the fast path sending.  So we need to compare
8322 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8323 			 * And stop doing IPv4 PMTUd if new_mss is less than
8324 			 * MAX(tcps_mss_min, ip_pmtu_min).
8325 			 */
8326 			if (new_mss < tcps->tcps_mss_min ||
8327 			    new_mss < ipst->ips_ip_pmtu_min) {
8328 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8329 				    0;
8330 			}
8331 
8332 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8333 			ASSERT(ratio >= 1);
8334 			tcp_mss_set(tcp, new_mss, B_TRUE);
8335 
8336 			/*
8337 			 * Make sure we have something to
8338 			 * send.
8339 			 */
8340 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8341 			    (tcp->tcp_xmit_head != NULL)) {
8342 				/*
8343 				 * Shrink tcp_cwnd in
8344 				 * proportion to the old MSS/new MSS.
8345 				 */
8346 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8347 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8348 				    (tcp->tcp_unsent == 0)) {
8349 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8350 				} else {
8351 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8352 				}
8353 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8354 				tcp->tcp_rexmit = B_TRUE;
8355 				tcp->tcp_dupack_cnt = 0;
8356 				tcp->tcp_snd_burst = TCP_CWND_SS;
8357 				tcp_ss_rexmit(tcp);
8358 			}
8359 			break;
8360 		case ICMP_PORT_UNREACHABLE:
8361 		case ICMP_PROTOCOL_UNREACHABLE:
8362 			switch (tcp->tcp_state) {
8363 			case TCPS_SYN_SENT:
8364 			case TCPS_SYN_RCVD:
8365 				/*
8366 				 * ICMP can snipe away incipient
8367 				 * TCP connections as long as
8368 				 * seq number is same as initial
8369 				 * send seq number.
8370 				 */
8371 				if (seg_seq == tcp->tcp_iss) {
8372 					(void) tcp_clean_death(tcp,
8373 					    ECONNREFUSED, 6);
8374 				}
8375 				break;
8376 			}
8377 			break;
8378 		case ICMP_HOST_UNREACHABLE:
8379 		case ICMP_NET_UNREACHABLE:
8380 			/* Record the error in case we finally time out. */
8381 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8382 				tcp->tcp_client_errno = EHOSTUNREACH;
8383 			else
8384 				tcp->tcp_client_errno = ENETUNREACH;
8385 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8386 				if (tcp->tcp_listener != NULL &&
8387 				    tcp->tcp_listener->tcp_syn_defense) {
8388 					/*
8389 					 * Ditch the half-open connection if we
8390 					 * suspect a SYN attack is under way.
8391 					 */
8392 					tcp_ip_ire_mark_advice(tcp);
8393 					(void) tcp_clean_death(tcp,
8394 					    tcp->tcp_client_errno, 7);
8395 				}
8396 			}
8397 			break;
8398 		default:
8399 			break;
8400 		}
8401 		break;
8402 	case ICMP_SOURCE_QUENCH: {
8403 		/*
8404 		 * use a global boolean to control
8405 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8406 		 * The default is false.
8407 		 */
8408 		if (tcp_icmp_source_quench) {
8409 			/*
8410 			 * Reduce the sending rate as if we got a
8411 			 * retransmit timeout
8412 			 */
8413 			uint32_t npkt;
8414 
8415 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8416 			    tcp->tcp_mss;
8417 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8418 			tcp->tcp_cwnd = tcp->tcp_mss;
8419 			tcp->tcp_cwnd_cnt = 0;
8420 		}
8421 		break;
8422 	}
8423 	}
8424 	freemsg(first_mp);
8425 }
8426 
8427 /*
8428  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8429  * error messages passed up by IP.
8430  * Assumes that IP has pulled up all the extension headers as well
8431  * as the ICMPv6 header.
8432  */
8433 static void
8434 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8435 {
8436 	icmp6_t *icmp6;
8437 	ip6_t	*ip6h;
8438 	uint16_t	iph_hdr_length;
8439 	tcpha_t	*tcpha;
8440 	uint8_t	*nexthdrp;
8441 	uint32_t new_mss;
8442 	uint32_t ratio;
8443 	boolean_t secure;
8444 	mblk_t *first_mp = mp;
8445 	size_t mp_size;
8446 	uint32_t seg_seq;
8447 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8448 
8449 	/*
8450 	 * The caller has determined if this is an IPSEC_IN packet and
8451 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8452 	 */
8453 	if (ipsec_mctl)
8454 		mp = mp->b_cont;
8455 
8456 	mp_size = MBLKL(mp);
8457 
8458 	/*
8459 	 * Verify that we have a complete IP header. If not, send it upstream.
8460 	 */
8461 	if (mp_size < sizeof (ip6_t)) {
8462 noticmpv6:
8463 		freemsg(first_mp);
8464 		return;
8465 	}
8466 
8467 	/*
8468 	 * Verify this is an ICMPV6 packet, else send it upstream.
8469 	 */
8470 	ip6h = (ip6_t *)mp->b_rptr;
8471 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8472 		iph_hdr_length = IPV6_HDR_LEN;
8473 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8474 	    &nexthdrp) ||
8475 	    *nexthdrp != IPPROTO_ICMPV6) {
8476 		goto noticmpv6;
8477 	}
8478 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8479 	ip6h = (ip6_t *)&icmp6[1];
8480 	/*
8481 	 * Verify if we have a complete ICMP and inner IP header.
8482 	 */
8483 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8484 		goto noticmpv6;
8485 
8486 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8487 		goto noticmpv6;
8488 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8489 	/*
8490 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8491 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8492 	 * packet.
8493 	 */
8494 	if ((*nexthdrp != IPPROTO_TCP) ||
8495 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8496 		goto noticmpv6;
8497 	}
8498 
8499 	/*
8500 	 * ICMP errors come on the right queue or come on
8501 	 * listener/global queue for detached connections and
8502 	 * get switched to the right queue. If it comes on the
8503 	 * right queue, policy check has already been done by IP
8504 	 * and thus free the first_mp without verifying the policy.
8505 	 * If it has come for a non-hard bound connection, we need
8506 	 * to verify policy as IP may not have done it.
8507 	 */
8508 	if (!tcp->tcp_hard_bound) {
8509 		if (ipsec_mctl) {
8510 			secure = ipsec_in_is_secure(first_mp);
8511 		} else {
8512 			secure = B_FALSE;
8513 		}
8514 		if (secure) {
8515 			/*
8516 			 * If we are willing to accept this in clear
8517 			 * we don't have to verify policy.
8518 			 */
8519 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8520 				if (!tcp_check_policy(tcp, first_mp,
8521 				    NULL, ip6h, secure, ipsec_mctl)) {
8522 					/*
8523 					 * tcp_check_policy called
8524 					 * ip_drop_packet() on failure.
8525 					 */
8526 					return;
8527 				}
8528 			}
8529 		}
8530 	} else if (ipsec_mctl) {
8531 		/*
8532 		 * This is a hard_bound connection. IP has already
8533 		 * verified policy. We don't have to do it again.
8534 		 */
8535 		freeb(first_mp);
8536 		first_mp = mp;
8537 		ipsec_mctl = B_FALSE;
8538 	}
8539 
8540 	seg_seq = ntohl(tcpha->tha_seq);
8541 	/*
8542 	 * TCP SHOULD check that the TCP sequence number contained in
8543 	 * payload of the ICMP error message is within the range
8544 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8545 	 */
8546 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8547 		/*
8548 		 * If the ICMP message is bogus, should we kill the
8549 		 * connection, or should we just drop the bogus ICMP
8550 		 * message? It would probably make more sense to just
8551 		 * drop the message so that if this one managed to get
8552 		 * in, the real connection should not suffer.
8553 		 */
8554 		goto noticmpv6;
8555 	}
8556 
8557 	switch (icmp6->icmp6_type) {
8558 	case ICMP6_PACKET_TOO_BIG:
8559 		/*
8560 		 * Reduce the MSS based on the new MTU.  This will
8561 		 * eliminate any fragmentation locally.
8562 		 * N.B.  There may well be some funny side-effects on
8563 		 * the local send policy and the remote receive policy.
8564 		 * Pending further research, we provide
8565 		 * tcp_ignore_path_mtu just in case this proves
8566 		 * disastrous somewhere.
8567 		 *
8568 		 * After updating the MSS, retransmit part of the
8569 		 * dropped segment using the new mss by calling
8570 		 * tcp_wput_data().  Need to adjust all those
8571 		 * params to make sure tcp_wput_data() work properly.
8572 		 */
8573 		if (tcps->tcps_ignore_path_mtu)
8574 			break;
8575 
8576 		/*
8577 		 * Decrease the MSS by time stamp options
8578 		 * IP options and IPSEC options. tcp_hdr_len
8579 		 * includes time stamp option and IP option
8580 		 * length.
8581 		 */
8582 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8583 		    tcp->tcp_ipsec_overhead;
8584 
8585 		/*
8586 		 * Only update the MSS if the new one is
8587 		 * smaller than the previous one.  This is
8588 		 * to avoid problems when getting multiple
8589 		 * ICMP errors for the same MTU.
8590 		 */
8591 		if (new_mss >= tcp->tcp_mss)
8592 			break;
8593 
8594 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8595 		ASSERT(ratio >= 1);
8596 		tcp_mss_set(tcp, new_mss, B_TRUE);
8597 
8598 		/*
8599 		 * Make sure we have something to
8600 		 * send.
8601 		 */
8602 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8603 		    (tcp->tcp_xmit_head != NULL)) {
8604 			/*
8605 			 * Shrink tcp_cwnd in
8606 			 * proportion to the old MSS/new MSS.
8607 			 */
8608 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8609 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8610 			    (tcp->tcp_unsent == 0)) {
8611 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8612 			} else {
8613 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8614 			}
8615 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8616 			tcp->tcp_rexmit = B_TRUE;
8617 			tcp->tcp_dupack_cnt = 0;
8618 			tcp->tcp_snd_burst = TCP_CWND_SS;
8619 			tcp_ss_rexmit(tcp);
8620 		}
8621 		break;
8622 
8623 	case ICMP6_DST_UNREACH:
8624 		switch (icmp6->icmp6_code) {
8625 		case ICMP6_DST_UNREACH_NOPORT:
8626 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8627 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8628 			    (seg_seq == tcp->tcp_iss)) {
8629 				(void) tcp_clean_death(tcp,
8630 				    ECONNREFUSED, 8);
8631 			}
8632 			break;
8633 
8634 		case ICMP6_DST_UNREACH_ADMIN:
8635 		case ICMP6_DST_UNREACH_NOROUTE:
8636 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8637 		case ICMP6_DST_UNREACH_ADDR:
8638 			/* Record the error in case we finally time out. */
8639 			tcp->tcp_client_errno = EHOSTUNREACH;
8640 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8641 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8642 			    (seg_seq == tcp->tcp_iss)) {
8643 				if (tcp->tcp_listener != NULL &&
8644 				    tcp->tcp_listener->tcp_syn_defense) {
8645 					/*
8646 					 * Ditch the half-open connection if we
8647 					 * suspect a SYN attack is under way.
8648 					 */
8649 					tcp_ip_ire_mark_advice(tcp);
8650 					(void) tcp_clean_death(tcp,
8651 					    tcp->tcp_client_errno, 9);
8652 				}
8653 			}
8654 
8655 
8656 			break;
8657 		default:
8658 			break;
8659 		}
8660 		break;
8661 
8662 	case ICMP6_PARAM_PROB:
8663 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8664 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8665 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8666 		    (uchar_t *)nexthdrp) {
8667 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8668 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8669 				(void) tcp_clean_death(tcp,
8670 				    ECONNREFUSED, 10);
8671 			}
8672 			break;
8673 		}
8674 		break;
8675 
8676 	case ICMP6_TIME_EXCEEDED:
8677 	default:
8678 		break;
8679 	}
8680 	freemsg(first_mp);
8681 }
8682 
8683 /*
8684  * Notify IP that we are having trouble with this connection.  IP should
8685  * blow the IRE away and start over.
8686  */
8687 static void
8688 tcp_ip_notify(tcp_t *tcp)
8689 {
8690 	struct iocblk	*iocp;
8691 	ipid_t	*ipid;
8692 	mblk_t	*mp;
8693 
8694 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8695 	if (tcp->tcp_ipversion == IPV6_VERSION)
8696 		return;
8697 
8698 	mp = mkiocb(IP_IOCTL);
8699 	if (mp == NULL)
8700 		return;
8701 
8702 	iocp = (struct iocblk *)mp->b_rptr;
8703 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8704 
8705 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8706 	if (!mp->b_cont) {
8707 		freeb(mp);
8708 		return;
8709 	}
8710 
8711 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8712 	mp->b_cont->b_wptr += iocp->ioc_count;
8713 	bzero(ipid, sizeof (*ipid));
8714 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8715 	ipid->ipid_ire_type = IRE_CACHE;
8716 	ipid->ipid_addr_offset = sizeof (ipid_t);
8717 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8718 	/*
8719 	 * Note: in the case of source routing we want to blow away the
8720 	 * route to the first source route hop.
8721 	 */
8722 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8723 	    sizeof (tcp->tcp_ipha->ipha_dst));
8724 
8725 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8726 }
8727 
8728 /* Unlink and return any mblk that looks like it contains an ire */
8729 static mblk_t *
8730 tcp_ire_mp(mblk_t **mpp)
8731 {
8732 	mblk_t 	*mp = *mpp;
8733 	mblk_t	*prev_mp = NULL;
8734 
8735 	for (;;) {
8736 		switch (DB_TYPE(mp)) {
8737 		case IRE_DB_TYPE:
8738 		case IRE_DB_REQ_TYPE:
8739 			if (mp == *mpp) {
8740 				*mpp = mp->b_cont;
8741 			} else {
8742 				prev_mp->b_cont = mp->b_cont;
8743 			}
8744 			mp->b_cont = NULL;
8745 			return (mp);
8746 		default:
8747 			break;
8748 		}
8749 		prev_mp = mp;
8750 		mp = mp->b_cont;
8751 		if (mp == NULL)
8752 			break;
8753 	}
8754 	return (mp);
8755 }
8756 
8757 /*
8758  * Timer callback routine for keepalive probe.  We do a fake resend of
8759  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8760  * check to see if we have heard anything from the other end for the last
8761  * RTO period.  If we have, set the timer to expire for another
8762  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8763  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8764  * the timeout if we have not heard from the other side.  If for more than
8765  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8766  * kill the connection unless the keepalive abort threshold is 0.  In
8767  * that case, we will probe "forever."
8768  */
8769 static void
8770 tcp_keepalive_killer(void *arg)
8771 {
8772 	mblk_t	*mp;
8773 	conn_t	*connp = (conn_t *)arg;
8774 	tcp_t  	*tcp = connp->conn_tcp;
8775 	int32_t	firetime;
8776 	int32_t	idletime;
8777 	int32_t	ka_intrvl;
8778 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8779 
8780 	tcp->tcp_ka_tid = 0;
8781 
8782 	if (tcp->tcp_fused)
8783 		return;
8784 
8785 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
8786 	ka_intrvl = tcp->tcp_ka_interval;
8787 
8788 	/*
8789 	 * Keepalive probe should only be sent if the application has not
8790 	 * done a close on the connection.
8791 	 */
8792 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8793 		return;
8794 	}
8795 	/* Timer fired too early, restart it. */
8796 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8797 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8798 		    MSEC_TO_TICK(ka_intrvl));
8799 		return;
8800 	}
8801 
8802 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8803 	/*
8804 	 * If we have not heard from the other side for a long
8805 	 * time, kill the connection unless the keepalive abort
8806 	 * threshold is 0.  In that case, we will probe "forever."
8807 	 */
8808 	if (tcp->tcp_ka_abort_thres != 0 &&
8809 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8810 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
8811 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8812 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8813 		return;
8814 	}
8815 
8816 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8817 	    idletime >= ka_intrvl) {
8818 		/* Fake resend of last ACKed byte. */
8819 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8820 
8821 		if (mp1 != NULL) {
8822 			*mp1->b_wptr++ = '\0';
8823 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8824 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8825 			freeb(mp1);
8826 			/*
8827 			 * if allocation failed, fall through to start the
8828 			 * timer back.
8829 			 */
8830 			if (mp != NULL) {
8831 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8832 				BUMP_MIB(&tcps->tcps_mib,
8833 				    tcpTimKeepaliveProbe);
8834 				if (tcp->tcp_ka_last_intrvl != 0) {
8835 					int max;
8836 					/*
8837 					 * We should probe again at least
8838 					 * in ka_intrvl, but not more than
8839 					 * tcp_rexmit_interval_max.
8840 					 */
8841 					max = tcps->tcps_rexmit_interval_max;
8842 					firetime = MIN(ka_intrvl - 1,
8843 					    tcp->tcp_ka_last_intrvl << 1);
8844 					if (firetime > max)
8845 						firetime = max;
8846 				} else {
8847 					firetime = tcp->tcp_rto;
8848 				}
8849 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8850 				    tcp_keepalive_killer,
8851 				    MSEC_TO_TICK(firetime));
8852 				tcp->tcp_ka_last_intrvl = firetime;
8853 				return;
8854 			}
8855 		}
8856 	} else {
8857 		tcp->tcp_ka_last_intrvl = 0;
8858 	}
8859 
8860 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8861 	if ((firetime = ka_intrvl - idletime) < 0) {
8862 		firetime = ka_intrvl;
8863 	}
8864 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8865 	    MSEC_TO_TICK(firetime));
8866 }
8867 
8868 int
8869 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8870 {
8871 	queue_t	*q = tcp->tcp_rq;
8872 	int32_t	mss = tcp->tcp_mss;
8873 	int	maxpsz;
8874 	conn_t	*connp = tcp->tcp_connp;
8875 
8876 	if (TCP_IS_DETACHED(tcp))
8877 		return (mss);
8878 	if (tcp->tcp_fused) {
8879 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8880 		mss = INFPSZ;
8881 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
8882 		/*
8883 		 * Set the sd_qn_maxpsz according to the socket send buffer
8884 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8885 		 * instruct the stream head to copyin user data into contiguous
8886 		 * kernel-allocated buffers without breaking it up into smaller
8887 		 * chunks.  We round up the buffer size to the nearest SMSS.
8888 		 */
8889 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8890 		if (tcp->tcp_kssl_ctx == NULL)
8891 			mss = INFPSZ;
8892 		else
8893 			mss = SSL3_MAX_RECORD_LEN;
8894 	} else {
8895 		/*
8896 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8897 		 * (and a multiple of the mss).  This instructs the stream
8898 		 * head to break down larger than SMSS writes into SMSS-
8899 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8900 		 */
8901 		/* XXX tune this with ndd tcp_maxpsz_multiplier */
8902 		maxpsz = tcp->tcp_maxpsz * mss;
8903 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8904 			maxpsz = tcp->tcp_xmit_hiwater/2;
8905 			/* Round up to nearest mss */
8906 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8907 		}
8908 	}
8909 
8910 	(void) proto_set_maxpsz(q, connp, maxpsz);
8911 	if (!(IPCL_IS_NONSTR(connp))) {
8912 		/* XXX do it in set_maxpsz()? */
8913 		tcp->tcp_wq->q_maxpsz = maxpsz;
8914 	}
8915 
8916 	if (set_maxblk)
8917 		(void) proto_set_tx_maxblk(q, connp, mss);
8918 	return (mss);
8919 }
8920 
8921 /*
8922  * Extract option values from a tcp header.  We put any found values into the
8923  * tcpopt struct and return a bitmask saying which options were found.
8924  */
8925 static int
8926 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8927 {
8928 	uchar_t		*endp;
8929 	int		len;
8930 	uint32_t	mss;
8931 	uchar_t		*up = (uchar_t *)tcph;
8932 	int		found = 0;
8933 	int32_t		sack_len;
8934 	tcp_seq		sack_begin, sack_end;
8935 	tcp_t		*tcp;
8936 
8937 	endp = up + TCP_HDR_LENGTH(tcph);
8938 	up += TCP_MIN_HEADER_LENGTH;
8939 	while (up < endp) {
8940 		len = endp - up;
8941 		switch (*up) {
8942 		case TCPOPT_EOL:
8943 			break;
8944 
8945 		case TCPOPT_NOP:
8946 			up++;
8947 			continue;
8948 
8949 		case TCPOPT_MAXSEG:
8950 			if (len < TCPOPT_MAXSEG_LEN ||
8951 			    up[1] != TCPOPT_MAXSEG_LEN)
8952 				break;
8953 
8954 			mss = BE16_TO_U16(up+2);
8955 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
8956 			tcpopt->tcp_opt_mss = mss;
8957 			found |= TCP_OPT_MSS_PRESENT;
8958 
8959 			up += TCPOPT_MAXSEG_LEN;
8960 			continue;
8961 
8962 		case TCPOPT_WSCALE:
8963 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
8964 				break;
8965 
8966 			if (up[2] > TCP_MAX_WINSHIFT)
8967 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
8968 			else
8969 				tcpopt->tcp_opt_wscale = up[2];
8970 			found |= TCP_OPT_WSCALE_PRESENT;
8971 
8972 			up += TCPOPT_WS_LEN;
8973 			continue;
8974 
8975 		case TCPOPT_SACK_PERMITTED:
8976 			if (len < TCPOPT_SACK_OK_LEN ||
8977 			    up[1] != TCPOPT_SACK_OK_LEN)
8978 				break;
8979 			found |= TCP_OPT_SACK_OK_PRESENT;
8980 			up += TCPOPT_SACK_OK_LEN;
8981 			continue;
8982 
8983 		case TCPOPT_SACK:
8984 			if (len <= 2 || up[1] <= 2 || len < up[1])
8985 				break;
8986 
8987 			/* If TCP is not interested in SACK blks... */
8988 			if ((tcp = tcpopt->tcp) == NULL) {
8989 				up += up[1];
8990 				continue;
8991 			}
8992 			sack_len = up[1] - TCPOPT_HEADER_LEN;
8993 			up += TCPOPT_HEADER_LEN;
8994 
8995 			/*
8996 			 * If the list is empty, allocate one and assume
8997 			 * nothing is sack'ed.
8998 			 */
8999 			ASSERT(tcp->tcp_sack_info != NULL);
9000 			if (tcp->tcp_notsack_list == NULL) {
9001 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9002 				    tcp->tcp_suna, tcp->tcp_snxt,
9003 				    &(tcp->tcp_num_notsack_blk),
9004 				    &(tcp->tcp_cnt_notsack_list));
9005 
9006 				/*
9007 				 * Make sure tcp_notsack_list is not NULL.
9008 				 * This happens when kmem_alloc(KM_NOSLEEP)
9009 				 * returns NULL.
9010 				 */
9011 				if (tcp->tcp_notsack_list == NULL) {
9012 					up += sack_len;
9013 					continue;
9014 				}
9015 				tcp->tcp_fack = tcp->tcp_suna;
9016 			}
9017 
9018 			while (sack_len > 0) {
9019 				if (up + 8 > endp) {
9020 					up = endp;
9021 					break;
9022 				}
9023 				sack_begin = BE32_TO_U32(up);
9024 				up += 4;
9025 				sack_end = BE32_TO_U32(up);
9026 				up += 4;
9027 				sack_len -= 8;
9028 				/*
9029 				 * Bounds checking.  Make sure the SACK
9030 				 * info is within tcp_suna and tcp_snxt.
9031 				 * If this SACK blk is out of bound, ignore
9032 				 * it but continue to parse the following
9033 				 * blks.
9034 				 */
9035 				if (SEQ_LEQ(sack_end, sack_begin) ||
9036 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9037 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9038 					continue;
9039 				}
9040 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9041 				    sack_begin, sack_end,
9042 				    &(tcp->tcp_num_notsack_blk),
9043 				    &(tcp->tcp_cnt_notsack_list));
9044 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9045 					tcp->tcp_fack = sack_end;
9046 				}
9047 			}
9048 			found |= TCP_OPT_SACK_PRESENT;
9049 			continue;
9050 
9051 		case TCPOPT_TSTAMP:
9052 			if (len < TCPOPT_TSTAMP_LEN ||
9053 			    up[1] != TCPOPT_TSTAMP_LEN)
9054 				break;
9055 
9056 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9057 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9058 
9059 			found |= TCP_OPT_TSTAMP_PRESENT;
9060 
9061 			up += TCPOPT_TSTAMP_LEN;
9062 			continue;
9063 
9064 		default:
9065 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9066 				break;
9067 			up += up[1];
9068 			continue;
9069 		}
9070 		break;
9071 	}
9072 	return (found);
9073 }
9074 
9075 /*
9076  * Set the mss associated with a particular tcp based on its current value,
9077  * and a new one passed in. Observe minimums and maximums, and reset
9078  * other state variables that we want to view as multiples of mss.
9079  *
9080  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9081  * highwater marks etc. need to be initialized or adjusted.
9082  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9083  *    packet arrives.
9084  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9085  *    ICMP6_PACKET_TOO_BIG arrives.
9086  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9087  *    to increase the MSS to use the extra bytes available.
9088  *
9089  * Callers except tcp_paws_check() ensure that they only reduce mss.
9090  */
9091 static void
9092 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9093 {
9094 	uint32_t	mss_max;
9095 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9096 
9097 	if (tcp->tcp_ipversion == IPV4_VERSION)
9098 		mss_max = tcps->tcps_mss_max_ipv4;
9099 	else
9100 		mss_max = tcps->tcps_mss_max_ipv6;
9101 
9102 	if (mss < tcps->tcps_mss_min)
9103 		mss = tcps->tcps_mss_min;
9104 	if (mss > mss_max)
9105 		mss = mss_max;
9106 	/*
9107 	 * Unless naglim has been set by our client to
9108 	 * a non-mss value, force naglim to track mss.
9109 	 * This can help to aggregate small writes.
9110 	 */
9111 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9112 		tcp->tcp_naglim = mss;
9113 	/*
9114 	 * TCP should be able to buffer at least 4 MSS data for obvious
9115 	 * performance reason.
9116 	 */
9117 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9118 		tcp->tcp_xmit_hiwater = mss << 2;
9119 
9120 	if (do_ss) {
9121 		/*
9122 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9123 		 * changing due to a reduction in MTU, presumably as a
9124 		 * result of a new path component, reset cwnd to its
9125 		 * "initial" value, as a multiple of the new mss.
9126 		 */
9127 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9128 	} else {
9129 		/*
9130 		 * Called by tcp_paws_check(), the mss increased
9131 		 * marginally to allow use of space previously taken
9132 		 * by the timestamp option. It would be inappropriate
9133 		 * to apply slow start or tcp_init_cwnd values to
9134 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9135 		 */
9136 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9137 		tcp->tcp_cwnd_cnt = 0;
9138 	}
9139 	tcp->tcp_mss = mss;
9140 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9141 }
9142 
9143 /* For /dev/tcp aka AF_INET open */
9144 static int
9145 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9146 {
9147 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9148 }
9149 
9150 /* For /dev/tcp6 aka AF_INET6 open */
9151 static int
9152 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9153 {
9154 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9155 }
9156 
9157 static conn_t *
9158 tcp_create_common(queue_t *q, cred_t *credp, boolean_t isv6,
9159     boolean_t issocket, int *errorp)
9160 {
9161 	tcp_t		*tcp = NULL;
9162 	conn_t		*connp;
9163 	int		err;
9164 	zoneid_t	zoneid;
9165 	tcp_stack_t	*tcps;
9166 	squeue_t	*sqp;
9167 
9168 	ASSERT(errorp != NULL);
9169 	/*
9170 	 * Find the proper zoneid and netstack.
9171 	 */
9172 	/*
9173 	 * Special case for install: miniroot needs to be able to
9174 	 * access files via NFS as though it were always in the
9175 	 * global zone.
9176 	 */
9177 	if (credp == kcred && nfs_global_client_only != 0) {
9178 		zoneid = GLOBAL_ZONEID;
9179 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9180 		    netstack_tcp;
9181 		ASSERT(tcps != NULL);
9182 	} else {
9183 		netstack_t *ns;
9184 
9185 		ns = netstack_find_by_cred(credp);
9186 		ASSERT(ns != NULL);
9187 		tcps = ns->netstack_tcp;
9188 		ASSERT(tcps != NULL);
9189 
9190 		/*
9191 		 * For exclusive stacks we set the zoneid to zero
9192 		 * to make TCP operate as if in the global zone.
9193 		 */
9194 		if (tcps->tcps_netstack->netstack_stackid !=
9195 		    GLOBAL_NETSTACKID)
9196 			zoneid = GLOBAL_ZONEID;
9197 		else
9198 			zoneid = crgetzoneid(credp);
9199 	}
9200 	/*
9201 	 * For stackid zero this is done from strplumb.c, but
9202 	 * non-zero stackids are handled here.
9203 	 */
9204 	if (tcps->tcps_g_q == NULL &&
9205 	    tcps->tcps_netstack->netstack_stackid !=
9206 	    GLOBAL_NETSTACKID) {
9207 		tcp_g_q_setup(tcps);
9208 	}
9209 
9210 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
9211 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
9212 	/*
9213 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9214 	 * so we drop it by one.
9215 	 */
9216 	netstack_rele(tcps->tcps_netstack);
9217 	if (connp == NULL) {
9218 		*errorp = ENOSR;
9219 		return (NULL);
9220 	}
9221 	connp->conn_sqp = sqp;
9222 	connp->conn_initial_sqp = connp->conn_sqp;
9223 	tcp = connp->conn_tcp;
9224 
9225 	if (isv6) {
9226 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9227 		connp->conn_send = ip_output_v6;
9228 		connp->conn_af_isv6 = B_TRUE;
9229 		connp->conn_pkt_isv6 = B_TRUE;
9230 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9231 		tcp->tcp_ipversion = IPV6_VERSION;
9232 		tcp->tcp_family = AF_INET6;
9233 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9234 	} else {
9235 		connp->conn_flags |= IPCL_TCP4;
9236 		connp->conn_send = ip_output;
9237 		connp->conn_af_isv6 = B_FALSE;
9238 		connp->conn_pkt_isv6 = B_FALSE;
9239 		tcp->tcp_ipversion = IPV4_VERSION;
9240 		tcp->tcp_family = AF_INET;
9241 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9242 	}
9243 
9244 	/*
9245 	 * TCP keeps a copy of cred for cache locality reasons but
9246 	 * we put a reference only once. If connp->conn_cred
9247 	 * becomes invalid, tcp_cred should also be set to NULL.
9248 	 */
9249 	tcp->tcp_cred = connp->conn_cred = credp;
9250 	crhold(connp->conn_cred);
9251 	tcp->tcp_cpid = curproc->p_pid;
9252 	tcp->tcp_open_time = lbolt64;
9253 	connp->conn_zoneid = zoneid;
9254 	connp->conn_mlp_type = mlptSingle;
9255 	connp->conn_ulp_labeled = !is_system_labeled();
9256 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9257 	ASSERT(tcp->tcp_tcps == tcps);
9258 
9259 	/*
9260 	 * If the caller has the process-wide flag set, then default to MAC
9261 	 * exempt mode.  This allows read-down to unlabeled hosts.
9262 	 */
9263 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9264 		connp->conn_mac_exempt = B_TRUE;
9265 
9266 	connp->conn_dev = NULL;
9267 	if (issocket) {
9268 		connp->conn_flags |= IPCL_SOCKET;
9269 		tcp->tcp_issocket = 1;
9270 	}
9271 
9272 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
9273 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9274 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
9275 
9276 	/* Non-zero default values */
9277 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9278 
9279 	if (q == NULL) {
9280 		/*
9281 		 * Create a helper stream for non-STREAMS socket.
9282 		 */
9283 		err = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
9284 		if (err != 0) {
9285 			ip1dbg(("tcp_create_common: create of IP helper stream "
9286 			    "failed\n"));
9287 			CONN_DEC_REF(connp);
9288 			*errorp = err;
9289 			return (NULL);
9290 		}
9291 		q = connp->conn_rq;
9292 	} else {
9293 		RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9294 	}
9295 
9296 	SOCK_CONNID_INIT(tcp->tcp_connid);
9297 	err = tcp_init(tcp, q);
9298 	if (err != 0) {
9299 		CONN_DEC_REF(connp);
9300 		*errorp = err;
9301 		return (NULL);
9302 	}
9303 
9304 	return (connp);
9305 }
9306 
9307 static int
9308 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9309     boolean_t isv6)
9310 {
9311 	tcp_t		*tcp = NULL;
9312 	conn_t		*connp = NULL;
9313 	int		err;
9314 	vmem_t		*minor_arena = NULL;
9315 	dev_t		conn_dev;
9316 	boolean_t	issocket;
9317 
9318 	if (q->q_ptr != NULL)
9319 		return (0);
9320 
9321 	if (sflag == MODOPEN)
9322 		return (EINVAL);
9323 
9324 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9325 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9326 		minor_arena = ip_minor_arena_la;
9327 	} else {
9328 		/*
9329 		 * Either minor numbers in the large arena were exhausted
9330 		 * or a non socket application is doing the open.
9331 		 * Try to allocate from the small arena.
9332 		 */
9333 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9334 			return (EBUSY);
9335 		}
9336 		minor_arena = ip_minor_arena_sa;
9337 	}
9338 
9339 	ASSERT(minor_arena != NULL);
9340 
9341 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
9342 
9343 	if (flag & SO_FALLBACK) {
9344 		/*
9345 		 * Non streams socket needs a stream to fallback to
9346 		 */
9347 		RD(q)->q_ptr = (void *)conn_dev;
9348 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
9349 		WR(q)->q_ptr = (void *)minor_arena;
9350 		qprocson(q);
9351 		return (0);
9352 	} else if (flag & SO_ACCEPTOR) {
9353 		q->q_qinfo = &tcp_acceptor_rinit;
9354 		/*
9355 		 * the conn_dev and minor_arena will be subsequently used by
9356 		 * tcp_wput_accept() and tcpclose_accept() to figure out the
9357 		 * minor device number for this connection from the q_ptr.
9358 		 */
9359 		RD(q)->q_ptr = (void *)conn_dev;
9360 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9361 		WR(q)->q_ptr = (void *)minor_arena;
9362 		qprocson(q);
9363 		return (0);
9364 	}
9365 
9366 	issocket = flag & SO_SOCKSTR;
9367 	connp = tcp_create_common(q, credp, isv6, issocket, &err);
9368 
9369 	if (connp == NULL) {
9370 		inet_minor_free(minor_arena, conn_dev);
9371 		q->q_ptr = WR(q)->q_ptr = NULL;
9372 		return (err);
9373 	}
9374 
9375 	q->q_ptr = WR(q)->q_ptr = connp;
9376 
9377 	connp->conn_dev = conn_dev;
9378 	connp->conn_minor_arena = minor_arena;
9379 
9380 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9381 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9382 
9383 	if (issocket) {
9384 		WR(q)->q_qinfo = &tcp_sock_winit;
9385 	} else {
9386 		tcp = connp->conn_tcp;
9387 #ifdef  _ILP32
9388 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9389 #else
9390 		tcp->tcp_acceptor_id = conn_dev;
9391 #endif  /* _ILP32 */
9392 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9393 	}
9394 
9395 	/*
9396 	 * Put the ref for TCP. Ref for IP was already put
9397 	 * by ipcl_conn_create. Also Make the conn_t globally
9398 	 * visible to walkers
9399 	 */
9400 	mutex_enter(&connp->conn_lock);
9401 	CONN_INC_REF_LOCKED(connp);
9402 	ASSERT(connp->conn_ref == 2);
9403 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9404 	mutex_exit(&connp->conn_lock);
9405 
9406 	qprocson(q);
9407 	return (0);
9408 }
9409 
9410 /*
9411  * Some TCP options can be "set" by requesting them in the option
9412  * buffer. This is needed for XTI feature test though we do not
9413  * allow it in general. We interpret that this mechanism is more
9414  * applicable to OSI protocols and need not be allowed in general.
9415  * This routine filters out options for which it is not allowed (most)
9416  * and lets through those (few) for which it is. [ The XTI interface
9417  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9418  * ever implemented will have to be allowed here ].
9419  */
9420 static boolean_t
9421 tcp_allow_connopt_set(int level, int name)
9422 {
9423 
9424 	switch (level) {
9425 	case IPPROTO_TCP:
9426 		switch (name) {
9427 		case TCP_NODELAY:
9428 			return (B_TRUE);
9429 		default:
9430 			return (B_FALSE);
9431 		}
9432 		/*NOTREACHED*/
9433 	default:
9434 		return (B_FALSE);
9435 	}
9436 	/*NOTREACHED*/
9437 }
9438 
9439 /*
9440  * this routine gets default values of certain options whose default
9441  * values are maintained by protocol specific code
9442  */
9443 /* ARGSUSED */
9444 int
9445 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9446 {
9447 	int32_t	*i1 = (int32_t *)ptr;
9448 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9449 
9450 	switch (level) {
9451 	case IPPROTO_TCP:
9452 		switch (name) {
9453 		case TCP_NOTIFY_THRESHOLD:
9454 			*i1 = tcps->tcps_ip_notify_interval;
9455 			break;
9456 		case TCP_ABORT_THRESHOLD:
9457 			*i1 = tcps->tcps_ip_abort_interval;
9458 			break;
9459 		case TCP_CONN_NOTIFY_THRESHOLD:
9460 			*i1 = tcps->tcps_ip_notify_cinterval;
9461 			break;
9462 		case TCP_CONN_ABORT_THRESHOLD:
9463 			*i1 = tcps->tcps_ip_abort_cinterval;
9464 			break;
9465 		default:
9466 			return (-1);
9467 		}
9468 		break;
9469 	case IPPROTO_IP:
9470 		switch (name) {
9471 		case IP_TTL:
9472 			*i1 = tcps->tcps_ipv4_ttl;
9473 			break;
9474 		default:
9475 			return (-1);
9476 		}
9477 		break;
9478 	case IPPROTO_IPV6:
9479 		switch (name) {
9480 		case IPV6_UNICAST_HOPS:
9481 			*i1 = tcps->tcps_ipv6_hoplimit;
9482 			break;
9483 		default:
9484 			return (-1);
9485 		}
9486 		break;
9487 	default:
9488 		return (-1);
9489 	}
9490 	return (sizeof (int));
9491 }
9492 
9493 static int
9494 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
9495 {
9496 	int		*i1 = (int *)ptr;
9497 	tcp_t		*tcp = connp->conn_tcp;
9498 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9499 
9500 	switch (level) {
9501 	case SOL_SOCKET:
9502 		switch (name) {
9503 		case SO_LINGER:	{
9504 			struct linger *lgr = (struct linger *)ptr;
9505 
9506 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9507 			lgr->l_linger = tcp->tcp_lingertime;
9508 			}
9509 			return (sizeof (struct linger));
9510 		case SO_DEBUG:
9511 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9512 			break;
9513 		case SO_KEEPALIVE:
9514 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9515 			break;
9516 		case SO_DONTROUTE:
9517 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9518 			break;
9519 		case SO_USELOOPBACK:
9520 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9521 			break;
9522 		case SO_BROADCAST:
9523 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9524 			break;
9525 		case SO_REUSEADDR:
9526 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9527 			break;
9528 		case SO_OOBINLINE:
9529 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9530 			break;
9531 		case SO_DGRAM_ERRIND:
9532 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9533 			break;
9534 		case SO_TYPE:
9535 			*i1 = SOCK_STREAM;
9536 			break;
9537 		case SO_SNDBUF:
9538 			*i1 = tcp->tcp_xmit_hiwater;
9539 			break;
9540 		case SO_RCVBUF:
9541 			*i1 = tcp->tcp_recv_hiwater;
9542 			break;
9543 		case SO_SND_COPYAVOID:
9544 			*i1 = tcp->tcp_snd_zcopy_on ?
9545 			    SO_SND_COPYAVOID : 0;
9546 			break;
9547 		case SO_ALLZONES:
9548 			*i1 = connp->conn_allzones ? 1 : 0;
9549 			break;
9550 		case SO_ANON_MLP:
9551 			*i1 = connp->conn_anon_mlp;
9552 			break;
9553 		case SO_MAC_EXEMPT:
9554 			*i1 = connp->conn_mac_exempt;
9555 			break;
9556 		case SO_EXCLBIND:
9557 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9558 			break;
9559 		case SO_PROTOTYPE:
9560 			*i1 = IPPROTO_TCP;
9561 			break;
9562 		case SO_DOMAIN:
9563 			*i1 = tcp->tcp_family;
9564 			break;
9565 		case SO_ACCEPTCONN:
9566 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
9567 		default:
9568 			return (-1);
9569 		}
9570 		break;
9571 	case IPPROTO_TCP:
9572 		switch (name) {
9573 		case TCP_NODELAY:
9574 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9575 			break;
9576 		case TCP_MAXSEG:
9577 			*i1 = tcp->tcp_mss;
9578 			break;
9579 		case TCP_NOTIFY_THRESHOLD:
9580 			*i1 = (int)tcp->tcp_first_timer_threshold;
9581 			break;
9582 		case TCP_ABORT_THRESHOLD:
9583 			*i1 = tcp->tcp_second_timer_threshold;
9584 			break;
9585 		case TCP_CONN_NOTIFY_THRESHOLD:
9586 			*i1 = tcp->tcp_first_ctimer_threshold;
9587 			break;
9588 		case TCP_CONN_ABORT_THRESHOLD:
9589 			*i1 = tcp->tcp_second_ctimer_threshold;
9590 			break;
9591 		case TCP_RECVDSTADDR:
9592 			*i1 = tcp->tcp_recvdstaddr;
9593 			break;
9594 		case TCP_ANONPRIVBIND:
9595 			*i1 = tcp->tcp_anon_priv_bind;
9596 			break;
9597 		case TCP_EXCLBIND:
9598 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9599 			break;
9600 		case TCP_INIT_CWND:
9601 			*i1 = tcp->tcp_init_cwnd;
9602 			break;
9603 		case TCP_KEEPALIVE_THRESHOLD:
9604 			*i1 = tcp->tcp_ka_interval;
9605 			break;
9606 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9607 			*i1 = tcp->tcp_ka_abort_thres;
9608 			break;
9609 		case TCP_CORK:
9610 			*i1 = tcp->tcp_cork;
9611 			break;
9612 		default:
9613 			return (-1);
9614 		}
9615 		break;
9616 	case IPPROTO_IP:
9617 		if (tcp->tcp_family != AF_INET)
9618 			return (-1);
9619 		switch (name) {
9620 		case IP_OPTIONS:
9621 		case T_IP_OPTIONS: {
9622 			/*
9623 			 * This is compatible with BSD in that in only return
9624 			 * the reverse source route with the final destination
9625 			 * as the last entry. The first 4 bytes of the option
9626 			 * will contain the final destination.
9627 			 */
9628 			int	opt_len;
9629 
9630 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9631 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9632 			ASSERT(opt_len >= 0);
9633 			/* Caller ensures enough space */
9634 			if (opt_len > 0) {
9635 				/*
9636 				 * TODO: Do we have to handle getsockopt on an
9637 				 * initiator as well?
9638 				 */
9639 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9640 			}
9641 			return (0);
9642 			}
9643 		case IP_TOS:
9644 		case T_IP_TOS:
9645 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9646 			break;
9647 		case IP_TTL:
9648 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9649 			break;
9650 		case IP_NEXTHOP:
9651 			/* Handled at IP level */
9652 			return (-EINVAL);
9653 		default:
9654 			return (-1);
9655 		}
9656 		break;
9657 	case IPPROTO_IPV6:
9658 		/*
9659 		 * IPPROTO_IPV6 options are only supported for sockets
9660 		 * that are using IPv6 on the wire.
9661 		 */
9662 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9663 			return (-1);
9664 		}
9665 		switch (name) {
9666 		case IPV6_UNICAST_HOPS:
9667 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9668 			break;	/* goto sizeof (int) option return */
9669 		case IPV6_BOUND_IF:
9670 			/* Zero if not set */
9671 			*i1 = tcp->tcp_bound_if;
9672 			break;	/* goto sizeof (int) option return */
9673 		case IPV6_RECVPKTINFO:
9674 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9675 				*i1 = 1;
9676 			else
9677 				*i1 = 0;
9678 			break;	/* goto sizeof (int) option return */
9679 		case IPV6_RECVTCLASS:
9680 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9681 				*i1 = 1;
9682 			else
9683 				*i1 = 0;
9684 			break;	/* goto sizeof (int) option return */
9685 		case IPV6_RECVHOPLIMIT:
9686 			if (tcp->tcp_ipv6_recvancillary &
9687 			    TCP_IPV6_RECVHOPLIMIT)
9688 				*i1 = 1;
9689 			else
9690 				*i1 = 0;
9691 			break;	/* goto sizeof (int) option return */
9692 		case IPV6_RECVHOPOPTS:
9693 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9694 				*i1 = 1;
9695 			else
9696 				*i1 = 0;
9697 			break;	/* goto sizeof (int) option return */
9698 		case IPV6_RECVDSTOPTS:
9699 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9700 				*i1 = 1;
9701 			else
9702 				*i1 = 0;
9703 			break;	/* goto sizeof (int) option return */
9704 		case _OLD_IPV6_RECVDSTOPTS:
9705 			if (tcp->tcp_ipv6_recvancillary &
9706 			    TCP_OLD_IPV6_RECVDSTOPTS)
9707 				*i1 = 1;
9708 			else
9709 				*i1 = 0;
9710 			break;	/* goto sizeof (int) option return */
9711 		case IPV6_RECVRTHDR:
9712 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9713 				*i1 = 1;
9714 			else
9715 				*i1 = 0;
9716 			break;	/* goto sizeof (int) option return */
9717 		case IPV6_RECVRTHDRDSTOPTS:
9718 			if (tcp->tcp_ipv6_recvancillary &
9719 			    TCP_IPV6_RECVRTDSTOPTS)
9720 				*i1 = 1;
9721 			else
9722 				*i1 = 0;
9723 			break;	/* goto sizeof (int) option return */
9724 		case IPV6_PKTINFO: {
9725 			/* XXX assumes that caller has room for max size! */
9726 			struct in6_pktinfo *pkti;
9727 
9728 			pkti = (struct in6_pktinfo *)ptr;
9729 			if (ipp->ipp_fields & IPPF_IFINDEX)
9730 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9731 			else
9732 				pkti->ipi6_ifindex = 0;
9733 			if (ipp->ipp_fields & IPPF_ADDR)
9734 				pkti->ipi6_addr = ipp->ipp_addr;
9735 			else
9736 				pkti->ipi6_addr = ipv6_all_zeros;
9737 			return (sizeof (struct in6_pktinfo));
9738 		}
9739 		case IPV6_TCLASS:
9740 			if (ipp->ipp_fields & IPPF_TCLASS)
9741 				*i1 = ipp->ipp_tclass;
9742 			else
9743 				*i1 = IPV6_FLOW_TCLASS(
9744 				    IPV6_DEFAULT_VERS_AND_FLOW);
9745 			break;	/* goto sizeof (int) option return */
9746 		case IPV6_NEXTHOP: {
9747 			sin6_t *sin6 = (sin6_t *)ptr;
9748 
9749 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9750 				return (0);
9751 			*sin6 = sin6_null;
9752 			sin6->sin6_family = AF_INET6;
9753 			sin6->sin6_addr = ipp->ipp_nexthop;
9754 			return (sizeof (sin6_t));
9755 		}
9756 		case IPV6_HOPOPTS:
9757 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9758 				return (0);
9759 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9760 				return (0);
9761 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9762 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9763 			if (tcp->tcp_label_len > 0) {
9764 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9765 				ptr[1] = (ipp->ipp_hopoptslen -
9766 				    tcp->tcp_label_len + 7) / 8 - 1;
9767 			}
9768 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9769 		case IPV6_RTHDRDSTOPTS:
9770 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9771 				return (0);
9772 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9773 			return (ipp->ipp_rtdstoptslen);
9774 		case IPV6_RTHDR:
9775 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9776 				return (0);
9777 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9778 			return (ipp->ipp_rthdrlen);
9779 		case IPV6_DSTOPTS:
9780 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9781 				return (0);
9782 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9783 			return (ipp->ipp_dstoptslen);
9784 		case IPV6_SRC_PREFERENCES:
9785 			return (ip6_get_src_preferences(connp,
9786 			    (uint32_t *)ptr));
9787 		case IPV6_PATHMTU: {
9788 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9789 
9790 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9791 				return (-1);
9792 
9793 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9794 			    connp->conn_fport, mtuinfo,
9795 			    connp->conn_netstack));
9796 		}
9797 		default:
9798 			return (-1);
9799 		}
9800 		break;
9801 	default:
9802 		return (-1);
9803 	}
9804 	return (sizeof (int));
9805 }
9806 
9807 /*
9808  * TCP routine to get the values of options.
9809  */
9810 int
9811 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
9812 {
9813 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
9814 }
9815 
9816 /* returns UNIX error, the optlen is a value-result arg */
9817 int
9818 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
9819     void *optvalp, socklen_t *optlen, cred_t *cr)
9820 {
9821 	conn_t		*connp = (conn_t *)proto_handle;
9822 	squeue_t	*sqp = connp->conn_sqp;
9823 	int		error;
9824 	t_uscalar_t	max_optbuf_len;
9825 	void		*optvalp_buf;
9826 	int		len;
9827 
9828 	ASSERT(connp->conn_upper_handle != NULL);
9829 
9830 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
9831 	    tcp_opt_obj.odb_opt_des_arr,
9832 	    tcp_opt_obj.odb_opt_arr_cnt,
9833 	    tcp_opt_obj.odb_topmost_tpiprovider,
9834 	    B_FALSE, B_TRUE, cr);
9835 	if (error != 0) {
9836 		if (error < 0) {
9837 			error = proto_tlitosyserr(-error);
9838 		}
9839 		return (error);
9840 	}
9841 
9842 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
9843 
9844 	error = squeue_synch_enter(sqp, connp, 0);
9845 	if (error == ENOMEM) {
9846 		return (ENOMEM);
9847 	}
9848 
9849 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
9850 	squeue_synch_exit(sqp, connp);
9851 
9852 	if (len < 0) {
9853 		/*
9854 		 * Pass on to IP
9855 		 */
9856 		kmem_free(optvalp_buf, max_optbuf_len);
9857 		return (ip_get_options(connp, level, option_name,
9858 		    optvalp, optlen, cr));
9859 	} else {
9860 		/*
9861 		 * update optlen and copy option value
9862 		 */
9863 		t_uscalar_t size = MIN(len, *optlen);
9864 		bcopy(optvalp_buf, optvalp, size);
9865 		bcopy(&size, optlen, sizeof (size));
9866 
9867 		kmem_free(optvalp_buf, max_optbuf_len);
9868 		return (0);
9869 	}
9870 }
9871 
9872 /*
9873  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9874  * Parameters are assumed to be verified by the caller.
9875  */
9876 /* ARGSUSED */
9877 int
9878 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
9879     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9880     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9881 {
9882 	tcp_t	*tcp = connp->conn_tcp;
9883 	int	*i1 = (int *)invalp;
9884 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9885 	boolean_t checkonly;
9886 	int	reterr;
9887 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9888 
9889 	switch (optset_context) {
9890 	case SETFN_OPTCOM_CHECKONLY:
9891 		checkonly = B_TRUE;
9892 		/*
9893 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9894 		 * inlen != 0 implies value supplied and
9895 		 * 	we have to "pretend" to set it.
9896 		 * inlen == 0 implies that there is no
9897 		 * 	value part in T_CHECK request and just validation
9898 		 * done elsewhere should be enough, we just return here.
9899 		 */
9900 		if (inlen == 0) {
9901 			*outlenp = 0;
9902 			return (0);
9903 		}
9904 		break;
9905 	case SETFN_OPTCOM_NEGOTIATE:
9906 		checkonly = B_FALSE;
9907 		break;
9908 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9909 	case SETFN_CONN_NEGOTIATE:
9910 		checkonly = B_FALSE;
9911 		/*
9912 		 * Negotiating local and "association-related" options
9913 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9914 		 * primitives is allowed by XTI, but we choose
9915 		 * to not implement this style negotiation for Internet
9916 		 * protocols (We interpret it is a must for OSI world but
9917 		 * optional for Internet protocols) for all options.
9918 		 * [ Will do only for the few options that enable test
9919 		 * suites that our XTI implementation of this feature
9920 		 * works for transports that do allow it ]
9921 		 */
9922 		if (!tcp_allow_connopt_set(level, name)) {
9923 			*outlenp = 0;
9924 			return (EINVAL);
9925 		}
9926 		break;
9927 	default:
9928 		/*
9929 		 * We should never get here
9930 		 */
9931 		*outlenp = 0;
9932 		return (EINVAL);
9933 	}
9934 
9935 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9936 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9937 
9938 	/*
9939 	 * For TCP, we should have no ancillary data sent down
9940 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9941 	 * has to be zero.
9942 	 */
9943 	ASSERT(thisdg_attrs == NULL);
9944 
9945 	/*
9946 	 * For fixed length options, no sanity check
9947 	 * of passed in length is done. It is assumed *_optcom_req()
9948 	 * routines do the right thing.
9949 	 */
9950 	switch (level) {
9951 	case SOL_SOCKET:
9952 		switch (name) {
9953 		case SO_LINGER: {
9954 			struct linger *lgr = (struct linger *)invalp;
9955 
9956 			if (!checkonly) {
9957 				if (lgr->l_onoff) {
9958 					tcp->tcp_linger = 1;
9959 					tcp->tcp_lingertime = lgr->l_linger;
9960 				} else {
9961 					tcp->tcp_linger = 0;
9962 					tcp->tcp_lingertime = 0;
9963 				}
9964 				/* struct copy */
9965 				*(struct linger *)outvalp = *lgr;
9966 			} else {
9967 				if (!lgr->l_onoff) {
9968 					((struct linger *)
9969 					    outvalp)->l_onoff = 0;
9970 					((struct linger *)
9971 					    outvalp)->l_linger = 0;
9972 				} else {
9973 					/* struct copy */
9974 					*(struct linger *)outvalp = *lgr;
9975 				}
9976 			}
9977 			*outlenp = sizeof (struct linger);
9978 			return (0);
9979 		}
9980 		case SO_DEBUG:
9981 			if (!checkonly)
9982 				tcp->tcp_debug = onoff;
9983 			break;
9984 		case SO_KEEPALIVE:
9985 			if (checkonly) {
9986 				/* check only case */
9987 				break;
9988 			}
9989 
9990 			if (!onoff) {
9991 				if (tcp->tcp_ka_enabled) {
9992 					if (tcp->tcp_ka_tid != 0) {
9993 						(void) TCP_TIMER_CANCEL(tcp,
9994 						    tcp->tcp_ka_tid);
9995 						tcp->tcp_ka_tid = 0;
9996 					}
9997 					tcp->tcp_ka_enabled = 0;
9998 				}
9999 				break;
10000 			}
10001 			if (!tcp->tcp_ka_enabled) {
10002 				/* Crank up the keepalive timer */
10003 				tcp->tcp_ka_last_intrvl = 0;
10004 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10005 				    tcp_keepalive_killer,
10006 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10007 				tcp->tcp_ka_enabled = 1;
10008 			}
10009 			break;
10010 		case SO_DONTROUTE:
10011 			/*
10012 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10013 			 * only of interest to IP.  We track them here only so
10014 			 * that we can report their current value.
10015 			 */
10016 			if (!checkonly) {
10017 				tcp->tcp_dontroute = onoff;
10018 				tcp->tcp_connp->conn_dontroute = onoff;
10019 			}
10020 			break;
10021 		case SO_USELOOPBACK:
10022 			if (!checkonly) {
10023 				tcp->tcp_useloopback = onoff;
10024 				tcp->tcp_connp->conn_loopback = onoff;
10025 			}
10026 			break;
10027 		case SO_BROADCAST:
10028 			if (!checkonly) {
10029 				tcp->tcp_broadcast = onoff;
10030 				tcp->tcp_connp->conn_broadcast = onoff;
10031 			}
10032 			break;
10033 		case SO_REUSEADDR:
10034 			if (!checkonly) {
10035 				tcp->tcp_reuseaddr = onoff;
10036 				tcp->tcp_connp->conn_reuseaddr = onoff;
10037 			}
10038 			break;
10039 		case SO_OOBINLINE:
10040 			if (!checkonly) {
10041 				tcp->tcp_oobinline = onoff;
10042 				if (IPCL_IS_NONSTR(tcp->tcp_connp))
10043 					proto_set_rx_oob_opt(connp, onoff);
10044 			}
10045 			break;
10046 		case SO_DGRAM_ERRIND:
10047 			if (!checkonly)
10048 				tcp->tcp_dgram_errind = onoff;
10049 			break;
10050 		case SO_SNDBUF: {
10051 			if (*i1 > tcps->tcps_max_buf) {
10052 				*outlenp = 0;
10053 				return (ENOBUFS);
10054 			}
10055 			if (checkonly)
10056 				break;
10057 
10058 			tcp->tcp_xmit_hiwater = *i1;
10059 			if (tcps->tcps_snd_lowat_fraction != 0)
10060 				tcp->tcp_xmit_lowater =
10061 				    tcp->tcp_xmit_hiwater /
10062 				    tcps->tcps_snd_lowat_fraction;
10063 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10064 			/*
10065 			 * If we are flow-controlled, recheck the condition.
10066 			 * There are apps that increase SO_SNDBUF size when
10067 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10068 			 * control condition to be lifted right away.
10069 			 */
10070 			mutex_enter(&tcp->tcp_non_sq_lock);
10071 			if (tcp->tcp_flow_stopped &&
10072 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10073 				tcp_clrqfull(tcp);
10074 			}
10075 			mutex_exit(&tcp->tcp_non_sq_lock);
10076 			break;
10077 		}
10078 		case SO_RCVBUF:
10079 			if (*i1 > tcps->tcps_max_buf) {
10080 				*outlenp = 0;
10081 				return (ENOBUFS);
10082 			}
10083 			/* Silently ignore zero */
10084 			if (!checkonly && *i1 != 0) {
10085 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10086 				(void) tcp_rwnd_set(tcp, *i1);
10087 			}
10088 			/*
10089 			 * XXX should we return the rwnd here
10090 			 * and tcp_opt_get ?
10091 			 */
10092 			break;
10093 		case SO_SND_COPYAVOID:
10094 			if (!checkonly) {
10095 				/* we only allow enable at most once for now */
10096 				if (tcp->tcp_loopback ||
10097 				    (tcp->tcp_kssl_ctx != NULL) ||
10098 				    (!tcp->tcp_snd_zcopy_aware &&
10099 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10100 					*outlenp = 0;
10101 					return (EOPNOTSUPP);
10102 				}
10103 				tcp->tcp_snd_zcopy_aware = 1;
10104 			}
10105 			break;
10106 		case SO_RCVTIMEO:
10107 		case SO_SNDTIMEO:
10108 			/*
10109 			 * Pass these two options in order for third part
10110 			 * protocol usage. Here just return directly.
10111 			 */
10112 			return (0);
10113 		case SO_ALLZONES:
10114 			/* Pass option along to IP level for handling */
10115 			return (-EINVAL);
10116 		case SO_ANON_MLP:
10117 			/* Pass option along to IP level for handling */
10118 			return (-EINVAL);
10119 		case SO_MAC_EXEMPT:
10120 			/* Pass option along to IP level for handling */
10121 			return (-EINVAL);
10122 		case SO_EXCLBIND:
10123 			if (!checkonly)
10124 				tcp->tcp_exclbind = onoff;
10125 			break;
10126 		default:
10127 			*outlenp = 0;
10128 			return (EINVAL);
10129 		}
10130 		break;
10131 	case IPPROTO_TCP:
10132 		switch (name) {
10133 		case TCP_NODELAY:
10134 			if (!checkonly)
10135 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10136 			break;
10137 		case TCP_NOTIFY_THRESHOLD:
10138 			if (!checkonly)
10139 				tcp->tcp_first_timer_threshold = *i1;
10140 			break;
10141 		case TCP_ABORT_THRESHOLD:
10142 			if (!checkonly)
10143 				tcp->tcp_second_timer_threshold = *i1;
10144 			break;
10145 		case TCP_CONN_NOTIFY_THRESHOLD:
10146 			if (!checkonly)
10147 				tcp->tcp_first_ctimer_threshold = *i1;
10148 			break;
10149 		case TCP_CONN_ABORT_THRESHOLD:
10150 			if (!checkonly)
10151 				tcp->tcp_second_ctimer_threshold = *i1;
10152 			break;
10153 		case TCP_RECVDSTADDR:
10154 			if (tcp->tcp_state > TCPS_LISTEN)
10155 				return (EOPNOTSUPP);
10156 			if (!checkonly)
10157 				tcp->tcp_recvdstaddr = onoff;
10158 			break;
10159 		case TCP_ANONPRIVBIND:
10160 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10161 			    IPPROTO_TCP)) != 0) {
10162 				*outlenp = 0;
10163 				return (reterr);
10164 			}
10165 			if (!checkonly) {
10166 				tcp->tcp_anon_priv_bind = onoff;
10167 			}
10168 			break;
10169 		case TCP_EXCLBIND:
10170 			if (!checkonly)
10171 				tcp->tcp_exclbind = onoff;
10172 			break;	/* goto sizeof (int) option return */
10173 		case TCP_INIT_CWND: {
10174 			uint32_t init_cwnd = *((uint32_t *)invalp);
10175 
10176 			if (checkonly)
10177 				break;
10178 
10179 			/*
10180 			 * Only allow socket with network configuration
10181 			 * privilege to set the initial cwnd to be larger
10182 			 * than allowed by RFC 3390.
10183 			 */
10184 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10185 				tcp->tcp_init_cwnd = init_cwnd;
10186 				break;
10187 			}
10188 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10189 				*outlenp = 0;
10190 				return (reterr);
10191 			}
10192 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10193 				*outlenp = 0;
10194 				return (EINVAL);
10195 			}
10196 			tcp->tcp_init_cwnd = init_cwnd;
10197 			break;
10198 		}
10199 		case TCP_KEEPALIVE_THRESHOLD:
10200 			if (checkonly)
10201 				break;
10202 
10203 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10204 			    *i1 > tcps->tcps_keepalive_interval_high) {
10205 				*outlenp = 0;
10206 				return (EINVAL);
10207 			}
10208 			if (*i1 != tcp->tcp_ka_interval) {
10209 				tcp->tcp_ka_interval = *i1;
10210 				/*
10211 				 * Check if we need to restart the
10212 				 * keepalive timer.
10213 				 */
10214 				if (tcp->tcp_ka_tid != 0) {
10215 					ASSERT(tcp->tcp_ka_enabled);
10216 					(void) TCP_TIMER_CANCEL(tcp,
10217 					    tcp->tcp_ka_tid);
10218 					tcp->tcp_ka_last_intrvl = 0;
10219 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10220 					    tcp_keepalive_killer,
10221 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10222 				}
10223 			}
10224 			break;
10225 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10226 			if (!checkonly) {
10227 				if (*i1 <
10228 				    tcps->tcps_keepalive_abort_interval_low ||
10229 				    *i1 >
10230 				    tcps->tcps_keepalive_abort_interval_high) {
10231 					*outlenp = 0;
10232 					return (EINVAL);
10233 				}
10234 				tcp->tcp_ka_abort_thres = *i1;
10235 			}
10236 			break;
10237 		case TCP_CORK:
10238 			if (!checkonly) {
10239 				/*
10240 				 * if tcp->tcp_cork was set and is now
10241 				 * being unset, we have to make sure that
10242 				 * the remaining data gets sent out. Also
10243 				 * unset tcp->tcp_cork so that tcp_wput_data()
10244 				 * can send data even if it is less than mss
10245 				 */
10246 				if (tcp->tcp_cork && onoff == 0 &&
10247 				    tcp->tcp_unsent > 0) {
10248 					tcp->tcp_cork = B_FALSE;
10249 					tcp_wput_data(tcp, NULL, B_FALSE);
10250 				}
10251 				tcp->tcp_cork = onoff;
10252 			}
10253 			break;
10254 		default:
10255 			*outlenp = 0;
10256 			return (EINVAL);
10257 		}
10258 		break;
10259 	case IPPROTO_IP:
10260 		if (tcp->tcp_family != AF_INET) {
10261 			*outlenp = 0;
10262 			return (ENOPROTOOPT);
10263 		}
10264 		switch (name) {
10265 		case IP_OPTIONS:
10266 		case T_IP_OPTIONS:
10267 			reterr = tcp_opt_set_header(tcp, checkonly,
10268 			    invalp, inlen);
10269 			if (reterr) {
10270 				*outlenp = 0;
10271 				return (reterr);
10272 			}
10273 			/* OK return - copy input buffer into output buffer */
10274 			if (invalp != outvalp) {
10275 				/* don't trust bcopy for identical src/dst */
10276 				bcopy(invalp, outvalp, inlen);
10277 			}
10278 			*outlenp = inlen;
10279 			return (0);
10280 		case IP_TOS:
10281 		case T_IP_TOS:
10282 			if (!checkonly) {
10283 				tcp->tcp_ipha->ipha_type_of_service =
10284 				    (uchar_t)*i1;
10285 				tcp->tcp_tos = (uchar_t)*i1;
10286 			}
10287 			break;
10288 		case IP_TTL:
10289 			if (!checkonly) {
10290 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10291 				tcp->tcp_ttl = (uchar_t)*i1;
10292 			}
10293 			break;
10294 		case IP_BOUND_IF:
10295 		case IP_NEXTHOP:
10296 			/* Handled at the IP level */
10297 			return (-EINVAL);
10298 		case IP_SEC_OPT:
10299 			/*
10300 			 * We should not allow policy setting after
10301 			 * we start listening for connections.
10302 			 */
10303 			if (tcp->tcp_state == TCPS_LISTEN) {
10304 				return (EINVAL);
10305 			} else {
10306 				/* Handled at the IP level */
10307 				return (-EINVAL);
10308 			}
10309 		default:
10310 			*outlenp = 0;
10311 			return (EINVAL);
10312 		}
10313 		break;
10314 	case IPPROTO_IPV6: {
10315 		ip6_pkt_t		*ipp;
10316 
10317 		/*
10318 		 * IPPROTO_IPV6 options are only supported for sockets
10319 		 * that are using IPv6 on the wire.
10320 		 */
10321 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10322 			*outlenp = 0;
10323 			return (ENOPROTOOPT);
10324 		}
10325 		/*
10326 		 * Only sticky options; no ancillary data
10327 		 */
10328 		ipp = &tcp->tcp_sticky_ipp;
10329 
10330 		switch (name) {
10331 		case IPV6_UNICAST_HOPS:
10332 			/* -1 means use default */
10333 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10334 				*outlenp = 0;
10335 				return (EINVAL);
10336 			}
10337 			if (!checkonly) {
10338 				if (*i1 == -1) {
10339 					tcp->tcp_ip6h->ip6_hops =
10340 					    ipp->ipp_unicast_hops =
10341 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10342 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10343 					/* Pass modified value to IP. */
10344 					*i1 = tcp->tcp_ip6h->ip6_hops;
10345 				} else {
10346 					tcp->tcp_ip6h->ip6_hops =
10347 					    ipp->ipp_unicast_hops =
10348 					    (uint8_t)*i1;
10349 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10350 				}
10351 				reterr = tcp_build_hdrs(tcp);
10352 				if (reterr != 0)
10353 					return (reterr);
10354 			}
10355 			break;
10356 		case IPV6_BOUND_IF:
10357 			if (!checkonly) {
10358 				tcp->tcp_bound_if = *i1;
10359 				PASS_OPT_TO_IP(connp);
10360 			}
10361 			break;
10362 		/*
10363 		 * Set boolean switches for ancillary data delivery
10364 		 */
10365 		case IPV6_RECVPKTINFO:
10366 			if (!checkonly) {
10367 				if (onoff)
10368 					tcp->tcp_ipv6_recvancillary |=
10369 					    TCP_IPV6_RECVPKTINFO;
10370 				else
10371 					tcp->tcp_ipv6_recvancillary &=
10372 					    ~TCP_IPV6_RECVPKTINFO;
10373 				/* Force it to be sent up with the next msg */
10374 				tcp->tcp_recvifindex = 0;
10375 				PASS_OPT_TO_IP(connp);
10376 			}
10377 			break;
10378 		case IPV6_RECVTCLASS:
10379 			if (!checkonly) {
10380 				if (onoff)
10381 					tcp->tcp_ipv6_recvancillary |=
10382 					    TCP_IPV6_RECVTCLASS;
10383 				else
10384 					tcp->tcp_ipv6_recvancillary &=
10385 					    ~TCP_IPV6_RECVTCLASS;
10386 				PASS_OPT_TO_IP(connp);
10387 			}
10388 			break;
10389 		case IPV6_RECVHOPLIMIT:
10390 			if (!checkonly) {
10391 				if (onoff)
10392 					tcp->tcp_ipv6_recvancillary |=
10393 					    TCP_IPV6_RECVHOPLIMIT;
10394 				else
10395 					tcp->tcp_ipv6_recvancillary &=
10396 					    ~TCP_IPV6_RECVHOPLIMIT;
10397 				/* Force it to be sent up with the next msg */
10398 				tcp->tcp_recvhops = 0xffffffffU;
10399 				PASS_OPT_TO_IP(connp);
10400 			}
10401 			break;
10402 		case IPV6_RECVHOPOPTS:
10403 			if (!checkonly) {
10404 				if (onoff)
10405 					tcp->tcp_ipv6_recvancillary |=
10406 					    TCP_IPV6_RECVHOPOPTS;
10407 				else
10408 					tcp->tcp_ipv6_recvancillary &=
10409 					    ~TCP_IPV6_RECVHOPOPTS;
10410 				PASS_OPT_TO_IP(connp);
10411 			}
10412 			break;
10413 		case IPV6_RECVDSTOPTS:
10414 			if (!checkonly) {
10415 				if (onoff)
10416 					tcp->tcp_ipv6_recvancillary |=
10417 					    TCP_IPV6_RECVDSTOPTS;
10418 				else
10419 					tcp->tcp_ipv6_recvancillary &=
10420 					    ~TCP_IPV6_RECVDSTOPTS;
10421 				PASS_OPT_TO_IP(connp);
10422 			}
10423 			break;
10424 		case _OLD_IPV6_RECVDSTOPTS:
10425 			if (!checkonly) {
10426 				if (onoff)
10427 					tcp->tcp_ipv6_recvancillary |=
10428 					    TCP_OLD_IPV6_RECVDSTOPTS;
10429 				else
10430 					tcp->tcp_ipv6_recvancillary &=
10431 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10432 			}
10433 			break;
10434 		case IPV6_RECVRTHDR:
10435 			if (!checkonly) {
10436 				if (onoff)
10437 					tcp->tcp_ipv6_recvancillary |=
10438 					    TCP_IPV6_RECVRTHDR;
10439 				else
10440 					tcp->tcp_ipv6_recvancillary &=
10441 					    ~TCP_IPV6_RECVRTHDR;
10442 				PASS_OPT_TO_IP(connp);
10443 			}
10444 			break;
10445 		case IPV6_RECVRTHDRDSTOPTS:
10446 			if (!checkonly) {
10447 				if (onoff)
10448 					tcp->tcp_ipv6_recvancillary |=
10449 					    TCP_IPV6_RECVRTDSTOPTS;
10450 				else
10451 					tcp->tcp_ipv6_recvancillary &=
10452 					    ~TCP_IPV6_RECVRTDSTOPTS;
10453 				PASS_OPT_TO_IP(connp);
10454 			}
10455 			break;
10456 		case IPV6_PKTINFO:
10457 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10458 				return (EINVAL);
10459 			if (checkonly)
10460 				break;
10461 
10462 			if (inlen == 0) {
10463 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10464 			} else {
10465 				struct in6_pktinfo *pkti;
10466 
10467 				pkti = (struct in6_pktinfo *)invalp;
10468 				/*
10469 				 * RFC 3542 states that ipi6_addr must be
10470 				 * the unspecified address when setting the
10471 				 * IPV6_PKTINFO sticky socket option on a
10472 				 * TCP socket.
10473 				 */
10474 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10475 					return (EINVAL);
10476 				/*
10477 				 * IP will validate the source address and
10478 				 * interface index.
10479 				 */
10480 				if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
10481 					reterr = ip_set_options(tcp->tcp_connp,
10482 					    level, name, invalp, inlen, cr);
10483 				} else {
10484 					reterr = ip6_set_pktinfo(cr,
10485 					    tcp->tcp_connp, pkti);
10486 				}
10487 				if (reterr != 0)
10488 					return (reterr);
10489 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10490 				ipp->ipp_addr = pkti->ipi6_addr;
10491 				if (ipp->ipp_ifindex != 0)
10492 					ipp->ipp_fields |= IPPF_IFINDEX;
10493 				else
10494 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10495 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10496 					ipp->ipp_fields |= IPPF_ADDR;
10497 				else
10498 					ipp->ipp_fields &= ~IPPF_ADDR;
10499 			}
10500 			reterr = tcp_build_hdrs(tcp);
10501 			if (reterr != 0)
10502 				return (reterr);
10503 			break;
10504 		case IPV6_TCLASS:
10505 			if (inlen != 0 && inlen != sizeof (int))
10506 				return (EINVAL);
10507 			if (checkonly)
10508 				break;
10509 
10510 			if (inlen == 0) {
10511 				ipp->ipp_fields &= ~IPPF_TCLASS;
10512 			} else {
10513 				if (*i1 > 255 || *i1 < -1)
10514 					return (EINVAL);
10515 				if (*i1 == -1) {
10516 					ipp->ipp_tclass = 0;
10517 					*i1 = 0;
10518 				} else {
10519 					ipp->ipp_tclass = *i1;
10520 				}
10521 				ipp->ipp_fields |= IPPF_TCLASS;
10522 			}
10523 			reterr = tcp_build_hdrs(tcp);
10524 			if (reterr != 0)
10525 				return (reterr);
10526 			break;
10527 		case IPV6_NEXTHOP:
10528 			/*
10529 			 * IP will verify that the nexthop is reachable
10530 			 * and fail for sticky options.
10531 			 */
10532 			if (inlen != 0 && inlen != sizeof (sin6_t))
10533 				return (EINVAL);
10534 			if (checkonly)
10535 				break;
10536 
10537 			if (inlen == 0) {
10538 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10539 			} else {
10540 				sin6_t *sin6 = (sin6_t *)invalp;
10541 
10542 				if (sin6->sin6_family != AF_INET6)
10543 					return (EAFNOSUPPORT);
10544 				if (IN6_IS_ADDR_V4MAPPED(
10545 				    &sin6->sin6_addr))
10546 					return (EADDRNOTAVAIL);
10547 				ipp->ipp_nexthop = sin6->sin6_addr;
10548 				if (!IN6_IS_ADDR_UNSPECIFIED(
10549 				    &ipp->ipp_nexthop))
10550 					ipp->ipp_fields |= IPPF_NEXTHOP;
10551 				else
10552 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10553 			}
10554 			reterr = tcp_build_hdrs(tcp);
10555 			if (reterr != 0)
10556 				return (reterr);
10557 			PASS_OPT_TO_IP(connp);
10558 			break;
10559 		case IPV6_HOPOPTS: {
10560 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10561 
10562 			/*
10563 			 * Sanity checks - minimum size, size a multiple of
10564 			 * eight bytes, and matching size passed in.
10565 			 */
10566 			if (inlen != 0 &&
10567 			    inlen != (8 * (hopts->ip6h_len + 1)))
10568 				return (EINVAL);
10569 
10570 			if (checkonly)
10571 				break;
10572 
10573 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10574 			    (uchar_t **)&ipp->ipp_hopopts,
10575 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10576 			if (reterr != 0)
10577 				return (reterr);
10578 			if (ipp->ipp_hopoptslen == 0)
10579 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10580 			else
10581 				ipp->ipp_fields |= IPPF_HOPOPTS;
10582 			reterr = tcp_build_hdrs(tcp);
10583 			if (reterr != 0)
10584 				return (reterr);
10585 			break;
10586 		}
10587 		case IPV6_RTHDRDSTOPTS: {
10588 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10589 
10590 			/*
10591 			 * Sanity checks - minimum size, size a multiple of
10592 			 * eight bytes, and matching size passed in.
10593 			 */
10594 			if (inlen != 0 &&
10595 			    inlen != (8 * (dopts->ip6d_len + 1)))
10596 				return (EINVAL);
10597 
10598 			if (checkonly)
10599 				break;
10600 
10601 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10602 			    (uchar_t **)&ipp->ipp_rtdstopts,
10603 			    &ipp->ipp_rtdstoptslen, 0);
10604 			if (reterr != 0)
10605 				return (reterr);
10606 			if (ipp->ipp_rtdstoptslen == 0)
10607 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10608 			else
10609 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10610 			reterr = tcp_build_hdrs(tcp);
10611 			if (reterr != 0)
10612 				return (reterr);
10613 			break;
10614 		}
10615 		case IPV6_DSTOPTS: {
10616 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10617 
10618 			/*
10619 			 * Sanity checks - minimum size, size a multiple of
10620 			 * eight bytes, and matching size passed in.
10621 			 */
10622 			if (inlen != 0 &&
10623 			    inlen != (8 * (dopts->ip6d_len + 1)))
10624 				return (EINVAL);
10625 
10626 			if (checkonly)
10627 				break;
10628 
10629 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10630 			    (uchar_t **)&ipp->ipp_dstopts,
10631 			    &ipp->ipp_dstoptslen, 0);
10632 			if (reterr != 0)
10633 				return (reterr);
10634 			if (ipp->ipp_dstoptslen == 0)
10635 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10636 			else
10637 				ipp->ipp_fields |= IPPF_DSTOPTS;
10638 			reterr = tcp_build_hdrs(tcp);
10639 			if (reterr != 0)
10640 				return (reterr);
10641 			break;
10642 		}
10643 		case IPV6_RTHDR: {
10644 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10645 
10646 			/*
10647 			 * Sanity checks - minimum size, size a multiple of
10648 			 * eight bytes, and matching size passed in.
10649 			 */
10650 			if (inlen != 0 &&
10651 			    inlen != (8 * (rt->ip6r_len + 1)))
10652 				return (EINVAL);
10653 
10654 			if (checkonly)
10655 				break;
10656 
10657 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10658 			    (uchar_t **)&ipp->ipp_rthdr,
10659 			    &ipp->ipp_rthdrlen, 0);
10660 			if (reterr != 0)
10661 				return (reterr);
10662 			if (ipp->ipp_rthdrlen == 0)
10663 				ipp->ipp_fields &= ~IPPF_RTHDR;
10664 			else
10665 				ipp->ipp_fields |= IPPF_RTHDR;
10666 			reterr = tcp_build_hdrs(tcp);
10667 			if (reterr != 0)
10668 				return (reterr);
10669 			break;
10670 		}
10671 		case IPV6_V6ONLY:
10672 			if (!checkonly) {
10673 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10674 			}
10675 			break;
10676 		case IPV6_USE_MIN_MTU:
10677 			if (inlen != sizeof (int))
10678 				return (EINVAL);
10679 
10680 			if (*i1 < -1 || *i1 > 1)
10681 				return (EINVAL);
10682 
10683 			if (checkonly)
10684 				break;
10685 
10686 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10687 			ipp->ipp_use_min_mtu = *i1;
10688 			break;
10689 		case IPV6_SEC_OPT:
10690 			/*
10691 			 * We should not allow policy setting after
10692 			 * we start listening for connections.
10693 			 */
10694 			if (tcp->tcp_state == TCPS_LISTEN) {
10695 				return (EINVAL);
10696 			} else {
10697 				/* Handled at the IP level */
10698 				return (-EINVAL);
10699 			}
10700 		case IPV6_SRC_PREFERENCES:
10701 			if (inlen != sizeof (uint32_t))
10702 				return (EINVAL);
10703 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10704 			    *(uint32_t *)invalp);
10705 			if (reterr != 0) {
10706 				*outlenp = 0;
10707 				return (reterr);
10708 			}
10709 			break;
10710 		default:
10711 			*outlenp = 0;
10712 			return (EINVAL);
10713 		}
10714 		break;
10715 	}		/* end IPPROTO_IPV6 */
10716 	default:
10717 		*outlenp = 0;
10718 		return (EINVAL);
10719 	}
10720 	/*
10721 	 * Common case of OK return with outval same as inval
10722 	 */
10723 	if (invalp != outvalp) {
10724 		/* don't trust bcopy for identical src/dst */
10725 		(void) bcopy(invalp, outvalp, inlen);
10726 	}
10727 	*outlenp = inlen;
10728 	return (0);
10729 }
10730 
10731 /* ARGSUSED */
10732 int
10733 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10734     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10735     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10736 {
10737 	conn_t	*connp =  Q_TO_CONN(q);
10738 
10739 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
10740 	    outlenp, outvalp, thisdg_attrs, cr, mblk));
10741 }
10742 
10743 int
10744 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
10745     const void *optvalp, socklen_t optlen, cred_t *cr)
10746 {
10747 	conn_t		*connp = (conn_t *)proto_handle;
10748 	squeue_t	*sqp = connp->conn_sqp;
10749 	int		error;
10750 
10751 	ASSERT(connp->conn_upper_handle != NULL);
10752 	/*
10753 	 * Entering the squeue synchronously can result in a context switch,
10754 	 * which can cause a rather sever performance degradation. So we try to
10755 	 * handle whatever options we can without entering the squeue.
10756 	 */
10757 	if (level == IPPROTO_TCP) {
10758 		switch (option_name) {
10759 		case TCP_NODELAY:
10760 			if (optlen != sizeof (int32_t))
10761 				return (EINVAL);
10762 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
10763 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
10764 			    connp->conn_tcp->tcp_mss;
10765 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
10766 			return (0);
10767 		default:
10768 			break;
10769 		}
10770 	}
10771 
10772 	error = squeue_synch_enter(sqp, connp, 0);
10773 	if (error == ENOMEM) {
10774 		return (ENOMEM);
10775 	}
10776 
10777 	error = proto_opt_check(level, option_name, optlen, NULL,
10778 	    tcp_opt_obj.odb_opt_des_arr,
10779 	    tcp_opt_obj.odb_opt_arr_cnt,
10780 	    tcp_opt_obj.odb_topmost_tpiprovider,
10781 	    B_TRUE, B_FALSE, cr);
10782 
10783 	if (error != 0) {
10784 		if (error < 0) {
10785 			error = proto_tlitosyserr(-error);
10786 		}
10787 		squeue_synch_exit(sqp, connp);
10788 		return (error);
10789 	}
10790 
10791 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
10792 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
10793 	    NULL, cr, NULL);
10794 	squeue_synch_exit(sqp, connp);
10795 
10796 	if (error < 0) {
10797 		/*
10798 		 * Pass on to ip
10799 		 */
10800 		error = ip_set_options(connp, level, option_name, optvalp,
10801 		    optlen, cr);
10802 	}
10803 	return (error);
10804 }
10805 
10806 /*
10807  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10808  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10809  * headers, and the maximum size tcp header (to avoid reallocation
10810  * on the fly for additional tcp options).
10811  * Returns failure if can't allocate memory.
10812  */
10813 static int
10814 tcp_build_hdrs(tcp_t *tcp)
10815 {
10816 	char	*hdrs;
10817 	uint_t	hdrs_len;
10818 	ip6i_t	*ip6i;
10819 	char	buf[TCP_MAX_HDR_LENGTH];
10820 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10821 	in6_addr_t src, dst;
10822 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10823 	conn_t *connp = tcp->tcp_connp;
10824 
10825 	/*
10826 	 * save the existing tcp header and source/dest IP addresses
10827 	 */
10828 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10829 	src = tcp->tcp_ip6h->ip6_src;
10830 	dst = tcp->tcp_ip6h->ip6_dst;
10831 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10832 	ASSERT(hdrs_len != 0);
10833 	if (hdrs_len > tcp->tcp_iphc_len) {
10834 		/* Need to reallocate */
10835 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10836 		if (hdrs == NULL)
10837 			return (ENOMEM);
10838 		if (tcp->tcp_iphc != NULL) {
10839 			if (tcp->tcp_hdr_grown) {
10840 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10841 			} else {
10842 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10843 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10844 			}
10845 			tcp->tcp_iphc_len = 0;
10846 		}
10847 		ASSERT(tcp->tcp_iphc_len == 0);
10848 		tcp->tcp_iphc = hdrs;
10849 		tcp->tcp_iphc_len = hdrs_len;
10850 		tcp->tcp_hdr_grown = B_TRUE;
10851 	}
10852 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10853 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10854 
10855 	/* Set header fields not in ipp */
10856 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10857 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10858 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10859 	} else {
10860 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10861 	}
10862 	/*
10863 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10864 	 *
10865 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10866 	 */
10867 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10868 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10869 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10870 
10871 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10872 
10873 	tcp->tcp_ip6h->ip6_src = src;
10874 	tcp->tcp_ip6h->ip6_dst = dst;
10875 
10876 	/*
10877 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10878 	 * the default value for TCP.
10879 	 */
10880 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10881 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
10882 
10883 	/*
10884 	 * If we're setting extension headers after a connection
10885 	 * has been established, and if we have a routing header
10886 	 * among the extension headers, call ip_massage_options_v6 to
10887 	 * manipulate the routing header/ip6_dst set the checksum
10888 	 * difference in the tcp header template.
10889 	 * (This happens in tcp_connect_ipv6 if the routing header
10890 	 * is set prior to the connect.)
10891 	 * Set the tcp_sum to zero first in case we've cleared a
10892 	 * routing header or don't have one at all.
10893 	 */
10894 	tcp->tcp_sum = 0;
10895 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10896 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10897 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10898 		    (uint8_t *)tcp->tcp_tcph);
10899 		if (rth != NULL) {
10900 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10901 			    rth, tcps->tcps_netstack);
10902 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10903 			    (tcp->tcp_sum >> 16));
10904 		}
10905 	}
10906 
10907 	/* Try to get everything in a single mblk */
10908 	(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
10909 	    hdrs_len + tcps->tcps_wroff_xtra);
10910 	return (0);
10911 }
10912 
10913 /*
10914  * Transfer any source route option from ipha to buf/dst in reversed form.
10915  */
10916 static int
10917 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10918 {
10919 	ipoptp_t	opts;
10920 	uchar_t		*opt;
10921 	uint8_t		optval;
10922 	uint8_t		optlen;
10923 	uint32_t	len = 0;
10924 
10925 	for (optval = ipoptp_first(&opts, ipha);
10926 	    optval != IPOPT_EOL;
10927 	    optval = ipoptp_next(&opts)) {
10928 		opt = opts.ipoptp_cur;
10929 		optlen = opts.ipoptp_len;
10930 		switch (optval) {
10931 			int	off1, off2;
10932 		case IPOPT_SSRR:
10933 		case IPOPT_LSRR:
10934 
10935 			/* Reverse source route */
10936 			/*
10937 			 * First entry should be the next to last one in the
10938 			 * current source route (the last entry is our
10939 			 * address.)
10940 			 * The last entry should be the final destination.
10941 			 */
10942 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10943 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10944 			off1 = IPOPT_MINOFF_SR - 1;
10945 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10946 			if (off2 < 0) {
10947 				/* No entries in source route */
10948 				break;
10949 			}
10950 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10951 			/*
10952 			 * Note: use src since ipha has not had its src
10953 			 * and dst reversed (it is in the state it was
10954 			 * received.
10955 			 */
10956 			bcopy(&ipha->ipha_src, buf + off2,
10957 			    IP_ADDR_LEN);
10958 			off2 -= IP_ADDR_LEN;
10959 
10960 			while (off2 > 0) {
10961 				bcopy(opt + off2, buf + off1,
10962 				    IP_ADDR_LEN);
10963 				off1 += IP_ADDR_LEN;
10964 				off2 -= IP_ADDR_LEN;
10965 			}
10966 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
10967 			buf += optlen;
10968 			len += optlen;
10969 			break;
10970 		}
10971 	}
10972 done:
10973 	/* Pad the resulting options */
10974 	while (len & 0x3) {
10975 		*buf++ = IPOPT_EOL;
10976 		len++;
10977 	}
10978 	return (len);
10979 }
10980 
10981 
10982 /*
10983  * Extract and revert a source route from ipha (if any)
10984  * and then update the relevant fields in both tcp_t and the standard header.
10985  */
10986 static void
10987 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
10988 {
10989 	char	buf[TCP_MAX_HDR_LENGTH];
10990 	uint_t	tcph_len;
10991 	int	len;
10992 
10993 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
10994 	len = IPH_HDR_LENGTH(ipha);
10995 	if (len == IP_SIMPLE_HDR_LENGTH)
10996 		/* Nothing to do */
10997 		return;
10998 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
10999 	    (len & 0x3))
11000 		return;
11001 
11002 	tcph_len = tcp->tcp_tcp_hdr_len;
11003 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11004 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11005 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11006 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11007 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11008 	len += IP_SIMPLE_HDR_LENGTH;
11009 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11010 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11011 	if ((int)tcp->tcp_sum < 0)
11012 		tcp->tcp_sum--;
11013 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11014 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11015 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11016 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11017 	tcp->tcp_ip_hdr_len = len;
11018 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11019 	    (IP_VERSION << 4) | (len >> 2);
11020 	len += tcph_len;
11021 	tcp->tcp_hdr_len = len;
11022 }
11023 
11024 /*
11025  * Copy the standard header into its new location,
11026  * lay in the new options and then update the relevant
11027  * fields in both tcp_t and the standard header.
11028  */
11029 static int
11030 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11031 {
11032 	uint_t	tcph_len;
11033 	uint8_t	*ip_optp;
11034 	tcph_t	*new_tcph;
11035 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11036 	conn_t	*connp = tcp->tcp_connp;
11037 
11038 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11039 		return (EINVAL);
11040 
11041 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11042 		return (EINVAL);
11043 
11044 	if (checkonly) {
11045 		/*
11046 		 * do not really set, just pretend to - T_CHECK
11047 		 */
11048 		return (0);
11049 	}
11050 
11051 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11052 	if (tcp->tcp_label_len > 0) {
11053 		int padlen;
11054 		uint8_t opt;
11055 
11056 		/* convert list termination to no-ops */
11057 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11058 		ip_optp += ip_optp[IPOPT_OLEN];
11059 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11060 		while (--padlen >= 0)
11061 			*ip_optp++ = opt;
11062 	}
11063 	tcph_len = tcp->tcp_tcp_hdr_len;
11064 	new_tcph = (tcph_t *)(ip_optp + len);
11065 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11066 	tcp->tcp_tcph = new_tcph;
11067 	bcopy(ptr, ip_optp, len);
11068 
11069 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11070 
11071 	tcp->tcp_ip_hdr_len = len;
11072 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11073 	    (IP_VERSION << 4) | (len >> 2);
11074 	tcp->tcp_hdr_len = len + tcph_len;
11075 	if (!TCP_IS_DETACHED(tcp)) {
11076 		/* Always allocate room for all options. */
11077 		(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
11078 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11079 	}
11080 	return (0);
11081 }
11082 
11083 /* Get callback routine passed to nd_load by tcp_param_register */
11084 /* ARGSUSED */
11085 static int
11086 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11087 {
11088 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11089 
11090 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11091 	return (0);
11092 }
11093 
11094 /*
11095  * Walk through the param array specified registering each element with the
11096  * named dispatch handler.
11097  */
11098 static boolean_t
11099 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11100 {
11101 	for (; cnt-- > 0; tcppa++) {
11102 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11103 			if (!nd_load(ndp, tcppa->tcp_param_name,
11104 			    tcp_param_get, tcp_param_set,
11105 			    (caddr_t)tcppa)) {
11106 				nd_free(ndp);
11107 				return (B_FALSE);
11108 			}
11109 		}
11110 	}
11111 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11112 	    KM_SLEEP);
11113 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11114 	    sizeof (tcpparam_t));
11115 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11116 	    tcp_param_get, tcp_param_set_aligned,
11117 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11118 		nd_free(ndp);
11119 		return (B_FALSE);
11120 	}
11121 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11122 	    KM_SLEEP);
11123 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11124 	    sizeof (tcpparam_t));
11125 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11126 	    tcp_param_get, tcp_param_set_aligned,
11127 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11128 		nd_free(ndp);
11129 		return (B_FALSE);
11130 	}
11131 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11132 	    KM_SLEEP);
11133 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11134 	    sizeof (tcpparam_t));
11135 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11136 	    tcp_param_get, tcp_param_set_aligned,
11137 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11138 		nd_free(ndp);
11139 		return (B_FALSE);
11140 	}
11141 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11142 	    KM_SLEEP);
11143 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11144 	    sizeof (tcpparam_t));
11145 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11146 	    tcp_param_get, tcp_param_set_aligned,
11147 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11148 		nd_free(ndp);
11149 		return (B_FALSE);
11150 	}
11151 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11152 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11153 		nd_free(ndp);
11154 		return (B_FALSE);
11155 	}
11156 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11157 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11158 		nd_free(ndp);
11159 		return (B_FALSE);
11160 	}
11161 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11162 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11163 		nd_free(ndp);
11164 		return (B_FALSE);
11165 	}
11166 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11167 	    tcp_1948_phrase_set, NULL)) {
11168 		nd_free(ndp);
11169 		return (B_FALSE);
11170 	}
11171 	/*
11172 	 * Dummy ndd variables - only to convey obsolescence information
11173 	 * through printing of their name (no get or set routines)
11174 	 * XXX Remove in future releases ?
11175 	 */
11176 	if (!nd_load(ndp,
11177 	    "tcp_close_wait_interval(obsoleted - "
11178 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11179 		nd_free(ndp);
11180 		return (B_FALSE);
11181 	}
11182 	return (B_TRUE);
11183 }
11184 
11185 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11186 /* ARGSUSED */
11187 static int
11188 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11189     cred_t *cr)
11190 {
11191 	long new_value;
11192 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11193 
11194 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11195 	    new_value < tcppa->tcp_param_min ||
11196 	    new_value > tcppa->tcp_param_max) {
11197 		return (EINVAL);
11198 	}
11199 	/*
11200 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11201 	 * round it up.  For future 64 bit requirement, we actually make it
11202 	 * a multiple of 8.
11203 	 */
11204 	if (new_value & 0x7) {
11205 		new_value = (new_value & ~0x7) + 0x8;
11206 	}
11207 	tcppa->tcp_param_val = new_value;
11208 	return (0);
11209 }
11210 
11211 /* Set callback routine passed to nd_load by tcp_param_register */
11212 /* ARGSUSED */
11213 static int
11214 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11215 {
11216 	long	new_value;
11217 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11218 
11219 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11220 	    new_value < tcppa->tcp_param_min ||
11221 	    new_value > tcppa->tcp_param_max) {
11222 		return (EINVAL);
11223 	}
11224 	tcppa->tcp_param_val = new_value;
11225 	return (0);
11226 }
11227 
11228 /*
11229  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11230  * is filled, return as much as we can.  The message passed in may be
11231  * multi-part, chained using b_cont.  "start" is the starting sequence
11232  * number for this piece.
11233  */
11234 static mblk_t *
11235 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11236 {
11237 	uint32_t	end;
11238 	mblk_t		*mp1;
11239 	mblk_t		*mp2;
11240 	mblk_t		*next_mp;
11241 	uint32_t	u1;
11242 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11243 
11244 	/* Walk through all the new pieces. */
11245 	do {
11246 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11247 		    (uintptr_t)INT_MAX);
11248 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11249 		next_mp = mp->b_cont;
11250 		if (start == end) {
11251 			/* Empty.  Blast it. */
11252 			freeb(mp);
11253 			continue;
11254 		}
11255 		mp->b_cont = NULL;
11256 		TCP_REASS_SET_SEQ(mp, start);
11257 		TCP_REASS_SET_END(mp, end);
11258 		mp1 = tcp->tcp_reass_tail;
11259 		if (!mp1) {
11260 			tcp->tcp_reass_tail = mp;
11261 			tcp->tcp_reass_head = mp;
11262 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11263 			UPDATE_MIB(&tcps->tcps_mib,
11264 			    tcpInDataUnorderBytes, end - start);
11265 			continue;
11266 		}
11267 		/* New stuff completely beyond tail? */
11268 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11269 			/* Link it on end. */
11270 			mp1->b_cont = mp;
11271 			tcp->tcp_reass_tail = mp;
11272 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11273 			UPDATE_MIB(&tcps->tcps_mib,
11274 			    tcpInDataUnorderBytes, end - start);
11275 			continue;
11276 		}
11277 		mp1 = tcp->tcp_reass_head;
11278 		u1 = TCP_REASS_SEQ(mp1);
11279 		/* New stuff at the front? */
11280 		if (SEQ_LT(start, u1)) {
11281 			/* Yes... Check for overlap. */
11282 			mp->b_cont = mp1;
11283 			tcp->tcp_reass_head = mp;
11284 			tcp_reass_elim_overlap(tcp, mp);
11285 			continue;
11286 		}
11287 		/*
11288 		 * The new piece fits somewhere between the head and tail.
11289 		 * We find our slot, where mp1 precedes us and mp2 trails.
11290 		 */
11291 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11292 			u1 = TCP_REASS_SEQ(mp2);
11293 			if (SEQ_LEQ(start, u1))
11294 				break;
11295 		}
11296 		/* Link ourselves in */
11297 		mp->b_cont = mp2;
11298 		mp1->b_cont = mp;
11299 
11300 		/* Trim overlap with following mblk(s) first */
11301 		tcp_reass_elim_overlap(tcp, mp);
11302 
11303 		/* Trim overlap with preceding mblk */
11304 		tcp_reass_elim_overlap(tcp, mp1);
11305 
11306 	} while (start = end, mp = next_mp);
11307 	mp1 = tcp->tcp_reass_head;
11308 	/* Anything ready to go? */
11309 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11310 		return (NULL);
11311 	/* Eat what we can off the queue */
11312 	for (;;) {
11313 		mp = mp1->b_cont;
11314 		end = TCP_REASS_END(mp1);
11315 		TCP_REASS_SET_SEQ(mp1, 0);
11316 		TCP_REASS_SET_END(mp1, 0);
11317 		if (!mp) {
11318 			tcp->tcp_reass_tail = NULL;
11319 			break;
11320 		}
11321 		if (end != TCP_REASS_SEQ(mp)) {
11322 			mp1->b_cont = NULL;
11323 			break;
11324 		}
11325 		mp1 = mp;
11326 	}
11327 	mp1 = tcp->tcp_reass_head;
11328 	tcp->tcp_reass_head = mp;
11329 	return (mp1);
11330 }
11331 
11332 /* Eliminate any overlap that mp may have over later mblks */
11333 static void
11334 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11335 {
11336 	uint32_t	end;
11337 	mblk_t		*mp1;
11338 	uint32_t	u1;
11339 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11340 
11341 	end = TCP_REASS_END(mp);
11342 	while ((mp1 = mp->b_cont) != NULL) {
11343 		u1 = TCP_REASS_SEQ(mp1);
11344 		if (!SEQ_GT(end, u1))
11345 			break;
11346 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11347 			mp->b_wptr -= end - u1;
11348 			TCP_REASS_SET_END(mp, u1);
11349 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11350 			UPDATE_MIB(&tcps->tcps_mib,
11351 			    tcpInDataPartDupBytes, end - u1);
11352 			break;
11353 		}
11354 		mp->b_cont = mp1->b_cont;
11355 		TCP_REASS_SET_SEQ(mp1, 0);
11356 		TCP_REASS_SET_END(mp1, 0);
11357 		freeb(mp1);
11358 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11359 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11360 	}
11361 	if (!mp1)
11362 		tcp->tcp_reass_tail = mp;
11363 }
11364 
11365 static uint_t
11366 tcp_rwnd_reopen(tcp_t *tcp)
11367 {
11368 	uint_t ret = 0;
11369 	uint_t thwin;
11370 
11371 	/* Learn the latest rwnd information that we sent to the other side. */
11372 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11373 	    << tcp->tcp_rcv_ws;
11374 	/* This is peer's calculated send window (our receive window). */
11375 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11376 	/*
11377 	 * Increase the receive window to max.  But we need to do receiver
11378 	 * SWS avoidance.  This means that we need to check the increase of
11379 	 * of receive window is at least 1 MSS.
11380 	 */
11381 	if (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss) {
11382 		/*
11383 		 * If the window that the other side knows is less than max
11384 		 * deferred acks segments, send an update immediately.
11385 		 */
11386 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11387 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
11388 			ret = TH_ACK_NEEDED;
11389 		}
11390 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
11391 	}
11392 	return (ret);
11393 }
11394 
11395 /*
11396  * Send up all messages queued on tcp_rcv_list.
11397  */
11398 static uint_t
11399 tcp_rcv_drain(tcp_t *tcp)
11400 {
11401 	mblk_t *mp;
11402 	uint_t ret = 0;
11403 #ifdef DEBUG
11404 	uint_t cnt = 0;
11405 #endif
11406 	queue_t	*q = tcp->tcp_rq;
11407 
11408 	/* Can't drain on an eager connection */
11409 	if (tcp->tcp_listener != NULL)
11410 		return (ret);
11411 
11412 	/* Can't be a non-STREAMS connection or sodirect enabled */
11413 	ASSERT((!IPCL_IS_NONSTR(tcp->tcp_connp)) && SOD_NOT_ENABLED(tcp));
11414 
11415 	/* No need for the push timer now. */
11416 	if (tcp->tcp_push_tid != 0) {
11417 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11418 		tcp->tcp_push_tid = 0;
11419 	}
11420 
11421 	/*
11422 	 * Handle two cases here: we are currently fused or we were
11423 	 * previously fused and have some urgent data to be delivered
11424 	 * upstream.  The latter happens because we either ran out of
11425 	 * memory or were detached and therefore sending the SIGURG was
11426 	 * deferred until this point.  In either case we pass control
11427 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11428 	 * some work.
11429 	 */
11430 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11431 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
11432 		    tcp->tcp_fused_sigurg_mp != NULL);
11433 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11434 		    &tcp->tcp_fused_sigurg_mp))
11435 			return (ret);
11436 	}
11437 
11438 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11439 		tcp->tcp_rcv_list = mp->b_next;
11440 		mp->b_next = NULL;
11441 #ifdef DEBUG
11442 		cnt += msgdsize(mp);
11443 #endif
11444 		/* Does this need SSL processing first? */
11445 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11446 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11447 			    mblk_t *, mp);
11448 			tcp_kssl_input(tcp, mp);
11449 			continue;
11450 		}
11451 		putnext(q, mp);
11452 	}
11453 #ifdef DEBUG
11454 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11455 #endif
11456 	tcp->tcp_rcv_last_head = NULL;
11457 	tcp->tcp_rcv_last_tail = NULL;
11458 	tcp->tcp_rcv_cnt = 0;
11459 
11460 	if (canputnext(q))
11461 		return (tcp_rwnd_reopen(tcp));
11462 
11463 	return (ret);
11464 }
11465 
11466 /*
11467  * Queue data on tcp_rcv_list which is a b_next chain.
11468  * tcp_rcv_last_head/tail is the last element of this chain.
11469  * Each element of the chain is a b_cont chain.
11470  *
11471  * M_DATA messages are added to the current element.
11472  * Other messages are added as new (b_next) elements.
11473  */
11474 void
11475 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11476 {
11477 	ASSERT(seg_len == msgdsize(mp));
11478 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11479 
11480 	if (tcp->tcp_rcv_list == NULL) {
11481 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11482 		tcp->tcp_rcv_list = mp;
11483 		tcp->tcp_rcv_last_head = mp;
11484 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11485 		tcp->tcp_rcv_last_tail->b_cont = mp;
11486 	} else {
11487 		tcp->tcp_rcv_last_head->b_next = mp;
11488 		tcp->tcp_rcv_last_head = mp;
11489 	}
11490 
11491 	while (mp->b_cont)
11492 		mp = mp->b_cont;
11493 
11494 	tcp->tcp_rcv_last_tail = mp;
11495 	tcp->tcp_rcv_cnt += seg_len;
11496 	tcp->tcp_rwnd -= seg_len;
11497 }
11498 
11499 /*
11500  * The tcp_rcv_sod_XXX() functions enqueue data directly to the socket
11501  * above, in addition when uioa is enabled schedule an asynchronous uio
11502  * prior to enqueuing. They implement the combinhed semantics of the
11503  * tcp_rcv_XXX() functions, tcp_rcv_list push logic, and STREAMS putnext()
11504  * canputnext(), i.e. flow-control with backenable.
11505  *
11506  * tcp_sod_wakeup() is called where tcp_rcv_drain() would be called in the
11507  * non sodirect connection but as there are no tcp_tcv_list mblk_t's we deal
11508  * with the rcv_wnd and push timer and call the sodirect wakeup function.
11509  *
11510  * Must be called with sodp->sod_lockp held and will return with the lock
11511  * released.
11512  */
11513 static uint_t
11514 tcp_rcv_sod_wakeup(tcp_t *tcp, sodirect_t *sodp)
11515 {
11516 	queue_t		*q = tcp->tcp_rq;
11517 	uint_t		thwin;
11518 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11519 	uint_t		ret = 0;
11520 
11521 	/* Can't be an eager connection */
11522 	ASSERT(tcp->tcp_listener == NULL);
11523 
11524 	/* Caller must have lock held */
11525 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11526 
11527 	/* Sodirect mode so must not be a tcp_rcv_list */
11528 	ASSERT(tcp->tcp_rcv_list == NULL);
11529 
11530 	if (SOD_QFULL(sodp)) {
11531 		/* Q is full, mark Q for need backenable */
11532 		SOD_QSETBE(sodp);
11533 	}
11534 	/* Last advertised rwnd, i.e. rwnd last sent in a packet */
11535 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11536 	    << tcp->tcp_rcv_ws;
11537 	/* This is peer's calculated send window (our available rwnd). */
11538 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11539 	/*
11540 	 * Increase the receive window to max.  But we need to do receiver
11541 	 * SWS avoidance.  This means that we need to check the increase of
11542 	 * of receive window is at least 1 MSS.
11543 	 */
11544 	if (!SOD_QFULL(sodp) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11545 		/*
11546 		 * If the window that the other side knows is less than max
11547 		 * deferred acks segments, send an update immediately.
11548 		 */
11549 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11550 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11551 			ret = TH_ACK_NEEDED;
11552 		}
11553 		tcp->tcp_rwnd = q->q_hiwat;
11554 	}
11555 
11556 	if (!SOD_QEMPTY(sodp)) {
11557 		/* Wakeup to socket */
11558 		sodp->sod_state &= SOD_WAKE_CLR;
11559 		sodp->sod_state |= SOD_WAKE_DONE;
11560 		(sodp->sod_wakeup)(sodp);
11561 		/* wakeup() does the mutex_ext() */
11562 	} else {
11563 		/* Q is empty, no need to wake */
11564 		sodp->sod_state &= SOD_WAKE_CLR;
11565 		sodp->sod_state |= SOD_WAKE_NOT;
11566 		mutex_exit(sodp->sod_lockp);
11567 	}
11568 
11569 	/* No need for the push timer now. */
11570 	if (tcp->tcp_push_tid != 0) {
11571 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11572 		tcp->tcp_push_tid = 0;
11573 	}
11574 
11575 	return (ret);
11576 }
11577 
11578 /*
11579  * Called where tcp_rcv_enqueue()/putnext(RD(q)) would be. For M_DATA
11580  * mblk_t's if uioa enabled then start a uioa asynchronous copy directly
11581  * to the user-land buffer and flag the mblk_t as such.
11582  *
11583  * Also, handle tcp_rwnd.
11584  */
11585 uint_t
11586 tcp_rcv_sod_enqueue(tcp_t *tcp, sodirect_t *sodp, mblk_t *mp, uint_t seg_len)
11587 {
11588 	uioa_t		*uioap = &sodp->sod_uioa;
11589 	boolean_t	qfull;
11590 	uint_t		thwin;
11591 
11592 	/* Can't be an eager connection */
11593 	ASSERT(tcp->tcp_listener == NULL);
11594 
11595 	/* Caller must have lock held */
11596 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11597 
11598 	/* Sodirect mode so must not be a tcp_rcv_list */
11599 	ASSERT(tcp->tcp_rcv_list == NULL);
11600 
11601 	/* Passed in segment length must be equal to mblk_t chain data size */
11602 	ASSERT(seg_len == msgdsize(mp));
11603 
11604 	if (DB_TYPE(mp) != M_DATA) {
11605 		/* Only process M_DATA mblk_t's */
11606 		goto enq;
11607 	}
11608 	if (uioap->uioa_state & UIOA_ENABLED) {
11609 		/* Uioa is enabled */
11610 		mblk_t		*mp1 = mp;
11611 		mblk_t		*lmp = NULL;
11612 
11613 		if (seg_len > uioap->uio_resid) {
11614 			/*
11615 			 * There isn't enough uio space for the mblk_t chain
11616 			 * so disable uioa such that this and any additional
11617 			 * mblk_t data is handled by the socket and schedule
11618 			 * the socket for wakeup to finish this uioa.
11619 			 */
11620 			uioap->uioa_state &= UIOA_CLR;
11621 			uioap->uioa_state |= UIOA_FINI;
11622 			if (sodp->sod_state & SOD_WAKE_NOT) {
11623 				sodp->sod_state &= SOD_WAKE_CLR;
11624 				sodp->sod_state |= SOD_WAKE_NEED;
11625 			}
11626 			goto enq;
11627 		}
11628 		do {
11629 			uint32_t	len = MBLKL(mp1);
11630 
11631 			if (!uioamove(mp1->b_rptr, len, UIO_READ, uioap)) {
11632 				/* Scheduled, mark dblk_t as such */
11633 				DB_FLAGS(mp1) |= DBLK_UIOA;
11634 			} else {
11635 				/* Error, turn off async processing */
11636 				uioap->uioa_state &= UIOA_CLR;
11637 				uioap->uioa_state |= UIOA_FINI;
11638 				break;
11639 			}
11640 			lmp = mp1;
11641 		} while ((mp1 = mp1->b_cont) != NULL);
11642 
11643 		if (mp1 != NULL || uioap->uio_resid == 0) {
11644 			/*
11645 			 * Not all mblk_t(s) uioamoved (error) or all uio
11646 			 * space has been consumed so schedule the socket
11647 			 * for wakeup to finish this uio.
11648 			 */
11649 			sodp->sod_state &= SOD_WAKE_CLR;
11650 			sodp->sod_state |= SOD_WAKE_NEED;
11651 
11652 			/* Break the mblk chain if neccessary. */
11653 			if (mp1 != NULL && lmp != NULL) {
11654 				mp->b_next = mp1;
11655 				lmp->b_cont = NULL;
11656 			}
11657 		}
11658 	} else if (uioap->uioa_state & UIOA_FINI) {
11659 		/*
11660 		 * Post UIO_ENABLED waiting for socket to finish processing
11661 		 * so just enqueue and update tcp_rwnd.
11662 		 */
11663 		if (SOD_QFULL(sodp))
11664 			tcp->tcp_rwnd -= seg_len;
11665 	} else if (sodp->sod_want > 0) {
11666 		/*
11667 		 * Uioa isn't enabled but sodirect has a pending read().
11668 		 */
11669 		if (SOD_QCNT(sodp) + seg_len >= sodp->sod_want) {
11670 			if (sodp->sod_state & SOD_WAKE_NOT) {
11671 				/* Schedule socket for wakeup */
11672 				sodp->sod_state &= SOD_WAKE_CLR;
11673 				sodp->sod_state |= SOD_WAKE_NEED;
11674 			}
11675 			tcp->tcp_rwnd -= seg_len;
11676 		}
11677 	} else if (SOD_QCNT(sodp) + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
11678 		/*
11679 		 * No pending sodirect read() so used the default
11680 		 * TCP push logic to guess that a push is needed.
11681 		 */
11682 		if (sodp->sod_state & SOD_WAKE_NOT) {
11683 			/* Schedule socket for wakeup */
11684 			sodp->sod_state &= SOD_WAKE_CLR;
11685 			sodp->sod_state |= SOD_WAKE_NEED;
11686 		}
11687 		tcp->tcp_rwnd -= seg_len;
11688 	} else {
11689 		/* Just update tcp_rwnd */
11690 		tcp->tcp_rwnd -= seg_len;
11691 	}
11692 enq:
11693 	qfull = SOD_QFULL(sodp);
11694 
11695 	(sodp->sod_enqueue)(sodp, mp);
11696 
11697 	if (! qfull && SOD_QFULL(sodp)) {
11698 		/* Wasn't QFULL, now QFULL, need back-enable */
11699 		SOD_QSETBE(sodp);
11700 	}
11701 
11702 	/*
11703 	 * Check to see if remote avail swnd < mss due to delayed ACK,
11704 	 * first get advertised rwnd.
11705 	 */
11706 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win));
11707 	/* Minus delayed ACK count */
11708 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11709 	if (thwin < tcp->tcp_mss) {
11710 		/* Remote avail swnd < mss, need ACK now */
11711 		return (TH_ACK_NEEDED);
11712 	}
11713 
11714 	return (0);
11715 }
11716 
11717 /*
11718  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11719  *
11720  * This is the default entry function into TCP on the read side. TCP is
11721  * always entered via squeue i.e. using squeue's for mutual exclusion.
11722  * When classifier does a lookup to find the tcp, it also puts a reference
11723  * on the conn structure associated so the tcp is guaranteed to exist
11724  * when we come here. We still need to check the state because it might
11725  * as well has been closed. The squeue processing function i.e. squeue_enter,
11726  * is responsible for doing the CONN_DEC_REF.
11727  *
11728  * Apart from the default entry point, IP also sends packets directly to
11729  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11730  * connections.
11731  */
11732 boolean_t tcp_outbound_squeue_switch = B_FALSE;
11733 void
11734 tcp_input(void *arg, mblk_t *mp, void *arg2)
11735 {
11736 	conn_t	*connp = (conn_t *)arg;
11737 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11738 
11739 	/* arg2 is the sqp */
11740 	ASSERT(arg2 != NULL);
11741 	ASSERT(mp != NULL);
11742 
11743 	/*
11744 	 * Don't accept any input on a closed tcp as this TCP logically does
11745 	 * not exist on the system. Don't proceed further with this TCP.
11746 	 * For eg. this packet could trigger another close of this tcp
11747 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11748 	 * tcp_clean_death / tcp_closei_local must be called at most once
11749 	 * on a TCP. In this case we need to refeed the packet into the
11750 	 * classifier and figure out where the packet should go. Need to
11751 	 * preserve the recv_ill somehow. Until we figure that out, for
11752 	 * now just drop the packet if we can't classify the packet.
11753 	 */
11754 	if (tcp->tcp_state == TCPS_CLOSED ||
11755 	    tcp->tcp_state == TCPS_BOUND) {
11756 		conn_t	*new_connp;
11757 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11758 
11759 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11760 		if (new_connp != NULL) {
11761 			tcp_reinput(new_connp, mp, arg2);
11762 			return;
11763 		}
11764 		/* We failed to classify. For now just drop the packet */
11765 		freemsg(mp);
11766 		return;
11767 	}
11768 
11769 	if (DB_TYPE(mp) != M_DATA) {
11770 		tcp_rput_common(tcp, mp);
11771 		return;
11772 	}
11773 
11774 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
11775 		squeue_t	*final_sqp;
11776 
11777 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
11778 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
11779 		DB_CKSUMSTART(mp) = 0;
11780 		if (tcp->tcp_state == TCPS_SYN_SENT &&
11781 		    connp->conn_final_sqp == NULL &&
11782 		    tcp_outbound_squeue_switch) {
11783 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
11784 			connp->conn_final_sqp = final_sqp;
11785 			if (connp->conn_final_sqp != connp->conn_sqp) {
11786 				CONN_INC_REF(connp);
11787 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
11788 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
11789 				    tcp_rput_data, connp, ip_squeue_flag,
11790 				    SQTAG_CONNECT_FINISH);
11791 				return;
11792 			}
11793 		}
11794 	}
11795 	tcp_rput_data(connp, mp, arg2);
11796 }
11797 
11798 /*
11799  * The read side put procedure.
11800  * The packets passed up by ip are assume to be aligned according to
11801  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11802  */
11803 static void
11804 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11805 {
11806 	/*
11807 	 * tcp_rput_data() does not expect M_CTL except for the case
11808 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11809 	 * type. Need to make sure that any other M_CTLs don't make
11810 	 * it to tcp_rput_data since it is not expecting any and doesn't
11811 	 * check for it.
11812 	 */
11813 	if (DB_TYPE(mp) == M_CTL) {
11814 		switch (*(uint32_t *)(mp->b_rptr)) {
11815 		case TCP_IOC_ABORT_CONN:
11816 			/*
11817 			 * Handle connection abort request.
11818 			 */
11819 			tcp_ioctl_abort_handler(tcp, mp);
11820 			return;
11821 		case IPSEC_IN:
11822 			/*
11823 			 * Only secure icmp arrive in TCP and they
11824 			 * don't go through data path.
11825 			 */
11826 			tcp_icmp_error(tcp, mp);
11827 			return;
11828 		case IN_PKTINFO:
11829 			/*
11830 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11831 			 * sockets that are receiving IPv4 traffic. tcp
11832 			 */
11833 			ASSERT(tcp->tcp_family == AF_INET6);
11834 			ASSERT(tcp->tcp_ipv6_recvancillary &
11835 			    TCP_IPV6_RECVPKTINFO);
11836 			tcp_rput_data(tcp->tcp_connp, mp,
11837 			    tcp->tcp_connp->conn_sqp);
11838 			return;
11839 		case MDT_IOC_INFO_UPDATE:
11840 			/*
11841 			 * Handle Multidata information update; the
11842 			 * following routine will free the message.
11843 			 */
11844 			if (tcp->tcp_connp->conn_mdt_ok) {
11845 				tcp_mdt_update(tcp,
11846 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11847 				    B_FALSE);
11848 			}
11849 			freemsg(mp);
11850 			return;
11851 		case LSO_IOC_INFO_UPDATE:
11852 			/*
11853 			 * Handle LSO information update; the following
11854 			 * routine will free the message.
11855 			 */
11856 			if (tcp->tcp_connp->conn_lso_ok) {
11857 				tcp_lso_update(tcp,
11858 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11859 			}
11860 			freemsg(mp);
11861 			return;
11862 		default:
11863 			/*
11864 			 * tcp_icmp_err() will process the M_CTL packets.
11865 			 * Non-ICMP packets, if any, will be discarded in
11866 			 * tcp_icmp_err(). We will process the ICMP packet
11867 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11868 			 * incoming ICMP packet may result in changing
11869 			 * the tcp_mss, which we would need if we have
11870 			 * packets to retransmit.
11871 			 */
11872 			tcp_icmp_error(tcp, mp);
11873 			return;
11874 		}
11875 	}
11876 
11877 	/* No point processing the message if tcp is already closed */
11878 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11879 		freemsg(mp);
11880 		return;
11881 	}
11882 
11883 	tcp_rput_other(tcp, mp);
11884 }
11885 
11886 
11887 /* The minimum of smoothed mean deviation in RTO calculation. */
11888 #define	TCP_SD_MIN	400
11889 
11890 /*
11891  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11892  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11893  * are the same as those in Appendix A.2 of that paper.
11894  *
11895  * m = new measurement
11896  * sa = smoothed RTT average (8 * average estimates).
11897  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11898  */
11899 static void
11900 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11901 {
11902 	long m = TICK_TO_MSEC(rtt);
11903 	clock_t sa = tcp->tcp_rtt_sa;
11904 	clock_t sv = tcp->tcp_rtt_sd;
11905 	clock_t rto;
11906 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11907 
11908 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11909 	tcp->tcp_rtt_update++;
11910 
11911 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11912 	if (sa != 0) {
11913 		/*
11914 		 * Update average estimator:
11915 		 *	new rtt = 7/8 old rtt + 1/8 Error
11916 		 */
11917 
11918 		/* m is now Error in estimate. */
11919 		m -= sa >> 3;
11920 		if ((sa += m) <= 0) {
11921 			/*
11922 			 * Don't allow the smoothed average to be negative.
11923 			 * We use 0 to denote reinitialization of the
11924 			 * variables.
11925 			 */
11926 			sa = 1;
11927 		}
11928 
11929 		/*
11930 		 * Update deviation estimator:
11931 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11932 		 */
11933 		if (m < 0)
11934 			m = -m;
11935 		m -= sv >> 2;
11936 		sv += m;
11937 	} else {
11938 		/*
11939 		 * This follows BSD's implementation.  So the reinitialized
11940 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11941 		 * link is bandwidth dominated, doubling the window size
11942 		 * during slow start means doubling the RTT.  We want to be
11943 		 * more conservative when we reinitialize our estimates.  3
11944 		 * is just a convenient number.
11945 		 */
11946 		sa = m << 3;
11947 		sv = m << 1;
11948 	}
11949 	if (sv < TCP_SD_MIN) {
11950 		/*
11951 		 * We do not know that if sa captures the delay ACK
11952 		 * effect as in a long train of segments, a receiver
11953 		 * does not delay its ACKs.  So set the minimum of sv
11954 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11955 		 * of BSD DATO.  That means the minimum of mean
11956 		 * deviation is 100 ms.
11957 		 *
11958 		 */
11959 		sv = TCP_SD_MIN;
11960 	}
11961 	tcp->tcp_rtt_sa = sa;
11962 	tcp->tcp_rtt_sd = sv;
11963 	/*
11964 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11965 	 *
11966 	 * Add tcp_rexmit_interval extra in case of extreme environment
11967 	 * where the algorithm fails to work.  The default value of
11968 	 * tcp_rexmit_interval_extra should be 0.
11969 	 *
11970 	 * As we use a finer grained clock than BSD and update
11971 	 * RTO for every ACKs, add in another .25 of RTT to the
11972 	 * deviation of RTO to accomodate burstiness of 1/4 of
11973 	 * window size.
11974 	 */
11975 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
11976 
11977 	if (rto > tcps->tcps_rexmit_interval_max) {
11978 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
11979 	} else if (rto < tcps->tcps_rexmit_interval_min) {
11980 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
11981 	} else {
11982 		tcp->tcp_rto = rto;
11983 	}
11984 
11985 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11986 	tcp->tcp_timer_backoff = 0;
11987 }
11988 
11989 /*
11990  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11991  * send queue which starts at the given seq. no.
11992  *
11993  * Parameters:
11994  *	tcp_t *tcp: the tcp instance pointer.
11995  *	uint32_t seq: the starting seq. no of the requested segment.
11996  *	int32_t *off: after the execution, *off will be the offset to
11997  *		the returned mblk which points to the requested seq no.
11998  *		It is the caller's responsibility to send in a non-null off.
11999  *
12000  * Return:
12001  *	A mblk_t pointer pointing to the requested segment in send queue.
12002  */
12003 static mblk_t *
12004 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12005 {
12006 	int32_t	cnt;
12007 	mblk_t	*mp;
12008 
12009 	/* Defensive coding.  Make sure we don't send incorrect data. */
12010 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12011 		return (NULL);
12012 
12013 	cnt = seq - tcp->tcp_suna;
12014 	mp = tcp->tcp_xmit_head;
12015 	while (cnt > 0 && mp != NULL) {
12016 		cnt -= mp->b_wptr - mp->b_rptr;
12017 		if (cnt < 0) {
12018 			cnt += mp->b_wptr - mp->b_rptr;
12019 			break;
12020 		}
12021 		mp = mp->b_cont;
12022 	}
12023 	ASSERT(mp != NULL);
12024 	*off = cnt;
12025 	return (mp);
12026 }
12027 
12028 /*
12029  * This function handles all retransmissions if SACK is enabled for this
12030  * connection.  First it calculates how many segments can be retransmitted
12031  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12032  * segments.  A segment is eligible if sack_cnt for that segment is greater
12033  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12034  * all eligible segments, it checks to see if TCP can send some new segments
12035  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12036  *
12037  * Parameters:
12038  *	tcp_t *tcp: the tcp structure of the connection.
12039  *	uint_t *flags: in return, appropriate value will be set for
12040  *	tcp_rput_data().
12041  */
12042 static void
12043 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12044 {
12045 	notsack_blk_t	*notsack_blk;
12046 	int32_t		usable_swnd;
12047 	int32_t		mss;
12048 	uint32_t	seg_len;
12049 	mblk_t		*xmit_mp;
12050 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12051 
12052 	ASSERT(tcp->tcp_sack_info != NULL);
12053 	ASSERT(tcp->tcp_notsack_list != NULL);
12054 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12055 
12056 	/* Defensive coding in case there is a bug... */
12057 	if (tcp->tcp_notsack_list == NULL) {
12058 		return;
12059 	}
12060 	notsack_blk = tcp->tcp_notsack_list;
12061 	mss = tcp->tcp_mss;
12062 
12063 	/*
12064 	 * Limit the num of outstanding data in the network to be
12065 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12066 	 */
12067 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12068 
12069 	/* At least retransmit 1 MSS of data. */
12070 	if (usable_swnd <= 0) {
12071 		usable_swnd = mss;
12072 	}
12073 
12074 	/* Make sure no new RTT samples will be taken. */
12075 	tcp->tcp_csuna = tcp->tcp_snxt;
12076 
12077 	notsack_blk = tcp->tcp_notsack_list;
12078 	while (usable_swnd > 0) {
12079 		mblk_t		*snxt_mp, *tmp_mp;
12080 		tcp_seq		begin = tcp->tcp_sack_snxt;
12081 		tcp_seq		end;
12082 		int32_t		off;
12083 
12084 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12085 			if (SEQ_GT(notsack_blk->end, begin) &&
12086 			    (notsack_blk->sack_cnt >=
12087 			    tcps->tcps_dupack_fast_retransmit)) {
12088 				end = notsack_blk->end;
12089 				if (SEQ_LT(begin, notsack_blk->begin)) {
12090 					begin = notsack_blk->begin;
12091 				}
12092 				break;
12093 			}
12094 		}
12095 		/*
12096 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12097 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12098 		 * set to tcp_cwnd_ssthresh.
12099 		 */
12100 		if (notsack_blk == NULL) {
12101 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12102 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12103 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12104 				ASSERT(tcp->tcp_cwnd > 0);
12105 				return;
12106 			} else {
12107 				usable_swnd = usable_swnd / mss;
12108 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12109 				    MAX(usable_swnd * mss, mss);
12110 				*flags |= TH_XMIT_NEEDED;
12111 				return;
12112 			}
12113 		}
12114 
12115 		/*
12116 		 * Note that we may send more than usable_swnd allows here
12117 		 * because of round off, but no more than 1 MSS of data.
12118 		 */
12119 		seg_len = end - begin;
12120 		if (seg_len > mss)
12121 			seg_len = mss;
12122 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12123 		ASSERT(snxt_mp != NULL);
12124 		/* This should not happen.  Defensive coding again... */
12125 		if (snxt_mp == NULL) {
12126 			return;
12127 		}
12128 
12129 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12130 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12131 		if (xmit_mp == NULL)
12132 			return;
12133 
12134 		usable_swnd -= seg_len;
12135 		tcp->tcp_pipe += seg_len;
12136 		tcp->tcp_sack_snxt = begin + seg_len;
12137 
12138 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12139 
12140 		/*
12141 		 * Update the send timestamp to avoid false retransmission.
12142 		 */
12143 		snxt_mp->b_prev = (mblk_t *)lbolt;
12144 
12145 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12146 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12147 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12148 		/*
12149 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12150 		 * This happens when new data sent during fast recovery is
12151 		 * also lost.  If TCP retransmits those new data, it needs
12152 		 * to extend SACK recover phase to avoid starting another
12153 		 * fast retransmit/recovery unnecessarily.
12154 		 */
12155 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12156 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12157 		}
12158 	}
12159 }
12160 
12161 /*
12162  * This function handles policy checking at TCP level for non-hard_bound/
12163  * detached connections.
12164  */
12165 static boolean_t
12166 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12167     boolean_t secure, boolean_t mctl_present)
12168 {
12169 	ipsec_latch_t *ipl = NULL;
12170 	ipsec_action_t *act = NULL;
12171 	mblk_t *data_mp;
12172 	ipsec_in_t *ii;
12173 	const char *reason;
12174 	kstat_named_t *counter;
12175 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12176 	ipsec_stack_t	*ipss;
12177 	ip_stack_t	*ipst;
12178 
12179 	ASSERT(mctl_present || !secure);
12180 
12181 	ASSERT((ipha == NULL && ip6h != NULL) ||
12182 	    (ip6h == NULL && ipha != NULL));
12183 
12184 	/*
12185 	 * We don't necessarily have an ipsec_in_act action to verify
12186 	 * policy because of assymetrical policy where we have only
12187 	 * outbound policy and no inbound policy (possible with global
12188 	 * policy).
12189 	 */
12190 	if (!secure) {
12191 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12192 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12193 			return (B_TRUE);
12194 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12195 		    "tcp_check_policy", ipha, ip6h, secure,
12196 		    tcps->tcps_netstack);
12197 		ipss = tcps->tcps_netstack->netstack_ipsec;
12198 
12199 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12200 		    DROPPER(ipss, ipds_tcp_clear),
12201 		    &tcps->tcps_dropper);
12202 		return (B_FALSE);
12203 	}
12204 
12205 	/*
12206 	 * We have a secure packet.
12207 	 */
12208 	if (act == NULL) {
12209 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12210 		    "tcp_check_policy", ipha, ip6h, secure,
12211 		    tcps->tcps_netstack);
12212 		ipss = tcps->tcps_netstack->netstack_ipsec;
12213 
12214 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12215 		    DROPPER(ipss, ipds_tcp_secure),
12216 		    &tcps->tcps_dropper);
12217 		return (B_FALSE);
12218 	}
12219 
12220 	/*
12221 	 * XXX This whole routine is currently incorrect.  ipl should
12222 	 * be set to the latch pointer, but is currently not set, so
12223 	 * we initialize it to NULL to avoid picking up random garbage.
12224 	 */
12225 	if (ipl == NULL)
12226 		return (B_TRUE);
12227 
12228 	data_mp = first_mp->b_cont;
12229 
12230 	ii = (ipsec_in_t *)first_mp->b_rptr;
12231 
12232 	ipst = tcps->tcps_netstack->netstack_ip;
12233 
12234 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12235 	    &counter, tcp->tcp_connp)) {
12236 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12237 		return (B_TRUE);
12238 	}
12239 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12240 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12241 	    reason);
12242 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12243 
12244 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12245 	    &tcps->tcps_dropper);
12246 	return (B_FALSE);
12247 }
12248 
12249 /*
12250  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12251  * retransmission after a timeout.
12252  *
12253  * To limit the number of duplicate segments, we limit the number of segment
12254  * to be sent in one time to tcp_snd_burst, the burst variable.
12255  */
12256 static void
12257 tcp_ss_rexmit(tcp_t *tcp)
12258 {
12259 	uint32_t	snxt;
12260 	uint32_t	smax;
12261 	int32_t		win;
12262 	int32_t		mss;
12263 	int32_t		off;
12264 	int32_t		burst = tcp->tcp_snd_burst;
12265 	mblk_t		*snxt_mp;
12266 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12267 
12268 	/*
12269 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12270 	 * all unack'ed segments.
12271 	 */
12272 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12273 		smax = tcp->tcp_rexmit_max;
12274 		snxt = tcp->tcp_rexmit_nxt;
12275 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12276 			snxt = tcp->tcp_suna;
12277 		}
12278 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12279 		win -= snxt - tcp->tcp_suna;
12280 		mss = tcp->tcp_mss;
12281 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12282 
12283 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12284 		    (burst > 0) && (snxt_mp != NULL)) {
12285 			mblk_t	*xmit_mp;
12286 			mblk_t	*old_snxt_mp = snxt_mp;
12287 			uint32_t cnt = mss;
12288 
12289 			if (win < cnt) {
12290 				cnt = win;
12291 			}
12292 			if (SEQ_GT(snxt + cnt, smax)) {
12293 				cnt = smax - snxt;
12294 			}
12295 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12296 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12297 			if (xmit_mp == NULL)
12298 				return;
12299 
12300 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12301 
12302 			snxt += cnt;
12303 			win -= cnt;
12304 			/*
12305 			 * Update the send timestamp to avoid false
12306 			 * retransmission.
12307 			 */
12308 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12309 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12310 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12311 
12312 			tcp->tcp_rexmit_nxt = snxt;
12313 			burst--;
12314 		}
12315 		/*
12316 		 * If we have transmitted all we have at the time
12317 		 * we started the retranmission, we can leave
12318 		 * the rest of the job to tcp_wput_data().  But we
12319 		 * need to check the send window first.  If the
12320 		 * win is not 0, go on with tcp_wput_data().
12321 		 */
12322 		if (SEQ_LT(snxt, smax) || win == 0) {
12323 			return;
12324 		}
12325 	}
12326 	/* Only call tcp_wput_data() if there is data to be sent. */
12327 	if (tcp->tcp_unsent) {
12328 		tcp_wput_data(tcp, NULL, B_FALSE);
12329 	}
12330 }
12331 
12332 /*
12333  * Process all TCP option in SYN segment.  Note that this function should
12334  * be called after tcp_adapt_ire() is called so that the necessary info
12335  * from IRE is already set in the tcp structure.
12336  *
12337  * This function sets up the correct tcp_mss value according to the
12338  * MSS option value and our header size.  It also sets up the window scale
12339  * and timestamp values, and initialize SACK info blocks.  But it does not
12340  * change receive window size after setting the tcp_mss value.  The caller
12341  * should do the appropriate change.
12342  */
12343 void
12344 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12345 {
12346 	int options;
12347 	tcp_opt_t tcpopt;
12348 	uint32_t mss_max;
12349 	char *tmp_tcph;
12350 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12351 
12352 	tcpopt.tcp = NULL;
12353 	options = tcp_parse_options(tcph, &tcpopt);
12354 
12355 	/*
12356 	 * Process MSS option.  Note that MSS option value does not account
12357 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12358 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12359 	 * IPv6.
12360 	 */
12361 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12362 		if (tcp->tcp_ipversion == IPV4_VERSION)
12363 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12364 		else
12365 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12366 	} else {
12367 		if (tcp->tcp_ipversion == IPV4_VERSION)
12368 			mss_max = tcps->tcps_mss_max_ipv4;
12369 		else
12370 			mss_max = tcps->tcps_mss_max_ipv6;
12371 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12372 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12373 		else if (tcpopt.tcp_opt_mss > mss_max)
12374 			tcpopt.tcp_opt_mss = mss_max;
12375 	}
12376 
12377 	/* Process Window Scale option. */
12378 	if (options & TCP_OPT_WSCALE_PRESENT) {
12379 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12380 		tcp->tcp_snd_ws_ok = B_TRUE;
12381 	} else {
12382 		tcp->tcp_snd_ws = B_FALSE;
12383 		tcp->tcp_snd_ws_ok = B_FALSE;
12384 		tcp->tcp_rcv_ws = B_FALSE;
12385 	}
12386 
12387 	/* Process Timestamp option. */
12388 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12389 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12390 		tmp_tcph = (char *)tcp->tcp_tcph;
12391 
12392 		tcp->tcp_snd_ts_ok = B_TRUE;
12393 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12394 		tcp->tcp_last_rcv_lbolt = lbolt64;
12395 		ASSERT(OK_32PTR(tmp_tcph));
12396 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12397 
12398 		/* Fill in our template header with basic timestamp option. */
12399 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12400 		tmp_tcph[0] = TCPOPT_NOP;
12401 		tmp_tcph[1] = TCPOPT_NOP;
12402 		tmp_tcph[2] = TCPOPT_TSTAMP;
12403 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12404 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12405 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12406 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12407 	} else {
12408 		tcp->tcp_snd_ts_ok = B_FALSE;
12409 	}
12410 
12411 	/*
12412 	 * Process SACK options.  If SACK is enabled for this connection,
12413 	 * then allocate the SACK info structure.  Note the following ways
12414 	 * when tcp_snd_sack_ok is set to true.
12415 	 *
12416 	 * For active connection: in tcp_adapt_ire() called in
12417 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12418 	 * is checked.
12419 	 *
12420 	 * For passive connection: in tcp_adapt_ire() called in
12421 	 * tcp_accept_comm().
12422 	 *
12423 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12424 	 * That check makes sure that if we did not send a SACK OK option,
12425 	 * we will not enable SACK for this connection even though the other
12426 	 * side sends us SACK OK option.  For active connection, the SACK
12427 	 * info structure has already been allocated.  So we need to free
12428 	 * it if SACK is disabled.
12429 	 */
12430 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12431 	    (tcp->tcp_snd_sack_ok ||
12432 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12433 		/* This should be true only in the passive case. */
12434 		if (tcp->tcp_sack_info == NULL) {
12435 			ASSERT(TCP_IS_DETACHED(tcp));
12436 			tcp->tcp_sack_info =
12437 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12438 		}
12439 		if (tcp->tcp_sack_info == NULL) {
12440 			tcp->tcp_snd_sack_ok = B_FALSE;
12441 		} else {
12442 			tcp->tcp_snd_sack_ok = B_TRUE;
12443 			if (tcp->tcp_snd_ts_ok) {
12444 				tcp->tcp_max_sack_blk = 3;
12445 			} else {
12446 				tcp->tcp_max_sack_blk = 4;
12447 			}
12448 		}
12449 	} else {
12450 		/*
12451 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12452 		 * no SACK info will be used for this
12453 		 * connection.  This assumes that SACK usage
12454 		 * permission is negotiated.  This may need
12455 		 * to be changed once this is clarified.
12456 		 */
12457 		if (tcp->tcp_sack_info != NULL) {
12458 			ASSERT(tcp->tcp_notsack_list == NULL);
12459 			kmem_cache_free(tcp_sack_info_cache,
12460 			    tcp->tcp_sack_info);
12461 			tcp->tcp_sack_info = NULL;
12462 		}
12463 		tcp->tcp_snd_sack_ok = B_FALSE;
12464 	}
12465 
12466 	/*
12467 	 * Now we know the exact TCP/IP header length, subtract
12468 	 * that from tcp_mss to get our side's MSS.
12469 	 */
12470 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12471 	/*
12472 	 * Here we assume that the other side's header size will be equal to
12473 	 * our header size.  We calculate the real MSS accordingly.  Need to
12474 	 * take into additional stuffs IPsec puts in.
12475 	 *
12476 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12477 	 */
12478 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12479 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12480 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12481 
12482 	/*
12483 	 * Set MSS to the smaller one of both ends of the connection.
12484 	 * We should not have called tcp_mss_set() before, but our
12485 	 * side of the MSS should have been set to a proper value
12486 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12487 	 * STREAM head parameters properly.
12488 	 *
12489 	 * If we have a larger-than-16-bit window but the other side
12490 	 * didn't want to do window scale, tcp_rwnd_set() will take
12491 	 * care of that.
12492 	 */
12493 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12494 }
12495 
12496 /*
12497  * Sends the T_CONN_IND to the listener. The caller calls this
12498  * functions via squeue to get inside the listener's perimeter
12499  * once the 3 way hand shake is done a T_CONN_IND needs to be
12500  * sent. As an optimization, the caller can call this directly
12501  * if listener's perimeter is same as eager's.
12502  */
12503 /* ARGSUSED */
12504 void
12505 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12506 {
12507 	conn_t			*lconnp = (conn_t *)arg;
12508 	tcp_t			*listener = lconnp->conn_tcp;
12509 	tcp_t			*tcp;
12510 	struct T_conn_ind	*conn_ind;
12511 	ipaddr_t 		*addr_cache;
12512 	boolean_t		need_send_conn_ind = B_FALSE;
12513 	tcp_stack_t		*tcps = listener->tcp_tcps;
12514 
12515 	/* retrieve the eager */
12516 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12517 	ASSERT(conn_ind->OPT_offset != 0 &&
12518 	    conn_ind->OPT_length == sizeof (intptr_t));
12519 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12520 	    conn_ind->OPT_length);
12521 
12522 	/*
12523 	 * TLI/XTI applications will get confused by
12524 	 * sending eager as an option since it violates
12525 	 * the option semantics. So remove the eager as
12526 	 * option since TLI/XTI app doesn't need it anyway.
12527 	 */
12528 	if (!TCP_IS_SOCKET(listener)) {
12529 		conn_ind->OPT_length = 0;
12530 		conn_ind->OPT_offset = 0;
12531 	}
12532 	if (listener->tcp_state == TCPS_CLOSED ||
12533 	    TCP_IS_DETACHED(listener)) {
12534 		/*
12535 		 * If listener has closed, it would have caused a
12536 		 * a cleanup/blowoff to happen for the eager. We
12537 		 * just need to return.
12538 		 */
12539 		freemsg(mp);
12540 		return;
12541 	}
12542 
12543 
12544 	/*
12545 	 * if the conn_req_q is full defer passing up the
12546 	 * T_CONN_IND until space is availabe after t_accept()
12547 	 * processing
12548 	 */
12549 	mutex_enter(&listener->tcp_eager_lock);
12550 
12551 	/*
12552 	 * Take the eager out, if it is in the list of droppable eagers
12553 	 * as we are here because the 3W handshake is over.
12554 	 */
12555 	MAKE_UNDROPPABLE(tcp);
12556 
12557 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12558 		tcp_t *tail;
12559 
12560 		/*
12561 		 * The eager already has an extra ref put in tcp_rput_data
12562 		 * so that it stays till accept comes back even though it
12563 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12564 		 */
12565 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12566 		listener->tcp_conn_req_cnt_q0--;
12567 		listener->tcp_conn_req_cnt_q++;
12568 
12569 		/* Move from SYN_RCVD to ESTABLISHED list  */
12570 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12571 		    tcp->tcp_eager_prev_q0;
12572 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12573 		    tcp->tcp_eager_next_q0;
12574 		tcp->tcp_eager_prev_q0 = NULL;
12575 		tcp->tcp_eager_next_q0 = NULL;
12576 
12577 		/*
12578 		 * Insert at end of the queue because sockfs
12579 		 * sends down T_CONN_RES in chronological
12580 		 * order. Leaving the older conn indications
12581 		 * at front of the queue helps reducing search
12582 		 * time.
12583 		 */
12584 		tail = listener->tcp_eager_last_q;
12585 		if (tail != NULL)
12586 			tail->tcp_eager_next_q = tcp;
12587 		else
12588 			listener->tcp_eager_next_q = tcp;
12589 		listener->tcp_eager_last_q = tcp;
12590 		tcp->tcp_eager_next_q = NULL;
12591 		/*
12592 		 * Delay sending up the T_conn_ind until we are
12593 		 * done with the eager. Once we have have sent up
12594 		 * the T_conn_ind, the accept can potentially complete
12595 		 * any time and release the refhold we have on the eager.
12596 		 */
12597 		need_send_conn_ind = B_TRUE;
12598 	} else {
12599 		/*
12600 		 * Defer connection on q0 and set deferred
12601 		 * connection bit true
12602 		 */
12603 		tcp->tcp_conn_def_q0 = B_TRUE;
12604 
12605 		/* take tcp out of q0 ... */
12606 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12607 		    tcp->tcp_eager_next_q0;
12608 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12609 		    tcp->tcp_eager_prev_q0;
12610 
12611 		/* ... and place it at the end of q0 */
12612 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12613 		tcp->tcp_eager_next_q0 = listener;
12614 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12615 		listener->tcp_eager_prev_q0 = tcp;
12616 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12617 	}
12618 
12619 	/* we have timed out before */
12620 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12621 		tcp->tcp_syn_rcvd_timeout = 0;
12622 		listener->tcp_syn_rcvd_timeout--;
12623 		if (listener->tcp_syn_defense &&
12624 		    listener->tcp_syn_rcvd_timeout <=
12625 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12626 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12627 		    listener->tcp_last_rcv_lbolt)) {
12628 			/*
12629 			 * Turn off the defense mode if we
12630 			 * believe the SYN attack is over.
12631 			 */
12632 			listener->tcp_syn_defense = B_FALSE;
12633 			if (listener->tcp_ip_addr_cache) {
12634 				kmem_free((void *)listener->tcp_ip_addr_cache,
12635 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12636 				listener->tcp_ip_addr_cache = NULL;
12637 			}
12638 		}
12639 	}
12640 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12641 	if (addr_cache != NULL) {
12642 		/*
12643 		 * We have finished a 3-way handshake with this
12644 		 * remote host. This proves the IP addr is good.
12645 		 * Cache it!
12646 		 */
12647 		addr_cache[IP_ADDR_CACHE_HASH(
12648 		    tcp->tcp_remote)] = tcp->tcp_remote;
12649 	}
12650 	mutex_exit(&listener->tcp_eager_lock);
12651 	if (need_send_conn_ind)
12652 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
12653 }
12654 
12655 /*
12656  * Send the newconn notification to ulp. The eager is blown off if the
12657  * notification fails.
12658  */
12659 static void
12660 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
12661 {
12662 	if (IPCL_IS_NONSTR(lconnp)) {
12663 		cred_t	*cr;
12664 		pid_t	cpid;
12665 
12666 		cr = msg_getcred(mp, &cpid);
12667 
12668 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
12669 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
12670 		    lconnp->conn_tcp);
12671 
12672 		/* Keep the message around in case of a fallback to TPI */
12673 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
12674 
12675 		/*
12676 		 * Notify the ULP about the newconn. It is guaranteed that no
12677 		 * tcp_accept() call will be made for the eager if the
12678 		 * notification fails, so it's safe to blow it off in that
12679 		 * case.
12680 		 *
12681 		 * The upper handle will be assigned when tcp_accept() is
12682 		 * called.
12683 		 */
12684 		if ((*lconnp->conn_upcalls->su_newconn)
12685 		    (lconnp->conn_upper_handle,
12686 		    (sock_lower_handle_t)econnp,
12687 		    &sock_tcp_downcalls, cr, cpid,
12688 		    &econnp->conn_upcalls) == NULL) {
12689 			/* Failed to allocate a socket */
12690 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
12691 			    tcpEstabResets);
12692 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
12693 			    econnp->conn_tcp->tcp_conn_req_seqnum);
12694 		}
12695 	} else {
12696 		putnext(lconnp->conn_tcp->tcp_rq, mp);
12697 	}
12698 }
12699 
12700 mblk_t *
12701 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12702     uint_t *ifindexp, ip6_pkt_t *ippp)
12703 {
12704 	ip_pktinfo_t	*pinfo;
12705 	ip6_t		*ip6h;
12706 	uchar_t		*rptr;
12707 	mblk_t		*first_mp = mp;
12708 	boolean_t	mctl_present = B_FALSE;
12709 	uint_t 		ifindex = 0;
12710 	ip6_pkt_t	ipp;
12711 	uint_t		ipvers;
12712 	uint_t		ip_hdr_len;
12713 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12714 
12715 	rptr = mp->b_rptr;
12716 	ASSERT(OK_32PTR(rptr));
12717 	ASSERT(tcp != NULL);
12718 	ipp.ipp_fields = 0;
12719 
12720 	switch DB_TYPE(mp) {
12721 	case M_CTL:
12722 		mp = mp->b_cont;
12723 		if (mp == NULL) {
12724 			freemsg(first_mp);
12725 			return (NULL);
12726 		}
12727 		if (DB_TYPE(mp) != M_DATA) {
12728 			freemsg(first_mp);
12729 			return (NULL);
12730 		}
12731 		mctl_present = B_TRUE;
12732 		break;
12733 	case M_DATA:
12734 		break;
12735 	default:
12736 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12737 		freemsg(mp);
12738 		return (NULL);
12739 	}
12740 	ipvers = IPH_HDR_VERSION(rptr);
12741 	if (ipvers == IPV4_VERSION) {
12742 		if (tcp == NULL) {
12743 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12744 			goto done;
12745 		}
12746 
12747 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12748 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12749 
12750 		/*
12751 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12752 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12753 		 */
12754 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12755 		    mctl_present) {
12756 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12757 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12758 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12759 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12760 				ipp.ipp_fields |= IPPF_IFINDEX;
12761 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12762 				ifindex = pinfo->ip_pkt_ifindex;
12763 			}
12764 			freeb(first_mp);
12765 			mctl_present = B_FALSE;
12766 		}
12767 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12768 	} else {
12769 		ip6h = (ip6_t *)rptr;
12770 
12771 		ASSERT(ipvers == IPV6_VERSION);
12772 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12773 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12774 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12775 
12776 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12777 			uint8_t	nexthdrp;
12778 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12779 
12780 			/* Look for ifindex information */
12781 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12782 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12783 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12784 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12785 					freemsg(first_mp);
12786 					return (NULL);
12787 				}
12788 
12789 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12790 					ASSERT(ip6i->ip6i_ifindex != 0);
12791 					ipp.ipp_fields |= IPPF_IFINDEX;
12792 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12793 					ifindex = ip6i->ip6i_ifindex;
12794 				}
12795 				rptr = (uchar_t *)&ip6i[1];
12796 				mp->b_rptr = rptr;
12797 				if (rptr == mp->b_wptr) {
12798 					mblk_t *mp1;
12799 					mp1 = mp->b_cont;
12800 					freeb(mp);
12801 					mp = mp1;
12802 					rptr = mp->b_rptr;
12803 				}
12804 				if (MBLKL(mp) < IPV6_HDR_LEN +
12805 				    sizeof (tcph_t)) {
12806 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12807 					freemsg(first_mp);
12808 					return (NULL);
12809 				}
12810 				ip6h = (ip6_t *)rptr;
12811 			}
12812 
12813 			/*
12814 			 * Find any potentially interesting extension headers
12815 			 * as well as the length of the IPv6 + extension
12816 			 * headers.
12817 			 */
12818 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12819 			/* Verify if this is a TCP packet */
12820 			if (nexthdrp != IPPROTO_TCP) {
12821 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12822 				freemsg(first_mp);
12823 				return (NULL);
12824 			}
12825 		} else {
12826 			ip_hdr_len = IPV6_HDR_LEN;
12827 		}
12828 	}
12829 
12830 done:
12831 	if (ipversp != NULL)
12832 		*ipversp = ipvers;
12833 	if (ip_hdr_lenp != NULL)
12834 		*ip_hdr_lenp = ip_hdr_len;
12835 	if (ippp != NULL)
12836 		*ippp = ipp;
12837 	if (ifindexp != NULL)
12838 		*ifindexp = ifindex;
12839 	if (mctl_present) {
12840 		freeb(first_mp);
12841 	}
12842 	return (mp);
12843 }
12844 
12845 /*
12846  * Handle M_DATA messages from IP. Its called directly from IP via
12847  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12848  * in this path.
12849  *
12850  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12851  * v4 and v6), we are called through tcp_input() and a M_CTL can
12852  * be present for options but tcp_find_pktinfo() deals with it. We
12853  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12854  *
12855  * The first argument is always the connp/tcp to which the mp belongs.
12856  * There are no exceptions to this rule. The caller has already put
12857  * a reference on this connp/tcp and once tcp_rput_data() returns,
12858  * the squeue will do the refrele.
12859  *
12860  * The TH_SYN for the listener directly go to tcp_conn_request via
12861  * squeue.
12862  *
12863  * sqp: NULL = recursive, sqp != NULL means called from squeue
12864  */
12865 void
12866 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12867 {
12868 	int32_t		bytes_acked;
12869 	int32_t		gap;
12870 	mblk_t		*mp1;
12871 	uint_t		flags;
12872 	uint32_t	new_swnd = 0;
12873 	uchar_t		*iphdr;
12874 	uchar_t		*rptr;
12875 	int32_t		rgap;
12876 	uint32_t	seg_ack;
12877 	int		seg_len;
12878 	uint_t		ip_hdr_len;
12879 	uint32_t	seg_seq;
12880 	tcph_t		*tcph;
12881 	int		urp;
12882 	tcp_opt_t	tcpopt;
12883 	uint_t		ipvers;
12884 	ip6_pkt_t	ipp;
12885 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12886 	uint32_t	cwnd;
12887 	uint32_t	add;
12888 	int		npkt;
12889 	int		mss;
12890 	conn_t		*connp = (conn_t *)arg;
12891 	squeue_t	*sqp = (squeue_t *)arg2;
12892 	tcp_t		*tcp = connp->conn_tcp;
12893 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12894 
12895 	/*
12896 	 * RST from fused tcp loopback peer should trigger an unfuse.
12897 	 */
12898 	if (tcp->tcp_fused) {
12899 		TCP_STAT(tcps, tcp_fusion_aborted);
12900 		tcp_unfuse(tcp);
12901 	}
12902 
12903 	iphdr = mp->b_rptr;
12904 	rptr = mp->b_rptr;
12905 	ASSERT(OK_32PTR(rptr));
12906 
12907 	/*
12908 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12909 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12910 	 * necessary information.
12911 	 */
12912 	if (IPCL_IS_TCP4(connp)) {
12913 		ipvers = IPV4_VERSION;
12914 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12915 	} else {
12916 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12917 		    NULL, &ipp);
12918 		if (mp == NULL) {
12919 			TCP_STAT(tcps, tcp_rput_v6_error);
12920 			return;
12921 		}
12922 		iphdr = mp->b_rptr;
12923 		rptr = mp->b_rptr;
12924 	}
12925 	ASSERT(DB_TYPE(mp) == M_DATA);
12926 	ASSERT(mp->b_next == NULL);
12927 
12928 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12929 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12930 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12931 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12932 	seg_len = (int)(mp->b_wptr - rptr) -
12933 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12934 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12935 		do {
12936 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12937 			    (uintptr_t)INT_MAX);
12938 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12939 		} while ((mp1 = mp1->b_cont) != NULL &&
12940 		    mp1->b_datap->db_type == M_DATA);
12941 	}
12942 
12943 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12944 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12945 		    seg_len, tcph);
12946 		return;
12947 	}
12948 
12949 	if (sqp != NULL) {
12950 		/*
12951 		 * This is the correct place to update tcp_last_recv_time. Note
12952 		 * that it is also updated for tcp structure that belongs to
12953 		 * global and listener queues which do not really need updating.
12954 		 * But that should not cause any harm.  And it is updated for
12955 		 * all kinds of incoming segments, not only for data segments.
12956 		 */
12957 		tcp->tcp_last_recv_time = lbolt;
12958 	}
12959 
12960 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12961 
12962 	BUMP_LOCAL(tcp->tcp_ibsegs);
12963 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
12964 
12965 	if ((flags & TH_URG) && sqp != NULL) {
12966 		/*
12967 		 * TCP can't handle urgent pointers that arrive before
12968 		 * the connection has been accept()ed since it can't
12969 		 * buffer OOB data.  Discard segment if this happens.
12970 		 *
12971 		 * We can't just rely on a non-null tcp_listener to indicate
12972 		 * that the accept() has completed since unlinking of the
12973 		 * eager and completion of the accept are not atomic.
12974 		 * tcp_detached, when it is not set (B_FALSE) indicates
12975 		 * that the accept() has completed.
12976 		 *
12977 		 * Nor can it reassemble urgent pointers, so discard
12978 		 * if it's not the next segment expected.
12979 		 *
12980 		 * Otherwise, collapse chain into one mblk (discard if
12981 		 * that fails).  This makes sure the headers, retransmitted
12982 		 * data, and new data all are in the same mblk.
12983 		 */
12984 		ASSERT(mp != NULL);
12985 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
12986 			freemsg(mp);
12987 			return;
12988 		}
12989 		/* Update pointers into message */
12990 		iphdr = rptr = mp->b_rptr;
12991 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12992 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12993 			/*
12994 			 * Since we can't handle any data with this urgent
12995 			 * pointer that is out of sequence, we expunge
12996 			 * the data.  This allows us to still register
12997 			 * the urgent mark and generate the M_PCSIG,
12998 			 * which we can do.
12999 			 */
13000 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13001 			seg_len = 0;
13002 		}
13003 	}
13004 
13005 	switch (tcp->tcp_state) {
13006 	case TCPS_SYN_SENT:
13007 		if (flags & TH_ACK) {
13008 			/*
13009 			 * Note that our stack cannot send data before a
13010 			 * connection is established, therefore the
13011 			 * following check is valid.  Otherwise, it has
13012 			 * to be changed.
13013 			 */
13014 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13015 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13016 				freemsg(mp);
13017 				if (flags & TH_RST)
13018 					return;
13019 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13020 				    tcp, seg_ack, 0, TH_RST);
13021 				return;
13022 			}
13023 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13024 		}
13025 		if (flags & TH_RST) {
13026 			freemsg(mp);
13027 			if (flags & TH_ACK)
13028 				(void) tcp_clean_death(tcp,
13029 				    ECONNREFUSED, 13);
13030 			return;
13031 		}
13032 		if (!(flags & TH_SYN)) {
13033 			freemsg(mp);
13034 			return;
13035 		}
13036 
13037 		/* Process all TCP options. */
13038 		tcp_process_options(tcp, tcph);
13039 		/*
13040 		 * The following changes our rwnd to be a multiple of the
13041 		 * MIN(peer MSS, our MSS) for performance reason.
13042 		 */
13043 		(void) tcp_rwnd_set(tcp,
13044 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
13045 
13046 		/* Is the other end ECN capable? */
13047 		if (tcp->tcp_ecn_ok) {
13048 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13049 				tcp->tcp_ecn_ok = B_FALSE;
13050 			}
13051 		}
13052 		/*
13053 		 * Clear ECN flags because it may interfere with later
13054 		 * processing.
13055 		 */
13056 		flags &= ~(TH_ECE|TH_CWR);
13057 
13058 		tcp->tcp_irs = seg_seq;
13059 		tcp->tcp_rack = seg_seq;
13060 		tcp->tcp_rnxt = seg_seq + 1;
13061 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13062 		if (!TCP_IS_DETACHED(tcp)) {
13063 			/* Allocate room for SACK options if needed. */
13064 			if (tcp->tcp_snd_sack_ok) {
13065 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13066 				    tcp->tcp_hdr_len +
13067 				    TCPOPT_MAX_SACK_LEN +
13068 				    (tcp->tcp_loopback ? 0 :
13069 				    tcps->tcps_wroff_xtra));
13070 			} else {
13071 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13072 				    tcp->tcp_hdr_len +
13073 				    (tcp->tcp_loopback ? 0 :
13074 				    tcps->tcps_wroff_xtra));
13075 			}
13076 		}
13077 		if (flags & TH_ACK) {
13078 			/*
13079 			 * If we can't get the confirmation upstream, pretend
13080 			 * we didn't even see this one.
13081 			 *
13082 			 * XXX: how can we pretend we didn't see it if we
13083 			 * have updated rnxt et. al.
13084 			 *
13085 			 * For loopback we defer sending up the T_CONN_CON
13086 			 * until after some checks below.
13087 			 */
13088 			mp1 = NULL;
13089 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13090 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13091 				freemsg(mp);
13092 				return;
13093 			}
13094 			/* SYN was acked - making progress */
13095 			if (tcp->tcp_ipversion == IPV6_VERSION)
13096 				tcp->tcp_ip_forward_progress = B_TRUE;
13097 
13098 			/* One for the SYN */
13099 			tcp->tcp_suna = tcp->tcp_iss + 1;
13100 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13101 			tcp->tcp_state = TCPS_ESTABLISHED;
13102 
13103 			/*
13104 			 * If SYN was retransmitted, need to reset all
13105 			 * retransmission info.  This is because this
13106 			 * segment will be treated as a dup ACK.
13107 			 */
13108 			if (tcp->tcp_rexmit) {
13109 				tcp->tcp_rexmit = B_FALSE;
13110 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13111 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13112 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13113 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13114 				tcp->tcp_ms_we_have_waited = 0;
13115 
13116 				/*
13117 				 * Set tcp_cwnd back to 1 MSS, per
13118 				 * recommendation from
13119 				 * draft-floyd-incr-init-win-01.txt,
13120 				 * Increasing TCP's Initial Window.
13121 				 */
13122 				tcp->tcp_cwnd = tcp->tcp_mss;
13123 			}
13124 
13125 			tcp->tcp_swl1 = seg_seq;
13126 			tcp->tcp_swl2 = seg_ack;
13127 
13128 			new_swnd = BE16_TO_U16(tcph->th_win);
13129 			tcp->tcp_swnd = new_swnd;
13130 			if (new_swnd > tcp->tcp_max_swnd)
13131 				tcp->tcp_max_swnd = new_swnd;
13132 
13133 			/*
13134 			 * Always send the three-way handshake ack immediately
13135 			 * in order to make the connection complete as soon as
13136 			 * possible on the accepting host.
13137 			 */
13138 			flags |= TH_ACK_NEEDED;
13139 
13140 			/*
13141 			 * Special case for loopback.  At this point we have
13142 			 * received SYN-ACK from the remote endpoint.  In
13143 			 * order to ensure that both endpoints reach the
13144 			 * fused state prior to any data exchange, the final
13145 			 * ACK needs to be sent before we indicate T_CONN_CON
13146 			 * to the module upstream.
13147 			 */
13148 			if (tcp->tcp_loopback) {
13149 				mblk_t *ack_mp;
13150 
13151 				ASSERT(!tcp->tcp_unfusable);
13152 				ASSERT(mp1 != NULL);
13153 				/*
13154 				 * For loopback, we always get a pure SYN-ACK
13155 				 * and only need to send back the final ACK
13156 				 * with no data (this is because the other
13157 				 * tcp is ours and we don't do T/TCP).  This
13158 				 * final ACK triggers the passive side to
13159 				 * perform fusion in ESTABLISHED state.
13160 				 */
13161 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13162 					if (tcp->tcp_ack_tid != 0) {
13163 						(void) TCP_TIMER_CANCEL(tcp,
13164 						    tcp->tcp_ack_tid);
13165 						tcp->tcp_ack_tid = 0;
13166 					}
13167 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13168 					BUMP_LOCAL(tcp->tcp_obsegs);
13169 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13170 
13171 					if (!IPCL_IS_NONSTR(connp)) {
13172 						/* Send up T_CONN_CON */
13173 						putnext(tcp->tcp_rq, mp1);
13174 					} else {
13175 						cred_t	*cr;
13176 						pid_t	cpid;
13177 
13178 						cr = msg_getcred(mp1, &cpid);
13179 						(*connp->conn_upcalls->
13180 						    su_connected)
13181 						    (connp->conn_upper_handle,
13182 						    tcp->tcp_connid, cr, cpid);
13183 						freemsg(mp1);
13184 					}
13185 
13186 					freemsg(mp);
13187 					return;
13188 				}
13189 				/*
13190 				 * Forget fusion; we need to handle more
13191 				 * complex cases below.  Send the deferred
13192 				 * T_CONN_CON message upstream and proceed
13193 				 * as usual.  Mark this tcp as not capable
13194 				 * of fusion.
13195 				 */
13196 				TCP_STAT(tcps, tcp_fusion_unfusable);
13197 				tcp->tcp_unfusable = B_TRUE;
13198 				if (!IPCL_IS_NONSTR(connp)) {
13199 					putnext(tcp->tcp_rq, mp1);
13200 				} else {
13201 					cred_t	*cr;
13202 					pid_t	cpid;
13203 
13204 					cr = msg_getcred(mp1, &cpid);
13205 					(*connp->conn_upcalls->su_connected)
13206 					    (connp->conn_upper_handle,
13207 					    tcp->tcp_connid, cr, cpid);
13208 					freemsg(mp1);
13209 				}
13210 			}
13211 
13212 			/*
13213 			 * Check to see if there is data to be sent.  If
13214 			 * yes, set the transmit flag.  Then check to see
13215 			 * if received data processing needs to be done.
13216 			 * If not, go straight to xmit_check.  This short
13217 			 * cut is OK as we don't support T/TCP.
13218 			 */
13219 			if (tcp->tcp_unsent)
13220 				flags |= TH_XMIT_NEEDED;
13221 
13222 			if (seg_len == 0 && !(flags & TH_URG)) {
13223 				freemsg(mp);
13224 				goto xmit_check;
13225 			}
13226 
13227 			flags &= ~TH_SYN;
13228 			seg_seq++;
13229 			break;
13230 		}
13231 		tcp->tcp_state = TCPS_SYN_RCVD;
13232 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13233 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13234 		if (mp1) {
13235 			/*
13236 			 * See comment in tcp_conn_request() for why we use
13237 			 * the open() time pid here.
13238 			 */
13239 			DB_CPID(mp1) = tcp->tcp_cpid;
13240 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13241 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13242 		}
13243 		freemsg(mp);
13244 		return;
13245 	case TCPS_SYN_RCVD:
13246 		if (flags & TH_ACK) {
13247 			/*
13248 			 * In this state, a SYN|ACK packet is either bogus
13249 			 * because the other side must be ACKing our SYN which
13250 			 * indicates it has seen the ACK for their SYN and
13251 			 * shouldn't retransmit it or we're crossing SYNs
13252 			 * on active open.
13253 			 */
13254 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13255 				freemsg(mp);
13256 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13257 				    tcp, seg_ack, 0, TH_RST);
13258 				return;
13259 			}
13260 			/*
13261 			 * NOTE: RFC 793 pg. 72 says this should be
13262 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13263 			 * but that would mean we have an ack that ignored
13264 			 * our SYN.
13265 			 */
13266 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13267 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13268 				freemsg(mp);
13269 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13270 				    tcp, seg_ack, 0, TH_RST);
13271 				return;
13272 			}
13273 		}
13274 		break;
13275 	case TCPS_LISTEN:
13276 		/*
13277 		 * Only a TLI listener can come through this path when a
13278 		 * acceptor is going back to be a listener and a packet
13279 		 * for the acceptor hits the classifier. For a socket
13280 		 * listener, this can never happen because a listener
13281 		 * can never accept connection on itself and hence a
13282 		 * socket acceptor can not go back to being a listener.
13283 		 */
13284 		ASSERT(!TCP_IS_SOCKET(tcp));
13285 		/*FALLTHRU*/
13286 	case TCPS_CLOSED:
13287 	case TCPS_BOUND: {
13288 		conn_t	*new_connp;
13289 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13290 
13291 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13292 		if (new_connp != NULL) {
13293 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13294 			return;
13295 		}
13296 		/* We failed to classify. For now just drop the packet */
13297 		freemsg(mp);
13298 		return;
13299 	}
13300 	case TCPS_IDLE:
13301 		/*
13302 		 * Handle the case where the tcp_clean_death() has happened
13303 		 * on a connection (application hasn't closed yet) but a packet
13304 		 * was already queued on squeue before tcp_clean_death()
13305 		 * was processed. Calling tcp_clean_death() twice on same
13306 		 * connection can result in weird behaviour.
13307 		 */
13308 		freemsg(mp);
13309 		return;
13310 	default:
13311 		break;
13312 	}
13313 
13314 	/*
13315 	 * Already on the correct queue/perimeter.
13316 	 * If this is a detached connection and not an eager
13317 	 * connection hanging off a listener then new data
13318 	 * (past the FIN) will cause a reset.
13319 	 * We do a special check here where it
13320 	 * is out of the main line, rather than check
13321 	 * if we are detached every time we see new
13322 	 * data down below.
13323 	 */
13324 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13325 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13326 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13327 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13328 
13329 		freemsg(mp);
13330 		/*
13331 		 * This could be an SSL closure alert. We're detached so just
13332 		 * acknowledge it this last time.
13333 		 */
13334 		if (tcp->tcp_kssl_ctx != NULL) {
13335 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13336 			tcp->tcp_kssl_ctx = NULL;
13337 
13338 			tcp->tcp_rnxt += seg_len;
13339 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13340 			flags |= TH_ACK_NEEDED;
13341 			goto ack_check;
13342 		}
13343 
13344 		tcp_xmit_ctl("new data when detached", tcp,
13345 		    tcp->tcp_snxt, 0, TH_RST);
13346 		(void) tcp_clean_death(tcp, EPROTO, 12);
13347 		return;
13348 	}
13349 
13350 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13351 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13352 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13353 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13354 
13355 	if (tcp->tcp_snd_ts_ok) {
13356 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13357 			/*
13358 			 * This segment is not acceptable.
13359 			 * Drop it and send back an ACK.
13360 			 */
13361 			freemsg(mp);
13362 			flags |= TH_ACK_NEEDED;
13363 			goto ack_check;
13364 		}
13365 	} else if (tcp->tcp_snd_sack_ok) {
13366 		ASSERT(tcp->tcp_sack_info != NULL);
13367 		tcpopt.tcp = tcp;
13368 		/*
13369 		 * SACK info in already updated in tcp_parse_options.  Ignore
13370 		 * all other TCP options...
13371 		 */
13372 		(void) tcp_parse_options(tcph, &tcpopt);
13373 	}
13374 try_again:;
13375 	mss = tcp->tcp_mss;
13376 	gap = seg_seq - tcp->tcp_rnxt;
13377 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13378 	/*
13379 	 * gap is the amount of sequence space between what we expect to see
13380 	 * and what we got for seg_seq.  A positive value for gap means
13381 	 * something got lost.  A negative value means we got some old stuff.
13382 	 */
13383 	if (gap < 0) {
13384 		/* Old stuff present.  Is the SYN in there? */
13385 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13386 		    (seg_len != 0)) {
13387 			flags &= ~TH_SYN;
13388 			seg_seq++;
13389 			urp--;
13390 			/* Recompute the gaps after noting the SYN. */
13391 			goto try_again;
13392 		}
13393 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13394 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13395 		    (seg_len > -gap ? -gap : seg_len));
13396 		/* Remove the old stuff from seg_len. */
13397 		seg_len += gap;
13398 		/*
13399 		 * Anything left?
13400 		 * Make sure to check for unack'd FIN when rest of data
13401 		 * has been previously ack'd.
13402 		 */
13403 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13404 			/*
13405 			 * Resets are only valid if they lie within our offered
13406 			 * window.  If the RST bit is set, we just ignore this
13407 			 * segment.
13408 			 */
13409 			if (flags & TH_RST) {
13410 				freemsg(mp);
13411 				return;
13412 			}
13413 
13414 			/*
13415 			 * The arriving of dup data packets indicate that we
13416 			 * may have postponed an ack for too long, or the other
13417 			 * side's RTT estimate is out of shape. Start acking
13418 			 * more often.
13419 			 */
13420 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13421 			    tcp->tcp_rack_cnt >= 1 &&
13422 			    tcp->tcp_rack_abs_max > 2) {
13423 				tcp->tcp_rack_abs_max--;
13424 			}
13425 			tcp->tcp_rack_cur_max = 1;
13426 
13427 			/*
13428 			 * This segment is "unacceptable".  None of its
13429 			 * sequence space lies within our advertized window.
13430 			 *
13431 			 * Adjust seg_len to the original value for tracing.
13432 			 */
13433 			seg_len -= gap;
13434 			if (tcp->tcp_debug) {
13435 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13436 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13437 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13438 				    "seg_len %d, rnxt %u, snxt %u, %s",
13439 				    gap, rgap, flags, seg_seq, seg_ack,
13440 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13441 				    tcp_display(tcp, NULL,
13442 				    DISP_ADDR_AND_PORT));
13443 			}
13444 
13445 			/*
13446 			 * Arrange to send an ACK in response to the
13447 			 * unacceptable segment per RFC 793 page 69. There
13448 			 * is only one small difference between ours and the
13449 			 * acceptability test in the RFC - we accept ACK-only
13450 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13451 			 * will be generated.
13452 			 *
13453 			 * Note that we have to ACK an ACK-only packet at least
13454 			 * for stacks that send 0-length keep-alives with
13455 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13456 			 * section 4.2.3.6. As long as we don't ever generate
13457 			 * an unacceptable packet in response to an incoming
13458 			 * packet that is unacceptable, it should not cause
13459 			 * "ACK wars".
13460 			 */
13461 			flags |=  TH_ACK_NEEDED;
13462 
13463 			/*
13464 			 * Continue processing this segment in order to use the
13465 			 * ACK information it contains, but skip all other
13466 			 * sequence-number processing.	Processing the ACK
13467 			 * information is necessary in order to
13468 			 * re-synchronize connections that may have lost
13469 			 * synchronization.
13470 			 *
13471 			 * We clear seg_len and flag fields related to
13472 			 * sequence number processing as they are not
13473 			 * to be trusted for an unacceptable segment.
13474 			 */
13475 			seg_len = 0;
13476 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13477 			goto process_ack;
13478 		}
13479 
13480 		/* Fix seg_seq, and chew the gap off the front. */
13481 		seg_seq = tcp->tcp_rnxt;
13482 		urp += gap;
13483 		do {
13484 			mblk_t	*mp2;
13485 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13486 			    (uintptr_t)UINT_MAX);
13487 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13488 			if (gap > 0) {
13489 				mp->b_rptr = mp->b_wptr - gap;
13490 				break;
13491 			}
13492 			mp2 = mp;
13493 			mp = mp->b_cont;
13494 			freeb(mp2);
13495 		} while (gap < 0);
13496 		/*
13497 		 * If the urgent data has already been acknowledged, we
13498 		 * should ignore TH_URG below
13499 		 */
13500 		if (urp < 0)
13501 			flags &= ~TH_URG;
13502 	}
13503 	/*
13504 	 * rgap is the amount of stuff received out of window.  A negative
13505 	 * value is the amount out of window.
13506 	 */
13507 	if (rgap < 0) {
13508 		mblk_t	*mp2;
13509 
13510 		if (tcp->tcp_rwnd == 0) {
13511 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13512 		} else {
13513 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13514 			UPDATE_MIB(&tcps->tcps_mib,
13515 			    tcpInDataPastWinBytes, -rgap);
13516 		}
13517 
13518 		/*
13519 		 * seg_len does not include the FIN, so if more than
13520 		 * just the FIN is out of window, we act like we don't
13521 		 * see it.  (If just the FIN is out of window, rgap
13522 		 * will be zero and we will go ahead and acknowledge
13523 		 * the FIN.)
13524 		 */
13525 		flags &= ~TH_FIN;
13526 
13527 		/* Fix seg_len and make sure there is something left. */
13528 		seg_len += rgap;
13529 		if (seg_len <= 0) {
13530 			/*
13531 			 * Resets are only valid if they lie within our offered
13532 			 * window.  If the RST bit is set, we just ignore this
13533 			 * segment.
13534 			 */
13535 			if (flags & TH_RST) {
13536 				freemsg(mp);
13537 				return;
13538 			}
13539 
13540 			/* Per RFC 793, we need to send back an ACK. */
13541 			flags |= TH_ACK_NEEDED;
13542 
13543 			/*
13544 			 * Send SIGURG as soon as possible i.e. even
13545 			 * if the TH_URG was delivered in a window probe
13546 			 * packet (which will be unacceptable).
13547 			 *
13548 			 * We generate a signal if none has been generated
13549 			 * for this connection or if this is a new urgent
13550 			 * byte. Also send a zero-length "unmarked" message
13551 			 * to inform SIOCATMARK that this is not the mark.
13552 			 *
13553 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13554 			 * is sent up. This plus the check for old data
13555 			 * (gap >= 0) handles the wraparound of the sequence
13556 			 * number space without having to always track the
13557 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13558 			 * this max in its rcv_up variable).
13559 			 *
13560 			 * This prevents duplicate SIGURGS due to a "late"
13561 			 * zero-window probe when the T_EXDATA_IND has already
13562 			 * been sent up.
13563 			 */
13564 			if ((flags & TH_URG) &&
13565 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13566 			    tcp->tcp_urp_last))) {
13567 				if (IPCL_IS_NONSTR(connp)) {
13568 					if (!TCP_IS_DETACHED(tcp)) {
13569 						(*connp->conn_upcalls->
13570 						    su_signal_oob)
13571 						    (connp->conn_upper_handle,
13572 						    urp);
13573 					}
13574 				} else {
13575 					mp1 = allocb(0, BPRI_MED);
13576 					if (mp1 == NULL) {
13577 						freemsg(mp);
13578 						return;
13579 					}
13580 					if (!TCP_IS_DETACHED(tcp) &&
13581 					    !putnextctl1(tcp->tcp_rq,
13582 					    M_PCSIG, SIGURG)) {
13583 						/* Try again on the rexmit. */
13584 						freemsg(mp1);
13585 						freemsg(mp);
13586 						return;
13587 					}
13588 					/*
13589 					 * If the next byte would be the mark
13590 					 * then mark with MARKNEXT else mark
13591 					 * with NOTMARKNEXT.
13592 					 */
13593 					if (gap == 0 && urp == 0)
13594 						mp1->b_flag |= MSGMARKNEXT;
13595 					else
13596 						mp1->b_flag |= MSGNOTMARKNEXT;
13597 					freemsg(tcp->tcp_urp_mark_mp);
13598 					tcp->tcp_urp_mark_mp = mp1;
13599 					flags |= TH_SEND_URP_MARK;
13600 				}
13601 				tcp->tcp_urp_last_valid = B_TRUE;
13602 				tcp->tcp_urp_last = urp + seg_seq;
13603 			}
13604 			/*
13605 			 * If this is a zero window probe, continue to
13606 			 * process the ACK part.  But we need to set seg_len
13607 			 * to 0 to avoid data processing.  Otherwise just
13608 			 * drop the segment and send back an ACK.
13609 			 */
13610 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13611 				flags &= ~(TH_SYN | TH_URG);
13612 				seg_len = 0;
13613 				goto process_ack;
13614 			} else {
13615 				freemsg(mp);
13616 				goto ack_check;
13617 			}
13618 		}
13619 		/* Pitch out of window stuff off the end. */
13620 		rgap = seg_len;
13621 		mp2 = mp;
13622 		do {
13623 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13624 			    (uintptr_t)INT_MAX);
13625 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13626 			if (rgap < 0) {
13627 				mp2->b_wptr += rgap;
13628 				if ((mp1 = mp2->b_cont) != NULL) {
13629 					mp2->b_cont = NULL;
13630 					freemsg(mp1);
13631 				}
13632 				break;
13633 			}
13634 		} while ((mp2 = mp2->b_cont) != NULL);
13635 	}
13636 ok:;
13637 	/*
13638 	 * TCP should check ECN info for segments inside the window only.
13639 	 * Therefore the check should be done here.
13640 	 */
13641 	if (tcp->tcp_ecn_ok) {
13642 		if (flags & TH_CWR) {
13643 			tcp->tcp_ecn_echo_on = B_FALSE;
13644 		}
13645 		/*
13646 		 * Note that both ECN_CE and CWR can be set in the
13647 		 * same segment.  In this case, we once again turn
13648 		 * on ECN_ECHO.
13649 		 */
13650 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13651 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13652 
13653 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13654 				tcp->tcp_ecn_echo_on = B_TRUE;
13655 			}
13656 		} else {
13657 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13658 
13659 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13660 			    htonl(IPH_ECN_CE << 20)) {
13661 				tcp->tcp_ecn_echo_on = B_TRUE;
13662 			}
13663 		}
13664 	}
13665 
13666 	/*
13667 	 * Check whether we can update tcp_ts_recent.  This test is
13668 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13669 	 * Extensions for High Performance: An Update", Internet Draft.
13670 	 */
13671 	if (tcp->tcp_snd_ts_ok &&
13672 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13673 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13674 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13675 		tcp->tcp_last_rcv_lbolt = lbolt64;
13676 	}
13677 
13678 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13679 		/*
13680 		 * FIN in an out of order segment.  We record this in
13681 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13682 		 * Clear the FIN so that any check on FIN flag will fail.
13683 		 * Remember that FIN also counts in the sequence number
13684 		 * space.  So we need to ack out of order FIN only segments.
13685 		 */
13686 		if (flags & TH_FIN) {
13687 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13688 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13689 			flags &= ~TH_FIN;
13690 			flags |= TH_ACK_NEEDED;
13691 		}
13692 		if (seg_len > 0) {
13693 			/* Fill in the SACK blk list. */
13694 			if (tcp->tcp_snd_sack_ok) {
13695 				ASSERT(tcp->tcp_sack_info != NULL);
13696 				tcp_sack_insert(tcp->tcp_sack_list,
13697 				    seg_seq, seg_seq + seg_len,
13698 				    &(tcp->tcp_num_sack_blk));
13699 			}
13700 
13701 			/*
13702 			 * Attempt reassembly and see if we have something
13703 			 * ready to go.
13704 			 */
13705 			mp = tcp_reass(tcp, mp, seg_seq);
13706 			/* Always ack out of order packets */
13707 			flags |= TH_ACK_NEEDED | TH_PUSH;
13708 			if (mp) {
13709 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13710 				    (uintptr_t)INT_MAX);
13711 				seg_len = mp->b_cont ? msgdsize(mp) :
13712 				    (int)(mp->b_wptr - mp->b_rptr);
13713 				seg_seq = tcp->tcp_rnxt;
13714 				/*
13715 				 * A gap is filled and the seq num and len
13716 				 * of the gap match that of a previously
13717 				 * received FIN, put the FIN flag back in.
13718 				 */
13719 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13720 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13721 					flags |= TH_FIN;
13722 					tcp->tcp_valid_bits &=
13723 					    ~TCP_OFO_FIN_VALID;
13724 				}
13725 			} else {
13726 				/*
13727 				 * Keep going even with NULL mp.
13728 				 * There may be a useful ACK or something else
13729 				 * we don't want to miss.
13730 				 *
13731 				 * But TCP should not perform fast retransmit
13732 				 * because of the ack number.  TCP uses
13733 				 * seg_len == 0 to determine if it is a pure
13734 				 * ACK.  And this is not a pure ACK.
13735 				 */
13736 				seg_len = 0;
13737 				ofo_seg = B_TRUE;
13738 			}
13739 		}
13740 	} else if (seg_len > 0) {
13741 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13742 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13743 		/*
13744 		 * If an out of order FIN was received before, and the seq
13745 		 * num and len of the new segment match that of the FIN,
13746 		 * put the FIN flag back in.
13747 		 */
13748 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13749 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13750 			flags |= TH_FIN;
13751 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13752 		}
13753 	}
13754 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13755 	if (flags & TH_RST) {
13756 		freemsg(mp);
13757 		switch (tcp->tcp_state) {
13758 		case TCPS_SYN_RCVD:
13759 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13760 			break;
13761 		case TCPS_ESTABLISHED:
13762 		case TCPS_FIN_WAIT_1:
13763 		case TCPS_FIN_WAIT_2:
13764 		case TCPS_CLOSE_WAIT:
13765 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13766 			break;
13767 		case TCPS_CLOSING:
13768 		case TCPS_LAST_ACK:
13769 			(void) tcp_clean_death(tcp, 0, 16);
13770 			break;
13771 		default:
13772 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13773 			(void) tcp_clean_death(tcp, ENXIO, 17);
13774 			break;
13775 		}
13776 		return;
13777 	}
13778 	if (flags & TH_SYN) {
13779 		/*
13780 		 * See RFC 793, Page 71
13781 		 *
13782 		 * The seq number must be in the window as it should
13783 		 * be "fixed" above.  If it is outside window, it should
13784 		 * be already rejected.  Note that we allow seg_seq to be
13785 		 * rnxt + rwnd because we want to accept 0 window probe.
13786 		 */
13787 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13788 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13789 		freemsg(mp);
13790 		/*
13791 		 * If the ACK flag is not set, just use our snxt as the
13792 		 * seq number of the RST segment.
13793 		 */
13794 		if (!(flags & TH_ACK)) {
13795 			seg_ack = tcp->tcp_snxt;
13796 		}
13797 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13798 		    TH_RST|TH_ACK);
13799 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13800 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13801 		return;
13802 	}
13803 	/*
13804 	 * urp could be -1 when the urp field in the packet is 0
13805 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13806 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13807 	 */
13808 	if (flags & TH_URG && urp >= 0) {
13809 		if (!tcp->tcp_urp_last_valid ||
13810 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13811 			if (IPCL_IS_NONSTR(connp)) {
13812 				if (!TCP_IS_DETACHED(tcp)) {
13813 					(*connp->conn_upcalls->su_signal_oob)
13814 					    (connp->conn_upper_handle, urp);
13815 				}
13816 			} else {
13817 				/*
13818 				 * If we haven't generated the signal yet for
13819 				 * this urgent pointer value, do it now.  Also,
13820 				 * send up a zero-length M_DATA indicating
13821 				 * whether or not this is the mark. The latter
13822 				 * is not needed when a T_EXDATA_IND is sent up.
13823 				 * However, if there are allocation failures
13824 				 * this code relies on the sender retransmitting
13825 				 * and the socket code for determining the mark
13826 				 * should not block waiting for the peer to
13827 				 * transmit. Thus, for simplicity we always
13828 				 * send up the mark indication.
13829 				 */
13830 				mp1 = allocb(0, BPRI_MED);
13831 				if (mp1 == NULL) {
13832 					freemsg(mp);
13833 					return;
13834 				}
13835 				if (!TCP_IS_DETACHED(tcp) &&
13836 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13837 				    SIGURG)) {
13838 					/* Try again on the rexmit. */
13839 					freemsg(mp1);
13840 					freemsg(mp);
13841 					return;
13842 				}
13843 				/*
13844 				 * Mark with NOTMARKNEXT for now.
13845 				 * The code below will change this to MARKNEXT
13846 				 * if we are at the mark.
13847 				 *
13848 				 * If there are allocation failures (e.g. in
13849 				 * dupmsg below) the next time tcp_rput_data
13850 				 * sees the urgent segment it will send up the
13851 				 * MSGMARKNEXT message.
13852 				 */
13853 				mp1->b_flag |= MSGNOTMARKNEXT;
13854 				freemsg(tcp->tcp_urp_mark_mp);
13855 				tcp->tcp_urp_mark_mp = mp1;
13856 				flags |= TH_SEND_URP_MARK;
13857 #ifdef DEBUG
13858 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13859 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13860 				    "last %x, %s",
13861 				    seg_seq, urp, tcp->tcp_urp_last,
13862 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13863 #endif /* DEBUG */
13864 			}
13865 			tcp->tcp_urp_last_valid = B_TRUE;
13866 			tcp->tcp_urp_last = urp + seg_seq;
13867 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13868 			/*
13869 			 * An allocation failure prevented the previous
13870 			 * tcp_rput_data from sending up the allocated
13871 			 * MSG*MARKNEXT message - send it up this time
13872 			 * around.
13873 			 */
13874 			flags |= TH_SEND_URP_MARK;
13875 		}
13876 
13877 		/*
13878 		 * If the urgent byte is in this segment, make sure that it is
13879 		 * all by itself.  This makes it much easier to deal with the
13880 		 * possibility of an allocation failure on the T_exdata_ind.
13881 		 * Note that seg_len is the number of bytes in the segment, and
13882 		 * urp is the offset into the segment of the urgent byte.
13883 		 * urp < seg_len means that the urgent byte is in this segment.
13884 		 */
13885 		if (urp < seg_len) {
13886 			if (seg_len != 1) {
13887 				uint32_t  tmp_rnxt;
13888 				/*
13889 				 * Break it up and feed it back in.
13890 				 * Re-attach the IP header.
13891 				 */
13892 				mp->b_rptr = iphdr;
13893 				if (urp > 0) {
13894 					/*
13895 					 * There is stuff before the urgent
13896 					 * byte.
13897 					 */
13898 					mp1 = dupmsg(mp);
13899 					if (!mp1) {
13900 						/*
13901 						 * Trim from urgent byte on.
13902 						 * The rest will come back.
13903 						 */
13904 						(void) adjmsg(mp,
13905 						    urp - seg_len);
13906 						tcp_rput_data(connp,
13907 						    mp, NULL);
13908 						return;
13909 					}
13910 					(void) adjmsg(mp1, urp - seg_len);
13911 					/* Feed this piece back in. */
13912 					tmp_rnxt = tcp->tcp_rnxt;
13913 					tcp_rput_data(connp, mp1, NULL);
13914 					/*
13915 					 * If the data passed back in was not
13916 					 * processed (ie: bad ACK) sending
13917 					 * the remainder back in will cause a
13918 					 * loop. In this case, drop the
13919 					 * packet and let the sender try
13920 					 * sending a good packet.
13921 					 */
13922 					if (tmp_rnxt == tcp->tcp_rnxt) {
13923 						freemsg(mp);
13924 						return;
13925 					}
13926 				}
13927 				if (urp != seg_len - 1) {
13928 					uint32_t  tmp_rnxt;
13929 					/*
13930 					 * There is stuff after the urgent
13931 					 * byte.
13932 					 */
13933 					mp1 = dupmsg(mp);
13934 					if (!mp1) {
13935 						/*
13936 						 * Trim everything beyond the
13937 						 * urgent byte.  The rest will
13938 						 * come back.
13939 						 */
13940 						(void) adjmsg(mp,
13941 						    urp + 1 - seg_len);
13942 						tcp_rput_data(connp,
13943 						    mp, NULL);
13944 						return;
13945 					}
13946 					(void) adjmsg(mp1, urp + 1 - seg_len);
13947 					tmp_rnxt = tcp->tcp_rnxt;
13948 					tcp_rput_data(connp, mp1, NULL);
13949 					/*
13950 					 * If the data passed back in was not
13951 					 * processed (ie: bad ACK) sending
13952 					 * the remainder back in will cause a
13953 					 * loop. In this case, drop the
13954 					 * packet and let the sender try
13955 					 * sending a good packet.
13956 					 */
13957 					if (tmp_rnxt == tcp->tcp_rnxt) {
13958 						freemsg(mp);
13959 						return;
13960 					}
13961 				}
13962 				tcp_rput_data(connp, mp, NULL);
13963 				return;
13964 			}
13965 			/*
13966 			 * This segment contains only the urgent byte.  We
13967 			 * have to allocate the T_exdata_ind, if we can.
13968 			 */
13969 			if (IPCL_IS_NONSTR(connp)) {
13970 				int error;
13971 
13972 				(*connp->conn_upcalls->su_recv)
13973 				    (connp->conn_upper_handle, mp, seg_len,
13974 				    MSG_OOB, &error, NULL);
13975 				/*
13976 				 * We should never be in middle of a
13977 				 * fallback, the squeue guarantees that.
13978 				 */
13979 				ASSERT(error != EOPNOTSUPP);
13980 				mp = NULL;
13981 				goto update_ack;
13982 			} else if (!tcp->tcp_urp_mp) {
13983 				struct T_exdata_ind *tei;
13984 				mp1 = allocb(sizeof (struct T_exdata_ind),
13985 				    BPRI_MED);
13986 				if (!mp1) {
13987 					/*
13988 					 * Sigh... It'll be back.
13989 					 * Generate any MSG*MARK message now.
13990 					 */
13991 					freemsg(mp);
13992 					seg_len = 0;
13993 					if (flags & TH_SEND_URP_MARK) {
13994 
13995 
13996 						ASSERT(tcp->tcp_urp_mark_mp);
13997 						tcp->tcp_urp_mark_mp->b_flag &=
13998 						    ~MSGNOTMARKNEXT;
13999 						tcp->tcp_urp_mark_mp->b_flag |=
14000 						    MSGMARKNEXT;
14001 					}
14002 					goto ack_check;
14003 				}
14004 				mp1->b_datap->db_type = M_PROTO;
14005 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14006 				tei->PRIM_type = T_EXDATA_IND;
14007 				tei->MORE_flag = 0;
14008 				mp1->b_wptr = (uchar_t *)&tei[1];
14009 				tcp->tcp_urp_mp = mp1;
14010 #ifdef DEBUG
14011 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14012 				    "tcp_rput: allocated exdata_ind %s",
14013 				    tcp_display(tcp, NULL,
14014 				    DISP_PORT_ONLY));
14015 #endif /* DEBUG */
14016 				/*
14017 				 * There is no need to send a separate MSG*MARK
14018 				 * message since the T_EXDATA_IND will be sent
14019 				 * now.
14020 				 */
14021 				flags &= ~TH_SEND_URP_MARK;
14022 				freemsg(tcp->tcp_urp_mark_mp);
14023 				tcp->tcp_urp_mark_mp = NULL;
14024 			}
14025 			/*
14026 			 * Now we are all set.  On the next putnext upstream,
14027 			 * tcp_urp_mp will be non-NULL and will get prepended
14028 			 * to what has to be this piece containing the urgent
14029 			 * byte.  If for any reason we abort this segment below,
14030 			 * if it comes back, we will have this ready, or it
14031 			 * will get blown off in close.
14032 			 */
14033 		} else if (urp == seg_len) {
14034 			/*
14035 			 * The urgent byte is the next byte after this sequence
14036 			 * number. If there is data it is marked with
14037 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14038 			 * since it is not needed. Otherwise, if the code
14039 			 * above just allocated a zero-length tcp_urp_mark_mp
14040 			 * message, that message is tagged with MSGMARKNEXT.
14041 			 * Sending up these MSGMARKNEXT messages makes
14042 			 * SIOCATMARK work correctly even though
14043 			 * the T_EXDATA_IND will not be sent up until the
14044 			 * urgent byte arrives.
14045 			 */
14046 			if (seg_len != 0) {
14047 				flags |= TH_MARKNEXT_NEEDED;
14048 				freemsg(tcp->tcp_urp_mark_mp);
14049 				tcp->tcp_urp_mark_mp = NULL;
14050 				flags &= ~TH_SEND_URP_MARK;
14051 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14052 				flags |= TH_SEND_URP_MARK;
14053 				tcp->tcp_urp_mark_mp->b_flag &=
14054 				    ~MSGNOTMARKNEXT;
14055 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14056 			}
14057 #ifdef DEBUG
14058 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14059 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14060 			    seg_len, flags,
14061 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14062 #endif /* DEBUG */
14063 		}
14064 #ifdef DEBUG
14065 		else {
14066 			/* Data left until we hit mark */
14067 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14068 			    "tcp_rput: URP %d bytes left, %s",
14069 			    urp - seg_len, tcp_display(tcp, NULL,
14070 			    DISP_PORT_ONLY));
14071 		}
14072 #endif /* DEBUG */
14073 	}
14074 
14075 process_ack:
14076 	if (!(flags & TH_ACK)) {
14077 		freemsg(mp);
14078 		goto xmit_check;
14079 	}
14080 	}
14081 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14082 
14083 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14084 		tcp->tcp_ip_forward_progress = B_TRUE;
14085 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14086 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
14087 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
14088 			/* 3-way handshake complete - pass up the T_CONN_IND */
14089 			tcp_t	*listener = tcp->tcp_listener;
14090 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14091 
14092 			tcp->tcp_tconnind_started = B_TRUE;
14093 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14094 			/*
14095 			 * We are here means eager is fine but it can
14096 			 * get a TH_RST at any point between now and till
14097 			 * accept completes and disappear. We need to
14098 			 * ensure that reference to eager is valid after
14099 			 * we get out of eager's perimeter. So we do
14100 			 * an extra refhold.
14101 			 */
14102 			CONN_INC_REF(connp);
14103 
14104 			/*
14105 			 * The listener also exists because of the refhold
14106 			 * done in tcp_conn_request. Its possible that it
14107 			 * might have closed. We will check that once we
14108 			 * get inside listeners context.
14109 			 */
14110 			CONN_INC_REF(listener->tcp_connp);
14111 			if (listener->tcp_connp->conn_sqp ==
14112 			    connp->conn_sqp) {
14113 				/*
14114 				 * We optimize by not calling an SQUEUE_ENTER
14115 				 * on the listener since we know that the
14116 				 * listener and eager squeues are the same.
14117 				 * We are able to make this check safely only
14118 				 * because neither the eager nor the listener
14119 				 * can change its squeue. Only an active connect
14120 				 * can change its squeue
14121 				 */
14122 				tcp_send_conn_ind(listener->tcp_connp, mp,
14123 				    listener->tcp_connp->conn_sqp);
14124 				CONN_DEC_REF(listener->tcp_connp);
14125 			} else if (!tcp->tcp_loopback) {
14126 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14127 				    mp, tcp_send_conn_ind,
14128 				    listener->tcp_connp, SQ_FILL,
14129 				    SQTAG_TCP_CONN_IND);
14130 			} else {
14131 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14132 				    mp, tcp_send_conn_ind,
14133 				    listener->tcp_connp, SQ_PROCESS,
14134 				    SQTAG_TCP_CONN_IND);
14135 			}
14136 		}
14137 
14138 		if (tcp->tcp_active_open) {
14139 			/*
14140 			 * We are seeing the final ack in the three way
14141 			 * hand shake of a active open'ed connection
14142 			 * so we must send up a T_CONN_CON
14143 			 */
14144 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14145 				freemsg(mp);
14146 				return;
14147 			}
14148 			/*
14149 			 * Don't fuse the loopback endpoints for
14150 			 * simultaneous active opens.
14151 			 */
14152 			if (tcp->tcp_loopback) {
14153 				TCP_STAT(tcps, tcp_fusion_unfusable);
14154 				tcp->tcp_unfusable = B_TRUE;
14155 			}
14156 		}
14157 
14158 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14159 		bytes_acked--;
14160 		/* SYN was acked - making progress */
14161 		if (tcp->tcp_ipversion == IPV6_VERSION)
14162 			tcp->tcp_ip_forward_progress = B_TRUE;
14163 
14164 		/*
14165 		 * If SYN was retransmitted, need to reset all
14166 		 * retransmission info as this segment will be
14167 		 * treated as a dup ACK.
14168 		 */
14169 		if (tcp->tcp_rexmit) {
14170 			tcp->tcp_rexmit = B_FALSE;
14171 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14172 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14173 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14174 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14175 			tcp->tcp_ms_we_have_waited = 0;
14176 			tcp->tcp_cwnd = mss;
14177 		}
14178 
14179 		/*
14180 		 * We set the send window to zero here.
14181 		 * This is needed if there is data to be
14182 		 * processed already on the queue.
14183 		 * Later (at swnd_update label), the
14184 		 * "new_swnd > tcp_swnd" condition is satisfied
14185 		 * the XMIT_NEEDED flag is set in the current
14186 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14187 		 * called if there is already data on queue in
14188 		 * this state.
14189 		 */
14190 		tcp->tcp_swnd = 0;
14191 
14192 		if (new_swnd > tcp->tcp_max_swnd)
14193 			tcp->tcp_max_swnd = new_swnd;
14194 		tcp->tcp_swl1 = seg_seq;
14195 		tcp->tcp_swl2 = seg_ack;
14196 		tcp->tcp_state = TCPS_ESTABLISHED;
14197 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14198 
14199 		/* Fuse when both sides are in ESTABLISHED state */
14200 		if (tcp->tcp_loopback && do_tcp_fusion)
14201 			tcp_fuse(tcp, iphdr, tcph);
14202 
14203 	}
14204 	/* This code follows 4.4BSD-Lite2 mostly. */
14205 	if (bytes_acked < 0)
14206 		goto est;
14207 
14208 	/*
14209 	 * If TCP is ECN capable and the congestion experience bit is
14210 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14211 	 * done once per window (or more loosely, per RTT).
14212 	 */
14213 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14214 		tcp->tcp_cwr = B_FALSE;
14215 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14216 		if (!tcp->tcp_cwr) {
14217 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14218 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14219 			tcp->tcp_cwnd = npkt * mss;
14220 			/*
14221 			 * If the cwnd is 0, use the timer to clock out
14222 			 * new segments.  This is required by the ECN spec.
14223 			 */
14224 			if (npkt == 0) {
14225 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14226 				/*
14227 				 * This makes sure that when the ACK comes
14228 				 * back, we will increase tcp_cwnd by 1 MSS.
14229 				 */
14230 				tcp->tcp_cwnd_cnt = 0;
14231 			}
14232 			tcp->tcp_cwr = B_TRUE;
14233 			/*
14234 			 * This marks the end of the current window of in
14235 			 * flight data.  That is why we don't use
14236 			 * tcp_suna + tcp_swnd.  Only data in flight can
14237 			 * provide ECN info.
14238 			 */
14239 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14240 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14241 		}
14242 	}
14243 
14244 	mp1 = tcp->tcp_xmit_head;
14245 	if (bytes_acked == 0) {
14246 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14247 			int dupack_cnt;
14248 
14249 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14250 			/*
14251 			 * Fast retransmit.  When we have seen exactly three
14252 			 * identical ACKs while we have unacked data
14253 			 * outstanding we take it as a hint that our peer
14254 			 * dropped something.
14255 			 *
14256 			 * If TCP is retransmitting, don't do fast retransmit.
14257 			 */
14258 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14259 			    ! tcp->tcp_rexmit) {
14260 				/* Do Limited Transmit */
14261 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14262 				    tcps->tcps_dupack_fast_retransmit) {
14263 					/*
14264 					 * RFC 3042
14265 					 *
14266 					 * What we need to do is temporarily
14267 					 * increase tcp_cwnd so that new
14268 					 * data can be sent if it is allowed
14269 					 * by the receive window (tcp_rwnd).
14270 					 * tcp_wput_data() will take care of
14271 					 * the rest.
14272 					 *
14273 					 * If the connection is SACK capable,
14274 					 * only do limited xmit when there
14275 					 * is SACK info.
14276 					 *
14277 					 * Note how tcp_cwnd is incremented.
14278 					 * The first dup ACK will increase
14279 					 * it by 1 MSS.  The second dup ACK
14280 					 * will increase it by 2 MSS.  This
14281 					 * means that only 1 new segment will
14282 					 * be sent for each dup ACK.
14283 					 */
14284 					if (tcp->tcp_unsent > 0 &&
14285 					    (!tcp->tcp_snd_sack_ok ||
14286 					    (tcp->tcp_snd_sack_ok &&
14287 					    tcp->tcp_notsack_list != NULL))) {
14288 						tcp->tcp_cwnd += mss <<
14289 						    (tcp->tcp_dupack_cnt - 1);
14290 						flags |= TH_LIMIT_XMIT;
14291 					}
14292 				} else if (dupack_cnt ==
14293 				    tcps->tcps_dupack_fast_retransmit) {
14294 
14295 				/*
14296 				 * If we have reduced tcp_ssthresh
14297 				 * because of ECN, do not reduce it again
14298 				 * unless it is already one window of data
14299 				 * away.  After one window of data, tcp_cwr
14300 				 * should then be cleared.  Note that
14301 				 * for non ECN capable connection, tcp_cwr
14302 				 * should always be false.
14303 				 *
14304 				 * Adjust cwnd since the duplicate
14305 				 * ack indicates that a packet was
14306 				 * dropped (due to congestion.)
14307 				 */
14308 				if (!tcp->tcp_cwr) {
14309 					npkt = ((tcp->tcp_snxt -
14310 					    tcp->tcp_suna) >> 1) / mss;
14311 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14312 					    mss;
14313 					tcp->tcp_cwnd = (npkt +
14314 					    tcp->tcp_dupack_cnt) * mss;
14315 				}
14316 				if (tcp->tcp_ecn_ok) {
14317 					tcp->tcp_cwr = B_TRUE;
14318 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14319 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14320 				}
14321 
14322 				/*
14323 				 * We do Hoe's algorithm.  Refer to her
14324 				 * paper "Improving the Start-up Behavior
14325 				 * of a Congestion Control Scheme for TCP,"
14326 				 * appeared in SIGCOMM'96.
14327 				 *
14328 				 * Save highest seq no we have sent so far.
14329 				 * Be careful about the invisible FIN byte.
14330 				 */
14331 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14332 				    (tcp->tcp_unsent == 0)) {
14333 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14334 				} else {
14335 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14336 				}
14337 
14338 				/*
14339 				 * Do not allow bursty traffic during.
14340 				 * fast recovery.  Refer to Fall and Floyd's
14341 				 * paper "Simulation-based Comparisons of
14342 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14343 				 * This is a best current practise.
14344 				 */
14345 				tcp->tcp_snd_burst = TCP_CWND_SS;
14346 
14347 				/*
14348 				 * For SACK:
14349 				 * Calculate tcp_pipe, which is the
14350 				 * estimated number of bytes in
14351 				 * network.
14352 				 *
14353 				 * tcp_fack is the highest sack'ed seq num
14354 				 * TCP has received.
14355 				 *
14356 				 * tcp_pipe is explained in the above quoted
14357 				 * Fall and Floyd's paper.  tcp_fack is
14358 				 * explained in Mathis and Mahdavi's
14359 				 * "Forward Acknowledgment: Refining TCP
14360 				 * Congestion Control" in SIGCOMM '96.
14361 				 */
14362 				if (tcp->tcp_snd_sack_ok) {
14363 					ASSERT(tcp->tcp_sack_info != NULL);
14364 					if (tcp->tcp_notsack_list != NULL) {
14365 						tcp->tcp_pipe = tcp->tcp_snxt -
14366 						    tcp->tcp_fack;
14367 						tcp->tcp_sack_snxt = seg_ack;
14368 						flags |= TH_NEED_SACK_REXMIT;
14369 					} else {
14370 						/*
14371 						 * Always initialize tcp_pipe
14372 						 * even though we don't have
14373 						 * any SACK info.  If later
14374 						 * we get SACK info and
14375 						 * tcp_pipe is not initialized,
14376 						 * funny things will happen.
14377 						 */
14378 						tcp->tcp_pipe =
14379 						    tcp->tcp_cwnd_ssthresh;
14380 					}
14381 				} else {
14382 					flags |= TH_REXMIT_NEEDED;
14383 				} /* tcp_snd_sack_ok */
14384 
14385 				} else {
14386 					/*
14387 					 * Here we perform congestion
14388 					 * avoidance, but NOT slow start.
14389 					 * This is known as the Fast
14390 					 * Recovery Algorithm.
14391 					 */
14392 					if (tcp->tcp_snd_sack_ok &&
14393 					    tcp->tcp_notsack_list != NULL) {
14394 						flags |= TH_NEED_SACK_REXMIT;
14395 						tcp->tcp_pipe -= mss;
14396 						if (tcp->tcp_pipe < 0)
14397 							tcp->tcp_pipe = 0;
14398 					} else {
14399 					/*
14400 					 * We know that one more packet has
14401 					 * left the pipe thus we can update
14402 					 * cwnd.
14403 					 */
14404 					cwnd = tcp->tcp_cwnd + mss;
14405 					if (cwnd > tcp->tcp_cwnd_max)
14406 						cwnd = tcp->tcp_cwnd_max;
14407 					tcp->tcp_cwnd = cwnd;
14408 					if (tcp->tcp_unsent > 0)
14409 						flags |= TH_XMIT_NEEDED;
14410 					}
14411 				}
14412 			}
14413 		} else if (tcp->tcp_zero_win_probe) {
14414 			/*
14415 			 * If the window has opened, need to arrange
14416 			 * to send additional data.
14417 			 */
14418 			if (new_swnd != 0) {
14419 				/* tcp_suna != tcp_snxt */
14420 				/* Packet contains a window update */
14421 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14422 				tcp->tcp_zero_win_probe = 0;
14423 				tcp->tcp_timer_backoff = 0;
14424 				tcp->tcp_ms_we_have_waited = 0;
14425 
14426 				/*
14427 				 * Transmit starting with tcp_suna since
14428 				 * the one byte probe is not ack'ed.
14429 				 * If TCP has sent more than one identical
14430 				 * probe, tcp_rexmit will be set.  That means
14431 				 * tcp_ss_rexmit() will send out the one
14432 				 * byte along with new data.  Otherwise,
14433 				 * fake the retransmission.
14434 				 */
14435 				flags |= TH_XMIT_NEEDED;
14436 				if (!tcp->tcp_rexmit) {
14437 					tcp->tcp_rexmit = B_TRUE;
14438 					tcp->tcp_dupack_cnt = 0;
14439 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14440 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14441 				}
14442 			}
14443 		}
14444 		goto swnd_update;
14445 	}
14446 
14447 	/*
14448 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14449 	 * If the ACK value acks something that we have not yet sent, it might
14450 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14451 	 * other side.
14452 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14453 	 * state is handled above, so we can always just drop the segment and
14454 	 * send an ACK here.
14455 	 *
14456 	 * Should we send ACKs in response to ACK only segments?
14457 	 */
14458 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14459 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14460 		/* drop the received segment */
14461 		freemsg(mp);
14462 
14463 		/*
14464 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14465 		 * greater than 0, check if the number of such
14466 		 * bogus ACks is greater than that count.  If yes,
14467 		 * don't send back any ACK.  This prevents TCP from
14468 		 * getting into an ACK storm if somehow an attacker
14469 		 * successfully spoofs an acceptable segment to our
14470 		 * peer.
14471 		 */
14472 		if (tcp_drop_ack_unsent_cnt > 0 &&
14473 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14474 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14475 			return;
14476 		}
14477 		mp = tcp_ack_mp(tcp);
14478 		if (mp != NULL) {
14479 			BUMP_LOCAL(tcp->tcp_obsegs);
14480 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14481 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14482 		}
14483 		return;
14484 	}
14485 
14486 	/*
14487 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14488 	 * blocks that are covered by this ACK.
14489 	 */
14490 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14491 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14492 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14493 	}
14494 
14495 	/*
14496 	 * If we got an ACK after fast retransmit, check to see
14497 	 * if it is a partial ACK.  If it is not and the congestion
14498 	 * window was inflated to account for the other side's
14499 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14500 	 */
14501 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14502 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14503 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14504 			tcp->tcp_dupack_cnt = 0;
14505 			/*
14506 			 * Restore the orig tcp_cwnd_ssthresh after
14507 			 * fast retransmit phase.
14508 			 */
14509 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14510 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14511 			}
14512 			tcp->tcp_rexmit_max = seg_ack;
14513 			tcp->tcp_cwnd_cnt = 0;
14514 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14515 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14516 
14517 			/*
14518 			 * Remove all notsack info to avoid confusion with
14519 			 * the next fast retrasnmit/recovery phase.
14520 			 */
14521 			if (tcp->tcp_snd_sack_ok &&
14522 			    tcp->tcp_notsack_list != NULL) {
14523 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14524 			}
14525 		} else {
14526 			if (tcp->tcp_snd_sack_ok &&
14527 			    tcp->tcp_notsack_list != NULL) {
14528 				flags |= TH_NEED_SACK_REXMIT;
14529 				tcp->tcp_pipe -= mss;
14530 				if (tcp->tcp_pipe < 0)
14531 					tcp->tcp_pipe = 0;
14532 			} else {
14533 				/*
14534 				 * Hoe's algorithm:
14535 				 *
14536 				 * Retransmit the unack'ed segment and
14537 				 * restart fast recovery.  Note that we
14538 				 * need to scale back tcp_cwnd to the
14539 				 * original value when we started fast
14540 				 * recovery.  This is to prevent overly
14541 				 * aggressive behaviour in sending new
14542 				 * segments.
14543 				 */
14544 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14545 				    tcps->tcps_dupack_fast_retransmit * mss;
14546 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14547 				flags |= TH_REXMIT_NEEDED;
14548 			}
14549 		}
14550 	} else {
14551 		tcp->tcp_dupack_cnt = 0;
14552 		if (tcp->tcp_rexmit) {
14553 			/*
14554 			 * TCP is retranmitting.  If the ACK ack's all
14555 			 * outstanding data, update tcp_rexmit_max and
14556 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14557 			 * to the correct value.
14558 			 *
14559 			 * Note that SEQ_LEQ() is used.  This is to avoid
14560 			 * unnecessary fast retransmit caused by dup ACKs
14561 			 * received when TCP does slow start retransmission
14562 			 * after a time out.  During this phase, TCP may
14563 			 * send out segments which are already received.
14564 			 * This causes dup ACKs to be sent back.
14565 			 */
14566 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14567 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14568 					tcp->tcp_rexmit_nxt = seg_ack;
14569 				}
14570 				if (seg_ack != tcp->tcp_rexmit_max) {
14571 					flags |= TH_XMIT_NEEDED;
14572 				}
14573 			} else {
14574 				tcp->tcp_rexmit = B_FALSE;
14575 				tcp->tcp_xmit_zc_clean = B_FALSE;
14576 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14577 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14578 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14579 			}
14580 			tcp->tcp_ms_we_have_waited = 0;
14581 		}
14582 	}
14583 
14584 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14585 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14586 	tcp->tcp_suna = seg_ack;
14587 	if (tcp->tcp_zero_win_probe != 0) {
14588 		tcp->tcp_zero_win_probe = 0;
14589 		tcp->tcp_timer_backoff = 0;
14590 	}
14591 
14592 	/*
14593 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14594 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14595 	 * will not reach here.
14596 	 */
14597 	if (mp1 == NULL) {
14598 		goto fin_acked;
14599 	}
14600 
14601 	/*
14602 	 * Update the congestion window.
14603 	 *
14604 	 * If TCP is not ECN capable or TCP is ECN capable but the
14605 	 * congestion experience bit is not set, increase the tcp_cwnd as
14606 	 * usual.
14607 	 */
14608 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14609 		cwnd = tcp->tcp_cwnd;
14610 		add = mss;
14611 
14612 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14613 			/*
14614 			 * This is to prevent an increase of less than 1 MSS of
14615 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14616 			 * may send out tinygrams in order to preserve mblk
14617 			 * boundaries.
14618 			 *
14619 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14620 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14621 			 * increased by 1 MSS for every RTTs.
14622 			 */
14623 			if (tcp->tcp_cwnd_cnt <= 0) {
14624 				tcp->tcp_cwnd_cnt = cwnd + add;
14625 			} else {
14626 				tcp->tcp_cwnd_cnt -= add;
14627 				add = 0;
14628 			}
14629 		}
14630 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14631 	}
14632 
14633 	/* See if the latest urgent data has been acknowledged */
14634 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14635 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14636 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14637 
14638 	/* Can we update the RTT estimates? */
14639 	if (tcp->tcp_snd_ts_ok) {
14640 		/* Ignore zero timestamp echo-reply. */
14641 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14642 			tcp_set_rto(tcp, (int32_t)lbolt -
14643 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14644 		}
14645 
14646 		/* If needed, restart the timer. */
14647 		if (tcp->tcp_set_timer == 1) {
14648 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14649 			tcp->tcp_set_timer = 0;
14650 		}
14651 		/*
14652 		 * Update tcp_csuna in case the other side stops sending
14653 		 * us timestamps.
14654 		 */
14655 		tcp->tcp_csuna = tcp->tcp_snxt;
14656 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14657 		/*
14658 		 * An ACK sequence we haven't seen before, so get the RTT
14659 		 * and update the RTO. But first check if the timestamp is
14660 		 * valid to use.
14661 		 */
14662 		if ((mp1->b_next != NULL) &&
14663 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14664 			tcp_set_rto(tcp, (int32_t)lbolt -
14665 			    (int32_t)(intptr_t)mp1->b_prev);
14666 		else
14667 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14668 
14669 		/* Remeber the last sequence to be ACKed */
14670 		tcp->tcp_csuna = seg_ack;
14671 		if (tcp->tcp_set_timer == 1) {
14672 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14673 			tcp->tcp_set_timer = 0;
14674 		}
14675 	} else {
14676 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14677 	}
14678 
14679 	/* Eat acknowledged bytes off the xmit queue. */
14680 	for (;;) {
14681 		mblk_t	*mp2;
14682 		uchar_t	*wptr;
14683 
14684 		wptr = mp1->b_wptr;
14685 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14686 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14687 		if (bytes_acked < 0) {
14688 			mp1->b_rptr = wptr + bytes_acked;
14689 			/*
14690 			 * Set a new timestamp if all the bytes timed by the
14691 			 * old timestamp have been ack'ed.
14692 			 */
14693 			if (SEQ_GT(seg_ack,
14694 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14695 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14696 				mp1->b_next = NULL;
14697 			}
14698 			break;
14699 		}
14700 		mp1->b_next = NULL;
14701 		mp1->b_prev = NULL;
14702 		mp2 = mp1;
14703 		mp1 = mp1->b_cont;
14704 
14705 		/*
14706 		 * This notification is required for some zero-copy
14707 		 * clients to maintain a copy semantic. After the data
14708 		 * is ack'ed, client is safe to modify or reuse the buffer.
14709 		 */
14710 		if (tcp->tcp_snd_zcopy_aware &&
14711 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14712 			tcp_zcopy_notify(tcp);
14713 		freeb(mp2);
14714 		if (bytes_acked == 0) {
14715 			if (mp1 == NULL) {
14716 				/* Everything is ack'ed, clear the tail. */
14717 				tcp->tcp_xmit_tail = NULL;
14718 				/*
14719 				 * Cancel the timer unless we are still
14720 				 * waiting for an ACK for the FIN packet.
14721 				 */
14722 				if (tcp->tcp_timer_tid != 0 &&
14723 				    tcp->tcp_snxt == tcp->tcp_suna) {
14724 					(void) TCP_TIMER_CANCEL(tcp,
14725 					    tcp->tcp_timer_tid);
14726 					tcp->tcp_timer_tid = 0;
14727 				}
14728 				goto pre_swnd_update;
14729 			}
14730 			if (mp2 != tcp->tcp_xmit_tail)
14731 				break;
14732 			tcp->tcp_xmit_tail = mp1;
14733 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14734 			    (uintptr_t)INT_MAX);
14735 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14736 			    mp1->b_rptr);
14737 			break;
14738 		}
14739 		if (mp1 == NULL) {
14740 			/*
14741 			 * More was acked but there is nothing more
14742 			 * outstanding.  This means that the FIN was
14743 			 * just acked or that we're talking to a clown.
14744 			 */
14745 fin_acked:
14746 			ASSERT(tcp->tcp_fin_sent);
14747 			tcp->tcp_xmit_tail = NULL;
14748 			if (tcp->tcp_fin_sent) {
14749 				/* FIN was acked - making progress */
14750 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14751 				    !tcp->tcp_fin_acked)
14752 					tcp->tcp_ip_forward_progress = B_TRUE;
14753 				tcp->tcp_fin_acked = B_TRUE;
14754 				if (tcp->tcp_linger_tid != 0 &&
14755 				    TCP_TIMER_CANCEL(tcp,
14756 				    tcp->tcp_linger_tid) >= 0) {
14757 					tcp_stop_lingering(tcp);
14758 					freemsg(mp);
14759 					mp = NULL;
14760 				}
14761 			} else {
14762 				/*
14763 				 * We should never get here because
14764 				 * we have already checked that the
14765 				 * number of bytes ack'ed should be
14766 				 * smaller than or equal to what we
14767 				 * have sent so far (it is the
14768 				 * acceptability check of the ACK).
14769 				 * We can only get here if the send
14770 				 * queue is corrupted.
14771 				 *
14772 				 * Terminate the connection and
14773 				 * panic the system.  It is better
14774 				 * for us to panic instead of
14775 				 * continuing to avoid other disaster.
14776 				 */
14777 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14778 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14779 				panic("Memory corruption "
14780 				    "detected for connection %s.",
14781 				    tcp_display(tcp, NULL,
14782 				    DISP_ADDR_AND_PORT));
14783 				/*NOTREACHED*/
14784 			}
14785 			goto pre_swnd_update;
14786 		}
14787 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14788 	}
14789 	if (tcp->tcp_unsent) {
14790 		flags |= TH_XMIT_NEEDED;
14791 	}
14792 pre_swnd_update:
14793 	tcp->tcp_xmit_head = mp1;
14794 swnd_update:
14795 	/*
14796 	 * The following check is different from most other implementations.
14797 	 * For bi-directional transfer, when segments are dropped, the
14798 	 * "normal" check will not accept a window update in those
14799 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14800 	 * segments which are outside receiver's window.  As TCP accepts
14801 	 * the ack in those retransmitted segments, if the window update in
14802 	 * the same segment is not accepted, TCP will incorrectly calculates
14803 	 * that it can send more segments.  This can create a deadlock
14804 	 * with the receiver if its window becomes zero.
14805 	 */
14806 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14807 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14808 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14809 		/*
14810 		 * The criteria for update is:
14811 		 *
14812 		 * 1. the segment acknowledges some data.  Or
14813 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14814 		 * 3. the segment is not old and the advertised window is
14815 		 * larger than the previous advertised window.
14816 		 */
14817 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14818 			flags |= TH_XMIT_NEEDED;
14819 		tcp->tcp_swnd = new_swnd;
14820 		if (new_swnd > tcp->tcp_max_swnd)
14821 			tcp->tcp_max_swnd = new_swnd;
14822 		tcp->tcp_swl1 = seg_seq;
14823 		tcp->tcp_swl2 = seg_ack;
14824 	}
14825 est:
14826 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14827 
14828 		switch (tcp->tcp_state) {
14829 		case TCPS_FIN_WAIT_1:
14830 			if (tcp->tcp_fin_acked) {
14831 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14832 				/*
14833 				 * We implement the non-standard BSD/SunOS
14834 				 * FIN_WAIT_2 flushing algorithm.
14835 				 * If there is no user attached to this
14836 				 * TCP endpoint, then this TCP struct
14837 				 * could hang around forever in FIN_WAIT_2
14838 				 * state if the peer forgets to send us
14839 				 * a FIN.  To prevent this, we wait only
14840 				 * 2*MSL (a convenient time value) for
14841 				 * the FIN to arrive.  If it doesn't show up,
14842 				 * we flush the TCP endpoint.  This algorithm,
14843 				 * though a violation of RFC-793, has worked
14844 				 * for over 10 years in BSD systems.
14845 				 * Note: SunOS 4.x waits 675 seconds before
14846 				 * flushing the FIN_WAIT_2 connection.
14847 				 */
14848 				TCP_TIMER_RESTART(tcp,
14849 				    tcps->tcps_fin_wait_2_flush_interval);
14850 			}
14851 			break;
14852 		case TCPS_FIN_WAIT_2:
14853 			break;	/* Shutdown hook? */
14854 		case TCPS_LAST_ACK:
14855 			freemsg(mp);
14856 			if (tcp->tcp_fin_acked) {
14857 				(void) tcp_clean_death(tcp, 0, 19);
14858 				return;
14859 			}
14860 			goto xmit_check;
14861 		case TCPS_CLOSING:
14862 			if (tcp->tcp_fin_acked) {
14863 				tcp->tcp_state = TCPS_TIME_WAIT;
14864 				/*
14865 				 * Unconditionally clear the exclusive binding
14866 				 * bit so this TIME-WAIT connection won't
14867 				 * interfere with new ones.
14868 				 */
14869 				tcp->tcp_exclbind = 0;
14870 				if (!TCP_IS_DETACHED(tcp)) {
14871 					TCP_TIMER_RESTART(tcp,
14872 					    tcps->tcps_time_wait_interval);
14873 				} else {
14874 					tcp_time_wait_append(tcp);
14875 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14876 				}
14877 			}
14878 			/*FALLTHRU*/
14879 		case TCPS_CLOSE_WAIT:
14880 			freemsg(mp);
14881 			goto xmit_check;
14882 		default:
14883 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14884 			break;
14885 		}
14886 	}
14887 	if (flags & TH_FIN) {
14888 		/* Make sure we ack the fin */
14889 		flags |= TH_ACK_NEEDED;
14890 		if (!tcp->tcp_fin_rcvd) {
14891 			tcp->tcp_fin_rcvd = B_TRUE;
14892 			tcp->tcp_rnxt++;
14893 			tcph = tcp->tcp_tcph;
14894 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14895 
14896 			/*
14897 			 * Generate the ordrel_ind at the end unless we
14898 			 * are an eager guy.
14899 			 * In the eager case tcp_rsrv will do this when run
14900 			 * after tcp_accept is done.
14901 			 */
14902 			if (tcp->tcp_listener == NULL &&
14903 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14904 				flags |= TH_ORDREL_NEEDED;
14905 			switch (tcp->tcp_state) {
14906 			case TCPS_SYN_RCVD:
14907 			case TCPS_ESTABLISHED:
14908 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14909 				/* Keepalive? */
14910 				break;
14911 			case TCPS_FIN_WAIT_1:
14912 				if (!tcp->tcp_fin_acked) {
14913 					tcp->tcp_state = TCPS_CLOSING;
14914 					break;
14915 				}
14916 				/* FALLTHRU */
14917 			case TCPS_FIN_WAIT_2:
14918 				tcp->tcp_state = TCPS_TIME_WAIT;
14919 				/*
14920 				 * Unconditionally clear the exclusive binding
14921 				 * bit so this TIME-WAIT connection won't
14922 				 * interfere with new ones.
14923 				 */
14924 				tcp->tcp_exclbind = 0;
14925 				if (!TCP_IS_DETACHED(tcp)) {
14926 					TCP_TIMER_RESTART(tcp,
14927 					    tcps->tcps_time_wait_interval);
14928 				} else {
14929 					tcp_time_wait_append(tcp);
14930 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14931 				}
14932 				if (seg_len) {
14933 					/*
14934 					 * implies data piggybacked on FIN.
14935 					 * break to handle data.
14936 					 */
14937 					break;
14938 				}
14939 				freemsg(mp);
14940 				goto ack_check;
14941 			}
14942 		}
14943 	}
14944 	if (mp == NULL)
14945 		goto xmit_check;
14946 	if (seg_len == 0) {
14947 		freemsg(mp);
14948 		goto xmit_check;
14949 	}
14950 	if (mp->b_rptr == mp->b_wptr) {
14951 		/*
14952 		 * The header has been consumed, so we remove the
14953 		 * zero-length mblk here.
14954 		 */
14955 		mp1 = mp;
14956 		mp = mp->b_cont;
14957 		freeb(mp1);
14958 	}
14959 update_ack:
14960 	tcph = tcp->tcp_tcph;
14961 	tcp->tcp_rack_cnt++;
14962 	{
14963 		uint32_t cur_max;
14964 
14965 		cur_max = tcp->tcp_rack_cur_max;
14966 		if (tcp->tcp_rack_cnt >= cur_max) {
14967 			/*
14968 			 * We have more unacked data than we should - send
14969 			 * an ACK now.
14970 			 */
14971 			flags |= TH_ACK_NEEDED;
14972 			cur_max++;
14973 			if (cur_max > tcp->tcp_rack_abs_max)
14974 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14975 			else
14976 				tcp->tcp_rack_cur_max = cur_max;
14977 		} else if (TCP_IS_DETACHED(tcp)) {
14978 			/* We don't have an ACK timer for detached TCP. */
14979 			flags |= TH_ACK_NEEDED;
14980 		} else if (seg_len < mss) {
14981 			/*
14982 			 * If we get a segment that is less than an mss, and we
14983 			 * already have unacknowledged data, and the amount
14984 			 * unacknowledged is not a multiple of mss, then we
14985 			 * better generate an ACK now.  Otherwise, this may be
14986 			 * the tail piece of a transaction, and we would rather
14987 			 * wait for the response.
14988 			 */
14989 			uint32_t udif;
14990 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14991 			    (uintptr_t)INT_MAX);
14992 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14993 			if (udif && (udif % mss))
14994 				flags |= TH_ACK_NEEDED;
14995 			else
14996 				flags |= TH_ACK_TIMER_NEEDED;
14997 		} else {
14998 			/* Start delayed ack timer */
14999 			flags |= TH_ACK_TIMER_NEEDED;
15000 		}
15001 	}
15002 	tcp->tcp_rnxt += seg_len;
15003 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15004 
15005 	if (mp == NULL)
15006 		goto xmit_check;
15007 
15008 	/* Update SACK list */
15009 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15010 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15011 		    &(tcp->tcp_num_sack_blk));
15012 	}
15013 
15014 	if (tcp->tcp_urp_mp) {
15015 		tcp->tcp_urp_mp->b_cont = mp;
15016 		mp = tcp->tcp_urp_mp;
15017 		tcp->tcp_urp_mp = NULL;
15018 		/* Ready for a new signal. */
15019 		tcp->tcp_urp_last_valid = B_FALSE;
15020 #ifdef DEBUG
15021 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15022 		    "tcp_rput: sending exdata_ind %s",
15023 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15024 #endif /* DEBUG */
15025 	}
15026 
15027 	/*
15028 	 * Check for ancillary data changes compared to last segment.
15029 	 */
15030 	if (tcp->tcp_ipv6_recvancillary != 0) {
15031 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15032 		ASSERT(mp != NULL);
15033 	}
15034 
15035 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15036 		/*
15037 		 * Side queue inbound data until the accept happens.
15038 		 * tcp_accept/tcp_rput drains this when the accept happens.
15039 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15040 		 * T_EXDATA_IND) it is queued on b_next.
15041 		 * XXX Make urgent data use this. Requires:
15042 		 *	Removing tcp_listener check for TH_URG
15043 		 *	Making M_PCPROTO and MARK messages skip the eager case
15044 		 */
15045 
15046 		if (tcp->tcp_kssl_pending) {
15047 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
15048 			    mblk_t *, mp);
15049 			tcp_kssl_input(tcp, mp);
15050 		} else {
15051 			tcp_rcv_enqueue(tcp, mp, seg_len);
15052 		}
15053 	} else {
15054 		sodirect_t	*sodp = tcp->tcp_sodirect;
15055 
15056 		/*
15057 		 * If an sodirect connection and an enabled sodirect_t then
15058 		 * sodp will be set to point to the tcp_t/sonode_t shared
15059 		 * sodirect_t and the sodirect_t's lock will be held.
15060 		 */
15061 		if (sodp != NULL) {
15062 			mutex_enter(sodp->sod_lockp);
15063 			if (!(sodp->sod_state & SOD_ENABLED) ||
15064 			    (tcp->tcp_kssl_ctx != NULL &&
15065 			    DB_TYPE(mp) == M_DATA)) {
15066 				mutex_exit(sodp->sod_lockp);
15067 				sodp = NULL;
15068 			} else {
15069 				mutex_exit(sodp->sod_lockp);
15070 			}
15071 		}
15072 		if (mp->b_datap->db_type != M_DATA ||
15073 		    (flags & TH_MARKNEXT_NEEDED)) {
15074 			if (IPCL_IS_NONSTR(connp)) {
15075 				int error;
15076 
15077 				if ((*connp->conn_upcalls->su_recv)
15078 				    (connp->conn_upper_handle, mp,
15079 				    seg_len, 0, &error, NULL) <= 0) {
15080 					/*
15081 					 * We should never be in middle of a
15082 					 * fallback, the squeue guarantees that.
15083 					 */
15084 					ASSERT(error != EOPNOTSUPP);
15085 					if (error == ENOSPC)
15086 						tcp->tcp_rwnd -= seg_len;
15087 				}
15088 			} else if (sodp != NULL) {
15089 				mutex_enter(sodp->sod_lockp);
15090 				SOD_UIOAFINI(sodp);
15091 				if (!SOD_QEMPTY(sodp) &&
15092 				    (sodp->sod_state & SOD_WAKE_NOT)) {
15093 					flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15094 					/* sod_wakeup() did the mutex_exit() */
15095 				} else {
15096 					mutex_exit(sodp->sod_lockp);
15097 				}
15098 			} else if (tcp->tcp_rcv_list != NULL) {
15099 				flags |= tcp_rcv_drain(tcp);
15100 			}
15101 			ASSERT(tcp->tcp_rcv_list == NULL ||
15102 			    tcp->tcp_fused_sigurg);
15103 
15104 			if (flags & TH_MARKNEXT_NEEDED) {
15105 #ifdef DEBUG
15106 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15107 				    "tcp_rput: sending MSGMARKNEXT %s",
15108 				    tcp_display(tcp, NULL,
15109 				    DISP_PORT_ONLY));
15110 #endif /* DEBUG */
15111 				mp->b_flag |= MSGMARKNEXT;
15112 				flags &= ~TH_MARKNEXT_NEEDED;
15113 			}
15114 
15115 			/* Does this need SSL processing first? */
15116 			if ((tcp->tcp_kssl_ctx != NULL) &&
15117 			    (DB_TYPE(mp) == M_DATA)) {
15118 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15119 				    mblk_t *, mp);
15120 				tcp_kssl_input(tcp, mp);
15121 			} else if (!IPCL_IS_NONSTR(connp)) {
15122 				/* Already handled non-STREAMS case. */
15123 				putnext(tcp->tcp_rq, mp);
15124 				if (!canputnext(tcp->tcp_rq))
15125 					tcp->tcp_rwnd -= seg_len;
15126 			}
15127 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15128 		    (DB_TYPE(mp) == M_DATA)) {
15129 			/* Does this need SSL processing first? */
15130 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
15131 			tcp_kssl_input(tcp, mp);
15132 		} else if (IPCL_IS_NONSTR(connp)) {
15133 			/* Non-STREAMS socket */
15134 			boolean_t push = flags & (TH_PUSH|TH_FIN);
15135 			int	error;
15136 
15137 			if ((*connp->conn_upcalls->su_recv)(
15138 			    connp->conn_upper_handle,
15139 			    mp, seg_len, 0, &error, &push) <= 0) {
15140 				/*
15141 				 * We should never be in middle of a
15142 				 * fallback, the squeue guarantees that.
15143 				 */
15144 				ASSERT(error != EOPNOTSUPP);
15145 				if (error == ENOSPC)
15146 					tcp->tcp_rwnd -= seg_len;
15147 			} else if (push) {
15148 				/*
15149 				 * PUSH bit set and sockfs is not
15150 				 * flow controlled
15151 				 */
15152 				flags |= tcp_rwnd_reopen(tcp);
15153 			}
15154 		} else if (sodp != NULL) {
15155 			/*
15156 			 * Sodirect so all mblk_t's are queued on the
15157 			 * socket directly, check for wakeup of blocked
15158 			 * reader (if any), and last if flow-controled.
15159 			 */
15160 			mutex_enter(sodp->sod_lockp);
15161 			flags |= tcp_rcv_sod_enqueue(tcp, sodp, mp, seg_len);
15162 			if ((sodp->sod_state & SOD_WAKE_NEED) ||
15163 			    (flags & (TH_PUSH|TH_FIN))) {
15164 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15165 				/* sod_wakeup() did the mutex_exit() */
15166 			} else {
15167 				if (SOD_QFULL(sodp)) {
15168 					/* Q is full, need backenable */
15169 					SOD_QSETBE(sodp);
15170 				}
15171 				mutex_exit(sodp->sod_lockp);
15172 			}
15173 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15174 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_recv_hiwater >> 3) {
15175 			if (tcp->tcp_rcv_list != NULL) {
15176 				/*
15177 				 * Enqueue the new segment first and then
15178 				 * call tcp_rcv_drain() to send all data
15179 				 * up.  The other way to do this is to
15180 				 * send all queued data up and then call
15181 				 * putnext() to send the new segment up.
15182 				 * This way can remove the else part later
15183 				 * on.
15184 				 *
15185 				 * We don't do this to avoid one more call to
15186 				 * canputnext() as tcp_rcv_drain() needs to
15187 				 * call canputnext().
15188 				 */
15189 				tcp_rcv_enqueue(tcp, mp, seg_len);
15190 				flags |= tcp_rcv_drain(tcp);
15191 			} else {
15192 				putnext(tcp->tcp_rq, mp);
15193 				if (!canputnext(tcp->tcp_rq))
15194 					tcp->tcp_rwnd -= seg_len;
15195 			}
15196 		} else {
15197 			/*
15198 			 * Enqueue all packets when processing an mblk
15199 			 * from the co queue and also enqueue normal packets.
15200 			 * For packets which belong to SSL stream do SSL
15201 			 * processing first.
15202 			 */
15203 			tcp_rcv_enqueue(tcp, mp, seg_len);
15204 		}
15205 		/*
15206 		 * Make sure the timer is running if we have data waiting
15207 		 * for a push bit. This provides resiliency against
15208 		 * implementations that do not correctly generate push bits.
15209 		 *
15210 		 * Note, for sodirect if Q isn't empty and there's not a
15211 		 * pending wakeup then we need a timer. Also note that sodp
15212 		 * is assumed to be still valid after exit()ing the sod_lockp
15213 		 * above and while the SOD state can change it can only change
15214 		 * such that the Q is empty now even though data was added
15215 		 * above.
15216 		 */
15217 		if (!IPCL_IS_NONSTR(connp) &&
15218 		    ((sodp != NULL && !SOD_QEMPTY(sodp) &&
15219 		    (sodp->sod_state & SOD_WAKE_NOT)) ||
15220 		    (sodp == NULL && tcp->tcp_rcv_list != NULL)) &&
15221 		    tcp->tcp_push_tid == 0) {
15222 			/*
15223 			 * The connection may be closed at this point, so don't
15224 			 * do anything for a detached tcp.
15225 			 */
15226 			if (!TCP_IS_DETACHED(tcp))
15227 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15228 				    tcp_push_timer,
15229 				    MSEC_TO_TICK(
15230 				    tcps->tcps_push_timer_interval));
15231 		}
15232 	}
15233 
15234 xmit_check:
15235 	/* Is there anything left to do? */
15236 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15237 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15238 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15239 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15240 		goto done;
15241 
15242 	/* Any transmit work to do and a non-zero window? */
15243 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15244 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15245 		if (flags & TH_REXMIT_NEEDED) {
15246 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15247 
15248 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15249 			if (snd_size > mss)
15250 				snd_size = mss;
15251 			if (snd_size > tcp->tcp_swnd)
15252 				snd_size = tcp->tcp_swnd;
15253 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15254 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15255 			    B_TRUE);
15256 
15257 			if (mp1 != NULL) {
15258 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15259 				tcp->tcp_csuna = tcp->tcp_snxt;
15260 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15261 				UPDATE_MIB(&tcps->tcps_mib,
15262 				    tcpRetransBytes, snd_size);
15263 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15264 			}
15265 		}
15266 		if (flags & TH_NEED_SACK_REXMIT) {
15267 			tcp_sack_rxmit(tcp, &flags);
15268 		}
15269 		/*
15270 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15271 		 * out new segment.  Note that tcp_rexmit should not be
15272 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15273 		 */
15274 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15275 			if (!tcp->tcp_rexmit) {
15276 				tcp_wput_data(tcp, NULL, B_FALSE);
15277 			} else {
15278 				tcp_ss_rexmit(tcp);
15279 			}
15280 		}
15281 		/*
15282 		 * Adjust tcp_cwnd back to normal value after sending
15283 		 * new data segments.
15284 		 */
15285 		if (flags & TH_LIMIT_XMIT) {
15286 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15287 			/*
15288 			 * This will restart the timer.  Restarting the
15289 			 * timer is used to avoid a timeout before the
15290 			 * limited transmitted segment's ACK gets back.
15291 			 */
15292 			if (tcp->tcp_xmit_head != NULL)
15293 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15294 		}
15295 
15296 		/* Anything more to do? */
15297 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15298 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15299 			goto done;
15300 	}
15301 ack_check:
15302 	if (flags & TH_SEND_URP_MARK) {
15303 		ASSERT(tcp->tcp_urp_mark_mp);
15304 		ASSERT(!IPCL_IS_NONSTR(connp));
15305 		/*
15306 		 * Send up any queued data and then send the mark message
15307 		 */
15308 		sodirect_t *sodp;
15309 
15310 		SOD_PTR_ENTER(tcp, sodp);
15311 
15312 		mp1 = tcp->tcp_urp_mark_mp;
15313 		tcp->tcp_urp_mark_mp = NULL;
15314 		if (sodp != NULL) {
15315 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15316 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15317 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15318 			}
15319 			ASSERT(tcp->tcp_rcv_list == NULL);
15320 
15321 			flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15322 			/* sod_wakeup() does the mutex_exit() */
15323 		} else if (tcp->tcp_rcv_list != NULL) {
15324 			flags |= tcp_rcv_drain(tcp);
15325 
15326 			ASSERT(tcp->tcp_rcv_list == NULL ||
15327 			    tcp->tcp_fused_sigurg);
15328 
15329 		}
15330 		putnext(tcp->tcp_rq, mp1);
15331 #ifdef DEBUG
15332 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15333 		    "tcp_rput: sending zero-length %s %s",
15334 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15335 		    "MSGNOTMARKNEXT"),
15336 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15337 #endif /* DEBUG */
15338 		flags &= ~TH_SEND_URP_MARK;
15339 	}
15340 	if (flags & TH_ACK_NEEDED) {
15341 		/*
15342 		 * Time to send an ack for some reason.
15343 		 */
15344 		mp1 = tcp_ack_mp(tcp);
15345 
15346 		if (mp1 != NULL) {
15347 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15348 			BUMP_LOCAL(tcp->tcp_obsegs);
15349 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15350 		}
15351 		if (tcp->tcp_ack_tid != 0) {
15352 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15353 			tcp->tcp_ack_tid = 0;
15354 		}
15355 	}
15356 	if (flags & TH_ACK_TIMER_NEEDED) {
15357 		/*
15358 		 * Arrange for deferred ACK or push wait timeout.
15359 		 * Start timer if it is not already running.
15360 		 */
15361 		if (tcp->tcp_ack_tid == 0) {
15362 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15363 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15364 			    (clock_t)tcps->tcps_local_dack_interval :
15365 			    (clock_t)tcps->tcps_deferred_ack_interval));
15366 		}
15367 	}
15368 	if (flags & TH_ORDREL_NEEDED) {
15369 		/*
15370 		 * Send up the ordrel_ind unless we are an eager guy.
15371 		 * In the eager case tcp_rsrv will do this when run
15372 		 * after tcp_accept is done.
15373 		 */
15374 		sodirect_t *sodp;
15375 
15376 		ASSERT(tcp->tcp_listener == NULL);
15377 
15378 		if (IPCL_IS_NONSTR(connp)) {
15379 			ASSERT(tcp->tcp_ordrel_mp == NULL);
15380 			tcp->tcp_ordrel_done = B_TRUE;
15381 			(*connp->conn_upcalls->su_opctl)
15382 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
15383 			goto done;
15384 		}
15385 
15386 		SOD_PTR_ENTER(tcp, sodp);
15387 		if (sodp != NULL) {
15388 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15389 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15390 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15391 			}
15392 			/* No more sodirect */
15393 			tcp->tcp_sodirect = NULL;
15394 			if (!SOD_QEMPTY(sodp)) {
15395 				/* Mblk(s) to process, notify */
15396 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15397 				/* sod_wakeup() does the mutex_exit() */
15398 			} else {
15399 				/* Nothing to process */
15400 				mutex_exit(sodp->sod_lockp);
15401 			}
15402 		} else if (tcp->tcp_rcv_list != NULL) {
15403 			/*
15404 			 * Push any mblk(s) enqueued from co processing.
15405 			 */
15406 			flags |= tcp_rcv_drain(tcp);
15407 
15408 			ASSERT(tcp->tcp_rcv_list == NULL ||
15409 			    tcp->tcp_fused_sigurg);
15410 		}
15411 
15412 		mp1 = tcp->tcp_ordrel_mp;
15413 		tcp->tcp_ordrel_mp = NULL;
15414 		tcp->tcp_ordrel_done = B_TRUE;
15415 		putnext(tcp->tcp_rq, mp1);
15416 	}
15417 done:
15418 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15419 }
15420 
15421 /*
15422  * This function does PAWS protection check. Returns B_TRUE if the
15423  * segment passes the PAWS test, else returns B_FALSE.
15424  */
15425 boolean_t
15426 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15427 {
15428 	uint8_t	flags;
15429 	int	options;
15430 	uint8_t *up;
15431 
15432 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15433 	/*
15434 	 * If timestamp option is aligned nicely, get values inline,
15435 	 * otherwise call general routine to parse.  Only do that
15436 	 * if timestamp is the only option.
15437 	 */
15438 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15439 	    TCPOPT_REAL_TS_LEN &&
15440 	    OK_32PTR((up = ((uint8_t *)tcph) +
15441 	    TCP_MIN_HEADER_LENGTH)) &&
15442 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15443 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15444 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15445 
15446 		options = TCP_OPT_TSTAMP_PRESENT;
15447 	} else {
15448 		if (tcp->tcp_snd_sack_ok) {
15449 			tcpoptp->tcp = tcp;
15450 		} else {
15451 			tcpoptp->tcp = NULL;
15452 		}
15453 		options = tcp_parse_options(tcph, tcpoptp);
15454 	}
15455 
15456 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15457 		/*
15458 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15459 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15460 		 */
15461 		if ((flags & TH_RST) == 0 &&
15462 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15463 		    tcp->tcp_ts_recent)) {
15464 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15465 			    PAWS_TIMEOUT)) {
15466 				/* This segment is not acceptable. */
15467 				return (B_FALSE);
15468 			} else {
15469 				/*
15470 				 * Connection has been idle for
15471 				 * too long.  Reset the timestamp
15472 				 * and assume the segment is valid.
15473 				 */
15474 				tcp->tcp_ts_recent =
15475 				    tcpoptp->tcp_opt_ts_val;
15476 			}
15477 		}
15478 	} else {
15479 		/*
15480 		 * If we don't get a timestamp on every packet, we
15481 		 * figure we can't really trust 'em, so we stop sending
15482 		 * and parsing them.
15483 		 */
15484 		tcp->tcp_snd_ts_ok = B_FALSE;
15485 
15486 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15487 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15488 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15489 		/*
15490 		 * Adjust the tcp_mss accordingly. We also need to
15491 		 * adjust tcp_cwnd here in accordance with the new mss.
15492 		 * But we avoid doing a slow start here so as to not
15493 		 * to lose on the transfer rate built up so far.
15494 		 */
15495 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15496 		if (tcp->tcp_snd_sack_ok) {
15497 			ASSERT(tcp->tcp_sack_info != NULL);
15498 			tcp->tcp_max_sack_blk = 4;
15499 		}
15500 	}
15501 	return (B_TRUE);
15502 }
15503 
15504 /*
15505  * Attach ancillary data to a received TCP segments for the
15506  * ancillary pieces requested by the application that are
15507  * different than they were in the previous data segment.
15508  *
15509  * Save the "current" values once memory allocation is ok so that
15510  * when memory allocation fails we can just wait for the next data segment.
15511  */
15512 static mblk_t *
15513 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15514 {
15515 	struct T_optdata_ind *todi;
15516 	int optlen;
15517 	uchar_t *optptr;
15518 	struct T_opthdr *toh;
15519 	uint_t addflag;	/* Which pieces to add */
15520 	mblk_t *mp1;
15521 
15522 	optlen = 0;
15523 	addflag = 0;
15524 	/* If app asked for pktinfo and the index has changed ... */
15525 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15526 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15527 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15528 		optlen += sizeof (struct T_opthdr) +
15529 		    sizeof (struct in6_pktinfo);
15530 		addflag |= TCP_IPV6_RECVPKTINFO;
15531 	}
15532 	/* If app asked for hoplimit and it has changed ... */
15533 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15534 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15535 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15536 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15537 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15538 	}
15539 	/* If app asked for tclass and it has changed ... */
15540 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15541 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15542 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15543 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15544 		addflag |= TCP_IPV6_RECVTCLASS;
15545 	}
15546 	/*
15547 	 * If app asked for hopbyhop headers and it has changed ...
15548 	 * For security labels, note that (1) security labels can't change on
15549 	 * a connected socket at all, (2) we're connected to at most one peer,
15550 	 * (3) if anything changes, then it must be some other extra option.
15551 	 */
15552 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15553 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15554 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15555 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15556 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15557 		    tcp->tcp_label_len;
15558 		addflag |= TCP_IPV6_RECVHOPOPTS;
15559 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15560 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15561 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15562 			return (mp);
15563 	}
15564 	/* If app asked for dst headers before routing headers ... */
15565 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15566 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15567 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15568 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15569 		optlen += sizeof (struct T_opthdr) +
15570 		    ipp->ipp_rtdstoptslen;
15571 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15572 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15573 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15574 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15575 			return (mp);
15576 	}
15577 	/* If app asked for routing headers and it has changed ... */
15578 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15579 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15580 	    (ipp->ipp_fields & IPPF_RTHDR),
15581 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15582 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15583 		addflag |= TCP_IPV6_RECVRTHDR;
15584 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15585 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15586 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15587 			return (mp);
15588 	}
15589 	/* If app asked for dest headers and it has changed ... */
15590 	if ((tcp->tcp_ipv6_recvancillary &
15591 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15592 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15593 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15594 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15595 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15596 		addflag |= TCP_IPV6_RECVDSTOPTS;
15597 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15598 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15599 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15600 			return (mp);
15601 	}
15602 
15603 	if (optlen == 0) {
15604 		/* Nothing to add */
15605 		return (mp);
15606 	}
15607 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15608 	if (mp1 == NULL) {
15609 		/*
15610 		 * Defer sending ancillary data until the next TCP segment
15611 		 * arrives.
15612 		 */
15613 		return (mp);
15614 	}
15615 	mp1->b_cont = mp;
15616 	mp = mp1;
15617 	mp->b_wptr += sizeof (*todi) + optlen;
15618 	mp->b_datap->db_type = M_PROTO;
15619 	todi = (struct T_optdata_ind *)mp->b_rptr;
15620 	todi->PRIM_type = T_OPTDATA_IND;
15621 	todi->DATA_flag = 1;	/* MORE data */
15622 	todi->OPT_length = optlen;
15623 	todi->OPT_offset = sizeof (*todi);
15624 	optptr = (uchar_t *)&todi[1];
15625 	/*
15626 	 * If app asked for pktinfo and the index has changed ...
15627 	 * Note that the local address never changes for the connection.
15628 	 */
15629 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15630 		struct in6_pktinfo *pkti;
15631 
15632 		toh = (struct T_opthdr *)optptr;
15633 		toh->level = IPPROTO_IPV6;
15634 		toh->name = IPV6_PKTINFO;
15635 		toh->len = sizeof (*toh) + sizeof (*pkti);
15636 		toh->status = 0;
15637 		optptr += sizeof (*toh);
15638 		pkti = (struct in6_pktinfo *)optptr;
15639 		if (tcp->tcp_ipversion == IPV6_VERSION)
15640 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15641 		else
15642 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15643 			    &pkti->ipi6_addr);
15644 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15645 		optptr += sizeof (*pkti);
15646 		ASSERT(OK_32PTR(optptr));
15647 		/* Save as "last" value */
15648 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15649 	}
15650 	/* If app asked for hoplimit and it has changed ... */
15651 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15652 		toh = (struct T_opthdr *)optptr;
15653 		toh->level = IPPROTO_IPV6;
15654 		toh->name = IPV6_HOPLIMIT;
15655 		toh->len = sizeof (*toh) + sizeof (uint_t);
15656 		toh->status = 0;
15657 		optptr += sizeof (*toh);
15658 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15659 		optptr += sizeof (uint_t);
15660 		ASSERT(OK_32PTR(optptr));
15661 		/* Save as "last" value */
15662 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15663 	}
15664 	/* If app asked for tclass and it has changed ... */
15665 	if (addflag & TCP_IPV6_RECVTCLASS) {
15666 		toh = (struct T_opthdr *)optptr;
15667 		toh->level = IPPROTO_IPV6;
15668 		toh->name = IPV6_TCLASS;
15669 		toh->len = sizeof (*toh) + sizeof (uint_t);
15670 		toh->status = 0;
15671 		optptr += sizeof (*toh);
15672 		*(uint_t *)optptr = ipp->ipp_tclass;
15673 		optptr += sizeof (uint_t);
15674 		ASSERT(OK_32PTR(optptr));
15675 		/* Save as "last" value */
15676 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15677 	}
15678 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15679 		toh = (struct T_opthdr *)optptr;
15680 		toh->level = IPPROTO_IPV6;
15681 		toh->name = IPV6_HOPOPTS;
15682 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15683 		    tcp->tcp_label_len;
15684 		toh->status = 0;
15685 		optptr += sizeof (*toh);
15686 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15687 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15688 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15689 		ASSERT(OK_32PTR(optptr));
15690 		/* Save as last value */
15691 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15692 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15693 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15694 	}
15695 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15696 		toh = (struct T_opthdr *)optptr;
15697 		toh->level = IPPROTO_IPV6;
15698 		toh->name = IPV6_RTHDRDSTOPTS;
15699 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15700 		toh->status = 0;
15701 		optptr += sizeof (*toh);
15702 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15703 		optptr += ipp->ipp_rtdstoptslen;
15704 		ASSERT(OK_32PTR(optptr));
15705 		/* Save as last value */
15706 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15707 		    &tcp->tcp_rtdstoptslen,
15708 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15709 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15710 	}
15711 	if (addflag & TCP_IPV6_RECVRTHDR) {
15712 		toh = (struct T_opthdr *)optptr;
15713 		toh->level = IPPROTO_IPV6;
15714 		toh->name = IPV6_RTHDR;
15715 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15716 		toh->status = 0;
15717 		optptr += sizeof (*toh);
15718 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15719 		optptr += ipp->ipp_rthdrlen;
15720 		ASSERT(OK_32PTR(optptr));
15721 		/* Save as last value */
15722 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15723 		    (ipp->ipp_fields & IPPF_RTHDR),
15724 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15725 	}
15726 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15727 		toh = (struct T_opthdr *)optptr;
15728 		toh->level = IPPROTO_IPV6;
15729 		toh->name = IPV6_DSTOPTS;
15730 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15731 		toh->status = 0;
15732 		optptr += sizeof (*toh);
15733 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15734 		optptr += ipp->ipp_dstoptslen;
15735 		ASSERT(OK_32PTR(optptr));
15736 		/* Save as last value */
15737 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15738 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15739 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15740 	}
15741 	ASSERT(optptr == mp->b_wptr);
15742 	return (mp);
15743 }
15744 
15745 /*
15746  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15747  * messages.
15748  */
15749 void
15750 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15751 {
15752 	uchar_t	*rptr = mp->b_rptr;
15753 	queue_t	*q = tcp->tcp_rq;
15754 	struct T_error_ack *tea;
15755 
15756 	switch (mp->b_datap->db_type) {
15757 	case M_PROTO:
15758 	case M_PCPROTO:
15759 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15760 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15761 			break;
15762 		tea = (struct T_error_ack *)rptr;
15763 		ASSERT(tea->PRIM_type != T_BIND_ACK);
15764 		ASSERT(tea->ERROR_prim != O_T_BIND_REQ &&
15765 		    tea->ERROR_prim != T_BIND_REQ);
15766 		switch (tea->PRIM_type) {
15767 		case T_ERROR_ACK:
15768 			if (tcp->tcp_debug) {
15769 				(void) strlog(TCP_MOD_ID, 0, 1,
15770 				    SL_TRACE|SL_ERROR,
15771 				    "tcp_rput_other: case T_ERROR_ACK, "
15772 				    "ERROR_prim == %d",
15773 				    tea->ERROR_prim);
15774 			}
15775 			switch (tea->ERROR_prim) {
15776 			case T_SVR4_OPTMGMT_REQ:
15777 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15778 					/* T_OPTMGMT_REQ generated by TCP */
15779 					printf("T_SVR4_OPTMGMT_REQ failed "
15780 					    "%d/%d - dropped (cnt %d)\n",
15781 					    tea->TLI_error, tea->UNIX_error,
15782 					    tcp->tcp_drop_opt_ack_cnt);
15783 					freemsg(mp);
15784 					tcp->tcp_drop_opt_ack_cnt--;
15785 					return;
15786 				}
15787 				break;
15788 			}
15789 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15790 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15791 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15792 				    "- dropped (cnt %d)\n",
15793 				    tea->TLI_error, tea->UNIX_error,
15794 				    tcp->tcp_drop_opt_ack_cnt);
15795 				freemsg(mp);
15796 				tcp->tcp_drop_opt_ack_cnt--;
15797 				return;
15798 			}
15799 			break;
15800 		case T_OPTMGMT_ACK:
15801 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15802 				/* T_OPTMGMT_REQ generated by TCP */
15803 				freemsg(mp);
15804 				tcp->tcp_drop_opt_ack_cnt--;
15805 				return;
15806 			}
15807 			break;
15808 		default:
15809 			ASSERT(tea->ERROR_prim != T_UNBIND_REQ);
15810 			break;
15811 		}
15812 		break;
15813 	case M_FLUSH:
15814 		if (*rptr & FLUSHR)
15815 			flushq(q, FLUSHDATA);
15816 		break;
15817 	default:
15818 		/* M_CTL will be directly sent to tcp_icmp_error() */
15819 		ASSERT(DB_TYPE(mp) != M_CTL);
15820 		break;
15821 	}
15822 	/*
15823 	 * Make sure we set this bit before sending the ACK for
15824 	 * bind. Otherwise accept could possibly run and free
15825 	 * this tcp struct.
15826 	 */
15827 	ASSERT(q != NULL);
15828 	putnext(q, mp);
15829 }
15830 
15831 /* ARGSUSED */
15832 static void
15833 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15834 {
15835 	conn_t	*connp = (conn_t *)arg;
15836 	tcp_t	*tcp = connp->conn_tcp;
15837 	queue_t	*q = tcp->tcp_rq;
15838 	uint_t	thwin;
15839 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15840 	sodirect_t	*sodp;
15841 	boolean_t	fc;
15842 
15843 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15844 	tcp->tcp_rsrv_mp = mp;
15845 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15846 
15847 	TCP_STAT(tcps, tcp_rsrv_calls);
15848 
15849 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15850 		return;
15851 	}
15852 
15853 	if (tcp->tcp_fused) {
15854 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15855 
15856 		ASSERT(tcp->tcp_fused);
15857 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15858 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15859 		ASSERT(!TCP_IS_DETACHED(tcp));
15860 		ASSERT(tcp->tcp_connp->conn_sqp ==
15861 		    peer_tcp->tcp_connp->conn_sqp);
15862 
15863 		/*
15864 		 * Normally we would not get backenabled in synchronous
15865 		 * streams mode, but in case this happens, we need to plug
15866 		 * synchronous streams during our drain to prevent a race
15867 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
15868 		 */
15869 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
15870 		if (tcp->tcp_rcv_list != NULL)
15871 			(void) tcp_rcv_drain(tcp);
15872 
15873 		if (peer_tcp > tcp) {
15874 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15875 			mutex_enter(&tcp->tcp_non_sq_lock);
15876 		} else {
15877 			mutex_enter(&tcp->tcp_non_sq_lock);
15878 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15879 		}
15880 
15881 		if (peer_tcp->tcp_flow_stopped &&
15882 		    (TCP_UNSENT_BYTES(peer_tcp) <=
15883 		    peer_tcp->tcp_xmit_lowater)) {
15884 			tcp_clrqfull(peer_tcp);
15885 		}
15886 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
15887 		mutex_exit(&tcp->tcp_non_sq_lock);
15888 
15889 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
15890 		TCP_STAT(tcps, tcp_fusion_backenabled);
15891 		return;
15892 	}
15893 
15894 	SOD_PTR_ENTER(tcp, sodp);
15895 	if (sodp != NULL) {
15896 		/* An sodirect connection */
15897 		if (SOD_QFULL(sodp)) {
15898 			/* Flow-controlled, need another back-enable */
15899 			fc = B_TRUE;
15900 			SOD_QSETBE(sodp);
15901 		} else {
15902 			/* Not flow-controlled */
15903 			fc = B_FALSE;
15904 		}
15905 		mutex_exit(sodp->sod_lockp);
15906 	} else if (canputnext(q)) {
15907 		/* STREAMS, not flow-controlled */
15908 		fc = B_FALSE;
15909 	} else {
15910 		/* STREAMS, flow-controlled */
15911 		fc = B_TRUE;
15912 	}
15913 	if (!fc) {
15914 		/* Not flow-controlled, open rwnd */
15915 		tcp->tcp_rwnd = q->q_hiwat;
15916 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15917 		    << tcp->tcp_rcv_ws;
15918 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15919 		/*
15920 		 * Send back a window update immediately if TCP is above
15921 		 * ESTABLISHED state and the increase of the rcv window
15922 		 * that the other side knows is at least 1 MSS after flow
15923 		 * control is lifted.
15924 		 */
15925 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15926 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15927 			tcp_xmit_ctl(NULL, tcp,
15928 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15929 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15930 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
15931 		}
15932 	}
15933 }
15934 
15935 /*
15936  * The read side service routine is called mostly when we get back-enabled as a
15937  * result of flow control relief.  Since we don't actually queue anything in
15938  * TCP, we have no data to send out of here.  What we do is clear the receive
15939  * window, and send out a window update.
15940  */
15941 static void
15942 tcp_rsrv(queue_t *q)
15943 {
15944 	conn_t		*connp = Q_TO_CONN(q);
15945 	tcp_t		*tcp = connp->conn_tcp;
15946 	mblk_t		*mp;
15947 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15948 
15949 	/* No code does a putq on the read side */
15950 	ASSERT(q->q_first == NULL);
15951 
15952 	/* Nothing to do for the default queue */
15953 	if (q == tcps->tcps_g_q) {
15954 		return;
15955 	}
15956 
15957 	/*
15958 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
15959 	 * been run.  So just return.
15960 	 */
15961 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15962 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
15963 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
15964 		return;
15965 	}
15966 	tcp->tcp_rsrv_mp = NULL;
15967 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15968 
15969 	CONN_INC_REF(connp);
15970 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15971 	    SQ_PROCESS, SQTAG_TCP_RSRV);
15972 }
15973 
15974 /*
15975  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15976  * We do not allow the receive window to shrink.  After setting rwnd,
15977  * set the flow control hiwat of the stream.
15978  *
15979  * This function is called in 2 cases:
15980  *
15981  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15982  *    connection (passive open) and in tcp_rput_data() for active connect.
15983  *    This is called after tcp_mss_set() when the desired MSS value is known.
15984  *    This makes sure that our window size is a mutiple of the other side's
15985  *    MSS.
15986  * 2) Handling SO_RCVBUF option.
15987  *
15988  * It is ASSUMED that the requested size is a multiple of the current MSS.
15989  *
15990  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15991  * user requests so.
15992  */
15993 static int
15994 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15995 {
15996 	uint32_t	mss = tcp->tcp_mss;
15997 	uint32_t	old_max_rwnd;
15998 	uint32_t	max_transmittable_rwnd;
15999 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16000 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16001 
16002 	if (tcp->tcp_fused) {
16003 		size_t sth_hiwat;
16004 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16005 
16006 		ASSERT(peer_tcp != NULL);
16007 		/*
16008 		 * Record the stream head's high water mark for
16009 		 * this endpoint; this is used for flow-control
16010 		 * purposes in tcp_fuse_output().
16011 		 */
16012 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16013 		if (!tcp_detached) {
16014 			(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
16015 			    sth_hiwat);
16016 			if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
16017 				conn_t *connp = tcp->tcp_connp;
16018 				struct sock_proto_props sopp;
16019 
16020 				sopp.sopp_flags = SOCKOPT_RCVTHRESH;
16021 				sopp.sopp_rcvthresh = sth_hiwat >> 3;
16022 
16023 				(*connp->conn_upcalls->su_set_proto_props)
16024 				    (connp->conn_upper_handle, &sopp);
16025 			}
16026 		}
16027 
16028 		/*
16029 		 * In the fusion case, the maxpsz stream head value of
16030 		 * our peer is set according to its send buffer size
16031 		 * and our receive buffer size; since the latter may
16032 		 * have changed we need to update the peer's maxpsz.
16033 		 */
16034 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16035 		return (rwnd);
16036 	}
16037 
16038 	if (tcp_detached) {
16039 		old_max_rwnd = tcp->tcp_rwnd;
16040 	} else {
16041 		old_max_rwnd = tcp->tcp_recv_hiwater;
16042 	}
16043 
16044 	/*
16045 	 * Insist on a receive window that is at least
16046 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16047 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16048 	 * and delayed acknowledgement.
16049 	 */
16050 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16051 
16052 	/*
16053 	 * If window size info has already been exchanged, TCP should not
16054 	 * shrink the window.  Shrinking window is doable if done carefully.
16055 	 * We may add that support later.  But so far there is not a real
16056 	 * need to do that.
16057 	 */
16058 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16059 		/* MSS may have changed, do a round up again. */
16060 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16061 	}
16062 
16063 	/*
16064 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16065 	 * can be applied even before the window scale option is decided.
16066 	 */
16067 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16068 	if (rwnd > max_transmittable_rwnd) {
16069 		rwnd = max_transmittable_rwnd -
16070 		    (max_transmittable_rwnd % mss);
16071 		if (rwnd < mss)
16072 			rwnd = max_transmittable_rwnd;
16073 		/*
16074 		 * If we're over the limit we may have to back down tcp_rwnd.
16075 		 * The increment below won't work for us. So we set all three
16076 		 * here and the increment below will have no effect.
16077 		 */
16078 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16079 	}
16080 	if (tcp->tcp_localnet) {
16081 		tcp->tcp_rack_abs_max =
16082 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16083 	} else {
16084 		/*
16085 		 * For a remote host on a different subnet (through a router),
16086 		 * we ack every other packet to be conforming to RFC1122.
16087 		 * tcp_deferred_acks_max is default to 2.
16088 		 */
16089 		tcp->tcp_rack_abs_max =
16090 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16091 	}
16092 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16093 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16094 	else
16095 		tcp->tcp_rack_cur_max = 0;
16096 	/*
16097 	 * Increment the current rwnd by the amount the maximum grew (we
16098 	 * can not overwrite it since we might be in the middle of a
16099 	 * connection.)
16100 	 */
16101 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16102 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16103 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16104 		tcp->tcp_cwnd_max = rwnd;
16105 
16106 	if (tcp_detached)
16107 		return (rwnd);
16108 	/*
16109 	 * We set the maximum receive window into rq->q_hiwat if it is
16110 	 * a STREAMS socket.
16111 	 * This is not actually used for flow control.
16112 	 */
16113 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
16114 		tcp->tcp_rq->q_hiwat = rwnd;
16115 	tcp->tcp_recv_hiwater = rwnd;
16116 	/*
16117 	 * Set the STREAM head high water mark. This doesn't have to be
16118 	 * here, since we are simply using default values, but we would
16119 	 * prefer to choose these values algorithmically, with a likely
16120 	 * relationship to rwnd.
16121 	 */
16122 	(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
16123 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16124 	return (rwnd);
16125 }
16126 
16127 /*
16128  * Return SNMP stuff in buffer in mpdata.
16129  */
16130 mblk_t *
16131 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16132 {
16133 	mblk_t			*mpdata;
16134 	mblk_t			*mp_conn_ctl = NULL;
16135 	mblk_t			*mp_conn_tail;
16136 	mblk_t			*mp_attr_ctl = NULL;
16137 	mblk_t			*mp_attr_tail;
16138 	mblk_t			*mp6_conn_ctl = NULL;
16139 	mblk_t			*mp6_conn_tail;
16140 	mblk_t			*mp6_attr_ctl = NULL;
16141 	mblk_t			*mp6_attr_tail;
16142 	struct opthdr		*optp;
16143 	mib2_tcpConnEntry_t	tce;
16144 	mib2_tcp6ConnEntry_t	tce6;
16145 	mib2_transportMLPEntry_t mlp;
16146 	connf_t			*connfp;
16147 	int			i;
16148 	boolean_t 		ispriv;
16149 	zoneid_t 		zoneid;
16150 	int			v4_conn_idx;
16151 	int			v6_conn_idx;
16152 	conn_t			*connp = Q_TO_CONN(q);
16153 	tcp_stack_t		*tcps;
16154 	ip_stack_t		*ipst;
16155 	mblk_t			*mp2ctl;
16156 
16157 	/*
16158 	 * make a copy of the original message
16159 	 */
16160 	mp2ctl = copymsg(mpctl);
16161 
16162 	if (mpctl == NULL ||
16163 	    (mpdata = mpctl->b_cont) == NULL ||
16164 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16165 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16166 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16167 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16168 		freemsg(mp_conn_ctl);
16169 		freemsg(mp_attr_ctl);
16170 		freemsg(mp6_conn_ctl);
16171 		freemsg(mp6_attr_ctl);
16172 		freemsg(mpctl);
16173 		freemsg(mp2ctl);
16174 		return (NULL);
16175 	}
16176 
16177 	ipst = connp->conn_netstack->netstack_ip;
16178 	tcps = connp->conn_netstack->netstack_tcp;
16179 
16180 	/* build table of connections -- need count in fixed part */
16181 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16182 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16183 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16184 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16185 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16186 
16187 	ispriv =
16188 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16189 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16190 
16191 	v4_conn_idx = v6_conn_idx = 0;
16192 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16193 
16194 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16195 		ipst = tcps->tcps_netstack->netstack_ip;
16196 
16197 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16198 
16199 		connp = NULL;
16200 
16201 		while ((connp =
16202 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16203 			tcp_t *tcp;
16204 			boolean_t needattr;
16205 
16206 			if (connp->conn_zoneid != zoneid)
16207 				continue;	/* not in this zone */
16208 
16209 			tcp = connp->conn_tcp;
16210 			UPDATE_MIB(&tcps->tcps_mib,
16211 			    tcpHCInSegs, tcp->tcp_ibsegs);
16212 			tcp->tcp_ibsegs = 0;
16213 			UPDATE_MIB(&tcps->tcps_mib,
16214 			    tcpHCOutSegs, tcp->tcp_obsegs);
16215 			tcp->tcp_obsegs = 0;
16216 
16217 			tce6.tcp6ConnState = tce.tcpConnState =
16218 			    tcp_snmp_state(tcp);
16219 			if (tce.tcpConnState == MIB2_TCP_established ||
16220 			    tce.tcpConnState == MIB2_TCP_closeWait)
16221 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16222 
16223 			needattr = B_FALSE;
16224 			bzero(&mlp, sizeof (mlp));
16225 			if (connp->conn_mlp_type != mlptSingle) {
16226 				if (connp->conn_mlp_type == mlptShared ||
16227 				    connp->conn_mlp_type == mlptBoth)
16228 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16229 				if (connp->conn_mlp_type == mlptPrivate ||
16230 				    connp->conn_mlp_type == mlptBoth)
16231 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16232 				needattr = B_TRUE;
16233 			}
16234 			if (connp->conn_peercred != NULL) {
16235 				ts_label_t *tsl;
16236 
16237 				tsl = crgetlabel(connp->conn_peercred);
16238 				mlp.tme_doi = label2doi(tsl);
16239 				mlp.tme_label = *label2bslabel(tsl);
16240 				needattr = B_TRUE;
16241 			}
16242 
16243 			/* Create a message to report on IPv6 entries */
16244 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16245 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16246 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16247 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16248 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16249 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16250 			/* Don't want just anybody seeing these... */
16251 			if (ispriv) {
16252 				tce6.tcp6ConnEntryInfo.ce_snxt =
16253 				    tcp->tcp_snxt;
16254 				tce6.tcp6ConnEntryInfo.ce_suna =
16255 				    tcp->tcp_suna;
16256 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16257 				    tcp->tcp_rnxt;
16258 				tce6.tcp6ConnEntryInfo.ce_rack =
16259 				    tcp->tcp_rack;
16260 			} else {
16261 				/*
16262 				 * Netstat, unfortunately, uses this to
16263 				 * get send/receive queue sizes.  How to fix?
16264 				 * Why not compute the difference only?
16265 				 */
16266 				tce6.tcp6ConnEntryInfo.ce_snxt =
16267 				    tcp->tcp_snxt - tcp->tcp_suna;
16268 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16269 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16270 				    tcp->tcp_rnxt - tcp->tcp_rack;
16271 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16272 			}
16273 
16274 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16275 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16276 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16277 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16278 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16279 
16280 			tce6.tcp6ConnCreationProcess =
16281 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16282 			    tcp->tcp_cpid;
16283 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16284 
16285 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16286 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16287 
16288 			mlp.tme_connidx = v6_conn_idx++;
16289 			if (needattr)
16290 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16291 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16292 			}
16293 			/*
16294 			 * Create an IPv4 table entry for IPv4 entries and also
16295 			 * for IPv6 entries which are bound to in6addr_any
16296 			 * but don't have IPV6_V6ONLY set.
16297 			 * (i.e. anything an IPv4 peer could connect to)
16298 			 */
16299 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16300 			    (tcp->tcp_state <= TCPS_LISTEN &&
16301 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16302 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16303 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16304 					tce.tcpConnRemAddress = INADDR_ANY;
16305 					tce.tcpConnLocalAddress = INADDR_ANY;
16306 				} else {
16307 					tce.tcpConnRemAddress =
16308 					    tcp->tcp_remote;
16309 					tce.tcpConnLocalAddress =
16310 					    tcp->tcp_ip_src;
16311 				}
16312 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16313 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16314 				/* Don't want just anybody seeing these... */
16315 				if (ispriv) {
16316 					tce.tcpConnEntryInfo.ce_snxt =
16317 					    tcp->tcp_snxt;
16318 					tce.tcpConnEntryInfo.ce_suna =
16319 					    tcp->tcp_suna;
16320 					tce.tcpConnEntryInfo.ce_rnxt =
16321 					    tcp->tcp_rnxt;
16322 					tce.tcpConnEntryInfo.ce_rack =
16323 					    tcp->tcp_rack;
16324 				} else {
16325 					/*
16326 					 * Netstat, unfortunately, uses this to
16327 					 * get send/receive queue sizes.  How
16328 					 * to fix?
16329 					 * Why not compute the difference only?
16330 					 */
16331 					tce.tcpConnEntryInfo.ce_snxt =
16332 					    tcp->tcp_snxt - tcp->tcp_suna;
16333 					tce.tcpConnEntryInfo.ce_suna = 0;
16334 					tce.tcpConnEntryInfo.ce_rnxt =
16335 					    tcp->tcp_rnxt - tcp->tcp_rack;
16336 					tce.tcpConnEntryInfo.ce_rack = 0;
16337 				}
16338 
16339 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16340 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16341 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16342 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16343 				tce.tcpConnEntryInfo.ce_state =
16344 				    tcp->tcp_state;
16345 
16346 				tce.tcpConnCreationProcess =
16347 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16348 				    tcp->tcp_cpid;
16349 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16350 
16351 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16352 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16353 
16354 				mlp.tme_connidx = v4_conn_idx++;
16355 				if (needattr)
16356 					(void) snmp_append_data2(
16357 					    mp_attr_ctl->b_cont,
16358 					    &mp_attr_tail, (char *)&mlp,
16359 					    sizeof (mlp));
16360 			}
16361 		}
16362 	}
16363 
16364 	/* fixed length structure for IPv4 and IPv6 counters */
16365 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16366 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16367 	    sizeof (mib2_tcp6ConnEntry_t));
16368 	/* synchronize 32- and 64-bit counters */
16369 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16370 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16371 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16372 	optp->level = MIB2_TCP;
16373 	optp->name = 0;
16374 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16375 	    sizeof (tcps->tcps_mib));
16376 	optp->len = msgdsize(mpdata);
16377 	qreply(q, mpctl);
16378 
16379 	/* table of connections... */
16380 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16381 	    sizeof (struct T_optmgmt_ack)];
16382 	optp->level = MIB2_TCP;
16383 	optp->name = MIB2_TCP_CONN;
16384 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16385 	qreply(q, mp_conn_ctl);
16386 
16387 	/* table of MLP attributes... */
16388 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16389 	    sizeof (struct T_optmgmt_ack)];
16390 	optp->level = MIB2_TCP;
16391 	optp->name = EXPER_XPORT_MLP;
16392 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16393 	if (optp->len == 0)
16394 		freemsg(mp_attr_ctl);
16395 	else
16396 		qreply(q, mp_attr_ctl);
16397 
16398 	/* table of IPv6 connections... */
16399 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16400 	    sizeof (struct T_optmgmt_ack)];
16401 	optp->level = MIB2_TCP6;
16402 	optp->name = MIB2_TCP6_CONN;
16403 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16404 	qreply(q, mp6_conn_ctl);
16405 
16406 	/* table of IPv6 MLP attributes... */
16407 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16408 	    sizeof (struct T_optmgmt_ack)];
16409 	optp->level = MIB2_TCP6;
16410 	optp->name = EXPER_XPORT_MLP;
16411 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16412 	if (optp->len == 0)
16413 		freemsg(mp6_attr_ctl);
16414 	else
16415 		qreply(q, mp6_attr_ctl);
16416 	return (mp2ctl);
16417 }
16418 
16419 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16420 /* ARGSUSED */
16421 int
16422 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16423 {
16424 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16425 
16426 	switch (level) {
16427 	case MIB2_TCP:
16428 		switch (name) {
16429 		case 13:
16430 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16431 				return (0);
16432 			/* TODO: delete entry defined by tce */
16433 			return (1);
16434 		default:
16435 			return (0);
16436 		}
16437 	default:
16438 		return (1);
16439 	}
16440 }
16441 
16442 /* Translate TCP state to MIB2 TCP state. */
16443 static int
16444 tcp_snmp_state(tcp_t *tcp)
16445 {
16446 	if (tcp == NULL)
16447 		return (0);
16448 
16449 	switch (tcp->tcp_state) {
16450 	case TCPS_CLOSED:
16451 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16452 	case TCPS_BOUND:
16453 		return (MIB2_TCP_closed);
16454 	case TCPS_LISTEN:
16455 		return (MIB2_TCP_listen);
16456 	case TCPS_SYN_SENT:
16457 		return (MIB2_TCP_synSent);
16458 	case TCPS_SYN_RCVD:
16459 		return (MIB2_TCP_synReceived);
16460 	case TCPS_ESTABLISHED:
16461 		return (MIB2_TCP_established);
16462 	case TCPS_CLOSE_WAIT:
16463 		return (MIB2_TCP_closeWait);
16464 	case TCPS_FIN_WAIT_1:
16465 		return (MIB2_TCP_finWait1);
16466 	case TCPS_CLOSING:
16467 		return (MIB2_TCP_closing);
16468 	case TCPS_LAST_ACK:
16469 		return (MIB2_TCP_lastAck);
16470 	case TCPS_FIN_WAIT_2:
16471 		return (MIB2_TCP_finWait2);
16472 	case TCPS_TIME_WAIT:
16473 		return (MIB2_TCP_timeWait);
16474 	default:
16475 		return (0);
16476 	}
16477 }
16478 
16479 /*
16480  * tcp_timer is the timer service routine.  It handles the retransmission,
16481  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16482  * from the state of the tcp instance what kind of action needs to be done
16483  * at the time it is called.
16484  */
16485 static void
16486 tcp_timer(void *arg)
16487 {
16488 	mblk_t		*mp;
16489 	clock_t		first_threshold;
16490 	clock_t		second_threshold;
16491 	clock_t		ms;
16492 	uint32_t	mss;
16493 	conn_t		*connp = (conn_t *)arg;
16494 	tcp_t		*tcp = connp->conn_tcp;
16495 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16496 
16497 	tcp->tcp_timer_tid = 0;
16498 
16499 	if (tcp->tcp_fused)
16500 		return;
16501 
16502 	first_threshold =  tcp->tcp_first_timer_threshold;
16503 	second_threshold = tcp->tcp_second_timer_threshold;
16504 	switch (tcp->tcp_state) {
16505 	case TCPS_IDLE:
16506 	case TCPS_BOUND:
16507 	case TCPS_LISTEN:
16508 		return;
16509 	case TCPS_SYN_RCVD: {
16510 		tcp_t	*listener = tcp->tcp_listener;
16511 
16512 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16513 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16514 			/* it's our first timeout */
16515 			tcp->tcp_syn_rcvd_timeout = 1;
16516 			mutex_enter(&listener->tcp_eager_lock);
16517 			listener->tcp_syn_rcvd_timeout++;
16518 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16519 				/*
16520 				 * Make this eager available for drop if we
16521 				 * need to drop one to accomodate a new
16522 				 * incoming SYN request.
16523 				 */
16524 				MAKE_DROPPABLE(listener, tcp);
16525 			}
16526 			if (!listener->tcp_syn_defense &&
16527 			    (listener->tcp_syn_rcvd_timeout >
16528 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
16529 			    (tcps->tcps_conn_req_max_q0 > 200)) {
16530 				/* We may be under attack. Put on a defense. */
16531 				listener->tcp_syn_defense = B_TRUE;
16532 				cmn_err(CE_WARN, "High TCP connect timeout "
16533 				    "rate! System (port %d) may be under a "
16534 				    "SYN flood attack!",
16535 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16536 
16537 				listener->tcp_ip_addr_cache = kmem_zalloc(
16538 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16539 				    KM_NOSLEEP);
16540 			}
16541 			mutex_exit(&listener->tcp_eager_lock);
16542 		} else if (listener != NULL) {
16543 			mutex_enter(&listener->tcp_eager_lock);
16544 			tcp->tcp_syn_rcvd_timeout++;
16545 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
16546 			    !tcp->tcp_closemp_used) {
16547 				/*
16548 				 * This is our second timeout. Put the tcp in
16549 				 * the list of droppable eagers to allow it to
16550 				 * be dropped, if needed. We don't check
16551 				 * whether tcp_dontdrop is set or not to
16552 				 * protect ourselve from a SYN attack where a
16553 				 * remote host can spoof itself as one of the
16554 				 * good IP source and continue to hold
16555 				 * resources too long.
16556 				 */
16557 				MAKE_DROPPABLE(listener, tcp);
16558 			}
16559 			mutex_exit(&listener->tcp_eager_lock);
16560 		}
16561 	}
16562 		/* FALLTHRU */
16563 	case TCPS_SYN_SENT:
16564 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16565 		second_threshold = tcp->tcp_second_ctimer_threshold;
16566 		break;
16567 	case TCPS_ESTABLISHED:
16568 	case TCPS_FIN_WAIT_1:
16569 	case TCPS_CLOSING:
16570 	case TCPS_CLOSE_WAIT:
16571 	case TCPS_LAST_ACK:
16572 		/* If we have data to rexmit */
16573 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16574 			clock_t	time_to_wait;
16575 
16576 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
16577 			if (!tcp->tcp_xmit_head)
16578 				break;
16579 			time_to_wait = lbolt -
16580 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16581 			time_to_wait = tcp->tcp_rto -
16582 			    TICK_TO_MSEC(time_to_wait);
16583 			/*
16584 			 * If the timer fires too early, 1 clock tick earlier,
16585 			 * restart the timer.
16586 			 */
16587 			if (time_to_wait > msec_per_tick) {
16588 				TCP_STAT(tcps, tcp_timer_fire_early);
16589 				TCP_TIMER_RESTART(tcp, time_to_wait);
16590 				return;
16591 			}
16592 			/*
16593 			 * When we probe zero windows, we force the swnd open.
16594 			 * If our peer acks with a closed window swnd will be
16595 			 * set to zero by tcp_rput(). As long as we are
16596 			 * receiving acks tcp_rput will
16597 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16598 			 * first and second interval actions.  NOTE: the timer
16599 			 * interval is allowed to continue its exponential
16600 			 * backoff.
16601 			 */
16602 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16603 				if (tcp->tcp_debug) {
16604 					(void) strlog(TCP_MOD_ID, 0, 1,
16605 					    SL_TRACE, "tcp_timer: zero win");
16606 				}
16607 			} else {
16608 				/*
16609 				 * After retransmission, we need to do
16610 				 * slow start.  Set the ssthresh to one
16611 				 * half of current effective window and
16612 				 * cwnd to one MSS.  Also reset
16613 				 * tcp_cwnd_cnt.
16614 				 *
16615 				 * Note that if tcp_ssthresh is reduced because
16616 				 * of ECN, do not reduce it again unless it is
16617 				 * already one window of data away (tcp_cwr
16618 				 * should then be cleared) or this is a
16619 				 * timeout for a retransmitted segment.
16620 				 */
16621 				uint32_t npkt;
16622 
16623 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16624 					npkt = ((tcp->tcp_timer_backoff ?
16625 					    tcp->tcp_cwnd_ssthresh :
16626 					    tcp->tcp_snxt -
16627 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16628 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16629 					    tcp->tcp_mss;
16630 				}
16631 				tcp->tcp_cwnd = tcp->tcp_mss;
16632 				tcp->tcp_cwnd_cnt = 0;
16633 				if (tcp->tcp_ecn_ok) {
16634 					tcp->tcp_cwr = B_TRUE;
16635 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16636 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16637 				}
16638 			}
16639 			break;
16640 		}
16641 		/*
16642 		 * We have something to send yet we cannot send.  The
16643 		 * reason can be:
16644 		 *
16645 		 * 1. Zero send window: we need to do zero window probe.
16646 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16647 		 * segments.
16648 		 * 3. SWS avoidance: receiver may have shrunk window,
16649 		 * reset our knowledge.
16650 		 *
16651 		 * Note that condition 2 can happen with either 1 or
16652 		 * 3.  But 1 and 3 are exclusive.
16653 		 */
16654 		if (tcp->tcp_unsent != 0) {
16655 			if (tcp->tcp_cwnd == 0) {
16656 				/*
16657 				 * Set tcp_cwnd to 1 MSS so that a
16658 				 * new segment can be sent out.  We
16659 				 * are "clocking out" new data when
16660 				 * the network is really congested.
16661 				 */
16662 				ASSERT(tcp->tcp_ecn_ok);
16663 				tcp->tcp_cwnd = tcp->tcp_mss;
16664 			}
16665 			if (tcp->tcp_swnd == 0) {
16666 				/* Extend window for zero window probe */
16667 				tcp->tcp_swnd++;
16668 				tcp->tcp_zero_win_probe = B_TRUE;
16669 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
16670 			} else {
16671 				/*
16672 				 * Handle timeout from sender SWS avoidance.
16673 				 * Reset our knowledge of the max send window
16674 				 * since the receiver might have reduced its
16675 				 * receive buffer.  Avoid setting tcp_max_swnd
16676 				 * to one since that will essentially disable
16677 				 * the SWS checks.
16678 				 *
16679 				 * Note that since we don't have a SWS
16680 				 * state variable, if the timeout is set
16681 				 * for ECN but not for SWS, this
16682 				 * code will also be executed.  This is
16683 				 * fine as tcp_max_swnd is updated
16684 				 * constantly and it will not affect
16685 				 * anything.
16686 				 */
16687 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16688 			}
16689 			tcp_wput_data(tcp, NULL, B_FALSE);
16690 			return;
16691 		}
16692 		/* Is there a FIN that needs to be to re retransmitted? */
16693 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16694 		    !tcp->tcp_fin_acked)
16695 			break;
16696 		/* Nothing to do, return without restarting timer. */
16697 		TCP_STAT(tcps, tcp_timer_fire_miss);
16698 		return;
16699 	case TCPS_FIN_WAIT_2:
16700 		/*
16701 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16702 		 * We waited some time for for peer's FIN, but it hasn't
16703 		 * arrived.  We flush the connection now to avoid
16704 		 * case where the peer has rebooted.
16705 		 */
16706 		if (TCP_IS_DETACHED(tcp)) {
16707 			(void) tcp_clean_death(tcp, 0, 23);
16708 		} else {
16709 			TCP_TIMER_RESTART(tcp,
16710 			    tcps->tcps_fin_wait_2_flush_interval);
16711 		}
16712 		return;
16713 	case TCPS_TIME_WAIT:
16714 		(void) tcp_clean_death(tcp, 0, 24);
16715 		return;
16716 	default:
16717 		if (tcp->tcp_debug) {
16718 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16719 			    "tcp_timer: strange state (%d) %s",
16720 			    tcp->tcp_state, tcp_display(tcp, NULL,
16721 			    DISP_PORT_ONLY));
16722 		}
16723 		return;
16724 	}
16725 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16726 		/*
16727 		 * For zero window probe, we need to send indefinitely,
16728 		 * unless we have not heard from the other side for some
16729 		 * time...
16730 		 */
16731 		if ((tcp->tcp_zero_win_probe == 0) ||
16732 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16733 		    second_threshold)) {
16734 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
16735 			/*
16736 			 * If TCP is in SYN_RCVD state, send back a
16737 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16738 			 * should be zero in TCPS_SYN_RCVD state.
16739 			 */
16740 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16741 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16742 				    "in SYN_RCVD",
16743 				    tcp, tcp->tcp_snxt,
16744 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16745 			}
16746 			(void) tcp_clean_death(tcp,
16747 			    tcp->tcp_client_errno ?
16748 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16749 			return;
16750 		} else {
16751 			/*
16752 			 * Set tcp_ms_we_have_waited to second_threshold
16753 			 * so that in next timeout, we will do the above
16754 			 * check (lbolt - tcp_last_recv_time).  This is
16755 			 * also to avoid overflow.
16756 			 *
16757 			 * We don't need to decrement tcp_timer_backoff
16758 			 * to avoid overflow because it will be decremented
16759 			 * later if new timeout value is greater than
16760 			 * tcp_rexmit_interval_max.  In the case when
16761 			 * tcp_rexmit_interval_max is greater than
16762 			 * second_threshold, it means that we will wait
16763 			 * longer than second_threshold to send the next
16764 			 * window probe.
16765 			 */
16766 			tcp->tcp_ms_we_have_waited = second_threshold;
16767 		}
16768 	} else if (ms > first_threshold) {
16769 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16770 		    tcp->tcp_xmit_head != NULL) {
16771 			tcp->tcp_xmit_head =
16772 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16773 		}
16774 		/*
16775 		 * We have been retransmitting for too long...  The RTT
16776 		 * we calculated is probably incorrect.  Reinitialize it.
16777 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16778 		 * tcp_rtt_update so that we won't accidentally cache a
16779 		 * bad value.  But only do this if this is not a zero
16780 		 * window probe.
16781 		 */
16782 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16783 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16784 			    (tcp->tcp_rtt_sa >> 5);
16785 			tcp->tcp_rtt_sa = 0;
16786 			tcp_ip_notify(tcp);
16787 			tcp->tcp_rtt_update = 0;
16788 		}
16789 	}
16790 	tcp->tcp_timer_backoff++;
16791 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16792 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16793 	    tcps->tcps_rexmit_interval_min) {
16794 		/*
16795 		 * This means the original RTO is tcp_rexmit_interval_min.
16796 		 * So we will use tcp_rexmit_interval_min as the RTO value
16797 		 * and do the backoff.
16798 		 */
16799 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
16800 	} else {
16801 		ms <<= tcp->tcp_timer_backoff;
16802 	}
16803 	if (ms > tcps->tcps_rexmit_interval_max) {
16804 		ms = tcps->tcps_rexmit_interval_max;
16805 		/*
16806 		 * ms is at max, decrement tcp_timer_backoff to avoid
16807 		 * overflow.
16808 		 */
16809 		tcp->tcp_timer_backoff--;
16810 	}
16811 	tcp->tcp_ms_we_have_waited += ms;
16812 	if (tcp->tcp_zero_win_probe == 0) {
16813 		tcp->tcp_rto = ms;
16814 	}
16815 	TCP_TIMER_RESTART(tcp, ms);
16816 	/*
16817 	 * This is after a timeout and tcp_rto is backed off.  Set
16818 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16819 	 * restart the timer with a correct value.
16820 	 */
16821 	tcp->tcp_set_timer = 1;
16822 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16823 	if (mss > tcp->tcp_mss)
16824 		mss = tcp->tcp_mss;
16825 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16826 		mss = tcp->tcp_swnd;
16827 
16828 	if ((mp = tcp->tcp_xmit_head) != NULL)
16829 		mp->b_prev = (mblk_t *)lbolt;
16830 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16831 	    B_TRUE);
16832 
16833 	/*
16834 	 * When slow start after retransmission begins, start with
16835 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16836 	 * start phase.  tcp_snd_burst controls how many segments
16837 	 * can be sent because of an ack.
16838 	 */
16839 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16840 	tcp->tcp_snd_burst = TCP_CWND_SS;
16841 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16842 	    (tcp->tcp_unsent == 0)) {
16843 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16844 	} else {
16845 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16846 	}
16847 	tcp->tcp_rexmit = B_TRUE;
16848 	tcp->tcp_dupack_cnt = 0;
16849 
16850 	/*
16851 	 * Remove all rexmit SACK blk to start from fresh.
16852 	 */
16853 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16854 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
16855 		tcp->tcp_num_notsack_blk = 0;
16856 		tcp->tcp_cnt_notsack_list = 0;
16857 	}
16858 	if (mp == NULL) {
16859 		return;
16860 	}
16861 	/*
16862 	 * Attach credentials to retransmitted initial SYNs.
16863 	 * In theory we should use the credentials from the connect()
16864 	 * call to ensure that getpeerucred() on the peer will be correct.
16865 	 * But we assume that SYN's are not dropped for loopback connections.
16866 	 */
16867 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16868 		mblk_setcred(mp, tcp->tcp_cred, tcp->tcp_cpid);
16869 	}
16870 
16871 	tcp->tcp_csuna = tcp->tcp_snxt;
16872 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
16873 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
16874 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16875 
16876 }
16877 
16878 static int
16879 tcp_do_unbind(conn_t *connp)
16880 {
16881 	tcp_t *tcp = connp->conn_tcp;
16882 	int error = 0;
16883 
16884 	switch (tcp->tcp_state) {
16885 	case TCPS_BOUND:
16886 	case TCPS_LISTEN:
16887 		break;
16888 	default:
16889 		return (-TOUTSTATE);
16890 	}
16891 
16892 	/*
16893 	 * Need to clean up all the eagers since after the unbind, segments
16894 	 * will no longer be delivered to this listener stream.
16895 	 */
16896 	mutex_enter(&tcp->tcp_eager_lock);
16897 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16898 		tcp_eager_cleanup(tcp, 0);
16899 	}
16900 	mutex_exit(&tcp->tcp_eager_lock);
16901 
16902 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16903 		tcp->tcp_ipha->ipha_src = 0;
16904 	} else {
16905 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16906 	}
16907 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16908 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16909 	tcp_bind_hash_remove(tcp);
16910 	tcp->tcp_state = TCPS_IDLE;
16911 	tcp->tcp_mdt = B_FALSE;
16912 
16913 	connp = tcp->tcp_connp;
16914 	connp->conn_mdt_ok = B_FALSE;
16915 	ipcl_hash_remove(connp);
16916 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16917 
16918 	return (error);
16919 }
16920 
16921 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16922 static void
16923 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
16924 {
16925 	int error = tcp_do_unbind(tcp->tcp_connp);
16926 
16927 	if (error > 0) {
16928 		tcp_err_ack(tcp, mp, TSYSERR, error);
16929 	} else if (error < 0) {
16930 		tcp_err_ack(tcp, mp, -error, 0);
16931 	} else {
16932 		/* Send M_FLUSH according to TPI */
16933 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16934 
16935 		mp = mi_tpi_ok_ack_alloc(mp);
16936 		putnext(tcp->tcp_rq, mp);
16937 	}
16938 }
16939 
16940 /*
16941  * Don't let port fall into the privileged range.
16942  * Since the extra privileged ports can be arbitrary we also
16943  * ensure that we exclude those from consideration.
16944  * tcp_g_epriv_ports is not sorted thus we loop over it until
16945  * there are no changes.
16946  *
16947  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16948  * but instead the code relies on:
16949  * - the fact that the address of the array and its size never changes
16950  * - the atomic assignment of the elements of the array
16951  *
16952  * Returns 0 if there are no more ports available.
16953  *
16954  * TS note: skip multilevel ports.
16955  */
16956 static in_port_t
16957 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
16958 {
16959 	int i;
16960 	boolean_t restart = B_FALSE;
16961 	tcp_stack_t *tcps = tcp->tcp_tcps;
16962 
16963 	if (random && tcp_random_anon_port != 0) {
16964 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16965 		    sizeof (in_port_t));
16966 		/*
16967 		 * Unless changed by a sys admin, the smallest anon port
16968 		 * is 32768 and the largest anon port is 65535.  It is
16969 		 * very likely (50%) for the random port to be smaller
16970 		 * than the smallest anon port.  When that happens,
16971 		 * add port % (anon port range) to the smallest anon
16972 		 * port to get the random port.  It should fall into the
16973 		 * valid anon port range.
16974 		 */
16975 		if (port < tcps->tcps_smallest_anon_port) {
16976 			port = tcps->tcps_smallest_anon_port +
16977 			    port % (tcps->tcps_largest_anon_port -
16978 			    tcps->tcps_smallest_anon_port);
16979 		}
16980 	}
16981 
16982 retry:
16983 	if (port < tcps->tcps_smallest_anon_port)
16984 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16985 
16986 	if (port > tcps->tcps_largest_anon_port) {
16987 		if (restart)
16988 			return (0);
16989 		restart = B_TRUE;
16990 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16991 	}
16992 
16993 	if (port < tcps->tcps_smallest_nonpriv_port)
16994 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
16995 
16996 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
16997 		if (port == tcps->tcps_g_epriv_ports[i]) {
16998 			port++;
16999 			/*
17000 			 * Make sure whether the port is in the
17001 			 * valid range.
17002 			 */
17003 			goto retry;
17004 		}
17005 	}
17006 	if (is_system_labeled() &&
17007 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17008 	    IPPROTO_TCP, B_TRUE)) != 0) {
17009 		port = i;
17010 		goto retry;
17011 	}
17012 	return (port);
17013 }
17014 
17015 /*
17016  * Return the next anonymous port in the privileged port range for
17017  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17018  * downwards.  This is the same behavior as documented in the userland
17019  * library call rresvport(3N).
17020  *
17021  * TS note: skip multilevel ports.
17022  */
17023 static in_port_t
17024 tcp_get_next_priv_port(const tcp_t *tcp)
17025 {
17026 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17027 	in_port_t nextport;
17028 	boolean_t restart = B_FALSE;
17029 	tcp_stack_t *tcps = tcp->tcp_tcps;
17030 retry:
17031 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17032 	    next_priv_port >= IPPORT_RESERVED) {
17033 		next_priv_port = IPPORT_RESERVED - 1;
17034 		if (restart)
17035 			return (0);
17036 		restart = B_TRUE;
17037 	}
17038 	if (is_system_labeled() &&
17039 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17040 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17041 		next_priv_port = nextport;
17042 		goto retry;
17043 	}
17044 	return (next_priv_port--);
17045 }
17046 
17047 /* The write side r/w procedure. */
17048 
17049 #if CCS_STATS
17050 struct {
17051 	struct {
17052 		int64_t count, bytes;
17053 	} tot, hit;
17054 } wrw_stats;
17055 #endif
17056 
17057 /*
17058  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17059  * messages.
17060  */
17061 /* ARGSUSED */
17062 static void
17063 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17064 {
17065 	conn_t	*connp = (conn_t *)arg;
17066 	tcp_t	*tcp = connp->conn_tcp;
17067 	queue_t	*q = tcp->tcp_wq;
17068 
17069 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17070 	/*
17071 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17072 	 * Once the close starts, streamhead and sockfs will not let any data
17073 	 * packets come down (close ensures that there are no threads using the
17074 	 * queue and no new threads will come down) but since qprocsoff()
17075 	 * hasn't happened yet, a M_FLUSH or some non data message might
17076 	 * get reflected back (in response to our own FLUSHRW) and get
17077 	 * processed after tcp_close() is done. The conn would still be valid
17078 	 * because a ref would have added but we need to check the state
17079 	 * before actually processing the packet.
17080 	 */
17081 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17082 		freemsg(mp);
17083 		return;
17084 	}
17085 
17086 	switch (DB_TYPE(mp)) {
17087 	case M_IOCDATA:
17088 		tcp_wput_iocdata(tcp, mp);
17089 		break;
17090 	case M_FLUSH:
17091 		tcp_wput_flush(tcp, mp);
17092 		break;
17093 	default:
17094 		CALL_IP_WPUT(connp, q, mp);
17095 		break;
17096 	}
17097 }
17098 
17099 /*
17100  * The TCP fast path write put procedure.
17101  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17102  */
17103 /* ARGSUSED */
17104 void
17105 tcp_output(void *arg, mblk_t *mp, void *arg2)
17106 {
17107 	int		len;
17108 	int		hdrlen;
17109 	int		plen;
17110 	mblk_t		*mp1;
17111 	uchar_t		*rptr;
17112 	uint32_t	snxt;
17113 	tcph_t		*tcph;
17114 	struct datab	*db;
17115 	uint32_t	suna;
17116 	uint32_t	mss;
17117 	ipaddr_t	*dst;
17118 	ipaddr_t	*src;
17119 	uint32_t	sum;
17120 	int		usable;
17121 	conn_t		*connp = (conn_t *)arg;
17122 	tcp_t		*tcp = connp->conn_tcp;
17123 	uint32_t	msize;
17124 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17125 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17126 
17127 	/*
17128 	 * Try and ASSERT the minimum possible references on the
17129 	 * conn early enough. Since we are executing on write side,
17130 	 * the connection is obviously not detached and that means
17131 	 * there is a ref each for TCP and IP. Since we are behind
17132 	 * the squeue, the minimum references needed are 3. If the
17133 	 * conn is in classifier hash list, there should be an
17134 	 * extra ref for that (we check both the possibilities).
17135 	 */
17136 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17137 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17138 
17139 	ASSERT(DB_TYPE(mp) == M_DATA);
17140 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17141 
17142 	mutex_enter(&tcp->tcp_non_sq_lock);
17143 	tcp->tcp_squeue_bytes -= msize;
17144 	mutex_exit(&tcp->tcp_non_sq_lock);
17145 
17146 	/* Check to see if this connection wants to be re-fused. */
17147 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
17148 		if (tcp->tcp_ipversion == IPV4_VERSION) {
17149 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
17150 			    &tcp->tcp_saved_tcph);
17151 		} else {
17152 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
17153 			    &tcp->tcp_saved_tcph);
17154 		}
17155 	}
17156 	/* Bypass tcp protocol for fused tcp loopback */
17157 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17158 		return;
17159 
17160 	mss = tcp->tcp_mss;
17161 	if (tcp->tcp_xmit_zc_clean)
17162 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17163 
17164 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17165 	len = (int)(mp->b_wptr - mp->b_rptr);
17166 
17167 	/*
17168 	 * Criteria for fast path:
17169 	 *
17170 	 *   1. no unsent data
17171 	 *   2. single mblk in request
17172 	 *   3. connection established
17173 	 *   4. data in mblk
17174 	 *   5. len <= mss
17175 	 *   6. no tcp_valid bits
17176 	 */
17177 	if ((tcp->tcp_unsent != 0) ||
17178 	    (tcp->tcp_cork) ||
17179 	    (mp->b_cont != NULL) ||
17180 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17181 	    (len == 0) ||
17182 	    (len > mss) ||
17183 	    (tcp->tcp_valid_bits != 0)) {
17184 		tcp_wput_data(tcp, mp, B_FALSE);
17185 		return;
17186 	}
17187 
17188 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17189 	ASSERT(tcp->tcp_fin_sent == 0);
17190 
17191 	/* queue new packet onto retransmission queue */
17192 	if (tcp->tcp_xmit_head == NULL) {
17193 		tcp->tcp_xmit_head = mp;
17194 	} else {
17195 		tcp->tcp_xmit_last->b_cont = mp;
17196 	}
17197 	tcp->tcp_xmit_last = mp;
17198 	tcp->tcp_xmit_tail = mp;
17199 
17200 	/* find out how much we can send */
17201 	/* BEGIN CSTYLED */
17202 	/*
17203 	 *    un-acked	   usable
17204 	 *  |--------------|-----------------|
17205 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
17206 	 */
17207 	/* END CSTYLED */
17208 
17209 	/* start sending from tcp_snxt */
17210 	snxt = tcp->tcp_snxt;
17211 
17212 	/*
17213 	 * Check to see if this connection has been idled for some
17214 	 * time and no ACK is expected.  If it is, we need to slow
17215 	 * start again to get back the connection's "self-clock" as
17216 	 * described in VJ's paper.
17217 	 *
17218 	 * Refer to the comment in tcp_mss_set() for the calculation
17219 	 * of tcp_cwnd after idle.
17220 	 */
17221 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17222 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17223 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
17224 	}
17225 
17226 	usable = tcp->tcp_swnd;		/* tcp window size */
17227 	if (usable > tcp->tcp_cwnd)
17228 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17229 	usable -= snxt;		/* subtract stuff already sent */
17230 	suna = tcp->tcp_suna;
17231 	usable += suna;
17232 	/* usable can be < 0 if the congestion window is smaller */
17233 	if (len > usable) {
17234 		/* Can't send complete M_DATA in one shot */
17235 		goto slow;
17236 	}
17237 
17238 	mutex_enter(&tcp->tcp_non_sq_lock);
17239 	if (tcp->tcp_flow_stopped &&
17240 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17241 		tcp_clrqfull(tcp);
17242 	}
17243 	mutex_exit(&tcp->tcp_non_sq_lock);
17244 
17245 	/*
17246 	 * determine if anything to send (Nagle).
17247 	 *
17248 	 *   1. len < tcp_mss (i.e. small)
17249 	 *   2. unacknowledged data present
17250 	 *   3. len < nagle limit
17251 	 *   4. last packet sent < nagle limit (previous packet sent)
17252 	 */
17253 	if ((len < mss) && (snxt != suna) &&
17254 	    (len < (int)tcp->tcp_naglim) &&
17255 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17256 		/*
17257 		 * This was the first unsent packet and normally
17258 		 * mss < xmit_hiwater so there is no need to worry
17259 		 * about flow control. The next packet will go
17260 		 * through the flow control check in tcp_wput_data().
17261 		 */
17262 		/* leftover work from above */
17263 		tcp->tcp_unsent = len;
17264 		tcp->tcp_xmit_tail_unsent = len;
17265 
17266 		return;
17267 	}
17268 
17269 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17270 
17271 	if (snxt == suna) {
17272 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17273 	}
17274 
17275 	/* we have always sent something */
17276 	tcp->tcp_rack_cnt = 0;
17277 
17278 	tcp->tcp_snxt = snxt + len;
17279 	tcp->tcp_rack = tcp->tcp_rnxt;
17280 
17281 	if ((mp1 = dupb(mp)) == 0)
17282 		goto no_memory;
17283 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17284 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17285 
17286 	/* adjust tcp header information */
17287 	tcph = tcp->tcp_tcph;
17288 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17289 
17290 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17291 	sum = (sum >> 16) + (sum & 0xFFFF);
17292 	U16_TO_ABE16(sum, tcph->th_sum);
17293 
17294 	U32_TO_ABE32(snxt, tcph->th_seq);
17295 
17296 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17297 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17298 	BUMP_LOCAL(tcp->tcp_obsegs);
17299 
17300 	/* Update the latest receive window size in TCP header. */
17301 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17302 	    tcph->th_win);
17303 
17304 	tcp->tcp_last_sent_len = (ushort_t)len;
17305 
17306 	plen = len + tcp->tcp_hdr_len;
17307 
17308 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17309 		tcp->tcp_ipha->ipha_length = htons(plen);
17310 	} else {
17311 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17312 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17313 	}
17314 
17315 	/* see if we need to allocate a mblk for the headers */
17316 	hdrlen = tcp->tcp_hdr_len;
17317 	rptr = mp1->b_rptr - hdrlen;
17318 	db = mp1->b_datap;
17319 	if ((db->db_ref != 2) || rptr < db->db_base ||
17320 	    (!OK_32PTR(rptr))) {
17321 		/* NOTE: we assume allocb returns an OK_32PTR */
17322 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17323 		    tcps->tcps_wroff_xtra, BPRI_MED);
17324 		if (!mp) {
17325 			freemsg(mp1);
17326 			goto no_memory;
17327 		}
17328 		mp->b_cont = mp1;
17329 		mp1 = mp;
17330 		/* Leave room for Link Level header */
17331 		/* hdrlen = tcp->tcp_hdr_len; */
17332 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17333 		mp1->b_wptr = &rptr[hdrlen];
17334 	}
17335 	mp1->b_rptr = rptr;
17336 
17337 	/* Fill in the timestamp option. */
17338 	if (tcp->tcp_snd_ts_ok) {
17339 		U32_TO_BE32((uint32_t)lbolt,
17340 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17341 		U32_TO_BE32(tcp->tcp_ts_recent,
17342 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17343 	} else {
17344 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17345 	}
17346 
17347 	/* copy header into outgoing packet */
17348 	dst = (ipaddr_t *)rptr;
17349 	src = (ipaddr_t *)tcp->tcp_iphc;
17350 	dst[0] = src[0];
17351 	dst[1] = src[1];
17352 	dst[2] = src[2];
17353 	dst[3] = src[3];
17354 	dst[4] = src[4];
17355 	dst[5] = src[5];
17356 	dst[6] = src[6];
17357 	dst[7] = src[7];
17358 	dst[8] = src[8];
17359 	dst[9] = src[9];
17360 	if (hdrlen -= 40) {
17361 		hdrlen >>= 2;
17362 		dst += 10;
17363 		src += 10;
17364 		do {
17365 			*dst++ = *src++;
17366 		} while (--hdrlen);
17367 	}
17368 
17369 	/*
17370 	 * Set the ECN info in the TCP header.  Note that this
17371 	 * is not the template header.
17372 	 */
17373 	if (tcp->tcp_ecn_ok) {
17374 		SET_ECT(tcp, rptr);
17375 
17376 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17377 		if (tcp->tcp_ecn_echo_on)
17378 			tcph->th_flags[0] |= TH_ECE;
17379 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17380 			tcph->th_flags[0] |= TH_CWR;
17381 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17382 		}
17383 	}
17384 
17385 	if (tcp->tcp_ip_forward_progress) {
17386 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17387 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17388 		tcp->tcp_ip_forward_progress = B_FALSE;
17389 	}
17390 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17391 	return;
17392 
17393 	/*
17394 	 * If we ran out of memory, we pretend to have sent the packet
17395 	 * and that it was lost on the wire.
17396 	 */
17397 no_memory:
17398 	return;
17399 
17400 slow:
17401 	/* leftover work from above */
17402 	tcp->tcp_unsent = len;
17403 	tcp->tcp_xmit_tail_unsent = len;
17404 	tcp_wput_data(tcp, NULL, B_FALSE);
17405 }
17406 
17407 /* ARGSUSED */
17408 void
17409 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17410 {
17411 	conn_t			*connp = (conn_t *)arg;
17412 	tcp_t			*tcp = connp->conn_tcp;
17413 	queue_t			*q = tcp->tcp_rq;
17414 	struct tcp_options	*tcpopt;
17415 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17416 
17417 	/* socket options */
17418 	uint_t 			sopp_flags;
17419 	ssize_t			sopp_rxhiwat;
17420 	ssize_t			sopp_maxblk;
17421 	ushort_t		sopp_wroff;
17422 	ushort_t		sopp_tail;
17423 	ushort_t		sopp_copyopt;
17424 
17425 	tcpopt = (struct tcp_options *)mp->b_rptr;
17426 
17427 	/*
17428 	 * Drop the eager's ref on the listener, that was placed when
17429 	 * this eager began life in tcp_conn_request.
17430 	 */
17431 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17432 	if (IPCL_IS_NONSTR(connp)) {
17433 		/* Safe to free conn_ind message */
17434 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17435 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17436 	}
17437 
17438 	tcp->tcp_detached = B_FALSE;
17439 
17440 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17441 		/*
17442 		 * Someone blewoff the eager before we could finish
17443 		 * the accept.
17444 		 *
17445 		 * The only reason eager exists it because we put in
17446 		 * a ref on it when conn ind went up. We need to send
17447 		 * a disconnect indication up while the last reference
17448 		 * on the eager will be dropped by the squeue when we
17449 		 * return.
17450 		 */
17451 		ASSERT(tcp->tcp_listener == NULL);
17452 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17453 			if (IPCL_IS_NONSTR(connp)) {
17454 				ASSERT(tcp->tcp_issocket);
17455 				(*connp->conn_upcalls->su_disconnected)(
17456 				    connp->conn_upper_handle, tcp->tcp_connid,
17457 				    ECONNREFUSED);
17458 				freemsg(mp);
17459 			} else {
17460 				struct	T_discon_ind	*tdi;
17461 
17462 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17463 				/*
17464 				 * Let us reuse the incoming mblk to avoid
17465 				 * memory allocation failure problems. We know
17466 				 * that the size of the incoming mblk i.e.
17467 				 * stroptions is greater than sizeof
17468 				 * T_discon_ind. So the reallocb below can't
17469 				 * fail.
17470 				 */
17471 				freemsg(mp->b_cont);
17472 				mp->b_cont = NULL;
17473 				ASSERT(DB_REF(mp) == 1);
17474 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17475 				    B_FALSE);
17476 				ASSERT(mp != NULL);
17477 				DB_TYPE(mp) = M_PROTO;
17478 				((union T_primitives *)mp->b_rptr)->type =
17479 				    T_DISCON_IND;
17480 				tdi = (struct T_discon_ind *)mp->b_rptr;
17481 				if (tcp->tcp_issocket) {
17482 					tdi->DISCON_reason = ECONNREFUSED;
17483 					tdi->SEQ_number = 0;
17484 				} else {
17485 					tdi->DISCON_reason = ENOPROTOOPT;
17486 					tdi->SEQ_number =
17487 					    tcp->tcp_conn_req_seqnum;
17488 				}
17489 				mp->b_wptr = mp->b_rptr +
17490 				    sizeof (struct T_discon_ind);
17491 				putnext(q, mp);
17492 				return;
17493 			}
17494 		}
17495 		if (tcp->tcp_hard_binding) {
17496 			tcp->tcp_hard_binding = B_FALSE;
17497 			tcp->tcp_hard_bound = B_TRUE;
17498 		}
17499 		return;
17500 	}
17501 
17502 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
17503 		int boundif = tcpopt->to_boundif;
17504 		uint_t len = sizeof (int);
17505 
17506 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17507 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
17508 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred, NULL);
17509 	}
17510 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
17511 		uint_t on = 1;
17512 		uint_t len = sizeof (uint_t);
17513 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17514 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
17515 		    (uchar_t *)&on, NULL, tcp->tcp_cred, NULL);
17516 	}
17517 
17518 	/*
17519 	 * For a loopback connection with tcp_direct_sockfs on, note that
17520 	 * we don't have to protect tcp_rcv_list yet because synchronous
17521 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17522 	 * possibly race with us.
17523 	 */
17524 
17525 	/*
17526 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17527 	 * properly.  This is the first time we know of the acceptor'
17528 	 * queue.  So we do it here.
17529 	 *
17530 	 * XXX
17531 	 */
17532 	if (tcp->tcp_rcv_list == NULL) {
17533 		/*
17534 		 * Recv queue is empty, tcp_rwnd should not have changed.
17535 		 * That means it should be equal to the listener's tcp_rwnd.
17536 		 */
17537 		if (!IPCL_IS_NONSTR(connp))
17538 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17539 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
17540 	} else {
17541 #ifdef DEBUG
17542 		mblk_t *tmp;
17543 		mblk_t	*mp1;
17544 		uint_t	cnt = 0;
17545 
17546 		mp1 = tcp->tcp_rcv_list;
17547 		while ((tmp = mp1) != NULL) {
17548 			mp1 = tmp->b_next;
17549 			cnt += msgdsize(tmp);
17550 		}
17551 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17552 #endif
17553 		/* There is some data, add them back to get the max. */
17554 		if (!IPCL_IS_NONSTR(connp))
17555 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17556 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17557 	}
17558 	/*
17559 	 * This is the first time we run on the correct
17560 	 * queue after tcp_accept. So fix all the q parameters
17561 	 * here.
17562 	 */
17563 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
17564 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17565 
17566 	/*
17567 	 * Record the stream head's high water mark for this endpoint;
17568 	 * this is used for flow-control purposes.
17569 	 */
17570 	sopp_rxhiwat = tcp->tcp_fused ?
17571 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
17572 	    MAX(tcp->tcp_recv_hiwater, tcps->tcps_sth_rcv_hiwat);
17573 
17574 	/*
17575 	 * Determine what write offset value to use depending on SACK and
17576 	 * whether the endpoint is fused or not.
17577 	 */
17578 	if (tcp->tcp_fused) {
17579 		ASSERT(tcp->tcp_loopback);
17580 		ASSERT(tcp->tcp_loopback_peer != NULL);
17581 		/*
17582 		 * For fused tcp loopback, set the stream head's write
17583 		 * offset value to zero since we won't be needing any room
17584 		 * for TCP/IP headers.  This would also improve performance
17585 		 * since it would reduce the amount of work done by kmem.
17586 		 * Non-fused tcp loopback case is handled separately below.
17587 		 */
17588 		sopp_wroff = 0;
17589 		/*
17590 		 * Update the peer's transmit parameters according to
17591 		 * our recently calculated high water mark value.
17592 		 */
17593 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17594 	} else if (tcp->tcp_snd_sack_ok) {
17595 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17596 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
17597 	} else {
17598 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17599 		    tcps->tcps_wroff_xtra);
17600 	}
17601 
17602 	/*
17603 	 * If this is endpoint is handling SSL, then reserve extra
17604 	 * offset and space at the end.
17605 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17606 	 * overriding the previous setting. The extra cost of signing and
17607 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17608 	 * instead of a single contiguous one by the stream head
17609 	 * largely outweighs the statistical reduction of ACKs, when
17610 	 * applicable. The peer will also save on decryption and verification
17611 	 * costs.
17612 	 */
17613 	if (tcp->tcp_kssl_ctx != NULL) {
17614 		sopp_wroff += SSL3_WROFFSET;
17615 
17616 		sopp_flags |= SOCKOPT_TAIL;
17617 		sopp_tail = SSL3_MAX_TAIL_LEN;
17618 
17619 		sopp_flags |= SOCKOPT_ZCOPY;
17620 		sopp_copyopt = ZCVMUNSAFE;
17621 
17622 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
17623 	}
17624 
17625 	/* Send the options up */
17626 	if (IPCL_IS_NONSTR(connp)) {
17627 		struct sock_proto_props sopp;
17628 
17629 		sopp.sopp_flags = sopp_flags;
17630 		sopp.sopp_wroff = sopp_wroff;
17631 		sopp.sopp_maxblk = sopp_maxblk;
17632 		sopp.sopp_rxhiwat = sopp_rxhiwat;
17633 		if (sopp_flags & SOCKOPT_TAIL) {
17634 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17635 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
17636 			sopp.sopp_tail = sopp_tail;
17637 			sopp.sopp_zcopyflag = sopp_copyopt;
17638 		}
17639 		(*connp->conn_upcalls->su_set_proto_props)
17640 		    (connp->conn_upper_handle, &sopp);
17641 	} else {
17642 		struct stroptions *stropt;
17643 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17644 		if (stropt_mp == NULL) {
17645 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
17646 			return;
17647 		}
17648 		DB_TYPE(stropt_mp) = M_SETOPTS;
17649 		stropt = (struct stroptions *)stropt_mp->b_rptr;
17650 		stropt_mp->b_wptr += sizeof (struct stroptions);
17651 		stropt = (struct stroptions *)stropt_mp->b_rptr;
17652 		stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
17653 		stropt->so_hiwat = sopp_rxhiwat;
17654 		stropt->so_wroff = sopp_wroff;
17655 		stropt->so_maxblk = sopp_maxblk;
17656 
17657 		if (sopp_flags & SOCKOPT_TAIL) {
17658 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17659 
17660 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
17661 			stropt->so_tail = sopp_tail;
17662 			stropt->so_copyopt = sopp_copyopt;
17663 		}
17664 
17665 		/* Send the options up */
17666 		putnext(q, stropt_mp);
17667 	}
17668 
17669 	freemsg(mp);
17670 	/*
17671 	 * Pass up any data and/or a fin that has been received.
17672 	 *
17673 	 * Adjust receive window in case it had decreased
17674 	 * (because there is data <=> tcp_rcv_list != NULL)
17675 	 * while the connection was detached. Note that
17676 	 * in case the eager was flow-controlled, w/o this
17677 	 * code, the rwnd may never open up again!
17678 	 */
17679 	if (tcp->tcp_rcv_list != NULL) {
17680 		if (IPCL_IS_NONSTR(connp)) {
17681 			mblk_t *mp;
17682 			int space_left;
17683 			int error;
17684 			boolean_t push = B_TRUE;
17685 
17686 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
17687 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
17688 			    &push) >= 0) {
17689 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
17690 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17691 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17692 					tcp_xmit_ctl(NULL,
17693 					    tcp, (tcp->tcp_swnd == 0) ?
17694 					    tcp->tcp_suna : tcp->tcp_snxt,
17695 					    tcp->tcp_rnxt, TH_ACK);
17696 				}
17697 			}
17698 			while ((mp = tcp->tcp_rcv_list) != NULL) {
17699 				push = B_TRUE;
17700 				tcp->tcp_rcv_list = mp->b_next;
17701 				mp->b_next = NULL;
17702 				space_left = (*connp->conn_upcalls->su_recv)
17703 				    (connp->conn_upper_handle, mp, msgdsize(mp),
17704 				    0, &error, &push);
17705 				if (space_left < 0) {
17706 					/*
17707 					 * We should never be in middle of a
17708 					 * fallback, the squeue guarantees that.
17709 					 */
17710 					ASSERT(error != EOPNOTSUPP);
17711 				}
17712 			}
17713 			tcp->tcp_rcv_last_head = NULL;
17714 			tcp->tcp_rcv_last_tail = NULL;
17715 			tcp->tcp_rcv_cnt = 0;
17716 		} else {
17717 			/* We drain directly in case of fused tcp loopback */
17718 			sodirect_t *sodp;
17719 
17720 			if (!tcp->tcp_fused && canputnext(q)) {
17721 				tcp->tcp_rwnd = q->q_hiwat;
17722 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17723 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17724 					tcp_xmit_ctl(NULL,
17725 					    tcp, (tcp->tcp_swnd == 0) ?
17726 					    tcp->tcp_suna : tcp->tcp_snxt,
17727 					    tcp->tcp_rnxt, TH_ACK);
17728 				}
17729 			}
17730 
17731 			SOD_PTR_ENTER(tcp, sodp);
17732 			if (sodp != NULL) {
17733 				/* Sodirect, move from rcv_list */
17734 				ASSERT(!tcp->tcp_fused);
17735 				while ((mp = tcp->tcp_rcv_list) != NULL) {
17736 					tcp->tcp_rcv_list = mp->b_next;
17737 					mp->b_next = NULL;
17738 					(void) tcp_rcv_sod_enqueue(tcp, sodp,
17739 					    mp, msgdsize(mp));
17740 				}
17741 				tcp->tcp_rcv_last_head = NULL;
17742 				tcp->tcp_rcv_last_tail = NULL;
17743 				tcp->tcp_rcv_cnt = 0;
17744 				(void) tcp_rcv_sod_wakeup(tcp, sodp);
17745 				/* sod_wakeup() did the mutex_exit() */
17746 			} else {
17747 				/* Not sodirect, drain */
17748 				(void) tcp_rcv_drain(tcp);
17749 			}
17750 		}
17751 
17752 		/*
17753 		 * For fused tcp loopback, back-enable peer endpoint
17754 		 * if it's currently flow-controlled.
17755 		 */
17756 		if (tcp->tcp_fused) {
17757 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17758 
17759 			ASSERT(peer_tcp != NULL);
17760 			ASSERT(peer_tcp->tcp_fused);
17761 			/*
17762 			 * In order to change the peer's tcp_flow_stopped,
17763 			 * we need to take locks for both end points. The
17764 			 * highest address is taken first.
17765 			 */
17766 			if (peer_tcp > tcp) {
17767 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
17768 				mutex_enter(&tcp->tcp_non_sq_lock);
17769 			} else {
17770 				mutex_enter(&tcp->tcp_non_sq_lock);
17771 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
17772 			}
17773 			if (peer_tcp->tcp_flow_stopped) {
17774 				tcp_clrqfull(peer_tcp);
17775 				TCP_STAT(tcps, tcp_fusion_backenabled);
17776 			}
17777 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
17778 			mutex_exit(&tcp->tcp_non_sq_lock);
17779 		}
17780 	}
17781 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17782 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17783 		tcp->tcp_ordrel_done = B_TRUE;
17784 		if (IPCL_IS_NONSTR(connp)) {
17785 			ASSERT(tcp->tcp_ordrel_mp == NULL);
17786 			(*connp->conn_upcalls->su_opctl)(
17787 			    connp->conn_upper_handle,
17788 			    SOCK_OPCTL_SHUT_RECV, 0);
17789 		} else {
17790 			mp = tcp->tcp_ordrel_mp;
17791 			tcp->tcp_ordrel_mp = NULL;
17792 			putnext(q, mp);
17793 		}
17794 	}
17795 	if (tcp->tcp_hard_binding) {
17796 		tcp->tcp_hard_binding = B_FALSE;
17797 		tcp->tcp_hard_bound = B_TRUE;
17798 	}
17799 
17800 	/* We can enable synchronous streams for STREAMS tcp endpoint now */
17801 	if (tcp->tcp_fused && !IPCL_IS_NONSTR(connp) &&
17802 	    tcp->tcp_loopback_peer != NULL &&
17803 	    !IPCL_IS_NONSTR(tcp->tcp_loopback_peer->tcp_connp)) {
17804 		tcp_fuse_syncstr_enable_pair(tcp);
17805 	}
17806 
17807 	if (tcp->tcp_ka_enabled) {
17808 		tcp->tcp_ka_last_intrvl = 0;
17809 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17810 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17811 	}
17812 
17813 	/*
17814 	 * At this point, eager is fully established and will
17815 	 * have the following references -
17816 	 *
17817 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17818 	 * 1 reference for the squeue which will be dropped by the squeue as
17819 	 *	soon as this function returns.
17820 	 * There will be 1 additonal reference for being in classifier
17821 	 *	hash list provided something bad hasn't happened.
17822 	 */
17823 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17824 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17825 }
17826 
17827 /*
17828  * The function called through squeue to get behind listener's perimeter to
17829  * send a deffered conn_ind.
17830  */
17831 /* ARGSUSED */
17832 void
17833 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17834 {
17835 	conn_t	*connp = (conn_t *)arg;
17836 	tcp_t *listener = connp->conn_tcp;
17837 	struct T_conn_ind *conn_ind;
17838 	tcp_t *tcp;
17839 
17840 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
17841 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17842 	    conn_ind->OPT_length);
17843 
17844 	if (listener->tcp_state == TCPS_CLOSED ||
17845 	    TCP_IS_DETACHED(listener)) {
17846 		/*
17847 		 * If listener has closed, it would have caused a
17848 		 * a cleanup/blowoff to happen for the eager.
17849 		 *
17850 		 * We need to drop the ref on eager that was put
17851 		 * tcp_rput_data() before trying to send the conn_ind
17852 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
17853 		 * and tcp_wput_accept() is sending this deferred conn_ind but
17854 		 * listener is closed so we drop the ref.
17855 		 */
17856 		CONN_DEC_REF(tcp->tcp_connp);
17857 		freemsg(mp);
17858 		return;
17859 	}
17860 
17861 	tcp_ulp_newconn(connp, tcp->tcp_connp, mp);
17862 }
17863 
17864 /* ARGSUSED */
17865 static int
17866 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
17867 {
17868 	tcp_t *listener, *eager;
17869 	mblk_t *opt_mp;
17870 	struct tcp_options *tcpopt;
17871 
17872 	listener = lconnp->conn_tcp;
17873 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17874 	eager = econnp->conn_tcp;
17875 	ASSERT(eager->tcp_listener != NULL);
17876 
17877 	ASSERT(eager->tcp_rq != NULL);
17878 
17879 	/* If tcp_fused and sodirect enabled disable it */
17880 	if (eager->tcp_fused && eager->tcp_sodirect != NULL) {
17881 		/* Fused, disable sodirect */
17882 		mutex_enter(eager->tcp_sodirect->sod_lockp);
17883 		SOD_DISABLE(eager->tcp_sodirect);
17884 		mutex_exit(eager->tcp_sodirect->sod_lockp);
17885 		eager->tcp_sodirect = NULL;
17886 	}
17887 
17888 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
17889 	if (opt_mp == NULL) {
17890 		return (-TPROTO);
17891 	}
17892 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
17893 	eager->tcp_issocket = B_TRUE;
17894 
17895 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17896 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
17897 	ASSERT(econnp->conn_netstack ==
17898 	    listener->tcp_connp->conn_netstack);
17899 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
17900 
17901 	/* Put the ref for IP */
17902 	CONN_INC_REF(econnp);
17903 
17904 	/*
17905 	 * We should have minimum of 3 references on the conn
17906 	 * at this point. One each for TCP and IP and one for
17907 	 * the T_conn_ind that was sent up when the 3-way handshake
17908 	 * completed. In the normal case we would also have another
17909 	 * reference (making a total of 4) for the conn being in the
17910 	 * classifier hash list. However the eager could have received
17911 	 * an RST subsequently and tcp_closei_local could have removed
17912 	 * the eager from the classifier hash list, hence we can't
17913 	 * assert that reference.
17914 	 */
17915 	ASSERT(econnp->conn_ref >= 3);
17916 
17917 	opt_mp->b_datap->db_type = M_SETOPTS;
17918 	opt_mp->b_wptr += sizeof (struct tcp_options);
17919 
17920 	/*
17921 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17922 	 * from listener to acceptor.
17923 	 */
17924 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
17925 	tcpopt->to_flags = 0;
17926 
17927 	if (listener->tcp_bound_if != 0) {
17928 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
17929 		tcpopt->to_boundif = listener->tcp_bound_if;
17930 	}
17931 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17932 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
17933 	}
17934 
17935 	mutex_enter(&listener->tcp_eager_lock);
17936 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17937 
17938 		tcp_t *tail;
17939 		tcp_t *tcp;
17940 		mblk_t *mp1;
17941 
17942 		tcp = listener->tcp_eager_prev_q0;
17943 		/*
17944 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
17945 		 * deferred T_conn_ind queue. We need to get to the head
17946 		 * of the queue in order to send up T_conn_ind the same
17947 		 * order as how the 3WHS is completed.
17948 		 */
17949 		while (tcp != listener) {
17950 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17951 			    !tcp->tcp_kssl_pending)
17952 				break;
17953 			else
17954 				tcp = tcp->tcp_eager_prev_q0;
17955 		}
17956 		/* None of the pending eagers can be sent up now */
17957 		if (tcp == listener)
17958 			goto no_more_eagers;
17959 
17960 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17961 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17962 		/* Move from q0 to q */
17963 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17964 		listener->tcp_conn_req_cnt_q0--;
17965 		listener->tcp_conn_req_cnt_q++;
17966 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17967 		    tcp->tcp_eager_prev_q0;
17968 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17969 		    tcp->tcp_eager_next_q0;
17970 		tcp->tcp_eager_prev_q0 = NULL;
17971 		tcp->tcp_eager_next_q0 = NULL;
17972 		tcp->tcp_conn_def_q0 = B_FALSE;
17973 
17974 		/* Make sure the tcp isn't in the list of droppables */
17975 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
17976 		    tcp->tcp_eager_prev_drop_q0 == NULL);
17977 
17978 		/*
17979 		 * Insert at end of the queue because sockfs sends
17980 		 * down T_CONN_RES in chronological order. Leaving
17981 		 * the older conn indications at front of the queue
17982 		 * helps reducing search time.
17983 		 */
17984 		tail = listener->tcp_eager_last_q;
17985 		if (tail != NULL) {
17986 			tail->tcp_eager_next_q = tcp;
17987 		} else {
17988 			listener->tcp_eager_next_q = tcp;
17989 		}
17990 		listener->tcp_eager_last_q = tcp;
17991 		tcp->tcp_eager_next_q = NULL;
17992 
17993 		/* Need to get inside the listener perimeter */
17994 		CONN_INC_REF(listener->tcp_connp);
17995 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
17996 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
17997 		    SQTAG_TCP_SEND_PENDING);
17998 	}
17999 no_more_eagers:
18000 	tcp_eager_unlink(eager);
18001 	mutex_exit(&listener->tcp_eager_lock);
18002 
18003 	/*
18004 	 * At this point, the eager is detached from the listener
18005 	 * but we still have an extra refs on eager (apart from the
18006 	 * usual tcp references). The ref was placed in tcp_rput_data
18007 	 * before sending the conn_ind in tcp_send_conn_ind.
18008 	 * The ref will be dropped in tcp_accept_finish().
18009 	 */
18010 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
18011 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
18012 	return (0);
18013 }
18014 
18015 int
18016 tcp_accept(sock_lower_handle_t lproto_handle,
18017     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
18018     cred_t *cr)
18019 {
18020 	conn_t *lconnp, *econnp;
18021 	tcp_t *listener, *eager;
18022 	tcp_stack_t	*tcps;
18023 
18024 	lconnp = (conn_t *)lproto_handle;
18025 	listener = lconnp->conn_tcp;
18026 	ASSERT(listener->tcp_state == TCPS_LISTEN);
18027 	econnp = (conn_t *)eproto_handle;
18028 	eager = econnp->conn_tcp;
18029 	ASSERT(eager->tcp_listener != NULL);
18030 	tcps = eager->tcp_tcps;
18031 
18032 	/*
18033 	 * It is OK to manipulate these fields outside the eager's squeue
18034 	 * because they will not start being used until tcp_accept_finish
18035 	 * has been called.
18036 	 */
18037 	ASSERT(lconnp->conn_upper_handle != NULL);
18038 	ASSERT(econnp->conn_upper_handle == NULL);
18039 	econnp->conn_upper_handle = sock_handle;
18040 	econnp->conn_upcalls = lconnp->conn_upcalls;
18041 	ASSERT(IPCL_IS_NONSTR(econnp));
18042 	/*
18043 	 * Create helper stream if it is a non-TPI TCP connection.
18044 	 */
18045 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
18046 		ip1dbg(("tcp_accept: create of IP helper stream"
18047 		    " failed\n"));
18048 		return (EPROTO);
18049 	}
18050 	eager->tcp_rq = econnp->conn_rq;
18051 	eager->tcp_wq = econnp->conn_wq;
18052 
18053 	ASSERT(eager->tcp_rq != NULL);
18054 
18055 	eager->tcp_sodirect = SOD_SOTOSODP(sock_handle);
18056 	return (tcp_accept_common(lconnp, econnp, cr));
18057 }
18058 
18059 
18060 /*
18061  * This is the STREAMS entry point for T_CONN_RES coming down on
18062  * Acceptor STREAM when  sockfs listener does accept processing.
18063  * Read the block comment on top of tcp_conn_request().
18064  */
18065 void
18066 tcp_tpi_accept(queue_t *q, mblk_t *mp)
18067 {
18068 	queue_t *rq = RD(q);
18069 	struct T_conn_res *conn_res;
18070 	tcp_t *eager;
18071 	tcp_t *listener;
18072 	struct T_ok_ack *ok;
18073 	t_scalar_t PRIM_type;
18074 	conn_t *econnp;
18075 	cred_t *cr;
18076 
18077 	ASSERT(DB_TYPE(mp) == M_PROTO);
18078 
18079 	/*
18080 	 * All Solaris components should pass a db_credp
18081 	 * for this TPI message, hence we ASSERT.
18082 	 * But in case there is some other M_PROTO that looks
18083 	 * like a TPI message sent by some other kernel
18084 	 * component, we check and return an error.
18085 	 */
18086 	cr = msg_getcred(mp, NULL);
18087 	ASSERT(cr != NULL);
18088 	if (cr == NULL) {
18089 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
18090 		if (mp != NULL)
18091 			putnext(rq, mp);
18092 		return;
18093 	}
18094 	conn_res = (struct T_conn_res *)mp->b_rptr;
18095 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18096 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18097 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18098 		if (mp != NULL)
18099 			putnext(rq, mp);
18100 		return;
18101 	}
18102 	switch (conn_res->PRIM_type) {
18103 	case O_T_CONN_RES:
18104 	case T_CONN_RES:
18105 		/*
18106 		 * We pass up an err ack if allocb fails. This will
18107 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18108 		 * tcp_eager_blowoff to be called. sockfs will then call
18109 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18110 		 * we need to do the allocb up here because we have to
18111 		 * make sure rq->q_qinfo->qi_qclose still points to the
18112 		 * correct function (tcpclose_accept) in case allocb
18113 		 * fails.
18114 		 */
18115 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18116 		    &eager, conn_res->OPT_length);
18117 		PRIM_type = conn_res->PRIM_type;
18118 		mp->b_datap->db_type = M_PCPROTO;
18119 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18120 		ok = (struct T_ok_ack *)mp->b_rptr;
18121 		ok->PRIM_type = T_OK_ACK;
18122 		ok->CORRECT_prim = PRIM_type;
18123 		econnp = eager->tcp_connp;
18124 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
18125 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
18126 		eager->tcp_rq = rq;
18127 		eager->tcp_wq = q;
18128 		rq->q_ptr = econnp;
18129 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
18130 		q->q_ptr = econnp;
18131 		q->q_qinfo = &tcp_winit;
18132 		listener = eager->tcp_listener;
18133 
18134 		/*
18135 		 * TCP is _D_SODIRECT and sockfs is directly above so
18136 		 * save shared sodirect_t pointer (if any).
18137 		 */
18138 		eager->tcp_sodirect = SOD_QTOSODP(eager->tcp_rq);
18139 		if (tcp_accept_common(listener->tcp_connp,
18140 		    econnp, cr) < 0) {
18141 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18142 			if (mp != NULL)
18143 				putnext(rq, mp);
18144 			return;
18145 		}
18146 
18147 		/*
18148 		 * Send the new local address also up to sockfs. There
18149 		 * should already be enough space in the mp that came
18150 		 * down from soaccept().
18151 		 */
18152 		if (eager->tcp_family == AF_INET) {
18153 			sin_t *sin;
18154 
18155 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18156 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18157 			sin = (sin_t *)mp->b_wptr;
18158 			mp->b_wptr += sizeof (sin_t);
18159 			sin->sin_family = AF_INET;
18160 			sin->sin_port = eager->tcp_lport;
18161 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18162 		} else {
18163 			sin6_t *sin6;
18164 
18165 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18166 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18167 			sin6 = (sin6_t *)mp->b_wptr;
18168 			mp->b_wptr += sizeof (sin6_t);
18169 			sin6->sin6_family = AF_INET6;
18170 			sin6->sin6_port = eager->tcp_lport;
18171 			if (eager->tcp_ipversion == IPV4_VERSION) {
18172 				sin6->sin6_flowinfo = 0;
18173 				IN6_IPADDR_TO_V4MAPPED(
18174 				    eager->tcp_ipha->ipha_src,
18175 				    &sin6->sin6_addr);
18176 			} else {
18177 				ASSERT(eager->tcp_ip6h != NULL);
18178 				sin6->sin6_flowinfo =
18179 				    eager->tcp_ip6h->ip6_vcf &
18180 				    ~IPV6_VERS_AND_FLOW_MASK;
18181 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18182 			}
18183 			sin6->sin6_scope_id = 0;
18184 			sin6->__sin6_src_id = 0;
18185 		}
18186 
18187 		putnext(rq, mp);
18188 		return;
18189 	default:
18190 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18191 		if (mp != NULL)
18192 			putnext(rq, mp);
18193 		return;
18194 	}
18195 }
18196 
18197 static int
18198 tcp_do_getsockname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18199 {
18200 	sin_t *sin = (sin_t *)sa;
18201 	sin6_t *sin6 = (sin6_t *)sa;
18202 
18203 	switch (tcp->tcp_family) {
18204 	case AF_INET:
18205 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18206 
18207 		if (*salenp < sizeof (sin_t))
18208 			return (EINVAL);
18209 
18210 		*sin = sin_null;
18211 		sin->sin_family = AF_INET;
18212 		if (tcp->tcp_state >= TCPS_BOUND) {
18213 			sin->sin_port = tcp->tcp_lport;
18214 			sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
18215 		}
18216 		*salenp = sizeof (sin_t);
18217 		break;
18218 
18219 	case AF_INET6:
18220 		if (*salenp < sizeof (sin6_t))
18221 			return (EINVAL);
18222 
18223 		*sin6 = sin6_null;
18224 		sin6->sin6_family = AF_INET6;
18225 		if (tcp->tcp_state >= TCPS_BOUND) {
18226 			sin6->sin6_port = tcp->tcp_lport;
18227 			if (tcp->tcp_ipversion == IPV4_VERSION) {
18228 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
18229 				    &sin6->sin6_addr);
18230 			} else {
18231 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
18232 			}
18233 		}
18234 		*salenp = sizeof (sin6_t);
18235 		break;
18236 	}
18237 
18238 	return (0);
18239 }
18240 
18241 static int
18242 tcp_do_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18243 {
18244 	sin_t *sin = (sin_t *)sa;
18245 	sin6_t *sin6 = (sin6_t *)sa;
18246 
18247 	if (tcp->tcp_state < TCPS_SYN_RCVD)
18248 		return (ENOTCONN);
18249 
18250 	switch (tcp->tcp_family) {
18251 	case AF_INET:
18252 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18253 
18254 		if (*salenp < sizeof (sin_t))
18255 			return (EINVAL);
18256 
18257 		*sin = sin_null;
18258 		sin->sin_family = AF_INET;
18259 		sin->sin_port = tcp->tcp_fport;
18260 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
18261 		    sin->sin_addr.s_addr);
18262 		*salenp = sizeof (sin_t);
18263 		break;
18264 
18265 	case AF_INET6:
18266 		if (*salenp < sizeof (sin6_t))
18267 			return (EINVAL);
18268 
18269 		*sin6 = sin6_null;
18270 		sin6->sin6_family = AF_INET6;
18271 		sin6->sin6_port = tcp->tcp_fport;
18272 		sin6->sin6_addr = tcp->tcp_remote_v6;
18273 		if (tcp->tcp_ipversion == IPV6_VERSION) {
18274 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
18275 			    ~IPV6_VERS_AND_FLOW_MASK;
18276 		}
18277 		*salenp = sizeof (sin6_t);
18278 		break;
18279 	}
18280 
18281 	return (0);
18282 }
18283 
18284 /*
18285  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
18286  */
18287 static void
18288 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
18289 {
18290 	void	*data;
18291 	mblk_t	*datamp = mp->b_cont;
18292 	tcp_t	*tcp = Q_TO_TCP(q);
18293 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
18294 
18295 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
18296 		cmdp->cb_error = EPROTO;
18297 		qreply(q, mp);
18298 		return;
18299 	}
18300 
18301 	data = datamp->b_rptr;
18302 
18303 	switch (cmdp->cb_cmd) {
18304 	case TI_GETPEERNAME:
18305 		cmdp->cb_error = tcp_do_getpeername(tcp, data, &cmdp->cb_len);
18306 		break;
18307 	case TI_GETMYNAME:
18308 		cmdp->cb_error = tcp_do_getsockname(tcp, data, &cmdp->cb_len);
18309 		break;
18310 	default:
18311 		cmdp->cb_error = EINVAL;
18312 		break;
18313 	}
18314 
18315 	qreply(q, mp);
18316 }
18317 
18318 void
18319 tcp_wput(queue_t *q, mblk_t *mp)
18320 {
18321 	conn_t	*connp = Q_TO_CONN(q);
18322 	tcp_t	*tcp;
18323 	void (*output_proc)();
18324 	t_scalar_t type;
18325 	uchar_t *rptr;
18326 	struct iocblk	*iocp;
18327 	size_t size;
18328 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18329 
18330 	ASSERT(connp->conn_ref >= 2);
18331 
18332 	switch (DB_TYPE(mp)) {
18333 	case M_DATA:
18334 		tcp = connp->conn_tcp;
18335 		ASSERT(tcp != NULL);
18336 
18337 		size = msgdsize(mp);
18338 
18339 		mutex_enter(&tcp->tcp_non_sq_lock);
18340 		tcp->tcp_squeue_bytes += size;
18341 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18342 			tcp_setqfull(tcp);
18343 		}
18344 		mutex_exit(&tcp->tcp_non_sq_lock);
18345 
18346 		CONN_INC_REF(connp);
18347 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18348 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18349 		return;
18350 
18351 	case M_CMD:
18352 		tcp_wput_cmdblk(q, mp);
18353 		return;
18354 
18355 	case M_PROTO:
18356 	case M_PCPROTO:
18357 		/*
18358 		 * if it is a snmp message, don't get behind the squeue
18359 		 */
18360 		tcp = connp->conn_tcp;
18361 		rptr = mp->b_rptr;
18362 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18363 			type = ((union T_primitives *)rptr)->type;
18364 		} else {
18365 			if (tcp->tcp_debug) {
18366 				(void) strlog(TCP_MOD_ID, 0, 1,
18367 				    SL_ERROR|SL_TRACE,
18368 				    "tcp_wput_proto, dropping one...");
18369 			}
18370 			freemsg(mp);
18371 			return;
18372 		}
18373 		if (type == T_SVR4_OPTMGMT_REQ) {
18374 			/*
18375 			 * All Solaris components should pass a db_credp
18376 			 * for this TPI message, hence we ASSERT.
18377 			 * But in case there is some other M_PROTO that looks
18378 			 * like a TPI message sent by some other kernel
18379 			 * component, we check and return an error.
18380 			 */
18381 			cred_t	*cr = msg_getcred(mp, NULL);
18382 
18383 			ASSERT(cr != NULL);
18384 			if (cr == NULL) {
18385 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
18386 				return;
18387 			}
18388 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18389 			    cr)) {
18390 				/*
18391 				 * This was a SNMP request
18392 				 */
18393 				return;
18394 			} else {
18395 				output_proc = tcp_wput_proto;
18396 			}
18397 		} else {
18398 			output_proc = tcp_wput_proto;
18399 		}
18400 		break;
18401 	case M_IOCTL:
18402 		/*
18403 		 * Most ioctls can be processed right away without going via
18404 		 * squeues - process them right here. Those that do require
18405 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18406 		 * are processed by tcp_wput_ioctl().
18407 		 */
18408 		iocp = (struct iocblk *)mp->b_rptr;
18409 		tcp = connp->conn_tcp;
18410 
18411 		switch (iocp->ioc_cmd) {
18412 		case TCP_IOC_ABORT_CONN:
18413 			tcp_ioctl_abort_conn(q, mp);
18414 			return;
18415 		case TI_GETPEERNAME:
18416 		case TI_GETMYNAME:
18417 			mi_copyin(q, mp, NULL,
18418 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18419 			return;
18420 		case ND_SET:
18421 			/* nd_getset does the necessary checks */
18422 		case ND_GET:
18423 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18424 				CALL_IP_WPUT(connp, q, mp);
18425 				return;
18426 			}
18427 			qreply(q, mp);
18428 			return;
18429 		case TCP_IOC_DEFAULT_Q:
18430 			/*
18431 			 * Wants to be the default wq. Check the credentials
18432 			 * first, the rest is executed via squeue.
18433 			 */
18434 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18435 				iocp->ioc_error = EPERM;
18436 				iocp->ioc_count = 0;
18437 				mp->b_datap->db_type = M_IOCACK;
18438 				qreply(q, mp);
18439 				return;
18440 			}
18441 			output_proc = tcp_wput_ioctl;
18442 			break;
18443 		default:
18444 			output_proc = tcp_wput_ioctl;
18445 			break;
18446 		}
18447 		break;
18448 	default:
18449 		output_proc = tcp_wput_nondata;
18450 		break;
18451 	}
18452 
18453 	CONN_INC_REF(connp);
18454 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18455 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18456 }
18457 
18458 /*
18459  * Initial STREAMS write side put() procedure for sockets. It tries to
18460  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18461  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18462  * are handled by tcp_wput() as usual.
18463  *
18464  * All further messages will also be handled by tcp_wput() because we cannot
18465  * be sure that the above short cut is safe later.
18466  */
18467 static void
18468 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18469 {
18470 	conn_t			*connp = Q_TO_CONN(wq);
18471 	tcp_t			*tcp = connp->conn_tcp;
18472 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18473 
18474 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18475 	wq->q_qinfo = &tcp_winit;
18476 
18477 	ASSERT(IPCL_IS_TCP(connp));
18478 	ASSERT(TCP_IS_SOCKET(tcp));
18479 
18480 	if (DB_TYPE(mp) == M_PCPROTO &&
18481 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18482 	    car->PRIM_type == T_CAPABILITY_REQ) {
18483 		tcp_capability_req(tcp, mp);
18484 		return;
18485 	}
18486 
18487 	tcp_wput(wq, mp);
18488 }
18489 
18490 /* ARGSUSED */
18491 static void
18492 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18493 {
18494 #ifdef DEBUG
18495 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18496 #endif
18497 	freemsg(mp);
18498 }
18499 
18500 static boolean_t
18501 tcp_zcopy_check(tcp_t *tcp)
18502 {
18503 	conn_t	*connp = tcp->tcp_connp;
18504 	ire_t	*ire;
18505 	boolean_t	zc_enabled = B_FALSE;
18506 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18507 
18508 	if (do_tcpzcopy == 2)
18509 		zc_enabled = B_TRUE;
18510 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18511 	    IPCL_IS_CONNECTED(connp) &&
18512 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18513 	    connp->conn_dontroute == 0 &&
18514 	    !connp->conn_nexthop_set &&
18515 	    connp->conn_outgoing_ill == NULL &&
18516 	    do_tcpzcopy == 1) {
18517 		/*
18518 		 * the checks above  closely resemble the fast path checks
18519 		 * in tcp_send_data().
18520 		 */
18521 		mutex_enter(&connp->conn_lock);
18522 		ire = connp->conn_ire_cache;
18523 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18524 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18525 			IRE_REFHOLD(ire);
18526 			if (ire->ire_stq != NULL) {
18527 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18528 
18529 				zc_enabled = ill && (ill->ill_capabilities &
18530 				    ILL_CAPAB_ZEROCOPY) &&
18531 				    (ill->ill_zerocopy_capab->
18532 				    ill_zerocopy_flags != 0);
18533 			}
18534 			IRE_REFRELE(ire);
18535 		}
18536 		mutex_exit(&connp->conn_lock);
18537 	}
18538 	tcp->tcp_snd_zcopy_on = zc_enabled;
18539 	if (!TCP_IS_DETACHED(tcp)) {
18540 		if (zc_enabled) {
18541 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18542 			    ZCVMSAFE);
18543 			TCP_STAT(tcps, tcp_zcopy_on);
18544 		} else {
18545 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18546 			    ZCVMUNSAFE);
18547 			TCP_STAT(tcps, tcp_zcopy_off);
18548 		}
18549 	}
18550 	return (zc_enabled);
18551 }
18552 
18553 static mblk_t *
18554 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18555 {
18556 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18557 
18558 	if (do_tcpzcopy == 2)
18559 		return (bp);
18560 	else if (tcp->tcp_snd_zcopy_on) {
18561 		tcp->tcp_snd_zcopy_on = B_FALSE;
18562 		if (!TCP_IS_DETACHED(tcp)) {
18563 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
18564 			    ZCVMUNSAFE);
18565 			TCP_STAT(tcps, tcp_zcopy_disable);
18566 		}
18567 	}
18568 	return (tcp_zcopy_backoff(tcp, bp, 0));
18569 }
18570 
18571 /*
18572  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18573  * the original desballoca'ed segmapped mblk.
18574  */
18575 static mblk_t *
18576 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18577 {
18578 	mblk_t *head, *tail, *nbp;
18579 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18580 
18581 	if (IS_VMLOANED_MBLK(bp)) {
18582 		TCP_STAT(tcps, tcp_zcopy_backoff);
18583 		if ((head = copyb(bp)) == NULL) {
18584 			/* fail to backoff; leave it for the next backoff */
18585 			tcp->tcp_xmit_zc_clean = B_FALSE;
18586 			return (bp);
18587 		}
18588 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18589 			if (fix_xmitlist)
18590 				tcp_zcopy_notify(tcp);
18591 			else
18592 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18593 		}
18594 		nbp = bp->b_cont;
18595 		if (fix_xmitlist) {
18596 			head->b_prev = bp->b_prev;
18597 			head->b_next = bp->b_next;
18598 			if (tcp->tcp_xmit_tail == bp)
18599 				tcp->tcp_xmit_tail = head;
18600 		}
18601 		bp->b_next = NULL;
18602 		bp->b_prev = NULL;
18603 		freeb(bp);
18604 	} else {
18605 		head = bp;
18606 		nbp = bp->b_cont;
18607 	}
18608 	tail = head;
18609 	while (nbp) {
18610 		if (IS_VMLOANED_MBLK(nbp)) {
18611 			TCP_STAT(tcps, tcp_zcopy_backoff);
18612 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18613 				tcp->tcp_xmit_zc_clean = B_FALSE;
18614 				tail->b_cont = nbp;
18615 				return (head);
18616 			}
18617 			tail = tail->b_cont;
18618 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18619 				if (fix_xmitlist)
18620 					tcp_zcopy_notify(tcp);
18621 				else
18622 					tail->b_datap->db_struioflag |=
18623 					    STRUIO_ZCNOTIFY;
18624 			}
18625 			bp = nbp;
18626 			nbp = nbp->b_cont;
18627 			if (fix_xmitlist) {
18628 				tail->b_prev = bp->b_prev;
18629 				tail->b_next = bp->b_next;
18630 				if (tcp->tcp_xmit_tail == bp)
18631 					tcp->tcp_xmit_tail = tail;
18632 			}
18633 			bp->b_next = NULL;
18634 			bp->b_prev = NULL;
18635 			freeb(bp);
18636 		} else {
18637 			tail->b_cont = nbp;
18638 			tail = nbp;
18639 			nbp = nbp->b_cont;
18640 		}
18641 	}
18642 	if (fix_xmitlist) {
18643 		tcp->tcp_xmit_last = tail;
18644 		tcp->tcp_xmit_zc_clean = B_TRUE;
18645 	}
18646 	return (head);
18647 }
18648 
18649 static void
18650 tcp_zcopy_notify(tcp_t *tcp)
18651 {
18652 	struct stdata	*stp;
18653 	conn_t *connp;
18654 
18655 	if (tcp->tcp_detached)
18656 		return;
18657 	connp = tcp->tcp_connp;
18658 	if (IPCL_IS_NONSTR(connp)) {
18659 		(*connp->conn_upcalls->su_zcopy_notify)
18660 		    (connp->conn_upper_handle);
18661 		return;
18662 	}
18663 	stp = STREAM(tcp->tcp_rq);
18664 	mutex_enter(&stp->sd_lock);
18665 	stp->sd_flag |= STZCNOTIFY;
18666 	cv_broadcast(&stp->sd_zcopy_wait);
18667 	mutex_exit(&stp->sd_lock);
18668 }
18669 
18670 static boolean_t
18671 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
18672 {
18673 	ire_t	*ire;
18674 	conn_t	*connp = tcp->tcp_connp;
18675 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18676 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18677 
18678 	mutex_enter(&connp->conn_lock);
18679 	ire = connp->conn_ire_cache;
18680 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18681 
18682 	if ((ire != NULL) &&
18683 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
18684 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
18685 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18686 		IRE_REFHOLD(ire);
18687 		mutex_exit(&connp->conn_lock);
18688 	} else {
18689 		boolean_t cached = B_FALSE;
18690 		ts_label_t *tsl;
18691 
18692 		/* force a recheck later on */
18693 		tcp->tcp_ire_ill_check_done = B_FALSE;
18694 
18695 		TCP_DBGSTAT(tcps, tcp_ire_null1);
18696 		connp->conn_ire_cache = NULL;
18697 		mutex_exit(&connp->conn_lock);
18698 
18699 		if (ire != NULL)
18700 			IRE_REFRELE_NOTR(ire);
18701 
18702 		tsl = crgetlabel(CONN_CRED(connp));
18703 		ire = (dst ?
18704 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
18705 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18706 		    connp->conn_zoneid, tsl, ipst));
18707 
18708 		if (ire == NULL) {
18709 			TCP_STAT(tcps, tcp_ire_null);
18710 			return (B_FALSE);
18711 		}
18712 
18713 		IRE_REFHOLD_NOTR(ire);
18714 
18715 		mutex_enter(&connp->conn_lock);
18716 		if (CONN_CACHE_IRE(connp)) {
18717 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18718 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18719 				TCP_CHECK_IREINFO(tcp, ire);
18720 				connp->conn_ire_cache = ire;
18721 				cached = B_TRUE;
18722 			}
18723 			rw_exit(&ire->ire_bucket->irb_lock);
18724 		}
18725 		mutex_exit(&connp->conn_lock);
18726 
18727 		/*
18728 		 * We can continue to use the ire but since it was
18729 		 * not cached, we should drop the extra reference.
18730 		 */
18731 		if (!cached)
18732 			IRE_REFRELE_NOTR(ire);
18733 
18734 		/*
18735 		 * Rampart note: no need to select a new label here, since
18736 		 * labels are not allowed to change during the life of a TCP
18737 		 * connection.
18738 		 */
18739 	}
18740 
18741 	*irep = ire;
18742 
18743 	return (B_TRUE);
18744 }
18745 
18746 /*
18747  * Called from tcp_send() or tcp_send_data() to find workable IRE.
18748  *
18749  * 0 = success;
18750  * 1 = failed to find ire and ill.
18751  */
18752 static boolean_t
18753 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
18754 {
18755 	ipha_t		*ipha;
18756 	ipaddr_t	dst;
18757 	ire_t		*ire;
18758 	ill_t		*ill;
18759 	mblk_t		*ire_fp_mp;
18760 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18761 
18762 	if (mp != NULL)
18763 		ipha = (ipha_t *)mp->b_rptr;
18764 	else
18765 		ipha = tcp->tcp_ipha;
18766 	dst = ipha->ipha_dst;
18767 
18768 	if (!tcp_send_find_ire(tcp, &dst, &ire))
18769 		return (B_FALSE);
18770 
18771 	if ((ire->ire_flags & RTF_MULTIRT) ||
18772 	    (ire->ire_stq == NULL) ||
18773 	    (ire->ire_nce == NULL) ||
18774 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18775 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18776 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
18777 		TCP_STAT(tcps, tcp_ip_ire_send);
18778 		IRE_REFRELE(ire);
18779 		return (B_FALSE);
18780 	}
18781 
18782 	ill = ire_to_ill(ire);
18783 	ASSERT(ill != NULL);
18784 
18785 	if (!tcp->tcp_ire_ill_check_done) {
18786 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18787 		tcp->tcp_ire_ill_check_done = B_TRUE;
18788 	}
18789 
18790 	*irep = ire;
18791 	*illp = ill;
18792 
18793 	return (B_TRUE);
18794 }
18795 
18796 static void
18797 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18798 {
18799 	ipha_t		*ipha;
18800 	ipaddr_t	src;
18801 	ipaddr_t	dst;
18802 	uint32_t	cksum;
18803 	ire_t		*ire;
18804 	uint16_t	*up;
18805 	ill_t		*ill;
18806 	conn_t		*connp = tcp->tcp_connp;
18807 	uint32_t	hcksum_txflags = 0;
18808 	mblk_t		*ire_fp_mp;
18809 	uint_t		ire_fp_mp_len;
18810 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18811 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18812 	cred_t		*cr;
18813 	pid_t		cpid;
18814 
18815 	ASSERT(DB_TYPE(mp) == M_DATA);
18816 
18817 	/*
18818 	 * Here we need to handle the overloading of the cred_t for
18819 	 * both getpeerucred and TX.
18820 	 * If this is a SYN then the caller already set db_credp so
18821 	 * that getpeerucred will work. But if TX is in use we might have
18822 	 * a conn_peercred which is different, and we need to use that cred
18823 	 * to make TX use the correct label and label dependent route.
18824 	 */
18825 	if (is_system_labeled()) {
18826 		cr = msg_getcred(mp, &cpid);
18827 		if (cr == NULL || connp->conn_peercred != NULL)
18828 			mblk_setcred(mp, CONN_CRED(connp), cpid);
18829 	}
18830 
18831 	ipha = (ipha_t *)mp->b_rptr;
18832 	src = ipha->ipha_src;
18833 	dst = ipha->ipha_dst;
18834 
18835 	ASSERT(q != NULL);
18836 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
18837 
18838 	/*
18839 	 * Drop off fast path for IPv6 and also if options are present or
18840 	 * we need to resolve a TS label.
18841 	 */
18842 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18843 	    !IPCL_IS_CONNECTED(connp) ||
18844 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
18845 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18846 	    !connp->conn_ulp_labeled ||
18847 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18848 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18849 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
18850 		if (tcp->tcp_snd_zcopy_aware)
18851 			mp = tcp_zcopy_disable(tcp, mp);
18852 		TCP_STAT(tcps, tcp_ip_send);
18853 		CALL_IP_WPUT(connp, q, mp);
18854 		return;
18855 	}
18856 
18857 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
18858 		if (tcp->tcp_snd_zcopy_aware)
18859 			mp = tcp_zcopy_backoff(tcp, mp, 0);
18860 		CALL_IP_WPUT(connp, q, mp);
18861 		return;
18862 	}
18863 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
18864 	ire_fp_mp_len = MBLKL(ire_fp_mp);
18865 
18866 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18867 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18868 #ifndef _BIG_ENDIAN
18869 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18870 #endif
18871 
18872 	/*
18873 	 * Check to see if we need to re-enable LSO/MDT for this connection
18874 	 * because it was previously disabled due to changes in the ill;
18875 	 * note that by doing it here, this re-enabling only applies when
18876 	 * the packet is not dispatched through CALL_IP_WPUT().
18877 	 *
18878 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
18879 	 * case, since that's how we ended up here.  For IPv6, we do the
18880 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18881 	 */
18882 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
18883 		/*
18884 		 * Restore LSO for this connection, so that next time around
18885 		 * it is eligible to go through tcp_lsosend() path again.
18886 		 */
18887 		TCP_STAT(tcps, tcp_lso_enabled);
18888 		tcp->tcp_lso = B_TRUE;
18889 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
18890 		    "interface %s\n", (void *)connp, ill->ill_name));
18891 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18892 		/*
18893 		 * Restore MDT for this connection, so that next time around
18894 		 * it is eligible to go through tcp_multisend() path again.
18895 		 */
18896 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
18897 		tcp->tcp_mdt = B_TRUE;
18898 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18899 		    "interface %s\n", (void *)connp, ill->ill_name));
18900 	}
18901 
18902 	if (tcp->tcp_snd_zcopy_aware) {
18903 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18904 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18905 			mp = tcp_zcopy_disable(tcp, mp);
18906 		/*
18907 		 * we shouldn't need to reset ipha as the mp containing
18908 		 * ipha should never be a zero-copy mp.
18909 		 */
18910 	}
18911 
18912 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18913 		ASSERT(ill->ill_hcksum_capab != NULL);
18914 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18915 	}
18916 
18917 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18918 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18919 
18920 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18921 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18922 
18923 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18924 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18925 
18926 	/* Software checksum? */
18927 	if (DB_CKSUMFLAGS(mp) == 0) {
18928 		TCP_STAT(tcps, tcp_out_sw_cksum);
18929 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
18930 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18931 	}
18932 
18933 	/* Calculate IP header checksum if hardware isn't capable */
18934 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18935 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18936 		    ((uint16_t *)ipha)[4]);
18937 	}
18938 
18939 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18940 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18941 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18942 
18943 	UPDATE_OB_PKT_COUNT(ire);
18944 	ire->ire_last_used_time = lbolt;
18945 
18946 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
18947 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
18948 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
18949 	    ntohs(ipha->ipha_length));
18950 
18951 	DTRACE_PROBE4(ip4__physical__out__start,
18952 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
18953 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
18954 	    ipst->ips_ipv4firewall_physical_out,
18955 	    NULL, ill, ipha, mp, mp, 0, ipst);
18956 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
18957 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
18958 
18959 	if (mp != NULL) {
18960 		if (ipst->ips_ipobs_enabled) {
18961 			zoneid_t szone;
18962 
18963 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
18964 			    ipst, ALL_ZONES);
18965 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
18966 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
18967 		}
18968 
18969 		ILL_SEND_TX(ill, ire, connp, mp, 0, NULL);
18970 	}
18971 
18972 	IRE_REFRELE(ire);
18973 }
18974 
18975 /*
18976  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18977  * if the receiver shrinks the window, i.e. moves the right window to the
18978  * left, the we should not send new data, but should retransmit normally the
18979  * old unacked data between suna and suna + swnd. We might has sent data
18980  * that is now outside the new window, pretend that we didn't send  it.
18981  */
18982 static void
18983 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18984 {
18985 	uint32_t	snxt = tcp->tcp_snxt;
18986 	mblk_t		*xmit_tail;
18987 	int32_t		offset;
18988 
18989 	ASSERT(shrunk_count > 0);
18990 
18991 	/* Pretend we didn't send the data outside the window */
18992 	snxt -= shrunk_count;
18993 
18994 	/* Get the mblk and the offset in it per the shrunk window */
18995 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
18996 
18997 	ASSERT(xmit_tail != NULL);
18998 
18999 	/* Reset all the values per the now shrunk window */
19000 	tcp->tcp_snxt = snxt;
19001 	tcp->tcp_xmit_tail = xmit_tail;
19002 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19003 	    offset;
19004 	tcp->tcp_unsent += shrunk_count;
19005 
19006 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19007 		/*
19008 		 * Make sure the timer is running so that we will probe a zero
19009 		 * window.
19010 		 */
19011 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19012 }
19013 
19014 
19015 /*
19016  * The TCP normal data output path.
19017  * NOTE: the logic of the fast path is duplicated from this function.
19018  */
19019 static void
19020 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19021 {
19022 	int		len;
19023 	mblk_t		*local_time;
19024 	mblk_t		*mp1;
19025 	uint32_t	snxt;
19026 	int		tail_unsent;
19027 	int		tcpstate;
19028 	int		usable = 0;
19029 	mblk_t		*xmit_tail;
19030 	queue_t		*q = tcp->tcp_wq;
19031 	int32_t		mss;
19032 	int32_t		num_sack_blk = 0;
19033 	int32_t		tcp_hdr_len;
19034 	int32_t		tcp_tcp_hdr_len;
19035 	int		mdt_thres;
19036 	int		rc;
19037 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19038 	ip_stack_t	*ipst;
19039 
19040 	tcpstate = tcp->tcp_state;
19041 	if (mp == NULL) {
19042 		/*
19043 		 * tcp_wput_data() with NULL mp should only be called when
19044 		 * there is unsent data.
19045 		 */
19046 		ASSERT(tcp->tcp_unsent > 0);
19047 		/* Really tacky... but we need this for detached closes. */
19048 		len = tcp->tcp_unsent;
19049 		goto data_null;
19050 	}
19051 
19052 #if CCS_STATS
19053 	wrw_stats.tot.count++;
19054 	wrw_stats.tot.bytes += msgdsize(mp);
19055 #endif
19056 	ASSERT(mp->b_datap->db_type == M_DATA);
19057 	/*
19058 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19059 	 * or before a connection attempt has begun.
19060 	 */
19061 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19062 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19063 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19064 #ifdef DEBUG
19065 			cmn_err(CE_WARN,
19066 			    "tcp_wput_data: data after ordrel, %s",
19067 			    tcp_display(tcp, NULL,
19068 			    DISP_ADDR_AND_PORT));
19069 #else
19070 			if (tcp->tcp_debug) {
19071 				(void) strlog(TCP_MOD_ID, 0, 1,
19072 				    SL_TRACE|SL_ERROR,
19073 				    "tcp_wput_data: data after ordrel, %s\n",
19074 				    tcp_display(tcp, NULL,
19075 				    DISP_ADDR_AND_PORT));
19076 			}
19077 #endif /* DEBUG */
19078 		}
19079 		if (tcp->tcp_snd_zcopy_aware &&
19080 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19081 			tcp_zcopy_notify(tcp);
19082 		freemsg(mp);
19083 		mutex_enter(&tcp->tcp_non_sq_lock);
19084 		if (tcp->tcp_flow_stopped &&
19085 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19086 			tcp_clrqfull(tcp);
19087 		}
19088 		mutex_exit(&tcp->tcp_non_sq_lock);
19089 		return;
19090 	}
19091 
19092 	/* Strip empties */
19093 	for (;;) {
19094 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19095 		    (uintptr_t)INT_MAX);
19096 		len = (int)(mp->b_wptr - mp->b_rptr);
19097 		if (len > 0)
19098 			break;
19099 		mp1 = mp;
19100 		mp = mp->b_cont;
19101 		freeb(mp1);
19102 		if (!mp) {
19103 			return;
19104 		}
19105 	}
19106 
19107 	/* If we are the first on the list ... */
19108 	if (tcp->tcp_xmit_head == NULL) {
19109 		tcp->tcp_xmit_head = mp;
19110 		tcp->tcp_xmit_tail = mp;
19111 		tcp->tcp_xmit_tail_unsent = len;
19112 	} else {
19113 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19114 		struct datab *dp;
19115 
19116 		mp1 = tcp->tcp_xmit_last;
19117 		if (len < tcp_tx_pull_len &&
19118 		    (dp = mp1->b_datap)->db_ref == 1 &&
19119 		    dp->db_lim - mp1->b_wptr >= len) {
19120 			ASSERT(len > 0);
19121 			ASSERT(!mp1->b_cont);
19122 			if (len == 1) {
19123 				*mp1->b_wptr++ = *mp->b_rptr;
19124 			} else {
19125 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19126 				mp1->b_wptr += len;
19127 			}
19128 			if (mp1 == tcp->tcp_xmit_tail)
19129 				tcp->tcp_xmit_tail_unsent += len;
19130 			mp1->b_cont = mp->b_cont;
19131 			if (tcp->tcp_snd_zcopy_aware &&
19132 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19133 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19134 			freeb(mp);
19135 			mp = mp1;
19136 		} else {
19137 			tcp->tcp_xmit_last->b_cont = mp;
19138 		}
19139 		len += tcp->tcp_unsent;
19140 	}
19141 
19142 	/* Tack on however many more positive length mblks we have */
19143 	if ((mp1 = mp->b_cont) != NULL) {
19144 		do {
19145 			int tlen;
19146 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19147 			    (uintptr_t)INT_MAX);
19148 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19149 			if (tlen <= 0) {
19150 				mp->b_cont = mp1->b_cont;
19151 				freeb(mp1);
19152 			} else {
19153 				len += tlen;
19154 				mp = mp1;
19155 			}
19156 		} while ((mp1 = mp->b_cont) != NULL);
19157 	}
19158 	tcp->tcp_xmit_last = mp;
19159 	tcp->tcp_unsent = len;
19160 
19161 	if (urgent)
19162 		usable = 1;
19163 
19164 data_null:
19165 	snxt = tcp->tcp_snxt;
19166 	xmit_tail = tcp->tcp_xmit_tail;
19167 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19168 
19169 	/*
19170 	 * Note that tcp_mss has been adjusted to take into account the
19171 	 * timestamp option if applicable.  Because SACK options do not
19172 	 * appear in every TCP segments and they are of variable lengths,
19173 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19174 	 * the actual segment length when we need to send a segment which
19175 	 * includes SACK options.
19176 	 */
19177 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19178 		int32_t	opt_len;
19179 
19180 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19181 		    tcp->tcp_num_sack_blk);
19182 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19183 		    2 + TCPOPT_HEADER_LEN;
19184 		mss = tcp->tcp_mss - opt_len;
19185 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19186 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19187 	} else {
19188 		mss = tcp->tcp_mss;
19189 		tcp_hdr_len = tcp->tcp_hdr_len;
19190 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19191 	}
19192 
19193 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19194 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19195 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19196 	}
19197 	if (tcpstate == TCPS_SYN_RCVD) {
19198 		/*
19199 		 * The three-way connection establishment handshake is not
19200 		 * complete yet. We want to queue the data for transmission
19201 		 * after entering ESTABLISHED state (RFC793). A jump to
19202 		 * "done" label effectively leaves data on the queue.
19203 		 */
19204 		goto done;
19205 	} else {
19206 		int usable_r;
19207 
19208 		/*
19209 		 * In the special case when cwnd is zero, which can only
19210 		 * happen if the connection is ECN capable, return now.
19211 		 * New segments is sent using tcp_timer().  The timer
19212 		 * is set in tcp_rput_data().
19213 		 */
19214 		if (tcp->tcp_cwnd == 0) {
19215 			/*
19216 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19217 			 * finished.
19218 			 */
19219 			ASSERT(tcp->tcp_ecn_ok ||
19220 			    tcp->tcp_state < TCPS_ESTABLISHED);
19221 			return;
19222 		}
19223 
19224 		/* NOTE: trouble if xmitting while SYN not acked? */
19225 		usable_r = snxt - tcp->tcp_suna;
19226 		usable_r = tcp->tcp_swnd - usable_r;
19227 
19228 		/*
19229 		 * Check if the receiver has shrunk the window.  If
19230 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19231 		 * cannot be set as there is unsent data, so FIN cannot
19232 		 * be sent out.  Otherwise, we need to take into account
19233 		 * of FIN as it consumes an "invisible" sequence number.
19234 		 */
19235 		ASSERT(tcp->tcp_fin_sent == 0);
19236 		if (usable_r < 0) {
19237 			/*
19238 			 * The receiver has shrunk the window and we have sent
19239 			 * -usable_r date beyond the window, re-adjust.
19240 			 *
19241 			 * If TCP window scaling is enabled, there can be
19242 			 * round down error as the advertised receive window
19243 			 * is actually right shifted n bits.  This means that
19244 			 * the lower n bits info is wiped out.  It will look
19245 			 * like the window is shrunk.  Do a check here to
19246 			 * see if the shrunk amount is actually within the
19247 			 * error in window calculation.  If it is, just
19248 			 * return.  Note that this check is inside the
19249 			 * shrunk window check.  This makes sure that even
19250 			 * though tcp_process_shrunk_swnd() is not called,
19251 			 * we will stop further processing.
19252 			 */
19253 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19254 				tcp_process_shrunk_swnd(tcp, -usable_r);
19255 			}
19256 			return;
19257 		}
19258 
19259 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19260 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19261 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19262 
19263 		/* usable = MIN(usable, unsent) */
19264 		if (usable_r > len)
19265 			usable_r = len;
19266 
19267 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19268 		if (usable_r > 0) {
19269 			usable = usable_r;
19270 		} else {
19271 			/* Bypass all other unnecessary processing. */
19272 			goto done;
19273 		}
19274 	}
19275 
19276 	local_time = (mblk_t *)lbolt;
19277 
19278 	/*
19279 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19280 	 * BSD.  This is more in line with the true intent of Nagle.
19281 	 *
19282 	 * The conditions are:
19283 	 * 1. The amount of unsent data (or amount of data which can be
19284 	 *    sent, whichever is smaller) is less than Nagle limit.
19285 	 * 2. The last sent size is also less than Nagle limit.
19286 	 * 3. There is unack'ed data.
19287 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19288 	 *    Nagle algorithm.  This reduces the probability that urgent
19289 	 *    bytes get "merged" together.
19290 	 * 5. The app has not closed the connection.  This eliminates the
19291 	 *    wait time of the receiving side waiting for the last piece of
19292 	 *    (small) data.
19293 	 *
19294 	 * If all are satisified, exit without sending anything.  Note
19295 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19296 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19297 	 * 4095).
19298 	 */
19299 	if (usable < (int)tcp->tcp_naglim &&
19300 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19301 	    snxt != tcp->tcp_suna &&
19302 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19303 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19304 		goto done;
19305 	}
19306 
19307 	if (tcp->tcp_cork) {
19308 		/*
19309 		 * if the tcp->tcp_cork option is set, then we have to force
19310 		 * TCP not to send partial segment (smaller than MSS bytes).
19311 		 * We are calculating the usable now based on full mss and
19312 		 * will save the rest of remaining data for later.
19313 		 */
19314 		if (usable < mss)
19315 			goto done;
19316 		usable = (usable / mss) * mss;
19317 	}
19318 
19319 	/* Update the latest receive window size in TCP header. */
19320 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19321 	    tcp->tcp_tcph->th_win);
19322 
19323 	/*
19324 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19325 	 *
19326 	 * 1. Simple TCP/IP{v4,v6} (no options).
19327 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19328 	 * 3. If the TCP connection is in ESTABLISHED state.
19329 	 * 4. The TCP is not detached.
19330 	 *
19331 	 * If any of the above conditions have changed during the
19332 	 * connection, stop using LSO/MDT and restore the stream head
19333 	 * parameters accordingly.
19334 	 */
19335 	ipst = tcps->tcps_netstack->netstack_ip;
19336 
19337 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19338 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19339 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19340 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19341 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19342 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19343 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19344 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19345 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19346 		if (tcp->tcp_lso) {
19347 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19348 			tcp->tcp_lso = B_FALSE;
19349 		} else {
19350 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19351 			tcp->tcp_mdt = B_FALSE;
19352 		}
19353 
19354 		/* Anything other than detached is considered pathological */
19355 		if (!TCP_IS_DETACHED(tcp)) {
19356 			if (tcp->tcp_lso)
19357 				TCP_STAT(tcps, tcp_lso_disabled);
19358 			else
19359 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19360 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19361 		}
19362 	}
19363 
19364 	/* Use MDT if sendable amount is greater than the threshold */
19365 	if (tcp->tcp_mdt &&
19366 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19367 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19368 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19369 	    (tcp->tcp_valid_bits == 0 ||
19370 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19371 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19372 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19373 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19374 		    local_time, mdt_thres);
19375 	} else {
19376 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19377 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19378 		    local_time, INT_MAX);
19379 	}
19380 
19381 	/* Pretend that all we were trying to send really got sent */
19382 	if (rc < 0 && tail_unsent < 0) {
19383 		do {
19384 			xmit_tail = xmit_tail->b_cont;
19385 			xmit_tail->b_prev = local_time;
19386 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19387 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19388 			tail_unsent += (int)(xmit_tail->b_wptr -
19389 			    xmit_tail->b_rptr);
19390 		} while (tail_unsent < 0);
19391 	}
19392 done:;
19393 	tcp->tcp_xmit_tail = xmit_tail;
19394 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19395 	len = tcp->tcp_snxt - snxt;
19396 	if (len) {
19397 		/*
19398 		 * If new data was sent, need to update the notsack
19399 		 * list, which is, afterall, data blocks that have
19400 		 * not been sack'ed by the receiver.  New data is
19401 		 * not sack'ed.
19402 		 */
19403 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19404 			/* len is a negative value. */
19405 			tcp->tcp_pipe -= len;
19406 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19407 			    tcp->tcp_snxt, snxt,
19408 			    &(tcp->tcp_num_notsack_blk),
19409 			    &(tcp->tcp_cnt_notsack_list));
19410 		}
19411 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19412 		tcp->tcp_rack = tcp->tcp_rnxt;
19413 		tcp->tcp_rack_cnt = 0;
19414 		if ((snxt + len) == tcp->tcp_suna) {
19415 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19416 		}
19417 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19418 		/*
19419 		 * Didn't send anything. Make sure the timer is running
19420 		 * so that we will probe a zero window.
19421 		 */
19422 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19423 	}
19424 	/* Note that len is the amount we just sent but with a negative sign */
19425 	tcp->tcp_unsent += len;
19426 	mutex_enter(&tcp->tcp_non_sq_lock);
19427 	if (tcp->tcp_flow_stopped) {
19428 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19429 			tcp_clrqfull(tcp);
19430 		}
19431 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19432 		tcp_setqfull(tcp);
19433 	}
19434 	mutex_exit(&tcp->tcp_non_sq_lock);
19435 }
19436 
19437 /*
19438  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19439  * outgoing TCP header with the template header, as well as other
19440  * options such as time-stamp, ECN and/or SACK.
19441  */
19442 static void
19443 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19444 {
19445 	tcph_t *tcp_tmpl, *tcp_h;
19446 	uint32_t *dst, *src;
19447 	int hdrlen;
19448 
19449 	ASSERT(OK_32PTR(rptr));
19450 
19451 	/* Template header */
19452 	tcp_tmpl = tcp->tcp_tcph;
19453 
19454 	/* Header of outgoing packet */
19455 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19456 
19457 	/* dst and src are opaque 32-bit fields, used for copying */
19458 	dst = (uint32_t *)rptr;
19459 	src = (uint32_t *)tcp->tcp_iphc;
19460 	hdrlen = tcp->tcp_hdr_len;
19461 
19462 	/* Fill time-stamp option if needed */
19463 	if (tcp->tcp_snd_ts_ok) {
19464 		U32_TO_BE32((uint32_t)now,
19465 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19466 		U32_TO_BE32(tcp->tcp_ts_recent,
19467 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19468 	} else {
19469 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19470 	}
19471 
19472 	/*
19473 	 * Copy the template header; is this really more efficient than
19474 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19475 	 * but perhaps not for other scenarios.
19476 	 */
19477 	dst[0] = src[0];
19478 	dst[1] = src[1];
19479 	dst[2] = src[2];
19480 	dst[3] = src[3];
19481 	dst[4] = src[4];
19482 	dst[5] = src[5];
19483 	dst[6] = src[6];
19484 	dst[7] = src[7];
19485 	dst[8] = src[8];
19486 	dst[9] = src[9];
19487 	if (hdrlen -= 40) {
19488 		hdrlen >>= 2;
19489 		dst += 10;
19490 		src += 10;
19491 		do {
19492 			*dst++ = *src++;
19493 		} while (--hdrlen);
19494 	}
19495 
19496 	/*
19497 	 * Set the ECN info in the TCP header if it is not a zero
19498 	 * window probe.  Zero window probe is only sent in
19499 	 * tcp_wput_data() and tcp_timer().
19500 	 */
19501 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19502 		SET_ECT(tcp, rptr);
19503 
19504 		if (tcp->tcp_ecn_echo_on)
19505 			tcp_h->th_flags[0] |= TH_ECE;
19506 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19507 			tcp_h->th_flags[0] |= TH_CWR;
19508 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19509 		}
19510 	}
19511 
19512 	/* Fill in SACK options */
19513 	if (num_sack_blk > 0) {
19514 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19515 		sack_blk_t *tmp;
19516 		int32_t	i;
19517 
19518 		wptr[0] = TCPOPT_NOP;
19519 		wptr[1] = TCPOPT_NOP;
19520 		wptr[2] = TCPOPT_SACK;
19521 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19522 		    sizeof (sack_blk_t);
19523 		wptr += TCPOPT_REAL_SACK_LEN;
19524 
19525 		tmp = tcp->tcp_sack_list;
19526 		for (i = 0; i < num_sack_blk; i++) {
19527 			U32_TO_BE32(tmp[i].begin, wptr);
19528 			wptr += sizeof (tcp_seq);
19529 			U32_TO_BE32(tmp[i].end, wptr);
19530 			wptr += sizeof (tcp_seq);
19531 		}
19532 		tcp_h->th_offset_and_rsrvd[0] +=
19533 		    ((num_sack_blk * 2 + 1) << 4);
19534 	}
19535 }
19536 
19537 /*
19538  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19539  * the destination address and SAP attribute, and if necessary, the
19540  * hardware checksum offload attribute to a Multidata message.
19541  */
19542 static int
19543 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19544     const uint32_t start, const uint32_t stuff, const uint32_t end,
19545     const uint32_t flags, tcp_stack_t *tcps)
19546 {
19547 	/* Add global destination address & SAP attribute */
19548 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19549 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19550 		    "destination address+SAP\n"));
19551 
19552 		if (dlmp != NULL)
19553 			TCP_STAT(tcps, tcp_mdt_allocfail);
19554 		return (-1);
19555 	}
19556 
19557 	/* Add global hwcksum attribute */
19558 	if (hwcksum &&
19559 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19560 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19561 		    "checksum attribute\n"));
19562 
19563 		TCP_STAT(tcps, tcp_mdt_allocfail);
19564 		return (-1);
19565 	}
19566 
19567 	return (0);
19568 }
19569 
19570 /*
19571  * Smaller and private version of pdescinfo_t used specifically for TCP,
19572  * which allows for only two payload spans per packet.
19573  */
19574 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19575 
19576 /*
19577  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19578  * scheme, and returns one the following:
19579  *
19580  * -1 = failed allocation.
19581  *  0 = success; burst count reached, or usable send window is too small,
19582  *      and that we'd rather wait until later before sending again.
19583  */
19584 static int
19585 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19586     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19587     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19588     const int mdt_thres)
19589 {
19590 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19591 	multidata_t	*mmd;
19592 	uint_t		obsegs, obbytes, hdr_frag_sz;
19593 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19594 	int		num_burst_seg, max_pld;
19595 	pdesc_t		*pkt;
19596 	tcp_pdescinfo_t	tcp_pkt_info;
19597 	pdescinfo_t	*pkt_info;
19598 	int		pbuf_idx, pbuf_idx_nxt;
19599 	int		seg_len, len, spill, af;
19600 	boolean_t	add_buffer, zcopy, clusterwide;
19601 	boolean_t	rconfirm = B_FALSE;
19602 	boolean_t	done = B_FALSE;
19603 	uint32_t	cksum;
19604 	uint32_t	hwcksum_flags;
19605 	ire_t		*ire = NULL;
19606 	ill_t		*ill;
19607 	ipha_t		*ipha;
19608 	ip6_t		*ip6h;
19609 	ipaddr_t	src, dst;
19610 	ill_zerocopy_capab_t *zc_cap = NULL;
19611 	uint16_t	*up;
19612 	int		err;
19613 	conn_t		*connp;
19614 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19615 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19616 	int		usable_mmd, tail_unsent_mmd;
19617 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
19618 	mblk_t		*xmit_tail_mmd;
19619 	netstackid_t	stack_id;
19620 
19621 #ifdef	_BIG_ENDIAN
19622 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19623 #else
19624 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19625 #endif
19626 
19627 #define	PREP_NEW_MULTIDATA() {			\
19628 	mmd = NULL;				\
19629 	md_mp = md_hbuf = NULL;			\
19630 	cur_hdr_off = 0;			\
19631 	max_pld = tcp->tcp_mdt_max_pld;		\
19632 	pbuf_idx = pbuf_idx_nxt = -1;		\
19633 	add_buffer = B_TRUE;			\
19634 	zcopy = B_FALSE;			\
19635 }
19636 
19637 #define	PREP_NEW_PBUF() {			\
19638 	md_pbuf = md_pbuf_nxt = NULL;		\
19639 	pbuf_idx = pbuf_idx_nxt = -1;		\
19640 	cur_pld_off = 0;			\
19641 	first_snxt = *snxt;			\
19642 	ASSERT(*tail_unsent > 0);		\
19643 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19644 }
19645 
19646 	ASSERT(mdt_thres >= mss);
19647 	ASSERT(*usable > 0 && *usable > mdt_thres);
19648 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19649 	ASSERT(!TCP_IS_DETACHED(tcp));
19650 	ASSERT(tcp->tcp_valid_bits == 0 ||
19651 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19652 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19653 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19654 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19655 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19656 
19657 	connp = tcp->tcp_connp;
19658 	ASSERT(connp != NULL);
19659 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
19660 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19661 
19662 	stack_id = connp->conn_netstack->netstack_stackid;
19663 
19664 	usable_mmd = tail_unsent_mmd = 0;
19665 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
19666 	xmit_tail_mmd = NULL;
19667 	/*
19668 	 * Note that tcp will only declare at most 2 payload spans per
19669 	 * packet, which is much lower than the maximum allowable number
19670 	 * of packet spans per Multidata.  For this reason, we use the
19671 	 * privately declared and smaller descriptor info structure, in
19672 	 * order to save some stack space.
19673 	 */
19674 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19675 
19676 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19677 	if (af == AF_INET) {
19678 		dst = tcp->tcp_ipha->ipha_dst;
19679 		src = tcp->tcp_ipha->ipha_src;
19680 		ASSERT(!CLASSD(dst));
19681 	}
19682 	ASSERT(af == AF_INET ||
19683 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19684 
19685 	obsegs = obbytes = 0;
19686 	num_burst_seg = tcp->tcp_snd_burst;
19687 	md_mp_head = NULL;
19688 	PREP_NEW_MULTIDATA();
19689 
19690 	/*
19691 	 * Before we go on further, make sure there is an IRE that we can
19692 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19693 	 * in proceeding any further, and we should just hand everything
19694 	 * off to the legacy path.
19695 	 */
19696 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
19697 		goto legacy_send_no_md;
19698 
19699 	ASSERT(ire != NULL);
19700 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19701 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19702 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19703 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19704 	/*
19705 	 * If we do support loopback for MDT (which requires modifications
19706 	 * to the receiving paths), the following assertions should go away,
19707 	 * and we would be sending the Multidata to loopback conn later on.
19708 	 */
19709 	ASSERT(!IRE_IS_LOCAL(ire));
19710 	ASSERT(ire->ire_stq != NULL);
19711 
19712 	ill = ire_to_ill(ire);
19713 	ASSERT(ill != NULL);
19714 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19715 
19716 	if (!tcp->tcp_ire_ill_check_done) {
19717 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19718 		tcp->tcp_ire_ill_check_done = B_TRUE;
19719 	}
19720 
19721 	/*
19722 	 * If the underlying interface conditions have changed, or if the
19723 	 * new interface does not support MDT, go back to legacy path.
19724 	 */
19725 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19726 		/* don't go through this path anymore for this connection */
19727 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
19728 		tcp->tcp_mdt = B_FALSE;
19729 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19730 		    "interface %s\n", (void *)connp, ill->ill_name));
19731 		/* IRE will be released prior to returning */
19732 		goto legacy_send_no_md;
19733 	}
19734 
19735 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19736 		zc_cap = ill->ill_zerocopy_capab;
19737 
19738 	/*
19739 	 * Check if we can take tcp fast-path. Note that "incomplete"
19740 	 * ire's (where the link-layer for next hop is not resolved
19741 	 * or where the fast-path header in nce_fp_mp is not available
19742 	 * yet) are sent down the legacy (slow) path.
19743 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19744 	 */
19745 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19746 		/* IRE will be released prior to returning */
19747 		goto legacy_send_no_md;
19748 	}
19749 
19750 	/* go to legacy path if interface doesn't support zerocopy */
19751 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19752 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19753 		/* IRE will be released prior to returning */
19754 		goto legacy_send_no_md;
19755 	}
19756 
19757 	/* does the interface support hardware checksum offload? */
19758 	hwcksum_flags = 0;
19759 	if (ILL_HCKSUM_CAPABLE(ill) &&
19760 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19761 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19762 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19763 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19764 		    HCKSUM_IPHDRCKSUM)
19765 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19766 
19767 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19768 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19769 			hwcksum_flags |= HCK_FULLCKSUM;
19770 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19771 		    HCKSUM_INET_PARTIAL)
19772 			hwcksum_flags |= HCK_PARTIALCKSUM;
19773 	}
19774 
19775 	/*
19776 	 * Each header fragment consists of the leading extra space,
19777 	 * followed by the TCP/IP header, and the trailing extra space.
19778 	 * We make sure that each header fragment begins on a 32-bit
19779 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19780 	 * aligned in tcp_mdt_update).
19781 	 */
19782 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19783 	    tcp->tcp_mdt_hdr_tail), 4);
19784 
19785 	/* are we starting from the beginning of data block? */
19786 	if (*tail_unsent == 0) {
19787 		*xmit_tail = (*xmit_tail)->b_cont;
19788 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19789 		*tail_unsent = (int)MBLKL(*xmit_tail);
19790 	}
19791 
19792 	/*
19793 	 * Here we create one or more Multidata messages, each made up of
19794 	 * one header buffer and up to N payload buffers.  This entire
19795 	 * operation is done within two loops:
19796 	 *
19797 	 * The outer loop mostly deals with creating the Multidata message,
19798 	 * as well as the header buffer that gets added to it.  It also
19799 	 * links the Multidata messages together such that all of them can
19800 	 * be sent down to the lower layer in a single putnext call; this
19801 	 * linking behavior depends on the tcp_mdt_chain tunable.
19802 	 *
19803 	 * The inner loop takes an existing Multidata message, and adds
19804 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19805 	 * packetizes those buffers by filling up the corresponding header
19806 	 * buffer fragments with the proper IP and TCP headers, and by
19807 	 * describing the layout of each packet in the packet descriptors
19808 	 * that get added to the Multidata.
19809 	 */
19810 	do {
19811 		/*
19812 		 * If usable send window is too small, or data blocks in
19813 		 * transmit list are smaller than our threshold (i.e. app
19814 		 * performs large writes followed by small ones), we hand
19815 		 * off the control over to the legacy path.  Note that we'll
19816 		 * get back the control once it encounters a large block.
19817 		 */
19818 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19819 		    (*xmit_tail)->b_cont != NULL &&
19820 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19821 			/* send down what we've got so far */
19822 			if (md_mp_head != NULL) {
19823 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19824 				    obsegs, obbytes, &rconfirm);
19825 			}
19826 			/*
19827 			 * Pass control over to tcp_send(), but tell it to
19828 			 * return to us once a large-size transmission is
19829 			 * possible.
19830 			 */
19831 			TCP_STAT(tcps, tcp_mdt_legacy_small);
19832 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19833 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19834 			    tail_unsent, xmit_tail, local_time,
19835 			    mdt_thres)) <= 0) {
19836 				/* burst count reached, or alloc failed */
19837 				IRE_REFRELE(ire);
19838 				return (err);
19839 			}
19840 
19841 			/* tcp_send() may have sent everything, so check */
19842 			if (*usable <= 0) {
19843 				IRE_REFRELE(ire);
19844 				return (0);
19845 			}
19846 
19847 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
19848 			/*
19849 			 * We may have delivered the Multidata, so make sure
19850 			 * to re-initialize before the next round.
19851 			 */
19852 			md_mp_head = NULL;
19853 			obsegs = obbytes = 0;
19854 			num_burst_seg = tcp->tcp_snd_burst;
19855 			PREP_NEW_MULTIDATA();
19856 
19857 			/* are we starting from the beginning of data block? */
19858 			if (*tail_unsent == 0) {
19859 				*xmit_tail = (*xmit_tail)->b_cont;
19860 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19861 				    (uintptr_t)INT_MAX);
19862 				*tail_unsent = (int)MBLKL(*xmit_tail);
19863 			}
19864 		}
19865 		/*
19866 		 * Record current values for parameters we may need to pass
19867 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
19868 		 * each iteration of the outer loop (each multidata message
19869 		 * creation). If we have a failure in the inner loop, we send
19870 		 * any complete multidata messages we have before reverting
19871 		 * to using the traditional non-md path.
19872 		 */
19873 		snxt_mmd = *snxt;
19874 		usable_mmd = *usable;
19875 		xmit_tail_mmd = *xmit_tail;
19876 		tail_unsent_mmd = *tail_unsent;
19877 		obsegs_mmd = obsegs;
19878 		obbytes_mmd = obbytes;
19879 
19880 		/*
19881 		 * max_pld limits the number of mblks in tcp's transmit
19882 		 * queue that can be added to a Multidata message.  Once
19883 		 * this counter reaches zero, no more additional mblks
19884 		 * can be added to it.  What happens afterwards depends
19885 		 * on whether or not we are set to chain the Multidata
19886 		 * messages.  If we are to link them together, reset
19887 		 * max_pld to its original value (tcp_mdt_max_pld) and
19888 		 * prepare to create a new Multidata message which will
19889 		 * get linked to md_mp_head.  Else, leave it alone and
19890 		 * let the inner loop break on its own.
19891 		 */
19892 		if (tcp_mdt_chain && max_pld == 0)
19893 			PREP_NEW_MULTIDATA();
19894 
19895 		/* adding a payload buffer; re-initialize values */
19896 		if (add_buffer)
19897 			PREP_NEW_PBUF();
19898 
19899 		/*
19900 		 * If we don't have a Multidata, either because we just
19901 		 * (re)entered this outer loop, or after we branched off
19902 		 * to tcp_send above, setup the Multidata and header
19903 		 * buffer to be used.
19904 		 */
19905 		if (md_mp == NULL) {
19906 			int md_hbuflen;
19907 			uint32_t start, stuff;
19908 
19909 			/*
19910 			 * Calculate Multidata header buffer size large enough
19911 			 * to hold all of the headers that can possibly be
19912 			 * sent at this moment.  We'd rather over-estimate
19913 			 * the size than running out of space; this is okay
19914 			 * since this buffer is small anyway.
19915 			 */
19916 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19917 
19918 			/*
19919 			 * Start and stuff offset for partial hardware
19920 			 * checksum offload; these are currently for IPv4.
19921 			 * For full checksum offload, they are set to zero.
19922 			 */
19923 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19924 				if (af == AF_INET) {
19925 					start = IP_SIMPLE_HDR_LENGTH;
19926 					stuff = IP_SIMPLE_HDR_LENGTH +
19927 					    TCP_CHECKSUM_OFFSET;
19928 				} else {
19929 					start = IPV6_HDR_LEN;
19930 					stuff = IPV6_HDR_LEN +
19931 					    TCP_CHECKSUM_OFFSET;
19932 				}
19933 			} else {
19934 				start = stuff = 0;
19935 			}
19936 
19937 			/*
19938 			 * Create the header buffer, Multidata, as well as
19939 			 * any necessary attributes (destination address,
19940 			 * SAP and hardware checksum offload) that should
19941 			 * be associated with the Multidata message.
19942 			 */
19943 			ASSERT(cur_hdr_off == 0);
19944 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19945 			    ((md_hbuf->b_wptr += md_hbuflen),
19946 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19947 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19948 			    /* fastpath mblk */
19949 			    ire->ire_nce->nce_res_mp,
19950 			    /* hardware checksum enabled */
19951 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19952 			    /* hardware checksum offsets */
19953 			    start, stuff, 0,
19954 			    /* hardware checksum flag */
19955 			    hwcksum_flags, tcps) != 0)) {
19956 legacy_send:
19957 				/*
19958 				 * We arrive here from a failure within the
19959 				 * inner (packetizer) loop or we fail one of
19960 				 * the conditionals above. We restore the
19961 				 * previously checkpointed values for:
19962 				 *    xmit_tail
19963 				 *    usable
19964 				 *    tail_unsent
19965 				 *    snxt
19966 				 *    obbytes
19967 				 *    obsegs
19968 				 * We should then be able to dispatch any
19969 				 * complete multidata before reverting to the
19970 				 * traditional path with consistent parameters
19971 				 * (the inner loop updates these as it
19972 				 * iterates).
19973 				 */
19974 				*xmit_tail = xmit_tail_mmd;
19975 				*usable = usable_mmd;
19976 				*tail_unsent = tail_unsent_mmd;
19977 				*snxt = snxt_mmd;
19978 				obbytes = obbytes_mmd;
19979 				obsegs = obsegs_mmd;
19980 				if (md_mp != NULL) {
19981 					/* Unlink message from the chain */
19982 					if (md_mp_head != NULL) {
19983 						err = (intptr_t)rmvb(md_mp_head,
19984 						    md_mp);
19985 						/*
19986 						 * We can't assert that rmvb
19987 						 * did not return -1, since we
19988 						 * may get here before linkb
19989 						 * happens.  We do, however,
19990 						 * check if we just removed the
19991 						 * only element in the list.
19992 						 */
19993 						if (err == 0)
19994 							md_mp_head = NULL;
19995 					}
19996 					/* md_hbuf gets freed automatically */
19997 					TCP_STAT(tcps, tcp_mdt_discarded);
19998 					freeb(md_mp);
19999 				} else {
20000 					/* Either allocb or mmd_alloc failed */
20001 					TCP_STAT(tcps, tcp_mdt_allocfail);
20002 					if (md_hbuf != NULL)
20003 						freeb(md_hbuf);
20004 				}
20005 
20006 				/* send down what we've got so far */
20007 				if (md_mp_head != NULL) {
20008 					tcp_multisend_data(tcp, ire, ill,
20009 					    md_mp_head, obsegs, obbytes,
20010 					    &rconfirm);
20011 				}
20012 legacy_send_no_md:
20013 				if (ire != NULL)
20014 					IRE_REFRELE(ire);
20015 				/*
20016 				 * Too bad; let the legacy path handle this.
20017 				 * We specify INT_MAX for the threshold, since
20018 				 * we gave up with the Multidata processings
20019 				 * and let the old path have it all.
20020 				 */
20021 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20022 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20023 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20024 				    snxt, tail_unsent, xmit_tail, local_time,
20025 				    INT_MAX));
20026 			}
20027 
20028 			/* link to any existing ones, if applicable */
20029 			TCP_STAT(tcps, tcp_mdt_allocd);
20030 			if (md_mp_head == NULL) {
20031 				md_mp_head = md_mp;
20032 			} else if (tcp_mdt_chain) {
20033 				TCP_STAT(tcps, tcp_mdt_linked);
20034 				linkb(md_mp_head, md_mp);
20035 			}
20036 		}
20037 
20038 		ASSERT(md_mp_head != NULL);
20039 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20040 		ASSERT(md_mp != NULL && mmd != NULL);
20041 		ASSERT(md_hbuf != NULL);
20042 
20043 		/*
20044 		 * Packetize the transmittable portion of the data block;
20045 		 * each data block is essentially added to the Multidata
20046 		 * as a payload buffer.  We also deal with adding more
20047 		 * than one payload buffers, which happens when the remaining
20048 		 * packetized portion of the current payload buffer is less
20049 		 * than MSS, while the next data block in transmit queue
20050 		 * has enough data to make up for one.  This "spillover"
20051 		 * case essentially creates a split-packet, where portions
20052 		 * of the packet's payload fragments may span across two
20053 		 * virtually discontiguous address blocks.
20054 		 */
20055 		seg_len = mss;
20056 		do {
20057 			len = seg_len;
20058 
20059 			/* one must remain NULL for DTRACE_IP_FASTPATH */
20060 			ipha = NULL;
20061 			ip6h = NULL;
20062 
20063 			ASSERT(len > 0);
20064 			ASSERT(max_pld >= 0);
20065 			ASSERT(!add_buffer || cur_pld_off == 0);
20066 
20067 			/*
20068 			 * First time around for this payload buffer; note
20069 			 * in the case of a spillover, the following has
20070 			 * been done prior to adding the split-packet
20071 			 * descriptor to Multidata, and we don't want to
20072 			 * repeat the process.
20073 			 */
20074 			if (add_buffer) {
20075 				ASSERT(mmd != NULL);
20076 				ASSERT(md_pbuf == NULL);
20077 				ASSERT(md_pbuf_nxt == NULL);
20078 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20079 
20080 				/*
20081 				 * Have we reached the limit?  We'd get to
20082 				 * this case when we're not chaining the
20083 				 * Multidata messages together, and since
20084 				 * we're done, terminate this loop.
20085 				 */
20086 				if (max_pld == 0)
20087 					break; /* done */
20088 
20089 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20090 					TCP_STAT(tcps, tcp_mdt_allocfail);
20091 					goto legacy_send; /* out_of_mem */
20092 				}
20093 
20094 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20095 				    zc_cap != NULL) {
20096 					if (!ip_md_zcopy_attr(mmd, NULL,
20097 					    zc_cap->ill_zerocopy_flags)) {
20098 						freeb(md_pbuf);
20099 						TCP_STAT(tcps,
20100 						    tcp_mdt_allocfail);
20101 						/* out_of_mem */
20102 						goto legacy_send;
20103 					}
20104 					zcopy = B_TRUE;
20105 				}
20106 
20107 				md_pbuf->b_rptr += base_pld_off;
20108 
20109 				/*
20110 				 * Add a payload buffer to the Multidata; this
20111 				 * operation must not fail, or otherwise our
20112 				 * logic in this routine is broken.  There
20113 				 * is no memory allocation done by the
20114 				 * routine, so any returned failure simply
20115 				 * tells us that we've done something wrong.
20116 				 *
20117 				 * A failure tells us that either we're adding
20118 				 * the same payload buffer more than once, or
20119 				 * we're trying to add more buffers than
20120 				 * allowed (max_pld calculation is wrong).
20121 				 * None of the above cases should happen, and
20122 				 * we panic because either there's horrible
20123 				 * heap corruption, and/or programming mistake.
20124 				 */
20125 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20126 				if (pbuf_idx < 0) {
20127 					cmn_err(CE_PANIC, "tcp_multisend: "
20128 					    "payload buffer logic error "
20129 					    "detected for tcp %p mmd %p "
20130 					    "pbuf %p (%d)\n",
20131 					    (void *)tcp, (void *)mmd,
20132 					    (void *)md_pbuf, pbuf_idx);
20133 				}
20134 
20135 				ASSERT(max_pld > 0);
20136 				--max_pld;
20137 				add_buffer = B_FALSE;
20138 			}
20139 
20140 			ASSERT(md_mp_head != NULL);
20141 			ASSERT(md_pbuf != NULL);
20142 			ASSERT(md_pbuf_nxt == NULL);
20143 			ASSERT(pbuf_idx != -1);
20144 			ASSERT(pbuf_idx_nxt == -1);
20145 			ASSERT(*usable > 0);
20146 
20147 			/*
20148 			 * We spillover to the next payload buffer only
20149 			 * if all of the following is true:
20150 			 *
20151 			 *   1. There is not enough data on the current
20152 			 *	payload buffer to make up `len',
20153 			 *   2. We are allowed to send `len',
20154 			 *   3. The next payload buffer length is large
20155 			 *	enough to accomodate `spill'.
20156 			 */
20157 			if ((spill = len - *tail_unsent) > 0 &&
20158 			    *usable >= len &&
20159 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20160 			    max_pld > 0) {
20161 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20162 				if (md_pbuf_nxt == NULL) {
20163 					TCP_STAT(tcps, tcp_mdt_allocfail);
20164 					goto legacy_send; /* out_of_mem */
20165 				}
20166 
20167 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20168 				    zc_cap != NULL) {
20169 					if (!ip_md_zcopy_attr(mmd, NULL,
20170 					    zc_cap->ill_zerocopy_flags)) {
20171 						freeb(md_pbuf_nxt);
20172 						TCP_STAT(tcps,
20173 						    tcp_mdt_allocfail);
20174 						/* out_of_mem */
20175 						goto legacy_send;
20176 					}
20177 					zcopy = B_TRUE;
20178 				}
20179 
20180 				/*
20181 				 * See comments above on the first call to
20182 				 * mmd_addpldbuf for explanation on the panic.
20183 				 */
20184 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20185 				if (pbuf_idx_nxt < 0) {
20186 					panic("tcp_multisend: "
20187 					    "next payload buffer logic error "
20188 					    "detected for tcp %p mmd %p "
20189 					    "pbuf %p (%d)\n",
20190 					    (void *)tcp, (void *)mmd,
20191 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20192 				}
20193 
20194 				ASSERT(max_pld > 0);
20195 				--max_pld;
20196 			} else if (spill > 0) {
20197 				/*
20198 				 * If there's a spillover, but the following
20199 				 * xmit_tail couldn't give us enough octets
20200 				 * to reach "len", then stop the current
20201 				 * Multidata creation and let the legacy
20202 				 * tcp_send() path take over.  We don't want
20203 				 * to send the tiny segment as part of this
20204 				 * Multidata for performance reasons; instead,
20205 				 * we let the legacy path deal with grouping
20206 				 * it with the subsequent small mblks.
20207 				 */
20208 				if (*usable >= len &&
20209 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20210 					max_pld = 0;
20211 					break;	/* done */
20212 				}
20213 
20214 				/*
20215 				 * We can't spillover, and we are near
20216 				 * the end of the current payload buffer,
20217 				 * so send what's left.
20218 				 */
20219 				ASSERT(*tail_unsent > 0);
20220 				len = *tail_unsent;
20221 			}
20222 
20223 			/* tail_unsent is negated if there is a spillover */
20224 			*tail_unsent -= len;
20225 			*usable -= len;
20226 			ASSERT(*usable >= 0);
20227 
20228 			if (*usable < mss)
20229 				seg_len = *usable;
20230 			/*
20231 			 * Sender SWS avoidance; see comments in tcp_send();
20232 			 * everything else is the same, except that we only
20233 			 * do this here if there is no more data to be sent
20234 			 * following the current xmit_tail.  We don't check
20235 			 * for 1-byte urgent data because we shouldn't get
20236 			 * here if TCP_URG_VALID is set.
20237 			 */
20238 			if (*usable > 0 && *usable < mss &&
20239 			    ((md_pbuf_nxt == NULL &&
20240 			    (*xmit_tail)->b_cont == NULL) ||
20241 			    (md_pbuf_nxt != NULL &&
20242 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20243 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20244 			    (tcp->tcp_unsent -
20245 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20246 			    !tcp->tcp_zero_win_probe) {
20247 				if ((*snxt + len) == tcp->tcp_snxt &&
20248 				    (*snxt + len) == tcp->tcp_suna) {
20249 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20250 				}
20251 				done = B_TRUE;
20252 			}
20253 
20254 			/*
20255 			 * Prime pump for IP's checksumming on our behalf;
20256 			 * include the adjustment for a source route if any.
20257 			 * Do this only for software/partial hardware checksum
20258 			 * offload, as this field gets zeroed out later for
20259 			 * the full hardware checksum offload case.
20260 			 */
20261 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20262 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20263 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20264 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20265 			}
20266 
20267 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20268 			*snxt += len;
20269 
20270 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20271 			/*
20272 			 * We set the PUSH bit only if TCP has no more buffered
20273 			 * data to be transmitted (or if sender SWS avoidance
20274 			 * takes place), as opposed to setting it for every
20275 			 * last packet in the burst.
20276 			 */
20277 			if (done ||
20278 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20279 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20280 
20281 			/*
20282 			 * Set FIN bit if this is our last segment; snxt
20283 			 * already includes its length, and it will not
20284 			 * be adjusted after this point.
20285 			 */
20286 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20287 			    *snxt == tcp->tcp_fss) {
20288 				if (!tcp->tcp_fin_acked) {
20289 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20290 					BUMP_MIB(&tcps->tcps_mib,
20291 					    tcpOutControl);
20292 				}
20293 				if (!tcp->tcp_fin_sent) {
20294 					tcp->tcp_fin_sent = B_TRUE;
20295 					/*
20296 					 * tcp state must be ESTABLISHED
20297 					 * in order for us to get here in
20298 					 * the first place.
20299 					 */
20300 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20301 
20302 					/*
20303 					 * Upon returning from this routine,
20304 					 * tcp_wput_data() will set tcp_snxt
20305 					 * to be equal to snxt + tcp_fin_sent.
20306 					 * This is essentially the same as
20307 					 * setting it to tcp_fss + 1.
20308 					 */
20309 				}
20310 			}
20311 
20312 			tcp->tcp_last_sent_len = (ushort_t)len;
20313 
20314 			len += tcp_hdr_len;
20315 			if (tcp->tcp_ipversion == IPV4_VERSION)
20316 				tcp->tcp_ipha->ipha_length = htons(len);
20317 			else
20318 				tcp->tcp_ip6h->ip6_plen = htons(len -
20319 				    ((char *)&tcp->tcp_ip6h[1] -
20320 				    tcp->tcp_iphc));
20321 
20322 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20323 
20324 			/* setup header fragment */
20325 			PDESC_HDR_ADD(pkt_info,
20326 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20327 			    tcp->tcp_mdt_hdr_head,		/* head room */
20328 			    tcp_hdr_len,			/* len */
20329 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20330 
20331 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20332 			    hdr_frag_sz);
20333 			ASSERT(MBLKIN(md_hbuf,
20334 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20335 			    PDESC_HDRSIZE(pkt_info)));
20336 
20337 			/* setup first payload fragment */
20338 			PDESC_PLD_INIT(pkt_info);
20339 			PDESC_PLD_SPAN_ADD(pkt_info,
20340 			    pbuf_idx,				/* index */
20341 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20342 			    tcp->tcp_last_sent_len);		/* len */
20343 
20344 			/* create a split-packet in case of a spillover */
20345 			if (md_pbuf_nxt != NULL) {
20346 				ASSERT(spill > 0);
20347 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20348 				ASSERT(!add_buffer);
20349 
20350 				md_pbuf = md_pbuf_nxt;
20351 				md_pbuf_nxt = NULL;
20352 				pbuf_idx = pbuf_idx_nxt;
20353 				pbuf_idx_nxt = -1;
20354 				cur_pld_off = spill;
20355 
20356 				/* trim out first payload fragment */
20357 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20358 
20359 				/* setup second payload fragment */
20360 				PDESC_PLD_SPAN_ADD(pkt_info,
20361 				    pbuf_idx,			/* index */
20362 				    md_pbuf->b_rptr,		/* start */
20363 				    spill);			/* len */
20364 
20365 				if ((*xmit_tail)->b_next == NULL) {
20366 					/*
20367 					 * Store the lbolt used for RTT
20368 					 * estimation. We can only record one
20369 					 * timestamp per mblk so we do it when
20370 					 * we reach the end of the payload
20371 					 * buffer.  Also we only take a new
20372 					 * timestamp sample when the previous
20373 					 * timed data from the same mblk has
20374 					 * been ack'ed.
20375 					 */
20376 					(*xmit_tail)->b_prev = local_time;
20377 					(*xmit_tail)->b_next =
20378 					    (mblk_t *)(uintptr_t)first_snxt;
20379 				}
20380 
20381 				first_snxt = *snxt - spill;
20382 
20383 				/*
20384 				 * Advance xmit_tail; usable could be 0 by
20385 				 * the time we got here, but we made sure
20386 				 * above that we would only spillover to
20387 				 * the next data block if usable includes
20388 				 * the spilled-over amount prior to the
20389 				 * subtraction.  Therefore, we are sure
20390 				 * that xmit_tail->b_cont can't be NULL.
20391 				 */
20392 				ASSERT((*xmit_tail)->b_cont != NULL);
20393 				*xmit_tail = (*xmit_tail)->b_cont;
20394 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20395 				    (uintptr_t)INT_MAX);
20396 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20397 			} else {
20398 				cur_pld_off += tcp->tcp_last_sent_len;
20399 			}
20400 
20401 			/*
20402 			 * Fill in the header using the template header, and
20403 			 * add options such as time-stamp, ECN and/or SACK,
20404 			 * as needed.
20405 			 */
20406 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20407 			    (clock_t)local_time, num_sack_blk);
20408 
20409 			/* take care of some IP header businesses */
20410 			if (af == AF_INET) {
20411 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20412 
20413 				ASSERT(OK_32PTR((uchar_t *)ipha));
20414 				ASSERT(PDESC_HDRL(pkt_info) >=
20415 				    IP_SIMPLE_HDR_LENGTH);
20416 				ASSERT(ipha->ipha_version_and_hdr_length ==
20417 				    IP_SIMPLE_HDR_VERSION);
20418 
20419 				/*
20420 				 * Assign ident value for current packet; see
20421 				 * related comments in ip_wput_ire() about the
20422 				 * contract private interface with clustering
20423 				 * group.
20424 				 */
20425 				clusterwide = B_FALSE;
20426 				if (cl_inet_ipident != NULL) {
20427 					ASSERT(cl_inet_isclusterwide != NULL);
20428 					if ((*cl_inet_isclusterwide)(stack_id,
20429 					    IPPROTO_IP, AF_INET,
20430 					    (uint8_t *)(uintptr_t)src, NULL)) {
20431 						ipha->ipha_ident =
20432 						    (*cl_inet_ipident)(stack_id,
20433 						    IPPROTO_IP, AF_INET,
20434 						    (uint8_t *)(uintptr_t)src,
20435 						    (uint8_t *)(uintptr_t)dst,
20436 						    NULL);
20437 						clusterwide = B_TRUE;
20438 					}
20439 				}
20440 
20441 				if (!clusterwide) {
20442 					ipha->ipha_ident = (uint16_t)
20443 					    atomic_add_32_nv(
20444 						&ire->ire_ident, 1);
20445 				}
20446 #ifndef _BIG_ENDIAN
20447 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20448 				    (ipha->ipha_ident >> 8);
20449 #endif
20450 			} else {
20451 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20452 
20453 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20454 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20455 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20456 				ASSERT(PDESC_HDRL(pkt_info) >=
20457 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20458 				    TCP_CHECKSUM_SIZE));
20459 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20460 
20461 				if (tcp->tcp_ip_forward_progress) {
20462 					rconfirm = B_TRUE;
20463 					tcp->tcp_ip_forward_progress = B_FALSE;
20464 				}
20465 			}
20466 
20467 			/* at least one payload span, and at most two */
20468 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20469 
20470 			/* add the packet descriptor to Multidata */
20471 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20472 			    KM_NOSLEEP)) == NULL) {
20473 				/*
20474 				 * Any failure other than ENOMEM indicates
20475 				 * that we have passed in invalid pkt_info
20476 				 * or parameters to mmd_addpdesc, which must
20477 				 * not happen.
20478 				 *
20479 				 * EINVAL is a result of failure on boundary
20480 				 * checks against the pkt_info contents.  It
20481 				 * should not happen, and we panic because
20482 				 * either there's horrible heap corruption,
20483 				 * and/or programming mistake.
20484 				 */
20485 				if (err != ENOMEM) {
20486 					cmn_err(CE_PANIC, "tcp_multisend: "
20487 					    "pdesc logic error detected for "
20488 					    "tcp %p mmd %p pinfo %p (%d)\n",
20489 					    (void *)tcp, (void *)mmd,
20490 					    (void *)pkt_info, err);
20491 				}
20492 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20493 				goto legacy_send; /* out_of_mem */
20494 			}
20495 			ASSERT(pkt != NULL);
20496 
20497 			/* calculate IP header and TCP checksums */
20498 			if (af == AF_INET) {
20499 				/* calculate pseudo-header checksum */
20500 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20501 				    (src >> 16) + (src & 0xFFFF);
20502 
20503 				/* offset for TCP header checksum */
20504 				up = IPH_TCPH_CHECKSUMP(ipha,
20505 				    IP_SIMPLE_HDR_LENGTH);
20506 			} else {
20507 				up = (uint16_t *)&ip6h->ip6_src;
20508 
20509 				/* calculate pseudo-header checksum */
20510 				cksum = up[0] + up[1] + up[2] + up[3] +
20511 				    up[4] + up[5] + up[6] + up[7] +
20512 				    up[8] + up[9] + up[10] + up[11] +
20513 				    up[12] + up[13] + up[14] + up[15];
20514 
20515 				/* Fold the initial sum */
20516 				cksum = (cksum & 0xffff) + (cksum >> 16);
20517 
20518 				up = (uint16_t *)(((uchar_t *)ip6h) +
20519 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20520 			}
20521 
20522 			if (hwcksum_flags & HCK_FULLCKSUM) {
20523 				/* clear checksum field for hardware */
20524 				*up = 0;
20525 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20526 				uint32_t sum;
20527 
20528 				/* pseudo-header checksumming */
20529 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20530 				sum = (sum & 0xFFFF) + (sum >> 16);
20531 				*up = (sum & 0xFFFF) + (sum >> 16);
20532 			} else {
20533 				/* software checksumming */
20534 				TCP_STAT(tcps, tcp_out_sw_cksum);
20535 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20536 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20537 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20538 				    cksum + IP_TCP_CSUM_COMP);
20539 				if (*up == 0)
20540 					*up = 0xFFFF;
20541 			}
20542 
20543 			/* IPv4 header checksum */
20544 			if (af == AF_INET) {
20545 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20546 					ipha->ipha_hdr_checksum = 0;
20547 				} else {
20548 					IP_HDR_CKSUM(ipha, cksum,
20549 					    ((uint32_t *)ipha)[0],
20550 					    ((uint16_t *)ipha)[4]);
20551 				}
20552 			}
20553 
20554 			if (af == AF_INET &&
20555 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20556 			    af == AF_INET6 &&
20557 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20558 				mblk_t	*mp, *mp1;
20559 				uchar_t	*hdr_rptr, *hdr_wptr;
20560 				uchar_t	*pld_rptr, *pld_wptr;
20561 
20562 				/*
20563 				 * We reconstruct a pseudo packet for the hooks
20564 				 * framework using mmd_transform_link().
20565 				 * If it is a split packet we pullup the
20566 				 * payload. FW_HOOKS expects a pkt comprising
20567 				 * of two mblks: a header and the payload.
20568 				 */
20569 				if ((mp = mmd_transform_link(pkt)) == NULL) {
20570 					TCP_STAT(tcps, tcp_mdt_allocfail);
20571 					goto legacy_send;
20572 				}
20573 
20574 				if (pkt_info->pld_cnt > 1) {
20575 					/* split payload, more than one pld */
20576 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
20577 					    NULL) {
20578 						freemsg(mp);
20579 						TCP_STAT(tcps,
20580 						    tcp_mdt_allocfail);
20581 						goto legacy_send;
20582 					}
20583 					freemsg(mp->b_cont);
20584 					mp->b_cont = mp1;
20585 				} else {
20586 					mp1 = mp->b_cont;
20587 				}
20588 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
20589 
20590 				/*
20591 				 * Remember the message offsets. This is so we
20592 				 * can detect changes when we return from the
20593 				 * FW_HOOKS callbacks.
20594 				 */
20595 				hdr_rptr = mp->b_rptr;
20596 				hdr_wptr = mp->b_wptr;
20597 				pld_rptr = mp->b_cont->b_rptr;
20598 				pld_wptr = mp->b_cont->b_wptr;
20599 
20600 				if (af == AF_INET) {
20601 					DTRACE_PROBE4(
20602 					    ip4__physical__out__start,
20603 					    ill_t *, NULL,
20604 					    ill_t *, ill,
20605 					    ipha_t *, ipha,
20606 					    mblk_t *, mp);
20607 					FW_HOOKS(
20608 					    ipst->ips_ip4_physical_out_event,
20609 					    ipst->ips_ipv4firewall_physical_out,
20610 					    NULL, ill, ipha, mp, mp, 0, ipst);
20611 					DTRACE_PROBE1(
20612 					    ip4__physical__out__end,
20613 					    mblk_t *, mp);
20614 				} else {
20615 					DTRACE_PROBE4(
20616 					    ip6__physical__out_start,
20617 					    ill_t *, NULL,
20618 					    ill_t *, ill,
20619 					    ip6_t *, ip6h,
20620 					    mblk_t *, mp);
20621 					FW_HOOKS6(
20622 					    ipst->ips_ip6_physical_out_event,
20623 					    ipst->ips_ipv6firewall_physical_out,
20624 					    NULL, ill, ip6h, mp, mp, 0, ipst);
20625 					DTRACE_PROBE1(
20626 					    ip6__physical__out__end,
20627 					    mblk_t *, mp);
20628 				}
20629 
20630 				if (mp == NULL ||
20631 				    (mp1 = mp->b_cont) == NULL ||
20632 				    mp->b_rptr != hdr_rptr ||
20633 				    mp->b_wptr != hdr_wptr ||
20634 				    mp1->b_rptr != pld_rptr ||
20635 				    mp1->b_wptr != pld_wptr ||
20636 				    mp1->b_cont != NULL) {
20637 					/*
20638 					 * We abandon multidata processing and
20639 					 * return to the normal path, either
20640 					 * when a packet is blocked, or when
20641 					 * the boundaries of header buffer or
20642 					 * payload buffer have been changed by
20643 					 * FW_HOOKS[6].
20644 					 */
20645 					if (mp != NULL)
20646 						freemsg(mp);
20647 					goto legacy_send;
20648 				}
20649 				/* Finished with the pseudo packet */
20650 				freemsg(mp);
20651 			}
20652 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
20653 			    ill, ipha, ip6h);
20654 			/* advance header offset */
20655 			cur_hdr_off += hdr_frag_sz;
20656 
20657 			obbytes += tcp->tcp_last_sent_len;
20658 			++obsegs;
20659 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20660 		    *tail_unsent > 0);
20661 
20662 		if ((*xmit_tail)->b_next == NULL) {
20663 			/*
20664 			 * Store the lbolt used for RTT estimation. We can only
20665 			 * record one timestamp per mblk so we do it when we
20666 			 * reach the end of the payload buffer. Also we only
20667 			 * take a new timestamp sample when the previous timed
20668 			 * data from the same mblk has been ack'ed.
20669 			 */
20670 			(*xmit_tail)->b_prev = local_time;
20671 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20672 		}
20673 
20674 		ASSERT(*tail_unsent >= 0);
20675 		if (*tail_unsent > 0) {
20676 			/*
20677 			 * We got here because we broke out of the above
20678 			 * loop due to of one of the following cases:
20679 			 *
20680 			 *   1. len < adjusted MSS (i.e. small),
20681 			 *   2. Sender SWS avoidance,
20682 			 *   3. max_pld is zero.
20683 			 *
20684 			 * We are done for this Multidata, so trim our
20685 			 * last payload buffer (if any) accordingly.
20686 			 */
20687 			if (md_pbuf != NULL)
20688 				md_pbuf->b_wptr -= *tail_unsent;
20689 		} else if (*usable > 0) {
20690 			*xmit_tail = (*xmit_tail)->b_cont;
20691 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20692 			    (uintptr_t)INT_MAX);
20693 			*tail_unsent = (int)MBLKL(*xmit_tail);
20694 			add_buffer = B_TRUE;
20695 		}
20696 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20697 	    (tcp_mdt_chain || max_pld > 0));
20698 
20699 	if (md_mp_head != NULL) {
20700 		/* send everything down */
20701 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20702 		    &rconfirm);
20703 	}
20704 
20705 #undef PREP_NEW_MULTIDATA
20706 #undef PREP_NEW_PBUF
20707 #undef IPVER
20708 
20709 	IRE_REFRELE(ire);
20710 	return (0);
20711 }
20712 
20713 /*
20714  * A wrapper function for sending one or more Multidata messages down to
20715  * the module below ip; this routine does not release the reference of the
20716  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20717  */
20718 static void
20719 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20720     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20721 {
20722 	uint64_t delta;
20723 	nce_t *nce;
20724 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20725 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20726 
20727 	ASSERT(ire != NULL && ill != NULL);
20728 	ASSERT(ire->ire_stq != NULL);
20729 	ASSERT(md_mp_head != NULL);
20730 	ASSERT(rconfirm != NULL);
20731 
20732 	/* adjust MIBs and IRE timestamp */
20733 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
20734 	tcp->tcp_obsegs += obsegs;
20735 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
20736 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
20737 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
20738 
20739 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20740 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
20741 	} else {
20742 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
20743 	}
20744 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
20745 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
20746 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
20747 
20748 	ire->ire_ob_pkt_count += obsegs;
20749 	if (ire->ire_ipif != NULL)
20750 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20751 	ire->ire_last_used_time = lbolt;
20752 
20753 	if (ipst->ips_ipobs_enabled) {
20754 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
20755 		pdesc_t *dl_pkt;
20756 		pdescinfo_t pinfo;
20757 		mblk_t *nmp;
20758 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
20759 
20760 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
20761 		    (dl_pkt != NULL);
20762 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
20763 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
20764 				continue;
20765 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
20766 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
20767 			freemsg(nmp);
20768 		}
20769 	}
20770 
20771 	/* send it down */
20772 	putnext(ire->ire_stq, md_mp_head);
20773 
20774 	/* we're done for TCP/IPv4 */
20775 	if (tcp->tcp_ipversion == IPV4_VERSION)
20776 		return;
20777 
20778 	nce = ire->ire_nce;
20779 
20780 	ASSERT(nce != NULL);
20781 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20782 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20783 
20784 	/* reachability confirmation? */
20785 	if (*rconfirm) {
20786 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20787 		if (nce->nce_state != ND_REACHABLE) {
20788 			mutex_enter(&nce->nce_lock);
20789 			nce->nce_state = ND_REACHABLE;
20790 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20791 			mutex_exit(&nce->nce_lock);
20792 			(void) untimeout(nce->nce_timeout_id);
20793 			if (ip_debug > 2) {
20794 				/* ip1dbg */
20795 				pr_addr_dbg("tcp_multisend_data: state "
20796 				    "for %s changed to REACHABLE\n",
20797 				    AF_INET6, &ire->ire_addr_v6);
20798 			}
20799 		}
20800 		/* reset transport reachability confirmation */
20801 		*rconfirm = B_FALSE;
20802 	}
20803 
20804 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20805 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20806 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20807 
20808 	if (delta > (uint64_t)ill->ill_reachable_time) {
20809 		mutex_enter(&nce->nce_lock);
20810 		switch (nce->nce_state) {
20811 		case ND_REACHABLE:
20812 		case ND_STALE:
20813 			/*
20814 			 * ND_REACHABLE is identical to ND_STALE in this
20815 			 * specific case. If reachable time has expired for
20816 			 * this neighbor (delta is greater than reachable
20817 			 * time), conceptually, the neighbor cache is no
20818 			 * longer in REACHABLE state, but already in STALE
20819 			 * state.  So the correct transition here is to
20820 			 * ND_DELAY.
20821 			 */
20822 			nce->nce_state = ND_DELAY;
20823 			mutex_exit(&nce->nce_lock);
20824 			NDP_RESTART_TIMER(nce,
20825 			    ipst->ips_delay_first_probe_time);
20826 			if (ip_debug > 3) {
20827 				/* ip2dbg */
20828 				pr_addr_dbg("tcp_multisend_data: state "
20829 				    "for %s changed to DELAY\n",
20830 				    AF_INET6, &ire->ire_addr_v6);
20831 			}
20832 			break;
20833 		case ND_DELAY:
20834 		case ND_PROBE:
20835 			mutex_exit(&nce->nce_lock);
20836 			/* Timers have already started */
20837 			break;
20838 		case ND_UNREACHABLE:
20839 			/*
20840 			 * ndp timer has detected that this nce is
20841 			 * unreachable and initiated deleting this nce
20842 			 * and all its associated IREs. This is a race
20843 			 * where we found the ire before it was deleted
20844 			 * and have just sent out a packet using this
20845 			 * unreachable nce.
20846 			 */
20847 			mutex_exit(&nce->nce_lock);
20848 			break;
20849 		default:
20850 			ASSERT(0);
20851 		}
20852 	}
20853 }
20854 
20855 /*
20856  * Derived from tcp_send_data().
20857  */
20858 static void
20859 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
20860     int num_lso_seg)
20861 {
20862 	ipha_t		*ipha;
20863 	mblk_t		*ire_fp_mp;
20864 	uint_t		ire_fp_mp_len;
20865 	uint32_t	hcksum_txflags = 0;
20866 	ipaddr_t	src;
20867 	ipaddr_t	dst;
20868 	uint32_t	cksum;
20869 	uint16_t	*up;
20870 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20871 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20872 
20873 	ASSERT(DB_TYPE(mp) == M_DATA);
20874 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20875 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
20876 	ASSERT(tcp->tcp_connp != NULL);
20877 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
20878 
20879 	ipha = (ipha_t *)mp->b_rptr;
20880 	src = ipha->ipha_src;
20881 	dst = ipha->ipha_dst;
20882 
20883 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
20884 
20885 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20886 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
20887 	    num_lso_seg);
20888 #ifndef _BIG_ENDIAN
20889 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20890 #endif
20891 	if (tcp->tcp_snd_zcopy_aware) {
20892 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
20893 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
20894 			mp = tcp_zcopy_disable(tcp, mp);
20895 	}
20896 
20897 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
20898 		ASSERT(ill->ill_hcksum_capab != NULL);
20899 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
20900 	}
20901 
20902 	/*
20903 	 * Since the TCP checksum should be recalculated by h/w, we can just
20904 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
20905 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
20906 	 * The partial pseudo-header excludes TCP length, that was calculated
20907 	 * in tcp_send(), so to zero *up before further processing.
20908 	 */
20909 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20910 
20911 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
20912 	*up = 0;
20913 
20914 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
20915 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
20916 
20917 	/*
20918 	 * Append LSO flags and mss to the mp.
20919 	 */
20920 	lso_info_set(mp, mss, HW_LSO);
20921 
20922 	ipha->ipha_fragment_offset_and_flags |=
20923 	    (uint32_t)htons(ire->ire_frag_flag);
20924 
20925 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
20926 	ire_fp_mp_len = MBLKL(ire_fp_mp);
20927 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
20928 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
20929 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
20930 
20931 	UPDATE_OB_PKT_COUNT(ire);
20932 	ire->ire_last_used_time = lbolt;
20933 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
20934 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
20935 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
20936 	    ntohs(ipha->ipha_length));
20937 
20938 	DTRACE_PROBE4(ip4__physical__out__start,
20939 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
20940 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
20941 	    ipst->ips_ipv4firewall_physical_out, NULL,
20942 	    ill, ipha, mp, mp, 0, ipst);
20943 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
20944 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
20945 
20946 	if (mp != NULL) {
20947 		if (ipst->ips_ipobs_enabled) {
20948 			zoneid_t szone;
20949 
20950 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
20951 			    ipst, ALL_ZONES);
20952 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
20953 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
20954 		}
20955 
20956 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0, NULL);
20957 	}
20958 }
20959 
20960 /*
20961  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20962  * scheme, and returns one of the following:
20963  *
20964  * -1 = failed allocation.
20965  *  0 = success; burst count reached, or usable send window is too small,
20966  *      and that we'd rather wait until later before sending again.
20967  *  1 = success; we are called from tcp_multisend(), and both usable send
20968  *      window and tail_unsent are greater than the MDT threshold, and thus
20969  *      Multidata Transmit should be used instead.
20970  */
20971 static int
20972 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20973     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20974     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20975     const int mdt_thres)
20976 {
20977 	int num_burst_seg = tcp->tcp_snd_burst;
20978 	ire_t		*ire = NULL;
20979 	ill_t		*ill = NULL;
20980 	mblk_t		*ire_fp_mp = NULL;
20981 	uint_t		ire_fp_mp_len = 0;
20982 	int		num_lso_seg = 1;
20983 	uint_t		lso_usable;
20984 	boolean_t	do_lso_send = B_FALSE;
20985 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20986 
20987 	/*
20988 	 * Check LSO capability before any further work. And the similar check
20989 	 * need to be done in for(;;) loop.
20990 	 * LSO will be deployed when therer is more than one mss of available
20991 	 * data and a burst transmission is allowed.
20992 	 */
20993 	if (tcp->tcp_lso &&
20994 	    (tcp->tcp_valid_bits == 0 ||
20995 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
20996 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20997 		/*
20998 		 * Try to find usable IRE/ILL and do basic check to the ILL.
20999 		 * Double check LSO usability before going further, since the
21000 		 * underlying interface could have been changed. In case of any
21001 		 * change of LSO capability, set tcp_ire_ill_check_done to
21002 		 * B_FALSE to force to check the ILL with the next send.
21003 		 */
21004 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill) &&
21005 		    tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
21006 			/*
21007 			 * Enable LSO with this transmission.
21008 			 * Since IRE has been hold in tcp_send_find_ire_ill(),
21009 			 * IRE_REFRELE(ire) should be called before return.
21010 			 */
21011 			do_lso_send = B_TRUE;
21012 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21013 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21014 			/* Round up to multiple of 4 */
21015 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21016 		} else {
21017 			tcp->tcp_lso = B_FALSE;
21018 			tcp->tcp_ire_ill_check_done = B_FALSE;
21019 			do_lso_send = B_FALSE;
21020 			ill = NULL;
21021 		}
21022 	}
21023 
21024 	for (;;) {
21025 		struct datab	*db;
21026 		tcph_t		*tcph;
21027 		uint32_t	sum;
21028 		mblk_t		*mp, *mp1;
21029 		uchar_t		*rptr;
21030 		int		len;
21031 
21032 		/*
21033 		 * If we're called by tcp_multisend(), and the amount of
21034 		 * sendable data as well as the size of current xmit_tail
21035 		 * is beyond the MDT threshold, return to the caller and
21036 		 * let the large data transmit be done using MDT.
21037 		 */
21038 		if (*usable > 0 && *usable > mdt_thres &&
21039 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21040 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21041 			ASSERT(tcp->tcp_mdt);
21042 			return (1);	/* success; do large send */
21043 		}
21044 
21045 		if (num_burst_seg == 0)
21046 			break;		/* success; burst count reached */
21047 
21048 		/*
21049 		 * Calculate the maximum payload length we can send in *one*
21050 		 * time.
21051 		 */
21052 		if (do_lso_send) {
21053 			/*
21054 			 * Check whether need to do LSO any more.
21055 			 */
21056 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21057 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21058 				lso_usable = MIN(lso_usable,
21059 				    num_burst_seg * mss);
21060 
21061 				num_lso_seg = lso_usable / mss;
21062 				if (lso_usable % mss) {
21063 					num_lso_seg++;
21064 					tcp->tcp_last_sent_len = (ushort_t)
21065 					    (lso_usable % mss);
21066 				} else {
21067 					tcp->tcp_last_sent_len = (ushort_t)mss;
21068 				}
21069 			} else {
21070 				do_lso_send = B_FALSE;
21071 				num_lso_seg = 1;
21072 				lso_usable = mss;
21073 			}
21074 		}
21075 
21076 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21077 
21078 		/*
21079 		 * Adjust num_burst_seg here.
21080 		 */
21081 		num_burst_seg -= num_lso_seg;
21082 
21083 		len = mss;
21084 		if (len > *usable) {
21085 			ASSERT(do_lso_send == B_FALSE);
21086 
21087 			len = *usable;
21088 			if (len <= 0) {
21089 				/* Terminate the loop */
21090 				break;	/* success; too small */
21091 			}
21092 			/*
21093 			 * Sender silly-window avoidance.
21094 			 * Ignore this if we are going to send a
21095 			 * zero window probe out.
21096 			 *
21097 			 * TODO: force data into microscopic window?
21098 			 *	==> (!pushed || (unsent > usable))
21099 			 */
21100 			if (len < (tcp->tcp_max_swnd >> 1) &&
21101 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21102 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21103 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21104 				/*
21105 				 * If the retransmit timer is not running
21106 				 * we start it so that we will retransmit
21107 				 * in the case when the the receiver has
21108 				 * decremented the window.
21109 				 */
21110 				if (*snxt == tcp->tcp_snxt &&
21111 				    *snxt == tcp->tcp_suna) {
21112 					/*
21113 					 * We are not supposed to send
21114 					 * anything.  So let's wait a little
21115 					 * bit longer before breaking SWS
21116 					 * avoidance.
21117 					 *
21118 					 * What should the value be?
21119 					 * Suggestion: MAX(init rexmit time,
21120 					 * tcp->tcp_rto)
21121 					 */
21122 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21123 				}
21124 				break;	/* success; too small */
21125 			}
21126 		}
21127 
21128 		tcph = tcp->tcp_tcph;
21129 
21130 		/*
21131 		 * The reason to adjust len here is that we need to set flags
21132 		 * and calculate checksum.
21133 		 */
21134 		if (do_lso_send)
21135 			len = lso_usable;
21136 
21137 		*usable -= len; /* Approximate - can be adjusted later */
21138 		if (*usable > 0)
21139 			tcph->th_flags[0] = TH_ACK;
21140 		else
21141 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21142 
21143 		/*
21144 		 * Prime pump for IP's checksumming on our behalf
21145 		 * Include the adjustment for a source route if any.
21146 		 */
21147 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21148 		sum = (sum >> 16) + (sum & 0xFFFF);
21149 		U16_TO_ABE16(sum, tcph->th_sum);
21150 
21151 		U32_TO_ABE32(*snxt, tcph->th_seq);
21152 
21153 		/*
21154 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21155 		 * set.  For the case when TCP_FSS_VALID is the only valid
21156 		 * bit (normal active close), branch off only when we think
21157 		 * that the FIN flag needs to be set.  Note for this case,
21158 		 * that (snxt + len) may not reflect the actual seg_len,
21159 		 * as len may be further reduced in tcp_xmit_mp().  If len
21160 		 * gets modified, we will end up here again.
21161 		 */
21162 		if (tcp->tcp_valid_bits != 0 &&
21163 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21164 		    ((*snxt + len) == tcp->tcp_fss))) {
21165 			uchar_t		*prev_rptr;
21166 			uint32_t	prev_snxt = tcp->tcp_snxt;
21167 
21168 			if (*tail_unsent == 0) {
21169 				ASSERT((*xmit_tail)->b_cont != NULL);
21170 				*xmit_tail = (*xmit_tail)->b_cont;
21171 				prev_rptr = (*xmit_tail)->b_rptr;
21172 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21173 				    (*xmit_tail)->b_rptr);
21174 			} else {
21175 				prev_rptr = (*xmit_tail)->b_rptr;
21176 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21177 				    *tail_unsent;
21178 			}
21179 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21180 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21181 			/* Restore tcp_snxt so we get amount sent right. */
21182 			tcp->tcp_snxt = prev_snxt;
21183 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21184 				/*
21185 				 * If the previous timestamp is still in use,
21186 				 * don't stomp on it.
21187 				 */
21188 				if ((*xmit_tail)->b_next == NULL) {
21189 					(*xmit_tail)->b_prev = local_time;
21190 					(*xmit_tail)->b_next =
21191 					    (mblk_t *)(uintptr_t)(*snxt);
21192 				}
21193 			} else
21194 				(*xmit_tail)->b_rptr = prev_rptr;
21195 
21196 			if (mp == NULL) {
21197 				if (ire != NULL)
21198 					IRE_REFRELE(ire);
21199 				return (-1);
21200 			}
21201 			mp1 = mp->b_cont;
21202 
21203 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21204 				tcp->tcp_last_sent_len = (ushort_t)len;
21205 			while (mp1->b_cont) {
21206 				*xmit_tail = (*xmit_tail)->b_cont;
21207 				(*xmit_tail)->b_prev = local_time;
21208 				(*xmit_tail)->b_next =
21209 				    (mblk_t *)(uintptr_t)(*snxt);
21210 				mp1 = mp1->b_cont;
21211 			}
21212 			*snxt += len;
21213 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21214 			BUMP_LOCAL(tcp->tcp_obsegs);
21215 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21216 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21217 			tcp_send_data(tcp, q, mp);
21218 			continue;
21219 		}
21220 
21221 		*snxt += len;	/* Adjust later if we don't send all of len */
21222 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21223 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21224 
21225 		if (*tail_unsent) {
21226 			/* Are the bytes above us in flight? */
21227 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21228 			if (rptr != (*xmit_tail)->b_rptr) {
21229 				*tail_unsent -= len;
21230 				if (len <= mss) /* LSO is unusable */
21231 					tcp->tcp_last_sent_len = (ushort_t)len;
21232 				len += tcp_hdr_len;
21233 				if (tcp->tcp_ipversion == IPV4_VERSION)
21234 					tcp->tcp_ipha->ipha_length = htons(len);
21235 				else
21236 					tcp->tcp_ip6h->ip6_plen =
21237 					    htons(len -
21238 					    ((char *)&tcp->tcp_ip6h[1] -
21239 					    tcp->tcp_iphc));
21240 				mp = dupb(*xmit_tail);
21241 				if (mp == NULL) {
21242 					if (ire != NULL)
21243 						IRE_REFRELE(ire);
21244 					return (-1);	/* out_of_mem */
21245 				}
21246 				mp->b_rptr = rptr;
21247 				/*
21248 				 * If the old timestamp is no longer in use,
21249 				 * sample a new timestamp now.
21250 				 */
21251 				if ((*xmit_tail)->b_next == NULL) {
21252 					(*xmit_tail)->b_prev = local_time;
21253 					(*xmit_tail)->b_next =
21254 					    (mblk_t *)(uintptr_t)(*snxt-len);
21255 				}
21256 				goto must_alloc;
21257 			}
21258 		} else {
21259 			*xmit_tail = (*xmit_tail)->b_cont;
21260 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21261 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21262 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21263 			    (*xmit_tail)->b_rptr);
21264 		}
21265 
21266 		(*xmit_tail)->b_prev = local_time;
21267 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21268 
21269 		*tail_unsent -= len;
21270 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21271 			tcp->tcp_last_sent_len = (ushort_t)len;
21272 
21273 		len += tcp_hdr_len;
21274 		if (tcp->tcp_ipversion == IPV4_VERSION)
21275 			tcp->tcp_ipha->ipha_length = htons(len);
21276 		else
21277 			tcp->tcp_ip6h->ip6_plen = htons(len -
21278 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21279 
21280 		mp = dupb(*xmit_tail);
21281 		if (mp == NULL) {
21282 			if (ire != NULL)
21283 				IRE_REFRELE(ire);
21284 			return (-1);	/* out_of_mem */
21285 		}
21286 
21287 		len = tcp_hdr_len;
21288 		/*
21289 		 * There are four reasons to allocate a new hdr mblk:
21290 		 *  1) The bytes above us are in use by another packet
21291 		 *  2) We don't have good alignment
21292 		 *  3) The mblk is being shared
21293 		 *  4) We don't have enough room for a header
21294 		 */
21295 		rptr = mp->b_rptr - len;
21296 		if (!OK_32PTR(rptr) ||
21297 		    ((db = mp->b_datap), db->db_ref != 2) ||
21298 		    rptr < db->db_base + ire_fp_mp_len) {
21299 			/* NOTE: we assume allocb returns an OK_32PTR */
21300 
21301 		must_alloc:;
21302 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21303 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21304 			if (mp1 == NULL) {
21305 				freemsg(mp);
21306 				if (ire != NULL)
21307 					IRE_REFRELE(ire);
21308 				return (-1);	/* out_of_mem */
21309 			}
21310 			mp1->b_cont = mp;
21311 			mp = mp1;
21312 			/* Leave room for Link Level header */
21313 			len = tcp_hdr_len;
21314 			rptr =
21315 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21316 			mp->b_wptr = &rptr[len];
21317 		}
21318 
21319 		/*
21320 		 * Fill in the header using the template header, and add
21321 		 * options such as time-stamp, ECN and/or SACK, as needed.
21322 		 */
21323 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21324 
21325 		mp->b_rptr = rptr;
21326 
21327 		if (*tail_unsent) {
21328 			int spill = *tail_unsent;
21329 
21330 			mp1 = mp->b_cont;
21331 			if (mp1 == NULL)
21332 				mp1 = mp;
21333 
21334 			/*
21335 			 * If we're a little short, tack on more mblks until
21336 			 * there is no more spillover.
21337 			 */
21338 			while (spill < 0) {
21339 				mblk_t *nmp;
21340 				int nmpsz;
21341 
21342 				nmp = (*xmit_tail)->b_cont;
21343 				nmpsz = MBLKL(nmp);
21344 
21345 				/*
21346 				 * Excess data in mblk; can we split it?
21347 				 * If MDT is enabled for the connection,
21348 				 * keep on splitting as this is a transient
21349 				 * send path.
21350 				 */
21351 				if (!do_lso_send && !tcp->tcp_mdt &&
21352 				    (spill + nmpsz > 0)) {
21353 					/*
21354 					 * Don't split if stream head was
21355 					 * told to break up larger writes
21356 					 * into smaller ones.
21357 					 */
21358 					if (tcp->tcp_maxpsz > 0)
21359 						break;
21360 
21361 					/*
21362 					 * Next mblk is less than SMSS/2
21363 					 * rounded up to nearest 64-byte;
21364 					 * let it get sent as part of the
21365 					 * next segment.
21366 					 */
21367 					if (tcp->tcp_localnet &&
21368 					    !tcp->tcp_cork &&
21369 					    (nmpsz < roundup((mss >> 1), 64)))
21370 						break;
21371 				}
21372 
21373 				*xmit_tail = nmp;
21374 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21375 				/* Stash for rtt use later */
21376 				(*xmit_tail)->b_prev = local_time;
21377 				(*xmit_tail)->b_next =
21378 				    (mblk_t *)(uintptr_t)(*snxt - len);
21379 				mp1->b_cont = dupb(*xmit_tail);
21380 				mp1 = mp1->b_cont;
21381 
21382 				spill += nmpsz;
21383 				if (mp1 == NULL) {
21384 					*tail_unsent = spill;
21385 					freemsg(mp);
21386 					if (ire != NULL)
21387 						IRE_REFRELE(ire);
21388 					return (-1);	/* out_of_mem */
21389 				}
21390 			}
21391 
21392 			/* Trim back any surplus on the last mblk */
21393 			if (spill >= 0) {
21394 				mp1->b_wptr -= spill;
21395 				*tail_unsent = spill;
21396 			} else {
21397 				/*
21398 				 * We did not send everything we could in
21399 				 * order to remain within the b_cont limit.
21400 				 */
21401 				*usable -= spill;
21402 				*snxt += spill;
21403 				tcp->tcp_last_sent_len += spill;
21404 				UPDATE_MIB(&tcps->tcps_mib,
21405 				    tcpOutDataBytes, spill);
21406 				/*
21407 				 * Adjust the checksum
21408 				 */
21409 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21410 				sum += spill;
21411 				sum = (sum >> 16) + (sum & 0xFFFF);
21412 				U16_TO_ABE16(sum, tcph->th_sum);
21413 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21414 					sum = ntohs(
21415 					    ((ipha_t *)rptr)->ipha_length) +
21416 					    spill;
21417 					((ipha_t *)rptr)->ipha_length =
21418 					    htons(sum);
21419 				} else {
21420 					sum = ntohs(
21421 					    ((ip6_t *)rptr)->ip6_plen) +
21422 					    spill;
21423 					((ip6_t *)rptr)->ip6_plen =
21424 					    htons(sum);
21425 				}
21426 				*tail_unsent = 0;
21427 			}
21428 		}
21429 		if (tcp->tcp_ip_forward_progress) {
21430 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21431 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21432 			tcp->tcp_ip_forward_progress = B_FALSE;
21433 		}
21434 
21435 		if (do_lso_send) {
21436 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21437 			    num_lso_seg);
21438 			tcp->tcp_obsegs += num_lso_seg;
21439 
21440 			TCP_STAT(tcps, tcp_lso_times);
21441 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21442 		} else {
21443 			tcp_send_data(tcp, q, mp);
21444 			BUMP_LOCAL(tcp->tcp_obsegs);
21445 		}
21446 	}
21447 
21448 	if (ire != NULL)
21449 		IRE_REFRELE(ire);
21450 	return (0);
21451 }
21452 
21453 /* Unlink and return any mblk that looks like it contains a MDT info */
21454 static mblk_t *
21455 tcp_mdt_info_mp(mblk_t *mp)
21456 {
21457 	mblk_t	*prev_mp;
21458 
21459 	for (;;) {
21460 		prev_mp = mp;
21461 		/* no more to process? */
21462 		if ((mp = mp->b_cont) == NULL)
21463 			break;
21464 
21465 		switch (DB_TYPE(mp)) {
21466 		case M_CTL:
21467 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21468 				continue;
21469 			ASSERT(prev_mp != NULL);
21470 			prev_mp->b_cont = mp->b_cont;
21471 			mp->b_cont = NULL;
21472 			return (mp);
21473 		default:
21474 			break;
21475 		}
21476 	}
21477 	return (mp);
21478 }
21479 
21480 /* MDT info update routine, called when IP notifies us about MDT */
21481 static void
21482 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21483 {
21484 	boolean_t prev_state;
21485 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21486 
21487 	/*
21488 	 * IP is telling us to abort MDT on this connection?  We know
21489 	 * this because the capability is only turned off when IP
21490 	 * encounters some pathological cases, e.g. link-layer change
21491 	 * where the new driver doesn't support MDT, or in situation
21492 	 * where MDT usage on the link-layer has been switched off.
21493 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21494 	 * if the link-layer doesn't support MDT, and if it does, it
21495 	 * will indicate that the feature is to be turned on.
21496 	 */
21497 	prev_state = tcp->tcp_mdt;
21498 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21499 	if (!tcp->tcp_mdt && !first) {
21500 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21501 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21502 		    (void *)tcp->tcp_connp));
21503 	}
21504 
21505 	/*
21506 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21507 	 * so disable MDT otherwise.  The checks are done here
21508 	 * and in tcp_wput_data().
21509 	 */
21510 	if (tcp->tcp_mdt &&
21511 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21512 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21513 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21514 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21515 		tcp->tcp_mdt = B_FALSE;
21516 
21517 	if (tcp->tcp_mdt) {
21518 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21519 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21520 			    "version (%d), expected version is %d",
21521 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21522 			tcp->tcp_mdt = B_FALSE;
21523 			return;
21524 		}
21525 
21526 		/*
21527 		 * We need the driver to be able to handle at least three
21528 		 * spans per packet in order for tcp MDT to be utilized.
21529 		 * The first is for the header portion, while the rest are
21530 		 * needed to handle a packet that straddles across two
21531 		 * virtually non-contiguous buffers; a typical tcp packet
21532 		 * therefore consists of only two spans.  Note that we take
21533 		 * a zero as "don't care".
21534 		 */
21535 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21536 		    mdt_capab->ill_mdt_span_limit < 3) {
21537 			tcp->tcp_mdt = B_FALSE;
21538 			return;
21539 		}
21540 
21541 		/* a zero means driver wants default value */
21542 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21543 		    tcps->tcps_mdt_max_pbufs);
21544 		if (tcp->tcp_mdt_max_pld == 0)
21545 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21546 
21547 		/* ensure 32-bit alignment */
21548 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21549 		    mdt_capab->ill_mdt_hdr_head), 4);
21550 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21551 		    mdt_capab->ill_mdt_hdr_tail), 4);
21552 
21553 		if (!first && !prev_state) {
21554 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21555 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21556 			    (void *)tcp->tcp_connp));
21557 		}
21558 	}
21559 }
21560 
21561 /* Unlink and return any mblk that looks like it contains a LSO info */
21562 static mblk_t *
21563 tcp_lso_info_mp(mblk_t *mp)
21564 {
21565 	mblk_t	*prev_mp;
21566 
21567 	for (;;) {
21568 		prev_mp = mp;
21569 		/* no more to process? */
21570 		if ((mp = mp->b_cont) == NULL)
21571 			break;
21572 
21573 		switch (DB_TYPE(mp)) {
21574 		case M_CTL:
21575 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21576 				continue;
21577 			ASSERT(prev_mp != NULL);
21578 			prev_mp->b_cont = mp->b_cont;
21579 			mp->b_cont = NULL;
21580 			return (mp);
21581 		default:
21582 			break;
21583 		}
21584 	}
21585 
21586 	return (mp);
21587 }
21588 
21589 /* LSO info update routine, called when IP notifies us about LSO */
21590 static void
21591 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21592 {
21593 	tcp_stack_t *tcps = tcp->tcp_tcps;
21594 
21595 	/*
21596 	 * IP is telling us to abort LSO on this connection?  We know
21597 	 * this because the capability is only turned off when IP
21598 	 * encounters some pathological cases, e.g. link-layer change
21599 	 * where the new NIC/driver doesn't support LSO, or in situation
21600 	 * where LSO usage on the link-layer has been switched off.
21601 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21602 	 * if the link-layer doesn't support LSO, and if it does, it
21603 	 * will indicate that the feature is to be turned on.
21604 	 */
21605 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21606 	TCP_STAT(tcps, tcp_lso_enabled);
21607 
21608 	/*
21609 	 * We currently only support LSO on simple TCP/IPv4,
21610 	 * so disable LSO otherwise.  The checks are done here
21611 	 * and in tcp_wput_data().
21612 	 */
21613 	if (tcp->tcp_lso &&
21614 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21615 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21616 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21617 		tcp->tcp_lso = B_FALSE;
21618 		TCP_STAT(tcps, tcp_lso_disabled);
21619 	} else {
21620 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21621 		    lso_capab->ill_lso_max);
21622 	}
21623 }
21624 
21625 static void
21626 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21627 {
21628 	conn_t *connp = tcp->tcp_connp;
21629 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21630 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21631 
21632 	ASSERT(ire != NULL);
21633 
21634 	/*
21635 	 * We may be in the fastpath here, and although we essentially do
21636 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21637 	 * we try to keep things as brief as possible.  After all, these
21638 	 * are only best-effort checks, and we do more thorough ones prior
21639 	 * to calling tcp_send()/tcp_multisend().
21640 	 */
21641 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
21642 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21643 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21644 	    !(ire->ire_flags & RTF_MULTIRT) &&
21645 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
21646 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21647 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21648 			/* Cache the result */
21649 			connp->conn_lso_ok = B_TRUE;
21650 
21651 			ASSERT(ill->ill_lso_capab != NULL);
21652 			if (!ill->ill_lso_capab->ill_lso_on) {
21653 				ill->ill_lso_capab->ill_lso_on = 1;
21654 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21655 				    "LSO for interface %s\n", (void *)connp,
21656 				    ill->ill_name));
21657 			}
21658 			tcp_lso_update(tcp, ill->ill_lso_capab);
21659 		} else if (ipst->ips_ip_multidata_outbound &&
21660 		    ILL_MDT_CAPABLE(ill)) {
21661 			/* Cache the result */
21662 			connp->conn_mdt_ok = B_TRUE;
21663 
21664 			ASSERT(ill->ill_mdt_capab != NULL);
21665 			if (!ill->ill_mdt_capab->ill_mdt_on) {
21666 				ill->ill_mdt_capab->ill_mdt_on = 1;
21667 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21668 				    "MDT for interface %s\n", (void *)connp,
21669 				    ill->ill_name));
21670 			}
21671 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21672 		}
21673 	}
21674 
21675 	/*
21676 	 * The goal is to reduce the number of generated tcp segments by
21677 	 * setting the maxpsz multiplier to 0; this will have an affect on
21678 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21679 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21680 	 * of outbound segments and incoming ACKs, thus allowing for better
21681 	 * network and system performance.  In contrast the legacy behavior
21682 	 * may result in sending less than SMSS size, because the last mblk
21683 	 * for some packets may have more data than needed to make up SMSS,
21684 	 * and the legacy code refused to "split" it.
21685 	 *
21686 	 * We apply the new behavior on following situations:
21687 	 *
21688 	 *   1) Loopback connections,
21689 	 *   2) Connections in which the remote peer is not on local subnet,
21690 	 *   3) Local subnet connections over the bge interface (see below).
21691 	 *
21692 	 * Ideally, we would like this behavior to apply for interfaces other
21693 	 * than bge.  However, doing so would negatively impact drivers which
21694 	 * perform dynamic mapping and unmapping of DMA resources, which are
21695 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21696 	 * packet will be generated by tcp).  The bge driver does not suffer
21697 	 * from this, as it copies the mblks into pre-mapped buffers, and
21698 	 * therefore does not require more I/O resources than before.
21699 	 *
21700 	 * Otherwise, this behavior is present on all network interfaces when
21701 	 * the destination endpoint is non-local, since reducing the number
21702 	 * of packets in general is good for the network.
21703 	 *
21704 	 * TODO We need to remove this hard-coded conditional for bge once
21705 	 *	a better "self-tuning" mechanism, or a way to comprehend
21706 	 *	the driver transmit strategy is devised.  Until the solution
21707 	 *	is found and well understood, we live with this hack.
21708 	 */
21709 	if (!tcp_static_maxpsz &&
21710 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21711 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21712 		/* override the default value */
21713 		tcp->tcp_maxpsz = 0;
21714 
21715 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21716 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21717 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21718 	}
21719 
21720 	/* set the stream head parameters accordingly */
21721 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21722 }
21723 
21724 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21725 static void
21726 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21727 {
21728 	uchar_t	fval = *mp->b_rptr;
21729 	mblk_t	*tail;
21730 	queue_t	*q = tcp->tcp_wq;
21731 
21732 	/* TODO: How should flush interact with urgent data? */
21733 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21734 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21735 		/*
21736 		 * Flush only data that has not yet been put on the wire.  If
21737 		 * we flush data that we have already transmitted, life, as we
21738 		 * know it, may come to an end.
21739 		 */
21740 		tail = tcp->tcp_xmit_tail;
21741 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21742 		tcp->tcp_xmit_tail_unsent = 0;
21743 		tcp->tcp_unsent = 0;
21744 		if (tail->b_wptr != tail->b_rptr)
21745 			tail = tail->b_cont;
21746 		if (tail) {
21747 			mblk_t **excess = &tcp->tcp_xmit_head;
21748 			for (;;) {
21749 				mblk_t *mp1 = *excess;
21750 				if (mp1 == tail)
21751 					break;
21752 				tcp->tcp_xmit_tail = mp1;
21753 				tcp->tcp_xmit_last = mp1;
21754 				excess = &mp1->b_cont;
21755 			}
21756 			*excess = NULL;
21757 			tcp_close_mpp(&tail);
21758 			if (tcp->tcp_snd_zcopy_aware)
21759 				tcp_zcopy_notify(tcp);
21760 		}
21761 		/*
21762 		 * We have no unsent data, so unsent must be less than
21763 		 * tcp_xmit_lowater, so re-enable flow.
21764 		 */
21765 		mutex_enter(&tcp->tcp_non_sq_lock);
21766 		if (tcp->tcp_flow_stopped) {
21767 			tcp_clrqfull(tcp);
21768 		}
21769 		mutex_exit(&tcp->tcp_non_sq_lock);
21770 	}
21771 	/*
21772 	 * TODO: you can't just flush these, you have to increase rwnd for one
21773 	 * thing.  For another, how should urgent data interact?
21774 	 */
21775 	if (fval & FLUSHR) {
21776 		*mp->b_rptr = fval & ~FLUSHW;
21777 		/* XXX */
21778 		qreply(q, mp);
21779 		return;
21780 	}
21781 	freemsg(mp);
21782 }
21783 
21784 /*
21785  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21786  * messages.
21787  */
21788 static void
21789 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21790 {
21791 	mblk_t	*mp1;
21792 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
21793 	STRUCT_HANDLE(strbuf, sb);
21794 	queue_t *q = tcp->tcp_wq;
21795 	int	error;
21796 	uint_t	addrlen;
21797 
21798 	/* Make sure it is one of ours. */
21799 	switch (iocp->ioc_cmd) {
21800 	case TI_GETMYNAME:
21801 	case TI_GETPEERNAME:
21802 		break;
21803 	default:
21804 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21805 		return;
21806 	}
21807 	switch (mi_copy_state(q, mp, &mp1)) {
21808 	case -1:
21809 		return;
21810 	case MI_COPY_CASE(MI_COPY_IN, 1):
21811 		break;
21812 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21813 		/* Copy out the strbuf. */
21814 		mi_copyout(q, mp);
21815 		return;
21816 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21817 		/* All done. */
21818 		mi_copy_done(q, mp, 0);
21819 		return;
21820 	default:
21821 		mi_copy_done(q, mp, EPROTO);
21822 		return;
21823 	}
21824 	/* Check alignment of the strbuf */
21825 	if (!OK_32PTR(mp1->b_rptr)) {
21826 		mi_copy_done(q, mp, EINVAL);
21827 		return;
21828 	}
21829 
21830 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
21831 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21832 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21833 		mi_copy_done(q, mp, EINVAL);
21834 		return;
21835 	}
21836 
21837 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21838 	if (mp1 == NULL)
21839 		return;
21840 
21841 	switch (iocp->ioc_cmd) {
21842 	case TI_GETMYNAME:
21843 		error = tcp_do_getsockname(tcp, (void *)mp1->b_rptr, &addrlen);
21844 		break;
21845 	case TI_GETPEERNAME:
21846 		error = tcp_do_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
21847 		break;
21848 	}
21849 
21850 	if (error != 0) {
21851 		mi_copy_done(q, mp, error);
21852 	} else {
21853 		mp1->b_wptr += addrlen;
21854 		STRUCT_FSET(sb, len, addrlen);
21855 
21856 		/* Copy out the address */
21857 		mi_copyout(q, mp);
21858 	}
21859 }
21860 
21861 static void
21862 tcp_disable_direct_sockfs(tcp_t *tcp)
21863 {
21864 #ifdef	_ILP32
21865 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
21866 #else
21867 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21868 #endif
21869 	/*
21870 	 * Insert this socket into the acceptor hash.
21871 	 * We might need it for T_CONN_RES message
21872 	 */
21873 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21874 
21875 	if (tcp->tcp_fused) {
21876 		/*
21877 		 * This is a fused loopback tcp; disable
21878 		 * read-side synchronous streams interface
21879 		 * and drain any queued data.  It is okay
21880 		 * to do this for non-synchronous streams
21881 		 * fused tcp as well.
21882 		 */
21883 		tcp_fuse_disable_pair(tcp, B_FALSE);
21884 	}
21885 	tcp->tcp_issocket = B_FALSE;
21886 	tcp->tcp_sodirect = NULL;
21887 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
21888 }
21889 
21890 /*
21891  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21892  * messages.
21893  */
21894 /* ARGSUSED */
21895 static void
21896 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21897 {
21898 	conn_t 	*connp = (conn_t *)arg;
21899 	tcp_t	*tcp = connp->conn_tcp;
21900 	queue_t	*q = tcp->tcp_wq;
21901 	struct iocblk	*iocp;
21902 
21903 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21904 	/*
21905 	 * Try and ASSERT the minimum possible references on the
21906 	 * conn early enough. Since we are executing on write side,
21907 	 * the connection is obviously not detached and that means
21908 	 * there is a ref each for TCP and IP. Since we are behind
21909 	 * the squeue, the minimum references needed are 3. If the
21910 	 * conn is in classifier hash list, there should be an
21911 	 * extra ref for that (we check both the possibilities).
21912 	 */
21913 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21914 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21915 
21916 	iocp = (struct iocblk *)mp->b_rptr;
21917 	switch (iocp->ioc_cmd) {
21918 	case TCP_IOC_DEFAULT_Q:
21919 		/* Wants to be the default wq. */
21920 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
21921 			iocp->ioc_error = EPERM;
21922 			iocp->ioc_count = 0;
21923 			mp->b_datap->db_type = M_IOCACK;
21924 			qreply(q, mp);
21925 			return;
21926 		}
21927 		tcp_def_q_set(tcp, mp);
21928 		return;
21929 	case _SIOCSOCKFALLBACK:
21930 		/*
21931 		 * Either sockmod is about to be popped and the socket
21932 		 * would now be treated as a plain stream, or a module
21933 		 * is about to be pushed so we could no longer use read-
21934 		 * side synchronous streams for fused loopback tcp.
21935 		 * Drain any queued data and disable direct sockfs
21936 		 * interface from now on.
21937 		 */
21938 		if (!tcp->tcp_issocket) {
21939 			DB_TYPE(mp) = M_IOCNAK;
21940 			iocp->ioc_error = EINVAL;
21941 		} else {
21942 			tcp_disable_direct_sockfs(tcp);
21943 			DB_TYPE(mp) = M_IOCACK;
21944 			iocp->ioc_error = 0;
21945 		}
21946 		iocp->ioc_count = 0;
21947 		iocp->ioc_rval = 0;
21948 		qreply(q, mp);
21949 		return;
21950 	}
21951 	CALL_IP_WPUT(connp, q, mp);
21952 }
21953 
21954 /*
21955  * This routine is called by tcp_wput() to handle all TPI requests.
21956  */
21957 /* ARGSUSED */
21958 static void
21959 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21960 {
21961 	conn_t 	*connp = (conn_t *)arg;
21962 	tcp_t	*tcp = connp->conn_tcp;
21963 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21964 	uchar_t *rptr;
21965 	t_scalar_t type;
21966 	cred_t *cr;
21967 
21968 	/*
21969 	 * Try and ASSERT the minimum possible references on the
21970 	 * conn early enough. Since we are executing on write side,
21971 	 * the connection is obviously not detached and that means
21972 	 * there is a ref each for TCP and IP. Since we are behind
21973 	 * the squeue, the minimum references needed are 3. If the
21974 	 * conn is in classifier hash list, there should be an
21975 	 * extra ref for that (we check both the possibilities).
21976 	 */
21977 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21978 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21979 
21980 	rptr = mp->b_rptr;
21981 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21982 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21983 		type = ((union T_primitives *)rptr)->type;
21984 		if (type == T_EXDATA_REQ) {
21985 			tcp_output_urgent(connp, mp->b_cont, arg2);
21986 			freeb(mp);
21987 		} else if (type != T_DATA_REQ) {
21988 			goto non_urgent_data;
21989 		} else {
21990 			/* TODO: options, flags, ... from user */
21991 			/* Set length to zero for reclamation below */
21992 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21993 			freeb(mp);
21994 		}
21995 		return;
21996 	} else {
21997 		if (tcp->tcp_debug) {
21998 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21999 			    "tcp_wput_proto, dropping one...");
22000 		}
22001 		freemsg(mp);
22002 		return;
22003 	}
22004 
22005 non_urgent_data:
22006 
22007 	switch ((int)tprim->type) {
22008 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22009 		/*
22010 		 * save the kssl_ent_t from the next block, and convert this
22011 		 * back to a normal bind_req.
22012 		 */
22013 		if (mp->b_cont != NULL) {
22014 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22015 
22016 			if (tcp->tcp_kssl_ent != NULL) {
22017 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22018 				    KSSL_NO_PROXY);
22019 				tcp->tcp_kssl_ent = NULL;
22020 			}
22021 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22022 			    sizeof (kssl_ent_t));
22023 			kssl_hold_ent(tcp->tcp_kssl_ent);
22024 			freemsg(mp->b_cont);
22025 			mp->b_cont = NULL;
22026 		}
22027 		tprim->type = T_BIND_REQ;
22028 
22029 	/* FALLTHROUGH */
22030 	case O_T_BIND_REQ:	/* bind request */
22031 	case T_BIND_REQ:	/* new semantics bind request */
22032 		tcp_tpi_bind(tcp, mp);
22033 		break;
22034 	case T_UNBIND_REQ:	/* unbind request */
22035 		tcp_tpi_unbind(tcp, mp);
22036 		break;
22037 	case O_T_CONN_RES:	/* old connection response XXX */
22038 	case T_CONN_RES:	/* connection response */
22039 		tcp_tli_accept(tcp, mp);
22040 		break;
22041 	case T_CONN_REQ:	/* connection request */
22042 		tcp_tpi_connect(tcp, mp);
22043 		break;
22044 	case T_DISCON_REQ:	/* disconnect request */
22045 		tcp_disconnect(tcp, mp);
22046 		break;
22047 	case T_CAPABILITY_REQ:
22048 		tcp_capability_req(tcp, mp);	/* capability request */
22049 		break;
22050 	case T_INFO_REQ:	/* information request */
22051 		tcp_info_req(tcp, mp);
22052 		break;
22053 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22054 	case T_OPTMGMT_REQ:
22055 		/*
22056 		 * Note:  no support for snmpcom_req() through new
22057 		 * T_OPTMGMT_REQ. See comments in ip.c
22058 		 */
22059 
22060 		/*
22061 		 * All Solaris components should pass a db_credp
22062 		 * for this TPI message, hence we ASSERT.
22063 		 * But in case there is some other M_PROTO that looks
22064 		 * like a TPI message sent by some other kernel
22065 		 * component, we check and return an error.
22066 		 */
22067 		cr = msg_getcred(mp, NULL);
22068 		ASSERT(cr != NULL);
22069 		if (cr == NULL) {
22070 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
22071 			return;
22072 		}
22073 		/*
22074 		 * If EINPROGRESS is returned, the request has been queued
22075 		 * for subsequent processing by ip_restart_optmgmt(), which
22076 		 * will do the CONN_DEC_REF().
22077 		 */
22078 		CONN_INC_REF(connp);
22079 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
22080 			if (svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22081 			    B_TRUE) != EINPROGRESS) {
22082 				CONN_DEC_REF(connp);
22083 			}
22084 		} else {
22085 			if (tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22086 			    B_TRUE) != EINPROGRESS) {
22087 				CONN_DEC_REF(connp);
22088 			}
22089 		}
22090 		break;
22091 
22092 	case T_UNITDATA_REQ:	/* unitdata request */
22093 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22094 		break;
22095 	case T_ORDREL_REQ:	/* orderly release req */
22096 		freemsg(mp);
22097 
22098 		if (tcp->tcp_fused)
22099 			tcp_unfuse(tcp);
22100 
22101 		if (tcp_xmit_end(tcp) != 0) {
22102 			/*
22103 			 * We were crossing FINs and got a reset from
22104 			 * the other side. Just ignore it.
22105 			 */
22106 			if (tcp->tcp_debug) {
22107 				(void) strlog(TCP_MOD_ID, 0, 1,
22108 				    SL_ERROR|SL_TRACE,
22109 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22110 				    "state %s",
22111 				    tcp_display(tcp, NULL,
22112 				    DISP_ADDR_AND_PORT));
22113 			}
22114 		}
22115 		break;
22116 	case T_ADDR_REQ:
22117 		tcp_addr_req(tcp, mp);
22118 		break;
22119 	default:
22120 		if (tcp->tcp_debug) {
22121 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22122 			    "tcp_wput_proto, bogus TPI msg, type %d",
22123 			    tprim->type);
22124 		}
22125 		/*
22126 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22127 		 * to recover.
22128 		 */
22129 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22130 		break;
22131 	}
22132 }
22133 
22134 /*
22135  * The TCP write service routine should never be called...
22136  */
22137 /* ARGSUSED */
22138 static void
22139 tcp_wsrv(queue_t *q)
22140 {
22141 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22142 
22143 	TCP_STAT(tcps, tcp_wsrv_called);
22144 }
22145 
22146 /* Non overlapping byte exchanger */
22147 static void
22148 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22149 {
22150 	uchar_t	uch;
22151 
22152 	while (len-- > 0) {
22153 		uch = a[len];
22154 		a[len] = b[len];
22155 		b[len] = uch;
22156 	}
22157 }
22158 
22159 /*
22160  * Send out a control packet on the tcp connection specified.  This routine
22161  * is typically called where we need a simple ACK or RST generated.
22162  */
22163 static void
22164 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22165 {
22166 	uchar_t		*rptr;
22167 	tcph_t		*tcph;
22168 	ipha_t		*ipha = NULL;
22169 	ip6_t		*ip6h = NULL;
22170 	uint32_t	sum;
22171 	int		tcp_hdr_len;
22172 	int		tcp_ip_hdr_len;
22173 	mblk_t		*mp;
22174 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22175 
22176 	/*
22177 	 * Save sum for use in source route later.
22178 	 */
22179 	ASSERT(tcp != NULL);
22180 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22181 	tcp_hdr_len = tcp->tcp_hdr_len;
22182 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22183 
22184 	/* If a text string is passed in with the request, pass it to strlog. */
22185 	if (str != NULL && tcp->tcp_debug) {
22186 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22187 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22188 		    str, seq, ack, ctl);
22189 	}
22190 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22191 	    BPRI_MED);
22192 	if (mp == NULL) {
22193 		return;
22194 	}
22195 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22196 	mp->b_rptr = rptr;
22197 	mp->b_wptr = &rptr[tcp_hdr_len];
22198 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22199 
22200 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22201 		ipha = (ipha_t *)rptr;
22202 		ipha->ipha_length = htons(tcp_hdr_len);
22203 	} else {
22204 		ip6h = (ip6_t *)rptr;
22205 		ASSERT(tcp != NULL);
22206 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22207 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22208 	}
22209 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22210 	tcph->th_flags[0] = (uint8_t)ctl;
22211 	if (ctl & TH_RST) {
22212 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22213 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22214 		/*
22215 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22216 		 */
22217 		if (tcp->tcp_snd_ts_ok &&
22218 		    tcp->tcp_state > TCPS_SYN_SENT) {
22219 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22220 			*(mp->b_wptr) = TCPOPT_EOL;
22221 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22222 				ipha->ipha_length = htons(tcp_hdr_len -
22223 				    TCPOPT_REAL_TS_LEN);
22224 			} else {
22225 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22226 				    TCPOPT_REAL_TS_LEN);
22227 			}
22228 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22229 			sum -= TCPOPT_REAL_TS_LEN;
22230 		}
22231 	}
22232 	if (ctl & TH_ACK) {
22233 		if (tcp->tcp_snd_ts_ok) {
22234 			U32_TO_BE32(lbolt,
22235 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22236 			U32_TO_BE32(tcp->tcp_ts_recent,
22237 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22238 		}
22239 
22240 		/* Update the latest receive window size in TCP header. */
22241 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22242 		    tcph->th_win);
22243 		tcp->tcp_rack = ack;
22244 		tcp->tcp_rack_cnt = 0;
22245 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22246 	}
22247 	BUMP_LOCAL(tcp->tcp_obsegs);
22248 	U32_TO_BE32(seq, tcph->th_seq);
22249 	U32_TO_BE32(ack, tcph->th_ack);
22250 	/*
22251 	 * Include the adjustment for a source route if any.
22252 	 */
22253 	sum = (sum >> 16) + (sum & 0xFFFF);
22254 	U16_TO_BE16(sum, tcph->th_sum);
22255 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22256 }
22257 
22258 /*
22259  * If this routine returns B_TRUE, TCP can generate a RST in response
22260  * to a segment.  If it returns B_FALSE, TCP should not respond.
22261  */
22262 static boolean_t
22263 tcp_send_rst_chk(tcp_stack_t *tcps)
22264 {
22265 	clock_t	now;
22266 
22267 	/*
22268 	 * TCP needs to protect itself from generating too many RSTs.
22269 	 * This can be a DoS attack by sending us random segments
22270 	 * soliciting RSTs.
22271 	 *
22272 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22273 	 * in each 1 second interval.  In this way, TCP still generate
22274 	 * RSTs in normal cases but when under attack, the impact is
22275 	 * limited.
22276 	 */
22277 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22278 		now = lbolt;
22279 		/* lbolt can wrap around. */
22280 		if ((tcps->tcps_last_rst_intrvl > now) ||
22281 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22282 		    1*SECONDS)) {
22283 			tcps->tcps_last_rst_intrvl = now;
22284 			tcps->tcps_rst_cnt = 1;
22285 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22286 			return (B_FALSE);
22287 		}
22288 	}
22289 	return (B_TRUE);
22290 }
22291 
22292 /*
22293  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22294  */
22295 static void
22296 tcp_ip_ire_mark_advice(tcp_t *tcp)
22297 {
22298 	mblk_t *mp;
22299 	ipic_t *ipic;
22300 
22301 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22302 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22303 		    &ipic);
22304 	} else {
22305 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22306 		    &ipic);
22307 	}
22308 	if (mp == NULL)
22309 		return;
22310 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22311 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22312 }
22313 
22314 /*
22315  * Return an IP advice ioctl mblk and set ipic to be the pointer
22316  * to the advice structure.
22317  */
22318 static mblk_t *
22319 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22320 {
22321 	struct iocblk *ioc;
22322 	mblk_t *mp, *mp1;
22323 
22324 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22325 	if (mp == NULL)
22326 		return (NULL);
22327 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22328 	*ipic = (ipic_t *)mp->b_rptr;
22329 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22330 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22331 
22332 	bcopy(addr, *ipic + 1, addr_len);
22333 
22334 	(*ipic)->ipic_addr_length = addr_len;
22335 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22336 
22337 	mp1 = mkiocb(IP_IOCTL);
22338 	if (mp1 == NULL) {
22339 		freemsg(mp);
22340 		return (NULL);
22341 	}
22342 	mp1->b_cont = mp;
22343 	ioc = (struct iocblk *)mp1->b_rptr;
22344 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22345 
22346 	return (mp1);
22347 }
22348 
22349 /*
22350  * Generate a reset based on an inbound packet, connp is set by caller
22351  * when RST is in response to an unexpected inbound packet for which
22352  * there is active tcp state in the system.
22353  *
22354  * IPSEC NOTE : Try to send the reply with the same protection as it came
22355  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22356  * the packet will go out at the same level of protection as it came in by
22357  * converting the IPSEC_IN to IPSEC_OUT.
22358  */
22359 static void
22360 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22361     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22362     tcp_stack_t *tcps, conn_t *connp)
22363 {
22364 	ipha_t		*ipha = NULL;
22365 	ip6_t		*ip6h = NULL;
22366 	ushort_t	len;
22367 	tcph_t		*tcph;
22368 	int		i;
22369 	mblk_t		*ipsec_mp;
22370 	boolean_t	mctl_present;
22371 	ipic_t		*ipic;
22372 	ipaddr_t	v4addr;
22373 	in6_addr_t	v6addr;
22374 	int		addr_len;
22375 	void		*addr;
22376 	queue_t		*q = tcps->tcps_g_q;
22377 	tcp_t		*tcp;
22378 	cred_t		*cr;
22379 	mblk_t		*nmp;
22380 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22381 
22382 	if (tcps->tcps_g_q == NULL) {
22383 		/*
22384 		 * For non-zero stackids the default queue isn't created
22385 		 * until the first open, thus there can be a need to send
22386 		 * a reset before then. But we can't do that, hence we just
22387 		 * drop the packet. Later during boot, when the default queue
22388 		 * has been setup, a retransmitted packet from the peer
22389 		 * will result in a reset.
22390 		 */
22391 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22392 		    GLOBAL_NETSTACKID);
22393 		freemsg(mp);
22394 		return;
22395 	}
22396 
22397 	if (connp != NULL)
22398 		tcp = connp->conn_tcp;
22399 	else
22400 		tcp = Q_TO_TCP(q);
22401 
22402 	if (!tcp_send_rst_chk(tcps)) {
22403 		tcps->tcps_rst_unsent++;
22404 		freemsg(mp);
22405 		return;
22406 	}
22407 
22408 	if (mp->b_datap->db_type == M_CTL) {
22409 		ipsec_mp = mp;
22410 		mp = mp->b_cont;
22411 		mctl_present = B_TRUE;
22412 	} else {
22413 		ipsec_mp = mp;
22414 		mctl_present = B_FALSE;
22415 	}
22416 
22417 	if (str && q && tcps->tcps_dbg) {
22418 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22419 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22420 		    "flags 0x%x",
22421 		    str, seq, ack, ctl);
22422 	}
22423 	if (mp->b_datap->db_ref != 1) {
22424 		mblk_t *mp1 = copyb(mp);
22425 		freemsg(mp);
22426 		mp = mp1;
22427 		if (!mp) {
22428 			if (mctl_present)
22429 				freeb(ipsec_mp);
22430 			return;
22431 		} else {
22432 			if (mctl_present) {
22433 				ipsec_mp->b_cont = mp;
22434 			} else {
22435 				ipsec_mp = mp;
22436 			}
22437 		}
22438 	} else if (mp->b_cont) {
22439 		freemsg(mp->b_cont);
22440 		mp->b_cont = NULL;
22441 	}
22442 	/*
22443 	 * We skip reversing source route here.
22444 	 * (for now we replace all IP options with EOL)
22445 	 */
22446 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22447 		ipha = (ipha_t *)mp->b_rptr;
22448 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22449 			mp->b_rptr[i] = IPOPT_EOL;
22450 		/*
22451 		 * Make sure that src address isn't flagrantly invalid.
22452 		 * Not all broadcast address checking for the src address
22453 		 * is possible, since we don't know the netmask of the src
22454 		 * addr.  No check for destination address is done, since
22455 		 * IP will not pass up a packet with a broadcast dest
22456 		 * address to TCP.  Similar checks are done below for IPv6.
22457 		 */
22458 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22459 		    CLASSD(ipha->ipha_src)) {
22460 			freemsg(ipsec_mp);
22461 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22462 			return;
22463 		}
22464 	} else {
22465 		ip6h = (ip6_t *)mp->b_rptr;
22466 
22467 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22468 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22469 			freemsg(ipsec_mp);
22470 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22471 			return;
22472 		}
22473 
22474 		/* Remove any extension headers assuming partial overlay */
22475 		if (ip_hdr_len > IPV6_HDR_LEN) {
22476 			uint8_t *to;
22477 
22478 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22479 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22480 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22481 			ip_hdr_len = IPV6_HDR_LEN;
22482 			ip6h = (ip6_t *)mp->b_rptr;
22483 			ip6h->ip6_nxt = IPPROTO_TCP;
22484 		}
22485 	}
22486 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22487 	if (tcph->th_flags[0] & TH_RST) {
22488 		freemsg(ipsec_mp);
22489 		return;
22490 	}
22491 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22492 	len = ip_hdr_len + sizeof (tcph_t);
22493 	mp->b_wptr = &mp->b_rptr[len];
22494 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22495 		ipha->ipha_length = htons(len);
22496 		/* Swap addresses */
22497 		v4addr = ipha->ipha_src;
22498 		ipha->ipha_src = ipha->ipha_dst;
22499 		ipha->ipha_dst = v4addr;
22500 		ipha->ipha_ident = 0;
22501 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22502 		addr_len = IP_ADDR_LEN;
22503 		addr = &v4addr;
22504 	} else {
22505 		/* No ip6i_t in this case */
22506 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22507 		/* Swap addresses */
22508 		v6addr = ip6h->ip6_src;
22509 		ip6h->ip6_src = ip6h->ip6_dst;
22510 		ip6h->ip6_dst = v6addr;
22511 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22512 		addr_len = IPV6_ADDR_LEN;
22513 		addr = &v6addr;
22514 	}
22515 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22516 	U32_TO_BE32(ack, tcph->th_ack);
22517 	U32_TO_BE32(seq, tcph->th_seq);
22518 	U16_TO_BE16(0, tcph->th_win);
22519 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22520 	tcph->th_flags[0] = (uint8_t)ctl;
22521 	if (ctl & TH_RST) {
22522 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22523 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22524 	}
22525 
22526 	/* IP trusts us to set up labels when required. */
22527 	if (is_system_labeled() && (cr = msg_getcred(mp, NULL)) != NULL &&
22528 	    crgetlabel(cr) != NULL) {
22529 		int err;
22530 
22531 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22532 			err = tsol_check_label(cr, &mp,
22533 			    tcp->tcp_connp->conn_mac_exempt,
22534 			    tcps->tcps_netstack->netstack_ip);
22535 		else
22536 			err = tsol_check_label_v6(cr, &mp,
22537 			    tcp->tcp_connp->conn_mac_exempt,
22538 			    tcps->tcps_netstack->netstack_ip);
22539 		if (mctl_present)
22540 			ipsec_mp->b_cont = mp;
22541 		else
22542 			ipsec_mp = mp;
22543 		if (err != 0) {
22544 			freemsg(ipsec_mp);
22545 			return;
22546 		}
22547 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22548 			ipha = (ipha_t *)mp->b_rptr;
22549 		} else {
22550 			ip6h = (ip6_t *)mp->b_rptr;
22551 		}
22552 	}
22553 
22554 	if (mctl_present) {
22555 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22556 
22557 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22558 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22559 			return;
22560 		}
22561 	}
22562 	if (zoneid == ALL_ZONES)
22563 		zoneid = GLOBAL_ZONEID;
22564 
22565 	/* Add the zoneid so ip_output routes it properly */
22566 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22567 		freemsg(ipsec_mp);
22568 		return;
22569 	}
22570 	ipsec_mp = nmp;
22571 
22572 	/*
22573 	 * NOTE:  one might consider tracing a TCP packet here, but
22574 	 * this function has no active TCP state and no tcp structure
22575 	 * that has a trace buffer.  If we traced here, we would have
22576 	 * to keep a local trace buffer in tcp_record_trace().
22577 	 *
22578 	 * TSol note: The mblk that contains the incoming packet was
22579 	 * reused by tcp_xmit_listener_reset, so it already contains
22580 	 * the right credentials and we don't need to call mblk_setcred.
22581 	 * Also the conn's cred is not right since it is associated
22582 	 * with tcps_g_q.
22583 	 */
22584 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22585 
22586 	/*
22587 	 * Tell IP to mark the IRE used for this destination temporary.
22588 	 * This way, we can limit our exposure to DoS attack because IP
22589 	 * creates an IRE for each destination.  If there are too many,
22590 	 * the time to do any routing lookup will be extremely long.  And
22591 	 * the lookup can be in interrupt context.
22592 	 *
22593 	 * Note that in normal circumstances, this marking should not
22594 	 * affect anything.  It would be nice if only 1 message is
22595 	 * needed to inform IP that the IRE created for this RST should
22596 	 * not be added to the cache table.  But there is currently
22597 	 * not such communication mechanism between TCP and IP.  So
22598 	 * the best we can do now is to send the advice ioctl to IP
22599 	 * to mark the IRE temporary.
22600 	 */
22601 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22602 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22603 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22604 	}
22605 }
22606 
22607 /*
22608  * Initiate closedown sequence on an active connection.  (May be called as
22609  * writer.)  Return value zero for OK return, non-zero for error return.
22610  */
22611 static int
22612 tcp_xmit_end(tcp_t *tcp)
22613 {
22614 	ipic_t	*ipic;
22615 	mblk_t	*mp;
22616 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22617 
22618 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22619 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22620 		/*
22621 		 * Invalid state, only states TCPS_SYN_RCVD,
22622 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22623 		 */
22624 		return (-1);
22625 	}
22626 
22627 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22628 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22629 	/*
22630 	 * If there is nothing more unsent, send the FIN now.
22631 	 * Otherwise, it will go out with the last segment.
22632 	 */
22633 	if (tcp->tcp_unsent == 0) {
22634 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22635 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22636 
22637 		if (mp) {
22638 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22639 		} else {
22640 			/*
22641 			 * Couldn't allocate msg.  Pretend we got it out.
22642 			 * Wait for rexmit timeout.
22643 			 */
22644 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22645 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22646 		}
22647 
22648 		/*
22649 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22650 		 * changed.
22651 		 */
22652 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22653 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22654 		}
22655 	} else {
22656 		/*
22657 		 * If tcp->tcp_cork is set, then the data will not get sent,
22658 		 * so we have to check that and unset it first.
22659 		 */
22660 		if (tcp->tcp_cork)
22661 			tcp->tcp_cork = B_FALSE;
22662 		tcp_wput_data(tcp, NULL, B_FALSE);
22663 	}
22664 
22665 	/*
22666 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22667 	 * is 0, don't update the cache.
22668 	 */
22669 	if (tcps->tcps_rtt_updates == 0 ||
22670 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
22671 		return (0);
22672 
22673 	/*
22674 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22675 	 * different from the destination.
22676 	 */
22677 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22678 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22679 			return (0);
22680 		}
22681 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22682 		    &ipic);
22683 	} else {
22684 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22685 		    &tcp->tcp_ip6h->ip6_dst))) {
22686 			return (0);
22687 		}
22688 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22689 		    &ipic);
22690 	}
22691 
22692 	/* Record route attributes in the IRE for use by future connections. */
22693 	if (mp == NULL)
22694 		return (0);
22695 
22696 	/*
22697 	 * We do not have a good algorithm to update ssthresh at this time.
22698 	 * So don't do any update.
22699 	 */
22700 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22701 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22702 
22703 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22704 
22705 	return (0);
22706 }
22707 
22708 /* ARGSUSED */
22709 void
22710 tcp_xmit_reset(void *arg, mblk_t *mp, void *arg2)
22711 {
22712 	conn_t *connp = (conn_t *)arg;
22713 	mblk_t *mp1;
22714 	tcp_t *tcp = connp->conn_tcp;
22715 	tcp_xmit_reset_event_t *eventp;
22716 
22717 	ASSERT(mp->b_datap->db_type == M_PROTO &&
22718 	    MBLKL(mp) == sizeof (tcp_xmit_reset_event_t));
22719 
22720 	if (tcp->tcp_state != TCPS_LISTEN) {
22721 		freemsg(mp);
22722 		return;
22723 	}
22724 
22725 	mp1 = mp->b_cont;
22726 	mp->b_cont = NULL;
22727 	eventp = (tcp_xmit_reset_event_t *)mp->b_rptr;
22728 	ASSERT(eventp->tcp_xre_tcps->tcps_netstack ==
22729 	    connp->conn_netstack);
22730 
22731 	tcp_xmit_listeners_reset(mp1, eventp->tcp_xre_iphdrlen,
22732 	    eventp->tcp_xre_zoneid, eventp->tcp_xre_tcps, connp);
22733 	freemsg(mp);
22734 }
22735 
22736 /*
22737  * Generate a "no listener here" RST in response to an "unknown" segment.
22738  * connp is set by caller when RST is in response to an unexpected
22739  * inbound packet for which there is active tcp state in the system.
22740  * Note that we are reusing the incoming mp to construct the outgoing RST.
22741  */
22742 void
22743 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
22744     tcp_stack_t *tcps, conn_t *connp)
22745 {
22746 	uchar_t		*rptr;
22747 	uint32_t	seg_len;
22748 	tcph_t		*tcph;
22749 	uint32_t	seg_seq;
22750 	uint32_t	seg_ack;
22751 	uint_t		flags;
22752 	mblk_t		*ipsec_mp;
22753 	ipha_t 		*ipha;
22754 	ip6_t 		*ip6h;
22755 	boolean_t	mctl_present = B_FALSE;
22756 	boolean_t	check = B_TRUE;
22757 	boolean_t	policy_present;
22758 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
22759 
22760 	TCP_STAT(tcps, tcp_no_listener);
22761 
22762 	ipsec_mp = mp;
22763 
22764 	if (mp->b_datap->db_type == M_CTL) {
22765 		ipsec_in_t *ii;
22766 
22767 		mctl_present = B_TRUE;
22768 		mp = mp->b_cont;
22769 
22770 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22771 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22772 		if (ii->ipsec_in_dont_check) {
22773 			check = B_FALSE;
22774 			if (!ii->ipsec_in_secure) {
22775 				freeb(ipsec_mp);
22776 				mctl_present = B_FALSE;
22777 				ipsec_mp = mp;
22778 			}
22779 		}
22780 	}
22781 
22782 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22783 		policy_present = ipss->ipsec_inbound_v4_policy_present;
22784 		ipha = (ipha_t *)mp->b_rptr;
22785 		ip6h = NULL;
22786 	} else {
22787 		policy_present = ipss->ipsec_inbound_v6_policy_present;
22788 		ipha = NULL;
22789 		ip6h = (ip6_t *)mp->b_rptr;
22790 	}
22791 
22792 	if (check && policy_present) {
22793 		/*
22794 		 * The conn_t parameter is NULL because we already know
22795 		 * nobody's home.
22796 		 */
22797 		ipsec_mp = ipsec_check_global_policy(
22798 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
22799 		    tcps->tcps_netstack);
22800 		if (ipsec_mp == NULL)
22801 			return;
22802 	}
22803 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22804 		DTRACE_PROBE2(
22805 		    tx__ip__log__error__nolistener__tcp,
22806 		    char *, "Could not reply with RST to mp(1)",
22807 		    mblk_t *, mp);
22808 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22809 		freemsg(ipsec_mp);
22810 		return;
22811 	}
22812 
22813 	rptr = mp->b_rptr;
22814 
22815 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22816 	seg_seq = BE32_TO_U32(tcph->th_seq);
22817 	seg_ack = BE32_TO_U32(tcph->th_ack);
22818 	flags = tcph->th_flags[0];
22819 
22820 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22821 	if (flags & TH_RST) {
22822 		freemsg(ipsec_mp);
22823 	} else if (flags & TH_ACK) {
22824 		tcp_xmit_early_reset("no tcp, reset",
22825 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
22826 		    connp);
22827 	} else {
22828 		if (flags & TH_SYN) {
22829 			seg_len++;
22830 		} else {
22831 			/*
22832 			 * Here we violate the RFC.  Note that a normal
22833 			 * TCP will never send a segment without the ACK
22834 			 * flag, except for RST or SYN segment.  This
22835 			 * segment is neither.  Just drop it on the
22836 			 * floor.
22837 			 */
22838 			freemsg(ipsec_mp);
22839 			tcps->tcps_rst_unsent++;
22840 			return;
22841 		}
22842 
22843 		tcp_xmit_early_reset("no tcp, reset/ack",
22844 		    ipsec_mp, 0, seg_seq + seg_len,
22845 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
22846 	}
22847 }
22848 
22849 /*
22850  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22851  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22852  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22853  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22854  * otherwise it will dup partial mblks.)
22855  * Otherwise, an appropriate ACK packet will be generated.  This
22856  * routine is not usually called to send new data for the first time.  It
22857  * is mostly called out of the timer for retransmits, and to generate ACKs.
22858  *
22859  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22860  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22861  * of the original mblk chain will be returned in *offset and *end_mp.
22862  */
22863 mblk_t *
22864 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22865     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22866     boolean_t rexmit)
22867 {
22868 	int	data_length;
22869 	int32_t	off = 0;
22870 	uint_t	flags;
22871 	mblk_t	*mp1;
22872 	mblk_t	*mp2;
22873 	uchar_t	*rptr;
22874 	tcph_t	*tcph;
22875 	int32_t	num_sack_blk = 0;
22876 	int32_t	sack_opt_len = 0;
22877 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22878 
22879 	/* Allocate for our maximum TCP header + link-level */
22880 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
22881 	    tcps->tcps_wroff_xtra, BPRI_MED);
22882 	if (!mp1)
22883 		return (NULL);
22884 	data_length = 0;
22885 
22886 	/*
22887 	 * Note that tcp_mss has been adjusted to take into account the
22888 	 * timestamp option if applicable.  Because SACK options do not
22889 	 * appear in every TCP segments and they are of variable lengths,
22890 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22891 	 * the actual segment length when we need to send a segment which
22892 	 * includes SACK options.
22893 	 */
22894 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22895 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22896 		    tcp->tcp_num_sack_blk);
22897 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22898 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22899 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22900 			max_to_send -= sack_opt_len;
22901 	}
22902 
22903 	if (offset != NULL) {
22904 		off = *offset;
22905 		/* We use offset as an indicator that end_mp is not NULL. */
22906 		*end_mp = NULL;
22907 	}
22908 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22909 		/* This could be faster with cooperation from downstream */
22910 		if (mp2 != mp1 && !sendall &&
22911 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22912 		    max_to_send)
22913 			/*
22914 			 * Don't send the next mblk since the whole mblk
22915 			 * does not fit.
22916 			 */
22917 			break;
22918 		mp2->b_cont = dupb(mp);
22919 		mp2 = mp2->b_cont;
22920 		if (!mp2) {
22921 			freemsg(mp1);
22922 			return (NULL);
22923 		}
22924 		mp2->b_rptr += off;
22925 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22926 		    (uintptr_t)INT_MAX);
22927 
22928 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22929 		if (data_length > max_to_send) {
22930 			mp2->b_wptr -= data_length - max_to_send;
22931 			data_length = max_to_send;
22932 			off = mp2->b_wptr - mp->b_rptr;
22933 			break;
22934 		} else {
22935 			off = 0;
22936 		}
22937 	}
22938 	if (offset != NULL) {
22939 		*offset = off;
22940 		*end_mp = mp;
22941 	}
22942 	if (seg_len != NULL) {
22943 		*seg_len = data_length;
22944 	}
22945 
22946 	/* Update the latest receive window size in TCP header. */
22947 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22948 	    tcp->tcp_tcph->th_win);
22949 
22950 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
22951 	mp1->b_rptr = rptr;
22952 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22953 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22954 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22955 	U32_TO_ABE32(seq, tcph->th_seq);
22956 
22957 	/*
22958 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22959 	 * that this function was called from tcp_wput_data. Thus, when called
22960 	 * to retransmit data the setting of the PUSH bit may appear some
22961 	 * what random in that it might get set when it should not. This
22962 	 * should not pose any performance issues.
22963 	 */
22964 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22965 	    tcp->tcp_unsent == data_length)) {
22966 		flags = TH_ACK | TH_PUSH;
22967 	} else {
22968 		flags = TH_ACK;
22969 	}
22970 
22971 	if (tcp->tcp_ecn_ok) {
22972 		if (tcp->tcp_ecn_echo_on)
22973 			flags |= TH_ECE;
22974 
22975 		/*
22976 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22977 		 * There is no TCP flow control for non-data segments, and
22978 		 * only data segment is transmitted reliably.
22979 		 */
22980 		if (data_length > 0 && !rexmit) {
22981 			SET_ECT(tcp, rptr);
22982 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
22983 				flags |= TH_CWR;
22984 				tcp->tcp_ecn_cwr_sent = B_TRUE;
22985 			}
22986 		}
22987 	}
22988 
22989 	if (tcp->tcp_valid_bits) {
22990 		uint32_t u1;
22991 
22992 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
22993 		    seq == tcp->tcp_iss) {
22994 			uchar_t	*wptr;
22995 
22996 			/*
22997 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
22998 			 * TCP can only be in SYN-SENT, SYN-RCVD or
22999 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23000 			 * our SYN is not ack'ed but the app closes this
23001 			 * TCP connection.
23002 			 */
23003 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23004 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23005 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23006 
23007 			/*
23008 			 * Tack on the MSS option.  It is always needed
23009 			 * for both active and passive open.
23010 			 *
23011 			 * MSS option value should be interface MTU - MIN
23012 			 * TCP/IP header according to RFC 793 as it means
23013 			 * the maximum segment size TCP can receive.  But
23014 			 * to get around some broken middle boxes/end hosts
23015 			 * out there, we allow the option value to be the
23016 			 * same as the MSS option size on the peer side.
23017 			 * In this way, the other side will not send
23018 			 * anything larger than they can receive.
23019 			 *
23020 			 * Note that for SYN_SENT state, the ndd param
23021 			 * tcp_use_smss_as_mss_opt has no effect as we
23022 			 * don't know the peer's MSS option value. So
23023 			 * the only case we need to take care of is in
23024 			 * SYN_RCVD state, which is done later.
23025 			 */
23026 			wptr = mp1->b_wptr;
23027 			wptr[0] = TCPOPT_MAXSEG;
23028 			wptr[1] = TCPOPT_MAXSEG_LEN;
23029 			wptr += 2;
23030 			u1 = tcp->tcp_if_mtu -
23031 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23032 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23033 			    TCP_MIN_HEADER_LENGTH;
23034 			U16_TO_BE16(u1, wptr);
23035 			mp1->b_wptr = wptr + 2;
23036 			/* Update the offset to cover the additional word */
23037 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23038 
23039 			/*
23040 			 * Note that the following way of filling in
23041 			 * TCP options are not optimal.  Some NOPs can
23042 			 * be saved.  But there is no need at this time
23043 			 * to optimize it.  When it is needed, we will
23044 			 * do it.
23045 			 */
23046 			switch (tcp->tcp_state) {
23047 			case TCPS_SYN_SENT:
23048 				flags = TH_SYN;
23049 
23050 				if (tcp->tcp_snd_ts_ok) {
23051 					uint32_t llbolt = (uint32_t)lbolt;
23052 
23053 					wptr = mp1->b_wptr;
23054 					wptr[0] = TCPOPT_NOP;
23055 					wptr[1] = TCPOPT_NOP;
23056 					wptr[2] = TCPOPT_TSTAMP;
23057 					wptr[3] = TCPOPT_TSTAMP_LEN;
23058 					wptr += 4;
23059 					U32_TO_BE32(llbolt, wptr);
23060 					wptr += 4;
23061 					ASSERT(tcp->tcp_ts_recent == 0);
23062 					U32_TO_BE32(0L, wptr);
23063 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23064 					tcph->th_offset_and_rsrvd[0] +=
23065 					    (3 << 4);
23066 				}
23067 
23068 				/*
23069 				 * Set up all the bits to tell other side
23070 				 * we are ECN capable.
23071 				 */
23072 				if (tcp->tcp_ecn_ok) {
23073 					flags |= (TH_ECE | TH_CWR);
23074 				}
23075 				break;
23076 			case TCPS_SYN_RCVD:
23077 				flags |= TH_SYN;
23078 
23079 				/*
23080 				 * Reset the MSS option value to be SMSS
23081 				 * We should probably add back the bytes
23082 				 * for timestamp option and IPsec.  We
23083 				 * don't do that as this is a workaround
23084 				 * for broken middle boxes/end hosts, it
23085 				 * is better for us to be more cautious.
23086 				 * They may not take these things into
23087 				 * account in their SMSS calculation.  Thus
23088 				 * the peer's calculated SMSS may be smaller
23089 				 * than what it can be.  This should be OK.
23090 				 */
23091 				if (tcps->tcps_use_smss_as_mss_opt) {
23092 					u1 = tcp->tcp_mss;
23093 					U16_TO_BE16(u1, wptr);
23094 				}
23095 
23096 				/*
23097 				 * If the other side is ECN capable, reply
23098 				 * that we are also ECN capable.
23099 				 */
23100 				if (tcp->tcp_ecn_ok)
23101 					flags |= TH_ECE;
23102 				break;
23103 			default:
23104 				/*
23105 				 * The above ASSERT() makes sure that this
23106 				 * must be FIN-WAIT-1 state.  Our SYN has
23107 				 * not been ack'ed so retransmit it.
23108 				 */
23109 				flags |= TH_SYN;
23110 				break;
23111 			}
23112 
23113 			if (tcp->tcp_snd_ws_ok) {
23114 				wptr = mp1->b_wptr;
23115 				wptr[0] =  TCPOPT_NOP;
23116 				wptr[1] =  TCPOPT_WSCALE;
23117 				wptr[2] =  TCPOPT_WS_LEN;
23118 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23119 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23120 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23121 			}
23122 
23123 			if (tcp->tcp_snd_sack_ok) {
23124 				wptr = mp1->b_wptr;
23125 				wptr[0] = TCPOPT_NOP;
23126 				wptr[1] = TCPOPT_NOP;
23127 				wptr[2] = TCPOPT_SACK_PERMITTED;
23128 				wptr[3] = TCPOPT_SACK_OK_LEN;
23129 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23130 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23131 			}
23132 
23133 			/* allocb() of adequate mblk assures space */
23134 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23135 			    (uintptr_t)INT_MAX);
23136 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23137 			/*
23138 			 * Get IP set to checksum on our behalf
23139 			 * Include the adjustment for a source route if any.
23140 			 */
23141 			u1 += tcp->tcp_sum;
23142 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23143 			U16_TO_BE16(u1, tcph->th_sum);
23144 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23145 		}
23146 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23147 		    (seq + data_length) == tcp->tcp_fss) {
23148 			if (!tcp->tcp_fin_acked) {
23149 				flags |= TH_FIN;
23150 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23151 			}
23152 			if (!tcp->tcp_fin_sent) {
23153 				tcp->tcp_fin_sent = B_TRUE;
23154 				switch (tcp->tcp_state) {
23155 				case TCPS_SYN_RCVD:
23156 				case TCPS_ESTABLISHED:
23157 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23158 					break;
23159 				case TCPS_CLOSE_WAIT:
23160 					tcp->tcp_state = TCPS_LAST_ACK;
23161 					break;
23162 				}
23163 				if (tcp->tcp_suna == tcp->tcp_snxt)
23164 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23165 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23166 			}
23167 		}
23168 		/*
23169 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23170 		 * is smaller than seq, u1 will become a very huge value.
23171 		 * So the comparison will fail.  Also note that tcp_urp
23172 		 * should be positive, see RFC 793 page 17.
23173 		 */
23174 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23175 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23176 		    u1 < (uint32_t)(64 * 1024)) {
23177 			flags |= TH_URG;
23178 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23179 			U32_TO_ABE16(u1, tcph->th_urp);
23180 		}
23181 	}
23182 	tcph->th_flags[0] = (uchar_t)flags;
23183 	tcp->tcp_rack = tcp->tcp_rnxt;
23184 	tcp->tcp_rack_cnt = 0;
23185 
23186 	if (tcp->tcp_snd_ts_ok) {
23187 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23188 			uint32_t llbolt = (uint32_t)lbolt;
23189 
23190 			U32_TO_BE32(llbolt,
23191 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23192 			U32_TO_BE32(tcp->tcp_ts_recent,
23193 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23194 		}
23195 	}
23196 
23197 	if (num_sack_blk > 0) {
23198 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23199 		sack_blk_t *tmp;
23200 		int32_t	i;
23201 
23202 		wptr[0] = TCPOPT_NOP;
23203 		wptr[1] = TCPOPT_NOP;
23204 		wptr[2] = TCPOPT_SACK;
23205 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23206 		    sizeof (sack_blk_t);
23207 		wptr += TCPOPT_REAL_SACK_LEN;
23208 
23209 		tmp = tcp->tcp_sack_list;
23210 		for (i = 0; i < num_sack_blk; i++) {
23211 			U32_TO_BE32(tmp[i].begin, wptr);
23212 			wptr += sizeof (tcp_seq);
23213 			U32_TO_BE32(tmp[i].end, wptr);
23214 			wptr += sizeof (tcp_seq);
23215 		}
23216 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23217 	}
23218 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23219 	data_length += (int)(mp1->b_wptr - rptr);
23220 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23221 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23222 	} else {
23223 		ip6_t *ip6 = (ip6_t *)(rptr +
23224 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23225 		    sizeof (ip6i_t) : 0));
23226 
23227 		ip6->ip6_plen = htons(data_length -
23228 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23229 	}
23230 
23231 	/*
23232 	 * Prime pump for IP
23233 	 * Include the adjustment for a source route if any.
23234 	 */
23235 	data_length -= tcp->tcp_ip_hdr_len;
23236 	data_length += tcp->tcp_sum;
23237 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23238 	U16_TO_ABE16(data_length, tcph->th_sum);
23239 	if (tcp->tcp_ip_forward_progress) {
23240 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23241 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23242 		tcp->tcp_ip_forward_progress = B_FALSE;
23243 	}
23244 	return (mp1);
23245 }
23246 
23247 /* This function handles the push timeout. */
23248 void
23249 tcp_push_timer(void *arg)
23250 {
23251 	conn_t	*connp = (conn_t *)arg;
23252 	tcp_t *tcp = connp->conn_tcp;
23253 	uint_t		flags;
23254 	sodirect_t	*sodp;
23255 
23256 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
23257 
23258 	ASSERT(tcp->tcp_listener == NULL);
23259 
23260 	ASSERT(!IPCL_IS_NONSTR(connp));
23261 
23262 	/*
23263 	 * We need to plug synchronous streams during our drain to prevent
23264 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23265 	 */
23266 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23267 	tcp->tcp_push_tid = 0;
23268 
23269 	SOD_PTR_ENTER(tcp, sodp);
23270 	if (sodp != NULL) {
23271 		flags = tcp_rcv_sod_wakeup(tcp, sodp);
23272 		/* sod_wakeup() does the mutex_exit() */
23273 	} else if (tcp->tcp_rcv_list != NULL) {
23274 		flags = tcp_rcv_drain(tcp);
23275 	}
23276 	if (flags == TH_ACK_NEEDED)
23277 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23278 
23279 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23280 }
23281 
23282 /*
23283  * This function handles delayed ACK timeout.
23284  */
23285 static void
23286 tcp_ack_timer(void *arg)
23287 {
23288 	conn_t	*connp = (conn_t *)arg;
23289 	tcp_t *tcp = connp->conn_tcp;
23290 	mblk_t *mp;
23291 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23292 
23293 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23294 
23295 	tcp->tcp_ack_tid = 0;
23296 
23297 	if (tcp->tcp_fused)
23298 		return;
23299 
23300 	/*
23301 	 * Do not send ACK if there is no outstanding unack'ed data.
23302 	 */
23303 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23304 		return;
23305 	}
23306 
23307 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23308 		/*
23309 		 * Make sure we don't allow deferred ACKs to result in
23310 		 * timer-based ACKing.  If we have held off an ACK
23311 		 * when there was more than an mss here, and the timer
23312 		 * goes off, we have to worry about the possibility
23313 		 * that the sender isn't doing slow-start, or is out
23314 		 * of step with us for some other reason.  We fall
23315 		 * permanently back in the direction of
23316 		 * ACK-every-other-packet as suggested in RFC 1122.
23317 		 */
23318 		if (tcp->tcp_rack_abs_max > 2)
23319 			tcp->tcp_rack_abs_max--;
23320 		tcp->tcp_rack_cur_max = 2;
23321 	}
23322 	mp = tcp_ack_mp(tcp);
23323 
23324 	if (mp != NULL) {
23325 		BUMP_LOCAL(tcp->tcp_obsegs);
23326 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23327 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23328 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23329 	}
23330 }
23331 
23332 
23333 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23334 static mblk_t *
23335 tcp_ack_mp(tcp_t *tcp)
23336 {
23337 	uint32_t	seq_no;
23338 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23339 
23340 	/*
23341 	 * There are a few cases to be considered while setting the sequence no.
23342 	 * Essentially, we can come here while processing an unacceptable pkt
23343 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23344 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23345 	 * If we are here for a zero window probe, stick with suna. In all
23346 	 * other cases, we check if suna + swnd encompasses snxt and set
23347 	 * the sequence number to snxt, if so. If snxt falls outside the
23348 	 * window (the receiver probably shrunk its window), we will go with
23349 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23350 	 * receiver.
23351 	 */
23352 	if (tcp->tcp_zero_win_probe) {
23353 		seq_no = tcp->tcp_suna;
23354 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23355 		ASSERT(tcp->tcp_swnd == 0);
23356 		seq_no = tcp->tcp_snxt;
23357 	} else {
23358 		seq_no = SEQ_GT(tcp->tcp_snxt,
23359 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23360 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23361 	}
23362 
23363 	if (tcp->tcp_valid_bits) {
23364 		/*
23365 		 * For the complex case where we have to send some
23366 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23367 		 */
23368 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23369 		    NULL, B_FALSE));
23370 	} else {
23371 		/* Generate a simple ACK */
23372 		int	data_length;
23373 		uchar_t	*rptr;
23374 		tcph_t	*tcph;
23375 		mblk_t	*mp1;
23376 		int32_t	tcp_hdr_len;
23377 		int32_t	tcp_tcp_hdr_len;
23378 		int32_t	num_sack_blk = 0;
23379 		int32_t sack_opt_len;
23380 
23381 		/*
23382 		 * Allocate space for TCP + IP headers
23383 		 * and link-level header
23384 		 */
23385 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23386 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23387 			    tcp->tcp_num_sack_blk);
23388 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23389 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23390 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23391 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23392 		} else {
23393 			tcp_hdr_len = tcp->tcp_hdr_len;
23394 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23395 		}
23396 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23397 		if (!mp1)
23398 			return (NULL);
23399 
23400 		/* Update the latest receive window size in TCP header. */
23401 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23402 		    tcp->tcp_tcph->th_win);
23403 		/* copy in prototype TCP + IP header */
23404 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23405 		mp1->b_rptr = rptr;
23406 		mp1->b_wptr = rptr + tcp_hdr_len;
23407 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23408 
23409 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23410 
23411 		/* Set the TCP sequence number. */
23412 		U32_TO_ABE32(seq_no, tcph->th_seq);
23413 
23414 		/* Set up the TCP flag field. */
23415 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23416 		if (tcp->tcp_ecn_echo_on)
23417 			tcph->th_flags[0] |= TH_ECE;
23418 
23419 		tcp->tcp_rack = tcp->tcp_rnxt;
23420 		tcp->tcp_rack_cnt = 0;
23421 
23422 		/* fill in timestamp option if in use */
23423 		if (tcp->tcp_snd_ts_ok) {
23424 			uint32_t llbolt = (uint32_t)lbolt;
23425 
23426 			U32_TO_BE32(llbolt,
23427 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23428 			U32_TO_BE32(tcp->tcp_ts_recent,
23429 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23430 		}
23431 
23432 		/* Fill in SACK options */
23433 		if (num_sack_blk > 0) {
23434 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23435 			sack_blk_t *tmp;
23436 			int32_t	i;
23437 
23438 			wptr[0] = TCPOPT_NOP;
23439 			wptr[1] = TCPOPT_NOP;
23440 			wptr[2] = TCPOPT_SACK;
23441 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23442 			    sizeof (sack_blk_t);
23443 			wptr += TCPOPT_REAL_SACK_LEN;
23444 
23445 			tmp = tcp->tcp_sack_list;
23446 			for (i = 0; i < num_sack_blk; i++) {
23447 				U32_TO_BE32(tmp[i].begin, wptr);
23448 				wptr += sizeof (tcp_seq);
23449 				U32_TO_BE32(tmp[i].end, wptr);
23450 				wptr += sizeof (tcp_seq);
23451 			}
23452 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23453 			    << 4);
23454 		}
23455 
23456 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23457 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23458 		} else {
23459 			/* Check for ip6i_t header in sticky hdrs */
23460 			ip6_t *ip6 = (ip6_t *)(rptr +
23461 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23462 			    sizeof (ip6i_t) : 0));
23463 
23464 			ip6->ip6_plen = htons(tcp_hdr_len -
23465 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23466 		}
23467 
23468 		/*
23469 		 * Prime pump for checksum calculation in IP.  Include the
23470 		 * adjustment for a source route if any.
23471 		 */
23472 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23473 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23474 		U16_TO_ABE16(data_length, tcph->th_sum);
23475 
23476 		if (tcp->tcp_ip_forward_progress) {
23477 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23478 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23479 			tcp->tcp_ip_forward_progress = B_FALSE;
23480 		}
23481 		return (mp1);
23482 	}
23483 }
23484 
23485 /*
23486  * Hash list insertion routine for tcp_t structures. Each hash bucket
23487  * contains a list of tcp_t entries, and each entry is bound to a unique
23488  * port. If there are multiple tcp_t's that are bound to the same port, then
23489  * one of them will be linked into the hash bucket list, and the rest will
23490  * hang off of that one entry. For each port, entries bound to a specific IP
23491  * address will be inserted before those those bound to INADDR_ANY.
23492  */
23493 static void
23494 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23495 {
23496 	tcp_t	**tcpp;
23497 	tcp_t	*tcpnext;
23498 	tcp_t	*tcphash;
23499 
23500 	if (tcp->tcp_ptpbhn != NULL) {
23501 		ASSERT(!caller_holds_lock);
23502 		tcp_bind_hash_remove(tcp);
23503 	}
23504 	tcpp = &tbf->tf_tcp;
23505 	if (!caller_holds_lock) {
23506 		mutex_enter(&tbf->tf_lock);
23507 	} else {
23508 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23509 	}
23510 	tcphash = tcpp[0];
23511 	tcpnext = NULL;
23512 	if (tcphash != NULL) {
23513 		/* Look for an entry using the same port */
23514 		while ((tcphash = tcpp[0]) != NULL &&
23515 		    tcp->tcp_lport != tcphash->tcp_lport)
23516 			tcpp = &(tcphash->tcp_bind_hash);
23517 
23518 		/* The port was not found, just add to the end */
23519 		if (tcphash == NULL)
23520 			goto insert;
23521 
23522 		/*
23523 		 * OK, there already exists an entry bound to the
23524 		 * same port.
23525 		 *
23526 		 * If the new tcp bound to the INADDR_ANY address
23527 		 * and the first one in the list is not bound to
23528 		 * INADDR_ANY we skip all entries until we find the
23529 		 * first one bound to INADDR_ANY.
23530 		 * This makes sure that applications binding to a
23531 		 * specific address get preference over those binding to
23532 		 * INADDR_ANY.
23533 		 */
23534 		tcpnext = tcphash;
23535 		tcphash = NULL;
23536 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23537 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23538 			while ((tcpnext = tcpp[0]) != NULL &&
23539 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23540 				tcpp = &(tcpnext->tcp_bind_hash_port);
23541 
23542 			if (tcpnext) {
23543 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23544 				tcphash = tcpnext->tcp_bind_hash;
23545 				if (tcphash != NULL) {
23546 					tcphash->tcp_ptpbhn =
23547 					    &(tcp->tcp_bind_hash);
23548 					tcpnext->tcp_bind_hash = NULL;
23549 				}
23550 			}
23551 		} else {
23552 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23553 			tcphash = tcpnext->tcp_bind_hash;
23554 			if (tcphash != NULL) {
23555 				tcphash->tcp_ptpbhn =
23556 				    &(tcp->tcp_bind_hash);
23557 				tcpnext->tcp_bind_hash = NULL;
23558 			}
23559 		}
23560 	}
23561 insert:
23562 	tcp->tcp_bind_hash_port = tcpnext;
23563 	tcp->tcp_bind_hash = tcphash;
23564 	tcp->tcp_ptpbhn = tcpp;
23565 	tcpp[0] = tcp;
23566 	if (!caller_holds_lock)
23567 		mutex_exit(&tbf->tf_lock);
23568 }
23569 
23570 /*
23571  * Hash list removal routine for tcp_t structures.
23572  */
23573 static void
23574 tcp_bind_hash_remove(tcp_t *tcp)
23575 {
23576 	tcp_t	*tcpnext;
23577 	kmutex_t *lockp;
23578 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23579 
23580 	if (tcp->tcp_ptpbhn == NULL)
23581 		return;
23582 
23583 	/*
23584 	 * Extract the lock pointer in case there are concurrent
23585 	 * hash_remove's for this instance.
23586 	 */
23587 	ASSERT(tcp->tcp_lport != 0);
23588 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23589 
23590 	ASSERT(lockp != NULL);
23591 	mutex_enter(lockp);
23592 	if (tcp->tcp_ptpbhn) {
23593 		tcpnext = tcp->tcp_bind_hash_port;
23594 		if (tcpnext != NULL) {
23595 			tcp->tcp_bind_hash_port = NULL;
23596 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23597 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
23598 			if (tcpnext->tcp_bind_hash != NULL) {
23599 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
23600 				    &(tcpnext->tcp_bind_hash);
23601 				tcp->tcp_bind_hash = NULL;
23602 			}
23603 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
23604 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23605 			tcp->tcp_bind_hash = NULL;
23606 		}
23607 		*tcp->tcp_ptpbhn = tcpnext;
23608 		tcp->tcp_ptpbhn = NULL;
23609 	}
23610 	mutex_exit(lockp);
23611 }
23612 
23613 
23614 /*
23615  * Hash list lookup routine for tcp_t structures.
23616  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23617  */
23618 static tcp_t *
23619 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23620 {
23621 	tf_t	*tf;
23622 	tcp_t	*tcp;
23623 
23624 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23625 	mutex_enter(&tf->tf_lock);
23626 	for (tcp = tf->tf_tcp; tcp != NULL;
23627 	    tcp = tcp->tcp_acceptor_hash) {
23628 		if (tcp->tcp_acceptor_id == id) {
23629 			CONN_INC_REF(tcp->tcp_connp);
23630 			mutex_exit(&tf->tf_lock);
23631 			return (tcp);
23632 		}
23633 	}
23634 	mutex_exit(&tf->tf_lock);
23635 	return (NULL);
23636 }
23637 
23638 
23639 /*
23640  * Hash list insertion routine for tcp_t structures.
23641  */
23642 void
23643 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23644 {
23645 	tf_t	*tf;
23646 	tcp_t	**tcpp;
23647 	tcp_t	*tcpnext;
23648 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23649 
23650 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23651 
23652 	if (tcp->tcp_ptpahn != NULL)
23653 		tcp_acceptor_hash_remove(tcp);
23654 	tcpp = &tf->tf_tcp;
23655 	mutex_enter(&tf->tf_lock);
23656 	tcpnext = tcpp[0];
23657 	if (tcpnext)
23658 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23659 	tcp->tcp_acceptor_hash = tcpnext;
23660 	tcp->tcp_ptpahn = tcpp;
23661 	tcpp[0] = tcp;
23662 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23663 	mutex_exit(&tf->tf_lock);
23664 }
23665 
23666 /*
23667  * Hash list removal routine for tcp_t structures.
23668  */
23669 static void
23670 tcp_acceptor_hash_remove(tcp_t *tcp)
23671 {
23672 	tcp_t	*tcpnext;
23673 	kmutex_t *lockp;
23674 
23675 	/*
23676 	 * Extract the lock pointer in case there are concurrent
23677 	 * hash_remove's for this instance.
23678 	 */
23679 	lockp = tcp->tcp_acceptor_lockp;
23680 
23681 	if (tcp->tcp_ptpahn == NULL)
23682 		return;
23683 
23684 	ASSERT(lockp != NULL);
23685 	mutex_enter(lockp);
23686 	if (tcp->tcp_ptpahn) {
23687 		tcpnext = tcp->tcp_acceptor_hash;
23688 		if (tcpnext) {
23689 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23690 			tcp->tcp_acceptor_hash = NULL;
23691 		}
23692 		*tcp->tcp_ptpahn = tcpnext;
23693 		tcp->tcp_ptpahn = NULL;
23694 	}
23695 	mutex_exit(lockp);
23696 	tcp->tcp_acceptor_lockp = NULL;
23697 }
23698 
23699 /*
23700  * Type three generator adapted from the random() function in 4.4 BSD:
23701  */
23702 
23703 /*
23704  * Copyright (c) 1983, 1993
23705  *	The Regents of the University of California.  All rights reserved.
23706  *
23707  * Redistribution and use in source and binary forms, with or without
23708  * modification, are permitted provided that the following conditions
23709  * are met:
23710  * 1. Redistributions of source code must retain the above copyright
23711  *    notice, this list of conditions and the following disclaimer.
23712  * 2. Redistributions in binary form must reproduce the above copyright
23713  *    notice, this list of conditions and the following disclaimer in the
23714  *    documentation and/or other materials provided with the distribution.
23715  * 3. All advertising materials mentioning features or use of this software
23716  *    must display the following acknowledgement:
23717  *	This product includes software developed by the University of
23718  *	California, Berkeley and its contributors.
23719  * 4. Neither the name of the University nor the names of its contributors
23720  *    may be used to endorse or promote products derived from this software
23721  *    without specific prior written permission.
23722  *
23723  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23724  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23725  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23726  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23727  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23728  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23729  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23730  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23731  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23732  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23733  * SUCH DAMAGE.
23734  */
23735 
23736 /* Type 3 -- x**31 + x**3 + 1 */
23737 #define	DEG_3		31
23738 #define	SEP_3		3
23739 
23740 
23741 /* Protected by tcp_random_lock */
23742 static int tcp_randtbl[DEG_3 + 1];
23743 
23744 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23745 static int *tcp_random_rptr = &tcp_randtbl[1];
23746 
23747 static int *tcp_random_state = &tcp_randtbl[1];
23748 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23749 
23750 kmutex_t tcp_random_lock;
23751 
23752 void
23753 tcp_random_init(void)
23754 {
23755 	int i;
23756 	hrtime_t hrt;
23757 	time_t wallclock;
23758 	uint64_t result;
23759 
23760 	/*
23761 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23762 	 * a longlong, which may contain resolution down to nanoseconds.
23763 	 * The current time will either be a 32-bit or a 64-bit quantity.
23764 	 * XOR the two together in a 64-bit result variable.
23765 	 * Convert the result to a 32-bit value by multiplying the high-order
23766 	 * 32-bits by the low-order 32-bits.
23767 	 */
23768 
23769 	hrt = gethrtime();
23770 	(void) drv_getparm(TIME, &wallclock);
23771 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23772 	mutex_enter(&tcp_random_lock);
23773 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23774 	    (result & 0xffffffff);
23775 
23776 	for (i = 1; i < DEG_3; i++)
23777 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23778 		    + 12345;
23779 	tcp_random_fptr = &tcp_random_state[SEP_3];
23780 	tcp_random_rptr = &tcp_random_state[0];
23781 	mutex_exit(&tcp_random_lock);
23782 	for (i = 0; i < 10 * DEG_3; i++)
23783 		(void) tcp_random();
23784 }
23785 
23786 /*
23787  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23788  * This range is selected to be approximately centered on TCP_ISS / 2,
23789  * and easy to compute. We get this value by generating a 32-bit random
23790  * number, selecting out the high-order 17 bits, and then adding one so
23791  * that we never return zero.
23792  */
23793 int
23794 tcp_random(void)
23795 {
23796 	int i;
23797 
23798 	mutex_enter(&tcp_random_lock);
23799 	*tcp_random_fptr += *tcp_random_rptr;
23800 
23801 	/*
23802 	 * The high-order bits are more random than the low-order bits,
23803 	 * so we select out the high-order 17 bits and add one so that
23804 	 * we never return zero.
23805 	 */
23806 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23807 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23808 		tcp_random_fptr = tcp_random_state;
23809 		++tcp_random_rptr;
23810 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23811 		tcp_random_rptr = tcp_random_state;
23812 
23813 	mutex_exit(&tcp_random_lock);
23814 	return (i);
23815 }
23816 
23817 static int
23818 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23819     int *t_errorp, int *sys_errorp)
23820 {
23821 	int error;
23822 	int is_absreq_failure;
23823 	t_scalar_t *opt_lenp;
23824 	t_scalar_t opt_offset;
23825 	int prim_type;
23826 	struct T_conn_req *tcreqp;
23827 	struct T_conn_res *tcresp;
23828 	cred_t *cr;
23829 
23830 	/*
23831 	 * All Solaris components should pass a db_credp
23832 	 * for this TPI message, hence we ASSERT.
23833 	 * But in case there is some other M_PROTO that looks
23834 	 * like a TPI message sent by some other kernel
23835 	 * component, we check and return an error.
23836 	 */
23837 	cr = msg_getcred(mp, NULL);
23838 	ASSERT(cr != NULL);
23839 	if (cr == NULL)
23840 		return (-1);
23841 
23842 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23843 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23844 	    prim_type == T_CONN_RES);
23845 
23846 	switch (prim_type) {
23847 	case T_CONN_REQ:
23848 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23849 		opt_offset = tcreqp->OPT_offset;
23850 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23851 		break;
23852 	case O_T_CONN_RES:
23853 	case T_CONN_RES:
23854 		tcresp = (struct T_conn_res *)mp->b_rptr;
23855 		opt_offset = tcresp->OPT_offset;
23856 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23857 		break;
23858 	}
23859 
23860 	*t_errorp = 0;
23861 	*sys_errorp = 0;
23862 	*do_disconnectp = 0;
23863 
23864 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23865 	    opt_offset, cr, &tcp_opt_obj,
23866 	    NULL, &is_absreq_failure);
23867 
23868 	switch (error) {
23869 	case  0:		/* no error */
23870 		ASSERT(is_absreq_failure == 0);
23871 		return (0);
23872 	case ENOPROTOOPT:
23873 		*t_errorp = TBADOPT;
23874 		break;
23875 	case EACCES:
23876 		*t_errorp = TACCES;
23877 		break;
23878 	default:
23879 		*t_errorp = TSYSERR; *sys_errorp = error;
23880 		break;
23881 	}
23882 	if (is_absreq_failure != 0) {
23883 		/*
23884 		 * The connection request should get the local ack
23885 		 * T_OK_ACK and then a T_DISCON_IND.
23886 		 */
23887 		*do_disconnectp = 1;
23888 	}
23889 	return (-1);
23890 }
23891 
23892 /*
23893  * Split this function out so that if the secret changes, I'm okay.
23894  *
23895  * Initialize the tcp_iss_cookie and tcp_iss_key.
23896  */
23897 
23898 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23899 
23900 static void
23901 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
23902 {
23903 	struct {
23904 		int32_t current_time;
23905 		uint32_t randnum;
23906 		uint16_t pad;
23907 		uint8_t ether[6];
23908 		uint8_t passwd[PASSWD_SIZE];
23909 	} tcp_iss_cookie;
23910 	time_t t;
23911 
23912 	/*
23913 	 * Start with the current absolute time.
23914 	 */
23915 	(void) drv_getparm(TIME, &t);
23916 	tcp_iss_cookie.current_time = t;
23917 
23918 	/*
23919 	 * XXX - Need a more random number per RFC 1750, not this crap.
23920 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23921 	 */
23922 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23923 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23924 
23925 	/*
23926 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23927 	 * as a good template.
23928 	 */
23929 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23930 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23931 
23932 	/*
23933 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23934 	 */
23935 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23936 
23937 	/*
23938 	 * See 4010593 if this section becomes a problem again,
23939 	 * but the local ethernet address is useful here.
23940 	 */
23941 	(void) localetheraddr(NULL,
23942 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23943 
23944 	/*
23945 	 * Hash 'em all together.  The MD5Final is called per-connection.
23946 	 */
23947 	mutex_enter(&tcps->tcps_iss_key_lock);
23948 	MD5Init(&tcps->tcps_iss_key);
23949 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
23950 	    sizeof (tcp_iss_cookie));
23951 	mutex_exit(&tcps->tcps_iss_key_lock);
23952 }
23953 
23954 /*
23955  * Set the RFC 1948 pass phrase
23956  */
23957 /* ARGSUSED */
23958 static int
23959 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23960     cred_t *cr)
23961 {
23962 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
23963 
23964 	/*
23965 	 * Basically, value contains a new pass phrase.  Pass it along!
23966 	 */
23967 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
23968 	return (0);
23969 }
23970 
23971 /* ARGSUSED */
23972 static int
23973 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23974 {
23975 	bzero(buf, sizeof (tcp_sack_info_t));
23976 	return (0);
23977 }
23978 
23979 /* ARGSUSED */
23980 static int
23981 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23982 {
23983 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23984 	return (0);
23985 }
23986 
23987 /*
23988  * Make sure we wait until the default queue is setup, yet allow
23989  * tcp_g_q_create() to open a TCP stream.
23990  * We need to allow tcp_g_q_create() do do an open
23991  * of tcp, hence we compare curhread.
23992  * All others have to wait until the tcps_g_q has been
23993  * setup.
23994  */
23995 void
23996 tcp_g_q_setup(tcp_stack_t *tcps)
23997 {
23998 	mutex_enter(&tcps->tcps_g_q_lock);
23999 	if (tcps->tcps_g_q != NULL) {
24000 		mutex_exit(&tcps->tcps_g_q_lock);
24001 		return;
24002 	}
24003 	if (tcps->tcps_g_q_creator == NULL) {
24004 		/* This thread will set it up */
24005 		tcps->tcps_g_q_creator = curthread;
24006 		mutex_exit(&tcps->tcps_g_q_lock);
24007 		tcp_g_q_create(tcps);
24008 		mutex_enter(&tcps->tcps_g_q_lock);
24009 		ASSERT(tcps->tcps_g_q_creator == curthread);
24010 		tcps->tcps_g_q_creator = NULL;
24011 		cv_signal(&tcps->tcps_g_q_cv);
24012 		ASSERT(tcps->tcps_g_q != NULL);
24013 		mutex_exit(&tcps->tcps_g_q_lock);
24014 		return;
24015 	}
24016 	/* Everybody but the creator has to wait */
24017 	if (tcps->tcps_g_q_creator != curthread) {
24018 		while (tcps->tcps_g_q == NULL)
24019 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24020 	}
24021 	mutex_exit(&tcps->tcps_g_q_lock);
24022 }
24023 
24024 #define	IP	"ip"
24025 
24026 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24027 
24028 /*
24029  * Create a default tcp queue here instead of in strplumb
24030  */
24031 void
24032 tcp_g_q_create(tcp_stack_t *tcps)
24033 {
24034 	int error;
24035 	ldi_handle_t	lh = NULL;
24036 	ldi_ident_t	li = NULL;
24037 	int		rval;
24038 	cred_t		*cr;
24039 	major_t IP_MAJ;
24040 
24041 #ifdef NS_DEBUG
24042 	(void) printf("tcp_g_q_create()\n");
24043 #endif
24044 
24045 	IP_MAJ = ddi_name_to_major(IP);
24046 
24047 	ASSERT(tcps->tcps_g_q_creator == curthread);
24048 
24049 	error = ldi_ident_from_major(IP_MAJ, &li);
24050 	if (error) {
24051 #ifdef DEBUG
24052 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24053 		    error);
24054 #endif
24055 		return;
24056 	}
24057 
24058 	cr = zone_get_kcred(netstackid_to_zoneid(
24059 	    tcps->tcps_netstack->netstack_stackid));
24060 	ASSERT(cr != NULL);
24061 	/*
24062 	 * We set the tcp default queue to IPv6 because IPv4 falls
24063 	 * back to IPv6 when it can't find a client, but
24064 	 * IPv6 does not fall back to IPv4.
24065 	 */
24066 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24067 	if (error) {
24068 #ifdef DEBUG
24069 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24070 		    error);
24071 #endif
24072 		goto out;
24073 	}
24074 
24075 	/*
24076 	 * This ioctl causes the tcp framework to cache a pointer to
24077 	 * this stream, so we don't want to close the stream after
24078 	 * this operation.
24079 	 * Use the kernel credentials that are for the zone we're in.
24080 	 */
24081 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24082 	    (intptr_t)0, FKIOCTL, cr, &rval);
24083 	if (error) {
24084 #ifdef DEBUG
24085 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24086 		    "error %d\n", error);
24087 #endif
24088 		goto out;
24089 	}
24090 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24091 	lh = NULL;
24092 out:
24093 	/* Close layered handles */
24094 	if (li)
24095 		ldi_ident_release(li);
24096 	/* Keep cred around until _inactive needs it */
24097 	tcps->tcps_g_q_cr = cr;
24098 }
24099 
24100 /*
24101  * We keep tcp_g_q set until all other tcp_t's in the zone
24102  * has gone away, and then when tcp_g_q_inactive() is called
24103  * we clear it.
24104  */
24105 void
24106 tcp_g_q_destroy(tcp_stack_t *tcps)
24107 {
24108 #ifdef NS_DEBUG
24109 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24110 	    tcps->tcps_netstack->netstack_stackid);
24111 #endif
24112 
24113 	if (tcps->tcps_g_q == NULL) {
24114 		return;	/* Nothing to cleanup */
24115 	}
24116 	/*
24117 	 * Drop reference corresponding to the default queue.
24118 	 * This reference was added from tcp_open when the default queue
24119 	 * was created, hence we compensate for this extra drop in
24120 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24121 	 * the default queue was the last one to be open, in which
24122 	 * case, then tcp_g_q_inactive will be
24123 	 * called as a result of the refrele.
24124 	 */
24125 	TCPS_REFRELE(tcps);
24126 }
24127 
24128 /*
24129  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24130  * Run by tcp_q_q_inactive using a taskq.
24131  */
24132 static void
24133 tcp_g_q_close(void *arg)
24134 {
24135 	tcp_stack_t *tcps = arg;
24136 	int error;
24137 	ldi_handle_t	lh = NULL;
24138 	ldi_ident_t	li = NULL;
24139 	cred_t		*cr;
24140 	major_t IP_MAJ;
24141 
24142 	IP_MAJ = ddi_name_to_major(IP);
24143 
24144 #ifdef NS_DEBUG
24145 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24146 	    tcps->tcps_netstack->netstack_stackid,
24147 	    tcps->tcps_netstack->netstack_refcnt);
24148 #endif
24149 	lh = tcps->tcps_g_q_lh;
24150 	if (lh == NULL)
24151 		return;	/* Nothing to cleanup */
24152 
24153 	ASSERT(tcps->tcps_refcnt == 1);
24154 	ASSERT(tcps->tcps_g_q != NULL);
24155 
24156 	error = ldi_ident_from_major(IP_MAJ, &li);
24157 	if (error) {
24158 #ifdef DEBUG
24159 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
24160 		    error);
24161 #endif
24162 		return;
24163 	}
24164 
24165 	cr = tcps->tcps_g_q_cr;
24166 	tcps->tcps_g_q_cr = NULL;
24167 	ASSERT(cr != NULL);
24168 
24169 	/*
24170 	 * Make sure we can break the recursion when tcp_close decrements
24171 	 * the reference count causing g_q_inactive to be called again.
24172 	 */
24173 	tcps->tcps_g_q_lh = NULL;
24174 
24175 	/* close the default queue */
24176 	(void) ldi_close(lh, FREAD|FWRITE, cr);
24177 	/*
24178 	 * At this point in time tcps and the rest of netstack_t might
24179 	 * have been deleted.
24180 	 */
24181 	tcps = NULL;
24182 
24183 	/* Close layered handles */
24184 	ldi_ident_release(li);
24185 	crfree(cr);
24186 }
24187 
24188 /*
24189  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24190  *
24191  * Have to ensure that the ldi routines are not used by an
24192  * interrupt thread by using a taskq.
24193  */
24194 void
24195 tcp_g_q_inactive(tcp_stack_t *tcps)
24196 {
24197 	if (tcps->tcps_g_q_lh == NULL)
24198 		return;	/* Nothing to cleanup */
24199 
24200 	ASSERT(tcps->tcps_refcnt == 0);
24201 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
24202 
24203 	if (servicing_interrupt()) {
24204 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
24205 		    (void *) tcps, TQ_SLEEP);
24206 	} else {
24207 		tcp_g_q_close(tcps);
24208 	}
24209 }
24210 
24211 /*
24212  * Called by IP when IP is loaded into the kernel
24213  */
24214 void
24215 tcp_ddi_g_init(void)
24216 {
24217 	tcp_timercache = kmem_cache_create("tcp_timercache",
24218 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24219 	    NULL, NULL, NULL, NULL, NULL, 0);
24220 
24221 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24222 	    sizeof (tcp_sack_info_t), 0,
24223 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24224 
24225 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24226 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24227 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24228 
24229 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24230 
24231 	/* Initialize the random number generator */
24232 	tcp_random_init();
24233 
24234 	/* A single callback independently of how many netstacks we have */
24235 	ip_squeue_init(tcp_squeue_add);
24236 
24237 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
24238 
24239 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
24240 	    TASKQ_PREPOPULATE);
24241 
24242 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
24243 
24244 	/*
24245 	 * We want to be informed each time a stack is created or
24246 	 * destroyed in the kernel, so we can maintain the
24247 	 * set of tcp_stack_t's.
24248 	 */
24249 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
24250 	    tcp_stack_fini);
24251 }
24252 
24253 
24254 #define	INET_NAME	"ip"
24255 
24256 /*
24257  * Initialize the TCP stack instance.
24258  */
24259 static void *
24260 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
24261 {
24262 	tcp_stack_t	*tcps;
24263 	tcpparam_t	*pa;
24264 	int		i;
24265 	int		error = 0;
24266 	major_t		major;
24267 
24268 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
24269 	tcps->tcps_netstack = ns;
24270 
24271 	/* Initialize locks */
24272 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24273 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
24274 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24275 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24276 
24277 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
24278 	tcps->tcps_g_epriv_ports[0] = 2049;
24279 	tcps->tcps_g_epriv_ports[1] = 4045;
24280 	tcps->tcps_min_anonpriv_port = 512;
24281 
24282 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
24283 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
24284 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
24285 	    TCP_FANOUT_SIZE, KM_SLEEP);
24286 
24287 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24288 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
24289 		    MUTEX_DEFAULT, NULL);
24290 	}
24291 
24292 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24293 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
24294 		    MUTEX_DEFAULT, NULL);
24295 	}
24296 
24297 	/* TCP's IPsec code calls the packet dropper. */
24298 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
24299 
24300 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
24301 	tcps->tcps_params = pa;
24302 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24303 
24304 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
24305 	    A_CNT(lcl_tcp_param_arr), tcps);
24306 
24307 	/*
24308 	 * Note: To really walk the device tree you need the devinfo
24309 	 * pointer to your device which is only available after probe/attach.
24310 	 * The following is safe only because it uses ddi_root_node()
24311 	 */
24312 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24313 	    tcp_opt_obj.odb_opt_arr_cnt);
24314 
24315 	/*
24316 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24317 	 * by the boot scripts.
24318 	 *
24319 	 * Use NULL name, as the name is caught by the new lockstats.
24320 	 *
24321 	 * Initialize with some random, non-guessable string, like the global
24322 	 * T_INFO_ACK.
24323 	 */
24324 
24325 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24326 	    sizeof (tcp_g_t_info_ack), tcps);
24327 
24328 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
24329 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
24330 
24331 	major = mod_name_to_major(INET_NAME);
24332 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
24333 	ASSERT(error == 0);
24334 	return (tcps);
24335 }
24336 
24337 /*
24338  * Called when the IP module is about to be unloaded.
24339  */
24340 void
24341 tcp_ddi_g_destroy(void)
24342 {
24343 	tcp_g_kstat_fini(tcp_g_kstat);
24344 	tcp_g_kstat = NULL;
24345 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
24346 
24347 	mutex_destroy(&tcp_random_lock);
24348 
24349 	kmem_cache_destroy(tcp_timercache);
24350 	kmem_cache_destroy(tcp_sack_info_cache);
24351 	kmem_cache_destroy(tcp_iphc_cache);
24352 
24353 	netstack_unregister(NS_TCP);
24354 	taskq_destroy(tcp_taskq);
24355 }
24356 
24357 /*
24358  * Shut down the TCP stack instance.
24359  */
24360 /* ARGSUSED */
24361 static void
24362 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24363 {
24364 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24365 
24366 	tcp_g_q_destroy(tcps);
24367 }
24368 
24369 /*
24370  * Free the TCP stack instance.
24371  */
24372 static void
24373 tcp_stack_fini(netstackid_t stackid, void *arg)
24374 {
24375 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24376 	int i;
24377 
24378 	nd_free(&tcps->tcps_g_nd);
24379 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24380 	tcps->tcps_params = NULL;
24381 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24382 	tcps->tcps_wroff_xtra_param = NULL;
24383 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24384 	tcps->tcps_mdt_head_param = NULL;
24385 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24386 	tcps->tcps_mdt_tail_param = NULL;
24387 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24388 	tcps->tcps_mdt_max_pbufs_param = NULL;
24389 
24390 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24391 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24392 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24393 	}
24394 
24395 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24396 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
24397 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
24398 	}
24399 
24400 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
24401 	tcps->tcps_bind_fanout = NULL;
24402 
24403 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
24404 	tcps->tcps_acceptor_fanout = NULL;
24405 
24406 	mutex_destroy(&tcps->tcps_iss_key_lock);
24407 	mutex_destroy(&tcps->tcps_g_q_lock);
24408 	cv_destroy(&tcps->tcps_g_q_cv);
24409 	mutex_destroy(&tcps->tcps_epriv_port_lock);
24410 
24411 	ip_drop_unregister(&tcps->tcps_dropper);
24412 
24413 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
24414 	tcps->tcps_kstat = NULL;
24415 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
24416 
24417 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
24418 	tcps->tcps_mibkp = NULL;
24419 
24420 	ldi_ident_release(tcps->tcps_ldi_ident);
24421 	kmem_free(tcps, sizeof (*tcps));
24422 }
24423 
24424 /*
24425  * Generate ISS, taking into account NDD changes may happen halfway through.
24426  * (If the iss is not zero, set it.)
24427  */
24428 
24429 static void
24430 tcp_iss_init(tcp_t *tcp)
24431 {
24432 	MD5_CTX context;
24433 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24434 	uint32_t answer[4];
24435 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24436 
24437 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
24438 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
24439 	switch (tcps->tcps_strong_iss) {
24440 	case 2:
24441 		mutex_enter(&tcps->tcps_iss_key_lock);
24442 		context = tcps->tcps_iss_key;
24443 		mutex_exit(&tcps->tcps_iss_key_lock);
24444 		arg.ports = tcp->tcp_ports;
24445 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24446 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24447 			    &arg.src);
24448 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24449 			    &arg.dst);
24450 		} else {
24451 			arg.src = tcp->tcp_ip6h->ip6_src;
24452 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24453 		}
24454 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24455 		MD5Final((uchar_t *)answer, &context);
24456 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24457 		/*
24458 		 * Now that we've hashed into a unique per-connection sequence
24459 		 * space, add a random increment per strong_iss == 1.  So I
24460 		 * guess we'll have to...
24461 		 */
24462 		/* FALLTHRU */
24463 	case 1:
24464 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24465 		break;
24466 	default:
24467 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24468 		break;
24469 	}
24470 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24471 	tcp->tcp_fss = tcp->tcp_iss - 1;
24472 	tcp->tcp_suna = tcp->tcp_iss;
24473 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24474 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24475 	tcp->tcp_csuna = tcp->tcp_snxt;
24476 }
24477 
24478 /*
24479  * Exported routine for extracting active tcp connection status.
24480  *
24481  * This is used by the Solaris Cluster Networking software to
24482  * gather a list of connections that need to be forwarded to
24483  * specific nodes in the cluster when configuration changes occur.
24484  *
24485  * The callback is invoked for each tcp_t structure from all netstacks,
24486  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
24487  * from the netstack with the specified stack_id. Returning
24488  * non-zero from the callback routine terminates the search.
24489  */
24490 int
24491 cl_tcp_walk_list(netstackid_t stack_id,
24492     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
24493 {
24494 	netstack_handle_t nh;
24495 	netstack_t *ns;
24496 	int ret = 0;
24497 
24498 	if (stack_id >= 0) {
24499 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
24500 			return (EINVAL);
24501 
24502 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24503 		    ns->netstack_tcp);
24504 		netstack_rele(ns);
24505 		return (ret);
24506 	}
24507 
24508 	netstack_next_init(&nh);
24509 	while ((ns = netstack_next(&nh)) != NULL) {
24510 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24511 		    ns->netstack_tcp);
24512 		netstack_rele(ns);
24513 	}
24514 	netstack_next_fini(&nh);
24515 	return (ret);
24516 }
24517 
24518 static int
24519 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
24520     tcp_stack_t *tcps)
24521 {
24522 	tcp_t *tcp;
24523 	cl_tcp_info_t	cl_tcpi;
24524 	connf_t	*connfp;
24525 	conn_t	*connp;
24526 	int	i;
24527 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24528 
24529 	ASSERT(callback != NULL);
24530 
24531 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24532 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
24533 		connp = NULL;
24534 
24535 		while ((connp =
24536 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24537 
24538 			tcp = connp->conn_tcp;
24539 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
24540 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
24541 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
24542 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
24543 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
24544 			/*
24545 			 * The macros tcp_laddr and tcp_faddr give the IPv4
24546 			 * addresses. They are copied implicitly below as
24547 			 * mapped addresses.
24548 			 */
24549 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
24550 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24551 				cl_tcpi.cl_tcpi_faddr =
24552 				    tcp->tcp_ipha->ipha_dst;
24553 			} else {
24554 				cl_tcpi.cl_tcpi_faddr_v6 =
24555 				    tcp->tcp_ip6h->ip6_dst;
24556 			}
24557 
24558 			/*
24559 			 * If the callback returns non-zero
24560 			 * we terminate the traversal.
24561 			 */
24562 			if ((*callback)(&cl_tcpi, arg) != 0) {
24563 				CONN_DEC_REF(tcp->tcp_connp);
24564 				return (1);
24565 			}
24566 		}
24567 	}
24568 
24569 	return (0);
24570 }
24571 
24572 /*
24573  * Macros used for accessing the different types of sockaddr
24574  * structures inside a tcp_ioc_abort_conn_t.
24575  */
24576 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
24577 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
24578 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
24579 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
24580 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
24581 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
24582 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
24583 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
24584 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
24585 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
24586 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
24587 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
24588 
24589 /*
24590  * Return the correct error code to mimic the behavior
24591  * of a connection reset.
24592  */
24593 #define	TCP_AC_GET_ERRCODE(state, err) {	\
24594 		switch ((state)) {		\
24595 		case TCPS_SYN_SENT:		\
24596 		case TCPS_SYN_RCVD:		\
24597 			(err) = ECONNREFUSED;	\
24598 			break;			\
24599 		case TCPS_ESTABLISHED:		\
24600 		case TCPS_FIN_WAIT_1:		\
24601 		case TCPS_FIN_WAIT_2:		\
24602 		case TCPS_CLOSE_WAIT:		\
24603 			(err) = ECONNRESET;	\
24604 			break;			\
24605 		case TCPS_CLOSING:		\
24606 		case TCPS_LAST_ACK:		\
24607 		case TCPS_TIME_WAIT:		\
24608 			(err) = 0;		\
24609 			break;			\
24610 		default:			\
24611 			(err) = ENXIO;		\
24612 		}				\
24613 	}
24614 
24615 /*
24616  * Check if a tcp structure matches the info in acp.
24617  */
24618 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24619 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24620 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24621 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24622 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24623 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24624 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24625 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24626 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24627 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24628 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24629 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24630 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24631 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24632 	&(tcp)->tcp_ip_src_v6)) &&				\
24633 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24634 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24635 	&(tcp)->tcp_remote_v6)) &&				\
24636 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24637 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24638 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24639 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24640 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24641 	(acp)->ac_end >= (tcp)->tcp_state))
24642 
24643 #define	TCP_AC_MATCH(acp, tcp)					\
24644 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24645 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24646 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24647 
24648 /*
24649  * Build a message containing a tcp_ioc_abort_conn_t structure
24650  * which is filled in with information from acp and tp.
24651  */
24652 static mblk_t *
24653 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24654 {
24655 	mblk_t *mp;
24656 	tcp_ioc_abort_conn_t *tacp;
24657 
24658 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24659 	if (mp == NULL)
24660 		return (NULL);
24661 
24662 	mp->b_datap->db_type = M_CTL;
24663 
24664 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24665 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24666 	    sizeof (uint32_t));
24667 
24668 	tacp->ac_start = acp->ac_start;
24669 	tacp->ac_end = acp->ac_end;
24670 	tacp->ac_zoneid = acp->ac_zoneid;
24671 
24672 	if (acp->ac_local.ss_family == AF_INET) {
24673 		tacp->ac_local.ss_family = AF_INET;
24674 		tacp->ac_remote.ss_family = AF_INET;
24675 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24676 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24677 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24678 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24679 	} else {
24680 		tacp->ac_local.ss_family = AF_INET6;
24681 		tacp->ac_remote.ss_family = AF_INET6;
24682 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24683 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24684 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24685 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24686 	}
24687 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24688 	return (mp);
24689 }
24690 
24691 /*
24692  * Print a tcp_ioc_abort_conn_t structure.
24693  */
24694 static void
24695 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24696 {
24697 	char lbuf[128];
24698 	char rbuf[128];
24699 	sa_family_t af;
24700 	in_port_t lport, rport;
24701 	ushort_t logflags;
24702 
24703 	af = acp->ac_local.ss_family;
24704 
24705 	if (af == AF_INET) {
24706 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24707 		    lbuf, 128);
24708 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24709 		    rbuf, 128);
24710 		lport = ntohs(TCP_AC_V4LPORT(acp));
24711 		rport = ntohs(TCP_AC_V4RPORT(acp));
24712 	} else {
24713 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24714 		    lbuf, 128);
24715 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24716 		    rbuf, 128);
24717 		lport = ntohs(TCP_AC_V6LPORT(acp));
24718 		rport = ntohs(TCP_AC_V6RPORT(acp));
24719 	}
24720 
24721 	logflags = SL_TRACE | SL_NOTE;
24722 	/*
24723 	 * Don't print this message to the console if the operation was done
24724 	 * to a non-global zone.
24725 	 */
24726 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24727 		logflags |= SL_CONSOLE;
24728 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
24729 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24730 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24731 	    acp->ac_start, acp->ac_end);
24732 }
24733 
24734 /*
24735  * Called inside tcp_rput when a message built using
24736  * tcp_ioctl_abort_build_msg is put into a queue.
24737  * Note that when we get here there is no wildcard in acp any more.
24738  */
24739 static void
24740 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24741 {
24742 	tcp_ioc_abort_conn_t *acp;
24743 
24744 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24745 	if (tcp->tcp_state <= acp->ac_end) {
24746 		/*
24747 		 * If we get here, we are already on the correct
24748 		 * squeue. This ioctl follows the following path
24749 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24750 		 * ->tcp_ioctl_abort->squeue_enter (if on a
24751 		 * different squeue)
24752 		 */
24753 		int errcode;
24754 
24755 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24756 		(void) tcp_clean_death(tcp, errcode, 26);
24757 	}
24758 	freemsg(mp);
24759 }
24760 
24761 /*
24762  * Abort all matching connections on a hash chain.
24763  */
24764 static int
24765 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24766     boolean_t exact, tcp_stack_t *tcps)
24767 {
24768 	int nmatch, err = 0;
24769 	tcp_t *tcp;
24770 	MBLKP mp, last, listhead = NULL;
24771 	conn_t	*tconnp;
24772 	connf_t	*connfp;
24773 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24774 
24775 	connfp = &ipst->ips_ipcl_conn_fanout[index];
24776 
24777 startover:
24778 	nmatch = 0;
24779 
24780 	mutex_enter(&connfp->connf_lock);
24781 	for (tconnp = connfp->connf_head; tconnp != NULL;
24782 	    tconnp = tconnp->conn_next) {
24783 		tcp = tconnp->conn_tcp;
24784 		if (TCP_AC_MATCH(acp, tcp)) {
24785 			CONN_INC_REF(tcp->tcp_connp);
24786 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24787 			if (mp == NULL) {
24788 				err = ENOMEM;
24789 				CONN_DEC_REF(tcp->tcp_connp);
24790 				break;
24791 			}
24792 			mp->b_prev = (mblk_t *)tcp;
24793 
24794 			if (listhead == NULL) {
24795 				listhead = mp;
24796 				last = mp;
24797 			} else {
24798 				last->b_next = mp;
24799 				last = mp;
24800 			}
24801 			nmatch++;
24802 			if (exact)
24803 				break;
24804 		}
24805 
24806 		/* Avoid holding lock for too long. */
24807 		if (nmatch >= 500)
24808 			break;
24809 	}
24810 	mutex_exit(&connfp->connf_lock);
24811 
24812 	/* Pass mp into the correct tcp */
24813 	while ((mp = listhead) != NULL) {
24814 		listhead = listhead->b_next;
24815 		tcp = (tcp_t *)mp->b_prev;
24816 		mp->b_next = mp->b_prev = NULL;
24817 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
24818 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
24819 	}
24820 
24821 	*count += nmatch;
24822 	if (nmatch >= 500 && err == 0)
24823 		goto startover;
24824 	return (err);
24825 }
24826 
24827 /*
24828  * Abort all connections that matches the attributes specified in acp.
24829  */
24830 static int
24831 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
24832 {
24833 	sa_family_t af;
24834 	uint32_t  ports;
24835 	uint16_t *pports;
24836 	int err = 0, count = 0;
24837 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24838 	int index = -1;
24839 	ushort_t logflags;
24840 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24841 
24842 	af = acp->ac_local.ss_family;
24843 
24844 	if (af == AF_INET) {
24845 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24846 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24847 			pports = (uint16_t *)&ports;
24848 			pports[1] = TCP_AC_V4LPORT(acp);
24849 			pports[0] = TCP_AC_V4RPORT(acp);
24850 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24851 		}
24852 	} else {
24853 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24854 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24855 			pports = (uint16_t *)&ports;
24856 			pports[1] = TCP_AC_V6LPORT(acp);
24857 			pports[0] = TCP_AC_V6RPORT(acp);
24858 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24859 		}
24860 	}
24861 
24862 	/*
24863 	 * For cases where remote addr, local port, and remote port are non-
24864 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24865 	 */
24866 	if (index != -1) {
24867 		err = tcp_ioctl_abort_bucket(acp, index,
24868 		    &count, exact, tcps);
24869 	} else {
24870 		/*
24871 		 * loop through all entries for wildcard case
24872 		 */
24873 		for (index = 0;
24874 		    index < ipst->ips_ipcl_conn_fanout_size;
24875 		    index++) {
24876 			err = tcp_ioctl_abort_bucket(acp, index,
24877 			    &count, exact, tcps);
24878 			if (err != 0)
24879 				break;
24880 		}
24881 	}
24882 
24883 	logflags = SL_TRACE | SL_NOTE;
24884 	/*
24885 	 * Don't print this message to the console if the operation was done
24886 	 * to a non-global zone.
24887 	 */
24888 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24889 		logflags |= SL_CONSOLE;
24890 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24891 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24892 	if (err == 0 && count == 0)
24893 		err = ENOENT;
24894 	return (err);
24895 }
24896 
24897 /*
24898  * Process the TCP_IOC_ABORT_CONN ioctl request.
24899  */
24900 static void
24901 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24902 {
24903 	int	err;
24904 	IOCP    iocp;
24905 	MBLKP   mp1;
24906 	sa_family_t laf, raf;
24907 	tcp_ioc_abort_conn_t *acp;
24908 	zone_t		*zptr;
24909 	conn_t		*connp = Q_TO_CONN(q);
24910 	zoneid_t	zoneid = connp->conn_zoneid;
24911 	tcp_t		*tcp = connp->conn_tcp;
24912 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24913 
24914 	iocp = (IOCP)mp->b_rptr;
24915 
24916 	if ((mp1 = mp->b_cont) == NULL ||
24917 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24918 		err = EINVAL;
24919 		goto out;
24920 	}
24921 
24922 	/* check permissions */
24923 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
24924 		err = EPERM;
24925 		goto out;
24926 	}
24927 
24928 	if (mp1->b_cont != NULL) {
24929 		freemsg(mp1->b_cont);
24930 		mp1->b_cont = NULL;
24931 	}
24932 
24933 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24934 	laf = acp->ac_local.ss_family;
24935 	raf = acp->ac_remote.ss_family;
24936 
24937 	/* check that a zone with the supplied zoneid exists */
24938 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24939 		zptr = zone_find_by_id(zoneid);
24940 		if (zptr != NULL) {
24941 			zone_rele(zptr);
24942 		} else {
24943 			err = EINVAL;
24944 			goto out;
24945 		}
24946 	}
24947 
24948 	/*
24949 	 * For exclusive stacks we set the zoneid to zero
24950 	 * to make TCP operate as if in the global zone.
24951 	 */
24952 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
24953 		acp->ac_zoneid = GLOBAL_ZONEID;
24954 
24955 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24956 	    acp->ac_start > acp->ac_end || laf != raf ||
24957 	    (laf != AF_INET && laf != AF_INET6)) {
24958 		err = EINVAL;
24959 		goto out;
24960 	}
24961 
24962 	tcp_ioctl_abort_dump(acp);
24963 	err = tcp_ioctl_abort(acp, tcps);
24964 
24965 out:
24966 	if (mp1 != NULL) {
24967 		freemsg(mp1);
24968 		mp->b_cont = NULL;
24969 	}
24970 
24971 	if (err != 0)
24972 		miocnak(q, mp, 0, err);
24973 	else
24974 		miocack(q, mp, 0, 0);
24975 }
24976 
24977 /*
24978  * tcp_time_wait_processing() handles processing of incoming packets when
24979  * the tcp is in the TIME_WAIT state.
24980  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24981  * on the time wait list.
24982  */
24983 void
24984 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24985     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24986 {
24987 	int32_t		bytes_acked;
24988 	int32_t		gap;
24989 	int32_t		rgap;
24990 	tcp_opt_t	tcpopt;
24991 	uint_t		flags;
24992 	uint32_t	new_swnd = 0;
24993 	conn_t		*connp;
24994 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24995 
24996 	BUMP_LOCAL(tcp->tcp_ibsegs);
24997 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
24998 
24999 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25000 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25001 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25002 	if (tcp->tcp_snd_ts_ok) {
25003 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25004 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25005 			    tcp->tcp_rnxt, TH_ACK);
25006 			goto done;
25007 		}
25008 	}
25009 	gap = seg_seq - tcp->tcp_rnxt;
25010 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25011 	if (gap < 0) {
25012 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25013 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25014 		    (seg_len > -gap ? -gap : seg_len));
25015 		seg_len += gap;
25016 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25017 			if (flags & TH_RST) {
25018 				goto done;
25019 			}
25020 			if ((flags & TH_FIN) && seg_len == -1) {
25021 				/*
25022 				 * When TCP receives a duplicate FIN in
25023 				 * TIME_WAIT state, restart the 2 MSL timer.
25024 				 * See page 73 in RFC 793. Make sure this TCP
25025 				 * is already on the TIME_WAIT list. If not,
25026 				 * just restart the timer.
25027 				 */
25028 				if (TCP_IS_DETACHED(tcp)) {
25029 					if (tcp_time_wait_remove(tcp, NULL) ==
25030 					    B_TRUE) {
25031 						tcp_time_wait_append(tcp);
25032 						TCP_DBGSTAT(tcps,
25033 						    tcp_rput_time_wait);
25034 					}
25035 				} else {
25036 					ASSERT(tcp != NULL);
25037 					TCP_TIMER_RESTART(tcp,
25038 					    tcps->tcps_time_wait_interval);
25039 				}
25040 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25041 				    tcp->tcp_rnxt, TH_ACK);
25042 				goto done;
25043 			}
25044 			flags |=  TH_ACK_NEEDED;
25045 			seg_len = 0;
25046 			goto process_ack;
25047 		}
25048 
25049 		/* Fix seg_seq, and chew the gap off the front. */
25050 		seg_seq = tcp->tcp_rnxt;
25051 	}
25052 
25053 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25054 		/*
25055 		 * Make sure that when we accept the connection, pick
25056 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25057 		 * old connection.
25058 		 *
25059 		 * The next ISS generated is equal to tcp_iss_incr_extra
25060 		 * + ISS_INCR/2 + other components depending on the
25061 		 * value of tcp_strong_iss.  We pre-calculate the new
25062 		 * ISS here and compare with tcp_snxt to determine if
25063 		 * we need to make adjustment to tcp_iss_incr_extra.
25064 		 *
25065 		 * The above calculation is ugly and is a
25066 		 * waste of CPU cycles...
25067 		 */
25068 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25069 		int32_t adj;
25070 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25071 
25072 		switch (tcps->tcps_strong_iss) {
25073 		case 2: {
25074 			/* Add time and MD5 components. */
25075 			uint32_t answer[4];
25076 			struct {
25077 				uint32_t ports;
25078 				in6_addr_t src;
25079 				in6_addr_t dst;
25080 			} arg;
25081 			MD5_CTX context;
25082 
25083 			mutex_enter(&tcps->tcps_iss_key_lock);
25084 			context = tcps->tcps_iss_key;
25085 			mutex_exit(&tcps->tcps_iss_key_lock);
25086 			arg.ports = tcp->tcp_ports;
25087 			/* We use MAPPED addresses in tcp_iss_init */
25088 			arg.src = tcp->tcp_ip_src_v6;
25089 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25090 				IN6_IPADDR_TO_V4MAPPED(
25091 				    tcp->tcp_ipha->ipha_dst,
25092 				    &arg.dst);
25093 			} else {
25094 				arg.dst =
25095 				    tcp->tcp_ip6h->ip6_dst;
25096 			}
25097 			MD5Update(&context, (uchar_t *)&arg,
25098 			    sizeof (arg));
25099 			MD5Final((uchar_t *)answer, &context);
25100 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25101 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25102 			break;
25103 		}
25104 		case 1:
25105 			/* Add time component and min random (i.e. 1). */
25106 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25107 			break;
25108 		default:
25109 			/* Add only time component. */
25110 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25111 			break;
25112 		}
25113 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25114 			/*
25115 			 * New ISS not guaranteed to be ISS_INCR/2
25116 			 * ahead of the current tcp_snxt, so add the
25117 			 * difference to tcp_iss_incr_extra.
25118 			 */
25119 			tcps->tcps_iss_incr_extra += adj;
25120 		}
25121 		/*
25122 		 * If tcp_clean_death() can not perform the task now,
25123 		 * drop the SYN packet and let the other side re-xmit.
25124 		 * Otherwise pass the SYN packet back in, since the
25125 		 * old tcp state has been cleaned up or freed.
25126 		 */
25127 		if (tcp_clean_death(tcp, 0, 27) == -1)
25128 			goto done;
25129 		/*
25130 		 * We will come back to tcp_rput_data
25131 		 * on the global queue. Packets destined
25132 		 * for the global queue will be checked
25133 		 * with global policy. But the policy for
25134 		 * this packet has already been checked as
25135 		 * this was destined for the detached
25136 		 * connection. We need to bypass policy
25137 		 * check this time by attaching a dummy
25138 		 * ipsec_in with ipsec_in_dont_check set.
25139 		 */
25140 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25141 		if (connp != NULL) {
25142 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25143 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25144 			return;
25145 		}
25146 		goto done;
25147 	}
25148 
25149 	/*
25150 	 * rgap is the amount of stuff received out of window.  A negative
25151 	 * value is the amount out of window.
25152 	 */
25153 	if (rgap < 0) {
25154 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25155 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
25156 		/* Fix seg_len and make sure there is something left. */
25157 		seg_len += rgap;
25158 		if (seg_len <= 0) {
25159 			if (flags & TH_RST) {
25160 				goto done;
25161 			}
25162 			flags |=  TH_ACK_NEEDED;
25163 			seg_len = 0;
25164 			goto process_ack;
25165 		}
25166 	}
25167 	/*
25168 	 * Check whether we can update tcp_ts_recent.  This test is
25169 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
25170 	 * Extensions for High Performance: An Update", Internet Draft.
25171 	 */
25172 	if (tcp->tcp_snd_ts_ok &&
25173 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
25174 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
25175 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
25176 		tcp->tcp_last_rcv_lbolt = lbolt64;
25177 	}
25178 
25179 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
25180 		/* Always ack out of order packets */
25181 		flags |= TH_ACK_NEEDED;
25182 		seg_len = 0;
25183 	} else if (seg_len > 0) {
25184 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
25185 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
25186 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
25187 	}
25188 	if (flags & TH_RST) {
25189 		(void) tcp_clean_death(tcp, 0, 28);
25190 		goto done;
25191 	}
25192 	if (flags & TH_SYN) {
25193 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
25194 		    TH_RST|TH_ACK);
25195 		/*
25196 		 * Do not delete the TCP structure if it is in
25197 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
25198 		 */
25199 		goto done;
25200 	}
25201 process_ack:
25202 	if (flags & TH_ACK) {
25203 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
25204 		if (bytes_acked <= 0) {
25205 			if (bytes_acked == 0 && seg_len == 0 &&
25206 			    new_swnd == tcp->tcp_swnd)
25207 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
25208 		} else {
25209 			/* Acks something not sent */
25210 			flags |= TH_ACK_NEEDED;
25211 		}
25212 	}
25213 	if (flags & TH_ACK_NEEDED) {
25214 		/*
25215 		 * Time to send an ack for some reason.
25216 		 */
25217 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25218 		    tcp->tcp_rnxt, TH_ACK);
25219 	}
25220 done:
25221 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25222 		DB_CKSUMSTART(mp) = 0;
25223 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
25224 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
25225 	}
25226 	freemsg(mp);
25227 }
25228 
25229 /*
25230  * TCP Timers Implementation.
25231  */
25232 timeout_id_t
25233 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25234 {
25235 	mblk_t *mp;
25236 	tcp_timer_t *tcpt;
25237 	tcp_t *tcp = connp->conn_tcp;
25238 
25239 	ASSERT(connp->conn_sqp != NULL);
25240 
25241 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
25242 
25243 	if (tcp->tcp_timercache == NULL) {
25244 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25245 	} else {
25246 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
25247 		mp = tcp->tcp_timercache;
25248 		tcp->tcp_timercache = mp->b_next;
25249 		mp->b_next = NULL;
25250 		ASSERT(mp->b_wptr == NULL);
25251 	}
25252 
25253 	CONN_INC_REF(connp);
25254 	tcpt = (tcp_timer_t *)mp->b_rptr;
25255 	tcpt->connp = connp;
25256 	tcpt->tcpt_proc = f;
25257 	/*
25258 	 * TCP timers are normal timeouts. Plus, they do not require more than
25259 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
25260 	 * rounding up the expiration to the next resolution boundary, we can
25261 	 * batch timers in the callout subsystem to make TCP timers more
25262 	 * efficient. The roundup also protects short timers from expiring too
25263 	 * early before they have a chance to be cancelled.
25264 	 */
25265 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
25266 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
25267 
25268 	return ((timeout_id_t)mp);
25269 }
25270 
25271 static void
25272 tcp_timer_callback(void *arg)
25273 {
25274 	mblk_t *mp = (mblk_t *)arg;
25275 	tcp_timer_t *tcpt;
25276 	conn_t	*connp;
25277 
25278 	tcpt = (tcp_timer_t *)mp->b_rptr;
25279 	connp = tcpt->connp;
25280 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
25281 	    SQ_FILL, SQTAG_TCP_TIMER);
25282 }
25283 
25284 static void
25285 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
25286 {
25287 	tcp_timer_t *tcpt;
25288 	conn_t *connp = (conn_t *)arg;
25289 	tcp_t *tcp = connp->conn_tcp;
25290 
25291 	tcpt = (tcp_timer_t *)mp->b_rptr;
25292 	ASSERT(connp == tcpt->connp);
25293 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
25294 
25295 	/*
25296 	 * If the TCP has reached the closed state, don't proceed any
25297 	 * further. This TCP logically does not exist on the system.
25298 	 * tcpt_proc could for example access queues, that have already
25299 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
25300 	 */
25301 	if (tcp->tcp_state != TCPS_CLOSED) {
25302 		(*tcpt->tcpt_proc)(connp);
25303 	} else {
25304 		tcp->tcp_timer_tid = 0;
25305 	}
25306 	tcp_timer_free(connp->conn_tcp, mp);
25307 }
25308 
25309 /*
25310  * There is potential race with untimeout and the handler firing at the same
25311  * time. The mblock may be freed by the handler while we are trying to use
25312  * it. But since both should execute on the same squeue, this race should not
25313  * occur.
25314  */
25315 clock_t
25316 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
25317 {
25318 	mblk_t	*mp = (mblk_t *)id;
25319 	tcp_timer_t *tcpt;
25320 	clock_t delta;
25321 
25322 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
25323 
25324 	if (mp == NULL)
25325 		return (-1);
25326 
25327 	tcpt = (tcp_timer_t *)mp->b_rptr;
25328 	ASSERT(tcpt->connp == connp);
25329 
25330 	delta = untimeout_default(tcpt->tcpt_tid, 0);
25331 
25332 	if (delta >= 0) {
25333 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
25334 		tcp_timer_free(connp->conn_tcp, mp);
25335 		CONN_DEC_REF(connp);
25336 	}
25337 
25338 	return (delta);
25339 }
25340 
25341 /*
25342  * Allocate space for the timer event. The allocation looks like mblk, but it is
25343  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25344  *
25345  * Dealing with failures: If we can't allocate from the timer cache we try
25346  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25347  * points to b_rptr.
25348  * If we can't allocate anything using allocb_tryhard(), we perform a last
25349  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25350  * save the actual allocation size in b_datap.
25351  */
25352 mblk_t *
25353 tcp_timermp_alloc(int kmflags)
25354 {
25355 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25356 	    kmflags & ~KM_PANIC);
25357 
25358 	if (mp != NULL) {
25359 		mp->b_next = mp->b_prev = NULL;
25360 		mp->b_rptr = (uchar_t *)(&mp[1]);
25361 		mp->b_wptr = NULL;
25362 		mp->b_datap = NULL;
25363 		mp->b_queue = NULL;
25364 		mp->b_cont = NULL;
25365 	} else if (kmflags & KM_PANIC) {
25366 		/*
25367 		 * Failed to allocate memory for the timer. Try allocating from
25368 		 * dblock caches.
25369 		 */
25370 		/* ipclassifier calls this from a constructor - hence no tcps */
25371 		TCP_G_STAT(tcp_timermp_allocfail);
25372 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25373 		if (mp == NULL) {
25374 			size_t size = 0;
25375 			/*
25376 			 * Memory is really low. Try tryhard allocation.
25377 			 *
25378 			 * ipclassifier calls this from a constructor -
25379 			 * hence no tcps
25380 			 */
25381 			TCP_G_STAT(tcp_timermp_allocdblfail);
25382 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25383 			    sizeof (tcp_timer_t), &size, kmflags);
25384 			mp->b_rptr = (uchar_t *)(&mp[1]);
25385 			mp->b_next = mp->b_prev = NULL;
25386 			mp->b_wptr = (uchar_t *)-1;
25387 			mp->b_datap = (dblk_t *)size;
25388 			mp->b_queue = NULL;
25389 			mp->b_cont = NULL;
25390 		}
25391 		ASSERT(mp->b_wptr != NULL);
25392 	}
25393 	/* ipclassifier calls this from a constructor - hence no tcps */
25394 	TCP_G_DBGSTAT(tcp_timermp_alloced);
25395 
25396 	return (mp);
25397 }
25398 
25399 /*
25400  * Free per-tcp timer cache.
25401  * It can only contain entries from tcp_timercache.
25402  */
25403 void
25404 tcp_timermp_free(tcp_t *tcp)
25405 {
25406 	mblk_t *mp;
25407 
25408 	while ((mp = tcp->tcp_timercache) != NULL) {
25409 		ASSERT(mp->b_wptr == NULL);
25410 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25411 		kmem_cache_free(tcp_timercache, mp);
25412 	}
25413 }
25414 
25415 /*
25416  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25417  * events there already (currently at most two events are cached).
25418  * If the event is not allocated from the timer cache, free it right away.
25419  */
25420 static void
25421 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25422 {
25423 	mblk_t *mp1 = tcp->tcp_timercache;
25424 
25425 	if (mp->b_wptr != NULL) {
25426 		/*
25427 		 * This allocation is not from a timer cache, free it right
25428 		 * away.
25429 		 */
25430 		if (mp->b_wptr != (uchar_t *)-1)
25431 			freeb(mp);
25432 		else
25433 			kmem_free(mp, (size_t)mp->b_datap);
25434 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25435 		/* Cache this timer block for future allocations */
25436 		mp->b_rptr = (uchar_t *)(&mp[1]);
25437 		mp->b_next = mp1;
25438 		tcp->tcp_timercache = mp;
25439 	} else {
25440 		kmem_cache_free(tcp_timercache, mp);
25441 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
25442 	}
25443 }
25444 
25445 /*
25446  * End of TCP Timers implementation.
25447  */
25448 
25449 /*
25450  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25451  * on the specified backing STREAMS q. Note, the caller may make the
25452  * decision to call based on the tcp_t.tcp_flow_stopped value which
25453  * when check outside the q's lock is only an advisory check ...
25454  */
25455 void
25456 tcp_setqfull(tcp_t *tcp)
25457 {
25458 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25459 	conn_t	*connp = tcp->tcp_connp;
25460 
25461 	if (tcp->tcp_closed)
25462 		return;
25463 
25464 	if (IPCL_IS_NONSTR(connp)) {
25465 		(*connp->conn_upcalls->su_txq_full)
25466 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
25467 		tcp->tcp_flow_stopped = B_TRUE;
25468 	} else {
25469 		queue_t *q = tcp->tcp_wq;
25470 
25471 		if (!(q->q_flag & QFULL)) {
25472 			mutex_enter(QLOCK(q));
25473 			if (!(q->q_flag & QFULL)) {
25474 				/* still need to set QFULL */
25475 				q->q_flag |= QFULL;
25476 				tcp->tcp_flow_stopped = B_TRUE;
25477 				mutex_exit(QLOCK(q));
25478 				TCP_STAT(tcps, tcp_flwctl_on);
25479 			} else {
25480 				mutex_exit(QLOCK(q));
25481 			}
25482 		}
25483 	}
25484 }
25485 
25486 void
25487 tcp_clrqfull(tcp_t *tcp)
25488 {
25489 	conn_t  *connp = tcp->tcp_connp;
25490 
25491 	if (tcp->tcp_closed)
25492 		return;
25493 
25494 	if (IPCL_IS_NONSTR(connp)) {
25495 		(*connp->conn_upcalls->su_txq_full)
25496 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
25497 		tcp->tcp_flow_stopped = B_FALSE;
25498 	} else {
25499 		queue_t *q = tcp->tcp_wq;
25500 
25501 		if (q->q_flag & QFULL) {
25502 			mutex_enter(QLOCK(q));
25503 			if (q->q_flag & QFULL) {
25504 				q->q_flag &= ~QFULL;
25505 				tcp->tcp_flow_stopped = B_FALSE;
25506 				mutex_exit(QLOCK(q));
25507 				if (q->q_flag & QWANTW)
25508 					qbackenable(q, 0);
25509 			} else {
25510 				mutex_exit(QLOCK(q));
25511 			}
25512 		}
25513 	}
25514 }
25515 
25516 /*
25517  * kstats related to squeues i.e. not per IP instance
25518  */
25519 static void *
25520 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
25521 {
25522 	kstat_t *ksp;
25523 
25524 	tcp_g_stat_t template = {
25525 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
25526 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
25527 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
25528 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
25529 	};
25530 
25531 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
25532 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25533 	    KSTAT_FLAG_VIRTUAL);
25534 
25535 	if (ksp == NULL)
25536 		return (NULL);
25537 
25538 	bcopy(&template, tcp_g_statp, sizeof (template));
25539 	ksp->ks_data = (void *)tcp_g_statp;
25540 
25541 	kstat_install(ksp);
25542 	return (ksp);
25543 }
25544 
25545 static void
25546 tcp_g_kstat_fini(kstat_t *ksp)
25547 {
25548 	if (ksp != NULL) {
25549 		kstat_delete(ksp);
25550 	}
25551 }
25552 
25553 
25554 static void *
25555 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
25556 {
25557 	kstat_t *ksp;
25558 
25559 	tcp_stat_t template = {
25560 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
25561 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
25562 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
25563 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
25564 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
25565 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
25566 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
25567 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
25568 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
25569 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
25570 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
25571 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
25572 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
25573 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
25574 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
25575 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
25576 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
25577 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
25578 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
25579 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
25580 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
25581 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
25582 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
25583 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
25584 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
25585 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
25586 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
25587 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
25588 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
25589 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
25590 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
25591 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
25592 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
25593 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
25594 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
25595 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
25596 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
25597 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
25598 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
25599 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
25600 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
25601 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
25602 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
25603 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
25604 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
25605 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
25606 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
25607 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
25608 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
25609 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
25610 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
25611 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
25612 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
25613 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
25614 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
25615 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
25616 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
25617 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
25618 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
25619 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
25620 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
25621 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
25622 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
25623 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
25624 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
25625 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
25626 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
25627 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
25628 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
25629 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
25630 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
25631 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
25632 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
25633 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
25634 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
25635 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
25636 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
25637 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
25638 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
25639 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
25640 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
25641 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
25642 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
25643 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
25644 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
25645 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
25646 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
25647 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
25648 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
25649 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
25650 	};
25651 
25652 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
25653 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25654 	    KSTAT_FLAG_VIRTUAL, stackid);
25655 
25656 	if (ksp == NULL)
25657 		return (NULL);
25658 
25659 	bcopy(&template, tcps_statisticsp, sizeof (template));
25660 	ksp->ks_data = (void *)tcps_statisticsp;
25661 	ksp->ks_private = (void *)(uintptr_t)stackid;
25662 
25663 	kstat_install(ksp);
25664 	return (ksp);
25665 }
25666 
25667 static void
25668 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
25669 {
25670 	if (ksp != NULL) {
25671 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25672 		kstat_delete_netstack(ksp, stackid);
25673 	}
25674 }
25675 
25676 /*
25677  * TCP Kstats implementation
25678  */
25679 static void *
25680 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
25681 {
25682 	kstat_t	*ksp;
25683 
25684 	tcp_named_kstat_t template = {
25685 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
25686 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
25687 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
25688 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
25689 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
25690 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
25691 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
25692 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
25693 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
25694 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
25695 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
25696 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
25697 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
25698 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
25699 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
25700 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
25701 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
25702 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
25703 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
25704 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
25705 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
25706 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
25707 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
25708 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
25709 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
25710 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
25711 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
25712 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
25713 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
25714 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
25715 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
25716 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
25717 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
25718 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
25719 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
25720 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
25721 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
25722 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
25723 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
25724 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
25725 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
25726 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
25727 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
25728 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
25729 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
25730 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
25731 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
25732 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
25733 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
25734 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
25735 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
25736 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
25737 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
25738 	};
25739 
25740 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
25741 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
25742 
25743 	if (ksp == NULL)
25744 		return (NULL);
25745 
25746 	template.rtoAlgorithm.value.ui32 = 4;
25747 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
25748 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
25749 	template.maxConn.value.i32 = -1;
25750 
25751 	bcopy(&template, ksp->ks_data, sizeof (template));
25752 	ksp->ks_update = tcp_kstat_update;
25753 	ksp->ks_private = (void *)(uintptr_t)stackid;
25754 
25755 	kstat_install(ksp);
25756 	return (ksp);
25757 }
25758 
25759 static void
25760 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
25761 {
25762 	if (ksp != NULL) {
25763 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25764 		kstat_delete_netstack(ksp, stackid);
25765 	}
25766 }
25767 
25768 static int
25769 tcp_kstat_update(kstat_t *kp, int rw)
25770 {
25771 	tcp_named_kstat_t *tcpkp;
25772 	tcp_t		*tcp;
25773 	connf_t		*connfp;
25774 	conn_t		*connp;
25775 	int 		i;
25776 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
25777 	netstack_t	*ns;
25778 	tcp_stack_t	*tcps;
25779 	ip_stack_t	*ipst;
25780 
25781 	if ((kp == NULL) || (kp->ks_data == NULL))
25782 		return (EIO);
25783 
25784 	if (rw == KSTAT_WRITE)
25785 		return (EACCES);
25786 
25787 	ns = netstack_find_by_stackid(stackid);
25788 	if (ns == NULL)
25789 		return (-1);
25790 	tcps = ns->netstack_tcp;
25791 	if (tcps == NULL) {
25792 		netstack_rele(ns);
25793 		return (-1);
25794 	}
25795 
25796 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25797 
25798 	tcpkp->currEstab.value.ui32 = 0;
25799 
25800 	ipst = ns->netstack_ip;
25801 
25802 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25803 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25804 		connp = NULL;
25805 		while ((connp =
25806 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25807 			tcp = connp->conn_tcp;
25808 			switch (tcp_snmp_state(tcp)) {
25809 			case MIB2_TCP_established:
25810 			case MIB2_TCP_closeWait:
25811 				tcpkp->currEstab.value.ui32++;
25812 				break;
25813 			}
25814 		}
25815 	}
25816 
25817 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
25818 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
25819 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
25820 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
25821 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
25822 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
25823 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
25824 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
25825 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
25826 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
25827 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
25828 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
25829 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
25830 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
25831 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
25832 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
25833 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
25834 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
25835 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
25836 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
25837 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
25838 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
25839 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
25840 	tcpkp->inDataInorderSegs.value.ui32 =
25841 	    tcps->tcps_mib.tcpInDataInorderSegs;
25842 	tcpkp->inDataInorderBytes.value.ui32 =
25843 	    tcps->tcps_mib.tcpInDataInorderBytes;
25844 	tcpkp->inDataUnorderSegs.value.ui32 =
25845 	    tcps->tcps_mib.tcpInDataUnorderSegs;
25846 	tcpkp->inDataUnorderBytes.value.ui32 =
25847 	    tcps->tcps_mib.tcpInDataUnorderBytes;
25848 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
25849 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
25850 	tcpkp->inDataPartDupSegs.value.ui32 =
25851 	    tcps->tcps_mib.tcpInDataPartDupSegs;
25852 	tcpkp->inDataPartDupBytes.value.ui32 =
25853 	    tcps->tcps_mib.tcpInDataPartDupBytes;
25854 	tcpkp->inDataPastWinSegs.value.ui32 =
25855 	    tcps->tcps_mib.tcpInDataPastWinSegs;
25856 	tcpkp->inDataPastWinBytes.value.ui32 =
25857 	    tcps->tcps_mib.tcpInDataPastWinBytes;
25858 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
25859 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
25860 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
25861 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
25862 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
25863 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
25864 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
25865 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
25866 	tcpkp->timKeepaliveProbe.value.ui32 =
25867 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
25868 	tcpkp->timKeepaliveDrop.value.ui32 =
25869 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
25870 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
25871 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
25872 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
25873 	tcpkp->outSackRetransSegs.value.ui32 =
25874 	    tcps->tcps_mib.tcpOutSackRetransSegs;
25875 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
25876 
25877 	netstack_rele(ns);
25878 	return (0);
25879 }
25880 
25881 void
25882 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25883 {
25884 	uint16_t	hdr_len;
25885 	ipha_t		*ipha;
25886 	uint8_t		*nexthdrp;
25887 	tcph_t		*tcph;
25888 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
25889 
25890 	/* Already has an eager */
25891 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25892 		TCP_STAT(tcps, tcp_reinput_syn);
25893 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25894 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
25895 		return;
25896 	}
25897 
25898 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25899 	case IPV4_VERSION:
25900 		ipha = (ipha_t *)mp->b_rptr;
25901 		hdr_len = IPH_HDR_LENGTH(ipha);
25902 		break;
25903 	case IPV6_VERSION:
25904 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25905 		    &hdr_len, &nexthdrp)) {
25906 			CONN_DEC_REF(connp);
25907 			freemsg(mp);
25908 			return;
25909 		}
25910 		break;
25911 	}
25912 
25913 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25914 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25915 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25916 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
25917 	}
25918 
25919 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25920 	    SQ_FILL, SQTAG_TCP_REINPUT);
25921 }
25922 
25923 static int
25924 tcp_squeue_switch(int val)
25925 {
25926 	int rval = SQ_FILL;
25927 
25928 	switch (val) {
25929 	case 1:
25930 		rval = SQ_NODRAIN;
25931 		break;
25932 	case 2:
25933 		rval = SQ_PROCESS;
25934 		break;
25935 	default:
25936 		break;
25937 	}
25938 	return (rval);
25939 }
25940 
25941 /*
25942  * This is called once for each squeue - globally for all stack
25943  * instances.
25944  */
25945 static void
25946 tcp_squeue_add(squeue_t *sqp)
25947 {
25948 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25949 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
25950 
25951 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25952 	tcp_time_wait->tcp_time_wait_tid =
25953 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
25954 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
25955 	    CALLOUT_FLAG_ROUNDUP);
25956 	if (tcp_free_list_max_cnt == 0) {
25957 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
25958 		    max_ncpus : boot_max_ncpus);
25959 
25960 		/*
25961 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
25962 		 */
25963 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
25964 		    (tcp_ncpus * sizeof (tcp_t) * 100);
25965 	}
25966 	tcp_time_wait->tcp_free_list_cnt = 0;
25967 }
25968 
25969 static int
25970 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error, cred_t *cr, pid_t pid)
25971 {
25972 	mblk_t	*ire_mp = NULL;
25973 	mblk_t	*syn_mp;
25974 	mblk_t	*mdti;
25975 	mblk_t	*lsoi;
25976 	int	retval;
25977 	tcph_t	*tcph;
25978 	uint32_t	mss;
25979 	queue_t	*q = tcp->tcp_rq;
25980 	conn_t	*connp = tcp->tcp_connp;
25981 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25982 
25983 	if (error == 0) {
25984 		/*
25985 		 * Adapt Multidata information, if any.  The
25986 		 * following tcp_mdt_update routine will free
25987 		 * the message.
25988 		 */
25989 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
25990 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
25991 			    b_rptr)->mdt_capab, B_TRUE);
25992 			freemsg(mdti);
25993 		}
25994 
25995 		/*
25996 		 * Check to update LSO information with tcp, and
25997 		 * tcp_lso_update routine will free the message.
25998 		 */
25999 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
26000 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
26001 			    b_rptr)->lso_capab);
26002 			freemsg(lsoi);
26003 		}
26004 
26005 		/* Get the IRE, if we had requested for it */
26006 		if (mp != NULL)
26007 			ire_mp = tcp_ire_mp(&mp);
26008 
26009 		if (tcp->tcp_hard_binding) {
26010 			tcp->tcp_hard_binding = B_FALSE;
26011 			tcp->tcp_hard_bound = B_TRUE;
26012 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
26013 			if (retval != 0) {
26014 				error = EADDRINUSE;
26015 				goto bind_failed;
26016 			}
26017 		} else {
26018 			if (ire_mp != NULL)
26019 				freeb(ire_mp);
26020 			goto after_syn_sent;
26021 		}
26022 
26023 		retval = tcp_adapt_ire(tcp, ire_mp);
26024 		if (ire_mp != NULL)
26025 			freeb(ire_mp);
26026 		if (retval == 0) {
26027 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
26028 			    ENETUNREACH : EADDRNOTAVAIL);
26029 			goto ipcl_rm;
26030 		}
26031 		/*
26032 		 * Don't let an endpoint connect to itself.
26033 		 * Also checked in tcp_connect() but that
26034 		 * check can't handle the case when the
26035 		 * local IP address is INADDR_ANY.
26036 		 */
26037 		if (tcp->tcp_ipversion == IPV4_VERSION) {
26038 			if ((tcp->tcp_ipha->ipha_dst ==
26039 			    tcp->tcp_ipha->ipha_src) &&
26040 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26041 			    tcp->tcp_tcph->th_fport))) {
26042 				error = EADDRNOTAVAIL;
26043 				goto ipcl_rm;
26044 			}
26045 		} else {
26046 			if (IN6_ARE_ADDR_EQUAL(
26047 			    &tcp->tcp_ip6h->ip6_dst,
26048 			    &tcp->tcp_ip6h->ip6_src) &&
26049 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26050 			    tcp->tcp_tcph->th_fport))) {
26051 				error = EADDRNOTAVAIL;
26052 				goto ipcl_rm;
26053 			}
26054 		}
26055 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
26056 		/*
26057 		 * This should not be possible!  Just for
26058 		 * defensive coding...
26059 		 */
26060 		if (tcp->tcp_state != TCPS_SYN_SENT)
26061 			goto after_syn_sent;
26062 
26063 		if (is_system_labeled() &&
26064 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
26065 			error = EHOSTUNREACH;
26066 			goto ipcl_rm;
26067 		}
26068 
26069 		/*
26070 		 * tcp_adapt_ire() does not adjust
26071 		 * for TCP/IP header length.
26072 		 */
26073 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
26074 
26075 		/*
26076 		 * Just make sure our rwnd is at
26077 		 * least tcp_recv_hiwat_mss * MSS
26078 		 * large, and round up to the nearest
26079 		 * MSS.
26080 		 *
26081 		 * We do the round up here because
26082 		 * we need to get the interface
26083 		 * MTU first before we can do the
26084 		 * round up.
26085 		 */
26086 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
26087 		    tcps->tcps_recv_hiwat_minmss * mss);
26088 		if (!IPCL_IS_NONSTR(connp))
26089 			q->q_hiwat = tcp->tcp_rwnd;
26090 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
26091 		tcp_set_ws_value(tcp);
26092 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
26093 		    tcp->tcp_tcph->th_win);
26094 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
26095 			tcp->tcp_snd_ws_ok = B_TRUE;
26096 
26097 		/*
26098 		 * Set tcp_snd_ts_ok to true
26099 		 * so that tcp_xmit_mp will
26100 		 * include the timestamp
26101 		 * option in the SYN segment.
26102 		 */
26103 		if (tcps->tcps_tstamp_always ||
26104 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
26105 			tcp->tcp_snd_ts_ok = B_TRUE;
26106 		}
26107 
26108 		/*
26109 		 * tcp_snd_sack_ok can be set in
26110 		 * tcp_adapt_ire() if the sack metric
26111 		 * is set.  So check it here also.
26112 		 */
26113 		if (tcps->tcps_sack_permitted == 2 ||
26114 		    tcp->tcp_snd_sack_ok) {
26115 			if (tcp->tcp_sack_info == NULL) {
26116 				tcp->tcp_sack_info =
26117 				    kmem_cache_alloc(tcp_sack_info_cache,
26118 				    KM_SLEEP);
26119 			}
26120 			tcp->tcp_snd_sack_ok = B_TRUE;
26121 		}
26122 
26123 		/*
26124 		 * Should we use ECN?  Note that the current
26125 		 * default value (SunOS 5.9) of tcp_ecn_permitted
26126 		 * is 1.  The reason for doing this is that there
26127 		 * are equipments out there that will drop ECN
26128 		 * enabled IP packets.  Setting it to 1 avoids
26129 		 * compatibility problems.
26130 		 */
26131 		if (tcps->tcps_ecn_permitted == 2)
26132 			tcp->tcp_ecn_ok = B_TRUE;
26133 
26134 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
26135 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
26136 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
26137 		if (syn_mp) {
26138 			if (cr == NULL) {
26139 				cr = tcp->tcp_cred;
26140 				pid = tcp->tcp_cpid;
26141 			}
26142 			mblk_setcred(syn_mp, cr, pid);
26143 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
26144 		}
26145 	after_syn_sent:
26146 		if (mp != NULL) {
26147 			ASSERT(mp->b_cont == NULL);
26148 			freeb(mp);
26149 		}
26150 		return (error);
26151 	} else {
26152 		/* error */
26153 		if (tcp->tcp_debug) {
26154 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
26155 			    "tcp_post_ip_bind: error == %d", error);
26156 		}
26157 		if (mp != NULL) {
26158 			freeb(mp);
26159 		}
26160 	}
26161 
26162 ipcl_rm:
26163 	/*
26164 	 * Need to unbind with classifier since we were just
26165 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
26166 	 */
26167 	tcp->tcp_hard_bound = B_FALSE;
26168 	tcp->tcp_hard_binding = B_FALSE;
26169 
26170 	ipcl_hash_remove(connp);
26171 
26172 bind_failed:
26173 	tcp->tcp_state = TCPS_IDLE;
26174 	if (tcp->tcp_ipversion == IPV4_VERSION)
26175 		tcp->tcp_ipha->ipha_src = 0;
26176 	else
26177 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
26178 	/*
26179 	 * Copy of the src addr. in tcp_t is needed since
26180 	 * the lookup funcs. can only look at tcp_t
26181 	 */
26182 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
26183 
26184 	tcph = tcp->tcp_tcph;
26185 	tcph->th_lport[0] = 0;
26186 	tcph->th_lport[1] = 0;
26187 	tcp_bind_hash_remove(tcp);
26188 	bzero(&connp->u_port, sizeof (connp->u_port));
26189 	/* blow away saved option results if any */
26190 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26191 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26192 
26193 	conn_delete_ire(tcp->tcp_connp, NULL);
26194 
26195 	return (error);
26196 }
26197 
26198 static int
26199 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
26200     boolean_t bind_to_req_port_only, cred_t *cr)
26201 {
26202 	in_port_t	mlp_port;
26203 	mlp_type_t 	addrtype, mlptype;
26204 	boolean_t	user_specified;
26205 	in_port_t	allocated_port;
26206 	in_port_t	requested_port = *requested_port_ptr;
26207 	conn_t		*connp;
26208 	zone_t		*zone;
26209 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26210 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
26211 
26212 	/*
26213 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
26214 	 */
26215 	if (cr == NULL)
26216 		cr = tcp->tcp_cred;
26217 	/*
26218 	 * Get a valid port (within the anonymous range and should not
26219 	 * be a privileged one) to use if the user has not given a port.
26220 	 * If multiple threads are here, they may all start with
26221 	 * with the same initial port. But, it should be fine as long as
26222 	 * tcp_bindi will ensure that no two threads will be assigned
26223 	 * the same port.
26224 	 *
26225 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
26226 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
26227 	 * unless TCP_ANONPRIVBIND option is set.
26228 	 */
26229 	mlptype = mlptSingle;
26230 	mlp_port = requested_port;
26231 	if (requested_port == 0) {
26232 		requested_port = tcp->tcp_anon_priv_bind ?
26233 		    tcp_get_next_priv_port(tcp) :
26234 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
26235 		    tcp, B_TRUE);
26236 		if (requested_port == 0) {
26237 			return (-TNOADDR);
26238 		}
26239 		user_specified = B_FALSE;
26240 
26241 		/*
26242 		 * If the user went through one of the RPC interfaces to create
26243 		 * this socket and RPC is MLP in this zone, then give him an
26244 		 * anonymous MLP.
26245 		 */
26246 		connp = tcp->tcp_connp;
26247 		if (connp->conn_anon_mlp && is_system_labeled()) {
26248 			zone = crgetzone(cr);
26249 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26250 			    IPV6_VERSION, &v6addr,
26251 			    tcps->tcps_netstack->netstack_ip);
26252 			if (addrtype == mlptSingle) {
26253 				return (-TNOADDR);
26254 			}
26255 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26256 			    PMAPPORT, addrtype);
26257 			mlp_port = PMAPPORT;
26258 		}
26259 	} else {
26260 		int i;
26261 		boolean_t priv = B_FALSE;
26262 
26263 		/*
26264 		 * If the requested_port is in the well-known privileged range,
26265 		 * verify that the stream was opened by a privileged user.
26266 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
26267 		 * but instead the code relies on:
26268 		 * - the fact that the address of the array and its size never
26269 		 *   changes
26270 		 * - the atomic assignment of the elements of the array
26271 		 */
26272 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
26273 			priv = B_TRUE;
26274 		} else {
26275 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
26276 				if (requested_port ==
26277 				    tcps->tcps_g_epriv_ports[i]) {
26278 					priv = B_TRUE;
26279 					break;
26280 				}
26281 			}
26282 		}
26283 		if (priv) {
26284 			if (secpolicy_net_privaddr(cr, requested_port,
26285 			    IPPROTO_TCP) != 0) {
26286 				if (tcp->tcp_debug) {
26287 					(void) strlog(TCP_MOD_ID, 0, 1,
26288 					    SL_ERROR|SL_TRACE,
26289 					    "tcp_bind: no priv for port %d",
26290 					    requested_port);
26291 				}
26292 				return (-TACCES);
26293 			}
26294 		}
26295 		user_specified = B_TRUE;
26296 
26297 		connp = tcp->tcp_connp;
26298 		if (is_system_labeled()) {
26299 			zone = crgetzone(cr);
26300 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26301 			    IPV6_VERSION, &v6addr,
26302 			    tcps->tcps_netstack->netstack_ip);
26303 			if (addrtype == mlptSingle) {
26304 				return (-TNOADDR);
26305 			}
26306 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26307 			    requested_port, addrtype);
26308 		}
26309 	}
26310 
26311 	if (mlptype != mlptSingle) {
26312 		if (secpolicy_net_bindmlp(cr) != 0) {
26313 			if (tcp->tcp_debug) {
26314 				(void) strlog(TCP_MOD_ID, 0, 1,
26315 				    SL_ERROR|SL_TRACE,
26316 				    "tcp_bind: no priv for multilevel port %d",
26317 				    requested_port);
26318 			}
26319 			return (-TACCES);
26320 		}
26321 
26322 		/*
26323 		 * If we're specifically binding a shared IP address and the
26324 		 * port is MLP on shared addresses, then check to see if this
26325 		 * zone actually owns the MLP.  Reject if not.
26326 		 */
26327 		if (mlptype == mlptShared && addrtype == mlptShared) {
26328 			/*
26329 			 * No need to handle exclusive-stack zones since
26330 			 * ALL_ZONES only applies to the shared stack.
26331 			 */
26332 			zoneid_t mlpzone;
26333 
26334 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26335 			    htons(mlp_port));
26336 			if (connp->conn_zoneid != mlpzone) {
26337 				if (tcp->tcp_debug) {
26338 					(void) strlog(TCP_MOD_ID, 0, 1,
26339 					    SL_ERROR|SL_TRACE,
26340 					    "tcp_bind: attempt to bind port "
26341 					    "%d on shared addr in zone %d "
26342 					    "(should be %d)",
26343 					    mlp_port, connp->conn_zoneid,
26344 					    mlpzone);
26345 				}
26346 				return (-TACCES);
26347 			}
26348 		}
26349 
26350 		if (!user_specified) {
26351 			int err;
26352 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26353 			    requested_port, B_TRUE);
26354 			if (err != 0) {
26355 				if (tcp->tcp_debug) {
26356 					(void) strlog(TCP_MOD_ID, 0, 1,
26357 					    SL_ERROR|SL_TRACE,
26358 					    "tcp_bind: cannot establish anon "
26359 					    "MLP for port %d",
26360 					    requested_port);
26361 				}
26362 				return (err);
26363 			}
26364 			connp->conn_anon_port = B_TRUE;
26365 		}
26366 		connp->conn_mlp_type = mlptype;
26367 	}
26368 
26369 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26370 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26371 
26372 	if (allocated_port == 0) {
26373 		connp->conn_mlp_type = mlptSingle;
26374 		if (connp->conn_anon_port) {
26375 			connp->conn_anon_port = B_FALSE;
26376 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26377 			    requested_port, B_FALSE);
26378 		}
26379 		if (bind_to_req_port_only) {
26380 			if (tcp->tcp_debug) {
26381 				(void) strlog(TCP_MOD_ID, 0, 1,
26382 				    SL_ERROR|SL_TRACE,
26383 				    "tcp_bind: requested addr busy");
26384 			}
26385 			return (-TADDRBUSY);
26386 		} else {
26387 			/* If we are out of ports, fail the bind. */
26388 			if (tcp->tcp_debug) {
26389 				(void) strlog(TCP_MOD_ID, 0, 1,
26390 				    SL_ERROR|SL_TRACE,
26391 				    "tcp_bind: out of ports?");
26392 			}
26393 			return (-TNOADDR);
26394 		}
26395 	}
26396 
26397 	/* Pass the allocated port back */
26398 	*requested_port_ptr = allocated_port;
26399 	return (0);
26400 }
26401 
26402 static int
26403 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26404     boolean_t bind_to_req_port_only)
26405 {
26406 	tcp_t	*tcp = connp->conn_tcp;
26407 	sin_t	*sin;
26408 	sin6_t  *sin6;
26409 	sin6_t	sin6addr;
26410 	in_port_t requested_port;
26411 	ipaddr_t	v4addr;
26412 	in6_addr_t	v6addr;
26413 	uint_t	origipversion;
26414 	int	error = 0;
26415 
26416 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
26417 
26418 	if (tcp->tcp_state == TCPS_BOUND) {
26419 		return (0);
26420 	} else if (tcp->tcp_state > TCPS_BOUND) {
26421 		if (tcp->tcp_debug) {
26422 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26423 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26424 		}
26425 		return (-TOUTSTATE);
26426 	}
26427 	origipversion = tcp->tcp_ipversion;
26428 
26429 	if (sa != NULL && !OK_32PTR((char *)sa)) {
26430 		if (tcp->tcp_debug) {
26431 			(void) strlog(TCP_MOD_ID, 0, 1,
26432 			    SL_ERROR|SL_TRACE,
26433 			    "tcp_bind: bad address parameter, "
26434 			    "address %p, len %d",
26435 			    (void *)sa, len);
26436 		}
26437 		return (-TPROTO);
26438 	}
26439 
26440 	switch (len) {
26441 	case 0:		/* request for a generic port */
26442 		if (tcp->tcp_family == AF_INET) {
26443 			sin = (sin_t *)&sin6addr;
26444 			*sin = sin_null;
26445 			sin->sin_family = AF_INET;
26446 			tcp->tcp_ipversion = IPV4_VERSION;
26447 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
26448 		} else {
26449 			ASSERT(tcp->tcp_family == AF_INET6);
26450 			sin6 = (sin6_t *)&sin6addr;
26451 			*sin6 = sin6_null;
26452 			sin6->sin6_family = AF_INET6;
26453 			tcp->tcp_ipversion = IPV6_VERSION;
26454 			V6_SET_ZERO(v6addr);
26455 		}
26456 		requested_port = 0;
26457 		break;
26458 
26459 	case sizeof (sin_t):	/* Complete IPv4 address */
26460 		sin = (sin_t *)sa;
26461 		/*
26462 		 * With sockets sockfs will accept bogus sin_family in
26463 		 * bind() and replace it with the family used in the socket
26464 		 * call.
26465 		 */
26466 		if (sin->sin_family != AF_INET ||
26467 		    tcp->tcp_family != AF_INET) {
26468 			return (EAFNOSUPPORT);
26469 		}
26470 		requested_port = ntohs(sin->sin_port);
26471 		tcp->tcp_ipversion = IPV4_VERSION;
26472 		v4addr = sin->sin_addr.s_addr;
26473 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
26474 		break;
26475 
26476 	case sizeof (sin6_t): /* Complete IPv6 address */
26477 		sin6 = (sin6_t *)sa;
26478 		if (sin6->sin6_family != AF_INET6 ||
26479 		    tcp->tcp_family != AF_INET6) {
26480 			return (EAFNOSUPPORT);
26481 		}
26482 		requested_port = ntohs(sin6->sin6_port);
26483 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
26484 		    IPV4_VERSION : IPV6_VERSION;
26485 		v6addr = sin6->sin6_addr;
26486 		break;
26487 
26488 	default:
26489 		if (tcp->tcp_debug) {
26490 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26491 			    "tcp_bind: bad address length, %d", len);
26492 		}
26493 		return (EAFNOSUPPORT);
26494 		/* return (-TBADADDR); */
26495 	}
26496 
26497 	tcp->tcp_bound_source_v6 = v6addr;
26498 
26499 	/* Check for change in ipversion */
26500 	if (origipversion != tcp->tcp_ipversion) {
26501 		ASSERT(tcp->tcp_family == AF_INET6);
26502 		error = tcp->tcp_ipversion == IPV6_VERSION ?
26503 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
26504 		if (error) {
26505 			return (ENOMEM);
26506 		}
26507 	}
26508 
26509 	/*
26510 	 * Initialize family specific fields. Copy of the src addr.
26511 	 * in tcp_t is needed for the lookup funcs.
26512 	 */
26513 	if (tcp->tcp_ipversion == IPV6_VERSION) {
26514 		tcp->tcp_ip6h->ip6_src = v6addr;
26515 	} else {
26516 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
26517 	}
26518 	tcp->tcp_ip_src_v6 = v6addr;
26519 
26520 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
26521 
26522 	error = tcp_bind_select_lport(tcp, &requested_port,
26523 	    bind_to_req_port_only, cr);
26524 
26525 	return (error);
26526 }
26527 
26528 /*
26529  * Return unix error is tli error is TSYSERR, otherwise return a negative
26530  * tli error.
26531  */
26532 int
26533 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26534     boolean_t bind_to_req_port_only)
26535 {
26536 	int error;
26537 	tcp_t *tcp = connp->conn_tcp;
26538 
26539 	if (tcp->tcp_state >= TCPS_BOUND) {
26540 		if (tcp->tcp_debug) {
26541 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26542 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26543 		}
26544 		return (-TOUTSTATE);
26545 	}
26546 
26547 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
26548 	if (error != 0)
26549 		return (error);
26550 
26551 	ASSERT(tcp->tcp_state == TCPS_BOUND);
26552 
26553 	tcp->tcp_conn_req_max = 0;
26554 
26555 	/*
26556 	 * We need to make sure that the conn_recv is set to a non-null
26557 	 * value before we insert the conn into the classifier table.
26558 	 * This is to avoid a race with an incoming packet which does an
26559 	 * ipcl_classify().
26560 	 */
26561 	connp->conn_recv = tcp_conn_request;
26562 
26563 	if (tcp->tcp_family == AF_INET6) {
26564 		ASSERT(tcp->tcp_connp->conn_af_isv6);
26565 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
26566 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
26567 	} else {
26568 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
26569 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
26570 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
26571 	}
26572 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
26573 }
26574 
26575 int
26576 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
26577     socklen_t len, cred_t *cr)
26578 {
26579 	int 		error;
26580 	conn_t		*connp = (conn_t *)proto_handle;
26581 	squeue_t	*sqp = connp->conn_sqp;
26582 
26583 	/* All Solaris components should pass a cred for this operation. */
26584 	ASSERT(cr != NULL);
26585 
26586 	ASSERT(sqp != NULL);
26587 	ASSERT(connp->conn_upper_handle != NULL);
26588 
26589 	error = squeue_synch_enter(sqp, connp, 0);
26590 	if (error != 0) {
26591 		/* failed to enter */
26592 		return (ENOSR);
26593 	}
26594 
26595 	/* binding to a NULL address really means unbind */
26596 	if (sa == NULL) {
26597 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
26598 			error = tcp_do_unbind(connp);
26599 		else
26600 			error = EINVAL;
26601 	} else {
26602 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
26603 	}
26604 
26605 	squeue_synch_exit(sqp, connp);
26606 
26607 	if (error < 0) {
26608 		if (error == -TOUTSTATE)
26609 			error = EINVAL;
26610 		else
26611 			error = proto_tlitosyserr(-error);
26612 	}
26613 
26614 	return (error);
26615 }
26616 
26617 /*
26618  * If the return value from this function is positive, it's a UNIX error.
26619  * Otherwise, if it's negative, then the absolute value is a TLI error.
26620  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
26621  */
26622 int
26623 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
26624     cred_t *cr, pid_t pid)
26625 {
26626 	tcp_t		*tcp = connp->conn_tcp;
26627 	sin_t		*sin = (sin_t *)sa;
26628 	sin6_t		*sin6 = (sin6_t *)sa;
26629 	ipaddr_t	*dstaddrp;
26630 	in_port_t	dstport;
26631 	uint_t		srcid;
26632 	int		error = 0;
26633 
26634 	switch (len) {
26635 	default:
26636 		/*
26637 		 * Should never happen
26638 		 */
26639 		return (EINVAL);
26640 
26641 	case sizeof (sin_t):
26642 		sin = (sin_t *)sa;
26643 		if (sin->sin_port == 0) {
26644 			return (-TBADADDR);
26645 		}
26646 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
26647 			return (EAFNOSUPPORT);
26648 		}
26649 		break;
26650 
26651 	case sizeof (sin6_t):
26652 		sin6 = (sin6_t *)sa;
26653 		if (sin6->sin6_port == 0) {
26654 			return (-TBADADDR);
26655 		}
26656 		break;
26657 	}
26658 	/*
26659 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
26660 	 * make sure that the template IP header in the tcp structure is an
26661 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
26662 	 * need to this before we call tcp_bindi() so that the port lookup
26663 	 * code will look for ports in the correct port space (IPv4 and
26664 	 * IPv6 have separate port spaces).
26665 	 */
26666 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
26667 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26668 		int err = 0;
26669 
26670 		err = tcp_header_init_ipv4(tcp);
26671 			if (err != 0) {
26672 				error = ENOMEM;
26673 				goto connect_failed;
26674 			}
26675 		if (tcp->tcp_lport != 0)
26676 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
26677 	}
26678 
26679 	switch (tcp->tcp_state) {
26680 	case TCPS_LISTEN:
26681 		/*
26682 		 * Listening sockets are not allowed to issue connect().
26683 		 */
26684 		if (IPCL_IS_NONSTR(connp))
26685 			return (EOPNOTSUPP);
26686 		/* FALLTHRU */
26687 	case TCPS_IDLE:
26688 		/*
26689 		 * We support quick connect, refer to comments in
26690 		 * tcp_connect_*()
26691 		 */
26692 		/* FALLTHRU */
26693 	case TCPS_BOUND:
26694 		/*
26695 		 * We must bump the generation before the operation start.
26696 		 * This is done to ensure that any upcall made later on sends
26697 		 * up the right generation to the socket.
26698 		 */
26699 		SOCK_CONNID_BUMP(tcp->tcp_connid);
26700 
26701 		if (tcp->tcp_family == AF_INET6) {
26702 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26703 				return (tcp_connect_ipv6(tcp,
26704 				    &sin6->sin6_addr,
26705 				    sin6->sin6_port, sin6->sin6_flowinfo,
26706 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
26707 				    cr, pid));
26708 			}
26709 			/*
26710 			 * Destination adress is mapped IPv6 address.
26711 			 * Source bound address should be unspecified or
26712 			 * IPv6 mapped address as well.
26713 			 */
26714 			if (!IN6_IS_ADDR_UNSPECIFIED(
26715 			    &tcp->tcp_bound_source_v6) &&
26716 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
26717 				return (EADDRNOTAVAIL);
26718 			}
26719 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
26720 			dstport = sin6->sin6_port;
26721 			srcid = sin6->__sin6_src_id;
26722 		} else {
26723 			dstaddrp = &sin->sin_addr.s_addr;
26724 			dstport = sin->sin_port;
26725 			srcid = 0;
26726 		}
26727 
26728 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
26729 		    pid);
26730 		break;
26731 	default:
26732 		return (-TOUTSTATE);
26733 	}
26734 	/*
26735 	 * Note: Code below is the "failure" case
26736 	 */
26737 connect_failed:
26738 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26739 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26740 	return (error);
26741 }
26742 
26743 int
26744 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
26745     socklen_t len, sock_connid_t *id, cred_t *cr)
26746 {
26747 	conn_t		*connp = (conn_t *)proto_handle;
26748 	tcp_t		*tcp = connp->conn_tcp;
26749 	squeue_t	*sqp = connp->conn_sqp;
26750 	int		error;
26751 
26752 	ASSERT(connp->conn_upper_handle != NULL);
26753 
26754 	/* All Solaris components should pass a cred for this operation. */
26755 	ASSERT(cr != NULL);
26756 
26757 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
26758 	if (error != 0) {
26759 		return (error);
26760 	}
26761 
26762 	error = squeue_synch_enter(sqp, connp, 0);
26763 	if (error != 0) {
26764 		/* failed to enter */
26765 		return (ENOSR);
26766 	}
26767 
26768 	/*
26769 	 * TCP supports quick connect, so no need to do an implicit bind
26770 	 */
26771 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
26772 	if (error == 0) {
26773 		*id = connp->conn_tcp->tcp_connid;
26774 	} else if (error < 0) {
26775 		if (error == -TOUTSTATE) {
26776 			switch (connp->conn_tcp->tcp_state) {
26777 			case TCPS_SYN_SENT:
26778 				error = EALREADY;
26779 				break;
26780 			case TCPS_ESTABLISHED:
26781 				error = EISCONN;
26782 				break;
26783 			case TCPS_LISTEN:
26784 				error = EOPNOTSUPP;
26785 				break;
26786 			default:
26787 				error = EINVAL;
26788 				break;
26789 			}
26790 		} else {
26791 			error = proto_tlitosyserr(-error);
26792 		}
26793 	}
26794 done:
26795 	squeue_synch_exit(sqp, connp);
26796 
26797 	return ((error == 0) ? EINPROGRESS : error);
26798 }
26799 
26800 /* ARGSUSED */
26801 sock_lower_handle_t
26802 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
26803     uint_t *smodep, int *errorp, int flags, cred_t *credp)
26804 {
26805 	conn_t		*connp;
26806 	boolean_t	isv6 = family == AF_INET6;
26807 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
26808 	    (proto != 0 && proto != IPPROTO_TCP)) {
26809 		*errorp = EPROTONOSUPPORT;
26810 		return (NULL);
26811 	}
26812 
26813 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
26814 	if (connp == NULL) {
26815 		return (NULL);
26816 	}
26817 
26818 	/*
26819 	 * Put the ref for TCP. Ref for IP was already put
26820 	 * by ipcl_conn_create. Also Make the conn_t globally
26821 	 * visible to walkers
26822 	 */
26823 	mutex_enter(&connp->conn_lock);
26824 	CONN_INC_REF_LOCKED(connp);
26825 	ASSERT(connp->conn_ref == 2);
26826 	connp->conn_state_flags &= ~CONN_INCIPIENT;
26827 
26828 	connp->conn_flags |= IPCL_NONSTR;
26829 	mutex_exit(&connp->conn_lock);
26830 
26831 	ASSERT(errorp != NULL);
26832 	*errorp = 0;
26833 	*sock_downcalls = &sock_tcp_downcalls;
26834 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
26835 	    SM_SENDFILESUPP;
26836 
26837 	return ((sock_lower_handle_t)connp);
26838 }
26839 
26840 /* ARGSUSED */
26841 void
26842 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
26843     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
26844 {
26845 	conn_t *connp = (conn_t *)proto_handle;
26846 	struct sock_proto_props sopp;
26847 
26848 	ASSERT(connp->conn_upper_handle == NULL);
26849 
26850 	/* All Solaris components should pass a cred for this operation. */
26851 	ASSERT(cr != NULL);
26852 
26853 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
26854 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
26855 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
26856 
26857 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
26858 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
26859 	sopp.sopp_maxpsz = INFPSZ;
26860 	sopp.sopp_maxblk = INFPSZ;
26861 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
26862 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
26863 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
26864 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
26865 	    tcp_rinfo.mi_minpsz;
26866 
26867 	connp->conn_upcalls = sock_upcalls;
26868 	connp->conn_upper_handle = sock_handle;
26869 
26870 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
26871 }
26872 
26873 /* ARGSUSED */
26874 int
26875 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
26876 {
26877 	conn_t *connp = (conn_t *)proto_handle;
26878 
26879 	ASSERT(connp->conn_upper_handle != NULL);
26880 
26881 	/* All Solaris components should pass a cred for this operation. */
26882 	ASSERT(cr != NULL);
26883 
26884 	tcp_close_common(connp, flags);
26885 
26886 	ip_free_helper_stream(connp);
26887 
26888 	/*
26889 	 * Drop IP's reference on the conn. This is the last reference
26890 	 * on the connp if the state was less than established. If the
26891 	 * connection has gone into timewait state, then we will have
26892 	 * one ref for the TCP and one more ref (total of two) for the
26893 	 * classifier connected hash list (a timewait connections stays
26894 	 * in connected hash till closed).
26895 	 *
26896 	 * We can't assert the references because there might be other
26897 	 * transient reference places because of some walkers or queued
26898 	 * packets in squeue for the timewait state.
26899 	 */
26900 	CONN_DEC_REF(connp);
26901 	return (0);
26902 }
26903 
26904 /* ARGSUSED */
26905 int
26906 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
26907     cred_t *cr)
26908 {
26909 	tcp_t		*tcp;
26910 	uint32_t	msize;
26911 	conn_t *connp = (conn_t *)proto_handle;
26912 	int32_t		tcpstate;
26913 
26914 	/* All Solaris components should pass a cred for this operation. */
26915 	ASSERT(cr != NULL);
26916 
26917 	ASSERT(connp->conn_ref >= 2);
26918 	ASSERT(connp->conn_upper_handle != NULL);
26919 
26920 	if (msg->msg_controllen != 0) {
26921 		return (EOPNOTSUPP);
26922 
26923 	}
26924 	switch (DB_TYPE(mp)) {
26925 	case M_DATA:
26926 		tcp = connp->conn_tcp;
26927 		ASSERT(tcp != NULL);
26928 
26929 		tcpstate = tcp->tcp_state;
26930 		if (tcpstate < TCPS_ESTABLISHED) {
26931 			freemsg(mp);
26932 			return (ENOTCONN);
26933 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
26934 			freemsg(mp);
26935 			return (EPIPE);
26936 		}
26937 
26938 		msize = msgdsize(mp);
26939 
26940 		mutex_enter(&tcp->tcp_non_sq_lock);
26941 		tcp->tcp_squeue_bytes += msize;
26942 		/*
26943 		 * Squeue Flow Control
26944 		 */
26945 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
26946 			tcp_setqfull(tcp);
26947 		}
26948 		mutex_exit(&tcp->tcp_non_sq_lock);
26949 
26950 		/*
26951 		 * The application may pass in an address in the msghdr, but
26952 		 * we ignore the address on connection-oriented sockets.
26953 		 * Just like BSD this code does not generate an error for
26954 		 * TCP (a CONNREQUIRED socket) when sending to an address
26955 		 * passed in with sendto/sendmsg. Instead the data is
26956 		 * delivered on the connection as if no address had been
26957 		 * supplied.
26958 		 */
26959 		CONN_INC_REF(connp);
26960 
26961 		if (msg != NULL && msg->msg_flags & MSG_OOB) {
26962 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
26963 			    tcp_output_urgent, connp, tcp_squeue_flag,
26964 			    SQTAG_TCP_OUTPUT);
26965 		} else {
26966 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
26967 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
26968 		}
26969 
26970 		return (0);
26971 
26972 	default:
26973 		ASSERT(0);
26974 	}
26975 
26976 	freemsg(mp);
26977 	return (0);
26978 }
26979 
26980 /* ARGSUSED */
26981 void
26982 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
26983 {
26984 	int len;
26985 	uint32_t msize;
26986 	conn_t *connp = (conn_t *)arg;
26987 	tcp_t *tcp = connp->conn_tcp;
26988 
26989 	msize = msgdsize(mp);
26990 
26991 	len = msize - 1;
26992 	if (len < 0) {
26993 		freemsg(mp);
26994 		return;
26995 	}
26996 
26997 	/*
26998 	 * Try to force urgent data out on the wire.
26999 	 * Even if we have unsent data this will
27000 	 * at least send the urgent flag.
27001 	 * XXX does not handle more flag correctly.
27002 	 */
27003 	len += tcp->tcp_unsent;
27004 	len += tcp->tcp_snxt;
27005 	tcp->tcp_urg = len;
27006 	tcp->tcp_valid_bits |= TCP_URG_VALID;
27007 
27008 	/* Bypass tcp protocol for fused tcp loopback */
27009 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
27010 		return;
27011 	tcp_wput_data(tcp, mp, B_TRUE);
27012 }
27013 
27014 /* ARGSUSED */
27015 int
27016 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27017     socklen_t *addrlenp, cred_t *cr)
27018 {
27019 	conn_t	*connp = (conn_t *)proto_handle;
27020 	tcp_t	*tcp = connp->conn_tcp;
27021 
27022 	ASSERT(connp->conn_upper_handle != NULL);
27023 	/* All Solaris components should pass a cred for this operation. */
27024 	ASSERT(cr != NULL);
27025 
27026 	ASSERT(tcp != NULL);
27027 
27028 	return (tcp_do_getpeername(tcp, addr, addrlenp));
27029 }
27030 
27031 /* ARGSUSED */
27032 int
27033 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27034     socklen_t *addrlenp, cred_t *cr)
27035 {
27036 	conn_t	*connp = (conn_t *)proto_handle;
27037 	tcp_t	*tcp = connp->conn_tcp;
27038 
27039 	/* All Solaris components should pass a cred for this operation. */
27040 	ASSERT(cr != NULL);
27041 
27042 	ASSERT(connp->conn_upper_handle != NULL);
27043 
27044 	return (tcp_do_getsockname(tcp, addr, addrlenp));
27045 }
27046 
27047 /*
27048  * tcp_fallback
27049  *
27050  * A direct socket is falling back to using STREAMS. The queue
27051  * that is being passed down was created using tcp_open() with
27052  * the SO_FALLBACK flag set. As a result, the queue is not
27053  * associated with a conn, and the q_ptrs instead contain the
27054  * dev and minor area that should be used.
27055  *
27056  * The 'direct_sockfs' flag indicates whether the FireEngine
27057  * optimizations should be used. The common case would be that
27058  * optimizations are enabled, and they might be subsequently
27059  * disabled using the _SIOCSOCKFALLBACK ioctl.
27060  */
27061 
27062 /*
27063  * An active connection is falling back to TPI. Gather all the information
27064  * required by the STREAM head and TPI sonode and send it up.
27065  */
27066 void
27067 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
27068     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
27069 {
27070 	conn_t			*connp = tcp->tcp_connp;
27071 	struct stroptions	*stropt;
27072 	struct T_capability_ack tca;
27073 	struct sockaddr_in6	laddr, faddr;
27074 	socklen_t 		laddrlen, faddrlen;
27075 	short			opts;
27076 	int			error;
27077 	mblk_t			*mp;
27078 
27079 	/* Disable I/OAT during fallback */
27080 	tcp->tcp_sodirect = NULL;
27081 
27082 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
27083 	connp->conn_minor_arena = WR(q)->q_ptr;
27084 
27085 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
27086 
27087 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
27088 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
27089 
27090 	WR(q)->q_qinfo = &tcp_sock_winit;
27091 
27092 	if (!direct_sockfs)
27093 		tcp_disable_direct_sockfs(tcp);
27094 
27095 	/*
27096 	 * free the helper stream
27097 	 */
27098 	ip_free_helper_stream(connp);
27099 
27100 	/*
27101 	 * Notify the STREAM head about options
27102 	 */
27103 	DB_TYPE(stropt_mp) = M_SETOPTS;
27104 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27105 	stropt_mp->b_wptr += sizeof (struct stroptions);
27106 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27107 	stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
27108 
27109 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
27110 	    tcp->tcp_tcps->tcps_wroff_xtra);
27111 	if (tcp->tcp_snd_sack_ok)
27112 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
27113 	stropt->so_hiwat = tcp->tcp_fused ?
27114 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
27115 	    MAX(tcp->tcp_recv_hiwater, tcp->tcp_tcps->tcps_sth_rcv_hiwat);
27116 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
27117 
27118 	putnext(RD(q), stropt_mp);
27119 
27120 	/*
27121 	 * Collect the information needed to sync with the sonode
27122 	 */
27123 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
27124 
27125 	laddrlen = faddrlen = sizeof (sin6_t);
27126 	(void) tcp_do_getsockname(tcp, (struct sockaddr *)&laddr, &laddrlen);
27127 	error = tcp_do_getpeername(tcp, (struct sockaddr *)&faddr, &faddrlen);
27128 	if (error != 0)
27129 		faddrlen = 0;
27130 
27131 	opts = 0;
27132 	if (tcp->tcp_oobinline)
27133 		opts |= SO_OOBINLINE;
27134 	if (tcp->tcp_dontroute)
27135 		opts |= SO_DONTROUTE;
27136 
27137 	/*
27138 	 * Notify the socket that the protocol is now quiescent,
27139 	 * and it's therefore safe move data from the socket
27140 	 * to the stream head.
27141 	 */
27142 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
27143 	    (struct sockaddr *)&laddr, laddrlen,
27144 	    (struct sockaddr *)&faddr, faddrlen, opts);
27145 
27146 	while ((mp = tcp->tcp_rcv_list) != NULL) {
27147 		tcp->tcp_rcv_list = mp->b_next;
27148 		mp->b_next = NULL;
27149 		putnext(q, mp);
27150 	}
27151 	tcp->tcp_rcv_last_head = NULL;
27152 	tcp->tcp_rcv_last_tail = NULL;
27153 	tcp->tcp_rcv_cnt = 0;
27154 }
27155 
27156 /*
27157  * An eager is falling back to TPI. All we have to do is send
27158  * up a T_CONN_IND.
27159  */
27160 void
27161 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
27162 {
27163 	tcp_t *listener = eager->tcp_listener;
27164 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
27165 
27166 	ASSERT(listener != NULL);
27167 	ASSERT(mp != NULL);
27168 
27169 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
27170 
27171 	/*
27172 	 * TLI/XTI applications will get confused by
27173 	 * sending eager as an option since it violates
27174 	 * the option semantics. So remove the eager as
27175 	 * option since TLI/XTI app doesn't need it anyway.
27176 	 */
27177 	if (!direct_sockfs) {
27178 		struct T_conn_ind *conn_ind;
27179 
27180 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
27181 		conn_ind->OPT_length = 0;
27182 		conn_ind->OPT_offset = 0;
27183 	}
27184 
27185 	/*
27186 	 * Sockfs guarantees that the listener will not be closed
27187 	 * during fallback. So we can safely use the listener's queue.
27188 	 */
27189 	putnext(listener->tcp_rq, mp);
27190 }
27191 
27192 int
27193 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
27194     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
27195 {
27196 	tcp_t			*tcp;
27197 	conn_t 			*connp = (conn_t *)proto_handle;
27198 	int			error;
27199 	mblk_t			*stropt_mp;
27200 	mblk_t			*ordrel_mp;
27201 	mblk_t			*fused_sigurp_mp;
27202 
27203 	tcp = connp->conn_tcp;
27204 
27205 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
27206 	    NULL);
27207 
27208 	/* Pre-allocate the T_ordrel_ind mblk. */
27209 	ASSERT(tcp->tcp_ordrel_mp == NULL);
27210 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
27211 	    STR_NOSIG, NULL);
27212 	ordrel_mp->b_datap->db_type = M_PROTO;
27213 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
27214 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
27215 
27216 	/* Pre-allocate the M_PCSIG used by fusion */
27217 	fused_sigurp_mp = allocb_wait(1, BPRI_HI, STR_NOSIG, NULL);
27218 
27219 	/*
27220 	 * Enter the squeue so that no new packets can come in
27221 	 */
27222 	error = squeue_synch_enter(connp->conn_sqp, connp, 0);
27223 	if (error != 0) {
27224 		/* failed to enter, free all the pre-allocated messages. */
27225 		freeb(stropt_mp);
27226 		freeb(ordrel_mp);
27227 		freeb(fused_sigurp_mp);
27228 		/*
27229 		 * We cannot process the eager, so at least send out a
27230 		 * RST so the peer can reconnect.
27231 		 */
27232 		if (tcp->tcp_listener != NULL) {
27233 			(void) tcp_eager_blowoff(tcp->tcp_listener,
27234 			    tcp->tcp_conn_req_seqnum);
27235 		}
27236 		return (ENOMEM);
27237 	}
27238 
27239 	/*
27240 	 * No longer a direct socket
27241 	 */
27242 	connp->conn_flags &= ~IPCL_NONSTR;
27243 
27244 	tcp->tcp_ordrel_mp = ordrel_mp;
27245 
27246 	if (tcp->tcp_fused) {
27247 		ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
27248 		tcp->tcp_fused_sigurg_mp = fused_sigurp_mp;
27249 	} else {
27250 		freeb(fused_sigurp_mp);
27251 	}
27252 
27253 	if (tcp->tcp_listener != NULL) {
27254 		/* The eager will deal with opts when accept() is called */
27255 		freeb(stropt_mp);
27256 		tcp_fallback_eager(tcp, direct_sockfs);
27257 	} else {
27258 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
27259 		    quiesced_cb);
27260 	}
27261 
27262 	/*
27263 	 * There should be atleast two ref's (IP + TCP)
27264 	 */
27265 	ASSERT(connp->conn_ref >= 2);
27266 	squeue_synch_exit(connp->conn_sqp, connp);
27267 
27268 	return (0);
27269 }
27270 
27271 /* ARGSUSED */
27272 static void
27273 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
27274 {
27275 	conn_t 	*connp = (conn_t *)arg;
27276 	tcp_t	*tcp = connp->conn_tcp;
27277 
27278 	freemsg(mp);
27279 
27280 	if (tcp->tcp_fused)
27281 		tcp_unfuse(tcp);
27282 
27283 	if (tcp_xmit_end(tcp) != 0) {
27284 		/*
27285 		 * We were crossing FINs and got a reset from
27286 		 * the other side. Just ignore it.
27287 		 */
27288 		if (tcp->tcp_debug) {
27289 			(void) strlog(TCP_MOD_ID, 0, 1,
27290 			    SL_ERROR|SL_TRACE,
27291 			    "tcp_shutdown_output() out of state %s",
27292 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
27293 		}
27294 	}
27295 }
27296 
27297 /* ARGSUSED */
27298 int
27299 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
27300 {
27301 	conn_t  *connp = (conn_t *)proto_handle;
27302 	tcp_t   *tcp = connp->conn_tcp;
27303 
27304 	ASSERT(connp->conn_upper_handle != NULL);
27305 
27306 	/* All Solaris components should pass a cred for this operation. */
27307 	ASSERT(cr != NULL);
27308 
27309 	/*
27310 	 * X/Open requires that we check the connected state.
27311 	 */
27312 	if (tcp->tcp_state < TCPS_SYN_SENT)
27313 		return (ENOTCONN);
27314 
27315 	/* shutdown the send side */
27316 	if (how != SHUT_RD) {
27317 		mblk_t *bp;
27318 
27319 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
27320 		CONN_INC_REF(connp);
27321 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
27322 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
27323 
27324 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27325 		    SOCK_OPCTL_SHUT_SEND, 0);
27326 	}
27327 
27328 	/* shutdown the recv side */
27329 	if (how != SHUT_WR)
27330 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27331 		    SOCK_OPCTL_SHUT_RECV, 0);
27332 
27333 	return (0);
27334 }
27335 
27336 /*
27337  * SOP_LISTEN() calls into tcp_listen().
27338  */
27339 /* ARGSUSED */
27340 int
27341 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27342 {
27343 	conn_t	*connp = (conn_t *)proto_handle;
27344 	int 	error;
27345 	squeue_t *sqp = connp->conn_sqp;
27346 
27347 	ASSERT(connp->conn_upper_handle != NULL);
27348 
27349 	/* All Solaris components should pass a cred for this operation. */
27350 	ASSERT(cr != NULL);
27351 
27352 	error = squeue_synch_enter(sqp, connp, 0);
27353 	if (error != 0) {
27354 		/* failed to enter */
27355 		return (ENOBUFS);
27356 	}
27357 
27358 	error = tcp_do_listen(connp, backlog, cr);
27359 	if (error == 0) {
27360 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27361 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
27362 	} else if (error < 0) {
27363 		if (error == -TOUTSTATE)
27364 			error = EINVAL;
27365 		else
27366 			error = proto_tlitosyserr(-error);
27367 	}
27368 	squeue_synch_exit(sqp, connp);
27369 	return (error);
27370 }
27371 
27372 static int
27373 tcp_do_listen(conn_t *connp, int backlog, cred_t *cr)
27374 {
27375 	tcp_t		*tcp = connp->conn_tcp;
27376 	sin_t		*sin;
27377 	sin6_t  	*sin6;
27378 	int		error = 0;
27379 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27380 
27381 	/* All Solaris components should pass a cred for this operation. */
27382 	ASSERT(cr != NULL);
27383 
27384 	if (tcp->tcp_state >= TCPS_BOUND) {
27385 		if ((tcp->tcp_state == TCPS_BOUND ||
27386 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
27387 			/*
27388 			 * Handle listen() increasing backlog.
27389 			 * This is more "liberal" then what the TPI spec
27390 			 * requires but is needed to avoid a t_unbind
27391 			 * when handling listen() since the port number
27392 			 * might be "stolen" between the unbind and bind.
27393 			 */
27394 			goto do_listen;
27395 		}
27396 		if (tcp->tcp_debug) {
27397 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27398 			    "tcp_listen: bad state, %d", tcp->tcp_state);
27399 		}
27400 		return (-TOUTSTATE);
27401 	} else {
27402 		int32_t len;
27403 		sin6_t	addr;
27404 
27405 		/* Do an implicit bind: Request for a generic port. */
27406 		if (tcp->tcp_family == AF_INET) {
27407 			len = sizeof (sin_t);
27408 			sin = (sin_t *)&addr;
27409 			*sin = sin_null;
27410 			sin->sin_family = AF_INET;
27411 			tcp->tcp_ipversion = IPV4_VERSION;
27412 		} else {
27413 			ASSERT(tcp->tcp_family == AF_INET6);
27414 			len = sizeof (sin6_t);
27415 			sin6 = (sin6_t *)&addr;
27416 			*sin6 = sin6_null;
27417 			sin6->sin6_family = AF_INET6;
27418 			tcp->tcp_ipversion = IPV6_VERSION;
27419 		}
27420 
27421 		error = tcp_bind_check(connp, (struct sockaddr *)&addr, len,
27422 		    cr, B_FALSE);
27423 		if (error)
27424 			return (error);
27425 		/* Fall through and do the fanout insertion */
27426 	}
27427 
27428 do_listen:
27429 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
27430 	tcp->tcp_conn_req_max = backlog;
27431 	if (tcp->tcp_conn_req_max) {
27432 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
27433 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
27434 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
27435 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
27436 		/*
27437 		 * If this is a listener, do not reset the eager list
27438 		 * and other stuffs.  Note that we don't check if the
27439 		 * existing eager list meets the new tcp_conn_req_max
27440 		 * requirement.
27441 		 */
27442 		if (tcp->tcp_state != TCPS_LISTEN) {
27443 			tcp->tcp_state = TCPS_LISTEN;
27444 			/* Initialize the chain. Don't need the eager_lock */
27445 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
27446 			tcp->tcp_eager_next_drop_q0 = tcp;
27447 			tcp->tcp_eager_prev_drop_q0 = tcp;
27448 			tcp->tcp_second_ctimer_threshold =
27449 			    tcps->tcps_ip_abort_linterval;
27450 		}
27451 	}
27452 
27453 	/*
27454 	 * We can call ip_bind directly, the processing continues
27455 	 * in tcp_post_ip_bind().
27456 	 *
27457 	 * We need to make sure that the conn_recv is set to a non-null
27458 	 * value before we insert the conn into the classifier table.
27459 	 * This is to avoid a race with an incoming packet which does an
27460 	 * ipcl_classify().
27461 	 */
27462 	connp->conn_recv = tcp_conn_request;
27463 	if (tcp->tcp_family == AF_INET) {
27464 		error = ip_proto_bind_laddr_v4(connp, NULL,
27465 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
27466 	} else {
27467 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27468 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
27469 	}
27470 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27471 }
27472 
27473 void
27474 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
27475 {
27476 	conn_t  *connp = (conn_t *)proto_handle;
27477 	tcp_t	*tcp = connp->conn_tcp;
27478 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27479 	uint_t thwin;
27480 
27481 	ASSERT(connp->conn_upper_handle != NULL);
27482 
27483 	(void) squeue_synch_enter(connp->conn_sqp, connp, 0);
27484 
27485 	/* Flow control condition has been removed. */
27486 	tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
27487 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
27488 	    << tcp->tcp_rcv_ws;
27489 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
27490 	/*
27491 	 * Send back a window update immediately if TCP is above
27492 	 * ESTABLISHED state and the increase of the rcv window
27493 	 * that the other side knows is at least 1 MSS after flow
27494 	 * control is lifted.
27495 	 */
27496 	if (tcp->tcp_state >= TCPS_ESTABLISHED &&
27497 	    (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss)) {
27498 		tcp_xmit_ctl(NULL, tcp,
27499 		    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
27500 		    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
27501 		BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
27502 	}
27503 
27504 	squeue_synch_exit(connp->conn_sqp, connp);
27505 }
27506 
27507 /* ARGSUSED */
27508 int
27509 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
27510     int mode, int32_t *rvalp, cred_t *cr)
27511 {
27512 	conn_t  	*connp = (conn_t *)proto_handle;
27513 	int		error;
27514 
27515 	ASSERT(connp->conn_upper_handle != NULL);
27516 
27517 	/* All Solaris components should pass a cred for this operation. */
27518 	ASSERT(cr != NULL);
27519 
27520 	switch (cmd) {
27521 		case ND_SET:
27522 		case ND_GET:
27523 		case TCP_IOC_DEFAULT_Q:
27524 		case _SIOCSOCKFALLBACK:
27525 		case TCP_IOC_ABORT_CONN:
27526 		case TI_GETPEERNAME:
27527 		case TI_GETMYNAME:
27528 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
27529 			    cmd));
27530 			error = EINVAL;
27531 			break;
27532 		default:
27533 			/*
27534 			 * Pass on to IP using helper stream
27535 			 */
27536 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
27537 			    cmd, arg, mode, cr, rvalp);
27538 			break;
27539 	}
27540 	return (error);
27541 }
27542 
27543 sock_downcalls_t sock_tcp_downcalls = {
27544 	tcp_activate,
27545 	tcp_accept,
27546 	tcp_bind,
27547 	tcp_listen,
27548 	tcp_connect,
27549 	tcp_getpeername,
27550 	tcp_getsockname,
27551 	tcp_getsockopt,
27552 	tcp_setsockopt,
27553 	tcp_sendmsg,
27554 	NULL,
27555 	NULL,
27556 	NULL,
27557 	tcp_shutdown,
27558 	tcp_clr_flowctrl,
27559 	tcp_ioctl,
27560 	tcp_close,
27561 };
27562