xref: /titanic_52/usr/src/uts/common/inet/tcp/tcp.c (revision 5699897cfc22a71e1441854892e3659f179ee0bc)
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 <net/pfkeyv2.h>
90 #include <inet/ipsec_info.h>
91 #include <inet/ipdrop.h>
92 
93 #include <inet/ipclassifier.h>
94 #include <inet/ip_ire.h>
95 #include <inet/ip_ftable.h>
96 #include <inet/ip_if.h>
97 #include <inet/ipp_common.h>
98 #include <inet/ip_netinfo.h>
99 #include <sys/squeue_impl.h>
100 #include <sys/squeue.h>
101 #include <inet/kssl/ksslapi.h>
102 #include <sys/tsol/label.h>
103 #include <sys/tsol/tnet.h>
104 #include <rpc/pmap_prot.h>
105 #include <sys/callo.h>
106 
107 /*
108  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
109  *
110  * (Read the detailed design doc in PSARC case directory)
111  *
112  * The entire tcp state is contained in tcp_t and conn_t structure
113  * which are allocated in tandem using ipcl_conn_create() and passing
114  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
115  * the references on the tcp_t. The tcp_t structure is never compressed
116  * and packets always land on the correct TCP perimeter from the time
117  * eager is created till the time tcp_t dies (as such the old mentat
118  * TCP global queue is not used for detached state and no IPSEC checking
119  * is required). The global queue is still allocated to send out resets
120  * for connection which have no listeners and IP directly calls
121  * tcp_xmit_listeners_reset() which does any policy check.
122  *
123  * Protection and Synchronisation mechanism:
124  *
125  * The tcp data structure does not use any kind of lock for protecting
126  * its state but instead uses 'squeues' for mutual exclusion from various
127  * read and write side threads. To access a tcp member, the thread should
128  * always be behind squeue (via squeue_enter with flags as SQ_FILL, SQ_PROCESS,
129  * or SQ_NODRAIN). Since the squeues allow a direct function call, caller
130  * can pass any tcp function having prototype of edesc_t as argument
131  * (different from traditional STREAMs model where packets come in only
132  * designated entry points). The list of functions that can be directly
133  * called via squeue are listed before the usual function prototype.
134  *
135  * Referencing:
136  *
137  * TCP is MT-Hot and we use a reference based scheme to make sure that the
138  * tcp structure doesn't disappear when its needed. When the application
139  * creates an outgoing connection or accepts an incoming connection, we
140  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
141  * The IP reference is just a symbolic reference since ip_tcpclose()
142  * looks at tcp structure after tcp_close_output() returns which could
143  * have dropped the last TCP reference. So as long as the connection is
144  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
145  * conn_t. The classifier puts its own reference when the connection is
146  * inserted in listen or connected hash. Anytime a thread needs to enter
147  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
148  * on write side or by doing a classify on read side and then puts a
149  * reference on the conn before doing squeue_enter/tryenter/fill. For
150  * read side, the classifier itself puts the reference under fanout lock
151  * to make sure that tcp can't disappear before it gets processed. The
152  * squeue will drop this reference automatically so the called function
153  * doesn't have to do a DEC_REF.
154  *
155  * Opening a new connection:
156  *
157  * The outgoing connection open is pretty simple. tcp_open() does the
158  * work in creating the conn/tcp structure and initializing it. The
159  * squeue assignment is done based on the CPU the application
160  * is running on. So for outbound connections, processing is always done
161  * on application CPU which might be different from the incoming CPU
162  * being interrupted by the NIC. An optimal way would be to figure out
163  * the NIC <-> CPU binding at listen time, and assign the outgoing
164  * connection to the squeue attached to the CPU that will be interrupted
165  * for incoming packets (we know the NIC based on the bind IP address).
166  * This might seem like a problem if more data is going out but the
167  * fact is that in most cases the transmit is ACK driven transmit where
168  * the outgoing data normally sits on TCP's xmit queue waiting to be
169  * transmitted.
170  *
171  * Accepting a connection:
172  *
173  * This is a more interesting case because of various races involved in
174  * establishing a eager in its own perimeter. Read the meta comment on
175  * top of tcp_conn_request(). But briefly, the squeue is picked by
176  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
177  *
178  * Closing a connection:
179  *
180  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
181  * via squeue to do the close and mark the tcp as detached if the connection
182  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
183  * reference but tcp_close() drop IP's reference always. So if tcp was
184  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
185  * and 1 because it is in classifier's connected hash. This is the condition
186  * we use to determine that its OK to clean up the tcp outside of squeue
187  * when time wait expires (check the ref under fanout and conn_lock and
188  * if it is 2, remove it from fanout hash and kill it).
189  *
190  * Although close just drops the necessary references and marks the
191  * tcp_detached state, tcp_close needs to know the tcp_detached has been
192  * set (under squeue) before letting the STREAM go away (because a
193  * inbound packet might attempt to go up the STREAM while the close
194  * has happened and tcp_detached is not set). So a special lock and
195  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
196  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
197  * tcp_detached.
198  *
199  * Special provisions and fast paths:
200  *
201  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
202  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
203  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
204  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
205  * check to send packets directly to tcp_rput_data via squeue. Everyone
206  * else comes through tcp_input() on the read side.
207  *
208  * We also make special provisions for sockfs by marking tcp_issocket
209  * whenever we have only sockfs on top of TCP. This allows us to skip
210  * putting the tcp in acceptor hash since a sockfs listener can never
211  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
212  * since eager has already been allocated and the accept now happens
213  * on acceptor STREAM. There is a big blob of comment on top of
214  * tcp_conn_request explaining the new accept. When socket is POP'd,
215  * sockfs sends us an ioctl to mark the fact and we go back to old
216  * behaviour. Once tcp_issocket is unset, its never set for the
217  * life of that connection.
218  *
219  * In support of on-board asynchronous DMA hardware (e.g. Intel I/OAT)
220  * two consoldiation private KAPIs are used to enqueue M_DATA mblk_t's
221  * directly to the socket (sodirect) and start an asynchronous copyout
222  * to a user-land receive-side buffer (uioa) when a blocking socket read
223  * (e.g. read, recv, ...) is pending.
224  *
225  * This is accomplished when tcp_issocket is set and tcp_sodirect is not
226  * NULL so points to an sodirect_t and if marked enabled then we enqueue
227  * all mblk_t's directly to the socket.
228  *
229  * Further, if the sodirect_t sod_uioa and if marked enabled (due to a
230  * blocking socket read, e.g. user-land read, recv, ...) then an asynchronous
231  * copyout will be started directly to the user-land uio buffer. Also, as we
232  * have a pending read, TCP's push logic can take into account the number of
233  * bytes to be received and only awake the blocked read()er when the uioa_t
234  * byte count has been satisfied.
235  *
236  * IPsec notes :
237  *
238  * Since a packet is always executed on the correct TCP perimeter
239  * all IPsec processing is defered to IP including checking new
240  * connections and setting IPSEC policies for new connection. The
241  * only exception is tcp_xmit_listeners_reset() which is called
242  * directly from IP and needs to policy check to see if TH_RST
243  * can be sent out.
244  *
245  * PFHooks notes :
246  *
247  * For mdt case, one meta buffer contains multiple packets. Mblks for every
248  * packet are assembled and passed to the hooks. When packets are blocked,
249  * or boundary of any packet is changed, the mdt processing is stopped, and
250  * packets of the meta buffer are send to the IP path one by one.
251  */
252 
253 /*
254  * Values for squeue switch:
255  * 1: SQ_NODRAIN
256  * 2: SQ_PROCESS
257  * 3: SQ_FILL
258  */
259 int tcp_squeue_wput = 2;	/* /etc/systems */
260 int tcp_squeue_flag;
261 
262 /*
263  * Macros for sodirect:
264  *
265  * SOD_PTR_ENTER(tcp, sodp) - for the tcp_t pointer "tcp" set the
266  * sodirect_t pointer "sodp" to the socket/tcp shared sodirect_t
267  * if it exists and is enabled, else to NULL. Note, in the current
268  * sodirect implementation the sod_lockp must not be held across any
269  * STREAMS call (e.g. putnext) else a "recursive mutex_enter" PANIC
270  * will result as sod_lockp is the streamhead stdata.sd_lock.
271  *
272  * SOD_NOT_ENABLED(tcp) - return true if not a sodirect tcp_t or the
273  * sodirect_t isn't enabled, usefull for ASSERT()ing that a recieve
274  * side tcp code path dealing with a tcp_rcv_list or putnext() isn't
275  * being used when sodirect code paths should be.
276  */
277 
278 #define	SOD_PTR_ENTER(tcp, sodp)					\
279 	(sodp) = (tcp)->tcp_sodirect;					\
280 									\
281 	if ((sodp) != NULL) {						\
282 		mutex_enter((sodp)->sod_lockp);				\
283 		if (!((sodp)->sod_state & SOD_ENABLED)) {		\
284 			mutex_exit((sodp)->sod_lockp);			\
285 			(sodp) = NULL;					\
286 		}							\
287 	}
288 
289 #define	SOD_NOT_ENABLED(tcp)						\
290 	((tcp)->tcp_sodirect == NULL ||					\
291 	    !((tcp)->tcp_sodirect->sod_state & SOD_ENABLED))
292 
293 /*
294  * This controls how tiny a write must be before we try to copy it
295  * into the the mblk on the tail of the transmit queue.  Not much
296  * speedup is observed for values larger than sixteen.  Zero will
297  * disable the optimisation.
298  */
299 int tcp_tx_pull_len = 16;
300 
301 /*
302  * TCP Statistics.
303  *
304  * How TCP statistics work.
305  *
306  * There are two types of statistics invoked by two macros.
307  *
308  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
309  * supposed to be used in non MT-hot paths of the code.
310  *
311  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
312  * supposed to be used for DEBUG purposes and may be used on a hot path.
313  *
314  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
315  * (use "kstat tcp" to get them).
316  *
317  * There is also additional debugging facility that marks tcp_clean_death()
318  * instances and saves them in tcp_t structure. It is triggered by
319  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
320  * tcp_clean_death() calls that counts the number of times each tag was hit. It
321  * is triggered by TCP_CLD_COUNTERS define.
322  *
323  * How to add new counters.
324  *
325  * 1) Add a field in the tcp_stat structure describing your counter.
326  * 2) Add a line in the template in tcp_kstat2_init() with the name
327  *    of the counter.
328  *
329  *    IMPORTANT!! - make sure that both are in sync !!
330  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
331  *
332  * Please avoid using private counters which are not kstat-exported.
333  *
334  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
335  * in tcp_t structure.
336  *
337  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
338  */
339 
340 #ifndef TCP_DEBUG_COUNTER
341 #ifdef DEBUG
342 #define	TCP_DEBUG_COUNTER 1
343 #else
344 #define	TCP_DEBUG_COUNTER 0
345 #endif
346 #endif
347 
348 #define	TCP_CLD_COUNTERS 0
349 
350 #define	TCP_TAG_CLEAN_DEATH 1
351 #define	TCP_MAX_CLEAN_DEATH_TAG 32
352 
353 #ifdef lint
354 static int _lint_dummy_;
355 #endif
356 
357 #if TCP_CLD_COUNTERS
358 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
359 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
360 #elif defined(lint)
361 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
362 #else
363 #define	TCP_CLD_STAT(x)
364 #endif
365 
366 #if TCP_DEBUG_COUNTER
367 #define	TCP_DBGSTAT(tcps, x)	\
368 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
369 #define	TCP_G_DBGSTAT(x)	\
370 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
371 #elif defined(lint)
372 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
373 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
374 #else
375 #define	TCP_DBGSTAT(tcps, x)
376 #define	TCP_G_DBGSTAT(x)
377 #endif
378 
379 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
380 
381 tcp_g_stat_t	tcp_g_statistics;
382 kstat_t		*tcp_g_kstat;
383 
384 /*
385  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
386  * tcp write side.
387  */
388 #define	CALL_IP_WPUT(connp, q, mp) {					\
389 	ASSERT(((q)->q_flag & QREADR) == 0);				\
390 	TCP_DBGSTAT(connp->conn_netstack->netstack_tcp, tcp_ip_output);	\
391 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
392 }
393 
394 /* Macros for timestamp comparisons */
395 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
396 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
397 
398 /*
399  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
400  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
401  * by adding three components: a time component which grows by 1 every 4096
402  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
403  * a per-connection component which grows by 125000 for every new connection;
404  * and an "extra" component that grows by a random amount centered
405  * approximately on 64000.  This causes the the ISS generator to cycle every
406  * 4.89 hours if no TCP connections are made, and faster if connections are
407  * made.
408  *
409  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
410  * components: a time component which grows by 250000 every second; and
411  * a per-connection component which grows by 125000 for every new connections.
412  *
413  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
414  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
415  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
416  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
417  * password.
418  */
419 #define	ISS_INCR	250000
420 #define	ISS_NSEC_SHT	12
421 
422 static sin_t	sin_null;	/* Zero address for quick clears */
423 static sin6_t	sin6_null;	/* Zero address for quick clears */
424 
425 /*
426  * This implementation follows the 4.3BSD interpretation of the urgent
427  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
428  * incompatible changes in protocols like telnet and rlogin.
429  */
430 #define	TCP_OLD_URP_INTERPRETATION	1
431 
432 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
433 	(TCP_IS_DETACHED(tcp) && \
434 	    (!(tcp)->tcp_hard_binding))
435 
436 /*
437  * TCP reassembly macros.  We hide starting and ending sequence numbers in
438  * b_next and b_prev of messages on the reassembly queue.  The messages are
439  * chained using b_cont.  These macros are used in tcp_reass() so we don't
440  * have to see the ugly casts and assignments.
441  */
442 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
443 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
444 					(mblk_t *)(uintptr_t)(u))
445 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
446 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
447 					(mblk_t *)(uintptr_t)(u))
448 
449 /*
450  * Implementation of TCP Timers.
451  * =============================
452  *
453  * INTERFACE:
454  *
455  * There are two basic functions dealing with tcp timers:
456  *
457  *	timeout_id_t	tcp_timeout(connp, func, time)
458  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
459  *	TCP_TIMER_RESTART(tcp, intvl)
460  *
461  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
462  * after 'time' ticks passed. The function called by timeout() must adhere to
463  * the same restrictions as a driver soft interrupt handler - it must not sleep
464  * or call other functions that might sleep. The value returned is the opaque
465  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
466  * cancel the request. The call to tcp_timeout() may fail in which case it
467  * returns zero. This is different from the timeout(9F) function which never
468  * fails.
469  *
470  * The call-back function 'func' always receives 'connp' as its single
471  * argument. It is always executed in the squeue corresponding to the tcp
472  * structure. The tcp structure is guaranteed to be present at the time the
473  * call-back is called.
474  *
475  * NOTE: The call-back function 'func' is never called if tcp is in
476  * 	the TCPS_CLOSED state.
477  *
478  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
479  * request. locks acquired by the call-back routine should not be held across
480  * the call to tcp_timeout_cancel() or a deadlock may result.
481  *
482  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
483  * Otherwise, it returns an integer value greater than or equal to 0. In
484  * particular, if the call-back function is already placed on the squeue, it can
485  * not be canceled.
486  *
487  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
488  * 	within squeue context corresponding to the tcp instance. Since the
489  *	call-back is also called via the same squeue, there are no race
490  *	conditions described in untimeout(9F) manual page since all calls are
491  *	strictly serialized.
492  *
493  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
494  *	stored in tcp_timer_tid and starts a new one using
495  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
496  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
497  *	field.
498  *
499  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
500  *	call-back may still be called, so it is possible tcp_timer() will be
501  *	called several times. This should not be a problem since tcp_timer()
502  *	should always check the tcp instance state.
503  *
504  *
505  * IMPLEMENTATION:
506  *
507  * TCP timers are implemented using three-stage process. The call to
508  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
509  * when the timer expires. The tcp_timer_callback() arranges the call of the
510  * tcp_timer_handler() function via squeue corresponding to the tcp
511  * instance. The tcp_timer_handler() calls actual requested timeout call-back
512  * and passes tcp instance as an argument to it. Information is passed between
513  * stages using the tcp_timer_t structure which contains the connp pointer, the
514  * tcp call-back to call and the timeout id returned by the timeout(9F).
515  *
516  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
517  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
518  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
519  * returns the pointer to this mblk.
520  *
521  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
522  * looks like a normal mblk without actual dblk attached to it.
523  *
524  * To optimize performance each tcp instance holds a small cache of timer
525  * mblocks. In the current implementation it caches up to two timer mblocks per
526  * tcp instance. The cache is preserved over tcp frees and is only freed when
527  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
528  * timer processing happens on a corresponding squeue, the cache manipulation
529  * does not require any locks. Experiments show that majority of timer mblocks
530  * allocations are satisfied from the tcp cache and do not involve kmem calls.
531  *
532  * The tcp_timeout() places a refhold on the connp instance which guarantees
533  * that it will be present at the time the call-back function fires. The
534  * tcp_timer_handler() drops the reference after calling the call-back, so the
535  * call-back function does not need to manipulate the references explicitly.
536  */
537 
538 typedef struct tcp_timer_s {
539 	conn_t	*connp;
540 	void 	(*tcpt_proc)(void *);
541 	callout_id_t   tcpt_tid;
542 } tcp_timer_t;
543 
544 static kmem_cache_t *tcp_timercache;
545 kmem_cache_t	*tcp_sack_info_cache;
546 kmem_cache_t	*tcp_iphc_cache;
547 
548 /*
549  * For scalability, we must not run a timer for every TCP connection
550  * in TIME_WAIT state.  To see why, consider (for time wait interval of
551  * 4 minutes):
552  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
553  *
554  * This list is ordered by time, so you need only delete from the head
555  * until you get to entries which aren't old enough to delete yet.
556  * The list consists of only the detached TIME_WAIT connections.
557  *
558  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
559  * becomes detached TIME_WAIT (either by changing the state and already
560  * being detached or the other way around). This means that the TIME_WAIT
561  * state can be extended (up to doubled) if the connection doesn't become
562  * detached for a long time.
563  *
564  * The list manipulations (including tcp_time_wait_next/prev)
565  * are protected by the tcp_time_wait_lock. The content of the
566  * detached TIME_WAIT connections is protected by the normal perimeters.
567  *
568  * This list is per squeue and squeues are shared across the tcp_stack_t's.
569  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
570  * and conn_netstack.
571  * The tcp_t's that are added to tcp_free_list are disassociated and
572  * have NULL tcp_tcps and conn_netstack pointers.
573  */
574 typedef struct tcp_squeue_priv_s {
575 	kmutex_t	tcp_time_wait_lock;
576 	callout_id_t	tcp_time_wait_tid;
577 	tcp_t		*tcp_time_wait_head;
578 	tcp_t		*tcp_time_wait_tail;
579 	tcp_t		*tcp_free_list;
580 	uint_t		tcp_free_list_cnt;
581 } tcp_squeue_priv_t;
582 
583 /*
584  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
585  * Running it every 5 seconds seems to give the best results.
586  */
587 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
588 
589 /*
590  * To prevent memory hog, limit the number of entries in tcp_free_list
591  * to 1% of available memory / number of cpus
592  */
593 uint_t tcp_free_list_max_cnt = 0;
594 
595 #define	TCP_XMIT_LOWATER	4096
596 #define	TCP_XMIT_HIWATER	49152
597 #define	TCP_RECV_LOWATER	2048
598 #define	TCP_RECV_HIWATER	49152
599 
600 /*
601  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
602  */
603 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
604 
605 #define	TIDUSZ	4096	/* transport interface data unit size */
606 
607 /*
608  * Bind hash list size and has function.  It has to be a power of 2 for
609  * hashing.
610  */
611 #define	TCP_BIND_FANOUT_SIZE	512
612 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
613 /*
614  * Size of listen and acceptor hash list.  It has to be a power of 2 for
615  * hashing.
616  */
617 #define	TCP_FANOUT_SIZE		256
618 
619 #ifdef	_ILP32
620 #define	TCP_ACCEPTOR_HASH(accid)					\
621 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
622 #else
623 #define	TCP_ACCEPTOR_HASH(accid)					\
624 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
625 #endif	/* _ILP32 */
626 
627 #define	IP_ADDR_CACHE_SIZE	2048
628 #define	IP_ADDR_CACHE_HASH(faddr)					\
629 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
630 
631 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
632 #define	TCP_HSP_HASH_SIZE 256
633 
634 #define	TCP_HSP_HASH(addr)					\
635 	(((addr>>24) ^ (addr >>16) ^			\
636 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
637 
638 /*
639  * TCP options struct returned from tcp_parse_options.
640  */
641 typedef struct tcp_opt_s {
642 	uint32_t	tcp_opt_mss;
643 	uint32_t	tcp_opt_wscale;
644 	uint32_t	tcp_opt_ts_val;
645 	uint32_t	tcp_opt_ts_ecr;
646 	tcp_t		*tcp;
647 } tcp_opt_t;
648 
649 /*
650  * TCP option struct passing information b/w lisenter and eager.
651  */
652 struct tcp_options {
653 	uint_t			to_flags;
654 	ssize_t			to_boundif;	/* IPV6_BOUND_IF */
655 	sock_upper_handle_t	to_handle;
656 };
657 
658 #define	TCPOPT_BOUNDIF		0x00000001	/* set IPV6_BOUND_IF */
659 #define	TCPOPT_RECVPKTINFO	0x00000002	/* set IPV6_RECVPKTINFO */
660 #define	TCPOPT_UPPERHANDLE	0x00000004	/* set upper handle */
661 
662 /*
663  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
664  */
665 
666 #ifdef _BIG_ENDIAN
667 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
668 	(TCPOPT_TSTAMP << 8) | 10)
669 #else
670 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
671 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
672 #endif
673 
674 /*
675  * Flags returned from tcp_parse_options.
676  */
677 #define	TCP_OPT_MSS_PRESENT	1
678 #define	TCP_OPT_WSCALE_PRESENT	2
679 #define	TCP_OPT_TSTAMP_PRESENT	4
680 #define	TCP_OPT_SACK_OK_PRESENT	8
681 #define	TCP_OPT_SACK_PRESENT	16
682 
683 /* TCP option length */
684 #define	TCPOPT_NOP_LEN		1
685 #define	TCPOPT_MAXSEG_LEN	4
686 #define	TCPOPT_WS_LEN		3
687 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
688 #define	TCPOPT_TSTAMP_LEN	10
689 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
690 #define	TCPOPT_SACK_OK_LEN	2
691 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
692 #define	TCPOPT_REAL_SACK_LEN	4
693 #define	TCPOPT_MAX_SACK_LEN	36
694 #define	TCPOPT_HEADER_LEN	2
695 
696 /* TCP cwnd burst factor. */
697 #define	TCP_CWND_INFINITE	65535
698 #define	TCP_CWND_SS		3
699 #define	TCP_CWND_NORMAL		5
700 
701 /* Maximum TCP initial cwin (start/restart). */
702 #define	TCP_MAX_INIT_CWND	8
703 
704 /*
705  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
706  * either tcp_slow_start_initial or tcp_slow_start_after idle
707  * depending on the caller.  If the upper layer has not used the
708  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
709  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
710  * If the upper layer has changed set the tcp_init_cwnd, just use
711  * it to calculate the tcp_cwnd.
712  */
713 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
714 {									\
715 	if ((tcp)->tcp_init_cwnd == 0) {				\
716 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
717 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
718 	} else {							\
719 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
720 	}								\
721 	tcp->tcp_cwnd_cnt = 0;						\
722 }
723 
724 /* TCP Timer control structure */
725 typedef struct tcpt_s {
726 	pfv_t	tcpt_pfv;	/* The routine we are to call */
727 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
728 } tcpt_t;
729 
730 /* Host Specific Parameter structure */
731 typedef struct tcp_hsp {
732 	struct tcp_hsp	*tcp_hsp_next;
733 	in6_addr_t	tcp_hsp_addr_v6;
734 	in6_addr_t	tcp_hsp_subnet_v6;
735 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
736 	int32_t		tcp_hsp_sendspace;
737 	int32_t		tcp_hsp_recvspace;
738 	int32_t		tcp_hsp_tstamp;
739 } tcp_hsp_t;
740 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
741 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
742 
743 /*
744  * Functions called directly via squeue having a prototype of edesc_t.
745  */
746 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
747 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
748 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
749 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
750 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
751 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
752 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
753 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
754 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
755 void		tcp_output_urgent(void *arg, mblk_t *mp, void *arg2);
756 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
757 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
758 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
759 
760 
761 /* Prototype for TCP functions */
762 static void	tcp_random_init(void);
763 int		tcp_random(void);
764 static void	tcp_tli_accept(tcp_t *tcp, mblk_t *mp);
765 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
766 		    tcp_t *eager);
767 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
768 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
769     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
770     boolean_t user_specified);
771 static void	tcp_closei_local(tcp_t *tcp);
772 static void	tcp_close_detached(tcp_t *tcp);
773 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
774 			mblk_t *idmp, mblk_t **defermp);
775 static void	tcp_tpi_connect(tcp_t *tcp, mblk_t *mp);
776 static int	tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
777 		    in_port_t dstport, uint_t srcid, cred_t *cr, pid_t pid);
778 static int 	tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
779 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
780 		    uint32_t scope_id, cred_t *cr, pid_t pid);
781 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
782 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
783 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
784 static char	*tcp_display(tcp_t *tcp, char *, char);
785 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
786 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
787 static void	tcp_eager_unlink(tcp_t *tcp);
788 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
789 		    int unixerr);
790 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
791 		    int tlierr, int unixerr);
792 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
793 		    cred_t *cr);
794 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
795 		    char *value, caddr_t cp, cred_t *cr);
796 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
797 		    char *value, caddr_t cp, cred_t *cr);
798 static int	tcp_tpistate(tcp_t *tcp);
799 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
800     int caller_holds_lock);
801 static void	tcp_bind_hash_remove(tcp_t *tcp);
802 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
803 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
804 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
805 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
806 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
807 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
808 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
809 void		tcp_g_q_setup(tcp_stack_t *);
810 void		tcp_g_q_create(tcp_stack_t *);
811 void		tcp_g_q_destroy(tcp_stack_t *);
812 static int	tcp_header_init_ipv4(tcp_t *tcp);
813 static int	tcp_header_init_ipv6(tcp_t *tcp);
814 int		tcp_init(tcp_t *tcp, queue_t *q);
815 static int	tcp_init_values(tcp_t *tcp);
816 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
817 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
818 static void	tcp_ip_notify(tcp_t *tcp);
819 static mblk_t	*tcp_ire_mp(mblk_t **mpp);
820 static void	tcp_iss_init(tcp_t *tcp);
821 static void	tcp_keepalive_killer(void *arg);
822 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
823 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
824 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
825 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
826 static boolean_t tcp_allow_connopt_set(int level, int name);
827 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
828 int		tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
829 int		tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level,
830 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
831 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
832 		    mblk_t *mblk);
833 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
834 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
835 		    uchar_t *ptr, uint_t len);
836 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
837 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
838     tcp_stack_t *);
839 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
840 		    caddr_t cp, cred_t *cr);
841 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
842 		    caddr_t cp, cred_t *cr);
843 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
844 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
845 		    caddr_t cp, cred_t *cr);
846 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
847 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
848 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
849 static void	tcp_reinit(tcp_t *tcp);
850 static void	tcp_reinit_values(tcp_t *tcp);
851 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
852 		    tcp_t *thisstream, cred_t *cr);
853 
854 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
855 static uint_t	tcp_rcv_drain(tcp_t *tcp);
856 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
857 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
858 static void	tcp_ss_rexmit(tcp_t *tcp);
859 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
860 static void	tcp_process_options(tcp_t *, tcph_t *);
861 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
862 static void	tcp_rsrv(queue_t *q);
863 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
864 static int	tcp_snmp_state(tcp_t *tcp);
865 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
866 		    cred_t *cr);
867 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
868 		    cred_t *cr);
869 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
870 		    cred_t *cr);
871 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
872 		    cred_t *cr);
873 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
874 		    cred_t *cr);
875 static void	tcp_timer(void *arg);
876 static void	tcp_timer_callback(void *);
877 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
878     boolean_t random);
879 static in_port_t tcp_get_next_priv_port(const tcp_t *);
880 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
881 static void	tcp_wput_fallback(queue_t *q, mblk_t *mp);
882 void		tcp_tpi_accept(queue_t *q, mblk_t *mp);
883 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
884 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
885 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
886 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
887 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
888 		    const int num_sack_blk, int *usable, uint_t *snxt,
889 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
890 		    const int mdt_thres);
891 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
892 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
893 		    const int num_sack_blk, int *usable, uint_t *snxt,
894 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
895 		    const int mdt_thres);
896 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
897 		    int num_sack_blk);
898 static void	tcp_wsrv(queue_t *q);
899 static int	tcp_xmit_end(tcp_t *tcp);
900 static void	tcp_ack_timer(void *arg);
901 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
902 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
903 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
904 		    zoneid_t zoneid, tcp_stack_t *, conn_t *connp);
905 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
906 		    uint32_t ack, int ctl);
907 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *);
908 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr, tcp_stack_t *);
909 static int	setmaxps(queue_t *q, int maxpsz);
910 static void	tcp_set_rto(tcp_t *, time_t);
911 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
912 		    boolean_t, boolean_t);
913 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
914 		    boolean_t ipsec_mctl);
915 static int	tcp_build_hdrs(tcp_t *);
916 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
917 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
918 		    tcph_t *tcph);
919 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
920 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
921 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
922 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
923 		    const boolean_t, const uint32_t, const uint32_t,
924 		    const uint32_t, const uint32_t, tcp_stack_t *);
925 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
926 		    const uint_t, const uint_t, boolean_t *);
927 static mblk_t	*tcp_lso_info_mp(mblk_t *);
928 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
929 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
930 extern mblk_t	*tcp_timermp_alloc(int);
931 extern void	tcp_timermp_free(tcp_t *);
932 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
933 static void	tcp_stop_lingering(tcp_t *tcp);
934 static void	tcp_close_linger_timeout(void *arg);
935 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
936 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
937 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
938 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
939 static void	tcp_g_kstat_fini(kstat_t *);
940 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
941 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
942 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
943 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
944 static int	tcp_kstat_update(kstat_t *kp, int rw);
945 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
946 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
947 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
948 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
949 			tcph_t *tcph, mblk_t *idmp);
950 static int	tcp_squeue_switch(int);
951 
952 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
953 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
954 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
955 static int	tcp_tpi_close(queue_t *, int);
956 static int	tcpclose_accept(queue_t *);
957 
958 static void	tcp_squeue_add(squeue_t *);
959 static boolean_t tcp_zcopy_check(tcp_t *);
960 static void	tcp_zcopy_notify(tcp_t *);
961 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
962 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
963 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
964 
965 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
966 
967 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
968 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
969 
970 static int tcp_accept(sock_lower_handle_t, sock_lower_handle_t,
971 	    sock_upper_handle_t, cred_t *);
972 static int tcp_listen(sock_lower_handle_t, int, cred_t *);
973 static int tcp_post_ip_bind(tcp_t *, mblk_t *, int, cred_t *, pid_t);
974 static int tcp_do_listen(conn_t *, int, cred_t *);
975 static int tcp_do_connect(conn_t *, const struct sockaddr *, socklen_t,
976     cred_t *, pid_t);
977 static int tcp_do_bind(conn_t *, struct sockaddr *, socklen_t, cred_t *,
978     boolean_t);
979 static int tcp_do_unbind(conn_t *);
980 static int tcp_bind_check(conn_t *, struct sockaddr *, socklen_t, cred_t *,
981     boolean_t);
982 
983 /*
984  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
985  *
986  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
987  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
988  * (defined in tcp.h) needs to be filled in and passed into the kernel
989  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
990  * structure contains the four-tuple of a TCP connection and a range of TCP
991  * states (specified by ac_start and ac_end). The use of wildcard addresses
992  * and ports is allowed. Connections with a matching four tuple and a state
993  * within the specified range will be aborted. The valid states for the
994  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
995  * inclusive.
996  *
997  * An application which has its connection aborted by this ioctl will receive
998  * an error that is dependent on the connection state at the time of the abort.
999  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
1000  * though a RST packet has been received.  If the connection state is equal to
1001  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
1002  * and all resources associated with the connection will be freed.
1003  */
1004 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
1005 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
1006 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
1007 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
1008 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
1009 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
1010     boolean_t, tcp_stack_t *);
1011 
1012 static struct module_info tcp_rinfo =  {
1013 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
1014 };
1015 
1016 static struct module_info tcp_winfo =  {
1017 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
1018 };
1019 
1020 /*
1021  * Entry points for TCP as a device. The normal case which supports
1022  * the TCP functionality.
1023  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
1024  */
1025 struct qinit tcp_rinitv4 = {
1026 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, NULL, &tcp_rinfo
1027 };
1028 
1029 struct qinit tcp_rinitv6 = {
1030 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_tpi_close, NULL, &tcp_rinfo
1031 };
1032 
1033 struct qinit tcp_winit = {
1034 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1035 };
1036 
1037 /* Initial entry point for TCP in socket mode. */
1038 struct qinit tcp_sock_winit = {
1039 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1040 };
1041 
1042 /* TCP entry point during fallback */
1043 struct qinit tcp_fallback_sock_winit = {
1044 	(pfi_t)tcp_wput_fallback, NULL, NULL, NULL, NULL, &tcp_winfo
1045 };
1046 
1047 /*
1048  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1049  * an accept. Avoid allocating data structures since eager has already
1050  * been created.
1051  */
1052 struct qinit tcp_acceptor_rinit = {
1053 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1054 };
1055 
1056 struct qinit tcp_acceptor_winit = {
1057 	(pfi_t)tcp_tpi_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1058 };
1059 
1060 /*
1061  * Entry points for TCP loopback (read side only)
1062  * The open routine is only used for reopens, thus no need to
1063  * have a separate one for tcp_openv6.
1064  */
1065 struct qinit tcp_loopback_rinit = {
1066 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, (pfi_t)0,
1067 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1068 };
1069 
1070 /* For AF_INET aka /dev/tcp */
1071 struct streamtab tcpinfov4 = {
1072 	&tcp_rinitv4, &tcp_winit
1073 };
1074 
1075 /* For AF_INET6 aka /dev/tcp6 */
1076 struct streamtab tcpinfov6 = {
1077 	&tcp_rinitv6, &tcp_winit
1078 };
1079 
1080 sock_downcalls_t sock_tcp_downcalls;
1081 
1082 /*
1083  * Have to ensure that tcp_g_q_close is not done by an
1084  * interrupt thread.
1085  */
1086 static taskq_t *tcp_taskq;
1087 
1088 /* Setable only in /etc/system. Move to ndd? */
1089 boolean_t tcp_icmp_source_quench = B_FALSE;
1090 
1091 /*
1092  * Following assumes TPI alignment requirements stay along 32 bit
1093  * boundaries
1094  */
1095 #define	ROUNDUP32(x) \
1096 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1097 
1098 /* Template for response to info request. */
1099 static struct T_info_ack tcp_g_t_info_ack = {
1100 	T_INFO_ACK,		/* PRIM_type */
1101 	0,			/* TSDU_size */
1102 	T_INFINITE,		/* ETSDU_size */
1103 	T_INVALID,		/* CDATA_size */
1104 	T_INVALID,		/* DDATA_size */
1105 	sizeof (sin_t),		/* ADDR_size */
1106 	0,			/* OPT_size - not initialized here */
1107 	TIDUSZ,			/* TIDU_size */
1108 	T_COTS_ORD,		/* SERV_type */
1109 	TCPS_IDLE,		/* CURRENT_state */
1110 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1111 };
1112 
1113 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1114 	T_INFO_ACK,		/* PRIM_type */
1115 	0,			/* TSDU_size */
1116 	T_INFINITE,		/* ETSDU_size */
1117 	T_INVALID,		/* CDATA_size */
1118 	T_INVALID,		/* DDATA_size */
1119 	sizeof (sin6_t),	/* ADDR_size */
1120 	0,			/* OPT_size - not initialized here */
1121 	TIDUSZ,		/* TIDU_size */
1122 	T_COTS_ORD,		/* SERV_type */
1123 	TCPS_IDLE,		/* CURRENT_state */
1124 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1125 };
1126 
1127 #define	MS	1L
1128 #define	SECONDS	(1000 * MS)
1129 #define	MINUTES	(60 * SECONDS)
1130 #define	HOURS	(60 * MINUTES)
1131 #define	DAYS	(24 * HOURS)
1132 
1133 #define	PARAM_MAX (~(uint32_t)0)
1134 
1135 /* Max size IP datagram is 64k - 1 */
1136 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1137 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1138 /* Max of the above */
1139 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1140 
1141 /* Largest TCP port number */
1142 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1143 
1144 /*
1145  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1146  * layer header.  It has to be a multiple of 4.
1147  */
1148 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1149 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1150 
1151 /*
1152  * All of these are alterable, within the min/max values given, at run time.
1153  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1154  * per the TCP spec.
1155  */
1156 /* BEGIN CSTYLED */
1157 static tcpparam_t	lcl_tcp_param_arr[] = {
1158  /*min		max		value		name */
1159  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1160  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1161  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1162  { 1,		1024,		1,		"tcp_conn_req_min" },
1163  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1164  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1165  { 0,		10,		0,		"tcp_debug" },
1166  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1167  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1168  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1169  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1170  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1171  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1172  { 1,		255,		64,		"tcp_ipv4_ttl"},
1173  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1174  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1175  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1176  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1177  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1178  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1179  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1180  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1181  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1182  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1183  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1184  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1185  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1186  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1187  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1188  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1189  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1190  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1191  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1192  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1193  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1194  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1195  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1196 /*
1197  * Question:  What default value should I set for tcp_strong_iss?
1198  */
1199  { 0,		2,		1,		"tcp_strong_iss"},
1200  { 0,		65536,		20,		"tcp_rtt_updates"},
1201  { 0,		1,		1,		"tcp_wscale_always"},
1202  { 0,		1,		0,		"tcp_tstamp_always"},
1203  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1204  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1205  { 0,		16,		2,		"tcp_deferred_acks_max"},
1206  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1207  { 1,		4,		4,		"tcp_slow_start_initial"},
1208  { 0,		2,		2,		"tcp_sack_permitted"},
1209  { 0,		1,		1,		"tcp_compression_enabled"},
1210  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1211  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1212  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1213  { 0,		1,		0,		"tcp_rev_src_routes"},
1214  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1215  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1216  { 0,		16,		8,		"tcp_local_dacks_max"},
1217  { 0,		2,		1,		"tcp_ecn_permitted"},
1218  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1219  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1220  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1221  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1222  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1223 };
1224 /* END CSTYLED */
1225 
1226 /*
1227  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1228  * each header fragment in the header buffer.  Each parameter value has
1229  * to be a multiple of 4 (32-bit aligned).
1230  */
1231 static tcpparam_t lcl_tcp_mdt_head_param =
1232 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1233 static tcpparam_t lcl_tcp_mdt_tail_param =
1234 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1235 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1236 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1237 
1238 /*
1239  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1240  * the maximum number of payload buffers associated per Multidata.
1241  */
1242 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1243 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1244 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1245 
1246 /* Round up the value to the nearest mss. */
1247 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1248 
1249 /*
1250  * Set ECN capable transport (ECT) code point in IP header.
1251  *
1252  * Note that there are 2 ECT code points '01' and '10', which are called
1253  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1254  * point ECT(0) for TCP as described in RFC 2481.
1255  */
1256 #define	SET_ECT(tcp, iph) \
1257 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1258 		/* We need to clear the code point first. */ \
1259 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1260 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1261 	} else { \
1262 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1263 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1264 	}
1265 
1266 /*
1267  * The format argument to pass to tcp_display().
1268  * DISP_PORT_ONLY means that the returned string has only port info.
1269  * DISP_ADDR_AND_PORT means that the returned string also contains the
1270  * remote and local IP address.
1271  */
1272 #define	DISP_PORT_ONLY		1
1273 #define	DISP_ADDR_AND_PORT	2
1274 
1275 #define	NDD_TOO_QUICK_MSG \
1276 	"ndd get info rate too high for non-privileged users, try again " \
1277 	"later.\n"
1278 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1279 
1280 #define	IS_VMLOANED_MBLK(mp) \
1281 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1282 
1283 
1284 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1285 boolean_t tcp_mdt_chain = B_TRUE;
1286 
1287 /*
1288  * MDT threshold in the form of effective send MSS multiplier; we take
1289  * the MDT path if the amount of unsent data exceeds the threshold value
1290  * (default threshold is 1*SMSS).
1291  */
1292 uint_t tcp_mdt_smss_threshold = 1;
1293 
1294 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1295 
1296 /*
1297  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1298  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1299  * determined dynamically during tcp_adapt_ire(), which is the default.
1300  */
1301 boolean_t tcp_static_maxpsz = B_FALSE;
1302 
1303 /* Setable in /etc/system */
1304 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1305 uint32_t tcp_random_anon_port = 1;
1306 
1307 /*
1308  * To reach to an eager in Q0 which can be dropped due to an incoming
1309  * new SYN request when Q0 is full, a new doubly linked list is
1310  * introduced. This list allows to select an eager from Q0 in O(1) time.
1311  * This is needed to avoid spending too much time walking through the
1312  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1313  * this new list has to be a member of Q0.
1314  * This list is headed by listener's tcp_t. When the list is empty,
1315  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1316  * of listener's tcp_t point to listener's tcp_t itself.
1317  *
1318  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1319  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1320  * These macros do not affect the eager's membership to Q0.
1321  */
1322 
1323 
1324 #define	MAKE_DROPPABLE(listener, eager)					\
1325 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1326 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1327 		    = (eager);						\
1328 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1329 		(eager)->tcp_eager_next_drop_q0 =			\
1330 		    (listener)->tcp_eager_next_drop_q0;			\
1331 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1332 	}
1333 
1334 #define	MAKE_UNDROPPABLE(eager)						\
1335 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1336 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1337 		    = (eager)->tcp_eager_prev_drop_q0;			\
1338 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1339 		    = (eager)->tcp_eager_next_drop_q0;			\
1340 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1341 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1342 	}
1343 
1344 /*
1345  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1346  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1347  * data, TCP will not respond with an ACK.  RFC 793 requires that
1348  * TCP responds with an ACK for such a bogus ACK.  By not following
1349  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1350  * an attacker successfully spoofs an acceptable segment to our
1351  * peer; or when our peer is "confused."
1352  */
1353 uint32_t tcp_drop_ack_unsent_cnt = 10;
1354 
1355 /*
1356  * Hook functions to enable cluster networking
1357  * On non-clustered systems these vectors must always be NULL.
1358  */
1359 
1360 void (*cl_inet_listen)(netstackid_t stack_id, uint8_t protocol,
1361 			    sa_family_t addr_family, uint8_t *laddrp,
1362 			    in_port_t lport, void *args) = NULL;
1363 void (*cl_inet_unlisten)(netstackid_t stack_id, uint8_t protocol,
1364 			    sa_family_t addr_family, uint8_t *laddrp,
1365 			    in_port_t lport, void *args) = NULL;
1366 
1367 int (*cl_inet_connect2)(netstackid_t stack_id, uint8_t protocol,
1368 			    boolean_t is_outgoing,
1369 			    sa_family_t addr_family,
1370 			    uint8_t *laddrp, in_port_t lport,
1371 			    uint8_t *faddrp, in_port_t fport,
1372 			    void *args) = NULL;
1373 
1374 void (*cl_inet_disconnect)(netstackid_t stack_id, uint8_t protocol,
1375 			    sa_family_t addr_family, uint8_t *laddrp,
1376 			    in_port_t lport, uint8_t *faddrp,
1377 			    in_port_t fport, void *args) = NULL;
1378 
1379 /*
1380  * The following are defined in ip.c
1381  */
1382 extern int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
1383 			    sa_family_t addr_family, uint8_t *laddrp,
1384 			    void *args);
1385 extern uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
1386 			    sa_family_t addr_family, uint8_t *laddrp,
1387 			    uint8_t *faddrp, void *args);
1388 
1389 
1390 /*
1391  * int CL_INET_CONNECT(conn_t *cp, tcp_t *tcp, boolean_t is_outgoing, int err)
1392  */
1393 #define	CL_INET_CONNECT(connp, tcp, is_outgoing, err) {		\
1394 	(err) = 0;						\
1395 	if (cl_inet_connect2 != NULL) {				\
1396 		/*						\
1397 		 * Running in cluster mode - register active connection	\
1398 		 * information						\
1399 		 */							\
1400 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1401 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1402 				(err) = (*cl_inet_connect2)(		\
1403 				    (connp)->conn_netstack->netstack_stackid,\
1404 				    IPPROTO_TCP, is_outgoing, AF_INET,	\
1405 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1406 				    (in_port_t)(tcp)->tcp_lport,	\
1407 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1408 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1409 			}						\
1410 		} else {						\
1411 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1412 			    &(tcp)->tcp_ip6h->ip6_src)) {		\
1413 				(err) = (*cl_inet_connect2)(		\
1414 				    (connp)->conn_netstack->netstack_stackid,\
1415 				    IPPROTO_TCP, is_outgoing, AF_INET6,	\
1416 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1417 				    (in_port_t)(tcp)->tcp_lport,	\
1418 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1419 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1420 			}						\
1421 		}							\
1422 	}								\
1423 }
1424 
1425 #define	CL_INET_DISCONNECT(connp, tcp)	{				\
1426 	if (cl_inet_disconnect != NULL) {				\
1427 		/*							\
1428 		 * Running in cluster mode - deregister active		\
1429 		 * connection information				\
1430 		 */							\
1431 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1432 			if ((tcp)->tcp_ip_src != 0) {			\
1433 				(*cl_inet_disconnect)(			\
1434 				    (connp)->conn_netstack->netstack_stackid,\
1435 				    IPPROTO_TCP, AF_INET,		\
1436 				    (uint8_t *)(&((tcp)->tcp_ip_src)),	\
1437 				    (in_port_t)(tcp)->tcp_lport,	\
1438 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1439 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1440 			}						\
1441 		} else {						\
1442 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1443 			    &(tcp)->tcp_ip_src_v6)) {			\
1444 				(*cl_inet_disconnect)(			\
1445 				    (connp)->conn_netstack->netstack_stackid,\
1446 				    IPPROTO_TCP, AF_INET6,		\
1447 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1448 				    (in_port_t)(tcp)->tcp_lport,	\
1449 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1450 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1451 			}						\
1452 		}							\
1453 	}								\
1454 }
1455 
1456 /*
1457  * Cluster networking hook for traversing current connection list.
1458  * This routine is used to extract the current list of live connections
1459  * which must continue to to be dispatched to this node.
1460  */
1461 int cl_tcp_walk_list(netstackid_t stack_id,
1462     int (*callback)(cl_tcp_info_t *, void *), void *arg);
1463 
1464 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1465     void *arg, tcp_stack_t *tcps);
1466 
1467 #define	DTRACE_IP_FASTPATH(mp, iph, ill, ipha, ip6h) 			\
1468 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,	\
1469 	    iph, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha,		\
1470 	    ip6_t *, ip6h, int, 0);
1471 
1472 /*
1473  * Figure out the value of window scale opton.  Note that the rwnd is
1474  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1475  * We cannot find the scale value and then do a round up of tcp_rwnd
1476  * because the scale value may not be correct after that.
1477  *
1478  * Set the compiler flag to make this function inline.
1479  */
1480 static void
1481 tcp_set_ws_value(tcp_t *tcp)
1482 {
1483 	int i;
1484 	uint32_t rwnd = tcp->tcp_rwnd;
1485 
1486 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1487 	    i++, rwnd >>= 1)
1488 		;
1489 	tcp->tcp_rcv_ws = i;
1490 }
1491 
1492 /*
1493  * Remove a connection from the list of detached TIME_WAIT connections.
1494  * It returns B_FALSE if it can't remove the connection from the list
1495  * as the connection has already been removed from the list due to an
1496  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1497  */
1498 static boolean_t
1499 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1500 {
1501 	boolean_t	locked = B_FALSE;
1502 
1503 	if (tcp_time_wait == NULL) {
1504 		tcp_time_wait = *((tcp_squeue_priv_t **)
1505 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1506 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1507 		locked = B_TRUE;
1508 	} else {
1509 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1510 	}
1511 
1512 	if (tcp->tcp_time_wait_expire == 0) {
1513 		ASSERT(tcp->tcp_time_wait_next == NULL);
1514 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1515 		if (locked)
1516 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1517 		return (B_FALSE);
1518 	}
1519 	ASSERT(TCP_IS_DETACHED(tcp));
1520 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1521 
1522 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1523 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1524 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1525 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1526 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1527 			    NULL;
1528 		} else {
1529 			tcp_time_wait->tcp_time_wait_tail = NULL;
1530 		}
1531 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1532 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1533 		ASSERT(tcp->tcp_time_wait_next == NULL);
1534 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1535 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1536 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1537 	} else {
1538 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1539 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1540 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1541 		    tcp->tcp_time_wait_next;
1542 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1543 		    tcp->tcp_time_wait_prev;
1544 	}
1545 	tcp->tcp_time_wait_next = NULL;
1546 	tcp->tcp_time_wait_prev = NULL;
1547 	tcp->tcp_time_wait_expire = 0;
1548 
1549 	if (locked)
1550 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1551 	return (B_TRUE);
1552 }
1553 
1554 /*
1555  * Add a connection to the list of detached TIME_WAIT connections
1556  * and set its time to expire.
1557  */
1558 static void
1559 tcp_time_wait_append(tcp_t *tcp)
1560 {
1561 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1562 	tcp_squeue_priv_t *tcp_time_wait =
1563 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1564 	    SQPRIVATE_TCP));
1565 
1566 	tcp_timers_stop(tcp);
1567 
1568 	/* Freed above */
1569 	ASSERT(tcp->tcp_timer_tid == 0);
1570 	ASSERT(tcp->tcp_ack_tid == 0);
1571 
1572 	/* must have happened at the time of detaching the tcp */
1573 	ASSERT(tcp->tcp_ptpahn == NULL);
1574 	ASSERT(tcp->tcp_flow_stopped == 0);
1575 	ASSERT(tcp->tcp_time_wait_next == NULL);
1576 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1577 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1578 	ASSERT(tcp->tcp_listener == NULL);
1579 
1580 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1581 	/*
1582 	 * The value computed below in tcp->tcp_time_wait_expire may
1583 	 * appear negative or wrap around. That is ok since our
1584 	 * interest is only in the difference between the current lbolt
1585 	 * value and tcp->tcp_time_wait_expire. But the value should not
1586 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1587 	 * The corresponding comparison in tcp_time_wait_collector() uses
1588 	 * modular arithmetic.
1589 	 */
1590 	tcp->tcp_time_wait_expire +=
1591 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1592 	if (tcp->tcp_time_wait_expire == 0)
1593 		tcp->tcp_time_wait_expire = 1;
1594 
1595 	ASSERT(TCP_IS_DETACHED(tcp));
1596 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1597 	ASSERT(tcp->tcp_time_wait_next == NULL);
1598 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1599 	TCP_DBGSTAT(tcps, tcp_time_wait);
1600 
1601 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1602 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1603 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1604 		tcp_time_wait->tcp_time_wait_head = tcp;
1605 	} else {
1606 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1607 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1608 		    TCPS_TIME_WAIT);
1609 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1610 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1611 	}
1612 	tcp_time_wait->tcp_time_wait_tail = tcp;
1613 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1614 }
1615 
1616 /* ARGSUSED */
1617 void
1618 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1619 {
1620 	conn_t	*connp = (conn_t *)arg;
1621 	tcp_t	*tcp = connp->conn_tcp;
1622 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1623 
1624 	ASSERT(tcp != NULL);
1625 	if (tcp->tcp_state == TCPS_CLOSED) {
1626 		return;
1627 	}
1628 
1629 	ASSERT((tcp->tcp_family == AF_INET &&
1630 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1631 	    (tcp->tcp_family == AF_INET6 &&
1632 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1633 	    tcp->tcp_ipversion == IPV6_VERSION)));
1634 	ASSERT(!tcp->tcp_listener);
1635 
1636 	TCP_STAT(tcps, tcp_time_wait_reap);
1637 	ASSERT(TCP_IS_DETACHED(tcp));
1638 
1639 	/*
1640 	 * Because they have no upstream client to rebind or tcp_close()
1641 	 * them later, we axe the connection here and now.
1642 	 */
1643 	tcp_close_detached(tcp);
1644 }
1645 
1646 /*
1647  * Remove cached/latched IPsec references.
1648  */
1649 void
1650 tcp_ipsec_cleanup(tcp_t *tcp)
1651 {
1652 	conn_t		*connp = tcp->tcp_connp;
1653 
1654 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1655 
1656 	if (connp->conn_latch != NULL) {
1657 		IPLATCH_REFRELE(connp->conn_latch,
1658 		    connp->conn_netstack);
1659 		connp->conn_latch = NULL;
1660 	}
1661 	if (connp->conn_policy != NULL) {
1662 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1663 		connp->conn_policy = NULL;
1664 	}
1665 }
1666 
1667 /*
1668  * Cleaup before placing on free list.
1669  * Disassociate from the netstack/tcp_stack_t since the freelist
1670  * is per squeue and not per netstack.
1671  */
1672 void
1673 tcp_cleanup(tcp_t *tcp)
1674 {
1675 	mblk_t		*mp;
1676 	char		*tcp_iphc;
1677 	int		tcp_iphc_len;
1678 	int		tcp_hdr_grown;
1679 	tcp_sack_info_t	*tcp_sack_info;
1680 	conn_t		*connp = tcp->tcp_connp;
1681 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1682 	netstack_t	*ns = tcps->tcps_netstack;
1683 	mblk_t		*tcp_rsrv_mp;
1684 
1685 	tcp_bind_hash_remove(tcp);
1686 
1687 	/* Cleanup that which needs the netstack first */
1688 	tcp_ipsec_cleanup(tcp);
1689 
1690 	tcp_free(tcp);
1691 
1692 	/* Release any SSL context */
1693 	if (tcp->tcp_kssl_ent != NULL) {
1694 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1695 		tcp->tcp_kssl_ent = NULL;
1696 	}
1697 
1698 	if (tcp->tcp_kssl_ctx != NULL) {
1699 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1700 		tcp->tcp_kssl_ctx = NULL;
1701 	}
1702 	tcp->tcp_kssl_pending = B_FALSE;
1703 
1704 	conn_delete_ire(connp, NULL);
1705 
1706 	/*
1707 	 * Since we will bzero the entire structure, we need to
1708 	 * remove it and reinsert it in global hash list. We
1709 	 * know the walkers can't get to this conn because we
1710 	 * had set CONDEMNED flag earlier and checked reference
1711 	 * under conn_lock so walker won't pick it and when we
1712 	 * go the ipcl_globalhash_remove() below, no walker
1713 	 * can get to it.
1714 	 */
1715 	ipcl_globalhash_remove(connp);
1716 
1717 	/*
1718 	 * Now it is safe to decrement the reference counts.
1719 	 * This might be the last reference on the netstack and TCPS
1720 	 * in which case it will cause the tcp_g_q_close and
1721 	 * the freeing of the IP Instance.
1722 	 */
1723 	connp->conn_netstack = NULL;
1724 	netstack_rele(ns);
1725 	ASSERT(tcps != NULL);
1726 	tcp->tcp_tcps = NULL;
1727 	TCPS_REFRELE(tcps);
1728 
1729 	/* Save some state */
1730 	mp = tcp->tcp_timercache;
1731 
1732 	tcp_sack_info = tcp->tcp_sack_info;
1733 	tcp_iphc = tcp->tcp_iphc;
1734 	tcp_iphc_len = tcp->tcp_iphc_len;
1735 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1736 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1737 
1738 	if (connp->conn_cred != NULL) {
1739 		crfree(connp->conn_cred);
1740 		connp->conn_cred = NULL;
1741 	}
1742 	if (connp->conn_peercred != NULL) {
1743 		crfree(connp->conn_peercred);
1744 		connp->conn_peercred = NULL;
1745 	}
1746 	ipcl_conn_cleanup(connp);
1747 	connp->conn_flags = IPCL_TCPCONN;
1748 	bzero(tcp, sizeof (tcp_t));
1749 
1750 	/* restore the state */
1751 	tcp->tcp_timercache = mp;
1752 
1753 	tcp->tcp_sack_info = tcp_sack_info;
1754 	tcp->tcp_iphc = tcp_iphc;
1755 	tcp->tcp_iphc_len = tcp_iphc_len;
1756 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1757 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1758 
1759 	tcp->tcp_connp = connp;
1760 
1761 	ASSERT(connp->conn_tcp == tcp);
1762 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1763 	connp->conn_state_flags = CONN_INCIPIENT;
1764 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1765 	ASSERT(connp->conn_ref == 1);
1766 }
1767 
1768 /*
1769  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1770  * is done forwards from the head.
1771  * This walks all stack instances since
1772  * tcp_time_wait remains global across all stacks.
1773  */
1774 /* ARGSUSED */
1775 void
1776 tcp_time_wait_collector(void *arg)
1777 {
1778 	tcp_t *tcp;
1779 	clock_t now;
1780 	mblk_t *mp;
1781 	conn_t *connp;
1782 	kmutex_t *lock;
1783 	boolean_t removed;
1784 
1785 	squeue_t *sqp = (squeue_t *)arg;
1786 	tcp_squeue_priv_t *tcp_time_wait =
1787 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1788 
1789 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1790 	tcp_time_wait->tcp_time_wait_tid = 0;
1791 
1792 	if (tcp_time_wait->tcp_free_list != NULL &&
1793 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1794 		TCP_G_STAT(tcp_freelist_cleanup);
1795 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1796 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1797 			tcp->tcp_time_wait_next = NULL;
1798 			tcp_time_wait->tcp_free_list_cnt--;
1799 			ASSERT(tcp->tcp_tcps == NULL);
1800 			CONN_DEC_REF(tcp->tcp_connp);
1801 		}
1802 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1803 	}
1804 
1805 	/*
1806 	 * In order to reap time waits reliably, we should use a
1807 	 * source of time that is not adjustable by the user -- hence
1808 	 * the call to ddi_get_lbolt().
1809 	 */
1810 	now = ddi_get_lbolt();
1811 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1812 		/*
1813 		 * Compare times using modular arithmetic, since
1814 		 * lbolt can wrapover.
1815 		 */
1816 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1817 			break;
1818 		}
1819 
1820 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1821 		ASSERT(removed);
1822 
1823 		connp = tcp->tcp_connp;
1824 		ASSERT(connp->conn_fanout != NULL);
1825 		lock = &connp->conn_fanout->connf_lock;
1826 		/*
1827 		 * This is essentially a TW reclaim fast path optimization for
1828 		 * performance where the timewait collector checks under the
1829 		 * fanout lock (so that no one else can get access to the
1830 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1831 		 * the classifier hash list. If ref count is indeed 2, we can
1832 		 * just remove the conn under the fanout lock and avoid
1833 		 * cleaning up the conn under the squeue, provided that
1834 		 * clustering callbacks are not enabled. If clustering is
1835 		 * enabled, we need to make the clustering callback before
1836 		 * setting the CONDEMNED flag and after dropping all locks and
1837 		 * so we forego this optimization and fall back to the slow
1838 		 * path. Also please see the comments in tcp_closei_local
1839 		 * regarding the refcnt logic.
1840 		 *
1841 		 * Since we are holding the tcp_time_wait_lock, its better
1842 		 * not to block on the fanout_lock because other connections
1843 		 * can't add themselves to time_wait list. So we do a
1844 		 * tryenter instead of mutex_enter.
1845 		 */
1846 		if (mutex_tryenter(lock)) {
1847 			mutex_enter(&connp->conn_lock);
1848 			if ((connp->conn_ref == 2) &&
1849 			    (cl_inet_disconnect == NULL)) {
1850 				ipcl_hash_remove_locked(connp,
1851 				    connp->conn_fanout);
1852 				/*
1853 				 * Set the CONDEMNED flag now itself so that
1854 				 * the refcnt cannot increase due to any
1855 				 * walker. But we have still not cleaned up
1856 				 * conn_ire_cache. This is still ok since
1857 				 * we are going to clean it up in tcp_cleanup
1858 				 * immediately and any interface unplumb
1859 				 * thread will wait till the ire is blown away
1860 				 */
1861 				connp->conn_state_flags |= CONN_CONDEMNED;
1862 				mutex_exit(lock);
1863 				mutex_exit(&connp->conn_lock);
1864 				if (tcp_time_wait->tcp_free_list_cnt <
1865 				    tcp_free_list_max_cnt) {
1866 					/* Add to head of tcp_free_list */
1867 					mutex_exit(
1868 					    &tcp_time_wait->tcp_time_wait_lock);
1869 					tcp_cleanup(tcp);
1870 					ASSERT(connp->conn_latch == NULL);
1871 					ASSERT(connp->conn_policy == NULL);
1872 					ASSERT(tcp->tcp_tcps == NULL);
1873 					ASSERT(connp->conn_netstack == NULL);
1874 
1875 					mutex_enter(
1876 					    &tcp_time_wait->tcp_time_wait_lock);
1877 					tcp->tcp_time_wait_next =
1878 					    tcp_time_wait->tcp_free_list;
1879 					tcp_time_wait->tcp_free_list = tcp;
1880 					tcp_time_wait->tcp_free_list_cnt++;
1881 					continue;
1882 				} else {
1883 					/* Do not add to tcp_free_list */
1884 					mutex_exit(
1885 					    &tcp_time_wait->tcp_time_wait_lock);
1886 					tcp_bind_hash_remove(tcp);
1887 					conn_delete_ire(tcp->tcp_connp, NULL);
1888 					tcp_ipsec_cleanup(tcp);
1889 					CONN_DEC_REF(tcp->tcp_connp);
1890 				}
1891 			} else {
1892 				CONN_INC_REF_LOCKED(connp);
1893 				mutex_exit(lock);
1894 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1895 				mutex_exit(&connp->conn_lock);
1896 				/*
1897 				 * We can reuse the closemp here since conn has
1898 				 * detached (otherwise we wouldn't even be in
1899 				 * time_wait list). tcp_closemp_used can safely
1900 				 * be changed without taking a lock as no other
1901 				 * thread can concurrently access it at this
1902 				 * point in the connection lifecycle.
1903 				 */
1904 
1905 				if (tcp->tcp_closemp.b_prev == NULL)
1906 					tcp->tcp_closemp_used = B_TRUE;
1907 				else
1908 					cmn_err(CE_PANIC,
1909 					    "tcp_timewait_collector: "
1910 					    "concurrent use of tcp_closemp: "
1911 					    "connp %p tcp %p\n", (void *)connp,
1912 					    (void *)tcp);
1913 
1914 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1915 				mp = &tcp->tcp_closemp;
1916 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1917 				    tcp_timewait_output, connp,
1918 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1919 			}
1920 		} else {
1921 			mutex_enter(&connp->conn_lock);
1922 			CONN_INC_REF_LOCKED(connp);
1923 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1924 			mutex_exit(&connp->conn_lock);
1925 			/*
1926 			 * We can reuse the closemp here since conn has
1927 			 * detached (otherwise we wouldn't even be in
1928 			 * time_wait list). tcp_closemp_used can safely
1929 			 * be changed without taking a lock as no other
1930 			 * thread can concurrently access it at this
1931 			 * point in the connection lifecycle.
1932 			 */
1933 
1934 			if (tcp->tcp_closemp.b_prev == NULL)
1935 				tcp->tcp_closemp_used = B_TRUE;
1936 			else
1937 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1938 				    "concurrent use of tcp_closemp: "
1939 				    "connp %p tcp %p\n", (void *)connp,
1940 				    (void *)tcp);
1941 
1942 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1943 			mp = &tcp->tcp_closemp;
1944 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1945 			    tcp_timewait_output, connp,
1946 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1947 		}
1948 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1949 	}
1950 
1951 	if (tcp_time_wait->tcp_free_list != NULL)
1952 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1953 
1954 	tcp_time_wait->tcp_time_wait_tid =
1955 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1956 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1957 	    CALLOUT_FLAG_ROUNDUP);
1958 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1959 }
1960 
1961 /*
1962  * Reply to a clients T_CONN_RES TPI message. This function
1963  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1964  * on the acceptor STREAM and processed in tcp_wput_accept().
1965  * Read the block comment on top of tcp_conn_request().
1966  */
1967 static void
1968 tcp_tli_accept(tcp_t *listener, mblk_t *mp)
1969 {
1970 	tcp_t	*acceptor;
1971 	tcp_t	*eager;
1972 	tcp_t   *tcp;
1973 	struct T_conn_res	*tcr;
1974 	t_uscalar_t	acceptor_id;
1975 	t_scalar_t	seqnum;
1976 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1977 	struct tcp_options *tcpopt;
1978 	mblk_t	*ok_mp;
1979 	mblk_t	*mp1;
1980 	tcp_stack_t	*tcps = listener->tcp_tcps;
1981 
1982 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1983 		tcp_err_ack(listener, mp, TPROTO, 0);
1984 		return;
1985 	}
1986 	tcr = (struct T_conn_res *)mp->b_rptr;
1987 
1988 	/*
1989 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1990 	 * read side queue of the streams device underneath us i.e. the
1991 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1992 	 * look it up in the queue_hash.  Under LP64 it sends down the
1993 	 * minor_t of the accepting endpoint.
1994 	 *
1995 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1996 	 * fanout hash lock is held.
1997 	 * This prevents any thread from entering the acceptor queue from
1998 	 * below (since it has not been hard bound yet i.e. any inbound
1999 	 * packets will arrive on the listener or default tcp queue and
2000 	 * go through tcp_lookup).
2001 	 * The CONN_INC_REF will prevent the acceptor from closing.
2002 	 *
2003 	 * XXX It is still possible for a tli application to send down data
2004 	 * on the accepting stream while another thread calls t_accept.
2005 	 * This should not be a problem for well-behaved applications since
2006 	 * the T_OK_ACK is sent after the queue swapping is completed.
2007 	 *
2008 	 * If the accepting fd is the same as the listening fd, avoid
2009 	 * queue hash lookup since that will return an eager listener in a
2010 	 * already established state.
2011 	 */
2012 	acceptor_id = tcr->ACCEPTOR_id;
2013 	mutex_enter(&listener->tcp_eager_lock);
2014 	if (listener->tcp_acceptor_id == acceptor_id) {
2015 		eager = listener->tcp_eager_next_q;
2016 		/* only count how many T_CONN_INDs so don't count q0 */
2017 		if ((listener->tcp_conn_req_cnt_q != 1) ||
2018 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
2019 			mutex_exit(&listener->tcp_eager_lock);
2020 			tcp_err_ack(listener, mp, TBADF, 0);
2021 			return;
2022 		}
2023 		if (listener->tcp_conn_req_cnt_q0 != 0) {
2024 			/* Throw away all the eagers on q0. */
2025 			tcp_eager_cleanup(listener, 1);
2026 		}
2027 		if (listener->tcp_syn_defense) {
2028 			listener->tcp_syn_defense = B_FALSE;
2029 			if (listener->tcp_ip_addr_cache != NULL) {
2030 				kmem_free(listener->tcp_ip_addr_cache,
2031 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
2032 				listener->tcp_ip_addr_cache = NULL;
2033 			}
2034 		}
2035 		/*
2036 		 * Transfer tcp_conn_req_max to the eager so that when
2037 		 * a disconnect occurs we can revert the endpoint to the
2038 		 * listen state.
2039 		 */
2040 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
2041 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
2042 		/*
2043 		 * Get a reference on the acceptor just like the
2044 		 * tcp_acceptor_hash_lookup below.
2045 		 */
2046 		acceptor = listener;
2047 		CONN_INC_REF(acceptor->tcp_connp);
2048 	} else {
2049 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
2050 		if (acceptor == NULL) {
2051 			if (listener->tcp_debug) {
2052 				(void) strlog(TCP_MOD_ID, 0, 1,
2053 				    SL_ERROR|SL_TRACE,
2054 				    "tcp_accept: did not find acceptor 0x%x\n",
2055 				    acceptor_id);
2056 			}
2057 			mutex_exit(&listener->tcp_eager_lock);
2058 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2059 			return;
2060 		}
2061 		/*
2062 		 * Verify acceptor state. The acceptable states for an acceptor
2063 		 * include TCPS_IDLE and TCPS_BOUND.
2064 		 */
2065 		switch (acceptor->tcp_state) {
2066 		case TCPS_IDLE:
2067 			/* FALLTHRU */
2068 		case TCPS_BOUND:
2069 			break;
2070 		default:
2071 			CONN_DEC_REF(acceptor->tcp_connp);
2072 			mutex_exit(&listener->tcp_eager_lock);
2073 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2074 			return;
2075 		}
2076 	}
2077 
2078 	/* The listener must be in TCPS_LISTEN */
2079 	if (listener->tcp_state != TCPS_LISTEN) {
2080 		CONN_DEC_REF(acceptor->tcp_connp);
2081 		mutex_exit(&listener->tcp_eager_lock);
2082 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2083 		return;
2084 	}
2085 
2086 	/*
2087 	 * Rendezvous with an eager connection request packet hanging off
2088 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2089 	 * tcp structure when the connection packet arrived in
2090 	 * tcp_conn_request().
2091 	 */
2092 	seqnum = tcr->SEQ_number;
2093 	eager = listener;
2094 	do {
2095 		eager = eager->tcp_eager_next_q;
2096 		if (eager == NULL) {
2097 			CONN_DEC_REF(acceptor->tcp_connp);
2098 			mutex_exit(&listener->tcp_eager_lock);
2099 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2100 			return;
2101 		}
2102 	} while (eager->tcp_conn_req_seqnum != seqnum);
2103 	mutex_exit(&listener->tcp_eager_lock);
2104 
2105 	/*
2106 	 * At this point, both acceptor and listener have 2 ref
2107 	 * that they begin with. Acceptor has one additional ref
2108 	 * we placed in lookup while listener has 3 additional
2109 	 * ref for being behind the squeue (tcp_accept() is
2110 	 * done on listener's squeue); being in classifier hash;
2111 	 * and eager's ref on listener.
2112 	 */
2113 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2114 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2115 
2116 	/*
2117 	 * The eager at this point is set in its own squeue and
2118 	 * could easily have been killed (tcp_accept_finish will
2119 	 * deal with that) because of a TH_RST so we can only
2120 	 * ASSERT for a single ref.
2121 	 */
2122 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2123 
2124 	/* Pre allocate the stroptions mblk also */
2125 	opt_mp = allocb(MAX(sizeof (struct tcp_options),
2126 	    sizeof (struct T_conn_res)), BPRI_HI);
2127 	if (opt_mp == NULL) {
2128 		CONN_DEC_REF(acceptor->tcp_connp);
2129 		CONN_DEC_REF(eager->tcp_connp);
2130 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2131 		return;
2132 	}
2133 	DB_TYPE(opt_mp) = M_SETOPTS;
2134 	opt_mp->b_wptr += sizeof (struct tcp_options);
2135 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
2136 	tcpopt->to_flags = 0;
2137 
2138 	/*
2139 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2140 	 * from listener to acceptor.
2141 	 */
2142 	if (listener->tcp_bound_if != 0) {
2143 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
2144 		tcpopt->to_boundif = listener->tcp_bound_if;
2145 	}
2146 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2147 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
2148 	}
2149 
2150 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2151 	if ((mp1 = copymsg(mp)) == NULL) {
2152 		CONN_DEC_REF(acceptor->tcp_connp);
2153 		CONN_DEC_REF(eager->tcp_connp);
2154 		freemsg(opt_mp);
2155 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2156 		return;
2157 	}
2158 
2159 	tcr = (struct T_conn_res *)mp1->b_rptr;
2160 
2161 	/*
2162 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2163 	 * which allocates a larger mblk and appends the new
2164 	 * local address to the ok_ack.  The address is copied by
2165 	 * soaccept() for getsockname().
2166 	 */
2167 	{
2168 		int extra;
2169 
2170 		extra = (eager->tcp_family == AF_INET) ?
2171 		    sizeof (sin_t) : sizeof (sin6_t);
2172 
2173 		/*
2174 		 * Try to re-use mp, if possible.  Otherwise, allocate
2175 		 * an mblk and return it as ok_mp.  In any case, mp
2176 		 * is no longer usable upon return.
2177 		 */
2178 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2179 			CONN_DEC_REF(acceptor->tcp_connp);
2180 			CONN_DEC_REF(eager->tcp_connp);
2181 			freemsg(opt_mp);
2182 			/* Original mp has been freed by now, so use mp1 */
2183 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2184 			return;
2185 		}
2186 
2187 		mp = NULL;	/* We should never use mp after this point */
2188 
2189 		switch (extra) {
2190 		case sizeof (sin_t): {
2191 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2192 
2193 				ok_mp->b_wptr += extra;
2194 				sin->sin_family = AF_INET;
2195 				sin->sin_port = eager->tcp_lport;
2196 				sin->sin_addr.s_addr =
2197 				    eager->tcp_ipha->ipha_src;
2198 				break;
2199 			}
2200 		case sizeof (sin6_t): {
2201 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2202 
2203 				ok_mp->b_wptr += extra;
2204 				sin6->sin6_family = AF_INET6;
2205 				sin6->sin6_port = eager->tcp_lport;
2206 				if (eager->tcp_ipversion == IPV4_VERSION) {
2207 					sin6->sin6_flowinfo = 0;
2208 					IN6_IPADDR_TO_V4MAPPED(
2209 					    eager->tcp_ipha->ipha_src,
2210 					    &sin6->sin6_addr);
2211 				} else {
2212 					ASSERT(eager->tcp_ip6h != NULL);
2213 					sin6->sin6_flowinfo =
2214 					    eager->tcp_ip6h->ip6_vcf &
2215 					    ~IPV6_VERS_AND_FLOW_MASK;
2216 					sin6->sin6_addr =
2217 					    eager->tcp_ip6h->ip6_src;
2218 				}
2219 				sin6->sin6_scope_id = 0;
2220 				sin6->__sin6_src_id = 0;
2221 				break;
2222 			}
2223 		default:
2224 			break;
2225 		}
2226 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2227 	}
2228 
2229 	/*
2230 	 * If there are no options we know that the T_CONN_RES will
2231 	 * succeed. However, we can't send the T_OK_ACK upstream until
2232 	 * the tcp_accept_swap is done since it would be dangerous to
2233 	 * let the application start using the new fd prior to the swap.
2234 	 */
2235 	tcp_accept_swap(listener, acceptor, eager);
2236 
2237 	/*
2238 	 * tcp_accept_swap unlinks eager from listener but does not drop
2239 	 * the eager's reference on the listener.
2240 	 */
2241 	ASSERT(eager->tcp_listener == NULL);
2242 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2243 
2244 	/*
2245 	 * The eager is now associated with its own queue. Insert in
2246 	 * the hash so that the connection can be reused for a future
2247 	 * T_CONN_RES.
2248 	 */
2249 	tcp_acceptor_hash_insert(acceptor_id, eager);
2250 
2251 	/*
2252 	 * We now do the processing of options with T_CONN_RES.
2253 	 * We delay till now since we wanted to have queue to pass to
2254 	 * option processing routines that points back to the right
2255 	 * instance structure which does not happen until after
2256 	 * tcp_accept_swap().
2257 	 *
2258 	 * Note:
2259 	 * The sanity of the logic here assumes that whatever options
2260 	 * are appropriate to inherit from listner=>eager are done
2261 	 * before this point, and whatever were to be overridden (or not)
2262 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2263 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2264 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2265 	 * This may not be true at this point in time but can be fixed
2266 	 * independently. This option processing code starts with
2267 	 * the instantiated acceptor instance and the final queue at
2268 	 * this point.
2269 	 */
2270 
2271 	if (tcr->OPT_length != 0) {
2272 		/* Options to process */
2273 		int t_error = 0;
2274 		int sys_error = 0;
2275 		int do_disconnect = 0;
2276 
2277 		if (tcp_conprim_opt_process(eager, mp1,
2278 		    &do_disconnect, &t_error, &sys_error) < 0) {
2279 			eager->tcp_accept_error = 1;
2280 			if (do_disconnect) {
2281 				/*
2282 				 * An option failed which does not allow
2283 				 * connection to be accepted.
2284 				 *
2285 				 * We allow T_CONN_RES to succeed and
2286 				 * put a T_DISCON_IND on the eager queue.
2287 				 */
2288 				ASSERT(t_error == 0 && sys_error == 0);
2289 				eager->tcp_send_discon_ind = 1;
2290 			} else {
2291 				ASSERT(t_error != 0);
2292 				freemsg(ok_mp);
2293 				/*
2294 				 * Original mp was either freed or set
2295 				 * to ok_mp above, so use mp1 instead.
2296 				 */
2297 				tcp_err_ack(listener, mp1, t_error, sys_error);
2298 				goto finish;
2299 			}
2300 		}
2301 		/*
2302 		 * Most likely success in setting options (except if
2303 		 * eager->tcp_send_discon_ind set).
2304 		 * mp1 option buffer represented by OPT_length/offset
2305 		 * potentially modified and contains results of setting
2306 		 * options at this point
2307 		 */
2308 	}
2309 
2310 	/* We no longer need mp1, since all options processing has passed */
2311 	freemsg(mp1);
2312 
2313 	putnext(listener->tcp_rq, ok_mp);
2314 
2315 	mutex_enter(&listener->tcp_eager_lock);
2316 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2317 		tcp_t	*tail;
2318 		mblk_t	*conn_ind;
2319 
2320 		/*
2321 		 * This path should not be executed if listener and
2322 		 * acceptor streams are the same.
2323 		 */
2324 		ASSERT(listener != acceptor);
2325 
2326 		tcp = listener->tcp_eager_prev_q0;
2327 		/*
2328 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2329 		 * deferred T_conn_ind queue. We need to get to the head of
2330 		 * the queue in order to send up T_conn_ind the same order as
2331 		 * how the 3WHS is completed.
2332 		 */
2333 		while (tcp != listener) {
2334 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2335 				break;
2336 			else
2337 				tcp = tcp->tcp_eager_prev_q0;
2338 		}
2339 		ASSERT(tcp != listener);
2340 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2341 		ASSERT(conn_ind != NULL);
2342 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2343 
2344 		/* Move from q0 to q */
2345 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2346 		listener->tcp_conn_req_cnt_q0--;
2347 		listener->tcp_conn_req_cnt_q++;
2348 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2349 		    tcp->tcp_eager_prev_q0;
2350 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2351 		    tcp->tcp_eager_next_q0;
2352 		tcp->tcp_eager_prev_q0 = NULL;
2353 		tcp->tcp_eager_next_q0 = NULL;
2354 		tcp->tcp_conn_def_q0 = B_FALSE;
2355 
2356 		/* Make sure the tcp isn't in the list of droppables */
2357 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2358 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2359 
2360 		/*
2361 		 * Insert at end of the queue because sockfs sends
2362 		 * down T_CONN_RES in chronological order. Leaving
2363 		 * the older conn indications at front of the queue
2364 		 * helps reducing search time.
2365 		 */
2366 		tail = listener->tcp_eager_last_q;
2367 		if (tail != NULL)
2368 			tail->tcp_eager_next_q = tcp;
2369 		else
2370 			listener->tcp_eager_next_q = tcp;
2371 		listener->tcp_eager_last_q = tcp;
2372 		tcp->tcp_eager_next_q = NULL;
2373 		mutex_exit(&listener->tcp_eager_lock);
2374 		putnext(tcp->tcp_rq, conn_ind);
2375 	} else {
2376 		mutex_exit(&listener->tcp_eager_lock);
2377 	}
2378 
2379 	/*
2380 	 * Done with the acceptor - free it
2381 	 *
2382 	 * Note: from this point on, no access to listener should be made
2383 	 * as listener can be equal to acceptor.
2384 	 */
2385 finish:
2386 	ASSERT(acceptor->tcp_detached);
2387 	ASSERT(tcps->tcps_g_q != NULL);
2388 	ASSERT(!IPCL_IS_NONSTR(acceptor->tcp_connp));
2389 	acceptor->tcp_rq = tcps->tcps_g_q;
2390 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2391 	(void) tcp_clean_death(acceptor, 0, 2);
2392 	CONN_DEC_REF(acceptor->tcp_connp);
2393 
2394 	/*
2395 	 * In case we already received a FIN we have to make tcp_rput send
2396 	 * the ordrel_ind. This will also send up a window update if the window
2397 	 * has opened up.
2398 	 *
2399 	 * In the normal case of a successful connection acceptance
2400 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2401 	 * indication that this was just accepted. This tells tcp_rput to
2402 	 * pass up any data queued in tcp_rcv_list.
2403 	 *
2404 	 * In the fringe case where options sent with T_CONN_RES failed and
2405 	 * we required, we would be indicating a T_DISCON_IND to blow
2406 	 * away this connection.
2407 	 */
2408 
2409 	/*
2410 	 * XXX: we currently have a problem if XTI application closes the
2411 	 * acceptor stream in between. This problem exists in on10-gate also
2412 	 * and is well know but nothing can be done short of major rewrite
2413 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2414 	 * eager same squeue as listener (we can distinguish non socket
2415 	 * listeners at the time of handling a SYN in tcp_conn_request)
2416 	 * and do most of the work that tcp_accept_finish does here itself
2417 	 * and then get behind the acceptor squeue to access the acceptor
2418 	 * queue.
2419 	 */
2420 	/*
2421 	 * We already have a ref on tcp so no need to do one before squeue_enter
2422 	 */
2423 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, opt_mp, tcp_accept_finish,
2424 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_ACCEPT_FINISH);
2425 }
2426 
2427 /*
2428  * Swap information between the eager and acceptor for a TLI/XTI client.
2429  * The sockfs accept is done on the acceptor stream and control goes
2430  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2431  * called. In either case, both the eager and listener are in their own
2432  * perimeter (squeue) and the code has to deal with potential race.
2433  *
2434  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2435  */
2436 static void
2437 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2438 {
2439 	conn_t	*econnp, *aconnp;
2440 
2441 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2442 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2443 	ASSERT(!eager->tcp_hard_bound);
2444 	ASSERT(!TCP_IS_SOCKET(acceptor));
2445 	ASSERT(!TCP_IS_SOCKET(eager));
2446 	ASSERT(!TCP_IS_SOCKET(listener));
2447 
2448 	acceptor->tcp_detached = B_TRUE;
2449 	/*
2450 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2451 	 * the acceptor id.
2452 	 */
2453 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2454 
2455 	/* remove eager from listen list... */
2456 	mutex_enter(&listener->tcp_eager_lock);
2457 	tcp_eager_unlink(eager);
2458 	ASSERT(eager->tcp_eager_next_q == NULL &&
2459 	    eager->tcp_eager_last_q == NULL);
2460 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2461 	    eager->tcp_eager_prev_q0 == NULL);
2462 	mutex_exit(&listener->tcp_eager_lock);
2463 	eager->tcp_rq = acceptor->tcp_rq;
2464 	eager->tcp_wq = acceptor->tcp_wq;
2465 
2466 	econnp = eager->tcp_connp;
2467 	aconnp = acceptor->tcp_connp;
2468 
2469 	eager->tcp_rq->q_ptr = econnp;
2470 	eager->tcp_wq->q_ptr = econnp;
2471 
2472 	/*
2473 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2474 	 * which might be a different squeue from our peer TCP instance.
2475 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2476 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2477 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2478 	 * above reach global visibility prior to the clearing of tcp_detached.
2479 	 */
2480 	membar_producer();
2481 	eager->tcp_detached = B_FALSE;
2482 
2483 	ASSERT(eager->tcp_ack_tid == 0);
2484 
2485 	econnp->conn_dev = aconnp->conn_dev;
2486 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2487 	ASSERT(econnp->conn_minor_arena != NULL);
2488 	if (eager->tcp_cred != NULL)
2489 		crfree(eager->tcp_cred);
2490 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2491 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2492 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2493 
2494 	aconnp->conn_cred = NULL;
2495 
2496 	econnp->conn_zoneid = aconnp->conn_zoneid;
2497 	econnp->conn_allzones = aconnp->conn_allzones;
2498 
2499 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2500 	aconnp->conn_mac_exempt = B_FALSE;
2501 
2502 	ASSERT(aconnp->conn_peercred == NULL);
2503 
2504 	/* Do the IPC initialization */
2505 	CONN_INC_REF(econnp);
2506 
2507 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2508 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2509 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2510 
2511 	/* Done with old IPC. Drop its ref on its connp */
2512 	CONN_DEC_REF(aconnp);
2513 }
2514 
2515 
2516 /*
2517  * Adapt to the information, such as rtt and rtt_sd, provided from the
2518  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2519  *
2520  * Checks for multicast and broadcast destination address.
2521  * Returns zero on failure; non-zero if ok.
2522  *
2523  * Note that the MSS calculation here is based on the info given in
2524  * the IRE.  We do not do any calculation based on TCP options.  They
2525  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2526  * knows which options to use.
2527  *
2528  * Note on how TCP gets its parameters for a connection.
2529  *
2530  * When a tcp_t structure is allocated, it gets all the default parameters.
2531  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2532  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2533  * default.
2534  *
2535  * An incoming SYN with a multicast or broadcast destination address, is dropped
2536  * in 1 of 2 places.
2537  *
2538  * 1. If the packet was received over the wire it is dropped in
2539  * ip_rput_process_broadcast()
2540  *
2541  * 2. If the packet was received through internal IP loopback, i.e. the packet
2542  * was generated and received on the same machine, it is dropped in
2543  * ip_wput_local()
2544  *
2545  * An incoming SYN with a multicast or broadcast source address is always
2546  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2547  * reject an attempt to connect to a broadcast or multicast (destination)
2548  * address.
2549  */
2550 static int
2551 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2552 {
2553 	tcp_hsp_t	*hsp;
2554 	ire_t		*ire;
2555 	ire_t		*sire = NULL;
2556 	iulp_t		*ire_uinfo = NULL;
2557 	uint32_t	mss_max;
2558 	uint32_t	mss;
2559 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2560 	conn_t		*connp = tcp->tcp_connp;
2561 	boolean_t	ire_cacheable = B_FALSE;
2562 	zoneid_t	zoneid = connp->conn_zoneid;
2563 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2564 	    MATCH_IRE_SECATTR;
2565 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2566 	ill_t		*ill = NULL;
2567 	boolean_t	incoming = (ire_mp == NULL);
2568 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2569 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2570 
2571 	ASSERT(connp->conn_ire_cache == NULL);
2572 
2573 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2574 
2575 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2576 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2577 			return (0);
2578 		}
2579 		/*
2580 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2581 		 * for the destination with the nexthop as gateway.
2582 		 * ire_ctable_lookup() is used because this particular
2583 		 * ire, if it exists, will be marked private.
2584 		 * If that is not available, use the interface ire
2585 		 * for the nexthop.
2586 		 *
2587 		 * TSol: tcp_update_label will detect label mismatches based
2588 		 * only on the destination's label, but that would not
2589 		 * detect label mismatches based on the security attributes
2590 		 * of routes or next hop gateway. Hence we need to pass the
2591 		 * label to ire_ftable_lookup below in order to locate the
2592 		 * right prefix (and/or) ire cache. Similarly we also need
2593 		 * pass the label to the ire_cache_lookup below to locate
2594 		 * the right ire that also matches on the label.
2595 		 */
2596 		if (tcp->tcp_connp->conn_nexthop_set) {
2597 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2598 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2599 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2600 			    ipst);
2601 			if (ire == NULL) {
2602 				ire = ire_ftable_lookup(
2603 				    tcp->tcp_connp->conn_nexthop_v4,
2604 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2605 				    tsl, match_flags, ipst);
2606 				if (ire == NULL)
2607 					return (0);
2608 			} else {
2609 				ire_uinfo = &ire->ire_uinfo;
2610 			}
2611 		} else {
2612 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2613 			    zoneid, tsl, ipst);
2614 			if (ire != NULL) {
2615 				ire_cacheable = B_TRUE;
2616 				ire_uinfo = (ire_mp != NULL) ?
2617 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2618 				    &ire->ire_uinfo;
2619 
2620 			} else {
2621 				if (ire_mp == NULL) {
2622 					ire = ire_ftable_lookup(
2623 					    tcp->tcp_connp->conn_rem,
2624 					    0, 0, 0, NULL, &sire, zoneid, 0,
2625 					    tsl, (MATCH_IRE_RECURSIVE |
2626 					    MATCH_IRE_DEFAULT), ipst);
2627 					if (ire == NULL)
2628 						return (0);
2629 					ire_uinfo = (sire != NULL) ?
2630 					    &sire->ire_uinfo :
2631 					    &ire->ire_uinfo;
2632 				} else {
2633 					ire = (ire_t *)ire_mp->b_rptr;
2634 					ire_uinfo =
2635 					    &((ire_t *)
2636 					    ire_mp->b_rptr)->ire_uinfo;
2637 				}
2638 			}
2639 		}
2640 		ASSERT(ire != NULL);
2641 
2642 		if ((ire->ire_src_addr == INADDR_ANY) ||
2643 		    (ire->ire_type & IRE_BROADCAST)) {
2644 			/*
2645 			 * ire->ire_mp is non null when ire_mp passed in is used
2646 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2647 			 */
2648 			if (ire->ire_mp == NULL)
2649 				ire_refrele(ire);
2650 			if (sire != NULL)
2651 				ire_refrele(sire);
2652 			return (0);
2653 		}
2654 
2655 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2656 			ipaddr_t src_addr;
2657 
2658 			/*
2659 			 * ip_bind_connected() has stored the correct source
2660 			 * address in conn_src.
2661 			 */
2662 			src_addr = tcp->tcp_connp->conn_src;
2663 			tcp->tcp_ipha->ipha_src = src_addr;
2664 			/*
2665 			 * Copy of the src addr. in tcp_t is needed
2666 			 * for the lookup funcs.
2667 			 */
2668 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2669 		}
2670 		/*
2671 		 * Set the fragment bit so that IP will tell us if the MTU
2672 		 * should change. IP tells us the latest setting of
2673 		 * ip_path_mtu_discovery through ire_frag_flag.
2674 		 */
2675 		if (ipst->ips_ip_path_mtu_discovery) {
2676 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2677 			    htons(IPH_DF);
2678 		}
2679 		/*
2680 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2681 		 * for IP_NEXTHOP. No cache ire has been found for the
2682 		 * destination and we are working with the nexthop's
2683 		 * interface ire. Since we need to forward all packets
2684 		 * to the nexthop first, we "blindly" set tcp_localnet
2685 		 * to false, eventhough the destination may also be
2686 		 * onlink.
2687 		 */
2688 		if (ire_uinfo == NULL)
2689 			tcp->tcp_localnet = 0;
2690 		else
2691 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2692 	} else {
2693 		/*
2694 		 * For incoming connection ire_mp = NULL
2695 		 * For outgoing connection ire_mp != NULL
2696 		 * Technically we should check conn_incoming_ill
2697 		 * when ire_mp is NULL and conn_outgoing_ill when
2698 		 * ire_mp is non-NULL. But this is performance
2699 		 * critical path and for IPV*_BOUND_IF, outgoing
2700 		 * and incoming ill are always set to the same value.
2701 		 */
2702 		ill_t	*dst_ill = NULL;
2703 		ipif_t  *dst_ipif = NULL;
2704 
2705 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2706 
2707 		if (connp->conn_outgoing_ill != NULL) {
2708 			/* Outgoing or incoming path */
2709 			int   err;
2710 
2711 			dst_ill = conn_get_held_ill(connp,
2712 			    &connp->conn_outgoing_ill, &err);
2713 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2714 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2715 				return (0);
2716 			}
2717 			match_flags |= MATCH_IRE_ILL;
2718 			dst_ipif = dst_ill->ill_ipif;
2719 		}
2720 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2721 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2722 
2723 		if (ire != NULL) {
2724 			ire_cacheable = B_TRUE;
2725 			ire_uinfo = (ire_mp != NULL) ?
2726 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2727 			    &ire->ire_uinfo;
2728 		} else {
2729 			if (ire_mp == NULL) {
2730 				ire = ire_ftable_lookup_v6(
2731 				    &tcp->tcp_connp->conn_remv6,
2732 				    0, 0, 0, dst_ipif, &sire, zoneid,
2733 				    0, tsl, match_flags, ipst);
2734 				if (ire == NULL) {
2735 					if (dst_ill != NULL)
2736 						ill_refrele(dst_ill);
2737 					return (0);
2738 				}
2739 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2740 				    &ire->ire_uinfo;
2741 			} else {
2742 				ire = (ire_t *)ire_mp->b_rptr;
2743 				ire_uinfo =
2744 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2745 			}
2746 		}
2747 		if (dst_ill != NULL)
2748 			ill_refrele(dst_ill);
2749 
2750 		ASSERT(ire != NULL);
2751 		ASSERT(ire_uinfo != NULL);
2752 
2753 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2754 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2755 			/*
2756 			 * ire->ire_mp is non null when ire_mp passed in is used
2757 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2758 			 */
2759 			if (ire->ire_mp == NULL)
2760 				ire_refrele(ire);
2761 			if (sire != NULL)
2762 				ire_refrele(sire);
2763 			return (0);
2764 		}
2765 
2766 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2767 			in6_addr_t	src_addr;
2768 
2769 			/*
2770 			 * ip_bind_connected_v6() has stored the correct source
2771 			 * address per IPv6 addr. selection policy in
2772 			 * conn_src_v6.
2773 			 */
2774 			src_addr = tcp->tcp_connp->conn_srcv6;
2775 
2776 			tcp->tcp_ip6h->ip6_src = src_addr;
2777 			/*
2778 			 * Copy of the src addr. in tcp_t is needed
2779 			 * for the lookup funcs.
2780 			 */
2781 			tcp->tcp_ip_src_v6 = src_addr;
2782 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2783 			    &connp->conn_srcv6));
2784 		}
2785 		tcp->tcp_localnet =
2786 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2787 	}
2788 
2789 	/*
2790 	 * This allows applications to fail quickly when connections are made
2791 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2792 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2793 	 */
2794 	if ((ire->ire_flags & RTF_REJECT) &&
2795 	    (ire->ire_flags & RTF_PRIVATE))
2796 		goto error;
2797 
2798 	/*
2799 	 * Make use of the cached rtt and rtt_sd values to calculate the
2800 	 * initial RTO.  Note that they are already initialized in
2801 	 * tcp_init_values().
2802 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2803 	 * IP_NEXTHOP, but instead are using the interface ire for the
2804 	 * nexthop, then we do not use the ire_uinfo from that ire to
2805 	 * do any initializations.
2806 	 */
2807 	if (ire_uinfo != NULL) {
2808 		if (ire_uinfo->iulp_rtt != 0) {
2809 			clock_t	rto;
2810 
2811 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2812 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2813 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2814 			    tcps->tcps_rexmit_interval_extra +
2815 			    (tcp->tcp_rtt_sa >> 5);
2816 
2817 			if (rto > tcps->tcps_rexmit_interval_max) {
2818 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2819 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2820 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2821 			} else {
2822 				tcp->tcp_rto = rto;
2823 			}
2824 		}
2825 		if (ire_uinfo->iulp_ssthresh != 0)
2826 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2827 		else
2828 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2829 		if (ire_uinfo->iulp_spipe > 0) {
2830 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2831 			    tcps->tcps_max_buf);
2832 			if (tcps->tcps_snd_lowat_fraction != 0)
2833 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2834 				    tcps->tcps_snd_lowat_fraction;
2835 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2836 		}
2837 		/*
2838 		 * Note that up till now, acceptor always inherits receive
2839 		 * window from the listener.  But if there is a metrics
2840 		 * associated with a host, we should use that instead of
2841 		 * inheriting it from listener. Thus we need to pass this
2842 		 * info back to the caller.
2843 		 */
2844 		if (ire_uinfo->iulp_rpipe > 0) {
2845 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2846 			    tcps->tcps_max_buf);
2847 		}
2848 
2849 		if (ire_uinfo->iulp_rtomax > 0) {
2850 			tcp->tcp_second_timer_threshold =
2851 			    ire_uinfo->iulp_rtomax;
2852 		}
2853 
2854 		/*
2855 		 * Use the metric option settings, iulp_tstamp_ok and
2856 		 * iulp_wscale_ok, only for active open. What this means
2857 		 * is that if the other side uses timestamp or window
2858 		 * scale option, TCP will also use those options. That
2859 		 * is for passive open.  If the application sets a
2860 		 * large window, window scale is enabled regardless of
2861 		 * the value in iulp_wscale_ok.  This is the behavior
2862 		 * since 2.6.  So we keep it.
2863 		 * The only case left in passive open processing is the
2864 		 * check for SACK.
2865 		 * For ECN, it should probably be like SACK.  But the
2866 		 * current value is binary, so we treat it like the other
2867 		 * cases.  The metric only controls active open.For passive
2868 		 * open, the ndd param, tcp_ecn_permitted, controls the
2869 		 * behavior.
2870 		 */
2871 		if (!tcp_detached) {
2872 			/*
2873 			 * The if check means that the following can only
2874 			 * be turned on by the metrics only IRE, but not off.
2875 			 */
2876 			if (ire_uinfo->iulp_tstamp_ok)
2877 				tcp->tcp_snd_ts_ok = B_TRUE;
2878 			if (ire_uinfo->iulp_wscale_ok)
2879 				tcp->tcp_snd_ws_ok = B_TRUE;
2880 			if (ire_uinfo->iulp_sack == 2)
2881 				tcp->tcp_snd_sack_ok = B_TRUE;
2882 			if (ire_uinfo->iulp_ecn_ok)
2883 				tcp->tcp_ecn_ok = B_TRUE;
2884 		} else {
2885 			/*
2886 			 * Passive open.
2887 			 *
2888 			 * As above, the if check means that SACK can only be
2889 			 * turned on by the metric only IRE.
2890 			 */
2891 			if (ire_uinfo->iulp_sack > 0) {
2892 				tcp->tcp_snd_sack_ok = B_TRUE;
2893 			}
2894 		}
2895 	}
2896 
2897 
2898 	/*
2899 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2900 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2901 	 * length of all those options exceeds 28 bytes.  But because
2902 	 * of the tcp_mss_min check below, we may not have a problem if
2903 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2904 	 * the negative problem still exists.  And the check defeats PMTUd.
2905 	 * In fact, if PMTUd finds that the MSS should be smaller than
2906 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2907 	 * value.
2908 	 *
2909 	 * We do not deal with that now.  All those problems related to
2910 	 * PMTUd will be fixed later.
2911 	 */
2912 	ASSERT(ire->ire_max_frag != 0);
2913 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2914 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2915 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2916 			mss = MIN(mss, IPV6_MIN_MTU);
2917 		}
2918 	}
2919 
2920 	/* Sanity check for MSS value. */
2921 	if (tcp->tcp_ipversion == IPV4_VERSION)
2922 		mss_max = tcps->tcps_mss_max_ipv4;
2923 	else
2924 		mss_max = tcps->tcps_mss_max_ipv6;
2925 
2926 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2927 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2928 		/*
2929 		 * After receiving an ICMPv6 "packet too big" message with a
2930 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2931 		 * will insert a 8-byte fragment header in every packet; we
2932 		 * reduce the MSS by that amount here.
2933 		 */
2934 		mss -= sizeof (ip6_frag_t);
2935 	}
2936 
2937 	if (tcp->tcp_ipsec_overhead == 0)
2938 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2939 
2940 	mss -= tcp->tcp_ipsec_overhead;
2941 
2942 	if (mss < tcps->tcps_mss_min)
2943 		mss = tcps->tcps_mss_min;
2944 	if (mss > mss_max)
2945 		mss = mss_max;
2946 
2947 	/* Note that this is the maximum MSS, excluding all options. */
2948 	tcp->tcp_mss = mss;
2949 
2950 	/*
2951 	 * Initialize the ISS here now that we have the full connection ID.
2952 	 * The RFC 1948 method of initial sequence number generation requires
2953 	 * knowledge of the full connection ID before setting the ISS.
2954 	 */
2955 
2956 	tcp_iss_init(tcp);
2957 
2958 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2959 		tcp->tcp_loopback = B_TRUE;
2960 
2961 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2962 		hsp = tcp_hsp_lookup(tcp->tcp_remote, tcps);
2963 	} else {
2964 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6, tcps);
2965 	}
2966 
2967 	if (hsp != NULL) {
2968 		/* Only modify if we're going to make them bigger */
2969 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2970 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2971 			if (tcps->tcps_snd_lowat_fraction != 0)
2972 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2973 				    tcps->tcps_snd_lowat_fraction;
2974 		}
2975 
2976 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2977 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2978 		}
2979 
2980 		/* Copy timestamp flag only for active open */
2981 		if (!tcp_detached)
2982 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2983 	}
2984 
2985 	if (sire != NULL)
2986 		IRE_REFRELE(sire);
2987 
2988 	/*
2989 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2990 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2991 	 */
2992 	if (tcp->tcp_loopback ||
2993 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2994 		/*
2995 		 * For incoming, see if this tcp may be MDT-capable.  For
2996 		 * outgoing, this process has been taken care of through
2997 		 * tcp_rput_other.
2998 		 */
2999 		tcp_ire_ill_check(tcp, ire, ill, incoming);
3000 		tcp->tcp_ire_ill_check_done = B_TRUE;
3001 	}
3002 
3003 	mutex_enter(&connp->conn_lock);
3004 	/*
3005 	 * Make sure that conn is not marked incipient
3006 	 * for incoming connections. A blind
3007 	 * removal of incipient flag is cheaper than
3008 	 * check and removal.
3009 	 */
3010 	connp->conn_state_flags &= ~CONN_INCIPIENT;
3011 
3012 	/*
3013 	 * Must not cache forwarding table routes
3014 	 * or recache an IRE after the conn_t has
3015 	 * had conn_ire_cache cleared and is flagged
3016 	 * unusable, (see the CONN_CACHE_IRE() macro).
3017 	 */
3018 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
3019 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
3020 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
3021 			connp->conn_ire_cache = ire;
3022 			IRE_UNTRACE_REF(ire);
3023 			rw_exit(&ire->ire_bucket->irb_lock);
3024 			mutex_exit(&connp->conn_lock);
3025 			return (1);
3026 		}
3027 		rw_exit(&ire->ire_bucket->irb_lock);
3028 	}
3029 	mutex_exit(&connp->conn_lock);
3030 
3031 	if (ire->ire_mp == NULL)
3032 		ire_refrele(ire);
3033 	return (1);
3034 
3035 error:
3036 	if (ire->ire_mp == NULL)
3037 		ire_refrele(ire);
3038 	if (sire != NULL)
3039 		ire_refrele(sire);
3040 	return (0);
3041 }
3042 
3043 static void
3044 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
3045 {
3046 	int	error;
3047 	conn_t	*connp = tcp->tcp_connp;
3048 	struct sockaddr	*sa;
3049 	mblk_t  *mp1;
3050 	struct T_bind_req *tbr;
3051 	int	backlog;
3052 	socklen_t	len;
3053 	sin_t	*sin;
3054 	sin6_t	*sin6;
3055 
3056 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3057 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3058 		if (tcp->tcp_debug) {
3059 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3060 			    "tcp_tpi_bind: bad req, len %u",
3061 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3062 		}
3063 		tcp_err_ack(tcp, mp, TPROTO, 0);
3064 		return;
3065 	}
3066 	/* Make sure the largest address fits */
3067 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3068 	if (mp1 == NULL) {
3069 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3070 		return;
3071 	}
3072 	mp = mp1;
3073 	tbr = (struct T_bind_req *)mp->b_rptr;
3074 
3075 	backlog = tbr->CONIND_number;
3076 	len = tbr->ADDR_length;
3077 
3078 	switch (len) {
3079 	case 0:		/* request for a generic port */
3080 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3081 		if (tcp->tcp_family == AF_INET) {
3082 			tbr->ADDR_length = sizeof (sin_t);
3083 			sin = (sin_t *)&tbr[1];
3084 			*sin = sin_null;
3085 			sin->sin_family = AF_INET;
3086 			sa = (struct sockaddr *)sin;
3087 			len = sizeof (sin_t);
3088 			mp->b_wptr = (uchar_t *)&sin[1];
3089 		} else {
3090 			ASSERT(tcp->tcp_family == AF_INET6);
3091 			tbr->ADDR_length = sizeof (sin6_t);
3092 			sin6 = (sin6_t *)&tbr[1];
3093 			*sin6 = sin6_null;
3094 			sin6->sin6_family = AF_INET6;
3095 			sa = (struct sockaddr *)sin6;
3096 			len = sizeof (sin6_t);
3097 			mp->b_wptr = (uchar_t *)&sin6[1];
3098 		}
3099 		break;
3100 
3101 	case sizeof (sin_t):    /* Complete IPv4 address */
3102 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
3103 		    sizeof (sin_t));
3104 		break;
3105 
3106 	case sizeof (sin6_t): /* Complete IPv6 address */
3107 		sa = (struct sockaddr *)mi_offset_param(mp,
3108 		    tbr->ADDR_offset, sizeof (sin6_t));
3109 		break;
3110 
3111 	default:
3112 		if (tcp->tcp_debug) {
3113 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3114 			    "tcp_tpi_bind: bad address length, %d",
3115 			    tbr->ADDR_length);
3116 		}
3117 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3118 		return;
3119 	}
3120 
3121 	error = tcp_bind_check(connp, sa, len, DB_CRED(mp),
3122 	    tbr->PRIM_type != O_T_BIND_REQ);
3123 	if (error == 0) {
3124 		if (tcp->tcp_family == AF_INET) {
3125 			sin = (sin_t *)sa;
3126 			sin->sin_port = tcp->tcp_lport;
3127 		} else {
3128 			sin6 = (sin6_t *)sa;
3129 			sin6->sin6_port = tcp->tcp_lport;
3130 		}
3131 
3132 		if (backlog > 0) {
3133 			error = tcp_do_listen(connp, backlog, DB_CRED(mp));
3134 		}
3135 	}
3136 done:
3137 	if (error > 0) {
3138 		tcp_err_ack(tcp, mp, TSYSERR, error);
3139 	} else if (error < 0) {
3140 		tcp_err_ack(tcp, mp, -error, 0);
3141 	} else {
3142 		mp->b_datap->db_type = M_PCPROTO;
3143 		tbr->PRIM_type = T_BIND_ACK;
3144 		putnext(tcp->tcp_rq, mp);
3145 	}
3146 }
3147 
3148 /*
3149  * If the "bind_to_req_port_only" parameter is set, if the requested port
3150  * number is available, return it, If not return 0
3151  *
3152  * If "bind_to_req_port_only" parameter is not set and
3153  * If the requested port number is available, return it.  If not, return
3154  * the first anonymous port we happen across.  If no anonymous ports are
3155  * available, return 0. addr is the requested local address, if any.
3156  *
3157  * In either case, when succeeding update the tcp_t to record the port number
3158  * and insert it in the bind hash table.
3159  *
3160  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3161  * without setting SO_REUSEADDR. This is needed so that they
3162  * can be viewed as two independent transport protocols.
3163  */
3164 static in_port_t
3165 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3166     int reuseaddr, boolean_t quick_connect,
3167     boolean_t bind_to_req_port_only, boolean_t user_specified)
3168 {
3169 	/* number of times we have run around the loop */
3170 	int count = 0;
3171 	/* maximum number of times to run around the loop */
3172 	int loopmax;
3173 	conn_t *connp = tcp->tcp_connp;
3174 	zoneid_t zoneid = connp->conn_zoneid;
3175 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3176 
3177 	/*
3178 	 * Lookup for free addresses is done in a loop and "loopmax"
3179 	 * influences how long we spin in the loop
3180 	 */
3181 	if (bind_to_req_port_only) {
3182 		/*
3183 		 * If the requested port is busy, don't bother to look
3184 		 * for a new one. Setting loop maximum count to 1 has
3185 		 * that effect.
3186 		 */
3187 		loopmax = 1;
3188 	} else {
3189 		/*
3190 		 * If the requested port is busy, look for a free one
3191 		 * in the anonymous port range.
3192 		 * Set loopmax appropriately so that one does not look
3193 		 * forever in the case all of the anonymous ports are in use.
3194 		 */
3195 		if (tcp->tcp_anon_priv_bind) {
3196 			/*
3197 			 * loopmax =
3198 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3199 			 */
3200 			loopmax = IPPORT_RESERVED -
3201 			    tcps->tcps_min_anonpriv_port;
3202 		} else {
3203 			loopmax = (tcps->tcps_largest_anon_port -
3204 			    tcps->tcps_smallest_anon_port + 1);
3205 		}
3206 	}
3207 	do {
3208 		uint16_t	lport;
3209 		tf_t		*tbf;
3210 		tcp_t		*ltcp;
3211 		conn_t		*lconnp;
3212 
3213 		lport = htons(port);
3214 
3215 		/*
3216 		 * Ensure that the tcp_t is not currently in the bind hash.
3217 		 * Hold the lock on the hash bucket to ensure that
3218 		 * the duplicate check plus the insertion is an atomic
3219 		 * operation.
3220 		 *
3221 		 * This function does an inline lookup on the bind hash list
3222 		 * Make sure that we access only members of tcp_t
3223 		 * and that we don't look at tcp_tcp, since we are not
3224 		 * doing a CONN_INC_REF.
3225 		 */
3226 		tcp_bind_hash_remove(tcp);
3227 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3228 		mutex_enter(&tbf->tf_lock);
3229 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3230 		    ltcp = ltcp->tcp_bind_hash) {
3231 			if (lport == ltcp->tcp_lport)
3232 				break;
3233 		}
3234 
3235 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
3236 			boolean_t not_socket;
3237 			boolean_t exclbind;
3238 
3239 			lconnp = ltcp->tcp_connp;
3240 
3241 			/*
3242 			 * On a labeled system, we must treat bindings to ports
3243 			 * on shared IP addresses by sockets with MAC exemption
3244 			 * privilege as being in all zones, as there's
3245 			 * otherwise no way to identify the right receiver.
3246 			 */
3247 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3248 			    IPCL_ZONE_MATCH(connp,
3249 			    ltcp->tcp_connp->conn_zoneid)) &&
3250 			    !lconnp->conn_mac_exempt &&
3251 			    !connp->conn_mac_exempt)
3252 				continue;
3253 
3254 			/*
3255 			 * If TCP_EXCLBIND is set for either the bound or
3256 			 * binding endpoint, the semantics of bind
3257 			 * is changed according to the following.
3258 			 *
3259 			 * spec = specified address (v4 or v6)
3260 			 * unspec = unspecified address (v4 or v6)
3261 			 * A = specified addresses are different for endpoints
3262 			 *
3263 			 * bound	bind to		allowed
3264 			 * -------------------------------------
3265 			 * unspec	unspec		no
3266 			 * unspec	spec		no
3267 			 * spec		unspec		no
3268 			 * spec		spec		yes if A
3269 			 *
3270 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3271 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3272 			 *
3273 			 * Note:
3274 			 *
3275 			 * 1. Because of TLI semantics, an endpoint can go
3276 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3277 			 * TCPS_BOUND, depending on whether it is originally
3278 			 * a listener or not.  That is why we need to check
3279 			 * for states greater than or equal to TCPS_BOUND
3280 			 * here.
3281 			 *
3282 			 * 2. Ideally, we should only check for state equals
3283 			 * to TCPS_LISTEN. And the following check should be
3284 			 * added.
3285 			 *
3286 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3287 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3288 			 *		...
3289 			 * }
3290 			 *
3291 			 * The semantics will be changed to this.  If the
3292 			 * endpoint on the list is in state not equal to
3293 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3294 			 * set, let the bind succeed.
3295 			 *
3296 			 * Because of (1), we cannot do that for TLI
3297 			 * endpoints.  But we can do that for socket endpoints.
3298 			 * If in future, we can change this going back
3299 			 * semantics, we can use the above check for TLI also.
3300 			 */
3301 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3302 			    TCP_IS_SOCKET(tcp));
3303 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3304 
3305 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3306 			    (exclbind && (not_socket ||
3307 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3308 				if (V6_OR_V4_INADDR_ANY(
3309 				    ltcp->tcp_bound_source_v6) ||
3310 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3311 				    IN6_ARE_ADDR_EQUAL(laddr,
3312 				    &ltcp->tcp_bound_source_v6)) {
3313 					break;
3314 				}
3315 				continue;
3316 			}
3317 
3318 			/*
3319 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3320 			 * have disjoint port number spaces, if *_EXCLBIND
3321 			 * is not set and only if the application binds to a
3322 			 * specific port. We use the same autoassigned port
3323 			 * number space for IPv4 and IPv6 sockets.
3324 			 */
3325 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3326 			    bind_to_req_port_only)
3327 				continue;
3328 
3329 			/*
3330 			 * Ideally, we should make sure that the source
3331 			 * address, remote address, and remote port in the
3332 			 * four tuple for this tcp-connection is unique.
3333 			 * However, trying to find out the local source
3334 			 * address would require too much code duplication
3335 			 * with IP, since IP needs needs to have that code
3336 			 * to support userland TCP implementations.
3337 			 */
3338 			if (quick_connect &&
3339 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3340 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3341 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3342 			    &ltcp->tcp_remote_v6)))
3343 				continue;
3344 
3345 			if (!reuseaddr) {
3346 				/*
3347 				 * No socket option SO_REUSEADDR.
3348 				 * If existing port is bound to
3349 				 * a non-wildcard IP address
3350 				 * and the requesting stream is
3351 				 * bound to a distinct
3352 				 * different IP addresses
3353 				 * (non-wildcard, also), keep
3354 				 * going.
3355 				 */
3356 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3357 				    !V6_OR_V4_INADDR_ANY(
3358 				    ltcp->tcp_bound_source_v6) &&
3359 				    !IN6_ARE_ADDR_EQUAL(laddr,
3360 				    &ltcp->tcp_bound_source_v6))
3361 					continue;
3362 				if (ltcp->tcp_state >= TCPS_BOUND) {
3363 					/*
3364 					 * This port is being used and
3365 					 * its state is >= TCPS_BOUND,
3366 					 * so we can't bind to it.
3367 					 */
3368 					break;
3369 				}
3370 			} else {
3371 				/*
3372 				 * socket option SO_REUSEADDR is set on the
3373 				 * binding tcp_t.
3374 				 *
3375 				 * If two streams are bound to
3376 				 * same IP address or both addr
3377 				 * and bound source are wildcards
3378 				 * (INADDR_ANY), we want to stop
3379 				 * searching.
3380 				 * We have found a match of IP source
3381 				 * address and source port, which is
3382 				 * refused regardless of the
3383 				 * SO_REUSEADDR setting, so we break.
3384 				 */
3385 				if (IN6_ARE_ADDR_EQUAL(laddr,
3386 				    &ltcp->tcp_bound_source_v6) &&
3387 				    (ltcp->tcp_state == TCPS_LISTEN ||
3388 				    ltcp->tcp_state == TCPS_BOUND))
3389 					break;
3390 			}
3391 		}
3392 		if (ltcp != NULL) {
3393 			/* The port number is busy */
3394 			mutex_exit(&tbf->tf_lock);
3395 		} else {
3396 			/*
3397 			 * This port is ours. Insert in fanout and mark as
3398 			 * bound to prevent others from getting the port
3399 			 * number.
3400 			 */
3401 			tcp->tcp_state = TCPS_BOUND;
3402 			tcp->tcp_lport = htons(port);
3403 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3404 
3405 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3406 			    tcp->tcp_lport)] == tbf);
3407 			tcp_bind_hash_insert(tbf, tcp, 1);
3408 
3409 			mutex_exit(&tbf->tf_lock);
3410 
3411 			/*
3412 			 * We don't want tcp_next_port_to_try to "inherit"
3413 			 * a port number supplied by the user in a bind.
3414 			 */
3415 			if (user_specified)
3416 				return (port);
3417 
3418 			/*
3419 			 * This is the only place where tcp_next_port_to_try
3420 			 * is updated. After the update, it may or may not
3421 			 * be in the valid range.
3422 			 */
3423 			if (!tcp->tcp_anon_priv_bind)
3424 				tcps->tcps_next_port_to_try = port + 1;
3425 			return (port);
3426 		}
3427 
3428 		if (tcp->tcp_anon_priv_bind) {
3429 			port = tcp_get_next_priv_port(tcp);
3430 		} else {
3431 			if (count == 0 && user_specified) {
3432 				/*
3433 				 * We may have to return an anonymous port. So
3434 				 * get one to start with.
3435 				 */
3436 				port =
3437 				    tcp_update_next_port(
3438 				    tcps->tcps_next_port_to_try,
3439 				    tcp, B_TRUE);
3440 				user_specified = B_FALSE;
3441 			} else {
3442 				port = tcp_update_next_port(port + 1, tcp,
3443 				    B_FALSE);
3444 			}
3445 		}
3446 		if (port == 0)
3447 			break;
3448 
3449 		/*
3450 		 * Don't let this loop run forever in the case where
3451 		 * all of the anonymous ports are in use.
3452 		 */
3453 	} while (++count < loopmax);
3454 	return (0);
3455 }
3456 
3457 /*
3458  * tcp_clean_death / tcp_close_detached must not be called more than once
3459  * on a tcp. Thus every function that potentially calls tcp_clean_death
3460  * must check for the tcp state before calling tcp_clean_death.
3461  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3462  * tcp_timer_handler, all check for the tcp state.
3463  */
3464 /* ARGSUSED */
3465 void
3466 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3467 {
3468 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3469 
3470 	freemsg(mp);
3471 	if (tcp->tcp_state > TCPS_BOUND)
3472 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3473 		    ETIMEDOUT, 5);
3474 }
3475 
3476 /*
3477  * We are dying for some reason.  Try to do it gracefully.  (May be called
3478  * as writer.)
3479  *
3480  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3481  * done by a service procedure).
3482  * TBD - Should the return value distinguish between the tcp_t being
3483  * freed and it being reinitialized?
3484  */
3485 static int
3486 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3487 {
3488 	mblk_t	*mp;
3489 	queue_t	*q;
3490 	conn_t	*connp = tcp->tcp_connp;
3491 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3492 	sodirect_t	*sodp;
3493 
3494 	TCP_CLD_STAT(tag);
3495 
3496 #if TCP_TAG_CLEAN_DEATH
3497 	tcp->tcp_cleandeathtag = tag;
3498 #endif
3499 
3500 	if (tcp->tcp_fused)
3501 		tcp_unfuse(tcp);
3502 
3503 	if (tcp->tcp_linger_tid != 0 &&
3504 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3505 		tcp_stop_lingering(tcp);
3506 	}
3507 
3508 	ASSERT(tcp != NULL);
3509 	ASSERT((tcp->tcp_family == AF_INET &&
3510 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3511 	    (tcp->tcp_family == AF_INET6 &&
3512 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3513 	    tcp->tcp_ipversion == IPV6_VERSION)));
3514 
3515 	if (TCP_IS_DETACHED(tcp)) {
3516 		if (tcp->tcp_hard_binding) {
3517 			/*
3518 			 * Its an eager that we are dealing with. We close the
3519 			 * eager but in case a conn_ind has already gone to the
3520 			 * listener, let tcp_accept_finish() send a discon_ind
3521 			 * to the listener and drop the last reference. If the
3522 			 * listener doesn't even know about the eager i.e. the
3523 			 * conn_ind hasn't gone up, blow away the eager and drop
3524 			 * the last reference as well. If the conn_ind has gone
3525 			 * up, state should be BOUND. tcp_accept_finish
3526 			 * will figure out that the connection has received a
3527 			 * RST and will send a DISCON_IND to the application.
3528 			 */
3529 			tcp_closei_local(tcp);
3530 			if (!tcp->tcp_tconnind_started) {
3531 				CONN_DEC_REF(connp);
3532 			} else {
3533 				tcp->tcp_state = TCPS_BOUND;
3534 			}
3535 		} else {
3536 			tcp_close_detached(tcp);
3537 		}
3538 		return (0);
3539 	}
3540 
3541 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3542 
3543 	/* If sodirect, not anymore */
3544 	SOD_PTR_ENTER(tcp, sodp);
3545 	if (sodp != NULL) {
3546 		tcp->tcp_sodirect = NULL;
3547 		mutex_exit(sodp->sod_lockp);
3548 	}
3549 
3550 	q = tcp->tcp_rq;
3551 
3552 	/* Trash all inbound data */
3553 	if (!IPCL_IS_NONSTR(connp)) {
3554 		ASSERT(q != NULL);
3555 		flushq(q, FLUSHALL);
3556 	}
3557 
3558 	/*
3559 	 * If we are at least part way open and there is error
3560 	 * (err==0 implies no error)
3561 	 * notify our client by a T_DISCON_IND.
3562 	 */
3563 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3564 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3565 		    !TCP_IS_SOCKET(tcp)) {
3566 			/*
3567 			 * Send M_FLUSH according to TPI. Because sockets will
3568 			 * (and must) ignore FLUSHR we do that only for TPI
3569 			 * endpoints and sockets in STREAMS mode.
3570 			 */
3571 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3572 		}
3573 		if (tcp->tcp_debug) {
3574 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3575 			    "tcp_clean_death: discon err %d", err);
3576 		}
3577 		if (IPCL_IS_NONSTR(connp)) {
3578 			/* Direct socket, use upcall */
3579 			(*connp->conn_upcalls->su_disconnected)(
3580 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3581 		} else {
3582 			mp = mi_tpi_discon_ind(NULL, err, 0);
3583 			if (mp != NULL) {
3584 				putnext(q, mp);
3585 			} else {
3586 				if (tcp->tcp_debug) {
3587 					(void) strlog(TCP_MOD_ID, 0, 1,
3588 					    SL_ERROR|SL_TRACE,
3589 					    "tcp_clean_death, sending M_ERROR");
3590 				}
3591 				(void) putnextctl1(q, M_ERROR, EPROTO);
3592 			}
3593 		}
3594 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3595 			/* SYN_SENT or SYN_RCVD */
3596 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3597 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3598 			/* ESTABLISHED or CLOSE_WAIT */
3599 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3600 		}
3601 	}
3602 
3603 	tcp_reinit(tcp);
3604 	if (IPCL_IS_NONSTR(connp))
3605 		(void) tcp_do_unbind(connp);
3606 
3607 	return (-1);
3608 }
3609 
3610 /*
3611  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3612  * to expire, stop the wait and finish the close.
3613  */
3614 static void
3615 tcp_stop_lingering(tcp_t *tcp)
3616 {
3617 	clock_t	delta = 0;
3618 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3619 
3620 	tcp->tcp_linger_tid = 0;
3621 	if (tcp->tcp_state > TCPS_LISTEN) {
3622 		tcp_acceptor_hash_remove(tcp);
3623 		mutex_enter(&tcp->tcp_non_sq_lock);
3624 		if (tcp->tcp_flow_stopped) {
3625 			tcp_clrqfull(tcp);
3626 		}
3627 		mutex_exit(&tcp->tcp_non_sq_lock);
3628 
3629 		if (tcp->tcp_timer_tid != 0) {
3630 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3631 			tcp->tcp_timer_tid = 0;
3632 		}
3633 		/*
3634 		 * Need to cancel those timers which will not be used when
3635 		 * TCP is detached.  This has to be done before the tcp_wq
3636 		 * is set to the global queue.
3637 		 */
3638 		tcp_timers_stop(tcp);
3639 
3640 		tcp->tcp_detached = B_TRUE;
3641 		ASSERT(tcps->tcps_g_q != NULL);
3642 		tcp->tcp_rq = tcps->tcps_g_q;
3643 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3644 
3645 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3646 			tcp_time_wait_append(tcp);
3647 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3648 			goto finish;
3649 		}
3650 
3651 		/*
3652 		 * If delta is zero the timer event wasn't executed and was
3653 		 * successfully canceled. In this case we need to restart it
3654 		 * with the minimal delta possible.
3655 		 */
3656 		if (delta >= 0) {
3657 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3658 			    delta ? delta : 1);
3659 		}
3660 	} else {
3661 		tcp_closei_local(tcp);
3662 		CONN_DEC_REF(tcp->tcp_connp);
3663 	}
3664 finish:
3665 	/* Signal closing thread that it can complete close */
3666 	mutex_enter(&tcp->tcp_closelock);
3667 	tcp->tcp_detached = B_TRUE;
3668 	ASSERT(tcps->tcps_g_q != NULL);
3669 
3670 	tcp->tcp_rq = tcps->tcps_g_q;
3671 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3672 
3673 	tcp->tcp_closed = 1;
3674 	cv_signal(&tcp->tcp_closecv);
3675 	mutex_exit(&tcp->tcp_closelock);
3676 }
3677 
3678 /*
3679  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3680  * expires.
3681  */
3682 static void
3683 tcp_close_linger_timeout(void *arg)
3684 {
3685 	conn_t	*connp = (conn_t *)arg;
3686 	tcp_t 	*tcp = connp->conn_tcp;
3687 
3688 	tcp->tcp_client_errno = ETIMEDOUT;
3689 	tcp_stop_lingering(tcp);
3690 }
3691 
3692 static void
3693 tcp_close_common(conn_t *connp, int flags)
3694 {
3695 	tcp_t		*tcp = connp->conn_tcp;
3696 	mblk_t 		*mp = &tcp->tcp_closemp;
3697 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3698 	mblk_t		*bp;
3699 
3700 	ASSERT(connp->conn_ref >= 2);
3701 
3702 	/*
3703 	 * Mark the conn as closing. ill_pending_mp_add will not
3704 	 * add any mp to the pending mp list, after this conn has
3705 	 * started closing. Same for sq_pending_mp_add
3706 	 */
3707 	mutex_enter(&connp->conn_lock);
3708 	connp->conn_state_flags |= CONN_CLOSING;
3709 	if (connp->conn_oper_pending_ill != NULL)
3710 		conn_ioctl_cleanup_reqd = B_TRUE;
3711 	CONN_INC_REF_LOCKED(connp);
3712 	mutex_exit(&connp->conn_lock);
3713 	tcp->tcp_closeflags = (uint8_t)flags;
3714 	ASSERT(connp->conn_ref >= 3);
3715 
3716 	/*
3717 	 * tcp_closemp_used is used below without any protection of a lock
3718 	 * as we don't expect any one else to use it concurrently at this
3719 	 * point otherwise it would be a major defect.
3720 	 */
3721 
3722 	if (mp->b_prev == NULL)
3723 		tcp->tcp_closemp_used = B_TRUE;
3724 	else
3725 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3726 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3727 
3728 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3729 
3730 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3731 	    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3732 
3733 	mutex_enter(&tcp->tcp_closelock);
3734 	while (!tcp->tcp_closed) {
3735 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3736 			/*
3737 			 * The cv_wait_sig() was interrupted. We now do the
3738 			 * following:
3739 			 *
3740 			 * 1) If the endpoint was lingering, we allow this
3741 			 * to be interrupted by cancelling the linger timeout
3742 			 * and closing normally.
3743 			 *
3744 			 * 2) Revert to calling cv_wait()
3745 			 *
3746 			 * We revert to using cv_wait() to avoid an
3747 			 * infinite loop which can occur if the calling
3748 			 * thread is higher priority than the squeue worker
3749 			 * thread and is bound to the same cpu.
3750 			 */
3751 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
3752 				mutex_exit(&tcp->tcp_closelock);
3753 				/* Entering squeue, bump ref count. */
3754 				CONN_INC_REF(connp);
3755 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3756 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3757 				    tcp_linger_interrupted, connp,
3758 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3759 				mutex_enter(&tcp->tcp_closelock);
3760 			}
3761 			break;
3762 		}
3763 	}
3764 	while (!tcp->tcp_closed)
3765 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3766 	mutex_exit(&tcp->tcp_closelock);
3767 
3768 	/*
3769 	 * In the case of listener streams that have eagers in the q or q0
3770 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3771 	 * tcp_wq of the eagers point to our queues. By waiting for the
3772 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3773 	 * up their queue pointers and also dropped their references to us.
3774 	 */
3775 	if (tcp->tcp_wait_for_eagers) {
3776 		mutex_enter(&connp->conn_lock);
3777 		while (connp->conn_ref != 1) {
3778 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3779 		}
3780 		mutex_exit(&connp->conn_lock);
3781 	}
3782 	/*
3783 	 * ioctl cleanup. The mp is queued in the
3784 	 * ill_pending_mp or in the sq_pending_mp.
3785 	 */
3786 	if (conn_ioctl_cleanup_reqd)
3787 		conn_ioctl_cleanup(connp);
3788 
3789 	tcp->tcp_cpid = -1;
3790 }
3791 
3792 static int
3793 tcp_tpi_close(queue_t *q, int flags)
3794 {
3795 	conn_t		*connp;
3796 
3797 	ASSERT(WR(q)->q_next == NULL);
3798 
3799 	if (flags & SO_FALLBACK) {
3800 		/*
3801 		 * stream is being closed while in fallback
3802 		 * simply free the resources that were allocated
3803 		 */
3804 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3805 		qprocsoff(q);
3806 		goto done;
3807 	}
3808 
3809 	connp = Q_TO_CONN(q);
3810 	/*
3811 	 * We are being closed as /dev/tcp or /dev/tcp6.
3812 	 */
3813 	tcp_close_common(connp, flags);
3814 
3815 	qprocsoff(q);
3816 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3817 
3818 	/*
3819 	 * Drop IP's reference on the conn. This is the last reference
3820 	 * on the connp if the state was less than established. If the
3821 	 * connection has gone into timewait state, then we will have
3822 	 * one ref for the TCP and one more ref (total of two) for the
3823 	 * classifier connected hash list (a timewait connections stays
3824 	 * in connected hash till closed).
3825 	 *
3826 	 * We can't assert the references because there might be other
3827 	 * transient reference places because of some walkers or queued
3828 	 * packets in squeue for the timewait state.
3829 	 */
3830 	CONN_DEC_REF(connp);
3831 done:
3832 	q->q_ptr = WR(q)->q_ptr = NULL;
3833 	return (0);
3834 }
3835 
3836 static int
3837 tcpclose_accept(queue_t *q)
3838 {
3839 	vmem_t	*minor_arena;
3840 	dev_t	conn_dev;
3841 
3842 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3843 
3844 	/*
3845 	 * We had opened an acceptor STREAM for sockfs which is
3846 	 * now being closed due to some error.
3847 	 */
3848 	qprocsoff(q);
3849 
3850 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3851 	conn_dev = (dev_t)RD(q)->q_ptr;
3852 	ASSERT(minor_arena != NULL);
3853 	ASSERT(conn_dev != 0);
3854 	inet_minor_free(minor_arena, conn_dev);
3855 	q->q_ptr = WR(q)->q_ptr = NULL;
3856 	return (0);
3857 }
3858 
3859 /*
3860  * Called by tcp_close() routine via squeue when lingering is
3861  * interrupted by a signal.
3862  */
3863 
3864 /* ARGSUSED */
3865 static void
3866 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
3867 {
3868 	conn_t	*connp = (conn_t *)arg;
3869 	tcp_t	*tcp = connp->conn_tcp;
3870 
3871 	freeb(mp);
3872 	if (tcp->tcp_linger_tid != 0 &&
3873 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3874 		tcp_stop_lingering(tcp);
3875 		tcp->tcp_client_errno = EINTR;
3876 	}
3877 }
3878 
3879 /*
3880  * Called by streams close routine via squeues when our client blows off her
3881  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3882  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3883  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3884  * acked.
3885  *
3886  * NOTE: tcp_close potentially returns error when lingering.
3887  * However, the stream head currently does not pass these errors
3888  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3889  * errors to the application (from tsleep()) and not errors
3890  * like ECONNRESET caused by receiving a reset packet.
3891  */
3892 
3893 /* ARGSUSED */
3894 static void
3895 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3896 {
3897 	char	*msg;
3898 	conn_t	*connp = (conn_t *)arg;
3899 	tcp_t	*tcp = connp->conn_tcp;
3900 	clock_t	delta = 0;
3901 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3902 
3903 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3904 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3905 
3906 	mutex_enter(&tcp->tcp_eager_lock);
3907 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3908 		/* Cleanup for listener */
3909 		tcp_eager_cleanup(tcp, 0);
3910 		tcp->tcp_wait_for_eagers = 1;
3911 	}
3912 	mutex_exit(&tcp->tcp_eager_lock);
3913 
3914 	connp->conn_mdt_ok = B_FALSE;
3915 	tcp->tcp_mdt = B_FALSE;
3916 
3917 	connp->conn_lso_ok = B_FALSE;
3918 	tcp->tcp_lso = B_FALSE;
3919 
3920 	msg = NULL;
3921 	switch (tcp->tcp_state) {
3922 	case TCPS_CLOSED:
3923 	case TCPS_IDLE:
3924 	case TCPS_BOUND:
3925 	case TCPS_LISTEN:
3926 		break;
3927 	case TCPS_SYN_SENT:
3928 		msg = "tcp_close, during connect";
3929 		break;
3930 	case TCPS_SYN_RCVD:
3931 		/*
3932 		 * Close during the connect 3-way handshake
3933 		 * but here there may or may not be pending data
3934 		 * already on queue. Process almost same as in
3935 		 * the ESTABLISHED state.
3936 		 */
3937 		/* FALLTHRU */
3938 	default:
3939 		if (tcp->tcp_sodirect != NULL) {
3940 			/* Ok, no more sodirect */
3941 			tcp->tcp_sodirect = NULL;
3942 		}
3943 
3944 		if (tcp->tcp_fused)
3945 			tcp_unfuse(tcp);
3946 
3947 		/*
3948 		 * If SO_LINGER has set a zero linger time, abort the
3949 		 * connection with a reset.
3950 		 */
3951 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3952 			msg = "tcp_close, zero lingertime";
3953 			break;
3954 		}
3955 
3956 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3957 		/*
3958 		 * Abort connection if there is unread data queued.
3959 		 */
3960 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3961 			msg = "tcp_close, unread data";
3962 			break;
3963 		}
3964 		/*
3965 		 * tcp_hard_bound is now cleared thus all packets go through
3966 		 * tcp_lookup. This fact is used by tcp_detach below.
3967 		 *
3968 		 * We have done a qwait() above which could have possibly
3969 		 * drained more messages in turn causing transition to a
3970 		 * different state. Check whether we have to do the rest
3971 		 * of the processing or not.
3972 		 */
3973 		if (tcp->tcp_state <= TCPS_LISTEN)
3974 			break;
3975 
3976 		/*
3977 		 * Transmit the FIN before detaching the tcp_t.
3978 		 * After tcp_detach returns this queue/perimeter
3979 		 * no longer owns the tcp_t thus others can modify it.
3980 		 */
3981 		(void) tcp_xmit_end(tcp);
3982 
3983 		/*
3984 		 * If lingering on close then wait until the fin is acked,
3985 		 * the SO_LINGER time passes, or a reset is sent/received.
3986 		 */
3987 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
3988 		    !(tcp->tcp_fin_acked) &&
3989 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3990 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3991 				tcp->tcp_client_errno = EWOULDBLOCK;
3992 			} else if (tcp->tcp_client_errno == 0) {
3993 
3994 				ASSERT(tcp->tcp_linger_tid == 0);
3995 
3996 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3997 				    tcp_close_linger_timeout,
3998 				    tcp->tcp_lingertime * hz);
3999 
4000 				/* tcp_close_linger_timeout will finish close */
4001 				if (tcp->tcp_linger_tid == 0)
4002 					tcp->tcp_client_errno = ENOSR;
4003 				else
4004 					return;
4005 			}
4006 
4007 			/*
4008 			 * Check if we need to detach or just close
4009 			 * the instance.
4010 			 */
4011 			if (tcp->tcp_state <= TCPS_LISTEN)
4012 				break;
4013 		}
4014 
4015 		/*
4016 		 * Make sure that no other thread will access the tcp_rq of
4017 		 * this instance (through lookups etc.) as tcp_rq will go
4018 		 * away shortly.
4019 		 */
4020 		tcp_acceptor_hash_remove(tcp);
4021 
4022 		mutex_enter(&tcp->tcp_non_sq_lock);
4023 		if (tcp->tcp_flow_stopped) {
4024 			tcp_clrqfull(tcp);
4025 		}
4026 		mutex_exit(&tcp->tcp_non_sq_lock);
4027 
4028 		if (tcp->tcp_timer_tid != 0) {
4029 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4030 			tcp->tcp_timer_tid = 0;
4031 		}
4032 		/*
4033 		 * Need to cancel those timers which will not be used when
4034 		 * TCP is detached.  This has to be done before the tcp_wq
4035 		 * is set to the global queue.
4036 		 */
4037 		tcp_timers_stop(tcp);
4038 
4039 		tcp->tcp_detached = B_TRUE;
4040 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4041 			tcp_time_wait_append(tcp);
4042 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
4043 			ASSERT(connp->conn_ref >= 3);
4044 			goto finish;
4045 		}
4046 
4047 		/*
4048 		 * If delta is zero the timer event wasn't executed and was
4049 		 * successfully canceled. In this case we need to restart it
4050 		 * with the minimal delta possible.
4051 		 */
4052 		if (delta >= 0)
4053 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4054 			    delta ? delta : 1);
4055 
4056 		ASSERT(connp->conn_ref >= 3);
4057 		goto finish;
4058 	}
4059 
4060 	/* Detach did not complete. Still need to remove q from stream. */
4061 	if (msg) {
4062 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4063 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4064 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4065 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4066 		    tcp->tcp_state == TCPS_SYN_RCVD)
4067 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4068 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4069 	}
4070 
4071 	tcp_closei_local(tcp);
4072 	CONN_DEC_REF(connp);
4073 	ASSERT(connp->conn_ref >= 2);
4074 
4075 finish:
4076 	/*
4077 	 * Although packets are always processed on the correct
4078 	 * tcp's perimeter and access is serialized via squeue's,
4079 	 * IP still needs a queue when sending packets in time_wait
4080 	 * state so use WR(tcps_g_q) till ip_output() can be
4081 	 * changed to deal with just connp. For read side, we
4082 	 * could have set tcp_rq to NULL but there are some cases
4083 	 * in tcp_rput_data() from early days of this code which
4084 	 * do a putnext without checking if tcp is closed. Those
4085 	 * need to be identified before both tcp_rq and tcp_wq
4086 	 * can be set to NULL and tcps_g_q can disappear forever.
4087 	 */
4088 	mutex_enter(&tcp->tcp_closelock);
4089 	/*
4090 	 * Don't change the queues in the case of a listener that has
4091 	 * eagers in its q or q0. It could surprise the eagers.
4092 	 * Instead wait for the eagers outside the squeue.
4093 	 */
4094 	if (!tcp->tcp_wait_for_eagers) {
4095 		tcp->tcp_detached = B_TRUE;
4096 		/*
4097 		 * When default queue is closing we set tcps_g_q to NULL
4098 		 * after the close is done.
4099 		 */
4100 		ASSERT(tcps->tcps_g_q != NULL);
4101 		tcp->tcp_rq = tcps->tcps_g_q;
4102 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4103 	}
4104 
4105 	/* Signal tcp_close() to finish closing. */
4106 	tcp->tcp_closed = 1;
4107 	cv_signal(&tcp->tcp_closecv);
4108 	mutex_exit(&tcp->tcp_closelock);
4109 }
4110 
4111 
4112 /*
4113  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4114  * Some stream heads get upset if they see these later on as anything but NULL.
4115  */
4116 static void
4117 tcp_close_mpp(mblk_t **mpp)
4118 {
4119 	mblk_t	*mp;
4120 
4121 	if ((mp = *mpp) != NULL) {
4122 		do {
4123 			mp->b_next = NULL;
4124 			mp->b_prev = NULL;
4125 		} while ((mp = mp->b_cont) != NULL);
4126 
4127 		mp = *mpp;
4128 		*mpp = NULL;
4129 		freemsg(mp);
4130 	}
4131 }
4132 
4133 /* Do detached close. */
4134 static void
4135 tcp_close_detached(tcp_t *tcp)
4136 {
4137 	if (tcp->tcp_fused)
4138 		tcp_unfuse(tcp);
4139 
4140 	/*
4141 	 * Clustering code serializes TCP disconnect callbacks and
4142 	 * cluster tcp list walks by blocking a TCP disconnect callback
4143 	 * if a cluster tcp list walk is in progress. This ensures
4144 	 * accurate accounting of TCPs in the cluster code even though
4145 	 * the TCP list walk itself is not atomic.
4146 	 */
4147 	tcp_closei_local(tcp);
4148 	CONN_DEC_REF(tcp->tcp_connp);
4149 }
4150 
4151 /*
4152  * Stop all TCP timers, and free the timer mblks if requested.
4153  */
4154 void
4155 tcp_timers_stop(tcp_t *tcp)
4156 {
4157 	if (tcp->tcp_timer_tid != 0) {
4158 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4159 		tcp->tcp_timer_tid = 0;
4160 	}
4161 	if (tcp->tcp_ka_tid != 0) {
4162 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4163 		tcp->tcp_ka_tid = 0;
4164 	}
4165 	if (tcp->tcp_ack_tid != 0) {
4166 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4167 		tcp->tcp_ack_tid = 0;
4168 	}
4169 	if (tcp->tcp_push_tid != 0) {
4170 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4171 		tcp->tcp_push_tid = 0;
4172 	}
4173 }
4174 
4175 /*
4176  * The tcp_t is going away. Remove it from all lists and set it
4177  * to TCPS_CLOSED. The freeing up of memory is deferred until
4178  * tcp_inactive. This is needed since a thread in tcp_rput might have
4179  * done a CONN_INC_REF on this structure before it was removed from the
4180  * hashes.
4181  */
4182 static void
4183 tcp_closei_local(tcp_t *tcp)
4184 {
4185 	ire_t 	*ire;
4186 	conn_t	*connp = tcp->tcp_connp;
4187 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4188 
4189 	if (!TCP_IS_SOCKET(tcp))
4190 		tcp_acceptor_hash_remove(tcp);
4191 
4192 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4193 	tcp->tcp_ibsegs = 0;
4194 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4195 	tcp->tcp_obsegs = 0;
4196 
4197 	/*
4198 	 * If we are an eager connection hanging off a listener that
4199 	 * hasn't formally accepted the connection yet, get off his
4200 	 * list and blow off any data that we have accumulated.
4201 	 */
4202 	if (tcp->tcp_listener != NULL) {
4203 		tcp_t	*listener = tcp->tcp_listener;
4204 		mutex_enter(&listener->tcp_eager_lock);
4205 		/*
4206 		 * tcp_tconnind_started == B_TRUE means that the
4207 		 * conn_ind has already gone to listener. At
4208 		 * this point, eager will be closed but we
4209 		 * leave it in listeners eager list so that
4210 		 * if listener decides to close without doing
4211 		 * accept, we can clean this up. In tcp_wput_accept
4212 		 * we take care of the case of accept on closed
4213 		 * eager.
4214 		 */
4215 		if (!tcp->tcp_tconnind_started) {
4216 			tcp_eager_unlink(tcp);
4217 			mutex_exit(&listener->tcp_eager_lock);
4218 			/*
4219 			 * We don't want to have any pointers to the
4220 			 * listener queue, after we have released our
4221 			 * reference on the listener
4222 			 */
4223 			ASSERT(tcps->tcps_g_q != NULL);
4224 			tcp->tcp_rq = tcps->tcps_g_q;
4225 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4226 			CONN_DEC_REF(listener->tcp_connp);
4227 		} else {
4228 			mutex_exit(&listener->tcp_eager_lock);
4229 		}
4230 	}
4231 
4232 	/* Stop all the timers */
4233 	tcp_timers_stop(tcp);
4234 
4235 	if (tcp->tcp_state == TCPS_LISTEN) {
4236 		if (tcp->tcp_ip_addr_cache) {
4237 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4238 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4239 			tcp->tcp_ip_addr_cache = NULL;
4240 		}
4241 	}
4242 	mutex_enter(&tcp->tcp_non_sq_lock);
4243 	if (tcp->tcp_flow_stopped)
4244 		tcp_clrqfull(tcp);
4245 	mutex_exit(&tcp->tcp_non_sq_lock);
4246 
4247 	tcp_bind_hash_remove(tcp);
4248 	/*
4249 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4250 	 * is trying to remove this tcp from the time wait list, we will
4251 	 * block in tcp_time_wait_remove while trying to acquire the
4252 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4253 	 * requires the ipcl_hash_remove to be ordered after the
4254 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4255 	 */
4256 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4257 		(void) tcp_time_wait_remove(tcp, NULL);
4258 	CL_INET_DISCONNECT(connp, tcp);
4259 	ipcl_hash_remove(connp);
4260 
4261 	/*
4262 	 * Delete the cached ire in conn_ire_cache and also mark
4263 	 * the conn as CONDEMNED
4264 	 */
4265 	mutex_enter(&connp->conn_lock);
4266 	connp->conn_state_flags |= CONN_CONDEMNED;
4267 	ire = connp->conn_ire_cache;
4268 	connp->conn_ire_cache = NULL;
4269 	mutex_exit(&connp->conn_lock);
4270 	if (ire != NULL)
4271 		IRE_REFRELE_NOTR(ire);
4272 
4273 	/* Need to cleanup any pending ioctls */
4274 	ASSERT(tcp->tcp_time_wait_next == NULL);
4275 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4276 	ASSERT(tcp->tcp_time_wait_expire == 0);
4277 	tcp->tcp_state = TCPS_CLOSED;
4278 
4279 	/* Release any SSL context */
4280 	if (tcp->tcp_kssl_ent != NULL) {
4281 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4282 		tcp->tcp_kssl_ent = NULL;
4283 	}
4284 	if (tcp->tcp_kssl_ctx != NULL) {
4285 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4286 		tcp->tcp_kssl_ctx = NULL;
4287 	}
4288 	tcp->tcp_kssl_pending = B_FALSE;
4289 
4290 	tcp_ipsec_cleanup(tcp);
4291 }
4292 
4293 /*
4294  * tcp is dying (called from ipcl_conn_destroy and error cases).
4295  * Free the tcp_t in either case.
4296  */
4297 void
4298 tcp_free(tcp_t *tcp)
4299 {
4300 	mblk_t	*mp;
4301 	ip6_pkt_t	*ipp;
4302 
4303 	ASSERT(tcp != NULL);
4304 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4305 
4306 	tcp->tcp_rq = NULL;
4307 	tcp->tcp_wq = NULL;
4308 
4309 	tcp_close_mpp(&tcp->tcp_xmit_head);
4310 	tcp_close_mpp(&tcp->tcp_reass_head);
4311 	if (tcp->tcp_rcv_list != NULL) {
4312 		/* Free b_next chain */
4313 		tcp_close_mpp(&tcp->tcp_rcv_list);
4314 	}
4315 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4316 		freemsg(mp);
4317 	}
4318 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4319 		freemsg(mp);
4320 	}
4321 
4322 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4323 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4324 		freeb(tcp->tcp_fused_sigurg_mp);
4325 		tcp->tcp_fused_sigurg_mp = NULL;
4326 	}
4327 
4328 	if (tcp->tcp_ordrel_mp != NULL) {
4329 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4330 		freeb(tcp->tcp_ordrel_mp);
4331 		tcp->tcp_ordrel_mp = NULL;
4332 	}
4333 
4334 	if (tcp->tcp_sack_info != NULL) {
4335 		if (tcp->tcp_notsack_list != NULL) {
4336 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4337 		}
4338 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4339 	}
4340 
4341 	if (tcp->tcp_hopopts != NULL) {
4342 		mi_free(tcp->tcp_hopopts);
4343 		tcp->tcp_hopopts = NULL;
4344 		tcp->tcp_hopoptslen = 0;
4345 	}
4346 	ASSERT(tcp->tcp_hopoptslen == 0);
4347 	if (tcp->tcp_dstopts != NULL) {
4348 		mi_free(tcp->tcp_dstopts);
4349 		tcp->tcp_dstopts = NULL;
4350 		tcp->tcp_dstoptslen = 0;
4351 	}
4352 	ASSERT(tcp->tcp_dstoptslen == 0);
4353 	if (tcp->tcp_rtdstopts != NULL) {
4354 		mi_free(tcp->tcp_rtdstopts);
4355 		tcp->tcp_rtdstopts = NULL;
4356 		tcp->tcp_rtdstoptslen = 0;
4357 	}
4358 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4359 	if (tcp->tcp_rthdr != NULL) {
4360 		mi_free(tcp->tcp_rthdr);
4361 		tcp->tcp_rthdr = NULL;
4362 		tcp->tcp_rthdrlen = 0;
4363 	}
4364 	ASSERT(tcp->tcp_rthdrlen == 0);
4365 
4366 	ipp = &tcp->tcp_sticky_ipp;
4367 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4368 	    IPPF_RTHDR))
4369 		ip6_pkt_free(ipp);
4370 
4371 	/*
4372 	 * Free memory associated with the tcp/ip header template.
4373 	 */
4374 
4375 	if (tcp->tcp_iphc != NULL)
4376 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4377 
4378 	/*
4379 	 * Following is really a blowing away a union.
4380 	 * It happens to have exactly two members of identical size
4381 	 * the following code is enough.
4382 	 */
4383 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4384 }
4385 
4386 
4387 /*
4388  * Put a connection confirmation message upstream built from the
4389  * address information within 'iph' and 'tcph'.  Report our success or failure.
4390  */
4391 static boolean_t
4392 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4393     mblk_t **defermp)
4394 {
4395 	sin_t	sin;
4396 	sin6_t	sin6;
4397 	mblk_t	*mp;
4398 	char	*optp = NULL;
4399 	int	optlen = 0;
4400 	cred_t	*cr;
4401 
4402 	if (defermp != NULL)
4403 		*defermp = NULL;
4404 
4405 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4406 		/*
4407 		 * Return in T_CONN_CON results of option negotiation through
4408 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4409 		 * negotiation, then what is received from remote end needs
4410 		 * to be taken into account but there is no such thing (yet?)
4411 		 * in our TCP/IP.
4412 		 * Note: We do not use mi_offset_param() here as
4413 		 * tcp_opts_conn_req contents do not directly come from
4414 		 * an application and are either generated in kernel or
4415 		 * from user input that was already verified.
4416 		 */
4417 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4418 		optp = (char *)(mp->b_rptr +
4419 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4420 		optlen = (int)
4421 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4422 	}
4423 
4424 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4425 		ipha_t *ipha = (ipha_t *)iphdr;
4426 
4427 		/* packet is IPv4 */
4428 		if (tcp->tcp_family == AF_INET) {
4429 			sin = sin_null;
4430 			sin.sin_addr.s_addr = ipha->ipha_src;
4431 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4432 			sin.sin_family = AF_INET;
4433 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4434 			    (int)sizeof (sin_t), optp, optlen);
4435 		} else {
4436 			sin6 = sin6_null;
4437 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4438 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4439 			sin6.sin6_family = AF_INET6;
4440 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4441 			    (int)sizeof (sin6_t), optp, optlen);
4442 
4443 		}
4444 	} else {
4445 		ip6_t	*ip6h = (ip6_t *)iphdr;
4446 
4447 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4448 		ASSERT(tcp->tcp_family == AF_INET6);
4449 		sin6 = sin6_null;
4450 		sin6.sin6_addr = ip6h->ip6_src;
4451 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4452 		sin6.sin6_family = AF_INET6;
4453 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4454 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4455 		    (int)sizeof (sin6_t), optp, optlen);
4456 	}
4457 
4458 	if (!mp)
4459 		return (B_FALSE);
4460 
4461 	if ((cr = DB_CRED(idmp)) != NULL) {
4462 		mblk_setcred(mp, cr);
4463 		DB_CPID(mp) = DB_CPID(idmp);
4464 	}
4465 
4466 	if (defermp == NULL) {
4467 		conn_t *connp = tcp->tcp_connp;
4468 		if (IPCL_IS_NONSTR(connp)) {
4469 			(*connp->conn_upcalls->su_connected)
4470 			    (connp->conn_upper_handle, tcp->tcp_connid, cr,
4471 			    DB_CPID(mp));
4472 			freemsg(mp);
4473 		} else {
4474 			putnext(tcp->tcp_rq, mp);
4475 		}
4476 	} else {
4477 		*defermp = mp;
4478 	}
4479 
4480 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4481 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4482 	return (B_TRUE);
4483 }
4484 
4485 /*
4486  * Defense for the SYN attack -
4487  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4488  *    one from the list of droppable eagers. This list is a subset of q0.
4489  *    see comments before the definition of MAKE_DROPPABLE().
4490  * 2. Don't drop a SYN request before its first timeout. This gives every
4491  *    request at least til the first timeout to complete its 3-way handshake.
4492  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4493  *    requests currently on the queue that has timed out. This will be used
4494  *    as an indicator of whether an attack is under way, so that appropriate
4495  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4496  *    either when eager goes into ESTABLISHED, or gets freed up.)
4497  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4498  *    # of timeout drops back to <= q0len/32 => SYN alert off
4499  */
4500 static boolean_t
4501 tcp_drop_q0(tcp_t *tcp)
4502 {
4503 	tcp_t	*eager;
4504 	mblk_t	*mp;
4505 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4506 
4507 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4508 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4509 
4510 	/* Pick oldest eager from the list of droppable eagers */
4511 	eager = tcp->tcp_eager_prev_drop_q0;
4512 
4513 	/* If list is empty. return B_FALSE */
4514 	if (eager == tcp) {
4515 		return (B_FALSE);
4516 	}
4517 
4518 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4519 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4520 		return (B_FALSE);
4521 
4522 	/*
4523 	 * Take this eager out from the list of droppable eagers since we are
4524 	 * going to drop it.
4525 	 */
4526 	MAKE_UNDROPPABLE(eager);
4527 
4528 	if (tcp->tcp_debug) {
4529 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4530 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4531 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4532 		    tcp->tcp_conn_req_cnt_q0,
4533 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4534 	}
4535 
4536 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4537 
4538 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4539 	CONN_INC_REF(eager->tcp_connp);
4540 
4541 	/* Mark the IRE created for this SYN request temporary */
4542 	tcp_ip_ire_mark_advice(eager);
4543 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4544 	    tcp_clean_death_wrapper, eager->tcp_connp,
4545 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4546 
4547 	return (B_TRUE);
4548 }
4549 
4550 int
4551 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4552     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4553 {
4554 	tcp_t 		*ltcp = lconnp->conn_tcp;
4555 	tcp_t		*tcp = connp->conn_tcp;
4556 	mblk_t		*tpi_mp;
4557 	ipha_t		*ipha;
4558 	ip6_t		*ip6h;
4559 	sin6_t 		sin6;
4560 	in6_addr_t 	v6dst;
4561 	int		err;
4562 	int		ifindex = 0;
4563 	cred_t		*cr;
4564 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4565 
4566 	if (ipvers == IPV4_VERSION) {
4567 		ipha = (ipha_t *)mp->b_rptr;
4568 
4569 		connp->conn_send = ip_output;
4570 		connp->conn_recv = tcp_input;
4571 
4572 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4573 		    &connp->conn_bound_source_v6);
4574 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4575 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4576 
4577 		sin6 = sin6_null;
4578 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4579 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4580 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4581 		sin6.sin6_family = AF_INET6;
4582 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4583 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4584 		if (tcp->tcp_recvdstaddr) {
4585 			sin6_t	sin6d;
4586 
4587 			sin6d = sin6_null;
4588 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4589 			    &sin6d.sin6_addr);
4590 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4591 			sin6d.sin6_family = AF_INET;
4592 			tpi_mp = mi_tpi_extconn_ind(NULL,
4593 			    (char *)&sin6d, sizeof (sin6_t),
4594 			    (char *)&tcp,
4595 			    (t_scalar_t)sizeof (intptr_t),
4596 			    (char *)&sin6d, sizeof (sin6_t),
4597 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4598 		} else {
4599 			tpi_mp = mi_tpi_conn_ind(NULL,
4600 			    (char *)&sin6, sizeof (sin6_t),
4601 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4602 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4603 		}
4604 	} else {
4605 		ip6h = (ip6_t *)mp->b_rptr;
4606 
4607 		connp->conn_send = ip_output_v6;
4608 		connp->conn_recv = tcp_input;
4609 
4610 		connp->conn_bound_source_v6 = ip6h->ip6_dst;
4611 		connp->conn_srcv6 = ip6h->ip6_dst;
4612 		connp->conn_remv6 = ip6h->ip6_src;
4613 
4614 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4615 		ifindex = (int)DB_CKSUMSTUFF(mp);
4616 		DB_CKSUMSTUFF(mp) = 0;
4617 
4618 		sin6 = sin6_null;
4619 		sin6.sin6_addr = ip6h->ip6_src;
4620 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4621 		sin6.sin6_family = AF_INET6;
4622 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4623 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4624 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4625 
4626 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4627 			/* Pass up the scope_id of remote addr */
4628 			sin6.sin6_scope_id = ifindex;
4629 		} else {
4630 			sin6.sin6_scope_id = 0;
4631 		}
4632 		if (tcp->tcp_recvdstaddr) {
4633 			sin6_t	sin6d;
4634 
4635 			sin6d = sin6_null;
4636 			sin6.sin6_addr = ip6h->ip6_dst;
4637 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4638 			sin6d.sin6_family = AF_INET;
4639 			tpi_mp = mi_tpi_extconn_ind(NULL,
4640 			    (char *)&sin6d, sizeof (sin6_t),
4641 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4642 			    (char *)&sin6d, sizeof (sin6_t),
4643 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4644 		} else {
4645 			tpi_mp = mi_tpi_conn_ind(NULL,
4646 			    (char *)&sin6, sizeof (sin6_t),
4647 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4648 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4649 		}
4650 	}
4651 
4652 	if (tpi_mp == NULL)
4653 		return (ENOMEM);
4654 
4655 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4656 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4657 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4658 	connp->conn_fully_bound = B_FALSE;
4659 
4660 	/* Inherit information from the "parent" */
4661 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4662 	tcp->tcp_family = ltcp->tcp_family;
4663 
4664 	tcp->tcp_wq = ltcp->tcp_wq;
4665 	tcp->tcp_rq = ltcp->tcp_rq;
4666 
4667 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4668 	tcp->tcp_detached = B_TRUE;
4669 	SOCK_CONNID_INIT(tcp->tcp_connid);
4670 	if ((err = tcp_init_values(tcp)) != 0) {
4671 		freemsg(tpi_mp);
4672 		return (err);
4673 	}
4674 
4675 	if (ipvers == IPV4_VERSION) {
4676 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4677 			freemsg(tpi_mp);
4678 			return (err);
4679 		}
4680 		ASSERT(tcp->tcp_ipha != NULL);
4681 	} else {
4682 		/* ifindex must be already set */
4683 		ASSERT(ifindex != 0);
4684 
4685 		if (ltcp->tcp_bound_if != 0)
4686 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4687 		else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src))
4688 			tcp->tcp_bound_if = ifindex;
4689 
4690 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4691 		tcp->tcp_recvifindex = 0;
4692 		tcp->tcp_recvhops = 0xffffffffU;
4693 		ASSERT(tcp->tcp_ip6h != NULL);
4694 	}
4695 
4696 	tcp->tcp_lport = ltcp->tcp_lport;
4697 
4698 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4699 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4700 			/*
4701 			 * Listener had options of some sort; eager inherits.
4702 			 * Free up the eager template and allocate one
4703 			 * of the right size.
4704 			 */
4705 			if (tcp->tcp_hdr_grown) {
4706 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4707 			} else {
4708 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4709 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4710 			}
4711 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4712 			    KM_NOSLEEP);
4713 			if (tcp->tcp_iphc == NULL) {
4714 				tcp->tcp_iphc_len = 0;
4715 				freemsg(tpi_mp);
4716 				return (ENOMEM);
4717 			}
4718 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4719 			tcp->tcp_hdr_grown = B_TRUE;
4720 		}
4721 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4722 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4723 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4724 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4725 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4726 
4727 		/*
4728 		 * Copy the IP+TCP header template from listener to eager
4729 		 */
4730 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4731 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4732 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4733 			    IPPROTO_RAW) {
4734 				tcp->tcp_ip6h =
4735 				    (ip6_t *)(tcp->tcp_iphc +
4736 				    sizeof (ip6i_t));
4737 			} else {
4738 				tcp->tcp_ip6h =
4739 				    (ip6_t *)(tcp->tcp_iphc);
4740 			}
4741 			tcp->tcp_ipha = NULL;
4742 		} else {
4743 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4744 			tcp->tcp_ip6h = NULL;
4745 		}
4746 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4747 		    tcp->tcp_ip_hdr_len);
4748 	} else {
4749 		/*
4750 		 * only valid case when ipversion of listener and
4751 		 * eager differ is when listener is IPv6 and
4752 		 * eager is IPv4.
4753 		 * Eager header template has been initialized to the
4754 		 * maximum v4 header sizes, which includes space for
4755 		 * TCP and IP options.
4756 		 */
4757 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4758 		    (tcp->tcp_ipversion == IPV4_VERSION));
4759 		ASSERT(tcp->tcp_iphc_len >=
4760 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4761 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4762 		/* copy IP header fields individually */
4763 		tcp->tcp_ipha->ipha_ttl =
4764 		    ltcp->tcp_ip6h->ip6_hops;
4765 		bcopy(ltcp->tcp_tcph->th_lport,
4766 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4767 	}
4768 
4769 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4770 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4771 	    sizeof (in_port_t));
4772 
4773 	if (ltcp->tcp_lport == 0) {
4774 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4775 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4776 		    sizeof (in_port_t));
4777 	}
4778 
4779 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4780 		ASSERT(ipha != NULL);
4781 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4782 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4783 
4784 		/* Source routing option copyover (reverse it) */
4785 		if (tcps->tcps_rev_src_routes)
4786 			tcp_opt_reverse(tcp, ipha);
4787 	} else {
4788 		ASSERT(ip6h != NULL);
4789 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4790 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4791 	}
4792 
4793 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4794 	ASSERT(!tcp->tcp_tconnind_started);
4795 	/*
4796 	 * If the SYN contains a credential, it's a loopback packet; attach
4797 	 * the credential to the TPI message.
4798 	 */
4799 	if ((cr = DB_CRED(idmp)) != NULL) {
4800 		mblk_setcred(tpi_mp, cr);
4801 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4802 	}
4803 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4804 
4805 	/* Inherit the listener's SSL protection state */
4806 
4807 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4808 		kssl_hold_ent(tcp->tcp_kssl_ent);
4809 		tcp->tcp_kssl_pending = B_TRUE;
4810 	}
4811 
4812 	/* Inherit the listener's non-STREAMS flag */
4813 	if (IPCL_IS_NONSTR(lconnp)) {
4814 		connp->conn_flags |= IPCL_NONSTR;
4815 		connp->conn_upcalls = lconnp->conn_upcalls;
4816 	}
4817 
4818 	return (0);
4819 }
4820 
4821 
4822 int
4823 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4824     tcph_t *tcph, mblk_t *idmp)
4825 {
4826 	tcp_t 		*ltcp = lconnp->conn_tcp;
4827 	tcp_t		*tcp = connp->conn_tcp;
4828 	sin_t		sin;
4829 	mblk_t		*tpi_mp = NULL;
4830 	int		err;
4831 	cred_t		*cr;
4832 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4833 
4834 	sin = sin_null;
4835 	sin.sin_addr.s_addr = ipha->ipha_src;
4836 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4837 	sin.sin_family = AF_INET;
4838 	if (ltcp->tcp_recvdstaddr) {
4839 		sin_t	sind;
4840 
4841 		sind = sin_null;
4842 		sind.sin_addr.s_addr = ipha->ipha_dst;
4843 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4844 		sind.sin_family = AF_INET;
4845 		tpi_mp = mi_tpi_extconn_ind(NULL,
4846 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4847 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4848 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4849 	} else {
4850 		tpi_mp = mi_tpi_conn_ind(NULL,
4851 		    (char *)&sin, sizeof (sin_t),
4852 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4853 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4854 	}
4855 
4856 	if (tpi_mp == NULL) {
4857 		return (ENOMEM);
4858 	}
4859 
4860 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4861 	connp->conn_send = ip_output;
4862 	connp->conn_recv = tcp_input;
4863 	connp->conn_fully_bound = B_FALSE;
4864 
4865 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_bound_source_v6);
4866 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4867 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4868 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4869 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4870 
4871 	/* Inherit information from the "parent" */
4872 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4873 	tcp->tcp_family = ltcp->tcp_family;
4874 	tcp->tcp_wq = ltcp->tcp_wq;
4875 	tcp->tcp_rq = ltcp->tcp_rq;
4876 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4877 	tcp->tcp_detached = B_TRUE;
4878 	SOCK_CONNID_INIT(tcp->tcp_connid);
4879 	if ((err = tcp_init_values(tcp)) != 0) {
4880 		freemsg(tpi_mp);
4881 		return (err);
4882 	}
4883 
4884 	/*
4885 	 * Let's make sure that eager tcp template has enough space to
4886 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4887 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4888 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4889 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4890 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4891 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4892 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4893 	 */
4894 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4895 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4896 
4897 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4898 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4899 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4900 	tcp->tcp_ttl = ltcp->tcp_ttl;
4901 	tcp->tcp_tos = ltcp->tcp_tos;
4902 
4903 	/* Copy the IP+TCP header template from listener to eager */
4904 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4905 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4906 	tcp->tcp_ip6h = NULL;
4907 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4908 	    tcp->tcp_ip_hdr_len);
4909 
4910 	/* Initialize the IP addresses and Ports */
4911 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4912 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4913 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4914 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4915 
4916 	/* Source routing option copyover (reverse it) */
4917 	if (tcps->tcps_rev_src_routes)
4918 		tcp_opt_reverse(tcp, ipha);
4919 
4920 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4921 	ASSERT(!tcp->tcp_tconnind_started);
4922 
4923 	/*
4924 	 * If the SYN contains a credential, it's a loopback packet; attach
4925 	 * the credential to the TPI message.
4926 	 */
4927 	if ((cr = DB_CRED(idmp)) != NULL) {
4928 		mblk_setcred(tpi_mp, cr);
4929 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4930 	}
4931 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4932 
4933 	/* Inherit the listener's SSL protection state */
4934 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4935 		kssl_hold_ent(tcp->tcp_kssl_ent);
4936 		tcp->tcp_kssl_pending = B_TRUE;
4937 	}
4938 
4939 	/* Inherit the listener's non-STREAMS flag */
4940 	if (IPCL_IS_NONSTR(lconnp)) {
4941 		connp->conn_flags |= IPCL_NONSTR;
4942 		connp->conn_upcalls = lconnp->conn_upcalls;
4943 	}
4944 
4945 	return (0);
4946 }
4947 
4948 /*
4949  * sets up conn for ipsec.
4950  * if the first mblk is M_CTL it is consumed and mpp is updated.
4951  * in case of error mpp is freed.
4952  */
4953 conn_t *
4954 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4955 {
4956 	conn_t 		*connp = tcp->tcp_connp;
4957 	conn_t 		*econnp;
4958 	squeue_t 	*new_sqp;
4959 	mblk_t 		*first_mp = *mpp;
4960 	mblk_t		*mp = *mpp;
4961 	boolean_t	mctl_present = B_FALSE;
4962 	uint_t		ipvers;
4963 
4964 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
4965 	if (econnp == NULL) {
4966 		freemsg(first_mp);
4967 		return (NULL);
4968 	}
4969 	if (DB_TYPE(mp) == M_CTL) {
4970 		if (mp->b_cont == NULL ||
4971 		    mp->b_cont->b_datap->db_type != M_DATA) {
4972 			freemsg(first_mp);
4973 			return (NULL);
4974 		}
4975 		mp = mp->b_cont;
4976 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4977 			freemsg(first_mp);
4978 			return (NULL);
4979 		}
4980 
4981 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4982 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4983 		mctl_present = B_TRUE;
4984 	} else {
4985 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4986 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4987 	}
4988 
4989 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4990 	DB_CKSUMSTART(mp) = 0;
4991 
4992 	ASSERT(OK_32PTR(mp->b_rptr));
4993 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
4994 	if (ipvers == IPV4_VERSION) {
4995 		uint16_t  	*up;
4996 		uint32_t	ports;
4997 		ipha_t		*ipha;
4998 
4999 		ipha = (ipha_t *)mp->b_rptr;
5000 		up = (uint16_t *)((uchar_t *)ipha +
5001 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5002 		ports = *(uint32_t *)up;
5003 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5004 		    ipha->ipha_dst, ipha->ipha_src, ports);
5005 	} else {
5006 		uint16_t  	*up;
5007 		uint32_t	ports;
5008 		uint16_t	ip_hdr_len;
5009 		uint8_t		*nexthdrp;
5010 		ip6_t 		*ip6h;
5011 		tcph_t		*tcph;
5012 
5013 		ip6h = (ip6_t *)mp->b_rptr;
5014 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5015 			ip_hdr_len = IPV6_HDR_LEN;
5016 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5017 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5018 			CONN_DEC_REF(econnp);
5019 			freemsg(first_mp);
5020 			return (NULL);
5021 		}
5022 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5023 		up = (uint16_t *)tcph->th_lport;
5024 		ports = *(uint32_t *)up;
5025 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5026 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5027 	}
5028 
5029 	/*
5030 	 * The caller already ensured that there is a sqp present.
5031 	 */
5032 	econnp->conn_sqp = new_sqp;
5033 	econnp->conn_initial_sqp = new_sqp;
5034 
5035 	if (connp->conn_policy != NULL) {
5036 		ipsec_in_t *ii;
5037 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5038 		ASSERT(ii->ipsec_in_policy == NULL);
5039 		IPPH_REFHOLD(connp->conn_policy);
5040 		ii->ipsec_in_policy = connp->conn_policy;
5041 
5042 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5043 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5044 			CONN_DEC_REF(econnp);
5045 			freemsg(first_mp);
5046 			return (NULL);
5047 		}
5048 	}
5049 
5050 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5051 		CONN_DEC_REF(econnp);
5052 		freemsg(first_mp);
5053 		return (NULL);
5054 	}
5055 
5056 	/*
5057 	 * If we know we have some policy, pass the "IPSEC"
5058 	 * options size TCP uses this adjust the MSS.
5059 	 */
5060 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5061 	if (mctl_present) {
5062 		freeb(first_mp);
5063 		*mpp = mp;
5064 	}
5065 
5066 	return (econnp);
5067 }
5068 
5069 /*
5070  * tcp_get_conn/tcp_free_conn
5071  *
5072  * tcp_get_conn is used to get a clean tcp connection structure.
5073  * It tries to reuse the connections put on the freelist by the
5074  * time_wait_collector failing which it goes to kmem_cache. This
5075  * way has two benefits compared to just allocating from and
5076  * freeing to kmem_cache.
5077  * 1) The time_wait_collector can free (which includes the cleanup)
5078  * outside the squeue. So when the interrupt comes, we have a clean
5079  * connection sitting in the freelist. Obviously, this buys us
5080  * performance.
5081  *
5082  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5083  * has multiple disadvantages - tying up the squeue during alloc, and the
5084  * fact that IPSec policy initialization has to happen here which
5085  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5086  * But allocating the conn/tcp in IP land is also not the best since
5087  * we can't check the 'q' and 'q0' which are protected by squeue and
5088  * blindly allocate memory which might have to be freed here if we are
5089  * not allowed to accept the connection. By using the freelist and
5090  * putting the conn/tcp back in freelist, we don't pay a penalty for
5091  * allocating memory without checking 'q/q0' and freeing it if we can't
5092  * accept the connection.
5093  *
5094  * Care should be taken to put the conn back in the same squeue's freelist
5095  * from which it was allocated. Best results are obtained if conn is
5096  * allocated from listener's squeue and freed to the same. Time wait
5097  * collector will free up the freelist is the connection ends up sitting
5098  * there for too long.
5099  */
5100 void *
5101 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5102 {
5103 	tcp_t			*tcp = NULL;
5104 	conn_t			*connp = NULL;
5105 	squeue_t		*sqp = (squeue_t *)arg;
5106 	tcp_squeue_priv_t 	*tcp_time_wait;
5107 	netstack_t		*ns;
5108 
5109 	tcp_time_wait =
5110 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5111 
5112 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5113 	tcp = tcp_time_wait->tcp_free_list;
5114 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5115 	if (tcp != NULL) {
5116 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5117 		tcp_time_wait->tcp_free_list_cnt--;
5118 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5119 		tcp->tcp_time_wait_next = NULL;
5120 		connp = tcp->tcp_connp;
5121 		connp->conn_flags |= IPCL_REUSED;
5122 
5123 		ASSERT(tcp->tcp_tcps == NULL);
5124 		ASSERT(connp->conn_netstack == NULL);
5125 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5126 		ns = tcps->tcps_netstack;
5127 		netstack_hold(ns);
5128 		connp->conn_netstack = ns;
5129 		tcp->tcp_tcps = tcps;
5130 		TCPS_REFHOLD(tcps);
5131 		ipcl_globalhash_insert(connp);
5132 		return ((void *)connp);
5133 	}
5134 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5135 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5136 	    tcps->tcps_netstack)) == NULL)
5137 		return (NULL);
5138 	tcp = connp->conn_tcp;
5139 	/*
5140 	 * Pre-allocate the tcp_rsrv_mp.  This mblk will not be freed
5141 	 * until this conn_t/tcp_t is freed at ipcl_conn_destroy().
5142 	 */
5143 	if ((tcp->tcp_rsrv_mp = allocb(0, BPRI_HI)) == NULL) {
5144 		ipcl_conn_destroy(connp);
5145 		return (NULL);
5146 	}
5147 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5148 	tcp->tcp_tcps = tcps;
5149 	TCPS_REFHOLD(tcps);
5150 
5151 	return ((void *)connp);
5152 }
5153 
5154 /*
5155  * Update the cached label for the given tcp_t.  This should be called once per
5156  * connection, and before any packets are sent or tcp_process_options is
5157  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5158  */
5159 static boolean_t
5160 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5161 {
5162 	conn_t *connp = tcp->tcp_connp;
5163 
5164 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5165 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5166 		int added;
5167 
5168 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5169 		    connp->conn_mac_exempt,
5170 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5171 			return (B_FALSE);
5172 
5173 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5174 		if (added == -1)
5175 			return (B_FALSE);
5176 		tcp->tcp_hdr_len += added;
5177 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5178 		tcp->tcp_ip_hdr_len += added;
5179 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5180 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5181 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5182 			    tcp->tcp_hdr_len);
5183 			if (added == -1)
5184 				return (B_FALSE);
5185 			tcp->tcp_hdr_len += added;
5186 			tcp->tcp_tcph = (tcph_t *)
5187 			    ((uchar_t *)tcp->tcp_tcph + added);
5188 			tcp->tcp_ip_hdr_len += added;
5189 		}
5190 	} else {
5191 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5192 
5193 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5194 		    connp->conn_mac_exempt,
5195 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5196 			return (B_FALSE);
5197 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5198 		    &tcp->tcp_label_len, optbuf) != 0)
5199 			return (B_FALSE);
5200 		if (tcp_build_hdrs(tcp) != 0)
5201 			return (B_FALSE);
5202 	}
5203 
5204 	connp->conn_ulp_labeled = 1;
5205 
5206 	return (B_TRUE);
5207 }
5208 
5209 /* BEGIN CSTYLED */
5210 /*
5211  *
5212  * The sockfs ACCEPT path:
5213  * =======================
5214  *
5215  * The eager is now established in its own perimeter as soon as SYN is
5216  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5217  * completes the accept processing on the acceptor STREAM. The sending
5218  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5219  * listener but a TLI/XTI listener completes the accept processing
5220  * on the listener perimeter.
5221  *
5222  * Common control flow for 3 way handshake:
5223  * ----------------------------------------
5224  *
5225  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5226  *					-> tcp_conn_request()
5227  *
5228  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5229  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5230  *
5231  * Sockfs ACCEPT Path:
5232  * -------------------
5233  *
5234  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5235  * as STREAM entry point)
5236  *
5237  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5238  *
5239  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5240  * association (we are not behind eager's squeue but sockfs is protecting us
5241  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5242  * is changed to point at tcp_wput().
5243  *
5244  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5245  * listener (done on listener's perimeter).
5246  *
5247  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5248  * accept.
5249  *
5250  * TLI/XTI client ACCEPT path:
5251  * ---------------------------
5252  *
5253  * soaccept() sends T_CONN_RES on the listener STREAM.
5254  *
5255  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5256  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5257  *
5258  * Locks:
5259  * ======
5260  *
5261  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5262  * and listeners->tcp_eager_next_q.
5263  *
5264  * Referencing:
5265  * ============
5266  *
5267  * 1) We start out in tcp_conn_request by eager placing a ref on
5268  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5269  *
5270  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5271  * doing so we place a ref on the eager. This ref is finally dropped at the
5272  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5273  * reference is dropped by the squeue framework.
5274  *
5275  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5276  *
5277  * The reference must be released by the same entity that added the reference
5278  * In the above scheme, the eager is the entity that adds and releases the
5279  * references. Note that tcp_accept_finish executes in the squeue of the eager
5280  * (albeit after it is attached to the acceptor stream). Though 1. executes
5281  * in the listener's squeue, the eager is nascent at this point and the
5282  * reference can be considered to have been added on behalf of the eager.
5283  *
5284  * Eager getting a Reset or listener closing:
5285  * ==========================================
5286  *
5287  * Once the listener and eager are linked, the listener never does the unlink.
5288  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5289  * a message on all eager perimeter. The eager then does the unlink, clears
5290  * any pointers to the listener's queue and drops the reference to the
5291  * listener. The listener waits in tcp_close outside the squeue until its
5292  * refcount has dropped to 1. This ensures that the listener has waited for
5293  * all eagers to clear their association with the listener.
5294  *
5295  * Similarly, if eager decides to go away, it can unlink itself and close.
5296  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5297  * the reference to eager is still valid because of the extra ref we put
5298  * in tcp_send_conn_ind.
5299  *
5300  * Listener can always locate the eager under the protection
5301  * of the listener->tcp_eager_lock, and then do a refhold
5302  * on the eager during the accept processing.
5303  *
5304  * The acceptor stream accesses the eager in the accept processing
5305  * based on the ref placed on eager before sending T_conn_ind.
5306  * The only entity that can negate this refhold is a listener close
5307  * which is mutually exclusive with an active acceptor stream.
5308  *
5309  * Eager's reference on the listener
5310  * ===================================
5311  *
5312  * If the accept happens (even on a closed eager) the eager drops its
5313  * reference on the listener at the start of tcp_accept_finish. If the
5314  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5315  * the reference is dropped in tcp_closei_local. If the listener closes,
5316  * the reference is dropped in tcp_eager_kill. In all cases the reference
5317  * is dropped while executing in the eager's context (squeue).
5318  */
5319 /* END CSTYLED */
5320 
5321 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5322 
5323 /*
5324  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5325  * tcp_rput_data will not see any SYN packets.
5326  */
5327 /* ARGSUSED */
5328 void
5329 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5330 {
5331 	tcph_t		*tcph;
5332 	uint32_t	seg_seq;
5333 	tcp_t		*eager;
5334 	uint_t		ipvers;
5335 	ipha_t		*ipha;
5336 	ip6_t		*ip6h;
5337 	int		err;
5338 	conn_t		*econnp = NULL;
5339 	squeue_t	*new_sqp;
5340 	mblk_t		*mp1;
5341 	uint_t 		ip_hdr_len;
5342 	conn_t		*connp = (conn_t *)arg;
5343 	tcp_t		*tcp = connp->conn_tcp;
5344 	cred_t		*credp;
5345 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5346 	ip_stack_t	*ipst;
5347 
5348 	if (tcp->tcp_state != TCPS_LISTEN)
5349 		goto error2;
5350 
5351 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5352 
5353 	mutex_enter(&tcp->tcp_eager_lock);
5354 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5355 		mutex_exit(&tcp->tcp_eager_lock);
5356 		TCP_STAT(tcps, tcp_listendrop);
5357 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5358 		if (tcp->tcp_debug) {
5359 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5360 			    "tcp_conn_request: listen backlog (max=%d) "
5361 			    "overflow (%d pending) on %s",
5362 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5363 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5364 		}
5365 		goto error2;
5366 	}
5367 
5368 	if (tcp->tcp_conn_req_cnt_q0 >=
5369 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5370 		/*
5371 		 * Q0 is full. Drop a pending half-open req from the queue
5372 		 * to make room for the new SYN req. Also mark the time we
5373 		 * drop a SYN.
5374 		 *
5375 		 * A more aggressive defense against SYN attack will
5376 		 * be to set the "tcp_syn_defense" flag now.
5377 		 */
5378 		TCP_STAT(tcps, tcp_listendropq0);
5379 		tcp->tcp_last_rcv_lbolt = lbolt64;
5380 		if (!tcp_drop_q0(tcp)) {
5381 			mutex_exit(&tcp->tcp_eager_lock);
5382 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5383 			if (tcp->tcp_debug) {
5384 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5385 				    "tcp_conn_request: listen half-open queue "
5386 				    "(max=%d) full (%d pending) on %s",
5387 				    tcps->tcps_conn_req_max_q0,
5388 				    tcp->tcp_conn_req_cnt_q0,
5389 				    tcp_display(tcp, NULL,
5390 				    DISP_PORT_ONLY));
5391 			}
5392 			goto error2;
5393 		}
5394 	}
5395 	mutex_exit(&tcp->tcp_eager_lock);
5396 
5397 	/*
5398 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5399 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5400 	 * link local address.  If IPSec is enabled, db_struioflag has
5401 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5402 	 * otherwise an error case if neither of them is set.
5403 	 */
5404 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5405 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5406 		DB_CKSUMSTART(mp) = 0;
5407 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5408 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5409 		if (econnp == NULL)
5410 			goto error2;
5411 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5412 		econnp->conn_sqp = new_sqp;
5413 		econnp->conn_initial_sqp = new_sqp;
5414 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5415 		/*
5416 		 * mp is updated in tcp_get_ipsec_conn().
5417 		 */
5418 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5419 		if (econnp == NULL) {
5420 			/*
5421 			 * mp freed by tcp_get_ipsec_conn.
5422 			 */
5423 			return;
5424 		}
5425 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5426 	} else {
5427 		goto error2;
5428 	}
5429 
5430 	ASSERT(DB_TYPE(mp) == M_DATA);
5431 
5432 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5433 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5434 	ASSERT(OK_32PTR(mp->b_rptr));
5435 	if (ipvers == IPV4_VERSION) {
5436 		ipha = (ipha_t *)mp->b_rptr;
5437 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5438 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5439 	} else {
5440 		ip6h = (ip6_t *)mp->b_rptr;
5441 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5442 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5443 	}
5444 
5445 	if (tcp->tcp_family == AF_INET) {
5446 		ASSERT(ipvers == IPV4_VERSION);
5447 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5448 	} else {
5449 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5450 	}
5451 
5452 	if (err)
5453 		goto error3;
5454 
5455 	eager = econnp->conn_tcp;
5456 
5457 	/*
5458 	 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that at close
5459 	 * time, we will always have that to send up.  Otherwise, we need to do
5460 	 * special handling in case the allocation fails at that time.
5461 	 */
5462 	ASSERT(eager->tcp_ordrel_mp == NULL);
5463 	if (!IPCL_IS_NONSTR(econnp) &&
5464 	    (eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5465 		goto error3;
5466 
5467 	/* Inherit various TCP parameters from the listener */
5468 	eager->tcp_naglim = tcp->tcp_naglim;
5469 	eager->tcp_first_timer_threshold =
5470 	    tcp->tcp_first_timer_threshold;
5471 	eager->tcp_second_timer_threshold =
5472 	    tcp->tcp_second_timer_threshold;
5473 
5474 	eager->tcp_first_ctimer_threshold =
5475 	    tcp->tcp_first_ctimer_threshold;
5476 	eager->tcp_second_ctimer_threshold =
5477 	    tcp->tcp_second_ctimer_threshold;
5478 
5479 	/*
5480 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5481 	 * If it does not, the eager's receive window will be set to the
5482 	 * listener's receive window later in this function.
5483 	 */
5484 	eager->tcp_rwnd = 0;
5485 
5486 	/*
5487 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5488 	 * calling tcp_process_options() where tcp_mss_set() is called
5489 	 * to set the initial cwnd.
5490 	 */
5491 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5492 
5493 	/*
5494 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5495 	 * zone id before the accept is completed in tcp_wput_accept().
5496 	 */
5497 	econnp->conn_zoneid = connp->conn_zoneid;
5498 	econnp->conn_allzones = connp->conn_allzones;
5499 
5500 	/* Copy nexthop information from listener to eager */
5501 	if (connp->conn_nexthop_set) {
5502 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5503 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5504 	}
5505 
5506 	/*
5507 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5508 	 * eager is accepted
5509 	 */
5510 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5511 	crhold(credp);
5512 
5513 	/*
5514 	 * If the caller has the process-wide flag set, then default to MAC
5515 	 * exempt mode.  This allows read-down to unlabeled hosts.
5516 	 */
5517 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5518 		econnp->conn_mac_exempt = B_TRUE;
5519 
5520 	if (is_system_labeled()) {
5521 		cred_t *cr;
5522 
5523 		if (connp->conn_mlp_type != mlptSingle) {
5524 			cr = econnp->conn_peercred = DB_CRED(mp);
5525 			if (cr != NULL)
5526 				crhold(cr);
5527 			else
5528 				cr = econnp->conn_cred;
5529 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5530 			    econnp, cred_t *, cr)
5531 		} else {
5532 			cr = econnp->conn_cred;
5533 			DTRACE_PROBE2(syn_accept, conn_t *,
5534 			    econnp, cred_t *, cr)
5535 		}
5536 
5537 		if (!tcp_update_label(eager, cr)) {
5538 			DTRACE_PROBE3(
5539 			    tx__ip__log__error__connrequest__tcp,
5540 			    char *, "eager connp(1) label on SYN mp(2) failed",
5541 			    conn_t *, econnp, mblk_t *, mp);
5542 			goto error3;
5543 		}
5544 	}
5545 
5546 	eager->tcp_hard_binding = B_TRUE;
5547 
5548 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5549 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5550 
5551 	CL_INET_CONNECT(connp, eager, B_FALSE, err);
5552 	if (err != 0) {
5553 		tcp_bind_hash_remove(eager);
5554 		goto error3;
5555 	}
5556 
5557 	/*
5558 	 * No need to check for multicast destination since ip will only pass
5559 	 * up multicasts to those that have expressed interest
5560 	 * TODO: what about rejecting broadcasts?
5561 	 * Also check that source is not a multicast or broadcast address.
5562 	 */
5563 	eager->tcp_state = TCPS_SYN_RCVD;
5564 
5565 
5566 	/*
5567 	 * There should be no ire in the mp as we are being called after
5568 	 * receiving the SYN.
5569 	 */
5570 	ASSERT(tcp_ire_mp(&mp) == NULL);
5571 
5572 	/*
5573 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5574 	 */
5575 
5576 	if (tcp_adapt_ire(eager, NULL) == 0) {
5577 		/* Undo the bind_hash_insert */
5578 		tcp_bind_hash_remove(eager);
5579 		goto error3;
5580 	}
5581 
5582 	/* Process all TCP options. */
5583 	tcp_process_options(eager, tcph);
5584 
5585 	/* Is the other end ECN capable? */
5586 	if (tcps->tcps_ecn_permitted >= 1 &&
5587 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5588 		eager->tcp_ecn_ok = B_TRUE;
5589 	}
5590 
5591 	/*
5592 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5593 	 * window size changed via SO_RCVBUF option.  First round up the
5594 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5595 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5596 	 * setting.
5597 	 *
5598 	 * Note if there is a rpipe metric associated with the remote host,
5599 	 * we should not inherit receive window size from listener.
5600 	 */
5601 	eager->tcp_rwnd = MSS_ROUNDUP(
5602 	    (eager->tcp_rwnd == 0 ? tcp->tcp_recv_hiwater:
5603 	    eager->tcp_rwnd), eager->tcp_mss);
5604 	if (eager->tcp_snd_ws_ok)
5605 		tcp_set_ws_value(eager);
5606 	/*
5607 	 * Note that this is the only place tcp_rwnd_set() is called for
5608 	 * accepting a connection.  We need to call it here instead of
5609 	 * after the 3-way handshake because we need to tell the other
5610 	 * side our rwnd in the SYN-ACK segment.
5611 	 */
5612 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5613 
5614 	/*
5615 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5616 	 * via soaccept()->soinheritoptions() which essentially applies
5617 	 * all the listener options to the new STREAM. The options that we
5618 	 * need to take care of are:
5619 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5620 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5621 	 * SO_SNDBUF, SO_RCVBUF.
5622 	 *
5623 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5624 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5625 	 *		tcp_maxpsz_set() gets called later from
5626 	 *		tcp_accept_finish(), the option takes effect.
5627 	 *
5628 	 */
5629 	/* Set the TCP options */
5630 	eager->tcp_recv_hiwater = tcp->tcp_recv_hiwater;
5631 	eager->tcp_recv_lowater = tcp->tcp_recv_lowater;
5632 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5633 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5634 	eager->tcp_oobinline = tcp->tcp_oobinline;
5635 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5636 	eager->tcp_broadcast = tcp->tcp_broadcast;
5637 	eager->tcp_useloopback = tcp->tcp_useloopback;
5638 	eager->tcp_dontroute = tcp->tcp_dontroute;
5639 	eager->tcp_debug = tcp->tcp_debug;
5640 	eager->tcp_linger = tcp->tcp_linger;
5641 	eager->tcp_lingertime = tcp->tcp_lingertime;
5642 	if (tcp->tcp_ka_enabled)
5643 		eager->tcp_ka_enabled = 1;
5644 
5645 	/* Set the IP options */
5646 	econnp->conn_broadcast = connp->conn_broadcast;
5647 	econnp->conn_loopback = connp->conn_loopback;
5648 	econnp->conn_dontroute = connp->conn_dontroute;
5649 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5650 
5651 	/* Put a ref on the listener for the eager. */
5652 	CONN_INC_REF(connp);
5653 	mutex_enter(&tcp->tcp_eager_lock);
5654 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5655 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5656 	tcp->tcp_eager_next_q0 = eager;
5657 	eager->tcp_eager_prev_q0 = tcp;
5658 
5659 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5660 	eager->tcp_listener = tcp;
5661 	eager->tcp_saved_listener = tcp;
5662 
5663 	/*
5664 	 * Tag this detached tcp vector for later retrieval
5665 	 * by our listener client in tcp_accept().
5666 	 */
5667 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5668 	tcp->tcp_conn_req_cnt_q0++;
5669 	if (++tcp->tcp_conn_req_seqnum == -1) {
5670 		/*
5671 		 * -1 is "special" and defined in TPI as something
5672 		 * that should never be used in T_CONN_IND
5673 		 */
5674 		++tcp->tcp_conn_req_seqnum;
5675 	}
5676 	mutex_exit(&tcp->tcp_eager_lock);
5677 
5678 	if (tcp->tcp_syn_defense) {
5679 		/* Don't drop the SYN that comes from a good IP source */
5680 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5681 		if (addr_cache != NULL && eager->tcp_remote ==
5682 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5683 			eager->tcp_dontdrop = B_TRUE;
5684 		}
5685 	}
5686 
5687 	/*
5688 	 * We need to insert the eager in its own perimeter but as soon
5689 	 * as we do that, we expose the eager to the classifier and
5690 	 * should not touch any field outside the eager's perimeter.
5691 	 * So do all the work necessary before inserting the eager
5692 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5693 	 * will succeed but undo everything if it fails.
5694 	 */
5695 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5696 	eager->tcp_irs = seg_seq;
5697 	eager->tcp_rack = seg_seq;
5698 	eager->tcp_rnxt = seg_seq + 1;
5699 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5700 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5701 	eager->tcp_state = TCPS_SYN_RCVD;
5702 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5703 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5704 	if (mp1 == NULL) {
5705 		/*
5706 		 * Increment the ref count as we are going to
5707 		 * enqueueing an mp in squeue
5708 		 */
5709 		CONN_INC_REF(econnp);
5710 		goto error;
5711 	}
5712 
5713 	DB_CPID(mp1) = tcp->tcp_cpid;
5714 	mblk_setcred(mp1, CONN_CRED(eager->tcp_connp));
5715 	eager->tcp_cpid = tcp->tcp_cpid;
5716 	eager->tcp_open_time = lbolt64;
5717 
5718 	/*
5719 	 * We need to start the rto timer. In normal case, we start
5720 	 * the timer after sending the packet on the wire (or at
5721 	 * least believing that packet was sent by waiting for
5722 	 * CALL_IP_WPUT() to return). Since this is the first packet
5723 	 * being sent on the wire for the eager, our initial tcp_rto
5724 	 * is at least tcp_rexmit_interval_min which is a fairly
5725 	 * large value to allow the algorithm to adjust slowly to large
5726 	 * fluctuations of RTT during first few transmissions.
5727 	 *
5728 	 * Starting the timer first and then sending the packet in this
5729 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5730 	 * is of the order of several 100ms and starting the timer
5731 	 * first and then sending the packet will result in difference
5732 	 * of few micro seconds.
5733 	 *
5734 	 * Without this optimization, we are forced to hold the fanout
5735 	 * lock across the ipcl_bind_insert() and sending the packet
5736 	 * so that we don't race against an incoming packet (maybe RST)
5737 	 * for this eager.
5738 	 *
5739 	 * It is necessary to acquire an extra reference on the eager
5740 	 * at this point and hold it until after tcp_send_data() to
5741 	 * ensure against an eager close race.
5742 	 */
5743 
5744 	CONN_INC_REF(eager->tcp_connp);
5745 
5746 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5747 
5748 	/*
5749 	 * Insert the eager in its own perimeter now. We are ready to deal
5750 	 * with any packets on eager.
5751 	 */
5752 	if (eager->tcp_ipversion == IPV4_VERSION) {
5753 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5754 			goto error;
5755 		}
5756 	} else {
5757 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5758 			goto error;
5759 		}
5760 	}
5761 
5762 	/* mark conn as fully-bound */
5763 	econnp->conn_fully_bound = B_TRUE;
5764 
5765 	/* Send the SYN-ACK */
5766 	tcp_send_data(eager, eager->tcp_wq, mp1);
5767 	CONN_DEC_REF(eager->tcp_connp);
5768 	freemsg(mp);
5769 
5770 	return;
5771 error:
5772 	freemsg(mp1);
5773 	eager->tcp_closemp_used = B_TRUE;
5774 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5775 	mp1 = &eager->tcp_closemp;
5776 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5777 	    econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5778 
5779 	/*
5780 	 * If a connection already exists, send the mp to that connections so
5781 	 * that it can be appropriately dealt with.
5782 	 */
5783 	ipst = tcps->tcps_netstack->netstack_ip;
5784 
5785 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
5786 		if (!IPCL_IS_CONNECTED(econnp)) {
5787 			/*
5788 			 * Something bad happened. ipcl_conn_insert()
5789 			 * failed because a connection already existed
5790 			 * in connected hash but we can't find it
5791 			 * anymore (someone blew it away). Just
5792 			 * free this message and hopefully remote
5793 			 * will retransmit at which time the SYN can be
5794 			 * treated as a new connection or dealth with
5795 			 * a TH_RST if a connection already exists.
5796 			 */
5797 			CONN_DEC_REF(econnp);
5798 			freemsg(mp);
5799 		} else {
5800 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp,
5801 			    tcp_input, econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5802 		}
5803 	} else {
5804 		/* Nobody wants this packet */
5805 		freemsg(mp);
5806 	}
5807 	return;
5808 error3:
5809 	CONN_DEC_REF(econnp);
5810 error2:
5811 	freemsg(mp);
5812 }
5813 
5814 /*
5815  * In an ideal case of vertical partition in NUMA architecture, its
5816  * beneficial to have the listener and all the incoming connections
5817  * tied to the same squeue. The other constraint is that incoming
5818  * connections should be tied to the squeue attached to interrupted
5819  * CPU for obvious locality reason so this leaves the listener to
5820  * be tied to the same squeue. Our only problem is that when listener
5821  * is binding, the CPU that will get interrupted by the NIC whose
5822  * IP address the listener is binding to is not even known. So
5823  * the code below allows us to change that binding at the time the
5824  * CPU is interrupted by virtue of incoming connection's squeue.
5825  *
5826  * This is usefull only in case of a listener bound to a specific IP
5827  * address. For other kind of listeners, they get bound the
5828  * very first time and there is no attempt to rebind them.
5829  */
5830 void
5831 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5832 {
5833 	conn_t		*connp = (conn_t *)arg;
5834 	squeue_t	*sqp = (squeue_t *)arg2;
5835 	squeue_t	*new_sqp;
5836 	uint32_t	conn_flags;
5837 
5838 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5839 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5840 	} else {
5841 		goto done;
5842 	}
5843 
5844 	if (connp->conn_fanout == NULL)
5845 		goto done;
5846 
5847 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5848 		mutex_enter(&connp->conn_fanout->connf_lock);
5849 		mutex_enter(&connp->conn_lock);
5850 		/*
5851 		 * No one from read or write side can access us now
5852 		 * except for already queued packets on this squeue.
5853 		 * But since we haven't changed the squeue yet, they
5854 		 * can't execute. If they are processed after we have
5855 		 * changed the squeue, they are sent back to the
5856 		 * correct squeue down below.
5857 		 * But a listner close can race with processing of
5858 		 * incoming SYN. If incoming SYN processing changes
5859 		 * the squeue then the listener close which is waiting
5860 		 * to enter the squeue would operate on the wrong
5861 		 * squeue. Hence we don't change the squeue here unless
5862 		 * the refcount is exactly the minimum refcount. The
5863 		 * minimum refcount of 4 is counted as - 1 each for
5864 		 * TCP and IP, 1 for being in the classifier hash, and
5865 		 * 1 for the mblk being processed.
5866 		 */
5867 
5868 		if (connp->conn_ref != 4 ||
5869 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5870 			mutex_exit(&connp->conn_lock);
5871 			mutex_exit(&connp->conn_fanout->connf_lock);
5872 			goto done;
5873 		}
5874 		if (connp->conn_sqp != new_sqp) {
5875 			while (connp->conn_sqp != new_sqp)
5876 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5877 		}
5878 
5879 		do {
5880 			conn_flags = connp->conn_flags;
5881 			conn_flags |= IPCL_FULLY_BOUND;
5882 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5883 			    conn_flags);
5884 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5885 
5886 		mutex_exit(&connp->conn_fanout->connf_lock);
5887 		mutex_exit(&connp->conn_lock);
5888 	}
5889 
5890 done:
5891 	if (connp->conn_sqp != sqp) {
5892 		CONN_INC_REF(connp);
5893 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5894 		    SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5895 	} else {
5896 		tcp_conn_request(connp, mp, sqp);
5897 	}
5898 }
5899 
5900 /*
5901  * Successful connect request processing begins when our client passes
5902  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5903  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5904  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_tpi_connect() -> IP
5905  *   upstream <- tcp_rput()		<- IP
5906  * After various error checks are completed, tcp_tpi_connect() lays
5907  * the target address and port into the composite header template,
5908  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5909  * request followed by an IRE request, and passes the three mblk message
5910  * down to IP looking like this:
5911  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5912  * Processing continues in tcp_rput() when we receive the following message:
5913  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5914  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5915  * to fire off the connection request, and then passes the T_OK_ACK mblk
5916  * upstream that we filled in below.  There are, of course, numerous
5917  * error conditions along the way which truncate the processing described
5918  * above.
5919  */
5920 static void
5921 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5922 {
5923 	sin_t		*sin;
5924 	queue_t		*q = tcp->tcp_wq;
5925 	struct T_conn_req	*tcr;
5926 	struct sockaddr	*sa;
5927 	socklen_t	len;
5928 	int		error;
5929 
5930 	tcr = (struct T_conn_req *)mp->b_rptr;
5931 
5932 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5933 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5934 		tcp_err_ack(tcp, mp, TPROTO, 0);
5935 		return;
5936 	}
5937 
5938 	/*
5939 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5940 	 * will always have that to send up.  Otherwise, we need to do
5941 	 * special handling in case the allocation fails at that time.
5942 	 * If the end point is TPI, the tcp_t can be reused and the
5943 	 * tcp_ordrel_mp may be allocated already.
5944 	 */
5945 	if (tcp->tcp_ordrel_mp == NULL) {
5946 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5947 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5948 			return;
5949 		}
5950 	}
5951 
5952 	/*
5953 	 * Determine packet type based on type of address passed in
5954 	 * the request should contain an IPv4 or IPv6 address.
5955 	 * Make sure that address family matches the type of
5956 	 * family of the the address passed down
5957 	 */
5958 	switch (tcr->DEST_length) {
5959 	default:
5960 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5961 		return;
5962 
5963 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5964 		/*
5965 		 * XXX: The check for valid DEST_length was not there
5966 		 * in earlier releases and some buggy
5967 		 * TLI apps (e.g Sybase) got away with not feeding
5968 		 * in sin_zero part of address.
5969 		 * We allow that bug to keep those buggy apps humming.
5970 		 * Test suites require the check on DEST_length.
5971 		 * We construct a new mblk with valid DEST_length
5972 		 * free the original so the rest of the code does
5973 		 * not have to keep track of this special shorter
5974 		 * length address case.
5975 		 */
5976 		mblk_t *nmp;
5977 		struct T_conn_req *ntcr;
5978 		sin_t *nsin;
5979 
5980 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5981 		    tcr->OPT_length, BPRI_HI);
5982 		if (nmp == NULL) {
5983 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5984 			return;
5985 		}
5986 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5987 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5988 		ntcr->PRIM_type = T_CONN_REQ;
5989 		ntcr->DEST_length = sizeof (sin_t);
5990 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5991 
5992 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5993 		*nsin = sin_null;
5994 		/* Get pointer to shorter address to copy from original mp */
5995 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5996 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5997 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5998 			freemsg(nmp);
5999 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6000 			return;
6001 		}
6002 		nsin->sin_family = sin->sin_family;
6003 		nsin->sin_port = sin->sin_port;
6004 		nsin->sin_addr = sin->sin_addr;
6005 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6006 		nmp->b_wptr = (uchar_t *)&nsin[1];
6007 		if (tcr->OPT_length != 0) {
6008 			ntcr->OPT_length = tcr->OPT_length;
6009 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6010 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6011 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6012 			    tcr->OPT_length);
6013 			nmp->b_wptr += tcr->OPT_length;
6014 		}
6015 		freemsg(mp);	/* original mp freed */
6016 		mp = nmp;	/* re-initialize original variables */
6017 		tcr = ntcr;
6018 	}
6019 	/* FALLTHRU */
6020 
6021 	case sizeof (sin_t):
6022 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6023 		    sizeof (sin_t));
6024 		len = sizeof (sin_t);
6025 		break;
6026 
6027 	case sizeof (sin6_t):
6028 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6029 		    sizeof (sin6_t));
6030 		len = sizeof (sin6_t);
6031 		break;
6032 	}
6033 
6034 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
6035 	if (error != 0) {
6036 		tcp_err_ack(tcp, mp, TSYSERR, error);
6037 		return;
6038 	}
6039 
6040 	/*
6041 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6042 	 * should key on their sequence number and cut them loose.
6043 	 */
6044 
6045 	/*
6046 	 * If options passed in, feed it for verification and handling
6047 	 */
6048 	if (tcr->OPT_length != 0) {
6049 		mblk_t	*ok_mp;
6050 		mblk_t	*discon_mp;
6051 		mblk_t  *conn_opts_mp;
6052 		int t_error, sys_error, do_disconnect;
6053 
6054 		conn_opts_mp = NULL;
6055 
6056 		if (tcp_conprim_opt_process(tcp, mp,
6057 		    &do_disconnect, &t_error, &sys_error) < 0) {
6058 			if (do_disconnect) {
6059 				ASSERT(t_error == 0 && sys_error == 0);
6060 				discon_mp = mi_tpi_discon_ind(NULL,
6061 				    ECONNREFUSED, 0);
6062 				if (!discon_mp) {
6063 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6064 					    TSYSERR, ENOMEM);
6065 					return;
6066 				}
6067 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6068 				if (!ok_mp) {
6069 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6070 					    TSYSERR, ENOMEM);
6071 					return;
6072 				}
6073 				qreply(q, ok_mp);
6074 				qreply(q, discon_mp); /* no flush! */
6075 			} else {
6076 				ASSERT(t_error != 0);
6077 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6078 				    sys_error);
6079 			}
6080 			return;
6081 		}
6082 		/*
6083 		 * Success in setting options, the mp option buffer represented
6084 		 * by OPT_length/offset has been potentially modified and
6085 		 * contains results of option processing. We copy it in
6086 		 * another mp to save it for potentially influencing returning
6087 		 * it in T_CONN_CONN.
6088 		 */
6089 		if (tcr->OPT_length != 0) { /* there are resulting options */
6090 			conn_opts_mp = copyb(mp);
6091 			if (!conn_opts_mp) {
6092 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6093 				    TSYSERR, ENOMEM);
6094 				return;
6095 			}
6096 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6097 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6098 			/*
6099 			 * Note:
6100 			 * These resulting option negotiation can include any
6101 			 * end-to-end negotiation options but there no such
6102 			 * thing (yet?) in our TCP/IP.
6103 			 */
6104 		}
6105 	}
6106 
6107 	/* call the non-TPI version */
6108 	error = tcp_do_connect(tcp->tcp_connp, sa, len, DB_CRED(mp),
6109 	    DB_CPID(mp));
6110 	if (error < 0) {
6111 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
6112 	} else if (error > 0) {
6113 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
6114 	} else {
6115 		mp = mi_tpi_ok_ack_alloc(mp);
6116 	}
6117 
6118 	/*
6119 	 * Note: Code below is the "failure" case
6120 	 */
6121 	/* return error ack and blow away saved option results if any */
6122 connect_failed:
6123 	if (mp != NULL)
6124 		putnext(tcp->tcp_rq, mp);
6125 	else {
6126 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6127 		    TSYSERR, ENOMEM);
6128 	}
6129 }
6130 
6131 /*
6132  * Handle connect to IPv4 destinations, including connections for AF_INET6
6133  * sockets connecting to IPv4 mapped IPv6 destinations.
6134  */
6135 static int
6136 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
6137     uint_t srcid, cred_t *cr, pid_t pid)
6138 {
6139 	tcph_t	*tcph;
6140 	mblk_t	*mp;
6141 	ipaddr_t dstaddr = *dstaddrp;
6142 	int32_t	oldstate;
6143 	uint16_t lport;
6144 	int	error = 0;
6145 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6146 
6147 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6148 
6149 	/* Check for attempt to connect to INADDR_ANY */
6150 	if (dstaddr == INADDR_ANY)  {
6151 		/*
6152 		 * SunOS 4.x and 4.3 BSD allow an application
6153 		 * to connect a TCP socket to INADDR_ANY.
6154 		 * When they do this, the kernel picks the
6155 		 * address of one interface and uses it
6156 		 * instead.  The kernel usually ends up
6157 		 * picking the address of the loopback
6158 		 * interface.  This is an undocumented feature.
6159 		 * However, we provide the same thing here
6160 		 * in order to have source and binary
6161 		 * compatibility with SunOS 4.x.
6162 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6163 		 * generate the T_CONN_CON.
6164 		 */
6165 		dstaddr = htonl(INADDR_LOOPBACK);
6166 		*dstaddrp = dstaddr;
6167 	}
6168 
6169 	/* Handle __sin6_src_id if socket not bound to an IP address */
6170 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6171 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6172 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6173 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6174 		    tcp->tcp_ipha->ipha_src);
6175 	}
6176 
6177 	/*
6178 	 * Don't let an endpoint connect to itself.  Note that
6179 	 * the test here does not catch the case where the
6180 	 * source IP addr was left unspecified by the user. In
6181 	 * this case, the source addr is set in tcp_adapt_ire()
6182 	 * using the reply to the T_BIND message that we send
6183 	 * down to IP here and the check is repeated in tcp_rput_other.
6184 	 */
6185 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6186 	    dstport == tcp->tcp_lport) {
6187 		error = -TBADADDR;
6188 		goto failed;
6189 	}
6190 
6191 	tcp->tcp_ipha->ipha_dst = dstaddr;
6192 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6193 
6194 	/*
6195 	 * Massage a source route if any putting the first hop
6196 	 * in iph_dst. Compute a starting value for the checksum which
6197 	 * takes into account that the original iph_dst should be
6198 	 * included in the checksum but that ip will include the
6199 	 * first hop in the source route in the tcp checksum.
6200 	 */
6201 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6202 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6203 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6204 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6205 	if ((int)tcp->tcp_sum < 0)
6206 		tcp->tcp_sum--;
6207 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6208 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6209 	    (tcp->tcp_sum >> 16));
6210 	tcph = tcp->tcp_tcph;
6211 	*(uint16_t *)tcph->th_fport = dstport;
6212 	tcp->tcp_fport = dstport;
6213 
6214 	oldstate = tcp->tcp_state;
6215 	/*
6216 	 * At this point the remote destination address and remote port fields
6217 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6218 	 * have to see which state tcp was in so we can take apropriate action.
6219 	 */
6220 	if (oldstate == TCPS_IDLE) {
6221 		/*
6222 		 * We support a quick connect capability here, allowing
6223 		 * clients to transition directly from IDLE to SYN_SENT
6224 		 * tcp_bindi will pick an unused port, insert the connection
6225 		 * in the bind hash and transition to BOUND state.
6226 		 */
6227 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6228 		    tcp, B_TRUE);
6229 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6230 		    B_FALSE, B_FALSE);
6231 		if (lport == 0) {
6232 			error = -TNOADDR;
6233 			goto failed;
6234 		}
6235 	}
6236 	tcp->tcp_state = TCPS_SYN_SENT;
6237 
6238 	mp = allocb(sizeof (ire_t), BPRI_HI);
6239 	if (mp == NULL) {
6240 		tcp->tcp_state = oldstate;
6241 		error = ENOMEM;
6242 		goto failed;
6243 	}
6244 
6245 	mp->b_wptr += sizeof (ire_t);
6246 	mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6247 	tcp->tcp_hard_binding = 1;
6248 
6249 	/*
6250 	 * We need to make sure that the conn_recv is set to a non-null
6251 	 * value before we insert the conn_t into the classifier table.
6252 	 * This is to avoid a race with an incoming packet which does
6253 	 * an ipcl_classify().
6254 	 */
6255 	tcp->tcp_connp->conn_recv = tcp_input;
6256 
6257 	if (tcp->tcp_family == AF_INET) {
6258 		error = ip_proto_bind_connected_v4(tcp->tcp_connp, &mp,
6259 		    IPPROTO_TCP, &tcp->tcp_ipha->ipha_src, tcp->tcp_lport,
6260 		    tcp->tcp_remote, tcp->tcp_fport, B_TRUE, B_TRUE);
6261 	} else {
6262 		in6_addr_t v6src;
6263 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6264 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6265 		} else {
6266 			v6src = tcp->tcp_ip6h->ip6_src;
6267 		}
6268 		error = ip_proto_bind_connected_v6(tcp->tcp_connp, &mp,
6269 		    IPPROTO_TCP, &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6270 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE);
6271 	}
6272 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6273 	tcp->tcp_active_open = 1;
6274 
6275 
6276 	return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6277 failed:
6278 	/* return error ack and blow away saved option results if any */
6279 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6280 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6281 	return (error);
6282 }
6283 
6284 /*
6285  * Handle connect to IPv6 destinations.
6286  */
6287 static int
6288 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
6289     uint32_t flowinfo, uint_t srcid, uint32_t scope_id, cred_t *cr, pid_t pid)
6290 {
6291 	tcph_t	*tcph;
6292 	mblk_t	*mp;
6293 	ip6_rthdr_t *rth;
6294 	int32_t  oldstate;
6295 	uint16_t lport;
6296 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6297 	int	error = 0;
6298 	conn_t	*connp = tcp->tcp_connp;
6299 
6300 	ASSERT(tcp->tcp_family == AF_INET6);
6301 
6302 	/*
6303 	 * If we're here, it means that the destination address is a native
6304 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6305 	 * reason why it might not be IPv6 is if the socket was bound to an
6306 	 * IPv4-mapped IPv6 address.
6307 	 */
6308 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6309 		return (-TBADADDR);
6310 	}
6311 
6312 	/*
6313 	 * Interpret a zero destination to mean loopback.
6314 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6315 	 * generate the T_CONN_CON.
6316 	 */
6317 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6318 		*dstaddrp = ipv6_loopback;
6319 	}
6320 
6321 	/* Handle __sin6_src_id if socket not bound to an IP address */
6322 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6323 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6324 		    connp->conn_zoneid, tcps->tcps_netstack);
6325 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6326 	}
6327 
6328 	/*
6329 	 * Take care of the scope_id now and add ip6i_t
6330 	 * if ip6i_t is not already allocated through TCP
6331 	 * sticky options. At this point tcp_ip6h does not
6332 	 * have dst info, thus use dstaddrp.
6333 	 */
6334 	if (scope_id != 0 &&
6335 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6336 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6337 		ip6i_t  *ip6i;
6338 
6339 		ipp->ipp_ifindex = scope_id;
6340 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6341 
6342 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6343 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6344 			/* Already allocated */
6345 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6346 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6347 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6348 		} else {
6349 			int reterr;
6350 
6351 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6352 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6353 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6354 			reterr = tcp_build_hdrs(tcp);
6355 			if (reterr != 0)
6356 				goto failed;
6357 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6358 		}
6359 	}
6360 
6361 	/*
6362 	 * Don't let an endpoint connect to itself.  Note that
6363 	 * the test here does not catch the case where the
6364 	 * source IP addr was left unspecified by the user. In
6365 	 * this case, the source addr is set in tcp_adapt_ire()
6366 	 * using the reply to the T_BIND message that we send
6367 	 * down to IP here and the check is repeated in tcp_rput_other.
6368 	 */
6369 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6370 	    (dstport == tcp->tcp_lport)) {
6371 		error = -TBADADDR;
6372 		goto failed;
6373 	}
6374 
6375 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6376 	tcp->tcp_remote_v6 = *dstaddrp;
6377 	tcp->tcp_ip6h->ip6_vcf =
6378 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6379 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6380 
6381 	/*
6382 	 * Massage a routing header (if present) putting the first hop
6383 	 * in ip6_dst. Compute a starting value for the checksum which
6384 	 * takes into account that the original ip6_dst should be
6385 	 * included in the checksum but that ip will include the
6386 	 * first hop in the source route in the tcp checksum.
6387 	 */
6388 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6389 	if (rth != NULL) {
6390 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6391 		    tcps->tcps_netstack);
6392 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6393 		    (tcp->tcp_sum >> 16));
6394 	} else {
6395 		tcp->tcp_sum = 0;
6396 	}
6397 
6398 	tcph = tcp->tcp_tcph;
6399 	*(uint16_t *)tcph->th_fport = dstport;
6400 	tcp->tcp_fport = dstport;
6401 
6402 	oldstate = tcp->tcp_state;
6403 	/*
6404 	 * At this point the remote destination address and remote port fields
6405 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6406 	 * have to see which state tcp was in so we can take apropriate action.
6407 	 */
6408 	if (oldstate == TCPS_IDLE) {
6409 		/*
6410 		 * We support a quick connect capability here, allowing
6411 		 * clients to transition directly from IDLE to SYN_SENT
6412 		 * tcp_bindi will pick an unused port, insert the connection
6413 		 * in the bind hash and transition to BOUND state.
6414 		 */
6415 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6416 		    tcp, B_TRUE);
6417 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6418 		    B_FALSE, B_FALSE);
6419 		if (lport == 0) {
6420 			error = -TNOADDR;
6421 			goto failed;
6422 		}
6423 	}
6424 	tcp->tcp_state = TCPS_SYN_SENT;
6425 
6426 	mp = allocb(sizeof (ire_t), BPRI_HI);
6427 	if (mp != NULL) {
6428 		in6_addr_t v6src;
6429 
6430 		mp->b_wptr += sizeof (ire_t);
6431 		mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6432 
6433 		tcp->tcp_hard_binding = 1;
6434 
6435 		/*
6436 		 * We need to make sure that the conn_recv is set to a non-null
6437 		 * value before we insert the conn_t into the classifier table.
6438 		 * This is to avoid a race with an incoming packet which does
6439 		 * an ipcl_classify().
6440 		 */
6441 		tcp->tcp_connp->conn_recv = tcp_input;
6442 
6443 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6444 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6445 		} else {
6446 			v6src = tcp->tcp_ip6h->ip6_src;
6447 		}
6448 		error = ip_proto_bind_connected_v6(connp, &mp, IPPROTO_TCP,
6449 		    &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6450 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE);
6451 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6452 		tcp->tcp_active_open = 1;
6453 
6454 		return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6455 	}
6456 	/* Error case */
6457 	tcp->tcp_state = oldstate;
6458 	error = ENOMEM;
6459 
6460 failed:
6461 	/* return error ack and blow away saved option results if any */
6462 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6463 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6464 	return (error);
6465 }
6466 
6467 /*
6468  * We need a stream q for detached closing tcp connections
6469  * to use.  Our client hereby indicates that this q is the
6470  * one to use.
6471  */
6472 static void
6473 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6474 {
6475 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6476 	queue_t	*q = tcp->tcp_wq;
6477 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6478 
6479 #ifdef NS_DEBUG
6480 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6481 	    tcps->tcps_netstack->netstack_stackid);
6482 #endif
6483 	mp->b_datap->db_type = M_IOCACK;
6484 	iocp->ioc_count = 0;
6485 	mutex_enter(&tcps->tcps_g_q_lock);
6486 	if (tcps->tcps_g_q != NULL) {
6487 		mutex_exit(&tcps->tcps_g_q_lock);
6488 		iocp->ioc_error = EALREADY;
6489 	} else {
6490 		int error = 0;
6491 		conn_t *connp = tcp->tcp_connp;
6492 		ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
6493 
6494 		tcps->tcps_g_q = tcp->tcp_rq;
6495 		mutex_exit(&tcps->tcps_g_q_lock);
6496 		iocp->ioc_error = 0;
6497 		iocp->ioc_rval = 0;
6498 		/*
6499 		 * We are passing tcp_sticky_ipp as NULL
6500 		 * as it is not useful for tcp_default queue
6501 		 *
6502 		 * Set conn_recv just in case.
6503 		 */
6504 		tcp->tcp_connp->conn_recv = tcp_conn_request;
6505 
6506 		ASSERT(connp->conn_af_isv6);
6507 		connp->conn_ulp = IPPROTO_TCP;
6508 
6509 		if (ipst->ips_ipcl_proto_fanout_v6[IPPROTO_TCP].connf_head !=
6510 		    NULL || connp->conn_mac_exempt) {
6511 			error = -TBADADDR;
6512 		} else {
6513 			connp->conn_srcv6 = ipv6_all_zeros;
6514 			ipcl_proto_insert_v6(connp, IPPROTO_TCP);
6515 		}
6516 
6517 		(void) tcp_post_ip_bind(tcp, NULL, error, NULL, 0);
6518 	}
6519 	qreply(q, mp);
6520 }
6521 
6522 static int
6523 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
6524 {
6525 	tcp_t	*ltcp = NULL;
6526 	conn_t	*connp;
6527 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6528 
6529 	/*
6530 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6531 	 * when the stream is in BOUND state. Do not send a reset,
6532 	 * since the destination IP address is not valid, and it can
6533 	 * be the initialized value of all zeros (broadcast address).
6534 	 *
6535 	 * XXX There won't be any pending bind request to IP.
6536 	 */
6537 	if (tcp->tcp_state <= TCPS_BOUND) {
6538 		if (tcp->tcp_debug) {
6539 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6540 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6541 		}
6542 		return (TOUTSTATE);
6543 	}
6544 
6545 
6546 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6547 
6548 		/*
6549 		 * According to TPI, for non-listeners, ignore seqnum
6550 		 * and disconnect.
6551 		 * Following interpretation of -1 seqnum is historical
6552 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6553 		 * a valid seqnum should not be -1).
6554 		 *
6555 		 *	-1 means disconnect everything
6556 		 *	regardless even on a listener.
6557 		 */
6558 
6559 		int old_state = tcp->tcp_state;
6560 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6561 
6562 		/*
6563 		 * The connection can't be on the tcp_time_wait_head list
6564 		 * since it is not detached.
6565 		 */
6566 		ASSERT(tcp->tcp_time_wait_next == NULL);
6567 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6568 		ASSERT(tcp->tcp_time_wait_expire == 0);
6569 		ltcp = NULL;
6570 		/*
6571 		 * If it used to be a listener, check to make sure no one else
6572 		 * has taken the port before switching back to LISTEN state.
6573 		 */
6574 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6575 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6576 			    tcp->tcp_ipha->ipha_src,
6577 			    tcp->tcp_connp->conn_zoneid, ipst);
6578 			if (connp != NULL)
6579 				ltcp = connp->conn_tcp;
6580 		} else {
6581 			/* Allow tcp_bound_if listeners? */
6582 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6583 			    &tcp->tcp_ip6h->ip6_src, 0,
6584 			    tcp->tcp_connp->conn_zoneid, ipst);
6585 			if (connp != NULL)
6586 				ltcp = connp->conn_tcp;
6587 		}
6588 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6589 			tcp->tcp_state = TCPS_LISTEN;
6590 		} else if (old_state > TCPS_BOUND) {
6591 			tcp->tcp_conn_req_max = 0;
6592 			tcp->tcp_state = TCPS_BOUND;
6593 		}
6594 		if (ltcp != NULL)
6595 			CONN_DEC_REF(ltcp->tcp_connp);
6596 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6597 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6598 		} else if (old_state == TCPS_ESTABLISHED ||
6599 		    old_state == TCPS_CLOSE_WAIT) {
6600 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6601 		}
6602 
6603 		if (tcp->tcp_fused)
6604 			tcp_unfuse(tcp);
6605 
6606 		mutex_enter(&tcp->tcp_eager_lock);
6607 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6608 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6609 			tcp_eager_cleanup(tcp, 0);
6610 		}
6611 		mutex_exit(&tcp->tcp_eager_lock);
6612 
6613 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6614 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6615 
6616 		tcp_reinit(tcp);
6617 
6618 		return (0);
6619 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6620 		return (TBADSEQ);
6621 	}
6622 	return (0);
6623 }
6624 
6625 /*
6626  * Our client hereby directs us to reject the connection request
6627  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6628  * of sending the appropriate RST, not an ICMP error.
6629  */
6630 static void
6631 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6632 {
6633 	t_scalar_t seqnum;
6634 	int	error;
6635 
6636 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6637 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6638 		tcp_err_ack(tcp, mp, TPROTO, 0);
6639 		return;
6640 	}
6641 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6642 	error = tcp_disconnect_common(tcp, seqnum);
6643 	if (error != 0)
6644 		tcp_err_ack(tcp, mp, error, 0);
6645 	else {
6646 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6647 			/* Send M_FLUSH according to TPI */
6648 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6649 		}
6650 		mp = mi_tpi_ok_ack_alloc(mp);
6651 		if (mp)
6652 			putnext(tcp->tcp_rq, mp);
6653 	}
6654 }
6655 
6656 /*
6657  * Diagnostic routine used to return a string associated with the tcp state.
6658  * Note that if the caller does not supply a buffer, it will use an internal
6659  * static string.  This means that if multiple threads call this function at
6660  * the same time, output can be corrupted...  Note also that this function
6661  * does not check the size of the supplied buffer.  The caller has to make
6662  * sure that it is big enough.
6663  */
6664 static char *
6665 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6666 {
6667 	char		buf1[30];
6668 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6669 	char		*buf;
6670 	char		*cp;
6671 	in6_addr_t	local, remote;
6672 	char		local_addrbuf[INET6_ADDRSTRLEN];
6673 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6674 
6675 	if (sup_buf != NULL)
6676 		buf = sup_buf;
6677 	else
6678 		buf = priv_buf;
6679 
6680 	if (tcp == NULL)
6681 		return ("NULL_TCP");
6682 	switch (tcp->tcp_state) {
6683 	case TCPS_CLOSED:
6684 		cp = "TCP_CLOSED";
6685 		break;
6686 	case TCPS_IDLE:
6687 		cp = "TCP_IDLE";
6688 		break;
6689 	case TCPS_BOUND:
6690 		cp = "TCP_BOUND";
6691 		break;
6692 	case TCPS_LISTEN:
6693 		cp = "TCP_LISTEN";
6694 		break;
6695 	case TCPS_SYN_SENT:
6696 		cp = "TCP_SYN_SENT";
6697 		break;
6698 	case TCPS_SYN_RCVD:
6699 		cp = "TCP_SYN_RCVD";
6700 		break;
6701 	case TCPS_ESTABLISHED:
6702 		cp = "TCP_ESTABLISHED";
6703 		break;
6704 	case TCPS_CLOSE_WAIT:
6705 		cp = "TCP_CLOSE_WAIT";
6706 		break;
6707 	case TCPS_FIN_WAIT_1:
6708 		cp = "TCP_FIN_WAIT_1";
6709 		break;
6710 	case TCPS_CLOSING:
6711 		cp = "TCP_CLOSING";
6712 		break;
6713 	case TCPS_LAST_ACK:
6714 		cp = "TCP_LAST_ACK";
6715 		break;
6716 	case TCPS_FIN_WAIT_2:
6717 		cp = "TCP_FIN_WAIT_2";
6718 		break;
6719 	case TCPS_TIME_WAIT:
6720 		cp = "TCP_TIME_WAIT";
6721 		break;
6722 	default:
6723 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6724 		cp = buf1;
6725 		break;
6726 	}
6727 	switch (format) {
6728 	case DISP_ADDR_AND_PORT:
6729 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6730 			/*
6731 			 * Note that we use the remote address in the tcp_b
6732 			 * structure.  This means that it will print out
6733 			 * the real destination address, not the next hop's
6734 			 * address if source routing is used.
6735 			 */
6736 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6737 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6738 
6739 		} else {
6740 			local = tcp->tcp_ip_src_v6;
6741 			remote = tcp->tcp_remote_v6;
6742 		}
6743 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6744 		    sizeof (local_addrbuf));
6745 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6746 		    sizeof (remote_addrbuf));
6747 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6748 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6749 		    ntohs(tcp->tcp_fport), cp);
6750 		break;
6751 	case DISP_PORT_ONLY:
6752 	default:
6753 		(void) mi_sprintf(buf, "[%u, %u] %s",
6754 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6755 		break;
6756 	}
6757 
6758 	return (buf);
6759 }
6760 
6761 /*
6762  * Called via squeue to get on to eager's perimeter. It sends a
6763  * TH_RST if eager is in the fanout table. The listener wants the
6764  * eager to disappear either by means of tcp_eager_blowoff() or
6765  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
6766  * called (via squeue) if the eager cannot be inserted in the
6767  * fanout table in tcp_conn_request().
6768  */
6769 /* ARGSUSED */
6770 void
6771 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6772 {
6773 	conn_t	*econnp = (conn_t *)arg;
6774 	tcp_t	*eager = econnp->conn_tcp;
6775 	tcp_t	*listener = eager->tcp_listener;
6776 	tcp_stack_t	*tcps = eager->tcp_tcps;
6777 
6778 	/*
6779 	 * We could be called because listener is closing. Since
6780 	 * the eager is using listener's queue's, its not safe.
6781 	 * Better use the default queue just to send the TH_RST
6782 	 * out.
6783 	 */
6784 	ASSERT(tcps->tcps_g_q != NULL);
6785 	eager->tcp_rq = tcps->tcps_g_q;
6786 	eager->tcp_wq = WR(tcps->tcps_g_q);
6787 
6788 	/*
6789 	 * An eager's conn_fanout will be NULL if it's a duplicate
6790 	 * for an existing 4-tuples in the conn fanout table.
6791 	 * We don't want to send an RST out in such case.
6792 	 */
6793 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
6794 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6795 		    eager, eager->tcp_snxt, 0, TH_RST);
6796 	}
6797 
6798 	/* We are here because listener wants this eager gone */
6799 	if (listener != NULL) {
6800 		mutex_enter(&listener->tcp_eager_lock);
6801 		tcp_eager_unlink(eager);
6802 		if (eager->tcp_tconnind_started) {
6803 			/*
6804 			 * The eager has sent a conn_ind up to the
6805 			 * listener but listener decides to close
6806 			 * instead. We need to drop the extra ref
6807 			 * placed on eager in tcp_rput_data() before
6808 			 * sending the conn_ind to listener.
6809 			 */
6810 			CONN_DEC_REF(econnp);
6811 		}
6812 		mutex_exit(&listener->tcp_eager_lock);
6813 		CONN_DEC_REF(listener->tcp_connp);
6814 	}
6815 
6816 	if (eager->tcp_state > TCPS_BOUND)
6817 		tcp_close_detached(eager);
6818 }
6819 
6820 /*
6821  * Reset any eager connection hanging off this listener marked
6822  * with 'seqnum' and then reclaim it's resources.
6823  */
6824 static boolean_t
6825 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6826 {
6827 	tcp_t	*eager;
6828 	mblk_t 	*mp;
6829 	tcp_stack_t	*tcps = listener->tcp_tcps;
6830 
6831 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
6832 	eager = listener;
6833 	mutex_enter(&listener->tcp_eager_lock);
6834 	do {
6835 		eager = eager->tcp_eager_next_q;
6836 		if (eager == NULL) {
6837 			mutex_exit(&listener->tcp_eager_lock);
6838 			return (B_FALSE);
6839 		}
6840 	} while (eager->tcp_conn_req_seqnum != seqnum);
6841 
6842 	if (eager->tcp_closemp_used) {
6843 		mutex_exit(&listener->tcp_eager_lock);
6844 		return (B_TRUE);
6845 	}
6846 	eager->tcp_closemp_used = B_TRUE;
6847 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6848 	CONN_INC_REF(eager->tcp_connp);
6849 	mutex_exit(&listener->tcp_eager_lock);
6850 	mp = &eager->tcp_closemp;
6851 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6852 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
6853 	return (B_TRUE);
6854 }
6855 
6856 /*
6857  * Reset any eager connection hanging off this listener
6858  * and then reclaim it's resources.
6859  */
6860 static void
6861 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6862 {
6863 	tcp_t	*eager;
6864 	mblk_t	*mp;
6865 	tcp_stack_t	*tcps = listener->tcp_tcps;
6866 
6867 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6868 
6869 	if (!q0_only) {
6870 		/* First cleanup q */
6871 		TCP_STAT(tcps, tcp_eager_blowoff_q);
6872 		eager = listener->tcp_eager_next_q;
6873 		while (eager != NULL) {
6874 			if (!eager->tcp_closemp_used) {
6875 				eager->tcp_closemp_used = B_TRUE;
6876 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6877 				CONN_INC_REF(eager->tcp_connp);
6878 				mp = &eager->tcp_closemp;
6879 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6880 				    tcp_eager_kill, eager->tcp_connp,
6881 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
6882 			}
6883 			eager = eager->tcp_eager_next_q;
6884 		}
6885 	}
6886 	/* Then cleanup q0 */
6887 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6888 	eager = listener->tcp_eager_next_q0;
6889 	while (eager != listener) {
6890 		if (!eager->tcp_closemp_used) {
6891 			eager->tcp_closemp_used = B_TRUE;
6892 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6893 			CONN_INC_REF(eager->tcp_connp);
6894 			mp = &eager->tcp_closemp;
6895 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6896 			    tcp_eager_kill, eager->tcp_connp, SQ_FILL,
6897 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6898 		}
6899 		eager = eager->tcp_eager_next_q0;
6900 	}
6901 }
6902 
6903 /*
6904  * If we are an eager connection hanging off a listener that hasn't
6905  * formally accepted the connection yet, get off his list and blow off
6906  * any data that we have accumulated.
6907  */
6908 static void
6909 tcp_eager_unlink(tcp_t *tcp)
6910 {
6911 	tcp_t	*listener = tcp->tcp_listener;
6912 
6913 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6914 	ASSERT(listener != NULL);
6915 	if (tcp->tcp_eager_next_q0 != NULL) {
6916 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6917 
6918 		/* Remove the eager tcp from q0 */
6919 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6920 		    tcp->tcp_eager_prev_q0;
6921 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6922 		    tcp->tcp_eager_next_q0;
6923 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6924 		listener->tcp_conn_req_cnt_q0--;
6925 
6926 		tcp->tcp_eager_next_q0 = NULL;
6927 		tcp->tcp_eager_prev_q0 = NULL;
6928 
6929 		/*
6930 		 * Take the eager out, if it is in the list of droppable
6931 		 * eagers.
6932 		 */
6933 		MAKE_UNDROPPABLE(tcp);
6934 
6935 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6936 			/* we have timed out before */
6937 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6938 			listener->tcp_syn_rcvd_timeout--;
6939 		}
6940 	} else {
6941 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6942 		tcp_t	*prev = NULL;
6943 
6944 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6945 			if (tcpp[0] == tcp) {
6946 				if (listener->tcp_eager_last_q == tcp) {
6947 					/*
6948 					 * If we are unlinking the last
6949 					 * element on the list, adjust
6950 					 * tail pointer. Set tail pointer
6951 					 * to nil when list is empty.
6952 					 */
6953 					ASSERT(tcp->tcp_eager_next_q == NULL);
6954 					if (listener->tcp_eager_last_q ==
6955 					    listener->tcp_eager_next_q) {
6956 						listener->tcp_eager_last_q =
6957 						    NULL;
6958 					} else {
6959 						/*
6960 						 * We won't get here if there
6961 						 * is only one eager in the
6962 						 * list.
6963 						 */
6964 						ASSERT(prev != NULL);
6965 						listener->tcp_eager_last_q =
6966 						    prev;
6967 					}
6968 				}
6969 				tcpp[0] = tcp->tcp_eager_next_q;
6970 				tcp->tcp_eager_next_q = NULL;
6971 				tcp->tcp_eager_last_q = NULL;
6972 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6973 				listener->tcp_conn_req_cnt_q--;
6974 				break;
6975 			}
6976 			prev = tcpp[0];
6977 		}
6978 	}
6979 	tcp->tcp_listener = NULL;
6980 }
6981 
6982 /* Shorthand to generate and send TPI error acks to our client */
6983 static void
6984 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6985 {
6986 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6987 		putnext(tcp->tcp_rq, mp);
6988 }
6989 
6990 /* Shorthand to generate and send TPI error acks to our client */
6991 static void
6992 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6993     int t_error, int sys_error)
6994 {
6995 	struct T_error_ack	*teackp;
6996 
6997 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
6998 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
6999 		teackp = (struct T_error_ack *)mp->b_rptr;
7000 		teackp->ERROR_prim = primitive;
7001 		teackp->TLI_error = t_error;
7002 		teackp->UNIX_error = sys_error;
7003 		putnext(tcp->tcp_rq, mp);
7004 	}
7005 }
7006 
7007 /*
7008  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7009  * but instead the code relies on:
7010  * - the fact that the address of the array and its size never changes
7011  * - the atomic assignment of the elements of the array
7012  */
7013 /* ARGSUSED */
7014 static int
7015 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7016 {
7017 	int i;
7018 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7019 
7020 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7021 		if (tcps->tcps_g_epriv_ports[i] != 0)
7022 			(void) mi_mpprintf(mp, "%d ",
7023 			    tcps->tcps_g_epriv_ports[i]);
7024 	}
7025 	return (0);
7026 }
7027 
7028 /*
7029  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7030  * threads from changing it at the same time.
7031  */
7032 /* ARGSUSED */
7033 static int
7034 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7035     cred_t *cr)
7036 {
7037 	long	new_value;
7038 	int	i;
7039 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7040 
7041 	/*
7042 	 * Fail the request if the new value does not lie within the
7043 	 * port number limits.
7044 	 */
7045 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7046 	    new_value <= 0 || new_value >= 65536) {
7047 		return (EINVAL);
7048 	}
7049 
7050 	mutex_enter(&tcps->tcps_epriv_port_lock);
7051 	/* Check if the value is already in the list */
7052 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7053 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7054 			mutex_exit(&tcps->tcps_epriv_port_lock);
7055 			return (EEXIST);
7056 		}
7057 	}
7058 	/* Find an empty slot */
7059 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7060 		if (tcps->tcps_g_epriv_ports[i] == 0)
7061 			break;
7062 	}
7063 	if (i == tcps->tcps_g_num_epriv_ports) {
7064 		mutex_exit(&tcps->tcps_epriv_port_lock);
7065 		return (EOVERFLOW);
7066 	}
7067 	/* Set the new value */
7068 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7069 	mutex_exit(&tcps->tcps_epriv_port_lock);
7070 	return (0);
7071 }
7072 
7073 /*
7074  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7075  * threads from changing it at the same time.
7076  */
7077 /* ARGSUSED */
7078 static int
7079 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7080     cred_t *cr)
7081 {
7082 	long	new_value;
7083 	int	i;
7084 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7085 
7086 	/*
7087 	 * Fail the request if the new value does not lie within the
7088 	 * port number limits.
7089 	 */
7090 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7091 	    new_value >= 65536) {
7092 		return (EINVAL);
7093 	}
7094 
7095 	mutex_enter(&tcps->tcps_epriv_port_lock);
7096 	/* Check that the value is already in the list */
7097 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7098 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7099 			break;
7100 	}
7101 	if (i == tcps->tcps_g_num_epriv_ports) {
7102 		mutex_exit(&tcps->tcps_epriv_port_lock);
7103 		return (ESRCH);
7104 	}
7105 	/* Clear the value */
7106 	tcps->tcps_g_epriv_ports[i] = 0;
7107 	mutex_exit(&tcps->tcps_epriv_port_lock);
7108 	return (0);
7109 }
7110 
7111 /* Return the TPI/TLI equivalent of our current tcp_state */
7112 static int
7113 tcp_tpistate(tcp_t *tcp)
7114 {
7115 	switch (tcp->tcp_state) {
7116 	case TCPS_IDLE:
7117 		return (TS_UNBND);
7118 	case TCPS_LISTEN:
7119 		/*
7120 		 * Return whether there are outstanding T_CONN_IND waiting
7121 		 * for the matching T_CONN_RES. Therefore don't count q0.
7122 		 */
7123 		if (tcp->tcp_conn_req_cnt_q > 0)
7124 			return (TS_WRES_CIND);
7125 		else
7126 			return (TS_IDLE);
7127 	case TCPS_BOUND:
7128 		return (TS_IDLE);
7129 	case TCPS_SYN_SENT:
7130 		return (TS_WCON_CREQ);
7131 	case TCPS_SYN_RCVD:
7132 		/*
7133 		 * Note: assumption: this has to the active open SYN_RCVD.
7134 		 * The passive instance is detached in SYN_RCVD stage of
7135 		 * incoming connection processing so we cannot get request
7136 		 * for T_info_ack on it.
7137 		 */
7138 		return (TS_WACK_CRES);
7139 	case TCPS_ESTABLISHED:
7140 		return (TS_DATA_XFER);
7141 	case TCPS_CLOSE_WAIT:
7142 		return (TS_WREQ_ORDREL);
7143 	case TCPS_FIN_WAIT_1:
7144 		return (TS_WIND_ORDREL);
7145 	case TCPS_FIN_WAIT_2:
7146 		return (TS_WIND_ORDREL);
7147 
7148 	case TCPS_CLOSING:
7149 	case TCPS_LAST_ACK:
7150 	case TCPS_TIME_WAIT:
7151 	case TCPS_CLOSED:
7152 		/*
7153 		 * Following TS_WACK_DREQ7 is a rendition of "not
7154 		 * yet TS_IDLE" TPI state. There is no best match to any
7155 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7156 		 * choose a value chosen that will map to TLI/XTI level
7157 		 * state of TSTATECHNG (state is process of changing) which
7158 		 * captures what this dummy state represents.
7159 		 */
7160 		return (TS_WACK_DREQ7);
7161 	default:
7162 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7163 		    tcp->tcp_state, tcp_display(tcp, NULL,
7164 		    DISP_PORT_ONLY));
7165 		return (TS_UNBND);
7166 	}
7167 }
7168 
7169 static void
7170 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7171 {
7172 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7173 
7174 	if (tcp->tcp_family == AF_INET6)
7175 		*tia = tcp_g_t_info_ack_v6;
7176 	else
7177 		*tia = tcp_g_t_info_ack;
7178 	tia->CURRENT_state = tcp_tpistate(tcp);
7179 	tia->OPT_size = tcp_max_optsize;
7180 	if (tcp->tcp_mss == 0) {
7181 		/* Not yet set - tcp_open does not set mss */
7182 		if (tcp->tcp_ipversion == IPV4_VERSION)
7183 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7184 		else
7185 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7186 	} else {
7187 		tia->TIDU_size = tcp->tcp_mss;
7188 	}
7189 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7190 }
7191 
7192 static void
7193 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
7194     t_uscalar_t cap_bits1)
7195 {
7196 	tcap->CAP_bits1 = 0;
7197 
7198 	if (cap_bits1 & TC1_INFO) {
7199 		tcp_copy_info(&tcap->INFO_ack, tcp);
7200 		tcap->CAP_bits1 |= TC1_INFO;
7201 	}
7202 
7203 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7204 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7205 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7206 	}
7207 
7208 }
7209 
7210 /*
7211  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7212  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7213  * tcp_g_t_info_ack.  The current state of the stream is copied from
7214  * tcp_state.
7215  */
7216 static void
7217 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7218 {
7219 	t_uscalar_t		cap_bits1;
7220 	struct T_capability_ack	*tcap;
7221 
7222 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7223 		freemsg(mp);
7224 		return;
7225 	}
7226 
7227 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7228 
7229 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7230 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7231 	if (mp == NULL)
7232 		return;
7233 
7234 	tcap = (struct T_capability_ack *)mp->b_rptr;
7235 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
7236 
7237 	putnext(tcp->tcp_rq, mp);
7238 }
7239 
7240 /*
7241  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7242  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7243  * The current state of the stream is copied from tcp_state.
7244  */
7245 static void
7246 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7247 {
7248 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7249 	    T_INFO_ACK);
7250 	if (!mp) {
7251 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7252 		return;
7253 	}
7254 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7255 	putnext(tcp->tcp_rq, mp);
7256 }
7257 
7258 /* Respond to the TPI addr request */
7259 static void
7260 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7261 {
7262 	sin_t	*sin;
7263 	mblk_t	*ackmp;
7264 	struct T_addr_ack *taa;
7265 
7266 	/* Make it large enough for worst case */
7267 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7268 	    2 * sizeof (sin6_t), 1);
7269 	if (ackmp == NULL) {
7270 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7271 		return;
7272 	}
7273 
7274 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7275 		tcp_addr_req_ipv6(tcp, ackmp);
7276 		return;
7277 	}
7278 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7279 
7280 	bzero(taa, sizeof (struct T_addr_ack));
7281 	ackmp->b_wptr = (uchar_t *)&taa[1];
7282 
7283 	taa->PRIM_type = T_ADDR_ACK;
7284 	ackmp->b_datap->db_type = M_PCPROTO;
7285 
7286 	/*
7287 	 * Note: Following code assumes 32 bit alignment of basic
7288 	 * data structures like sin_t and struct T_addr_ack.
7289 	 */
7290 	if (tcp->tcp_state >= TCPS_BOUND) {
7291 		/*
7292 		 * Fill in local address
7293 		 */
7294 		taa->LOCADDR_length = sizeof (sin_t);
7295 		taa->LOCADDR_offset = sizeof (*taa);
7296 
7297 		sin = (sin_t *)&taa[1];
7298 
7299 		/* Fill zeroes and then intialize non-zero fields */
7300 		*sin = sin_null;
7301 
7302 		sin->sin_family = AF_INET;
7303 
7304 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7305 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7306 
7307 		ackmp->b_wptr = (uchar_t *)&sin[1];
7308 
7309 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7310 			/*
7311 			 * Fill in Remote address
7312 			 */
7313 			taa->REMADDR_length = sizeof (sin_t);
7314 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7315 			    taa->LOCADDR_length);
7316 
7317 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7318 			*sin = sin_null;
7319 			sin->sin_family = AF_INET;
7320 			sin->sin_addr.s_addr = tcp->tcp_remote;
7321 			sin->sin_port = tcp->tcp_fport;
7322 
7323 			ackmp->b_wptr = (uchar_t *)&sin[1];
7324 		}
7325 	}
7326 	putnext(tcp->tcp_rq, ackmp);
7327 }
7328 
7329 /* Assumes that tcp_addr_req gets enough space and alignment */
7330 static void
7331 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7332 {
7333 	sin6_t	*sin6;
7334 	struct T_addr_ack *taa;
7335 
7336 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7337 	ASSERT(OK_32PTR(ackmp->b_rptr));
7338 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7339 	    2 * sizeof (sin6_t));
7340 
7341 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7342 
7343 	bzero(taa, sizeof (struct T_addr_ack));
7344 	ackmp->b_wptr = (uchar_t *)&taa[1];
7345 
7346 	taa->PRIM_type = T_ADDR_ACK;
7347 	ackmp->b_datap->db_type = M_PCPROTO;
7348 
7349 	/*
7350 	 * Note: Following code assumes 32 bit alignment of basic
7351 	 * data structures like sin6_t and struct T_addr_ack.
7352 	 */
7353 	if (tcp->tcp_state >= TCPS_BOUND) {
7354 		/*
7355 		 * Fill in local address
7356 		 */
7357 		taa->LOCADDR_length = sizeof (sin6_t);
7358 		taa->LOCADDR_offset = sizeof (*taa);
7359 
7360 		sin6 = (sin6_t *)&taa[1];
7361 		*sin6 = sin6_null;
7362 
7363 		sin6->sin6_family = AF_INET6;
7364 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7365 		sin6->sin6_port = tcp->tcp_lport;
7366 
7367 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7368 
7369 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7370 			/*
7371 			 * Fill in Remote address
7372 			 */
7373 			taa->REMADDR_length = sizeof (sin6_t);
7374 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7375 			    taa->LOCADDR_length);
7376 
7377 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7378 			*sin6 = sin6_null;
7379 			sin6->sin6_family = AF_INET6;
7380 			sin6->sin6_flowinfo =
7381 			    tcp->tcp_ip6h->ip6_vcf &
7382 			    ~IPV6_VERS_AND_FLOW_MASK;
7383 			sin6->sin6_addr = tcp->tcp_remote_v6;
7384 			sin6->sin6_port = tcp->tcp_fport;
7385 
7386 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7387 		}
7388 	}
7389 	putnext(tcp->tcp_rq, ackmp);
7390 }
7391 
7392 /*
7393  * Handle reinitialization of a tcp structure.
7394  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7395  */
7396 static void
7397 tcp_reinit(tcp_t *tcp)
7398 {
7399 	mblk_t	*mp;
7400 	int 	err;
7401 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7402 
7403 	TCP_STAT(tcps, tcp_reinit_calls);
7404 
7405 	/* tcp_reinit should never be called for detached tcp_t's */
7406 	ASSERT(tcp->tcp_listener == NULL);
7407 	ASSERT((tcp->tcp_family == AF_INET &&
7408 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7409 	    (tcp->tcp_family == AF_INET6 &&
7410 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7411 	    tcp->tcp_ipversion == IPV6_VERSION)));
7412 
7413 	/* Cancel outstanding timers */
7414 	tcp_timers_stop(tcp);
7415 
7416 	/*
7417 	 * Reset everything in the state vector, after updating global
7418 	 * MIB data from instance counters.
7419 	 */
7420 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7421 	tcp->tcp_ibsegs = 0;
7422 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7423 	tcp->tcp_obsegs = 0;
7424 
7425 	tcp_close_mpp(&tcp->tcp_xmit_head);
7426 	if (tcp->tcp_snd_zcopy_aware)
7427 		tcp_zcopy_notify(tcp);
7428 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7429 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7430 	mutex_enter(&tcp->tcp_non_sq_lock);
7431 	if (tcp->tcp_flow_stopped &&
7432 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7433 		tcp_clrqfull(tcp);
7434 	}
7435 	mutex_exit(&tcp->tcp_non_sq_lock);
7436 	tcp_close_mpp(&tcp->tcp_reass_head);
7437 	tcp->tcp_reass_tail = NULL;
7438 	if (tcp->tcp_rcv_list != NULL) {
7439 		/* Free b_next chain */
7440 		tcp_close_mpp(&tcp->tcp_rcv_list);
7441 		tcp->tcp_rcv_last_head = NULL;
7442 		tcp->tcp_rcv_last_tail = NULL;
7443 		tcp->tcp_rcv_cnt = 0;
7444 	}
7445 	tcp->tcp_rcv_last_tail = NULL;
7446 
7447 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7448 		freemsg(mp);
7449 		tcp->tcp_urp_mp = NULL;
7450 	}
7451 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7452 		freemsg(mp);
7453 		tcp->tcp_urp_mark_mp = NULL;
7454 	}
7455 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7456 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7457 		freeb(tcp->tcp_fused_sigurg_mp);
7458 		tcp->tcp_fused_sigurg_mp = NULL;
7459 	}
7460 	if (tcp->tcp_ordrel_mp != NULL) {
7461 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7462 		freeb(tcp->tcp_ordrel_mp);
7463 		tcp->tcp_ordrel_mp = NULL;
7464 	}
7465 
7466 	/*
7467 	 * Following is a union with two members which are
7468 	 * identical types and size so the following cleanup
7469 	 * is enough.
7470 	 */
7471 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7472 
7473 	CL_INET_DISCONNECT(tcp->tcp_connp, tcp);
7474 
7475 	/*
7476 	 * The connection can't be on the tcp_time_wait_head list
7477 	 * since it is not detached.
7478 	 */
7479 	ASSERT(tcp->tcp_time_wait_next == NULL);
7480 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7481 	ASSERT(tcp->tcp_time_wait_expire == 0);
7482 
7483 	if (tcp->tcp_kssl_pending) {
7484 		tcp->tcp_kssl_pending = B_FALSE;
7485 
7486 		/* Don't reset if the initialized by bind. */
7487 		if (tcp->tcp_kssl_ent != NULL) {
7488 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7489 			    KSSL_NO_PROXY);
7490 		}
7491 	}
7492 	if (tcp->tcp_kssl_ctx != NULL) {
7493 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7494 		tcp->tcp_kssl_ctx = NULL;
7495 	}
7496 
7497 	/*
7498 	 * Reset/preserve other values
7499 	 */
7500 	tcp_reinit_values(tcp);
7501 	ipcl_hash_remove(tcp->tcp_connp);
7502 	conn_delete_ire(tcp->tcp_connp, NULL);
7503 	tcp_ipsec_cleanup(tcp);
7504 
7505 	if (tcp->tcp_conn_req_max != 0) {
7506 		/*
7507 		 * This is the case when a TLI program uses the same
7508 		 * transport end point to accept a connection.  This
7509 		 * makes the TCP both a listener and acceptor.  When
7510 		 * this connection is closed, we need to set the state
7511 		 * back to TCPS_LISTEN.  Make sure that the eager list
7512 		 * is reinitialized.
7513 		 *
7514 		 * Note that this stream is still bound to the four
7515 		 * tuples of the previous connection in IP.  If a new
7516 		 * SYN with different foreign address comes in, IP will
7517 		 * not find it and will send it to the global queue.  In
7518 		 * the global queue, TCP will do a tcp_lookup_listener()
7519 		 * to find this stream.  This works because this stream
7520 		 * is only removed from connected hash.
7521 		 *
7522 		 */
7523 		tcp->tcp_state = TCPS_LISTEN;
7524 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7525 		tcp->tcp_eager_next_drop_q0 = tcp;
7526 		tcp->tcp_eager_prev_drop_q0 = tcp;
7527 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7528 		if (tcp->tcp_family == AF_INET6) {
7529 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7530 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7531 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7532 		} else {
7533 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7534 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7535 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7536 		}
7537 	} else {
7538 		tcp->tcp_state = TCPS_BOUND;
7539 	}
7540 
7541 	/*
7542 	 * Initialize to default values
7543 	 * Can't fail since enough header template space already allocated
7544 	 * at open().
7545 	 */
7546 	err = tcp_init_values(tcp);
7547 	ASSERT(err == 0);
7548 	/* Restore state in tcp_tcph */
7549 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7550 	if (tcp->tcp_ipversion == IPV4_VERSION)
7551 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7552 	else
7553 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7554 	/*
7555 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7556 	 * since the lookup funcs can only lookup on tcp_t
7557 	 */
7558 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7559 
7560 	ASSERT(tcp->tcp_ptpbhn != NULL);
7561 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
7562 		tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7563 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
7564 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
7565 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7566 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7567 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7568 }
7569 
7570 /*
7571  * Force values to zero that need be zero.
7572  * Do not touch values asociated with the BOUND or LISTEN state
7573  * since the connection will end up in that state after the reinit.
7574  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7575  * structure!
7576  */
7577 static void
7578 tcp_reinit_values(tcp)
7579 	tcp_t *tcp;
7580 {
7581 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7582 
7583 #ifndef	lint
7584 #define	DONTCARE(x)
7585 #define	PRESERVE(x)
7586 #else
7587 #define	DONTCARE(x)	((x) = (x))
7588 #define	PRESERVE(x)	((x) = (x))
7589 #endif	/* lint */
7590 
7591 	PRESERVE(tcp->tcp_bind_hash_port);
7592 	PRESERVE(tcp->tcp_bind_hash);
7593 	PRESERVE(tcp->tcp_ptpbhn);
7594 	PRESERVE(tcp->tcp_acceptor_hash);
7595 	PRESERVE(tcp->tcp_ptpahn);
7596 
7597 	/* Should be ASSERT NULL on these with new code! */
7598 	ASSERT(tcp->tcp_time_wait_next == NULL);
7599 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7600 	ASSERT(tcp->tcp_time_wait_expire == 0);
7601 	PRESERVE(tcp->tcp_state);
7602 	PRESERVE(tcp->tcp_rq);
7603 	PRESERVE(tcp->tcp_wq);
7604 
7605 	ASSERT(tcp->tcp_xmit_head == NULL);
7606 	ASSERT(tcp->tcp_xmit_last == NULL);
7607 	ASSERT(tcp->tcp_unsent == 0);
7608 	ASSERT(tcp->tcp_xmit_tail == NULL);
7609 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7610 
7611 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7612 	tcp->tcp_suna = 0;			/* Displayed in mib */
7613 	tcp->tcp_swnd = 0;
7614 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7615 
7616 	ASSERT(tcp->tcp_ibsegs == 0);
7617 	ASSERT(tcp->tcp_obsegs == 0);
7618 
7619 	if (tcp->tcp_iphc != NULL) {
7620 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7621 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7622 	}
7623 
7624 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7625 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7626 	DONTCARE(tcp->tcp_ipha);
7627 	DONTCARE(tcp->tcp_ip6h);
7628 	DONTCARE(tcp->tcp_ip_hdr_len);
7629 	DONTCARE(tcp->tcp_tcph);
7630 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7631 	tcp->tcp_valid_bits = 0;
7632 
7633 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7634 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7635 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7636 	tcp->tcp_last_rcv_lbolt = 0;
7637 
7638 	tcp->tcp_init_cwnd = 0;
7639 
7640 	tcp->tcp_urp_last_valid = 0;
7641 	tcp->tcp_hard_binding = 0;
7642 	tcp->tcp_hard_bound = 0;
7643 	PRESERVE(tcp->tcp_cred);
7644 	PRESERVE(tcp->tcp_cpid);
7645 	PRESERVE(tcp->tcp_open_time);
7646 	PRESERVE(tcp->tcp_exclbind);
7647 
7648 	tcp->tcp_fin_acked = 0;
7649 	tcp->tcp_fin_rcvd = 0;
7650 	tcp->tcp_fin_sent = 0;
7651 	tcp->tcp_ordrel_done = 0;
7652 
7653 	tcp->tcp_debug = 0;
7654 	tcp->tcp_dontroute = 0;
7655 	tcp->tcp_broadcast = 0;
7656 
7657 	tcp->tcp_useloopback = 0;
7658 	tcp->tcp_reuseaddr = 0;
7659 	tcp->tcp_oobinline = 0;
7660 	tcp->tcp_dgram_errind = 0;
7661 
7662 	tcp->tcp_detached = 0;
7663 	tcp->tcp_bind_pending = 0;
7664 	tcp->tcp_unbind_pending = 0;
7665 
7666 	tcp->tcp_snd_ws_ok = B_FALSE;
7667 	tcp->tcp_snd_ts_ok = B_FALSE;
7668 	tcp->tcp_linger = 0;
7669 	tcp->tcp_ka_enabled = 0;
7670 	tcp->tcp_zero_win_probe = 0;
7671 
7672 	tcp->tcp_loopback = 0;
7673 	tcp->tcp_refuse = 0;
7674 	tcp->tcp_localnet = 0;
7675 	tcp->tcp_syn_defense = 0;
7676 	tcp->tcp_set_timer = 0;
7677 
7678 	tcp->tcp_active_open = 0;
7679 	tcp->tcp_rexmit = B_FALSE;
7680 	tcp->tcp_xmit_zc_clean = B_FALSE;
7681 
7682 	tcp->tcp_snd_sack_ok = B_FALSE;
7683 	PRESERVE(tcp->tcp_recvdstaddr);
7684 	tcp->tcp_hwcksum = B_FALSE;
7685 
7686 	tcp->tcp_ire_ill_check_done = B_FALSE;
7687 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7688 
7689 	tcp->tcp_mdt = B_FALSE;
7690 	tcp->tcp_mdt_hdr_head = 0;
7691 	tcp->tcp_mdt_hdr_tail = 0;
7692 
7693 	tcp->tcp_conn_def_q0 = 0;
7694 	tcp->tcp_ip_forward_progress = B_FALSE;
7695 	tcp->tcp_anon_priv_bind = 0;
7696 	tcp->tcp_ecn_ok = B_FALSE;
7697 
7698 	tcp->tcp_cwr = B_FALSE;
7699 	tcp->tcp_ecn_echo_on = B_FALSE;
7700 
7701 	if (tcp->tcp_sack_info != NULL) {
7702 		if (tcp->tcp_notsack_list != NULL) {
7703 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7704 		}
7705 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7706 		tcp->tcp_sack_info = NULL;
7707 	}
7708 
7709 	tcp->tcp_rcv_ws = 0;
7710 	tcp->tcp_snd_ws = 0;
7711 	tcp->tcp_ts_recent = 0;
7712 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7713 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7714 	tcp->tcp_if_mtu = 0;
7715 
7716 	ASSERT(tcp->tcp_reass_head == NULL);
7717 	ASSERT(tcp->tcp_reass_tail == NULL);
7718 
7719 	tcp->tcp_cwnd_cnt = 0;
7720 
7721 	ASSERT(tcp->tcp_rcv_list == NULL);
7722 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7723 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7724 	ASSERT(tcp->tcp_rcv_cnt == 0);
7725 
7726 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7727 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7728 	tcp->tcp_csuna = 0;
7729 
7730 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7731 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7732 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7733 	tcp->tcp_rtt_update = 0;
7734 
7735 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7736 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7737 
7738 	tcp->tcp_rack = 0;			/* Displayed in mib */
7739 	tcp->tcp_rack_cnt = 0;
7740 	tcp->tcp_rack_cur_max = 0;
7741 	tcp->tcp_rack_abs_max = 0;
7742 
7743 	tcp->tcp_max_swnd = 0;
7744 
7745 	ASSERT(tcp->tcp_listener == NULL);
7746 
7747 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7748 
7749 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7750 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7751 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7752 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7753 
7754 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7755 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7756 	PRESERVE(tcp->tcp_conn_req_max);
7757 	PRESERVE(tcp->tcp_conn_req_seqnum);
7758 
7759 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7760 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7761 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7762 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7763 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7764 
7765 	tcp->tcp_lingertime = 0;
7766 
7767 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7768 	ASSERT(tcp->tcp_urp_mp == NULL);
7769 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7770 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7771 
7772 	ASSERT(tcp->tcp_eager_next_q == NULL);
7773 	ASSERT(tcp->tcp_eager_last_q == NULL);
7774 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7775 	    tcp->tcp_eager_prev_q0 == NULL) ||
7776 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7777 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7778 
7779 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
7780 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
7781 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
7782 
7783 	tcp->tcp_client_errno = 0;
7784 
7785 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7786 
7787 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7788 
7789 	PRESERVE(tcp->tcp_bound_source_v6);
7790 	tcp->tcp_last_sent_len = 0;
7791 	tcp->tcp_dupack_cnt = 0;
7792 
7793 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7794 	PRESERVE(tcp->tcp_lport);
7795 
7796 	PRESERVE(tcp->tcp_acceptor_lockp);
7797 
7798 	ASSERT(tcp->tcp_ordrel_mp == NULL);
7799 	PRESERVE(tcp->tcp_acceptor_id);
7800 	DONTCARE(tcp->tcp_ipsec_overhead);
7801 
7802 	PRESERVE(tcp->tcp_family);
7803 	if (tcp->tcp_family == AF_INET6) {
7804 		tcp->tcp_ipversion = IPV6_VERSION;
7805 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7806 	} else {
7807 		tcp->tcp_ipversion = IPV4_VERSION;
7808 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7809 	}
7810 
7811 	tcp->tcp_bound_if = 0;
7812 	tcp->tcp_ipv6_recvancillary = 0;
7813 	tcp->tcp_recvifindex = 0;
7814 	tcp->tcp_recvhops = 0;
7815 	tcp->tcp_closed = 0;
7816 	tcp->tcp_cleandeathtag = 0;
7817 	if (tcp->tcp_hopopts != NULL) {
7818 		mi_free(tcp->tcp_hopopts);
7819 		tcp->tcp_hopopts = NULL;
7820 		tcp->tcp_hopoptslen = 0;
7821 	}
7822 	ASSERT(tcp->tcp_hopoptslen == 0);
7823 	if (tcp->tcp_dstopts != NULL) {
7824 		mi_free(tcp->tcp_dstopts);
7825 		tcp->tcp_dstopts = NULL;
7826 		tcp->tcp_dstoptslen = 0;
7827 	}
7828 	ASSERT(tcp->tcp_dstoptslen == 0);
7829 	if (tcp->tcp_rtdstopts != NULL) {
7830 		mi_free(tcp->tcp_rtdstopts);
7831 		tcp->tcp_rtdstopts = NULL;
7832 		tcp->tcp_rtdstoptslen = 0;
7833 	}
7834 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7835 	if (tcp->tcp_rthdr != NULL) {
7836 		mi_free(tcp->tcp_rthdr);
7837 		tcp->tcp_rthdr = NULL;
7838 		tcp->tcp_rthdrlen = 0;
7839 	}
7840 	ASSERT(tcp->tcp_rthdrlen == 0);
7841 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7842 
7843 	/* Reset fusion-related fields */
7844 	tcp->tcp_fused = B_FALSE;
7845 	tcp->tcp_unfusable = B_FALSE;
7846 	tcp->tcp_fused_sigurg = B_FALSE;
7847 	tcp->tcp_direct_sockfs = B_FALSE;
7848 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7849 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7850 	tcp->tcp_loopback_peer = NULL;
7851 	tcp->tcp_fuse_rcv_hiwater = 0;
7852 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7853 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7854 
7855 	tcp->tcp_lso = B_FALSE;
7856 
7857 	tcp->tcp_in_ack_unsent = 0;
7858 	tcp->tcp_cork = B_FALSE;
7859 	tcp->tcp_tconnind_started = B_FALSE;
7860 
7861 	PRESERVE(tcp->tcp_squeue_bytes);
7862 
7863 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7864 	ASSERT(!tcp->tcp_kssl_pending);
7865 	PRESERVE(tcp->tcp_kssl_ent);
7866 
7867 	/* Sodirect */
7868 	tcp->tcp_sodirect = NULL;
7869 
7870 	tcp->tcp_closemp_used = B_FALSE;
7871 
7872 	PRESERVE(tcp->tcp_rsrv_mp);
7873 	PRESERVE(tcp->tcp_rsrv_mp_lock);
7874 
7875 #ifdef DEBUG
7876 	DONTCARE(tcp->tcmp_stk[0]);
7877 #endif
7878 
7879 	PRESERVE(tcp->tcp_connid);
7880 
7881 
7882 #undef	DONTCARE
7883 #undef	PRESERVE
7884 }
7885 
7886 /*
7887  * Allocate necessary resources and initialize state vector.
7888  * Guaranteed not to fail so that when an error is returned,
7889  * the caller doesn't need to do any additional cleanup.
7890  */
7891 int
7892 tcp_init(tcp_t *tcp, queue_t *q)
7893 {
7894 	int	err;
7895 
7896 	tcp->tcp_rq = q;
7897 	tcp->tcp_wq = WR(q);
7898 	tcp->tcp_state = TCPS_IDLE;
7899 	if ((err = tcp_init_values(tcp)) != 0)
7900 		tcp_timers_stop(tcp);
7901 	return (err);
7902 }
7903 
7904 static int
7905 tcp_init_values(tcp_t *tcp)
7906 {
7907 	int	err;
7908 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7909 
7910 	ASSERT((tcp->tcp_family == AF_INET &&
7911 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7912 	    (tcp->tcp_family == AF_INET6 &&
7913 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7914 	    tcp->tcp_ipversion == IPV6_VERSION)));
7915 
7916 	/*
7917 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7918 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7919 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7920 	 * during first few transmissions of a connection as seen in slow
7921 	 * links.
7922 	 */
7923 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
7924 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
7925 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7926 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7927 	    tcps->tcps_conn_grace_period;
7928 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
7929 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
7930 	tcp->tcp_timer_backoff = 0;
7931 	tcp->tcp_ms_we_have_waited = 0;
7932 	tcp->tcp_last_recv_time = lbolt;
7933 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
7934 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7935 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7936 
7937 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
7938 
7939 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
7940 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
7941 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
7942 	/*
7943 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7944 	 * passive open.
7945 	 */
7946 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
7947 
7948 	tcp->tcp_naglim = tcps->tcps_naglim_def;
7949 
7950 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7951 
7952 	tcp->tcp_mdt_hdr_head = 0;
7953 	tcp->tcp_mdt_hdr_tail = 0;
7954 
7955 	/* Reset fusion-related fields */
7956 	tcp->tcp_fused = B_FALSE;
7957 	tcp->tcp_unfusable = B_FALSE;
7958 	tcp->tcp_fused_sigurg = B_FALSE;
7959 	tcp->tcp_direct_sockfs = B_FALSE;
7960 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7961 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7962 	tcp->tcp_loopback_peer = NULL;
7963 	tcp->tcp_fuse_rcv_hiwater = 0;
7964 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7965 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7966 
7967 	/* Sodirect */
7968 	tcp->tcp_sodirect = NULL;
7969 
7970 	/* Initialize the header template */
7971 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7972 		err = tcp_header_init_ipv4(tcp);
7973 	} else {
7974 		err = tcp_header_init_ipv6(tcp);
7975 	}
7976 	if (err)
7977 		return (err);
7978 
7979 	/*
7980 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7981 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7982 	 */
7983 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7984 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
7985 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
7986 
7987 	tcp->tcp_cork = B_FALSE;
7988 	/*
7989 	 * Init the tcp_debug option.  This value determines whether TCP
7990 	 * calls strlog() to print out debug messages.  Doing this
7991 	 * initialization here means that this value is not inherited thru
7992 	 * tcp_reinit().
7993 	 */
7994 	tcp->tcp_debug = tcps->tcps_dbg;
7995 
7996 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
7997 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
7998 
7999 	return (0);
8000 }
8001 
8002 /*
8003  * Initialize the IPv4 header. Loses any record of any IP options.
8004  */
8005 static int
8006 tcp_header_init_ipv4(tcp_t *tcp)
8007 {
8008 	tcph_t		*tcph;
8009 	uint32_t	sum;
8010 	conn_t		*connp;
8011 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8012 
8013 	/*
8014 	 * This is a simple initialization. If there's
8015 	 * already a template, it should never be too small,
8016 	 * so reuse it.  Otherwise, allocate space for the new one.
8017 	 */
8018 	if (tcp->tcp_iphc == NULL) {
8019 		ASSERT(tcp->tcp_iphc_len == 0);
8020 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8021 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8022 		if (tcp->tcp_iphc == NULL) {
8023 			tcp->tcp_iphc_len = 0;
8024 			return (ENOMEM);
8025 		}
8026 	}
8027 
8028 	/* options are gone; may need a new label */
8029 	connp = tcp->tcp_connp;
8030 	connp->conn_mlp_type = mlptSingle;
8031 	connp->conn_ulp_labeled = !is_system_labeled();
8032 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8033 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8034 	tcp->tcp_ip6h = NULL;
8035 	tcp->tcp_ipversion = IPV4_VERSION;
8036 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8037 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8038 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8039 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8040 	tcp->tcp_ipha->ipha_version_and_hdr_length
8041 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8042 	tcp->tcp_ipha->ipha_ident = 0;
8043 
8044 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8045 	tcp->tcp_tos = 0;
8046 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8047 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8048 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8049 
8050 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8051 	tcp->tcp_tcph = tcph;
8052 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8053 	/*
8054 	 * IP wants our header length in the checksum field to
8055 	 * allow it to perform a single pseudo-header+checksum
8056 	 * calculation on behalf of TCP.
8057 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8058 	 */
8059 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8060 	sum = (sum >> 16) + (sum & 0xFFFF);
8061 	U16_TO_ABE16(sum, tcph->th_sum);
8062 	return (0);
8063 }
8064 
8065 /*
8066  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8067  */
8068 static int
8069 tcp_header_init_ipv6(tcp_t *tcp)
8070 {
8071 	tcph_t	*tcph;
8072 	uint32_t	sum;
8073 	conn_t	*connp;
8074 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8075 
8076 	/*
8077 	 * This is a simple initialization. If there's
8078 	 * already a template, it should never be too small,
8079 	 * so reuse it. Otherwise, allocate space for the new one.
8080 	 * Ensure that there is enough space to "downgrade" the tcp_t
8081 	 * to an IPv4 tcp_t. This requires having space for a full load
8082 	 * of IPv4 options, as well as a full load of TCP options
8083 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8084 	 * than a v6 header and a TCP header with a full load of TCP options
8085 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8086 	 * We want to avoid reallocation in the "downgraded" case when
8087 	 * processing outbound IPv4 options.
8088 	 */
8089 	if (tcp->tcp_iphc == NULL) {
8090 		ASSERT(tcp->tcp_iphc_len == 0);
8091 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8092 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8093 		if (tcp->tcp_iphc == NULL) {
8094 			tcp->tcp_iphc_len = 0;
8095 			return (ENOMEM);
8096 		}
8097 	}
8098 
8099 	/* options are gone; may need a new label */
8100 	connp = tcp->tcp_connp;
8101 	connp->conn_mlp_type = mlptSingle;
8102 	connp->conn_ulp_labeled = !is_system_labeled();
8103 
8104 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8105 	tcp->tcp_ipversion = IPV6_VERSION;
8106 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8107 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8108 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8109 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8110 	tcp->tcp_ipha = NULL;
8111 
8112 	/* Initialize the header template */
8113 
8114 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8115 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8116 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8117 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8118 
8119 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8120 	tcp->tcp_tcph = tcph;
8121 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8122 	/*
8123 	 * IP wants our header length in the checksum field to
8124 	 * allow it to perform a single psuedo-header+checksum
8125 	 * calculation on behalf of TCP.
8126 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8127 	 */
8128 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8129 	sum = (sum >> 16) + (sum & 0xFFFF);
8130 	U16_TO_ABE16(sum, tcph->th_sum);
8131 	return (0);
8132 }
8133 
8134 /* At minimum we need 8 bytes in the TCP header for the lookup */
8135 #define	ICMP_MIN_TCP_HDR	8
8136 
8137 /*
8138  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8139  * passed up by IP. The message is always received on the correct tcp_t.
8140  * Assumes that IP has pulled up everything up to and including the ICMP header.
8141  */
8142 void
8143 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8144 {
8145 	icmph_t *icmph;
8146 	ipha_t	*ipha;
8147 	int	iph_hdr_length;
8148 	tcph_t	*tcph;
8149 	boolean_t ipsec_mctl = B_FALSE;
8150 	boolean_t secure;
8151 	mblk_t *first_mp = mp;
8152 	int32_t new_mss;
8153 	uint32_t ratio;
8154 	size_t mp_size = MBLKL(mp);
8155 	uint32_t seg_seq;
8156 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8157 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8158 
8159 	/* Assume IP provides aligned packets - otherwise toss */
8160 	if (!OK_32PTR(mp->b_rptr)) {
8161 		freemsg(mp);
8162 		return;
8163 	}
8164 
8165 	/*
8166 	 * Since ICMP errors are normal data marked with M_CTL when sent
8167 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8168 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8169 	 */
8170 	if ((mp_size == sizeof (ipsec_info_t)) &&
8171 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8172 		ASSERT(mp->b_cont != NULL);
8173 		mp = mp->b_cont;
8174 		/* IP should have done this */
8175 		ASSERT(OK_32PTR(mp->b_rptr));
8176 		mp_size = MBLKL(mp);
8177 		ipsec_mctl = B_TRUE;
8178 	}
8179 
8180 	/*
8181 	 * Verify that we have a complete outer IP header. If not, drop it.
8182 	 */
8183 	if (mp_size < sizeof (ipha_t)) {
8184 noticmpv4:
8185 		freemsg(first_mp);
8186 		return;
8187 	}
8188 
8189 	ipha = (ipha_t *)mp->b_rptr;
8190 	/*
8191 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8192 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8193 	 */
8194 	switch (IPH_HDR_VERSION(ipha)) {
8195 	case IPV6_VERSION:
8196 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8197 		return;
8198 	case IPV4_VERSION:
8199 		break;
8200 	default:
8201 		goto noticmpv4;
8202 	}
8203 
8204 	/* Skip past the outer IP and ICMP headers */
8205 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8206 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8207 	/*
8208 	 * If we don't have the correct outer IP header length or if the ULP
8209 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8210 	 * send it upstream.
8211 	 */
8212 	if (iph_hdr_length < sizeof (ipha_t) ||
8213 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8214 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8215 		goto noticmpv4;
8216 	}
8217 	ipha = (ipha_t *)&icmph[1];
8218 
8219 	/* Skip past the inner IP and find the ULP header */
8220 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8221 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8222 	/*
8223 	 * If we don't have the correct inner IP header length or if the ULP
8224 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8225 	 * bytes of TCP header, drop it.
8226 	 */
8227 	if (iph_hdr_length < sizeof (ipha_t) ||
8228 	    ipha->ipha_protocol != IPPROTO_TCP ||
8229 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8230 		goto noticmpv4;
8231 	}
8232 
8233 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8234 		if (ipsec_mctl) {
8235 			secure = ipsec_in_is_secure(first_mp);
8236 		} else {
8237 			secure = B_FALSE;
8238 		}
8239 		if (secure) {
8240 			/*
8241 			 * If we are willing to accept this in clear
8242 			 * we don't have to verify policy.
8243 			 */
8244 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8245 				if (!tcp_check_policy(tcp, first_mp,
8246 				    ipha, NULL, secure, ipsec_mctl)) {
8247 					/*
8248 					 * tcp_check_policy called
8249 					 * ip_drop_packet() on failure.
8250 					 */
8251 					return;
8252 				}
8253 			}
8254 		}
8255 	} else if (ipsec_mctl) {
8256 		/*
8257 		 * This is a hard_bound connection. IP has already
8258 		 * verified policy. We don't have to do it again.
8259 		 */
8260 		freeb(first_mp);
8261 		first_mp = mp;
8262 		ipsec_mctl = B_FALSE;
8263 	}
8264 
8265 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8266 	/*
8267 	 * TCP SHOULD check that the TCP sequence number contained in
8268 	 * payload of the ICMP error message is within the range
8269 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8270 	 */
8271 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8272 		/*
8273 		 * The ICMP message is bogus, just drop it.  But if this is
8274 		 * an ICMP too big message, IP has already changed
8275 		 * the ire_max_frag to the bogus value.  We need to change
8276 		 * it back.
8277 		 */
8278 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8279 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8280 			conn_t *connp = tcp->tcp_connp;
8281 			ire_t *ire;
8282 			int flag;
8283 
8284 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8285 				flag = tcp->tcp_ipha->
8286 				    ipha_fragment_offset_and_flags;
8287 			} else {
8288 				flag = 0;
8289 			}
8290 			mutex_enter(&connp->conn_lock);
8291 			if ((ire = connp->conn_ire_cache) != NULL) {
8292 				mutex_enter(&ire->ire_lock);
8293 				mutex_exit(&connp->conn_lock);
8294 				ire->ire_max_frag = tcp->tcp_if_mtu;
8295 				ire->ire_frag_flag |= flag;
8296 				mutex_exit(&ire->ire_lock);
8297 			} else {
8298 				mutex_exit(&connp->conn_lock);
8299 			}
8300 		}
8301 		goto noticmpv4;
8302 	}
8303 
8304 	switch (icmph->icmph_type) {
8305 	case ICMP_DEST_UNREACHABLE:
8306 		switch (icmph->icmph_code) {
8307 		case ICMP_FRAGMENTATION_NEEDED:
8308 			/*
8309 			 * Reduce the MSS based on the new MTU.  This will
8310 			 * eliminate any fragmentation locally.
8311 			 * N.B.  There may well be some funny side-effects on
8312 			 * the local send policy and the remote receive policy.
8313 			 * Pending further research, we provide
8314 			 * tcp_ignore_path_mtu just in case this proves
8315 			 * disastrous somewhere.
8316 			 *
8317 			 * After updating the MSS, retransmit part of the
8318 			 * dropped segment using the new mss by calling
8319 			 * tcp_wput_data().  Need to adjust all those
8320 			 * params to make sure tcp_wput_data() work properly.
8321 			 */
8322 			if (tcps->tcps_ignore_path_mtu ||
8323 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8324 				break;
8325 
8326 			/*
8327 			 * Decrease the MSS by time stamp options
8328 			 * IP options and IPSEC options. tcp_hdr_len
8329 			 * includes time stamp option and IP option
8330 			 * length.  Note that new_mss may be negative
8331 			 * if tcp_ipsec_overhead is large and the
8332 			 * icmph_du_mtu is the minimum value, which is 68.
8333 			 */
8334 			new_mss = ntohs(icmph->icmph_du_mtu) -
8335 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8336 
8337 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8338 			    new_mss);
8339 
8340 			/*
8341 			 * Only update the MSS if the new one is
8342 			 * smaller than the previous one.  This is
8343 			 * to avoid problems when getting multiple
8344 			 * ICMP errors for the same MTU.
8345 			 */
8346 			if (new_mss >= tcp->tcp_mss)
8347 				break;
8348 
8349 			/*
8350 			 * Note that we are using the template header's DF
8351 			 * bit in the fast path sending.  So we need to compare
8352 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8353 			 * And stop doing IPv4 PMTUd if new_mss is less than
8354 			 * MAX(tcps_mss_min, ip_pmtu_min).
8355 			 */
8356 			if (new_mss < tcps->tcps_mss_min ||
8357 			    new_mss < ipst->ips_ip_pmtu_min) {
8358 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8359 				    0;
8360 			}
8361 
8362 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8363 			ASSERT(ratio >= 1);
8364 			tcp_mss_set(tcp, new_mss, B_TRUE);
8365 
8366 			/*
8367 			 * Make sure we have something to
8368 			 * send.
8369 			 */
8370 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8371 			    (tcp->tcp_xmit_head != NULL)) {
8372 				/*
8373 				 * Shrink tcp_cwnd in
8374 				 * proportion to the old MSS/new MSS.
8375 				 */
8376 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8377 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8378 				    (tcp->tcp_unsent == 0)) {
8379 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8380 				} else {
8381 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8382 				}
8383 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8384 				tcp->tcp_rexmit = B_TRUE;
8385 				tcp->tcp_dupack_cnt = 0;
8386 				tcp->tcp_snd_burst = TCP_CWND_SS;
8387 				tcp_ss_rexmit(tcp);
8388 			}
8389 			break;
8390 		case ICMP_PORT_UNREACHABLE:
8391 		case ICMP_PROTOCOL_UNREACHABLE:
8392 			switch (tcp->tcp_state) {
8393 			case TCPS_SYN_SENT:
8394 			case TCPS_SYN_RCVD:
8395 				/*
8396 				 * ICMP can snipe away incipient
8397 				 * TCP connections as long as
8398 				 * seq number is same as initial
8399 				 * send seq number.
8400 				 */
8401 				if (seg_seq == tcp->tcp_iss) {
8402 					(void) tcp_clean_death(tcp,
8403 					    ECONNREFUSED, 6);
8404 				}
8405 				break;
8406 			}
8407 			break;
8408 		case ICMP_HOST_UNREACHABLE:
8409 		case ICMP_NET_UNREACHABLE:
8410 			/* Record the error in case we finally time out. */
8411 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8412 				tcp->tcp_client_errno = EHOSTUNREACH;
8413 			else
8414 				tcp->tcp_client_errno = ENETUNREACH;
8415 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8416 				if (tcp->tcp_listener != NULL &&
8417 				    tcp->tcp_listener->tcp_syn_defense) {
8418 					/*
8419 					 * Ditch the half-open connection if we
8420 					 * suspect a SYN attack is under way.
8421 					 */
8422 					tcp_ip_ire_mark_advice(tcp);
8423 					(void) tcp_clean_death(tcp,
8424 					    tcp->tcp_client_errno, 7);
8425 				}
8426 			}
8427 			break;
8428 		default:
8429 			break;
8430 		}
8431 		break;
8432 	case ICMP_SOURCE_QUENCH: {
8433 		/*
8434 		 * use a global boolean to control
8435 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8436 		 * The default is false.
8437 		 */
8438 		if (tcp_icmp_source_quench) {
8439 			/*
8440 			 * Reduce the sending rate as if we got a
8441 			 * retransmit timeout
8442 			 */
8443 			uint32_t npkt;
8444 
8445 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8446 			    tcp->tcp_mss;
8447 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8448 			tcp->tcp_cwnd = tcp->tcp_mss;
8449 			tcp->tcp_cwnd_cnt = 0;
8450 		}
8451 		break;
8452 	}
8453 	}
8454 	freemsg(first_mp);
8455 }
8456 
8457 /*
8458  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8459  * error messages passed up by IP.
8460  * Assumes that IP has pulled up all the extension headers as well
8461  * as the ICMPv6 header.
8462  */
8463 static void
8464 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8465 {
8466 	icmp6_t *icmp6;
8467 	ip6_t	*ip6h;
8468 	uint16_t	iph_hdr_length;
8469 	tcpha_t	*tcpha;
8470 	uint8_t	*nexthdrp;
8471 	uint32_t new_mss;
8472 	uint32_t ratio;
8473 	boolean_t secure;
8474 	mblk_t *first_mp = mp;
8475 	size_t mp_size;
8476 	uint32_t seg_seq;
8477 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8478 
8479 	/*
8480 	 * The caller has determined if this is an IPSEC_IN packet and
8481 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8482 	 */
8483 	if (ipsec_mctl)
8484 		mp = mp->b_cont;
8485 
8486 	mp_size = MBLKL(mp);
8487 
8488 	/*
8489 	 * Verify that we have a complete IP header. If not, send it upstream.
8490 	 */
8491 	if (mp_size < sizeof (ip6_t)) {
8492 noticmpv6:
8493 		freemsg(first_mp);
8494 		return;
8495 	}
8496 
8497 	/*
8498 	 * Verify this is an ICMPV6 packet, else send it upstream.
8499 	 */
8500 	ip6h = (ip6_t *)mp->b_rptr;
8501 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8502 		iph_hdr_length = IPV6_HDR_LEN;
8503 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8504 	    &nexthdrp) ||
8505 	    *nexthdrp != IPPROTO_ICMPV6) {
8506 		goto noticmpv6;
8507 	}
8508 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8509 	ip6h = (ip6_t *)&icmp6[1];
8510 	/*
8511 	 * Verify if we have a complete ICMP and inner IP header.
8512 	 */
8513 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8514 		goto noticmpv6;
8515 
8516 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8517 		goto noticmpv6;
8518 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8519 	/*
8520 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8521 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8522 	 * packet.
8523 	 */
8524 	if ((*nexthdrp != IPPROTO_TCP) ||
8525 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8526 		goto noticmpv6;
8527 	}
8528 
8529 	/*
8530 	 * ICMP errors come on the right queue or come on
8531 	 * listener/global queue for detached connections and
8532 	 * get switched to the right queue. If it comes on the
8533 	 * right queue, policy check has already been done by IP
8534 	 * and thus free the first_mp without verifying the policy.
8535 	 * If it has come for a non-hard bound connection, we need
8536 	 * to verify policy as IP may not have done it.
8537 	 */
8538 	if (!tcp->tcp_hard_bound) {
8539 		if (ipsec_mctl) {
8540 			secure = ipsec_in_is_secure(first_mp);
8541 		} else {
8542 			secure = B_FALSE;
8543 		}
8544 		if (secure) {
8545 			/*
8546 			 * If we are willing to accept this in clear
8547 			 * we don't have to verify policy.
8548 			 */
8549 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8550 				if (!tcp_check_policy(tcp, first_mp,
8551 				    NULL, ip6h, secure, ipsec_mctl)) {
8552 					/*
8553 					 * tcp_check_policy called
8554 					 * ip_drop_packet() on failure.
8555 					 */
8556 					return;
8557 				}
8558 			}
8559 		}
8560 	} else if (ipsec_mctl) {
8561 		/*
8562 		 * This is a hard_bound connection. IP has already
8563 		 * verified policy. We don't have to do it again.
8564 		 */
8565 		freeb(first_mp);
8566 		first_mp = mp;
8567 		ipsec_mctl = B_FALSE;
8568 	}
8569 
8570 	seg_seq = ntohl(tcpha->tha_seq);
8571 	/*
8572 	 * TCP SHOULD check that the TCP sequence number contained in
8573 	 * payload of the ICMP error message is within the range
8574 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8575 	 */
8576 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8577 		/*
8578 		 * If the ICMP message is bogus, should we kill the
8579 		 * connection, or should we just drop the bogus ICMP
8580 		 * message? It would probably make more sense to just
8581 		 * drop the message so that if this one managed to get
8582 		 * in, the real connection should not suffer.
8583 		 */
8584 		goto noticmpv6;
8585 	}
8586 
8587 	switch (icmp6->icmp6_type) {
8588 	case ICMP6_PACKET_TOO_BIG:
8589 		/*
8590 		 * Reduce the MSS based on the new MTU.  This will
8591 		 * eliminate any fragmentation locally.
8592 		 * N.B.  There may well be some funny side-effects on
8593 		 * the local send policy and the remote receive policy.
8594 		 * Pending further research, we provide
8595 		 * tcp_ignore_path_mtu just in case this proves
8596 		 * disastrous somewhere.
8597 		 *
8598 		 * After updating the MSS, retransmit part of the
8599 		 * dropped segment using the new mss by calling
8600 		 * tcp_wput_data().  Need to adjust all those
8601 		 * params to make sure tcp_wput_data() work properly.
8602 		 */
8603 		if (tcps->tcps_ignore_path_mtu)
8604 			break;
8605 
8606 		/*
8607 		 * Decrease the MSS by time stamp options
8608 		 * IP options and IPSEC options. tcp_hdr_len
8609 		 * includes time stamp option and IP option
8610 		 * length.
8611 		 */
8612 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8613 		    tcp->tcp_ipsec_overhead;
8614 
8615 		/*
8616 		 * Only update the MSS if the new one is
8617 		 * smaller than the previous one.  This is
8618 		 * to avoid problems when getting multiple
8619 		 * ICMP errors for the same MTU.
8620 		 */
8621 		if (new_mss >= tcp->tcp_mss)
8622 			break;
8623 
8624 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8625 		ASSERT(ratio >= 1);
8626 		tcp_mss_set(tcp, new_mss, B_TRUE);
8627 
8628 		/*
8629 		 * Make sure we have something to
8630 		 * send.
8631 		 */
8632 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8633 		    (tcp->tcp_xmit_head != NULL)) {
8634 			/*
8635 			 * Shrink tcp_cwnd in
8636 			 * proportion to the old MSS/new MSS.
8637 			 */
8638 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8639 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8640 			    (tcp->tcp_unsent == 0)) {
8641 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8642 			} else {
8643 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8644 			}
8645 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8646 			tcp->tcp_rexmit = B_TRUE;
8647 			tcp->tcp_dupack_cnt = 0;
8648 			tcp->tcp_snd_burst = TCP_CWND_SS;
8649 			tcp_ss_rexmit(tcp);
8650 		}
8651 		break;
8652 
8653 	case ICMP6_DST_UNREACH:
8654 		switch (icmp6->icmp6_code) {
8655 		case ICMP6_DST_UNREACH_NOPORT:
8656 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8657 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8658 			    (seg_seq == tcp->tcp_iss)) {
8659 				(void) tcp_clean_death(tcp,
8660 				    ECONNREFUSED, 8);
8661 			}
8662 			break;
8663 
8664 		case ICMP6_DST_UNREACH_ADMIN:
8665 		case ICMP6_DST_UNREACH_NOROUTE:
8666 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8667 		case ICMP6_DST_UNREACH_ADDR:
8668 			/* Record the error in case we finally time out. */
8669 			tcp->tcp_client_errno = EHOSTUNREACH;
8670 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8671 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8672 			    (seg_seq == tcp->tcp_iss)) {
8673 				if (tcp->tcp_listener != NULL &&
8674 				    tcp->tcp_listener->tcp_syn_defense) {
8675 					/*
8676 					 * Ditch the half-open connection if we
8677 					 * suspect a SYN attack is under way.
8678 					 */
8679 					tcp_ip_ire_mark_advice(tcp);
8680 					(void) tcp_clean_death(tcp,
8681 					    tcp->tcp_client_errno, 9);
8682 				}
8683 			}
8684 
8685 
8686 			break;
8687 		default:
8688 			break;
8689 		}
8690 		break;
8691 
8692 	case ICMP6_PARAM_PROB:
8693 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8694 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8695 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8696 		    (uchar_t *)nexthdrp) {
8697 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8698 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8699 				(void) tcp_clean_death(tcp,
8700 				    ECONNREFUSED, 10);
8701 			}
8702 			break;
8703 		}
8704 		break;
8705 
8706 	case ICMP6_TIME_EXCEEDED:
8707 	default:
8708 		break;
8709 	}
8710 	freemsg(first_mp);
8711 }
8712 
8713 /*
8714  * Notify IP that we are having trouble with this connection.  IP should
8715  * blow the IRE away and start over.
8716  */
8717 static void
8718 tcp_ip_notify(tcp_t *tcp)
8719 {
8720 	struct iocblk	*iocp;
8721 	ipid_t	*ipid;
8722 	mblk_t	*mp;
8723 
8724 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8725 	if (tcp->tcp_ipversion == IPV6_VERSION)
8726 		return;
8727 
8728 	mp = mkiocb(IP_IOCTL);
8729 	if (mp == NULL)
8730 		return;
8731 
8732 	iocp = (struct iocblk *)mp->b_rptr;
8733 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8734 
8735 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8736 	if (!mp->b_cont) {
8737 		freeb(mp);
8738 		return;
8739 	}
8740 
8741 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8742 	mp->b_cont->b_wptr += iocp->ioc_count;
8743 	bzero(ipid, sizeof (*ipid));
8744 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8745 	ipid->ipid_ire_type = IRE_CACHE;
8746 	ipid->ipid_addr_offset = sizeof (ipid_t);
8747 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8748 	/*
8749 	 * Note: in the case of source routing we want to blow away the
8750 	 * route to the first source route hop.
8751 	 */
8752 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8753 	    sizeof (tcp->tcp_ipha->ipha_dst));
8754 
8755 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8756 }
8757 
8758 /* Unlink and return any mblk that looks like it contains an ire */
8759 static mblk_t *
8760 tcp_ire_mp(mblk_t **mpp)
8761 {
8762 	mblk_t 	*mp = *mpp;
8763 	mblk_t	*prev_mp = NULL;
8764 
8765 	for (;;) {
8766 		switch (DB_TYPE(mp)) {
8767 		case IRE_DB_TYPE:
8768 		case IRE_DB_REQ_TYPE:
8769 			if (mp == *mpp) {
8770 				*mpp = mp->b_cont;
8771 			} else {
8772 				prev_mp->b_cont = mp->b_cont;
8773 			}
8774 			mp->b_cont = NULL;
8775 			return (mp);
8776 		default:
8777 			break;
8778 		}
8779 		prev_mp = mp;
8780 		mp = mp->b_cont;
8781 		if (mp == NULL)
8782 			break;
8783 	}
8784 	return (mp);
8785 }
8786 
8787 /*
8788  * Timer callback routine for keepalive probe.  We do a fake resend of
8789  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8790  * check to see if we have heard anything from the other end for the last
8791  * RTO period.  If we have, set the timer to expire for another
8792  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8793  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8794  * the timeout if we have not heard from the other side.  If for more than
8795  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8796  * kill the connection unless the keepalive abort threshold is 0.  In
8797  * that case, we will probe "forever."
8798  */
8799 static void
8800 tcp_keepalive_killer(void *arg)
8801 {
8802 	mblk_t	*mp;
8803 	conn_t	*connp = (conn_t *)arg;
8804 	tcp_t  	*tcp = connp->conn_tcp;
8805 	int32_t	firetime;
8806 	int32_t	idletime;
8807 	int32_t	ka_intrvl;
8808 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8809 
8810 	tcp->tcp_ka_tid = 0;
8811 
8812 	if (tcp->tcp_fused)
8813 		return;
8814 
8815 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
8816 	ka_intrvl = tcp->tcp_ka_interval;
8817 
8818 	/*
8819 	 * Keepalive probe should only be sent if the application has not
8820 	 * done a close on the connection.
8821 	 */
8822 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8823 		return;
8824 	}
8825 	/* Timer fired too early, restart it. */
8826 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8827 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8828 		    MSEC_TO_TICK(ka_intrvl));
8829 		return;
8830 	}
8831 
8832 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8833 	/*
8834 	 * If we have not heard from the other side for a long
8835 	 * time, kill the connection unless the keepalive abort
8836 	 * threshold is 0.  In that case, we will probe "forever."
8837 	 */
8838 	if (tcp->tcp_ka_abort_thres != 0 &&
8839 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8840 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
8841 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8842 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8843 		return;
8844 	}
8845 
8846 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8847 	    idletime >= ka_intrvl) {
8848 		/* Fake resend of last ACKed byte. */
8849 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8850 
8851 		if (mp1 != NULL) {
8852 			*mp1->b_wptr++ = '\0';
8853 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8854 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8855 			freeb(mp1);
8856 			/*
8857 			 * if allocation failed, fall through to start the
8858 			 * timer back.
8859 			 */
8860 			if (mp != NULL) {
8861 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8862 				BUMP_MIB(&tcps->tcps_mib,
8863 				    tcpTimKeepaliveProbe);
8864 				if (tcp->tcp_ka_last_intrvl != 0) {
8865 					int max;
8866 					/*
8867 					 * We should probe again at least
8868 					 * in ka_intrvl, but not more than
8869 					 * tcp_rexmit_interval_max.
8870 					 */
8871 					max = tcps->tcps_rexmit_interval_max;
8872 					firetime = MIN(ka_intrvl - 1,
8873 					    tcp->tcp_ka_last_intrvl << 1);
8874 					if (firetime > max)
8875 						firetime = max;
8876 				} else {
8877 					firetime = tcp->tcp_rto;
8878 				}
8879 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8880 				    tcp_keepalive_killer,
8881 				    MSEC_TO_TICK(firetime));
8882 				tcp->tcp_ka_last_intrvl = firetime;
8883 				return;
8884 			}
8885 		}
8886 	} else {
8887 		tcp->tcp_ka_last_intrvl = 0;
8888 	}
8889 
8890 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8891 	if ((firetime = ka_intrvl - idletime) < 0) {
8892 		firetime = ka_intrvl;
8893 	}
8894 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8895 	    MSEC_TO_TICK(firetime));
8896 }
8897 
8898 int
8899 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8900 {
8901 	queue_t	*q = tcp->tcp_rq;
8902 	int32_t	mss = tcp->tcp_mss;
8903 	int	maxpsz;
8904 	conn_t	*connp = tcp->tcp_connp;
8905 
8906 	if (TCP_IS_DETACHED(tcp))
8907 		return (mss);
8908 	if (tcp->tcp_fused) {
8909 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8910 		mss = INFPSZ;
8911 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
8912 		/*
8913 		 * Set the sd_qn_maxpsz according to the socket send buffer
8914 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8915 		 * instruct the stream head to copyin user data into contiguous
8916 		 * kernel-allocated buffers without breaking it up into smaller
8917 		 * chunks.  We round up the buffer size to the nearest SMSS.
8918 		 */
8919 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8920 		if (tcp->tcp_kssl_ctx == NULL)
8921 			mss = INFPSZ;
8922 		else
8923 			mss = SSL3_MAX_RECORD_LEN;
8924 	} else {
8925 		/*
8926 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8927 		 * (and a multiple of the mss).  This instructs the stream
8928 		 * head to break down larger than SMSS writes into SMSS-
8929 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8930 		 */
8931 		/* XXX tune this with ndd tcp_maxpsz_multiplier */
8932 		maxpsz = tcp->tcp_maxpsz * mss;
8933 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8934 			maxpsz = tcp->tcp_xmit_hiwater/2;
8935 			/* Round up to nearest mss */
8936 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8937 		}
8938 	}
8939 
8940 	(void) proto_set_maxpsz(q, connp, maxpsz);
8941 	if (!(IPCL_IS_NONSTR(connp))) {
8942 		/* XXX do it in set_maxpsz()? */
8943 		tcp->tcp_wq->q_maxpsz = maxpsz;
8944 	}
8945 
8946 	if (set_maxblk)
8947 		(void) proto_set_tx_maxblk(q, connp, mss);
8948 	return (mss);
8949 }
8950 
8951 /*
8952  * Extract option values from a tcp header.  We put any found values into the
8953  * tcpopt struct and return a bitmask saying which options were found.
8954  */
8955 static int
8956 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8957 {
8958 	uchar_t		*endp;
8959 	int		len;
8960 	uint32_t	mss;
8961 	uchar_t		*up = (uchar_t *)tcph;
8962 	int		found = 0;
8963 	int32_t		sack_len;
8964 	tcp_seq		sack_begin, sack_end;
8965 	tcp_t		*tcp;
8966 
8967 	endp = up + TCP_HDR_LENGTH(tcph);
8968 	up += TCP_MIN_HEADER_LENGTH;
8969 	while (up < endp) {
8970 		len = endp - up;
8971 		switch (*up) {
8972 		case TCPOPT_EOL:
8973 			break;
8974 
8975 		case TCPOPT_NOP:
8976 			up++;
8977 			continue;
8978 
8979 		case TCPOPT_MAXSEG:
8980 			if (len < TCPOPT_MAXSEG_LEN ||
8981 			    up[1] != TCPOPT_MAXSEG_LEN)
8982 				break;
8983 
8984 			mss = BE16_TO_U16(up+2);
8985 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
8986 			tcpopt->tcp_opt_mss = mss;
8987 			found |= TCP_OPT_MSS_PRESENT;
8988 
8989 			up += TCPOPT_MAXSEG_LEN;
8990 			continue;
8991 
8992 		case TCPOPT_WSCALE:
8993 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
8994 				break;
8995 
8996 			if (up[2] > TCP_MAX_WINSHIFT)
8997 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
8998 			else
8999 				tcpopt->tcp_opt_wscale = up[2];
9000 			found |= TCP_OPT_WSCALE_PRESENT;
9001 
9002 			up += TCPOPT_WS_LEN;
9003 			continue;
9004 
9005 		case TCPOPT_SACK_PERMITTED:
9006 			if (len < TCPOPT_SACK_OK_LEN ||
9007 			    up[1] != TCPOPT_SACK_OK_LEN)
9008 				break;
9009 			found |= TCP_OPT_SACK_OK_PRESENT;
9010 			up += TCPOPT_SACK_OK_LEN;
9011 			continue;
9012 
9013 		case TCPOPT_SACK:
9014 			if (len <= 2 || up[1] <= 2 || len < up[1])
9015 				break;
9016 
9017 			/* If TCP is not interested in SACK blks... */
9018 			if ((tcp = tcpopt->tcp) == NULL) {
9019 				up += up[1];
9020 				continue;
9021 			}
9022 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9023 			up += TCPOPT_HEADER_LEN;
9024 
9025 			/*
9026 			 * If the list is empty, allocate one and assume
9027 			 * nothing is sack'ed.
9028 			 */
9029 			ASSERT(tcp->tcp_sack_info != NULL);
9030 			if (tcp->tcp_notsack_list == NULL) {
9031 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9032 				    tcp->tcp_suna, tcp->tcp_snxt,
9033 				    &(tcp->tcp_num_notsack_blk),
9034 				    &(tcp->tcp_cnt_notsack_list));
9035 
9036 				/*
9037 				 * Make sure tcp_notsack_list is not NULL.
9038 				 * This happens when kmem_alloc(KM_NOSLEEP)
9039 				 * returns NULL.
9040 				 */
9041 				if (tcp->tcp_notsack_list == NULL) {
9042 					up += sack_len;
9043 					continue;
9044 				}
9045 				tcp->tcp_fack = tcp->tcp_suna;
9046 			}
9047 
9048 			while (sack_len > 0) {
9049 				if (up + 8 > endp) {
9050 					up = endp;
9051 					break;
9052 				}
9053 				sack_begin = BE32_TO_U32(up);
9054 				up += 4;
9055 				sack_end = BE32_TO_U32(up);
9056 				up += 4;
9057 				sack_len -= 8;
9058 				/*
9059 				 * Bounds checking.  Make sure the SACK
9060 				 * info is within tcp_suna and tcp_snxt.
9061 				 * If this SACK blk is out of bound, ignore
9062 				 * it but continue to parse the following
9063 				 * blks.
9064 				 */
9065 				if (SEQ_LEQ(sack_end, sack_begin) ||
9066 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9067 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9068 					continue;
9069 				}
9070 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9071 				    sack_begin, sack_end,
9072 				    &(tcp->tcp_num_notsack_blk),
9073 				    &(tcp->tcp_cnt_notsack_list));
9074 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9075 					tcp->tcp_fack = sack_end;
9076 				}
9077 			}
9078 			found |= TCP_OPT_SACK_PRESENT;
9079 			continue;
9080 
9081 		case TCPOPT_TSTAMP:
9082 			if (len < TCPOPT_TSTAMP_LEN ||
9083 			    up[1] != TCPOPT_TSTAMP_LEN)
9084 				break;
9085 
9086 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9087 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9088 
9089 			found |= TCP_OPT_TSTAMP_PRESENT;
9090 
9091 			up += TCPOPT_TSTAMP_LEN;
9092 			continue;
9093 
9094 		default:
9095 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9096 				break;
9097 			up += up[1];
9098 			continue;
9099 		}
9100 		break;
9101 	}
9102 	return (found);
9103 }
9104 
9105 /*
9106  * Set the mss associated with a particular tcp based on its current value,
9107  * and a new one passed in. Observe minimums and maximums, and reset
9108  * other state variables that we want to view as multiples of mss.
9109  *
9110  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9111  * highwater marks etc. need to be initialized or adjusted.
9112  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9113  *    packet arrives.
9114  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9115  *    ICMP6_PACKET_TOO_BIG arrives.
9116  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9117  *    to increase the MSS to use the extra bytes available.
9118  *
9119  * Callers except tcp_paws_check() ensure that they only reduce mss.
9120  */
9121 static void
9122 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9123 {
9124 	uint32_t	mss_max;
9125 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9126 
9127 	if (tcp->tcp_ipversion == IPV4_VERSION)
9128 		mss_max = tcps->tcps_mss_max_ipv4;
9129 	else
9130 		mss_max = tcps->tcps_mss_max_ipv6;
9131 
9132 	if (mss < tcps->tcps_mss_min)
9133 		mss = tcps->tcps_mss_min;
9134 	if (mss > mss_max)
9135 		mss = mss_max;
9136 	/*
9137 	 * Unless naglim has been set by our client to
9138 	 * a non-mss value, force naglim to track mss.
9139 	 * This can help to aggregate small writes.
9140 	 */
9141 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9142 		tcp->tcp_naglim = mss;
9143 	/*
9144 	 * TCP should be able to buffer at least 4 MSS data for obvious
9145 	 * performance reason.
9146 	 */
9147 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9148 		tcp->tcp_xmit_hiwater = mss << 2;
9149 
9150 	if (do_ss) {
9151 		/*
9152 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9153 		 * changing due to a reduction in MTU, presumably as a
9154 		 * result of a new path component, reset cwnd to its
9155 		 * "initial" value, as a multiple of the new mss.
9156 		 */
9157 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9158 	} else {
9159 		/*
9160 		 * Called by tcp_paws_check(), the mss increased
9161 		 * marginally to allow use of space previously taken
9162 		 * by the timestamp option. It would be inappropriate
9163 		 * to apply slow start or tcp_init_cwnd values to
9164 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9165 		 */
9166 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9167 		tcp->tcp_cwnd_cnt = 0;
9168 	}
9169 	tcp->tcp_mss = mss;
9170 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9171 }
9172 
9173 /* For /dev/tcp aka AF_INET open */
9174 static int
9175 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9176 {
9177 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9178 }
9179 
9180 /* For /dev/tcp6 aka AF_INET6 open */
9181 static int
9182 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9183 {
9184 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9185 }
9186 
9187 static conn_t *
9188 tcp_create_common(queue_t *q, cred_t *credp, boolean_t isv6,
9189     boolean_t issocket, int *errorp)
9190 {
9191 	tcp_t		*tcp = NULL;
9192 	conn_t		*connp;
9193 	int		err;
9194 	zoneid_t	zoneid;
9195 	tcp_stack_t	*tcps;
9196 	squeue_t	*sqp;
9197 
9198 	ASSERT(errorp != NULL);
9199 	/*
9200 	 * Find the proper zoneid and netstack.
9201 	 */
9202 	/*
9203 	 * Special case for install: miniroot needs to be able to
9204 	 * access files via NFS as though it were always in the
9205 	 * global zone.
9206 	 */
9207 	if (credp == kcred && nfs_global_client_only != 0) {
9208 		zoneid = GLOBAL_ZONEID;
9209 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9210 		    netstack_tcp;
9211 		ASSERT(tcps != NULL);
9212 	} else {
9213 		netstack_t *ns;
9214 
9215 		ns = netstack_find_by_cred(credp);
9216 		ASSERT(ns != NULL);
9217 		tcps = ns->netstack_tcp;
9218 		ASSERT(tcps != NULL);
9219 
9220 		/*
9221 		 * For exclusive stacks we set the zoneid to zero
9222 		 * to make TCP operate as if in the global zone.
9223 		 */
9224 		if (tcps->tcps_netstack->netstack_stackid !=
9225 		    GLOBAL_NETSTACKID)
9226 			zoneid = GLOBAL_ZONEID;
9227 		else
9228 			zoneid = crgetzoneid(credp);
9229 	}
9230 	/*
9231 	 * For stackid zero this is done from strplumb.c, but
9232 	 * non-zero stackids are handled here.
9233 	 */
9234 	if (tcps->tcps_g_q == NULL &&
9235 	    tcps->tcps_netstack->netstack_stackid !=
9236 	    GLOBAL_NETSTACKID) {
9237 		tcp_g_q_setup(tcps);
9238 	}
9239 
9240 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
9241 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
9242 	/*
9243 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9244 	 * so we drop it by one.
9245 	 */
9246 	netstack_rele(tcps->tcps_netstack);
9247 	if (connp == NULL) {
9248 		*errorp = ENOSR;
9249 		return (NULL);
9250 	}
9251 	connp->conn_sqp = sqp;
9252 	connp->conn_initial_sqp = connp->conn_sqp;
9253 	tcp = connp->conn_tcp;
9254 
9255 	if (isv6) {
9256 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9257 		connp->conn_send = ip_output_v6;
9258 		connp->conn_af_isv6 = B_TRUE;
9259 		connp->conn_pkt_isv6 = B_TRUE;
9260 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9261 		tcp->tcp_ipversion = IPV6_VERSION;
9262 		tcp->tcp_family = AF_INET6;
9263 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9264 	} else {
9265 		connp->conn_flags |= IPCL_TCP4;
9266 		connp->conn_send = ip_output;
9267 		connp->conn_af_isv6 = B_FALSE;
9268 		connp->conn_pkt_isv6 = B_FALSE;
9269 		tcp->tcp_ipversion = IPV4_VERSION;
9270 		tcp->tcp_family = AF_INET;
9271 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9272 	}
9273 
9274 	/*
9275 	 * TCP keeps a copy of cred for cache locality reasons but
9276 	 * we put a reference only once. If connp->conn_cred
9277 	 * becomes invalid, tcp_cred should also be set to NULL.
9278 	 */
9279 	tcp->tcp_cred = connp->conn_cred = credp;
9280 	crhold(connp->conn_cred);
9281 	tcp->tcp_cpid = curproc->p_pid;
9282 	tcp->tcp_open_time = lbolt64;
9283 	connp->conn_zoneid = zoneid;
9284 	connp->conn_mlp_type = mlptSingle;
9285 	connp->conn_ulp_labeled = !is_system_labeled();
9286 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9287 	ASSERT(tcp->tcp_tcps == tcps);
9288 
9289 	/*
9290 	 * If the caller has the process-wide flag set, then default to MAC
9291 	 * exempt mode.  This allows read-down to unlabeled hosts.
9292 	 */
9293 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9294 		connp->conn_mac_exempt = B_TRUE;
9295 
9296 	connp->conn_dev = NULL;
9297 	if (issocket) {
9298 		connp->conn_flags |= IPCL_SOCKET;
9299 		tcp->tcp_issocket = 1;
9300 	}
9301 
9302 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
9303 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9304 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
9305 
9306 	/* Non-zero default values */
9307 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9308 
9309 	if (q == NULL) {
9310 		/*
9311 		 * Create a helper stream for non-STREAMS socket.
9312 		 */
9313 		err = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
9314 		if (err != 0) {
9315 			ip1dbg(("tcp_create_common: create of IP helper stream "
9316 			    "failed\n"));
9317 			CONN_DEC_REF(connp);
9318 			*errorp = err;
9319 			return (NULL);
9320 		}
9321 		q = connp->conn_rq;
9322 	} else {
9323 		RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9324 	}
9325 
9326 	SOCK_CONNID_INIT(tcp->tcp_connid);
9327 	err = tcp_init(tcp, q);
9328 	if (err != 0) {
9329 		CONN_DEC_REF(connp);
9330 		*errorp = err;
9331 		return (NULL);
9332 	}
9333 
9334 	return (connp);
9335 }
9336 
9337 static int
9338 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9339     boolean_t isv6)
9340 {
9341 	tcp_t		*tcp = NULL;
9342 	conn_t		*connp = NULL;
9343 	int		err;
9344 	vmem_t		*minor_arena = NULL;
9345 	dev_t		conn_dev;
9346 	boolean_t	issocket;
9347 
9348 	if (q->q_ptr != NULL)
9349 		return (0);
9350 
9351 	if (sflag == MODOPEN)
9352 		return (EINVAL);
9353 
9354 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9355 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9356 		minor_arena = ip_minor_arena_la;
9357 	} else {
9358 		/*
9359 		 * Either minor numbers in the large arena were exhausted
9360 		 * or a non socket application is doing the open.
9361 		 * Try to allocate from the small arena.
9362 		 */
9363 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9364 			return (EBUSY);
9365 		}
9366 		minor_arena = ip_minor_arena_sa;
9367 	}
9368 
9369 	ASSERT(minor_arena != NULL);
9370 
9371 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
9372 
9373 	if (flag & SO_FALLBACK) {
9374 		/*
9375 		 * Non streams socket needs a stream to fallback to
9376 		 */
9377 		RD(q)->q_ptr = (void *)conn_dev;
9378 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
9379 		WR(q)->q_ptr = (void *)minor_arena;
9380 		qprocson(q);
9381 		return (0);
9382 	} else if (flag & SO_ACCEPTOR) {
9383 		q->q_qinfo = &tcp_acceptor_rinit;
9384 		/*
9385 		 * the conn_dev and minor_arena will be subsequently used by
9386 		 * tcp_wput_accept() and tcpclose_accept() to figure out the
9387 		 * minor device number for this connection from the q_ptr.
9388 		 */
9389 		RD(q)->q_ptr = (void *)conn_dev;
9390 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9391 		WR(q)->q_ptr = (void *)minor_arena;
9392 		qprocson(q);
9393 		return (0);
9394 	}
9395 
9396 	issocket = flag & SO_SOCKSTR;
9397 	connp = tcp_create_common(q, credp, isv6, issocket, &err);
9398 
9399 	if (connp == NULL) {
9400 		inet_minor_free(minor_arena, conn_dev);
9401 		q->q_ptr = WR(q)->q_ptr = NULL;
9402 		return (err);
9403 	}
9404 
9405 	q->q_ptr = WR(q)->q_ptr = connp;
9406 
9407 	connp->conn_dev = conn_dev;
9408 	connp->conn_minor_arena = minor_arena;
9409 
9410 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9411 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9412 
9413 	if (issocket) {
9414 		WR(q)->q_qinfo = &tcp_sock_winit;
9415 	} else {
9416 		tcp = connp->conn_tcp;
9417 #ifdef  _ILP32
9418 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9419 #else
9420 		tcp->tcp_acceptor_id = conn_dev;
9421 #endif  /* _ILP32 */
9422 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9423 	}
9424 
9425 	/*
9426 	 * Put the ref for TCP. Ref for IP was already put
9427 	 * by ipcl_conn_create. Also Make the conn_t globally
9428 	 * visible to walkers
9429 	 */
9430 	mutex_enter(&connp->conn_lock);
9431 	CONN_INC_REF_LOCKED(connp);
9432 	ASSERT(connp->conn_ref == 2);
9433 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9434 	mutex_exit(&connp->conn_lock);
9435 
9436 	qprocson(q);
9437 	return (0);
9438 }
9439 
9440 /*
9441  * Some TCP options can be "set" by requesting them in the option
9442  * buffer. This is needed for XTI feature test though we do not
9443  * allow it in general. We interpret that this mechanism is more
9444  * applicable to OSI protocols and need not be allowed in general.
9445  * This routine filters out options for which it is not allowed (most)
9446  * and lets through those (few) for which it is. [ The XTI interface
9447  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9448  * ever implemented will have to be allowed here ].
9449  */
9450 static boolean_t
9451 tcp_allow_connopt_set(int level, int name)
9452 {
9453 
9454 	switch (level) {
9455 	case IPPROTO_TCP:
9456 		switch (name) {
9457 		case TCP_NODELAY:
9458 			return (B_TRUE);
9459 		default:
9460 			return (B_FALSE);
9461 		}
9462 		/*NOTREACHED*/
9463 	default:
9464 		return (B_FALSE);
9465 	}
9466 	/*NOTREACHED*/
9467 }
9468 
9469 /*
9470  * this routine gets default values of certain options whose default
9471  * values are maintained by protocol specific code
9472  */
9473 /* ARGSUSED */
9474 int
9475 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9476 {
9477 	int32_t	*i1 = (int32_t *)ptr;
9478 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9479 
9480 	switch (level) {
9481 	case IPPROTO_TCP:
9482 		switch (name) {
9483 		case TCP_NOTIFY_THRESHOLD:
9484 			*i1 = tcps->tcps_ip_notify_interval;
9485 			break;
9486 		case TCP_ABORT_THRESHOLD:
9487 			*i1 = tcps->tcps_ip_abort_interval;
9488 			break;
9489 		case TCP_CONN_NOTIFY_THRESHOLD:
9490 			*i1 = tcps->tcps_ip_notify_cinterval;
9491 			break;
9492 		case TCP_CONN_ABORT_THRESHOLD:
9493 			*i1 = tcps->tcps_ip_abort_cinterval;
9494 			break;
9495 		default:
9496 			return (-1);
9497 		}
9498 		break;
9499 	case IPPROTO_IP:
9500 		switch (name) {
9501 		case IP_TTL:
9502 			*i1 = tcps->tcps_ipv4_ttl;
9503 			break;
9504 		default:
9505 			return (-1);
9506 		}
9507 		break;
9508 	case IPPROTO_IPV6:
9509 		switch (name) {
9510 		case IPV6_UNICAST_HOPS:
9511 			*i1 = tcps->tcps_ipv6_hoplimit;
9512 			break;
9513 		default:
9514 			return (-1);
9515 		}
9516 		break;
9517 	default:
9518 		return (-1);
9519 	}
9520 	return (sizeof (int));
9521 }
9522 
9523 static int
9524 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
9525 {
9526 	int		*i1 = (int *)ptr;
9527 	tcp_t		*tcp = connp->conn_tcp;
9528 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9529 
9530 	switch (level) {
9531 	case SOL_SOCKET:
9532 		switch (name) {
9533 		case SO_LINGER:	{
9534 			struct linger *lgr = (struct linger *)ptr;
9535 
9536 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9537 			lgr->l_linger = tcp->tcp_lingertime;
9538 			}
9539 			return (sizeof (struct linger));
9540 		case SO_DEBUG:
9541 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9542 			break;
9543 		case SO_KEEPALIVE:
9544 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9545 			break;
9546 		case SO_DONTROUTE:
9547 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9548 			break;
9549 		case SO_USELOOPBACK:
9550 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9551 			break;
9552 		case SO_BROADCAST:
9553 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9554 			break;
9555 		case SO_REUSEADDR:
9556 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9557 			break;
9558 		case SO_OOBINLINE:
9559 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9560 			break;
9561 		case SO_DGRAM_ERRIND:
9562 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9563 			break;
9564 		case SO_TYPE:
9565 			*i1 = SOCK_STREAM;
9566 			break;
9567 		case SO_SNDBUF:
9568 			*i1 = tcp->tcp_xmit_hiwater;
9569 			break;
9570 		case SO_RCVBUF:
9571 			*i1 = tcp->tcp_recv_hiwater;
9572 			break;
9573 		case SO_SND_COPYAVOID:
9574 			*i1 = tcp->tcp_snd_zcopy_on ?
9575 			    SO_SND_COPYAVOID : 0;
9576 			break;
9577 		case SO_ALLZONES:
9578 			*i1 = connp->conn_allzones ? 1 : 0;
9579 			break;
9580 		case SO_ANON_MLP:
9581 			*i1 = connp->conn_anon_mlp;
9582 			break;
9583 		case SO_MAC_EXEMPT:
9584 			*i1 = connp->conn_mac_exempt;
9585 			break;
9586 		case SO_EXCLBIND:
9587 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9588 			break;
9589 		case SO_PROTOTYPE:
9590 			*i1 = IPPROTO_TCP;
9591 			break;
9592 		case SO_DOMAIN:
9593 			*i1 = tcp->tcp_family;
9594 			break;
9595 		case SO_ACCEPTCONN:
9596 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
9597 		default:
9598 			return (-1);
9599 		}
9600 		break;
9601 	case IPPROTO_TCP:
9602 		switch (name) {
9603 		case TCP_NODELAY:
9604 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9605 			break;
9606 		case TCP_MAXSEG:
9607 			*i1 = tcp->tcp_mss;
9608 			break;
9609 		case TCP_NOTIFY_THRESHOLD:
9610 			*i1 = (int)tcp->tcp_first_timer_threshold;
9611 			break;
9612 		case TCP_ABORT_THRESHOLD:
9613 			*i1 = tcp->tcp_second_timer_threshold;
9614 			break;
9615 		case TCP_CONN_NOTIFY_THRESHOLD:
9616 			*i1 = tcp->tcp_first_ctimer_threshold;
9617 			break;
9618 		case TCP_CONN_ABORT_THRESHOLD:
9619 			*i1 = tcp->tcp_second_ctimer_threshold;
9620 			break;
9621 		case TCP_RECVDSTADDR:
9622 			*i1 = tcp->tcp_recvdstaddr;
9623 			break;
9624 		case TCP_ANONPRIVBIND:
9625 			*i1 = tcp->tcp_anon_priv_bind;
9626 			break;
9627 		case TCP_EXCLBIND:
9628 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9629 			break;
9630 		case TCP_INIT_CWND:
9631 			*i1 = tcp->tcp_init_cwnd;
9632 			break;
9633 		case TCP_KEEPALIVE_THRESHOLD:
9634 			*i1 = tcp->tcp_ka_interval;
9635 			break;
9636 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9637 			*i1 = tcp->tcp_ka_abort_thres;
9638 			break;
9639 		case TCP_CORK:
9640 			*i1 = tcp->tcp_cork;
9641 			break;
9642 		default:
9643 			return (-1);
9644 		}
9645 		break;
9646 	case IPPROTO_IP:
9647 		if (tcp->tcp_family != AF_INET)
9648 			return (-1);
9649 		switch (name) {
9650 		case IP_OPTIONS:
9651 		case T_IP_OPTIONS: {
9652 			/*
9653 			 * This is compatible with BSD in that in only return
9654 			 * the reverse source route with the final destination
9655 			 * as the last entry. The first 4 bytes of the option
9656 			 * will contain the final destination.
9657 			 */
9658 			int	opt_len;
9659 
9660 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9661 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9662 			ASSERT(opt_len >= 0);
9663 			/* Caller ensures enough space */
9664 			if (opt_len > 0) {
9665 				/*
9666 				 * TODO: Do we have to handle getsockopt on an
9667 				 * initiator as well?
9668 				 */
9669 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9670 			}
9671 			return (0);
9672 			}
9673 		case IP_TOS:
9674 		case T_IP_TOS:
9675 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9676 			break;
9677 		case IP_TTL:
9678 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9679 			break;
9680 		case IP_NEXTHOP:
9681 			/* Handled at IP level */
9682 			return (-EINVAL);
9683 		default:
9684 			return (-1);
9685 		}
9686 		break;
9687 	case IPPROTO_IPV6:
9688 		/*
9689 		 * IPPROTO_IPV6 options are only supported for sockets
9690 		 * that are using IPv6 on the wire.
9691 		 */
9692 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9693 			return (-1);
9694 		}
9695 		switch (name) {
9696 		case IPV6_UNICAST_HOPS:
9697 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9698 			break;	/* goto sizeof (int) option return */
9699 		case IPV6_BOUND_IF:
9700 			/* Zero if not set */
9701 			*i1 = tcp->tcp_bound_if;
9702 			break;	/* goto sizeof (int) option return */
9703 		case IPV6_RECVPKTINFO:
9704 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9705 				*i1 = 1;
9706 			else
9707 				*i1 = 0;
9708 			break;	/* goto sizeof (int) option return */
9709 		case IPV6_RECVTCLASS:
9710 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9711 				*i1 = 1;
9712 			else
9713 				*i1 = 0;
9714 			break;	/* goto sizeof (int) option return */
9715 		case IPV6_RECVHOPLIMIT:
9716 			if (tcp->tcp_ipv6_recvancillary &
9717 			    TCP_IPV6_RECVHOPLIMIT)
9718 				*i1 = 1;
9719 			else
9720 				*i1 = 0;
9721 			break;	/* goto sizeof (int) option return */
9722 		case IPV6_RECVHOPOPTS:
9723 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9724 				*i1 = 1;
9725 			else
9726 				*i1 = 0;
9727 			break;	/* goto sizeof (int) option return */
9728 		case IPV6_RECVDSTOPTS:
9729 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9730 				*i1 = 1;
9731 			else
9732 				*i1 = 0;
9733 			break;	/* goto sizeof (int) option return */
9734 		case _OLD_IPV6_RECVDSTOPTS:
9735 			if (tcp->tcp_ipv6_recvancillary &
9736 			    TCP_OLD_IPV6_RECVDSTOPTS)
9737 				*i1 = 1;
9738 			else
9739 				*i1 = 0;
9740 			break;	/* goto sizeof (int) option return */
9741 		case IPV6_RECVRTHDR:
9742 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9743 				*i1 = 1;
9744 			else
9745 				*i1 = 0;
9746 			break;	/* goto sizeof (int) option return */
9747 		case IPV6_RECVRTHDRDSTOPTS:
9748 			if (tcp->tcp_ipv6_recvancillary &
9749 			    TCP_IPV6_RECVRTDSTOPTS)
9750 				*i1 = 1;
9751 			else
9752 				*i1 = 0;
9753 			break;	/* goto sizeof (int) option return */
9754 		case IPV6_PKTINFO: {
9755 			/* XXX assumes that caller has room for max size! */
9756 			struct in6_pktinfo *pkti;
9757 
9758 			pkti = (struct in6_pktinfo *)ptr;
9759 			if (ipp->ipp_fields & IPPF_IFINDEX)
9760 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9761 			else
9762 				pkti->ipi6_ifindex = 0;
9763 			if (ipp->ipp_fields & IPPF_ADDR)
9764 				pkti->ipi6_addr = ipp->ipp_addr;
9765 			else
9766 				pkti->ipi6_addr = ipv6_all_zeros;
9767 			return (sizeof (struct in6_pktinfo));
9768 		}
9769 		case IPV6_TCLASS:
9770 			if (ipp->ipp_fields & IPPF_TCLASS)
9771 				*i1 = ipp->ipp_tclass;
9772 			else
9773 				*i1 = IPV6_FLOW_TCLASS(
9774 				    IPV6_DEFAULT_VERS_AND_FLOW);
9775 			break;	/* goto sizeof (int) option return */
9776 		case IPV6_NEXTHOP: {
9777 			sin6_t *sin6 = (sin6_t *)ptr;
9778 
9779 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9780 				return (0);
9781 			*sin6 = sin6_null;
9782 			sin6->sin6_family = AF_INET6;
9783 			sin6->sin6_addr = ipp->ipp_nexthop;
9784 			return (sizeof (sin6_t));
9785 		}
9786 		case IPV6_HOPOPTS:
9787 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9788 				return (0);
9789 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9790 				return (0);
9791 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9792 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9793 			if (tcp->tcp_label_len > 0) {
9794 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9795 				ptr[1] = (ipp->ipp_hopoptslen -
9796 				    tcp->tcp_label_len + 7) / 8 - 1;
9797 			}
9798 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9799 		case IPV6_RTHDRDSTOPTS:
9800 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9801 				return (0);
9802 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9803 			return (ipp->ipp_rtdstoptslen);
9804 		case IPV6_RTHDR:
9805 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9806 				return (0);
9807 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9808 			return (ipp->ipp_rthdrlen);
9809 		case IPV6_DSTOPTS:
9810 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9811 				return (0);
9812 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9813 			return (ipp->ipp_dstoptslen);
9814 		case IPV6_SRC_PREFERENCES:
9815 			return (ip6_get_src_preferences(connp,
9816 			    (uint32_t *)ptr));
9817 		case IPV6_PATHMTU: {
9818 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9819 
9820 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9821 				return (-1);
9822 
9823 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9824 			    connp->conn_fport, mtuinfo,
9825 			    connp->conn_netstack));
9826 		}
9827 		default:
9828 			return (-1);
9829 		}
9830 		break;
9831 	default:
9832 		return (-1);
9833 	}
9834 	return (sizeof (int));
9835 }
9836 
9837 /*
9838  * TCP routine to get the values of options.
9839  */
9840 int
9841 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
9842 {
9843 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
9844 }
9845 
9846 /* returns UNIX error, the optlen is a value-result arg */
9847 int
9848 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
9849     void *optvalp, socklen_t *optlen, cred_t *cr)
9850 {
9851 	conn_t		*connp = (conn_t *)proto_handle;
9852 	squeue_t	*sqp = connp->conn_sqp;
9853 	int		error;
9854 	t_uscalar_t	max_optbuf_len;
9855 	void		*optvalp_buf;
9856 	int		len;
9857 
9858 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
9859 	    tcp_opt_obj.odb_opt_des_arr,
9860 	    tcp_opt_obj.odb_opt_arr_cnt,
9861 	    tcp_opt_obj.odb_topmost_tpiprovider,
9862 	    B_FALSE, B_TRUE, cr);
9863 	if (error != 0) {
9864 		if (error < 0) {
9865 			error = proto_tlitosyserr(-error);
9866 		}
9867 		return (error);
9868 	}
9869 
9870 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
9871 
9872 	error = squeue_synch_enter(sqp, connp, 0);
9873 	if (error == ENOMEM) {
9874 		return (ENOMEM);
9875 	}
9876 
9877 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
9878 	squeue_synch_exit(sqp, connp);
9879 
9880 	if (len < 0) {
9881 		/*
9882 		 * Pass on to IP
9883 		 */
9884 		kmem_free(optvalp_buf, max_optbuf_len);
9885 		return (ip_get_options(connp, level, option_name,
9886 		    optvalp, optlen, cr));
9887 	} else {
9888 		/*
9889 		 * update optlen and copy option value
9890 		 */
9891 		t_uscalar_t size = MIN(len, *optlen);
9892 		bcopy(optvalp_buf, optvalp, size);
9893 		bcopy(&size, optlen, sizeof (size));
9894 
9895 		kmem_free(optvalp_buf, max_optbuf_len);
9896 		return (0);
9897 	}
9898 }
9899 
9900 /*
9901  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9902  * Parameters are assumed to be verified by the caller.
9903  */
9904 /* ARGSUSED */
9905 int
9906 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
9907     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9908     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9909 {
9910 	tcp_t	*tcp = connp->conn_tcp;
9911 	int	*i1 = (int *)invalp;
9912 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9913 	boolean_t checkonly;
9914 	int	reterr;
9915 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9916 
9917 	switch (optset_context) {
9918 	case SETFN_OPTCOM_CHECKONLY:
9919 		checkonly = B_TRUE;
9920 		/*
9921 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9922 		 * inlen != 0 implies value supplied and
9923 		 * 	we have to "pretend" to set it.
9924 		 * inlen == 0 implies that there is no
9925 		 * 	value part in T_CHECK request and just validation
9926 		 * done elsewhere should be enough, we just return here.
9927 		 */
9928 		if (inlen == 0) {
9929 			*outlenp = 0;
9930 			return (0);
9931 		}
9932 		break;
9933 	case SETFN_OPTCOM_NEGOTIATE:
9934 		checkonly = B_FALSE;
9935 		break;
9936 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9937 	case SETFN_CONN_NEGOTIATE:
9938 		checkonly = B_FALSE;
9939 		/*
9940 		 * Negotiating local and "association-related" options
9941 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9942 		 * primitives is allowed by XTI, but we choose
9943 		 * to not implement this style negotiation for Internet
9944 		 * protocols (We interpret it is a must for OSI world but
9945 		 * optional for Internet protocols) for all options.
9946 		 * [ Will do only for the few options that enable test
9947 		 * suites that our XTI implementation of this feature
9948 		 * works for transports that do allow it ]
9949 		 */
9950 		if (!tcp_allow_connopt_set(level, name)) {
9951 			*outlenp = 0;
9952 			return (EINVAL);
9953 		}
9954 		break;
9955 	default:
9956 		/*
9957 		 * We should never get here
9958 		 */
9959 		*outlenp = 0;
9960 		return (EINVAL);
9961 	}
9962 
9963 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9964 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9965 
9966 	/*
9967 	 * For TCP, we should have no ancillary data sent down
9968 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9969 	 * has to be zero.
9970 	 */
9971 	ASSERT(thisdg_attrs == NULL);
9972 
9973 	/*
9974 	 * For fixed length options, no sanity check
9975 	 * of passed in length is done. It is assumed *_optcom_req()
9976 	 * routines do the right thing.
9977 	 */
9978 	switch (level) {
9979 	case SOL_SOCKET:
9980 		switch (name) {
9981 		case SO_LINGER: {
9982 			struct linger *lgr = (struct linger *)invalp;
9983 
9984 			if (!checkonly) {
9985 				if (lgr->l_onoff) {
9986 					tcp->tcp_linger = 1;
9987 					tcp->tcp_lingertime = lgr->l_linger;
9988 				} else {
9989 					tcp->tcp_linger = 0;
9990 					tcp->tcp_lingertime = 0;
9991 				}
9992 				/* struct copy */
9993 				*(struct linger *)outvalp = *lgr;
9994 			} else {
9995 				if (!lgr->l_onoff) {
9996 					((struct linger *)
9997 					    outvalp)->l_onoff = 0;
9998 					((struct linger *)
9999 					    outvalp)->l_linger = 0;
10000 				} else {
10001 					/* struct copy */
10002 					*(struct linger *)outvalp = *lgr;
10003 				}
10004 			}
10005 			*outlenp = sizeof (struct linger);
10006 			return (0);
10007 		}
10008 		case SO_DEBUG:
10009 			if (!checkonly)
10010 				tcp->tcp_debug = onoff;
10011 			break;
10012 		case SO_KEEPALIVE:
10013 			if (checkonly) {
10014 				/* check only case */
10015 				break;
10016 			}
10017 
10018 			if (!onoff) {
10019 				if (tcp->tcp_ka_enabled) {
10020 					if (tcp->tcp_ka_tid != 0) {
10021 						(void) TCP_TIMER_CANCEL(tcp,
10022 						    tcp->tcp_ka_tid);
10023 						tcp->tcp_ka_tid = 0;
10024 					}
10025 					tcp->tcp_ka_enabled = 0;
10026 				}
10027 				break;
10028 			}
10029 			if (!tcp->tcp_ka_enabled) {
10030 				/* Crank up the keepalive timer */
10031 				tcp->tcp_ka_last_intrvl = 0;
10032 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10033 				    tcp_keepalive_killer,
10034 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10035 				tcp->tcp_ka_enabled = 1;
10036 			}
10037 			break;
10038 		case SO_DONTROUTE:
10039 			/*
10040 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10041 			 * only of interest to IP.  We track them here only so
10042 			 * that we can report their current value.
10043 			 */
10044 			if (!checkonly) {
10045 				tcp->tcp_dontroute = onoff;
10046 				tcp->tcp_connp->conn_dontroute = onoff;
10047 			}
10048 			break;
10049 		case SO_USELOOPBACK:
10050 			if (!checkonly) {
10051 				tcp->tcp_useloopback = onoff;
10052 				tcp->tcp_connp->conn_loopback = onoff;
10053 			}
10054 			break;
10055 		case SO_BROADCAST:
10056 			if (!checkonly) {
10057 				tcp->tcp_broadcast = onoff;
10058 				tcp->tcp_connp->conn_broadcast = onoff;
10059 			}
10060 			break;
10061 		case SO_REUSEADDR:
10062 			if (!checkonly) {
10063 				tcp->tcp_reuseaddr = onoff;
10064 				tcp->tcp_connp->conn_reuseaddr = onoff;
10065 			}
10066 			break;
10067 		case SO_OOBINLINE:
10068 			if (!checkonly) {
10069 				tcp->tcp_oobinline = onoff;
10070 				if (IPCL_IS_NONSTR(tcp->tcp_connp))
10071 					proto_set_rx_oob_opt(connp, onoff);
10072 			}
10073 			break;
10074 		case SO_DGRAM_ERRIND:
10075 			if (!checkonly)
10076 				tcp->tcp_dgram_errind = onoff;
10077 			break;
10078 		case SO_SNDBUF: {
10079 			if (*i1 > tcps->tcps_max_buf) {
10080 				*outlenp = 0;
10081 				return (ENOBUFS);
10082 			}
10083 			if (checkonly)
10084 				break;
10085 
10086 			tcp->tcp_xmit_hiwater = *i1;
10087 			if (tcps->tcps_snd_lowat_fraction != 0)
10088 				tcp->tcp_xmit_lowater =
10089 				    tcp->tcp_xmit_hiwater /
10090 				    tcps->tcps_snd_lowat_fraction;
10091 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10092 			/*
10093 			 * If we are flow-controlled, recheck the condition.
10094 			 * There are apps that increase SO_SNDBUF size when
10095 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10096 			 * control condition to be lifted right away.
10097 			 */
10098 			mutex_enter(&tcp->tcp_non_sq_lock);
10099 			if (tcp->tcp_flow_stopped &&
10100 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10101 				tcp_clrqfull(tcp);
10102 			}
10103 			mutex_exit(&tcp->tcp_non_sq_lock);
10104 			break;
10105 		}
10106 		case SO_RCVBUF:
10107 			if (*i1 > tcps->tcps_max_buf) {
10108 				*outlenp = 0;
10109 				return (ENOBUFS);
10110 			}
10111 			/* Silently ignore zero */
10112 			if (!checkonly && *i1 != 0) {
10113 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10114 				(void) tcp_rwnd_set(tcp, *i1);
10115 			}
10116 			/*
10117 			 * XXX should we return the rwnd here
10118 			 * and tcp_opt_get ?
10119 			 */
10120 			break;
10121 		case SO_SND_COPYAVOID:
10122 			if (!checkonly) {
10123 				/* we only allow enable at most once for now */
10124 				if (tcp->tcp_loopback ||
10125 				    (tcp->tcp_kssl_ctx != NULL) ||
10126 				    (!tcp->tcp_snd_zcopy_aware &&
10127 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10128 					*outlenp = 0;
10129 					return (EOPNOTSUPP);
10130 				}
10131 				tcp->tcp_snd_zcopy_aware = 1;
10132 			}
10133 			break;
10134 		case SO_ALLZONES:
10135 			/* Pass option along to IP level for handling */
10136 			return (-EINVAL);
10137 		case SO_ANON_MLP:
10138 			/* Pass option along to IP level for handling */
10139 			return (-EINVAL);
10140 		case SO_MAC_EXEMPT:
10141 			/* Pass option along to IP level for handling */
10142 			return (-EINVAL);
10143 		case SO_EXCLBIND:
10144 			if (!checkonly)
10145 				tcp->tcp_exclbind = onoff;
10146 			break;
10147 		default:
10148 			*outlenp = 0;
10149 			return (EINVAL);
10150 		}
10151 		break;
10152 	case IPPROTO_TCP:
10153 		switch (name) {
10154 		case TCP_NODELAY:
10155 			if (!checkonly)
10156 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10157 			break;
10158 		case TCP_NOTIFY_THRESHOLD:
10159 			if (!checkonly)
10160 				tcp->tcp_first_timer_threshold = *i1;
10161 			break;
10162 		case TCP_ABORT_THRESHOLD:
10163 			if (!checkonly)
10164 				tcp->tcp_second_timer_threshold = *i1;
10165 			break;
10166 		case TCP_CONN_NOTIFY_THRESHOLD:
10167 			if (!checkonly)
10168 				tcp->tcp_first_ctimer_threshold = *i1;
10169 			break;
10170 		case TCP_CONN_ABORT_THRESHOLD:
10171 			if (!checkonly)
10172 				tcp->tcp_second_ctimer_threshold = *i1;
10173 			break;
10174 		case TCP_RECVDSTADDR:
10175 			if (tcp->tcp_state > TCPS_LISTEN)
10176 				return (EOPNOTSUPP);
10177 			if (!checkonly)
10178 				tcp->tcp_recvdstaddr = onoff;
10179 			break;
10180 		case TCP_ANONPRIVBIND:
10181 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10182 			    IPPROTO_TCP)) != 0) {
10183 				*outlenp = 0;
10184 				return (reterr);
10185 			}
10186 			if (!checkonly) {
10187 				tcp->tcp_anon_priv_bind = onoff;
10188 			}
10189 			break;
10190 		case TCP_EXCLBIND:
10191 			if (!checkonly)
10192 				tcp->tcp_exclbind = onoff;
10193 			break;	/* goto sizeof (int) option return */
10194 		case TCP_INIT_CWND: {
10195 			uint32_t init_cwnd = *((uint32_t *)invalp);
10196 
10197 			if (checkonly)
10198 				break;
10199 
10200 			/*
10201 			 * Only allow socket with network configuration
10202 			 * privilege to set the initial cwnd to be larger
10203 			 * than allowed by RFC 3390.
10204 			 */
10205 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10206 				tcp->tcp_init_cwnd = init_cwnd;
10207 				break;
10208 			}
10209 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10210 				*outlenp = 0;
10211 				return (reterr);
10212 			}
10213 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10214 				*outlenp = 0;
10215 				return (EINVAL);
10216 			}
10217 			tcp->tcp_init_cwnd = init_cwnd;
10218 			break;
10219 		}
10220 		case TCP_KEEPALIVE_THRESHOLD:
10221 			if (checkonly)
10222 				break;
10223 
10224 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10225 			    *i1 > tcps->tcps_keepalive_interval_high) {
10226 				*outlenp = 0;
10227 				return (EINVAL);
10228 			}
10229 			if (*i1 != tcp->tcp_ka_interval) {
10230 				tcp->tcp_ka_interval = *i1;
10231 				/*
10232 				 * Check if we need to restart the
10233 				 * keepalive timer.
10234 				 */
10235 				if (tcp->tcp_ka_tid != 0) {
10236 					ASSERT(tcp->tcp_ka_enabled);
10237 					(void) TCP_TIMER_CANCEL(tcp,
10238 					    tcp->tcp_ka_tid);
10239 					tcp->tcp_ka_last_intrvl = 0;
10240 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10241 					    tcp_keepalive_killer,
10242 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10243 				}
10244 			}
10245 			break;
10246 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10247 			if (!checkonly) {
10248 				if (*i1 <
10249 				    tcps->tcps_keepalive_abort_interval_low ||
10250 				    *i1 >
10251 				    tcps->tcps_keepalive_abort_interval_high) {
10252 					*outlenp = 0;
10253 					return (EINVAL);
10254 				}
10255 				tcp->tcp_ka_abort_thres = *i1;
10256 			}
10257 			break;
10258 		case TCP_CORK:
10259 			if (!checkonly) {
10260 				/*
10261 				 * if tcp->tcp_cork was set and is now
10262 				 * being unset, we have to make sure that
10263 				 * the remaining data gets sent out. Also
10264 				 * unset tcp->tcp_cork so that tcp_wput_data()
10265 				 * can send data even if it is less than mss
10266 				 */
10267 				if (tcp->tcp_cork && onoff == 0 &&
10268 				    tcp->tcp_unsent > 0) {
10269 					tcp->tcp_cork = B_FALSE;
10270 					tcp_wput_data(tcp, NULL, B_FALSE);
10271 				}
10272 				tcp->tcp_cork = onoff;
10273 			}
10274 			break;
10275 		default:
10276 			*outlenp = 0;
10277 			return (EINVAL);
10278 		}
10279 		break;
10280 	case IPPROTO_IP:
10281 		if (tcp->tcp_family != AF_INET) {
10282 			*outlenp = 0;
10283 			return (ENOPROTOOPT);
10284 		}
10285 		switch (name) {
10286 		case IP_OPTIONS:
10287 		case T_IP_OPTIONS:
10288 			reterr = tcp_opt_set_header(tcp, checkonly,
10289 			    invalp, inlen);
10290 			if (reterr) {
10291 				*outlenp = 0;
10292 				return (reterr);
10293 			}
10294 			/* OK return - copy input buffer into output buffer */
10295 			if (invalp != outvalp) {
10296 				/* don't trust bcopy for identical src/dst */
10297 				bcopy(invalp, outvalp, inlen);
10298 			}
10299 			*outlenp = inlen;
10300 			return (0);
10301 		case IP_TOS:
10302 		case T_IP_TOS:
10303 			if (!checkonly) {
10304 				tcp->tcp_ipha->ipha_type_of_service =
10305 				    (uchar_t)*i1;
10306 				tcp->tcp_tos = (uchar_t)*i1;
10307 			}
10308 			break;
10309 		case IP_TTL:
10310 			if (!checkonly) {
10311 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10312 				tcp->tcp_ttl = (uchar_t)*i1;
10313 			}
10314 			break;
10315 		case IP_BOUND_IF:
10316 		case IP_NEXTHOP:
10317 			/* Handled at the IP level */
10318 			return (-EINVAL);
10319 		case IP_SEC_OPT:
10320 			/*
10321 			 * We should not allow policy setting after
10322 			 * we start listening for connections.
10323 			 */
10324 			if (tcp->tcp_state == TCPS_LISTEN) {
10325 				return (EINVAL);
10326 			} else {
10327 				/* Handled at the IP level */
10328 				return (-EINVAL);
10329 			}
10330 		default:
10331 			*outlenp = 0;
10332 			return (EINVAL);
10333 		}
10334 		break;
10335 	case IPPROTO_IPV6: {
10336 		ip6_pkt_t		*ipp;
10337 
10338 		/*
10339 		 * IPPROTO_IPV6 options are only supported for sockets
10340 		 * that are using IPv6 on the wire.
10341 		 */
10342 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10343 			*outlenp = 0;
10344 			return (ENOPROTOOPT);
10345 		}
10346 		/*
10347 		 * Only sticky options; no ancillary data
10348 		 */
10349 		ipp = &tcp->tcp_sticky_ipp;
10350 
10351 		switch (name) {
10352 		case IPV6_UNICAST_HOPS:
10353 			/* -1 means use default */
10354 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10355 				*outlenp = 0;
10356 				return (EINVAL);
10357 			}
10358 			if (!checkonly) {
10359 				if (*i1 == -1) {
10360 					tcp->tcp_ip6h->ip6_hops =
10361 					    ipp->ipp_unicast_hops =
10362 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10363 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10364 					/* Pass modified value to IP. */
10365 					*i1 = tcp->tcp_ip6h->ip6_hops;
10366 				} else {
10367 					tcp->tcp_ip6h->ip6_hops =
10368 					    ipp->ipp_unicast_hops =
10369 					    (uint8_t)*i1;
10370 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10371 				}
10372 				reterr = tcp_build_hdrs(tcp);
10373 				if (reterr != 0)
10374 					return (reterr);
10375 			}
10376 			break;
10377 		case IPV6_BOUND_IF:
10378 			if (!checkonly) {
10379 				tcp->tcp_bound_if = *i1;
10380 				PASS_OPT_TO_IP(connp);
10381 			}
10382 			break;
10383 		/*
10384 		 * Set boolean switches for ancillary data delivery
10385 		 */
10386 		case IPV6_RECVPKTINFO:
10387 			if (!checkonly) {
10388 				if (onoff)
10389 					tcp->tcp_ipv6_recvancillary |=
10390 					    TCP_IPV6_RECVPKTINFO;
10391 				else
10392 					tcp->tcp_ipv6_recvancillary &=
10393 					    ~TCP_IPV6_RECVPKTINFO;
10394 				/* Force it to be sent up with the next msg */
10395 				tcp->tcp_recvifindex = 0;
10396 				PASS_OPT_TO_IP(connp);
10397 			}
10398 			break;
10399 		case IPV6_RECVTCLASS:
10400 			if (!checkonly) {
10401 				if (onoff)
10402 					tcp->tcp_ipv6_recvancillary |=
10403 					    TCP_IPV6_RECVTCLASS;
10404 				else
10405 					tcp->tcp_ipv6_recvancillary &=
10406 					    ~TCP_IPV6_RECVTCLASS;
10407 				PASS_OPT_TO_IP(connp);
10408 			}
10409 			break;
10410 		case IPV6_RECVHOPLIMIT:
10411 			if (!checkonly) {
10412 				if (onoff)
10413 					tcp->tcp_ipv6_recvancillary |=
10414 					    TCP_IPV6_RECVHOPLIMIT;
10415 				else
10416 					tcp->tcp_ipv6_recvancillary &=
10417 					    ~TCP_IPV6_RECVHOPLIMIT;
10418 				/* Force it to be sent up with the next msg */
10419 				tcp->tcp_recvhops = 0xffffffffU;
10420 				PASS_OPT_TO_IP(connp);
10421 			}
10422 			break;
10423 		case IPV6_RECVHOPOPTS:
10424 			if (!checkonly) {
10425 				if (onoff)
10426 					tcp->tcp_ipv6_recvancillary |=
10427 					    TCP_IPV6_RECVHOPOPTS;
10428 				else
10429 					tcp->tcp_ipv6_recvancillary &=
10430 					    ~TCP_IPV6_RECVHOPOPTS;
10431 				PASS_OPT_TO_IP(connp);
10432 			}
10433 			break;
10434 		case IPV6_RECVDSTOPTS:
10435 			if (!checkonly) {
10436 				if (onoff)
10437 					tcp->tcp_ipv6_recvancillary |=
10438 					    TCP_IPV6_RECVDSTOPTS;
10439 				else
10440 					tcp->tcp_ipv6_recvancillary &=
10441 					    ~TCP_IPV6_RECVDSTOPTS;
10442 				PASS_OPT_TO_IP(connp);
10443 			}
10444 			break;
10445 		case _OLD_IPV6_RECVDSTOPTS:
10446 			if (!checkonly) {
10447 				if (onoff)
10448 					tcp->tcp_ipv6_recvancillary |=
10449 					    TCP_OLD_IPV6_RECVDSTOPTS;
10450 				else
10451 					tcp->tcp_ipv6_recvancillary &=
10452 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10453 			}
10454 			break;
10455 		case IPV6_RECVRTHDR:
10456 			if (!checkonly) {
10457 				if (onoff)
10458 					tcp->tcp_ipv6_recvancillary |=
10459 					    TCP_IPV6_RECVRTHDR;
10460 				else
10461 					tcp->tcp_ipv6_recvancillary &=
10462 					    ~TCP_IPV6_RECVRTHDR;
10463 				PASS_OPT_TO_IP(connp);
10464 			}
10465 			break;
10466 		case IPV6_RECVRTHDRDSTOPTS:
10467 			if (!checkonly) {
10468 				if (onoff)
10469 					tcp->tcp_ipv6_recvancillary |=
10470 					    TCP_IPV6_RECVRTDSTOPTS;
10471 				else
10472 					tcp->tcp_ipv6_recvancillary &=
10473 					    ~TCP_IPV6_RECVRTDSTOPTS;
10474 				PASS_OPT_TO_IP(connp);
10475 			}
10476 			break;
10477 		case IPV6_PKTINFO:
10478 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10479 				return (EINVAL);
10480 			if (checkonly)
10481 				break;
10482 
10483 			if (inlen == 0) {
10484 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10485 			} else {
10486 				struct in6_pktinfo *pkti;
10487 
10488 				pkti = (struct in6_pktinfo *)invalp;
10489 				/*
10490 				 * RFC 3542 states that ipi6_addr must be
10491 				 * the unspecified address when setting the
10492 				 * IPV6_PKTINFO sticky socket option on a
10493 				 * TCP socket.
10494 				 */
10495 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10496 					return (EINVAL);
10497 				/*
10498 				 * IP will validate the source address and
10499 				 * interface index.
10500 				 */
10501 				if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
10502 					reterr = ip_set_options(tcp->tcp_connp,
10503 					    level, name, invalp, inlen, cr);
10504 				} else {
10505 					reterr = ip6_set_pktinfo(cr,
10506 					    tcp->tcp_connp, pkti, mblk);
10507 				}
10508 				if (reterr != 0)
10509 					return (reterr);
10510 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10511 				ipp->ipp_addr = pkti->ipi6_addr;
10512 				if (ipp->ipp_ifindex != 0)
10513 					ipp->ipp_fields |= IPPF_IFINDEX;
10514 				else
10515 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10516 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10517 					ipp->ipp_fields |= IPPF_ADDR;
10518 				else
10519 					ipp->ipp_fields &= ~IPPF_ADDR;
10520 			}
10521 			reterr = tcp_build_hdrs(tcp);
10522 			if (reterr != 0)
10523 				return (reterr);
10524 			break;
10525 		case IPV6_TCLASS:
10526 			if (inlen != 0 && inlen != sizeof (int))
10527 				return (EINVAL);
10528 			if (checkonly)
10529 				break;
10530 
10531 			if (inlen == 0) {
10532 				ipp->ipp_fields &= ~IPPF_TCLASS;
10533 			} else {
10534 				if (*i1 > 255 || *i1 < -1)
10535 					return (EINVAL);
10536 				if (*i1 == -1) {
10537 					ipp->ipp_tclass = 0;
10538 					*i1 = 0;
10539 				} else {
10540 					ipp->ipp_tclass = *i1;
10541 				}
10542 				ipp->ipp_fields |= IPPF_TCLASS;
10543 			}
10544 			reterr = tcp_build_hdrs(tcp);
10545 			if (reterr != 0)
10546 				return (reterr);
10547 			break;
10548 		case IPV6_NEXTHOP:
10549 			/*
10550 			 * IP will verify that the nexthop is reachable
10551 			 * and fail for sticky options.
10552 			 */
10553 			if (inlen != 0 && inlen != sizeof (sin6_t))
10554 				return (EINVAL);
10555 			if (checkonly)
10556 				break;
10557 
10558 			if (inlen == 0) {
10559 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10560 			} else {
10561 				sin6_t *sin6 = (sin6_t *)invalp;
10562 
10563 				if (sin6->sin6_family != AF_INET6)
10564 					return (EAFNOSUPPORT);
10565 				if (IN6_IS_ADDR_V4MAPPED(
10566 				    &sin6->sin6_addr))
10567 					return (EADDRNOTAVAIL);
10568 				ipp->ipp_nexthop = sin6->sin6_addr;
10569 				if (!IN6_IS_ADDR_UNSPECIFIED(
10570 				    &ipp->ipp_nexthop))
10571 					ipp->ipp_fields |= IPPF_NEXTHOP;
10572 				else
10573 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10574 			}
10575 			reterr = tcp_build_hdrs(tcp);
10576 			if (reterr != 0)
10577 				return (reterr);
10578 			PASS_OPT_TO_IP(connp);
10579 			break;
10580 		case IPV6_HOPOPTS: {
10581 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10582 
10583 			/*
10584 			 * Sanity checks - minimum size, size a multiple of
10585 			 * eight bytes, and matching size passed in.
10586 			 */
10587 			if (inlen != 0 &&
10588 			    inlen != (8 * (hopts->ip6h_len + 1)))
10589 				return (EINVAL);
10590 
10591 			if (checkonly)
10592 				break;
10593 
10594 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10595 			    (uchar_t **)&ipp->ipp_hopopts,
10596 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10597 			if (reterr != 0)
10598 				return (reterr);
10599 			if (ipp->ipp_hopoptslen == 0)
10600 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10601 			else
10602 				ipp->ipp_fields |= IPPF_HOPOPTS;
10603 			reterr = tcp_build_hdrs(tcp);
10604 			if (reterr != 0)
10605 				return (reterr);
10606 			break;
10607 		}
10608 		case IPV6_RTHDRDSTOPTS: {
10609 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10610 
10611 			/*
10612 			 * Sanity checks - minimum size, size a multiple of
10613 			 * eight bytes, and matching size passed in.
10614 			 */
10615 			if (inlen != 0 &&
10616 			    inlen != (8 * (dopts->ip6d_len + 1)))
10617 				return (EINVAL);
10618 
10619 			if (checkonly)
10620 				break;
10621 
10622 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10623 			    (uchar_t **)&ipp->ipp_rtdstopts,
10624 			    &ipp->ipp_rtdstoptslen, 0);
10625 			if (reterr != 0)
10626 				return (reterr);
10627 			if (ipp->ipp_rtdstoptslen == 0)
10628 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10629 			else
10630 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10631 			reterr = tcp_build_hdrs(tcp);
10632 			if (reterr != 0)
10633 				return (reterr);
10634 			break;
10635 		}
10636 		case IPV6_DSTOPTS: {
10637 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10638 
10639 			/*
10640 			 * Sanity checks - minimum size, size a multiple of
10641 			 * eight bytes, and matching size passed in.
10642 			 */
10643 			if (inlen != 0 &&
10644 			    inlen != (8 * (dopts->ip6d_len + 1)))
10645 				return (EINVAL);
10646 
10647 			if (checkonly)
10648 				break;
10649 
10650 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10651 			    (uchar_t **)&ipp->ipp_dstopts,
10652 			    &ipp->ipp_dstoptslen, 0);
10653 			if (reterr != 0)
10654 				return (reterr);
10655 			if (ipp->ipp_dstoptslen == 0)
10656 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10657 			else
10658 				ipp->ipp_fields |= IPPF_DSTOPTS;
10659 			reterr = tcp_build_hdrs(tcp);
10660 			if (reterr != 0)
10661 				return (reterr);
10662 			break;
10663 		}
10664 		case IPV6_RTHDR: {
10665 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10666 
10667 			/*
10668 			 * Sanity checks - minimum size, size a multiple of
10669 			 * eight bytes, and matching size passed in.
10670 			 */
10671 			if (inlen != 0 &&
10672 			    inlen != (8 * (rt->ip6r_len + 1)))
10673 				return (EINVAL);
10674 
10675 			if (checkonly)
10676 				break;
10677 
10678 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10679 			    (uchar_t **)&ipp->ipp_rthdr,
10680 			    &ipp->ipp_rthdrlen, 0);
10681 			if (reterr != 0)
10682 				return (reterr);
10683 			if (ipp->ipp_rthdrlen == 0)
10684 				ipp->ipp_fields &= ~IPPF_RTHDR;
10685 			else
10686 				ipp->ipp_fields |= IPPF_RTHDR;
10687 			reterr = tcp_build_hdrs(tcp);
10688 			if (reterr != 0)
10689 				return (reterr);
10690 			break;
10691 		}
10692 		case IPV6_V6ONLY:
10693 			if (!checkonly) {
10694 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10695 			}
10696 			break;
10697 		case IPV6_USE_MIN_MTU:
10698 			if (inlen != sizeof (int))
10699 				return (EINVAL);
10700 
10701 			if (*i1 < -1 || *i1 > 1)
10702 				return (EINVAL);
10703 
10704 			if (checkonly)
10705 				break;
10706 
10707 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10708 			ipp->ipp_use_min_mtu = *i1;
10709 			break;
10710 		case IPV6_SEC_OPT:
10711 			/*
10712 			 * We should not allow policy setting after
10713 			 * we start listening for connections.
10714 			 */
10715 			if (tcp->tcp_state == TCPS_LISTEN) {
10716 				return (EINVAL);
10717 			} else {
10718 				/* Handled at the IP level */
10719 				return (-EINVAL);
10720 			}
10721 		case IPV6_SRC_PREFERENCES:
10722 			if (inlen != sizeof (uint32_t))
10723 				return (EINVAL);
10724 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10725 			    *(uint32_t *)invalp);
10726 			if (reterr != 0) {
10727 				*outlenp = 0;
10728 				return (reterr);
10729 			}
10730 			break;
10731 		default:
10732 			*outlenp = 0;
10733 			return (EINVAL);
10734 		}
10735 		break;
10736 	}		/* end IPPROTO_IPV6 */
10737 	default:
10738 		*outlenp = 0;
10739 		return (EINVAL);
10740 	}
10741 	/*
10742 	 * Common case of OK return with outval same as inval
10743 	 */
10744 	if (invalp != outvalp) {
10745 		/* don't trust bcopy for identical src/dst */
10746 		(void) bcopy(invalp, outvalp, inlen);
10747 	}
10748 	*outlenp = inlen;
10749 	return (0);
10750 }
10751 
10752 /* ARGSUSED */
10753 int
10754 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10755     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10756     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10757 {
10758 	conn_t	*connp =  Q_TO_CONN(q);
10759 
10760 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
10761 	    outlenp, outvalp, thisdg_attrs, cr, mblk));
10762 }
10763 
10764 int
10765 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
10766     const void *optvalp, socklen_t optlen, cred_t *cr)
10767 {
10768 	conn_t		*connp = (conn_t *)proto_handle;
10769 	squeue_t	*sqp = connp->conn_sqp;
10770 	int		error;
10771 
10772 	/*
10773 	 * Entering the squeue synchronously can result in a context switch,
10774 	 * which can cause a rather sever performance degradation. So we try to
10775 	 * handle whatever options we can without entering the squeue.
10776 	 */
10777 	if (level == IPPROTO_TCP) {
10778 		switch (option_name) {
10779 		case TCP_NODELAY:
10780 			if (optlen != sizeof (int32_t))
10781 				return (EINVAL);
10782 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
10783 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
10784 			    connp->conn_tcp->tcp_mss;
10785 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
10786 			return (0);
10787 		default:
10788 			break;
10789 		}
10790 	}
10791 
10792 	error = squeue_synch_enter(sqp, connp, 0);
10793 	if (error == ENOMEM) {
10794 		return (ENOMEM);
10795 	}
10796 
10797 	error = proto_opt_check(level, option_name, optlen, NULL,
10798 	    tcp_opt_obj.odb_opt_des_arr,
10799 	    tcp_opt_obj.odb_opt_arr_cnt,
10800 	    tcp_opt_obj.odb_topmost_tpiprovider,
10801 	    B_TRUE, B_FALSE, cr);
10802 
10803 	if (error != 0) {
10804 		if (error < 0) {
10805 			error = proto_tlitosyserr(-error);
10806 		}
10807 		squeue_synch_exit(sqp, connp);
10808 		return (error);
10809 	}
10810 
10811 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
10812 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
10813 	    NULL, cr, NULL);
10814 	squeue_synch_exit(sqp, connp);
10815 
10816 	if (error < 0) {
10817 		/*
10818 		 * Pass on to ip
10819 		 */
10820 		error = ip_set_options(connp, level, option_name, optvalp,
10821 		    optlen, cr);
10822 	}
10823 	return (error);
10824 }
10825 
10826 /*
10827  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10828  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10829  * headers, and the maximum size tcp header (to avoid reallocation
10830  * on the fly for additional tcp options).
10831  * Returns failure if can't allocate memory.
10832  */
10833 static int
10834 tcp_build_hdrs(tcp_t *tcp)
10835 {
10836 	char	*hdrs;
10837 	uint_t	hdrs_len;
10838 	ip6i_t	*ip6i;
10839 	char	buf[TCP_MAX_HDR_LENGTH];
10840 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10841 	in6_addr_t src, dst;
10842 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10843 	conn_t *connp = tcp->tcp_connp;
10844 
10845 	/*
10846 	 * save the existing tcp header and source/dest IP addresses
10847 	 */
10848 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10849 	src = tcp->tcp_ip6h->ip6_src;
10850 	dst = tcp->tcp_ip6h->ip6_dst;
10851 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10852 	ASSERT(hdrs_len != 0);
10853 	if (hdrs_len > tcp->tcp_iphc_len) {
10854 		/* Need to reallocate */
10855 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10856 		if (hdrs == NULL)
10857 			return (ENOMEM);
10858 		if (tcp->tcp_iphc != NULL) {
10859 			if (tcp->tcp_hdr_grown) {
10860 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10861 			} else {
10862 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10863 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10864 			}
10865 			tcp->tcp_iphc_len = 0;
10866 		}
10867 		ASSERT(tcp->tcp_iphc_len == 0);
10868 		tcp->tcp_iphc = hdrs;
10869 		tcp->tcp_iphc_len = hdrs_len;
10870 		tcp->tcp_hdr_grown = B_TRUE;
10871 	}
10872 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10873 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10874 
10875 	/* Set header fields not in ipp */
10876 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10877 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10878 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10879 	} else {
10880 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10881 	}
10882 	/*
10883 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10884 	 *
10885 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10886 	 */
10887 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10888 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10889 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10890 
10891 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10892 
10893 	tcp->tcp_ip6h->ip6_src = src;
10894 	tcp->tcp_ip6h->ip6_dst = dst;
10895 
10896 	/*
10897 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10898 	 * the default value for TCP.
10899 	 */
10900 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10901 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
10902 
10903 	/*
10904 	 * If we're setting extension headers after a connection
10905 	 * has been established, and if we have a routing header
10906 	 * among the extension headers, call ip_massage_options_v6 to
10907 	 * manipulate the routing header/ip6_dst set the checksum
10908 	 * difference in the tcp header template.
10909 	 * (This happens in tcp_connect_ipv6 if the routing header
10910 	 * is set prior to the connect.)
10911 	 * Set the tcp_sum to zero first in case we've cleared a
10912 	 * routing header or don't have one at all.
10913 	 */
10914 	tcp->tcp_sum = 0;
10915 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10916 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10917 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10918 		    (uint8_t *)tcp->tcp_tcph);
10919 		if (rth != NULL) {
10920 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10921 			    rth, tcps->tcps_netstack);
10922 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10923 			    (tcp->tcp_sum >> 16));
10924 		}
10925 	}
10926 
10927 	/* Try to get everything in a single mblk */
10928 	(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
10929 	    hdrs_len + tcps->tcps_wroff_xtra);
10930 	return (0);
10931 }
10932 
10933 /*
10934  * Transfer any source route option from ipha to buf/dst in reversed form.
10935  */
10936 static int
10937 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10938 {
10939 	ipoptp_t	opts;
10940 	uchar_t		*opt;
10941 	uint8_t		optval;
10942 	uint8_t		optlen;
10943 	uint32_t	len = 0;
10944 
10945 	for (optval = ipoptp_first(&opts, ipha);
10946 	    optval != IPOPT_EOL;
10947 	    optval = ipoptp_next(&opts)) {
10948 		opt = opts.ipoptp_cur;
10949 		optlen = opts.ipoptp_len;
10950 		switch (optval) {
10951 			int	off1, off2;
10952 		case IPOPT_SSRR:
10953 		case IPOPT_LSRR:
10954 
10955 			/* Reverse source route */
10956 			/*
10957 			 * First entry should be the next to last one in the
10958 			 * current source route (the last entry is our
10959 			 * address.)
10960 			 * The last entry should be the final destination.
10961 			 */
10962 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10963 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10964 			off1 = IPOPT_MINOFF_SR - 1;
10965 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10966 			if (off2 < 0) {
10967 				/* No entries in source route */
10968 				break;
10969 			}
10970 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10971 			/*
10972 			 * Note: use src since ipha has not had its src
10973 			 * and dst reversed (it is in the state it was
10974 			 * received.
10975 			 */
10976 			bcopy(&ipha->ipha_src, buf + off2,
10977 			    IP_ADDR_LEN);
10978 			off2 -= IP_ADDR_LEN;
10979 
10980 			while (off2 > 0) {
10981 				bcopy(opt + off2, buf + off1,
10982 				    IP_ADDR_LEN);
10983 				off1 += IP_ADDR_LEN;
10984 				off2 -= IP_ADDR_LEN;
10985 			}
10986 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
10987 			buf += optlen;
10988 			len += optlen;
10989 			break;
10990 		}
10991 	}
10992 done:
10993 	/* Pad the resulting options */
10994 	while (len & 0x3) {
10995 		*buf++ = IPOPT_EOL;
10996 		len++;
10997 	}
10998 	return (len);
10999 }
11000 
11001 
11002 /*
11003  * Extract and revert a source route from ipha (if any)
11004  * and then update the relevant fields in both tcp_t and the standard header.
11005  */
11006 static void
11007 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11008 {
11009 	char	buf[TCP_MAX_HDR_LENGTH];
11010 	uint_t	tcph_len;
11011 	int	len;
11012 
11013 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11014 	len = IPH_HDR_LENGTH(ipha);
11015 	if (len == IP_SIMPLE_HDR_LENGTH)
11016 		/* Nothing to do */
11017 		return;
11018 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11019 	    (len & 0x3))
11020 		return;
11021 
11022 	tcph_len = tcp->tcp_tcp_hdr_len;
11023 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11024 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11025 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11026 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11027 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11028 	len += IP_SIMPLE_HDR_LENGTH;
11029 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11030 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11031 	if ((int)tcp->tcp_sum < 0)
11032 		tcp->tcp_sum--;
11033 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11034 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11035 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11036 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11037 	tcp->tcp_ip_hdr_len = len;
11038 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11039 	    (IP_VERSION << 4) | (len >> 2);
11040 	len += tcph_len;
11041 	tcp->tcp_hdr_len = len;
11042 }
11043 
11044 /*
11045  * Copy the standard header into its new location,
11046  * lay in the new options and then update the relevant
11047  * fields in both tcp_t and the standard header.
11048  */
11049 static int
11050 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11051 {
11052 	uint_t	tcph_len;
11053 	uint8_t	*ip_optp;
11054 	tcph_t	*new_tcph;
11055 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11056 	conn_t	*connp = tcp->tcp_connp;
11057 
11058 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11059 		return (EINVAL);
11060 
11061 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11062 		return (EINVAL);
11063 
11064 	if (checkonly) {
11065 		/*
11066 		 * do not really set, just pretend to - T_CHECK
11067 		 */
11068 		return (0);
11069 	}
11070 
11071 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11072 	if (tcp->tcp_label_len > 0) {
11073 		int padlen;
11074 		uint8_t opt;
11075 
11076 		/* convert list termination to no-ops */
11077 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11078 		ip_optp += ip_optp[IPOPT_OLEN];
11079 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11080 		while (--padlen >= 0)
11081 			*ip_optp++ = opt;
11082 	}
11083 	tcph_len = tcp->tcp_tcp_hdr_len;
11084 	new_tcph = (tcph_t *)(ip_optp + len);
11085 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11086 	tcp->tcp_tcph = new_tcph;
11087 	bcopy(ptr, ip_optp, len);
11088 
11089 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11090 
11091 	tcp->tcp_ip_hdr_len = len;
11092 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11093 	    (IP_VERSION << 4) | (len >> 2);
11094 	tcp->tcp_hdr_len = len + tcph_len;
11095 	if (!TCP_IS_DETACHED(tcp)) {
11096 		/* Always allocate room for all options. */
11097 		(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
11098 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11099 	}
11100 	return (0);
11101 }
11102 
11103 /* Get callback routine passed to nd_load by tcp_param_register */
11104 /* ARGSUSED */
11105 static int
11106 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11107 {
11108 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11109 
11110 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11111 	return (0);
11112 }
11113 
11114 /*
11115  * Walk through the param array specified registering each element with the
11116  * named dispatch handler.
11117  */
11118 static boolean_t
11119 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11120 {
11121 	for (; cnt-- > 0; tcppa++) {
11122 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11123 			if (!nd_load(ndp, tcppa->tcp_param_name,
11124 			    tcp_param_get, tcp_param_set,
11125 			    (caddr_t)tcppa)) {
11126 				nd_free(ndp);
11127 				return (B_FALSE);
11128 			}
11129 		}
11130 	}
11131 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11132 	    KM_SLEEP);
11133 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11134 	    sizeof (tcpparam_t));
11135 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11136 	    tcp_param_get, tcp_param_set_aligned,
11137 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11138 		nd_free(ndp);
11139 		return (B_FALSE);
11140 	}
11141 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11142 	    KM_SLEEP);
11143 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11144 	    sizeof (tcpparam_t));
11145 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11146 	    tcp_param_get, tcp_param_set_aligned,
11147 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11148 		nd_free(ndp);
11149 		return (B_FALSE);
11150 	}
11151 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11152 	    KM_SLEEP);
11153 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11154 	    sizeof (tcpparam_t));
11155 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11156 	    tcp_param_get, tcp_param_set_aligned,
11157 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11158 		nd_free(ndp);
11159 		return (B_FALSE);
11160 	}
11161 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11162 	    KM_SLEEP);
11163 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11164 	    sizeof (tcpparam_t));
11165 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11166 	    tcp_param_get, tcp_param_set_aligned,
11167 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11168 		nd_free(ndp);
11169 		return (B_FALSE);
11170 	}
11171 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11172 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11173 		nd_free(ndp);
11174 		return (B_FALSE);
11175 	}
11176 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11177 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11178 		nd_free(ndp);
11179 		return (B_FALSE);
11180 	}
11181 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11182 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11183 		nd_free(ndp);
11184 		return (B_FALSE);
11185 	}
11186 	if (!nd_load(ndp, "tcp_status", tcp_status_report, NULL,
11187 	    NULL)) {
11188 		nd_free(ndp);
11189 		return (B_FALSE);
11190 	}
11191 	if (!nd_load(ndp, "tcp_bind_hash", tcp_bind_hash_report,
11192 	    NULL, NULL)) {
11193 		nd_free(ndp);
11194 		return (B_FALSE);
11195 	}
11196 	if (!nd_load(ndp, "tcp_listen_hash",
11197 	    tcp_listen_hash_report, NULL, NULL)) {
11198 		nd_free(ndp);
11199 		return (B_FALSE);
11200 	}
11201 	if (!nd_load(ndp, "tcp_conn_hash", tcp_conn_hash_report,
11202 	    NULL, NULL)) {
11203 		nd_free(ndp);
11204 		return (B_FALSE);
11205 	}
11206 	if (!nd_load(ndp, "tcp_acceptor_hash",
11207 	    tcp_acceptor_hash_report, NULL, NULL)) {
11208 		nd_free(ndp);
11209 		return (B_FALSE);
11210 	}
11211 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11212 	    tcp_1948_phrase_set, NULL)) {
11213 		nd_free(ndp);
11214 		return (B_FALSE);
11215 	}
11216 	/*
11217 	 * Dummy ndd variables - only to convey obsolescence information
11218 	 * through printing of their name (no get or set routines)
11219 	 * XXX Remove in future releases ?
11220 	 */
11221 	if (!nd_load(ndp,
11222 	    "tcp_close_wait_interval(obsoleted - "
11223 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11224 		nd_free(ndp);
11225 		return (B_FALSE);
11226 	}
11227 	return (B_TRUE);
11228 }
11229 
11230 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11231 /* ARGSUSED */
11232 static int
11233 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11234     cred_t *cr)
11235 {
11236 	long new_value;
11237 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11238 
11239 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11240 	    new_value < tcppa->tcp_param_min ||
11241 	    new_value > tcppa->tcp_param_max) {
11242 		return (EINVAL);
11243 	}
11244 	/*
11245 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11246 	 * round it up.  For future 64 bit requirement, we actually make it
11247 	 * a multiple of 8.
11248 	 */
11249 	if (new_value & 0x7) {
11250 		new_value = (new_value & ~0x7) + 0x8;
11251 	}
11252 	tcppa->tcp_param_val = new_value;
11253 	return (0);
11254 }
11255 
11256 /* Set callback routine passed to nd_load by tcp_param_register */
11257 /* ARGSUSED */
11258 static int
11259 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11260 {
11261 	long	new_value;
11262 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11263 
11264 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11265 	    new_value < tcppa->tcp_param_min ||
11266 	    new_value > tcppa->tcp_param_max) {
11267 		return (EINVAL);
11268 	}
11269 	tcppa->tcp_param_val = new_value;
11270 	return (0);
11271 }
11272 
11273 /*
11274  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11275  * is filled, return as much as we can.  The message passed in may be
11276  * multi-part, chained using b_cont.  "start" is the starting sequence
11277  * number for this piece.
11278  */
11279 static mblk_t *
11280 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11281 {
11282 	uint32_t	end;
11283 	mblk_t		*mp1;
11284 	mblk_t		*mp2;
11285 	mblk_t		*next_mp;
11286 	uint32_t	u1;
11287 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11288 
11289 	/* Walk through all the new pieces. */
11290 	do {
11291 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11292 		    (uintptr_t)INT_MAX);
11293 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11294 		next_mp = mp->b_cont;
11295 		if (start == end) {
11296 			/* Empty.  Blast it. */
11297 			freeb(mp);
11298 			continue;
11299 		}
11300 		mp->b_cont = NULL;
11301 		TCP_REASS_SET_SEQ(mp, start);
11302 		TCP_REASS_SET_END(mp, end);
11303 		mp1 = tcp->tcp_reass_tail;
11304 		if (!mp1) {
11305 			tcp->tcp_reass_tail = mp;
11306 			tcp->tcp_reass_head = mp;
11307 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11308 			UPDATE_MIB(&tcps->tcps_mib,
11309 			    tcpInDataUnorderBytes, end - start);
11310 			continue;
11311 		}
11312 		/* New stuff completely beyond tail? */
11313 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11314 			/* Link it on end. */
11315 			mp1->b_cont = mp;
11316 			tcp->tcp_reass_tail = mp;
11317 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11318 			UPDATE_MIB(&tcps->tcps_mib,
11319 			    tcpInDataUnorderBytes, end - start);
11320 			continue;
11321 		}
11322 		mp1 = tcp->tcp_reass_head;
11323 		u1 = TCP_REASS_SEQ(mp1);
11324 		/* New stuff at the front? */
11325 		if (SEQ_LT(start, u1)) {
11326 			/* Yes... Check for overlap. */
11327 			mp->b_cont = mp1;
11328 			tcp->tcp_reass_head = mp;
11329 			tcp_reass_elim_overlap(tcp, mp);
11330 			continue;
11331 		}
11332 		/*
11333 		 * The new piece fits somewhere between the head and tail.
11334 		 * We find our slot, where mp1 precedes us and mp2 trails.
11335 		 */
11336 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11337 			u1 = TCP_REASS_SEQ(mp2);
11338 			if (SEQ_LEQ(start, u1))
11339 				break;
11340 		}
11341 		/* Link ourselves in */
11342 		mp->b_cont = mp2;
11343 		mp1->b_cont = mp;
11344 
11345 		/* Trim overlap with following mblk(s) first */
11346 		tcp_reass_elim_overlap(tcp, mp);
11347 
11348 		/* Trim overlap with preceding mblk */
11349 		tcp_reass_elim_overlap(tcp, mp1);
11350 
11351 	} while (start = end, mp = next_mp);
11352 	mp1 = tcp->tcp_reass_head;
11353 	/* Anything ready to go? */
11354 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11355 		return (NULL);
11356 	/* Eat what we can off the queue */
11357 	for (;;) {
11358 		mp = mp1->b_cont;
11359 		end = TCP_REASS_END(mp1);
11360 		TCP_REASS_SET_SEQ(mp1, 0);
11361 		TCP_REASS_SET_END(mp1, 0);
11362 		if (!mp) {
11363 			tcp->tcp_reass_tail = NULL;
11364 			break;
11365 		}
11366 		if (end != TCP_REASS_SEQ(mp)) {
11367 			mp1->b_cont = NULL;
11368 			break;
11369 		}
11370 		mp1 = mp;
11371 	}
11372 	mp1 = tcp->tcp_reass_head;
11373 	tcp->tcp_reass_head = mp;
11374 	return (mp1);
11375 }
11376 
11377 /* Eliminate any overlap that mp may have over later mblks */
11378 static void
11379 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11380 {
11381 	uint32_t	end;
11382 	mblk_t		*mp1;
11383 	uint32_t	u1;
11384 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11385 
11386 	end = TCP_REASS_END(mp);
11387 	while ((mp1 = mp->b_cont) != NULL) {
11388 		u1 = TCP_REASS_SEQ(mp1);
11389 		if (!SEQ_GT(end, u1))
11390 			break;
11391 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11392 			mp->b_wptr -= end - u1;
11393 			TCP_REASS_SET_END(mp, u1);
11394 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11395 			UPDATE_MIB(&tcps->tcps_mib,
11396 			    tcpInDataPartDupBytes, end - u1);
11397 			break;
11398 		}
11399 		mp->b_cont = mp1->b_cont;
11400 		TCP_REASS_SET_SEQ(mp1, 0);
11401 		TCP_REASS_SET_END(mp1, 0);
11402 		freeb(mp1);
11403 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11404 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11405 	}
11406 	if (!mp1)
11407 		tcp->tcp_reass_tail = mp;
11408 }
11409 
11410 static uint_t
11411 tcp_rwnd_reopen(tcp_t *tcp)
11412 {
11413 	uint_t ret = 0;
11414 	uint_t thwin;
11415 
11416 	/* Learn the latest rwnd information that we sent to the other side. */
11417 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11418 	    << tcp->tcp_rcv_ws;
11419 	/* This is peer's calculated send window (our receive window). */
11420 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11421 	/*
11422 	 * Increase the receive window to max.  But we need to do receiver
11423 	 * SWS avoidance.  This means that we need to check the increase of
11424 	 * of receive window is at least 1 MSS.
11425 	 */
11426 	if (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss) {
11427 		/*
11428 		 * If the window that the other side knows is less than max
11429 		 * deferred acks segments, send an update immediately.
11430 		 */
11431 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11432 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
11433 			ret = TH_ACK_NEEDED;
11434 		}
11435 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
11436 	}
11437 	return (ret);
11438 }
11439 
11440 /*
11441  * Send up all messages queued on tcp_rcv_list.
11442  */
11443 static uint_t
11444 tcp_rcv_drain(tcp_t *tcp)
11445 {
11446 	mblk_t *mp;
11447 	uint_t ret = 0;
11448 #ifdef DEBUG
11449 	uint_t cnt = 0;
11450 #endif
11451 	queue_t	*q = tcp->tcp_rq;
11452 
11453 	/* Can't drain on an eager connection */
11454 	if (tcp->tcp_listener != NULL)
11455 		return (ret);
11456 
11457 	/* Can't be a non-STREAMS connection or sodirect enabled */
11458 	ASSERT((!IPCL_IS_NONSTR(tcp->tcp_connp)) && SOD_NOT_ENABLED(tcp));
11459 
11460 	/* No need for the push timer now. */
11461 	if (tcp->tcp_push_tid != 0) {
11462 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11463 		tcp->tcp_push_tid = 0;
11464 	}
11465 
11466 	/*
11467 	 * Handle two cases here: we are currently fused or we were
11468 	 * previously fused and have some urgent data to be delivered
11469 	 * upstream.  The latter happens because we either ran out of
11470 	 * memory or were detached and therefore sending the SIGURG was
11471 	 * deferred until this point.  In either case we pass control
11472 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11473 	 * some work.
11474 	 */
11475 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11476 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
11477 		    tcp->tcp_fused_sigurg_mp != NULL);
11478 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11479 		    &tcp->tcp_fused_sigurg_mp))
11480 			return (ret);
11481 	}
11482 
11483 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11484 		tcp->tcp_rcv_list = mp->b_next;
11485 		mp->b_next = NULL;
11486 #ifdef DEBUG
11487 		cnt += msgdsize(mp);
11488 #endif
11489 		/* Does this need SSL processing first? */
11490 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11491 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11492 			    mblk_t *, mp);
11493 			tcp_kssl_input(tcp, mp);
11494 			continue;
11495 		}
11496 		putnext(q, mp);
11497 	}
11498 #ifdef DEBUG
11499 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11500 #endif
11501 	tcp->tcp_rcv_last_head = NULL;
11502 	tcp->tcp_rcv_last_tail = NULL;
11503 	tcp->tcp_rcv_cnt = 0;
11504 
11505 	if (canputnext(q))
11506 		return (tcp_rwnd_reopen(tcp));
11507 
11508 	return (ret);
11509 }
11510 
11511 /*
11512  * Queue data on tcp_rcv_list which is a b_next chain.
11513  * tcp_rcv_last_head/tail is the last element of this chain.
11514  * Each element of the chain is a b_cont chain.
11515  *
11516  * M_DATA messages are added to the current element.
11517  * Other messages are added as new (b_next) elements.
11518  */
11519 void
11520 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11521 {
11522 	ASSERT(seg_len == msgdsize(mp));
11523 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11524 
11525 	if (tcp->tcp_rcv_list == NULL) {
11526 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11527 		tcp->tcp_rcv_list = mp;
11528 		tcp->tcp_rcv_last_head = mp;
11529 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11530 		tcp->tcp_rcv_last_tail->b_cont = mp;
11531 	} else {
11532 		tcp->tcp_rcv_last_head->b_next = mp;
11533 		tcp->tcp_rcv_last_head = mp;
11534 	}
11535 
11536 	while (mp->b_cont)
11537 		mp = mp->b_cont;
11538 
11539 	tcp->tcp_rcv_last_tail = mp;
11540 	tcp->tcp_rcv_cnt += seg_len;
11541 	tcp->tcp_rwnd -= seg_len;
11542 }
11543 
11544 /*
11545  * The tcp_rcv_sod_XXX() functions enqueue data directly to the socket
11546  * above, in addition when uioa is enabled schedule an asynchronous uio
11547  * prior to enqueuing. They implement the combinhed semantics of the
11548  * tcp_rcv_XXX() functions, tcp_rcv_list push logic, and STREAMS putnext()
11549  * canputnext(), i.e. flow-control with backenable.
11550  *
11551  * tcp_sod_wakeup() is called where tcp_rcv_drain() would be called in the
11552  * non sodirect connection but as there are no tcp_tcv_list mblk_t's we deal
11553  * with the rcv_wnd and push timer and call the sodirect wakeup function.
11554  *
11555  * Must be called with sodp->sod_lockp held and will return with the lock
11556  * released.
11557  */
11558 static uint_t
11559 tcp_rcv_sod_wakeup(tcp_t *tcp, sodirect_t *sodp)
11560 {
11561 	queue_t		*q = tcp->tcp_rq;
11562 	uint_t		thwin;
11563 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11564 	uint_t		ret = 0;
11565 
11566 	/* Can't be an eager connection */
11567 	ASSERT(tcp->tcp_listener == NULL);
11568 
11569 	/* Caller must have lock held */
11570 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11571 
11572 	/* Sodirect mode so must not be a tcp_rcv_list */
11573 	ASSERT(tcp->tcp_rcv_list == NULL);
11574 
11575 	if (SOD_QFULL(sodp)) {
11576 		/* Q is full, mark Q for need backenable */
11577 		SOD_QSETBE(sodp);
11578 	}
11579 	/* Last advertised rwnd, i.e. rwnd last sent in a packet */
11580 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11581 	    << tcp->tcp_rcv_ws;
11582 	/* This is peer's calculated send window (our available rwnd). */
11583 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11584 	/*
11585 	 * Increase the receive window to max.  But we need to do receiver
11586 	 * SWS avoidance.  This means that we need to check the increase of
11587 	 * of receive window is at least 1 MSS.
11588 	 */
11589 	if (!SOD_QFULL(sodp) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11590 		/*
11591 		 * If the window that the other side knows is less than max
11592 		 * deferred acks segments, send an update immediately.
11593 		 */
11594 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11595 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11596 			ret = TH_ACK_NEEDED;
11597 		}
11598 		tcp->tcp_rwnd = q->q_hiwat;
11599 	}
11600 
11601 	if (!SOD_QEMPTY(sodp)) {
11602 		/* Wakeup to socket */
11603 		sodp->sod_state &= SOD_WAKE_CLR;
11604 		sodp->sod_state |= SOD_WAKE_DONE;
11605 		(sodp->sod_wakeup)(sodp);
11606 		/* wakeup() does the mutex_ext() */
11607 	} else {
11608 		/* Q is empty, no need to wake */
11609 		sodp->sod_state &= SOD_WAKE_CLR;
11610 		sodp->sod_state |= SOD_WAKE_NOT;
11611 		mutex_exit(sodp->sod_lockp);
11612 	}
11613 
11614 	/* No need for the push timer now. */
11615 	if (tcp->tcp_push_tid != 0) {
11616 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11617 		tcp->tcp_push_tid = 0;
11618 	}
11619 
11620 	return (ret);
11621 }
11622 
11623 /*
11624  * Called where tcp_rcv_enqueue()/putnext(RD(q)) would be. For M_DATA
11625  * mblk_t's if uioa enabled then start a uioa asynchronous copy directly
11626  * to the user-land buffer and flag the mblk_t as such.
11627  *
11628  * Also, handle tcp_rwnd.
11629  */
11630 uint_t
11631 tcp_rcv_sod_enqueue(tcp_t *tcp, sodirect_t *sodp, mblk_t *mp, uint_t seg_len)
11632 {
11633 	uioa_t		*uioap = &sodp->sod_uioa;
11634 	boolean_t	qfull;
11635 	uint_t		thwin;
11636 
11637 	/* Can't be an eager connection */
11638 	ASSERT(tcp->tcp_listener == NULL);
11639 
11640 	/* Caller must have lock held */
11641 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11642 
11643 	/* Sodirect mode so must not be a tcp_rcv_list */
11644 	ASSERT(tcp->tcp_rcv_list == NULL);
11645 
11646 	/* Passed in segment length must be equal to mblk_t chain data size */
11647 	ASSERT(seg_len == msgdsize(mp));
11648 
11649 	if (DB_TYPE(mp) != M_DATA) {
11650 		/* Only process M_DATA mblk_t's */
11651 		goto enq;
11652 	}
11653 	if (uioap->uioa_state & UIOA_ENABLED) {
11654 		/* Uioa is enabled */
11655 		mblk_t		*mp1 = mp;
11656 		mblk_t		*lmp = NULL;
11657 
11658 		if (seg_len > uioap->uio_resid) {
11659 			/*
11660 			 * There isn't enough uio space for the mblk_t chain
11661 			 * so disable uioa such that this and any additional
11662 			 * mblk_t data is handled by the socket and schedule
11663 			 * the socket for wakeup to finish this uioa.
11664 			 */
11665 			uioap->uioa_state &= UIOA_CLR;
11666 			uioap->uioa_state |= UIOA_FINI;
11667 			if (sodp->sod_state & SOD_WAKE_NOT) {
11668 				sodp->sod_state &= SOD_WAKE_CLR;
11669 				sodp->sod_state |= SOD_WAKE_NEED;
11670 			}
11671 			goto enq;
11672 		}
11673 		do {
11674 			uint32_t	len = MBLKL(mp1);
11675 
11676 			if (!uioamove(mp1->b_rptr, len, UIO_READ, uioap)) {
11677 				/* Scheduled, mark dblk_t as such */
11678 				DB_FLAGS(mp1) |= DBLK_UIOA;
11679 			} else {
11680 				/* Error, turn off async processing */
11681 				uioap->uioa_state &= UIOA_CLR;
11682 				uioap->uioa_state |= UIOA_FINI;
11683 				break;
11684 			}
11685 			lmp = mp1;
11686 		} while ((mp1 = mp1->b_cont) != NULL);
11687 
11688 		if (mp1 != NULL || uioap->uio_resid == 0) {
11689 			/*
11690 			 * Not all mblk_t(s) uioamoved (error) or all uio
11691 			 * space has been consumed so schedule the socket
11692 			 * for wakeup to finish this uio.
11693 			 */
11694 			sodp->sod_state &= SOD_WAKE_CLR;
11695 			sodp->sod_state |= SOD_WAKE_NEED;
11696 
11697 			/* Break the mblk chain if neccessary. */
11698 			if (mp1 != NULL && lmp != NULL) {
11699 				mp->b_next = mp1;
11700 				lmp->b_cont = NULL;
11701 			}
11702 		}
11703 	} else if (uioap->uioa_state & UIOA_FINI) {
11704 		/*
11705 		 * Post UIO_ENABLED waiting for socket to finish processing
11706 		 * so just enqueue and update tcp_rwnd.
11707 		 */
11708 		if (SOD_QFULL(sodp))
11709 			tcp->tcp_rwnd -= seg_len;
11710 	} else if (sodp->sod_want > 0) {
11711 		/*
11712 		 * Uioa isn't enabled but sodirect has a pending read().
11713 		 */
11714 		if (SOD_QCNT(sodp) + seg_len >= sodp->sod_want) {
11715 			if (sodp->sod_state & SOD_WAKE_NOT) {
11716 				/* Schedule socket for wakeup */
11717 				sodp->sod_state &= SOD_WAKE_CLR;
11718 				sodp->sod_state |= SOD_WAKE_NEED;
11719 			}
11720 			tcp->tcp_rwnd -= seg_len;
11721 		}
11722 	} else if (SOD_QCNT(sodp) + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
11723 		/*
11724 		 * No pending sodirect read() so used the default
11725 		 * TCP push logic to guess that a push is needed.
11726 		 */
11727 		if (sodp->sod_state & SOD_WAKE_NOT) {
11728 			/* Schedule socket for wakeup */
11729 			sodp->sod_state &= SOD_WAKE_CLR;
11730 			sodp->sod_state |= SOD_WAKE_NEED;
11731 		}
11732 		tcp->tcp_rwnd -= seg_len;
11733 	} else {
11734 		/* Just update tcp_rwnd */
11735 		tcp->tcp_rwnd -= seg_len;
11736 	}
11737 enq:
11738 	qfull = SOD_QFULL(sodp);
11739 
11740 	(sodp->sod_enqueue)(sodp, mp);
11741 
11742 	if (! qfull && SOD_QFULL(sodp)) {
11743 		/* Wasn't QFULL, now QFULL, need back-enable */
11744 		SOD_QSETBE(sodp);
11745 	}
11746 
11747 	/*
11748 	 * Check to see if remote avail swnd < mss due to delayed ACK,
11749 	 * first get advertised rwnd.
11750 	 */
11751 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win));
11752 	/* Minus delayed ACK count */
11753 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11754 	if (thwin < tcp->tcp_mss) {
11755 		/* Remote avail swnd < mss, need ACK now */
11756 		return (TH_ACK_NEEDED);
11757 	}
11758 
11759 	return (0);
11760 }
11761 
11762 /*
11763  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11764  *
11765  * This is the default entry function into TCP on the read side. TCP is
11766  * always entered via squeue i.e. using squeue's for mutual exclusion.
11767  * When classifier does a lookup to find the tcp, it also puts a reference
11768  * on the conn structure associated so the tcp is guaranteed to exist
11769  * when we come here. We still need to check the state because it might
11770  * as well has been closed. The squeue processing function i.e. squeue_enter,
11771  * is responsible for doing the CONN_DEC_REF.
11772  *
11773  * Apart from the default entry point, IP also sends packets directly to
11774  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11775  * connections.
11776  */
11777 boolean_t tcp_outbound_squeue_switch = B_FALSE;
11778 void
11779 tcp_input(void *arg, mblk_t *mp, void *arg2)
11780 {
11781 	conn_t	*connp = (conn_t *)arg;
11782 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11783 
11784 	/* arg2 is the sqp */
11785 	ASSERT(arg2 != NULL);
11786 	ASSERT(mp != NULL);
11787 
11788 	/*
11789 	 * Don't accept any input on a closed tcp as this TCP logically does
11790 	 * not exist on the system. Don't proceed further with this TCP.
11791 	 * For eg. this packet could trigger another close of this tcp
11792 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11793 	 * tcp_clean_death / tcp_closei_local must be called at most once
11794 	 * on a TCP. In this case we need to refeed the packet into the
11795 	 * classifier and figure out where the packet should go. Need to
11796 	 * preserve the recv_ill somehow. Until we figure that out, for
11797 	 * now just drop the packet if we can't classify the packet.
11798 	 */
11799 	if (tcp->tcp_state == TCPS_CLOSED ||
11800 	    tcp->tcp_state == TCPS_BOUND) {
11801 		conn_t	*new_connp;
11802 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11803 
11804 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11805 		if (new_connp != NULL) {
11806 			tcp_reinput(new_connp, mp, arg2);
11807 			return;
11808 		}
11809 		/* We failed to classify. For now just drop the packet */
11810 		freemsg(mp);
11811 		return;
11812 	}
11813 
11814 	if (DB_TYPE(mp) != M_DATA) {
11815 		tcp_rput_common(tcp, mp);
11816 		return;
11817 	}
11818 
11819 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
11820 		squeue_t	*final_sqp;
11821 
11822 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
11823 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
11824 		DB_CKSUMSTART(mp) = 0;
11825 		if (tcp->tcp_state == TCPS_SYN_SENT &&
11826 		    connp->conn_final_sqp == NULL &&
11827 		    tcp_outbound_squeue_switch) {
11828 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
11829 			connp->conn_final_sqp = final_sqp;
11830 			if (connp->conn_final_sqp != connp->conn_sqp) {
11831 				CONN_INC_REF(connp);
11832 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
11833 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
11834 				    tcp_rput_data, connp, ip_squeue_flag,
11835 				    SQTAG_CONNECT_FINISH);
11836 				return;
11837 			}
11838 		}
11839 	}
11840 	tcp_rput_data(connp, mp, arg2);
11841 }
11842 
11843 /*
11844  * The read side put procedure.
11845  * The packets passed up by ip are assume to be aligned according to
11846  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11847  */
11848 static void
11849 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11850 {
11851 	/*
11852 	 * tcp_rput_data() does not expect M_CTL except for the case
11853 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11854 	 * type. Need to make sure that any other M_CTLs don't make
11855 	 * it to tcp_rput_data since it is not expecting any and doesn't
11856 	 * check for it.
11857 	 */
11858 	if (DB_TYPE(mp) == M_CTL) {
11859 		switch (*(uint32_t *)(mp->b_rptr)) {
11860 		case TCP_IOC_ABORT_CONN:
11861 			/*
11862 			 * Handle connection abort request.
11863 			 */
11864 			tcp_ioctl_abort_handler(tcp, mp);
11865 			return;
11866 		case IPSEC_IN:
11867 			/*
11868 			 * Only secure icmp arrive in TCP and they
11869 			 * don't go through data path.
11870 			 */
11871 			tcp_icmp_error(tcp, mp);
11872 			return;
11873 		case IN_PKTINFO:
11874 			/*
11875 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11876 			 * sockets that are receiving IPv4 traffic. tcp
11877 			 */
11878 			ASSERT(tcp->tcp_family == AF_INET6);
11879 			ASSERT(tcp->tcp_ipv6_recvancillary &
11880 			    TCP_IPV6_RECVPKTINFO);
11881 			tcp_rput_data(tcp->tcp_connp, mp,
11882 			    tcp->tcp_connp->conn_sqp);
11883 			return;
11884 		case MDT_IOC_INFO_UPDATE:
11885 			/*
11886 			 * Handle Multidata information update; the
11887 			 * following routine will free the message.
11888 			 */
11889 			if (tcp->tcp_connp->conn_mdt_ok) {
11890 				tcp_mdt_update(tcp,
11891 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11892 				    B_FALSE);
11893 			}
11894 			freemsg(mp);
11895 			return;
11896 		case LSO_IOC_INFO_UPDATE:
11897 			/*
11898 			 * Handle LSO information update; the following
11899 			 * routine will free the message.
11900 			 */
11901 			if (tcp->tcp_connp->conn_lso_ok) {
11902 				tcp_lso_update(tcp,
11903 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11904 			}
11905 			freemsg(mp);
11906 			return;
11907 		default:
11908 			/*
11909 			 * tcp_icmp_err() will process the M_CTL packets.
11910 			 * Non-ICMP packets, if any, will be discarded in
11911 			 * tcp_icmp_err(). We will process the ICMP packet
11912 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11913 			 * incoming ICMP packet may result in changing
11914 			 * the tcp_mss, which we would need if we have
11915 			 * packets to retransmit.
11916 			 */
11917 			tcp_icmp_error(tcp, mp);
11918 			return;
11919 		}
11920 	}
11921 
11922 	/* No point processing the message if tcp is already closed */
11923 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11924 		freemsg(mp);
11925 		return;
11926 	}
11927 
11928 	tcp_rput_other(tcp, mp);
11929 }
11930 
11931 
11932 /* The minimum of smoothed mean deviation in RTO calculation. */
11933 #define	TCP_SD_MIN	400
11934 
11935 /*
11936  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11937  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11938  * are the same as those in Appendix A.2 of that paper.
11939  *
11940  * m = new measurement
11941  * sa = smoothed RTT average (8 * average estimates).
11942  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11943  */
11944 static void
11945 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11946 {
11947 	long m = TICK_TO_MSEC(rtt);
11948 	clock_t sa = tcp->tcp_rtt_sa;
11949 	clock_t sv = tcp->tcp_rtt_sd;
11950 	clock_t rto;
11951 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11952 
11953 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11954 	tcp->tcp_rtt_update++;
11955 
11956 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11957 	if (sa != 0) {
11958 		/*
11959 		 * Update average estimator:
11960 		 *	new rtt = 7/8 old rtt + 1/8 Error
11961 		 */
11962 
11963 		/* m is now Error in estimate. */
11964 		m -= sa >> 3;
11965 		if ((sa += m) <= 0) {
11966 			/*
11967 			 * Don't allow the smoothed average to be negative.
11968 			 * We use 0 to denote reinitialization of the
11969 			 * variables.
11970 			 */
11971 			sa = 1;
11972 		}
11973 
11974 		/*
11975 		 * Update deviation estimator:
11976 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11977 		 */
11978 		if (m < 0)
11979 			m = -m;
11980 		m -= sv >> 2;
11981 		sv += m;
11982 	} else {
11983 		/*
11984 		 * This follows BSD's implementation.  So the reinitialized
11985 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11986 		 * link is bandwidth dominated, doubling the window size
11987 		 * during slow start means doubling the RTT.  We want to be
11988 		 * more conservative when we reinitialize our estimates.  3
11989 		 * is just a convenient number.
11990 		 */
11991 		sa = m << 3;
11992 		sv = m << 1;
11993 	}
11994 	if (sv < TCP_SD_MIN) {
11995 		/*
11996 		 * We do not know that if sa captures the delay ACK
11997 		 * effect as in a long train of segments, a receiver
11998 		 * does not delay its ACKs.  So set the minimum of sv
11999 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
12000 		 * of BSD DATO.  That means the minimum of mean
12001 		 * deviation is 100 ms.
12002 		 *
12003 		 */
12004 		sv = TCP_SD_MIN;
12005 	}
12006 	tcp->tcp_rtt_sa = sa;
12007 	tcp->tcp_rtt_sd = sv;
12008 	/*
12009 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
12010 	 *
12011 	 * Add tcp_rexmit_interval extra in case of extreme environment
12012 	 * where the algorithm fails to work.  The default value of
12013 	 * tcp_rexmit_interval_extra should be 0.
12014 	 *
12015 	 * As we use a finer grained clock than BSD and update
12016 	 * RTO for every ACKs, add in another .25 of RTT to the
12017 	 * deviation of RTO to accomodate burstiness of 1/4 of
12018 	 * window size.
12019 	 */
12020 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
12021 
12022 	if (rto > tcps->tcps_rexmit_interval_max) {
12023 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
12024 	} else if (rto < tcps->tcps_rexmit_interval_min) {
12025 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
12026 	} else {
12027 		tcp->tcp_rto = rto;
12028 	}
12029 
12030 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12031 	tcp->tcp_timer_backoff = 0;
12032 }
12033 
12034 /*
12035  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12036  * send queue which starts at the given seq. no.
12037  *
12038  * Parameters:
12039  *	tcp_t *tcp: the tcp instance pointer.
12040  *	uint32_t seq: the starting seq. no of the requested segment.
12041  *	int32_t *off: after the execution, *off will be the offset to
12042  *		the returned mblk which points to the requested seq no.
12043  *		It is the caller's responsibility to send in a non-null off.
12044  *
12045  * Return:
12046  *	A mblk_t pointer pointing to the requested segment in send queue.
12047  */
12048 static mblk_t *
12049 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12050 {
12051 	int32_t	cnt;
12052 	mblk_t	*mp;
12053 
12054 	/* Defensive coding.  Make sure we don't send incorrect data. */
12055 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12056 		return (NULL);
12057 
12058 	cnt = seq - tcp->tcp_suna;
12059 	mp = tcp->tcp_xmit_head;
12060 	while (cnt > 0 && mp != NULL) {
12061 		cnt -= mp->b_wptr - mp->b_rptr;
12062 		if (cnt < 0) {
12063 			cnt += mp->b_wptr - mp->b_rptr;
12064 			break;
12065 		}
12066 		mp = mp->b_cont;
12067 	}
12068 	ASSERT(mp != NULL);
12069 	*off = cnt;
12070 	return (mp);
12071 }
12072 
12073 /*
12074  * This function handles all retransmissions if SACK is enabled for this
12075  * connection.  First it calculates how many segments can be retransmitted
12076  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12077  * segments.  A segment is eligible if sack_cnt for that segment is greater
12078  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12079  * all eligible segments, it checks to see if TCP can send some new segments
12080  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12081  *
12082  * Parameters:
12083  *	tcp_t *tcp: the tcp structure of the connection.
12084  *	uint_t *flags: in return, appropriate value will be set for
12085  *	tcp_rput_data().
12086  */
12087 static void
12088 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12089 {
12090 	notsack_blk_t	*notsack_blk;
12091 	int32_t		usable_swnd;
12092 	int32_t		mss;
12093 	uint32_t	seg_len;
12094 	mblk_t		*xmit_mp;
12095 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12096 
12097 	ASSERT(tcp->tcp_sack_info != NULL);
12098 	ASSERT(tcp->tcp_notsack_list != NULL);
12099 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12100 
12101 	/* Defensive coding in case there is a bug... */
12102 	if (tcp->tcp_notsack_list == NULL) {
12103 		return;
12104 	}
12105 	notsack_blk = tcp->tcp_notsack_list;
12106 	mss = tcp->tcp_mss;
12107 
12108 	/*
12109 	 * Limit the num of outstanding data in the network to be
12110 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12111 	 */
12112 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12113 
12114 	/* At least retransmit 1 MSS of data. */
12115 	if (usable_swnd <= 0) {
12116 		usable_swnd = mss;
12117 	}
12118 
12119 	/* Make sure no new RTT samples will be taken. */
12120 	tcp->tcp_csuna = tcp->tcp_snxt;
12121 
12122 	notsack_blk = tcp->tcp_notsack_list;
12123 	while (usable_swnd > 0) {
12124 		mblk_t		*snxt_mp, *tmp_mp;
12125 		tcp_seq		begin = tcp->tcp_sack_snxt;
12126 		tcp_seq		end;
12127 		int32_t		off;
12128 
12129 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12130 			if (SEQ_GT(notsack_blk->end, begin) &&
12131 			    (notsack_blk->sack_cnt >=
12132 			    tcps->tcps_dupack_fast_retransmit)) {
12133 				end = notsack_blk->end;
12134 				if (SEQ_LT(begin, notsack_blk->begin)) {
12135 					begin = notsack_blk->begin;
12136 				}
12137 				break;
12138 			}
12139 		}
12140 		/*
12141 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12142 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12143 		 * set to tcp_cwnd_ssthresh.
12144 		 */
12145 		if (notsack_blk == NULL) {
12146 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12147 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12148 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12149 				ASSERT(tcp->tcp_cwnd > 0);
12150 				return;
12151 			} else {
12152 				usable_swnd = usable_swnd / mss;
12153 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12154 				    MAX(usable_swnd * mss, mss);
12155 				*flags |= TH_XMIT_NEEDED;
12156 				return;
12157 			}
12158 		}
12159 
12160 		/*
12161 		 * Note that we may send more than usable_swnd allows here
12162 		 * because of round off, but no more than 1 MSS of data.
12163 		 */
12164 		seg_len = end - begin;
12165 		if (seg_len > mss)
12166 			seg_len = mss;
12167 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12168 		ASSERT(snxt_mp != NULL);
12169 		/* This should not happen.  Defensive coding again... */
12170 		if (snxt_mp == NULL) {
12171 			return;
12172 		}
12173 
12174 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12175 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12176 		if (xmit_mp == NULL)
12177 			return;
12178 
12179 		usable_swnd -= seg_len;
12180 		tcp->tcp_pipe += seg_len;
12181 		tcp->tcp_sack_snxt = begin + seg_len;
12182 
12183 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12184 
12185 		/*
12186 		 * Update the send timestamp to avoid false retransmission.
12187 		 */
12188 		snxt_mp->b_prev = (mblk_t *)lbolt;
12189 
12190 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12191 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12192 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12193 		/*
12194 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12195 		 * This happens when new data sent during fast recovery is
12196 		 * also lost.  If TCP retransmits those new data, it needs
12197 		 * to extend SACK recover phase to avoid starting another
12198 		 * fast retransmit/recovery unnecessarily.
12199 		 */
12200 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12201 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12202 		}
12203 	}
12204 }
12205 
12206 /*
12207  * This function handles policy checking at TCP level for non-hard_bound/
12208  * detached connections.
12209  */
12210 static boolean_t
12211 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12212     boolean_t secure, boolean_t mctl_present)
12213 {
12214 	ipsec_latch_t *ipl = NULL;
12215 	ipsec_action_t *act = NULL;
12216 	mblk_t *data_mp;
12217 	ipsec_in_t *ii;
12218 	const char *reason;
12219 	kstat_named_t *counter;
12220 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12221 	ipsec_stack_t	*ipss;
12222 	ip_stack_t	*ipst;
12223 
12224 	ASSERT(mctl_present || !secure);
12225 
12226 	ASSERT((ipha == NULL && ip6h != NULL) ||
12227 	    (ip6h == NULL && ipha != NULL));
12228 
12229 	/*
12230 	 * We don't necessarily have an ipsec_in_act action to verify
12231 	 * policy because of assymetrical policy where we have only
12232 	 * outbound policy and no inbound policy (possible with global
12233 	 * policy).
12234 	 */
12235 	if (!secure) {
12236 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12237 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12238 			return (B_TRUE);
12239 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12240 		    "tcp_check_policy", ipha, ip6h, secure,
12241 		    tcps->tcps_netstack);
12242 		ipss = tcps->tcps_netstack->netstack_ipsec;
12243 
12244 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12245 		    DROPPER(ipss, ipds_tcp_clear),
12246 		    &tcps->tcps_dropper);
12247 		return (B_FALSE);
12248 	}
12249 
12250 	/*
12251 	 * We have a secure packet.
12252 	 */
12253 	if (act == NULL) {
12254 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12255 		    "tcp_check_policy", ipha, ip6h, secure,
12256 		    tcps->tcps_netstack);
12257 		ipss = tcps->tcps_netstack->netstack_ipsec;
12258 
12259 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12260 		    DROPPER(ipss, ipds_tcp_secure),
12261 		    &tcps->tcps_dropper);
12262 		return (B_FALSE);
12263 	}
12264 
12265 	/*
12266 	 * XXX This whole routine is currently incorrect.  ipl should
12267 	 * be set to the latch pointer, but is currently not set, so
12268 	 * we initialize it to NULL to avoid picking up random garbage.
12269 	 */
12270 	if (ipl == NULL)
12271 		return (B_TRUE);
12272 
12273 	data_mp = first_mp->b_cont;
12274 
12275 	ii = (ipsec_in_t *)first_mp->b_rptr;
12276 
12277 	ipst = tcps->tcps_netstack->netstack_ip;
12278 
12279 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12280 	    &counter, tcp->tcp_connp)) {
12281 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12282 		return (B_TRUE);
12283 	}
12284 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12285 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12286 	    reason);
12287 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12288 
12289 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12290 	    &tcps->tcps_dropper);
12291 	return (B_FALSE);
12292 }
12293 
12294 /*
12295  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12296  * retransmission after a timeout.
12297  *
12298  * To limit the number of duplicate segments, we limit the number of segment
12299  * to be sent in one time to tcp_snd_burst, the burst variable.
12300  */
12301 static void
12302 tcp_ss_rexmit(tcp_t *tcp)
12303 {
12304 	uint32_t	snxt;
12305 	uint32_t	smax;
12306 	int32_t		win;
12307 	int32_t		mss;
12308 	int32_t		off;
12309 	int32_t		burst = tcp->tcp_snd_burst;
12310 	mblk_t		*snxt_mp;
12311 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12312 
12313 	/*
12314 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12315 	 * all unack'ed segments.
12316 	 */
12317 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12318 		smax = tcp->tcp_rexmit_max;
12319 		snxt = tcp->tcp_rexmit_nxt;
12320 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12321 			snxt = tcp->tcp_suna;
12322 		}
12323 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12324 		win -= snxt - tcp->tcp_suna;
12325 		mss = tcp->tcp_mss;
12326 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12327 
12328 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12329 		    (burst > 0) && (snxt_mp != NULL)) {
12330 			mblk_t	*xmit_mp;
12331 			mblk_t	*old_snxt_mp = snxt_mp;
12332 			uint32_t cnt = mss;
12333 
12334 			if (win < cnt) {
12335 				cnt = win;
12336 			}
12337 			if (SEQ_GT(snxt + cnt, smax)) {
12338 				cnt = smax - snxt;
12339 			}
12340 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12341 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12342 			if (xmit_mp == NULL)
12343 				return;
12344 
12345 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12346 
12347 			snxt += cnt;
12348 			win -= cnt;
12349 			/*
12350 			 * Update the send timestamp to avoid false
12351 			 * retransmission.
12352 			 */
12353 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12354 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12355 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12356 
12357 			tcp->tcp_rexmit_nxt = snxt;
12358 			burst--;
12359 		}
12360 		/*
12361 		 * If we have transmitted all we have at the time
12362 		 * we started the retranmission, we can leave
12363 		 * the rest of the job to tcp_wput_data().  But we
12364 		 * need to check the send window first.  If the
12365 		 * win is not 0, go on with tcp_wput_data().
12366 		 */
12367 		if (SEQ_LT(snxt, smax) || win == 0) {
12368 			return;
12369 		}
12370 	}
12371 	/* Only call tcp_wput_data() if there is data to be sent. */
12372 	if (tcp->tcp_unsent) {
12373 		tcp_wput_data(tcp, NULL, B_FALSE);
12374 	}
12375 }
12376 
12377 /*
12378  * Process all TCP option in SYN segment.  Note that this function should
12379  * be called after tcp_adapt_ire() is called so that the necessary info
12380  * from IRE is already set in the tcp structure.
12381  *
12382  * This function sets up the correct tcp_mss value according to the
12383  * MSS option value and our header size.  It also sets up the window scale
12384  * and timestamp values, and initialize SACK info blocks.  But it does not
12385  * change receive window size after setting the tcp_mss value.  The caller
12386  * should do the appropriate change.
12387  */
12388 void
12389 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12390 {
12391 	int options;
12392 	tcp_opt_t tcpopt;
12393 	uint32_t mss_max;
12394 	char *tmp_tcph;
12395 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12396 
12397 	tcpopt.tcp = NULL;
12398 	options = tcp_parse_options(tcph, &tcpopt);
12399 
12400 	/*
12401 	 * Process MSS option.  Note that MSS option value does not account
12402 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12403 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12404 	 * IPv6.
12405 	 */
12406 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12407 		if (tcp->tcp_ipversion == IPV4_VERSION)
12408 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12409 		else
12410 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12411 	} else {
12412 		if (tcp->tcp_ipversion == IPV4_VERSION)
12413 			mss_max = tcps->tcps_mss_max_ipv4;
12414 		else
12415 			mss_max = tcps->tcps_mss_max_ipv6;
12416 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12417 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12418 		else if (tcpopt.tcp_opt_mss > mss_max)
12419 			tcpopt.tcp_opt_mss = mss_max;
12420 	}
12421 
12422 	/* Process Window Scale option. */
12423 	if (options & TCP_OPT_WSCALE_PRESENT) {
12424 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12425 		tcp->tcp_snd_ws_ok = B_TRUE;
12426 	} else {
12427 		tcp->tcp_snd_ws = B_FALSE;
12428 		tcp->tcp_snd_ws_ok = B_FALSE;
12429 		tcp->tcp_rcv_ws = B_FALSE;
12430 	}
12431 
12432 	/* Process Timestamp option. */
12433 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12434 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12435 		tmp_tcph = (char *)tcp->tcp_tcph;
12436 
12437 		tcp->tcp_snd_ts_ok = B_TRUE;
12438 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12439 		tcp->tcp_last_rcv_lbolt = lbolt64;
12440 		ASSERT(OK_32PTR(tmp_tcph));
12441 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12442 
12443 		/* Fill in our template header with basic timestamp option. */
12444 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12445 		tmp_tcph[0] = TCPOPT_NOP;
12446 		tmp_tcph[1] = TCPOPT_NOP;
12447 		tmp_tcph[2] = TCPOPT_TSTAMP;
12448 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12449 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12450 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12451 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12452 	} else {
12453 		tcp->tcp_snd_ts_ok = B_FALSE;
12454 	}
12455 
12456 	/*
12457 	 * Process SACK options.  If SACK is enabled for this connection,
12458 	 * then allocate the SACK info structure.  Note the following ways
12459 	 * when tcp_snd_sack_ok is set to true.
12460 	 *
12461 	 * For active connection: in tcp_adapt_ire() called in
12462 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12463 	 * is checked.
12464 	 *
12465 	 * For passive connection: in tcp_adapt_ire() called in
12466 	 * tcp_accept_comm().
12467 	 *
12468 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12469 	 * That check makes sure that if we did not send a SACK OK option,
12470 	 * we will not enable SACK for this connection even though the other
12471 	 * side sends us SACK OK option.  For active connection, the SACK
12472 	 * info structure has already been allocated.  So we need to free
12473 	 * it if SACK is disabled.
12474 	 */
12475 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12476 	    (tcp->tcp_snd_sack_ok ||
12477 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12478 		/* This should be true only in the passive case. */
12479 		if (tcp->tcp_sack_info == NULL) {
12480 			ASSERT(TCP_IS_DETACHED(tcp));
12481 			tcp->tcp_sack_info =
12482 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12483 		}
12484 		if (tcp->tcp_sack_info == NULL) {
12485 			tcp->tcp_snd_sack_ok = B_FALSE;
12486 		} else {
12487 			tcp->tcp_snd_sack_ok = B_TRUE;
12488 			if (tcp->tcp_snd_ts_ok) {
12489 				tcp->tcp_max_sack_blk = 3;
12490 			} else {
12491 				tcp->tcp_max_sack_blk = 4;
12492 			}
12493 		}
12494 	} else {
12495 		/*
12496 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12497 		 * no SACK info will be used for this
12498 		 * connection.  This assumes that SACK usage
12499 		 * permission is negotiated.  This may need
12500 		 * to be changed once this is clarified.
12501 		 */
12502 		if (tcp->tcp_sack_info != NULL) {
12503 			ASSERT(tcp->tcp_notsack_list == NULL);
12504 			kmem_cache_free(tcp_sack_info_cache,
12505 			    tcp->tcp_sack_info);
12506 			tcp->tcp_sack_info = NULL;
12507 		}
12508 		tcp->tcp_snd_sack_ok = B_FALSE;
12509 	}
12510 
12511 	/*
12512 	 * Now we know the exact TCP/IP header length, subtract
12513 	 * that from tcp_mss to get our side's MSS.
12514 	 */
12515 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12516 	/*
12517 	 * Here we assume that the other side's header size will be equal to
12518 	 * our header size.  We calculate the real MSS accordingly.  Need to
12519 	 * take into additional stuffs IPsec puts in.
12520 	 *
12521 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12522 	 */
12523 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12524 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12525 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12526 
12527 	/*
12528 	 * Set MSS to the smaller one of both ends of the connection.
12529 	 * We should not have called tcp_mss_set() before, but our
12530 	 * side of the MSS should have been set to a proper value
12531 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12532 	 * STREAM head parameters properly.
12533 	 *
12534 	 * If we have a larger-than-16-bit window but the other side
12535 	 * didn't want to do window scale, tcp_rwnd_set() will take
12536 	 * care of that.
12537 	 */
12538 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12539 }
12540 
12541 /*
12542  * Sends the T_CONN_IND to the listener. The caller calls this
12543  * functions via squeue to get inside the listener's perimeter
12544  * once the 3 way hand shake is done a T_CONN_IND needs to be
12545  * sent. As an optimization, the caller can call this directly
12546  * if listener's perimeter is same as eager's.
12547  */
12548 /* ARGSUSED */
12549 void
12550 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12551 {
12552 	conn_t			*lconnp = (conn_t *)arg;
12553 	tcp_t			*listener = lconnp->conn_tcp;
12554 	tcp_t			*tcp;
12555 	struct T_conn_ind	*conn_ind;
12556 	ipaddr_t 		*addr_cache;
12557 	boolean_t		need_send_conn_ind = B_FALSE;
12558 	tcp_stack_t		*tcps = listener->tcp_tcps;
12559 
12560 	/* retrieve the eager */
12561 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12562 	ASSERT(conn_ind->OPT_offset != 0 &&
12563 	    conn_ind->OPT_length == sizeof (intptr_t));
12564 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12565 	    conn_ind->OPT_length);
12566 
12567 	/*
12568 	 * TLI/XTI applications will get confused by
12569 	 * sending eager as an option since it violates
12570 	 * the option semantics. So remove the eager as
12571 	 * option since TLI/XTI app doesn't need it anyway.
12572 	 */
12573 	if (!TCP_IS_SOCKET(listener)) {
12574 		conn_ind->OPT_length = 0;
12575 		conn_ind->OPT_offset = 0;
12576 	}
12577 	if (listener->tcp_state == TCPS_CLOSED ||
12578 	    TCP_IS_DETACHED(listener)) {
12579 		/*
12580 		 * If listener has closed, it would have caused a
12581 		 * a cleanup/blowoff to happen for the eager. We
12582 		 * just need to return.
12583 		 */
12584 		freemsg(mp);
12585 		return;
12586 	}
12587 
12588 
12589 	/*
12590 	 * if the conn_req_q is full defer passing up the
12591 	 * T_CONN_IND until space is availabe after t_accept()
12592 	 * processing
12593 	 */
12594 	mutex_enter(&listener->tcp_eager_lock);
12595 
12596 	/*
12597 	 * Take the eager out, if it is in the list of droppable eagers
12598 	 * as we are here because the 3W handshake is over.
12599 	 */
12600 	MAKE_UNDROPPABLE(tcp);
12601 
12602 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12603 		tcp_t *tail;
12604 
12605 		/*
12606 		 * The eager already has an extra ref put in tcp_rput_data
12607 		 * so that it stays till accept comes back even though it
12608 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12609 		 */
12610 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12611 		listener->tcp_conn_req_cnt_q0--;
12612 		listener->tcp_conn_req_cnt_q++;
12613 
12614 		/* Move from SYN_RCVD to ESTABLISHED list  */
12615 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12616 		    tcp->tcp_eager_prev_q0;
12617 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12618 		    tcp->tcp_eager_next_q0;
12619 		tcp->tcp_eager_prev_q0 = NULL;
12620 		tcp->tcp_eager_next_q0 = NULL;
12621 
12622 		/*
12623 		 * Insert at end of the queue because sockfs
12624 		 * sends down T_CONN_RES in chronological
12625 		 * order. Leaving the older conn indications
12626 		 * at front of the queue helps reducing search
12627 		 * time.
12628 		 */
12629 		tail = listener->tcp_eager_last_q;
12630 		if (tail != NULL)
12631 			tail->tcp_eager_next_q = tcp;
12632 		else
12633 			listener->tcp_eager_next_q = tcp;
12634 		listener->tcp_eager_last_q = tcp;
12635 		tcp->tcp_eager_next_q = NULL;
12636 		/*
12637 		 * Delay sending up the T_conn_ind until we are
12638 		 * done with the eager. Once we have have sent up
12639 		 * the T_conn_ind, the accept can potentially complete
12640 		 * any time and release the refhold we have on the eager.
12641 		 */
12642 		need_send_conn_ind = B_TRUE;
12643 	} else {
12644 		/*
12645 		 * Defer connection on q0 and set deferred
12646 		 * connection bit true
12647 		 */
12648 		tcp->tcp_conn_def_q0 = B_TRUE;
12649 
12650 		/* take tcp out of q0 ... */
12651 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12652 		    tcp->tcp_eager_next_q0;
12653 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12654 		    tcp->tcp_eager_prev_q0;
12655 
12656 		/* ... and place it at the end of q0 */
12657 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12658 		tcp->tcp_eager_next_q0 = listener;
12659 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12660 		listener->tcp_eager_prev_q0 = tcp;
12661 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12662 	}
12663 
12664 	/* we have timed out before */
12665 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12666 		tcp->tcp_syn_rcvd_timeout = 0;
12667 		listener->tcp_syn_rcvd_timeout--;
12668 		if (listener->tcp_syn_defense &&
12669 		    listener->tcp_syn_rcvd_timeout <=
12670 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12671 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12672 		    listener->tcp_last_rcv_lbolt)) {
12673 			/*
12674 			 * Turn off the defense mode if we
12675 			 * believe the SYN attack is over.
12676 			 */
12677 			listener->tcp_syn_defense = B_FALSE;
12678 			if (listener->tcp_ip_addr_cache) {
12679 				kmem_free((void *)listener->tcp_ip_addr_cache,
12680 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12681 				listener->tcp_ip_addr_cache = NULL;
12682 			}
12683 		}
12684 	}
12685 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12686 	if (addr_cache != NULL) {
12687 		/*
12688 		 * We have finished a 3-way handshake with this
12689 		 * remote host. This proves the IP addr is good.
12690 		 * Cache it!
12691 		 */
12692 		addr_cache[IP_ADDR_CACHE_HASH(
12693 		    tcp->tcp_remote)] = tcp->tcp_remote;
12694 	}
12695 	mutex_exit(&listener->tcp_eager_lock);
12696 	if (need_send_conn_ind) {
12697 		if (IPCL_IS_NONSTR(lconnp)) {
12698 			ASSERT(tcp->tcp_listener == listener);
12699 			ASSERT(tcp->tcp_saved_listener == listener);
12700 			if ((*lconnp->conn_upcalls->su_newconn)
12701 			    (lconnp->conn_upper_handle,
12702 			    (sock_lower_handle_t)tcp->tcp_connp,
12703 			    &sock_tcp_downcalls, DB_CRED(mp), DB_CPID(mp),
12704 			    &tcp->tcp_connp->conn_upcalls) != NULL) {
12705 				/*
12706 				 * Keep the message around
12707 				 * in case of fallback
12708 				 */
12709 				tcp->tcp_conn.tcp_eager_conn_ind = mp;
12710 			} else {
12711 				freemsg(mp);
12712 			}
12713 		} else {
12714 			putnext(listener->tcp_rq, mp);
12715 		}
12716 	}
12717 }
12718 
12719 mblk_t *
12720 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12721     uint_t *ifindexp, ip6_pkt_t *ippp)
12722 {
12723 	ip_pktinfo_t	*pinfo;
12724 	ip6_t		*ip6h;
12725 	uchar_t		*rptr;
12726 	mblk_t		*first_mp = mp;
12727 	boolean_t	mctl_present = B_FALSE;
12728 	uint_t 		ifindex = 0;
12729 	ip6_pkt_t	ipp;
12730 	uint_t		ipvers;
12731 	uint_t		ip_hdr_len;
12732 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12733 
12734 	rptr = mp->b_rptr;
12735 	ASSERT(OK_32PTR(rptr));
12736 	ASSERT(tcp != NULL);
12737 	ipp.ipp_fields = 0;
12738 
12739 	switch DB_TYPE(mp) {
12740 	case M_CTL:
12741 		mp = mp->b_cont;
12742 		if (mp == NULL) {
12743 			freemsg(first_mp);
12744 			return (NULL);
12745 		}
12746 		if (DB_TYPE(mp) != M_DATA) {
12747 			freemsg(first_mp);
12748 			return (NULL);
12749 		}
12750 		mctl_present = B_TRUE;
12751 		break;
12752 	case M_DATA:
12753 		break;
12754 	default:
12755 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12756 		freemsg(mp);
12757 		return (NULL);
12758 	}
12759 	ipvers = IPH_HDR_VERSION(rptr);
12760 	if (ipvers == IPV4_VERSION) {
12761 		if (tcp == NULL) {
12762 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12763 			goto done;
12764 		}
12765 
12766 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12767 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12768 
12769 		/*
12770 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12771 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12772 		 */
12773 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12774 		    mctl_present) {
12775 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12776 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12777 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12778 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12779 				ipp.ipp_fields |= IPPF_IFINDEX;
12780 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12781 				ifindex = pinfo->ip_pkt_ifindex;
12782 			}
12783 			freeb(first_mp);
12784 			mctl_present = B_FALSE;
12785 		}
12786 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12787 	} else {
12788 		ip6h = (ip6_t *)rptr;
12789 
12790 		ASSERT(ipvers == IPV6_VERSION);
12791 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12792 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12793 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12794 
12795 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12796 			uint8_t	nexthdrp;
12797 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12798 
12799 			/* Look for ifindex information */
12800 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12801 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12802 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12803 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12804 					freemsg(first_mp);
12805 					return (NULL);
12806 				}
12807 
12808 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12809 					ASSERT(ip6i->ip6i_ifindex != 0);
12810 					ipp.ipp_fields |= IPPF_IFINDEX;
12811 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12812 					ifindex = ip6i->ip6i_ifindex;
12813 				}
12814 				rptr = (uchar_t *)&ip6i[1];
12815 				mp->b_rptr = rptr;
12816 				if (rptr == mp->b_wptr) {
12817 					mblk_t *mp1;
12818 					mp1 = mp->b_cont;
12819 					freeb(mp);
12820 					mp = mp1;
12821 					rptr = mp->b_rptr;
12822 				}
12823 				if (MBLKL(mp) < IPV6_HDR_LEN +
12824 				    sizeof (tcph_t)) {
12825 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12826 					freemsg(first_mp);
12827 					return (NULL);
12828 				}
12829 				ip6h = (ip6_t *)rptr;
12830 			}
12831 
12832 			/*
12833 			 * Find any potentially interesting extension headers
12834 			 * as well as the length of the IPv6 + extension
12835 			 * headers.
12836 			 */
12837 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12838 			/* Verify if this is a TCP packet */
12839 			if (nexthdrp != IPPROTO_TCP) {
12840 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12841 				freemsg(first_mp);
12842 				return (NULL);
12843 			}
12844 		} else {
12845 			ip_hdr_len = IPV6_HDR_LEN;
12846 		}
12847 	}
12848 
12849 done:
12850 	if (ipversp != NULL)
12851 		*ipversp = ipvers;
12852 	if (ip_hdr_lenp != NULL)
12853 		*ip_hdr_lenp = ip_hdr_len;
12854 	if (ippp != NULL)
12855 		*ippp = ipp;
12856 	if (ifindexp != NULL)
12857 		*ifindexp = ifindex;
12858 	if (mctl_present) {
12859 		freeb(first_mp);
12860 	}
12861 	return (mp);
12862 }
12863 
12864 /*
12865  * Handle M_DATA messages from IP. Its called directly from IP via
12866  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12867  * in this path.
12868  *
12869  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12870  * v4 and v6), we are called through tcp_input() and a M_CTL can
12871  * be present for options but tcp_find_pktinfo() deals with it. We
12872  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12873  *
12874  * The first argument is always the connp/tcp to which the mp belongs.
12875  * There are no exceptions to this rule. The caller has already put
12876  * a reference on this connp/tcp and once tcp_rput_data() returns,
12877  * the squeue will do the refrele.
12878  *
12879  * The TH_SYN for the listener directly go to tcp_conn_request via
12880  * squeue.
12881  *
12882  * sqp: NULL = recursive, sqp != NULL means called from squeue
12883  */
12884 void
12885 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12886 {
12887 	int32_t		bytes_acked;
12888 	int32_t		gap;
12889 	mblk_t		*mp1;
12890 	uint_t		flags;
12891 	uint32_t	new_swnd = 0;
12892 	uchar_t		*iphdr;
12893 	uchar_t		*rptr;
12894 	int32_t		rgap;
12895 	uint32_t	seg_ack;
12896 	int		seg_len;
12897 	uint_t		ip_hdr_len;
12898 	uint32_t	seg_seq;
12899 	tcph_t		*tcph;
12900 	int		urp;
12901 	tcp_opt_t	tcpopt;
12902 	uint_t		ipvers;
12903 	ip6_pkt_t	ipp;
12904 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12905 	uint32_t	cwnd;
12906 	uint32_t	add;
12907 	int		npkt;
12908 	int		mss;
12909 	conn_t		*connp = (conn_t *)arg;
12910 	squeue_t	*sqp = (squeue_t *)arg2;
12911 	tcp_t		*tcp = connp->conn_tcp;
12912 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12913 
12914 	/*
12915 	 * RST from fused tcp loopback peer should trigger an unfuse.
12916 	 */
12917 	if (tcp->tcp_fused) {
12918 		TCP_STAT(tcps, tcp_fusion_aborted);
12919 		tcp_unfuse(tcp);
12920 	}
12921 
12922 	iphdr = mp->b_rptr;
12923 	rptr = mp->b_rptr;
12924 	ASSERT(OK_32PTR(rptr));
12925 
12926 	/*
12927 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12928 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12929 	 * necessary information.
12930 	 */
12931 	if (IPCL_IS_TCP4(connp)) {
12932 		ipvers = IPV4_VERSION;
12933 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12934 	} else {
12935 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12936 		    NULL, &ipp);
12937 		if (mp == NULL) {
12938 			TCP_STAT(tcps, tcp_rput_v6_error);
12939 			return;
12940 		}
12941 		iphdr = mp->b_rptr;
12942 		rptr = mp->b_rptr;
12943 	}
12944 	ASSERT(DB_TYPE(mp) == M_DATA);
12945 	ASSERT(mp->b_next == NULL);
12946 
12947 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12948 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12949 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12950 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12951 	seg_len = (int)(mp->b_wptr - rptr) -
12952 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12953 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12954 		do {
12955 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12956 			    (uintptr_t)INT_MAX);
12957 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12958 		} while ((mp1 = mp1->b_cont) != NULL &&
12959 		    mp1->b_datap->db_type == M_DATA);
12960 	}
12961 
12962 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12963 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12964 		    seg_len, tcph);
12965 		return;
12966 	}
12967 
12968 	if (sqp != NULL) {
12969 		/*
12970 		 * This is the correct place to update tcp_last_recv_time. Note
12971 		 * that it is also updated for tcp structure that belongs to
12972 		 * global and listener queues which do not really need updating.
12973 		 * But that should not cause any harm.  And it is updated for
12974 		 * all kinds of incoming segments, not only for data segments.
12975 		 */
12976 		tcp->tcp_last_recv_time = lbolt;
12977 	}
12978 
12979 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12980 
12981 	BUMP_LOCAL(tcp->tcp_ibsegs);
12982 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
12983 
12984 	if ((flags & TH_URG) && sqp != NULL) {
12985 		/*
12986 		 * TCP can't handle urgent pointers that arrive before
12987 		 * the connection has been accept()ed since it can't
12988 		 * buffer OOB data.  Discard segment if this happens.
12989 		 *
12990 		 * We can't just rely on a non-null tcp_listener to indicate
12991 		 * that the accept() has completed since unlinking of the
12992 		 * eager and completion of the accept are not atomic.
12993 		 * tcp_detached, when it is not set (B_FALSE) indicates
12994 		 * that the accept() has completed.
12995 		 *
12996 		 * Nor can it reassemble urgent pointers, so discard
12997 		 * if it's not the next segment expected.
12998 		 *
12999 		 * Otherwise, collapse chain into one mblk (discard if
13000 		 * that fails).  This makes sure the headers, retransmitted
13001 		 * data, and new data all are in the same mblk.
13002 		 */
13003 		ASSERT(mp != NULL);
13004 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
13005 			freemsg(mp);
13006 			return;
13007 		}
13008 		/* Update pointers into message */
13009 		iphdr = rptr = mp->b_rptr;
13010 		tcph = (tcph_t *)&rptr[ip_hdr_len];
13011 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
13012 			/*
13013 			 * Since we can't handle any data with this urgent
13014 			 * pointer that is out of sequence, we expunge
13015 			 * the data.  This allows us to still register
13016 			 * the urgent mark and generate the M_PCSIG,
13017 			 * which we can do.
13018 			 */
13019 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13020 			seg_len = 0;
13021 		}
13022 	}
13023 
13024 	switch (tcp->tcp_state) {
13025 	case TCPS_SYN_SENT:
13026 		if (flags & TH_ACK) {
13027 			/*
13028 			 * Note that our stack cannot send data before a
13029 			 * connection is established, therefore the
13030 			 * following check is valid.  Otherwise, it has
13031 			 * to be changed.
13032 			 */
13033 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13034 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13035 				freemsg(mp);
13036 				if (flags & TH_RST)
13037 					return;
13038 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13039 				    tcp, seg_ack, 0, TH_RST);
13040 				return;
13041 			}
13042 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13043 		}
13044 		if (flags & TH_RST) {
13045 			freemsg(mp);
13046 			if (flags & TH_ACK)
13047 				(void) tcp_clean_death(tcp,
13048 				    ECONNREFUSED, 13);
13049 			return;
13050 		}
13051 		if (!(flags & TH_SYN)) {
13052 			freemsg(mp);
13053 			return;
13054 		}
13055 
13056 		/* Process all TCP options. */
13057 		tcp_process_options(tcp, tcph);
13058 		/*
13059 		 * The following changes our rwnd to be a multiple of the
13060 		 * MIN(peer MSS, our MSS) for performance reason.
13061 		 */
13062 		(void) tcp_rwnd_set(tcp,
13063 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
13064 
13065 		/* Is the other end ECN capable? */
13066 		if (tcp->tcp_ecn_ok) {
13067 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13068 				tcp->tcp_ecn_ok = B_FALSE;
13069 			}
13070 		}
13071 		/*
13072 		 * Clear ECN flags because it may interfere with later
13073 		 * processing.
13074 		 */
13075 		flags &= ~(TH_ECE|TH_CWR);
13076 
13077 		tcp->tcp_irs = seg_seq;
13078 		tcp->tcp_rack = seg_seq;
13079 		tcp->tcp_rnxt = seg_seq + 1;
13080 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13081 		if (!TCP_IS_DETACHED(tcp)) {
13082 			/* Allocate room for SACK options if needed. */
13083 			if (tcp->tcp_snd_sack_ok) {
13084 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13085 				    tcp->tcp_hdr_len +
13086 				    TCPOPT_MAX_SACK_LEN +
13087 				    (tcp->tcp_loopback ? 0 :
13088 				    tcps->tcps_wroff_xtra));
13089 			} else {
13090 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13091 				    tcp->tcp_hdr_len +
13092 				    (tcp->tcp_loopback ? 0 :
13093 				    tcps->tcps_wroff_xtra));
13094 			}
13095 		}
13096 		if (flags & TH_ACK) {
13097 			/*
13098 			 * If we can't get the confirmation upstream, pretend
13099 			 * we didn't even see this one.
13100 			 *
13101 			 * XXX: how can we pretend we didn't see it if we
13102 			 * have updated rnxt et. al.
13103 			 *
13104 			 * For loopback we defer sending up the T_CONN_CON
13105 			 * until after some checks below.
13106 			 */
13107 			mp1 = NULL;
13108 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13109 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13110 				freemsg(mp);
13111 				return;
13112 			}
13113 			/* SYN was acked - making progress */
13114 			if (tcp->tcp_ipversion == IPV6_VERSION)
13115 				tcp->tcp_ip_forward_progress = B_TRUE;
13116 
13117 			/* One for the SYN */
13118 			tcp->tcp_suna = tcp->tcp_iss + 1;
13119 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13120 			tcp->tcp_state = TCPS_ESTABLISHED;
13121 
13122 			/*
13123 			 * If SYN was retransmitted, need to reset all
13124 			 * retransmission info.  This is because this
13125 			 * segment will be treated as a dup ACK.
13126 			 */
13127 			if (tcp->tcp_rexmit) {
13128 				tcp->tcp_rexmit = B_FALSE;
13129 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13130 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13131 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13132 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13133 				tcp->tcp_ms_we_have_waited = 0;
13134 
13135 				/*
13136 				 * Set tcp_cwnd back to 1 MSS, per
13137 				 * recommendation from
13138 				 * draft-floyd-incr-init-win-01.txt,
13139 				 * Increasing TCP's Initial Window.
13140 				 */
13141 				tcp->tcp_cwnd = tcp->tcp_mss;
13142 			}
13143 
13144 			tcp->tcp_swl1 = seg_seq;
13145 			tcp->tcp_swl2 = seg_ack;
13146 
13147 			new_swnd = BE16_TO_U16(tcph->th_win);
13148 			tcp->tcp_swnd = new_swnd;
13149 			if (new_swnd > tcp->tcp_max_swnd)
13150 				tcp->tcp_max_swnd = new_swnd;
13151 
13152 			/*
13153 			 * Always send the three-way handshake ack immediately
13154 			 * in order to make the connection complete as soon as
13155 			 * possible on the accepting host.
13156 			 */
13157 			flags |= TH_ACK_NEEDED;
13158 
13159 			/*
13160 			 * Special case for loopback.  At this point we have
13161 			 * received SYN-ACK from the remote endpoint.  In
13162 			 * order to ensure that both endpoints reach the
13163 			 * fused state prior to any data exchange, the final
13164 			 * ACK needs to be sent before we indicate T_CONN_CON
13165 			 * to the module upstream.
13166 			 */
13167 			if (tcp->tcp_loopback) {
13168 				mblk_t *ack_mp;
13169 
13170 				ASSERT(!tcp->tcp_unfusable);
13171 				ASSERT(mp1 != NULL);
13172 				/*
13173 				 * For loopback, we always get a pure SYN-ACK
13174 				 * and only need to send back the final ACK
13175 				 * with no data (this is because the other
13176 				 * tcp is ours and we don't do T/TCP).  This
13177 				 * final ACK triggers the passive side to
13178 				 * perform fusion in ESTABLISHED state.
13179 				 */
13180 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13181 					if (tcp->tcp_ack_tid != 0) {
13182 						(void) TCP_TIMER_CANCEL(tcp,
13183 						    tcp->tcp_ack_tid);
13184 						tcp->tcp_ack_tid = 0;
13185 					}
13186 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13187 					BUMP_LOCAL(tcp->tcp_obsegs);
13188 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13189 
13190 					if (!IPCL_IS_NONSTR(connp)) {
13191 						/* Send up T_CONN_CON */
13192 						putnext(tcp->tcp_rq, mp1);
13193 					} else {
13194 						(*connp->conn_upcalls->
13195 						    su_connected)
13196 						    (connp->conn_upper_handle,
13197 						    tcp->tcp_connid,
13198 						    DB_CRED(mp1),
13199 						    DB_CPID(mp1));
13200 						freemsg(mp1);
13201 					}
13202 
13203 					freemsg(mp);
13204 					return;
13205 				}
13206 				/*
13207 				 * Forget fusion; we need to handle more
13208 				 * complex cases below.  Send the deferred
13209 				 * T_CONN_CON message upstream and proceed
13210 				 * as usual.  Mark this tcp as not capable
13211 				 * of fusion.
13212 				 */
13213 				TCP_STAT(tcps, tcp_fusion_unfusable);
13214 				tcp->tcp_unfusable = B_TRUE;
13215 				if (!IPCL_IS_NONSTR(connp)) {
13216 					putnext(tcp->tcp_rq, mp1);
13217 				} else {
13218 					(*connp->conn_upcalls->su_connected)
13219 					    (connp->conn_upper_handle,
13220 					    tcp->tcp_connid, DB_CRED(mp1),
13221 					    DB_CPID(mp1));
13222 					freemsg(mp1);
13223 				}
13224 			}
13225 
13226 			/*
13227 			 * Check to see if there is data to be sent.  If
13228 			 * yes, set the transmit flag.  Then check to see
13229 			 * if received data processing needs to be done.
13230 			 * If not, go straight to xmit_check.  This short
13231 			 * cut is OK as we don't support T/TCP.
13232 			 */
13233 			if (tcp->tcp_unsent)
13234 				flags |= TH_XMIT_NEEDED;
13235 
13236 			if (seg_len == 0 && !(flags & TH_URG)) {
13237 				freemsg(mp);
13238 				goto xmit_check;
13239 			}
13240 
13241 			flags &= ~TH_SYN;
13242 			seg_seq++;
13243 			break;
13244 		}
13245 		tcp->tcp_state = TCPS_SYN_RCVD;
13246 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13247 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13248 		if (mp1) {
13249 			DB_CPID(mp1) = tcp->tcp_cpid;
13250 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13251 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13252 		}
13253 		freemsg(mp);
13254 		return;
13255 	case TCPS_SYN_RCVD:
13256 		if (flags & TH_ACK) {
13257 			/*
13258 			 * In this state, a SYN|ACK packet is either bogus
13259 			 * because the other side must be ACKing our SYN which
13260 			 * indicates it has seen the ACK for their SYN and
13261 			 * shouldn't retransmit it or we're crossing SYNs
13262 			 * on active open.
13263 			 */
13264 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13265 				freemsg(mp);
13266 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13267 				    tcp, seg_ack, 0, TH_RST);
13268 				return;
13269 			}
13270 			/*
13271 			 * NOTE: RFC 793 pg. 72 says this should be
13272 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13273 			 * but that would mean we have an ack that ignored
13274 			 * our SYN.
13275 			 */
13276 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13277 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13278 				freemsg(mp);
13279 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13280 				    tcp, seg_ack, 0, TH_RST);
13281 				return;
13282 			}
13283 		}
13284 		break;
13285 	case TCPS_LISTEN:
13286 		/*
13287 		 * Only a TLI listener can come through this path when a
13288 		 * acceptor is going back to be a listener and a packet
13289 		 * for the acceptor hits the classifier. For a socket
13290 		 * listener, this can never happen because a listener
13291 		 * can never accept connection on itself and hence a
13292 		 * socket acceptor can not go back to being a listener.
13293 		 */
13294 		ASSERT(!TCP_IS_SOCKET(tcp));
13295 		/*FALLTHRU*/
13296 	case TCPS_CLOSED:
13297 	case TCPS_BOUND: {
13298 		conn_t	*new_connp;
13299 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13300 
13301 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13302 		if (new_connp != NULL) {
13303 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13304 			return;
13305 		}
13306 		/* We failed to classify. For now just drop the packet */
13307 		freemsg(mp);
13308 		return;
13309 	}
13310 	case TCPS_IDLE:
13311 		/*
13312 		 * Handle the case where the tcp_clean_death() has happened
13313 		 * on a connection (application hasn't closed yet) but a packet
13314 		 * was already queued on squeue before tcp_clean_death()
13315 		 * was processed. Calling tcp_clean_death() twice on same
13316 		 * connection can result in weird behaviour.
13317 		 */
13318 		freemsg(mp);
13319 		return;
13320 	default:
13321 		break;
13322 	}
13323 
13324 	/*
13325 	 * Already on the correct queue/perimeter.
13326 	 * If this is a detached connection and not an eager
13327 	 * connection hanging off a listener then new data
13328 	 * (past the FIN) will cause a reset.
13329 	 * We do a special check here where it
13330 	 * is out of the main line, rather than check
13331 	 * if we are detached every time we see new
13332 	 * data down below.
13333 	 */
13334 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13335 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13336 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13337 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13338 
13339 		freemsg(mp);
13340 		/*
13341 		 * This could be an SSL closure alert. We're detached so just
13342 		 * acknowledge it this last time.
13343 		 */
13344 		if (tcp->tcp_kssl_ctx != NULL) {
13345 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13346 			tcp->tcp_kssl_ctx = NULL;
13347 
13348 			tcp->tcp_rnxt += seg_len;
13349 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13350 			flags |= TH_ACK_NEEDED;
13351 			goto ack_check;
13352 		}
13353 
13354 		tcp_xmit_ctl("new data when detached", tcp,
13355 		    tcp->tcp_snxt, 0, TH_RST);
13356 		(void) tcp_clean_death(tcp, EPROTO, 12);
13357 		return;
13358 	}
13359 
13360 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13361 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13362 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13363 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13364 
13365 	if (tcp->tcp_snd_ts_ok) {
13366 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13367 			/*
13368 			 * This segment is not acceptable.
13369 			 * Drop it and send back an ACK.
13370 			 */
13371 			freemsg(mp);
13372 			flags |= TH_ACK_NEEDED;
13373 			goto ack_check;
13374 		}
13375 	} else if (tcp->tcp_snd_sack_ok) {
13376 		ASSERT(tcp->tcp_sack_info != NULL);
13377 		tcpopt.tcp = tcp;
13378 		/*
13379 		 * SACK info in already updated in tcp_parse_options.  Ignore
13380 		 * all other TCP options...
13381 		 */
13382 		(void) tcp_parse_options(tcph, &tcpopt);
13383 	}
13384 try_again:;
13385 	mss = tcp->tcp_mss;
13386 	gap = seg_seq - tcp->tcp_rnxt;
13387 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13388 	/*
13389 	 * gap is the amount of sequence space between what we expect to see
13390 	 * and what we got for seg_seq.  A positive value for gap means
13391 	 * something got lost.  A negative value means we got some old stuff.
13392 	 */
13393 	if (gap < 0) {
13394 		/* Old stuff present.  Is the SYN in there? */
13395 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13396 		    (seg_len != 0)) {
13397 			flags &= ~TH_SYN;
13398 			seg_seq++;
13399 			urp--;
13400 			/* Recompute the gaps after noting the SYN. */
13401 			goto try_again;
13402 		}
13403 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13404 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13405 		    (seg_len > -gap ? -gap : seg_len));
13406 		/* Remove the old stuff from seg_len. */
13407 		seg_len += gap;
13408 		/*
13409 		 * Anything left?
13410 		 * Make sure to check for unack'd FIN when rest of data
13411 		 * has been previously ack'd.
13412 		 */
13413 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13414 			/*
13415 			 * Resets are only valid if they lie within our offered
13416 			 * window.  If the RST bit is set, we just ignore this
13417 			 * segment.
13418 			 */
13419 			if (flags & TH_RST) {
13420 				freemsg(mp);
13421 				return;
13422 			}
13423 
13424 			/*
13425 			 * The arriving of dup data packets indicate that we
13426 			 * may have postponed an ack for too long, or the other
13427 			 * side's RTT estimate is out of shape. Start acking
13428 			 * more often.
13429 			 */
13430 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13431 			    tcp->tcp_rack_cnt >= 1 &&
13432 			    tcp->tcp_rack_abs_max > 2) {
13433 				tcp->tcp_rack_abs_max--;
13434 			}
13435 			tcp->tcp_rack_cur_max = 1;
13436 
13437 			/*
13438 			 * This segment is "unacceptable".  None of its
13439 			 * sequence space lies within our advertized window.
13440 			 *
13441 			 * Adjust seg_len to the original value for tracing.
13442 			 */
13443 			seg_len -= gap;
13444 			if (tcp->tcp_debug) {
13445 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13446 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13447 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13448 				    "seg_len %d, rnxt %u, snxt %u, %s",
13449 				    gap, rgap, flags, seg_seq, seg_ack,
13450 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13451 				    tcp_display(tcp, NULL,
13452 				    DISP_ADDR_AND_PORT));
13453 			}
13454 
13455 			/*
13456 			 * Arrange to send an ACK in response to the
13457 			 * unacceptable segment per RFC 793 page 69. There
13458 			 * is only one small difference between ours and the
13459 			 * acceptability test in the RFC - we accept ACK-only
13460 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13461 			 * will be generated.
13462 			 *
13463 			 * Note that we have to ACK an ACK-only packet at least
13464 			 * for stacks that send 0-length keep-alives with
13465 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13466 			 * section 4.2.3.6. As long as we don't ever generate
13467 			 * an unacceptable packet in response to an incoming
13468 			 * packet that is unacceptable, it should not cause
13469 			 * "ACK wars".
13470 			 */
13471 			flags |=  TH_ACK_NEEDED;
13472 
13473 			/*
13474 			 * Continue processing this segment in order to use the
13475 			 * ACK information it contains, but skip all other
13476 			 * sequence-number processing.	Processing the ACK
13477 			 * information is necessary in order to
13478 			 * re-synchronize connections that may have lost
13479 			 * synchronization.
13480 			 *
13481 			 * We clear seg_len and flag fields related to
13482 			 * sequence number processing as they are not
13483 			 * to be trusted for an unacceptable segment.
13484 			 */
13485 			seg_len = 0;
13486 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13487 			goto process_ack;
13488 		}
13489 
13490 		/* Fix seg_seq, and chew the gap off the front. */
13491 		seg_seq = tcp->tcp_rnxt;
13492 		urp += gap;
13493 		do {
13494 			mblk_t	*mp2;
13495 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13496 			    (uintptr_t)UINT_MAX);
13497 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13498 			if (gap > 0) {
13499 				mp->b_rptr = mp->b_wptr - gap;
13500 				break;
13501 			}
13502 			mp2 = mp;
13503 			mp = mp->b_cont;
13504 			freeb(mp2);
13505 		} while (gap < 0);
13506 		/*
13507 		 * If the urgent data has already been acknowledged, we
13508 		 * should ignore TH_URG below
13509 		 */
13510 		if (urp < 0)
13511 			flags &= ~TH_URG;
13512 	}
13513 	/*
13514 	 * rgap is the amount of stuff received out of window.  A negative
13515 	 * value is the amount out of window.
13516 	 */
13517 	if (rgap < 0) {
13518 		mblk_t	*mp2;
13519 
13520 		if (tcp->tcp_rwnd == 0) {
13521 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13522 		} else {
13523 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13524 			UPDATE_MIB(&tcps->tcps_mib,
13525 			    tcpInDataPastWinBytes, -rgap);
13526 		}
13527 
13528 		/*
13529 		 * seg_len does not include the FIN, so if more than
13530 		 * just the FIN is out of window, we act like we don't
13531 		 * see it.  (If just the FIN is out of window, rgap
13532 		 * will be zero and we will go ahead and acknowledge
13533 		 * the FIN.)
13534 		 */
13535 		flags &= ~TH_FIN;
13536 
13537 		/* Fix seg_len and make sure there is something left. */
13538 		seg_len += rgap;
13539 		if (seg_len <= 0) {
13540 			/*
13541 			 * Resets are only valid if they lie within our offered
13542 			 * window.  If the RST bit is set, we just ignore this
13543 			 * segment.
13544 			 */
13545 			if (flags & TH_RST) {
13546 				freemsg(mp);
13547 				return;
13548 			}
13549 
13550 			/* Per RFC 793, we need to send back an ACK. */
13551 			flags |= TH_ACK_NEEDED;
13552 
13553 			/*
13554 			 * Send SIGURG as soon as possible i.e. even
13555 			 * if the TH_URG was delivered in a window probe
13556 			 * packet (which will be unacceptable).
13557 			 *
13558 			 * We generate a signal if none has been generated
13559 			 * for this connection or if this is a new urgent
13560 			 * byte. Also send a zero-length "unmarked" message
13561 			 * to inform SIOCATMARK that this is not the mark.
13562 			 *
13563 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13564 			 * is sent up. This plus the check for old data
13565 			 * (gap >= 0) handles the wraparound of the sequence
13566 			 * number space without having to always track the
13567 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13568 			 * this max in its rcv_up variable).
13569 			 *
13570 			 * This prevents duplicate SIGURGS due to a "late"
13571 			 * zero-window probe when the T_EXDATA_IND has already
13572 			 * been sent up.
13573 			 */
13574 			if ((flags & TH_URG) &&
13575 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13576 			    tcp->tcp_urp_last))) {
13577 				if (IPCL_IS_NONSTR(connp)) {
13578 					if (!TCP_IS_DETACHED(tcp)) {
13579 						(*connp->conn_upcalls->
13580 						    su_signal_oob)
13581 						    (connp->conn_upper_handle,
13582 						    urp);
13583 					}
13584 				} else {
13585 					mp1 = allocb(0, BPRI_MED);
13586 					if (mp1 == NULL) {
13587 						freemsg(mp);
13588 						return;
13589 					}
13590 					if (!TCP_IS_DETACHED(tcp) &&
13591 					    !putnextctl1(tcp->tcp_rq,
13592 					    M_PCSIG, SIGURG)) {
13593 						/* Try again on the rexmit. */
13594 						freemsg(mp1);
13595 						freemsg(mp);
13596 						return;
13597 					}
13598 					/*
13599 					 * If the next byte would be the mark
13600 					 * then mark with MARKNEXT else mark
13601 					 * with NOTMARKNEXT.
13602 					 */
13603 					if (gap == 0 && urp == 0)
13604 						mp1->b_flag |= MSGMARKNEXT;
13605 					else
13606 						mp1->b_flag |= MSGNOTMARKNEXT;
13607 					freemsg(tcp->tcp_urp_mark_mp);
13608 					tcp->tcp_urp_mark_mp = mp1;
13609 					flags |= TH_SEND_URP_MARK;
13610 				}
13611 				tcp->tcp_urp_last_valid = B_TRUE;
13612 				tcp->tcp_urp_last = urp + seg_seq;
13613 			}
13614 			/*
13615 			 * If this is a zero window probe, continue to
13616 			 * process the ACK part.  But we need to set seg_len
13617 			 * to 0 to avoid data processing.  Otherwise just
13618 			 * drop the segment and send back an ACK.
13619 			 */
13620 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13621 				flags &= ~(TH_SYN | TH_URG);
13622 				seg_len = 0;
13623 				goto process_ack;
13624 			} else {
13625 				freemsg(mp);
13626 				goto ack_check;
13627 			}
13628 		}
13629 		/* Pitch out of window stuff off the end. */
13630 		rgap = seg_len;
13631 		mp2 = mp;
13632 		do {
13633 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13634 			    (uintptr_t)INT_MAX);
13635 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13636 			if (rgap < 0) {
13637 				mp2->b_wptr += rgap;
13638 				if ((mp1 = mp2->b_cont) != NULL) {
13639 					mp2->b_cont = NULL;
13640 					freemsg(mp1);
13641 				}
13642 				break;
13643 			}
13644 		} while ((mp2 = mp2->b_cont) != NULL);
13645 	}
13646 ok:;
13647 	/*
13648 	 * TCP should check ECN info for segments inside the window only.
13649 	 * Therefore the check should be done here.
13650 	 */
13651 	if (tcp->tcp_ecn_ok) {
13652 		if (flags & TH_CWR) {
13653 			tcp->tcp_ecn_echo_on = B_FALSE;
13654 		}
13655 		/*
13656 		 * Note that both ECN_CE and CWR can be set in the
13657 		 * same segment.  In this case, we once again turn
13658 		 * on ECN_ECHO.
13659 		 */
13660 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13661 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13662 
13663 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13664 				tcp->tcp_ecn_echo_on = B_TRUE;
13665 			}
13666 		} else {
13667 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13668 
13669 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13670 			    htonl(IPH_ECN_CE << 20)) {
13671 				tcp->tcp_ecn_echo_on = B_TRUE;
13672 			}
13673 		}
13674 	}
13675 
13676 	/*
13677 	 * Check whether we can update tcp_ts_recent.  This test is
13678 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13679 	 * Extensions for High Performance: An Update", Internet Draft.
13680 	 */
13681 	if (tcp->tcp_snd_ts_ok &&
13682 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13683 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13684 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13685 		tcp->tcp_last_rcv_lbolt = lbolt64;
13686 	}
13687 
13688 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13689 		/*
13690 		 * FIN in an out of order segment.  We record this in
13691 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13692 		 * Clear the FIN so that any check on FIN flag will fail.
13693 		 * Remember that FIN also counts in the sequence number
13694 		 * space.  So we need to ack out of order FIN only segments.
13695 		 */
13696 		if (flags & TH_FIN) {
13697 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13698 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13699 			flags &= ~TH_FIN;
13700 			flags |= TH_ACK_NEEDED;
13701 		}
13702 		if (seg_len > 0) {
13703 			/* Fill in the SACK blk list. */
13704 			if (tcp->tcp_snd_sack_ok) {
13705 				ASSERT(tcp->tcp_sack_info != NULL);
13706 				tcp_sack_insert(tcp->tcp_sack_list,
13707 				    seg_seq, seg_seq + seg_len,
13708 				    &(tcp->tcp_num_sack_blk));
13709 			}
13710 
13711 			/*
13712 			 * Attempt reassembly and see if we have something
13713 			 * ready to go.
13714 			 */
13715 			mp = tcp_reass(tcp, mp, seg_seq);
13716 			/* Always ack out of order packets */
13717 			flags |= TH_ACK_NEEDED | TH_PUSH;
13718 			if (mp) {
13719 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13720 				    (uintptr_t)INT_MAX);
13721 				seg_len = mp->b_cont ? msgdsize(mp) :
13722 				    (int)(mp->b_wptr - mp->b_rptr);
13723 				seg_seq = tcp->tcp_rnxt;
13724 				/*
13725 				 * A gap is filled and the seq num and len
13726 				 * of the gap match that of a previously
13727 				 * received FIN, put the FIN flag back in.
13728 				 */
13729 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13730 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13731 					flags |= TH_FIN;
13732 					tcp->tcp_valid_bits &=
13733 					    ~TCP_OFO_FIN_VALID;
13734 				}
13735 			} else {
13736 				/*
13737 				 * Keep going even with NULL mp.
13738 				 * There may be a useful ACK or something else
13739 				 * we don't want to miss.
13740 				 *
13741 				 * But TCP should not perform fast retransmit
13742 				 * because of the ack number.  TCP uses
13743 				 * seg_len == 0 to determine if it is a pure
13744 				 * ACK.  And this is not a pure ACK.
13745 				 */
13746 				seg_len = 0;
13747 				ofo_seg = B_TRUE;
13748 			}
13749 		}
13750 	} else if (seg_len > 0) {
13751 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13752 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13753 		/*
13754 		 * If an out of order FIN was received before, and the seq
13755 		 * num and len of the new segment match that of the FIN,
13756 		 * put the FIN flag back in.
13757 		 */
13758 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13759 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13760 			flags |= TH_FIN;
13761 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13762 		}
13763 	}
13764 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13765 	if (flags & TH_RST) {
13766 		freemsg(mp);
13767 		switch (tcp->tcp_state) {
13768 		case TCPS_SYN_RCVD:
13769 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13770 			break;
13771 		case TCPS_ESTABLISHED:
13772 		case TCPS_FIN_WAIT_1:
13773 		case TCPS_FIN_WAIT_2:
13774 		case TCPS_CLOSE_WAIT:
13775 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13776 			break;
13777 		case TCPS_CLOSING:
13778 		case TCPS_LAST_ACK:
13779 			(void) tcp_clean_death(tcp, 0, 16);
13780 			break;
13781 		default:
13782 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13783 			(void) tcp_clean_death(tcp, ENXIO, 17);
13784 			break;
13785 		}
13786 		return;
13787 	}
13788 	if (flags & TH_SYN) {
13789 		/*
13790 		 * See RFC 793, Page 71
13791 		 *
13792 		 * The seq number must be in the window as it should
13793 		 * be "fixed" above.  If it is outside window, it should
13794 		 * be already rejected.  Note that we allow seg_seq to be
13795 		 * rnxt + rwnd because we want to accept 0 window probe.
13796 		 */
13797 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13798 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13799 		freemsg(mp);
13800 		/*
13801 		 * If the ACK flag is not set, just use our snxt as the
13802 		 * seq number of the RST segment.
13803 		 */
13804 		if (!(flags & TH_ACK)) {
13805 			seg_ack = tcp->tcp_snxt;
13806 		}
13807 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13808 		    TH_RST|TH_ACK);
13809 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13810 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13811 		return;
13812 	}
13813 	/*
13814 	 * urp could be -1 when the urp field in the packet is 0
13815 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13816 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13817 	 */
13818 	if (flags & TH_URG && urp >= 0) {
13819 		if (!tcp->tcp_urp_last_valid ||
13820 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13821 			if (IPCL_IS_NONSTR(connp)) {
13822 				if (!TCP_IS_DETACHED(tcp)) {
13823 					(*connp->conn_upcalls->su_signal_oob)
13824 					    (connp->conn_upper_handle, urp);
13825 				}
13826 			} else {
13827 				/*
13828 				 * If we haven't generated the signal yet for
13829 				 * this urgent pointer value, do it now.  Also,
13830 				 * send up a zero-length M_DATA indicating
13831 				 * whether or not this is the mark. The latter
13832 				 * is not needed when a T_EXDATA_IND is sent up.
13833 				 * However, if there are allocation failures
13834 				 * this code relies on the sender retransmitting
13835 				 * and the socket code for determining the mark
13836 				 * should not block waiting for the peer to
13837 				 * transmit. Thus, for simplicity we always
13838 				 * send up the mark indication.
13839 				 */
13840 				mp1 = allocb(0, BPRI_MED);
13841 				if (mp1 == NULL) {
13842 					freemsg(mp);
13843 					return;
13844 				}
13845 				if (!TCP_IS_DETACHED(tcp) &&
13846 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13847 				    SIGURG)) {
13848 					/* Try again on the rexmit. */
13849 					freemsg(mp1);
13850 					freemsg(mp);
13851 					return;
13852 				}
13853 				/*
13854 				 * Mark with NOTMARKNEXT for now.
13855 				 * The code below will change this to MARKNEXT
13856 				 * if we are at the mark.
13857 				 *
13858 				 * If there are allocation failures (e.g. in
13859 				 * dupmsg below) the next time tcp_rput_data
13860 				 * sees the urgent segment it will send up the
13861 				 * MSGMARKNEXT message.
13862 				 */
13863 				mp1->b_flag |= MSGNOTMARKNEXT;
13864 				freemsg(tcp->tcp_urp_mark_mp);
13865 				tcp->tcp_urp_mark_mp = mp1;
13866 				flags |= TH_SEND_URP_MARK;
13867 #ifdef DEBUG
13868 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13869 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13870 				    "last %x, %s",
13871 				    seg_seq, urp, tcp->tcp_urp_last,
13872 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13873 #endif /* DEBUG */
13874 			}
13875 			tcp->tcp_urp_last_valid = B_TRUE;
13876 			tcp->tcp_urp_last = urp + seg_seq;
13877 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13878 			/*
13879 			 * An allocation failure prevented the previous
13880 			 * tcp_rput_data from sending up the allocated
13881 			 * MSG*MARKNEXT message - send it up this time
13882 			 * around.
13883 			 */
13884 			flags |= TH_SEND_URP_MARK;
13885 		}
13886 
13887 		/*
13888 		 * If the urgent byte is in this segment, make sure that it is
13889 		 * all by itself.  This makes it much easier to deal with the
13890 		 * possibility of an allocation failure on the T_exdata_ind.
13891 		 * Note that seg_len is the number of bytes in the segment, and
13892 		 * urp is the offset into the segment of the urgent byte.
13893 		 * urp < seg_len means that the urgent byte is in this segment.
13894 		 */
13895 		if (urp < seg_len) {
13896 			if (seg_len != 1) {
13897 				uint32_t  tmp_rnxt;
13898 				/*
13899 				 * Break it up and feed it back in.
13900 				 * Re-attach the IP header.
13901 				 */
13902 				mp->b_rptr = iphdr;
13903 				if (urp > 0) {
13904 					/*
13905 					 * There is stuff before the urgent
13906 					 * byte.
13907 					 */
13908 					mp1 = dupmsg(mp);
13909 					if (!mp1) {
13910 						/*
13911 						 * Trim from urgent byte on.
13912 						 * The rest will come back.
13913 						 */
13914 						(void) adjmsg(mp,
13915 						    urp - seg_len);
13916 						tcp_rput_data(connp,
13917 						    mp, NULL);
13918 						return;
13919 					}
13920 					(void) adjmsg(mp1, urp - seg_len);
13921 					/* Feed this piece back in. */
13922 					tmp_rnxt = tcp->tcp_rnxt;
13923 					tcp_rput_data(connp, mp1, NULL);
13924 					/*
13925 					 * If the data passed back in was not
13926 					 * processed (ie: bad ACK) sending
13927 					 * the remainder back in will cause a
13928 					 * loop. In this case, drop the
13929 					 * packet and let the sender try
13930 					 * sending a good packet.
13931 					 */
13932 					if (tmp_rnxt == tcp->tcp_rnxt) {
13933 						freemsg(mp);
13934 						return;
13935 					}
13936 				}
13937 				if (urp != seg_len - 1) {
13938 					uint32_t  tmp_rnxt;
13939 					/*
13940 					 * There is stuff after the urgent
13941 					 * byte.
13942 					 */
13943 					mp1 = dupmsg(mp);
13944 					if (!mp1) {
13945 						/*
13946 						 * Trim everything beyond the
13947 						 * urgent byte.  The rest will
13948 						 * come back.
13949 						 */
13950 						(void) adjmsg(mp,
13951 						    urp + 1 - seg_len);
13952 						tcp_rput_data(connp,
13953 						    mp, NULL);
13954 						return;
13955 					}
13956 					(void) adjmsg(mp1, urp + 1 - seg_len);
13957 					tmp_rnxt = tcp->tcp_rnxt;
13958 					tcp_rput_data(connp, mp1, NULL);
13959 					/*
13960 					 * If the data passed back in was not
13961 					 * processed (ie: bad ACK) sending
13962 					 * the remainder back in will cause a
13963 					 * loop. In this case, drop the
13964 					 * packet and let the sender try
13965 					 * sending a good packet.
13966 					 */
13967 					if (tmp_rnxt == tcp->tcp_rnxt) {
13968 						freemsg(mp);
13969 						return;
13970 					}
13971 				}
13972 				tcp_rput_data(connp, mp, NULL);
13973 				return;
13974 			}
13975 			/*
13976 			 * This segment contains only the urgent byte.  We
13977 			 * have to allocate the T_exdata_ind, if we can.
13978 			 */
13979 			if (IPCL_IS_NONSTR(connp)) {
13980 				int error;
13981 
13982 				(*connp->conn_upcalls->su_recv)
13983 				    (connp->conn_upper_handle, mp, seg_len,
13984 				    MSG_OOB, &error, NULL);
13985 				mp = NULL;
13986 				goto update_ack;
13987 			} else if (!tcp->tcp_urp_mp) {
13988 				struct T_exdata_ind *tei;
13989 				mp1 = allocb(sizeof (struct T_exdata_ind),
13990 				    BPRI_MED);
13991 				if (!mp1) {
13992 					/*
13993 					 * Sigh... It'll be back.
13994 					 * Generate any MSG*MARK message now.
13995 					 */
13996 					freemsg(mp);
13997 					seg_len = 0;
13998 					if (flags & TH_SEND_URP_MARK) {
13999 
14000 
14001 						ASSERT(tcp->tcp_urp_mark_mp);
14002 						tcp->tcp_urp_mark_mp->b_flag &=
14003 						    ~MSGNOTMARKNEXT;
14004 						tcp->tcp_urp_mark_mp->b_flag |=
14005 						    MSGMARKNEXT;
14006 					}
14007 					goto ack_check;
14008 				}
14009 				mp1->b_datap->db_type = M_PROTO;
14010 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14011 				tei->PRIM_type = T_EXDATA_IND;
14012 				tei->MORE_flag = 0;
14013 				mp1->b_wptr = (uchar_t *)&tei[1];
14014 				tcp->tcp_urp_mp = mp1;
14015 #ifdef DEBUG
14016 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14017 				    "tcp_rput: allocated exdata_ind %s",
14018 				    tcp_display(tcp, NULL,
14019 				    DISP_PORT_ONLY));
14020 #endif /* DEBUG */
14021 				/*
14022 				 * There is no need to send a separate MSG*MARK
14023 				 * message since the T_EXDATA_IND will be sent
14024 				 * now.
14025 				 */
14026 				flags &= ~TH_SEND_URP_MARK;
14027 				freemsg(tcp->tcp_urp_mark_mp);
14028 				tcp->tcp_urp_mark_mp = NULL;
14029 			}
14030 			/*
14031 			 * Now we are all set.  On the next putnext upstream,
14032 			 * tcp_urp_mp will be non-NULL and will get prepended
14033 			 * to what has to be this piece containing the urgent
14034 			 * byte.  If for any reason we abort this segment below,
14035 			 * if it comes back, we will have this ready, or it
14036 			 * will get blown off in close.
14037 			 */
14038 		} else if (urp == seg_len) {
14039 			/*
14040 			 * The urgent byte is the next byte after this sequence
14041 			 * number. If there is data it is marked with
14042 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14043 			 * since it is not needed. Otherwise, if the code
14044 			 * above just allocated a zero-length tcp_urp_mark_mp
14045 			 * message, that message is tagged with MSGMARKNEXT.
14046 			 * Sending up these MSGMARKNEXT messages makes
14047 			 * SIOCATMARK work correctly even though
14048 			 * the T_EXDATA_IND will not be sent up until the
14049 			 * urgent byte arrives.
14050 			 */
14051 			if (seg_len != 0) {
14052 				flags |= TH_MARKNEXT_NEEDED;
14053 				freemsg(tcp->tcp_urp_mark_mp);
14054 				tcp->tcp_urp_mark_mp = NULL;
14055 				flags &= ~TH_SEND_URP_MARK;
14056 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14057 				flags |= TH_SEND_URP_MARK;
14058 				tcp->tcp_urp_mark_mp->b_flag &=
14059 				    ~MSGNOTMARKNEXT;
14060 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14061 			}
14062 #ifdef DEBUG
14063 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14064 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14065 			    seg_len, flags,
14066 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14067 #endif /* DEBUG */
14068 		}
14069 #ifdef DEBUG
14070 		else {
14071 			/* Data left until we hit mark */
14072 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14073 			    "tcp_rput: URP %d bytes left, %s",
14074 			    urp - seg_len, tcp_display(tcp, NULL,
14075 			    DISP_PORT_ONLY));
14076 		}
14077 #endif /* DEBUG */
14078 	}
14079 
14080 process_ack:
14081 	if (!(flags & TH_ACK)) {
14082 		freemsg(mp);
14083 		goto xmit_check;
14084 	}
14085 	}
14086 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14087 
14088 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14089 		tcp->tcp_ip_forward_progress = B_TRUE;
14090 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14091 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
14092 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
14093 			/* 3-way handshake complete - pass up the T_CONN_IND */
14094 			tcp_t	*listener = tcp->tcp_listener;
14095 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14096 
14097 			tcp->tcp_tconnind_started = B_TRUE;
14098 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14099 			/*
14100 			 * We are here means eager is fine but it can
14101 			 * get a TH_RST at any point between now and till
14102 			 * accept completes and disappear. We need to
14103 			 * ensure that reference to eager is valid after
14104 			 * we get out of eager's perimeter. So we do
14105 			 * an extra refhold.
14106 			 */
14107 			CONN_INC_REF(connp);
14108 
14109 			/*
14110 			 * The listener also exists because of the refhold
14111 			 * done in tcp_conn_request. Its possible that it
14112 			 * might have closed. We will check that once we
14113 			 * get inside listeners context.
14114 			 */
14115 			CONN_INC_REF(listener->tcp_connp);
14116 			if (listener->tcp_connp->conn_sqp ==
14117 			    connp->conn_sqp) {
14118 				/*
14119 				 * We optimize by not calling an SQUEUE_ENTER
14120 				 * on the listener since we know that the
14121 				 * listener and eager squeues are the same.
14122 				 * We are able to make this check safely only
14123 				 * because neither the eager nor the listener
14124 				 * can change its squeue. Only an active connect
14125 				 * can change its squeue
14126 				 */
14127 				tcp_send_conn_ind(listener->tcp_connp, mp,
14128 				    listener->tcp_connp->conn_sqp);
14129 				CONN_DEC_REF(listener->tcp_connp);
14130 			} else if (!tcp->tcp_loopback) {
14131 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14132 				    mp, tcp_send_conn_ind,
14133 				    listener->tcp_connp, SQ_FILL,
14134 				    SQTAG_TCP_CONN_IND);
14135 			} else {
14136 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14137 				    mp, tcp_send_conn_ind,
14138 				    listener->tcp_connp, SQ_PROCESS,
14139 				    SQTAG_TCP_CONN_IND);
14140 			}
14141 		}
14142 
14143 		if (tcp->tcp_active_open) {
14144 			/*
14145 			 * We are seeing the final ack in the three way
14146 			 * hand shake of a active open'ed connection
14147 			 * so we must send up a T_CONN_CON
14148 			 */
14149 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14150 				freemsg(mp);
14151 				return;
14152 			}
14153 			/*
14154 			 * Don't fuse the loopback endpoints for
14155 			 * simultaneous active opens.
14156 			 */
14157 			if (tcp->tcp_loopback) {
14158 				TCP_STAT(tcps, tcp_fusion_unfusable);
14159 				tcp->tcp_unfusable = B_TRUE;
14160 			}
14161 		}
14162 
14163 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14164 		bytes_acked--;
14165 		/* SYN was acked - making progress */
14166 		if (tcp->tcp_ipversion == IPV6_VERSION)
14167 			tcp->tcp_ip_forward_progress = B_TRUE;
14168 
14169 		/*
14170 		 * If SYN was retransmitted, need to reset all
14171 		 * retransmission info as this segment will be
14172 		 * treated as a dup ACK.
14173 		 */
14174 		if (tcp->tcp_rexmit) {
14175 			tcp->tcp_rexmit = B_FALSE;
14176 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14177 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14178 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14179 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14180 			tcp->tcp_ms_we_have_waited = 0;
14181 			tcp->tcp_cwnd = mss;
14182 		}
14183 
14184 		/*
14185 		 * We set the send window to zero here.
14186 		 * This is needed if there is data to be
14187 		 * processed already on the queue.
14188 		 * Later (at swnd_update label), the
14189 		 * "new_swnd > tcp_swnd" condition is satisfied
14190 		 * the XMIT_NEEDED flag is set in the current
14191 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14192 		 * called if there is already data on queue in
14193 		 * this state.
14194 		 */
14195 		tcp->tcp_swnd = 0;
14196 
14197 		if (new_swnd > tcp->tcp_max_swnd)
14198 			tcp->tcp_max_swnd = new_swnd;
14199 		tcp->tcp_swl1 = seg_seq;
14200 		tcp->tcp_swl2 = seg_ack;
14201 		tcp->tcp_state = TCPS_ESTABLISHED;
14202 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14203 
14204 		/* Fuse when both sides are in ESTABLISHED state */
14205 		if (tcp->tcp_loopback && do_tcp_fusion)
14206 			tcp_fuse(tcp, iphdr, tcph);
14207 
14208 	}
14209 	/* This code follows 4.4BSD-Lite2 mostly. */
14210 	if (bytes_acked < 0)
14211 		goto est;
14212 
14213 	/*
14214 	 * If TCP is ECN capable and the congestion experience bit is
14215 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14216 	 * done once per window (or more loosely, per RTT).
14217 	 */
14218 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14219 		tcp->tcp_cwr = B_FALSE;
14220 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14221 		if (!tcp->tcp_cwr) {
14222 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14223 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14224 			tcp->tcp_cwnd = npkt * mss;
14225 			/*
14226 			 * If the cwnd is 0, use the timer to clock out
14227 			 * new segments.  This is required by the ECN spec.
14228 			 */
14229 			if (npkt == 0) {
14230 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14231 				/*
14232 				 * This makes sure that when the ACK comes
14233 				 * back, we will increase tcp_cwnd by 1 MSS.
14234 				 */
14235 				tcp->tcp_cwnd_cnt = 0;
14236 			}
14237 			tcp->tcp_cwr = B_TRUE;
14238 			/*
14239 			 * This marks the end of the current window of in
14240 			 * flight data.  That is why we don't use
14241 			 * tcp_suna + tcp_swnd.  Only data in flight can
14242 			 * provide ECN info.
14243 			 */
14244 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14245 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14246 		}
14247 	}
14248 
14249 	mp1 = tcp->tcp_xmit_head;
14250 	if (bytes_acked == 0) {
14251 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14252 			int dupack_cnt;
14253 
14254 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14255 			/*
14256 			 * Fast retransmit.  When we have seen exactly three
14257 			 * identical ACKs while we have unacked data
14258 			 * outstanding we take it as a hint that our peer
14259 			 * dropped something.
14260 			 *
14261 			 * If TCP is retransmitting, don't do fast retransmit.
14262 			 */
14263 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14264 			    ! tcp->tcp_rexmit) {
14265 				/* Do Limited Transmit */
14266 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14267 				    tcps->tcps_dupack_fast_retransmit) {
14268 					/*
14269 					 * RFC 3042
14270 					 *
14271 					 * What we need to do is temporarily
14272 					 * increase tcp_cwnd so that new
14273 					 * data can be sent if it is allowed
14274 					 * by the receive window (tcp_rwnd).
14275 					 * tcp_wput_data() will take care of
14276 					 * the rest.
14277 					 *
14278 					 * If the connection is SACK capable,
14279 					 * only do limited xmit when there
14280 					 * is SACK info.
14281 					 *
14282 					 * Note how tcp_cwnd is incremented.
14283 					 * The first dup ACK will increase
14284 					 * it by 1 MSS.  The second dup ACK
14285 					 * will increase it by 2 MSS.  This
14286 					 * means that only 1 new segment will
14287 					 * be sent for each dup ACK.
14288 					 */
14289 					if (tcp->tcp_unsent > 0 &&
14290 					    (!tcp->tcp_snd_sack_ok ||
14291 					    (tcp->tcp_snd_sack_ok &&
14292 					    tcp->tcp_notsack_list != NULL))) {
14293 						tcp->tcp_cwnd += mss <<
14294 						    (tcp->tcp_dupack_cnt - 1);
14295 						flags |= TH_LIMIT_XMIT;
14296 					}
14297 				} else if (dupack_cnt ==
14298 				    tcps->tcps_dupack_fast_retransmit) {
14299 
14300 				/*
14301 				 * If we have reduced tcp_ssthresh
14302 				 * because of ECN, do not reduce it again
14303 				 * unless it is already one window of data
14304 				 * away.  After one window of data, tcp_cwr
14305 				 * should then be cleared.  Note that
14306 				 * for non ECN capable connection, tcp_cwr
14307 				 * should always be false.
14308 				 *
14309 				 * Adjust cwnd since the duplicate
14310 				 * ack indicates that a packet was
14311 				 * dropped (due to congestion.)
14312 				 */
14313 				if (!tcp->tcp_cwr) {
14314 					npkt = ((tcp->tcp_snxt -
14315 					    tcp->tcp_suna) >> 1) / mss;
14316 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14317 					    mss;
14318 					tcp->tcp_cwnd = (npkt +
14319 					    tcp->tcp_dupack_cnt) * mss;
14320 				}
14321 				if (tcp->tcp_ecn_ok) {
14322 					tcp->tcp_cwr = B_TRUE;
14323 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14324 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14325 				}
14326 
14327 				/*
14328 				 * We do Hoe's algorithm.  Refer to her
14329 				 * paper "Improving the Start-up Behavior
14330 				 * of a Congestion Control Scheme for TCP,"
14331 				 * appeared in SIGCOMM'96.
14332 				 *
14333 				 * Save highest seq no we have sent so far.
14334 				 * Be careful about the invisible FIN byte.
14335 				 */
14336 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14337 				    (tcp->tcp_unsent == 0)) {
14338 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14339 				} else {
14340 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14341 				}
14342 
14343 				/*
14344 				 * Do not allow bursty traffic during.
14345 				 * fast recovery.  Refer to Fall and Floyd's
14346 				 * paper "Simulation-based Comparisons of
14347 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14348 				 * This is a best current practise.
14349 				 */
14350 				tcp->tcp_snd_burst = TCP_CWND_SS;
14351 
14352 				/*
14353 				 * For SACK:
14354 				 * Calculate tcp_pipe, which is the
14355 				 * estimated number of bytes in
14356 				 * network.
14357 				 *
14358 				 * tcp_fack is the highest sack'ed seq num
14359 				 * TCP has received.
14360 				 *
14361 				 * tcp_pipe is explained in the above quoted
14362 				 * Fall and Floyd's paper.  tcp_fack is
14363 				 * explained in Mathis and Mahdavi's
14364 				 * "Forward Acknowledgment: Refining TCP
14365 				 * Congestion Control" in SIGCOMM '96.
14366 				 */
14367 				if (tcp->tcp_snd_sack_ok) {
14368 					ASSERT(tcp->tcp_sack_info != NULL);
14369 					if (tcp->tcp_notsack_list != NULL) {
14370 						tcp->tcp_pipe = tcp->tcp_snxt -
14371 						    tcp->tcp_fack;
14372 						tcp->tcp_sack_snxt = seg_ack;
14373 						flags |= TH_NEED_SACK_REXMIT;
14374 					} else {
14375 						/*
14376 						 * Always initialize tcp_pipe
14377 						 * even though we don't have
14378 						 * any SACK info.  If later
14379 						 * we get SACK info and
14380 						 * tcp_pipe is not initialized,
14381 						 * funny things will happen.
14382 						 */
14383 						tcp->tcp_pipe =
14384 						    tcp->tcp_cwnd_ssthresh;
14385 					}
14386 				} else {
14387 					flags |= TH_REXMIT_NEEDED;
14388 				} /* tcp_snd_sack_ok */
14389 
14390 				} else {
14391 					/*
14392 					 * Here we perform congestion
14393 					 * avoidance, but NOT slow start.
14394 					 * This is known as the Fast
14395 					 * Recovery Algorithm.
14396 					 */
14397 					if (tcp->tcp_snd_sack_ok &&
14398 					    tcp->tcp_notsack_list != NULL) {
14399 						flags |= TH_NEED_SACK_REXMIT;
14400 						tcp->tcp_pipe -= mss;
14401 						if (tcp->tcp_pipe < 0)
14402 							tcp->tcp_pipe = 0;
14403 					} else {
14404 					/*
14405 					 * We know that one more packet has
14406 					 * left the pipe thus we can update
14407 					 * cwnd.
14408 					 */
14409 					cwnd = tcp->tcp_cwnd + mss;
14410 					if (cwnd > tcp->tcp_cwnd_max)
14411 						cwnd = tcp->tcp_cwnd_max;
14412 					tcp->tcp_cwnd = cwnd;
14413 					if (tcp->tcp_unsent > 0)
14414 						flags |= TH_XMIT_NEEDED;
14415 					}
14416 				}
14417 			}
14418 		} else if (tcp->tcp_zero_win_probe) {
14419 			/*
14420 			 * If the window has opened, need to arrange
14421 			 * to send additional data.
14422 			 */
14423 			if (new_swnd != 0) {
14424 				/* tcp_suna != tcp_snxt */
14425 				/* Packet contains a window update */
14426 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14427 				tcp->tcp_zero_win_probe = 0;
14428 				tcp->tcp_timer_backoff = 0;
14429 				tcp->tcp_ms_we_have_waited = 0;
14430 
14431 				/*
14432 				 * Transmit starting with tcp_suna since
14433 				 * the one byte probe is not ack'ed.
14434 				 * If TCP has sent more than one identical
14435 				 * probe, tcp_rexmit will be set.  That means
14436 				 * tcp_ss_rexmit() will send out the one
14437 				 * byte along with new data.  Otherwise,
14438 				 * fake the retransmission.
14439 				 */
14440 				flags |= TH_XMIT_NEEDED;
14441 				if (!tcp->tcp_rexmit) {
14442 					tcp->tcp_rexmit = B_TRUE;
14443 					tcp->tcp_dupack_cnt = 0;
14444 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14445 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14446 				}
14447 			}
14448 		}
14449 		goto swnd_update;
14450 	}
14451 
14452 	/*
14453 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14454 	 * If the ACK value acks something that we have not yet sent, it might
14455 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14456 	 * other side.
14457 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14458 	 * state is handled above, so we can always just drop the segment and
14459 	 * send an ACK here.
14460 	 *
14461 	 * Should we send ACKs in response to ACK only segments?
14462 	 */
14463 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14464 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14465 		/* drop the received segment */
14466 		freemsg(mp);
14467 
14468 		/*
14469 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14470 		 * greater than 0, check if the number of such
14471 		 * bogus ACks is greater than that count.  If yes,
14472 		 * don't send back any ACK.  This prevents TCP from
14473 		 * getting into an ACK storm if somehow an attacker
14474 		 * successfully spoofs an acceptable segment to our
14475 		 * peer.
14476 		 */
14477 		if (tcp_drop_ack_unsent_cnt > 0 &&
14478 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14479 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14480 			return;
14481 		}
14482 		mp = tcp_ack_mp(tcp);
14483 		if (mp != NULL) {
14484 			BUMP_LOCAL(tcp->tcp_obsegs);
14485 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14486 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14487 		}
14488 		return;
14489 	}
14490 
14491 	/*
14492 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14493 	 * blocks that are covered by this ACK.
14494 	 */
14495 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14496 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14497 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14498 	}
14499 
14500 	/*
14501 	 * If we got an ACK after fast retransmit, check to see
14502 	 * if it is a partial ACK.  If it is not and the congestion
14503 	 * window was inflated to account for the other side's
14504 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14505 	 */
14506 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14507 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14508 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14509 			tcp->tcp_dupack_cnt = 0;
14510 			/*
14511 			 * Restore the orig tcp_cwnd_ssthresh after
14512 			 * fast retransmit phase.
14513 			 */
14514 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14515 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14516 			}
14517 			tcp->tcp_rexmit_max = seg_ack;
14518 			tcp->tcp_cwnd_cnt = 0;
14519 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14520 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14521 
14522 			/*
14523 			 * Remove all notsack info to avoid confusion with
14524 			 * the next fast retrasnmit/recovery phase.
14525 			 */
14526 			if (tcp->tcp_snd_sack_ok &&
14527 			    tcp->tcp_notsack_list != NULL) {
14528 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14529 			}
14530 		} else {
14531 			if (tcp->tcp_snd_sack_ok &&
14532 			    tcp->tcp_notsack_list != NULL) {
14533 				flags |= TH_NEED_SACK_REXMIT;
14534 				tcp->tcp_pipe -= mss;
14535 				if (tcp->tcp_pipe < 0)
14536 					tcp->tcp_pipe = 0;
14537 			} else {
14538 				/*
14539 				 * Hoe's algorithm:
14540 				 *
14541 				 * Retransmit the unack'ed segment and
14542 				 * restart fast recovery.  Note that we
14543 				 * need to scale back tcp_cwnd to the
14544 				 * original value when we started fast
14545 				 * recovery.  This is to prevent overly
14546 				 * aggressive behaviour in sending new
14547 				 * segments.
14548 				 */
14549 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14550 				    tcps->tcps_dupack_fast_retransmit * mss;
14551 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14552 				flags |= TH_REXMIT_NEEDED;
14553 			}
14554 		}
14555 	} else {
14556 		tcp->tcp_dupack_cnt = 0;
14557 		if (tcp->tcp_rexmit) {
14558 			/*
14559 			 * TCP is retranmitting.  If the ACK ack's all
14560 			 * outstanding data, update tcp_rexmit_max and
14561 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14562 			 * to the correct value.
14563 			 *
14564 			 * Note that SEQ_LEQ() is used.  This is to avoid
14565 			 * unnecessary fast retransmit caused by dup ACKs
14566 			 * received when TCP does slow start retransmission
14567 			 * after a time out.  During this phase, TCP may
14568 			 * send out segments which are already received.
14569 			 * This causes dup ACKs to be sent back.
14570 			 */
14571 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14572 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14573 					tcp->tcp_rexmit_nxt = seg_ack;
14574 				}
14575 				if (seg_ack != tcp->tcp_rexmit_max) {
14576 					flags |= TH_XMIT_NEEDED;
14577 				}
14578 			} else {
14579 				tcp->tcp_rexmit = B_FALSE;
14580 				tcp->tcp_xmit_zc_clean = B_FALSE;
14581 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14582 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14583 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14584 			}
14585 			tcp->tcp_ms_we_have_waited = 0;
14586 		}
14587 	}
14588 
14589 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14590 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14591 	tcp->tcp_suna = seg_ack;
14592 	if (tcp->tcp_zero_win_probe != 0) {
14593 		tcp->tcp_zero_win_probe = 0;
14594 		tcp->tcp_timer_backoff = 0;
14595 	}
14596 
14597 	/*
14598 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14599 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14600 	 * will not reach here.
14601 	 */
14602 	if (mp1 == NULL) {
14603 		goto fin_acked;
14604 	}
14605 
14606 	/*
14607 	 * Update the congestion window.
14608 	 *
14609 	 * If TCP is not ECN capable or TCP is ECN capable but the
14610 	 * congestion experience bit is not set, increase the tcp_cwnd as
14611 	 * usual.
14612 	 */
14613 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14614 		cwnd = tcp->tcp_cwnd;
14615 		add = mss;
14616 
14617 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14618 			/*
14619 			 * This is to prevent an increase of less than 1 MSS of
14620 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14621 			 * may send out tinygrams in order to preserve mblk
14622 			 * boundaries.
14623 			 *
14624 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14625 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14626 			 * increased by 1 MSS for every RTTs.
14627 			 */
14628 			if (tcp->tcp_cwnd_cnt <= 0) {
14629 				tcp->tcp_cwnd_cnt = cwnd + add;
14630 			} else {
14631 				tcp->tcp_cwnd_cnt -= add;
14632 				add = 0;
14633 			}
14634 		}
14635 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14636 	}
14637 
14638 	/* See if the latest urgent data has been acknowledged */
14639 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14640 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14641 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14642 
14643 	/* Can we update the RTT estimates? */
14644 	if (tcp->tcp_snd_ts_ok) {
14645 		/* Ignore zero timestamp echo-reply. */
14646 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14647 			tcp_set_rto(tcp, (int32_t)lbolt -
14648 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14649 		}
14650 
14651 		/* If needed, restart the timer. */
14652 		if (tcp->tcp_set_timer == 1) {
14653 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14654 			tcp->tcp_set_timer = 0;
14655 		}
14656 		/*
14657 		 * Update tcp_csuna in case the other side stops sending
14658 		 * us timestamps.
14659 		 */
14660 		tcp->tcp_csuna = tcp->tcp_snxt;
14661 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14662 		/*
14663 		 * An ACK sequence we haven't seen before, so get the RTT
14664 		 * and update the RTO. But first check if the timestamp is
14665 		 * valid to use.
14666 		 */
14667 		if ((mp1->b_next != NULL) &&
14668 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14669 			tcp_set_rto(tcp, (int32_t)lbolt -
14670 			    (int32_t)(intptr_t)mp1->b_prev);
14671 		else
14672 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14673 
14674 		/* Remeber the last sequence to be ACKed */
14675 		tcp->tcp_csuna = seg_ack;
14676 		if (tcp->tcp_set_timer == 1) {
14677 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14678 			tcp->tcp_set_timer = 0;
14679 		}
14680 	} else {
14681 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14682 	}
14683 
14684 	/* Eat acknowledged bytes off the xmit queue. */
14685 	for (;;) {
14686 		mblk_t	*mp2;
14687 		uchar_t	*wptr;
14688 
14689 		wptr = mp1->b_wptr;
14690 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14691 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14692 		if (bytes_acked < 0) {
14693 			mp1->b_rptr = wptr + bytes_acked;
14694 			/*
14695 			 * Set a new timestamp if all the bytes timed by the
14696 			 * old timestamp have been ack'ed.
14697 			 */
14698 			if (SEQ_GT(seg_ack,
14699 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14700 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14701 				mp1->b_next = NULL;
14702 			}
14703 			break;
14704 		}
14705 		mp1->b_next = NULL;
14706 		mp1->b_prev = NULL;
14707 		mp2 = mp1;
14708 		mp1 = mp1->b_cont;
14709 
14710 		/*
14711 		 * This notification is required for some zero-copy
14712 		 * clients to maintain a copy semantic. After the data
14713 		 * is ack'ed, client is safe to modify or reuse the buffer.
14714 		 */
14715 		if (tcp->tcp_snd_zcopy_aware &&
14716 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14717 			tcp_zcopy_notify(tcp);
14718 		freeb(mp2);
14719 		if (bytes_acked == 0) {
14720 			if (mp1 == NULL) {
14721 				/* Everything is ack'ed, clear the tail. */
14722 				tcp->tcp_xmit_tail = NULL;
14723 				/*
14724 				 * Cancel the timer unless we are still
14725 				 * waiting for an ACK for the FIN packet.
14726 				 */
14727 				if (tcp->tcp_timer_tid != 0 &&
14728 				    tcp->tcp_snxt == tcp->tcp_suna) {
14729 					(void) TCP_TIMER_CANCEL(tcp,
14730 					    tcp->tcp_timer_tid);
14731 					tcp->tcp_timer_tid = 0;
14732 				}
14733 				goto pre_swnd_update;
14734 			}
14735 			if (mp2 != tcp->tcp_xmit_tail)
14736 				break;
14737 			tcp->tcp_xmit_tail = mp1;
14738 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14739 			    (uintptr_t)INT_MAX);
14740 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14741 			    mp1->b_rptr);
14742 			break;
14743 		}
14744 		if (mp1 == NULL) {
14745 			/*
14746 			 * More was acked but there is nothing more
14747 			 * outstanding.  This means that the FIN was
14748 			 * just acked or that we're talking to a clown.
14749 			 */
14750 fin_acked:
14751 			ASSERT(tcp->tcp_fin_sent);
14752 			tcp->tcp_xmit_tail = NULL;
14753 			if (tcp->tcp_fin_sent) {
14754 				/* FIN was acked - making progress */
14755 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14756 				    !tcp->tcp_fin_acked)
14757 					tcp->tcp_ip_forward_progress = B_TRUE;
14758 				tcp->tcp_fin_acked = B_TRUE;
14759 				if (tcp->tcp_linger_tid != 0 &&
14760 				    TCP_TIMER_CANCEL(tcp,
14761 				    tcp->tcp_linger_tid) >= 0) {
14762 					tcp_stop_lingering(tcp);
14763 					freemsg(mp);
14764 					mp = NULL;
14765 				}
14766 			} else {
14767 				/*
14768 				 * We should never get here because
14769 				 * we have already checked that the
14770 				 * number of bytes ack'ed should be
14771 				 * smaller than or equal to what we
14772 				 * have sent so far (it is the
14773 				 * acceptability check of the ACK).
14774 				 * We can only get here if the send
14775 				 * queue is corrupted.
14776 				 *
14777 				 * Terminate the connection and
14778 				 * panic the system.  It is better
14779 				 * for us to panic instead of
14780 				 * continuing to avoid other disaster.
14781 				 */
14782 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14783 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14784 				panic("Memory corruption "
14785 				    "detected for connection %s.",
14786 				    tcp_display(tcp, NULL,
14787 				    DISP_ADDR_AND_PORT));
14788 				/*NOTREACHED*/
14789 			}
14790 			goto pre_swnd_update;
14791 		}
14792 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14793 	}
14794 	if (tcp->tcp_unsent) {
14795 		flags |= TH_XMIT_NEEDED;
14796 	}
14797 pre_swnd_update:
14798 	tcp->tcp_xmit_head = mp1;
14799 swnd_update:
14800 	/*
14801 	 * The following check is different from most other implementations.
14802 	 * For bi-directional transfer, when segments are dropped, the
14803 	 * "normal" check will not accept a window update in those
14804 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14805 	 * segments which are outside receiver's window.  As TCP accepts
14806 	 * the ack in those retransmitted segments, if the window update in
14807 	 * the same segment is not accepted, TCP will incorrectly calculates
14808 	 * that it can send more segments.  This can create a deadlock
14809 	 * with the receiver if its window becomes zero.
14810 	 */
14811 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14812 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14813 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14814 		/*
14815 		 * The criteria for update is:
14816 		 *
14817 		 * 1. the segment acknowledges some data.  Or
14818 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14819 		 * 3. the segment is not old and the advertised window is
14820 		 * larger than the previous advertised window.
14821 		 */
14822 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14823 			flags |= TH_XMIT_NEEDED;
14824 		tcp->tcp_swnd = new_swnd;
14825 		if (new_swnd > tcp->tcp_max_swnd)
14826 			tcp->tcp_max_swnd = new_swnd;
14827 		tcp->tcp_swl1 = seg_seq;
14828 		tcp->tcp_swl2 = seg_ack;
14829 	}
14830 est:
14831 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14832 
14833 		switch (tcp->tcp_state) {
14834 		case TCPS_FIN_WAIT_1:
14835 			if (tcp->tcp_fin_acked) {
14836 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14837 				/*
14838 				 * We implement the non-standard BSD/SunOS
14839 				 * FIN_WAIT_2 flushing algorithm.
14840 				 * If there is no user attached to this
14841 				 * TCP endpoint, then this TCP struct
14842 				 * could hang around forever in FIN_WAIT_2
14843 				 * state if the peer forgets to send us
14844 				 * a FIN.  To prevent this, we wait only
14845 				 * 2*MSL (a convenient time value) for
14846 				 * the FIN to arrive.  If it doesn't show up,
14847 				 * we flush the TCP endpoint.  This algorithm,
14848 				 * though a violation of RFC-793, has worked
14849 				 * for over 10 years in BSD systems.
14850 				 * Note: SunOS 4.x waits 675 seconds before
14851 				 * flushing the FIN_WAIT_2 connection.
14852 				 */
14853 				TCP_TIMER_RESTART(tcp,
14854 				    tcps->tcps_fin_wait_2_flush_interval);
14855 			}
14856 			break;
14857 		case TCPS_FIN_WAIT_2:
14858 			break;	/* Shutdown hook? */
14859 		case TCPS_LAST_ACK:
14860 			freemsg(mp);
14861 			if (tcp->tcp_fin_acked) {
14862 				(void) tcp_clean_death(tcp, 0, 19);
14863 				return;
14864 			}
14865 			goto xmit_check;
14866 		case TCPS_CLOSING:
14867 			if (tcp->tcp_fin_acked) {
14868 				tcp->tcp_state = TCPS_TIME_WAIT;
14869 				/*
14870 				 * Unconditionally clear the exclusive binding
14871 				 * bit so this TIME-WAIT connection won't
14872 				 * interfere with new ones.
14873 				 */
14874 				tcp->tcp_exclbind = 0;
14875 				if (!TCP_IS_DETACHED(tcp)) {
14876 					TCP_TIMER_RESTART(tcp,
14877 					    tcps->tcps_time_wait_interval);
14878 				} else {
14879 					tcp_time_wait_append(tcp);
14880 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14881 				}
14882 			}
14883 			/*FALLTHRU*/
14884 		case TCPS_CLOSE_WAIT:
14885 			freemsg(mp);
14886 			goto xmit_check;
14887 		default:
14888 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14889 			break;
14890 		}
14891 	}
14892 	if (flags & TH_FIN) {
14893 		/* Make sure we ack the fin */
14894 		flags |= TH_ACK_NEEDED;
14895 		if (!tcp->tcp_fin_rcvd) {
14896 			tcp->tcp_fin_rcvd = B_TRUE;
14897 			tcp->tcp_rnxt++;
14898 			tcph = tcp->tcp_tcph;
14899 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14900 
14901 			/*
14902 			 * Generate the ordrel_ind at the end unless we
14903 			 * are an eager guy.
14904 			 * In the eager case tcp_rsrv will do this when run
14905 			 * after tcp_accept is done.
14906 			 */
14907 			if (tcp->tcp_listener == NULL &&
14908 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14909 				flags |= TH_ORDREL_NEEDED;
14910 			switch (tcp->tcp_state) {
14911 			case TCPS_SYN_RCVD:
14912 			case TCPS_ESTABLISHED:
14913 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14914 				/* Keepalive? */
14915 				break;
14916 			case TCPS_FIN_WAIT_1:
14917 				if (!tcp->tcp_fin_acked) {
14918 					tcp->tcp_state = TCPS_CLOSING;
14919 					break;
14920 				}
14921 				/* FALLTHRU */
14922 			case TCPS_FIN_WAIT_2:
14923 				tcp->tcp_state = TCPS_TIME_WAIT;
14924 				/*
14925 				 * Unconditionally clear the exclusive binding
14926 				 * bit so this TIME-WAIT connection won't
14927 				 * interfere with new ones.
14928 				 */
14929 				tcp->tcp_exclbind = 0;
14930 				if (!TCP_IS_DETACHED(tcp)) {
14931 					TCP_TIMER_RESTART(tcp,
14932 					    tcps->tcps_time_wait_interval);
14933 				} else {
14934 					tcp_time_wait_append(tcp);
14935 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14936 				}
14937 				if (seg_len) {
14938 					/*
14939 					 * implies data piggybacked on FIN.
14940 					 * break to handle data.
14941 					 */
14942 					break;
14943 				}
14944 				freemsg(mp);
14945 				goto ack_check;
14946 			}
14947 		}
14948 	}
14949 	if (mp == NULL)
14950 		goto xmit_check;
14951 	if (seg_len == 0) {
14952 		freemsg(mp);
14953 		goto xmit_check;
14954 	}
14955 	if (mp->b_rptr == mp->b_wptr) {
14956 		/*
14957 		 * The header has been consumed, so we remove the
14958 		 * zero-length mblk here.
14959 		 */
14960 		mp1 = mp;
14961 		mp = mp->b_cont;
14962 		freeb(mp1);
14963 	}
14964 update_ack:
14965 	tcph = tcp->tcp_tcph;
14966 	tcp->tcp_rack_cnt++;
14967 	{
14968 		uint32_t cur_max;
14969 
14970 		cur_max = tcp->tcp_rack_cur_max;
14971 		if (tcp->tcp_rack_cnt >= cur_max) {
14972 			/*
14973 			 * We have more unacked data than we should - send
14974 			 * an ACK now.
14975 			 */
14976 			flags |= TH_ACK_NEEDED;
14977 			cur_max++;
14978 			if (cur_max > tcp->tcp_rack_abs_max)
14979 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14980 			else
14981 				tcp->tcp_rack_cur_max = cur_max;
14982 		} else if (TCP_IS_DETACHED(tcp)) {
14983 			/* We don't have an ACK timer for detached TCP. */
14984 			flags |= TH_ACK_NEEDED;
14985 		} else if (seg_len < mss) {
14986 			/*
14987 			 * If we get a segment that is less than an mss, and we
14988 			 * already have unacknowledged data, and the amount
14989 			 * unacknowledged is not a multiple of mss, then we
14990 			 * better generate an ACK now.  Otherwise, this may be
14991 			 * the tail piece of a transaction, and we would rather
14992 			 * wait for the response.
14993 			 */
14994 			uint32_t udif;
14995 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14996 			    (uintptr_t)INT_MAX);
14997 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14998 			if (udif && (udif % mss))
14999 				flags |= TH_ACK_NEEDED;
15000 			else
15001 				flags |= TH_ACK_TIMER_NEEDED;
15002 		} else {
15003 			/* Start delayed ack timer */
15004 			flags |= TH_ACK_TIMER_NEEDED;
15005 		}
15006 	}
15007 	tcp->tcp_rnxt += seg_len;
15008 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15009 
15010 	if (mp == NULL)
15011 		goto xmit_check;
15012 
15013 	/* Update SACK list */
15014 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15015 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15016 		    &(tcp->tcp_num_sack_blk));
15017 	}
15018 
15019 	if (tcp->tcp_urp_mp) {
15020 		tcp->tcp_urp_mp->b_cont = mp;
15021 		mp = tcp->tcp_urp_mp;
15022 		tcp->tcp_urp_mp = NULL;
15023 		/* Ready for a new signal. */
15024 		tcp->tcp_urp_last_valid = B_FALSE;
15025 #ifdef DEBUG
15026 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15027 		    "tcp_rput: sending exdata_ind %s",
15028 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15029 #endif /* DEBUG */
15030 	}
15031 
15032 	/*
15033 	 * Check for ancillary data changes compared to last segment.
15034 	 */
15035 	if (tcp->tcp_ipv6_recvancillary != 0) {
15036 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15037 		ASSERT(mp != NULL);
15038 	}
15039 
15040 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15041 		/*
15042 		 * Side queue inbound data until the accept happens.
15043 		 * tcp_accept/tcp_rput drains this when the accept happens.
15044 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15045 		 * T_EXDATA_IND) it is queued on b_next.
15046 		 * XXX Make urgent data use this. Requires:
15047 		 *	Removing tcp_listener check for TH_URG
15048 		 *	Making M_PCPROTO and MARK messages skip the eager case
15049 		 */
15050 
15051 		if (tcp->tcp_kssl_pending) {
15052 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
15053 			    mblk_t *, mp);
15054 			tcp_kssl_input(tcp, mp);
15055 		} else {
15056 			tcp_rcv_enqueue(tcp, mp, seg_len);
15057 		}
15058 	} else {
15059 		sodirect_t	*sodp = tcp->tcp_sodirect;
15060 
15061 		/*
15062 		 * If an sodirect connection and an enabled sodirect_t then
15063 		 * sodp will be set to point to the tcp_t/sonode_t shared
15064 		 * sodirect_t and the sodirect_t's lock will be held.
15065 		 */
15066 		if (sodp != NULL) {
15067 			mutex_enter(sodp->sod_lockp);
15068 			if (!(sodp->sod_state & SOD_ENABLED) ||
15069 			    (tcp->tcp_kssl_ctx != NULL &&
15070 			    DB_TYPE(mp) == M_DATA)) {
15071 				sodp = NULL;
15072 			}
15073 			mutex_exit(sodp->sod_lockp);
15074 		}
15075 		if (mp->b_datap->db_type != M_DATA ||
15076 		    (flags & TH_MARKNEXT_NEEDED)) {
15077 			if (IPCL_IS_NONSTR(connp)) {
15078 				int error;
15079 
15080 				if ((*connp->conn_upcalls->su_recv)
15081 				    (connp->conn_upper_handle, mp,
15082 				    seg_len, 0, &error, NULL) <= 0) {
15083 					if (error == ENOSPC) {
15084 						tcp->tcp_rwnd -= seg_len;
15085 					} else if (error == EOPNOTSUPP) {
15086 						tcp_rcv_enqueue(tcp, mp,
15087 						    seg_len);
15088 					}
15089 				}
15090 			} else if (sodp != NULL) {
15091 				mutex_enter(sodp->sod_lockp);
15092 				SOD_UIOAFINI(sodp);
15093 				if (!SOD_QEMPTY(sodp) &&
15094 				    (sodp->sod_state & SOD_WAKE_NOT)) {
15095 					flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15096 					/* sod_wakeup() did the mutex_exit() */
15097 				} else {
15098 					mutex_exit(sodp->sod_lockp);
15099 				}
15100 			} else if (tcp->tcp_rcv_list != NULL) {
15101 				flags |= tcp_rcv_drain(tcp);
15102 			}
15103 			ASSERT(tcp->tcp_rcv_list == NULL ||
15104 			    tcp->tcp_fused_sigurg);
15105 
15106 			if (flags & TH_MARKNEXT_NEEDED) {
15107 #ifdef DEBUG
15108 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15109 				    "tcp_rput: sending MSGMARKNEXT %s",
15110 				    tcp_display(tcp, NULL,
15111 				    DISP_PORT_ONLY));
15112 #endif /* DEBUG */
15113 				mp->b_flag |= MSGMARKNEXT;
15114 				flags &= ~TH_MARKNEXT_NEEDED;
15115 			}
15116 
15117 			/* Does this need SSL processing first? */
15118 			if ((tcp->tcp_kssl_ctx != NULL) &&
15119 			    (DB_TYPE(mp) == M_DATA)) {
15120 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15121 				    mblk_t *, mp);
15122 				tcp_kssl_input(tcp, mp);
15123 			} else if (!IPCL_IS_NONSTR(connp)) {
15124 				/* Already handled non-STREAMS case. */
15125 				putnext(tcp->tcp_rq, mp);
15126 				if (!canputnext(tcp->tcp_rq))
15127 					tcp->tcp_rwnd -= seg_len;
15128 			}
15129 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15130 		    (DB_TYPE(mp) == M_DATA)) {
15131 			/* Does this need SSL processing first? */
15132 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
15133 			tcp_kssl_input(tcp, mp);
15134 		} else if (IPCL_IS_NONSTR(connp)) {
15135 			/* Non-STREAMS socket */
15136 			boolean_t push = flags & (TH_PUSH|TH_FIN);
15137 			int	error;
15138 
15139 			if ((*connp->conn_upcalls->su_recv)(
15140 			    connp->conn_upper_handle,
15141 			    mp, seg_len, 0, &error, &push) <= 0) {
15142 				if (error == ENOSPC) {
15143 					tcp->tcp_rwnd -= seg_len;
15144 				} else if (error == EOPNOTSUPP) {
15145 					tcp_rcv_enqueue(tcp, mp, seg_len);
15146 				}
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 static char tcp_report_header[] =
16480 	"TCP     " MI_COL_HDRPAD_STR
16481 	"zone dest	    snxt     suna     "
16482 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16483 	"recent   [lport,fport] state";
16484 
16485 /*
16486  * TCP status report triggered via the Named Dispatch mechanism.
16487  */
16488 /* ARGSUSED */
16489 static void
16490 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16491     cred_t *cr)
16492 {
16493 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16494 	boolean_t ispriv = secpolicy_ip_config(cr, B_TRUE) == 0;
16495 	char cflag;
16496 	in6_addr_t	v6dst;
16497 	char buf[80];
16498 	uint_t print_len, buf_len;
16499 
16500 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16501 	if (buf_len <= 0)
16502 		return;
16503 
16504 	if (hashval >= 0)
16505 		(void) sprintf(hash, "%03d ", hashval);
16506 	else
16507 		hash[0] = '\0';
16508 
16509 	/*
16510 	 * Note that we use the remote address in the tcp_b  structure.
16511 	 * This means that it will print out the real destination address,
16512 	 * not the next hop's address if source routing is used.  This
16513 	 * avoid the confusion on the output because user may not
16514 	 * know that source routing is used for a connection.
16515 	 */
16516 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16517 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16518 	} else {
16519 		v6dst = tcp->tcp_remote_v6;
16520 	}
16521 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16522 	/*
16523 	 * the ispriv checks are so that normal users cannot determine
16524 	 * sequence number information using NDD.
16525 	 */
16526 
16527 	if (TCP_IS_DETACHED(tcp))
16528 		cflag = '*';
16529 	else
16530 		cflag = ' ';
16531 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16532 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16533 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16534 	    hash,
16535 	    (void *)tcp,
16536 	    tcp->tcp_connp->conn_zoneid,
16537 	    addrbuf,
16538 	    (ispriv) ? tcp->tcp_snxt : 0,
16539 	    (ispriv) ? tcp->tcp_suna : 0,
16540 	    tcp->tcp_swnd,
16541 	    (ispriv) ? tcp->tcp_rnxt : 0,
16542 	    (ispriv) ? tcp->tcp_rack : 0,
16543 	    tcp->tcp_rwnd,
16544 	    tcp->tcp_rto,
16545 	    tcp->tcp_mss,
16546 	    tcp->tcp_snd_ws_ok,
16547 	    tcp->tcp_snd_ws,
16548 	    tcp->tcp_rcv_ws,
16549 	    tcp->tcp_snd_ts_ok,
16550 	    tcp->tcp_ts_recent,
16551 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16552 	if (print_len < buf_len) {
16553 		((mblk_t *)mp)->b_wptr += print_len;
16554 	} else {
16555 		((mblk_t *)mp)->b_wptr += buf_len;
16556 	}
16557 }
16558 
16559 /*
16560  * TCP status report (for listeners only) triggered via the Named Dispatch
16561  * mechanism.
16562  */
16563 /* ARGSUSED */
16564 static void
16565 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16566 {
16567 	char addrbuf[INET6_ADDRSTRLEN];
16568 	in6_addr_t	v6dst;
16569 	uint_t print_len, buf_len;
16570 
16571 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16572 	if (buf_len <= 0)
16573 		return;
16574 
16575 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16576 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16577 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16578 	} else {
16579 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16580 		    addrbuf, sizeof (addrbuf));
16581 	}
16582 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16583 	    "%03d "
16584 	    MI_COL_PTRFMT_STR
16585 	    "%d %s %05u %08u %d/%d/%d%c\n",
16586 	    hashval, (void *)tcp,
16587 	    tcp->tcp_connp->conn_zoneid,
16588 	    addrbuf,
16589 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16590 	    tcp->tcp_conn_req_seqnum,
16591 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16592 	    tcp->tcp_conn_req_max,
16593 	    tcp->tcp_syn_defense ? '*' : ' ');
16594 	if (print_len < buf_len) {
16595 		((mblk_t *)mp)->b_wptr += print_len;
16596 	} else {
16597 		((mblk_t *)mp)->b_wptr += buf_len;
16598 	}
16599 }
16600 
16601 /* TCP status report triggered via the Named Dispatch mechanism. */
16602 /* ARGSUSED */
16603 static int
16604 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16605 {
16606 	tcp_t	*tcp;
16607 	int	i;
16608 	conn_t	*connp;
16609 	connf_t	*connfp;
16610 	zoneid_t zoneid;
16611 	tcp_stack_t *tcps;
16612 	ip_stack_t *ipst;
16613 
16614 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16615 	tcps = Q_TO_TCP(q)->tcp_tcps;
16616 
16617 	/*
16618 	 * Because of the ndd constraint, at most we can have 64K buffer
16619 	 * to put in all TCP info.  So to be more efficient, just
16620 	 * allocate a 64K buffer here, assuming we need that large buffer.
16621 	 * This may be a problem as any user can read tcp_status.  Therefore
16622 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16623 	 * This should be OK as normal users should not do this too often.
16624 	 */
16625 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16626 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16627 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16628 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16629 			return (0);
16630 		}
16631 	}
16632 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16633 		/* The following may work even if we cannot get a large buf. */
16634 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16635 		return (0);
16636 	}
16637 
16638 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16639 
16640 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16641 
16642 		ipst = tcps->tcps_netstack->netstack_ip;
16643 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16644 
16645 		connp = NULL;
16646 
16647 		while ((connp =
16648 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16649 			tcp = connp->conn_tcp;
16650 			if (zoneid != GLOBAL_ZONEID &&
16651 			    zoneid != connp->conn_zoneid)
16652 				continue;
16653 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16654 			    cr);
16655 		}
16656 
16657 	}
16658 
16659 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16660 	return (0);
16661 }
16662 
16663 /* TCP status report triggered via the Named Dispatch mechanism. */
16664 /* ARGSUSED */
16665 static int
16666 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16667 {
16668 	tf_t	*tbf;
16669 	tcp_t	*tcp, *ltcp;
16670 	int	i;
16671 	zoneid_t zoneid;
16672 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
16673 
16674 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16675 
16676 	/* Refer to comments in tcp_status_report(). */
16677 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16678 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16679 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16680 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16681 			return (0);
16682 		}
16683 	}
16684 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16685 		/* The following may work even if we cannot get a large buf. */
16686 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16687 		return (0);
16688 	}
16689 
16690 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16691 
16692 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
16693 		tbf = &tcps->tcps_bind_fanout[i];
16694 		mutex_enter(&tbf->tf_lock);
16695 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
16696 		    ltcp = ltcp->tcp_bind_hash) {
16697 			for (tcp = ltcp; tcp != NULL;
16698 			    tcp = tcp->tcp_bind_hash_port) {
16699 				if (zoneid != GLOBAL_ZONEID &&
16700 				    zoneid != tcp->tcp_connp->conn_zoneid)
16701 					continue;
16702 				CONN_INC_REF(tcp->tcp_connp);
16703 				tcp_report_item(mp->b_cont, tcp, i,
16704 				    Q_TO_TCP(q), cr);
16705 				CONN_DEC_REF(tcp->tcp_connp);
16706 			}
16707 		}
16708 		mutex_exit(&tbf->tf_lock);
16709 	}
16710 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16711 	return (0);
16712 }
16713 
16714 /* TCP status report triggered via the Named Dispatch mechanism. */
16715 /* ARGSUSED */
16716 static int
16717 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16718 {
16719 	connf_t	*connfp;
16720 	conn_t	*connp;
16721 	tcp_t	*tcp;
16722 	int	i;
16723 	zoneid_t zoneid;
16724 	tcp_stack_t *tcps;
16725 	ip_stack_t	*ipst;
16726 
16727 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16728 	tcps = Q_TO_TCP(q)->tcp_tcps;
16729 
16730 	/* Refer to comments in tcp_status_report(). */
16731 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16732 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16733 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16734 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16735 			return (0);
16736 		}
16737 	}
16738 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16739 		/* The following may work even if we cannot get a large buf. */
16740 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16741 		return (0);
16742 	}
16743 
16744 	(void) mi_mpprintf(mp,
16745 	    "    TCP    " MI_COL_HDRPAD_STR
16746 	    "zone IP addr	 port  seqnum   backlog (q0/q/max)");
16747 
16748 	ipst = tcps->tcps_netstack->netstack_ip;
16749 
16750 	for (i = 0; i < ipst->ips_ipcl_bind_fanout_size; i++) {
16751 		connfp = &ipst->ips_ipcl_bind_fanout[i];
16752 		connp = NULL;
16753 		while ((connp =
16754 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16755 			tcp = connp->conn_tcp;
16756 			if (zoneid != GLOBAL_ZONEID &&
16757 			    zoneid != connp->conn_zoneid)
16758 				continue;
16759 			tcp_report_listener(mp->b_cont, tcp, i);
16760 		}
16761 	}
16762 
16763 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16764 	return (0);
16765 }
16766 
16767 /* TCP status report triggered via the Named Dispatch mechanism. */
16768 /* ARGSUSED */
16769 static int
16770 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16771 {
16772 	connf_t	*connfp;
16773 	conn_t	*connp;
16774 	tcp_t	*tcp;
16775 	int	i;
16776 	zoneid_t zoneid;
16777 	tcp_stack_t *tcps;
16778 	ip_stack_t *ipst;
16779 
16780 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16781 	tcps = Q_TO_TCP(q)->tcp_tcps;
16782 	ipst = tcps->tcps_netstack->netstack_ip;
16783 
16784 	/* Refer to comments in tcp_status_report(). */
16785 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16786 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16787 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16788 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16789 			return (0);
16790 		}
16791 	}
16792 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16793 		/* The following may work even if we cannot get a large buf. */
16794 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16795 		return (0);
16796 	}
16797 
16798 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16799 	    ipst->ips_ipcl_conn_fanout_size);
16800 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16801 
16802 	for (i = 0; i < ipst->ips_ipcl_conn_fanout_size; i++) {
16803 		connfp =  &ipst->ips_ipcl_conn_fanout[i];
16804 		connp = NULL;
16805 		while ((connp =
16806 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16807 			tcp = connp->conn_tcp;
16808 			if (zoneid != GLOBAL_ZONEID &&
16809 			    zoneid != connp->conn_zoneid)
16810 				continue;
16811 			tcp_report_item(mp->b_cont, tcp, i,
16812 			    Q_TO_TCP(q), cr);
16813 		}
16814 	}
16815 
16816 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16817 	return (0);
16818 }
16819 
16820 /* TCP status report triggered via the Named Dispatch mechanism. */
16821 /* ARGSUSED */
16822 static int
16823 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16824 {
16825 	tf_t	*tf;
16826 	tcp_t	*tcp;
16827 	int	i;
16828 	zoneid_t zoneid;
16829 	tcp_stack_t	*tcps;
16830 
16831 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16832 	tcps = Q_TO_TCP(q)->tcp_tcps;
16833 
16834 	/* Refer to comments in tcp_status_report(). */
16835 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16836 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16837 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16838 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16839 			return (0);
16840 		}
16841 	}
16842 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16843 		/* The following may work even if we cannot get a large buf. */
16844 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16845 		return (0);
16846 	}
16847 
16848 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16849 
16850 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
16851 		tf = &tcps->tcps_acceptor_fanout[i];
16852 		mutex_enter(&tf->tf_lock);
16853 		for (tcp = tf->tf_tcp; tcp != NULL;
16854 		    tcp = tcp->tcp_acceptor_hash) {
16855 			if (zoneid != GLOBAL_ZONEID &&
16856 			    zoneid != tcp->tcp_connp->conn_zoneid)
16857 				continue;
16858 			tcp_report_item(mp->b_cont, tcp, i,
16859 			    Q_TO_TCP(q), cr);
16860 		}
16861 		mutex_exit(&tf->tf_lock);
16862 	}
16863 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16864 	return (0);
16865 }
16866 
16867 /*
16868  * tcp_timer is the timer service routine.  It handles the retransmission,
16869  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16870  * from the state of the tcp instance what kind of action needs to be done
16871  * at the time it is called.
16872  */
16873 static void
16874 tcp_timer(void *arg)
16875 {
16876 	mblk_t		*mp;
16877 	clock_t		first_threshold;
16878 	clock_t		second_threshold;
16879 	clock_t		ms;
16880 	uint32_t	mss;
16881 	conn_t		*connp = (conn_t *)arg;
16882 	tcp_t		*tcp = connp->conn_tcp;
16883 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16884 
16885 	tcp->tcp_timer_tid = 0;
16886 
16887 	if (tcp->tcp_fused)
16888 		return;
16889 
16890 	first_threshold =  tcp->tcp_first_timer_threshold;
16891 	second_threshold = tcp->tcp_second_timer_threshold;
16892 	switch (tcp->tcp_state) {
16893 	case TCPS_IDLE:
16894 	case TCPS_BOUND:
16895 	case TCPS_LISTEN:
16896 		return;
16897 	case TCPS_SYN_RCVD: {
16898 		tcp_t	*listener = tcp->tcp_listener;
16899 
16900 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16901 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16902 			/* it's our first timeout */
16903 			tcp->tcp_syn_rcvd_timeout = 1;
16904 			mutex_enter(&listener->tcp_eager_lock);
16905 			listener->tcp_syn_rcvd_timeout++;
16906 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16907 				/*
16908 				 * Make this eager available for drop if we
16909 				 * need to drop one to accomodate a new
16910 				 * incoming SYN request.
16911 				 */
16912 				MAKE_DROPPABLE(listener, tcp);
16913 			}
16914 			if (!listener->tcp_syn_defense &&
16915 			    (listener->tcp_syn_rcvd_timeout >
16916 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
16917 			    (tcps->tcps_conn_req_max_q0 > 200)) {
16918 				/* We may be under attack. Put on a defense. */
16919 				listener->tcp_syn_defense = B_TRUE;
16920 				cmn_err(CE_WARN, "High TCP connect timeout "
16921 				    "rate! System (port %d) may be under a "
16922 				    "SYN flood attack!",
16923 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16924 
16925 				listener->tcp_ip_addr_cache = kmem_zalloc(
16926 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16927 				    KM_NOSLEEP);
16928 			}
16929 			mutex_exit(&listener->tcp_eager_lock);
16930 		} else if (listener != NULL) {
16931 			mutex_enter(&listener->tcp_eager_lock);
16932 			tcp->tcp_syn_rcvd_timeout++;
16933 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
16934 			    !tcp->tcp_closemp_used) {
16935 				/*
16936 				 * This is our second timeout. Put the tcp in
16937 				 * the list of droppable eagers to allow it to
16938 				 * be dropped, if needed. We don't check
16939 				 * whether tcp_dontdrop is set or not to
16940 				 * protect ourselve from a SYN attack where a
16941 				 * remote host can spoof itself as one of the
16942 				 * good IP source and continue to hold
16943 				 * resources too long.
16944 				 */
16945 				MAKE_DROPPABLE(listener, tcp);
16946 			}
16947 			mutex_exit(&listener->tcp_eager_lock);
16948 		}
16949 	}
16950 		/* FALLTHRU */
16951 	case TCPS_SYN_SENT:
16952 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16953 		second_threshold = tcp->tcp_second_ctimer_threshold;
16954 		break;
16955 	case TCPS_ESTABLISHED:
16956 	case TCPS_FIN_WAIT_1:
16957 	case TCPS_CLOSING:
16958 	case TCPS_CLOSE_WAIT:
16959 	case TCPS_LAST_ACK:
16960 		/* If we have data to rexmit */
16961 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16962 			clock_t	time_to_wait;
16963 
16964 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
16965 			if (!tcp->tcp_xmit_head)
16966 				break;
16967 			time_to_wait = lbolt -
16968 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16969 			time_to_wait = tcp->tcp_rto -
16970 			    TICK_TO_MSEC(time_to_wait);
16971 			/*
16972 			 * If the timer fires too early, 1 clock tick earlier,
16973 			 * restart the timer.
16974 			 */
16975 			if (time_to_wait > msec_per_tick) {
16976 				TCP_STAT(tcps, tcp_timer_fire_early);
16977 				TCP_TIMER_RESTART(tcp, time_to_wait);
16978 				return;
16979 			}
16980 			/*
16981 			 * When we probe zero windows, we force the swnd open.
16982 			 * If our peer acks with a closed window swnd will be
16983 			 * set to zero by tcp_rput(). As long as we are
16984 			 * receiving acks tcp_rput will
16985 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16986 			 * first and second interval actions.  NOTE: the timer
16987 			 * interval is allowed to continue its exponential
16988 			 * backoff.
16989 			 */
16990 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16991 				if (tcp->tcp_debug) {
16992 					(void) strlog(TCP_MOD_ID, 0, 1,
16993 					    SL_TRACE, "tcp_timer: zero win");
16994 				}
16995 			} else {
16996 				/*
16997 				 * After retransmission, we need to do
16998 				 * slow start.  Set the ssthresh to one
16999 				 * half of current effective window and
17000 				 * cwnd to one MSS.  Also reset
17001 				 * tcp_cwnd_cnt.
17002 				 *
17003 				 * Note that if tcp_ssthresh is reduced because
17004 				 * of ECN, do not reduce it again unless it is
17005 				 * already one window of data away (tcp_cwr
17006 				 * should then be cleared) or this is a
17007 				 * timeout for a retransmitted segment.
17008 				 */
17009 				uint32_t npkt;
17010 
17011 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
17012 					npkt = ((tcp->tcp_timer_backoff ?
17013 					    tcp->tcp_cwnd_ssthresh :
17014 					    tcp->tcp_snxt -
17015 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
17016 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
17017 					    tcp->tcp_mss;
17018 				}
17019 				tcp->tcp_cwnd = tcp->tcp_mss;
17020 				tcp->tcp_cwnd_cnt = 0;
17021 				if (tcp->tcp_ecn_ok) {
17022 					tcp->tcp_cwr = B_TRUE;
17023 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17024 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17025 				}
17026 			}
17027 			break;
17028 		}
17029 		/*
17030 		 * We have something to send yet we cannot send.  The
17031 		 * reason can be:
17032 		 *
17033 		 * 1. Zero send window: we need to do zero window probe.
17034 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17035 		 * segments.
17036 		 * 3. SWS avoidance: receiver may have shrunk window,
17037 		 * reset our knowledge.
17038 		 *
17039 		 * Note that condition 2 can happen with either 1 or
17040 		 * 3.  But 1 and 3 are exclusive.
17041 		 */
17042 		if (tcp->tcp_unsent != 0) {
17043 			if (tcp->tcp_cwnd == 0) {
17044 				/*
17045 				 * Set tcp_cwnd to 1 MSS so that a
17046 				 * new segment can be sent out.  We
17047 				 * are "clocking out" new data when
17048 				 * the network is really congested.
17049 				 */
17050 				ASSERT(tcp->tcp_ecn_ok);
17051 				tcp->tcp_cwnd = tcp->tcp_mss;
17052 			}
17053 			if (tcp->tcp_swnd == 0) {
17054 				/* Extend window for zero window probe */
17055 				tcp->tcp_swnd++;
17056 				tcp->tcp_zero_win_probe = B_TRUE;
17057 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
17058 			} else {
17059 				/*
17060 				 * Handle timeout from sender SWS avoidance.
17061 				 * Reset our knowledge of the max send window
17062 				 * since the receiver might have reduced its
17063 				 * receive buffer.  Avoid setting tcp_max_swnd
17064 				 * to one since that will essentially disable
17065 				 * the SWS checks.
17066 				 *
17067 				 * Note that since we don't have a SWS
17068 				 * state variable, if the timeout is set
17069 				 * for ECN but not for SWS, this
17070 				 * code will also be executed.  This is
17071 				 * fine as tcp_max_swnd is updated
17072 				 * constantly and it will not affect
17073 				 * anything.
17074 				 */
17075 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17076 			}
17077 			tcp_wput_data(tcp, NULL, B_FALSE);
17078 			return;
17079 		}
17080 		/* Is there a FIN that needs to be to re retransmitted? */
17081 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17082 		    !tcp->tcp_fin_acked)
17083 			break;
17084 		/* Nothing to do, return without restarting timer. */
17085 		TCP_STAT(tcps, tcp_timer_fire_miss);
17086 		return;
17087 	case TCPS_FIN_WAIT_2:
17088 		/*
17089 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17090 		 * We waited some time for for peer's FIN, but it hasn't
17091 		 * arrived.  We flush the connection now to avoid
17092 		 * case where the peer has rebooted.
17093 		 */
17094 		if (TCP_IS_DETACHED(tcp)) {
17095 			(void) tcp_clean_death(tcp, 0, 23);
17096 		} else {
17097 			TCP_TIMER_RESTART(tcp,
17098 			    tcps->tcps_fin_wait_2_flush_interval);
17099 		}
17100 		return;
17101 	case TCPS_TIME_WAIT:
17102 		(void) tcp_clean_death(tcp, 0, 24);
17103 		return;
17104 	default:
17105 		if (tcp->tcp_debug) {
17106 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
17107 			    "tcp_timer: strange state (%d) %s",
17108 			    tcp->tcp_state, tcp_display(tcp, NULL,
17109 			    DISP_PORT_ONLY));
17110 		}
17111 		return;
17112 	}
17113 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17114 		/*
17115 		 * For zero window probe, we need to send indefinitely,
17116 		 * unless we have not heard from the other side for some
17117 		 * time...
17118 		 */
17119 		if ((tcp->tcp_zero_win_probe == 0) ||
17120 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17121 		    second_threshold)) {
17122 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
17123 			/*
17124 			 * If TCP is in SYN_RCVD state, send back a
17125 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17126 			 * should be zero in TCPS_SYN_RCVD state.
17127 			 */
17128 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17129 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17130 				    "in SYN_RCVD",
17131 				    tcp, tcp->tcp_snxt,
17132 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17133 			}
17134 			(void) tcp_clean_death(tcp,
17135 			    tcp->tcp_client_errno ?
17136 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17137 			return;
17138 		} else {
17139 			/*
17140 			 * Set tcp_ms_we_have_waited to second_threshold
17141 			 * so that in next timeout, we will do the above
17142 			 * check (lbolt - tcp_last_recv_time).  This is
17143 			 * also to avoid overflow.
17144 			 *
17145 			 * We don't need to decrement tcp_timer_backoff
17146 			 * to avoid overflow because it will be decremented
17147 			 * later if new timeout value is greater than
17148 			 * tcp_rexmit_interval_max.  In the case when
17149 			 * tcp_rexmit_interval_max is greater than
17150 			 * second_threshold, it means that we will wait
17151 			 * longer than second_threshold to send the next
17152 			 * window probe.
17153 			 */
17154 			tcp->tcp_ms_we_have_waited = second_threshold;
17155 		}
17156 	} else if (ms > first_threshold) {
17157 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17158 		    tcp->tcp_xmit_head != NULL) {
17159 			tcp->tcp_xmit_head =
17160 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17161 		}
17162 		/*
17163 		 * We have been retransmitting for too long...  The RTT
17164 		 * we calculated is probably incorrect.  Reinitialize it.
17165 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17166 		 * tcp_rtt_update so that we won't accidentally cache a
17167 		 * bad value.  But only do this if this is not a zero
17168 		 * window probe.
17169 		 */
17170 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17171 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17172 			    (tcp->tcp_rtt_sa >> 5);
17173 			tcp->tcp_rtt_sa = 0;
17174 			tcp_ip_notify(tcp);
17175 			tcp->tcp_rtt_update = 0;
17176 		}
17177 	}
17178 	tcp->tcp_timer_backoff++;
17179 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17180 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17181 	    tcps->tcps_rexmit_interval_min) {
17182 		/*
17183 		 * This means the original RTO is tcp_rexmit_interval_min.
17184 		 * So we will use tcp_rexmit_interval_min as the RTO value
17185 		 * and do the backoff.
17186 		 */
17187 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
17188 	} else {
17189 		ms <<= tcp->tcp_timer_backoff;
17190 	}
17191 	if (ms > tcps->tcps_rexmit_interval_max) {
17192 		ms = tcps->tcps_rexmit_interval_max;
17193 		/*
17194 		 * ms is at max, decrement tcp_timer_backoff to avoid
17195 		 * overflow.
17196 		 */
17197 		tcp->tcp_timer_backoff--;
17198 	}
17199 	tcp->tcp_ms_we_have_waited += ms;
17200 	if (tcp->tcp_zero_win_probe == 0) {
17201 		tcp->tcp_rto = ms;
17202 	}
17203 	TCP_TIMER_RESTART(tcp, ms);
17204 	/*
17205 	 * This is after a timeout and tcp_rto is backed off.  Set
17206 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17207 	 * restart the timer with a correct value.
17208 	 */
17209 	tcp->tcp_set_timer = 1;
17210 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17211 	if (mss > tcp->tcp_mss)
17212 		mss = tcp->tcp_mss;
17213 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17214 		mss = tcp->tcp_swnd;
17215 
17216 	if ((mp = tcp->tcp_xmit_head) != NULL)
17217 		mp->b_prev = (mblk_t *)lbolt;
17218 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17219 	    B_TRUE);
17220 
17221 	/*
17222 	 * When slow start after retransmission begins, start with
17223 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17224 	 * start phase.  tcp_snd_burst controls how many segments
17225 	 * can be sent because of an ack.
17226 	 */
17227 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17228 	tcp->tcp_snd_burst = TCP_CWND_SS;
17229 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17230 	    (tcp->tcp_unsent == 0)) {
17231 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17232 	} else {
17233 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17234 	}
17235 	tcp->tcp_rexmit = B_TRUE;
17236 	tcp->tcp_dupack_cnt = 0;
17237 
17238 	/*
17239 	 * Remove all rexmit SACK blk to start from fresh.
17240 	 */
17241 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17242 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17243 		tcp->tcp_num_notsack_blk = 0;
17244 		tcp->tcp_cnt_notsack_list = 0;
17245 	}
17246 	if (mp == NULL) {
17247 		return;
17248 	}
17249 	/* Attach credentials to retransmitted initial SYNs. */
17250 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17251 		mblk_setcred(mp, tcp->tcp_cred);
17252 		DB_CPID(mp) = tcp->tcp_cpid;
17253 	}
17254 
17255 	tcp->tcp_csuna = tcp->tcp_snxt;
17256 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17257 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17258 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17259 
17260 }
17261 
17262 static int
17263 tcp_do_unbind(conn_t *connp)
17264 {
17265 	tcp_t *tcp = connp->conn_tcp;
17266 	int error = 0;
17267 
17268 	switch (tcp->tcp_state) {
17269 	case TCPS_BOUND:
17270 	case TCPS_LISTEN:
17271 		break;
17272 	default:
17273 		return (-TOUTSTATE);
17274 	}
17275 
17276 	/*
17277 	 * Need to clean up all the eagers since after the unbind, segments
17278 	 * will no longer be delivered to this listener stream.
17279 	 */
17280 	mutex_enter(&tcp->tcp_eager_lock);
17281 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17282 		tcp_eager_cleanup(tcp, 0);
17283 	}
17284 	mutex_exit(&tcp->tcp_eager_lock);
17285 
17286 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17287 		tcp->tcp_ipha->ipha_src = 0;
17288 	} else {
17289 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17290 	}
17291 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17292 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17293 	tcp_bind_hash_remove(tcp);
17294 	tcp->tcp_state = TCPS_IDLE;
17295 	tcp->tcp_mdt = B_FALSE;
17296 
17297 	connp = tcp->tcp_connp;
17298 	connp->conn_mdt_ok = B_FALSE;
17299 	ipcl_hash_remove(connp);
17300 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17301 
17302 	return (error);
17303 }
17304 
17305 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17306 static void
17307 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
17308 {
17309 	int error = tcp_do_unbind(tcp->tcp_connp);
17310 
17311 	if (error > 0) {
17312 		tcp_err_ack(tcp, mp, TSYSERR, error);
17313 	} else if (error < 0) {
17314 		tcp_err_ack(tcp, mp, -error, 0);
17315 	} else {
17316 		/* Send M_FLUSH according to TPI */
17317 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17318 
17319 		mp = mi_tpi_ok_ack_alloc(mp);
17320 		putnext(tcp->tcp_rq, mp);
17321 	}
17322 }
17323 
17324 /*
17325  * Don't let port fall into the privileged range.
17326  * Since the extra privileged ports can be arbitrary we also
17327  * ensure that we exclude those from consideration.
17328  * tcp_g_epriv_ports is not sorted thus we loop over it until
17329  * there are no changes.
17330  *
17331  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17332  * but instead the code relies on:
17333  * - the fact that the address of the array and its size never changes
17334  * - the atomic assignment of the elements of the array
17335  *
17336  * Returns 0 if there are no more ports available.
17337  *
17338  * TS note: skip multilevel ports.
17339  */
17340 static in_port_t
17341 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17342 {
17343 	int i;
17344 	boolean_t restart = B_FALSE;
17345 	tcp_stack_t *tcps = tcp->tcp_tcps;
17346 
17347 	if (random && tcp_random_anon_port != 0) {
17348 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17349 		    sizeof (in_port_t));
17350 		/*
17351 		 * Unless changed by a sys admin, the smallest anon port
17352 		 * is 32768 and the largest anon port is 65535.  It is
17353 		 * very likely (50%) for the random port to be smaller
17354 		 * than the smallest anon port.  When that happens,
17355 		 * add port % (anon port range) to the smallest anon
17356 		 * port to get the random port.  It should fall into the
17357 		 * valid anon port range.
17358 		 */
17359 		if (port < tcps->tcps_smallest_anon_port) {
17360 			port = tcps->tcps_smallest_anon_port +
17361 			    port % (tcps->tcps_largest_anon_port -
17362 			    tcps->tcps_smallest_anon_port);
17363 		}
17364 	}
17365 
17366 retry:
17367 	if (port < tcps->tcps_smallest_anon_port)
17368 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17369 
17370 	if (port > tcps->tcps_largest_anon_port) {
17371 		if (restart)
17372 			return (0);
17373 		restart = B_TRUE;
17374 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17375 	}
17376 
17377 	if (port < tcps->tcps_smallest_nonpriv_port)
17378 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17379 
17380 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17381 		if (port == tcps->tcps_g_epriv_ports[i]) {
17382 			port++;
17383 			/*
17384 			 * Make sure whether the port is in the
17385 			 * valid range.
17386 			 */
17387 			goto retry;
17388 		}
17389 	}
17390 	if (is_system_labeled() &&
17391 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17392 	    IPPROTO_TCP, B_TRUE)) != 0) {
17393 		port = i;
17394 		goto retry;
17395 	}
17396 	return (port);
17397 }
17398 
17399 /*
17400  * Return the next anonymous port in the privileged port range for
17401  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17402  * downwards.  This is the same behavior as documented in the userland
17403  * library call rresvport(3N).
17404  *
17405  * TS note: skip multilevel ports.
17406  */
17407 static in_port_t
17408 tcp_get_next_priv_port(const tcp_t *tcp)
17409 {
17410 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17411 	in_port_t nextport;
17412 	boolean_t restart = B_FALSE;
17413 	tcp_stack_t *tcps = tcp->tcp_tcps;
17414 retry:
17415 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17416 	    next_priv_port >= IPPORT_RESERVED) {
17417 		next_priv_port = IPPORT_RESERVED - 1;
17418 		if (restart)
17419 			return (0);
17420 		restart = B_TRUE;
17421 	}
17422 	if (is_system_labeled() &&
17423 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17424 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17425 		next_priv_port = nextport;
17426 		goto retry;
17427 	}
17428 	return (next_priv_port--);
17429 }
17430 
17431 /* The write side r/w procedure. */
17432 
17433 #if CCS_STATS
17434 struct {
17435 	struct {
17436 		int64_t count, bytes;
17437 	} tot, hit;
17438 } wrw_stats;
17439 #endif
17440 
17441 /*
17442  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17443  * messages.
17444  */
17445 /* ARGSUSED */
17446 static void
17447 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17448 {
17449 	conn_t	*connp = (conn_t *)arg;
17450 	tcp_t	*tcp = connp->conn_tcp;
17451 	queue_t	*q = tcp->tcp_wq;
17452 
17453 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17454 	/*
17455 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17456 	 * Once the close starts, streamhead and sockfs will not let any data
17457 	 * packets come down (close ensures that there are no threads using the
17458 	 * queue and no new threads will come down) but since qprocsoff()
17459 	 * hasn't happened yet, a M_FLUSH or some non data message might
17460 	 * get reflected back (in response to our own FLUSHRW) and get
17461 	 * processed after tcp_close() is done. The conn would still be valid
17462 	 * because a ref would have added but we need to check the state
17463 	 * before actually processing the packet.
17464 	 */
17465 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17466 		freemsg(mp);
17467 		return;
17468 	}
17469 
17470 	switch (DB_TYPE(mp)) {
17471 	case M_IOCDATA:
17472 		tcp_wput_iocdata(tcp, mp);
17473 		break;
17474 	case M_FLUSH:
17475 		tcp_wput_flush(tcp, mp);
17476 		break;
17477 	default:
17478 		CALL_IP_WPUT(connp, q, mp);
17479 		break;
17480 	}
17481 }
17482 
17483 /*
17484  * The TCP fast path write put procedure.
17485  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17486  */
17487 /* ARGSUSED */
17488 void
17489 tcp_output(void *arg, mblk_t *mp, void *arg2)
17490 {
17491 	int		len;
17492 	int		hdrlen;
17493 	int		plen;
17494 	mblk_t		*mp1;
17495 	uchar_t		*rptr;
17496 	uint32_t	snxt;
17497 	tcph_t		*tcph;
17498 	struct datab	*db;
17499 	uint32_t	suna;
17500 	uint32_t	mss;
17501 	ipaddr_t	*dst;
17502 	ipaddr_t	*src;
17503 	uint32_t	sum;
17504 	int		usable;
17505 	conn_t		*connp = (conn_t *)arg;
17506 	tcp_t		*tcp = connp->conn_tcp;
17507 	uint32_t	msize;
17508 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17509 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17510 
17511 	/*
17512 	 * Try and ASSERT the minimum possible references on the
17513 	 * conn early enough. Since we are executing on write side,
17514 	 * the connection is obviously not detached and that means
17515 	 * there is a ref each for TCP and IP. Since we are behind
17516 	 * the squeue, the minimum references needed are 3. If the
17517 	 * conn is in classifier hash list, there should be an
17518 	 * extra ref for that (we check both the possibilities).
17519 	 */
17520 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17521 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17522 
17523 	ASSERT(DB_TYPE(mp) == M_DATA);
17524 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17525 
17526 	mutex_enter(&tcp->tcp_non_sq_lock);
17527 	tcp->tcp_squeue_bytes -= msize;
17528 	mutex_exit(&tcp->tcp_non_sq_lock);
17529 
17530 	/* Check to see if this connection wants to be re-fused. */
17531 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
17532 		if (tcp->tcp_ipversion == IPV4_VERSION) {
17533 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
17534 			    &tcp->tcp_saved_tcph);
17535 		} else {
17536 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
17537 			    &tcp->tcp_saved_tcph);
17538 		}
17539 	}
17540 	/* Bypass tcp protocol for fused tcp loopback */
17541 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17542 		return;
17543 
17544 	mss = tcp->tcp_mss;
17545 	if (tcp->tcp_xmit_zc_clean)
17546 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17547 
17548 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17549 	len = (int)(mp->b_wptr - mp->b_rptr);
17550 
17551 	/*
17552 	 * Criteria for fast path:
17553 	 *
17554 	 *   1. no unsent data
17555 	 *   2. single mblk in request
17556 	 *   3. connection established
17557 	 *   4. data in mblk
17558 	 *   5. len <= mss
17559 	 *   6. no tcp_valid bits
17560 	 */
17561 	if ((tcp->tcp_unsent != 0) ||
17562 	    (tcp->tcp_cork) ||
17563 	    (mp->b_cont != NULL) ||
17564 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17565 	    (len == 0) ||
17566 	    (len > mss) ||
17567 	    (tcp->tcp_valid_bits != 0)) {
17568 		tcp_wput_data(tcp, mp, B_FALSE);
17569 		return;
17570 	}
17571 
17572 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17573 	ASSERT(tcp->tcp_fin_sent == 0);
17574 
17575 	/* queue new packet onto retransmission queue */
17576 	if (tcp->tcp_xmit_head == NULL) {
17577 		tcp->tcp_xmit_head = mp;
17578 	} else {
17579 		tcp->tcp_xmit_last->b_cont = mp;
17580 	}
17581 	tcp->tcp_xmit_last = mp;
17582 	tcp->tcp_xmit_tail = mp;
17583 
17584 	/* find out how much we can send */
17585 	/* BEGIN CSTYLED */
17586 	/*
17587 	 *    un-acked	   usable
17588 	 *  |--------------|-----------------|
17589 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
17590 	 */
17591 	/* END CSTYLED */
17592 
17593 	/* start sending from tcp_snxt */
17594 	snxt = tcp->tcp_snxt;
17595 
17596 	/*
17597 	 * Check to see if this connection has been idled for some
17598 	 * time and no ACK is expected.  If it is, we need to slow
17599 	 * start again to get back the connection's "self-clock" as
17600 	 * described in VJ's paper.
17601 	 *
17602 	 * Refer to the comment in tcp_mss_set() for the calculation
17603 	 * of tcp_cwnd after idle.
17604 	 */
17605 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17606 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17607 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
17608 	}
17609 
17610 	usable = tcp->tcp_swnd;		/* tcp window size */
17611 	if (usable > tcp->tcp_cwnd)
17612 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17613 	usable -= snxt;		/* subtract stuff already sent */
17614 	suna = tcp->tcp_suna;
17615 	usable += suna;
17616 	/* usable can be < 0 if the congestion window is smaller */
17617 	if (len > usable) {
17618 		/* Can't send complete M_DATA in one shot */
17619 		goto slow;
17620 	}
17621 
17622 	mutex_enter(&tcp->tcp_non_sq_lock);
17623 	if (tcp->tcp_flow_stopped &&
17624 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17625 		tcp_clrqfull(tcp);
17626 	}
17627 	mutex_exit(&tcp->tcp_non_sq_lock);
17628 
17629 	/*
17630 	 * determine if anything to send (Nagle).
17631 	 *
17632 	 *   1. len < tcp_mss (i.e. small)
17633 	 *   2. unacknowledged data present
17634 	 *   3. len < nagle limit
17635 	 *   4. last packet sent < nagle limit (previous packet sent)
17636 	 */
17637 	if ((len < mss) && (snxt != suna) &&
17638 	    (len < (int)tcp->tcp_naglim) &&
17639 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17640 		/*
17641 		 * This was the first unsent packet and normally
17642 		 * mss < xmit_hiwater so there is no need to worry
17643 		 * about flow control. The next packet will go
17644 		 * through the flow control check in tcp_wput_data().
17645 		 */
17646 		/* leftover work from above */
17647 		tcp->tcp_unsent = len;
17648 		tcp->tcp_xmit_tail_unsent = len;
17649 
17650 		return;
17651 	}
17652 
17653 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17654 
17655 	if (snxt == suna) {
17656 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17657 	}
17658 
17659 	/* we have always sent something */
17660 	tcp->tcp_rack_cnt = 0;
17661 
17662 	tcp->tcp_snxt = snxt + len;
17663 	tcp->tcp_rack = tcp->tcp_rnxt;
17664 
17665 	if ((mp1 = dupb(mp)) == 0)
17666 		goto no_memory;
17667 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17668 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17669 
17670 	/* adjust tcp header information */
17671 	tcph = tcp->tcp_tcph;
17672 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17673 
17674 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17675 	sum = (sum >> 16) + (sum & 0xFFFF);
17676 	U16_TO_ABE16(sum, tcph->th_sum);
17677 
17678 	U32_TO_ABE32(snxt, tcph->th_seq);
17679 
17680 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17681 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17682 	BUMP_LOCAL(tcp->tcp_obsegs);
17683 
17684 	/* Update the latest receive window size in TCP header. */
17685 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17686 	    tcph->th_win);
17687 
17688 	tcp->tcp_last_sent_len = (ushort_t)len;
17689 
17690 	plen = len + tcp->tcp_hdr_len;
17691 
17692 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17693 		tcp->tcp_ipha->ipha_length = htons(plen);
17694 	} else {
17695 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17696 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17697 	}
17698 
17699 	/* see if we need to allocate a mblk for the headers */
17700 	hdrlen = tcp->tcp_hdr_len;
17701 	rptr = mp1->b_rptr - hdrlen;
17702 	db = mp1->b_datap;
17703 	if ((db->db_ref != 2) || rptr < db->db_base ||
17704 	    (!OK_32PTR(rptr))) {
17705 		/* NOTE: we assume allocb returns an OK_32PTR */
17706 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17707 		    tcps->tcps_wroff_xtra, BPRI_MED);
17708 		if (!mp) {
17709 			freemsg(mp1);
17710 			goto no_memory;
17711 		}
17712 		mp->b_cont = mp1;
17713 		mp1 = mp;
17714 		/* Leave room for Link Level header */
17715 		/* hdrlen = tcp->tcp_hdr_len; */
17716 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17717 		mp1->b_wptr = &rptr[hdrlen];
17718 	}
17719 	mp1->b_rptr = rptr;
17720 
17721 	/* Fill in the timestamp option. */
17722 	if (tcp->tcp_snd_ts_ok) {
17723 		U32_TO_BE32((uint32_t)lbolt,
17724 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17725 		U32_TO_BE32(tcp->tcp_ts_recent,
17726 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17727 	} else {
17728 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17729 	}
17730 
17731 	/* copy header into outgoing packet */
17732 	dst = (ipaddr_t *)rptr;
17733 	src = (ipaddr_t *)tcp->tcp_iphc;
17734 	dst[0] = src[0];
17735 	dst[1] = src[1];
17736 	dst[2] = src[2];
17737 	dst[3] = src[3];
17738 	dst[4] = src[4];
17739 	dst[5] = src[5];
17740 	dst[6] = src[6];
17741 	dst[7] = src[7];
17742 	dst[8] = src[8];
17743 	dst[9] = src[9];
17744 	if (hdrlen -= 40) {
17745 		hdrlen >>= 2;
17746 		dst += 10;
17747 		src += 10;
17748 		do {
17749 			*dst++ = *src++;
17750 		} while (--hdrlen);
17751 	}
17752 
17753 	/*
17754 	 * Set the ECN info in the TCP header.  Note that this
17755 	 * is not the template header.
17756 	 */
17757 	if (tcp->tcp_ecn_ok) {
17758 		SET_ECT(tcp, rptr);
17759 
17760 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17761 		if (tcp->tcp_ecn_echo_on)
17762 			tcph->th_flags[0] |= TH_ECE;
17763 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17764 			tcph->th_flags[0] |= TH_CWR;
17765 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17766 		}
17767 	}
17768 
17769 	if (tcp->tcp_ip_forward_progress) {
17770 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17771 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17772 		tcp->tcp_ip_forward_progress = B_FALSE;
17773 	}
17774 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17775 	return;
17776 
17777 	/*
17778 	 * If we ran out of memory, we pretend to have sent the packet
17779 	 * and that it was lost on the wire.
17780 	 */
17781 no_memory:
17782 	return;
17783 
17784 slow:
17785 	/* leftover work from above */
17786 	tcp->tcp_unsent = len;
17787 	tcp->tcp_xmit_tail_unsent = len;
17788 	tcp_wput_data(tcp, NULL, B_FALSE);
17789 }
17790 
17791 /* ARGSUSED */
17792 void
17793 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17794 {
17795 	conn_t			*connp = (conn_t *)arg;
17796 	tcp_t			*tcp = connp->conn_tcp;
17797 	queue_t			*q = tcp->tcp_rq;
17798 	struct tcp_options	*tcpopt;
17799 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17800 
17801 	/* socket options */
17802 	uint_t 			sopp_flags;
17803 	ssize_t			sopp_rxhiwat;
17804 	ssize_t			sopp_maxblk;
17805 	ushort_t		sopp_wroff;
17806 	ushort_t		sopp_tail;
17807 	ushort_t		sopp_copyopt;
17808 
17809 	tcpopt = (struct tcp_options *)mp->b_rptr;
17810 
17811 	/*
17812 	 * Drop the eager's ref on the listener, that was placed when
17813 	 * this eager began life in tcp_conn_request.
17814 	 */
17815 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17816 	if (IPCL_IS_NONSTR(connp)) {
17817 		/* Safe to free conn_ind message */
17818 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17819 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17820 
17821 		/* The listener tells us which upper handle to use */
17822 		ASSERT(tcpopt->to_flags & TCPOPT_UPPERHANDLE);
17823 		connp->conn_upper_handle = tcpopt->to_handle;
17824 	}
17825 
17826 	tcp->tcp_detached = B_FALSE;
17827 
17828 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17829 		/*
17830 		 * Someone blewoff the eager before we could finish
17831 		 * the accept.
17832 		 *
17833 		 * The only reason eager exists it because we put in
17834 		 * a ref on it when conn ind went up. We need to send
17835 		 * a disconnect indication up while the last reference
17836 		 * on the eager will be dropped by the squeue when we
17837 		 * return.
17838 		 */
17839 		ASSERT(tcp->tcp_listener == NULL);
17840 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17841 			if (IPCL_IS_NONSTR(connp)) {
17842 				ASSERT(tcp->tcp_issocket);
17843 				(*connp->conn_upcalls->su_disconnected)(
17844 				    connp->conn_upper_handle, tcp->tcp_connid,
17845 				    ECONNREFUSED);
17846 				freemsg(mp);
17847 			} else {
17848 				struct	T_discon_ind	*tdi;
17849 
17850 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17851 				/*
17852 				 * Let us reuse the incoming mblk to avoid
17853 				 * memory allocation failure problems. We know
17854 				 * that the size of the incoming mblk i.e.
17855 				 * stroptions is greater than sizeof
17856 				 * T_discon_ind. So the reallocb below can't
17857 				 * fail.
17858 				 */
17859 				freemsg(mp->b_cont);
17860 				mp->b_cont = NULL;
17861 				ASSERT(DB_REF(mp) == 1);
17862 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17863 				    B_FALSE);
17864 				ASSERT(mp != NULL);
17865 				DB_TYPE(mp) = M_PROTO;
17866 				((union T_primitives *)mp->b_rptr)->type =
17867 				    T_DISCON_IND;
17868 				tdi = (struct T_discon_ind *)mp->b_rptr;
17869 				if (tcp->tcp_issocket) {
17870 					tdi->DISCON_reason = ECONNREFUSED;
17871 					tdi->SEQ_number = 0;
17872 				} else {
17873 					tdi->DISCON_reason = ENOPROTOOPT;
17874 					tdi->SEQ_number =
17875 					    tcp->tcp_conn_req_seqnum;
17876 				}
17877 				mp->b_wptr = mp->b_rptr +
17878 				    sizeof (struct T_discon_ind);
17879 				putnext(q, mp);
17880 				return;
17881 			}
17882 		}
17883 		if (tcp->tcp_hard_binding) {
17884 			tcp->tcp_hard_binding = B_FALSE;
17885 			tcp->tcp_hard_bound = B_TRUE;
17886 		}
17887 		return;
17888 	}
17889 
17890 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
17891 		int boundif = tcpopt->to_boundif;
17892 		uint_t len = sizeof (int);
17893 
17894 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17895 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
17896 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred, NULL);
17897 	}
17898 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
17899 		uint_t on = 1;
17900 		uint_t len = sizeof (uint_t);
17901 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17902 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
17903 		    (uchar_t *)&on, NULL, tcp->tcp_cred, NULL);
17904 	}
17905 
17906 	/*
17907 	 * For a loopback connection with tcp_direct_sockfs on, note that
17908 	 * we don't have to protect tcp_rcv_list yet because synchronous
17909 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17910 	 * possibly race with us.
17911 	 */
17912 
17913 	/*
17914 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17915 	 * properly.  This is the first time we know of the acceptor'
17916 	 * queue.  So we do it here.
17917 	 *
17918 	 * XXX
17919 	 */
17920 	if (tcp->tcp_rcv_list == NULL) {
17921 		/*
17922 		 * Recv queue is empty, tcp_rwnd should not have changed.
17923 		 * That means it should be equal to the listener's tcp_rwnd.
17924 		 */
17925 		if (!IPCL_IS_NONSTR(connp))
17926 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17927 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
17928 	} else {
17929 #ifdef DEBUG
17930 		mblk_t *tmp;
17931 		mblk_t	*mp1;
17932 		uint_t	cnt = 0;
17933 
17934 		mp1 = tcp->tcp_rcv_list;
17935 		while ((tmp = mp1) != NULL) {
17936 			mp1 = tmp->b_next;
17937 			cnt += msgdsize(tmp);
17938 		}
17939 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17940 #endif
17941 		/* There is some data, add them back to get the max. */
17942 		if (!IPCL_IS_NONSTR(connp))
17943 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17944 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17945 	}
17946 	/*
17947 	 * This is the first time we run on the correct
17948 	 * queue after tcp_accept. So fix all the q parameters
17949 	 * here.
17950 	 */
17951 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
17952 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17953 
17954 	/*
17955 	 * Record the stream head's high water mark for this endpoint;
17956 	 * this is used for flow-control purposes.
17957 	 */
17958 	sopp_rxhiwat = tcp->tcp_fused ?
17959 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
17960 	    MAX(tcp->tcp_recv_hiwater, tcps->tcps_sth_rcv_hiwat);
17961 
17962 	/*
17963 	 * Determine what write offset value to use depending on SACK and
17964 	 * whether the endpoint is fused or not.
17965 	 */
17966 	if (tcp->tcp_fused) {
17967 		ASSERT(tcp->tcp_loopback);
17968 		ASSERT(tcp->tcp_loopback_peer != NULL);
17969 		/*
17970 		 * For fused tcp loopback, set the stream head's write
17971 		 * offset value to zero since we won't be needing any room
17972 		 * for TCP/IP headers.  This would also improve performance
17973 		 * since it would reduce the amount of work done by kmem.
17974 		 * Non-fused tcp loopback case is handled separately below.
17975 		 */
17976 		sopp_wroff = 0;
17977 		/*
17978 		 * Update the peer's transmit parameters according to
17979 		 * our recently calculated high water mark value.
17980 		 */
17981 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17982 	} else if (tcp->tcp_snd_sack_ok) {
17983 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17984 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
17985 	} else {
17986 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17987 		    tcps->tcps_wroff_xtra);
17988 	}
17989 
17990 	/*
17991 	 * If this is endpoint is handling SSL, then reserve extra
17992 	 * offset and space at the end.
17993 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17994 	 * overriding the previous setting. The extra cost of signing and
17995 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17996 	 * instead of a single contiguous one by the stream head
17997 	 * largely outweighs the statistical reduction of ACKs, when
17998 	 * applicable. The peer will also save on decryption and verification
17999 	 * costs.
18000 	 */
18001 	if (tcp->tcp_kssl_ctx != NULL) {
18002 		sopp_wroff += SSL3_WROFFSET;
18003 
18004 		sopp_flags |= SOCKOPT_TAIL;
18005 		sopp_tail = SSL3_MAX_TAIL_LEN;
18006 
18007 		sopp_flags |= SOCKOPT_ZCOPY;
18008 		sopp_copyopt = ZCVMUNSAFE;
18009 
18010 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
18011 	}
18012 
18013 	/* Send the options up */
18014 	if (IPCL_IS_NONSTR(connp)) {
18015 		struct sock_proto_props sopp;
18016 
18017 		sopp.sopp_flags = sopp_flags;
18018 		sopp.sopp_wroff = sopp_wroff;
18019 		sopp.sopp_maxblk = sopp_maxblk;
18020 		sopp.sopp_rxhiwat = sopp_rxhiwat;
18021 		if (sopp_flags & SOCKOPT_TAIL) {
18022 			ASSERT(tcp->tcp_kssl_ctx != NULL);
18023 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
18024 			sopp.sopp_tail = sopp_tail;
18025 			sopp.sopp_zcopyflag = sopp_copyopt;
18026 		}
18027 		(*connp->conn_upcalls->su_set_proto_props)
18028 		    (connp->conn_upper_handle, &sopp);
18029 	} else {
18030 		struct stroptions *stropt;
18031 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18032 		if (stropt_mp == NULL) {
18033 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
18034 			return;
18035 		}
18036 		DB_TYPE(stropt_mp) = M_SETOPTS;
18037 		stropt = (struct stroptions *)stropt_mp->b_rptr;
18038 		stropt_mp->b_wptr += sizeof (struct stroptions);
18039 		stropt = (struct stroptions *)stropt_mp->b_rptr;
18040 		stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
18041 		stropt->so_hiwat = sopp_rxhiwat;
18042 		stropt->so_wroff = sopp_wroff;
18043 		stropt->so_maxblk = sopp_maxblk;
18044 
18045 		if (sopp_flags & SOCKOPT_TAIL) {
18046 			ASSERT(tcp->tcp_kssl_ctx != NULL);
18047 
18048 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
18049 			stropt->so_tail = sopp_tail;
18050 			stropt->so_copyopt = sopp_copyopt;
18051 		}
18052 
18053 		/* Send the options up */
18054 		putnext(q, stropt_mp);
18055 	}
18056 
18057 	freemsg(mp);
18058 	/*
18059 	 * Pass up any data and/or a fin that has been received.
18060 	 *
18061 	 * Adjust receive window in case it had decreased
18062 	 * (because there is data <=> tcp_rcv_list != NULL)
18063 	 * while the connection was detached. Note that
18064 	 * in case the eager was flow-controlled, w/o this
18065 	 * code, the rwnd may never open up again!
18066 	 */
18067 	if (tcp->tcp_rcv_list != NULL) {
18068 		if (IPCL_IS_NONSTR(connp)) {
18069 			mblk_t *mp;
18070 			int space_left;
18071 			int error;
18072 			boolean_t push = B_TRUE;
18073 
18074 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
18075 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
18076 			    &push) >= 0) {
18077 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
18078 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18079 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
18080 					tcp_xmit_ctl(NULL,
18081 					    tcp, (tcp->tcp_swnd == 0) ?
18082 					    tcp->tcp_suna : tcp->tcp_snxt,
18083 					    tcp->tcp_rnxt, TH_ACK);
18084 				}
18085 			}
18086 			while ((mp = tcp->tcp_rcv_list) != NULL) {
18087 				push = B_TRUE;
18088 				tcp->tcp_rcv_list = mp->b_next;
18089 				mp->b_next = NULL;
18090 				space_left = (*connp->conn_upcalls->su_recv)
18091 				    (connp->conn_upper_handle, mp, msgdsize(mp),
18092 				    0, &error, &push);
18093 				if (space_left < 0) {
18094 					/*
18095 					 * At this point the eager is not
18096 					 * visible to anyone, so fallback
18097 					 * can not happen.
18098 					 */
18099 					ASSERT(error != EOPNOTSUPP);
18100 				}
18101 			}
18102 			tcp->tcp_rcv_last_head = NULL;
18103 			tcp->tcp_rcv_last_tail = NULL;
18104 			tcp->tcp_rcv_cnt = 0;
18105 		} else {
18106 			/* We drain directly in case of fused tcp loopback */
18107 			sodirect_t *sodp;
18108 
18109 			if (!tcp->tcp_fused && canputnext(q)) {
18110 				tcp->tcp_rwnd = q->q_hiwat;
18111 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18112 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
18113 					tcp_xmit_ctl(NULL,
18114 					    tcp, (tcp->tcp_swnd == 0) ?
18115 					    tcp->tcp_suna : tcp->tcp_snxt,
18116 					    tcp->tcp_rnxt, TH_ACK);
18117 				}
18118 			}
18119 
18120 			SOD_PTR_ENTER(tcp, sodp);
18121 			if (sodp != NULL) {
18122 				/* Sodirect, move from rcv_list */
18123 				ASSERT(!tcp->tcp_fused);
18124 				while ((mp = tcp->tcp_rcv_list) != NULL) {
18125 					tcp->tcp_rcv_list = mp->b_next;
18126 					mp->b_next = NULL;
18127 					(void) tcp_rcv_sod_enqueue(tcp, sodp,
18128 					    mp, msgdsize(mp));
18129 				}
18130 				tcp->tcp_rcv_last_head = NULL;
18131 				tcp->tcp_rcv_last_tail = NULL;
18132 				tcp->tcp_rcv_cnt = 0;
18133 				(void) tcp_rcv_sod_wakeup(tcp, sodp);
18134 				/* sod_wakeup() did the mutex_exit() */
18135 			} else {
18136 				/* Not sodirect, drain */
18137 				(void) tcp_rcv_drain(tcp);
18138 			}
18139 		}
18140 
18141 		/*
18142 		 * For fused tcp loopback, back-enable peer endpoint
18143 		 * if it's currently flow-controlled.
18144 		 */
18145 		if (tcp->tcp_fused) {
18146 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18147 
18148 			ASSERT(peer_tcp != NULL);
18149 			ASSERT(peer_tcp->tcp_fused);
18150 			/*
18151 			 * In order to change the peer's tcp_flow_stopped,
18152 			 * we need to take locks for both end points. The
18153 			 * highest address is taken first.
18154 			 */
18155 			if (peer_tcp > tcp) {
18156 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18157 				mutex_enter(&tcp->tcp_non_sq_lock);
18158 			} else {
18159 				mutex_enter(&tcp->tcp_non_sq_lock);
18160 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18161 			}
18162 			if (peer_tcp->tcp_flow_stopped) {
18163 				tcp_clrqfull(peer_tcp);
18164 				TCP_STAT(tcps, tcp_fusion_backenabled);
18165 			}
18166 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18167 			mutex_exit(&tcp->tcp_non_sq_lock);
18168 		}
18169 	}
18170 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18171 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18172 		tcp->tcp_ordrel_done = B_TRUE;
18173 		if (IPCL_IS_NONSTR(connp)) {
18174 			ASSERT(tcp->tcp_ordrel_mp == NULL);
18175 			(*connp->conn_upcalls->su_opctl)(
18176 			    connp->conn_upper_handle,
18177 			    SOCK_OPCTL_SHUT_RECV, 0);
18178 		} else {
18179 			mp = tcp->tcp_ordrel_mp;
18180 			tcp->tcp_ordrel_mp = NULL;
18181 			putnext(q, mp);
18182 		}
18183 	}
18184 	if (tcp->tcp_hard_binding) {
18185 		tcp->tcp_hard_binding = B_FALSE;
18186 		tcp->tcp_hard_bound = B_TRUE;
18187 	}
18188 
18189 	/* We can enable synchronous streams for STREAMS tcp endpoint now */
18190 	if (tcp->tcp_fused && !IPCL_IS_NONSTR(connp) &&
18191 	    tcp->tcp_loopback_peer != NULL &&
18192 	    !IPCL_IS_NONSTR(tcp->tcp_loopback_peer->tcp_connp)) {
18193 		tcp_fuse_syncstr_enable_pair(tcp);
18194 	}
18195 
18196 	if (tcp->tcp_ka_enabled) {
18197 		tcp->tcp_ka_last_intrvl = 0;
18198 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18199 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18200 	}
18201 
18202 	/*
18203 	 * At this point, eager is fully established and will
18204 	 * have the following references -
18205 	 *
18206 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18207 	 * 1 reference for the squeue which will be dropped by the squeue as
18208 	 *	soon as this function returns.
18209 	 * There will be 1 additonal reference for being in classifier
18210 	 *	hash list provided something bad hasn't happened.
18211 	 */
18212 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18213 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18214 }
18215 
18216 /*
18217  * The function called through squeue to get behind listener's perimeter to
18218  * send a deffered conn_ind.
18219  */
18220 /* ARGSUSED */
18221 void
18222 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18223 {
18224 	conn_t	*connp = (conn_t *)arg;
18225 	tcp_t *listener = connp->conn_tcp;
18226 	struct T_conn_ind *conn_ind;
18227 	tcp_t *tcp;
18228 
18229 	if (listener->tcp_state == TCPS_CLOSED ||
18230 	    TCP_IS_DETACHED(listener)) {
18231 		/*
18232 		 * If listener has closed, it would have caused a
18233 		 * a cleanup/blowoff to happen for the eager.
18234 		 */
18235 
18236 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18237 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18238 		    conn_ind->OPT_length);
18239 		/*
18240 		 * We need to drop the ref on eager that was put
18241 		 * tcp_rput_data() before trying to send the conn_ind
18242 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18243 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18244 		 * listener is closed so we drop the ref.
18245 		 */
18246 		CONN_DEC_REF(tcp->tcp_connp);
18247 		freemsg(mp);
18248 		return;
18249 	}
18250 	if (IPCL_IS_NONSTR(connp)) {
18251 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18252 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18253 		    conn_ind->OPT_length);
18254 
18255 		if ((*connp->conn_upcalls->su_newconn)
18256 		    (connp->conn_upper_handle,
18257 		    (sock_lower_handle_t)tcp->tcp_connp,
18258 		    &sock_tcp_downcalls, DB_CRED(mp), DB_CPID(mp),
18259 		    &tcp->tcp_connp->conn_upcalls) != NULL) {
18260 			/* Keep the message around in case of fallback */
18261 			tcp->tcp_conn.tcp_eager_conn_ind = mp;
18262 		} else {
18263 			freemsg(mp);
18264 		}
18265 	} else {
18266 		putnext(listener->tcp_rq, mp);
18267 	}
18268 }
18269 
18270 /* ARGSUSED */
18271 static int
18272 tcp_accept_common(conn_t *lconnp, conn_t *econnp,
18273     sock_upper_handle_t sock_handle, cred_t *cr)
18274 {
18275 	tcp_t *listener, *eager;
18276 	mblk_t *opt_mp;
18277 	struct tcp_options *tcpopt;
18278 
18279 	listener = lconnp->conn_tcp;
18280 	ASSERT(listener->tcp_state == TCPS_LISTEN);
18281 	eager = econnp->conn_tcp;
18282 	ASSERT(eager->tcp_listener != NULL);
18283 
18284 	ASSERT(eager->tcp_rq != NULL);
18285 
18286 	/* If tcp_fused and sodirect enabled disable it */
18287 	if (eager->tcp_fused && eager->tcp_sodirect != NULL) {
18288 		/* Fused, disable sodirect */
18289 		mutex_enter(eager->tcp_sodirect->sod_lockp);
18290 		SOD_DISABLE(eager->tcp_sodirect);
18291 		mutex_exit(eager->tcp_sodirect->sod_lockp);
18292 		eager->tcp_sodirect = NULL;
18293 	}
18294 
18295 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
18296 	if (opt_mp == NULL) {
18297 		return (-TPROTO);
18298 	}
18299 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
18300 	eager->tcp_issocket = B_TRUE;
18301 
18302 	econnp->conn_upcalls = lconnp->conn_upcalls;
18303 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18304 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18305 	ASSERT(econnp->conn_netstack ==
18306 	    listener->tcp_connp->conn_netstack);
18307 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18308 
18309 	/* Put the ref for IP */
18310 	CONN_INC_REF(econnp);
18311 
18312 	/*
18313 	 * We should have minimum of 3 references on the conn
18314 	 * at this point. One each for TCP and IP and one for
18315 	 * the T_conn_ind that was sent up when the 3-way handshake
18316 	 * completed. In the normal case we would also have another
18317 	 * reference (making a total of 4) for the conn being in the
18318 	 * classifier hash list. However the eager could have received
18319 	 * an RST subsequently and tcp_closei_local could have removed
18320 	 * the eager from the classifier hash list, hence we can't
18321 	 * assert that reference.
18322 	 */
18323 	ASSERT(econnp->conn_ref >= 3);
18324 
18325 	opt_mp->b_datap->db_type = M_SETOPTS;
18326 	opt_mp->b_wptr += sizeof (struct tcp_options);
18327 
18328 	/*
18329 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18330 	 * from listener to acceptor. In case of non-STREAMS sockets,
18331 	 * we also need to pass the upper handle along.
18332 	 */
18333 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
18334 	tcpopt->to_flags = 0;
18335 
18336 	if (IPCL_IS_NONSTR(econnp)) {
18337 		ASSERT(sock_handle != NULL);
18338 		tcpopt->to_flags |= TCPOPT_UPPERHANDLE;
18339 		tcpopt->to_handle = sock_handle;
18340 	}
18341 	if (listener->tcp_bound_if != 0) {
18342 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
18343 		tcpopt->to_boundif = listener->tcp_bound_if;
18344 	}
18345 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18346 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
18347 	}
18348 
18349 	mutex_enter(&listener->tcp_eager_lock);
18350 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18351 
18352 		tcp_t *tail;
18353 		tcp_t *tcp;
18354 		mblk_t *mp1;
18355 
18356 		tcp = listener->tcp_eager_prev_q0;
18357 		/*
18358 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
18359 		 * deferred T_conn_ind queue. We need to get to the head
18360 		 * of the queue in order to send up T_conn_ind the same
18361 		 * order as how the 3WHS is completed.
18362 		 */
18363 		while (tcp != listener) {
18364 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18365 			    !tcp->tcp_kssl_pending)
18366 				break;
18367 			else
18368 				tcp = tcp->tcp_eager_prev_q0;
18369 		}
18370 		/* None of the pending eagers can be sent up now */
18371 		if (tcp == listener)
18372 			goto no_more_eagers;
18373 
18374 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18375 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18376 		/* Move from q0 to q */
18377 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18378 		listener->tcp_conn_req_cnt_q0--;
18379 		listener->tcp_conn_req_cnt_q++;
18380 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18381 		    tcp->tcp_eager_prev_q0;
18382 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18383 		    tcp->tcp_eager_next_q0;
18384 		tcp->tcp_eager_prev_q0 = NULL;
18385 		tcp->tcp_eager_next_q0 = NULL;
18386 		tcp->tcp_conn_def_q0 = B_FALSE;
18387 
18388 		/* Make sure the tcp isn't in the list of droppables */
18389 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18390 		    tcp->tcp_eager_prev_drop_q0 == NULL);
18391 
18392 		/*
18393 		 * Insert at end of the queue because sockfs sends
18394 		 * down T_CONN_RES in chronological order. Leaving
18395 		 * the older conn indications at front of the queue
18396 		 * helps reducing search time.
18397 		 */
18398 		tail = listener->tcp_eager_last_q;
18399 		if (tail != NULL) {
18400 			tail->tcp_eager_next_q = tcp;
18401 		} else {
18402 			listener->tcp_eager_next_q = tcp;
18403 		}
18404 		listener->tcp_eager_last_q = tcp;
18405 		tcp->tcp_eager_next_q = NULL;
18406 
18407 		/* Need to get inside the listener perimeter */
18408 		CONN_INC_REF(listener->tcp_connp);
18409 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
18410 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
18411 		    SQTAG_TCP_SEND_PENDING);
18412 	}
18413 no_more_eagers:
18414 	tcp_eager_unlink(eager);
18415 	mutex_exit(&listener->tcp_eager_lock);
18416 
18417 	/*
18418 	 * At this point, the eager is detached from the listener
18419 	 * but we still have an extra refs on eager (apart from the
18420 	 * usual tcp references). The ref was placed in tcp_rput_data
18421 	 * before sending the conn_ind in tcp_send_conn_ind.
18422 	 * The ref will be dropped in tcp_accept_finish().
18423 	 */
18424 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
18425 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
18426 	return (0);
18427 }
18428 
18429 int
18430 tcp_accept(sock_lower_handle_t lproto_handle,
18431     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
18432     cred_t *cr)
18433 {
18434 	conn_t *lconnp, *econnp;
18435 	tcp_t *listener, *eager;
18436 	tcp_stack_t	*tcps;
18437 
18438 	lconnp = (conn_t *)lproto_handle;
18439 	listener = lconnp->conn_tcp;
18440 	ASSERT(listener->tcp_state == TCPS_LISTEN);
18441 	econnp = (conn_t *)eproto_handle;
18442 	eager = econnp->conn_tcp;
18443 	ASSERT(eager->tcp_listener != NULL);
18444 	tcps = eager->tcp_tcps;
18445 
18446 	ASSERT(IPCL_IS_NONSTR(econnp));
18447 	/*
18448 	 * Create helper stream if it is a non-TPI TCP connection.
18449 	 */
18450 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
18451 		ip1dbg(("tcp_accept: create of IP helper stream"
18452 		    " failed\n"));
18453 		return (EPROTO);
18454 	}
18455 	eager->tcp_rq = econnp->conn_rq;
18456 	eager->tcp_wq = econnp->conn_wq;
18457 
18458 	ASSERT(eager->tcp_rq != NULL);
18459 
18460 	eager->tcp_sodirect = SOD_SOTOSODP(sock_handle);
18461 	return (tcp_accept_common(lconnp, econnp, sock_handle, cr));
18462 }
18463 
18464 
18465 /*
18466  * This is the STREAMS entry point for T_CONN_RES coming down on
18467  * Acceptor STREAM when  sockfs listener does accept processing.
18468  * Read the block comment on top of tcp_conn_request().
18469  */
18470 void
18471 tcp_tpi_accept(queue_t *q, mblk_t *mp)
18472 {
18473 	queue_t *rq = RD(q);
18474 	struct T_conn_res *conn_res;
18475 	tcp_t *eager;
18476 	tcp_t *listener;
18477 	struct T_ok_ack *ok;
18478 	t_scalar_t PRIM_type;
18479 	conn_t *econnp;
18480 
18481 	ASSERT(DB_TYPE(mp) == M_PROTO);
18482 
18483 	conn_res = (struct T_conn_res *)mp->b_rptr;
18484 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18485 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18486 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18487 		if (mp != NULL)
18488 			putnext(rq, mp);
18489 		return;
18490 	}
18491 	switch (conn_res->PRIM_type) {
18492 	case O_T_CONN_RES:
18493 	case T_CONN_RES:
18494 		/*
18495 		 * We pass up an err ack if allocb fails. This will
18496 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18497 		 * tcp_eager_blowoff to be called. sockfs will then call
18498 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18499 		 * we need to do the allocb up here because we have to
18500 		 * make sure rq->q_qinfo->qi_qclose still points to the
18501 		 * correct function (tcpclose_accept) in case allocb
18502 		 * fails.
18503 		 */
18504 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18505 		    &eager, conn_res->OPT_length);
18506 		PRIM_type = conn_res->PRIM_type;
18507 		mp->b_datap->db_type = M_PCPROTO;
18508 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18509 		ok = (struct T_ok_ack *)mp->b_rptr;
18510 		ok->PRIM_type = T_OK_ACK;
18511 		ok->CORRECT_prim = PRIM_type;
18512 		econnp = eager->tcp_connp;
18513 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
18514 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
18515 		eager->tcp_rq = rq;
18516 		eager->tcp_wq = q;
18517 		rq->q_ptr = econnp;
18518 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
18519 		q->q_ptr = econnp;
18520 		q->q_qinfo = &tcp_winit;
18521 		listener = eager->tcp_listener;
18522 
18523 		/*
18524 		 * TCP is _D_SODIRECT and sockfs is directly above so
18525 		 * save shared sodirect_t pointer (if any).
18526 		 */
18527 		eager->tcp_sodirect = SOD_QTOSODP(eager->tcp_rq);
18528 		if (tcp_accept_common(listener->tcp_connp,
18529 		    econnp, NULL, CRED()) < 0) {
18530 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18531 			if (mp != NULL)
18532 				putnext(rq, mp);
18533 			return;
18534 		}
18535 
18536 		/*
18537 		 * Send the new local address also up to sockfs. There
18538 		 * should already be enough space in the mp that came
18539 		 * down from soaccept().
18540 		 */
18541 		if (eager->tcp_family == AF_INET) {
18542 			sin_t *sin;
18543 
18544 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18545 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18546 			sin = (sin_t *)mp->b_wptr;
18547 			mp->b_wptr += sizeof (sin_t);
18548 			sin->sin_family = AF_INET;
18549 			sin->sin_port = eager->tcp_lport;
18550 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18551 		} else {
18552 			sin6_t *sin6;
18553 
18554 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18555 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18556 			sin6 = (sin6_t *)mp->b_wptr;
18557 			mp->b_wptr += sizeof (sin6_t);
18558 			sin6->sin6_family = AF_INET6;
18559 			sin6->sin6_port = eager->tcp_lport;
18560 			if (eager->tcp_ipversion == IPV4_VERSION) {
18561 				sin6->sin6_flowinfo = 0;
18562 				IN6_IPADDR_TO_V4MAPPED(
18563 				    eager->tcp_ipha->ipha_src,
18564 				    &sin6->sin6_addr);
18565 			} else {
18566 				ASSERT(eager->tcp_ip6h != NULL);
18567 				sin6->sin6_flowinfo =
18568 				    eager->tcp_ip6h->ip6_vcf &
18569 				    ~IPV6_VERS_AND_FLOW_MASK;
18570 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18571 			}
18572 			sin6->sin6_scope_id = 0;
18573 			sin6->__sin6_src_id = 0;
18574 		}
18575 
18576 		putnext(rq, mp);
18577 		return;
18578 	default:
18579 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18580 		if (mp != NULL)
18581 			putnext(rq, mp);
18582 		return;
18583 	}
18584 }
18585 
18586 static int
18587 tcp_getmyname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18588 {
18589 	sin_t *sin = (sin_t *)sa;
18590 	sin6_t *sin6 = (sin6_t *)sa;
18591 
18592 	switch (tcp->tcp_family) {
18593 	case AF_INET:
18594 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18595 
18596 		if (*salenp < sizeof (sin_t))
18597 			return (EINVAL);
18598 
18599 		*sin = sin_null;
18600 		sin->sin_family = AF_INET;
18601 		sin->sin_port = tcp->tcp_lport;
18602 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
18603 		break;
18604 
18605 	case AF_INET6:
18606 		if (*salenp < sizeof (sin6_t))
18607 			return (EINVAL);
18608 
18609 		*sin6 = sin6_null;
18610 		sin6->sin6_family = AF_INET6;
18611 		sin6->sin6_port = tcp->tcp_lport;
18612 		if (tcp->tcp_ipversion == IPV4_VERSION) {
18613 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
18614 			    &sin6->sin6_addr);
18615 		} else {
18616 			sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
18617 		}
18618 		break;
18619 	}
18620 
18621 	return (0);
18622 }
18623 
18624 static int
18625 i_tcp_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18626 {
18627 	sin_t *sin = (sin_t *)sa;
18628 	sin6_t *sin6 = (sin6_t *)sa;
18629 
18630 	if (tcp->tcp_state < TCPS_SYN_RCVD)
18631 		return (ENOTCONN);
18632 
18633 	switch (tcp->tcp_family) {
18634 	case AF_INET:
18635 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18636 
18637 		if (*salenp < sizeof (sin_t))
18638 			return (EINVAL);
18639 
18640 		*sin = sin_null;
18641 		sin->sin_family = AF_INET;
18642 		sin->sin_port = tcp->tcp_fport;
18643 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
18644 		    sin->sin_addr.s_addr);
18645 		*salenp = sizeof (sin_t);
18646 		break;
18647 
18648 	case AF_INET6:
18649 		if (*salenp < sizeof (sin6_t))
18650 			return (EINVAL);
18651 
18652 		*sin6 = sin6_null;
18653 		sin6->sin6_family = AF_INET6;
18654 		sin6->sin6_port = tcp->tcp_fport;
18655 		sin6->sin6_addr = tcp->tcp_remote_v6;
18656 		if (tcp->tcp_ipversion == IPV6_VERSION) {
18657 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
18658 			    ~IPV6_VERS_AND_FLOW_MASK;
18659 		}
18660 		*salenp = sizeof (sin6_t);
18661 		break;
18662 	}
18663 
18664 	return (0);
18665 }
18666 
18667 /*
18668  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
18669  */
18670 static void
18671 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
18672 {
18673 	void	*data;
18674 	mblk_t	*datamp = mp->b_cont;
18675 	tcp_t	*tcp = Q_TO_TCP(q);
18676 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
18677 
18678 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
18679 		cmdp->cb_error = EPROTO;
18680 		qreply(q, mp);
18681 		return;
18682 	}
18683 
18684 	data = datamp->b_rptr;
18685 
18686 	switch (cmdp->cb_cmd) {
18687 	case TI_GETPEERNAME:
18688 		cmdp->cb_error = i_tcp_getpeername(tcp, data, &cmdp->cb_len);
18689 		break;
18690 	case TI_GETMYNAME:
18691 		cmdp->cb_error = tcp_getmyname(tcp, data, &cmdp->cb_len);
18692 		break;
18693 	default:
18694 		cmdp->cb_error = EINVAL;
18695 		break;
18696 	}
18697 
18698 	qreply(q, mp);
18699 }
18700 
18701 void
18702 tcp_wput(queue_t *q, mblk_t *mp)
18703 {
18704 	conn_t	*connp = Q_TO_CONN(q);
18705 	tcp_t	*tcp;
18706 	void (*output_proc)();
18707 	t_scalar_t type;
18708 	uchar_t *rptr;
18709 	struct iocblk	*iocp;
18710 	size_t size;
18711 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18712 
18713 	ASSERT(connp->conn_ref >= 2);
18714 
18715 	switch (DB_TYPE(mp)) {
18716 	case M_DATA:
18717 		tcp = connp->conn_tcp;
18718 		ASSERT(tcp != NULL);
18719 
18720 		size = msgdsize(mp);
18721 
18722 		mutex_enter(&tcp->tcp_non_sq_lock);
18723 		tcp->tcp_squeue_bytes += size;
18724 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18725 			tcp_setqfull(tcp);
18726 		}
18727 		mutex_exit(&tcp->tcp_non_sq_lock);
18728 
18729 		CONN_INC_REF(connp);
18730 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18731 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18732 		return;
18733 
18734 	case M_CMD:
18735 		tcp_wput_cmdblk(q, mp);
18736 		return;
18737 
18738 	case M_PROTO:
18739 	case M_PCPROTO:
18740 		/*
18741 		 * if it is a snmp message, don't get behind the squeue
18742 		 */
18743 		tcp = connp->conn_tcp;
18744 		rptr = mp->b_rptr;
18745 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18746 			type = ((union T_primitives *)rptr)->type;
18747 		} else {
18748 			if (tcp->tcp_debug) {
18749 				(void) strlog(TCP_MOD_ID, 0, 1,
18750 				    SL_ERROR|SL_TRACE,
18751 				    "tcp_wput_proto, dropping one...");
18752 			}
18753 			freemsg(mp);
18754 			return;
18755 		}
18756 		if (type == T_SVR4_OPTMGMT_REQ) {
18757 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
18758 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18759 			    cr)) {
18760 				/*
18761 				 * This was a SNMP request
18762 				 */
18763 				return;
18764 			} else {
18765 				output_proc = tcp_wput_proto;
18766 			}
18767 		} else {
18768 			output_proc = tcp_wput_proto;
18769 		}
18770 		break;
18771 	case M_IOCTL:
18772 		/*
18773 		 * Most ioctls can be processed right away without going via
18774 		 * squeues - process them right here. Those that do require
18775 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18776 		 * are processed by tcp_wput_ioctl().
18777 		 */
18778 		iocp = (struct iocblk *)mp->b_rptr;
18779 		tcp = connp->conn_tcp;
18780 
18781 		switch (iocp->ioc_cmd) {
18782 		case TCP_IOC_ABORT_CONN:
18783 			tcp_ioctl_abort_conn(q, mp);
18784 			return;
18785 		case TI_GETPEERNAME:
18786 		case TI_GETMYNAME:
18787 			mi_copyin(q, mp, NULL,
18788 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18789 			return;
18790 		case ND_SET:
18791 			/* nd_getset does the necessary checks */
18792 		case ND_GET:
18793 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18794 				CALL_IP_WPUT(connp, q, mp);
18795 				return;
18796 			}
18797 			qreply(q, mp);
18798 			return;
18799 		case TCP_IOC_DEFAULT_Q:
18800 			/*
18801 			 * Wants to be the default wq. Check the credentials
18802 			 * first, the rest is executed via squeue.
18803 			 */
18804 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18805 				iocp->ioc_error = EPERM;
18806 				iocp->ioc_count = 0;
18807 				mp->b_datap->db_type = M_IOCACK;
18808 				qreply(q, mp);
18809 				return;
18810 			}
18811 			output_proc = tcp_wput_ioctl;
18812 			break;
18813 		default:
18814 			output_proc = tcp_wput_ioctl;
18815 			break;
18816 		}
18817 		break;
18818 	default:
18819 		output_proc = tcp_wput_nondata;
18820 		break;
18821 	}
18822 
18823 	CONN_INC_REF(connp);
18824 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18825 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18826 }
18827 
18828 /*
18829  * Initial STREAMS write side put() procedure for sockets. It tries to
18830  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18831  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18832  * are handled by tcp_wput() as usual.
18833  *
18834  * All further messages will also be handled by tcp_wput() because we cannot
18835  * be sure that the above short cut is safe later.
18836  */
18837 static void
18838 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18839 {
18840 	conn_t			*connp = Q_TO_CONN(wq);
18841 	tcp_t			*tcp = connp->conn_tcp;
18842 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18843 
18844 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18845 	wq->q_qinfo = &tcp_winit;
18846 
18847 	ASSERT(IPCL_IS_TCP(connp));
18848 	ASSERT(TCP_IS_SOCKET(tcp));
18849 
18850 	if (DB_TYPE(mp) == M_PCPROTO &&
18851 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18852 	    car->PRIM_type == T_CAPABILITY_REQ) {
18853 		tcp_capability_req(tcp, mp);
18854 		return;
18855 	}
18856 
18857 	tcp_wput(wq, mp);
18858 }
18859 
18860 /* ARGSUSED */
18861 static void
18862 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18863 {
18864 #ifdef DEBUG
18865 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18866 #endif
18867 	freemsg(mp);
18868 }
18869 
18870 static boolean_t
18871 tcp_zcopy_check(tcp_t *tcp)
18872 {
18873 	conn_t	*connp = tcp->tcp_connp;
18874 	ire_t	*ire;
18875 	boolean_t	zc_enabled = B_FALSE;
18876 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18877 
18878 	if (do_tcpzcopy == 2)
18879 		zc_enabled = B_TRUE;
18880 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18881 	    IPCL_IS_CONNECTED(connp) &&
18882 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18883 	    connp->conn_dontroute == 0 &&
18884 	    !connp->conn_nexthop_set &&
18885 	    connp->conn_outgoing_ill == NULL &&
18886 	    do_tcpzcopy == 1) {
18887 		/*
18888 		 * the checks above  closely resemble the fast path checks
18889 		 * in tcp_send_data().
18890 		 */
18891 		mutex_enter(&connp->conn_lock);
18892 		ire = connp->conn_ire_cache;
18893 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18894 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18895 			IRE_REFHOLD(ire);
18896 			if (ire->ire_stq != NULL) {
18897 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18898 
18899 				zc_enabled = ill && (ill->ill_capabilities &
18900 				    ILL_CAPAB_ZEROCOPY) &&
18901 				    (ill->ill_zerocopy_capab->
18902 				    ill_zerocopy_flags != 0);
18903 			}
18904 			IRE_REFRELE(ire);
18905 		}
18906 		mutex_exit(&connp->conn_lock);
18907 	}
18908 	tcp->tcp_snd_zcopy_on = zc_enabled;
18909 	if (!TCP_IS_DETACHED(tcp)) {
18910 		if (zc_enabled) {
18911 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18912 			    ZCVMSAFE);
18913 			TCP_STAT(tcps, tcp_zcopy_on);
18914 		} else {
18915 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18916 			    ZCVMUNSAFE);
18917 			TCP_STAT(tcps, tcp_zcopy_off);
18918 		}
18919 	}
18920 	return (zc_enabled);
18921 }
18922 
18923 static mblk_t *
18924 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18925 {
18926 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18927 
18928 	if (do_tcpzcopy == 2)
18929 		return (bp);
18930 	else if (tcp->tcp_snd_zcopy_on) {
18931 		tcp->tcp_snd_zcopy_on = B_FALSE;
18932 		if (!TCP_IS_DETACHED(tcp)) {
18933 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
18934 			    ZCVMUNSAFE);
18935 			TCP_STAT(tcps, tcp_zcopy_disable);
18936 		}
18937 	}
18938 	return (tcp_zcopy_backoff(tcp, bp, 0));
18939 }
18940 
18941 /*
18942  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18943  * the original desballoca'ed segmapped mblk.
18944  */
18945 static mblk_t *
18946 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18947 {
18948 	mblk_t *head, *tail, *nbp;
18949 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18950 
18951 	if (IS_VMLOANED_MBLK(bp)) {
18952 		TCP_STAT(tcps, tcp_zcopy_backoff);
18953 		if ((head = copyb(bp)) == NULL) {
18954 			/* fail to backoff; leave it for the next backoff */
18955 			tcp->tcp_xmit_zc_clean = B_FALSE;
18956 			return (bp);
18957 		}
18958 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18959 			if (fix_xmitlist)
18960 				tcp_zcopy_notify(tcp);
18961 			else
18962 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18963 		}
18964 		nbp = bp->b_cont;
18965 		if (fix_xmitlist) {
18966 			head->b_prev = bp->b_prev;
18967 			head->b_next = bp->b_next;
18968 			if (tcp->tcp_xmit_tail == bp)
18969 				tcp->tcp_xmit_tail = head;
18970 		}
18971 		bp->b_next = NULL;
18972 		bp->b_prev = NULL;
18973 		freeb(bp);
18974 	} else {
18975 		head = bp;
18976 		nbp = bp->b_cont;
18977 	}
18978 	tail = head;
18979 	while (nbp) {
18980 		if (IS_VMLOANED_MBLK(nbp)) {
18981 			TCP_STAT(tcps, tcp_zcopy_backoff);
18982 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18983 				tcp->tcp_xmit_zc_clean = B_FALSE;
18984 				tail->b_cont = nbp;
18985 				return (head);
18986 			}
18987 			tail = tail->b_cont;
18988 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18989 				if (fix_xmitlist)
18990 					tcp_zcopy_notify(tcp);
18991 				else
18992 					tail->b_datap->db_struioflag |=
18993 					    STRUIO_ZCNOTIFY;
18994 			}
18995 			bp = nbp;
18996 			nbp = nbp->b_cont;
18997 			if (fix_xmitlist) {
18998 				tail->b_prev = bp->b_prev;
18999 				tail->b_next = bp->b_next;
19000 				if (tcp->tcp_xmit_tail == bp)
19001 					tcp->tcp_xmit_tail = tail;
19002 			}
19003 			bp->b_next = NULL;
19004 			bp->b_prev = NULL;
19005 			freeb(bp);
19006 		} else {
19007 			tail->b_cont = nbp;
19008 			tail = nbp;
19009 			nbp = nbp->b_cont;
19010 		}
19011 	}
19012 	if (fix_xmitlist) {
19013 		tcp->tcp_xmit_last = tail;
19014 		tcp->tcp_xmit_zc_clean = B_TRUE;
19015 	}
19016 	return (head);
19017 }
19018 
19019 static void
19020 tcp_zcopy_notify(tcp_t *tcp)
19021 {
19022 	struct stdata	*stp;
19023 	conn_t *connp;
19024 
19025 	if (tcp->tcp_detached)
19026 		return;
19027 	connp = tcp->tcp_connp;
19028 	if (IPCL_IS_NONSTR(connp)) {
19029 		(*connp->conn_upcalls->su_zcopy_notify)
19030 		    (connp->conn_upper_handle);
19031 		return;
19032 	}
19033 	stp = STREAM(tcp->tcp_rq);
19034 	mutex_enter(&stp->sd_lock);
19035 	stp->sd_flag |= STZCNOTIFY;
19036 	cv_broadcast(&stp->sd_zcopy_wait);
19037 	mutex_exit(&stp->sd_lock);
19038 }
19039 
19040 static boolean_t
19041 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
19042 {
19043 	ire_t	*ire;
19044 	conn_t	*connp = tcp->tcp_connp;
19045 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19046 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19047 
19048 	mutex_enter(&connp->conn_lock);
19049 	ire = connp->conn_ire_cache;
19050 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19051 
19052 	if ((ire != NULL) &&
19053 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
19054 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
19055 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19056 		IRE_REFHOLD(ire);
19057 		mutex_exit(&connp->conn_lock);
19058 	} else {
19059 		boolean_t cached = B_FALSE;
19060 		ts_label_t *tsl;
19061 
19062 		/* force a recheck later on */
19063 		tcp->tcp_ire_ill_check_done = B_FALSE;
19064 
19065 		TCP_DBGSTAT(tcps, tcp_ire_null1);
19066 		connp->conn_ire_cache = NULL;
19067 		mutex_exit(&connp->conn_lock);
19068 
19069 		if (ire != NULL)
19070 			IRE_REFRELE_NOTR(ire);
19071 
19072 		tsl = crgetlabel(CONN_CRED(connp));
19073 		ire = (dst ?
19074 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
19075 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19076 		    connp->conn_zoneid, tsl, ipst));
19077 
19078 		if (ire == NULL) {
19079 			TCP_STAT(tcps, tcp_ire_null);
19080 			return (B_FALSE);
19081 		}
19082 
19083 		IRE_REFHOLD_NOTR(ire);
19084 
19085 		mutex_enter(&connp->conn_lock);
19086 		if (CONN_CACHE_IRE(connp)) {
19087 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19088 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19089 				TCP_CHECK_IREINFO(tcp, ire);
19090 				connp->conn_ire_cache = ire;
19091 				cached = B_TRUE;
19092 			}
19093 			rw_exit(&ire->ire_bucket->irb_lock);
19094 		}
19095 		mutex_exit(&connp->conn_lock);
19096 
19097 		/*
19098 		 * We can continue to use the ire but since it was
19099 		 * not cached, we should drop the extra reference.
19100 		 */
19101 		if (!cached)
19102 			IRE_REFRELE_NOTR(ire);
19103 
19104 		/*
19105 		 * Rampart note: no need to select a new label here, since
19106 		 * labels are not allowed to change during the life of a TCP
19107 		 * connection.
19108 		 */
19109 	}
19110 
19111 	*irep = ire;
19112 
19113 	return (B_TRUE);
19114 }
19115 
19116 /*
19117  * Called from tcp_send() or tcp_send_data() to find workable IRE.
19118  *
19119  * 0 = success;
19120  * 1 = failed to find ire and ill.
19121  */
19122 static boolean_t
19123 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
19124 {
19125 	ipha_t		*ipha;
19126 	ipaddr_t	dst;
19127 	ire_t		*ire;
19128 	ill_t		*ill;
19129 	mblk_t		*ire_fp_mp;
19130 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19131 
19132 	if (mp != NULL)
19133 		ipha = (ipha_t *)mp->b_rptr;
19134 	else
19135 		ipha = tcp->tcp_ipha;
19136 	dst = ipha->ipha_dst;
19137 
19138 	if (!tcp_send_find_ire(tcp, &dst, &ire))
19139 		return (B_FALSE);
19140 
19141 	if ((ire->ire_flags & RTF_MULTIRT) ||
19142 	    (ire->ire_stq == NULL) ||
19143 	    (ire->ire_nce == NULL) ||
19144 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
19145 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
19146 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
19147 		TCP_STAT(tcps, tcp_ip_ire_send);
19148 		IRE_REFRELE(ire);
19149 		return (B_FALSE);
19150 	}
19151 
19152 	ill = ire_to_ill(ire);
19153 	ASSERT(ill != NULL);
19154 
19155 	if (!tcp->tcp_ire_ill_check_done) {
19156 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19157 		tcp->tcp_ire_ill_check_done = B_TRUE;
19158 	}
19159 
19160 	*irep = ire;
19161 	*illp = ill;
19162 
19163 	return (B_TRUE);
19164 }
19165 
19166 static void
19167 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
19168 {
19169 	ipha_t		*ipha;
19170 	ipaddr_t	src;
19171 	ipaddr_t	dst;
19172 	uint32_t	cksum;
19173 	ire_t		*ire;
19174 	uint16_t	*up;
19175 	ill_t		*ill;
19176 	conn_t		*connp = tcp->tcp_connp;
19177 	uint32_t	hcksum_txflags = 0;
19178 	mblk_t		*ire_fp_mp;
19179 	uint_t		ire_fp_mp_len;
19180 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19181 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19182 
19183 	ASSERT(DB_TYPE(mp) == M_DATA);
19184 
19185 	if (is_system_labeled() && DB_CRED(mp) == NULL)
19186 		mblk_setcred(mp, CONN_CRED(tcp->tcp_connp));
19187 
19188 	ipha = (ipha_t *)mp->b_rptr;
19189 	src = ipha->ipha_src;
19190 	dst = ipha->ipha_dst;
19191 
19192 	ASSERT(q != NULL);
19193 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
19194 
19195 	/*
19196 	 * Drop off fast path for IPv6 and also if options are present or
19197 	 * we need to resolve a TS label.
19198 	 */
19199 	if (tcp->tcp_ipversion != IPV4_VERSION ||
19200 	    !IPCL_IS_CONNECTED(connp) ||
19201 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
19202 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
19203 	    !connp->conn_ulp_labeled ||
19204 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
19205 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
19206 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
19207 		if (tcp->tcp_snd_zcopy_aware)
19208 			mp = tcp_zcopy_disable(tcp, mp);
19209 		TCP_STAT(tcps, tcp_ip_send);
19210 		CALL_IP_WPUT(connp, q, mp);
19211 		return;
19212 	}
19213 
19214 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
19215 		if (tcp->tcp_snd_zcopy_aware)
19216 			mp = tcp_zcopy_backoff(tcp, mp, 0);
19217 		CALL_IP_WPUT(connp, q, mp);
19218 		return;
19219 	}
19220 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
19221 	ire_fp_mp_len = MBLKL(ire_fp_mp);
19222 
19223 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19224 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19225 #ifndef _BIG_ENDIAN
19226 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19227 #endif
19228 
19229 	/*
19230 	 * Check to see if we need to re-enable LSO/MDT for this connection
19231 	 * because it was previously disabled due to changes in the ill;
19232 	 * note that by doing it here, this re-enabling only applies when
19233 	 * the packet is not dispatched through CALL_IP_WPUT().
19234 	 *
19235 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
19236 	 * case, since that's how we ended up here.  For IPv6, we do the
19237 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
19238 	 */
19239 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
19240 		/*
19241 		 * Restore LSO for this connection, so that next time around
19242 		 * it is eligible to go through tcp_lsosend() path again.
19243 		 */
19244 		TCP_STAT(tcps, tcp_lso_enabled);
19245 		tcp->tcp_lso = B_TRUE;
19246 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
19247 		    "interface %s\n", (void *)connp, ill->ill_name));
19248 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
19249 		/*
19250 		 * Restore MDT for this connection, so that next time around
19251 		 * it is eligible to go through tcp_multisend() path again.
19252 		 */
19253 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
19254 		tcp->tcp_mdt = B_TRUE;
19255 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
19256 		    "interface %s\n", (void *)connp, ill->ill_name));
19257 	}
19258 
19259 	if (tcp->tcp_snd_zcopy_aware) {
19260 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
19261 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
19262 			mp = tcp_zcopy_disable(tcp, mp);
19263 		/*
19264 		 * we shouldn't need to reset ipha as the mp containing
19265 		 * ipha should never be a zero-copy mp.
19266 		 */
19267 	}
19268 
19269 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
19270 		ASSERT(ill->ill_hcksum_capab != NULL);
19271 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
19272 	}
19273 
19274 	/* pseudo-header checksum (do it in parts for IP header checksum) */
19275 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19276 
19277 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
19278 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
19279 
19280 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
19281 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
19282 
19283 	/* Software checksum? */
19284 	if (DB_CKSUMFLAGS(mp) == 0) {
19285 		TCP_STAT(tcps, tcp_out_sw_cksum);
19286 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
19287 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
19288 	}
19289 
19290 	/* Calculate IP header checksum if hardware isn't capable */
19291 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
19292 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
19293 		    ((uint16_t *)ipha)[4]);
19294 	}
19295 
19296 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
19297 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
19298 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
19299 
19300 	UPDATE_OB_PKT_COUNT(ire);
19301 	ire->ire_last_used_time = lbolt;
19302 
19303 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
19304 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
19305 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
19306 	    ntohs(ipha->ipha_length));
19307 
19308 	DTRACE_PROBE4(ip4__physical__out__start,
19309 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
19310 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
19311 	    ipst->ips_ipv4firewall_physical_out,
19312 	    NULL, ill, ipha, mp, mp, 0, ipst);
19313 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19314 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
19315 
19316 	if (mp != NULL) {
19317 		if (ipst->ips_ipobs_enabled) {
19318 			zoneid_t szone;
19319 
19320 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
19321 			    ipst, ALL_ZONES);
19322 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
19323 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
19324 		}
19325 
19326 		ILL_SEND_TX(ill, ire, connp, mp, 0);
19327 	}
19328 
19329 	IRE_REFRELE(ire);
19330 }
19331 
19332 /*
19333  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19334  * if the receiver shrinks the window, i.e. moves the right window to the
19335  * left, the we should not send new data, but should retransmit normally the
19336  * old unacked data between suna and suna + swnd. We might has sent data
19337  * that is now outside the new window, pretend that we didn't send  it.
19338  */
19339 static void
19340 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19341 {
19342 	uint32_t	snxt = tcp->tcp_snxt;
19343 	mblk_t		*xmit_tail;
19344 	int32_t		offset;
19345 
19346 	ASSERT(shrunk_count > 0);
19347 
19348 	/* Pretend we didn't send the data outside the window */
19349 	snxt -= shrunk_count;
19350 
19351 	/* Get the mblk and the offset in it per the shrunk window */
19352 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19353 
19354 	ASSERT(xmit_tail != NULL);
19355 
19356 	/* Reset all the values per the now shrunk window */
19357 	tcp->tcp_snxt = snxt;
19358 	tcp->tcp_xmit_tail = xmit_tail;
19359 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19360 	    offset;
19361 	tcp->tcp_unsent += shrunk_count;
19362 
19363 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19364 		/*
19365 		 * Make sure the timer is running so that we will probe a zero
19366 		 * window.
19367 		 */
19368 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19369 }
19370 
19371 
19372 /*
19373  * The TCP normal data output path.
19374  * NOTE: the logic of the fast path is duplicated from this function.
19375  */
19376 static void
19377 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19378 {
19379 	int		len;
19380 	mblk_t		*local_time;
19381 	mblk_t		*mp1;
19382 	uint32_t	snxt;
19383 	int		tail_unsent;
19384 	int		tcpstate;
19385 	int		usable = 0;
19386 	mblk_t		*xmit_tail;
19387 	queue_t		*q = tcp->tcp_wq;
19388 	int32_t		mss;
19389 	int32_t		num_sack_blk = 0;
19390 	int32_t		tcp_hdr_len;
19391 	int32_t		tcp_tcp_hdr_len;
19392 	int		mdt_thres;
19393 	int		rc;
19394 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19395 	ip_stack_t	*ipst;
19396 
19397 	tcpstate = tcp->tcp_state;
19398 	if (mp == NULL) {
19399 		/*
19400 		 * tcp_wput_data() with NULL mp should only be called when
19401 		 * there is unsent data.
19402 		 */
19403 		ASSERT(tcp->tcp_unsent > 0);
19404 		/* Really tacky... but we need this for detached closes. */
19405 		len = tcp->tcp_unsent;
19406 		goto data_null;
19407 	}
19408 
19409 #if CCS_STATS
19410 	wrw_stats.tot.count++;
19411 	wrw_stats.tot.bytes += msgdsize(mp);
19412 #endif
19413 	ASSERT(mp->b_datap->db_type == M_DATA);
19414 	/*
19415 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19416 	 * or before a connection attempt has begun.
19417 	 */
19418 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19419 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19420 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19421 #ifdef DEBUG
19422 			cmn_err(CE_WARN,
19423 			    "tcp_wput_data: data after ordrel, %s",
19424 			    tcp_display(tcp, NULL,
19425 			    DISP_ADDR_AND_PORT));
19426 #else
19427 			if (tcp->tcp_debug) {
19428 				(void) strlog(TCP_MOD_ID, 0, 1,
19429 				    SL_TRACE|SL_ERROR,
19430 				    "tcp_wput_data: data after ordrel, %s\n",
19431 				    tcp_display(tcp, NULL,
19432 				    DISP_ADDR_AND_PORT));
19433 			}
19434 #endif /* DEBUG */
19435 		}
19436 		if (tcp->tcp_snd_zcopy_aware &&
19437 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19438 			tcp_zcopy_notify(tcp);
19439 		freemsg(mp);
19440 		mutex_enter(&tcp->tcp_non_sq_lock);
19441 		if (tcp->tcp_flow_stopped &&
19442 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19443 			tcp_clrqfull(tcp);
19444 		}
19445 		mutex_exit(&tcp->tcp_non_sq_lock);
19446 		return;
19447 	}
19448 
19449 	/* Strip empties */
19450 	for (;;) {
19451 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19452 		    (uintptr_t)INT_MAX);
19453 		len = (int)(mp->b_wptr - mp->b_rptr);
19454 		if (len > 0)
19455 			break;
19456 		mp1 = mp;
19457 		mp = mp->b_cont;
19458 		freeb(mp1);
19459 		if (!mp) {
19460 			return;
19461 		}
19462 	}
19463 
19464 	/* If we are the first on the list ... */
19465 	if (tcp->tcp_xmit_head == NULL) {
19466 		tcp->tcp_xmit_head = mp;
19467 		tcp->tcp_xmit_tail = mp;
19468 		tcp->tcp_xmit_tail_unsent = len;
19469 	} else {
19470 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19471 		struct datab *dp;
19472 
19473 		mp1 = tcp->tcp_xmit_last;
19474 		if (len < tcp_tx_pull_len &&
19475 		    (dp = mp1->b_datap)->db_ref == 1 &&
19476 		    dp->db_lim - mp1->b_wptr >= len) {
19477 			ASSERT(len > 0);
19478 			ASSERT(!mp1->b_cont);
19479 			if (len == 1) {
19480 				*mp1->b_wptr++ = *mp->b_rptr;
19481 			} else {
19482 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19483 				mp1->b_wptr += len;
19484 			}
19485 			if (mp1 == tcp->tcp_xmit_tail)
19486 				tcp->tcp_xmit_tail_unsent += len;
19487 			mp1->b_cont = mp->b_cont;
19488 			if (tcp->tcp_snd_zcopy_aware &&
19489 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19490 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19491 			freeb(mp);
19492 			mp = mp1;
19493 		} else {
19494 			tcp->tcp_xmit_last->b_cont = mp;
19495 		}
19496 		len += tcp->tcp_unsent;
19497 	}
19498 
19499 	/* Tack on however many more positive length mblks we have */
19500 	if ((mp1 = mp->b_cont) != NULL) {
19501 		do {
19502 			int tlen;
19503 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19504 			    (uintptr_t)INT_MAX);
19505 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19506 			if (tlen <= 0) {
19507 				mp->b_cont = mp1->b_cont;
19508 				freeb(mp1);
19509 			} else {
19510 				len += tlen;
19511 				mp = mp1;
19512 			}
19513 		} while ((mp1 = mp->b_cont) != NULL);
19514 	}
19515 	tcp->tcp_xmit_last = mp;
19516 	tcp->tcp_unsent = len;
19517 
19518 	if (urgent)
19519 		usable = 1;
19520 
19521 data_null:
19522 	snxt = tcp->tcp_snxt;
19523 	xmit_tail = tcp->tcp_xmit_tail;
19524 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19525 
19526 	/*
19527 	 * Note that tcp_mss has been adjusted to take into account the
19528 	 * timestamp option if applicable.  Because SACK options do not
19529 	 * appear in every TCP segments and they are of variable lengths,
19530 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19531 	 * the actual segment length when we need to send a segment which
19532 	 * includes SACK options.
19533 	 */
19534 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19535 		int32_t	opt_len;
19536 
19537 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19538 		    tcp->tcp_num_sack_blk);
19539 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19540 		    2 + TCPOPT_HEADER_LEN;
19541 		mss = tcp->tcp_mss - opt_len;
19542 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19543 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19544 	} else {
19545 		mss = tcp->tcp_mss;
19546 		tcp_hdr_len = tcp->tcp_hdr_len;
19547 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19548 	}
19549 
19550 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19551 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19552 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19553 	}
19554 	if (tcpstate == TCPS_SYN_RCVD) {
19555 		/*
19556 		 * The three-way connection establishment handshake is not
19557 		 * complete yet. We want to queue the data for transmission
19558 		 * after entering ESTABLISHED state (RFC793). A jump to
19559 		 * "done" label effectively leaves data on the queue.
19560 		 */
19561 		goto done;
19562 	} else {
19563 		int usable_r;
19564 
19565 		/*
19566 		 * In the special case when cwnd is zero, which can only
19567 		 * happen if the connection is ECN capable, return now.
19568 		 * New segments is sent using tcp_timer().  The timer
19569 		 * is set in tcp_rput_data().
19570 		 */
19571 		if (tcp->tcp_cwnd == 0) {
19572 			/*
19573 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19574 			 * finished.
19575 			 */
19576 			ASSERT(tcp->tcp_ecn_ok ||
19577 			    tcp->tcp_state < TCPS_ESTABLISHED);
19578 			return;
19579 		}
19580 
19581 		/* NOTE: trouble if xmitting while SYN not acked? */
19582 		usable_r = snxt - tcp->tcp_suna;
19583 		usable_r = tcp->tcp_swnd - usable_r;
19584 
19585 		/*
19586 		 * Check if the receiver has shrunk the window.  If
19587 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19588 		 * cannot be set as there is unsent data, so FIN cannot
19589 		 * be sent out.  Otherwise, we need to take into account
19590 		 * of FIN as it consumes an "invisible" sequence number.
19591 		 */
19592 		ASSERT(tcp->tcp_fin_sent == 0);
19593 		if (usable_r < 0) {
19594 			/*
19595 			 * The receiver has shrunk the window and we have sent
19596 			 * -usable_r date beyond the window, re-adjust.
19597 			 *
19598 			 * If TCP window scaling is enabled, there can be
19599 			 * round down error as the advertised receive window
19600 			 * is actually right shifted n bits.  This means that
19601 			 * the lower n bits info is wiped out.  It will look
19602 			 * like the window is shrunk.  Do a check here to
19603 			 * see if the shrunk amount is actually within the
19604 			 * error in window calculation.  If it is, just
19605 			 * return.  Note that this check is inside the
19606 			 * shrunk window check.  This makes sure that even
19607 			 * though tcp_process_shrunk_swnd() is not called,
19608 			 * we will stop further processing.
19609 			 */
19610 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19611 				tcp_process_shrunk_swnd(tcp, -usable_r);
19612 			}
19613 			return;
19614 		}
19615 
19616 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19617 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19618 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19619 
19620 		/* usable = MIN(usable, unsent) */
19621 		if (usable_r > len)
19622 			usable_r = len;
19623 
19624 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19625 		if (usable_r > 0) {
19626 			usable = usable_r;
19627 		} else {
19628 			/* Bypass all other unnecessary processing. */
19629 			goto done;
19630 		}
19631 	}
19632 
19633 	local_time = (mblk_t *)lbolt;
19634 
19635 	/*
19636 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19637 	 * BSD.  This is more in line with the true intent of Nagle.
19638 	 *
19639 	 * The conditions are:
19640 	 * 1. The amount of unsent data (or amount of data which can be
19641 	 *    sent, whichever is smaller) is less than Nagle limit.
19642 	 * 2. The last sent size is also less than Nagle limit.
19643 	 * 3. There is unack'ed data.
19644 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19645 	 *    Nagle algorithm.  This reduces the probability that urgent
19646 	 *    bytes get "merged" together.
19647 	 * 5. The app has not closed the connection.  This eliminates the
19648 	 *    wait time of the receiving side waiting for the last piece of
19649 	 *    (small) data.
19650 	 *
19651 	 * If all are satisified, exit without sending anything.  Note
19652 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19653 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19654 	 * 4095).
19655 	 */
19656 	if (usable < (int)tcp->tcp_naglim &&
19657 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19658 	    snxt != tcp->tcp_suna &&
19659 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19660 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19661 		goto done;
19662 	}
19663 
19664 	if (tcp->tcp_cork) {
19665 		/*
19666 		 * if the tcp->tcp_cork option is set, then we have to force
19667 		 * TCP not to send partial segment (smaller than MSS bytes).
19668 		 * We are calculating the usable now based on full mss and
19669 		 * will save the rest of remaining data for later.
19670 		 */
19671 		if (usable < mss)
19672 			goto done;
19673 		usable = (usable / mss) * mss;
19674 	}
19675 
19676 	/* Update the latest receive window size in TCP header. */
19677 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19678 	    tcp->tcp_tcph->th_win);
19679 
19680 	/*
19681 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19682 	 *
19683 	 * 1. Simple TCP/IP{v4,v6} (no options).
19684 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19685 	 * 3. If the TCP connection is in ESTABLISHED state.
19686 	 * 4. The TCP is not detached.
19687 	 *
19688 	 * If any of the above conditions have changed during the
19689 	 * connection, stop using LSO/MDT and restore the stream head
19690 	 * parameters accordingly.
19691 	 */
19692 	ipst = tcps->tcps_netstack->netstack_ip;
19693 
19694 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19695 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19696 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19697 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19698 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19699 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19700 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19701 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19702 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19703 		if (tcp->tcp_lso) {
19704 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19705 			tcp->tcp_lso = B_FALSE;
19706 		} else {
19707 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19708 			tcp->tcp_mdt = B_FALSE;
19709 		}
19710 
19711 		/* Anything other than detached is considered pathological */
19712 		if (!TCP_IS_DETACHED(tcp)) {
19713 			if (tcp->tcp_lso)
19714 				TCP_STAT(tcps, tcp_lso_disabled);
19715 			else
19716 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19717 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19718 		}
19719 	}
19720 
19721 	/* Use MDT if sendable amount is greater than the threshold */
19722 	if (tcp->tcp_mdt &&
19723 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19724 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19725 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19726 	    (tcp->tcp_valid_bits == 0 ||
19727 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19728 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19729 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19730 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19731 		    local_time, mdt_thres);
19732 	} else {
19733 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19734 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19735 		    local_time, INT_MAX);
19736 	}
19737 
19738 	/* Pretend that all we were trying to send really got sent */
19739 	if (rc < 0 && tail_unsent < 0) {
19740 		do {
19741 			xmit_tail = xmit_tail->b_cont;
19742 			xmit_tail->b_prev = local_time;
19743 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19744 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19745 			tail_unsent += (int)(xmit_tail->b_wptr -
19746 			    xmit_tail->b_rptr);
19747 		} while (tail_unsent < 0);
19748 	}
19749 done:;
19750 	tcp->tcp_xmit_tail = xmit_tail;
19751 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19752 	len = tcp->tcp_snxt - snxt;
19753 	if (len) {
19754 		/*
19755 		 * If new data was sent, need to update the notsack
19756 		 * list, which is, afterall, data blocks that have
19757 		 * not been sack'ed by the receiver.  New data is
19758 		 * not sack'ed.
19759 		 */
19760 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19761 			/* len is a negative value. */
19762 			tcp->tcp_pipe -= len;
19763 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19764 			    tcp->tcp_snxt, snxt,
19765 			    &(tcp->tcp_num_notsack_blk),
19766 			    &(tcp->tcp_cnt_notsack_list));
19767 		}
19768 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19769 		tcp->tcp_rack = tcp->tcp_rnxt;
19770 		tcp->tcp_rack_cnt = 0;
19771 		if ((snxt + len) == tcp->tcp_suna) {
19772 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19773 		}
19774 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19775 		/*
19776 		 * Didn't send anything. Make sure the timer is running
19777 		 * so that we will probe a zero window.
19778 		 */
19779 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19780 	}
19781 	/* Note that len is the amount we just sent but with a negative sign */
19782 	tcp->tcp_unsent += len;
19783 	mutex_enter(&tcp->tcp_non_sq_lock);
19784 	if (tcp->tcp_flow_stopped) {
19785 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19786 			tcp_clrqfull(tcp);
19787 		}
19788 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19789 		tcp_setqfull(tcp);
19790 	}
19791 	mutex_exit(&tcp->tcp_non_sq_lock);
19792 }
19793 
19794 /*
19795  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19796  * outgoing TCP header with the template header, as well as other
19797  * options such as time-stamp, ECN and/or SACK.
19798  */
19799 static void
19800 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19801 {
19802 	tcph_t *tcp_tmpl, *tcp_h;
19803 	uint32_t *dst, *src;
19804 	int hdrlen;
19805 
19806 	ASSERT(OK_32PTR(rptr));
19807 
19808 	/* Template header */
19809 	tcp_tmpl = tcp->tcp_tcph;
19810 
19811 	/* Header of outgoing packet */
19812 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19813 
19814 	/* dst and src are opaque 32-bit fields, used for copying */
19815 	dst = (uint32_t *)rptr;
19816 	src = (uint32_t *)tcp->tcp_iphc;
19817 	hdrlen = tcp->tcp_hdr_len;
19818 
19819 	/* Fill time-stamp option if needed */
19820 	if (tcp->tcp_snd_ts_ok) {
19821 		U32_TO_BE32((uint32_t)now,
19822 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19823 		U32_TO_BE32(tcp->tcp_ts_recent,
19824 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19825 	} else {
19826 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19827 	}
19828 
19829 	/*
19830 	 * Copy the template header; is this really more efficient than
19831 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19832 	 * but perhaps not for other scenarios.
19833 	 */
19834 	dst[0] = src[0];
19835 	dst[1] = src[1];
19836 	dst[2] = src[2];
19837 	dst[3] = src[3];
19838 	dst[4] = src[4];
19839 	dst[5] = src[5];
19840 	dst[6] = src[6];
19841 	dst[7] = src[7];
19842 	dst[8] = src[8];
19843 	dst[9] = src[9];
19844 	if (hdrlen -= 40) {
19845 		hdrlen >>= 2;
19846 		dst += 10;
19847 		src += 10;
19848 		do {
19849 			*dst++ = *src++;
19850 		} while (--hdrlen);
19851 	}
19852 
19853 	/*
19854 	 * Set the ECN info in the TCP header if it is not a zero
19855 	 * window probe.  Zero window probe is only sent in
19856 	 * tcp_wput_data() and tcp_timer().
19857 	 */
19858 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19859 		SET_ECT(tcp, rptr);
19860 
19861 		if (tcp->tcp_ecn_echo_on)
19862 			tcp_h->th_flags[0] |= TH_ECE;
19863 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19864 			tcp_h->th_flags[0] |= TH_CWR;
19865 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19866 		}
19867 	}
19868 
19869 	/* Fill in SACK options */
19870 	if (num_sack_blk > 0) {
19871 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19872 		sack_blk_t *tmp;
19873 		int32_t	i;
19874 
19875 		wptr[0] = TCPOPT_NOP;
19876 		wptr[1] = TCPOPT_NOP;
19877 		wptr[2] = TCPOPT_SACK;
19878 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19879 		    sizeof (sack_blk_t);
19880 		wptr += TCPOPT_REAL_SACK_LEN;
19881 
19882 		tmp = tcp->tcp_sack_list;
19883 		for (i = 0; i < num_sack_blk; i++) {
19884 			U32_TO_BE32(tmp[i].begin, wptr);
19885 			wptr += sizeof (tcp_seq);
19886 			U32_TO_BE32(tmp[i].end, wptr);
19887 			wptr += sizeof (tcp_seq);
19888 		}
19889 		tcp_h->th_offset_and_rsrvd[0] +=
19890 		    ((num_sack_blk * 2 + 1) << 4);
19891 	}
19892 }
19893 
19894 /*
19895  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19896  * the destination address and SAP attribute, and if necessary, the
19897  * hardware checksum offload attribute to a Multidata message.
19898  */
19899 static int
19900 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19901     const uint32_t start, const uint32_t stuff, const uint32_t end,
19902     const uint32_t flags, tcp_stack_t *tcps)
19903 {
19904 	/* Add global destination address & SAP attribute */
19905 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19906 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19907 		    "destination address+SAP\n"));
19908 
19909 		if (dlmp != NULL)
19910 			TCP_STAT(tcps, tcp_mdt_allocfail);
19911 		return (-1);
19912 	}
19913 
19914 	/* Add global hwcksum attribute */
19915 	if (hwcksum &&
19916 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19917 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19918 		    "checksum attribute\n"));
19919 
19920 		TCP_STAT(tcps, tcp_mdt_allocfail);
19921 		return (-1);
19922 	}
19923 
19924 	return (0);
19925 }
19926 
19927 /*
19928  * Smaller and private version of pdescinfo_t used specifically for TCP,
19929  * which allows for only two payload spans per packet.
19930  */
19931 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19932 
19933 /*
19934  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19935  * scheme, and returns one the following:
19936  *
19937  * -1 = failed allocation.
19938  *  0 = success; burst count reached, or usable send window is too small,
19939  *      and that we'd rather wait until later before sending again.
19940  */
19941 static int
19942 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19943     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19944     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19945     const int mdt_thres)
19946 {
19947 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19948 	multidata_t	*mmd;
19949 	uint_t		obsegs, obbytes, hdr_frag_sz;
19950 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19951 	int		num_burst_seg, max_pld;
19952 	pdesc_t		*pkt;
19953 	tcp_pdescinfo_t	tcp_pkt_info;
19954 	pdescinfo_t	*pkt_info;
19955 	int		pbuf_idx, pbuf_idx_nxt;
19956 	int		seg_len, len, spill, af;
19957 	boolean_t	add_buffer, zcopy, clusterwide;
19958 	boolean_t	rconfirm = B_FALSE;
19959 	boolean_t	done = B_FALSE;
19960 	uint32_t	cksum;
19961 	uint32_t	hwcksum_flags;
19962 	ire_t		*ire = NULL;
19963 	ill_t		*ill;
19964 	ipha_t		*ipha;
19965 	ip6_t		*ip6h;
19966 	ipaddr_t	src, dst;
19967 	ill_zerocopy_capab_t *zc_cap = NULL;
19968 	uint16_t	*up;
19969 	int		err;
19970 	conn_t		*connp;
19971 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19972 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19973 	int		usable_mmd, tail_unsent_mmd;
19974 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
19975 	mblk_t		*xmit_tail_mmd;
19976 	netstackid_t	stack_id;
19977 
19978 #ifdef	_BIG_ENDIAN
19979 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19980 #else
19981 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19982 #endif
19983 
19984 #define	PREP_NEW_MULTIDATA() {			\
19985 	mmd = NULL;				\
19986 	md_mp = md_hbuf = NULL;			\
19987 	cur_hdr_off = 0;			\
19988 	max_pld = tcp->tcp_mdt_max_pld;		\
19989 	pbuf_idx = pbuf_idx_nxt = -1;		\
19990 	add_buffer = B_TRUE;			\
19991 	zcopy = B_FALSE;			\
19992 }
19993 
19994 #define	PREP_NEW_PBUF() {			\
19995 	md_pbuf = md_pbuf_nxt = NULL;		\
19996 	pbuf_idx = pbuf_idx_nxt = -1;		\
19997 	cur_pld_off = 0;			\
19998 	first_snxt = *snxt;			\
19999 	ASSERT(*tail_unsent > 0);		\
20000 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
20001 }
20002 
20003 	ASSERT(mdt_thres >= mss);
20004 	ASSERT(*usable > 0 && *usable > mdt_thres);
20005 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20006 	ASSERT(!TCP_IS_DETACHED(tcp));
20007 	ASSERT(tcp->tcp_valid_bits == 0 ||
20008 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
20009 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
20010 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
20011 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20012 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
20013 
20014 	connp = tcp->tcp_connp;
20015 	ASSERT(connp != NULL);
20016 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
20017 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
20018 
20019 	stack_id = connp->conn_netstack->netstack_stackid;
20020 
20021 	usable_mmd = tail_unsent_mmd = 0;
20022 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
20023 	xmit_tail_mmd = NULL;
20024 	/*
20025 	 * Note that tcp will only declare at most 2 payload spans per
20026 	 * packet, which is much lower than the maximum allowable number
20027 	 * of packet spans per Multidata.  For this reason, we use the
20028 	 * privately declared and smaller descriptor info structure, in
20029 	 * order to save some stack space.
20030 	 */
20031 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
20032 
20033 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
20034 	if (af == AF_INET) {
20035 		dst = tcp->tcp_ipha->ipha_dst;
20036 		src = tcp->tcp_ipha->ipha_src;
20037 		ASSERT(!CLASSD(dst));
20038 	}
20039 	ASSERT(af == AF_INET ||
20040 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
20041 
20042 	obsegs = obbytes = 0;
20043 	num_burst_seg = tcp->tcp_snd_burst;
20044 	md_mp_head = NULL;
20045 	PREP_NEW_MULTIDATA();
20046 
20047 	/*
20048 	 * Before we go on further, make sure there is an IRE that we can
20049 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
20050 	 * in proceeding any further, and we should just hand everything
20051 	 * off to the legacy path.
20052 	 */
20053 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
20054 		goto legacy_send_no_md;
20055 
20056 	ASSERT(ire != NULL);
20057 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
20058 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
20059 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
20060 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
20061 	/*
20062 	 * If we do support loopback for MDT (which requires modifications
20063 	 * to the receiving paths), the following assertions should go away,
20064 	 * and we would be sending the Multidata to loopback conn later on.
20065 	 */
20066 	ASSERT(!IRE_IS_LOCAL(ire));
20067 	ASSERT(ire->ire_stq != NULL);
20068 
20069 	ill = ire_to_ill(ire);
20070 	ASSERT(ill != NULL);
20071 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
20072 
20073 	if (!tcp->tcp_ire_ill_check_done) {
20074 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
20075 		tcp->tcp_ire_ill_check_done = B_TRUE;
20076 	}
20077 
20078 	/*
20079 	 * If the underlying interface conditions have changed, or if the
20080 	 * new interface does not support MDT, go back to legacy path.
20081 	 */
20082 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
20083 		/* don't go through this path anymore for this connection */
20084 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
20085 		tcp->tcp_mdt = B_FALSE;
20086 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
20087 		    "interface %s\n", (void *)connp, ill->ill_name));
20088 		/* IRE will be released prior to returning */
20089 		goto legacy_send_no_md;
20090 	}
20091 
20092 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
20093 		zc_cap = ill->ill_zerocopy_capab;
20094 
20095 	/*
20096 	 * Check if we can take tcp fast-path. Note that "incomplete"
20097 	 * ire's (where the link-layer for next hop is not resolved
20098 	 * or where the fast-path header in nce_fp_mp is not available
20099 	 * yet) are sent down the legacy (slow) path.
20100 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
20101 	 */
20102 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
20103 		/* IRE will be released prior to returning */
20104 		goto legacy_send_no_md;
20105 	}
20106 
20107 	/* go to legacy path if interface doesn't support zerocopy */
20108 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
20109 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
20110 		/* IRE will be released prior to returning */
20111 		goto legacy_send_no_md;
20112 	}
20113 
20114 	/* does the interface support hardware checksum offload? */
20115 	hwcksum_flags = 0;
20116 	if (ILL_HCKSUM_CAPABLE(ill) &&
20117 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
20118 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
20119 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
20120 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20121 		    HCKSUM_IPHDRCKSUM)
20122 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
20123 
20124 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20125 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
20126 			hwcksum_flags |= HCK_FULLCKSUM;
20127 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20128 		    HCKSUM_INET_PARTIAL)
20129 			hwcksum_flags |= HCK_PARTIALCKSUM;
20130 	}
20131 
20132 	/*
20133 	 * Each header fragment consists of the leading extra space,
20134 	 * followed by the TCP/IP header, and the trailing extra space.
20135 	 * We make sure that each header fragment begins on a 32-bit
20136 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
20137 	 * aligned in tcp_mdt_update).
20138 	 */
20139 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
20140 	    tcp->tcp_mdt_hdr_tail), 4);
20141 
20142 	/* are we starting from the beginning of data block? */
20143 	if (*tail_unsent == 0) {
20144 		*xmit_tail = (*xmit_tail)->b_cont;
20145 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
20146 		*tail_unsent = (int)MBLKL(*xmit_tail);
20147 	}
20148 
20149 	/*
20150 	 * Here we create one or more Multidata messages, each made up of
20151 	 * one header buffer and up to N payload buffers.  This entire
20152 	 * operation is done within two loops:
20153 	 *
20154 	 * The outer loop mostly deals with creating the Multidata message,
20155 	 * as well as the header buffer that gets added to it.  It also
20156 	 * links the Multidata messages together such that all of them can
20157 	 * be sent down to the lower layer in a single putnext call; this
20158 	 * linking behavior depends on the tcp_mdt_chain tunable.
20159 	 *
20160 	 * The inner loop takes an existing Multidata message, and adds
20161 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
20162 	 * packetizes those buffers by filling up the corresponding header
20163 	 * buffer fragments with the proper IP and TCP headers, and by
20164 	 * describing the layout of each packet in the packet descriptors
20165 	 * that get added to the Multidata.
20166 	 */
20167 	do {
20168 		/*
20169 		 * If usable send window is too small, or data blocks in
20170 		 * transmit list are smaller than our threshold (i.e. app
20171 		 * performs large writes followed by small ones), we hand
20172 		 * off the control over to the legacy path.  Note that we'll
20173 		 * get back the control once it encounters a large block.
20174 		 */
20175 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
20176 		    (*xmit_tail)->b_cont != NULL &&
20177 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
20178 			/* send down what we've got so far */
20179 			if (md_mp_head != NULL) {
20180 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
20181 				    obsegs, obbytes, &rconfirm);
20182 			}
20183 			/*
20184 			 * Pass control over to tcp_send(), but tell it to
20185 			 * return to us once a large-size transmission is
20186 			 * possible.
20187 			 */
20188 			TCP_STAT(tcps, tcp_mdt_legacy_small);
20189 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
20190 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
20191 			    tail_unsent, xmit_tail, local_time,
20192 			    mdt_thres)) <= 0) {
20193 				/* burst count reached, or alloc failed */
20194 				IRE_REFRELE(ire);
20195 				return (err);
20196 			}
20197 
20198 			/* tcp_send() may have sent everything, so check */
20199 			if (*usable <= 0) {
20200 				IRE_REFRELE(ire);
20201 				return (0);
20202 			}
20203 
20204 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
20205 			/*
20206 			 * We may have delivered the Multidata, so make sure
20207 			 * to re-initialize before the next round.
20208 			 */
20209 			md_mp_head = NULL;
20210 			obsegs = obbytes = 0;
20211 			num_burst_seg = tcp->tcp_snd_burst;
20212 			PREP_NEW_MULTIDATA();
20213 
20214 			/* are we starting from the beginning of data block? */
20215 			if (*tail_unsent == 0) {
20216 				*xmit_tail = (*xmit_tail)->b_cont;
20217 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20218 				    (uintptr_t)INT_MAX);
20219 				*tail_unsent = (int)MBLKL(*xmit_tail);
20220 			}
20221 		}
20222 		/*
20223 		 * Record current values for parameters we may need to pass
20224 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
20225 		 * each iteration of the outer loop (each multidata message
20226 		 * creation). If we have a failure in the inner loop, we send
20227 		 * any complete multidata messages we have before reverting
20228 		 * to using the traditional non-md path.
20229 		 */
20230 		snxt_mmd = *snxt;
20231 		usable_mmd = *usable;
20232 		xmit_tail_mmd = *xmit_tail;
20233 		tail_unsent_mmd = *tail_unsent;
20234 		obsegs_mmd = obsegs;
20235 		obbytes_mmd = obbytes;
20236 
20237 		/*
20238 		 * max_pld limits the number of mblks in tcp's transmit
20239 		 * queue that can be added to a Multidata message.  Once
20240 		 * this counter reaches zero, no more additional mblks
20241 		 * can be added to it.  What happens afterwards depends
20242 		 * on whether or not we are set to chain the Multidata
20243 		 * messages.  If we are to link them together, reset
20244 		 * max_pld to its original value (tcp_mdt_max_pld) and
20245 		 * prepare to create a new Multidata message which will
20246 		 * get linked to md_mp_head.  Else, leave it alone and
20247 		 * let the inner loop break on its own.
20248 		 */
20249 		if (tcp_mdt_chain && max_pld == 0)
20250 			PREP_NEW_MULTIDATA();
20251 
20252 		/* adding a payload buffer; re-initialize values */
20253 		if (add_buffer)
20254 			PREP_NEW_PBUF();
20255 
20256 		/*
20257 		 * If we don't have a Multidata, either because we just
20258 		 * (re)entered this outer loop, or after we branched off
20259 		 * to tcp_send above, setup the Multidata and header
20260 		 * buffer to be used.
20261 		 */
20262 		if (md_mp == NULL) {
20263 			int md_hbuflen;
20264 			uint32_t start, stuff;
20265 
20266 			/*
20267 			 * Calculate Multidata header buffer size large enough
20268 			 * to hold all of the headers that can possibly be
20269 			 * sent at this moment.  We'd rather over-estimate
20270 			 * the size than running out of space; this is okay
20271 			 * since this buffer is small anyway.
20272 			 */
20273 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
20274 
20275 			/*
20276 			 * Start and stuff offset for partial hardware
20277 			 * checksum offload; these are currently for IPv4.
20278 			 * For full checksum offload, they are set to zero.
20279 			 */
20280 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
20281 				if (af == AF_INET) {
20282 					start = IP_SIMPLE_HDR_LENGTH;
20283 					stuff = IP_SIMPLE_HDR_LENGTH +
20284 					    TCP_CHECKSUM_OFFSET;
20285 				} else {
20286 					start = IPV6_HDR_LEN;
20287 					stuff = IPV6_HDR_LEN +
20288 					    TCP_CHECKSUM_OFFSET;
20289 				}
20290 			} else {
20291 				start = stuff = 0;
20292 			}
20293 
20294 			/*
20295 			 * Create the header buffer, Multidata, as well as
20296 			 * any necessary attributes (destination address,
20297 			 * SAP and hardware checksum offload) that should
20298 			 * be associated with the Multidata message.
20299 			 */
20300 			ASSERT(cur_hdr_off == 0);
20301 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
20302 			    ((md_hbuf->b_wptr += md_hbuflen),
20303 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
20304 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
20305 			    /* fastpath mblk */
20306 			    ire->ire_nce->nce_res_mp,
20307 			    /* hardware checksum enabled */
20308 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
20309 			    /* hardware checksum offsets */
20310 			    start, stuff, 0,
20311 			    /* hardware checksum flag */
20312 			    hwcksum_flags, tcps) != 0)) {
20313 legacy_send:
20314 				/*
20315 				 * We arrive here from a failure within the
20316 				 * inner (packetizer) loop or we fail one of
20317 				 * the conditionals above. We restore the
20318 				 * previously checkpointed values for:
20319 				 *    xmit_tail
20320 				 *    usable
20321 				 *    tail_unsent
20322 				 *    snxt
20323 				 *    obbytes
20324 				 *    obsegs
20325 				 * We should then be able to dispatch any
20326 				 * complete multidata before reverting to the
20327 				 * traditional path with consistent parameters
20328 				 * (the inner loop updates these as it
20329 				 * iterates).
20330 				 */
20331 				*xmit_tail = xmit_tail_mmd;
20332 				*usable = usable_mmd;
20333 				*tail_unsent = tail_unsent_mmd;
20334 				*snxt = snxt_mmd;
20335 				obbytes = obbytes_mmd;
20336 				obsegs = obsegs_mmd;
20337 				if (md_mp != NULL) {
20338 					/* Unlink message from the chain */
20339 					if (md_mp_head != NULL) {
20340 						err = (intptr_t)rmvb(md_mp_head,
20341 						    md_mp);
20342 						/*
20343 						 * We can't assert that rmvb
20344 						 * did not return -1, since we
20345 						 * may get here before linkb
20346 						 * happens.  We do, however,
20347 						 * check if we just removed the
20348 						 * only element in the list.
20349 						 */
20350 						if (err == 0)
20351 							md_mp_head = NULL;
20352 					}
20353 					/* md_hbuf gets freed automatically */
20354 					TCP_STAT(tcps, tcp_mdt_discarded);
20355 					freeb(md_mp);
20356 				} else {
20357 					/* Either allocb or mmd_alloc failed */
20358 					TCP_STAT(tcps, tcp_mdt_allocfail);
20359 					if (md_hbuf != NULL)
20360 						freeb(md_hbuf);
20361 				}
20362 
20363 				/* send down what we've got so far */
20364 				if (md_mp_head != NULL) {
20365 					tcp_multisend_data(tcp, ire, ill,
20366 					    md_mp_head, obsegs, obbytes,
20367 					    &rconfirm);
20368 				}
20369 legacy_send_no_md:
20370 				if (ire != NULL)
20371 					IRE_REFRELE(ire);
20372 				/*
20373 				 * Too bad; let the legacy path handle this.
20374 				 * We specify INT_MAX for the threshold, since
20375 				 * we gave up with the Multidata processings
20376 				 * and let the old path have it all.
20377 				 */
20378 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20379 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20380 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20381 				    snxt, tail_unsent, xmit_tail, local_time,
20382 				    INT_MAX));
20383 			}
20384 
20385 			/* link to any existing ones, if applicable */
20386 			TCP_STAT(tcps, tcp_mdt_allocd);
20387 			if (md_mp_head == NULL) {
20388 				md_mp_head = md_mp;
20389 			} else if (tcp_mdt_chain) {
20390 				TCP_STAT(tcps, tcp_mdt_linked);
20391 				linkb(md_mp_head, md_mp);
20392 			}
20393 		}
20394 
20395 		ASSERT(md_mp_head != NULL);
20396 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20397 		ASSERT(md_mp != NULL && mmd != NULL);
20398 		ASSERT(md_hbuf != NULL);
20399 
20400 		/*
20401 		 * Packetize the transmittable portion of the data block;
20402 		 * each data block is essentially added to the Multidata
20403 		 * as a payload buffer.  We also deal with adding more
20404 		 * than one payload buffers, which happens when the remaining
20405 		 * packetized portion of the current payload buffer is less
20406 		 * than MSS, while the next data block in transmit queue
20407 		 * has enough data to make up for one.  This "spillover"
20408 		 * case essentially creates a split-packet, where portions
20409 		 * of the packet's payload fragments may span across two
20410 		 * virtually discontiguous address blocks.
20411 		 */
20412 		seg_len = mss;
20413 		do {
20414 			len = seg_len;
20415 
20416 			/* one must remain NULL for DTRACE_IP_FASTPATH */
20417 			ipha = NULL;
20418 			ip6h = NULL;
20419 
20420 			ASSERT(len > 0);
20421 			ASSERT(max_pld >= 0);
20422 			ASSERT(!add_buffer || cur_pld_off == 0);
20423 
20424 			/*
20425 			 * First time around for this payload buffer; note
20426 			 * in the case of a spillover, the following has
20427 			 * been done prior to adding the split-packet
20428 			 * descriptor to Multidata, and we don't want to
20429 			 * repeat the process.
20430 			 */
20431 			if (add_buffer) {
20432 				ASSERT(mmd != NULL);
20433 				ASSERT(md_pbuf == NULL);
20434 				ASSERT(md_pbuf_nxt == NULL);
20435 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20436 
20437 				/*
20438 				 * Have we reached the limit?  We'd get to
20439 				 * this case when we're not chaining the
20440 				 * Multidata messages together, and since
20441 				 * we're done, terminate this loop.
20442 				 */
20443 				if (max_pld == 0)
20444 					break; /* done */
20445 
20446 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20447 					TCP_STAT(tcps, tcp_mdt_allocfail);
20448 					goto legacy_send; /* out_of_mem */
20449 				}
20450 
20451 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20452 				    zc_cap != NULL) {
20453 					if (!ip_md_zcopy_attr(mmd, NULL,
20454 					    zc_cap->ill_zerocopy_flags)) {
20455 						freeb(md_pbuf);
20456 						TCP_STAT(tcps,
20457 						    tcp_mdt_allocfail);
20458 						/* out_of_mem */
20459 						goto legacy_send;
20460 					}
20461 					zcopy = B_TRUE;
20462 				}
20463 
20464 				md_pbuf->b_rptr += base_pld_off;
20465 
20466 				/*
20467 				 * Add a payload buffer to the Multidata; this
20468 				 * operation must not fail, or otherwise our
20469 				 * logic in this routine is broken.  There
20470 				 * is no memory allocation done by the
20471 				 * routine, so any returned failure simply
20472 				 * tells us that we've done something wrong.
20473 				 *
20474 				 * A failure tells us that either we're adding
20475 				 * the same payload buffer more than once, or
20476 				 * we're trying to add more buffers than
20477 				 * allowed (max_pld calculation is wrong).
20478 				 * None of the above cases should happen, and
20479 				 * we panic because either there's horrible
20480 				 * heap corruption, and/or programming mistake.
20481 				 */
20482 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20483 				if (pbuf_idx < 0) {
20484 					cmn_err(CE_PANIC, "tcp_multisend: "
20485 					    "payload buffer logic error "
20486 					    "detected for tcp %p mmd %p "
20487 					    "pbuf %p (%d)\n",
20488 					    (void *)tcp, (void *)mmd,
20489 					    (void *)md_pbuf, pbuf_idx);
20490 				}
20491 
20492 				ASSERT(max_pld > 0);
20493 				--max_pld;
20494 				add_buffer = B_FALSE;
20495 			}
20496 
20497 			ASSERT(md_mp_head != NULL);
20498 			ASSERT(md_pbuf != NULL);
20499 			ASSERT(md_pbuf_nxt == NULL);
20500 			ASSERT(pbuf_idx != -1);
20501 			ASSERT(pbuf_idx_nxt == -1);
20502 			ASSERT(*usable > 0);
20503 
20504 			/*
20505 			 * We spillover to the next payload buffer only
20506 			 * if all of the following is true:
20507 			 *
20508 			 *   1. There is not enough data on the current
20509 			 *	payload buffer to make up `len',
20510 			 *   2. We are allowed to send `len',
20511 			 *   3. The next payload buffer length is large
20512 			 *	enough to accomodate `spill'.
20513 			 */
20514 			if ((spill = len - *tail_unsent) > 0 &&
20515 			    *usable >= len &&
20516 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20517 			    max_pld > 0) {
20518 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20519 				if (md_pbuf_nxt == NULL) {
20520 					TCP_STAT(tcps, tcp_mdt_allocfail);
20521 					goto legacy_send; /* out_of_mem */
20522 				}
20523 
20524 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20525 				    zc_cap != NULL) {
20526 					if (!ip_md_zcopy_attr(mmd, NULL,
20527 					    zc_cap->ill_zerocopy_flags)) {
20528 						freeb(md_pbuf_nxt);
20529 						TCP_STAT(tcps,
20530 						    tcp_mdt_allocfail);
20531 						/* out_of_mem */
20532 						goto legacy_send;
20533 					}
20534 					zcopy = B_TRUE;
20535 				}
20536 
20537 				/*
20538 				 * See comments above on the first call to
20539 				 * mmd_addpldbuf for explanation on the panic.
20540 				 */
20541 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20542 				if (pbuf_idx_nxt < 0) {
20543 					panic("tcp_multisend: "
20544 					    "next payload buffer logic error "
20545 					    "detected for tcp %p mmd %p "
20546 					    "pbuf %p (%d)\n",
20547 					    (void *)tcp, (void *)mmd,
20548 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20549 				}
20550 
20551 				ASSERT(max_pld > 0);
20552 				--max_pld;
20553 			} else if (spill > 0) {
20554 				/*
20555 				 * If there's a spillover, but the following
20556 				 * xmit_tail couldn't give us enough octets
20557 				 * to reach "len", then stop the current
20558 				 * Multidata creation and let the legacy
20559 				 * tcp_send() path take over.  We don't want
20560 				 * to send the tiny segment as part of this
20561 				 * Multidata for performance reasons; instead,
20562 				 * we let the legacy path deal with grouping
20563 				 * it with the subsequent small mblks.
20564 				 */
20565 				if (*usable >= len &&
20566 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20567 					max_pld = 0;
20568 					break;	/* done */
20569 				}
20570 
20571 				/*
20572 				 * We can't spillover, and we are near
20573 				 * the end of the current payload buffer,
20574 				 * so send what's left.
20575 				 */
20576 				ASSERT(*tail_unsent > 0);
20577 				len = *tail_unsent;
20578 			}
20579 
20580 			/* tail_unsent is negated if there is a spillover */
20581 			*tail_unsent -= len;
20582 			*usable -= len;
20583 			ASSERT(*usable >= 0);
20584 
20585 			if (*usable < mss)
20586 				seg_len = *usable;
20587 			/*
20588 			 * Sender SWS avoidance; see comments in tcp_send();
20589 			 * everything else is the same, except that we only
20590 			 * do this here if there is no more data to be sent
20591 			 * following the current xmit_tail.  We don't check
20592 			 * for 1-byte urgent data because we shouldn't get
20593 			 * here if TCP_URG_VALID is set.
20594 			 */
20595 			if (*usable > 0 && *usable < mss &&
20596 			    ((md_pbuf_nxt == NULL &&
20597 			    (*xmit_tail)->b_cont == NULL) ||
20598 			    (md_pbuf_nxt != NULL &&
20599 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20600 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20601 			    (tcp->tcp_unsent -
20602 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20603 			    !tcp->tcp_zero_win_probe) {
20604 				if ((*snxt + len) == tcp->tcp_snxt &&
20605 				    (*snxt + len) == tcp->tcp_suna) {
20606 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20607 				}
20608 				done = B_TRUE;
20609 			}
20610 
20611 			/*
20612 			 * Prime pump for IP's checksumming on our behalf;
20613 			 * include the adjustment for a source route if any.
20614 			 * Do this only for software/partial hardware checksum
20615 			 * offload, as this field gets zeroed out later for
20616 			 * the full hardware checksum offload case.
20617 			 */
20618 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20619 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20620 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20621 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20622 			}
20623 
20624 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20625 			*snxt += len;
20626 
20627 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20628 			/*
20629 			 * We set the PUSH bit only if TCP has no more buffered
20630 			 * data to be transmitted (or if sender SWS avoidance
20631 			 * takes place), as opposed to setting it for every
20632 			 * last packet in the burst.
20633 			 */
20634 			if (done ||
20635 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20636 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20637 
20638 			/*
20639 			 * Set FIN bit if this is our last segment; snxt
20640 			 * already includes its length, and it will not
20641 			 * be adjusted after this point.
20642 			 */
20643 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20644 			    *snxt == tcp->tcp_fss) {
20645 				if (!tcp->tcp_fin_acked) {
20646 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20647 					BUMP_MIB(&tcps->tcps_mib,
20648 					    tcpOutControl);
20649 				}
20650 				if (!tcp->tcp_fin_sent) {
20651 					tcp->tcp_fin_sent = B_TRUE;
20652 					/*
20653 					 * tcp state must be ESTABLISHED
20654 					 * in order for us to get here in
20655 					 * the first place.
20656 					 */
20657 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20658 
20659 					/*
20660 					 * Upon returning from this routine,
20661 					 * tcp_wput_data() will set tcp_snxt
20662 					 * to be equal to snxt + tcp_fin_sent.
20663 					 * This is essentially the same as
20664 					 * setting it to tcp_fss + 1.
20665 					 */
20666 				}
20667 			}
20668 
20669 			tcp->tcp_last_sent_len = (ushort_t)len;
20670 
20671 			len += tcp_hdr_len;
20672 			if (tcp->tcp_ipversion == IPV4_VERSION)
20673 				tcp->tcp_ipha->ipha_length = htons(len);
20674 			else
20675 				tcp->tcp_ip6h->ip6_plen = htons(len -
20676 				    ((char *)&tcp->tcp_ip6h[1] -
20677 				    tcp->tcp_iphc));
20678 
20679 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20680 
20681 			/* setup header fragment */
20682 			PDESC_HDR_ADD(pkt_info,
20683 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20684 			    tcp->tcp_mdt_hdr_head,		/* head room */
20685 			    tcp_hdr_len,			/* len */
20686 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20687 
20688 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20689 			    hdr_frag_sz);
20690 			ASSERT(MBLKIN(md_hbuf,
20691 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20692 			    PDESC_HDRSIZE(pkt_info)));
20693 
20694 			/* setup first payload fragment */
20695 			PDESC_PLD_INIT(pkt_info);
20696 			PDESC_PLD_SPAN_ADD(pkt_info,
20697 			    pbuf_idx,				/* index */
20698 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20699 			    tcp->tcp_last_sent_len);		/* len */
20700 
20701 			/* create a split-packet in case of a spillover */
20702 			if (md_pbuf_nxt != NULL) {
20703 				ASSERT(spill > 0);
20704 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20705 				ASSERT(!add_buffer);
20706 
20707 				md_pbuf = md_pbuf_nxt;
20708 				md_pbuf_nxt = NULL;
20709 				pbuf_idx = pbuf_idx_nxt;
20710 				pbuf_idx_nxt = -1;
20711 				cur_pld_off = spill;
20712 
20713 				/* trim out first payload fragment */
20714 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20715 
20716 				/* setup second payload fragment */
20717 				PDESC_PLD_SPAN_ADD(pkt_info,
20718 				    pbuf_idx,			/* index */
20719 				    md_pbuf->b_rptr,		/* start */
20720 				    spill);			/* len */
20721 
20722 				if ((*xmit_tail)->b_next == NULL) {
20723 					/*
20724 					 * Store the lbolt used for RTT
20725 					 * estimation. We can only record one
20726 					 * timestamp per mblk so we do it when
20727 					 * we reach the end of the payload
20728 					 * buffer.  Also we only take a new
20729 					 * timestamp sample when the previous
20730 					 * timed data from the same mblk has
20731 					 * been ack'ed.
20732 					 */
20733 					(*xmit_tail)->b_prev = local_time;
20734 					(*xmit_tail)->b_next =
20735 					    (mblk_t *)(uintptr_t)first_snxt;
20736 				}
20737 
20738 				first_snxt = *snxt - spill;
20739 
20740 				/*
20741 				 * Advance xmit_tail; usable could be 0 by
20742 				 * the time we got here, but we made sure
20743 				 * above that we would only spillover to
20744 				 * the next data block if usable includes
20745 				 * the spilled-over amount prior to the
20746 				 * subtraction.  Therefore, we are sure
20747 				 * that xmit_tail->b_cont can't be NULL.
20748 				 */
20749 				ASSERT((*xmit_tail)->b_cont != NULL);
20750 				*xmit_tail = (*xmit_tail)->b_cont;
20751 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20752 				    (uintptr_t)INT_MAX);
20753 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20754 			} else {
20755 				cur_pld_off += tcp->tcp_last_sent_len;
20756 			}
20757 
20758 			/*
20759 			 * Fill in the header using the template header, and
20760 			 * add options such as time-stamp, ECN and/or SACK,
20761 			 * as needed.
20762 			 */
20763 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20764 			    (clock_t)local_time, num_sack_blk);
20765 
20766 			/* take care of some IP header businesses */
20767 			if (af == AF_INET) {
20768 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20769 
20770 				ASSERT(OK_32PTR((uchar_t *)ipha));
20771 				ASSERT(PDESC_HDRL(pkt_info) >=
20772 				    IP_SIMPLE_HDR_LENGTH);
20773 				ASSERT(ipha->ipha_version_and_hdr_length ==
20774 				    IP_SIMPLE_HDR_VERSION);
20775 
20776 				/*
20777 				 * Assign ident value for current packet; see
20778 				 * related comments in ip_wput_ire() about the
20779 				 * contract private interface with clustering
20780 				 * group.
20781 				 */
20782 				clusterwide = B_FALSE;
20783 				if (cl_inet_ipident != NULL) {
20784 					ASSERT(cl_inet_isclusterwide != NULL);
20785 					if ((*cl_inet_isclusterwide)(stack_id,
20786 					    IPPROTO_IP, AF_INET,
20787 					    (uint8_t *)(uintptr_t)src, NULL)) {
20788 						ipha->ipha_ident =
20789 						    (*cl_inet_ipident)(stack_id,
20790 						    IPPROTO_IP, AF_INET,
20791 						    (uint8_t *)(uintptr_t)src,
20792 						    (uint8_t *)(uintptr_t)dst,
20793 						    NULL);
20794 						clusterwide = B_TRUE;
20795 					}
20796 				}
20797 
20798 				if (!clusterwide) {
20799 					ipha->ipha_ident = (uint16_t)
20800 					    atomic_add_32_nv(
20801 						&ire->ire_ident, 1);
20802 				}
20803 #ifndef _BIG_ENDIAN
20804 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20805 				    (ipha->ipha_ident >> 8);
20806 #endif
20807 			} else {
20808 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20809 
20810 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20811 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20812 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20813 				ASSERT(PDESC_HDRL(pkt_info) >=
20814 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20815 				    TCP_CHECKSUM_SIZE));
20816 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20817 
20818 				if (tcp->tcp_ip_forward_progress) {
20819 					rconfirm = B_TRUE;
20820 					tcp->tcp_ip_forward_progress = B_FALSE;
20821 				}
20822 			}
20823 
20824 			/* at least one payload span, and at most two */
20825 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20826 
20827 			/* add the packet descriptor to Multidata */
20828 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20829 			    KM_NOSLEEP)) == NULL) {
20830 				/*
20831 				 * Any failure other than ENOMEM indicates
20832 				 * that we have passed in invalid pkt_info
20833 				 * or parameters to mmd_addpdesc, which must
20834 				 * not happen.
20835 				 *
20836 				 * EINVAL is a result of failure on boundary
20837 				 * checks against the pkt_info contents.  It
20838 				 * should not happen, and we panic because
20839 				 * either there's horrible heap corruption,
20840 				 * and/or programming mistake.
20841 				 */
20842 				if (err != ENOMEM) {
20843 					cmn_err(CE_PANIC, "tcp_multisend: "
20844 					    "pdesc logic error detected for "
20845 					    "tcp %p mmd %p pinfo %p (%d)\n",
20846 					    (void *)tcp, (void *)mmd,
20847 					    (void *)pkt_info, err);
20848 				}
20849 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20850 				goto legacy_send; /* out_of_mem */
20851 			}
20852 			ASSERT(pkt != NULL);
20853 
20854 			/* calculate IP header and TCP checksums */
20855 			if (af == AF_INET) {
20856 				/* calculate pseudo-header checksum */
20857 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20858 				    (src >> 16) + (src & 0xFFFF);
20859 
20860 				/* offset for TCP header checksum */
20861 				up = IPH_TCPH_CHECKSUMP(ipha,
20862 				    IP_SIMPLE_HDR_LENGTH);
20863 			} else {
20864 				up = (uint16_t *)&ip6h->ip6_src;
20865 
20866 				/* calculate pseudo-header checksum */
20867 				cksum = up[0] + up[1] + up[2] + up[3] +
20868 				    up[4] + up[5] + up[6] + up[7] +
20869 				    up[8] + up[9] + up[10] + up[11] +
20870 				    up[12] + up[13] + up[14] + up[15];
20871 
20872 				/* Fold the initial sum */
20873 				cksum = (cksum & 0xffff) + (cksum >> 16);
20874 
20875 				up = (uint16_t *)(((uchar_t *)ip6h) +
20876 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20877 			}
20878 
20879 			if (hwcksum_flags & HCK_FULLCKSUM) {
20880 				/* clear checksum field for hardware */
20881 				*up = 0;
20882 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20883 				uint32_t sum;
20884 
20885 				/* pseudo-header checksumming */
20886 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20887 				sum = (sum & 0xFFFF) + (sum >> 16);
20888 				*up = (sum & 0xFFFF) + (sum >> 16);
20889 			} else {
20890 				/* software checksumming */
20891 				TCP_STAT(tcps, tcp_out_sw_cksum);
20892 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20893 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20894 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20895 				    cksum + IP_TCP_CSUM_COMP);
20896 				if (*up == 0)
20897 					*up = 0xFFFF;
20898 			}
20899 
20900 			/* IPv4 header checksum */
20901 			if (af == AF_INET) {
20902 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20903 					ipha->ipha_hdr_checksum = 0;
20904 				} else {
20905 					IP_HDR_CKSUM(ipha, cksum,
20906 					    ((uint32_t *)ipha)[0],
20907 					    ((uint16_t *)ipha)[4]);
20908 				}
20909 			}
20910 
20911 			if (af == AF_INET &&
20912 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20913 			    af == AF_INET6 &&
20914 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20915 				mblk_t	*mp, *mp1;
20916 				uchar_t	*hdr_rptr, *hdr_wptr;
20917 				uchar_t	*pld_rptr, *pld_wptr;
20918 
20919 				/*
20920 				 * We reconstruct a pseudo packet for the hooks
20921 				 * framework using mmd_transform_link().
20922 				 * If it is a split packet we pullup the
20923 				 * payload. FW_HOOKS expects a pkt comprising
20924 				 * of two mblks: a header and the payload.
20925 				 */
20926 				if ((mp = mmd_transform_link(pkt)) == NULL) {
20927 					TCP_STAT(tcps, tcp_mdt_allocfail);
20928 					goto legacy_send;
20929 				}
20930 
20931 				if (pkt_info->pld_cnt > 1) {
20932 					/* split payload, more than one pld */
20933 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
20934 					    NULL) {
20935 						freemsg(mp);
20936 						TCP_STAT(tcps,
20937 						    tcp_mdt_allocfail);
20938 						goto legacy_send;
20939 					}
20940 					freemsg(mp->b_cont);
20941 					mp->b_cont = mp1;
20942 				} else {
20943 					mp1 = mp->b_cont;
20944 				}
20945 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
20946 
20947 				/*
20948 				 * Remember the message offsets. This is so we
20949 				 * can detect changes when we return from the
20950 				 * FW_HOOKS callbacks.
20951 				 */
20952 				hdr_rptr = mp->b_rptr;
20953 				hdr_wptr = mp->b_wptr;
20954 				pld_rptr = mp->b_cont->b_rptr;
20955 				pld_wptr = mp->b_cont->b_wptr;
20956 
20957 				if (af == AF_INET) {
20958 					DTRACE_PROBE4(
20959 					    ip4__physical__out__start,
20960 					    ill_t *, NULL,
20961 					    ill_t *, ill,
20962 					    ipha_t *, ipha,
20963 					    mblk_t *, mp);
20964 					FW_HOOKS(
20965 					    ipst->ips_ip4_physical_out_event,
20966 					    ipst->ips_ipv4firewall_physical_out,
20967 					    NULL, ill, ipha, mp, mp, 0, ipst);
20968 					DTRACE_PROBE1(
20969 					    ip4__physical__out__end,
20970 					    mblk_t *, mp);
20971 				} else {
20972 					DTRACE_PROBE4(
20973 					    ip6__physical__out_start,
20974 					    ill_t *, NULL,
20975 					    ill_t *, ill,
20976 					    ip6_t *, ip6h,
20977 					    mblk_t *, mp);
20978 					FW_HOOKS6(
20979 					    ipst->ips_ip6_physical_out_event,
20980 					    ipst->ips_ipv6firewall_physical_out,
20981 					    NULL, ill, ip6h, mp, mp, 0, ipst);
20982 					DTRACE_PROBE1(
20983 					    ip6__physical__out__end,
20984 					    mblk_t *, mp);
20985 				}
20986 
20987 				if (mp == NULL ||
20988 				    (mp1 = mp->b_cont) == NULL ||
20989 				    mp->b_rptr != hdr_rptr ||
20990 				    mp->b_wptr != hdr_wptr ||
20991 				    mp1->b_rptr != pld_rptr ||
20992 				    mp1->b_wptr != pld_wptr ||
20993 				    mp1->b_cont != NULL) {
20994 					/*
20995 					 * We abandon multidata processing and
20996 					 * return to the normal path, either
20997 					 * when a packet is blocked, or when
20998 					 * the boundaries of header buffer or
20999 					 * payload buffer have been changed by
21000 					 * FW_HOOKS[6].
21001 					 */
21002 					if (mp != NULL)
21003 						freemsg(mp);
21004 					goto legacy_send;
21005 				}
21006 				/* Finished with the pseudo packet */
21007 				freemsg(mp);
21008 			}
21009 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
21010 			    ill, ipha, ip6h);
21011 			/* advance header offset */
21012 			cur_hdr_off += hdr_frag_sz;
21013 
21014 			obbytes += tcp->tcp_last_sent_len;
21015 			++obsegs;
21016 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
21017 		    *tail_unsent > 0);
21018 
21019 		if ((*xmit_tail)->b_next == NULL) {
21020 			/*
21021 			 * Store the lbolt used for RTT estimation. We can only
21022 			 * record one timestamp per mblk so we do it when we
21023 			 * reach the end of the payload buffer. Also we only
21024 			 * take a new timestamp sample when the previous timed
21025 			 * data from the same mblk has been ack'ed.
21026 			 */
21027 			(*xmit_tail)->b_prev = local_time;
21028 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
21029 		}
21030 
21031 		ASSERT(*tail_unsent >= 0);
21032 		if (*tail_unsent > 0) {
21033 			/*
21034 			 * We got here because we broke out of the above
21035 			 * loop due to of one of the following cases:
21036 			 *
21037 			 *   1. len < adjusted MSS (i.e. small),
21038 			 *   2. Sender SWS avoidance,
21039 			 *   3. max_pld is zero.
21040 			 *
21041 			 * We are done for this Multidata, so trim our
21042 			 * last payload buffer (if any) accordingly.
21043 			 */
21044 			if (md_pbuf != NULL)
21045 				md_pbuf->b_wptr -= *tail_unsent;
21046 		} else if (*usable > 0) {
21047 			*xmit_tail = (*xmit_tail)->b_cont;
21048 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
21049 			    (uintptr_t)INT_MAX);
21050 			*tail_unsent = (int)MBLKL(*xmit_tail);
21051 			add_buffer = B_TRUE;
21052 		}
21053 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
21054 	    (tcp_mdt_chain || max_pld > 0));
21055 
21056 	if (md_mp_head != NULL) {
21057 		/* send everything down */
21058 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
21059 		    &rconfirm);
21060 	}
21061 
21062 #undef PREP_NEW_MULTIDATA
21063 #undef PREP_NEW_PBUF
21064 #undef IPVER
21065 
21066 	IRE_REFRELE(ire);
21067 	return (0);
21068 }
21069 
21070 /*
21071  * A wrapper function for sending one or more Multidata messages down to
21072  * the module below ip; this routine does not release the reference of the
21073  * IRE (caller does that).  This routine is analogous to tcp_send_data().
21074  */
21075 static void
21076 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
21077     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
21078 {
21079 	uint64_t delta;
21080 	nce_t *nce;
21081 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21082 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21083 
21084 	ASSERT(ire != NULL && ill != NULL);
21085 	ASSERT(ire->ire_stq != NULL);
21086 	ASSERT(md_mp_head != NULL);
21087 	ASSERT(rconfirm != NULL);
21088 
21089 	/* adjust MIBs and IRE timestamp */
21090 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
21091 	tcp->tcp_obsegs += obsegs;
21092 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
21093 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
21094 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
21095 
21096 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21097 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
21098 	} else {
21099 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
21100 	}
21101 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
21102 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
21103 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
21104 
21105 	ire->ire_ob_pkt_count += obsegs;
21106 	if (ire->ire_ipif != NULL)
21107 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
21108 	ire->ire_last_used_time = lbolt;
21109 
21110 	if (ipst->ips_ipobs_enabled) {
21111 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
21112 		pdesc_t *dl_pkt;
21113 		pdescinfo_t pinfo;
21114 		mblk_t *nmp;
21115 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
21116 
21117 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
21118 		    (dl_pkt != NULL);
21119 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
21120 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
21121 				continue;
21122 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
21123 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
21124 			freemsg(nmp);
21125 		}
21126 	}
21127 
21128 	/* send it down */
21129 	putnext(ire->ire_stq, md_mp_head);
21130 
21131 	/* we're done for TCP/IPv4 */
21132 	if (tcp->tcp_ipversion == IPV4_VERSION)
21133 		return;
21134 
21135 	nce = ire->ire_nce;
21136 
21137 	ASSERT(nce != NULL);
21138 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
21139 	ASSERT(nce->nce_state != ND_INCOMPLETE);
21140 
21141 	/* reachability confirmation? */
21142 	if (*rconfirm) {
21143 		nce->nce_last = TICK_TO_MSEC(lbolt64);
21144 		if (nce->nce_state != ND_REACHABLE) {
21145 			mutex_enter(&nce->nce_lock);
21146 			nce->nce_state = ND_REACHABLE;
21147 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
21148 			mutex_exit(&nce->nce_lock);
21149 			(void) untimeout(nce->nce_timeout_id);
21150 			if (ip_debug > 2) {
21151 				/* ip1dbg */
21152 				pr_addr_dbg("tcp_multisend_data: state "
21153 				    "for %s changed to REACHABLE\n",
21154 				    AF_INET6, &ire->ire_addr_v6);
21155 			}
21156 		}
21157 		/* reset transport reachability confirmation */
21158 		*rconfirm = B_FALSE;
21159 	}
21160 
21161 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
21162 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
21163 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
21164 
21165 	if (delta > (uint64_t)ill->ill_reachable_time) {
21166 		mutex_enter(&nce->nce_lock);
21167 		switch (nce->nce_state) {
21168 		case ND_REACHABLE:
21169 		case ND_STALE:
21170 			/*
21171 			 * ND_REACHABLE is identical to ND_STALE in this
21172 			 * specific case. If reachable time has expired for
21173 			 * this neighbor (delta is greater than reachable
21174 			 * time), conceptually, the neighbor cache is no
21175 			 * longer in REACHABLE state, but already in STALE
21176 			 * state.  So the correct transition here is to
21177 			 * ND_DELAY.
21178 			 */
21179 			nce->nce_state = ND_DELAY;
21180 			mutex_exit(&nce->nce_lock);
21181 			NDP_RESTART_TIMER(nce,
21182 			    ipst->ips_delay_first_probe_time);
21183 			if (ip_debug > 3) {
21184 				/* ip2dbg */
21185 				pr_addr_dbg("tcp_multisend_data: state "
21186 				    "for %s changed to DELAY\n",
21187 				    AF_INET6, &ire->ire_addr_v6);
21188 			}
21189 			break;
21190 		case ND_DELAY:
21191 		case ND_PROBE:
21192 			mutex_exit(&nce->nce_lock);
21193 			/* Timers have already started */
21194 			break;
21195 		case ND_UNREACHABLE:
21196 			/*
21197 			 * ndp timer has detected that this nce is
21198 			 * unreachable and initiated deleting this nce
21199 			 * and all its associated IREs. This is a race
21200 			 * where we found the ire before it was deleted
21201 			 * and have just sent out a packet using this
21202 			 * unreachable nce.
21203 			 */
21204 			mutex_exit(&nce->nce_lock);
21205 			break;
21206 		default:
21207 			ASSERT(0);
21208 		}
21209 	}
21210 }
21211 
21212 /*
21213  * Derived from tcp_send_data().
21214  */
21215 static void
21216 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
21217     int num_lso_seg)
21218 {
21219 	ipha_t		*ipha;
21220 	mblk_t		*ire_fp_mp;
21221 	uint_t		ire_fp_mp_len;
21222 	uint32_t	hcksum_txflags = 0;
21223 	ipaddr_t	src;
21224 	ipaddr_t	dst;
21225 	uint32_t	cksum;
21226 	uint16_t	*up;
21227 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21228 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21229 
21230 	ASSERT(DB_TYPE(mp) == M_DATA);
21231 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
21232 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
21233 	ASSERT(tcp->tcp_connp != NULL);
21234 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
21235 
21236 	ipha = (ipha_t *)mp->b_rptr;
21237 	src = ipha->ipha_src;
21238 	dst = ipha->ipha_dst;
21239 
21240 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
21241 
21242 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21243 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
21244 	    num_lso_seg);
21245 #ifndef _BIG_ENDIAN
21246 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21247 #endif
21248 	if (tcp->tcp_snd_zcopy_aware) {
21249 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
21250 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
21251 			mp = tcp_zcopy_disable(tcp, mp);
21252 	}
21253 
21254 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
21255 		ASSERT(ill->ill_hcksum_capab != NULL);
21256 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
21257 	}
21258 
21259 	/*
21260 	 * Since the TCP checksum should be recalculated by h/w, we can just
21261 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
21262 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
21263 	 * The partial pseudo-header excludes TCP length, that was calculated
21264 	 * in tcp_send(), so to zero *up before further processing.
21265 	 */
21266 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21267 
21268 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
21269 	*up = 0;
21270 
21271 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
21272 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
21273 
21274 	/*
21275 	 * Append LSO flags and mss to the mp.
21276 	 */
21277 	lso_info_set(mp, mss, HW_LSO);
21278 
21279 	ipha->ipha_fragment_offset_and_flags |=
21280 	    (uint32_t)htons(ire->ire_frag_flag);
21281 
21282 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
21283 	ire_fp_mp_len = MBLKL(ire_fp_mp);
21284 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
21285 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
21286 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
21287 
21288 	UPDATE_OB_PKT_COUNT(ire);
21289 	ire->ire_last_used_time = lbolt;
21290 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
21291 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
21292 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
21293 	    ntohs(ipha->ipha_length));
21294 
21295 	DTRACE_PROBE4(ip4__physical__out__start,
21296 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
21297 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
21298 	    ipst->ips_ipv4firewall_physical_out, NULL,
21299 	    ill, ipha, mp, mp, 0, ipst);
21300 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21301 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
21302 
21303 	if (mp != NULL) {
21304 		if (ipst->ips_ipobs_enabled) {
21305 			zoneid_t szone;
21306 
21307 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
21308 			    ipst, ALL_ZONES);
21309 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
21310 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
21311 		}
21312 
21313 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0);
21314 	}
21315 }
21316 
21317 /*
21318  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
21319  * scheme, and returns one of the following:
21320  *
21321  * -1 = failed allocation.
21322  *  0 = success; burst count reached, or usable send window is too small,
21323  *      and that we'd rather wait until later before sending again.
21324  *  1 = success; we are called from tcp_multisend(), and both usable send
21325  *      window and tail_unsent are greater than the MDT threshold, and thus
21326  *      Multidata Transmit should be used instead.
21327  */
21328 static int
21329 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
21330     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
21331     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
21332     const int mdt_thres)
21333 {
21334 	int num_burst_seg = tcp->tcp_snd_burst;
21335 	ire_t		*ire = NULL;
21336 	ill_t		*ill = NULL;
21337 	mblk_t		*ire_fp_mp = NULL;
21338 	uint_t		ire_fp_mp_len = 0;
21339 	int		num_lso_seg = 1;
21340 	uint_t		lso_usable;
21341 	boolean_t	do_lso_send = B_FALSE;
21342 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21343 
21344 	/*
21345 	 * Check LSO capability before any further work. And the similar check
21346 	 * need to be done in for(;;) loop.
21347 	 * LSO will be deployed when therer is more than one mss of available
21348 	 * data and a burst transmission is allowed.
21349 	 */
21350 	if (tcp->tcp_lso &&
21351 	    (tcp->tcp_valid_bits == 0 ||
21352 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21353 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21354 		/*
21355 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21356 		 */
21357 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
21358 			/*
21359 			 * Enable LSO with this transmission.
21360 			 * Since IRE has been hold in
21361 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
21362 			 * should be called before return.
21363 			 */
21364 			do_lso_send = B_TRUE;
21365 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21366 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21367 			/* Round up to multiple of 4 */
21368 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21369 		} else {
21370 			do_lso_send = B_FALSE;
21371 			ill = NULL;
21372 		}
21373 	}
21374 
21375 	for (;;) {
21376 		struct datab	*db;
21377 		tcph_t		*tcph;
21378 		uint32_t	sum;
21379 		mblk_t		*mp, *mp1;
21380 		uchar_t		*rptr;
21381 		int		len;
21382 
21383 		/*
21384 		 * If we're called by tcp_multisend(), and the amount of
21385 		 * sendable data as well as the size of current xmit_tail
21386 		 * is beyond the MDT threshold, return to the caller and
21387 		 * let the large data transmit be done using MDT.
21388 		 */
21389 		if (*usable > 0 && *usable > mdt_thres &&
21390 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21391 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21392 			ASSERT(tcp->tcp_mdt);
21393 			return (1);	/* success; do large send */
21394 		}
21395 
21396 		if (num_burst_seg == 0)
21397 			break;		/* success; burst count reached */
21398 
21399 		/*
21400 		 * Calculate the maximum payload length we can send in *one*
21401 		 * time.
21402 		 */
21403 		if (do_lso_send) {
21404 			/*
21405 			 * Check whether need to do LSO any more.
21406 			 */
21407 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21408 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21409 				lso_usable = MIN(lso_usable,
21410 				    num_burst_seg * mss);
21411 
21412 				num_lso_seg = lso_usable / mss;
21413 				if (lso_usable % mss) {
21414 					num_lso_seg++;
21415 					tcp->tcp_last_sent_len = (ushort_t)
21416 					    (lso_usable % mss);
21417 				} else {
21418 					tcp->tcp_last_sent_len = (ushort_t)mss;
21419 				}
21420 			} else {
21421 				do_lso_send = B_FALSE;
21422 				num_lso_seg = 1;
21423 				lso_usable = mss;
21424 			}
21425 		}
21426 
21427 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21428 
21429 		/*
21430 		 * Adjust num_burst_seg here.
21431 		 */
21432 		num_burst_seg -= num_lso_seg;
21433 
21434 		len = mss;
21435 		if (len > *usable) {
21436 			ASSERT(do_lso_send == B_FALSE);
21437 
21438 			len = *usable;
21439 			if (len <= 0) {
21440 				/* Terminate the loop */
21441 				break;	/* success; too small */
21442 			}
21443 			/*
21444 			 * Sender silly-window avoidance.
21445 			 * Ignore this if we are going to send a
21446 			 * zero window probe out.
21447 			 *
21448 			 * TODO: force data into microscopic window?
21449 			 *	==> (!pushed || (unsent > usable))
21450 			 */
21451 			if (len < (tcp->tcp_max_swnd >> 1) &&
21452 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21453 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21454 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21455 				/*
21456 				 * If the retransmit timer is not running
21457 				 * we start it so that we will retransmit
21458 				 * in the case when the the receiver has
21459 				 * decremented the window.
21460 				 */
21461 				if (*snxt == tcp->tcp_snxt &&
21462 				    *snxt == tcp->tcp_suna) {
21463 					/*
21464 					 * We are not supposed to send
21465 					 * anything.  So let's wait a little
21466 					 * bit longer before breaking SWS
21467 					 * avoidance.
21468 					 *
21469 					 * What should the value be?
21470 					 * Suggestion: MAX(init rexmit time,
21471 					 * tcp->tcp_rto)
21472 					 */
21473 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21474 				}
21475 				break;	/* success; too small */
21476 			}
21477 		}
21478 
21479 		tcph = tcp->tcp_tcph;
21480 
21481 		/*
21482 		 * The reason to adjust len here is that we need to set flags
21483 		 * and calculate checksum.
21484 		 */
21485 		if (do_lso_send)
21486 			len = lso_usable;
21487 
21488 		*usable -= len; /* Approximate - can be adjusted later */
21489 		if (*usable > 0)
21490 			tcph->th_flags[0] = TH_ACK;
21491 		else
21492 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21493 
21494 		/*
21495 		 * Prime pump for IP's checksumming on our behalf
21496 		 * Include the adjustment for a source route if any.
21497 		 */
21498 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21499 		sum = (sum >> 16) + (sum & 0xFFFF);
21500 		U16_TO_ABE16(sum, tcph->th_sum);
21501 
21502 		U32_TO_ABE32(*snxt, tcph->th_seq);
21503 
21504 		/*
21505 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21506 		 * set.  For the case when TCP_FSS_VALID is the only valid
21507 		 * bit (normal active close), branch off only when we think
21508 		 * that the FIN flag needs to be set.  Note for this case,
21509 		 * that (snxt + len) may not reflect the actual seg_len,
21510 		 * as len may be further reduced in tcp_xmit_mp().  If len
21511 		 * gets modified, we will end up here again.
21512 		 */
21513 		if (tcp->tcp_valid_bits != 0 &&
21514 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21515 		    ((*snxt + len) == tcp->tcp_fss))) {
21516 			uchar_t		*prev_rptr;
21517 			uint32_t	prev_snxt = tcp->tcp_snxt;
21518 
21519 			if (*tail_unsent == 0) {
21520 				ASSERT((*xmit_tail)->b_cont != NULL);
21521 				*xmit_tail = (*xmit_tail)->b_cont;
21522 				prev_rptr = (*xmit_tail)->b_rptr;
21523 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21524 				    (*xmit_tail)->b_rptr);
21525 			} else {
21526 				prev_rptr = (*xmit_tail)->b_rptr;
21527 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21528 				    *tail_unsent;
21529 			}
21530 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21531 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21532 			/* Restore tcp_snxt so we get amount sent right. */
21533 			tcp->tcp_snxt = prev_snxt;
21534 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21535 				/*
21536 				 * If the previous timestamp is still in use,
21537 				 * don't stomp on it.
21538 				 */
21539 				if ((*xmit_tail)->b_next == NULL) {
21540 					(*xmit_tail)->b_prev = local_time;
21541 					(*xmit_tail)->b_next =
21542 					    (mblk_t *)(uintptr_t)(*snxt);
21543 				}
21544 			} else
21545 				(*xmit_tail)->b_rptr = prev_rptr;
21546 
21547 			if (mp == NULL) {
21548 				if (ire != NULL)
21549 					IRE_REFRELE(ire);
21550 				return (-1);
21551 			}
21552 			mp1 = mp->b_cont;
21553 
21554 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21555 				tcp->tcp_last_sent_len = (ushort_t)len;
21556 			while (mp1->b_cont) {
21557 				*xmit_tail = (*xmit_tail)->b_cont;
21558 				(*xmit_tail)->b_prev = local_time;
21559 				(*xmit_tail)->b_next =
21560 				    (mblk_t *)(uintptr_t)(*snxt);
21561 				mp1 = mp1->b_cont;
21562 			}
21563 			*snxt += len;
21564 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21565 			BUMP_LOCAL(tcp->tcp_obsegs);
21566 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21567 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21568 			tcp_send_data(tcp, q, mp);
21569 			continue;
21570 		}
21571 
21572 		*snxt += len;	/* Adjust later if we don't send all of len */
21573 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21574 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21575 
21576 		if (*tail_unsent) {
21577 			/* Are the bytes above us in flight? */
21578 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21579 			if (rptr != (*xmit_tail)->b_rptr) {
21580 				*tail_unsent -= len;
21581 				if (len <= mss) /* LSO is unusable */
21582 					tcp->tcp_last_sent_len = (ushort_t)len;
21583 				len += tcp_hdr_len;
21584 				if (tcp->tcp_ipversion == IPV4_VERSION)
21585 					tcp->tcp_ipha->ipha_length = htons(len);
21586 				else
21587 					tcp->tcp_ip6h->ip6_plen =
21588 					    htons(len -
21589 					    ((char *)&tcp->tcp_ip6h[1] -
21590 					    tcp->tcp_iphc));
21591 				mp = dupb(*xmit_tail);
21592 				if (mp == NULL) {
21593 					if (ire != NULL)
21594 						IRE_REFRELE(ire);
21595 					return (-1);	/* out_of_mem */
21596 				}
21597 				mp->b_rptr = rptr;
21598 				/*
21599 				 * If the old timestamp is no longer in use,
21600 				 * sample a new timestamp now.
21601 				 */
21602 				if ((*xmit_tail)->b_next == NULL) {
21603 					(*xmit_tail)->b_prev = local_time;
21604 					(*xmit_tail)->b_next =
21605 					    (mblk_t *)(uintptr_t)(*snxt-len);
21606 				}
21607 				goto must_alloc;
21608 			}
21609 		} else {
21610 			*xmit_tail = (*xmit_tail)->b_cont;
21611 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21612 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21613 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21614 			    (*xmit_tail)->b_rptr);
21615 		}
21616 
21617 		(*xmit_tail)->b_prev = local_time;
21618 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21619 
21620 		*tail_unsent -= len;
21621 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21622 			tcp->tcp_last_sent_len = (ushort_t)len;
21623 
21624 		len += tcp_hdr_len;
21625 		if (tcp->tcp_ipversion == IPV4_VERSION)
21626 			tcp->tcp_ipha->ipha_length = htons(len);
21627 		else
21628 			tcp->tcp_ip6h->ip6_plen = htons(len -
21629 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21630 
21631 		mp = dupb(*xmit_tail);
21632 		if (mp == NULL) {
21633 			if (ire != NULL)
21634 				IRE_REFRELE(ire);
21635 			return (-1);	/* out_of_mem */
21636 		}
21637 
21638 		len = tcp_hdr_len;
21639 		/*
21640 		 * There are four reasons to allocate a new hdr mblk:
21641 		 *  1) The bytes above us are in use by another packet
21642 		 *  2) We don't have good alignment
21643 		 *  3) The mblk is being shared
21644 		 *  4) We don't have enough room for a header
21645 		 */
21646 		rptr = mp->b_rptr - len;
21647 		if (!OK_32PTR(rptr) ||
21648 		    ((db = mp->b_datap), db->db_ref != 2) ||
21649 		    rptr < db->db_base + ire_fp_mp_len) {
21650 			/* NOTE: we assume allocb returns an OK_32PTR */
21651 
21652 		must_alloc:;
21653 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21654 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21655 			if (mp1 == NULL) {
21656 				freemsg(mp);
21657 				if (ire != NULL)
21658 					IRE_REFRELE(ire);
21659 				return (-1);	/* out_of_mem */
21660 			}
21661 			mp1->b_cont = mp;
21662 			mp = mp1;
21663 			/* Leave room for Link Level header */
21664 			len = tcp_hdr_len;
21665 			rptr =
21666 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21667 			mp->b_wptr = &rptr[len];
21668 		}
21669 
21670 		/*
21671 		 * Fill in the header using the template header, and add
21672 		 * options such as time-stamp, ECN and/or SACK, as needed.
21673 		 */
21674 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21675 
21676 		mp->b_rptr = rptr;
21677 
21678 		if (*tail_unsent) {
21679 			int spill = *tail_unsent;
21680 
21681 			mp1 = mp->b_cont;
21682 			if (mp1 == NULL)
21683 				mp1 = mp;
21684 
21685 			/*
21686 			 * If we're a little short, tack on more mblks until
21687 			 * there is no more spillover.
21688 			 */
21689 			while (spill < 0) {
21690 				mblk_t *nmp;
21691 				int nmpsz;
21692 
21693 				nmp = (*xmit_tail)->b_cont;
21694 				nmpsz = MBLKL(nmp);
21695 
21696 				/*
21697 				 * Excess data in mblk; can we split it?
21698 				 * If MDT is enabled for the connection,
21699 				 * keep on splitting as this is a transient
21700 				 * send path.
21701 				 */
21702 				if (!do_lso_send && !tcp->tcp_mdt &&
21703 				    (spill + nmpsz > 0)) {
21704 					/*
21705 					 * Don't split if stream head was
21706 					 * told to break up larger writes
21707 					 * into smaller ones.
21708 					 */
21709 					if (tcp->tcp_maxpsz > 0)
21710 						break;
21711 
21712 					/*
21713 					 * Next mblk is less than SMSS/2
21714 					 * rounded up to nearest 64-byte;
21715 					 * let it get sent as part of the
21716 					 * next segment.
21717 					 */
21718 					if (tcp->tcp_localnet &&
21719 					    !tcp->tcp_cork &&
21720 					    (nmpsz < roundup((mss >> 1), 64)))
21721 						break;
21722 				}
21723 
21724 				*xmit_tail = nmp;
21725 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21726 				/* Stash for rtt use later */
21727 				(*xmit_tail)->b_prev = local_time;
21728 				(*xmit_tail)->b_next =
21729 				    (mblk_t *)(uintptr_t)(*snxt - len);
21730 				mp1->b_cont = dupb(*xmit_tail);
21731 				mp1 = mp1->b_cont;
21732 
21733 				spill += nmpsz;
21734 				if (mp1 == NULL) {
21735 					*tail_unsent = spill;
21736 					freemsg(mp);
21737 					if (ire != NULL)
21738 						IRE_REFRELE(ire);
21739 					return (-1);	/* out_of_mem */
21740 				}
21741 			}
21742 
21743 			/* Trim back any surplus on the last mblk */
21744 			if (spill >= 0) {
21745 				mp1->b_wptr -= spill;
21746 				*tail_unsent = spill;
21747 			} else {
21748 				/*
21749 				 * We did not send everything we could in
21750 				 * order to remain within the b_cont limit.
21751 				 */
21752 				*usable -= spill;
21753 				*snxt += spill;
21754 				tcp->tcp_last_sent_len += spill;
21755 				UPDATE_MIB(&tcps->tcps_mib,
21756 				    tcpOutDataBytes, spill);
21757 				/*
21758 				 * Adjust the checksum
21759 				 */
21760 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21761 				sum += spill;
21762 				sum = (sum >> 16) + (sum & 0xFFFF);
21763 				U16_TO_ABE16(sum, tcph->th_sum);
21764 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21765 					sum = ntohs(
21766 					    ((ipha_t *)rptr)->ipha_length) +
21767 					    spill;
21768 					((ipha_t *)rptr)->ipha_length =
21769 					    htons(sum);
21770 				} else {
21771 					sum = ntohs(
21772 					    ((ip6_t *)rptr)->ip6_plen) +
21773 					    spill;
21774 					((ip6_t *)rptr)->ip6_plen =
21775 					    htons(sum);
21776 				}
21777 				*tail_unsent = 0;
21778 			}
21779 		}
21780 		if (tcp->tcp_ip_forward_progress) {
21781 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21782 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21783 			tcp->tcp_ip_forward_progress = B_FALSE;
21784 		}
21785 
21786 		if (do_lso_send) {
21787 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21788 			    num_lso_seg);
21789 			tcp->tcp_obsegs += num_lso_seg;
21790 
21791 			TCP_STAT(tcps, tcp_lso_times);
21792 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21793 		} else {
21794 			tcp_send_data(tcp, q, mp);
21795 			BUMP_LOCAL(tcp->tcp_obsegs);
21796 		}
21797 	}
21798 
21799 	if (ire != NULL)
21800 		IRE_REFRELE(ire);
21801 	return (0);
21802 }
21803 
21804 /* Unlink and return any mblk that looks like it contains a MDT info */
21805 static mblk_t *
21806 tcp_mdt_info_mp(mblk_t *mp)
21807 {
21808 	mblk_t	*prev_mp;
21809 
21810 	for (;;) {
21811 		prev_mp = mp;
21812 		/* no more to process? */
21813 		if ((mp = mp->b_cont) == NULL)
21814 			break;
21815 
21816 		switch (DB_TYPE(mp)) {
21817 		case M_CTL:
21818 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21819 				continue;
21820 			ASSERT(prev_mp != NULL);
21821 			prev_mp->b_cont = mp->b_cont;
21822 			mp->b_cont = NULL;
21823 			return (mp);
21824 		default:
21825 			break;
21826 		}
21827 	}
21828 	return (mp);
21829 }
21830 
21831 /* MDT info update routine, called when IP notifies us about MDT */
21832 static void
21833 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21834 {
21835 	boolean_t prev_state;
21836 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21837 
21838 	/*
21839 	 * IP is telling us to abort MDT on this connection?  We know
21840 	 * this because the capability is only turned off when IP
21841 	 * encounters some pathological cases, e.g. link-layer change
21842 	 * where the new driver doesn't support MDT, or in situation
21843 	 * where MDT usage on the link-layer has been switched off.
21844 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21845 	 * if the link-layer doesn't support MDT, and if it does, it
21846 	 * will indicate that the feature is to be turned on.
21847 	 */
21848 	prev_state = tcp->tcp_mdt;
21849 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21850 	if (!tcp->tcp_mdt && !first) {
21851 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21852 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21853 		    (void *)tcp->tcp_connp));
21854 	}
21855 
21856 	/*
21857 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21858 	 * so disable MDT otherwise.  The checks are done here
21859 	 * and in tcp_wput_data().
21860 	 */
21861 	if (tcp->tcp_mdt &&
21862 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21863 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21864 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21865 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21866 		tcp->tcp_mdt = B_FALSE;
21867 
21868 	if (tcp->tcp_mdt) {
21869 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21870 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21871 			    "version (%d), expected version is %d",
21872 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21873 			tcp->tcp_mdt = B_FALSE;
21874 			return;
21875 		}
21876 
21877 		/*
21878 		 * We need the driver to be able to handle at least three
21879 		 * spans per packet in order for tcp MDT to be utilized.
21880 		 * The first is for the header portion, while the rest are
21881 		 * needed to handle a packet that straddles across two
21882 		 * virtually non-contiguous buffers; a typical tcp packet
21883 		 * therefore consists of only two spans.  Note that we take
21884 		 * a zero as "don't care".
21885 		 */
21886 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21887 		    mdt_capab->ill_mdt_span_limit < 3) {
21888 			tcp->tcp_mdt = B_FALSE;
21889 			return;
21890 		}
21891 
21892 		/* a zero means driver wants default value */
21893 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21894 		    tcps->tcps_mdt_max_pbufs);
21895 		if (tcp->tcp_mdt_max_pld == 0)
21896 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21897 
21898 		/* ensure 32-bit alignment */
21899 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21900 		    mdt_capab->ill_mdt_hdr_head), 4);
21901 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21902 		    mdt_capab->ill_mdt_hdr_tail), 4);
21903 
21904 		if (!first && !prev_state) {
21905 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21906 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21907 			    (void *)tcp->tcp_connp));
21908 		}
21909 	}
21910 }
21911 
21912 /* Unlink and return any mblk that looks like it contains a LSO info */
21913 static mblk_t *
21914 tcp_lso_info_mp(mblk_t *mp)
21915 {
21916 	mblk_t	*prev_mp;
21917 
21918 	for (;;) {
21919 		prev_mp = mp;
21920 		/* no more to process? */
21921 		if ((mp = mp->b_cont) == NULL)
21922 			break;
21923 
21924 		switch (DB_TYPE(mp)) {
21925 		case M_CTL:
21926 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21927 				continue;
21928 			ASSERT(prev_mp != NULL);
21929 			prev_mp->b_cont = mp->b_cont;
21930 			mp->b_cont = NULL;
21931 			return (mp);
21932 		default:
21933 			break;
21934 		}
21935 	}
21936 
21937 	return (mp);
21938 }
21939 
21940 /* LSO info update routine, called when IP notifies us about LSO */
21941 static void
21942 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21943 {
21944 	tcp_stack_t *tcps = tcp->tcp_tcps;
21945 
21946 	/*
21947 	 * IP is telling us to abort LSO on this connection?  We know
21948 	 * this because the capability is only turned off when IP
21949 	 * encounters some pathological cases, e.g. link-layer change
21950 	 * where the new NIC/driver doesn't support LSO, or in situation
21951 	 * where LSO usage on the link-layer has been switched off.
21952 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21953 	 * if the link-layer doesn't support LSO, and if it does, it
21954 	 * will indicate that the feature is to be turned on.
21955 	 */
21956 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21957 	TCP_STAT(tcps, tcp_lso_enabled);
21958 
21959 	/*
21960 	 * We currently only support LSO on simple TCP/IPv4,
21961 	 * so disable LSO otherwise.  The checks are done here
21962 	 * and in tcp_wput_data().
21963 	 */
21964 	if (tcp->tcp_lso &&
21965 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21966 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21967 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21968 		tcp->tcp_lso = B_FALSE;
21969 		TCP_STAT(tcps, tcp_lso_disabled);
21970 	} else {
21971 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21972 		    lso_capab->ill_lso_max);
21973 	}
21974 }
21975 
21976 static void
21977 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21978 {
21979 	conn_t *connp = tcp->tcp_connp;
21980 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21981 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21982 
21983 	ASSERT(ire != NULL);
21984 
21985 	/*
21986 	 * We may be in the fastpath here, and although we essentially do
21987 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21988 	 * we try to keep things as brief as possible.  After all, these
21989 	 * are only best-effort checks, and we do more thorough ones prior
21990 	 * to calling tcp_send()/tcp_multisend().
21991 	 */
21992 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
21993 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21994 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21995 	    !(ire->ire_flags & RTF_MULTIRT) &&
21996 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
21997 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21998 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21999 			/* Cache the result */
22000 			connp->conn_lso_ok = B_TRUE;
22001 
22002 			ASSERT(ill->ill_lso_capab != NULL);
22003 			if (!ill->ill_lso_capab->ill_lso_on) {
22004 				ill->ill_lso_capab->ill_lso_on = 1;
22005 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22006 				    "LSO for interface %s\n", (void *)connp,
22007 				    ill->ill_name));
22008 			}
22009 			tcp_lso_update(tcp, ill->ill_lso_capab);
22010 		} else if (ipst->ips_ip_multidata_outbound &&
22011 		    ILL_MDT_CAPABLE(ill)) {
22012 			/* Cache the result */
22013 			connp->conn_mdt_ok = B_TRUE;
22014 
22015 			ASSERT(ill->ill_mdt_capab != NULL);
22016 			if (!ill->ill_mdt_capab->ill_mdt_on) {
22017 				ill->ill_mdt_capab->ill_mdt_on = 1;
22018 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22019 				    "MDT for interface %s\n", (void *)connp,
22020 				    ill->ill_name));
22021 			}
22022 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
22023 		}
22024 	}
22025 
22026 	/*
22027 	 * The goal is to reduce the number of generated tcp segments by
22028 	 * setting the maxpsz multiplier to 0; this will have an affect on
22029 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
22030 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
22031 	 * of outbound segments and incoming ACKs, thus allowing for better
22032 	 * network and system performance.  In contrast the legacy behavior
22033 	 * may result in sending less than SMSS size, because the last mblk
22034 	 * for some packets may have more data than needed to make up SMSS,
22035 	 * and the legacy code refused to "split" it.
22036 	 *
22037 	 * We apply the new behavior on following situations:
22038 	 *
22039 	 *   1) Loopback connections,
22040 	 *   2) Connections in which the remote peer is not on local subnet,
22041 	 *   3) Local subnet connections over the bge interface (see below).
22042 	 *
22043 	 * Ideally, we would like this behavior to apply for interfaces other
22044 	 * than bge.  However, doing so would negatively impact drivers which
22045 	 * perform dynamic mapping and unmapping of DMA resources, which are
22046 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
22047 	 * packet will be generated by tcp).  The bge driver does not suffer
22048 	 * from this, as it copies the mblks into pre-mapped buffers, and
22049 	 * therefore does not require more I/O resources than before.
22050 	 *
22051 	 * Otherwise, this behavior is present on all network interfaces when
22052 	 * the destination endpoint is non-local, since reducing the number
22053 	 * of packets in general is good for the network.
22054 	 *
22055 	 * TODO We need to remove this hard-coded conditional for bge once
22056 	 *	a better "self-tuning" mechanism, or a way to comprehend
22057 	 *	the driver transmit strategy is devised.  Until the solution
22058 	 *	is found and well understood, we live with this hack.
22059 	 */
22060 	if (!tcp_static_maxpsz &&
22061 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
22062 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
22063 		/* override the default value */
22064 		tcp->tcp_maxpsz = 0;
22065 
22066 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
22067 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
22068 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
22069 	}
22070 
22071 	/* set the stream head parameters accordingly */
22072 	(void) tcp_maxpsz_set(tcp, B_TRUE);
22073 }
22074 
22075 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
22076 static void
22077 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
22078 {
22079 	uchar_t	fval = *mp->b_rptr;
22080 	mblk_t	*tail;
22081 	queue_t	*q = tcp->tcp_wq;
22082 
22083 	/* TODO: How should flush interact with urgent data? */
22084 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
22085 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
22086 		/*
22087 		 * Flush only data that has not yet been put on the wire.  If
22088 		 * we flush data that we have already transmitted, life, as we
22089 		 * know it, may come to an end.
22090 		 */
22091 		tail = tcp->tcp_xmit_tail;
22092 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
22093 		tcp->tcp_xmit_tail_unsent = 0;
22094 		tcp->tcp_unsent = 0;
22095 		if (tail->b_wptr != tail->b_rptr)
22096 			tail = tail->b_cont;
22097 		if (tail) {
22098 			mblk_t **excess = &tcp->tcp_xmit_head;
22099 			for (;;) {
22100 				mblk_t *mp1 = *excess;
22101 				if (mp1 == tail)
22102 					break;
22103 				tcp->tcp_xmit_tail = mp1;
22104 				tcp->tcp_xmit_last = mp1;
22105 				excess = &mp1->b_cont;
22106 			}
22107 			*excess = NULL;
22108 			tcp_close_mpp(&tail);
22109 			if (tcp->tcp_snd_zcopy_aware)
22110 				tcp_zcopy_notify(tcp);
22111 		}
22112 		/*
22113 		 * We have no unsent data, so unsent must be less than
22114 		 * tcp_xmit_lowater, so re-enable flow.
22115 		 */
22116 		mutex_enter(&tcp->tcp_non_sq_lock);
22117 		if (tcp->tcp_flow_stopped) {
22118 			tcp_clrqfull(tcp);
22119 		}
22120 		mutex_exit(&tcp->tcp_non_sq_lock);
22121 	}
22122 	/*
22123 	 * TODO: you can't just flush these, you have to increase rwnd for one
22124 	 * thing.  For another, how should urgent data interact?
22125 	 */
22126 	if (fval & FLUSHR) {
22127 		*mp->b_rptr = fval & ~FLUSHW;
22128 		/* XXX */
22129 		qreply(q, mp);
22130 		return;
22131 	}
22132 	freemsg(mp);
22133 }
22134 
22135 /*
22136  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
22137  * messages.
22138  */
22139 static void
22140 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
22141 {
22142 	mblk_t	*mp1;
22143 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
22144 	STRUCT_HANDLE(strbuf, sb);
22145 	queue_t *q = tcp->tcp_wq;
22146 	int	error;
22147 	uint_t	addrlen;
22148 
22149 	/* Make sure it is one of ours. */
22150 	switch (iocp->ioc_cmd) {
22151 	case TI_GETMYNAME:
22152 	case TI_GETPEERNAME:
22153 		break;
22154 	default:
22155 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
22156 		return;
22157 	}
22158 	switch (mi_copy_state(q, mp, &mp1)) {
22159 	case -1:
22160 		return;
22161 	case MI_COPY_CASE(MI_COPY_IN, 1):
22162 		break;
22163 	case MI_COPY_CASE(MI_COPY_OUT, 1):
22164 		/* Copy out the strbuf. */
22165 		mi_copyout(q, mp);
22166 		return;
22167 	case MI_COPY_CASE(MI_COPY_OUT, 2):
22168 		/* All done. */
22169 		mi_copy_done(q, mp, 0);
22170 		return;
22171 	default:
22172 		mi_copy_done(q, mp, EPROTO);
22173 		return;
22174 	}
22175 	/* Check alignment of the strbuf */
22176 	if (!OK_32PTR(mp1->b_rptr)) {
22177 		mi_copy_done(q, mp, EINVAL);
22178 		return;
22179 	}
22180 
22181 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
22182 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
22183 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
22184 		mi_copy_done(q, mp, EINVAL);
22185 		return;
22186 	}
22187 
22188 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
22189 	if (mp1 == NULL)
22190 		return;
22191 
22192 	switch (iocp->ioc_cmd) {
22193 	case TI_GETMYNAME:
22194 		error = tcp_getmyname(tcp, (void *)mp1->b_rptr, &addrlen);
22195 		break;
22196 	case TI_GETPEERNAME:
22197 		error = i_tcp_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
22198 		break;
22199 	}
22200 
22201 	if (error != 0) {
22202 		mi_copy_done(q, mp, error);
22203 	} else {
22204 		mp1->b_wptr += addrlen;
22205 		STRUCT_FSET(sb, len, addrlen);
22206 
22207 		/* Copy out the address */
22208 		mi_copyout(q, mp);
22209 	}
22210 }
22211 
22212 static void
22213 tcp_disable_direct_sockfs(tcp_t *tcp)
22214 {
22215 #ifdef	_ILP32
22216 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
22217 #else
22218 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
22219 #endif
22220 	/*
22221 	 * Insert this socket into the acceptor hash.
22222 	 * We might need it for T_CONN_RES message
22223 	 */
22224 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
22225 
22226 	if (tcp->tcp_fused) {
22227 		/*
22228 		 * This is a fused loopback tcp; disable
22229 		 * read-side synchronous streams interface
22230 		 * and drain any queued data.  It is okay
22231 		 * to do this for non-synchronous streams
22232 		 * fused tcp as well.
22233 		 */
22234 		tcp_fuse_disable_pair(tcp, B_FALSE);
22235 	}
22236 	tcp->tcp_issocket = B_FALSE;
22237 	tcp->tcp_sodirect = NULL;
22238 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
22239 }
22240 
22241 /*
22242  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
22243  * messages.
22244  */
22245 /* ARGSUSED */
22246 static void
22247 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
22248 {
22249 	conn_t 	*connp = (conn_t *)arg;
22250 	tcp_t	*tcp = connp->conn_tcp;
22251 	queue_t	*q = tcp->tcp_wq;
22252 	struct iocblk	*iocp;
22253 
22254 	ASSERT(DB_TYPE(mp) == M_IOCTL);
22255 	/*
22256 	 * Try and ASSERT the minimum possible references on the
22257 	 * conn early enough. Since we are executing on write side,
22258 	 * the connection is obviously not detached and that means
22259 	 * there is a ref each for TCP and IP. Since we are behind
22260 	 * the squeue, the minimum references needed are 3. If the
22261 	 * conn is in classifier hash list, there should be an
22262 	 * extra ref for that (we check both the possibilities).
22263 	 */
22264 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22265 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22266 
22267 	iocp = (struct iocblk *)mp->b_rptr;
22268 	switch (iocp->ioc_cmd) {
22269 	case TCP_IOC_DEFAULT_Q:
22270 		/* Wants to be the default wq. */
22271 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
22272 			iocp->ioc_error = EPERM;
22273 			iocp->ioc_count = 0;
22274 			mp->b_datap->db_type = M_IOCACK;
22275 			qreply(q, mp);
22276 			return;
22277 		}
22278 		tcp_def_q_set(tcp, mp);
22279 		return;
22280 	case _SIOCSOCKFALLBACK:
22281 		/*
22282 		 * Either sockmod is about to be popped and the socket
22283 		 * would now be treated as a plain stream, or a module
22284 		 * is about to be pushed so we could no longer use read-
22285 		 * side synchronous streams for fused loopback tcp.
22286 		 * Drain any queued data and disable direct sockfs
22287 		 * interface from now on.
22288 		 */
22289 		if (!tcp->tcp_issocket) {
22290 			DB_TYPE(mp) = M_IOCNAK;
22291 			iocp->ioc_error = EINVAL;
22292 		} else {
22293 			tcp_disable_direct_sockfs(tcp);
22294 			DB_TYPE(mp) = M_IOCACK;
22295 			iocp->ioc_error = 0;
22296 		}
22297 		iocp->ioc_count = 0;
22298 		iocp->ioc_rval = 0;
22299 		qreply(q, mp);
22300 		return;
22301 	}
22302 	CALL_IP_WPUT(connp, q, mp);
22303 }
22304 
22305 /*
22306  * This routine is called by tcp_wput() to handle all TPI requests.
22307  */
22308 /* ARGSUSED */
22309 static void
22310 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22311 {
22312 	conn_t 	*connp = (conn_t *)arg;
22313 	tcp_t	*tcp = connp->conn_tcp;
22314 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22315 	uchar_t *rptr;
22316 	t_scalar_t type;
22317 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
22318 
22319 	/*
22320 	 * Try and ASSERT the minimum possible references on the
22321 	 * conn early enough. Since we are executing on write side,
22322 	 * the connection is obviously not detached and that means
22323 	 * there is a ref each for TCP and IP. Since we are behind
22324 	 * the squeue, the minimum references needed are 3. If the
22325 	 * conn is in classifier hash list, there should be an
22326 	 * extra ref for that (we check both the possibilities).
22327 	 */
22328 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22329 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22330 
22331 	rptr = mp->b_rptr;
22332 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22333 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22334 		type = ((union T_primitives *)rptr)->type;
22335 		if (type == T_EXDATA_REQ) {
22336 			tcp_output_urgent(connp, mp->b_cont, arg2);
22337 			freeb(mp);
22338 		} else if (type != T_DATA_REQ) {
22339 			goto non_urgent_data;
22340 		} else {
22341 			/* TODO: options, flags, ... from user */
22342 			/* Set length to zero for reclamation below */
22343 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22344 			freeb(mp);
22345 		}
22346 		return;
22347 	} else {
22348 		if (tcp->tcp_debug) {
22349 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22350 			    "tcp_wput_proto, dropping one...");
22351 		}
22352 		freemsg(mp);
22353 		return;
22354 	}
22355 
22356 non_urgent_data:
22357 
22358 	switch ((int)tprim->type) {
22359 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22360 		/*
22361 		 * save the kssl_ent_t from the next block, and convert this
22362 		 * back to a normal bind_req.
22363 		 */
22364 		if (mp->b_cont != NULL) {
22365 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22366 
22367 			if (tcp->tcp_kssl_ent != NULL) {
22368 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22369 				    KSSL_NO_PROXY);
22370 				tcp->tcp_kssl_ent = NULL;
22371 			}
22372 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22373 			    sizeof (kssl_ent_t));
22374 			kssl_hold_ent(tcp->tcp_kssl_ent);
22375 			freemsg(mp->b_cont);
22376 			mp->b_cont = NULL;
22377 		}
22378 		tprim->type = T_BIND_REQ;
22379 
22380 	/* FALLTHROUGH */
22381 	case O_T_BIND_REQ:	/* bind request */
22382 	case T_BIND_REQ:	/* new semantics bind request */
22383 		tcp_tpi_bind(tcp, mp);
22384 		break;
22385 	case T_UNBIND_REQ:	/* unbind request */
22386 		tcp_tpi_unbind(tcp, mp);
22387 		break;
22388 	case O_T_CONN_RES:	/* old connection response XXX */
22389 	case T_CONN_RES:	/* connection response */
22390 		tcp_tli_accept(tcp, mp);
22391 		break;
22392 	case T_CONN_REQ:	/* connection request */
22393 		tcp_tpi_connect(tcp, mp);
22394 		break;
22395 	case T_DISCON_REQ:	/* disconnect request */
22396 		tcp_disconnect(tcp, mp);
22397 		break;
22398 	case T_CAPABILITY_REQ:
22399 		tcp_capability_req(tcp, mp);	/* capability request */
22400 		break;
22401 	case T_INFO_REQ:	/* information request */
22402 		tcp_info_req(tcp, mp);
22403 		break;
22404 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22405 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr,
22406 		    &tcp_opt_obj, B_TRUE);
22407 		break;
22408 	case T_OPTMGMT_REQ:
22409 		/*
22410 		 * Note:  no support for snmpcom_req() through new
22411 		 * T_OPTMGMT_REQ. See comments in ip.c
22412 		 */
22413 		/* Only IP is allowed to return meaningful value */
22414 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22415 		    B_TRUE);
22416 		break;
22417 
22418 	case T_UNITDATA_REQ:	/* unitdata request */
22419 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22420 		break;
22421 	case T_ORDREL_REQ:	/* orderly release req */
22422 		freemsg(mp);
22423 
22424 		if (tcp->tcp_fused)
22425 			tcp_unfuse(tcp);
22426 
22427 		if (tcp_xmit_end(tcp) != 0) {
22428 			/*
22429 			 * We were crossing FINs and got a reset from
22430 			 * the other side. Just ignore it.
22431 			 */
22432 			if (tcp->tcp_debug) {
22433 				(void) strlog(TCP_MOD_ID, 0, 1,
22434 				    SL_ERROR|SL_TRACE,
22435 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22436 				    "state %s",
22437 				    tcp_display(tcp, NULL,
22438 				    DISP_ADDR_AND_PORT));
22439 			}
22440 		}
22441 		break;
22442 	case T_ADDR_REQ:
22443 		tcp_addr_req(tcp, mp);
22444 		break;
22445 	default:
22446 		if (tcp->tcp_debug) {
22447 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22448 			    "tcp_wput_proto, bogus TPI msg, type %d",
22449 			    tprim->type);
22450 		}
22451 		/*
22452 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22453 		 * to recover.
22454 		 */
22455 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22456 		break;
22457 	}
22458 }
22459 
22460 /*
22461  * The TCP write service routine should never be called...
22462  */
22463 /* ARGSUSED */
22464 static void
22465 tcp_wsrv(queue_t *q)
22466 {
22467 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22468 
22469 	TCP_STAT(tcps, tcp_wsrv_called);
22470 }
22471 
22472 /* Non overlapping byte exchanger */
22473 static void
22474 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22475 {
22476 	uchar_t	uch;
22477 
22478 	while (len-- > 0) {
22479 		uch = a[len];
22480 		a[len] = b[len];
22481 		b[len] = uch;
22482 	}
22483 }
22484 
22485 /*
22486  * Send out a control packet on the tcp connection specified.  This routine
22487  * is typically called where we need a simple ACK or RST generated.
22488  */
22489 static void
22490 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22491 {
22492 	uchar_t		*rptr;
22493 	tcph_t		*tcph;
22494 	ipha_t		*ipha = NULL;
22495 	ip6_t		*ip6h = NULL;
22496 	uint32_t	sum;
22497 	int		tcp_hdr_len;
22498 	int		tcp_ip_hdr_len;
22499 	mblk_t		*mp;
22500 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22501 
22502 	/*
22503 	 * Save sum for use in source route later.
22504 	 */
22505 	ASSERT(tcp != NULL);
22506 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22507 	tcp_hdr_len = tcp->tcp_hdr_len;
22508 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22509 
22510 	/* If a text string is passed in with the request, pass it to strlog. */
22511 	if (str != NULL && tcp->tcp_debug) {
22512 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22513 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22514 		    str, seq, ack, ctl);
22515 	}
22516 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22517 	    BPRI_MED);
22518 	if (mp == NULL) {
22519 		return;
22520 	}
22521 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22522 	mp->b_rptr = rptr;
22523 	mp->b_wptr = &rptr[tcp_hdr_len];
22524 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22525 
22526 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22527 		ipha = (ipha_t *)rptr;
22528 		ipha->ipha_length = htons(tcp_hdr_len);
22529 	} else {
22530 		ip6h = (ip6_t *)rptr;
22531 		ASSERT(tcp != NULL);
22532 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22533 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22534 	}
22535 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22536 	tcph->th_flags[0] = (uint8_t)ctl;
22537 	if (ctl & TH_RST) {
22538 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22539 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22540 		/*
22541 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22542 		 */
22543 		if (tcp->tcp_snd_ts_ok &&
22544 		    tcp->tcp_state > TCPS_SYN_SENT) {
22545 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22546 			*(mp->b_wptr) = TCPOPT_EOL;
22547 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22548 				ipha->ipha_length = htons(tcp_hdr_len -
22549 				    TCPOPT_REAL_TS_LEN);
22550 			} else {
22551 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22552 				    TCPOPT_REAL_TS_LEN);
22553 			}
22554 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22555 			sum -= TCPOPT_REAL_TS_LEN;
22556 		}
22557 	}
22558 	if (ctl & TH_ACK) {
22559 		if (tcp->tcp_snd_ts_ok) {
22560 			U32_TO_BE32(lbolt,
22561 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22562 			U32_TO_BE32(tcp->tcp_ts_recent,
22563 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22564 		}
22565 
22566 		/* Update the latest receive window size in TCP header. */
22567 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22568 		    tcph->th_win);
22569 		tcp->tcp_rack = ack;
22570 		tcp->tcp_rack_cnt = 0;
22571 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22572 	}
22573 	BUMP_LOCAL(tcp->tcp_obsegs);
22574 	U32_TO_BE32(seq, tcph->th_seq);
22575 	U32_TO_BE32(ack, tcph->th_ack);
22576 	/*
22577 	 * Include the adjustment for a source route if any.
22578 	 */
22579 	sum = (sum >> 16) + (sum & 0xFFFF);
22580 	U16_TO_BE16(sum, tcph->th_sum);
22581 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22582 }
22583 
22584 /*
22585  * If this routine returns B_TRUE, TCP can generate a RST in response
22586  * to a segment.  If it returns B_FALSE, TCP should not respond.
22587  */
22588 static boolean_t
22589 tcp_send_rst_chk(tcp_stack_t *tcps)
22590 {
22591 	clock_t	now;
22592 
22593 	/*
22594 	 * TCP needs to protect itself from generating too many RSTs.
22595 	 * This can be a DoS attack by sending us random segments
22596 	 * soliciting RSTs.
22597 	 *
22598 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22599 	 * in each 1 second interval.  In this way, TCP still generate
22600 	 * RSTs in normal cases but when under attack, the impact is
22601 	 * limited.
22602 	 */
22603 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22604 		now = lbolt;
22605 		/* lbolt can wrap around. */
22606 		if ((tcps->tcps_last_rst_intrvl > now) ||
22607 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22608 		    1*SECONDS)) {
22609 			tcps->tcps_last_rst_intrvl = now;
22610 			tcps->tcps_rst_cnt = 1;
22611 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22612 			return (B_FALSE);
22613 		}
22614 	}
22615 	return (B_TRUE);
22616 }
22617 
22618 /*
22619  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22620  */
22621 static void
22622 tcp_ip_ire_mark_advice(tcp_t *tcp)
22623 {
22624 	mblk_t *mp;
22625 	ipic_t *ipic;
22626 
22627 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22628 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22629 		    &ipic);
22630 	} else {
22631 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22632 		    &ipic);
22633 	}
22634 	if (mp == NULL)
22635 		return;
22636 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22637 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22638 }
22639 
22640 /*
22641  * Return an IP advice ioctl mblk and set ipic to be the pointer
22642  * to the advice structure.
22643  */
22644 static mblk_t *
22645 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22646 {
22647 	struct iocblk *ioc;
22648 	mblk_t *mp, *mp1;
22649 
22650 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22651 	if (mp == NULL)
22652 		return (NULL);
22653 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22654 	*ipic = (ipic_t *)mp->b_rptr;
22655 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22656 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22657 
22658 	bcopy(addr, *ipic + 1, addr_len);
22659 
22660 	(*ipic)->ipic_addr_length = addr_len;
22661 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22662 
22663 	mp1 = mkiocb(IP_IOCTL);
22664 	if (mp1 == NULL) {
22665 		freemsg(mp);
22666 		return (NULL);
22667 	}
22668 	mp1->b_cont = mp;
22669 	ioc = (struct iocblk *)mp1->b_rptr;
22670 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22671 
22672 	return (mp1);
22673 }
22674 
22675 /*
22676  * Generate a reset based on an inbound packet, connp is set by caller
22677  * when RST is in response to an unexpected inbound packet for which
22678  * there is active tcp state in the system.
22679  *
22680  * IPSEC NOTE : Try to send the reply with the same protection as it came
22681  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22682  * the packet will go out at the same level of protection as it came in by
22683  * converting the IPSEC_IN to IPSEC_OUT.
22684  */
22685 static void
22686 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22687     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22688     tcp_stack_t *tcps, conn_t *connp)
22689 {
22690 	ipha_t		*ipha = NULL;
22691 	ip6_t		*ip6h = NULL;
22692 	ushort_t	len;
22693 	tcph_t		*tcph;
22694 	int		i;
22695 	mblk_t		*ipsec_mp;
22696 	boolean_t	mctl_present;
22697 	ipic_t		*ipic;
22698 	ipaddr_t	v4addr;
22699 	in6_addr_t	v6addr;
22700 	int		addr_len;
22701 	void		*addr;
22702 	queue_t		*q = tcps->tcps_g_q;
22703 	tcp_t		*tcp;
22704 	cred_t		*cr;
22705 	mblk_t		*nmp;
22706 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22707 
22708 	if (tcps->tcps_g_q == NULL) {
22709 		/*
22710 		 * For non-zero stackids the default queue isn't created
22711 		 * until the first open, thus there can be a need to send
22712 		 * a reset before then. But we can't do that, hence we just
22713 		 * drop the packet. Later during boot, when the default queue
22714 		 * has been setup, a retransmitted packet from the peer
22715 		 * will result in a reset.
22716 		 */
22717 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22718 		    GLOBAL_NETSTACKID);
22719 		freemsg(mp);
22720 		return;
22721 	}
22722 
22723 	if (connp != NULL)
22724 		tcp = connp->conn_tcp;
22725 	else
22726 		tcp = Q_TO_TCP(q);
22727 
22728 	if (!tcp_send_rst_chk(tcps)) {
22729 		tcps->tcps_rst_unsent++;
22730 		freemsg(mp);
22731 		return;
22732 	}
22733 
22734 	if (mp->b_datap->db_type == M_CTL) {
22735 		ipsec_mp = mp;
22736 		mp = mp->b_cont;
22737 		mctl_present = B_TRUE;
22738 	} else {
22739 		ipsec_mp = mp;
22740 		mctl_present = B_FALSE;
22741 	}
22742 
22743 	if (str && q && tcps->tcps_dbg) {
22744 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22745 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22746 		    "flags 0x%x",
22747 		    str, seq, ack, ctl);
22748 	}
22749 	if (mp->b_datap->db_ref != 1) {
22750 		mblk_t *mp1 = copyb(mp);
22751 		freemsg(mp);
22752 		mp = mp1;
22753 		if (!mp) {
22754 			if (mctl_present)
22755 				freeb(ipsec_mp);
22756 			return;
22757 		} else {
22758 			if (mctl_present) {
22759 				ipsec_mp->b_cont = mp;
22760 			} else {
22761 				ipsec_mp = mp;
22762 			}
22763 		}
22764 	} else if (mp->b_cont) {
22765 		freemsg(mp->b_cont);
22766 		mp->b_cont = NULL;
22767 	}
22768 	/*
22769 	 * We skip reversing source route here.
22770 	 * (for now we replace all IP options with EOL)
22771 	 */
22772 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22773 		ipha = (ipha_t *)mp->b_rptr;
22774 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22775 			mp->b_rptr[i] = IPOPT_EOL;
22776 		/*
22777 		 * Make sure that src address isn't flagrantly invalid.
22778 		 * Not all broadcast address checking for the src address
22779 		 * is possible, since we don't know the netmask of the src
22780 		 * addr.  No check for destination address is done, since
22781 		 * IP will not pass up a packet with a broadcast dest
22782 		 * address to TCP.  Similar checks are done below for IPv6.
22783 		 */
22784 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22785 		    CLASSD(ipha->ipha_src)) {
22786 			freemsg(ipsec_mp);
22787 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22788 			return;
22789 		}
22790 	} else {
22791 		ip6h = (ip6_t *)mp->b_rptr;
22792 
22793 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22794 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22795 			freemsg(ipsec_mp);
22796 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22797 			return;
22798 		}
22799 
22800 		/* Remove any extension headers assuming partial overlay */
22801 		if (ip_hdr_len > IPV6_HDR_LEN) {
22802 			uint8_t *to;
22803 
22804 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22805 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22806 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22807 			ip_hdr_len = IPV6_HDR_LEN;
22808 			ip6h = (ip6_t *)mp->b_rptr;
22809 			ip6h->ip6_nxt = IPPROTO_TCP;
22810 		}
22811 	}
22812 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22813 	if (tcph->th_flags[0] & TH_RST) {
22814 		freemsg(ipsec_mp);
22815 		return;
22816 	}
22817 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22818 	len = ip_hdr_len + sizeof (tcph_t);
22819 	mp->b_wptr = &mp->b_rptr[len];
22820 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22821 		ipha->ipha_length = htons(len);
22822 		/* Swap addresses */
22823 		v4addr = ipha->ipha_src;
22824 		ipha->ipha_src = ipha->ipha_dst;
22825 		ipha->ipha_dst = v4addr;
22826 		ipha->ipha_ident = 0;
22827 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22828 		addr_len = IP_ADDR_LEN;
22829 		addr = &v4addr;
22830 	} else {
22831 		/* No ip6i_t in this case */
22832 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22833 		/* Swap addresses */
22834 		v6addr = ip6h->ip6_src;
22835 		ip6h->ip6_src = ip6h->ip6_dst;
22836 		ip6h->ip6_dst = v6addr;
22837 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22838 		addr_len = IPV6_ADDR_LEN;
22839 		addr = &v6addr;
22840 	}
22841 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22842 	U32_TO_BE32(ack, tcph->th_ack);
22843 	U32_TO_BE32(seq, tcph->th_seq);
22844 	U16_TO_BE16(0, tcph->th_win);
22845 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22846 	tcph->th_flags[0] = (uint8_t)ctl;
22847 	if (ctl & TH_RST) {
22848 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22849 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22850 	}
22851 
22852 	/* IP trusts us to set up labels when required. */
22853 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
22854 	    crgetlabel(cr) != NULL) {
22855 		int err;
22856 
22857 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22858 			err = tsol_check_label(cr, &mp,
22859 			    tcp->tcp_connp->conn_mac_exempt,
22860 			    tcps->tcps_netstack->netstack_ip);
22861 		else
22862 			err = tsol_check_label_v6(cr, &mp,
22863 			    tcp->tcp_connp->conn_mac_exempt,
22864 			    tcps->tcps_netstack->netstack_ip);
22865 		if (mctl_present)
22866 			ipsec_mp->b_cont = mp;
22867 		else
22868 			ipsec_mp = mp;
22869 		if (err != 0) {
22870 			freemsg(ipsec_mp);
22871 			return;
22872 		}
22873 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22874 			ipha = (ipha_t *)mp->b_rptr;
22875 		} else {
22876 			ip6h = (ip6_t *)mp->b_rptr;
22877 		}
22878 	}
22879 
22880 	if (mctl_present) {
22881 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22882 
22883 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22884 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22885 			return;
22886 		}
22887 	}
22888 	if (zoneid == ALL_ZONES)
22889 		zoneid = GLOBAL_ZONEID;
22890 
22891 	/* Add the zoneid so ip_output routes it properly */
22892 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22893 		freemsg(ipsec_mp);
22894 		return;
22895 	}
22896 	ipsec_mp = nmp;
22897 
22898 	/*
22899 	 * NOTE:  one might consider tracing a TCP packet here, but
22900 	 * this function has no active TCP state and no tcp structure
22901 	 * that has a trace buffer.  If we traced here, we would have
22902 	 * to keep a local trace buffer in tcp_record_trace().
22903 	 *
22904 	 * TSol note: The mblk that contains the incoming packet was
22905 	 * reused by tcp_xmit_listener_reset, so it already contains
22906 	 * the right credentials and we don't need to call mblk_setcred.
22907 	 * Also the conn's cred is not right since it is associated
22908 	 * with tcps_g_q.
22909 	 */
22910 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22911 
22912 	/*
22913 	 * Tell IP to mark the IRE used for this destination temporary.
22914 	 * This way, we can limit our exposure to DoS attack because IP
22915 	 * creates an IRE for each destination.  If there are too many,
22916 	 * the time to do any routing lookup will be extremely long.  And
22917 	 * the lookup can be in interrupt context.
22918 	 *
22919 	 * Note that in normal circumstances, this marking should not
22920 	 * affect anything.  It would be nice if only 1 message is
22921 	 * needed to inform IP that the IRE created for this RST should
22922 	 * not be added to the cache table.  But there is currently
22923 	 * not such communication mechanism between TCP and IP.  So
22924 	 * the best we can do now is to send the advice ioctl to IP
22925 	 * to mark the IRE temporary.
22926 	 */
22927 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22928 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22929 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22930 	}
22931 }
22932 
22933 /*
22934  * Initiate closedown sequence on an active connection.  (May be called as
22935  * writer.)  Return value zero for OK return, non-zero for error return.
22936  */
22937 static int
22938 tcp_xmit_end(tcp_t *tcp)
22939 {
22940 	ipic_t	*ipic;
22941 	mblk_t	*mp;
22942 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22943 
22944 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22945 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22946 		/*
22947 		 * Invalid state, only states TCPS_SYN_RCVD,
22948 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22949 		 */
22950 		return (-1);
22951 	}
22952 
22953 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22954 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22955 	/*
22956 	 * If there is nothing more unsent, send the FIN now.
22957 	 * Otherwise, it will go out with the last segment.
22958 	 */
22959 	if (tcp->tcp_unsent == 0) {
22960 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22961 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22962 
22963 		if (mp) {
22964 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22965 		} else {
22966 			/*
22967 			 * Couldn't allocate msg.  Pretend we got it out.
22968 			 * Wait for rexmit timeout.
22969 			 */
22970 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22971 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22972 		}
22973 
22974 		/*
22975 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22976 		 * changed.
22977 		 */
22978 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22979 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22980 		}
22981 	} else {
22982 		/*
22983 		 * If tcp->tcp_cork is set, then the data will not get sent,
22984 		 * so we have to check that and unset it first.
22985 		 */
22986 		if (tcp->tcp_cork)
22987 			tcp->tcp_cork = B_FALSE;
22988 		tcp_wput_data(tcp, NULL, B_FALSE);
22989 	}
22990 
22991 	/*
22992 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22993 	 * is 0, don't update the cache.
22994 	 */
22995 	if (tcps->tcps_rtt_updates == 0 ||
22996 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
22997 		return (0);
22998 
22999 	/*
23000 	 * NOTE: should not update if source routes i.e. if tcp_remote if
23001 	 * different from the destination.
23002 	 */
23003 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23004 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
23005 			return (0);
23006 		}
23007 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
23008 		    &ipic);
23009 	} else {
23010 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
23011 		    &tcp->tcp_ip6h->ip6_dst))) {
23012 			return (0);
23013 		}
23014 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
23015 		    &ipic);
23016 	}
23017 
23018 	/* Record route attributes in the IRE for use by future connections. */
23019 	if (mp == NULL)
23020 		return (0);
23021 
23022 	/*
23023 	 * We do not have a good algorithm to update ssthresh at this time.
23024 	 * So don't do any update.
23025 	 */
23026 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
23027 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
23028 
23029 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23030 
23031 	return (0);
23032 }
23033 
23034 /*
23035  * Generate a "no listener here" RST in response to an "unknown" segment.
23036  * connp is set by caller when RST is in response to an unexpected
23037  * inbound packet for which there is active tcp state in the system.
23038  * Note that we are reusing the incoming mp to construct the outgoing RST.
23039  */
23040 void
23041 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
23042     tcp_stack_t *tcps, conn_t *connp)
23043 {
23044 	uchar_t		*rptr;
23045 	uint32_t	seg_len;
23046 	tcph_t		*tcph;
23047 	uint32_t	seg_seq;
23048 	uint32_t	seg_ack;
23049 	uint_t		flags;
23050 	mblk_t		*ipsec_mp;
23051 	ipha_t 		*ipha;
23052 	ip6_t 		*ip6h;
23053 	boolean_t	mctl_present = B_FALSE;
23054 	boolean_t	check = B_TRUE;
23055 	boolean_t	policy_present;
23056 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
23057 
23058 	TCP_STAT(tcps, tcp_no_listener);
23059 
23060 	ipsec_mp = mp;
23061 
23062 	if (mp->b_datap->db_type == M_CTL) {
23063 		ipsec_in_t *ii;
23064 
23065 		mctl_present = B_TRUE;
23066 		mp = mp->b_cont;
23067 
23068 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23069 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23070 		if (ii->ipsec_in_dont_check) {
23071 			check = B_FALSE;
23072 			if (!ii->ipsec_in_secure) {
23073 				freeb(ipsec_mp);
23074 				mctl_present = B_FALSE;
23075 				ipsec_mp = mp;
23076 			}
23077 		}
23078 	}
23079 
23080 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23081 		policy_present = ipss->ipsec_inbound_v4_policy_present;
23082 		ipha = (ipha_t *)mp->b_rptr;
23083 		ip6h = NULL;
23084 	} else {
23085 		policy_present = ipss->ipsec_inbound_v6_policy_present;
23086 		ipha = NULL;
23087 		ip6h = (ip6_t *)mp->b_rptr;
23088 	}
23089 
23090 	if (check && policy_present) {
23091 		/*
23092 		 * The conn_t parameter is NULL because we already know
23093 		 * nobody's home.
23094 		 */
23095 		ipsec_mp = ipsec_check_global_policy(
23096 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
23097 		    tcps->tcps_netstack);
23098 		if (ipsec_mp == NULL)
23099 			return;
23100 	}
23101 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
23102 		DTRACE_PROBE2(
23103 		    tx__ip__log__error__nolistener__tcp,
23104 		    char *, "Could not reply with RST to mp(1)",
23105 		    mblk_t *, mp);
23106 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
23107 		freemsg(ipsec_mp);
23108 		return;
23109 	}
23110 
23111 	rptr = mp->b_rptr;
23112 
23113 	tcph = (tcph_t *)&rptr[ip_hdr_len];
23114 	seg_seq = BE32_TO_U32(tcph->th_seq);
23115 	seg_ack = BE32_TO_U32(tcph->th_ack);
23116 	flags = tcph->th_flags[0];
23117 
23118 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
23119 	if (flags & TH_RST) {
23120 		freemsg(ipsec_mp);
23121 	} else if (flags & TH_ACK) {
23122 		tcp_xmit_early_reset("no tcp, reset",
23123 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
23124 		    connp);
23125 	} else {
23126 		if (flags & TH_SYN) {
23127 			seg_len++;
23128 		} else {
23129 			/*
23130 			 * Here we violate the RFC.  Note that a normal
23131 			 * TCP will never send a segment without the ACK
23132 			 * flag, except for RST or SYN segment.  This
23133 			 * segment is neither.  Just drop it on the
23134 			 * floor.
23135 			 */
23136 			freemsg(ipsec_mp);
23137 			tcps->tcps_rst_unsent++;
23138 			return;
23139 		}
23140 
23141 		tcp_xmit_early_reset("no tcp, reset/ack",
23142 		    ipsec_mp, 0, seg_seq + seg_len,
23143 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
23144 	}
23145 }
23146 
23147 /*
23148  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
23149  * ip and tcp header ready to pass down to IP.  If the mp passed in is
23150  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
23151  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
23152  * otherwise it will dup partial mblks.)
23153  * Otherwise, an appropriate ACK packet will be generated.  This
23154  * routine is not usually called to send new data for the first time.  It
23155  * is mostly called out of the timer for retransmits, and to generate ACKs.
23156  *
23157  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
23158  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
23159  * of the original mblk chain will be returned in *offset and *end_mp.
23160  */
23161 mblk_t *
23162 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
23163     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
23164     boolean_t rexmit)
23165 {
23166 	int	data_length;
23167 	int32_t	off = 0;
23168 	uint_t	flags;
23169 	mblk_t	*mp1;
23170 	mblk_t	*mp2;
23171 	uchar_t	*rptr;
23172 	tcph_t	*tcph;
23173 	int32_t	num_sack_blk = 0;
23174 	int32_t	sack_opt_len = 0;
23175 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23176 
23177 	/* Allocate for our maximum TCP header + link-level */
23178 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
23179 	    tcps->tcps_wroff_xtra, BPRI_MED);
23180 	if (!mp1)
23181 		return (NULL);
23182 	data_length = 0;
23183 
23184 	/*
23185 	 * Note that tcp_mss has been adjusted to take into account the
23186 	 * timestamp option if applicable.  Because SACK options do not
23187 	 * appear in every TCP segments and they are of variable lengths,
23188 	 * they cannot be included in tcp_mss.  Thus we need to calculate
23189 	 * the actual segment length when we need to send a segment which
23190 	 * includes SACK options.
23191 	 */
23192 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23193 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23194 		    tcp->tcp_num_sack_blk);
23195 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23196 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23197 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
23198 			max_to_send -= sack_opt_len;
23199 	}
23200 
23201 	if (offset != NULL) {
23202 		off = *offset;
23203 		/* We use offset as an indicator that end_mp is not NULL. */
23204 		*end_mp = NULL;
23205 	}
23206 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
23207 		/* This could be faster with cooperation from downstream */
23208 		if (mp2 != mp1 && !sendall &&
23209 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
23210 		    max_to_send)
23211 			/*
23212 			 * Don't send the next mblk since the whole mblk
23213 			 * does not fit.
23214 			 */
23215 			break;
23216 		mp2->b_cont = dupb(mp);
23217 		mp2 = mp2->b_cont;
23218 		if (!mp2) {
23219 			freemsg(mp1);
23220 			return (NULL);
23221 		}
23222 		mp2->b_rptr += off;
23223 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
23224 		    (uintptr_t)INT_MAX);
23225 
23226 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
23227 		if (data_length > max_to_send) {
23228 			mp2->b_wptr -= data_length - max_to_send;
23229 			data_length = max_to_send;
23230 			off = mp2->b_wptr - mp->b_rptr;
23231 			break;
23232 		} else {
23233 			off = 0;
23234 		}
23235 	}
23236 	if (offset != NULL) {
23237 		*offset = off;
23238 		*end_mp = mp;
23239 	}
23240 	if (seg_len != NULL) {
23241 		*seg_len = data_length;
23242 	}
23243 
23244 	/* Update the latest receive window size in TCP header. */
23245 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23246 	    tcp->tcp_tcph->th_win);
23247 
23248 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23249 	mp1->b_rptr = rptr;
23250 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
23251 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23252 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23253 	U32_TO_ABE32(seq, tcph->th_seq);
23254 
23255 	/*
23256 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
23257 	 * that this function was called from tcp_wput_data. Thus, when called
23258 	 * to retransmit data the setting of the PUSH bit may appear some
23259 	 * what random in that it might get set when it should not. This
23260 	 * should not pose any performance issues.
23261 	 */
23262 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
23263 	    tcp->tcp_unsent == data_length)) {
23264 		flags = TH_ACK | TH_PUSH;
23265 	} else {
23266 		flags = TH_ACK;
23267 	}
23268 
23269 	if (tcp->tcp_ecn_ok) {
23270 		if (tcp->tcp_ecn_echo_on)
23271 			flags |= TH_ECE;
23272 
23273 		/*
23274 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
23275 		 * There is no TCP flow control for non-data segments, and
23276 		 * only data segment is transmitted reliably.
23277 		 */
23278 		if (data_length > 0 && !rexmit) {
23279 			SET_ECT(tcp, rptr);
23280 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23281 				flags |= TH_CWR;
23282 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23283 			}
23284 		}
23285 	}
23286 
23287 	if (tcp->tcp_valid_bits) {
23288 		uint32_t u1;
23289 
23290 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23291 		    seq == tcp->tcp_iss) {
23292 			uchar_t	*wptr;
23293 
23294 			/*
23295 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23296 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23297 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23298 			 * our SYN is not ack'ed but the app closes this
23299 			 * TCP connection.
23300 			 */
23301 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23302 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23303 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23304 
23305 			/*
23306 			 * Tack on the MSS option.  It is always needed
23307 			 * for both active and passive open.
23308 			 *
23309 			 * MSS option value should be interface MTU - MIN
23310 			 * TCP/IP header according to RFC 793 as it means
23311 			 * the maximum segment size TCP can receive.  But
23312 			 * to get around some broken middle boxes/end hosts
23313 			 * out there, we allow the option value to be the
23314 			 * same as the MSS option size on the peer side.
23315 			 * In this way, the other side will not send
23316 			 * anything larger than they can receive.
23317 			 *
23318 			 * Note that for SYN_SENT state, the ndd param
23319 			 * tcp_use_smss_as_mss_opt has no effect as we
23320 			 * don't know the peer's MSS option value. So
23321 			 * the only case we need to take care of is in
23322 			 * SYN_RCVD state, which is done later.
23323 			 */
23324 			wptr = mp1->b_wptr;
23325 			wptr[0] = TCPOPT_MAXSEG;
23326 			wptr[1] = TCPOPT_MAXSEG_LEN;
23327 			wptr += 2;
23328 			u1 = tcp->tcp_if_mtu -
23329 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23330 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23331 			    TCP_MIN_HEADER_LENGTH;
23332 			U16_TO_BE16(u1, wptr);
23333 			mp1->b_wptr = wptr + 2;
23334 			/* Update the offset to cover the additional word */
23335 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23336 
23337 			/*
23338 			 * Note that the following way of filling in
23339 			 * TCP options are not optimal.  Some NOPs can
23340 			 * be saved.  But there is no need at this time
23341 			 * to optimize it.  When it is needed, we will
23342 			 * do it.
23343 			 */
23344 			switch (tcp->tcp_state) {
23345 			case TCPS_SYN_SENT:
23346 				flags = TH_SYN;
23347 
23348 				if (tcp->tcp_snd_ts_ok) {
23349 					uint32_t llbolt = (uint32_t)lbolt;
23350 
23351 					wptr = mp1->b_wptr;
23352 					wptr[0] = TCPOPT_NOP;
23353 					wptr[1] = TCPOPT_NOP;
23354 					wptr[2] = TCPOPT_TSTAMP;
23355 					wptr[3] = TCPOPT_TSTAMP_LEN;
23356 					wptr += 4;
23357 					U32_TO_BE32(llbolt, wptr);
23358 					wptr += 4;
23359 					ASSERT(tcp->tcp_ts_recent == 0);
23360 					U32_TO_BE32(0L, wptr);
23361 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23362 					tcph->th_offset_and_rsrvd[0] +=
23363 					    (3 << 4);
23364 				}
23365 
23366 				/*
23367 				 * Set up all the bits to tell other side
23368 				 * we are ECN capable.
23369 				 */
23370 				if (tcp->tcp_ecn_ok) {
23371 					flags |= (TH_ECE | TH_CWR);
23372 				}
23373 				break;
23374 			case TCPS_SYN_RCVD:
23375 				flags |= TH_SYN;
23376 
23377 				/*
23378 				 * Reset the MSS option value to be SMSS
23379 				 * We should probably add back the bytes
23380 				 * for timestamp option and IPsec.  We
23381 				 * don't do that as this is a workaround
23382 				 * for broken middle boxes/end hosts, it
23383 				 * is better for us to be more cautious.
23384 				 * They may not take these things into
23385 				 * account in their SMSS calculation.  Thus
23386 				 * the peer's calculated SMSS may be smaller
23387 				 * than what it can be.  This should be OK.
23388 				 */
23389 				if (tcps->tcps_use_smss_as_mss_opt) {
23390 					u1 = tcp->tcp_mss;
23391 					U16_TO_BE16(u1, wptr);
23392 				}
23393 
23394 				/*
23395 				 * If the other side is ECN capable, reply
23396 				 * that we are also ECN capable.
23397 				 */
23398 				if (tcp->tcp_ecn_ok)
23399 					flags |= TH_ECE;
23400 				break;
23401 			default:
23402 				/*
23403 				 * The above ASSERT() makes sure that this
23404 				 * must be FIN-WAIT-1 state.  Our SYN has
23405 				 * not been ack'ed so retransmit it.
23406 				 */
23407 				flags |= TH_SYN;
23408 				break;
23409 			}
23410 
23411 			if (tcp->tcp_snd_ws_ok) {
23412 				wptr = mp1->b_wptr;
23413 				wptr[0] =  TCPOPT_NOP;
23414 				wptr[1] =  TCPOPT_WSCALE;
23415 				wptr[2] =  TCPOPT_WS_LEN;
23416 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23417 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23418 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23419 			}
23420 
23421 			if (tcp->tcp_snd_sack_ok) {
23422 				wptr = mp1->b_wptr;
23423 				wptr[0] = TCPOPT_NOP;
23424 				wptr[1] = TCPOPT_NOP;
23425 				wptr[2] = TCPOPT_SACK_PERMITTED;
23426 				wptr[3] = TCPOPT_SACK_OK_LEN;
23427 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23428 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23429 			}
23430 
23431 			/* allocb() of adequate mblk assures space */
23432 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23433 			    (uintptr_t)INT_MAX);
23434 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23435 			/*
23436 			 * Get IP set to checksum on our behalf
23437 			 * Include the adjustment for a source route if any.
23438 			 */
23439 			u1 += tcp->tcp_sum;
23440 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23441 			U16_TO_BE16(u1, tcph->th_sum);
23442 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23443 		}
23444 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23445 		    (seq + data_length) == tcp->tcp_fss) {
23446 			if (!tcp->tcp_fin_acked) {
23447 				flags |= TH_FIN;
23448 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23449 			}
23450 			if (!tcp->tcp_fin_sent) {
23451 				tcp->tcp_fin_sent = B_TRUE;
23452 				switch (tcp->tcp_state) {
23453 				case TCPS_SYN_RCVD:
23454 				case TCPS_ESTABLISHED:
23455 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23456 					break;
23457 				case TCPS_CLOSE_WAIT:
23458 					tcp->tcp_state = TCPS_LAST_ACK;
23459 					break;
23460 				}
23461 				if (tcp->tcp_suna == tcp->tcp_snxt)
23462 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23463 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23464 			}
23465 		}
23466 		/*
23467 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23468 		 * is smaller than seq, u1 will become a very huge value.
23469 		 * So the comparison will fail.  Also note that tcp_urp
23470 		 * should be positive, see RFC 793 page 17.
23471 		 */
23472 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23473 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23474 		    u1 < (uint32_t)(64 * 1024)) {
23475 			flags |= TH_URG;
23476 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23477 			U32_TO_ABE16(u1, tcph->th_urp);
23478 		}
23479 	}
23480 	tcph->th_flags[0] = (uchar_t)flags;
23481 	tcp->tcp_rack = tcp->tcp_rnxt;
23482 	tcp->tcp_rack_cnt = 0;
23483 
23484 	if (tcp->tcp_snd_ts_ok) {
23485 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23486 			uint32_t llbolt = (uint32_t)lbolt;
23487 
23488 			U32_TO_BE32(llbolt,
23489 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23490 			U32_TO_BE32(tcp->tcp_ts_recent,
23491 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23492 		}
23493 	}
23494 
23495 	if (num_sack_blk > 0) {
23496 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23497 		sack_blk_t *tmp;
23498 		int32_t	i;
23499 
23500 		wptr[0] = TCPOPT_NOP;
23501 		wptr[1] = TCPOPT_NOP;
23502 		wptr[2] = TCPOPT_SACK;
23503 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23504 		    sizeof (sack_blk_t);
23505 		wptr += TCPOPT_REAL_SACK_LEN;
23506 
23507 		tmp = tcp->tcp_sack_list;
23508 		for (i = 0; i < num_sack_blk; i++) {
23509 			U32_TO_BE32(tmp[i].begin, wptr);
23510 			wptr += sizeof (tcp_seq);
23511 			U32_TO_BE32(tmp[i].end, wptr);
23512 			wptr += sizeof (tcp_seq);
23513 		}
23514 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23515 	}
23516 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23517 	data_length += (int)(mp1->b_wptr - rptr);
23518 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23519 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23520 	} else {
23521 		ip6_t *ip6 = (ip6_t *)(rptr +
23522 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23523 		    sizeof (ip6i_t) : 0));
23524 
23525 		ip6->ip6_plen = htons(data_length -
23526 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23527 	}
23528 
23529 	/*
23530 	 * Prime pump for IP
23531 	 * Include the adjustment for a source route if any.
23532 	 */
23533 	data_length -= tcp->tcp_ip_hdr_len;
23534 	data_length += tcp->tcp_sum;
23535 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23536 	U16_TO_ABE16(data_length, tcph->th_sum);
23537 	if (tcp->tcp_ip_forward_progress) {
23538 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23539 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23540 		tcp->tcp_ip_forward_progress = B_FALSE;
23541 	}
23542 	return (mp1);
23543 }
23544 
23545 /* This function handles the push timeout. */
23546 void
23547 tcp_push_timer(void *arg)
23548 {
23549 	conn_t	*connp = (conn_t *)arg;
23550 	tcp_t *tcp = connp->conn_tcp;
23551 	uint_t		flags;
23552 	sodirect_t	*sodp;
23553 
23554 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
23555 
23556 	ASSERT(tcp->tcp_listener == NULL);
23557 
23558 	ASSERT(!IPCL_IS_NONSTR(connp));
23559 
23560 	/*
23561 	 * We need to plug synchronous streams during our drain to prevent
23562 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23563 	 */
23564 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23565 	tcp->tcp_push_tid = 0;
23566 
23567 	SOD_PTR_ENTER(tcp, sodp);
23568 	if (sodp != NULL) {
23569 		flags = tcp_rcv_sod_wakeup(tcp, sodp);
23570 		/* sod_wakeup() does the mutex_exit() */
23571 	} else if (tcp->tcp_rcv_list != NULL) {
23572 		flags = tcp_rcv_drain(tcp);
23573 	}
23574 	if (flags == TH_ACK_NEEDED)
23575 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23576 
23577 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23578 }
23579 
23580 /*
23581  * This function handles delayed ACK timeout.
23582  */
23583 static void
23584 tcp_ack_timer(void *arg)
23585 {
23586 	conn_t	*connp = (conn_t *)arg;
23587 	tcp_t *tcp = connp->conn_tcp;
23588 	mblk_t *mp;
23589 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23590 
23591 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23592 
23593 	tcp->tcp_ack_tid = 0;
23594 
23595 	if (tcp->tcp_fused)
23596 		return;
23597 
23598 	/*
23599 	 * Do not send ACK if there is no outstanding unack'ed data.
23600 	 */
23601 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23602 		return;
23603 	}
23604 
23605 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23606 		/*
23607 		 * Make sure we don't allow deferred ACKs to result in
23608 		 * timer-based ACKing.  If we have held off an ACK
23609 		 * when there was more than an mss here, and the timer
23610 		 * goes off, we have to worry about the possibility
23611 		 * that the sender isn't doing slow-start, or is out
23612 		 * of step with us for some other reason.  We fall
23613 		 * permanently back in the direction of
23614 		 * ACK-every-other-packet as suggested in RFC 1122.
23615 		 */
23616 		if (tcp->tcp_rack_abs_max > 2)
23617 			tcp->tcp_rack_abs_max--;
23618 		tcp->tcp_rack_cur_max = 2;
23619 	}
23620 	mp = tcp_ack_mp(tcp);
23621 
23622 	if (mp != NULL) {
23623 		BUMP_LOCAL(tcp->tcp_obsegs);
23624 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23625 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23626 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23627 	}
23628 }
23629 
23630 
23631 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23632 static mblk_t *
23633 tcp_ack_mp(tcp_t *tcp)
23634 {
23635 	uint32_t	seq_no;
23636 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23637 
23638 	/*
23639 	 * There are a few cases to be considered while setting the sequence no.
23640 	 * Essentially, we can come here while processing an unacceptable pkt
23641 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23642 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23643 	 * If we are here for a zero window probe, stick with suna. In all
23644 	 * other cases, we check if suna + swnd encompasses snxt and set
23645 	 * the sequence number to snxt, if so. If snxt falls outside the
23646 	 * window (the receiver probably shrunk its window), we will go with
23647 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23648 	 * receiver.
23649 	 */
23650 	if (tcp->tcp_zero_win_probe) {
23651 		seq_no = tcp->tcp_suna;
23652 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23653 		ASSERT(tcp->tcp_swnd == 0);
23654 		seq_no = tcp->tcp_snxt;
23655 	} else {
23656 		seq_no = SEQ_GT(tcp->tcp_snxt,
23657 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23658 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23659 	}
23660 
23661 	if (tcp->tcp_valid_bits) {
23662 		/*
23663 		 * For the complex case where we have to send some
23664 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23665 		 */
23666 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23667 		    NULL, B_FALSE));
23668 	} else {
23669 		/* Generate a simple ACK */
23670 		int	data_length;
23671 		uchar_t	*rptr;
23672 		tcph_t	*tcph;
23673 		mblk_t	*mp1;
23674 		int32_t	tcp_hdr_len;
23675 		int32_t	tcp_tcp_hdr_len;
23676 		int32_t	num_sack_blk = 0;
23677 		int32_t sack_opt_len;
23678 
23679 		/*
23680 		 * Allocate space for TCP + IP headers
23681 		 * and link-level header
23682 		 */
23683 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23684 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23685 			    tcp->tcp_num_sack_blk);
23686 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23687 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23688 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23689 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23690 		} else {
23691 			tcp_hdr_len = tcp->tcp_hdr_len;
23692 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23693 		}
23694 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23695 		if (!mp1)
23696 			return (NULL);
23697 
23698 		/* Update the latest receive window size in TCP header. */
23699 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23700 		    tcp->tcp_tcph->th_win);
23701 		/* copy in prototype TCP + IP header */
23702 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23703 		mp1->b_rptr = rptr;
23704 		mp1->b_wptr = rptr + tcp_hdr_len;
23705 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23706 
23707 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23708 
23709 		/* Set the TCP sequence number. */
23710 		U32_TO_ABE32(seq_no, tcph->th_seq);
23711 
23712 		/* Set up the TCP flag field. */
23713 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23714 		if (tcp->tcp_ecn_echo_on)
23715 			tcph->th_flags[0] |= TH_ECE;
23716 
23717 		tcp->tcp_rack = tcp->tcp_rnxt;
23718 		tcp->tcp_rack_cnt = 0;
23719 
23720 		/* fill in timestamp option if in use */
23721 		if (tcp->tcp_snd_ts_ok) {
23722 			uint32_t llbolt = (uint32_t)lbolt;
23723 
23724 			U32_TO_BE32(llbolt,
23725 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23726 			U32_TO_BE32(tcp->tcp_ts_recent,
23727 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23728 		}
23729 
23730 		/* Fill in SACK options */
23731 		if (num_sack_blk > 0) {
23732 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23733 			sack_blk_t *tmp;
23734 			int32_t	i;
23735 
23736 			wptr[0] = TCPOPT_NOP;
23737 			wptr[1] = TCPOPT_NOP;
23738 			wptr[2] = TCPOPT_SACK;
23739 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23740 			    sizeof (sack_blk_t);
23741 			wptr += TCPOPT_REAL_SACK_LEN;
23742 
23743 			tmp = tcp->tcp_sack_list;
23744 			for (i = 0; i < num_sack_blk; i++) {
23745 				U32_TO_BE32(tmp[i].begin, wptr);
23746 				wptr += sizeof (tcp_seq);
23747 				U32_TO_BE32(tmp[i].end, wptr);
23748 				wptr += sizeof (tcp_seq);
23749 			}
23750 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23751 			    << 4);
23752 		}
23753 
23754 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23755 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23756 		} else {
23757 			/* Check for ip6i_t header in sticky hdrs */
23758 			ip6_t *ip6 = (ip6_t *)(rptr +
23759 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23760 			    sizeof (ip6i_t) : 0));
23761 
23762 			ip6->ip6_plen = htons(tcp_hdr_len -
23763 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23764 		}
23765 
23766 		/*
23767 		 * Prime pump for checksum calculation in IP.  Include the
23768 		 * adjustment for a source route if any.
23769 		 */
23770 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23771 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23772 		U16_TO_ABE16(data_length, tcph->th_sum);
23773 
23774 		if (tcp->tcp_ip_forward_progress) {
23775 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23776 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23777 			tcp->tcp_ip_forward_progress = B_FALSE;
23778 		}
23779 		return (mp1);
23780 	}
23781 }
23782 
23783 /*
23784  * Hash list insertion routine for tcp_t structures. Each hash bucket
23785  * contains a list of tcp_t entries, and each entry is bound to a unique
23786  * port. If there are multiple tcp_t's that are bound to the same port, then
23787  * one of them will be linked into the hash bucket list, and the rest will
23788  * hang off of that one entry. For each port, entries bound to a specific IP
23789  * address will be inserted before those those bound to INADDR_ANY.
23790  */
23791 static void
23792 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23793 {
23794 	tcp_t	**tcpp;
23795 	tcp_t	*tcpnext;
23796 	tcp_t	*tcphash;
23797 
23798 	if (tcp->tcp_ptpbhn != NULL) {
23799 		ASSERT(!caller_holds_lock);
23800 		tcp_bind_hash_remove(tcp);
23801 	}
23802 	tcpp = &tbf->tf_tcp;
23803 	if (!caller_holds_lock) {
23804 		mutex_enter(&tbf->tf_lock);
23805 	} else {
23806 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23807 	}
23808 	tcphash = tcpp[0];
23809 	tcpnext = NULL;
23810 	if (tcphash != NULL) {
23811 		/* Look for an entry using the same port */
23812 		while ((tcphash = tcpp[0]) != NULL &&
23813 		    tcp->tcp_lport != tcphash->tcp_lport)
23814 			tcpp = &(tcphash->tcp_bind_hash);
23815 
23816 		/* The port was not found, just add to the end */
23817 		if (tcphash == NULL)
23818 			goto insert;
23819 
23820 		/*
23821 		 * OK, there already exists an entry bound to the
23822 		 * same port.
23823 		 *
23824 		 * If the new tcp bound to the INADDR_ANY address
23825 		 * and the first one in the list is not bound to
23826 		 * INADDR_ANY we skip all entries until we find the
23827 		 * first one bound to INADDR_ANY.
23828 		 * This makes sure that applications binding to a
23829 		 * specific address get preference over those binding to
23830 		 * INADDR_ANY.
23831 		 */
23832 		tcpnext = tcphash;
23833 		tcphash = NULL;
23834 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23835 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23836 			while ((tcpnext = tcpp[0]) != NULL &&
23837 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23838 				tcpp = &(tcpnext->tcp_bind_hash_port);
23839 
23840 			if (tcpnext) {
23841 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23842 				tcphash = tcpnext->tcp_bind_hash;
23843 				if (tcphash != NULL) {
23844 					tcphash->tcp_ptpbhn =
23845 					    &(tcp->tcp_bind_hash);
23846 					tcpnext->tcp_bind_hash = NULL;
23847 				}
23848 			}
23849 		} else {
23850 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23851 			tcphash = tcpnext->tcp_bind_hash;
23852 			if (tcphash != NULL) {
23853 				tcphash->tcp_ptpbhn =
23854 				    &(tcp->tcp_bind_hash);
23855 				tcpnext->tcp_bind_hash = NULL;
23856 			}
23857 		}
23858 	}
23859 insert:
23860 	tcp->tcp_bind_hash_port = tcpnext;
23861 	tcp->tcp_bind_hash = tcphash;
23862 	tcp->tcp_ptpbhn = tcpp;
23863 	tcpp[0] = tcp;
23864 	if (!caller_holds_lock)
23865 		mutex_exit(&tbf->tf_lock);
23866 }
23867 
23868 /*
23869  * Hash list removal routine for tcp_t structures.
23870  */
23871 static void
23872 tcp_bind_hash_remove(tcp_t *tcp)
23873 {
23874 	tcp_t	*tcpnext;
23875 	kmutex_t *lockp;
23876 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23877 
23878 	if (tcp->tcp_ptpbhn == NULL)
23879 		return;
23880 
23881 	/*
23882 	 * Extract the lock pointer in case there are concurrent
23883 	 * hash_remove's for this instance.
23884 	 */
23885 	ASSERT(tcp->tcp_lport != 0);
23886 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23887 
23888 	ASSERT(lockp != NULL);
23889 	mutex_enter(lockp);
23890 	if (tcp->tcp_ptpbhn) {
23891 		tcpnext = tcp->tcp_bind_hash_port;
23892 		if (tcpnext != NULL) {
23893 			tcp->tcp_bind_hash_port = NULL;
23894 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23895 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
23896 			if (tcpnext->tcp_bind_hash != NULL) {
23897 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
23898 				    &(tcpnext->tcp_bind_hash);
23899 				tcp->tcp_bind_hash = NULL;
23900 			}
23901 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
23902 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23903 			tcp->tcp_bind_hash = NULL;
23904 		}
23905 		*tcp->tcp_ptpbhn = tcpnext;
23906 		tcp->tcp_ptpbhn = NULL;
23907 	}
23908 	mutex_exit(lockp);
23909 }
23910 
23911 
23912 /*
23913  * Hash list lookup routine for tcp_t structures.
23914  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23915  */
23916 static tcp_t *
23917 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23918 {
23919 	tf_t	*tf;
23920 	tcp_t	*tcp;
23921 
23922 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23923 	mutex_enter(&tf->tf_lock);
23924 	for (tcp = tf->tf_tcp; tcp != NULL;
23925 	    tcp = tcp->tcp_acceptor_hash) {
23926 		if (tcp->tcp_acceptor_id == id) {
23927 			CONN_INC_REF(tcp->tcp_connp);
23928 			mutex_exit(&tf->tf_lock);
23929 			return (tcp);
23930 		}
23931 	}
23932 	mutex_exit(&tf->tf_lock);
23933 	return (NULL);
23934 }
23935 
23936 
23937 /*
23938  * Hash list insertion routine for tcp_t structures.
23939  */
23940 void
23941 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23942 {
23943 	tf_t	*tf;
23944 	tcp_t	**tcpp;
23945 	tcp_t	*tcpnext;
23946 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23947 
23948 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23949 
23950 	if (tcp->tcp_ptpahn != NULL)
23951 		tcp_acceptor_hash_remove(tcp);
23952 	tcpp = &tf->tf_tcp;
23953 	mutex_enter(&tf->tf_lock);
23954 	tcpnext = tcpp[0];
23955 	if (tcpnext)
23956 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23957 	tcp->tcp_acceptor_hash = tcpnext;
23958 	tcp->tcp_ptpahn = tcpp;
23959 	tcpp[0] = tcp;
23960 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23961 	mutex_exit(&tf->tf_lock);
23962 }
23963 
23964 /*
23965  * Hash list removal routine for tcp_t structures.
23966  */
23967 static void
23968 tcp_acceptor_hash_remove(tcp_t *tcp)
23969 {
23970 	tcp_t	*tcpnext;
23971 	kmutex_t *lockp;
23972 
23973 	/*
23974 	 * Extract the lock pointer in case there are concurrent
23975 	 * hash_remove's for this instance.
23976 	 */
23977 	lockp = tcp->tcp_acceptor_lockp;
23978 
23979 	if (tcp->tcp_ptpahn == NULL)
23980 		return;
23981 
23982 	ASSERT(lockp != NULL);
23983 	mutex_enter(lockp);
23984 	if (tcp->tcp_ptpahn) {
23985 		tcpnext = tcp->tcp_acceptor_hash;
23986 		if (tcpnext) {
23987 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23988 			tcp->tcp_acceptor_hash = NULL;
23989 		}
23990 		*tcp->tcp_ptpahn = tcpnext;
23991 		tcp->tcp_ptpahn = NULL;
23992 	}
23993 	mutex_exit(lockp);
23994 	tcp->tcp_acceptor_lockp = NULL;
23995 }
23996 
23997 /* Data for fast netmask macro used by tcp_hsp_lookup */
23998 
23999 static ipaddr_t netmasks[] = {
24000 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24001 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24002 };
24003 
24004 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24005 
24006 /*
24007  * XXX This routine should go away and instead we should use the metrics
24008  * associated with the routes to determine the default sndspace and rcvspace.
24009  */
24010 static tcp_hsp_t *
24011 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24012 {
24013 	tcp_hsp_t *hsp = NULL;
24014 
24015 	/* Quick check without acquiring the lock. */
24016 	if (tcps->tcps_hsp_hash == NULL)
24017 		return (NULL);
24018 
24019 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24020 
24021 	/* This routine finds the best-matching HSP for address addr. */
24022 
24023 	if (tcps->tcps_hsp_hash) {
24024 		int i;
24025 		ipaddr_t srchaddr;
24026 		tcp_hsp_t *hsp_net;
24027 
24028 		/* We do three passes: host, network, and subnet. */
24029 
24030 		srchaddr = addr;
24031 
24032 		for (i = 1; i <= 3; i++) {
24033 			/* Look for exact match on srchaddr */
24034 
24035 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24036 			while (hsp) {
24037 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24038 				    hsp->tcp_hsp_addr == srchaddr)
24039 					break;
24040 				hsp = hsp->tcp_hsp_next;
24041 			}
24042 			ASSERT(hsp == NULL ||
24043 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24044 
24045 			/*
24046 			 * If this is the first pass:
24047 			 *   If we found a match, great, return it.
24048 			 *   If not, search for the network on the second pass.
24049 			 */
24050 
24051 			if (i == 1)
24052 				if (hsp)
24053 					break;
24054 				else
24055 				{
24056 					srchaddr = addr & netmask(addr);
24057 					continue;
24058 				}
24059 
24060 			/*
24061 			 * If this is the second pass:
24062 			 *   If we found a match, but there's a subnet mask,
24063 			 *    save the match but try again using the subnet
24064 			 *    mask on the third pass.
24065 			 *   Otherwise, return whatever we found.
24066 			 */
24067 
24068 			if (i == 2) {
24069 				if (hsp && hsp->tcp_hsp_subnet) {
24070 					hsp_net = hsp;
24071 					srchaddr = addr & hsp->tcp_hsp_subnet;
24072 					continue;
24073 				} else {
24074 					break;
24075 				}
24076 			}
24077 
24078 			/*
24079 			 * This must be the third pass.  If we didn't find
24080 			 * anything, return the saved network HSP instead.
24081 			 */
24082 
24083 			if (!hsp)
24084 				hsp = hsp_net;
24085 		}
24086 	}
24087 
24088 	rw_exit(&tcps->tcps_hsp_lock);
24089 	return (hsp);
24090 }
24091 
24092 /*
24093  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24094  * match lookup.
24095  */
24096 static tcp_hsp_t *
24097 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
24098 {
24099 	tcp_hsp_t *hsp = NULL;
24100 
24101 	/* Quick check without acquiring the lock. */
24102 	if (tcps->tcps_hsp_hash == NULL)
24103 		return (NULL);
24104 
24105 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24106 
24107 	/* This routine finds the best-matching HSP for address addr. */
24108 
24109 	if (tcps->tcps_hsp_hash) {
24110 		int i;
24111 		in6_addr_t v6srchaddr;
24112 		tcp_hsp_t *hsp_net;
24113 
24114 		/* We do three passes: host, network, and subnet. */
24115 
24116 		v6srchaddr = *v6addr;
24117 
24118 		for (i = 1; i <= 3; i++) {
24119 			/* Look for exact match on srchaddr */
24120 
24121 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
24122 			    V4_PART_OF_V6(v6srchaddr))];
24123 			while (hsp) {
24124 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24125 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24126 				    &v6srchaddr))
24127 					break;
24128 				hsp = hsp->tcp_hsp_next;
24129 			}
24130 
24131 			/*
24132 			 * If this is the first pass:
24133 			 *   If we found a match, great, return it.
24134 			 *   If not, search for the network on the second pass.
24135 			 */
24136 
24137 			if (i == 1)
24138 				if (hsp)
24139 					break;
24140 				else {
24141 					/* Assume a 64 bit mask */
24142 					v6srchaddr.s6_addr32[0] =
24143 					    v6addr->s6_addr32[0];
24144 					v6srchaddr.s6_addr32[1] =
24145 					    v6addr->s6_addr32[1];
24146 					v6srchaddr.s6_addr32[2] = 0;
24147 					v6srchaddr.s6_addr32[3] = 0;
24148 					continue;
24149 				}
24150 
24151 			/*
24152 			 * If this is the second pass:
24153 			 *   If we found a match, but there's a subnet mask,
24154 			 *    save the match but try again using the subnet
24155 			 *    mask on the third pass.
24156 			 *   Otherwise, return whatever we found.
24157 			 */
24158 
24159 			if (i == 2) {
24160 				ASSERT(hsp == NULL ||
24161 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24162 				if (hsp &&
24163 				    !IN6_IS_ADDR_UNSPECIFIED(
24164 				    &hsp->tcp_hsp_subnet_v6)) {
24165 					hsp_net = hsp;
24166 					V6_MASK_COPY(*v6addr,
24167 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24168 					continue;
24169 				} else {
24170 					break;
24171 				}
24172 			}
24173 
24174 			/*
24175 			 * This must be the third pass.  If we didn't find
24176 			 * anything, return the saved network HSP instead.
24177 			 */
24178 
24179 			if (!hsp)
24180 				hsp = hsp_net;
24181 		}
24182 	}
24183 
24184 	rw_exit(&tcps->tcps_hsp_lock);
24185 	return (hsp);
24186 }
24187 
24188 /*
24189  * Type three generator adapted from the random() function in 4.4 BSD:
24190  */
24191 
24192 /*
24193  * Copyright (c) 1983, 1993
24194  *	The Regents of the University of California.  All rights reserved.
24195  *
24196  * Redistribution and use in source and binary forms, with or without
24197  * modification, are permitted provided that the following conditions
24198  * are met:
24199  * 1. Redistributions of source code must retain the above copyright
24200  *    notice, this list of conditions and the following disclaimer.
24201  * 2. Redistributions in binary form must reproduce the above copyright
24202  *    notice, this list of conditions and the following disclaimer in the
24203  *    documentation and/or other materials provided with the distribution.
24204  * 3. All advertising materials mentioning features or use of this software
24205  *    must display the following acknowledgement:
24206  *	This product includes software developed by the University of
24207  *	California, Berkeley and its contributors.
24208  * 4. Neither the name of the University nor the names of its contributors
24209  *    may be used to endorse or promote products derived from this software
24210  *    without specific prior written permission.
24211  *
24212  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24213  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24214  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24215  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24216  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24217  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24218  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24219  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24220  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24221  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24222  * SUCH DAMAGE.
24223  */
24224 
24225 /* Type 3 -- x**31 + x**3 + 1 */
24226 #define	DEG_3		31
24227 #define	SEP_3		3
24228 
24229 
24230 /* Protected by tcp_random_lock */
24231 static int tcp_randtbl[DEG_3 + 1];
24232 
24233 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24234 static int *tcp_random_rptr = &tcp_randtbl[1];
24235 
24236 static int *tcp_random_state = &tcp_randtbl[1];
24237 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24238 
24239 kmutex_t tcp_random_lock;
24240 
24241 void
24242 tcp_random_init(void)
24243 {
24244 	int i;
24245 	hrtime_t hrt;
24246 	time_t wallclock;
24247 	uint64_t result;
24248 
24249 	/*
24250 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24251 	 * a longlong, which may contain resolution down to nanoseconds.
24252 	 * The current time will either be a 32-bit or a 64-bit quantity.
24253 	 * XOR the two together in a 64-bit result variable.
24254 	 * Convert the result to a 32-bit value by multiplying the high-order
24255 	 * 32-bits by the low-order 32-bits.
24256 	 */
24257 
24258 	hrt = gethrtime();
24259 	(void) drv_getparm(TIME, &wallclock);
24260 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24261 	mutex_enter(&tcp_random_lock);
24262 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24263 	    (result & 0xffffffff);
24264 
24265 	for (i = 1; i < DEG_3; i++)
24266 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24267 		    + 12345;
24268 	tcp_random_fptr = &tcp_random_state[SEP_3];
24269 	tcp_random_rptr = &tcp_random_state[0];
24270 	mutex_exit(&tcp_random_lock);
24271 	for (i = 0; i < 10 * DEG_3; i++)
24272 		(void) tcp_random();
24273 }
24274 
24275 /*
24276  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24277  * This range is selected to be approximately centered on TCP_ISS / 2,
24278  * and easy to compute. We get this value by generating a 32-bit random
24279  * number, selecting out the high-order 17 bits, and then adding one so
24280  * that we never return zero.
24281  */
24282 int
24283 tcp_random(void)
24284 {
24285 	int i;
24286 
24287 	mutex_enter(&tcp_random_lock);
24288 	*tcp_random_fptr += *tcp_random_rptr;
24289 
24290 	/*
24291 	 * The high-order bits are more random than the low-order bits,
24292 	 * so we select out the high-order 17 bits and add one so that
24293 	 * we never return zero.
24294 	 */
24295 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24296 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24297 		tcp_random_fptr = tcp_random_state;
24298 		++tcp_random_rptr;
24299 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24300 		tcp_random_rptr = tcp_random_state;
24301 
24302 	mutex_exit(&tcp_random_lock);
24303 	return (i);
24304 }
24305 
24306 static int
24307 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24308     int *t_errorp, int *sys_errorp)
24309 {
24310 	int error;
24311 	int is_absreq_failure;
24312 	t_scalar_t *opt_lenp;
24313 	t_scalar_t opt_offset;
24314 	int prim_type;
24315 	struct T_conn_req *tcreqp;
24316 	struct T_conn_res *tcresp;
24317 	cred_t *cr;
24318 
24319 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
24320 
24321 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24322 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24323 	    prim_type == T_CONN_RES);
24324 
24325 	switch (prim_type) {
24326 	case T_CONN_REQ:
24327 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24328 		opt_offset = tcreqp->OPT_offset;
24329 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24330 		break;
24331 	case O_T_CONN_RES:
24332 	case T_CONN_RES:
24333 		tcresp = (struct T_conn_res *)mp->b_rptr;
24334 		opt_offset = tcresp->OPT_offset;
24335 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24336 		break;
24337 	}
24338 
24339 	*t_errorp = 0;
24340 	*sys_errorp = 0;
24341 	*do_disconnectp = 0;
24342 
24343 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24344 	    opt_offset, cr, &tcp_opt_obj,
24345 	    NULL, &is_absreq_failure);
24346 
24347 	switch (error) {
24348 	case  0:		/* no error */
24349 		ASSERT(is_absreq_failure == 0);
24350 		return (0);
24351 	case ENOPROTOOPT:
24352 		*t_errorp = TBADOPT;
24353 		break;
24354 	case EACCES:
24355 		*t_errorp = TACCES;
24356 		break;
24357 	default:
24358 		*t_errorp = TSYSERR; *sys_errorp = error;
24359 		break;
24360 	}
24361 	if (is_absreq_failure != 0) {
24362 		/*
24363 		 * The connection request should get the local ack
24364 		 * T_OK_ACK and then a T_DISCON_IND.
24365 		 */
24366 		*do_disconnectp = 1;
24367 	}
24368 	return (-1);
24369 }
24370 
24371 /*
24372  * Split this function out so that if the secret changes, I'm okay.
24373  *
24374  * Initialize the tcp_iss_cookie and tcp_iss_key.
24375  */
24376 
24377 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24378 
24379 static void
24380 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
24381 {
24382 	struct {
24383 		int32_t current_time;
24384 		uint32_t randnum;
24385 		uint16_t pad;
24386 		uint8_t ether[6];
24387 		uint8_t passwd[PASSWD_SIZE];
24388 	} tcp_iss_cookie;
24389 	time_t t;
24390 
24391 	/*
24392 	 * Start with the current absolute time.
24393 	 */
24394 	(void) drv_getparm(TIME, &t);
24395 	tcp_iss_cookie.current_time = t;
24396 
24397 	/*
24398 	 * XXX - Need a more random number per RFC 1750, not this crap.
24399 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24400 	 */
24401 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24402 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24403 
24404 	/*
24405 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24406 	 * as a good template.
24407 	 */
24408 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24409 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24410 
24411 	/*
24412 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24413 	 */
24414 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24415 
24416 	/*
24417 	 * See 4010593 if this section becomes a problem again,
24418 	 * but the local ethernet address is useful here.
24419 	 */
24420 	(void) localetheraddr(NULL,
24421 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24422 
24423 	/*
24424 	 * Hash 'em all together.  The MD5Final is called per-connection.
24425 	 */
24426 	mutex_enter(&tcps->tcps_iss_key_lock);
24427 	MD5Init(&tcps->tcps_iss_key);
24428 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
24429 	    sizeof (tcp_iss_cookie));
24430 	mutex_exit(&tcps->tcps_iss_key_lock);
24431 }
24432 
24433 /*
24434  * Set the RFC 1948 pass phrase
24435  */
24436 /* ARGSUSED */
24437 static int
24438 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24439     cred_t *cr)
24440 {
24441 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24442 
24443 	/*
24444 	 * Basically, value contains a new pass phrase.  Pass it along!
24445 	 */
24446 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
24447 	return (0);
24448 }
24449 
24450 /* ARGSUSED */
24451 static int
24452 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24453 {
24454 	bzero(buf, sizeof (tcp_sack_info_t));
24455 	return (0);
24456 }
24457 
24458 /* ARGSUSED */
24459 static int
24460 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24461 {
24462 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24463 	return (0);
24464 }
24465 
24466 /*
24467  * Make sure we wait until the default queue is setup, yet allow
24468  * tcp_g_q_create() to open a TCP stream.
24469  * We need to allow tcp_g_q_create() do do an open
24470  * of tcp, hence we compare curhread.
24471  * All others have to wait until the tcps_g_q has been
24472  * setup.
24473  */
24474 void
24475 tcp_g_q_setup(tcp_stack_t *tcps)
24476 {
24477 	mutex_enter(&tcps->tcps_g_q_lock);
24478 	if (tcps->tcps_g_q != NULL) {
24479 		mutex_exit(&tcps->tcps_g_q_lock);
24480 		return;
24481 	}
24482 	if (tcps->tcps_g_q_creator == NULL) {
24483 		/* This thread will set it up */
24484 		tcps->tcps_g_q_creator = curthread;
24485 		mutex_exit(&tcps->tcps_g_q_lock);
24486 		tcp_g_q_create(tcps);
24487 		mutex_enter(&tcps->tcps_g_q_lock);
24488 		ASSERT(tcps->tcps_g_q_creator == curthread);
24489 		tcps->tcps_g_q_creator = NULL;
24490 		cv_signal(&tcps->tcps_g_q_cv);
24491 		ASSERT(tcps->tcps_g_q != NULL);
24492 		mutex_exit(&tcps->tcps_g_q_lock);
24493 		return;
24494 	}
24495 	/* Everybody but the creator has to wait */
24496 	if (tcps->tcps_g_q_creator != curthread) {
24497 		while (tcps->tcps_g_q == NULL)
24498 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24499 	}
24500 	mutex_exit(&tcps->tcps_g_q_lock);
24501 }
24502 
24503 #define	IP	"ip"
24504 
24505 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24506 
24507 /*
24508  * Create a default tcp queue here instead of in strplumb
24509  */
24510 void
24511 tcp_g_q_create(tcp_stack_t *tcps)
24512 {
24513 	int error;
24514 	ldi_handle_t	lh = NULL;
24515 	ldi_ident_t	li = NULL;
24516 	int		rval;
24517 	cred_t		*cr;
24518 	major_t IP_MAJ;
24519 
24520 #ifdef NS_DEBUG
24521 	(void) printf("tcp_g_q_create()\n");
24522 #endif
24523 
24524 	IP_MAJ = ddi_name_to_major(IP);
24525 
24526 	ASSERT(tcps->tcps_g_q_creator == curthread);
24527 
24528 	error = ldi_ident_from_major(IP_MAJ, &li);
24529 	if (error) {
24530 #ifdef DEBUG
24531 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24532 		    error);
24533 #endif
24534 		return;
24535 	}
24536 
24537 	cr = zone_get_kcred(netstackid_to_zoneid(
24538 	    tcps->tcps_netstack->netstack_stackid));
24539 	ASSERT(cr != NULL);
24540 	/*
24541 	 * We set the tcp default queue to IPv6 because IPv4 falls
24542 	 * back to IPv6 when it can't find a client, but
24543 	 * IPv6 does not fall back to IPv4.
24544 	 */
24545 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24546 	if (error) {
24547 #ifdef DEBUG
24548 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24549 		    error);
24550 #endif
24551 		goto out;
24552 	}
24553 
24554 	/*
24555 	 * This ioctl causes the tcp framework to cache a pointer to
24556 	 * this stream, so we don't want to close the stream after
24557 	 * this operation.
24558 	 * Use the kernel credentials that are for the zone we're in.
24559 	 */
24560 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24561 	    (intptr_t)0, FKIOCTL, cr, &rval);
24562 	if (error) {
24563 #ifdef DEBUG
24564 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24565 		    "error %d\n", error);
24566 #endif
24567 		goto out;
24568 	}
24569 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24570 	lh = NULL;
24571 out:
24572 	/* Close layered handles */
24573 	if (li)
24574 		ldi_ident_release(li);
24575 	/* Keep cred around until _inactive needs it */
24576 	tcps->tcps_g_q_cr = cr;
24577 }
24578 
24579 /*
24580  * We keep tcp_g_q set until all other tcp_t's in the zone
24581  * has gone away, and then when tcp_g_q_inactive() is called
24582  * we clear it.
24583  */
24584 void
24585 tcp_g_q_destroy(tcp_stack_t *tcps)
24586 {
24587 #ifdef NS_DEBUG
24588 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24589 	    tcps->tcps_netstack->netstack_stackid);
24590 #endif
24591 
24592 	if (tcps->tcps_g_q == NULL) {
24593 		return;	/* Nothing to cleanup */
24594 	}
24595 	/*
24596 	 * Drop reference corresponding to the default queue.
24597 	 * This reference was added from tcp_open when the default queue
24598 	 * was created, hence we compensate for this extra drop in
24599 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24600 	 * the default queue was the last one to be open, in which
24601 	 * case, then tcp_g_q_inactive will be
24602 	 * called as a result of the refrele.
24603 	 */
24604 	TCPS_REFRELE(tcps);
24605 }
24606 
24607 /*
24608  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24609  * Run by tcp_q_q_inactive using a taskq.
24610  */
24611 static void
24612 tcp_g_q_close(void *arg)
24613 {
24614 	tcp_stack_t *tcps = arg;
24615 	int error;
24616 	ldi_handle_t	lh = NULL;
24617 	ldi_ident_t	li = NULL;
24618 	cred_t		*cr;
24619 	major_t IP_MAJ;
24620 
24621 	IP_MAJ = ddi_name_to_major(IP);
24622 
24623 #ifdef NS_DEBUG
24624 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24625 	    tcps->tcps_netstack->netstack_stackid,
24626 	    tcps->tcps_netstack->netstack_refcnt);
24627 #endif
24628 	lh = tcps->tcps_g_q_lh;
24629 	if (lh == NULL)
24630 		return;	/* Nothing to cleanup */
24631 
24632 	ASSERT(tcps->tcps_refcnt == 1);
24633 	ASSERT(tcps->tcps_g_q != NULL);
24634 
24635 	error = ldi_ident_from_major(IP_MAJ, &li);
24636 	if (error) {
24637 #ifdef DEBUG
24638 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
24639 		    error);
24640 #endif
24641 		return;
24642 	}
24643 
24644 	cr = tcps->tcps_g_q_cr;
24645 	tcps->tcps_g_q_cr = NULL;
24646 	ASSERT(cr != NULL);
24647 
24648 	/*
24649 	 * Make sure we can break the recursion when tcp_close decrements
24650 	 * the reference count causing g_q_inactive to be called again.
24651 	 */
24652 	tcps->tcps_g_q_lh = NULL;
24653 
24654 	/* close the default queue */
24655 	(void) ldi_close(lh, FREAD|FWRITE, cr);
24656 	/*
24657 	 * At this point in time tcps and the rest of netstack_t might
24658 	 * have been deleted.
24659 	 */
24660 	tcps = NULL;
24661 
24662 	/* Close layered handles */
24663 	ldi_ident_release(li);
24664 	crfree(cr);
24665 }
24666 
24667 /*
24668  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24669  *
24670  * Have to ensure that the ldi routines are not used by an
24671  * interrupt thread by using a taskq.
24672  */
24673 void
24674 tcp_g_q_inactive(tcp_stack_t *tcps)
24675 {
24676 	if (tcps->tcps_g_q_lh == NULL)
24677 		return;	/* Nothing to cleanup */
24678 
24679 	ASSERT(tcps->tcps_refcnt == 0);
24680 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
24681 
24682 	if (servicing_interrupt()) {
24683 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
24684 		    (void *) tcps, TQ_SLEEP);
24685 	} else {
24686 		tcp_g_q_close(tcps);
24687 	}
24688 }
24689 
24690 /*
24691  * Called by IP when IP is loaded into the kernel
24692  */
24693 void
24694 tcp_ddi_g_init(void)
24695 {
24696 	tcp_timercache = kmem_cache_create("tcp_timercache",
24697 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24698 	    NULL, NULL, NULL, NULL, NULL, 0);
24699 
24700 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24701 	    sizeof (tcp_sack_info_t), 0,
24702 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24703 
24704 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24705 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24706 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24707 
24708 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24709 
24710 	/* Initialize the random number generator */
24711 	tcp_random_init();
24712 
24713 	/* A single callback independently of how many netstacks we have */
24714 	ip_squeue_init(tcp_squeue_add);
24715 
24716 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
24717 
24718 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
24719 	    TASKQ_PREPOPULATE);
24720 
24721 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
24722 
24723 	/*
24724 	 * We want to be informed each time a stack is created or
24725 	 * destroyed in the kernel, so we can maintain the
24726 	 * set of tcp_stack_t's.
24727 	 */
24728 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
24729 	    tcp_stack_fini);
24730 }
24731 
24732 
24733 #define	INET_NAME	"ip"
24734 
24735 /*
24736  * Initialize the TCP stack instance.
24737  */
24738 static void *
24739 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
24740 {
24741 	tcp_stack_t	*tcps;
24742 	tcpparam_t	*pa;
24743 	int		i;
24744 	int		error = 0;
24745 	major_t		major;
24746 
24747 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
24748 	tcps->tcps_netstack = ns;
24749 
24750 	/* Initialize locks */
24751 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
24752 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24753 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
24754 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24755 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24756 
24757 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
24758 	tcps->tcps_g_epriv_ports[0] = 2049;
24759 	tcps->tcps_g_epriv_ports[1] = 4045;
24760 	tcps->tcps_min_anonpriv_port = 512;
24761 
24762 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
24763 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
24764 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
24765 	    TCP_FANOUT_SIZE, KM_SLEEP);
24766 
24767 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24768 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
24769 		    MUTEX_DEFAULT, NULL);
24770 	}
24771 
24772 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24773 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
24774 		    MUTEX_DEFAULT, NULL);
24775 	}
24776 
24777 	/* TCP's IPsec code calls the packet dropper. */
24778 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
24779 
24780 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
24781 	tcps->tcps_params = pa;
24782 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24783 
24784 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
24785 	    A_CNT(lcl_tcp_param_arr), tcps);
24786 
24787 	/*
24788 	 * Note: To really walk the device tree you need the devinfo
24789 	 * pointer to your device which is only available after probe/attach.
24790 	 * The following is safe only because it uses ddi_root_node()
24791 	 */
24792 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24793 	    tcp_opt_obj.odb_opt_arr_cnt);
24794 
24795 	/*
24796 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24797 	 * by the boot scripts.
24798 	 *
24799 	 * Use NULL name, as the name is caught by the new lockstats.
24800 	 *
24801 	 * Initialize with some random, non-guessable string, like the global
24802 	 * T_INFO_ACK.
24803 	 */
24804 
24805 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24806 	    sizeof (tcp_g_t_info_ack), tcps);
24807 
24808 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
24809 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
24810 
24811 	major = mod_name_to_major(INET_NAME);
24812 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
24813 	ASSERT(error == 0);
24814 	return (tcps);
24815 }
24816 
24817 /*
24818  * Called when the IP module is about to be unloaded.
24819  */
24820 void
24821 tcp_ddi_g_destroy(void)
24822 {
24823 	tcp_g_kstat_fini(tcp_g_kstat);
24824 	tcp_g_kstat = NULL;
24825 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
24826 
24827 	mutex_destroy(&tcp_random_lock);
24828 
24829 	kmem_cache_destroy(tcp_timercache);
24830 	kmem_cache_destroy(tcp_sack_info_cache);
24831 	kmem_cache_destroy(tcp_iphc_cache);
24832 
24833 	netstack_unregister(NS_TCP);
24834 	taskq_destroy(tcp_taskq);
24835 }
24836 
24837 /*
24838  * Shut down the TCP stack instance.
24839  */
24840 /* ARGSUSED */
24841 static void
24842 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24843 {
24844 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24845 
24846 	tcp_g_q_destroy(tcps);
24847 }
24848 
24849 /*
24850  * Free the TCP stack instance.
24851  */
24852 static void
24853 tcp_stack_fini(netstackid_t stackid, void *arg)
24854 {
24855 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24856 	int i;
24857 
24858 	nd_free(&tcps->tcps_g_nd);
24859 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24860 	tcps->tcps_params = NULL;
24861 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24862 	tcps->tcps_wroff_xtra_param = NULL;
24863 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24864 	tcps->tcps_mdt_head_param = NULL;
24865 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24866 	tcps->tcps_mdt_tail_param = NULL;
24867 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24868 	tcps->tcps_mdt_max_pbufs_param = NULL;
24869 
24870 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24871 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24872 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24873 	}
24874 
24875 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24876 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
24877 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
24878 	}
24879 
24880 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
24881 	tcps->tcps_bind_fanout = NULL;
24882 
24883 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
24884 	tcps->tcps_acceptor_fanout = NULL;
24885 
24886 	mutex_destroy(&tcps->tcps_iss_key_lock);
24887 	rw_destroy(&tcps->tcps_hsp_lock);
24888 	mutex_destroy(&tcps->tcps_g_q_lock);
24889 	cv_destroy(&tcps->tcps_g_q_cv);
24890 	mutex_destroy(&tcps->tcps_epriv_port_lock);
24891 
24892 	ip_drop_unregister(&tcps->tcps_dropper);
24893 
24894 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
24895 	tcps->tcps_kstat = NULL;
24896 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
24897 
24898 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
24899 	tcps->tcps_mibkp = NULL;
24900 
24901 	ldi_ident_release(tcps->tcps_ldi_ident);
24902 	kmem_free(tcps, sizeof (*tcps));
24903 }
24904 
24905 /*
24906  * Generate ISS, taking into account NDD changes may happen halfway through.
24907  * (If the iss is not zero, set it.)
24908  */
24909 
24910 static void
24911 tcp_iss_init(tcp_t *tcp)
24912 {
24913 	MD5_CTX context;
24914 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24915 	uint32_t answer[4];
24916 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24917 
24918 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
24919 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
24920 	switch (tcps->tcps_strong_iss) {
24921 	case 2:
24922 		mutex_enter(&tcps->tcps_iss_key_lock);
24923 		context = tcps->tcps_iss_key;
24924 		mutex_exit(&tcps->tcps_iss_key_lock);
24925 		arg.ports = tcp->tcp_ports;
24926 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24927 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24928 			    &arg.src);
24929 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24930 			    &arg.dst);
24931 		} else {
24932 			arg.src = tcp->tcp_ip6h->ip6_src;
24933 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24934 		}
24935 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24936 		MD5Final((uchar_t *)answer, &context);
24937 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24938 		/*
24939 		 * Now that we've hashed into a unique per-connection sequence
24940 		 * space, add a random increment per strong_iss == 1.  So I
24941 		 * guess we'll have to...
24942 		 */
24943 		/* FALLTHRU */
24944 	case 1:
24945 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24946 		break;
24947 	default:
24948 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24949 		break;
24950 	}
24951 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24952 	tcp->tcp_fss = tcp->tcp_iss - 1;
24953 	tcp->tcp_suna = tcp->tcp_iss;
24954 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24955 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24956 	tcp->tcp_csuna = tcp->tcp_snxt;
24957 }
24958 
24959 /*
24960  * Exported routine for extracting active tcp connection status.
24961  *
24962  * This is used by the Solaris Cluster Networking software to
24963  * gather a list of connections that need to be forwarded to
24964  * specific nodes in the cluster when configuration changes occur.
24965  *
24966  * The callback is invoked for each tcp_t structure from all netstacks,
24967  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
24968  * from the netstack with the specified stack_id. Returning
24969  * non-zero from the callback routine terminates the search.
24970  */
24971 int
24972 cl_tcp_walk_list(netstackid_t stack_id,
24973     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
24974 {
24975 	netstack_handle_t nh;
24976 	netstack_t *ns;
24977 	int ret = 0;
24978 
24979 	if (stack_id >= 0) {
24980 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
24981 			return (EINVAL);
24982 
24983 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24984 		    ns->netstack_tcp);
24985 		netstack_rele(ns);
24986 		return (ret);
24987 	}
24988 
24989 	netstack_next_init(&nh);
24990 	while ((ns = netstack_next(&nh)) != NULL) {
24991 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24992 		    ns->netstack_tcp);
24993 		netstack_rele(ns);
24994 	}
24995 	netstack_next_fini(&nh);
24996 	return (ret);
24997 }
24998 
24999 static int
25000 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25001     tcp_stack_t *tcps)
25002 {
25003 	tcp_t *tcp;
25004 	cl_tcp_info_t	cl_tcpi;
25005 	connf_t	*connfp;
25006 	conn_t	*connp;
25007 	int	i;
25008 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25009 
25010 	ASSERT(callback != NULL);
25011 
25012 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25013 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25014 		connp = NULL;
25015 
25016 		while ((connp =
25017 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25018 
25019 			tcp = connp->conn_tcp;
25020 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
25021 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
25022 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
25023 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
25024 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
25025 			/*
25026 			 * The macros tcp_laddr and tcp_faddr give the IPv4
25027 			 * addresses. They are copied implicitly below as
25028 			 * mapped addresses.
25029 			 */
25030 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
25031 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25032 				cl_tcpi.cl_tcpi_faddr =
25033 				    tcp->tcp_ipha->ipha_dst;
25034 			} else {
25035 				cl_tcpi.cl_tcpi_faddr_v6 =
25036 				    tcp->tcp_ip6h->ip6_dst;
25037 			}
25038 
25039 			/*
25040 			 * If the callback returns non-zero
25041 			 * we terminate the traversal.
25042 			 */
25043 			if ((*callback)(&cl_tcpi, arg) != 0) {
25044 				CONN_DEC_REF(tcp->tcp_connp);
25045 				return (1);
25046 			}
25047 		}
25048 	}
25049 
25050 	return (0);
25051 }
25052 
25053 /*
25054  * Macros used for accessing the different types of sockaddr
25055  * structures inside a tcp_ioc_abort_conn_t.
25056  */
25057 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
25058 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
25059 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
25060 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
25061 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
25062 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
25063 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
25064 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
25065 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
25066 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
25067 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
25068 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
25069 
25070 /*
25071  * Return the correct error code to mimic the behavior
25072  * of a connection reset.
25073  */
25074 #define	TCP_AC_GET_ERRCODE(state, err) {	\
25075 		switch ((state)) {		\
25076 		case TCPS_SYN_SENT:		\
25077 		case TCPS_SYN_RCVD:		\
25078 			(err) = ECONNREFUSED;	\
25079 			break;			\
25080 		case TCPS_ESTABLISHED:		\
25081 		case TCPS_FIN_WAIT_1:		\
25082 		case TCPS_FIN_WAIT_2:		\
25083 		case TCPS_CLOSE_WAIT:		\
25084 			(err) = ECONNRESET;	\
25085 			break;			\
25086 		case TCPS_CLOSING:		\
25087 		case TCPS_LAST_ACK:		\
25088 		case TCPS_TIME_WAIT:		\
25089 			(err) = 0;		\
25090 			break;			\
25091 		default:			\
25092 			(err) = ENXIO;		\
25093 		}				\
25094 	}
25095 
25096 /*
25097  * Check if a tcp structure matches the info in acp.
25098  */
25099 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
25100 	(((acp)->ac_local.ss_family == AF_INET) ?		\
25101 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
25102 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
25103 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
25104 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
25105 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
25106 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
25107 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
25108 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
25109 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25110 	(acp)->ac_end >= (tcp)->tcp_state) :		\
25111 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
25112 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
25113 	&(tcp)->tcp_ip_src_v6)) &&				\
25114 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
25115 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
25116 	&(tcp)->tcp_remote_v6)) &&				\
25117 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
25118 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
25119 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
25120 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
25121 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25122 	(acp)->ac_end >= (tcp)->tcp_state))
25123 
25124 #define	TCP_AC_MATCH(acp, tcp)					\
25125 	(((acp)->ac_zoneid == ALL_ZONES ||			\
25126 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
25127 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
25128 
25129 /*
25130  * Build a message containing a tcp_ioc_abort_conn_t structure
25131  * which is filled in with information from acp and tp.
25132  */
25133 static mblk_t *
25134 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
25135 {
25136 	mblk_t *mp;
25137 	tcp_ioc_abort_conn_t *tacp;
25138 
25139 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
25140 	if (mp == NULL)
25141 		return (NULL);
25142 
25143 	mp->b_datap->db_type = M_CTL;
25144 
25145 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
25146 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
25147 	    sizeof (uint32_t));
25148 
25149 	tacp->ac_start = acp->ac_start;
25150 	tacp->ac_end = acp->ac_end;
25151 	tacp->ac_zoneid = acp->ac_zoneid;
25152 
25153 	if (acp->ac_local.ss_family == AF_INET) {
25154 		tacp->ac_local.ss_family = AF_INET;
25155 		tacp->ac_remote.ss_family = AF_INET;
25156 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
25157 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
25158 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
25159 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
25160 	} else {
25161 		tacp->ac_local.ss_family = AF_INET6;
25162 		tacp->ac_remote.ss_family = AF_INET6;
25163 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
25164 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
25165 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
25166 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
25167 	}
25168 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
25169 	return (mp);
25170 }
25171 
25172 /*
25173  * Print a tcp_ioc_abort_conn_t structure.
25174  */
25175 static void
25176 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
25177 {
25178 	char lbuf[128];
25179 	char rbuf[128];
25180 	sa_family_t af;
25181 	in_port_t lport, rport;
25182 	ushort_t logflags;
25183 
25184 	af = acp->ac_local.ss_family;
25185 
25186 	if (af == AF_INET) {
25187 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
25188 		    lbuf, 128);
25189 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
25190 		    rbuf, 128);
25191 		lport = ntohs(TCP_AC_V4LPORT(acp));
25192 		rport = ntohs(TCP_AC_V4RPORT(acp));
25193 	} else {
25194 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
25195 		    lbuf, 128);
25196 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
25197 		    rbuf, 128);
25198 		lport = ntohs(TCP_AC_V6LPORT(acp));
25199 		rport = ntohs(TCP_AC_V6RPORT(acp));
25200 	}
25201 
25202 	logflags = SL_TRACE | SL_NOTE;
25203 	/*
25204 	 * Don't print this message to the console if the operation was done
25205 	 * to a non-global zone.
25206 	 */
25207 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25208 		logflags |= SL_CONSOLE;
25209 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
25210 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
25211 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
25212 	    acp->ac_start, acp->ac_end);
25213 }
25214 
25215 /*
25216  * Called inside tcp_rput when a message built using
25217  * tcp_ioctl_abort_build_msg is put into a queue.
25218  * Note that when we get here there is no wildcard in acp any more.
25219  */
25220 static void
25221 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
25222 {
25223 	tcp_ioc_abort_conn_t *acp;
25224 
25225 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
25226 	if (tcp->tcp_state <= acp->ac_end) {
25227 		/*
25228 		 * If we get here, we are already on the correct
25229 		 * squeue. This ioctl follows the following path
25230 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
25231 		 * ->tcp_ioctl_abort->squeue_enter (if on a
25232 		 * different squeue)
25233 		 */
25234 		int errcode;
25235 
25236 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
25237 		(void) tcp_clean_death(tcp, errcode, 26);
25238 	}
25239 	freemsg(mp);
25240 }
25241 
25242 /*
25243  * Abort all matching connections on a hash chain.
25244  */
25245 static int
25246 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
25247     boolean_t exact, tcp_stack_t *tcps)
25248 {
25249 	int nmatch, err = 0;
25250 	tcp_t *tcp;
25251 	MBLKP mp, last, listhead = NULL;
25252 	conn_t	*tconnp;
25253 	connf_t	*connfp;
25254 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25255 
25256 	connfp = &ipst->ips_ipcl_conn_fanout[index];
25257 
25258 startover:
25259 	nmatch = 0;
25260 
25261 	mutex_enter(&connfp->connf_lock);
25262 	for (tconnp = connfp->connf_head; tconnp != NULL;
25263 	    tconnp = tconnp->conn_next) {
25264 		tcp = tconnp->conn_tcp;
25265 		if (TCP_AC_MATCH(acp, tcp)) {
25266 			CONN_INC_REF(tcp->tcp_connp);
25267 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
25268 			if (mp == NULL) {
25269 				err = ENOMEM;
25270 				CONN_DEC_REF(tcp->tcp_connp);
25271 				break;
25272 			}
25273 			mp->b_prev = (mblk_t *)tcp;
25274 
25275 			if (listhead == NULL) {
25276 				listhead = mp;
25277 				last = mp;
25278 			} else {
25279 				last->b_next = mp;
25280 				last = mp;
25281 			}
25282 			nmatch++;
25283 			if (exact)
25284 				break;
25285 		}
25286 
25287 		/* Avoid holding lock for too long. */
25288 		if (nmatch >= 500)
25289 			break;
25290 	}
25291 	mutex_exit(&connfp->connf_lock);
25292 
25293 	/* Pass mp into the correct tcp */
25294 	while ((mp = listhead) != NULL) {
25295 		listhead = listhead->b_next;
25296 		tcp = (tcp_t *)mp->b_prev;
25297 		mp->b_next = mp->b_prev = NULL;
25298 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
25299 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
25300 	}
25301 
25302 	*count += nmatch;
25303 	if (nmatch >= 500 && err == 0)
25304 		goto startover;
25305 	return (err);
25306 }
25307 
25308 /*
25309  * Abort all connections that matches the attributes specified in acp.
25310  */
25311 static int
25312 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
25313 {
25314 	sa_family_t af;
25315 	uint32_t  ports;
25316 	uint16_t *pports;
25317 	int err = 0, count = 0;
25318 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25319 	int index = -1;
25320 	ushort_t logflags;
25321 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25322 
25323 	af = acp->ac_local.ss_family;
25324 
25325 	if (af == AF_INET) {
25326 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25327 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25328 			pports = (uint16_t *)&ports;
25329 			pports[1] = TCP_AC_V4LPORT(acp);
25330 			pports[0] = TCP_AC_V4RPORT(acp);
25331 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25332 		}
25333 	} else {
25334 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25335 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25336 			pports = (uint16_t *)&ports;
25337 			pports[1] = TCP_AC_V6LPORT(acp);
25338 			pports[0] = TCP_AC_V6RPORT(acp);
25339 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25340 		}
25341 	}
25342 
25343 	/*
25344 	 * For cases where remote addr, local port, and remote port are non-
25345 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25346 	 */
25347 	if (index != -1) {
25348 		err = tcp_ioctl_abort_bucket(acp, index,
25349 		    &count, exact, tcps);
25350 	} else {
25351 		/*
25352 		 * loop through all entries for wildcard case
25353 		 */
25354 		for (index = 0;
25355 		    index < ipst->ips_ipcl_conn_fanout_size;
25356 		    index++) {
25357 			err = tcp_ioctl_abort_bucket(acp, index,
25358 			    &count, exact, tcps);
25359 			if (err != 0)
25360 				break;
25361 		}
25362 	}
25363 
25364 	logflags = SL_TRACE | SL_NOTE;
25365 	/*
25366 	 * Don't print this message to the console if the operation was done
25367 	 * to a non-global zone.
25368 	 */
25369 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25370 		logflags |= SL_CONSOLE;
25371 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25372 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25373 	if (err == 0 && count == 0)
25374 		err = ENOENT;
25375 	return (err);
25376 }
25377 
25378 /*
25379  * Process the TCP_IOC_ABORT_CONN ioctl request.
25380  */
25381 static void
25382 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25383 {
25384 	int	err;
25385 	IOCP    iocp;
25386 	MBLKP   mp1;
25387 	sa_family_t laf, raf;
25388 	tcp_ioc_abort_conn_t *acp;
25389 	zone_t		*zptr;
25390 	conn_t		*connp = Q_TO_CONN(q);
25391 	zoneid_t	zoneid = connp->conn_zoneid;
25392 	tcp_t		*tcp = connp->conn_tcp;
25393 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25394 
25395 	iocp = (IOCP)mp->b_rptr;
25396 
25397 	if ((mp1 = mp->b_cont) == NULL ||
25398 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25399 		err = EINVAL;
25400 		goto out;
25401 	}
25402 
25403 	/* check permissions */
25404 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
25405 		err = EPERM;
25406 		goto out;
25407 	}
25408 
25409 	if (mp1->b_cont != NULL) {
25410 		freemsg(mp1->b_cont);
25411 		mp1->b_cont = NULL;
25412 	}
25413 
25414 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25415 	laf = acp->ac_local.ss_family;
25416 	raf = acp->ac_remote.ss_family;
25417 
25418 	/* check that a zone with the supplied zoneid exists */
25419 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25420 		zptr = zone_find_by_id(zoneid);
25421 		if (zptr != NULL) {
25422 			zone_rele(zptr);
25423 		} else {
25424 			err = EINVAL;
25425 			goto out;
25426 		}
25427 	}
25428 
25429 	/*
25430 	 * For exclusive stacks we set the zoneid to zero
25431 	 * to make TCP operate as if in the global zone.
25432 	 */
25433 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
25434 		acp->ac_zoneid = GLOBAL_ZONEID;
25435 
25436 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25437 	    acp->ac_start > acp->ac_end || laf != raf ||
25438 	    (laf != AF_INET && laf != AF_INET6)) {
25439 		err = EINVAL;
25440 		goto out;
25441 	}
25442 
25443 	tcp_ioctl_abort_dump(acp);
25444 	err = tcp_ioctl_abort(acp, tcps);
25445 
25446 out:
25447 	if (mp1 != NULL) {
25448 		freemsg(mp1);
25449 		mp->b_cont = NULL;
25450 	}
25451 
25452 	if (err != 0)
25453 		miocnak(q, mp, 0, err);
25454 	else
25455 		miocack(q, mp, 0, 0);
25456 }
25457 
25458 /*
25459  * tcp_time_wait_processing() handles processing of incoming packets when
25460  * the tcp is in the TIME_WAIT state.
25461  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25462  * on the time wait list.
25463  */
25464 void
25465 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25466     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25467 {
25468 	int32_t		bytes_acked;
25469 	int32_t		gap;
25470 	int32_t		rgap;
25471 	tcp_opt_t	tcpopt;
25472 	uint_t		flags;
25473 	uint32_t	new_swnd = 0;
25474 	conn_t		*connp;
25475 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25476 
25477 	BUMP_LOCAL(tcp->tcp_ibsegs);
25478 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
25479 
25480 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25481 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25482 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25483 	if (tcp->tcp_snd_ts_ok) {
25484 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25485 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25486 			    tcp->tcp_rnxt, TH_ACK);
25487 			goto done;
25488 		}
25489 	}
25490 	gap = seg_seq - tcp->tcp_rnxt;
25491 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25492 	if (gap < 0) {
25493 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25494 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25495 		    (seg_len > -gap ? -gap : seg_len));
25496 		seg_len += gap;
25497 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25498 			if (flags & TH_RST) {
25499 				goto done;
25500 			}
25501 			if ((flags & TH_FIN) && seg_len == -1) {
25502 				/*
25503 				 * When TCP receives a duplicate FIN in
25504 				 * TIME_WAIT state, restart the 2 MSL timer.
25505 				 * See page 73 in RFC 793. Make sure this TCP
25506 				 * is already on the TIME_WAIT list. If not,
25507 				 * just restart the timer.
25508 				 */
25509 				if (TCP_IS_DETACHED(tcp)) {
25510 					if (tcp_time_wait_remove(tcp, NULL) ==
25511 					    B_TRUE) {
25512 						tcp_time_wait_append(tcp);
25513 						TCP_DBGSTAT(tcps,
25514 						    tcp_rput_time_wait);
25515 					}
25516 				} else {
25517 					ASSERT(tcp != NULL);
25518 					TCP_TIMER_RESTART(tcp,
25519 					    tcps->tcps_time_wait_interval);
25520 				}
25521 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25522 				    tcp->tcp_rnxt, TH_ACK);
25523 				goto done;
25524 			}
25525 			flags |=  TH_ACK_NEEDED;
25526 			seg_len = 0;
25527 			goto process_ack;
25528 		}
25529 
25530 		/* Fix seg_seq, and chew the gap off the front. */
25531 		seg_seq = tcp->tcp_rnxt;
25532 	}
25533 
25534 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25535 		/*
25536 		 * Make sure that when we accept the connection, pick
25537 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25538 		 * old connection.
25539 		 *
25540 		 * The next ISS generated is equal to tcp_iss_incr_extra
25541 		 * + ISS_INCR/2 + other components depending on the
25542 		 * value of tcp_strong_iss.  We pre-calculate the new
25543 		 * ISS here and compare with tcp_snxt to determine if
25544 		 * we need to make adjustment to tcp_iss_incr_extra.
25545 		 *
25546 		 * The above calculation is ugly and is a
25547 		 * waste of CPU cycles...
25548 		 */
25549 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25550 		int32_t adj;
25551 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25552 
25553 		switch (tcps->tcps_strong_iss) {
25554 		case 2: {
25555 			/* Add time and MD5 components. */
25556 			uint32_t answer[4];
25557 			struct {
25558 				uint32_t ports;
25559 				in6_addr_t src;
25560 				in6_addr_t dst;
25561 			} arg;
25562 			MD5_CTX context;
25563 
25564 			mutex_enter(&tcps->tcps_iss_key_lock);
25565 			context = tcps->tcps_iss_key;
25566 			mutex_exit(&tcps->tcps_iss_key_lock);
25567 			arg.ports = tcp->tcp_ports;
25568 			/* We use MAPPED addresses in tcp_iss_init */
25569 			arg.src = tcp->tcp_ip_src_v6;
25570 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25571 				IN6_IPADDR_TO_V4MAPPED(
25572 				    tcp->tcp_ipha->ipha_dst,
25573 				    &arg.dst);
25574 			} else {
25575 				arg.dst =
25576 				    tcp->tcp_ip6h->ip6_dst;
25577 			}
25578 			MD5Update(&context, (uchar_t *)&arg,
25579 			    sizeof (arg));
25580 			MD5Final((uchar_t *)answer, &context);
25581 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25582 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25583 			break;
25584 		}
25585 		case 1:
25586 			/* Add time component and min random (i.e. 1). */
25587 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25588 			break;
25589 		default:
25590 			/* Add only time component. */
25591 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25592 			break;
25593 		}
25594 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25595 			/*
25596 			 * New ISS not guaranteed to be ISS_INCR/2
25597 			 * ahead of the current tcp_snxt, so add the
25598 			 * difference to tcp_iss_incr_extra.
25599 			 */
25600 			tcps->tcps_iss_incr_extra += adj;
25601 		}
25602 		/*
25603 		 * If tcp_clean_death() can not perform the task now,
25604 		 * drop the SYN packet and let the other side re-xmit.
25605 		 * Otherwise pass the SYN packet back in, since the
25606 		 * old tcp state has been cleaned up or freed.
25607 		 */
25608 		if (tcp_clean_death(tcp, 0, 27) == -1)
25609 			goto done;
25610 		/*
25611 		 * We will come back to tcp_rput_data
25612 		 * on the global queue. Packets destined
25613 		 * for the global queue will be checked
25614 		 * with global policy. But the policy for
25615 		 * this packet has already been checked as
25616 		 * this was destined for the detached
25617 		 * connection. We need to bypass policy
25618 		 * check this time by attaching a dummy
25619 		 * ipsec_in with ipsec_in_dont_check set.
25620 		 */
25621 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25622 		if (connp != NULL) {
25623 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25624 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25625 			return;
25626 		}
25627 		goto done;
25628 	}
25629 
25630 	/*
25631 	 * rgap is the amount of stuff received out of window.  A negative
25632 	 * value is the amount out of window.
25633 	 */
25634 	if (rgap < 0) {
25635 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25636 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
25637 		/* Fix seg_len and make sure there is something left. */
25638 		seg_len += rgap;
25639 		if (seg_len <= 0) {
25640 			if (flags & TH_RST) {
25641 				goto done;
25642 			}
25643 			flags |=  TH_ACK_NEEDED;
25644 			seg_len = 0;
25645 			goto process_ack;
25646 		}
25647 	}
25648 	/*
25649 	 * Check whether we can update tcp_ts_recent.  This test is
25650 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
25651 	 * Extensions for High Performance: An Update", Internet Draft.
25652 	 */
25653 	if (tcp->tcp_snd_ts_ok &&
25654 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
25655 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
25656 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
25657 		tcp->tcp_last_rcv_lbolt = lbolt64;
25658 	}
25659 
25660 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
25661 		/* Always ack out of order packets */
25662 		flags |= TH_ACK_NEEDED;
25663 		seg_len = 0;
25664 	} else if (seg_len > 0) {
25665 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
25666 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
25667 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
25668 	}
25669 	if (flags & TH_RST) {
25670 		(void) tcp_clean_death(tcp, 0, 28);
25671 		goto done;
25672 	}
25673 	if (flags & TH_SYN) {
25674 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
25675 		    TH_RST|TH_ACK);
25676 		/*
25677 		 * Do not delete the TCP structure if it is in
25678 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
25679 		 */
25680 		goto done;
25681 	}
25682 process_ack:
25683 	if (flags & TH_ACK) {
25684 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
25685 		if (bytes_acked <= 0) {
25686 			if (bytes_acked == 0 && seg_len == 0 &&
25687 			    new_swnd == tcp->tcp_swnd)
25688 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
25689 		} else {
25690 			/* Acks something not sent */
25691 			flags |= TH_ACK_NEEDED;
25692 		}
25693 	}
25694 	if (flags & TH_ACK_NEEDED) {
25695 		/*
25696 		 * Time to send an ack for some reason.
25697 		 */
25698 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25699 		    tcp->tcp_rnxt, TH_ACK);
25700 	}
25701 done:
25702 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25703 		DB_CKSUMSTART(mp) = 0;
25704 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
25705 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
25706 	}
25707 	freemsg(mp);
25708 }
25709 
25710 /*
25711  * TCP Timers Implementation.
25712  */
25713 timeout_id_t
25714 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25715 {
25716 	mblk_t *mp;
25717 	tcp_timer_t *tcpt;
25718 	tcp_t *tcp = connp->conn_tcp;
25719 
25720 	ASSERT(connp->conn_sqp != NULL);
25721 
25722 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
25723 
25724 	if (tcp->tcp_timercache == NULL) {
25725 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25726 	} else {
25727 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
25728 		mp = tcp->tcp_timercache;
25729 		tcp->tcp_timercache = mp->b_next;
25730 		mp->b_next = NULL;
25731 		ASSERT(mp->b_wptr == NULL);
25732 	}
25733 
25734 	CONN_INC_REF(connp);
25735 	tcpt = (tcp_timer_t *)mp->b_rptr;
25736 	tcpt->connp = connp;
25737 	tcpt->tcpt_proc = f;
25738 	/*
25739 	 * TCP timers are normal timeouts. Plus, they do not require more than
25740 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
25741 	 * rounding up the expiration to the next resolution boundary, we can
25742 	 * batch timers in the callout subsystem to make TCP timers more
25743 	 * efficient. The roundup also protects short timers from expiring too
25744 	 * early before they have a chance to be cancelled.
25745 	 */
25746 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
25747 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
25748 
25749 	return ((timeout_id_t)mp);
25750 }
25751 
25752 static void
25753 tcp_timer_callback(void *arg)
25754 {
25755 	mblk_t *mp = (mblk_t *)arg;
25756 	tcp_timer_t *tcpt;
25757 	conn_t	*connp;
25758 
25759 	tcpt = (tcp_timer_t *)mp->b_rptr;
25760 	connp = tcpt->connp;
25761 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
25762 	    SQ_FILL, SQTAG_TCP_TIMER);
25763 }
25764 
25765 static void
25766 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
25767 {
25768 	tcp_timer_t *tcpt;
25769 	conn_t *connp = (conn_t *)arg;
25770 	tcp_t *tcp = connp->conn_tcp;
25771 
25772 	tcpt = (tcp_timer_t *)mp->b_rptr;
25773 	ASSERT(connp == tcpt->connp);
25774 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
25775 
25776 	/*
25777 	 * If the TCP has reached the closed state, don't proceed any
25778 	 * further. This TCP logically does not exist on the system.
25779 	 * tcpt_proc could for example access queues, that have already
25780 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
25781 	 */
25782 	if (tcp->tcp_state != TCPS_CLOSED) {
25783 		(*tcpt->tcpt_proc)(connp);
25784 	} else {
25785 		tcp->tcp_timer_tid = 0;
25786 	}
25787 	tcp_timer_free(connp->conn_tcp, mp);
25788 }
25789 
25790 /*
25791  * There is potential race with untimeout and the handler firing at the same
25792  * time. The mblock may be freed by the handler while we are trying to use
25793  * it. But since both should execute on the same squeue, this race should not
25794  * occur.
25795  */
25796 clock_t
25797 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
25798 {
25799 	mblk_t	*mp = (mblk_t *)id;
25800 	tcp_timer_t *tcpt;
25801 	clock_t delta;
25802 
25803 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
25804 
25805 	if (mp == NULL)
25806 		return (-1);
25807 
25808 	tcpt = (tcp_timer_t *)mp->b_rptr;
25809 	ASSERT(tcpt->connp == connp);
25810 
25811 	delta = untimeout_default(tcpt->tcpt_tid, 0);
25812 
25813 	if (delta >= 0) {
25814 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
25815 		tcp_timer_free(connp->conn_tcp, mp);
25816 		CONN_DEC_REF(connp);
25817 	}
25818 
25819 	return (delta);
25820 }
25821 
25822 /*
25823  * Allocate space for the timer event. The allocation looks like mblk, but it is
25824  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25825  *
25826  * Dealing with failures: If we can't allocate from the timer cache we try
25827  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25828  * points to b_rptr.
25829  * If we can't allocate anything using allocb_tryhard(), we perform a last
25830  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25831  * save the actual allocation size in b_datap.
25832  */
25833 mblk_t *
25834 tcp_timermp_alloc(int kmflags)
25835 {
25836 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25837 	    kmflags & ~KM_PANIC);
25838 
25839 	if (mp != NULL) {
25840 		mp->b_next = mp->b_prev = NULL;
25841 		mp->b_rptr = (uchar_t *)(&mp[1]);
25842 		mp->b_wptr = NULL;
25843 		mp->b_datap = NULL;
25844 		mp->b_queue = NULL;
25845 		mp->b_cont = NULL;
25846 	} else if (kmflags & KM_PANIC) {
25847 		/*
25848 		 * Failed to allocate memory for the timer. Try allocating from
25849 		 * dblock caches.
25850 		 */
25851 		/* ipclassifier calls this from a constructor - hence no tcps */
25852 		TCP_G_STAT(tcp_timermp_allocfail);
25853 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25854 		if (mp == NULL) {
25855 			size_t size = 0;
25856 			/*
25857 			 * Memory is really low. Try tryhard allocation.
25858 			 *
25859 			 * ipclassifier calls this from a constructor -
25860 			 * hence no tcps
25861 			 */
25862 			TCP_G_STAT(tcp_timermp_allocdblfail);
25863 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25864 			    sizeof (tcp_timer_t), &size, kmflags);
25865 			mp->b_rptr = (uchar_t *)(&mp[1]);
25866 			mp->b_next = mp->b_prev = NULL;
25867 			mp->b_wptr = (uchar_t *)-1;
25868 			mp->b_datap = (dblk_t *)size;
25869 			mp->b_queue = NULL;
25870 			mp->b_cont = NULL;
25871 		}
25872 		ASSERT(mp->b_wptr != NULL);
25873 	}
25874 	/* ipclassifier calls this from a constructor - hence no tcps */
25875 	TCP_G_DBGSTAT(tcp_timermp_alloced);
25876 
25877 	return (mp);
25878 }
25879 
25880 /*
25881  * Free per-tcp timer cache.
25882  * It can only contain entries from tcp_timercache.
25883  */
25884 void
25885 tcp_timermp_free(tcp_t *tcp)
25886 {
25887 	mblk_t *mp;
25888 
25889 	while ((mp = tcp->tcp_timercache) != NULL) {
25890 		ASSERT(mp->b_wptr == NULL);
25891 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25892 		kmem_cache_free(tcp_timercache, mp);
25893 	}
25894 }
25895 
25896 /*
25897  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25898  * events there already (currently at most two events are cached).
25899  * If the event is not allocated from the timer cache, free it right away.
25900  */
25901 static void
25902 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25903 {
25904 	mblk_t *mp1 = tcp->tcp_timercache;
25905 
25906 	if (mp->b_wptr != NULL) {
25907 		/*
25908 		 * This allocation is not from a timer cache, free it right
25909 		 * away.
25910 		 */
25911 		if (mp->b_wptr != (uchar_t *)-1)
25912 			freeb(mp);
25913 		else
25914 			kmem_free(mp, (size_t)mp->b_datap);
25915 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25916 		/* Cache this timer block for future allocations */
25917 		mp->b_rptr = (uchar_t *)(&mp[1]);
25918 		mp->b_next = mp1;
25919 		tcp->tcp_timercache = mp;
25920 	} else {
25921 		kmem_cache_free(tcp_timercache, mp);
25922 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
25923 	}
25924 }
25925 
25926 /*
25927  * End of TCP Timers implementation.
25928  */
25929 
25930 /*
25931  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25932  * on the specified backing STREAMS q. Note, the caller may make the
25933  * decision to call based on the tcp_t.tcp_flow_stopped value which
25934  * when check outside the q's lock is only an advisory check ...
25935  */
25936 void
25937 tcp_setqfull(tcp_t *tcp)
25938 {
25939 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25940 	conn_t	*connp = tcp->tcp_connp;
25941 
25942 	if (tcp->tcp_closed)
25943 		return;
25944 
25945 	if (IPCL_IS_NONSTR(connp)) {
25946 		(*connp->conn_upcalls->su_txq_full)
25947 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
25948 		tcp->tcp_flow_stopped = B_TRUE;
25949 	} else {
25950 		queue_t *q = tcp->tcp_wq;
25951 
25952 		if (!(q->q_flag & QFULL)) {
25953 			mutex_enter(QLOCK(q));
25954 			if (!(q->q_flag & QFULL)) {
25955 				/* still need to set QFULL */
25956 				q->q_flag |= QFULL;
25957 				tcp->tcp_flow_stopped = B_TRUE;
25958 				mutex_exit(QLOCK(q));
25959 				TCP_STAT(tcps, tcp_flwctl_on);
25960 			} else {
25961 				mutex_exit(QLOCK(q));
25962 			}
25963 		}
25964 	}
25965 }
25966 
25967 void
25968 tcp_clrqfull(tcp_t *tcp)
25969 {
25970 	conn_t  *connp = tcp->tcp_connp;
25971 
25972 	if (tcp->tcp_closed)
25973 		return;
25974 
25975 	if (IPCL_IS_NONSTR(connp)) {
25976 		(*connp->conn_upcalls->su_txq_full)
25977 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
25978 		tcp->tcp_flow_stopped = B_FALSE;
25979 	} else {
25980 		queue_t *q = tcp->tcp_wq;
25981 
25982 		if (q->q_flag & QFULL) {
25983 			mutex_enter(QLOCK(q));
25984 			if (q->q_flag & QFULL) {
25985 				q->q_flag &= ~QFULL;
25986 				tcp->tcp_flow_stopped = B_FALSE;
25987 				mutex_exit(QLOCK(q));
25988 				if (q->q_flag & QWANTW)
25989 					qbackenable(q, 0);
25990 			} else {
25991 				mutex_exit(QLOCK(q));
25992 			}
25993 		}
25994 	}
25995 }
25996 
25997 /*
25998  * kstats related to squeues i.e. not per IP instance
25999  */
26000 static void *
26001 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26002 {
26003 	kstat_t *ksp;
26004 
26005 	tcp_g_stat_t template = {
26006 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26007 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
26008 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
26009 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
26010 	};
26011 
26012 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
26013 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26014 	    KSTAT_FLAG_VIRTUAL);
26015 
26016 	if (ksp == NULL)
26017 		return (NULL);
26018 
26019 	bcopy(&template, tcp_g_statp, sizeof (template));
26020 	ksp->ks_data = (void *)tcp_g_statp;
26021 
26022 	kstat_install(ksp);
26023 	return (ksp);
26024 }
26025 
26026 static void
26027 tcp_g_kstat_fini(kstat_t *ksp)
26028 {
26029 	if (ksp != NULL) {
26030 		kstat_delete(ksp);
26031 	}
26032 }
26033 
26034 
26035 static void *
26036 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
26037 {
26038 	kstat_t *ksp;
26039 
26040 	tcp_stat_t template = {
26041 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
26042 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
26043 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
26044 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
26045 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
26046 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
26047 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
26048 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
26049 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
26050 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
26051 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
26052 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
26053 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
26054 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
26055 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
26056 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
26057 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
26058 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
26059 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
26060 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
26061 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
26062 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
26063 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
26064 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
26065 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
26066 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
26067 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
26068 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
26069 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
26070 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
26071 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
26072 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
26073 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
26074 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
26075 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
26076 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
26077 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
26078 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
26079 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
26080 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
26081 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
26082 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
26083 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
26084 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
26085 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
26086 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
26087 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
26088 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
26089 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
26090 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
26091 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
26092 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
26093 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
26094 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
26095 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
26096 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
26097 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
26098 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
26099 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
26100 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
26101 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
26102 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
26103 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
26104 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
26105 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
26106 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
26107 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
26108 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
26109 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
26110 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
26111 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
26112 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
26113 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
26114 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
26115 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
26116 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
26117 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
26118 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
26119 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
26120 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
26121 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
26122 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
26123 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
26124 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
26125 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
26126 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
26127 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
26128 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
26129 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
26130 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
26131 	};
26132 
26133 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
26134 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26135 	    KSTAT_FLAG_VIRTUAL, stackid);
26136 
26137 	if (ksp == NULL)
26138 		return (NULL);
26139 
26140 	bcopy(&template, tcps_statisticsp, sizeof (template));
26141 	ksp->ks_data = (void *)tcps_statisticsp;
26142 	ksp->ks_private = (void *)(uintptr_t)stackid;
26143 
26144 	kstat_install(ksp);
26145 	return (ksp);
26146 }
26147 
26148 static void
26149 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
26150 {
26151 	if (ksp != NULL) {
26152 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26153 		kstat_delete_netstack(ksp, stackid);
26154 	}
26155 }
26156 
26157 /*
26158  * TCP Kstats implementation
26159  */
26160 static void *
26161 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
26162 {
26163 	kstat_t	*ksp;
26164 
26165 	tcp_named_kstat_t template = {
26166 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
26167 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
26168 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
26169 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
26170 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
26171 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
26172 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
26173 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
26174 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
26175 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
26176 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
26177 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
26178 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
26179 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
26180 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
26181 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
26182 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
26183 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
26184 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
26185 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
26186 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
26187 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
26188 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
26189 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
26190 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
26191 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
26192 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
26193 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
26194 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
26195 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
26196 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
26197 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
26198 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
26199 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
26200 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
26201 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
26202 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
26203 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
26204 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
26205 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
26206 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
26207 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
26208 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
26209 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
26210 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
26211 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
26212 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
26213 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
26214 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
26215 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
26216 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
26217 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
26218 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
26219 	};
26220 
26221 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
26222 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
26223 
26224 	if (ksp == NULL)
26225 		return (NULL);
26226 
26227 	template.rtoAlgorithm.value.ui32 = 4;
26228 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
26229 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
26230 	template.maxConn.value.i32 = -1;
26231 
26232 	bcopy(&template, ksp->ks_data, sizeof (template));
26233 	ksp->ks_update = tcp_kstat_update;
26234 	ksp->ks_private = (void *)(uintptr_t)stackid;
26235 
26236 	kstat_install(ksp);
26237 	return (ksp);
26238 }
26239 
26240 static void
26241 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
26242 {
26243 	if (ksp != NULL) {
26244 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26245 		kstat_delete_netstack(ksp, stackid);
26246 	}
26247 }
26248 
26249 static int
26250 tcp_kstat_update(kstat_t *kp, int rw)
26251 {
26252 	tcp_named_kstat_t *tcpkp;
26253 	tcp_t		*tcp;
26254 	connf_t		*connfp;
26255 	conn_t		*connp;
26256 	int 		i;
26257 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
26258 	netstack_t	*ns;
26259 	tcp_stack_t	*tcps;
26260 	ip_stack_t	*ipst;
26261 
26262 	if ((kp == NULL) || (kp->ks_data == NULL))
26263 		return (EIO);
26264 
26265 	if (rw == KSTAT_WRITE)
26266 		return (EACCES);
26267 
26268 	ns = netstack_find_by_stackid(stackid);
26269 	if (ns == NULL)
26270 		return (-1);
26271 	tcps = ns->netstack_tcp;
26272 	if (tcps == NULL) {
26273 		netstack_rele(ns);
26274 		return (-1);
26275 	}
26276 
26277 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
26278 
26279 	tcpkp->currEstab.value.ui32 = 0;
26280 
26281 	ipst = ns->netstack_ip;
26282 
26283 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
26284 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
26285 		connp = NULL;
26286 		while ((connp =
26287 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
26288 			tcp = connp->conn_tcp;
26289 			switch (tcp_snmp_state(tcp)) {
26290 			case MIB2_TCP_established:
26291 			case MIB2_TCP_closeWait:
26292 				tcpkp->currEstab.value.ui32++;
26293 				break;
26294 			}
26295 		}
26296 	}
26297 
26298 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
26299 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
26300 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
26301 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
26302 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
26303 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
26304 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
26305 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
26306 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
26307 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
26308 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
26309 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
26310 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
26311 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
26312 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
26313 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
26314 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
26315 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
26316 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
26317 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
26318 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
26319 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
26320 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
26321 	tcpkp->inDataInorderSegs.value.ui32 =
26322 	    tcps->tcps_mib.tcpInDataInorderSegs;
26323 	tcpkp->inDataInorderBytes.value.ui32 =
26324 	    tcps->tcps_mib.tcpInDataInorderBytes;
26325 	tcpkp->inDataUnorderSegs.value.ui32 =
26326 	    tcps->tcps_mib.tcpInDataUnorderSegs;
26327 	tcpkp->inDataUnorderBytes.value.ui32 =
26328 	    tcps->tcps_mib.tcpInDataUnorderBytes;
26329 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
26330 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
26331 	tcpkp->inDataPartDupSegs.value.ui32 =
26332 	    tcps->tcps_mib.tcpInDataPartDupSegs;
26333 	tcpkp->inDataPartDupBytes.value.ui32 =
26334 	    tcps->tcps_mib.tcpInDataPartDupBytes;
26335 	tcpkp->inDataPastWinSegs.value.ui32 =
26336 	    tcps->tcps_mib.tcpInDataPastWinSegs;
26337 	tcpkp->inDataPastWinBytes.value.ui32 =
26338 	    tcps->tcps_mib.tcpInDataPastWinBytes;
26339 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
26340 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
26341 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
26342 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
26343 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
26344 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
26345 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
26346 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
26347 	tcpkp->timKeepaliveProbe.value.ui32 =
26348 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
26349 	tcpkp->timKeepaliveDrop.value.ui32 =
26350 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
26351 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
26352 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
26353 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
26354 	tcpkp->outSackRetransSegs.value.ui32 =
26355 	    tcps->tcps_mib.tcpOutSackRetransSegs;
26356 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
26357 
26358 	netstack_rele(ns);
26359 	return (0);
26360 }
26361 
26362 void
26363 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
26364 {
26365 	uint16_t	hdr_len;
26366 	ipha_t		*ipha;
26367 	uint8_t		*nexthdrp;
26368 	tcph_t		*tcph;
26369 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26370 
26371 	/* Already has an eager */
26372 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26373 		TCP_STAT(tcps, tcp_reinput_syn);
26374 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26375 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
26376 		return;
26377 	}
26378 
26379 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
26380 	case IPV4_VERSION:
26381 		ipha = (ipha_t *)mp->b_rptr;
26382 		hdr_len = IPH_HDR_LENGTH(ipha);
26383 		break;
26384 	case IPV6_VERSION:
26385 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
26386 		    &hdr_len, &nexthdrp)) {
26387 			CONN_DEC_REF(connp);
26388 			freemsg(mp);
26389 			return;
26390 		}
26391 		break;
26392 	}
26393 
26394 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
26395 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
26396 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
26397 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
26398 	}
26399 
26400 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26401 	    SQ_FILL, SQTAG_TCP_REINPUT);
26402 }
26403 
26404 static int
26405 tcp_squeue_switch(int val)
26406 {
26407 	int rval = SQ_FILL;
26408 
26409 	switch (val) {
26410 	case 1:
26411 		rval = SQ_NODRAIN;
26412 		break;
26413 	case 2:
26414 		rval = SQ_PROCESS;
26415 		break;
26416 	default:
26417 		break;
26418 	}
26419 	return (rval);
26420 }
26421 
26422 /*
26423  * This is called once for each squeue - globally for all stack
26424  * instances.
26425  */
26426 static void
26427 tcp_squeue_add(squeue_t *sqp)
26428 {
26429 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
26430 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
26431 
26432 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
26433 	tcp_time_wait->tcp_time_wait_tid =
26434 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
26435 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
26436 	    CALLOUT_FLAG_ROUNDUP);
26437 	if (tcp_free_list_max_cnt == 0) {
26438 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
26439 		    max_ncpus : boot_max_ncpus);
26440 
26441 		/*
26442 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
26443 		 */
26444 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
26445 		    (tcp_ncpus * sizeof (tcp_t) * 100);
26446 	}
26447 	tcp_time_wait->tcp_free_list_cnt = 0;
26448 }
26449 
26450 static int
26451 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error, cred_t *cr, pid_t pid)
26452 {
26453 	mblk_t	*ire_mp = NULL;
26454 	mblk_t	*syn_mp;
26455 	mblk_t	*mdti;
26456 	mblk_t	*lsoi;
26457 	int	retval;
26458 	tcph_t	*tcph;
26459 	uint32_t	mss;
26460 	queue_t	*q = tcp->tcp_rq;
26461 	conn_t	*connp = tcp->tcp_connp;
26462 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26463 
26464 	if (error == 0) {
26465 		/*
26466 		 * Adapt Multidata information, if any.  The
26467 		 * following tcp_mdt_update routine will free
26468 		 * the message.
26469 		 */
26470 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
26471 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
26472 			    b_rptr)->mdt_capab, B_TRUE);
26473 			freemsg(mdti);
26474 		}
26475 
26476 		/*
26477 		 * Check to update LSO information with tcp, and
26478 		 * tcp_lso_update routine will free the message.
26479 		 */
26480 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
26481 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
26482 			    b_rptr)->lso_capab);
26483 			freemsg(lsoi);
26484 		}
26485 
26486 		/* Get the IRE, if we had requested for it */
26487 		if (mp != NULL)
26488 			ire_mp = tcp_ire_mp(&mp);
26489 
26490 		if (tcp->tcp_hard_binding) {
26491 			tcp->tcp_hard_binding = B_FALSE;
26492 			tcp->tcp_hard_bound = B_TRUE;
26493 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
26494 			if (retval != 0) {
26495 				error = EADDRINUSE;
26496 				goto bind_failed;
26497 			}
26498 		} else {
26499 			if (ire_mp != NULL)
26500 				freeb(ire_mp);
26501 			goto after_syn_sent;
26502 		}
26503 
26504 		retval = tcp_adapt_ire(tcp, ire_mp);
26505 		if (ire_mp != NULL)
26506 			freeb(ire_mp);
26507 		if (retval == 0) {
26508 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
26509 			    ENETUNREACH : EADDRNOTAVAIL);
26510 			goto ipcl_rm;
26511 		}
26512 		/*
26513 		 * Don't let an endpoint connect to itself.
26514 		 * Also checked in tcp_connect() but that
26515 		 * check can't handle the case when the
26516 		 * local IP address is INADDR_ANY.
26517 		 */
26518 		if (tcp->tcp_ipversion == IPV4_VERSION) {
26519 			if ((tcp->tcp_ipha->ipha_dst ==
26520 			    tcp->tcp_ipha->ipha_src) &&
26521 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26522 			    tcp->tcp_tcph->th_fport))) {
26523 				error = EADDRNOTAVAIL;
26524 				goto ipcl_rm;
26525 			}
26526 		} else {
26527 			if (IN6_ARE_ADDR_EQUAL(
26528 			    &tcp->tcp_ip6h->ip6_dst,
26529 			    &tcp->tcp_ip6h->ip6_src) &&
26530 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26531 			    tcp->tcp_tcph->th_fport))) {
26532 				error = EADDRNOTAVAIL;
26533 				goto ipcl_rm;
26534 			}
26535 		}
26536 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
26537 		/*
26538 		 * This should not be possible!  Just for
26539 		 * defensive coding...
26540 		 */
26541 		if (tcp->tcp_state != TCPS_SYN_SENT)
26542 			goto after_syn_sent;
26543 
26544 		if (is_system_labeled() &&
26545 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
26546 			error = EHOSTUNREACH;
26547 			goto ipcl_rm;
26548 		}
26549 
26550 		/*
26551 		 * tcp_adapt_ire() does not adjust
26552 		 * for TCP/IP header length.
26553 		 */
26554 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
26555 
26556 		/*
26557 		 * Just make sure our rwnd is at
26558 		 * least tcp_recv_hiwat_mss * MSS
26559 		 * large, and round up to the nearest
26560 		 * MSS.
26561 		 *
26562 		 * We do the round up here because
26563 		 * we need to get the interface
26564 		 * MTU first before we can do the
26565 		 * round up.
26566 		 */
26567 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
26568 		    tcps->tcps_recv_hiwat_minmss * mss);
26569 		if (!IPCL_IS_NONSTR(connp))
26570 			q->q_hiwat = tcp->tcp_rwnd;
26571 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
26572 		tcp_set_ws_value(tcp);
26573 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
26574 		    tcp->tcp_tcph->th_win);
26575 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
26576 			tcp->tcp_snd_ws_ok = B_TRUE;
26577 
26578 		/*
26579 		 * Set tcp_snd_ts_ok to true
26580 		 * so that tcp_xmit_mp will
26581 		 * include the timestamp
26582 		 * option in the SYN segment.
26583 		 */
26584 		if (tcps->tcps_tstamp_always ||
26585 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
26586 			tcp->tcp_snd_ts_ok = B_TRUE;
26587 		}
26588 
26589 		/*
26590 		 * tcp_snd_sack_ok can be set in
26591 		 * tcp_adapt_ire() if the sack metric
26592 		 * is set.  So check it here also.
26593 		 */
26594 		if (tcps->tcps_sack_permitted == 2 ||
26595 		    tcp->tcp_snd_sack_ok) {
26596 			if (tcp->tcp_sack_info == NULL) {
26597 				tcp->tcp_sack_info =
26598 				    kmem_cache_alloc(tcp_sack_info_cache,
26599 				    KM_SLEEP);
26600 			}
26601 			tcp->tcp_snd_sack_ok = B_TRUE;
26602 		}
26603 
26604 		/*
26605 		 * Should we use ECN?  Note that the current
26606 		 * default value (SunOS 5.9) of tcp_ecn_permitted
26607 		 * is 1.  The reason for doing this is that there
26608 		 * are equipments out there that will drop ECN
26609 		 * enabled IP packets.  Setting it to 1 avoids
26610 		 * compatibility problems.
26611 		 */
26612 		if (tcps->tcps_ecn_permitted == 2)
26613 			tcp->tcp_ecn_ok = B_TRUE;
26614 
26615 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
26616 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
26617 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
26618 		if (syn_mp) {
26619 			if (cr == NULL) {
26620 				cr = tcp->tcp_cred;
26621 				pid = tcp->tcp_cpid;
26622 			}
26623 			mblk_setcred(syn_mp, cr);
26624 			DB_CPID(syn_mp) = pid;
26625 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
26626 		}
26627 	after_syn_sent:
26628 		if (mp != NULL) {
26629 			ASSERT(mp->b_cont == NULL);
26630 			freeb(mp);
26631 		}
26632 		return (error);
26633 	} else {
26634 		/* error */
26635 		if (tcp->tcp_debug) {
26636 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
26637 			    "tcp_post_ip_bind: error == %d", error);
26638 		}
26639 		if (mp != NULL) {
26640 			freeb(mp);
26641 		}
26642 	}
26643 
26644 ipcl_rm:
26645 	/*
26646 	 * Need to unbind with classifier since we were just
26647 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
26648 	 */
26649 	tcp->tcp_hard_bound = B_FALSE;
26650 	tcp->tcp_hard_binding = B_FALSE;
26651 
26652 	ipcl_hash_remove(connp);
26653 
26654 bind_failed:
26655 	tcp->tcp_state = TCPS_IDLE;
26656 	if (tcp->tcp_ipversion == IPV4_VERSION)
26657 		tcp->tcp_ipha->ipha_src = 0;
26658 	else
26659 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
26660 	/*
26661 	 * Copy of the src addr. in tcp_t is needed since
26662 	 * the lookup funcs. can only look at tcp_t
26663 	 */
26664 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
26665 
26666 	tcph = tcp->tcp_tcph;
26667 	tcph->th_lport[0] = 0;
26668 	tcph->th_lport[1] = 0;
26669 	tcp_bind_hash_remove(tcp);
26670 	bzero(&connp->u_port, sizeof (connp->u_port));
26671 	/* blow away saved option results if any */
26672 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26673 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26674 
26675 	conn_delete_ire(tcp->tcp_connp, NULL);
26676 
26677 	return (error);
26678 }
26679 
26680 static int
26681 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
26682     boolean_t bind_to_req_port_only, cred_t *cr)
26683 {
26684 	in_port_t	mlp_port;
26685 	mlp_type_t 	addrtype, mlptype;
26686 	boolean_t	user_specified;
26687 	in_port_t	allocated_port;
26688 	in_port_t	requested_port = *requested_port_ptr;
26689 	conn_t		*connp;
26690 	zone_t		*zone;
26691 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26692 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
26693 
26694 	/*
26695 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
26696 	 */
26697 	if (cr == NULL)
26698 		cr = tcp->tcp_cred;
26699 	/*
26700 	 * Get a valid port (within the anonymous range and should not
26701 	 * be a privileged one) to use if the user has not given a port.
26702 	 * If multiple threads are here, they may all start with
26703 	 * with the same initial port. But, it should be fine as long as
26704 	 * tcp_bindi will ensure that no two threads will be assigned
26705 	 * the same port.
26706 	 *
26707 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
26708 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
26709 	 * unless TCP_ANONPRIVBIND option is set.
26710 	 */
26711 	mlptype = mlptSingle;
26712 	mlp_port = requested_port;
26713 	if (requested_port == 0) {
26714 		requested_port = tcp->tcp_anon_priv_bind ?
26715 		    tcp_get_next_priv_port(tcp) :
26716 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
26717 		    tcp, B_TRUE);
26718 		if (requested_port == 0) {
26719 			return (-TNOADDR);
26720 		}
26721 		user_specified = B_FALSE;
26722 
26723 		/*
26724 		 * If the user went through one of the RPC interfaces to create
26725 		 * this socket and RPC is MLP in this zone, then give him an
26726 		 * anonymous MLP.
26727 		 */
26728 		connp = tcp->tcp_connp;
26729 		if (connp->conn_anon_mlp && is_system_labeled()) {
26730 			zone = crgetzone(cr);
26731 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26732 			    IPV6_VERSION, &v6addr,
26733 			    tcps->tcps_netstack->netstack_ip);
26734 			if (addrtype == mlptSingle) {
26735 				return (-TNOADDR);
26736 			}
26737 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26738 			    PMAPPORT, addrtype);
26739 			mlp_port = PMAPPORT;
26740 		}
26741 	} else {
26742 		int i;
26743 		boolean_t priv = B_FALSE;
26744 
26745 		/*
26746 		 * If the requested_port is in the well-known privileged range,
26747 		 * verify that the stream was opened by a privileged user.
26748 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
26749 		 * but instead the code relies on:
26750 		 * - the fact that the address of the array and its size never
26751 		 *   changes
26752 		 * - the atomic assignment of the elements of the array
26753 		 */
26754 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
26755 			priv = B_TRUE;
26756 		} else {
26757 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
26758 				if (requested_port ==
26759 				    tcps->tcps_g_epriv_ports[i]) {
26760 					priv = B_TRUE;
26761 					break;
26762 				}
26763 			}
26764 		}
26765 		if (priv) {
26766 			if (secpolicy_net_privaddr(cr, requested_port,
26767 			    IPPROTO_TCP) != 0) {
26768 				if (tcp->tcp_debug) {
26769 					(void) strlog(TCP_MOD_ID, 0, 1,
26770 					    SL_ERROR|SL_TRACE,
26771 					    "tcp_bind: no priv for port %d",
26772 					    requested_port);
26773 				}
26774 				return (-TACCES);
26775 			}
26776 		}
26777 		user_specified = B_TRUE;
26778 
26779 		connp = tcp->tcp_connp;
26780 		if (is_system_labeled()) {
26781 			zone = crgetzone(cr);
26782 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26783 			    IPV6_VERSION, &v6addr,
26784 			    tcps->tcps_netstack->netstack_ip);
26785 			if (addrtype == mlptSingle) {
26786 				return (-TNOADDR);
26787 			}
26788 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26789 			    requested_port, addrtype);
26790 		}
26791 	}
26792 
26793 	if (mlptype != mlptSingle) {
26794 		if (secpolicy_net_bindmlp(cr) != 0) {
26795 			if (tcp->tcp_debug) {
26796 				(void) strlog(TCP_MOD_ID, 0, 1,
26797 				    SL_ERROR|SL_TRACE,
26798 				    "tcp_bind: no priv for multilevel port %d",
26799 				    requested_port);
26800 			}
26801 			return (-TACCES);
26802 		}
26803 
26804 		/*
26805 		 * If we're specifically binding a shared IP address and the
26806 		 * port is MLP on shared addresses, then check to see if this
26807 		 * zone actually owns the MLP.  Reject if not.
26808 		 */
26809 		if (mlptype == mlptShared && addrtype == mlptShared) {
26810 			/*
26811 			 * No need to handle exclusive-stack zones since
26812 			 * ALL_ZONES only applies to the shared stack.
26813 			 */
26814 			zoneid_t mlpzone;
26815 
26816 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26817 			    htons(mlp_port));
26818 			if (connp->conn_zoneid != mlpzone) {
26819 				if (tcp->tcp_debug) {
26820 					(void) strlog(TCP_MOD_ID, 0, 1,
26821 					    SL_ERROR|SL_TRACE,
26822 					    "tcp_bind: attempt to bind port "
26823 					    "%d on shared addr in zone %d "
26824 					    "(should be %d)",
26825 					    mlp_port, connp->conn_zoneid,
26826 					    mlpzone);
26827 				}
26828 				return (-TACCES);
26829 			}
26830 		}
26831 
26832 		if (!user_specified) {
26833 			int err;
26834 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26835 			    requested_port, B_TRUE);
26836 			if (err != 0) {
26837 				if (tcp->tcp_debug) {
26838 					(void) strlog(TCP_MOD_ID, 0, 1,
26839 					    SL_ERROR|SL_TRACE,
26840 					    "tcp_bind: cannot establish anon "
26841 					    "MLP for port %d",
26842 					    requested_port);
26843 				}
26844 				return (err);
26845 			}
26846 			connp->conn_anon_port = B_TRUE;
26847 		}
26848 		connp->conn_mlp_type = mlptype;
26849 	}
26850 
26851 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26852 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26853 
26854 	if (allocated_port == 0) {
26855 		connp->conn_mlp_type = mlptSingle;
26856 		if (connp->conn_anon_port) {
26857 			connp->conn_anon_port = B_FALSE;
26858 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26859 			    requested_port, B_FALSE);
26860 		}
26861 		if (bind_to_req_port_only) {
26862 			if (tcp->tcp_debug) {
26863 				(void) strlog(TCP_MOD_ID, 0, 1,
26864 				    SL_ERROR|SL_TRACE,
26865 				    "tcp_bind: requested addr busy");
26866 			}
26867 			return (-TADDRBUSY);
26868 		} else {
26869 			/* If we are out of ports, fail the bind. */
26870 			if (tcp->tcp_debug) {
26871 				(void) strlog(TCP_MOD_ID, 0, 1,
26872 				    SL_ERROR|SL_TRACE,
26873 				    "tcp_bind: out of ports?");
26874 			}
26875 			return (-TNOADDR);
26876 		}
26877 	}
26878 
26879 	/* Pass the allocated port back */
26880 	*requested_port_ptr = allocated_port;
26881 	return (0);
26882 }
26883 
26884 static int
26885 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26886     boolean_t bind_to_req_port_only)
26887 {
26888 	tcp_t	*tcp = connp->conn_tcp;
26889 
26890 	sin_t	*sin;
26891 	sin6_t  *sin6;
26892 	sin6_t		sin6addr;
26893 	in_port_t requested_port;
26894 	ipaddr_t	v4addr;
26895 	in6_addr_t	v6addr;
26896 	uint_t	origipversion;
26897 	int	error = 0;
26898 
26899 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
26900 
26901 	if (tcp->tcp_state == TCPS_BOUND) {
26902 		return (0);
26903 	} else if (tcp->tcp_state > TCPS_BOUND) {
26904 		if (tcp->tcp_debug) {
26905 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26906 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26907 		}
26908 		return (-TOUTSTATE);
26909 	}
26910 	origipversion = tcp->tcp_ipversion;
26911 
26912 	if (sa != NULL && !OK_32PTR((char *)sa)) {
26913 		if (tcp->tcp_debug) {
26914 			(void) strlog(TCP_MOD_ID, 0, 1,
26915 			    SL_ERROR|SL_TRACE,
26916 			    "tcp_bind: bad address parameter, "
26917 			    "address %p, len %d",
26918 			    (void *)sa, len);
26919 		}
26920 		return (-TPROTO);
26921 	}
26922 
26923 	switch (len) {
26924 	case 0:		/* request for a generic port */
26925 		if (tcp->tcp_family == AF_INET) {
26926 			sin = (sin_t *)&sin6addr;
26927 			*sin = sin_null;
26928 			sin->sin_family = AF_INET;
26929 			tcp->tcp_ipversion = IPV4_VERSION;
26930 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
26931 		} else {
26932 			ASSERT(tcp->tcp_family == AF_INET6);
26933 			sin6 = (sin6_t *)&sin6addr;
26934 			*sin6 = sin6_null;
26935 			sin6->sin6_family = AF_INET6;
26936 			tcp->tcp_ipversion = IPV6_VERSION;
26937 			V6_SET_ZERO(v6addr);
26938 		}
26939 		requested_port = 0;
26940 		break;
26941 
26942 	case sizeof (sin_t):	/* Complete IPv4 address */
26943 		sin = (sin_t *)sa;
26944 		/*
26945 		 * With sockets sockfs will accept bogus sin_family in
26946 		 * bind() and replace it with the family used in the socket
26947 		 * call.
26948 		 */
26949 		if (sin->sin_family != AF_INET ||
26950 		    tcp->tcp_family != AF_INET) {
26951 			return (EAFNOSUPPORT);
26952 		}
26953 		requested_port = ntohs(sin->sin_port);
26954 		tcp->tcp_ipversion = IPV4_VERSION;
26955 		v4addr = sin->sin_addr.s_addr;
26956 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
26957 		break;
26958 
26959 	case sizeof (sin6_t): /* Complete IPv6 address */
26960 		sin6 = (sin6_t *)sa;
26961 		if (sin6->sin6_family != AF_INET6 ||
26962 		    tcp->tcp_family != AF_INET6) {
26963 			return (EAFNOSUPPORT);
26964 		}
26965 		requested_port = ntohs(sin6->sin6_port);
26966 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
26967 		    IPV4_VERSION : IPV6_VERSION;
26968 		v6addr = sin6->sin6_addr;
26969 		break;
26970 
26971 	default:
26972 		if (tcp->tcp_debug) {
26973 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26974 			    "tcp_bind: bad address length, %d", len);
26975 		}
26976 		return (EAFNOSUPPORT);
26977 		/* return (-TBADADDR); */
26978 	}
26979 
26980 	tcp->tcp_bound_source_v6 = v6addr;
26981 
26982 	/* Check for change in ipversion */
26983 	if (origipversion != tcp->tcp_ipversion) {
26984 		ASSERT(tcp->tcp_family == AF_INET6);
26985 		error = tcp->tcp_ipversion == IPV6_VERSION ?
26986 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
26987 		if (error) {
26988 			return (ENOMEM);
26989 		}
26990 	}
26991 
26992 	/*
26993 	 * Initialize family specific fields. Copy of the src addr.
26994 	 * in tcp_t is needed for the lookup funcs.
26995 	 */
26996 	if (tcp->tcp_ipversion == IPV6_VERSION) {
26997 		tcp->tcp_ip6h->ip6_src = v6addr;
26998 	} else {
26999 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
27000 	}
27001 	tcp->tcp_ip_src_v6 = v6addr;
27002 
27003 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
27004 
27005 	error = tcp_bind_select_lport(tcp, &requested_port,
27006 	    bind_to_req_port_only, cr);
27007 
27008 	return (error);
27009 }
27010 
27011 /*
27012  * Return unix error is tli error is TSYSERR, otherwise return a negative
27013  * tli error.
27014  */
27015 int
27016 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
27017     boolean_t bind_to_req_port_only)
27018 {
27019 	int error;
27020 	tcp_t *tcp = connp->conn_tcp;
27021 
27022 	if (tcp->tcp_state >= TCPS_BOUND) {
27023 		if (tcp->tcp_debug) {
27024 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27025 			    "tcp_bind: bad state, %d", tcp->tcp_state);
27026 		}
27027 		return (-TOUTSTATE);
27028 	}
27029 
27030 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
27031 	if (error != 0)
27032 		return (error);
27033 
27034 	ASSERT(tcp->tcp_state == TCPS_BOUND);
27035 
27036 	tcp->tcp_conn_req_max = 0;
27037 
27038 	/*
27039 	 * We need to make sure that the conn_recv is set to a non-null
27040 	 * value before we insert the conn into the classifier table.
27041 	 * This is to avoid a race with an incoming packet which does an
27042 	 * ipcl_classify().
27043 	 */
27044 	connp->conn_recv = tcp_conn_request;
27045 
27046 	if (tcp->tcp_family == AF_INET6) {
27047 		ASSERT(tcp->tcp_connp->conn_af_isv6);
27048 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27049 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
27050 	} else {
27051 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
27052 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
27053 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
27054 	}
27055 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27056 }
27057 
27058 int
27059 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
27060     socklen_t len, cred_t *cr)
27061 {
27062 	int 		error;
27063 	conn_t		*connp = (conn_t *)proto_handle;
27064 	squeue_t	*sqp = connp->conn_sqp;
27065 
27066 	ASSERT(sqp != NULL);
27067 
27068 	error = squeue_synch_enter(sqp, connp, 0);
27069 	if (error != 0) {
27070 		/* failed to enter */
27071 		return (ENOSR);
27072 	}
27073 
27074 	/* binding to a NULL address really means unbind */
27075 	if (sa == NULL) {
27076 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
27077 			error = tcp_do_unbind(connp);
27078 		else
27079 			error = EINVAL;
27080 	} else {
27081 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
27082 	}
27083 
27084 	squeue_synch_exit(sqp, connp);
27085 
27086 	if (error < 0) {
27087 		if (error == -TOUTSTATE)
27088 			error = EINVAL;
27089 		else
27090 			error = proto_tlitosyserr(-error);
27091 	}
27092 
27093 	return (error);
27094 }
27095 
27096 /*
27097  * If the return value from this function is positive, it's a UNIX error.
27098  * Otherwise, if it's negative, then the absolute value is a TLI error.
27099  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
27100  */
27101 int
27102 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
27103     cred_t *cr, pid_t pid)
27104 {
27105 	tcp_t		*tcp = connp->conn_tcp;
27106 	sin_t		*sin = (sin_t *)sa;
27107 	sin6_t		*sin6 = (sin6_t *)sa;
27108 	ipaddr_t	*dstaddrp;
27109 	in_port_t	dstport;
27110 	uint_t		srcid;
27111 	int		error = 0;
27112 
27113 	switch (len) {
27114 	default:
27115 		/*
27116 		 * Should never happen
27117 		 */
27118 		return (EINVAL);
27119 
27120 	case sizeof (sin_t):
27121 		sin = (sin_t *)sa;
27122 		if (sin->sin_port == 0) {
27123 			return (-TBADADDR);
27124 		}
27125 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
27126 			return (EAFNOSUPPORT);
27127 		}
27128 		break;
27129 
27130 	case sizeof (sin6_t):
27131 		sin6 = (sin6_t *)sa;
27132 		if (sin6->sin6_port == 0) {
27133 			return (-TBADADDR);
27134 		}
27135 		break;
27136 	}
27137 	/*
27138 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
27139 	 * make sure that the template IP header in the tcp structure is an
27140 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
27141 	 * need to this before we call tcp_bindi() so that the port lookup
27142 	 * code will look for ports in the correct port space (IPv4 and
27143 	 * IPv6 have separate port spaces).
27144 	 */
27145 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
27146 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
27147 		int err = 0;
27148 
27149 		err = tcp_header_init_ipv4(tcp);
27150 			if (err != 0) {
27151 				error = ENOMEM;
27152 				goto connect_failed;
27153 			}
27154 		if (tcp->tcp_lport != 0)
27155 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
27156 	}
27157 
27158 	switch (tcp->tcp_state) {
27159 	case TCPS_LISTEN:
27160 		/*
27161 		 * Listening sockets are not allowed to issue connect().
27162 		 */
27163 		if (IPCL_IS_NONSTR(connp))
27164 			return (EOPNOTSUPP);
27165 		/* FALLTHRU */
27166 	case TCPS_IDLE:
27167 		/*
27168 		 * We support quick connect, refer to comments in
27169 		 * tcp_connect_*()
27170 		 */
27171 		/* FALLTHRU */
27172 	case TCPS_BOUND:
27173 		/*
27174 		 * We must bump the generation before the operation start.
27175 		 * This is done to ensure that any upcall made later on sends
27176 		 * up the right generation to the socket.
27177 		 */
27178 		SOCK_CONNID_BUMP(tcp->tcp_connid);
27179 
27180 		if (tcp->tcp_family == AF_INET6) {
27181 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
27182 				return (tcp_connect_ipv6(tcp,
27183 				    &sin6->sin6_addr,
27184 				    sin6->sin6_port, sin6->sin6_flowinfo,
27185 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
27186 				    cr, pid));
27187 			}
27188 			/*
27189 			 * Destination adress is mapped IPv6 address.
27190 			 * Source bound address should be unspecified or
27191 			 * IPv6 mapped address as well.
27192 			 */
27193 			if (!IN6_IS_ADDR_UNSPECIFIED(
27194 			    &tcp->tcp_bound_source_v6) &&
27195 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
27196 				return (EADDRNOTAVAIL);
27197 			}
27198 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
27199 			dstport = sin6->sin6_port;
27200 			srcid = sin6->__sin6_src_id;
27201 		} else {
27202 			dstaddrp = &sin->sin_addr.s_addr;
27203 			dstport = sin->sin_port;
27204 			srcid = 0;
27205 		}
27206 
27207 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
27208 		    pid);
27209 		break;
27210 	default:
27211 		return (-TOUTSTATE);
27212 	}
27213 	/*
27214 	 * Note: Code below is the "failure" case
27215 	 */
27216 connect_failed:
27217 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
27218 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
27219 	return (error);
27220 }
27221 
27222 int
27223 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
27224     socklen_t len, sock_connid_t *id, cred_t *cr)
27225 {
27226 	conn_t		*connp = (conn_t *)proto_handle;
27227 	tcp_t		*tcp = connp->conn_tcp;
27228 	squeue_t	*sqp = connp->conn_sqp;
27229 	int		error;
27230 
27231 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
27232 	if (error != 0) {
27233 		return (error);
27234 	}
27235 
27236 	error = squeue_synch_enter(sqp, connp, 0);
27237 	if (error != 0) {
27238 		/* failed to enter */
27239 		return (ENOSR);
27240 	}
27241 
27242 	/*
27243 	 * TCP supports quick connect, so no need to do an implicit bind
27244 	 */
27245 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
27246 	if (error == 0) {
27247 		*id = connp->conn_tcp->tcp_connid;
27248 	} else if (error < 0) {
27249 		if (error == -TOUTSTATE) {
27250 			switch (connp->conn_tcp->tcp_state) {
27251 			case TCPS_SYN_SENT:
27252 				error = EALREADY;
27253 				break;
27254 			case TCPS_ESTABLISHED:
27255 				error = EISCONN;
27256 				break;
27257 			case TCPS_LISTEN:
27258 				error = EOPNOTSUPP;
27259 				break;
27260 			default:
27261 				error = EINVAL;
27262 				break;
27263 			}
27264 		} else {
27265 			error = proto_tlitosyserr(-error);
27266 		}
27267 	}
27268 done:
27269 	squeue_synch_exit(sqp, connp);
27270 
27271 	return ((error == 0) ? EINPROGRESS : error);
27272 }
27273 
27274 /* ARGSUSED */
27275 sock_lower_handle_t
27276 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
27277     uint_t *smodep, int *errorp, int flags, cred_t *credp)
27278 {
27279 	conn_t		*connp;
27280 	boolean_t	isv6 = family == AF_INET6;
27281 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
27282 	    (proto != 0 && proto != IPPROTO_TCP)) {
27283 		*errorp = EPROTONOSUPPORT;
27284 		return (NULL);
27285 	}
27286 
27287 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
27288 	if (connp == NULL) {
27289 		return (NULL);
27290 	}
27291 
27292 	/*
27293 	 * Put the ref for TCP. Ref for IP was already put
27294 	 * by ipcl_conn_create. Also Make the conn_t globally
27295 	 * visible to walkers
27296 	 */
27297 	mutex_enter(&connp->conn_lock);
27298 	CONN_INC_REF_LOCKED(connp);
27299 	ASSERT(connp->conn_ref == 2);
27300 	connp->conn_state_flags &= ~CONN_INCIPIENT;
27301 
27302 	connp->conn_flags |= IPCL_NONSTR;
27303 	mutex_exit(&connp->conn_lock);
27304 
27305 	ASSERT(errorp != NULL);
27306 	*errorp = 0;
27307 	*sock_downcalls = &sock_tcp_downcalls;
27308 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
27309 	    SM_SENDFILESUPP;
27310 
27311 	return ((sock_lower_handle_t)connp);
27312 }
27313 
27314 /* ARGSUSED */
27315 void
27316 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
27317     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
27318 {
27319 	conn_t *connp = (conn_t *)proto_handle;
27320 	struct sock_proto_props sopp;
27321 
27322 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
27323 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
27324 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
27325 
27326 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
27327 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
27328 	sopp.sopp_maxpsz = INFPSZ;
27329 	sopp.sopp_maxblk = INFPSZ;
27330 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
27331 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
27332 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
27333 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
27334 	    tcp_rinfo.mi_minpsz;
27335 
27336 	connp->conn_upcalls = sock_upcalls;
27337 	connp->conn_upper_handle = sock_handle;
27338 
27339 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
27340 }
27341 
27342 /* ARGSUSED */
27343 int
27344 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
27345 {
27346 	conn_t *connp = (conn_t *)proto_handle;
27347 
27348 	tcp_close_common(connp, flags);
27349 
27350 	ip_free_helper_stream(connp);
27351 
27352 	/*
27353 	 * Drop IP's reference on the conn. This is the last reference
27354 	 * on the connp if the state was less than established. If the
27355 	 * connection has gone into timewait state, then we will have
27356 	 * one ref for the TCP and one more ref (total of two) for the
27357 	 * classifier connected hash list (a timewait connections stays
27358 	 * in connected hash till closed).
27359 	 *
27360 	 * We can't assert the references because there might be other
27361 	 * transient reference places because of some walkers or queued
27362 	 * packets in squeue for the timewait state.
27363 	 */
27364 	CONN_DEC_REF(connp);
27365 	return (0);
27366 }
27367 
27368 /* ARGSUSED */
27369 int
27370 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
27371     cred_t *cr)
27372 {
27373 	tcp_t		*tcp;
27374 	uint32_t	msize;
27375 	conn_t *connp = (conn_t *)proto_handle;
27376 	int32_t		tcpstate;
27377 
27378 	ASSERT(connp->conn_ref >= 2);
27379 
27380 	if (msg->msg_controllen != 0) {
27381 		return (EOPNOTSUPP);
27382 
27383 	}
27384 	switch (DB_TYPE(mp)) {
27385 	case M_DATA:
27386 		tcp = connp->conn_tcp;
27387 		ASSERT(tcp != NULL);
27388 
27389 		tcpstate = tcp->tcp_state;
27390 		if (tcpstate < TCPS_ESTABLISHED) {
27391 			freemsg(mp);
27392 			return (ENOTCONN);
27393 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
27394 			freemsg(mp);
27395 			return (EPIPE);
27396 		}
27397 
27398 		msize = msgdsize(mp);
27399 
27400 		mutex_enter(&tcp->tcp_non_sq_lock);
27401 		tcp->tcp_squeue_bytes += msize;
27402 		/*
27403 		 * Squeue Flow Control
27404 		 */
27405 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
27406 			tcp_setqfull(tcp);
27407 		}
27408 		mutex_exit(&tcp->tcp_non_sq_lock);
27409 
27410 		/*
27411 		 * The application may pass in an address in the msghdr, but
27412 		 * we ignore the address on connection-oriented sockets.
27413 		 * Just like BSD this code does not generate an error for
27414 		 * TCP (a CONNREQUIRED socket) when sending to an address
27415 		 * passed in with sendto/sendmsg. Instead the data is
27416 		 * delivered on the connection as if no address had been
27417 		 * supplied.
27418 		 */
27419 		CONN_INC_REF(connp);
27420 
27421 		if (msg != NULL && msg->msg_flags & MSG_OOB) {
27422 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
27423 			    tcp_output_urgent, connp, tcp_squeue_flag,
27424 			    SQTAG_TCP_OUTPUT);
27425 		} else {
27426 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
27427 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
27428 		}
27429 
27430 		return (0);
27431 
27432 	default:
27433 		ASSERT(0);
27434 	}
27435 
27436 	freemsg(mp);
27437 	return (0);
27438 }
27439 
27440 /* ARGSUSED */
27441 void
27442 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
27443 {
27444 	int len;
27445 	uint32_t msize;
27446 	conn_t *connp = (conn_t *)arg;
27447 	tcp_t *tcp = connp->conn_tcp;
27448 
27449 	msize = msgdsize(mp);
27450 
27451 	len = msize - 1;
27452 	if (len < 0) {
27453 		freemsg(mp);
27454 		return;
27455 	}
27456 
27457 	/*
27458 	 * Try to force urgent data out on the wire.
27459 	 * Even if we have unsent data this will
27460 	 * at least send the urgent flag.
27461 	 * XXX does not handle more flag correctly.
27462 	 */
27463 	len += tcp->tcp_unsent;
27464 	len += tcp->tcp_snxt;
27465 	tcp->tcp_urg = len;
27466 	tcp->tcp_valid_bits |= TCP_URG_VALID;
27467 
27468 	/* Bypass tcp protocol for fused tcp loopback */
27469 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
27470 		return;
27471 	tcp_wput_data(tcp, mp, B_TRUE);
27472 }
27473 
27474 /* ARGSUSED */
27475 int
27476 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27477     socklen_t *addrlen, cred_t *cr)
27478 {
27479 	sin_t   *sin;
27480 	sin6_t  *sin6;
27481 	conn_t	*connp = (conn_t *)proto_handle;
27482 	tcp_t	*tcp = connp->conn_tcp;
27483 
27484 	ASSERT(tcp != NULL);
27485 	if (tcp->tcp_state < TCPS_SYN_RCVD)
27486 		return (ENOTCONN);
27487 
27488 	addr->sa_family = tcp->tcp_family;
27489 	switch (tcp->tcp_family) {
27490 	case AF_INET:
27491 		if (*addrlen < sizeof (sin_t))
27492 			return (EINVAL);
27493 
27494 		sin = (sin_t *)addr;
27495 		*sin = sin_null;
27496 		sin->sin_family = AF_INET;
27497 		if (tcp->tcp_ipversion == IPV4_VERSION) {
27498 			IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
27499 			    sin->sin_addr.s_addr);
27500 		}
27501 		sin->sin_port = tcp->tcp_fport;
27502 		*addrlen = sizeof (struct sockaddr_in);
27503 		break;
27504 	case AF_INET6:
27505 		sin6 = (sin6_t *)addr;
27506 		*sin6 = sin6_null;
27507 		sin6->sin6_family = AF_INET6;
27508 
27509 		if (*addrlen < sizeof (struct sockaddr_in6))
27510 			return (EINVAL);
27511 
27512 		if (tcp->tcp_ipversion == IPV6_VERSION) {
27513 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
27514 			    ~IPV6_VERS_AND_FLOW_MASK;
27515 		}
27516 
27517 		sin6->sin6_addr = tcp->tcp_remote_v6;
27518 		sin6->sin6_port = tcp->tcp_fport;
27519 		*addrlen = sizeof (struct sockaddr_in6);
27520 		break;
27521 	}
27522 	return (0);
27523 }
27524 
27525 /* ARGSUSED */
27526 int
27527 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27528     socklen_t *addrlenp, cred_t *cr)
27529 {
27530 	sin_t   *sin;
27531 	sin6_t  *sin6;
27532 	conn_t	*connp = (conn_t *)proto_handle;
27533 	tcp_t	*tcp = connp->conn_tcp;
27534 
27535 	switch (tcp->tcp_family) {
27536 	case AF_INET:
27537 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
27538 		if (*addrlenp < sizeof (sin_t))
27539 			return (EINVAL);
27540 		sin = (sin_t *)addr;
27541 		*sin = sin_null;
27542 		sin->sin_family = AF_INET;
27543 		*addrlenp = sizeof (sin_t);
27544 		if (tcp->tcp_state >= TCPS_BOUND) {
27545 			sin->sin_addr.s_addr =  tcp->tcp_ipha->ipha_src;
27546 			sin->sin_port = tcp->tcp_lport;
27547 		}
27548 		break;
27549 
27550 	case AF_INET6:
27551 		if (*addrlenp < sizeof (sin6_t))
27552 			return (EINVAL);
27553 		sin6 = (sin6_t *)addr;
27554 		*sin6 = sin6_null;
27555 		sin6->sin6_family = AF_INET6;
27556 		*addrlenp = sizeof (sin6_t);
27557 		if (tcp->tcp_state >= TCPS_BOUND) {
27558 			sin6->sin6_port = tcp->tcp_lport;
27559 			if (tcp->tcp_ipversion == IPV4_VERSION) {
27560 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
27561 				    &sin6->sin6_addr);
27562 			} else {
27563 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
27564 			}
27565 		}
27566 		break;
27567 	}
27568 	return (0);
27569 }
27570 
27571 /*
27572  * tcp_fallback
27573  *
27574  * A direct socket is falling back to using STREAMS. Hanging
27575  * off of the queue is a temporary tcp_t, which was created using
27576  * tcp_open(). The tcp_open() was called as part of the regular
27577  * sockfs create path, i.e., the SO_SOCKSTR flag is passed down,
27578  * and therefore the temporary tcp_t is marked to be a socket
27579  * (i.e., IPCL_SOCKET, tcp_issocket). So the optimizations
27580  * introduced by FireEngine will be used.
27581  *
27582  * The tcp_t associated with the socket falling back will
27583  * still be marked as a socket, although the direct socket flag
27584  * (IPCL_NONSTR) is removed. A fall back to true TPI semantics
27585  * will not take place until a _SIOCSOCKFALLBACK ioctl is issued.
27586  *
27587  * If the above mentioned behavior, i.e., the tmp tcp_t is created
27588  * as a STREAMS/TPI endpoint, then we will need to do more work here.
27589  * Such as inserting the direct socket into the acceptor hash.
27590  */
27591 void
27592 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
27593     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
27594 {
27595 	tcp_t			*tcp, *eager;
27596 	conn_t 			*connp = (conn_t *)proto_handle;
27597 	int			error;
27598 	struct T_capability_ack tca;
27599 	struct sockaddr_in6	laddr, faddr;
27600 	socklen_t 		laddrlen, faddrlen;
27601 	short			opts;
27602 	struct stroptions	*stropt;
27603 	mblk_t			*stropt_mp;
27604 	mblk_t			*mp;
27605 	mblk_t			*conn_ind_head = NULL;
27606 	mblk_t			*conn_ind_tail = NULL;
27607 	mblk_t			*ordrel_mp;
27608 	mblk_t			*fused_sigurp_mp;
27609 
27610 	tcp = connp->conn_tcp;
27611 	/*
27612 	 * No support for acceptor fallback
27613 	 */
27614 	ASSERT(q->q_qinfo != &tcp_acceptor_rinit);
27615 
27616 	stropt_mp = allocb_wait(sizeof (*stropt), BPRI_HI, STR_NOSIG, NULL);
27617 
27618 	/* Pre-allocate the T_ordrel_ind mblk. */
27619 	ASSERT(tcp->tcp_ordrel_mp == NULL);
27620 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
27621 	    STR_NOSIG, NULL);
27622 	ordrel_mp->b_datap->db_type = M_PROTO;
27623 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
27624 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
27625 
27626 	/* Pre-allocate the M_PCSIG anyway */
27627 	fused_sigurp_mp = allocb_wait(1, BPRI_HI, STR_NOSIG, NULL);
27628 
27629 	/*
27630 	 * Enter the squeue so that no new packets can come in
27631 	 */
27632 	error = squeue_synch_enter(connp->conn_sqp, connp, 0);
27633 	if (error != 0) {
27634 		/* failed to enter, free all the pre-allocated messages. */
27635 		freeb(stropt_mp);
27636 		freeb(ordrel_mp);
27637 		freeb(fused_sigurp_mp);
27638 		return;
27639 	}
27640 
27641 	/* Disable I/OAT during fallback */
27642 	tcp->tcp_sodirect = NULL;
27643 
27644 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
27645 	connp->conn_minor_arena = WR(q)->q_ptr;
27646 
27647 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
27648 
27649 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
27650 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
27651 
27652 	WR(q)->q_qinfo = &tcp_sock_winit;
27653 
27654 	if (!direct_sockfs)
27655 		tcp_disable_direct_sockfs(tcp);
27656 
27657 	/*
27658 	 * free the helper stream
27659 	 */
27660 	ip_free_helper_stream(connp);
27661 
27662 	/*
27663 	 * Notify the STREAM head about options
27664 	 */
27665 	DB_TYPE(stropt_mp) = M_SETOPTS;
27666 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27667 	stropt_mp->b_wptr += sizeof (struct stroptions);
27668 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27669 	stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
27670 
27671 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
27672 	    tcp->tcp_tcps->tcps_wroff_xtra);
27673 	if (tcp->tcp_snd_sack_ok)
27674 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
27675 	stropt->so_hiwat = tcp->tcp_fused ?
27676 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
27677 	    MAX(tcp->tcp_recv_hiwater, tcp->tcp_tcps->tcps_sth_rcv_hiwat);
27678 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
27679 
27680 	putnext(RD(q), stropt_mp);
27681 
27682 	/*
27683 	 * Collect the information needed to sync with the sonode
27684 	 */
27685 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
27686 
27687 	laddrlen = faddrlen = sizeof (sin6_t);
27688 	(void) tcp_getsockname(proto_handle, (struct sockaddr *)&laddr,
27689 	    &laddrlen, CRED());
27690 	error = tcp_getpeername(proto_handle, (struct sockaddr *)&faddr,
27691 	    &faddrlen, CRED());
27692 	if (error != 0)
27693 		faddrlen = 0;
27694 
27695 	opts = 0;
27696 	if (tcp->tcp_oobinline)
27697 		opts |= SO_OOBINLINE;
27698 	if (tcp->tcp_dontroute)
27699 		opts |= SO_DONTROUTE;
27700 
27701 	/*
27702 	 * Notify the socket that the protocol is now quiescent,
27703 	 * and it's therefore safe move data from the socket
27704 	 * to the stream head.
27705 	 */
27706 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
27707 	    (struct sockaddr *)&laddr, laddrlen,
27708 	    (struct sockaddr *)&faddr, faddrlen, opts);
27709 
27710 	while ((mp = tcp->tcp_rcv_list) != NULL) {
27711 		tcp->tcp_rcv_list = mp->b_next;
27712 		mp->b_next = NULL;
27713 		putnext(q, mp);
27714 	}
27715 	tcp->tcp_rcv_last_head = NULL;
27716 	tcp->tcp_rcv_last_tail = NULL;
27717 	tcp->tcp_rcv_cnt = 0;
27718 
27719 	/*
27720 	 * No longer a direct socket
27721 	 */
27722 	connp->conn_flags &= ~IPCL_NONSTR;
27723 
27724 	tcp->tcp_ordrel_mp = ordrel_mp;
27725 
27726 	if (tcp->tcp_fused) {
27727 		ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
27728 		tcp->tcp_fused_sigurg_mp = fused_sigurp_mp;
27729 	} else {
27730 		freeb(fused_sigurp_mp);
27731 	}
27732 
27733 	/*
27734 	 * Send T_CONN_IND messages for all ESTABLISHED connections.
27735 	 */
27736 	mutex_enter(&tcp->tcp_eager_lock);
27737 	for (eager = tcp->tcp_eager_next_q; eager != NULL;
27738 	    eager = eager->tcp_eager_next_q) {
27739 		mp = eager->tcp_conn.tcp_eager_conn_ind;
27740 
27741 		eager->tcp_conn.tcp_eager_conn_ind = NULL;
27742 		ASSERT(mp != NULL);
27743 		/*
27744 		 * TLI/XTI applications will get confused by
27745 		 * sending eager as an option since it violates
27746 		 * the option semantics. So remove the eager as
27747 		 * option since TLI/XTI app doesn't need it anyway.
27748 		 */
27749 		if (!TCP_IS_SOCKET(tcp)) {
27750 			struct T_conn_ind *conn_ind;
27751 
27752 			conn_ind = (struct T_conn_ind *)mp->b_rptr;
27753 			conn_ind->OPT_length = 0;
27754 			conn_ind->OPT_offset = 0;
27755 		}
27756 		if (conn_ind_head == NULL) {
27757 			conn_ind_head = mp;
27758 		} else {
27759 			conn_ind_tail->b_next = mp;
27760 		}
27761 		conn_ind_tail = mp;
27762 	}
27763 	mutex_exit(&tcp->tcp_eager_lock);
27764 
27765 	mp = conn_ind_head;
27766 	while (mp != NULL) {
27767 		mblk_t *nmp = mp->b_next;
27768 		mp->b_next = NULL;
27769 
27770 		putnext(tcp->tcp_rq, mp);
27771 		mp = nmp;
27772 	}
27773 
27774 	/*
27775 	 * There should be atleast two ref's (IP + TCP)
27776 	 */
27777 	ASSERT(connp->conn_ref >= 2);
27778 	squeue_synch_exit(connp->conn_sqp, connp);
27779 }
27780 
27781 /* ARGSUSED */
27782 static void
27783 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
27784 {
27785 	conn_t 	*connp = (conn_t *)arg;
27786 	tcp_t	*tcp = connp->conn_tcp;
27787 
27788 	freemsg(mp);
27789 
27790 	if (tcp->tcp_fused)
27791 		tcp_unfuse(tcp);
27792 
27793 	if (tcp_xmit_end(tcp) != 0) {
27794 		/*
27795 		 * We were crossing FINs and got a reset from
27796 		 * the other side. Just ignore it.
27797 		 */
27798 		if (tcp->tcp_debug) {
27799 			(void) strlog(TCP_MOD_ID, 0, 1,
27800 			    SL_ERROR|SL_TRACE,
27801 			    "tcp_shutdown_output() out of state %s",
27802 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
27803 		}
27804 	}
27805 }
27806 
27807 /* ARGSUSED */
27808 int
27809 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
27810 {
27811 	conn_t  *connp = (conn_t *)proto_handle;
27812 	tcp_t   *tcp = connp->conn_tcp;
27813 
27814 	/*
27815 	 * X/Open requires that we check the connected state.
27816 	 */
27817 	if (tcp->tcp_state < TCPS_SYN_SENT)
27818 		return (ENOTCONN);
27819 
27820 	/* shutdown the send side */
27821 	if (how != SHUT_RD) {
27822 		mblk_t *bp;
27823 
27824 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
27825 		CONN_INC_REF(connp);
27826 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
27827 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
27828 
27829 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27830 		    SOCK_OPCTL_SHUT_SEND, 0);
27831 	}
27832 
27833 	/* shutdown the recv side */
27834 	if (how != SHUT_WR)
27835 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27836 		    SOCK_OPCTL_SHUT_RECV, 0);
27837 
27838 	return (0);
27839 }
27840 
27841 /*
27842  * SOP_LISTEN() calls into tcp_listen().
27843  */
27844 /* ARGSUSED */
27845 int
27846 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27847 {
27848 	conn_t	*connp = (conn_t *)proto_handle;
27849 	int 	error;
27850 	squeue_t *sqp = connp->conn_sqp;
27851 
27852 	error = squeue_synch_enter(sqp, connp, 0);
27853 	if (error != 0) {
27854 		/* failed to enter */
27855 		return (ENOBUFS);
27856 	}
27857 
27858 	error = tcp_do_listen(connp, backlog, cr);
27859 	if (error == 0) {
27860 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27861 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
27862 	} else if (error < 0) {
27863 		if (error == -TOUTSTATE)
27864 			error = EINVAL;
27865 		else
27866 			error = proto_tlitosyserr(-error);
27867 	}
27868 	squeue_synch_exit(sqp, connp);
27869 	return (error);
27870 }
27871 
27872 static int
27873 tcp_do_listen(conn_t *connp, int backlog, cred_t *cr)
27874 {
27875 	tcp_t		*tcp = connp->conn_tcp;
27876 	sin_t		*sin;
27877 	sin6_t  	*sin6;
27878 	int		error = 0;
27879 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27880 
27881 	if (tcp->tcp_state >= TCPS_BOUND) {
27882 		if ((tcp->tcp_state == TCPS_BOUND ||
27883 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
27884 			/*
27885 			 * Handle listen() increasing backlog.
27886 			 * This is more "liberal" then what the TPI spec
27887 			 * requires but is needed to avoid a t_unbind
27888 			 * when handling listen() since the port number
27889 			 * might be "stolen" between the unbind and bind.
27890 			 */
27891 			goto do_listen;
27892 		}
27893 		if (tcp->tcp_debug) {
27894 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27895 			    "tcp_listen: bad state, %d", tcp->tcp_state);
27896 		}
27897 		return (-TOUTSTATE);
27898 	} else {
27899 		int32_t len;
27900 		sin6_t	addr;
27901 
27902 		/* Do an implicit bind: Request for a generic port. */
27903 		if (tcp->tcp_family == AF_INET) {
27904 			len = sizeof (sin_t);
27905 			sin = (sin_t *)&addr;
27906 			*sin = sin_null;
27907 			sin->sin_family = AF_INET;
27908 			tcp->tcp_ipversion = IPV4_VERSION;
27909 		} else {
27910 			ASSERT(tcp->tcp_family == AF_INET6);
27911 			len = sizeof (sin6_t);
27912 			sin6 = (sin6_t *)&addr;
27913 			*sin6 = sin6_null;
27914 			sin6->sin6_family = AF_INET6;
27915 			tcp->tcp_ipversion = IPV6_VERSION;
27916 		}
27917 
27918 		error = tcp_bind_check(connp, (struct sockaddr *)&addr, len,
27919 		    cr, B_FALSE);
27920 		if (error)
27921 			return (error);
27922 		/* Fall through and do the fanout insertion */
27923 	}
27924 
27925 do_listen:
27926 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
27927 	tcp->tcp_conn_req_max = backlog;
27928 	if (tcp->tcp_conn_req_max) {
27929 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
27930 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
27931 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
27932 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
27933 		/*
27934 		 * If this is a listener, do not reset the eager list
27935 		 * and other stuffs.  Note that we don't check if the
27936 		 * existing eager list meets the new tcp_conn_req_max
27937 		 * requirement.
27938 		 */
27939 		if (tcp->tcp_state != TCPS_LISTEN) {
27940 			tcp->tcp_state = TCPS_LISTEN;
27941 			/* Initialize the chain. Don't need the eager_lock */
27942 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
27943 			tcp->tcp_eager_next_drop_q0 = tcp;
27944 			tcp->tcp_eager_prev_drop_q0 = tcp;
27945 			tcp->tcp_second_ctimer_threshold =
27946 			    tcps->tcps_ip_abort_linterval;
27947 		}
27948 	}
27949 
27950 	/*
27951 	 * We can call ip_bind directly, the processing continues
27952 	 * in tcp_post_ip_bind().
27953 	 *
27954 	 * We need to make sure that the conn_recv is set to a non-null
27955 	 * value before we insert the conn into the classifier table.
27956 	 * This is to avoid a race with an incoming packet which does an
27957 	 * ipcl_classify().
27958 	 */
27959 	connp->conn_recv = tcp_conn_request;
27960 	if (tcp->tcp_family == AF_INET) {
27961 		error = ip_proto_bind_laddr_v4(connp, NULL,
27962 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
27963 	} else {
27964 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27965 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
27966 	}
27967 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27968 }
27969 
27970 void
27971 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
27972 {
27973 	conn_t  *connp = (conn_t *)proto_handle;
27974 	tcp_t	*tcp = connp->conn_tcp;
27975 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27976 	uint_t thwin;
27977 
27978 	(void) squeue_synch_enter(connp->conn_sqp, connp, 0);
27979 
27980 	/* Flow control condition has been removed. */
27981 	tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
27982 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
27983 	    << tcp->tcp_rcv_ws;
27984 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
27985 	/*
27986 	 * Send back a window update immediately if TCP is above
27987 	 * ESTABLISHED state and the increase of the rcv window
27988 	 * that the other side knows is at least 1 MSS after flow
27989 	 * control is lifted.
27990 	 */
27991 	if (tcp->tcp_state >= TCPS_ESTABLISHED &&
27992 	    (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss)) {
27993 		tcp_xmit_ctl(NULL, tcp,
27994 		    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
27995 		    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
27996 		BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
27997 	}
27998 
27999 	squeue_synch_exit(connp->conn_sqp, connp);
28000 }
28001 
28002 /* ARGSUSED */
28003 int
28004 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
28005     int mode, int32_t *rvalp, cred_t *cr)
28006 {
28007 	conn_t  	*connp = (conn_t *)proto_handle;
28008 	int		error;
28009 
28010 	switch (cmd) {
28011 		case ND_SET:
28012 		case ND_GET:
28013 		case TCP_IOC_DEFAULT_Q:
28014 		case _SIOCSOCKFALLBACK:
28015 		case TCP_IOC_ABORT_CONN:
28016 		case TI_GETPEERNAME:
28017 		case TI_GETMYNAME:
28018 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
28019 			    cmd));
28020 			error = EINVAL;
28021 			break;
28022 		default:
28023 			/*
28024 			 * Pass on to IP using helper stream
28025 			 */
28026 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
28027 			    cmd, arg, mode, cr, rvalp);
28028 			break;
28029 	}
28030 	return (error);
28031 }
28032 
28033 sock_downcalls_t sock_tcp_downcalls = {
28034 	tcp_activate,
28035 	tcp_accept,
28036 	tcp_bind,
28037 	tcp_listen,
28038 	tcp_connect,
28039 	tcp_getpeername,
28040 	tcp_getsockname,
28041 	tcp_getsockopt,
28042 	tcp_setsockopt,
28043 	tcp_sendmsg,
28044 	NULL,
28045 	NULL,
28046 	NULL,
28047 	tcp_shutdown,
28048 	tcp_clr_flowctrl,
28049 	tcp_ioctl,
28050 	tcp_close,
28051 };
28052