xref: /titanic_52/usr/src/uts/common/inet/tcp/tcp.c (revision 8cae6764ee663bd6a0b140294645a7c2fd8399b8)
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 };
656 
657 #define	TCPOPT_BOUNDIF		0x00000001	/* set IPV6_BOUND_IF */
658 #define	TCPOPT_RECVPKTINFO	0x00000002	/* set IPV6_RECVPKTINFO */
659 
660 /*
661  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
662  */
663 
664 #ifdef _BIG_ENDIAN
665 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
666 	(TCPOPT_TSTAMP << 8) | 10)
667 #else
668 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
669 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
670 #endif
671 
672 /*
673  * Flags returned from tcp_parse_options.
674  */
675 #define	TCP_OPT_MSS_PRESENT	1
676 #define	TCP_OPT_WSCALE_PRESENT	2
677 #define	TCP_OPT_TSTAMP_PRESENT	4
678 #define	TCP_OPT_SACK_OK_PRESENT	8
679 #define	TCP_OPT_SACK_PRESENT	16
680 
681 /* TCP option length */
682 #define	TCPOPT_NOP_LEN		1
683 #define	TCPOPT_MAXSEG_LEN	4
684 #define	TCPOPT_WS_LEN		3
685 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
686 #define	TCPOPT_TSTAMP_LEN	10
687 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
688 #define	TCPOPT_SACK_OK_LEN	2
689 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
690 #define	TCPOPT_REAL_SACK_LEN	4
691 #define	TCPOPT_MAX_SACK_LEN	36
692 #define	TCPOPT_HEADER_LEN	2
693 
694 /* TCP cwnd burst factor. */
695 #define	TCP_CWND_INFINITE	65535
696 #define	TCP_CWND_SS		3
697 #define	TCP_CWND_NORMAL		5
698 
699 /* Maximum TCP initial cwin (start/restart). */
700 #define	TCP_MAX_INIT_CWND	8
701 
702 /*
703  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
704  * either tcp_slow_start_initial or tcp_slow_start_after idle
705  * depending on the caller.  If the upper layer has not used the
706  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
707  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
708  * If the upper layer has changed set the tcp_init_cwnd, just use
709  * it to calculate the tcp_cwnd.
710  */
711 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
712 {									\
713 	if ((tcp)->tcp_init_cwnd == 0) {				\
714 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
715 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
716 	} else {							\
717 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
718 	}								\
719 	tcp->tcp_cwnd_cnt = 0;						\
720 }
721 
722 /* TCP Timer control structure */
723 typedef struct tcpt_s {
724 	pfv_t	tcpt_pfv;	/* The routine we are to call */
725 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
726 } tcpt_t;
727 
728 /* Host Specific Parameter structure */
729 typedef struct tcp_hsp {
730 	struct tcp_hsp	*tcp_hsp_next;
731 	in6_addr_t	tcp_hsp_addr_v6;
732 	in6_addr_t	tcp_hsp_subnet_v6;
733 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
734 	int32_t		tcp_hsp_sendspace;
735 	int32_t		tcp_hsp_recvspace;
736 	int32_t		tcp_hsp_tstamp;
737 } tcp_hsp_t;
738 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
739 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
740 
741 /*
742  * Functions called directly via squeue having a prototype of edesc_t.
743  */
744 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
745 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
746 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
747 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
748 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
749 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
750 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
751 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
752 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
753 void		tcp_output_urgent(void *arg, mblk_t *mp, void *arg2);
754 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
755 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
756 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
757 
758 
759 /* Prototype for TCP functions */
760 static void	tcp_random_init(void);
761 int		tcp_random(void);
762 static void	tcp_tli_accept(tcp_t *tcp, mblk_t *mp);
763 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
764 		    tcp_t *eager);
765 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
766 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
767     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
768     boolean_t user_specified);
769 static void	tcp_closei_local(tcp_t *tcp);
770 static void	tcp_close_detached(tcp_t *tcp);
771 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
772 			mblk_t *idmp, mblk_t **defermp);
773 static void	tcp_tpi_connect(tcp_t *tcp, mblk_t *mp);
774 static int	tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
775 		    in_port_t dstport, uint_t srcid, cred_t *cr, pid_t pid);
776 static int 	tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
777 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
778 		    uint32_t scope_id, cred_t *cr, pid_t pid);
779 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
780 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
781 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
782 static char	*tcp_display(tcp_t *tcp, char *, char);
783 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
784 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
785 static void	tcp_eager_unlink(tcp_t *tcp);
786 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
787 		    int unixerr);
788 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
789 		    int tlierr, int unixerr);
790 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
791 		    cred_t *cr);
792 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
793 		    char *value, caddr_t cp, cred_t *cr);
794 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
795 		    char *value, caddr_t cp, cred_t *cr);
796 static int	tcp_tpistate(tcp_t *tcp);
797 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
798     int caller_holds_lock);
799 static void	tcp_bind_hash_remove(tcp_t *tcp);
800 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
801 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
802 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
803 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
804 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
805 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
806 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
807 void		tcp_g_q_setup(tcp_stack_t *);
808 void		tcp_g_q_create(tcp_stack_t *);
809 void		tcp_g_q_destroy(tcp_stack_t *);
810 static int	tcp_header_init_ipv4(tcp_t *tcp);
811 static int	tcp_header_init_ipv6(tcp_t *tcp);
812 int		tcp_init(tcp_t *tcp, queue_t *q);
813 static int	tcp_init_values(tcp_t *tcp);
814 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
815 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
816 static void	tcp_ip_notify(tcp_t *tcp);
817 static mblk_t	*tcp_ire_mp(mblk_t **mpp);
818 static void	tcp_iss_init(tcp_t *tcp);
819 static void	tcp_keepalive_killer(void *arg);
820 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
821 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
822 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
823 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
824 static boolean_t tcp_allow_connopt_set(int level, int name);
825 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
826 int		tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
827 int		tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level,
828 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
829 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
830 		    mblk_t *mblk);
831 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
832 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
833 		    uchar_t *ptr, uint_t len);
834 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
835 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
836     tcp_stack_t *);
837 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
838 		    caddr_t cp, cred_t *cr);
839 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
840 		    caddr_t cp, cred_t *cr);
841 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
842 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
843 		    caddr_t cp, cred_t *cr);
844 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
845 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
846 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
847 static void	tcp_reinit(tcp_t *tcp);
848 static void	tcp_reinit_values(tcp_t *tcp);
849 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
850 		    tcp_t *thisstream, cred_t *cr);
851 
852 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
853 static uint_t	tcp_rcv_drain(tcp_t *tcp);
854 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
855 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
856 static void	tcp_ss_rexmit(tcp_t *tcp);
857 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
858 static void	tcp_process_options(tcp_t *, tcph_t *);
859 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
860 static void	tcp_rsrv(queue_t *q);
861 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
862 static int	tcp_snmp_state(tcp_t *tcp);
863 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
864 		    cred_t *cr);
865 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
866 		    cred_t *cr);
867 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
868 		    cred_t *cr);
869 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
870 		    cred_t *cr);
871 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
872 		    cred_t *cr);
873 static void	tcp_timer(void *arg);
874 static void	tcp_timer_callback(void *);
875 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
876     boolean_t random);
877 static in_port_t tcp_get_next_priv_port(const tcp_t *);
878 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
879 static void	tcp_wput_fallback(queue_t *q, mblk_t *mp);
880 void		tcp_tpi_accept(queue_t *q, mblk_t *mp);
881 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
882 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
883 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
884 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
885 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
886 		    const int num_sack_blk, int *usable, uint_t *snxt,
887 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
888 		    const int mdt_thres);
889 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
890 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
891 		    const int num_sack_blk, int *usable, uint_t *snxt,
892 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
893 		    const int mdt_thres);
894 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
895 		    int num_sack_blk);
896 static void	tcp_wsrv(queue_t *q);
897 static int	tcp_xmit_end(tcp_t *tcp);
898 static void	tcp_ack_timer(void *arg);
899 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
900 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
901 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
902 		    zoneid_t zoneid, tcp_stack_t *, conn_t *connp);
903 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
904 		    uint32_t ack, int ctl);
905 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *);
906 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr, tcp_stack_t *);
907 static int	setmaxps(queue_t *q, int maxpsz);
908 static void	tcp_set_rto(tcp_t *, time_t);
909 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
910 		    boolean_t, boolean_t);
911 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
912 		    boolean_t ipsec_mctl);
913 static int	tcp_build_hdrs(tcp_t *);
914 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
915 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
916 		    tcph_t *tcph);
917 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
918 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
919 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
920 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
921 		    const boolean_t, const uint32_t, const uint32_t,
922 		    const uint32_t, const uint32_t, tcp_stack_t *);
923 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
924 		    const uint_t, const uint_t, boolean_t *);
925 static mblk_t	*tcp_lso_info_mp(mblk_t *);
926 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
927 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
928 extern mblk_t	*tcp_timermp_alloc(int);
929 extern void	tcp_timermp_free(tcp_t *);
930 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
931 static void	tcp_stop_lingering(tcp_t *tcp);
932 static void	tcp_close_linger_timeout(void *arg);
933 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
934 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
935 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
936 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
937 static void	tcp_g_kstat_fini(kstat_t *);
938 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
939 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
940 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
941 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
942 static int	tcp_kstat_update(kstat_t *kp, int rw);
943 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
944 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
945 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
946 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
947 			tcph_t *tcph, mblk_t *idmp);
948 static int	tcp_squeue_switch(int);
949 
950 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
951 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
952 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
953 static int	tcp_tpi_close(queue_t *, int);
954 static int	tcpclose_accept(queue_t *);
955 
956 static void	tcp_squeue_add(squeue_t *);
957 static boolean_t tcp_zcopy_check(tcp_t *);
958 static void	tcp_zcopy_notify(tcp_t *);
959 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
960 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
961 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
962 
963 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
964 
965 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
966 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
967 
968 static int tcp_accept(sock_lower_handle_t, sock_lower_handle_t,
969 	    sock_upper_handle_t, cred_t *);
970 static int tcp_listen(sock_lower_handle_t, int, cred_t *);
971 static int tcp_post_ip_bind(tcp_t *, mblk_t *, int, cred_t *, pid_t);
972 static int tcp_do_listen(conn_t *, int, cred_t *);
973 static int tcp_do_connect(conn_t *, const struct sockaddr *, socklen_t,
974     cred_t *, pid_t);
975 static int tcp_do_bind(conn_t *, struct sockaddr *, socklen_t, cred_t *,
976     boolean_t);
977 static int tcp_do_unbind(conn_t *);
978 static int tcp_bind_check(conn_t *, struct sockaddr *, socklen_t, cred_t *,
979     boolean_t);
980 
981 static void tcp_ulp_newconn(conn_t *, conn_t *, mblk_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 	}
4816 
4817 	return (0);
4818 }
4819 
4820 
4821 int
4822 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4823     tcph_t *tcph, mblk_t *idmp)
4824 {
4825 	tcp_t 		*ltcp = lconnp->conn_tcp;
4826 	tcp_t		*tcp = connp->conn_tcp;
4827 	sin_t		sin;
4828 	mblk_t		*tpi_mp = NULL;
4829 	int		err;
4830 	cred_t		*cr;
4831 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4832 
4833 	sin = sin_null;
4834 	sin.sin_addr.s_addr = ipha->ipha_src;
4835 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4836 	sin.sin_family = AF_INET;
4837 	if (ltcp->tcp_recvdstaddr) {
4838 		sin_t	sind;
4839 
4840 		sind = sin_null;
4841 		sind.sin_addr.s_addr = ipha->ipha_dst;
4842 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4843 		sind.sin_family = AF_INET;
4844 		tpi_mp = mi_tpi_extconn_ind(NULL,
4845 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4846 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4847 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4848 	} else {
4849 		tpi_mp = mi_tpi_conn_ind(NULL,
4850 		    (char *)&sin, sizeof (sin_t),
4851 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4852 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4853 	}
4854 
4855 	if (tpi_mp == NULL) {
4856 		return (ENOMEM);
4857 	}
4858 
4859 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4860 	connp->conn_send = ip_output;
4861 	connp->conn_recv = tcp_input;
4862 	connp->conn_fully_bound = B_FALSE;
4863 
4864 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_bound_source_v6);
4865 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4866 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4867 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4868 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4869 
4870 	/* Inherit information from the "parent" */
4871 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4872 	tcp->tcp_family = ltcp->tcp_family;
4873 	tcp->tcp_wq = ltcp->tcp_wq;
4874 	tcp->tcp_rq = ltcp->tcp_rq;
4875 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4876 	tcp->tcp_detached = B_TRUE;
4877 	SOCK_CONNID_INIT(tcp->tcp_connid);
4878 	if ((err = tcp_init_values(tcp)) != 0) {
4879 		freemsg(tpi_mp);
4880 		return (err);
4881 	}
4882 
4883 	/*
4884 	 * Let's make sure that eager tcp template has enough space to
4885 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4886 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4887 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4888 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4889 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4890 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4891 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4892 	 */
4893 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4894 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4895 
4896 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4897 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4898 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4899 	tcp->tcp_ttl = ltcp->tcp_ttl;
4900 	tcp->tcp_tos = ltcp->tcp_tos;
4901 
4902 	/* Copy the IP+TCP header template from listener to eager */
4903 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4904 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4905 	tcp->tcp_ip6h = NULL;
4906 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4907 	    tcp->tcp_ip_hdr_len);
4908 
4909 	/* Initialize the IP addresses and Ports */
4910 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4911 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4912 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4913 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4914 
4915 	/* Source routing option copyover (reverse it) */
4916 	if (tcps->tcps_rev_src_routes)
4917 		tcp_opt_reverse(tcp, ipha);
4918 
4919 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4920 	ASSERT(!tcp->tcp_tconnind_started);
4921 
4922 	/*
4923 	 * If the SYN contains a credential, it's a loopback packet; attach
4924 	 * the credential to the TPI message.
4925 	 */
4926 	if ((cr = DB_CRED(idmp)) != NULL) {
4927 		mblk_setcred(tpi_mp, cr);
4928 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4929 	}
4930 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4931 
4932 	/* Inherit the listener's SSL protection state */
4933 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4934 		kssl_hold_ent(tcp->tcp_kssl_ent);
4935 		tcp->tcp_kssl_pending = B_TRUE;
4936 	}
4937 
4938 	/* Inherit the listener's non-STREAMS flag */
4939 	if (IPCL_IS_NONSTR(lconnp)) {
4940 		connp->conn_flags |= IPCL_NONSTR;
4941 	}
4942 
4943 	return (0);
4944 }
4945 
4946 /*
4947  * sets up conn for ipsec.
4948  * if the first mblk is M_CTL it is consumed and mpp is updated.
4949  * in case of error mpp is freed.
4950  */
4951 conn_t *
4952 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4953 {
4954 	conn_t 		*connp = tcp->tcp_connp;
4955 	conn_t 		*econnp;
4956 	squeue_t 	*new_sqp;
4957 	mblk_t 		*first_mp = *mpp;
4958 	mblk_t		*mp = *mpp;
4959 	boolean_t	mctl_present = B_FALSE;
4960 	uint_t		ipvers;
4961 
4962 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
4963 	if (econnp == NULL) {
4964 		freemsg(first_mp);
4965 		return (NULL);
4966 	}
4967 	if (DB_TYPE(mp) == M_CTL) {
4968 		if (mp->b_cont == NULL ||
4969 		    mp->b_cont->b_datap->db_type != M_DATA) {
4970 			freemsg(first_mp);
4971 			return (NULL);
4972 		}
4973 		mp = mp->b_cont;
4974 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4975 			freemsg(first_mp);
4976 			return (NULL);
4977 		}
4978 
4979 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4980 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4981 		mctl_present = B_TRUE;
4982 	} else {
4983 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4984 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4985 	}
4986 
4987 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4988 	DB_CKSUMSTART(mp) = 0;
4989 
4990 	ASSERT(OK_32PTR(mp->b_rptr));
4991 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
4992 	if (ipvers == IPV4_VERSION) {
4993 		uint16_t  	*up;
4994 		uint32_t	ports;
4995 		ipha_t		*ipha;
4996 
4997 		ipha = (ipha_t *)mp->b_rptr;
4998 		up = (uint16_t *)((uchar_t *)ipha +
4999 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5000 		ports = *(uint32_t *)up;
5001 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5002 		    ipha->ipha_dst, ipha->ipha_src, ports);
5003 	} else {
5004 		uint16_t  	*up;
5005 		uint32_t	ports;
5006 		uint16_t	ip_hdr_len;
5007 		uint8_t		*nexthdrp;
5008 		ip6_t 		*ip6h;
5009 		tcph_t		*tcph;
5010 
5011 		ip6h = (ip6_t *)mp->b_rptr;
5012 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5013 			ip_hdr_len = IPV6_HDR_LEN;
5014 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5015 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5016 			CONN_DEC_REF(econnp);
5017 			freemsg(first_mp);
5018 			return (NULL);
5019 		}
5020 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5021 		up = (uint16_t *)tcph->th_lport;
5022 		ports = *(uint32_t *)up;
5023 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5024 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5025 	}
5026 
5027 	/*
5028 	 * The caller already ensured that there is a sqp present.
5029 	 */
5030 	econnp->conn_sqp = new_sqp;
5031 	econnp->conn_initial_sqp = new_sqp;
5032 
5033 	if (connp->conn_policy != NULL) {
5034 		ipsec_in_t *ii;
5035 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5036 		ASSERT(ii->ipsec_in_policy == NULL);
5037 		IPPH_REFHOLD(connp->conn_policy);
5038 		ii->ipsec_in_policy = connp->conn_policy;
5039 
5040 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5041 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5042 			CONN_DEC_REF(econnp);
5043 			freemsg(first_mp);
5044 			return (NULL);
5045 		}
5046 	}
5047 
5048 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5049 		CONN_DEC_REF(econnp);
5050 		freemsg(first_mp);
5051 		return (NULL);
5052 	}
5053 
5054 	/*
5055 	 * If we know we have some policy, pass the "IPSEC"
5056 	 * options size TCP uses this adjust the MSS.
5057 	 */
5058 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5059 	if (mctl_present) {
5060 		freeb(first_mp);
5061 		*mpp = mp;
5062 	}
5063 
5064 	return (econnp);
5065 }
5066 
5067 /*
5068  * tcp_get_conn/tcp_free_conn
5069  *
5070  * tcp_get_conn is used to get a clean tcp connection structure.
5071  * It tries to reuse the connections put on the freelist by the
5072  * time_wait_collector failing which it goes to kmem_cache. This
5073  * way has two benefits compared to just allocating from and
5074  * freeing to kmem_cache.
5075  * 1) The time_wait_collector can free (which includes the cleanup)
5076  * outside the squeue. So when the interrupt comes, we have a clean
5077  * connection sitting in the freelist. Obviously, this buys us
5078  * performance.
5079  *
5080  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5081  * has multiple disadvantages - tying up the squeue during alloc, and the
5082  * fact that IPSec policy initialization has to happen here which
5083  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5084  * But allocating the conn/tcp in IP land is also not the best since
5085  * we can't check the 'q' and 'q0' which are protected by squeue and
5086  * blindly allocate memory which might have to be freed here if we are
5087  * not allowed to accept the connection. By using the freelist and
5088  * putting the conn/tcp back in freelist, we don't pay a penalty for
5089  * allocating memory without checking 'q/q0' and freeing it if we can't
5090  * accept the connection.
5091  *
5092  * Care should be taken to put the conn back in the same squeue's freelist
5093  * from which it was allocated. Best results are obtained if conn is
5094  * allocated from listener's squeue and freed to the same. Time wait
5095  * collector will free up the freelist is the connection ends up sitting
5096  * there for too long.
5097  */
5098 void *
5099 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5100 {
5101 	tcp_t			*tcp = NULL;
5102 	conn_t			*connp = NULL;
5103 	squeue_t		*sqp = (squeue_t *)arg;
5104 	tcp_squeue_priv_t 	*tcp_time_wait;
5105 	netstack_t		*ns;
5106 
5107 	tcp_time_wait =
5108 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5109 
5110 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5111 	tcp = tcp_time_wait->tcp_free_list;
5112 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5113 	if (tcp != NULL) {
5114 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5115 		tcp_time_wait->tcp_free_list_cnt--;
5116 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5117 		tcp->tcp_time_wait_next = NULL;
5118 		connp = tcp->tcp_connp;
5119 		connp->conn_flags |= IPCL_REUSED;
5120 
5121 		ASSERT(tcp->tcp_tcps == NULL);
5122 		ASSERT(connp->conn_netstack == NULL);
5123 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5124 		ns = tcps->tcps_netstack;
5125 		netstack_hold(ns);
5126 		connp->conn_netstack = ns;
5127 		tcp->tcp_tcps = tcps;
5128 		TCPS_REFHOLD(tcps);
5129 		ipcl_globalhash_insert(connp);
5130 		return ((void *)connp);
5131 	}
5132 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5133 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5134 	    tcps->tcps_netstack)) == NULL)
5135 		return (NULL);
5136 	tcp = connp->conn_tcp;
5137 	/*
5138 	 * Pre-allocate the tcp_rsrv_mp.  This mblk will not be freed
5139 	 * until this conn_t/tcp_t is freed at ipcl_conn_destroy().
5140 	 */
5141 	if ((tcp->tcp_rsrv_mp = allocb(0, BPRI_HI)) == NULL) {
5142 		ipcl_conn_destroy(connp);
5143 		return (NULL);
5144 	}
5145 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5146 	tcp->tcp_tcps = tcps;
5147 	TCPS_REFHOLD(tcps);
5148 
5149 	return ((void *)connp);
5150 }
5151 
5152 /*
5153  * Update the cached label for the given tcp_t.  This should be called once per
5154  * connection, and before any packets are sent or tcp_process_options is
5155  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5156  */
5157 static boolean_t
5158 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5159 {
5160 	conn_t *connp = tcp->tcp_connp;
5161 
5162 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5163 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5164 		int added;
5165 
5166 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5167 		    connp->conn_mac_exempt,
5168 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5169 			return (B_FALSE);
5170 
5171 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5172 		if (added == -1)
5173 			return (B_FALSE);
5174 		tcp->tcp_hdr_len += added;
5175 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5176 		tcp->tcp_ip_hdr_len += added;
5177 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5178 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5179 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5180 			    tcp->tcp_hdr_len);
5181 			if (added == -1)
5182 				return (B_FALSE);
5183 			tcp->tcp_hdr_len += added;
5184 			tcp->tcp_tcph = (tcph_t *)
5185 			    ((uchar_t *)tcp->tcp_tcph + added);
5186 			tcp->tcp_ip_hdr_len += added;
5187 		}
5188 	} else {
5189 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5190 
5191 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5192 		    connp->conn_mac_exempt,
5193 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5194 			return (B_FALSE);
5195 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5196 		    &tcp->tcp_label_len, optbuf) != 0)
5197 			return (B_FALSE);
5198 		if (tcp_build_hdrs(tcp) != 0)
5199 			return (B_FALSE);
5200 	}
5201 
5202 	connp->conn_ulp_labeled = 1;
5203 
5204 	return (B_TRUE);
5205 }
5206 
5207 /* BEGIN CSTYLED */
5208 /*
5209  *
5210  * The sockfs ACCEPT path:
5211  * =======================
5212  *
5213  * The eager is now established in its own perimeter as soon as SYN is
5214  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5215  * completes the accept processing on the acceptor STREAM. The sending
5216  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5217  * listener but a TLI/XTI listener completes the accept processing
5218  * on the listener perimeter.
5219  *
5220  * Common control flow for 3 way handshake:
5221  * ----------------------------------------
5222  *
5223  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5224  *					-> tcp_conn_request()
5225  *
5226  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5227  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5228  *
5229  * Sockfs ACCEPT Path:
5230  * -------------------
5231  *
5232  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5233  * as STREAM entry point)
5234  *
5235  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5236  *
5237  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5238  * association (we are not behind eager's squeue but sockfs is protecting us
5239  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5240  * is changed to point at tcp_wput().
5241  *
5242  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5243  * listener (done on listener's perimeter).
5244  *
5245  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5246  * accept.
5247  *
5248  * TLI/XTI client ACCEPT path:
5249  * ---------------------------
5250  *
5251  * soaccept() sends T_CONN_RES on the listener STREAM.
5252  *
5253  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5254  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5255  *
5256  * Locks:
5257  * ======
5258  *
5259  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5260  * and listeners->tcp_eager_next_q.
5261  *
5262  * Referencing:
5263  * ============
5264  *
5265  * 1) We start out in tcp_conn_request by eager placing a ref on
5266  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5267  *
5268  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5269  * doing so we place a ref on the eager. This ref is finally dropped at the
5270  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5271  * reference is dropped by the squeue framework.
5272  *
5273  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5274  *
5275  * The reference must be released by the same entity that added the reference
5276  * In the above scheme, the eager is the entity that adds and releases the
5277  * references. Note that tcp_accept_finish executes in the squeue of the eager
5278  * (albeit after it is attached to the acceptor stream). Though 1. executes
5279  * in the listener's squeue, the eager is nascent at this point and the
5280  * reference can be considered to have been added on behalf of the eager.
5281  *
5282  * Eager getting a Reset or listener closing:
5283  * ==========================================
5284  *
5285  * Once the listener and eager are linked, the listener never does the unlink.
5286  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5287  * a message on all eager perimeter. The eager then does the unlink, clears
5288  * any pointers to the listener's queue and drops the reference to the
5289  * listener. The listener waits in tcp_close outside the squeue until its
5290  * refcount has dropped to 1. This ensures that the listener has waited for
5291  * all eagers to clear their association with the listener.
5292  *
5293  * Similarly, if eager decides to go away, it can unlink itself and close.
5294  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5295  * the reference to eager is still valid because of the extra ref we put
5296  * in tcp_send_conn_ind.
5297  *
5298  * Listener can always locate the eager under the protection
5299  * of the listener->tcp_eager_lock, and then do a refhold
5300  * on the eager during the accept processing.
5301  *
5302  * The acceptor stream accesses the eager in the accept processing
5303  * based on the ref placed on eager before sending T_conn_ind.
5304  * The only entity that can negate this refhold is a listener close
5305  * which is mutually exclusive with an active acceptor stream.
5306  *
5307  * Eager's reference on the listener
5308  * ===================================
5309  *
5310  * If the accept happens (even on a closed eager) the eager drops its
5311  * reference on the listener at the start of tcp_accept_finish. If the
5312  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5313  * the reference is dropped in tcp_closei_local. If the listener closes,
5314  * the reference is dropped in tcp_eager_kill. In all cases the reference
5315  * is dropped while executing in the eager's context (squeue).
5316  */
5317 /* END CSTYLED */
5318 
5319 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5320 
5321 /*
5322  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5323  * tcp_rput_data will not see any SYN packets.
5324  */
5325 /* ARGSUSED */
5326 void
5327 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5328 {
5329 	tcph_t		*tcph;
5330 	uint32_t	seg_seq;
5331 	tcp_t		*eager;
5332 	uint_t		ipvers;
5333 	ipha_t		*ipha;
5334 	ip6_t		*ip6h;
5335 	int		err;
5336 	conn_t		*econnp = NULL;
5337 	squeue_t	*new_sqp;
5338 	mblk_t		*mp1;
5339 	uint_t 		ip_hdr_len;
5340 	conn_t		*connp = (conn_t *)arg;
5341 	tcp_t		*tcp = connp->conn_tcp;
5342 	cred_t		*credp;
5343 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5344 	ip_stack_t	*ipst;
5345 
5346 	if (tcp->tcp_state != TCPS_LISTEN)
5347 		goto error2;
5348 
5349 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5350 
5351 	mutex_enter(&tcp->tcp_eager_lock);
5352 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5353 		mutex_exit(&tcp->tcp_eager_lock);
5354 		TCP_STAT(tcps, tcp_listendrop);
5355 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5356 		if (tcp->tcp_debug) {
5357 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5358 			    "tcp_conn_request: listen backlog (max=%d) "
5359 			    "overflow (%d pending) on %s",
5360 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5361 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5362 		}
5363 		goto error2;
5364 	}
5365 
5366 	if (tcp->tcp_conn_req_cnt_q0 >=
5367 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5368 		/*
5369 		 * Q0 is full. Drop a pending half-open req from the queue
5370 		 * to make room for the new SYN req. Also mark the time we
5371 		 * drop a SYN.
5372 		 *
5373 		 * A more aggressive defense against SYN attack will
5374 		 * be to set the "tcp_syn_defense" flag now.
5375 		 */
5376 		TCP_STAT(tcps, tcp_listendropq0);
5377 		tcp->tcp_last_rcv_lbolt = lbolt64;
5378 		if (!tcp_drop_q0(tcp)) {
5379 			mutex_exit(&tcp->tcp_eager_lock);
5380 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5381 			if (tcp->tcp_debug) {
5382 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5383 				    "tcp_conn_request: listen half-open queue "
5384 				    "(max=%d) full (%d pending) on %s",
5385 				    tcps->tcps_conn_req_max_q0,
5386 				    tcp->tcp_conn_req_cnt_q0,
5387 				    tcp_display(tcp, NULL,
5388 				    DISP_PORT_ONLY));
5389 			}
5390 			goto error2;
5391 		}
5392 	}
5393 	mutex_exit(&tcp->tcp_eager_lock);
5394 
5395 	/*
5396 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5397 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5398 	 * link local address.  If IPSec is enabled, db_struioflag has
5399 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5400 	 * otherwise an error case if neither of them is set.
5401 	 */
5402 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5403 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5404 		DB_CKSUMSTART(mp) = 0;
5405 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5406 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5407 		if (econnp == NULL)
5408 			goto error2;
5409 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5410 		econnp->conn_sqp = new_sqp;
5411 		econnp->conn_initial_sqp = new_sqp;
5412 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5413 		/*
5414 		 * mp is updated in tcp_get_ipsec_conn().
5415 		 */
5416 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5417 		if (econnp == NULL) {
5418 			/*
5419 			 * mp freed by tcp_get_ipsec_conn.
5420 			 */
5421 			return;
5422 		}
5423 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5424 	} else {
5425 		goto error2;
5426 	}
5427 
5428 	ASSERT(DB_TYPE(mp) == M_DATA);
5429 
5430 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5431 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5432 	ASSERT(OK_32PTR(mp->b_rptr));
5433 	if (ipvers == IPV4_VERSION) {
5434 		ipha = (ipha_t *)mp->b_rptr;
5435 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5436 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5437 	} else {
5438 		ip6h = (ip6_t *)mp->b_rptr;
5439 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5440 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5441 	}
5442 
5443 	if (tcp->tcp_family == AF_INET) {
5444 		ASSERT(ipvers == IPV4_VERSION);
5445 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5446 	} else {
5447 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5448 	}
5449 
5450 	if (err)
5451 		goto error3;
5452 
5453 	eager = econnp->conn_tcp;
5454 
5455 	/*
5456 	 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that at close
5457 	 * time, we will always have that to send up.  Otherwise, we need to do
5458 	 * special handling in case the allocation fails at that time.
5459 	 */
5460 	ASSERT(eager->tcp_ordrel_mp == NULL);
5461 	if (!IPCL_IS_NONSTR(econnp) &&
5462 	    (eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5463 		goto error3;
5464 
5465 	/* Inherit various TCP parameters from the listener */
5466 	eager->tcp_naglim = tcp->tcp_naglim;
5467 	eager->tcp_first_timer_threshold =
5468 	    tcp->tcp_first_timer_threshold;
5469 	eager->tcp_second_timer_threshold =
5470 	    tcp->tcp_second_timer_threshold;
5471 
5472 	eager->tcp_first_ctimer_threshold =
5473 	    tcp->tcp_first_ctimer_threshold;
5474 	eager->tcp_second_ctimer_threshold =
5475 	    tcp->tcp_second_ctimer_threshold;
5476 
5477 	/*
5478 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5479 	 * If it does not, the eager's receive window will be set to the
5480 	 * listener's receive window later in this function.
5481 	 */
5482 	eager->tcp_rwnd = 0;
5483 
5484 	/*
5485 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5486 	 * calling tcp_process_options() where tcp_mss_set() is called
5487 	 * to set the initial cwnd.
5488 	 */
5489 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5490 
5491 	/*
5492 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5493 	 * zone id before the accept is completed in tcp_wput_accept().
5494 	 */
5495 	econnp->conn_zoneid = connp->conn_zoneid;
5496 	econnp->conn_allzones = connp->conn_allzones;
5497 
5498 	/* Copy nexthop information from listener to eager */
5499 	if (connp->conn_nexthop_set) {
5500 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5501 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5502 	}
5503 
5504 	/*
5505 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5506 	 * eager is accepted
5507 	 */
5508 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5509 	crhold(credp);
5510 
5511 	/*
5512 	 * If the caller has the process-wide flag set, then default to MAC
5513 	 * exempt mode.  This allows read-down to unlabeled hosts.
5514 	 */
5515 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5516 		econnp->conn_mac_exempt = B_TRUE;
5517 
5518 	if (is_system_labeled()) {
5519 		cred_t *cr;
5520 
5521 		if (connp->conn_mlp_type != mlptSingle) {
5522 			cr = econnp->conn_peercred = DB_CRED(mp);
5523 			if (cr != NULL)
5524 				crhold(cr);
5525 			else
5526 				cr = econnp->conn_cred;
5527 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5528 			    econnp, cred_t *, cr)
5529 		} else {
5530 			cr = econnp->conn_cred;
5531 			DTRACE_PROBE2(syn_accept, conn_t *,
5532 			    econnp, cred_t *, cr)
5533 		}
5534 
5535 		if (!tcp_update_label(eager, cr)) {
5536 			DTRACE_PROBE3(
5537 			    tx__ip__log__error__connrequest__tcp,
5538 			    char *, "eager connp(1) label on SYN mp(2) failed",
5539 			    conn_t *, econnp, mblk_t *, mp);
5540 			goto error3;
5541 		}
5542 	}
5543 
5544 	eager->tcp_hard_binding = B_TRUE;
5545 
5546 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5547 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5548 
5549 	CL_INET_CONNECT(connp, eager, B_FALSE, err);
5550 	if (err != 0) {
5551 		tcp_bind_hash_remove(eager);
5552 		goto error3;
5553 	}
5554 
5555 	/*
5556 	 * No need to check for multicast destination since ip will only pass
5557 	 * up multicasts to those that have expressed interest
5558 	 * TODO: what about rejecting broadcasts?
5559 	 * Also check that source is not a multicast or broadcast address.
5560 	 */
5561 	eager->tcp_state = TCPS_SYN_RCVD;
5562 
5563 
5564 	/*
5565 	 * There should be no ire in the mp as we are being called after
5566 	 * receiving the SYN.
5567 	 */
5568 	ASSERT(tcp_ire_mp(&mp) == NULL);
5569 
5570 	/*
5571 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5572 	 */
5573 
5574 	if (tcp_adapt_ire(eager, NULL) == 0) {
5575 		/* Undo the bind_hash_insert */
5576 		tcp_bind_hash_remove(eager);
5577 		goto error3;
5578 	}
5579 
5580 	/* Process all TCP options. */
5581 	tcp_process_options(eager, tcph);
5582 
5583 	/* Is the other end ECN capable? */
5584 	if (tcps->tcps_ecn_permitted >= 1 &&
5585 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5586 		eager->tcp_ecn_ok = B_TRUE;
5587 	}
5588 
5589 	/*
5590 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5591 	 * window size changed via SO_RCVBUF option.  First round up the
5592 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5593 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5594 	 * setting.
5595 	 *
5596 	 * Note if there is a rpipe metric associated with the remote host,
5597 	 * we should not inherit receive window size from listener.
5598 	 */
5599 	eager->tcp_rwnd = MSS_ROUNDUP(
5600 	    (eager->tcp_rwnd == 0 ? tcp->tcp_recv_hiwater:
5601 	    eager->tcp_rwnd), eager->tcp_mss);
5602 	if (eager->tcp_snd_ws_ok)
5603 		tcp_set_ws_value(eager);
5604 	/*
5605 	 * Note that this is the only place tcp_rwnd_set() is called for
5606 	 * accepting a connection.  We need to call it here instead of
5607 	 * after the 3-way handshake because we need to tell the other
5608 	 * side our rwnd in the SYN-ACK segment.
5609 	 */
5610 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5611 
5612 	/*
5613 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5614 	 * via soaccept()->soinheritoptions() which essentially applies
5615 	 * all the listener options to the new STREAM. The options that we
5616 	 * need to take care of are:
5617 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5618 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5619 	 * SO_SNDBUF, SO_RCVBUF.
5620 	 *
5621 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5622 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5623 	 *		tcp_maxpsz_set() gets called later from
5624 	 *		tcp_accept_finish(), the option takes effect.
5625 	 *
5626 	 */
5627 	/* Set the TCP options */
5628 	eager->tcp_recv_hiwater = tcp->tcp_recv_hiwater;
5629 	eager->tcp_recv_lowater = tcp->tcp_recv_lowater;
5630 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5631 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5632 	eager->tcp_oobinline = tcp->tcp_oobinline;
5633 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5634 	eager->tcp_broadcast = tcp->tcp_broadcast;
5635 	eager->tcp_useloopback = tcp->tcp_useloopback;
5636 	eager->tcp_dontroute = tcp->tcp_dontroute;
5637 	eager->tcp_debug = tcp->tcp_debug;
5638 	eager->tcp_linger = tcp->tcp_linger;
5639 	eager->tcp_lingertime = tcp->tcp_lingertime;
5640 	if (tcp->tcp_ka_enabled)
5641 		eager->tcp_ka_enabled = 1;
5642 
5643 	/* Set the IP options */
5644 	econnp->conn_broadcast = connp->conn_broadcast;
5645 	econnp->conn_loopback = connp->conn_loopback;
5646 	econnp->conn_dontroute = connp->conn_dontroute;
5647 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5648 
5649 	/* Put a ref on the listener for the eager. */
5650 	CONN_INC_REF(connp);
5651 	mutex_enter(&tcp->tcp_eager_lock);
5652 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5653 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5654 	tcp->tcp_eager_next_q0 = eager;
5655 	eager->tcp_eager_prev_q0 = tcp;
5656 
5657 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5658 	eager->tcp_listener = tcp;
5659 	eager->tcp_saved_listener = tcp;
5660 
5661 	/*
5662 	 * Tag this detached tcp vector for later retrieval
5663 	 * by our listener client in tcp_accept().
5664 	 */
5665 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5666 	tcp->tcp_conn_req_cnt_q0++;
5667 	if (++tcp->tcp_conn_req_seqnum == -1) {
5668 		/*
5669 		 * -1 is "special" and defined in TPI as something
5670 		 * that should never be used in T_CONN_IND
5671 		 */
5672 		++tcp->tcp_conn_req_seqnum;
5673 	}
5674 	mutex_exit(&tcp->tcp_eager_lock);
5675 
5676 	if (tcp->tcp_syn_defense) {
5677 		/* Don't drop the SYN that comes from a good IP source */
5678 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5679 		if (addr_cache != NULL && eager->tcp_remote ==
5680 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5681 			eager->tcp_dontdrop = B_TRUE;
5682 		}
5683 	}
5684 
5685 	/*
5686 	 * We need to insert the eager in its own perimeter but as soon
5687 	 * as we do that, we expose the eager to the classifier and
5688 	 * should not touch any field outside the eager's perimeter.
5689 	 * So do all the work necessary before inserting the eager
5690 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5691 	 * will succeed but undo everything if it fails.
5692 	 */
5693 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5694 	eager->tcp_irs = seg_seq;
5695 	eager->tcp_rack = seg_seq;
5696 	eager->tcp_rnxt = seg_seq + 1;
5697 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5698 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5699 	eager->tcp_state = TCPS_SYN_RCVD;
5700 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5701 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5702 	if (mp1 == NULL) {
5703 		/*
5704 		 * Increment the ref count as we are going to
5705 		 * enqueueing an mp in squeue
5706 		 */
5707 		CONN_INC_REF(econnp);
5708 		goto error;
5709 	}
5710 
5711 	DB_CPID(mp1) = tcp->tcp_cpid;
5712 	mblk_setcred(mp1, CONN_CRED(eager->tcp_connp));
5713 	eager->tcp_cpid = tcp->tcp_cpid;
5714 	eager->tcp_open_time = lbolt64;
5715 
5716 	/*
5717 	 * We need to start the rto timer. In normal case, we start
5718 	 * the timer after sending the packet on the wire (or at
5719 	 * least believing that packet was sent by waiting for
5720 	 * CALL_IP_WPUT() to return). Since this is the first packet
5721 	 * being sent on the wire for the eager, our initial tcp_rto
5722 	 * is at least tcp_rexmit_interval_min which is a fairly
5723 	 * large value to allow the algorithm to adjust slowly to large
5724 	 * fluctuations of RTT during first few transmissions.
5725 	 *
5726 	 * Starting the timer first and then sending the packet in this
5727 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5728 	 * is of the order of several 100ms and starting the timer
5729 	 * first and then sending the packet will result in difference
5730 	 * of few micro seconds.
5731 	 *
5732 	 * Without this optimization, we are forced to hold the fanout
5733 	 * lock across the ipcl_bind_insert() and sending the packet
5734 	 * so that we don't race against an incoming packet (maybe RST)
5735 	 * for this eager.
5736 	 *
5737 	 * It is necessary to acquire an extra reference on the eager
5738 	 * at this point and hold it until after tcp_send_data() to
5739 	 * ensure against an eager close race.
5740 	 */
5741 
5742 	CONN_INC_REF(eager->tcp_connp);
5743 
5744 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5745 
5746 	/*
5747 	 * Insert the eager in its own perimeter now. We are ready to deal
5748 	 * with any packets on eager.
5749 	 */
5750 	if (eager->tcp_ipversion == IPV4_VERSION) {
5751 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5752 			goto error;
5753 		}
5754 	} else {
5755 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5756 			goto error;
5757 		}
5758 	}
5759 
5760 	/* mark conn as fully-bound */
5761 	econnp->conn_fully_bound = B_TRUE;
5762 
5763 	/* Send the SYN-ACK */
5764 	tcp_send_data(eager, eager->tcp_wq, mp1);
5765 	CONN_DEC_REF(eager->tcp_connp);
5766 	freemsg(mp);
5767 
5768 	return;
5769 error:
5770 	freemsg(mp1);
5771 	eager->tcp_closemp_used = B_TRUE;
5772 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5773 	mp1 = &eager->tcp_closemp;
5774 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5775 	    econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5776 
5777 	/*
5778 	 * If a connection already exists, send the mp to that connections so
5779 	 * that it can be appropriately dealt with.
5780 	 */
5781 	ipst = tcps->tcps_netstack->netstack_ip;
5782 
5783 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
5784 		if (!IPCL_IS_CONNECTED(econnp)) {
5785 			/*
5786 			 * Something bad happened. ipcl_conn_insert()
5787 			 * failed because a connection already existed
5788 			 * in connected hash but we can't find it
5789 			 * anymore (someone blew it away). Just
5790 			 * free this message and hopefully remote
5791 			 * will retransmit at which time the SYN can be
5792 			 * treated as a new connection or dealth with
5793 			 * a TH_RST if a connection already exists.
5794 			 */
5795 			CONN_DEC_REF(econnp);
5796 			freemsg(mp);
5797 		} else {
5798 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp,
5799 			    tcp_input, econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5800 		}
5801 	} else {
5802 		/* Nobody wants this packet */
5803 		freemsg(mp);
5804 	}
5805 	return;
5806 error3:
5807 	CONN_DEC_REF(econnp);
5808 error2:
5809 	freemsg(mp);
5810 }
5811 
5812 /*
5813  * In an ideal case of vertical partition in NUMA architecture, its
5814  * beneficial to have the listener and all the incoming connections
5815  * tied to the same squeue. The other constraint is that incoming
5816  * connections should be tied to the squeue attached to interrupted
5817  * CPU for obvious locality reason so this leaves the listener to
5818  * be tied to the same squeue. Our only problem is that when listener
5819  * is binding, the CPU that will get interrupted by the NIC whose
5820  * IP address the listener is binding to is not even known. So
5821  * the code below allows us to change that binding at the time the
5822  * CPU is interrupted by virtue of incoming connection's squeue.
5823  *
5824  * This is usefull only in case of a listener bound to a specific IP
5825  * address. For other kind of listeners, they get bound the
5826  * very first time and there is no attempt to rebind them.
5827  */
5828 void
5829 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5830 {
5831 	conn_t		*connp = (conn_t *)arg;
5832 	squeue_t	*sqp = (squeue_t *)arg2;
5833 	squeue_t	*new_sqp;
5834 	uint32_t	conn_flags;
5835 
5836 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5837 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5838 	} else {
5839 		goto done;
5840 	}
5841 
5842 	if (connp->conn_fanout == NULL)
5843 		goto done;
5844 
5845 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5846 		mutex_enter(&connp->conn_fanout->connf_lock);
5847 		mutex_enter(&connp->conn_lock);
5848 		/*
5849 		 * No one from read or write side can access us now
5850 		 * except for already queued packets on this squeue.
5851 		 * But since we haven't changed the squeue yet, they
5852 		 * can't execute. If they are processed after we have
5853 		 * changed the squeue, they are sent back to the
5854 		 * correct squeue down below.
5855 		 * But a listner close can race with processing of
5856 		 * incoming SYN. If incoming SYN processing changes
5857 		 * the squeue then the listener close which is waiting
5858 		 * to enter the squeue would operate on the wrong
5859 		 * squeue. Hence we don't change the squeue here unless
5860 		 * the refcount is exactly the minimum refcount. The
5861 		 * minimum refcount of 4 is counted as - 1 each for
5862 		 * TCP and IP, 1 for being in the classifier hash, and
5863 		 * 1 for the mblk being processed.
5864 		 */
5865 
5866 		if (connp->conn_ref != 4 ||
5867 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5868 			mutex_exit(&connp->conn_lock);
5869 			mutex_exit(&connp->conn_fanout->connf_lock);
5870 			goto done;
5871 		}
5872 		if (connp->conn_sqp != new_sqp) {
5873 			while (connp->conn_sqp != new_sqp)
5874 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5875 		}
5876 
5877 		do {
5878 			conn_flags = connp->conn_flags;
5879 			conn_flags |= IPCL_FULLY_BOUND;
5880 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5881 			    conn_flags);
5882 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5883 
5884 		mutex_exit(&connp->conn_fanout->connf_lock);
5885 		mutex_exit(&connp->conn_lock);
5886 	}
5887 
5888 done:
5889 	if (connp->conn_sqp != sqp) {
5890 		CONN_INC_REF(connp);
5891 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5892 		    SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5893 	} else {
5894 		tcp_conn_request(connp, mp, sqp);
5895 	}
5896 }
5897 
5898 /*
5899  * Successful connect request processing begins when our client passes
5900  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5901  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5902  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_tpi_connect() -> IP
5903  *   upstream <- tcp_rput()		<- IP
5904  * After various error checks are completed, tcp_tpi_connect() lays
5905  * the target address and port into the composite header template,
5906  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5907  * request followed by an IRE request, and passes the three mblk message
5908  * down to IP looking like this:
5909  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5910  * Processing continues in tcp_rput() when we receive the following message:
5911  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5912  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5913  * to fire off the connection request, and then passes the T_OK_ACK mblk
5914  * upstream that we filled in below.  There are, of course, numerous
5915  * error conditions along the way which truncate the processing described
5916  * above.
5917  */
5918 static void
5919 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5920 {
5921 	sin_t		*sin;
5922 	queue_t		*q = tcp->tcp_wq;
5923 	struct T_conn_req	*tcr;
5924 	struct sockaddr	*sa;
5925 	socklen_t	len;
5926 	int		error;
5927 
5928 	tcr = (struct T_conn_req *)mp->b_rptr;
5929 
5930 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5931 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5932 		tcp_err_ack(tcp, mp, TPROTO, 0);
5933 		return;
5934 	}
5935 
5936 	/*
5937 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5938 	 * will always have that to send up.  Otherwise, we need to do
5939 	 * special handling in case the allocation fails at that time.
5940 	 * If the end point is TPI, the tcp_t can be reused and the
5941 	 * tcp_ordrel_mp may be allocated already.
5942 	 */
5943 	if (tcp->tcp_ordrel_mp == NULL) {
5944 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5945 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5946 			return;
5947 		}
5948 	}
5949 
5950 	/*
5951 	 * Determine packet type based on type of address passed in
5952 	 * the request should contain an IPv4 or IPv6 address.
5953 	 * Make sure that address family matches the type of
5954 	 * family of the the address passed down
5955 	 */
5956 	switch (tcr->DEST_length) {
5957 	default:
5958 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5959 		return;
5960 
5961 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5962 		/*
5963 		 * XXX: The check for valid DEST_length was not there
5964 		 * in earlier releases and some buggy
5965 		 * TLI apps (e.g Sybase) got away with not feeding
5966 		 * in sin_zero part of address.
5967 		 * We allow that bug to keep those buggy apps humming.
5968 		 * Test suites require the check on DEST_length.
5969 		 * We construct a new mblk with valid DEST_length
5970 		 * free the original so the rest of the code does
5971 		 * not have to keep track of this special shorter
5972 		 * length address case.
5973 		 */
5974 		mblk_t *nmp;
5975 		struct T_conn_req *ntcr;
5976 		sin_t *nsin;
5977 
5978 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5979 		    tcr->OPT_length, BPRI_HI);
5980 		if (nmp == NULL) {
5981 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5982 			return;
5983 		}
5984 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5985 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5986 		ntcr->PRIM_type = T_CONN_REQ;
5987 		ntcr->DEST_length = sizeof (sin_t);
5988 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5989 
5990 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5991 		*nsin = sin_null;
5992 		/* Get pointer to shorter address to copy from original mp */
5993 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5994 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5995 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5996 			freemsg(nmp);
5997 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5998 			return;
5999 		}
6000 		nsin->sin_family = sin->sin_family;
6001 		nsin->sin_port = sin->sin_port;
6002 		nsin->sin_addr = sin->sin_addr;
6003 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6004 		nmp->b_wptr = (uchar_t *)&nsin[1];
6005 		if (tcr->OPT_length != 0) {
6006 			ntcr->OPT_length = tcr->OPT_length;
6007 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6008 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6009 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6010 			    tcr->OPT_length);
6011 			nmp->b_wptr += tcr->OPT_length;
6012 		}
6013 		freemsg(mp);	/* original mp freed */
6014 		mp = nmp;	/* re-initialize original variables */
6015 		tcr = ntcr;
6016 	}
6017 	/* FALLTHRU */
6018 
6019 	case sizeof (sin_t):
6020 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6021 		    sizeof (sin_t));
6022 		len = sizeof (sin_t);
6023 		break;
6024 
6025 	case sizeof (sin6_t):
6026 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6027 		    sizeof (sin6_t));
6028 		len = sizeof (sin6_t);
6029 		break;
6030 	}
6031 
6032 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
6033 	if (error != 0) {
6034 		tcp_err_ack(tcp, mp, TSYSERR, error);
6035 		return;
6036 	}
6037 
6038 	/*
6039 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6040 	 * should key on their sequence number and cut them loose.
6041 	 */
6042 
6043 	/*
6044 	 * If options passed in, feed it for verification and handling
6045 	 */
6046 	if (tcr->OPT_length != 0) {
6047 		mblk_t	*ok_mp;
6048 		mblk_t	*discon_mp;
6049 		mblk_t  *conn_opts_mp;
6050 		int t_error, sys_error, do_disconnect;
6051 
6052 		conn_opts_mp = NULL;
6053 
6054 		if (tcp_conprim_opt_process(tcp, mp,
6055 		    &do_disconnect, &t_error, &sys_error) < 0) {
6056 			if (do_disconnect) {
6057 				ASSERT(t_error == 0 && sys_error == 0);
6058 				discon_mp = mi_tpi_discon_ind(NULL,
6059 				    ECONNREFUSED, 0);
6060 				if (!discon_mp) {
6061 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6062 					    TSYSERR, ENOMEM);
6063 					return;
6064 				}
6065 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6066 				if (!ok_mp) {
6067 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6068 					    TSYSERR, ENOMEM);
6069 					return;
6070 				}
6071 				qreply(q, ok_mp);
6072 				qreply(q, discon_mp); /* no flush! */
6073 			} else {
6074 				ASSERT(t_error != 0);
6075 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6076 				    sys_error);
6077 			}
6078 			return;
6079 		}
6080 		/*
6081 		 * Success in setting options, the mp option buffer represented
6082 		 * by OPT_length/offset has been potentially modified and
6083 		 * contains results of option processing. We copy it in
6084 		 * another mp to save it for potentially influencing returning
6085 		 * it in T_CONN_CONN.
6086 		 */
6087 		if (tcr->OPT_length != 0) { /* there are resulting options */
6088 			conn_opts_mp = copyb(mp);
6089 			if (!conn_opts_mp) {
6090 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6091 				    TSYSERR, ENOMEM);
6092 				return;
6093 			}
6094 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6095 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6096 			/*
6097 			 * Note:
6098 			 * These resulting option negotiation can include any
6099 			 * end-to-end negotiation options but there no such
6100 			 * thing (yet?) in our TCP/IP.
6101 			 */
6102 		}
6103 	}
6104 
6105 	/* call the non-TPI version */
6106 	error = tcp_do_connect(tcp->tcp_connp, sa, len, DB_CRED(mp),
6107 	    DB_CPID(mp));
6108 	if (error < 0) {
6109 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
6110 	} else if (error > 0) {
6111 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
6112 	} else {
6113 		mp = mi_tpi_ok_ack_alloc(mp);
6114 	}
6115 
6116 	/*
6117 	 * Note: Code below is the "failure" case
6118 	 */
6119 	/* return error ack and blow away saved option results if any */
6120 connect_failed:
6121 	if (mp != NULL)
6122 		putnext(tcp->tcp_rq, mp);
6123 	else {
6124 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6125 		    TSYSERR, ENOMEM);
6126 	}
6127 }
6128 
6129 /*
6130  * Handle connect to IPv4 destinations, including connections for AF_INET6
6131  * sockets connecting to IPv4 mapped IPv6 destinations.
6132  */
6133 static int
6134 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
6135     uint_t srcid, cred_t *cr, pid_t pid)
6136 {
6137 	tcph_t	*tcph;
6138 	mblk_t	*mp;
6139 	ipaddr_t dstaddr = *dstaddrp;
6140 	int32_t	oldstate;
6141 	uint16_t lport;
6142 	int	error = 0;
6143 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6144 
6145 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6146 
6147 	/* Check for attempt to connect to INADDR_ANY */
6148 	if (dstaddr == INADDR_ANY)  {
6149 		/*
6150 		 * SunOS 4.x and 4.3 BSD allow an application
6151 		 * to connect a TCP socket to INADDR_ANY.
6152 		 * When they do this, the kernel picks the
6153 		 * address of one interface and uses it
6154 		 * instead.  The kernel usually ends up
6155 		 * picking the address of the loopback
6156 		 * interface.  This is an undocumented feature.
6157 		 * However, we provide the same thing here
6158 		 * in order to have source and binary
6159 		 * compatibility with SunOS 4.x.
6160 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6161 		 * generate the T_CONN_CON.
6162 		 */
6163 		dstaddr = htonl(INADDR_LOOPBACK);
6164 		*dstaddrp = dstaddr;
6165 	}
6166 
6167 	/* Handle __sin6_src_id if socket not bound to an IP address */
6168 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6169 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6170 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6171 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6172 		    tcp->tcp_ipha->ipha_src);
6173 	}
6174 
6175 	/*
6176 	 * Don't let an endpoint connect to itself.  Note that
6177 	 * the test here does not catch the case where the
6178 	 * source IP addr was left unspecified by the user. In
6179 	 * this case, the source addr is set in tcp_adapt_ire()
6180 	 * using the reply to the T_BIND message that we send
6181 	 * down to IP here and the check is repeated in tcp_rput_other.
6182 	 */
6183 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6184 	    dstport == tcp->tcp_lport) {
6185 		error = -TBADADDR;
6186 		goto failed;
6187 	}
6188 
6189 	tcp->tcp_ipha->ipha_dst = dstaddr;
6190 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6191 
6192 	/*
6193 	 * Massage a source route if any putting the first hop
6194 	 * in iph_dst. Compute a starting value for the checksum which
6195 	 * takes into account that the original iph_dst should be
6196 	 * included in the checksum but that ip will include the
6197 	 * first hop in the source route in the tcp checksum.
6198 	 */
6199 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6200 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6201 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6202 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6203 	if ((int)tcp->tcp_sum < 0)
6204 		tcp->tcp_sum--;
6205 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6206 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6207 	    (tcp->tcp_sum >> 16));
6208 	tcph = tcp->tcp_tcph;
6209 	*(uint16_t *)tcph->th_fport = dstport;
6210 	tcp->tcp_fport = dstport;
6211 
6212 	oldstate = tcp->tcp_state;
6213 	/*
6214 	 * At this point the remote destination address and remote port fields
6215 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6216 	 * have to see which state tcp was in so we can take apropriate action.
6217 	 */
6218 	if (oldstate == TCPS_IDLE) {
6219 		/*
6220 		 * We support a quick connect capability here, allowing
6221 		 * clients to transition directly from IDLE to SYN_SENT
6222 		 * tcp_bindi will pick an unused port, insert the connection
6223 		 * in the bind hash and transition to BOUND state.
6224 		 */
6225 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6226 		    tcp, B_TRUE);
6227 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6228 		    B_FALSE, B_FALSE);
6229 		if (lport == 0) {
6230 			error = -TNOADDR;
6231 			goto failed;
6232 		}
6233 	}
6234 	tcp->tcp_state = TCPS_SYN_SENT;
6235 
6236 	mp = allocb(sizeof (ire_t), BPRI_HI);
6237 	if (mp == NULL) {
6238 		tcp->tcp_state = oldstate;
6239 		error = ENOMEM;
6240 		goto failed;
6241 	}
6242 
6243 	mp->b_wptr += sizeof (ire_t);
6244 	mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6245 	tcp->tcp_hard_binding = 1;
6246 
6247 	/*
6248 	 * We need to make sure that the conn_recv is set to a non-null
6249 	 * value before we insert the conn_t into the classifier table.
6250 	 * This is to avoid a race with an incoming packet which does
6251 	 * an ipcl_classify().
6252 	 */
6253 	tcp->tcp_connp->conn_recv = tcp_input;
6254 
6255 	if (tcp->tcp_family == AF_INET) {
6256 		error = ip_proto_bind_connected_v4(tcp->tcp_connp, &mp,
6257 		    IPPROTO_TCP, &tcp->tcp_ipha->ipha_src, tcp->tcp_lport,
6258 		    tcp->tcp_remote, tcp->tcp_fport, B_TRUE, B_TRUE);
6259 	} else {
6260 		in6_addr_t v6src;
6261 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6262 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6263 		} else {
6264 			v6src = tcp->tcp_ip6h->ip6_src;
6265 		}
6266 		error = ip_proto_bind_connected_v6(tcp->tcp_connp, &mp,
6267 		    IPPROTO_TCP, &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6268 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE);
6269 	}
6270 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6271 	tcp->tcp_active_open = 1;
6272 
6273 
6274 	return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6275 failed:
6276 	/* return error ack and blow away saved option results if any */
6277 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6278 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6279 	return (error);
6280 }
6281 
6282 /*
6283  * Handle connect to IPv6 destinations.
6284  */
6285 static int
6286 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
6287     uint32_t flowinfo, uint_t srcid, uint32_t scope_id, cred_t *cr, pid_t pid)
6288 {
6289 	tcph_t	*tcph;
6290 	mblk_t	*mp;
6291 	ip6_rthdr_t *rth;
6292 	int32_t  oldstate;
6293 	uint16_t lport;
6294 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6295 	int	error = 0;
6296 	conn_t	*connp = tcp->tcp_connp;
6297 
6298 	ASSERT(tcp->tcp_family == AF_INET6);
6299 
6300 	/*
6301 	 * If we're here, it means that the destination address is a native
6302 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6303 	 * reason why it might not be IPv6 is if the socket was bound to an
6304 	 * IPv4-mapped IPv6 address.
6305 	 */
6306 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6307 		return (-TBADADDR);
6308 	}
6309 
6310 	/*
6311 	 * Interpret a zero destination to mean loopback.
6312 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6313 	 * generate the T_CONN_CON.
6314 	 */
6315 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6316 		*dstaddrp = ipv6_loopback;
6317 	}
6318 
6319 	/* Handle __sin6_src_id if socket not bound to an IP address */
6320 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6321 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6322 		    connp->conn_zoneid, tcps->tcps_netstack);
6323 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6324 	}
6325 
6326 	/*
6327 	 * Take care of the scope_id now and add ip6i_t
6328 	 * if ip6i_t is not already allocated through TCP
6329 	 * sticky options. At this point tcp_ip6h does not
6330 	 * have dst info, thus use dstaddrp.
6331 	 */
6332 	if (scope_id != 0 &&
6333 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6334 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6335 		ip6i_t  *ip6i;
6336 
6337 		ipp->ipp_ifindex = scope_id;
6338 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6339 
6340 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6341 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6342 			/* Already allocated */
6343 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6344 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6345 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6346 		} else {
6347 			int reterr;
6348 
6349 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6350 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6351 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6352 			reterr = tcp_build_hdrs(tcp);
6353 			if (reterr != 0)
6354 				goto failed;
6355 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6356 		}
6357 	}
6358 
6359 	/*
6360 	 * Don't let an endpoint connect to itself.  Note that
6361 	 * the test here does not catch the case where the
6362 	 * source IP addr was left unspecified by the user. In
6363 	 * this case, the source addr is set in tcp_adapt_ire()
6364 	 * using the reply to the T_BIND message that we send
6365 	 * down to IP here and the check is repeated in tcp_rput_other.
6366 	 */
6367 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6368 	    (dstport == tcp->tcp_lport)) {
6369 		error = -TBADADDR;
6370 		goto failed;
6371 	}
6372 
6373 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6374 	tcp->tcp_remote_v6 = *dstaddrp;
6375 	tcp->tcp_ip6h->ip6_vcf =
6376 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6377 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6378 
6379 	/*
6380 	 * Massage a routing header (if present) putting the first hop
6381 	 * in ip6_dst. Compute a starting value for the checksum which
6382 	 * takes into account that the original ip6_dst should be
6383 	 * included in the checksum but that ip will include the
6384 	 * first hop in the source route in the tcp checksum.
6385 	 */
6386 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6387 	if (rth != NULL) {
6388 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6389 		    tcps->tcps_netstack);
6390 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6391 		    (tcp->tcp_sum >> 16));
6392 	} else {
6393 		tcp->tcp_sum = 0;
6394 	}
6395 
6396 	tcph = tcp->tcp_tcph;
6397 	*(uint16_t *)tcph->th_fport = dstport;
6398 	tcp->tcp_fport = dstport;
6399 
6400 	oldstate = tcp->tcp_state;
6401 	/*
6402 	 * At this point the remote destination address and remote port fields
6403 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6404 	 * have to see which state tcp was in so we can take apropriate action.
6405 	 */
6406 	if (oldstate == TCPS_IDLE) {
6407 		/*
6408 		 * We support a quick connect capability here, allowing
6409 		 * clients to transition directly from IDLE to SYN_SENT
6410 		 * tcp_bindi will pick an unused port, insert the connection
6411 		 * in the bind hash and transition to BOUND state.
6412 		 */
6413 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6414 		    tcp, B_TRUE);
6415 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6416 		    B_FALSE, B_FALSE);
6417 		if (lport == 0) {
6418 			error = -TNOADDR;
6419 			goto failed;
6420 		}
6421 	}
6422 	tcp->tcp_state = TCPS_SYN_SENT;
6423 
6424 	mp = allocb(sizeof (ire_t), BPRI_HI);
6425 	if (mp != NULL) {
6426 		in6_addr_t v6src;
6427 
6428 		mp->b_wptr += sizeof (ire_t);
6429 		mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6430 
6431 		tcp->tcp_hard_binding = 1;
6432 
6433 		/*
6434 		 * We need to make sure that the conn_recv is set to a non-null
6435 		 * value before we insert the conn_t into the classifier table.
6436 		 * This is to avoid a race with an incoming packet which does
6437 		 * an ipcl_classify().
6438 		 */
6439 		tcp->tcp_connp->conn_recv = tcp_input;
6440 
6441 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6442 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6443 		} else {
6444 			v6src = tcp->tcp_ip6h->ip6_src;
6445 		}
6446 		error = ip_proto_bind_connected_v6(connp, &mp, IPPROTO_TCP,
6447 		    &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6448 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE);
6449 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6450 		tcp->tcp_active_open = 1;
6451 
6452 		return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6453 	}
6454 	/* Error case */
6455 	tcp->tcp_state = oldstate;
6456 	error = ENOMEM;
6457 
6458 failed:
6459 	/* return error ack and blow away saved option results if any */
6460 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6461 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6462 	return (error);
6463 }
6464 
6465 /*
6466  * We need a stream q for detached closing tcp connections
6467  * to use.  Our client hereby indicates that this q is the
6468  * one to use.
6469  */
6470 static void
6471 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6472 {
6473 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6474 	queue_t	*q = tcp->tcp_wq;
6475 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6476 
6477 #ifdef NS_DEBUG
6478 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6479 	    tcps->tcps_netstack->netstack_stackid);
6480 #endif
6481 	mp->b_datap->db_type = M_IOCACK;
6482 	iocp->ioc_count = 0;
6483 	mutex_enter(&tcps->tcps_g_q_lock);
6484 	if (tcps->tcps_g_q != NULL) {
6485 		mutex_exit(&tcps->tcps_g_q_lock);
6486 		iocp->ioc_error = EALREADY;
6487 	} else {
6488 		int error = 0;
6489 		conn_t *connp = tcp->tcp_connp;
6490 		ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
6491 
6492 		tcps->tcps_g_q = tcp->tcp_rq;
6493 		mutex_exit(&tcps->tcps_g_q_lock);
6494 		iocp->ioc_error = 0;
6495 		iocp->ioc_rval = 0;
6496 		/*
6497 		 * We are passing tcp_sticky_ipp as NULL
6498 		 * as it is not useful for tcp_default queue
6499 		 *
6500 		 * Set conn_recv just in case.
6501 		 */
6502 		tcp->tcp_connp->conn_recv = tcp_conn_request;
6503 
6504 		ASSERT(connp->conn_af_isv6);
6505 		connp->conn_ulp = IPPROTO_TCP;
6506 
6507 		if (ipst->ips_ipcl_proto_fanout_v6[IPPROTO_TCP].connf_head !=
6508 		    NULL || connp->conn_mac_exempt) {
6509 			error = -TBADADDR;
6510 		} else {
6511 			connp->conn_srcv6 = ipv6_all_zeros;
6512 			ipcl_proto_insert_v6(connp, IPPROTO_TCP);
6513 		}
6514 
6515 		(void) tcp_post_ip_bind(tcp, NULL, error, NULL, 0);
6516 	}
6517 	qreply(q, mp);
6518 }
6519 
6520 static int
6521 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
6522 {
6523 	tcp_t	*ltcp = NULL;
6524 	conn_t	*connp;
6525 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6526 
6527 	/*
6528 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6529 	 * when the stream is in BOUND state. Do not send a reset,
6530 	 * since the destination IP address is not valid, and it can
6531 	 * be the initialized value of all zeros (broadcast address).
6532 	 *
6533 	 * XXX There won't be any pending bind request to IP.
6534 	 */
6535 	if (tcp->tcp_state <= TCPS_BOUND) {
6536 		if (tcp->tcp_debug) {
6537 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6538 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6539 		}
6540 		return (TOUTSTATE);
6541 	}
6542 
6543 
6544 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6545 
6546 		/*
6547 		 * According to TPI, for non-listeners, ignore seqnum
6548 		 * and disconnect.
6549 		 * Following interpretation of -1 seqnum is historical
6550 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6551 		 * a valid seqnum should not be -1).
6552 		 *
6553 		 *	-1 means disconnect everything
6554 		 *	regardless even on a listener.
6555 		 */
6556 
6557 		int old_state = tcp->tcp_state;
6558 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6559 
6560 		/*
6561 		 * The connection can't be on the tcp_time_wait_head list
6562 		 * since it is not detached.
6563 		 */
6564 		ASSERT(tcp->tcp_time_wait_next == NULL);
6565 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6566 		ASSERT(tcp->tcp_time_wait_expire == 0);
6567 		ltcp = NULL;
6568 		/*
6569 		 * If it used to be a listener, check to make sure no one else
6570 		 * has taken the port before switching back to LISTEN state.
6571 		 */
6572 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6573 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6574 			    tcp->tcp_ipha->ipha_src,
6575 			    tcp->tcp_connp->conn_zoneid, ipst);
6576 			if (connp != NULL)
6577 				ltcp = connp->conn_tcp;
6578 		} else {
6579 			/* Allow tcp_bound_if listeners? */
6580 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6581 			    &tcp->tcp_ip6h->ip6_src, 0,
6582 			    tcp->tcp_connp->conn_zoneid, ipst);
6583 			if (connp != NULL)
6584 				ltcp = connp->conn_tcp;
6585 		}
6586 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6587 			tcp->tcp_state = TCPS_LISTEN;
6588 		} else if (old_state > TCPS_BOUND) {
6589 			tcp->tcp_conn_req_max = 0;
6590 			tcp->tcp_state = TCPS_BOUND;
6591 		}
6592 		if (ltcp != NULL)
6593 			CONN_DEC_REF(ltcp->tcp_connp);
6594 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6595 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6596 		} else if (old_state == TCPS_ESTABLISHED ||
6597 		    old_state == TCPS_CLOSE_WAIT) {
6598 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6599 		}
6600 
6601 		if (tcp->tcp_fused)
6602 			tcp_unfuse(tcp);
6603 
6604 		mutex_enter(&tcp->tcp_eager_lock);
6605 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6606 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6607 			tcp_eager_cleanup(tcp, 0);
6608 		}
6609 		mutex_exit(&tcp->tcp_eager_lock);
6610 
6611 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6612 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6613 
6614 		tcp_reinit(tcp);
6615 
6616 		return (0);
6617 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6618 		return (TBADSEQ);
6619 	}
6620 	return (0);
6621 }
6622 
6623 /*
6624  * Our client hereby directs us to reject the connection request
6625  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6626  * of sending the appropriate RST, not an ICMP error.
6627  */
6628 static void
6629 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6630 {
6631 	t_scalar_t seqnum;
6632 	int	error;
6633 
6634 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6635 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6636 		tcp_err_ack(tcp, mp, TPROTO, 0);
6637 		return;
6638 	}
6639 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6640 	error = tcp_disconnect_common(tcp, seqnum);
6641 	if (error != 0)
6642 		tcp_err_ack(tcp, mp, error, 0);
6643 	else {
6644 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6645 			/* Send M_FLUSH according to TPI */
6646 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6647 		}
6648 		mp = mi_tpi_ok_ack_alloc(mp);
6649 		if (mp)
6650 			putnext(tcp->tcp_rq, mp);
6651 	}
6652 }
6653 
6654 /*
6655  * Diagnostic routine used to return a string associated with the tcp state.
6656  * Note that if the caller does not supply a buffer, it will use an internal
6657  * static string.  This means that if multiple threads call this function at
6658  * the same time, output can be corrupted...  Note also that this function
6659  * does not check the size of the supplied buffer.  The caller has to make
6660  * sure that it is big enough.
6661  */
6662 static char *
6663 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6664 {
6665 	char		buf1[30];
6666 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6667 	char		*buf;
6668 	char		*cp;
6669 	in6_addr_t	local, remote;
6670 	char		local_addrbuf[INET6_ADDRSTRLEN];
6671 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6672 
6673 	if (sup_buf != NULL)
6674 		buf = sup_buf;
6675 	else
6676 		buf = priv_buf;
6677 
6678 	if (tcp == NULL)
6679 		return ("NULL_TCP");
6680 	switch (tcp->tcp_state) {
6681 	case TCPS_CLOSED:
6682 		cp = "TCP_CLOSED";
6683 		break;
6684 	case TCPS_IDLE:
6685 		cp = "TCP_IDLE";
6686 		break;
6687 	case TCPS_BOUND:
6688 		cp = "TCP_BOUND";
6689 		break;
6690 	case TCPS_LISTEN:
6691 		cp = "TCP_LISTEN";
6692 		break;
6693 	case TCPS_SYN_SENT:
6694 		cp = "TCP_SYN_SENT";
6695 		break;
6696 	case TCPS_SYN_RCVD:
6697 		cp = "TCP_SYN_RCVD";
6698 		break;
6699 	case TCPS_ESTABLISHED:
6700 		cp = "TCP_ESTABLISHED";
6701 		break;
6702 	case TCPS_CLOSE_WAIT:
6703 		cp = "TCP_CLOSE_WAIT";
6704 		break;
6705 	case TCPS_FIN_WAIT_1:
6706 		cp = "TCP_FIN_WAIT_1";
6707 		break;
6708 	case TCPS_CLOSING:
6709 		cp = "TCP_CLOSING";
6710 		break;
6711 	case TCPS_LAST_ACK:
6712 		cp = "TCP_LAST_ACK";
6713 		break;
6714 	case TCPS_FIN_WAIT_2:
6715 		cp = "TCP_FIN_WAIT_2";
6716 		break;
6717 	case TCPS_TIME_WAIT:
6718 		cp = "TCP_TIME_WAIT";
6719 		break;
6720 	default:
6721 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6722 		cp = buf1;
6723 		break;
6724 	}
6725 	switch (format) {
6726 	case DISP_ADDR_AND_PORT:
6727 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6728 			/*
6729 			 * Note that we use the remote address in the tcp_b
6730 			 * structure.  This means that it will print out
6731 			 * the real destination address, not the next hop's
6732 			 * address if source routing is used.
6733 			 */
6734 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6735 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6736 
6737 		} else {
6738 			local = tcp->tcp_ip_src_v6;
6739 			remote = tcp->tcp_remote_v6;
6740 		}
6741 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6742 		    sizeof (local_addrbuf));
6743 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6744 		    sizeof (remote_addrbuf));
6745 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6746 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6747 		    ntohs(tcp->tcp_fport), cp);
6748 		break;
6749 	case DISP_PORT_ONLY:
6750 	default:
6751 		(void) mi_sprintf(buf, "[%u, %u] %s",
6752 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6753 		break;
6754 	}
6755 
6756 	return (buf);
6757 }
6758 
6759 /*
6760  * Called via squeue to get on to eager's perimeter. It sends a
6761  * TH_RST if eager is in the fanout table. The listener wants the
6762  * eager to disappear either by means of tcp_eager_blowoff() or
6763  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
6764  * called (via squeue) if the eager cannot be inserted in the
6765  * fanout table in tcp_conn_request().
6766  */
6767 /* ARGSUSED */
6768 void
6769 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6770 {
6771 	conn_t	*econnp = (conn_t *)arg;
6772 	tcp_t	*eager = econnp->conn_tcp;
6773 	tcp_t	*listener = eager->tcp_listener;
6774 	tcp_stack_t	*tcps = eager->tcp_tcps;
6775 
6776 	/*
6777 	 * We could be called because listener is closing. Since
6778 	 * the eager is using listener's queue's, its not safe.
6779 	 * Better use the default queue just to send the TH_RST
6780 	 * out.
6781 	 */
6782 	ASSERT(tcps->tcps_g_q != NULL);
6783 	eager->tcp_rq = tcps->tcps_g_q;
6784 	eager->tcp_wq = WR(tcps->tcps_g_q);
6785 
6786 	/*
6787 	 * An eager's conn_fanout will be NULL if it's a duplicate
6788 	 * for an existing 4-tuples in the conn fanout table.
6789 	 * We don't want to send an RST out in such case.
6790 	 */
6791 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
6792 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6793 		    eager, eager->tcp_snxt, 0, TH_RST);
6794 	}
6795 
6796 	/* We are here because listener wants this eager gone */
6797 	if (listener != NULL) {
6798 		mutex_enter(&listener->tcp_eager_lock);
6799 		tcp_eager_unlink(eager);
6800 		if (eager->tcp_tconnind_started) {
6801 			/*
6802 			 * The eager has sent a conn_ind up to the
6803 			 * listener but listener decides to close
6804 			 * instead. We need to drop the extra ref
6805 			 * placed on eager in tcp_rput_data() before
6806 			 * sending the conn_ind to listener.
6807 			 */
6808 			CONN_DEC_REF(econnp);
6809 		}
6810 		mutex_exit(&listener->tcp_eager_lock);
6811 		CONN_DEC_REF(listener->tcp_connp);
6812 	}
6813 
6814 	if (eager->tcp_state > TCPS_BOUND)
6815 		tcp_close_detached(eager);
6816 }
6817 
6818 /*
6819  * Reset any eager connection hanging off this listener marked
6820  * with 'seqnum' and then reclaim it's resources.
6821  */
6822 static boolean_t
6823 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6824 {
6825 	tcp_t	*eager;
6826 	mblk_t 	*mp;
6827 	tcp_stack_t	*tcps = listener->tcp_tcps;
6828 
6829 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
6830 	eager = listener;
6831 	mutex_enter(&listener->tcp_eager_lock);
6832 	do {
6833 		eager = eager->tcp_eager_next_q;
6834 		if (eager == NULL) {
6835 			mutex_exit(&listener->tcp_eager_lock);
6836 			return (B_FALSE);
6837 		}
6838 	} while (eager->tcp_conn_req_seqnum != seqnum);
6839 
6840 	if (eager->tcp_closemp_used) {
6841 		mutex_exit(&listener->tcp_eager_lock);
6842 		return (B_TRUE);
6843 	}
6844 	eager->tcp_closemp_used = B_TRUE;
6845 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6846 	CONN_INC_REF(eager->tcp_connp);
6847 	mutex_exit(&listener->tcp_eager_lock);
6848 	mp = &eager->tcp_closemp;
6849 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6850 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
6851 	return (B_TRUE);
6852 }
6853 
6854 /*
6855  * Reset any eager connection hanging off this listener
6856  * and then reclaim it's resources.
6857  */
6858 static void
6859 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6860 {
6861 	tcp_t	*eager;
6862 	mblk_t	*mp;
6863 	tcp_stack_t	*tcps = listener->tcp_tcps;
6864 
6865 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6866 
6867 	if (!q0_only) {
6868 		/* First cleanup q */
6869 		TCP_STAT(tcps, tcp_eager_blowoff_q);
6870 		eager = listener->tcp_eager_next_q;
6871 		while (eager != NULL) {
6872 			if (!eager->tcp_closemp_used) {
6873 				eager->tcp_closemp_used = B_TRUE;
6874 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6875 				CONN_INC_REF(eager->tcp_connp);
6876 				mp = &eager->tcp_closemp;
6877 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6878 				    tcp_eager_kill, eager->tcp_connp,
6879 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
6880 			}
6881 			eager = eager->tcp_eager_next_q;
6882 		}
6883 	}
6884 	/* Then cleanup q0 */
6885 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6886 	eager = listener->tcp_eager_next_q0;
6887 	while (eager != listener) {
6888 		if (!eager->tcp_closemp_used) {
6889 			eager->tcp_closemp_used = B_TRUE;
6890 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6891 			CONN_INC_REF(eager->tcp_connp);
6892 			mp = &eager->tcp_closemp;
6893 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6894 			    tcp_eager_kill, eager->tcp_connp, SQ_FILL,
6895 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6896 		}
6897 		eager = eager->tcp_eager_next_q0;
6898 	}
6899 }
6900 
6901 /*
6902  * If we are an eager connection hanging off a listener that hasn't
6903  * formally accepted the connection yet, get off his list and blow off
6904  * any data that we have accumulated.
6905  */
6906 static void
6907 tcp_eager_unlink(tcp_t *tcp)
6908 {
6909 	tcp_t	*listener = tcp->tcp_listener;
6910 
6911 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6912 	ASSERT(listener != NULL);
6913 	if (tcp->tcp_eager_next_q0 != NULL) {
6914 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6915 
6916 		/* Remove the eager tcp from q0 */
6917 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6918 		    tcp->tcp_eager_prev_q0;
6919 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6920 		    tcp->tcp_eager_next_q0;
6921 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6922 		listener->tcp_conn_req_cnt_q0--;
6923 
6924 		tcp->tcp_eager_next_q0 = NULL;
6925 		tcp->tcp_eager_prev_q0 = NULL;
6926 
6927 		/*
6928 		 * Take the eager out, if it is in the list of droppable
6929 		 * eagers.
6930 		 */
6931 		MAKE_UNDROPPABLE(tcp);
6932 
6933 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6934 			/* we have timed out before */
6935 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6936 			listener->tcp_syn_rcvd_timeout--;
6937 		}
6938 	} else {
6939 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6940 		tcp_t	*prev = NULL;
6941 
6942 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6943 			if (tcpp[0] == tcp) {
6944 				if (listener->tcp_eager_last_q == tcp) {
6945 					/*
6946 					 * If we are unlinking the last
6947 					 * element on the list, adjust
6948 					 * tail pointer. Set tail pointer
6949 					 * to nil when list is empty.
6950 					 */
6951 					ASSERT(tcp->tcp_eager_next_q == NULL);
6952 					if (listener->tcp_eager_last_q ==
6953 					    listener->tcp_eager_next_q) {
6954 						listener->tcp_eager_last_q =
6955 						    NULL;
6956 					} else {
6957 						/*
6958 						 * We won't get here if there
6959 						 * is only one eager in the
6960 						 * list.
6961 						 */
6962 						ASSERT(prev != NULL);
6963 						listener->tcp_eager_last_q =
6964 						    prev;
6965 					}
6966 				}
6967 				tcpp[0] = tcp->tcp_eager_next_q;
6968 				tcp->tcp_eager_next_q = NULL;
6969 				tcp->tcp_eager_last_q = NULL;
6970 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6971 				listener->tcp_conn_req_cnt_q--;
6972 				break;
6973 			}
6974 			prev = tcpp[0];
6975 		}
6976 	}
6977 	tcp->tcp_listener = NULL;
6978 }
6979 
6980 /* Shorthand to generate and send TPI error acks to our client */
6981 static void
6982 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6983 {
6984 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6985 		putnext(tcp->tcp_rq, mp);
6986 }
6987 
6988 /* Shorthand to generate and send TPI error acks to our client */
6989 static void
6990 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6991     int t_error, int sys_error)
6992 {
6993 	struct T_error_ack	*teackp;
6994 
6995 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
6996 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
6997 		teackp = (struct T_error_ack *)mp->b_rptr;
6998 		teackp->ERROR_prim = primitive;
6999 		teackp->TLI_error = t_error;
7000 		teackp->UNIX_error = sys_error;
7001 		putnext(tcp->tcp_rq, mp);
7002 	}
7003 }
7004 
7005 /*
7006  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7007  * but instead the code relies on:
7008  * - the fact that the address of the array and its size never changes
7009  * - the atomic assignment of the elements of the array
7010  */
7011 /* ARGSUSED */
7012 static int
7013 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7014 {
7015 	int i;
7016 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7017 
7018 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7019 		if (tcps->tcps_g_epriv_ports[i] != 0)
7020 			(void) mi_mpprintf(mp, "%d ",
7021 			    tcps->tcps_g_epriv_ports[i]);
7022 	}
7023 	return (0);
7024 }
7025 
7026 /*
7027  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7028  * threads from changing it at the same time.
7029  */
7030 /* ARGSUSED */
7031 static int
7032 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7033     cred_t *cr)
7034 {
7035 	long	new_value;
7036 	int	i;
7037 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7038 
7039 	/*
7040 	 * Fail the request if the new value does not lie within the
7041 	 * port number limits.
7042 	 */
7043 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7044 	    new_value <= 0 || new_value >= 65536) {
7045 		return (EINVAL);
7046 	}
7047 
7048 	mutex_enter(&tcps->tcps_epriv_port_lock);
7049 	/* Check if the value is already in the list */
7050 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7051 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7052 			mutex_exit(&tcps->tcps_epriv_port_lock);
7053 			return (EEXIST);
7054 		}
7055 	}
7056 	/* Find an empty slot */
7057 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7058 		if (tcps->tcps_g_epriv_ports[i] == 0)
7059 			break;
7060 	}
7061 	if (i == tcps->tcps_g_num_epriv_ports) {
7062 		mutex_exit(&tcps->tcps_epriv_port_lock);
7063 		return (EOVERFLOW);
7064 	}
7065 	/* Set the new value */
7066 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7067 	mutex_exit(&tcps->tcps_epriv_port_lock);
7068 	return (0);
7069 }
7070 
7071 /*
7072  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7073  * threads from changing it at the same time.
7074  */
7075 /* ARGSUSED */
7076 static int
7077 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7078     cred_t *cr)
7079 {
7080 	long	new_value;
7081 	int	i;
7082 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7083 
7084 	/*
7085 	 * Fail the request if the new value does not lie within the
7086 	 * port number limits.
7087 	 */
7088 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7089 	    new_value >= 65536) {
7090 		return (EINVAL);
7091 	}
7092 
7093 	mutex_enter(&tcps->tcps_epriv_port_lock);
7094 	/* Check that the value is already in the list */
7095 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7096 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7097 			break;
7098 	}
7099 	if (i == tcps->tcps_g_num_epriv_ports) {
7100 		mutex_exit(&tcps->tcps_epriv_port_lock);
7101 		return (ESRCH);
7102 	}
7103 	/* Clear the value */
7104 	tcps->tcps_g_epriv_ports[i] = 0;
7105 	mutex_exit(&tcps->tcps_epriv_port_lock);
7106 	return (0);
7107 }
7108 
7109 /* Return the TPI/TLI equivalent of our current tcp_state */
7110 static int
7111 tcp_tpistate(tcp_t *tcp)
7112 {
7113 	switch (tcp->tcp_state) {
7114 	case TCPS_IDLE:
7115 		return (TS_UNBND);
7116 	case TCPS_LISTEN:
7117 		/*
7118 		 * Return whether there are outstanding T_CONN_IND waiting
7119 		 * for the matching T_CONN_RES. Therefore don't count q0.
7120 		 */
7121 		if (tcp->tcp_conn_req_cnt_q > 0)
7122 			return (TS_WRES_CIND);
7123 		else
7124 			return (TS_IDLE);
7125 	case TCPS_BOUND:
7126 		return (TS_IDLE);
7127 	case TCPS_SYN_SENT:
7128 		return (TS_WCON_CREQ);
7129 	case TCPS_SYN_RCVD:
7130 		/*
7131 		 * Note: assumption: this has to the active open SYN_RCVD.
7132 		 * The passive instance is detached in SYN_RCVD stage of
7133 		 * incoming connection processing so we cannot get request
7134 		 * for T_info_ack on it.
7135 		 */
7136 		return (TS_WACK_CRES);
7137 	case TCPS_ESTABLISHED:
7138 		return (TS_DATA_XFER);
7139 	case TCPS_CLOSE_WAIT:
7140 		return (TS_WREQ_ORDREL);
7141 	case TCPS_FIN_WAIT_1:
7142 		return (TS_WIND_ORDREL);
7143 	case TCPS_FIN_WAIT_2:
7144 		return (TS_WIND_ORDREL);
7145 
7146 	case TCPS_CLOSING:
7147 	case TCPS_LAST_ACK:
7148 	case TCPS_TIME_WAIT:
7149 	case TCPS_CLOSED:
7150 		/*
7151 		 * Following TS_WACK_DREQ7 is a rendition of "not
7152 		 * yet TS_IDLE" TPI state. There is no best match to any
7153 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7154 		 * choose a value chosen that will map to TLI/XTI level
7155 		 * state of TSTATECHNG (state is process of changing) which
7156 		 * captures what this dummy state represents.
7157 		 */
7158 		return (TS_WACK_DREQ7);
7159 	default:
7160 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7161 		    tcp->tcp_state, tcp_display(tcp, NULL,
7162 		    DISP_PORT_ONLY));
7163 		return (TS_UNBND);
7164 	}
7165 }
7166 
7167 static void
7168 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7169 {
7170 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7171 
7172 	if (tcp->tcp_family == AF_INET6)
7173 		*tia = tcp_g_t_info_ack_v6;
7174 	else
7175 		*tia = tcp_g_t_info_ack;
7176 	tia->CURRENT_state = tcp_tpistate(tcp);
7177 	tia->OPT_size = tcp_max_optsize;
7178 	if (tcp->tcp_mss == 0) {
7179 		/* Not yet set - tcp_open does not set mss */
7180 		if (tcp->tcp_ipversion == IPV4_VERSION)
7181 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7182 		else
7183 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7184 	} else {
7185 		tia->TIDU_size = tcp->tcp_mss;
7186 	}
7187 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7188 }
7189 
7190 static void
7191 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
7192     t_uscalar_t cap_bits1)
7193 {
7194 	tcap->CAP_bits1 = 0;
7195 
7196 	if (cap_bits1 & TC1_INFO) {
7197 		tcp_copy_info(&tcap->INFO_ack, tcp);
7198 		tcap->CAP_bits1 |= TC1_INFO;
7199 	}
7200 
7201 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7202 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7203 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7204 	}
7205 
7206 }
7207 
7208 /*
7209  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7210  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7211  * tcp_g_t_info_ack.  The current state of the stream is copied from
7212  * tcp_state.
7213  */
7214 static void
7215 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7216 {
7217 	t_uscalar_t		cap_bits1;
7218 	struct T_capability_ack	*tcap;
7219 
7220 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7221 		freemsg(mp);
7222 		return;
7223 	}
7224 
7225 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7226 
7227 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7228 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7229 	if (mp == NULL)
7230 		return;
7231 
7232 	tcap = (struct T_capability_ack *)mp->b_rptr;
7233 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
7234 
7235 	putnext(tcp->tcp_rq, mp);
7236 }
7237 
7238 /*
7239  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7240  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7241  * The current state of the stream is copied from tcp_state.
7242  */
7243 static void
7244 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7245 {
7246 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7247 	    T_INFO_ACK);
7248 	if (!mp) {
7249 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7250 		return;
7251 	}
7252 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7253 	putnext(tcp->tcp_rq, mp);
7254 }
7255 
7256 /* Respond to the TPI addr request */
7257 static void
7258 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7259 {
7260 	sin_t	*sin;
7261 	mblk_t	*ackmp;
7262 	struct T_addr_ack *taa;
7263 
7264 	/* Make it large enough for worst case */
7265 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7266 	    2 * sizeof (sin6_t), 1);
7267 	if (ackmp == NULL) {
7268 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7269 		return;
7270 	}
7271 
7272 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7273 		tcp_addr_req_ipv6(tcp, ackmp);
7274 		return;
7275 	}
7276 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7277 
7278 	bzero(taa, sizeof (struct T_addr_ack));
7279 	ackmp->b_wptr = (uchar_t *)&taa[1];
7280 
7281 	taa->PRIM_type = T_ADDR_ACK;
7282 	ackmp->b_datap->db_type = M_PCPROTO;
7283 
7284 	/*
7285 	 * Note: Following code assumes 32 bit alignment of basic
7286 	 * data structures like sin_t and struct T_addr_ack.
7287 	 */
7288 	if (tcp->tcp_state >= TCPS_BOUND) {
7289 		/*
7290 		 * Fill in local address
7291 		 */
7292 		taa->LOCADDR_length = sizeof (sin_t);
7293 		taa->LOCADDR_offset = sizeof (*taa);
7294 
7295 		sin = (sin_t *)&taa[1];
7296 
7297 		/* Fill zeroes and then intialize non-zero fields */
7298 		*sin = sin_null;
7299 
7300 		sin->sin_family = AF_INET;
7301 
7302 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7303 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7304 
7305 		ackmp->b_wptr = (uchar_t *)&sin[1];
7306 
7307 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7308 			/*
7309 			 * Fill in Remote address
7310 			 */
7311 			taa->REMADDR_length = sizeof (sin_t);
7312 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7313 			    taa->LOCADDR_length);
7314 
7315 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7316 			*sin = sin_null;
7317 			sin->sin_family = AF_INET;
7318 			sin->sin_addr.s_addr = tcp->tcp_remote;
7319 			sin->sin_port = tcp->tcp_fport;
7320 
7321 			ackmp->b_wptr = (uchar_t *)&sin[1];
7322 		}
7323 	}
7324 	putnext(tcp->tcp_rq, ackmp);
7325 }
7326 
7327 /* Assumes that tcp_addr_req gets enough space and alignment */
7328 static void
7329 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7330 {
7331 	sin6_t	*sin6;
7332 	struct T_addr_ack *taa;
7333 
7334 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7335 	ASSERT(OK_32PTR(ackmp->b_rptr));
7336 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7337 	    2 * sizeof (sin6_t));
7338 
7339 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7340 
7341 	bzero(taa, sizeof (struct T_addr_ack));
7342 	ackmp->b_wptr = (uchar_t *)&taa[1];
7343 
7344 	taa->PRIM_type = T_ADDR_ACK;
7345 	ackmp->b_datap->db_type = M_PCPROTO;
7346 
7347 	/*
7348 	 * Note: Following code assumes 32 bit alignment of basic
7349 	 * data structures like sin6_t and struct T_addr_ack.
7350 	 */
7351 	if (tcp->tcp_state >= TCPS_BOUND) {
7352 		/*
7353 		 * Fill in local address
7354 		 */
7355 		taa->LOCADDR_length = sizeof (sin6_t);
7356 		taa->LOCADDR_offset = sizeof (*taa);
7357 
7358 		sin6 = (sin6_t *)&taa[1];
7359 		*sin6 = sin6_null;
7360 
7361 		sin6->sin6_family = AF_INET6;
7362 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7363 		sin6->sin6_port = tcp->tcp_lport;
7364 
7365 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7366 
7367 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7368 			/*
7369 			 * Fill in Remote address
7370 			 */
7371 			taa->REMADDR_length = sizeof (sin6_t);
7372 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7373 			    taa->LOCADDR_length);
7374 
7375 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7376 			*sin6 = sin6_null;
7377 			sin6->sin6_family = AF_INET6;
7378 			sin6->sin6_flowinfo =
7379 			    tcp->tcp_ip6h->ip6_vcf &
7380 			    ~IPV6_VERS_AND_FLOW_MASK;
7381 			sin6->sin6_addr = tcp->tcp_remote_v6;
7382 			sin6->sin6_port = tcp->tcp_fport;
7383 
7384 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7385 		}
7386 	}
7387 	putnext(tcp->tcp_rq, ackmp);
7388 }
7389 
7390 /*
7391  * Handle reinitialization of a tcp structure.
7392  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7393  */
7394 static void
7395 tcp_reinit(tcp_t *tcp)
7396 {
7397 	mblk_t	*mp;
7398 	int 	err;
7399 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7400 
7401 	TCP_STAT(tcps, tcp_reinit_calls);
7402 
7403 	/* tcp_reinit should never be called for detached tcp_t's */
7404 	ASSERT(tcp->tcp_listener == NULL);
7405 	ASSERT((tcp->tcp_family == AF_INET &&
7406 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7407 	    (tcp->tcp_family == AF_INET6 &&
7408 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7409 	    tcp->tcp_ipversion == IPV6_VERSION)));
7410 
7411 	/* Cancel outstanding timers */
7412 	tcp_timers_stop(tcp);
7413 
7414 	/*
7415 	 * Reset everything in the state vector, after updating global
7416 	 * MIB data from instance counters.
7417 	 */
7418 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7419 	tcp->tcp_ibsegs = 0;
7420 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7421 	tcp->tcp_obsegs = 0;
7422 
7423 	tcp_close_mpp(&tcp->tcp_xmit_head);
7424 	if (tcp->tcp_snd_zcopy_aware)
7425 		tcp_zcopy_notify(tcp);
7426 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7427 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7428 	mutex_enter(&tcp->tcp_non_sq_lock);
7429 	if (tcp->tcp_flow_stopped &&
7430 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7431 		tcp_clrqfull(tcp);
7432 	}
7433 	mutex_exit(&tcp->tcp_non_sq_lock);
7434 	tcp_close_mpp(&tcp->tcp_reass_head);
7435 	tcp->tcp_reass_tail = NULL;
7436 	if (tcp->tcp_rcv_list != NULL) {
7437 		/* Free b_next chain */
7438 		tcp_close_mpp(&tcp->tcp_rcv_list);
7439 		tcp->tcp_rcv_last_head = NULL;
7440 		tcp->tcp_rcv_last_tail = NULL;
7441 		tcp->tcp_rcv_cnt = 0;
7442 	}
7443 	tcp->tcp_rcv_last_tail = NULL;
7444 
7445 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7446 		freemsg(mp);
7447 		tcp->tcp_urp_mp = NULL;
7448 	}
7449 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7450 		freemsg(mp);
7451 		tcp->tcp_urp_mark_mp = NULL;
7452 	}
7453 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7454 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7455 		freeb(tcp->tcp_fused_sigurg_mp);
7456 		tcp->tcp_fused_sigurg_mp = NULL;
7457 	}
7458 	if (tcp->tcp_ordrel_mp != NULL) {
7459 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7460 		freeb(tcp->tcp_ordrel_mp);
7461 		tcp->tcp_ordrel_mp = NULL;
7462 	}
7463 
7464 	/*
7465 	 * Following is a union with two members which are
7466 	 * identical types and size so the following cleanup
7467 	 * is enough.
7468 	 */
7469 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7470 
7471 	CL_INET_DISCONNECT(tcp->tcp_connp, tcp);
7472 
7473 	/*
7474 	 * The connection can't be on the tcp_time_wait_head list
7475 	 * since it is not detached.
7476 	 */
7477 	ASSERT(tcp->tcp_time_wait_next == NULL);
7478 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7479 	ASSERT(tcp->tcp_time_wait_expire == 0);
7480 
7481 	if (tcp->tcp_kssl_pending) {
7482 		tcp->tcp_kssl_pending = B_FALSE;
7483 
7484 		/* Don't reset if the initialized by bind. */
7485 		if (tcp->tcp_kssl_ent != NULL) {
7486 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7487 			    KSSL_NO_PROXY);
7488 		}
7489 	}
7490 	if (tcp->tcp_kssl_ctx != NULL) {
7491 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7492 		tcp->tcp_kssl_ctx = NULL;
7493 	}
7494 
7495 	/*
7496 	 * Reset/preserve other values
7497 	 */
7498 	tcp_reinit_values(tcp);
7499 	ipcl_hash_remove(tcp->tcp_connp);
7500 	conn_delete_ire(tcp->tcp_connp, NULL);
7501 	tcp_ipsec_cleanup(tcp);
7502 
7503 	if (tcp->tcp_conn_req_max != 0) {
7504 		/*
7505 		 * This is the case when a TLI program uses the same
7506 		 * transport end point to accept a connection.  This
7507 		 * makes the TCP both a listener and acceptor.  When
7508 		 * this connection is closed, we need to set the state
7509 		 * back to TCPS_LISTEN.  Make sure that the eager list
7510 		 * is reinitialized.
7511 		 *
7512 		 * Note that this stream is still bound to the four
7513 		 * tuples of the previous connection in IP.  If a new
7514 		 * SYN with different foreign address comes in, IP will
7515 		 * not find it and will send it to the global queue.  In
7516 		 * the global queue, TCP will do a tcp_lookup_listener()
7517 		 * to find this stream.  This works because this stream
7518 		 * is only removed from connected hash.
7519 		 *
7520 		 */
7521 		tcp->tcp_state = TCPS_LISTEN;
7522 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7523 		tcp->tcp_eager_next_drop_q0 = tcp;
7524 		tcp->tcp_eager_prev_drop_q0 = tcp;
7525 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7526 		if (tcp->tcp_family == AF_INET6) {
7527 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7528 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7529 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7530 		} else {
7531 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7532 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7533 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7534 		}
7535 	} else {
7536 		tcp->tcp_state = TCPS_BOUND;
7537 	}
7538 
7539 	/*
7540 	 * Initialize to default values
7541 	 * Can't fail since enough header template space already allocated
7542 	 * at open().
7543 	 */
7544 	err = tcp_init_values(tcp);
7545 	ASSERT(err == 0);
7546 	/* Restore state in tcp_tcph */
7547 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7548 	if (tcp->tcp_ipversion == IPV4_VERSION)
7549 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7550 	else
7551 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7552 	/*
7553 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7554 	 * since the lookup funcs can only lookup on tcp_t
7555 	 */
7556 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7557 
7558 	ASSERT(tcp->tcp_ptpbhn != NULL);
7559 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
7560 		tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7561 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
7562 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
7563 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7564 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7565 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7566 }
7567 
7568 /*
7569  * Force values to zero that need be zero.
7570  * Do not touch values asociated with the BOUND or LISTEN state
7571  * since the connection will end up in that state after the reinit.
7572  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7573  * structure!
7574  */
7575 static void
7576 tcp_reinit_values(tcp)
7577 	tcp_t *tcp;
7578 {
7579 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7580 
7581 #ifndef	lint
7582 #define	DONTCARE(x)
7583 #define	PRESERVE(x)
7584 #else
7585 #define	DONTCARE(x)	((x) = (x))
7586 #define	PRESERVE(x)	((x) = (x))
7587 #endif	/* lint */
7588 
7589 	PRESERVE(tcp->tcp_bind_hash_port);
7590 	PRESERVE(tcp->tcp_bind_hash);
7591 	PRESERVE(tcp->tcp_ptpbhn);
7592 	PRESERVE(tcp->tcp_acceptor_hash);
7593 	PRESERVE(tcp->tcp_ptpahn);
7594 
7595 	/* Should be ASSERT NULL on these with new code! */
7596 	ASSERT(tcp->tcp_time_wait_next == NULL);
7597 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7598 	ASSERT(tcp->tcp_time_wait_expire == 0);
7599 	PRESERVE(tcp->tcp_state);
7600 	PRESERVE(tcp->tcp_rq);
7601 	PRESERVE(tcp->tcp_wq);
7602 
7603 	ASSERT(tcp->tcp_xmit_head == NULL);
7604 	ASSERT(tcp->tcp_xmit_last == NULL);
7605 	ASSERT(tcp->tcp_unsent == 0);
7606 	ASSERT(tcp->tcp_xmit_tail == NULL);
7607 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7608 
7609 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7610 	tcp->tcp_suna = 0;			/* Displayed in mib */
7611 	tcp->tcp_swnd = 0;
7612 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7613 
7614 	ASSERT(tcp->tcp_ibsegs == 0);
7615 	ASSERT(tcp->tcp_obsegs == 0);
7616 
7617 	if (tcp->tcp_iphc != NULL) {
7618 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7619 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7620 	}
7621 
7622 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7623 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7624 	DONTCARE(tcp->tcp_ipha);
7625 	DONTCARE(tcp->tcp_ip6h);
7626 	DONTCARE(tcp->tcp_ip_hdr_len);
7627 	DONTCARE(tcp->tcp_tcph);
7628 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7629 	tcp->tcp_valid_bits = 0;
7630 
7631 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7632 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7633 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7634 	tcp->tcp_last_rcv_lbolt = 0;
7635 
7636 	tcp->tcp_init_cwnd = 0;
7637 
7638 	tcp->tcp_urp_last_valid = 0;
7639 	tcp->tcp_hard_binding = 0;
7640 	tcp->tcp_hard_bound = 0;
7641 	PRESERVE(tcp->tcp_cred);
7642 	PRESERVE(tcp->tcp_cpid);
7643 	PRESERVE(tcp->tcp_open_time);
7644 	PRESERVE(tcp->tcp_exclbind);
7645 
7646 	tcp->tcp_fin_acked = 0;
7647 	tcp->tcp_fin_rcvd = 0;
7648 	tcp->tcp_fin_sent = 0;
7649 	tcp->tcp_ordrel_done = 0;
7650 
7651 	tcp->tcp_debug = 0;
7652 	tcp->tcp_dontroute = 0;
7653 	tcp->tcp_broadcast = 0;
7654 
7655 	tcp->tcp_useloopback = 0;
7656 	tcp->tcp_reuseaddr = 0;
7657 	tcp->tcp_oobinline = 0;
7658 	tcp->tcp_dgram_errind = 0;
7659 
7660 	tcp->tcp_detached = 0;
7661 	tcp->tcp_bind_pending = 0;
7662 	tcp->tcp_unbind_pending = 0;
7663 
7664 	tcp->tcp_snd_ws_ok = B_FALSE;
7665 	tcp->tcp_snd_ts_ok = B_FALSE;
7666 	tcp->tcp_linger = 0;
7667 	tcp->tcp_ka_enabled = 0;
7668 	tcp->tcp_zero_win_probe = 0;
7669 
7670 	tcp->tcp_loopback = 0;
7671 	tcp->tcp_refuse = 0;
7672 	tcp->tcp_localnet = 0;
7673 	tcp->tcp_syn_defense = 0;
7674 	tcp->tcp_set_timer = 0;
7675 
7676 	tcp->tcp_active_open = 0;
7677 	tcp->tcp_rexmit = B_FALSE;
7678 	tcp->tcp_xmit_zc_clean = B_FALSE;
7679 
7680 	tcp->tcp_snd_sack_ok = B_FALSE;
7681 	PRESERVE(tcp->tcp_recvdstaddr);
7682 	tcp->tcp_hwcksum = B_FALSE;
7683 
7684 	tcp->tcp_ire_ill_check_done = B_FALSE;
7685 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7686 
7687 	tcp->tcp_mdt = B_FALSE;
7688 	tcp->tcp_mdt_hdr_head = 0;
7689 	tcp->tcp_mdt_hdr_tail = 0;
7690 
7691 	tcp->tcp_conn_def_q0 = 0;
7692 	tcp->tcp_ip_forward_progress = B_FALSE;
7693 	tcp->tcp_anon_priv_bind = 0;
7694 	tcp->tcp_ecn_ok = B_FALSE;
7695 
7696 	tcp->tcp_cwr = B_FALSE;
7697 	tcp->tcp_ecn_echo_on = B_FALSE;
7698 
7699 	if (tcp->tcp_sack_info != NULL) {
7700 		if (tcp->tcp_notsack_list != NULL) {
7701 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7702 		}
7703 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7704 		tcp->tcp_sack_info = NULL;
7705 	}
7706 
7707 	tcp->tcp_rcv_ws = 0;
7708 	tcp->tcp_snd_ws = 0;
7709 	tcp->tcp_ts_recent = 0;
7710 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7711 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7712 	tcp->tcp_if_mtu = 0;
7713 
7714 	ASSERT(tcp->tcp_reass_head == NULL);
7715 	ASSERT(tcp->tcp_reass_tail == NULL);
7716 
7717 	tcp->tcp_cwnd_cnt = 0;
7718 
7719 	ASSERT(tcp->tcp_rcv_list == NULL);
7720 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7721 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7722 	ASSERT(tcp->tcp_rcv_cnt == 0);
7723 
7724 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7725 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7726 	tcp->tcp_csuna = 0;
7727 
7728 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7729 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7730 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7731 	tcp->tcp_rtt_update = 0;
7732 
7733 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7734 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7735 
7736 	tcp->tcp_rack = 0;			/* Displayed in mib */
7737 	tcp->tcp_rack_cnt = 0;
7738 	tcp->tcp_rack_cur_max = 0;
7739 	tcp->tcp_rack_abs_max = 0;
7740 
7741 	tcp->tcp_max_swnd = 0;
7742 
7743 	ASSERT(tcp->tcp_listener == NULL);
7744 
7745 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7746 
7747 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7748 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7749 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7750 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7751 
7752 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7753 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7754 	PRESERVE(tcp->tcp_conn_req_max);
7755 	PRESERVE(tcp->tcp_conn_req_seqnum);
7756 
7757 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7758 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7759 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7760 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7761 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7762 
7763 	tcp->tcp_lingertime = 0;
7764 
7765 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7766 	ASSERT(tcp->tcp_urp_mp == NULL);
7767 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7768 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7769 
7770 	ASSERT(tcp->tcp_eager_next_q == NULL);
7771 	ASSERT(tcp->tcp_eager_last_q == NULL);
7772 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7773 	    tcp->tcp_eager_prev_q0 == NULL) ||
7774 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7775 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7776 
7777 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
7778 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
7779 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
7780 
7781 	tcp->tcp_client_errno = 0;
7782 
7783 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7784 
7785 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7786 
7787 	PRESERVE(tcp->tcp_bound_source_v6);
7788 	tcp->tcp_last_sent_len = 0;
7789 	tcp->tcp_dupack_cnt = 0;
7790 
7791 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7792 	PRESERVE(tcp->tcp_lport);
7793 
7794 	PRESERVE(tcp->tcp_acceptor_lockp);
7795 
7796 	ASSERT(tcp->tcp_ordrel_mp == NULL);
7797 	PRESERVE(tcp->tcp_acceptor_id);
7798 	DONTCARE(tcp->tcp_ipsec_overhead);
7799 
7800 	PRESERVE(tcp->tcp_family);
7801 	if (tcp->tcp_family == AF_INET6) {
7802 		tcp->tcp_ipversion = IPV6_VERSION;
7803 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7804 	} else {
7805 		tcp->tcp_ipversion = IPV4_VERSION;
7806 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7807 	}
7808 
7809 	tcp->tcp_bound_if = 0;
7810 	tcp->tcp_ipv6_recvancillary = 0;
7811 	tcp->tcp_recvifindex = 0;
7812 	tcp->tcp_recvhops = 0;
7813 	tcp->tcp_closed = 0;
7814 	tcp->tcp_cleandeathtag = 0;
7815 	if (tcp->tcp_hopopts != NULL) {
7816 		mi_free(tcp->tcp_hopopts);
7817 		tcp->tcp_hopopts = NULL;
7818 		tcp->tcp_hopoptslen = 0;
7819 	}
7820 	ASSERT(tcp->tcp_hopoptslen == 0);
7821 	if (tcp->tcp_dstopts != NULL) {
7822 		mi_free(tcp->tcp_dstopts);
7823 		tcp->tcp_dstopts = NULL;
7824 		tcp->tcp_dstoptslen = 0;
7825 	}
7826 	ASSERT(tcp->tcp_dstoptslen == 0);
7827 	if (tcp->tcp_rtdstopts != NULL) {
7828 		mi_free(tcp->tcp_rtdstopts);
7829 		tcp->tcp_rtdstopts = NULL;
7830 		tcp->tcp_rtdstoptslen = 0;
7831 	}
7832 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7833 	if (tcp->tcp_rthdr != NULL) {
7834 		mi_free(tcp->tcp_rthdr);
7835 		tcp->tcp_rthdr = NULL;
7836 		tcp->tcp_rthdrlen = 0;
7837 	}
7838 	ASSERT(tcp->tcp_rthdrlen == 0);
7839 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7840 
7841 	/* Reset fusion-related fields */
7842 	tcp->tcp_fused = B_FALSE;
7843 	tcp->tcp_unfusable = B_FALSE;
7844 	tcp->tcp_fused_sigurg = B_FALSE;
7845 	tcp->tcp_direct_sockfs = B_FALSE;
7846 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7847 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7848 	tcp->tcp_loopback_peer = NULL;
7849 	tcp->tcp_fuse_rcv_hiwater = 0;
7850 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7851 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7852 
7853 	tcp->tcp_lso = B_FALSE;
7854 
7855 	tcp->tcp_in_ack_unsent = 0;
7856 	tcp->tcp_cork = B_FALSE;
7857 	tcp->tcp_tconnind_started = B_FALSE;
7858 
7859 	PRESERVE(tcp->tcp_squeue_bytes);
7860 
7861 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7862 	ASSERT(!tcp->tcp_kssl_pending);
7863 	PRESERVE(tcp->tcp_kssl_ent);
7864 
7865 	/* Sodirect */
7866 	tcp->tcp_sodirect = NULL;
7867 
7868 	tcp->tcp_closemp_used = B_FALSE;
7869 
7870 	PRESERVE(tcp->tcp_rsrv_mp);
7871 	PRESERVE(tcp->tcp_rsrv_mp_lock);
7872 
7873 #ifdef DEBUG
7874 	DONTCARE(tcp->tcmp_stk[0]);
7875 #endif
7876 
7877 	PRESERVE(tcp->tcp_connid);
7878 
7879 
7880 #undef	DONTCARE
7881 #undef	PRESERVE
7882 }
7883 
7884 /*
7885  * Allocate necessary resources and initialize state vector.
7886  * Guaranteed not to fail so that when an error is returned,
7887  * the caller doesn't need to do any additional cleanup.
7888  */
7889 int
7890 tcp_init(tcp_t *tcp, queue_t *q)
7891 {
7892 	int	err;
7893 
7894 	tcp->tcp_rq = q;
7895 	tcp->tcp_wq = WR(q);
7896 	tcp->tcp_state = TCPS_IDLE;
7897 	if ((err = tcp_init_values(tcp)) != 0)
7898 		tcp_timers_stop(tcp);
7899 	return (err);
7900 }
7901 
7902 static int
7903 tcp_init_values(tcp_t *tcp)
7904 {
7905 	int	err;
7906 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7907 
7908 	ASSERT((tcp->tcp_family == AF_INET &&
7909 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7910 	    (tcp->tcp_family == AF_INET6 &&
7911 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7912 	    tcp->tcp_ipversion == IPV6_VERSION)));
7913 
7914 	/*
7915 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7916 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7917 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7918 	 * during first few transmissions of a connection as seen in slow
7919 	 * links.
7920 	 */
7921 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
7922 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
7923 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7924 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7925 	    tcps->tcps_conn_grace_period;
7926 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
7927 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
7928 	tcp->tcp_timer_backoff = 0;
7929 	tcp->tcp_ms_we_have_waited = 0;
7930 	tcp->tcp_last_recv_time = lbolt;
7931 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
7932 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7933 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7934 
7935 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
7936 
7937 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
7938 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
7939 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
7940 	/*
7941 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7942 	 * passive open.
7943 	 */
7944 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
7945 
7946 	tcp->tcp_naglim = tcps->tcps_naglim_def;
7947 
7948 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7949 
7950 	tcp->tcp_mdt_hdr_head = 0;
7951 	tcp->tcp_mdt_hdr_tail = 0;
7952 
7953 	/* Reset fusion-related fields */
7954 	tcp->tcp_fused = B_FALSE;
7955 	tcp->tcp_unfusable = B_FALSE;
7956 	tcp->tcp_fused_sigurg = B_FALSE;
7957 	tcp->tcp_direct_sockfs = B_FALSE;
7958 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7959 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7960 	tcp->tcp_loopback_peer = NULL;
7961 	tcp->tcp_fuse_rcv_hiwater = 0;
7962 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7963 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7964 
7965 	/* Sodirect */
7966 	tcp->tcp_sodirect = NULL;
7967 
7968 	/* Initialize the header template */
7969 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7970 		err = tcp_header_init_ipv4(tcp);
7971 	} else {
7972 		err = tcp_header_init_ipv6(tcp);
7973 	}
7974 	if (err)
7975 		return (err);
7976 
7977 	/*
7978 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7979 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7980 	 */
7981 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7982 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
7983 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
7984 
7985 	tcp->tcp_cork = B_FALSE;
7986 	/*
7987 	 * Init the tcp_debug option.  This value determines whether TCP
7988 	 * calls strlog() to print out debug messages.  Doing this
7989 	 * initialization here means that this value is not inherited thru
7990 	 * tcp_reinit().
7991 	 */
7992 	tcp->tcp_debug = tcps->tcps_dbg;
7993 
7994 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
7995 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
7996 
7997 	return (0);
7998 }
7999 
8000 /*
8001  * Initialize the IPv4 header. Loses any record of any IP options.
8002  */
8003 static int
8004 tcp_header_init_ipv4(tcp_t *tcp)
8005 {
8006 	tcph_t		*tcph;
8007 	uint32_t	sum;
8008 	conn_t		*connp;
8009 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8010 
8011 	/*
8012 	 * This is a simple initialization. If there's
8013 	 * already a template, it should never be too small,
8014 	 * so reuse it.  Otherwise, allocate space for the new one.
8015 	 */
8016 	if (tcp->tcp_iphc == NULL) {
8017 		ASSERT(tcp->tcp_iphc_len == 0);
8018 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8019 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8020 		if (tcp->tcp_iphc == NULL) {
8021 			tcp->tcp_iphc_len = 0;
8022 			return (ENOMEM);
8023 		}
8024 	}
8025 
8026 	/* options are gone; may need a new label */
8027 	connp = tcp->tcp_connp;
8028 	connp->conn_mlp_type = mlptSingle;
8029 	connp->conn_ulp_labeled = !is_system_labeled();
8030 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8031 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8032 	tcp->tcp_ip6h = NULL;
8033 	tcp->tcp_ipversion = IPV4_VERSION;
8034 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8035 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8036 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8037 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8038 	tcp->tcp_ipha->ipha_version_and_hdr_length
8039 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8040 	tcp->tcp_ipha->ipha_ident = 0;
8041 
8042 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8043 	tcp->tcp_tos = 0;
8044 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8045 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8046 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8047 
8048 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8049 	tcp->tcp_tcph = tcph;
8050 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8051 	/*
8052 	 * IP wants our header length in the checksum field to
8053 	 * allow it to perform a single pseudo-header+checksum
8054 	 * calculation on behalf of TCP.
8055 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8056 	 */
8057 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8058 	sum = (sum >> 16) + (sum & 0xFFFF);
8059 	U16_TO_ABE16(sum, tcph->th_sum);
8060 	return (0);
8061 }
8062 
8063 /*
8064  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8065  */
8066 static int
8067 tcp_header_init_ipv6(tcp_t *tcp)
8068 {
8069 	tcph_t	*tcph;
8070 	uint32_t	sum;
8071 	conn_t	*connp;
8072 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8073 
8074 	/*
8075 	 * This is a simple initialization. If there's
8076 	 * already a template, it should never be too small,
8077 	 * so reuse it. Otherwise, allocate space for the new one.
8078 	 * Ensure that there is enough space to "downgrade" the tcp_t
8079 	 * to an IPv4 tcp_t. This requires having space for a full load
8080 	 * of IPv4 options, as well as a full load of TCP options
8081 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8082 	 * than a v6 header and a TCP header with a full load of TCP options
8083 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8084 	 * We want to avoid reallocation in the "downgraded" case when
8085 	 * processing outbound IPv4 options.
8086 	 */
8087 	if (tcp->tcp_iphc == NULL) {
8088 		ASSERT(tcp->tcp_iphc_len == 0);
8089 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8090 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8091 		if (tcp->tcp_iphc == NULL) {
8092 			tcp->tcp_iphc_len = 0;
8093 			return (ENOMEM);
8094 		}
8095 	}
8096 
8097 	/* options are gone; may need a new label */
8098 	connp = tcp->tcp_connp;
8099 	connp->conn_mlp_type = mlptSingle;
8100 	connp->conn_ulp_labeled = !is_system_labeled();
8101 
8102 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8103 	tcp->tcp_ipversion = IPV6_VERSION;
8104 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8105 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8106 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8107 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8108 	tcp->tcp_ipha = NULL;
8109 
8110 	/* Initialize the header template */
8111 
8112 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8113 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8114 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8115 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8116 
8117 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8118 	tcp->tcp_tcph = tcph;
8119 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8120 	/*
8121 	 * IP wants our header length in the checksum field to
8122 	 * allow it to perform a single psuedo-header+checksum
8123 	 * calculation on behalf of TCP.
8124 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8125 	 */
8126 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8127 	sum = (sum >> 16) + (sum & 0xFFFF);
8128 	U16_TO_ABE16(sum, tcph->th_sum);
8129 	return (0);
8130 }
8131 
8132 /* At minimum we need 8 bytes in the TCP header for the lookup */
8133 #define	ICMP_MIN_TCP_HDR	8
8134 
8135 /*
8136  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8137  * passed up by IP. The message is always received on the correct tcp_t.
8138  * Assumes that IP has pulled up everything up to and including the ICMP header.
8139  */
8140 void
8141 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8142 {
8143 	icmph_t *icmph;
8144 	ipha_t	*ipha;
8145 	int	iph_hdr_length;
8146 	tcph_t	*tcph;
8147 	boolean_t ipsec_mctl = B_FALSE;
8148 	boolean_t secure;
8149 	mblk_t *first_mp = mp;
8150 	int32_t new_mss;
8151 	uint32_t ratio;
8152 	size_t mp_size = MBLKL(mp);
8153 	uint32_t seg_seq;
8154 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8155 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8156 
8157 	/* Assume IP provides aligned packets - otherwise toss */
8158 	if (!OK_32PTR(mp->b_rptr)) {
8159 		freemsg(mp);
8160 		return;
8161 	}
8162 
8163 	/*
8164 	 * Since ICMP errors are normal data marked with M_CTL when sent
8165 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8166 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8167 	 */
8168 	if ((mp_size == sizeof (ipsec_info_t)) &&
8169 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8170 		ASSERT(mp->b_cont != NULL);
8171 		mp = mp->b_cont;
8172 		/* IP should have done this */
8173 		ASSERT(OK_32PTR(mp->b_rptr));
8174 		mp_size = MBLKL(mp);
8175 		ipsec_mctl = B_TRUE;
8176 	}
8177 
8178 	/*
8179 	 * Verify that we have a complete outer IP header. If not, drop it.
8180 	 */
8181 	if (mp_size < sizeof (ipha_t)) {
8182 noticmpv4:
8183 		freemsg(first_mp);
8184 		return;
8185 	}
8186 
8187 	ipha = (ipha_t *)mp->b_rptr;
8188 	/*
8189 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8190 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8191 	 */
8192 	switch (IPH_HDR_VERSION(ipha)) {
8193 	case IPV6_VERSION:
8194 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8195 		return;
8196 	case IPV4_VERSION:
8197 		break;
8198 	default:
8199 		goto noticmpv4;
8200 	}
8201 
8202 	/* Skip past the outer IP and ICMP headers */
8203 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8204 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8205 	/*
8206 	 * If we don't have the correct outer IP header length or if the ULP
8207 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8208 	 * send it upstream.
8209 	 */
8210 	if (iph_hdr_length < sizeof (ipha_t) ||
8211 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8212 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8213 		goto noticmpv4;
8214 	}
8215 	ipha = (ipha_t *)&icmph[1];
8216 
8217 	/* Skip past the inner IP and find the ULP header */
8218 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8219 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8220 	/*
8221 	 * If we don't have the correct inner IP header length or if the ULP
8222 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8223 	 * bytes of TCP header, drop it.
8224 	 */
8225 	if (iph_hdr_length < sizeof (ipha_t) ||
8226 	    ipha->ipha_protocol != IPPROTO_TCP ||
8227 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8228 		goto noticmpv4;
8229 	}
8230 
8231 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8232 		if (ipsec_mctl) {
8233 			secure = ipsec_in_is_secure(first_mp);
8234 		} else {
8235 			secure = B_FALSE;
8236 		}
8237 		if (secure) {
8238 			/*
8239 			 * If we are willing to accept this in clear
8240 			 * we don't have to verify policy.
8241 			 */
8242 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8243 				if (!tcp_check_policy(tcp, first_mp,
8244 				    ipha, NULL, secure, ipsec_mctl)) {
8245 					/*
8246 					 * tcp_check_policy called
8247 					 * ip_drop_packet() on failure.
8248 					 */
8249 					return;
8250 				}
8251 			}
8252 		}
8253 	} else if (ipsec_mctl) {
8254 		/*
8255 		 * This is a hard_bound connection. IP has already
8256 		 * verified policy. We don't have to do it again.
8257 		 */
8258 		freeb(first_mp);
8259 		first_mp = mp;
8260 		ipsec_mctl = B_FALSE;
8261 	}
8262 
8263 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8264 	/*
8265 	 * TCP SHOULD check that the TCP sequence number contained in
8266 	 * payload of the ICMP error message is within the range
8267 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8268 	 */
8269 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8270 		/*
8271 		 * The ICMP message is bogus, just drop it.  But if this is
8272 		 * an ICMP too big message, IP has already changed
8273 		 * the ire_max_frag to the bogus value.  We need to change
8274 		 * it back.
8275 		 */
8276 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8277 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8278 			conn_t *connp = tcp->tcp_connp;
8279 			ire_t *ire;
8280 			int flag;
8281 
8282 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8283 				flag = tcp->tcp_ipha->
8284 				    ipha_fragment_offset_and_flags;
8285 			} else {
8286 				flag = 0;
8287 			}
8288 			mutex_enter(&connp->conn_lock);
8289 			if ((ire = connp->conn_ire_cache) != NULL) {
8290 				mutex_enter(&ire->ire_lock);
8291 				mutex_exit(&connp->conn_lock);
8292 				ire->ire_max_frag = tcp->tcp_if_mtu;
8293 				ire->ire_frag_flag |= flag;
8294 				mutex_exit(&ire->ire_lock);
8295 			} else {
8296 				mutex_exit(&connp->conn_lock);
8297 			}
8298 		}
8299 		goto noticmpv4;
8300 	}
8301 
8302 	switch (icmph->icmph_type) {
8303 	case ICMP_DEST_UNREACHABLE:
8304 		switch (icmph->icmph_code) {
8305 		case ICMP_FRAGMENTATION_NEEDED:
8306 			/*
8307 			 * Reduce the MSS based on the new MTU.  This will
8308 			 * eliminate any fragmentation locally.
8309 			 * N.B.  There may well be some funny side-effects on
8310 			 * the local send policy and the remote receive policy.
8311 			 * Pending further research, we provide
8312 			 * tcp_ignore_path_mtu just in case this proves
8313 			 * disastrous somewhere.
8314 			 *
8315 			 * After updating the MSS, retransmit part of the
8316 			 * dropped segment using the new mss by calling
8317 			 * tcp_wput_data().  Need to adjust all those
8318 			 * params to make sure tcp_wput_data() work properly.
8319 			 */
8320 			if (tcps->tcps_ignore_path_mtu ||
8321 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8322 				break;
8323 
8324 			/*
8325 			 * Decrease the MSS by time stamp options
8326 			 * IP options and IPSEC options. tcp_hdr_len
8327 			 * includes time stamp option and IP option
8328 			 * length.  Note that new_mss may be negative
8329 			 * if tcp_ipsec_overhead is large and the
8330 			 * icmph_du_mtu is the minimum value, which is 68.
8331 			 */
8332 			new_mss = ntohs(icmph->icmph_du_mtu) -
8333 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8334 
8335 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8336 			    new_mss);
8337 
8338 			/*
8339 			 * Only update the MSS if the new one is
8340 			 * smaller than the previous one.  This is
8341 			 * to avoid problems when getting multiple
8342 			 * ICMP errors for the same MTU.
8343 			 */
8344 			if (new_mss >= tcp->tcp_mss)
8345 				break;
8346 
8347 			/*
8348 			 * Note that we are using the template header's DF
8349 			 * bit in the fast path sending.  So we need to compare
8350 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8351 			 * And stop doing IPv4 PMTUd if new_mss is less than
8352 			 * MAX(tcps_mss_min, ip_pmtu_min).
8353 			 */
8354 			if (new_mss < tcps->tcps_mss_min ||
8355 			    new_mss < ipst->ips_ip_pmtu_min) {
8356 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8357 				    0;
8358 			}
8359 
8360 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8361 			ASSERT(ratio >= 1);
8362 			tcp_mss_set(tcp, new_mss, B_TRUE);
8363 
8364 			/*
8365 			 * Make sure we have something to
8366 			 * send.
8367 			 */
8368 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8369 			    (tcp->tcp_xmit_head != NULL)) {
8370 				/*
8371 				 * Shrink tcp_cwnd in
8372 				 * proportion to the old MSS/new MSS.
8373 				 */
8374 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8375 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8376 				    (tcp->tcp_unsent == 0)) {
8377 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8378 				} else {
8379 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8380 				}
8381 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8382 				tcp->tcp_rexmit = B_TRUE;
8383 				tcp->tcp_dupack_cnt = 0;
8384 				tcp->tcp_snd_burst = TCP_CWND_SS;
8385 				tcp_ss_rexmit(tcp);
8386 			}
8387 			break;
8388 		case ICMP_PORT_UNREACHABLE:
8389 		case ICMP_PROTOCOL_UNREACHABLE:
8390 			switch (tcp->tcp_state) {
8391 			case TCPS_SYN_SENT:
8392 			case TCPS_SYN_RCVD:
8393 				/*
8394 				 * ICMP can snipe away incipient
8395 				 * TCP connections as long as
8396 				 * seq number is same as initial
8397 				 * send seq number.
8398 				 */
8399 				if (seg_seq == tcp->tcp_iss) {
8400 					(void) tcp_clean_death(tcp,
8401 					    ECONNREFUSED, 6);
8402 				}
8403 				break;
8404 			}
8405 			break;
8406 		case ICMP_HOST_UNREACHABLE:
8407 		case ICMP_NET_UNREACHABLE:
8408 			/* Record the error in case we finally time out. */
8409 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8410 				tcp->tcp_client_errno = EHOSTUNREACH;
8411 			else
8412 				tcp->tcp_client_errno = ENETUNREACH;
8413 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8414 				if (tcp->tcp_listener != NULL &&
8415 				    tcp->tcp_listener->tcp_syn_defense) {
8416 					/*
8417 					 * Ditch the half-open connection if we
8418 					 * suspect a SYN attack is under way.
8419 					 */
8420 					tcp_ip_ire_mark_advice(tcp);
8421 					(void) tcp_clean_death(tcp,
8422 					    tcp->tcp_client_errno, 7);
8423 				}
8424 			}
8425 			break;
8426 		default:
8427 			break;
8428 		}
8429 		break;
8430 	case ICMP_SOURCE_QUENCH: {
8431 		/*
8432 		 * use a global boolean to control
8433 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8434 		 * The default is false.
8435 		 */
8436 		if (tcp_icmp_source_quench) {
8437 			/*
8438 			 * Reduce the sending rate as if we got a
8439 			 * retransmit timeout
8440 			 */
8441 			uint32_t npkt;
8442 
8443 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8444 			    tcp->tcp_mss;
8445 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8446 			tcp->tcp_cwnd = tcp->tcp_mss;
8447 			tcp->tcp_cwnd_cnt = 0;
8448 		}
8449 		break;
8450 	}
8451 	}
8452 	freemsg(first_mp);
8453 }
8454 
8455 /*
8456  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8457  * error messages passed up by IP.
8458  * Assumes that IP has pulled up all the extension headers as well
8459  * as the ICMPv6 header.
8460  */
8461 static void
8462 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8463 {
8464 	icmp6_t *icmp6;
8465 	ip6_t	*ip6h;
8466 	uint16_t	iph_hdr_length;
8467 	tcpha_t	*tcpha;
8468 	uint8_t	*nexthdrp;
8469 	uint32_t new_mss;
8470 	uint32_t ratio;
8471 	boolean_t secure;
8472 	mblk_t *first_mp = mp;
8473 	size_t mp_size;
8474 	uint32_t seg_seq;
8475 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8476 
8477 	/*
8478 	 * The caller has determined if this is an IPSEC_IN packet and
8479 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8480 	 */
8481 	if (ipsec_mctl)
8482 		mp = mp->b_cont;
8483 
8484 	mp_size = MBLKL(mp);
8485 
8486 	/*
8487 	 * Verify that we have a complete IP header. If not, send it upstream.
8488 	 */
8489 	if (mp_size < sizeof (ip6_t)) {
8490 noticmpv6:
8491 		freemsg(first_mp);
8492 		return;
8493 	}
8494 
8495 	/*
8496 	 * Verify this is an ICMPV6 packet, else send it upstream.
8497 	 */
8498 	ip6h = (ip6_t *)mp->b_rptr;
8499 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8500 		iph_hdr_length = IPV6_HDR_LEN;
8501 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8502 	    &nexthdrp) ||
8503 	    *nexthdrp != IPPROTO_ICMPV6) {
8504 		goto noticmpv6;
8505 	}
8506 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8507 	ip6h = (ip6_t *)&icmp6[1];
8508 	/*
8509 	 * Verify if we have a complete ICMP and inner IP header.
8510 	 */
8511 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8512 		goto noticmpv6;
8513 
8514 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8515 		goto noticmpv6;
8516 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8517 	/*
8518 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8519 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8520 	 * packet.
8521 	 */
8522 	if ((*nexthdrp != IPPROTO_TCP) ||
8523 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8524 		goto noticmpv6;
8525 	}
8526 
8527 	/*
8528 	 * ICMP errors come on the right queue or come on
8529 	 * listener/global queue for detached connections and
8530 	 * get switched to the right queue. If it comes on the
8531 	 * right queue, policy check has already been done by IP
8532 	 * and thus free the first_mp without verifying the policy.
8533 	 * If it has come for a non-hard bound connection, we need
8534 	 * to verify policy as IP may not have done it.
8535 	 */
8536 	if (!tcp->tcp_hard_bound) {
8537 		if (ipsec_mctl) {
8538 			secure = ipsec_in_is_secure(first_mp);
8539 		} else {
8540 			secure = B_FALSE;
8541 		}
8542 		if (secure) {
8543 			/*
8544 			 * If we are willing to accept this in clear
8545 			 * we don't have to verify policy.
8546 			 */
8547 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8548 				if (!tcp_check_policy(tcp, first_mp,
8549 				    NULL, ip6h, secure, ipsec_mctl)) {
8550 					/*
8551 					 * tcp_check_policy called
8552 					 * ip_drop_packet() on failure.
8553 					 */
8554 					return;
8555 				}
8556 			}
8557 		}
8558 	} else if (ipsec_mctl) {
8559 		/*
8560 		 * This is a hard_bound connection. IP has already
8561 		 * verified policy. We don't have to do it again.
8562 		 */
8563 		freeb(first_mp);
8564 		first_mp = mp;
8565 		ipsec_mctl = B_FALSE;
8566 	}
8567 
8568 	seg_seq = ntohl(tcpha->tha_seq);
8569 	/*
8570 	 * TCP SHOULD check that the TCP sequence number contained in
8571 	 * payload of the ICMP error message is within the range
8572 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8573 	 */
8574 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8575 		/*
8576 		 * If the ICMP message is bogus, should we kill the
8577 		 * connection, or should we just drop the bogus ICMP
8578 		 * message? It would probably make more sense to just
8579 		 * drop the message so that if this one managed to get
8580 		 * in, the real connection should not suffer.
8581 		 */
8582 		goto noticmpv6;
8583 	}
8584 
8585 	switch (icmp6->icmp6_type) {
8586 	case ICMP6_PACKET_TOO_BIG:
8587 		/*
8588 		 * Reduce the MSS based on the new MTU.  This will
8589 		 * eliminate any fragmentation locally.
8590 		 * N.B.  There may well be some funny side-effects on
8591 		 * the local send policy and the remote receive policy.
8592 		 * Pending further research, we provide
8593 		 * tcp_ignore_path_mtu just in case this proves
8594 		 * disastrous somewhere.
8595 		 *
8596 		 * After updating the MSS, retransmit part of the
8597 		 * dropped segment using the new mss by calling
8598 		 * tcp_wput_data().  Need to adjust all those
8599 		 * params to make sure tcp_wput_data() work properly.
8600 		 */
8601 		if (tcps->tcps_ignore_path_mtu)
8602 			break;
8603 
8604 		/*
8605 		 * Decrease the MSS by time stamp options
8606 		 * IP options and IPSEC options. tcp_hdr_len
8607 		 * includes time stamp option and IP option
8608 		 * length.
8609 		 */
8610 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8611 		    tcp->tcp_ipsec_overhead;
8612 
8613 		/*
8614 		 * Only update the MSS if the new one is
8615 		 * smaller than the previous one.  This is
8616 		 * to avoid problems when getting multiple
8617 		 * ICMP errors for the same MTU.
8618 		 */
8619 		if (new_mss >= tcp->tcp_mss)
8620 			break;
8621 
8622 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8623 		ASSERT(ratio >= 1);
8624 		tcp_mss_set(tcp, new_mss, B_TRUE);
8625 
8626 		/*
8627 		 * Make sure we have something to
8628 		 * send.
8629 		 */
8630 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8631 		    (tcp->tcp_xmit_head != NULL)) {
8632 			/*
8633 			 * Shrink tcp_cwnd in
8634 			 * proportion to the old MSS/new MSS.
8635 			 */
8636 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8637 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8638 			    (tcp->tcp_unsent == 0)) {
8639 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8640 			} else {
8641 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8642 			}
8643 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8644 			tcp->tcp_rexmit = B_TRUE;
8645 			tcp->tcp_dupack_cnt = 0;
8646 			tcp->tcp_snd_burst = TCP_CWND_SS;
8647 			tcp_ss_rexmit(tcp);
8648 		}
8649 		break;
8650 
8651 	case ICMP6_DST_UNREACH:
8652 		switch (icmp6->icmp6_code) {
8653 		case ICMP6_DST_UNREACH_NOPORT:
8654 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8655 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8656 			    (seg_seq == tcp->tcp_iss)) {
8657 				(void) tcp_clean_death(tcp,
8658 				    ECONNREFUSED, 8);
8659 			}
8660 			break;
8661 
8662 		case ICMP6_DST_UNREACH_ADMIN:
8663 		case ICMP6_DST_UNREACH_NOROUTE:
8664 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8665 		case ICMP6_DST_UNREACH_ADDR:
8666 			/* Record the error in case we finally time out. */
8667 			tcp->tcp_client_errno = EHOSTUNREACH;
8668 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8669 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8670 			    (seg_seq == tcp->tcp_iss)) {
8671 				if (tcp->tcp_listener != NULL &&
8672 				    tcp->tcp_listener->tcp_syn_defense) {
8673 					/*
8674 					 * Ditch the half-open connection if we
8675 					 * suspect a SYN attack is under way.
8676 					 */
8677 					tcp_ip_ire_mark_advice(tcp);
8678 					(void) tcp_clean_death(tcp,
8679 					    tcp->tcp_client_errno, 9);
8680 				}
8681 			}
8682 
8683 
8684 			break;
8685 		default:
8686 			break;
8687 		}
8688 		break;
8689 
8690 	case ICMP6_PARAM_PROB:
8691 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8692 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8693 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8694 		    (uchar_t *)nexthdrp) {
8695 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8696 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8697 				(void) tcp_clean_death(tcp,
8698 				    ECONNREFUSED, 10);
8699 			}
8700 			break;
8701 		}
8702 		break;
8703 
8704 	case ICMP6_TIME_EXCEEDED:
8705 	default:
8706 		break;
8707 	}
8708 	freemsg(first_mp);
8709 }
8710 
8711 /*
8712  * Notify IP that we are having trouble with this connection.  IP should
8713  * blow the IRE away and start over.
8714  */
8715 static void
8716 tcp_ip_notify(tcp_t *tcp)
8717 {
8718 	struct iocblk	*iocp;
8719 	ipid_t	*ipid;
8720 	mblk_t	*mp;
8721 
8722 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8723 	if (tcp->tcp_ipversion == IPV6_VERSION)
8724 		return;
8725 
8726 	mp = mkiocb(IP_IOCTL);
8727 	if (mp == NULL)
8728 		return;
8729 
8730 	iocp = (struct iocblk *)mp->b_rptr;
8731 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8732 
8733 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8734 	if (!mp->b_cont) {
8735 		freeb(mp);
8736 		return;
8737 	}
8738 
8739 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8740 	mp->b_cont->b_wptr += iocp->ioc_count;
8741 	bzero(ipid, sizeof (*ipid));
8742 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8743 	ipid->ipid_ire_type = IRE_CACHE;
8744 	ipid->ipid_addr_offset = sizeof (ipid_t);
8745 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8746 	/*
8747 	 * Note: in the case of source routing we want to blow away the
8748 	 * route to the first source route hop.
8749 	 */
8750 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8751 	    sizeof (tcp->tcp_ipha->ipha_dst));
8752 
8753 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8754 }
8755 
8756 /* Unlink and return any mblk that looks like it contains an ire */
8757 static mblk_t *
8758 tcp_ire_mp(mblk_t **mpp)
8759 {
8760 	mblk_t 	*mp = *mpp;
8761 	mblk_t	*prev_mp = NULL;
8762 
8763 	for (;;) {
8764 		switch (DB_TYPE(mp)) {
8765 		case IRE_DB_TYPE:
8766 		case IRE_DB_REQ_TYPE:
8767 			if (mp == *mpp) {
8768 				*mpp = mp->b_cont;
8769 			} else {
8770 				prev_mp->b_cont = mp->b_cont;
8771 			}
8772 			mp->b_cont = NULL;
8773 			return (mp);
8774 		default:
8775 			break;
8776 		}
8777 		prev_mp = mp;
8778 		mp = mp->b_cont;
8779 		if (mp == NULL)
8780 			break;
8781 	}
8782 	return (mp);
8783 }
8784 
8785 /*
8786  * Timer callback routine for keepalive probe.  We do a fake resend of
8787  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8788  * check to see if we have heard anything from the other end for the last
8789  * RTO period.  If we have, set the timer to expire for another
8790  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8791  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8792  * the timeout if we have not heard from the other side.  If for more than
8793  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8794  * kill the connection unless the keepalive abort threshold is 0.  In
8795  * that case, we will probe "forever."
8796  */
8797 static void
8798 tcp_keepalive_killer(void *arg)
8799 {
8800 	mblk_t	*mp;
8801 	conn_t	*connp = (conn_t *)arg;
8802 	tcp_t  	*tcp = connp->conn_tcp;
8803 	int32_t	firetime;
8804 	int32_t	idletime;
8805 	int32_t	ka_intrvl;
8806 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8807 
8808 	tcp->tcp_ka_tid = 0;
8809 
8810 	if (tcp->tcp_fused)
8811 		return;
8812 
8813 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
8814 	ka_intrvl = tcp->tcp_ka_interval;
8815 
8816 	/*
8817 	 * Keepalive probe should only be sent if the application has not
8818 	 * done a close on the connection.
8819 	 */
8820 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8821 		return;
8822 	}
8823 	/* Timer fired too early, restart it. */
8824 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8825 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8826 		    MSEC_TO_TICK(ka_intrvl));
8827 		return;
8828 	}
8829 
8830 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8831 	/*
8832 	 * If we have not heard from the other side for a long
8833 	 * time, kill the connection unless the keepalive abort
8834 	 * threshold is 0.  In that case, we will probe "forever."
8835 	 */
8836 	if (tcp->tcp_ka_abort_thres != 0 &&
8837 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8838 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
8839 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8840 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8841 		return;
8842 	}
8843 
8844 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8845 	    idletime >= ka_intrvl) {
8846 		/* Fake resend of last ACKed byte. */
8847 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8848 
8849 		if (mp1 != NULL) {
8850 			*mp1->b_wptr++ = '\0';
8851 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8852 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8853 			freeb(mp1);
8854 			/*
8855 			 * if allocation failed, fall through to start the
8856 			 * timer back.
8857 			 */
8858 			if (mp != NULL) {
8859 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8860 				BUMP_MIB(&tcps->tcps_mib,
8861 				    tcpTimKeepaliveProbe);
8862 				if (tcp->tcp_ka_last_intrvl != 0) {
8863 					int max;
8864 					/*
8865 					 * We should probe again at least
8866 					 * in ka_intrvl, but not more than
8867 					 * tcp_rexmit_interval_max.
8868 					 */
8869 					max = tcps->tcps_rexmit_interval_max;
8870 					firetime = MIN(ka_intrvl - 1,
8871 					    tcp->tcp_ka_last_intrvl << 1);
8872 					if (firetime > max)
8873 						firetime = max;
8874 				} else {
8875 					firetime = tcp->tcp_rto;
8876 				}
8877 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8878 				    tcp_keepalive_killer,
8879 				    MSEC_TO_TICK(firetime));
8880 				tcp->tcp_ka_last_intrvl = firetime;
8881 				return;
8882 			}
8883 		}
8884 	} else {
8885 		tcp->tcp_ka_last_intrvl = 0;
8886 	}
8887 
8888 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8889 	if ((firetime = ka_intrvl - idletime) < 0) {
8890 		firetime = ka_intrvl;
8891 	}
8892 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8893 	    MSEC_TO_TICK(firetime));
8894 }
8895 
8896 int
8897 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8898 {
8899 	queue_t	*q = tcp->tcp_rq;
8900 	int32_t	mss = tcp->tcp_mss;
8901 	int	maxpsz;
8902 	conn_t	*connp = tcp->tcp_connp;
8903 
8904 	if (TCP_IS_DETACHED(tcp))
8905 		return (mss);
8906 	if (tcp->tcp_fused) {
8907 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8908 		mss = INFPSZ;
8909 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
8910 		/*
8911 		 * Set the sd_qn_maxpsz according to the socket send buffer
8912 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8913 		 * instruct the stream head to copyin user data into contiguous
8914 		 * kernel-allocated buffers without breaking it up into smaller
8915 		 * chunks.  We round up the buffer size to the nearest SMSS.
8916 		 */
8917 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8918 		if (tcp->tcp_kssl_ctx == NULL)
8919 			mss = INFPSZ;
8920 		else
8921 			mss = SSL3_MAX_RECORD_LEN;
8922 	} else {
8923 		/*
8924 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8925 		 * (and a multiple of the mss).  This instructs the stream
8926 		 * head to break down larger than SMSS writes into SMSS-
8927 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8928 		 */
8929 		/* XXX tune this with ndd tcp_maxpsz_multiplier */
8930 		maxpsz = tcp->tcp_maxpsz * mss;
8931 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8932 			maxpsz = tcp->tcp_xmit_hiwater/2;
8933 			/* Round up to nearest mss */
8934 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8935 		}
8936 	}
8937 
8938 	(void) proto_set_maxpsz(q, connp, maxpsz);
8939 	if (!(IPCL_IS_NONSTR(connp))) {
8940 		/* XXX do it in set_maxpsz()? */
8941 		tcp->tcp_wq->q_maxpsz = maxpsz;
8942 	}
8943 
8944 	if (set_maxblk)
8945 		(void) proto_set_tx_maxblk(q, connp, mss);
8946 	return (mss);
8947 }
8948 
8949 /*
8950  * Extract option values from a tcp header.  We put any found values into the
8951  * tcpopt struct and return a bitmask saying which options were found.
8952  */
8953 static int
8954 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8955 {
8956 	uchar_t		*endp;
8957 	int		len;
8958 	uint32_t	mss;
8959 	uchar_t		*up = (uchar_t *)tcph;
8960 	int		found = 0;
8961 	int32_t		sack_len;
8962 	tcp_seq		sack_begin, sack_end;
8963 	tcp_t		*tcp;
8964 
8965 	endp = up + TCP_HDR_LENGTH(tcph);
8966 	up += TCP_MIN_HEADER_LENGTH;
8967 	while (up < endp) {
8968 		len = endp - up;
8969 		switch (*up) {
8970 		case TCPOPT_EOL:
8971 			break;
8972 
8973 		case TCPOPT_NOP:
8974 			up++;
8975 			continue;
8976 
8977 		case TCPOPT_MAXSEG:
8978 			if (len < TCPOPT_MAXSEG_LEN ||
8979 			    up[1] != TCPOPT_MAXSEG_LEN)
8980 				break;
8981 
8982 			mss = BE16_TO_U16(up+2);
8983 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
8984 			tcpopt->tcp_opt_mss = mss;
8985 			found |= TCP_OPT_MSS_PRESENT;
8986 
8987 			up += TCPOPT_MAXSEG_LEN;
8988 			continue;
8989 
8990 		case TCPOPT_WSCALE:
8991 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
8992 				break;
8993 
8994 			if (up[2] > TCP_MAX_WINSHIFT)
8995 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
8996 			else
8997 				tcpopt->tcp_opt_wscale = up[2];
8998 			found |= TCP_OPT_WSCALE_PRESENT;
8999 
9000 			up += TCPOPT_WS_LEN;
9001 			continue;
9002 
9003 		case TCPOPT_SACK_PERMITTED:
9004 			if (len < TCPOPT_SACK_OK_LEN ||
9005 			    up[1] != TCPOPT_SACK_OK_LEN)
9006 				break;
9007 			found |= TCP_OPT_SACK_OK_PRESENT;
9008 			up += TCPOPT_SACK_OK_LEN;
9009 			continue;
9010 
9011 		case TCPOPT_SACK:
9012 			if (len <= 2 || up[1] <= 2 || len < up[1])
9013 				break;
9014 
9015 			/* If TCP is not interested in SACK blks... */
9016 			if ((tcp = tcpopt->tcp) == NULL) {
9017 				up += up[1];
9018 				continue;
9019 			}
9020 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9021 			up += TCPOPT_HEADER_LEN;
9022 
9023 			/*
9024 			 * If the list is empty, allocate one and assume
9025 			 * nothing is sack'ed.
9026 			 */
9027 			ASSERT(tcp->tcp_sack_info != NULL);
9028 			if (tcp->tcp_notsack_list == NULL) {
9029 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9030 				    tcp->tcp_suna, tcp->tcp_snxt,
9031 				    &(tcp->tcp_num_notsack_blk),
9032 				    &(tcp->tcp_cnt_notsack_list));
9033 
9034 				/*
9035 				 * Make sure tcp_notsack_list is not NULL.
9036 				 * This happens when kmem_alloc(KM_NOSLEEP)
9037 				 * returns NULL.
9038 				 */
9039 				if (tcp->tcp_notsack_list == NULL) {
9040 					up += sack_len;
9041 					continue;
9042 				}
9043 				tcp->tcp_fack = tcp->tcp_suna;
9044 			}
9045 
9046 			while (sack_len > 0) {
9047 				if (up + 8 > endp) {
9048 					up = endp;
9049 					break;
9050 				}
9051 				sack_begin = BE32_TO_U32(up);
9052 				up += 4;
9053 				sack_end = BE32_TO_U32(up);
9054 				up += 4;
9055 				sack_len -= 8;
9056 				/*
9057 				 * Bounds checking.  Make sure the SACK
9058 				 * info is within tcp_suna and tcp_snxt.
9059 				 * If this SACK blk is out of bound, ignore
9060 				 * it but continue to parse the following
9061 				 * blks.
9062 				 */
9063 				if (SEQ_LEQ(sack_end, sack_begin) ||
9064 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9065 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9066 					continue;
9067 				}
9068 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9069 				    sack_begin, sack_end,
9070 				    &(tcp->tcp_num_notsack_blk),
9071 				    &(tcp->tcp_cnt_notsack_list));
9072 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9073 					tcp->tcp_fack = sack_end;
9074 				}
9075 			}
9076 			found |= TCP_OPT_SACK_PRESENT;
9077 			continue;
9078 
9079 		case TCPOPT_TSTAMP:
9080 			if (len < TCPOPT_TSTAMP_LEN ||
9081 			    up[1] != TCPOPT_TSTAMP_LEN)
9082 				break;
9083 
9084 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9085 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9086 
9087 			found |= TCP_OPT_TSTAMP_PRESENT;
9088 
9089 			up += TCPOPT_TSTAMP_LEN;
9090 			continue;
9091 
9092 		default:
9093 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9094 				break;
9095 			up += up[1];
9096 			continue;
9097 		}
9098 		break;
9099 	}
9100 	return (found);
9101 }
9102 
9103 /*
9104  * Set the mss associated with a particular tcp based on its current value,
9105  * and a new one passed in. Observe minimums and maximums, and reset
9106  * other state variables that we want to view as multiples of mss.
9107  *
9108  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9109  * highwater marks etc. need to be initialized or adjusted.
9110  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9111  *    packet arrives.
9112  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9113  *    ICMP6_PACKET_TOO_BIG arrives.
9114  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9115  *    to increase the MSS to use the extra bytes available.
9116  *
9117  * Callers except tcp_paws_check() ensure that they only reduce mss.
9118  */
9119 static void
9120 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9121 {
9122 	uint32_t	mss_max;
9123 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9124 
9125 	if (tcp->tcp_ipversion == IPV4_VERSION)
9126 		mss_max = tcps->tcps_mss_max_ipv4;
9127 	else
9128 		mss_max = tcps->tcps_mss_max_ipv6;
9129 
9130 	if (mss < tcps->tcps_mss_min)
9131 		mss = tcps->tcps_mss_min;
9132 	if (mss > mss_max)
9133 		mss = mss_max;
9134 	/*
9135 	 * Unless naglim has been set by our client to
9136 	 * a non-mss value, force naglim to track mss.
9137 	 * This can help to aggregate small writes.
9138 	 */
9139 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9140 		tcp->tcp_naglim = mss;
9141 	/*
9142 	 * TCP should be able to buffer at least 4 MSS data for obvious
9143 	 * performance reason.
9144 	 */
9145 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9146 		tcp->tcp_xmit_hiwater = mss << 2;
9147 
9148 	if (do_ss) {
9149 		/*
9150 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9151 		 * changing due to a reduction in MTU, presumably as a
9152 		 * result of a new path component, reset cwnd to its
9153 		 * "initial" value, as a multiple of the new mss.
9154 		 */
9155 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9156 	} else {
9157 		/*
9158 		 * Called by tcp_paws_check(), the mss increased
9159 		 * marginally to allow use of space previously taken
9160 		 * by the timestamp option. It would be inappropriate
9161 		 * to apply slow start or tcp_init_cwnd values to
9162 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9163 		 */
9164 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9165 		tcp->tcp_cwnd_cnt = 0;
9166 	}
9167 	tcp->tcp_mss = mss;
9168 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9169 }
9170 
9171 /* For /dev/tcp aka AF_INET open */
9172 static int
9173 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9174 {
9175 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9176 }
9177 
9178 /* For /dev/tcp6 aka AF_INET6 open */
9179 static int
9180 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9181 {
9182 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9183 }
9184 
9185 static conn_t *
9186 tcp_create_common(queue_t *q, cred_t *credp, boolean_t isv6,
9187     boolean_t issocket, int *errorp)
9188 {
9189 	tcp_t		*tcp = NULL;
9190 	conn_t		*connp;
9191 	int		err;
9192 	zoneid_t	zoneid;
9193 	tcp_stack_t	*tcps;
9194 	squeue_t	*sqp;
9195 
9196 	ASSERT(errorp != NULL);
9197 	/*
9198 	 * Find the proper zoneid and netstack.
9199 	 */
9200 	/*
9201 	 * Special case for install: miniroot needs to be able to
9202 	 * access files via NFS as though it were always in the
9203 	 * global zone.
9204 	 */
9205 	if (credp == kcred && nfs_global_client_only != 0) {
9206 		zoneid = GLOBAL_ZONEID;
9207 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9208 		    netstack_tcp;
9209 		ASSERT(tcps != NULL);
9210 	} else {
9211 		netstack_t *ns;
9212 
9213 		ns = netstack_find_by_cred(credp);
9214 		ASSERT(ns != NULL);
9215 		tcps = ns->netstack_tcp;
9216 		ASSERT(tcps != NULL);
9217 
9218 		/*
9219 		 * For exclusive stacks we set the zoneid to zero
9220 		 * to make TCP operate as if in the global zone.
9221 		 */
9222 		if (tcps->tcps_netstack->netstack_stackid !=
9223 		    GLOBAL_NETSTACKID)
9224 			zoneid = GLOBAL_ZONEID;
9225 		else
9226 			zoneid = crgetzoneid(credp);
9227 	}
9228 	/*
9229 	 * For stackid zero this is done from strplumb.c, but
9230 	 * non-zero stackids are handled here.
9231 	 */
9232 	if (tcps->tcps_g_q == NULL &&
9233 	    tcps->tcps_netstack->netstack_stackid !=
9234 	    GLOBAL_NETSTACKID) {
9235 		tcp_g_q_setup(tcps);
9236 	}
9237 
9238 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
9239 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
9240 	/*
9241 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9242 	 * so we drop it by one.
9243 	 */
9244 	netstack_rele(tcps->tcps_netstack);
9245 	if (connp == NULL) {
9246 		*errorp = ENOSR;
9247 		return (NULL);
9248 	}
9249 	connp->conn_sqp = sqp;
9250 	connp->conn_initial_sqp = connp->conn_sqp;
9251 	tcp = connp->conn_tcp;
9252 
9253 	if (isv6) {
9254 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9255 		connp->conn_send = ip_output_v6;
9256 		connp->conn_af_isv6 = B_TRUE;
9257 		connp->conn_pkt_isv6 = B_TRUE;
9258 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9259 		tcp->tcp_ipversion = IPV6_VERSION;
9260 		tcp->tcp_family = AF_INET6;
9261 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9262 	} else {
9263 		connp->conn_flags |= IPCL_TCP4;
9264 		connp->conn_send = ip_output;
9265 		connp->conn_af_isv6 = B_FALSE;
9266 		connp->conn_pkt_isv6 = B_FALSE;
9267 		tcp->tcp_ipversion = IPV4_VERSION;
9268 		tcp->tcp_family = AF_INET;
9269 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9270 	}
9271 
9272 	/*
9273 	 * TCP keeps a copy of cred for cache locality reasons but
9274 	 * we put a reference only once. If connp->conn_cred
9275 	 * becomes invalid, tcp_cred should also be set to NULL.
9276 	 */
9277 	tcp->tcp_cred = connp->conn_cred = credp;
9278 	crhold(connp->conn_cred);
9279 	tcp->tcp_cpid = curproc->p_pid;
9280 	tcp->tcp_open_time = lbolt64;
9281 	connp->conn_zoneid = zoneid;
9282 	connp->conn_mlp_type = mlptSingle;
9283 	connp->conn_ulp_labeled = !is_system_labeled();
9284 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9285 	ASSERT(tcp->tcp_tcps == tcps);
9286 
9287 	/*
9288 	 * If the caller has the process-wide flag set, then default to MAC
9289 	 * exempt mode.  This allows read-down to unlabeled hosts.
9290 	 */
9291 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9292 		connp->conn_mac_exempt = B_TRUE;
9293 
9294 	connp->conn_dev = NULL;
9295 	if (issocket) {
9296 		connp->conn_flags |= IPCL_SOCKET;
9297 		tcp->tcp_issocket = 1;
9298 	}
9299 
9300 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
9301 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9302 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
9303 
9304 	/* Non-zero default values */
9305 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9306 
9307 	if (q == NULL) {
9308 		/*
9309 		 * Create a helper stream for non-STREAMS socket.
9310 		 */
9311 		err = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
9312 		if (err != 0) {
9313 			ip1dbg(("tcp_create_common: create of IP helper stream "
9314 			    "failed\n"));
9315 			CONN_DEC_REF(connp);
9316 			*errorp = err;
9317 			return (NULL);
9318 		}
9319 		q = connp->conn_rq;
9320 	} else {
9321 		RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9322 	}
9323 
9324 	SOCK_CONNID_INIT(tcp->tcp_connid);
9325 	err = tcp_init(tcp, q);
9326 	if (err != 0) {
9327 		CONN_DEC_REF(connp);
9328 		*errorp = err;
9329 		return (NULL);
9330 	}
9331 
9332 	return (connp);
9333 }
9334 
9335 static int
9336 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9337     boolean_t isv6)
9338 {
9339 	tcp_t		*tcp = NULL;
9340 	conn_t		*connp = NULL;
9341 	int		err;
9342 	vmem_t		*minor_arena = NULL;
9343 	dev_t		conn_dev;
9344 	boolean_t	issocket;
9345 
9346 	if (q->q_ptr != NULL)
9347 		return (0);
9348 
9349 	if (sflag == MODOPEN)
9350 		return (EINVAL);
9351 
9352 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9353 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9354 		minor_arena = ip_minor_arena_la;
9355 	} else {
9356 		/*
9357 		 * Either minor numbers in the large arena were exhausted
9358 		 * or a non socket application is doing the open.
9359 		 * Try to allocate from the small arena.
9360 		 */
9361 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9362 			return (EBUSY);
9363 		}
9364 		minor_arena = ip_minor_arena_sa;
9365 	}
9366 
9367 	ASSERT(minor_arena != NULL);
9368 
9369 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
9370 
9371 	if (flag & SO_FALLBACK) {
9372 		/*
9373 		 * Non streams socket needs a stream to fallback to
9374 		 */
9375 		RD(q)->q_ptr = (void *)conn_dev;
9376 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
9377 		WR(q)->q_ptr = (void *)minor_arena;
9378 		qprocson(q);
9379 		return (0);
9380 	} else if (flag & SO_ACCEPTOR) {
9381 		q->q_qinfo = &tcp_acceptor_rinit;
9382 		/*
9383 		 * the conn_dev and minor_arena will be subsequently used by
9384 		 * tcp_wput_accept() and tcpclose_accept() to figure out the
9385 		 * minor device number for this connection from the q_ptr.
9386 		 */
9387 		RD(q)->q_ptr = (void *)conn_dev;
9388 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9389 		WR(q)->q_ptr = (void *)minor_arena;
9390 		qprocson(q);
9391 		return (0);
9392 	}
9393 
9394 	issocket = flag & SO_SOCKSTR;
9395 	connp = tcp_create_common(q, credp, isv6, issocket, &err);
9396 
9397 	if (connp == NULL) {
9398 		inet_minor_free(minor_arena, conn_dev);
9399 		q->q_ptr = WR(q)->q_ptr = NULL;
9400 		return (err);
9401 	}
9402 
9403 	q->q_ptr = WR(q)->q_ptr = connp;
9404 
9405 	connp->conn_dev = conn_dev;
9406 	connp->conn_minor_arena = minor_arena;
9407 
9408 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9409 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9410 
9411 	if (issocket) {
9412 		WR(q)->q_qinfo = &tcp_sock_winit;
9413 	} else {
9414 		tcp = connp->conn_tcp;
9415 #ifdef  _ILP32
9416 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9417 #else
9418 		tcp->tcp_acceptor_id = conn_dev;
9419 #endif  /* _ILP32 */
9420 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9421 	}
9422 
9423 	/*
9424 	 * Put the ref for TCP. Ref for IP was already put
9425 	 * by ipcl_conn_create. Also Make the conn_t globally
9426 	 * visible to walkers
9427 	 */
9428 	mutex_enter(&connp->conn_lock);
9429 	CONN_INC_REF_LOCKED(connp);
9430 	ASSERT(connp->conn_ref == 2);
9431 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9432 	mutex_exit(&connp->conn_lock);
9433 
9434 	qprocson(q);
9435 	return (0);
9436 }
9437 
9438 /*
9439  * Some TCP options can be "set" by requesting them in the option
9440  * buffer. This is needed for XTI feature test though we do not
9441  * allow it in general. We interpret that this mechanism is more
9442  * applicable to OSI protocols and need not be allowed in general.
9443  * This routine filters out options for which it is not allowed (most)
9444  * and lets through those (few) for which it is. [ The XTI interface
9445  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9446  * ever implemented will have to be allowed here ].
9447  */
9448 static boolean_t
9449 tcp_allow_connopt_set(int level, int name)
9450 {
9451 
9452 	switch (level) {
9453 	case IPPROTO_TCP:
9454 		switch (name) {
9455 		case TCP_NODELAY:
9456 			return (B_TRUE);
9457 		default:
9458 			return (B_FALSE);
9459 		}
9460 		/*NOTREACHED*/
9461 	default:
9462 		return (B_FALSE);
9463 	}
9464 	/*NOTREACHED*/
9465 }
9466 
9467 /*
9468  * this routine gets default values of certain options whose default
9469  * values are maintained by protocol specific code
9470  */
9471 /* ARGSUSED */
9472 int
9473 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9474 {
9475 	int32_t	*i1 = (int32_t *)ptr;
9476 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9477 
9478 	switch (level) {
9479 	case IPPROTO_TCP:
9480 		switch (name) {
9481 		case TCP_NOTIFY_THRESHOLD:
9482 			*i1 = tcps->tcps_ip_notify_interval;
9483 			break;
9484 		case TCP_ABORT_THRESHOLD:
9485 			*i1 = tcps->tcps_ip_abort_interval;
9486 			break;
9487 		case TCP_CONN_NOTIFY_THRESHOLD:
9488 			*i1 = tcps->tcps_ip_notify_cinterval;
9489 			break;
9490 		case TCP_CONN_ABORT_THRESHOLD:
9491 			*i1 = tcps->tcps_ip_abort_cinterval;
9492 			break;
9493 		default:
9494 			return (-1);
9495 		}
9496 		break;
9497 	case IPPROTO_IP:
9498 		switch (name) {
9499 		case IP_TTL:
9500 			*i1 = tcps->tcps_ipv4_ttl;
9501 			break;
9502 		default:
9503 			return (-1);
9504 		}
9505 		break;
9506 	case IPPROTO_IPV6:
9507 		switch (name) {
9508 		case IPV6_UNICAST_HOPS:
9509 			*i1 = tcps->tcps_ipv6_hoplimit;
9510 			break;
9511 		default:
9512 			return (-1);
9513 		}
9514 		break;
9515 	default:
9516 		return (-1);
9517 	}
9518 	return (sizeof (int));
9519 }
9520 
9521 static int
9522 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
9523 {
9524 	int		*i1 = (int *)ptr;
9525 	tcp_t		*tcp = connp->conn_tcp;
9526 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9527 
9528 	switch (level) {
9529 	case SOL_SOCKET:
9530 		switch (name) {
9531 		case SO_LINGER:	{
9532 			struct linger *lgr = (struct linger *)ptr;
9533 
9534 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9535 			lgr->l_linger = tcp->tcp_lingertime;
9536 			}
9537 			return (sizeof (struct linger));
9538 		case SO_DEBUG:
9539 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9540 			break;
9541 		case SO_KEEPALIVE:
9542 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9543 			break;
9544 		case SO_DONTROUTE:
9545 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9546 			break;
9547 		case SO_USELOOPBACK:
9548 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9549 			break;
9550 		case SO_BROADCAST:
9551 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9552 			break;
9553 		case SO_REUSEADDR:
9554 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9555 			break;
9556 		case SO_OOBINLINE:
9557 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9558 			break;
9559 		case SO_DGRAM_ERRIND:
9560 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9561 			break;
9562 		case SO_TYPE:
9563 			*i1 = SOCK_STREAM;
9564 			break;
9565 		case SO_SNDBUF:
9566 			*i1 = tcp->tcp_xmit_hiwater;
9567 			break;
9568 		case SO_RCVBUF:
9569 			*i1 = tcp->tcp_recv_hiwater;
9570 			break;
9571 		case SO_SND_COPYAVOID:
9572 			*i1 = tcp->tcp_snd_zcopy_on ?
9573 			    SO_SND_COPYAVOID : 0;
9574 			break;
9575 		case SO_ALLZONES:
9576 			*i1 = connp->conn_allzones ? 1 : 0;
9577 			break;
9578 		case SO_ANON_MLP:
9579 			*i1 = connp->conn_anon_mlp;
9580 			break;
9581 		case SO_MAC_EXEMPT:
9582 			*i1 = connp->conn_mac_exempt;
9583 			break;
9584 		case SO_EXCLBIND:
9585 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9586 			break;
9587 		case SO_PROTOTYPE:
9588 			*i1 = IPPROTO_TCP;
9589 			break;
9590 		case SO_DOMAIN:
9591 			*i1 = tcp->tcp_family;
9592 			break;
9593 		case SO_ACCEPTCONN:
9594 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
9595 		default:
9596 			return (-1);
9597 		}
9598 		break;
9599 	case IPPROTO_TCP:
9600 		switch (name) {
9601 		case TCP_NODELAY:
9602 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9603 			break;
9604 		case TCP_MAXSEG:
9605 			*i1 = tcp->tcp_mss;
9606 			break;
9607 		case TCP_NOTIFY_THRESHOLD:
9608 			*i1 = (int)tcp->tcp_first_timer_threshold;
9609 			break;
9610 		case TCP_ABORT_THRESHOLD:
9611 			*i1 = tcp->tcp_second_timer_threshold;
9612 			break;
9613 		case TCP_CONN_NOTIFY_THRESHOLD:
9614 			*i1 = tcp->tcp_first_ctimer_threshold;
9615 			break;
9616 		case TCP_CONN_ABORT_THRESHOLD:
9617 			*i1 = tcp->tcp_second_ctimer_threshold;
9618 			break;
9619 		case TCP_RECVDSTADDR:
9620 			*i1 = tcp->tcp_recvdstaddr;
9621 			break;
9622 		case TCP_ANONPRIVBIND:
9623 			*i1 = tcp->tcp_anon_priv_bind;
9624 			break;
9625 		case TCP_EXCLBIND:
9626 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9627 			break;
9628 		case TCP_INIT_CWND:
9629 			*i1 = tcp->tcp_init_cwnd;
9630 			break;
9631 		case TCP_KEEPALIVE_THRESHOLD:
9632 			*i1 = tcp->tcp_ka_interval;
9633 			break;
9634 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9635 			*i1 = tcp->tcp_ka_abort_thres;
9636 			break;
9637 		case TCP_CORK:
9638 			*i1 = tcp->tcp_cork;
9639 			break;
9640 		default:
9641 			return (-1);
9642 		}
9643 		break;
9644 	case IPPROTO_IP:
9645 		if (tcp->tcp_family != AF_INET)
9646 			return (-1);
9647 		switch (name) {
9648 		case IP_OPTIONS:
9649 		case T_IP_OPTIONS: {
9650 			/*
9651 			 * This is compatible with BSD in that in only return
9652 			 * the reverse source route with the final destination
9653 			 * as the last entry. The first 4 bytes of the option
9654 			 * will contain the final destination.
9655 			 */
9656 			int	opt_len;
9657 
9658 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9659 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9660 			ASSERT(opt_len >= 0);
9661 			/* Caller ensures enough space */
9662 			if (opt_len > 0) {
9663 				/*
9664 				 * TODO: Do we have to handle getsockopt on an
9665 				 * initiator as well?
9666 				 */
9667 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9668 			}
9669 			return (0);
9670 			}
9671 		case IP_TOS:
9672 		case T_IP_TOS:
9673 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9674 			break;
9675 		case IP_TTL:
9676 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9677 			break;
9678 		case IP_NEXTHOP:
9679 			/* Handled at IP level */
9680 			return (-EINVAL);
9681 		default:
9682 			return (-1);
9683 		}
9684 		break;
9685 	case IPPROTO_IPV6:
9686 		/*
9687 		 * IPPROTO_IPV6 options are only supported for sockets
9688 		 * that are using IPv6 on the wire.
9689 		 */
9690 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9691 			return (-1);
9692 		}
9693 		switch (name) {
9694 		case IPV6_UNICAST_HOPS:
9695 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9696 			break;	/* goto sizeof (int) option return */
9697 		case IPV6_BOUND_IF:
9698 			/* Zero if not set */
9699 			*i1 = tcp->tcp_bound_if;
9700 			break;	/* goto sizeof (int) option return */
9701 		case IPV6_RECVPKTINFO:
9702 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9703 				*i1 = 1;
9704 			else
9705 				*i1 = 0;
9706 			break;	/* goto sizeof (int) option return */
9707 		case IPV6_RECVTCLASS:
9708 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9709 				*i1 = 1;
9710 			else
9711 				*i1 = 0;
9712 			break;	/* goto sizeof (int) option return */
9713 		case IPV6_RECVHOPLIMIT:
9714 			if (tcp->tcp_ipv6_recvancillary &
9715 			    TCP_IPV6_RECVHOPLIMIT)
9716 				*i1 = 1;
9717 			else
9718 				*i1 = 0;
9719 			break;	/* goto sizeof (int) option return */
9720 		case IPV6_RECVHOPOPTS:
9721 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9722 				*i1 = 1;
9723 			else
9724 				*i1 = 0;
9725 			break;	/* goto sizeof (int) option return */
9726 		case IPV6_RECVDSTOPTS:
9727 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9728 				*i1 = 1;
9729 			else
9730 				*i1 = 0;
9731 			break;	/* goto sizeof (int) option return */
9732 		case _OLD_IPV6_RECVDSTOPTS:
9733 			if (tcp->tcp_ipv6_recvancillary &
9734 			    TCP_OLD_IPV6_RECVDSTOPTS)
9735 				*i1 = 1;
9736 			else
9737 				*i1 = 0;
9738 			break;	/* goto sizeof (int) option return */
9739 		case IPV6_RECVRTHDR:
9740 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9741 				*i1 = 1;
9742 			else
9743 				*i1 = 0;
9744 			break;	/* goto sizeof (int) option return */
9745 		case IPV6_RECVRTHDRDSTOPTS:
9746 			if (tcp->tcp_ipv6_recvancillary &
9747 			    TCP_IPV6_RECVRTDSTOPTS)
9748 				*i1 = 1;
9749 			else
9750 				*i1 = 0;
9751 			break;	/* goto sizeof (int) option return */
9752 		case IPV6_PKTINFO: {
9753 			/* XXX assumes that caller has room for max size! */
9754 			struct in6_pktinfo *pkti;
9755 
9756 			pkti = (struct in6_pktinfo *)ptr;
9757 			if (ipp->ipp_fields & IPPF_IFINDEX)
9758 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9759 			else
9760 				pkti->ipi6_ifindex = 0;
9761 			if (ipp->ipp_fields & IPPF_ADDR)
9762 				pkti->ipi6_addr = ipp->ipp_addr;
9763 			else
9764 				pkti->ipi6_addr = ipv6_all_zeros;
9765 			return (sizeof (struct in6_pktinfo));
9766 		}
9767 		case IPV6_TCLASS:
9768 			if (ipp->ipp_fields & IPPF_TCLASS)
9769 				*i1 = ipp->ipp_tclass;
9770 			else
9771 				*i1 = IPV6_FLOW_TCLASS(
9772 				    IPV6_DEFAULT_VERS_AND_FLOW);
9773 			break;	/* goto sizeof (int) option return */
9774 		case IPV6_NEXTHOP: {
9775 			sin6_t *sin6 = (sin6_t *)ptr;
9776 
9777 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9778 				return (0);
9779 			*sin6 = sin6_null;
9780 			sin6->sin6_family = AF_INET6;
9781 			sin6->sin6_addr = ipp->ipp_nexthop;
9782 			return (sizeof (sin6_t));
9783 		}
9784 		case IPV6_HOPOPTS:
9785 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9786 				return (0);
9787 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9788 				return (0);
9789 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9790 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9791 			if (tcp->tcp_label_len > 0) {
9792 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9793 				ptr[1] = (ipp->ipp_hopoptslen -
9794 				    tcp->tcp_label_len + 7) / 8 - 1;
9795 			}
9796 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9797 		case IPV6_RTHDRDSTOPTS:
9798 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9799 				return (0);
9800 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9801 			return (ipp->ipp_rtdstoptslen);
9802 		case IPV6_RTHDR:
9803 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9804 				return (0);
9805 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9806 			return (ipp->ipp_rthdrlen);
9807 		case IPV6_DSTOPTS:
9808 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9809 				return (0);
9810 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9811 			return (ipp->ipp_dstoptslen);
9812 		case IPV6_SRC_PREFERENCES:
9813 			return (ip6_get_src_preferences(connp,
9814 			    (uint32_t *)ptr));
9815 		case IPV6_PATHMTU: {
9816 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9817 
9818 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9819 				return (-1);
9820 
9821 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9822 			    connp->conn_fport, mtuinfo,
9823 			    connp->conn_netstack));
9824 		}
9825 		default:
9826 			return (-1);
9827 		}
9828 		break;
9829 	default:
9830 		return (-1);
9831 	}
9832 	return (sizeof (int));
9833 }
9834 
9835 /*
9836  * TCP routine to get the values of options.
9837  */
9838 int
9839 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
9840 {
9841 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
9842 }
9843 
9844 /* returns UNIX error, the optlen is a value-result arg */
9845 int
9846 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
9847     void *optvalp, socklen_t *optlen, cred_t *cr)
9848 {
9849 	conn_t		*connp = (conn_t *)proto_handle;
9850 	squeue_t	*sqp = connp->conn_sqp;
9851 	int		error;
9852 	t_uscalar_t	max_optbuf_len;
9853 	void		*optvalp_buf;
9854 	int		len;
9855 
9856 	ASSERT(connp->conn_upper_handle != NULL);
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_RCVTIMEO:
10135 		case SO_SNDTIMEO:
10136 			/*
10137 			 * Pass these two options in order for third part
10138 			 * protocol usage. Here just return directly.
10139 			 */
10140 			return (0);
10141 		case SO_ALLZONES:
10142 			/* Pass option along to IP level for handling */
10143 			return (-EINVAL);
10144 		case SO_ANON_MLP:
10145 			/* Pass option along to IP level for handling */
10146 			return (-EINVAL);
10147 		case SO_MAC_EXEMPT:
10148 			/* Pass option along to IP level for handling */
10149 			return (-EINVAL);
10150 		case SO_EXCLBIND:
10151 			if (!checkonly)
10152 				tcp->tcp_exclbind = onoff;
10153 			break;
10154 		default:
10155 			*outlenp = 0;
10156 			return (EINVAL);
10157 		}
10158 		break;
10159 	case IPPROTO_TCP:
10160 		switch (name) {
10161 		case TCP_NODELAY:
10162 			if (!checkonly)
10163 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10164 			break;
10165 		case TCP_NOTIFY_THRESHOLD:
10166 			if (!checkonly)
10167 				tcp->tcp_first_timer_threshold = *i1;
10168 			break;
10169 		case TCP_ABORT_THRESHOLD:
10170 			if (!checkonly)
10171 				tcp->tcp_second_timer_threshold = *i1;
10172 			break;
10173 		case TCP_CONN_NOTIFY_THRESHOLD:
10174 			if (!checkonly)
10175 				tcp->tcp_first_ctimer_threshold = *i1;
10176 			break;
10177 		case TCP_CONN_ABORT_THRESHOLD:
10178 			if (!checkonly)
10179 				tcp->tcp_second_ctimer_threshold = *i1;
10180 			break;
10181 		case TCP_RECVDSTADDR:
10182 			if (tcp->tcp_state > TCPS_LISTEN)
10183 				return (EOPNOTSUPP);
10184 			if (!checkonly)
10185 				tcp->tcp_recvdstaddr = onoff;
10186 			break;
10187 		case TCP_ANONPRIVBIND:
10188 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10189 			    IPPROTO_TCP)) != 0) {
10190 				*outlenp = 0;
10191 				return (reterr);
10192 			}
10193 			if (!checkonly) {
10194 				tcp->tcp_anon_priv_bind = onoff;
10195 			}
10196 			break;
10197 		case TCP_EXCLBIND:
10198 			if (!checkonly)
10199 				tcp->tcp_exclbind = onoff;
10200 			break;	/* goto sizeof (int) option return */
10201 		case TCP_INIT_CWND: {
10202 			uint32_t init_cwnd = *((uint32_t *)invalp);
10203 
10204 			if (checkonly)
10205 				break;
10206 
10207 			/*
10208 			 * Only allow socket with network configuration
10209 			 * privilege to set the initial cwnd to be larger
10210 			 * than allowed by RFC 3390.
10211 			 */
10212 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10213 				tcp->tcp_init_cwnd = init_cwnd;
10214 				break;
10215 			}
10216 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10217 				*outlenp = 0;
10218 				return (reterr);
10219 			}
10220 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10221 				*outlenp = 0;
10222 				return (EINVAL);
10223 			}
10224 			tcp->tcp_init_cwnd = init_cwnd;
10225 			break;
10226 		}
10227 		case TCP_KEEPALIVE_THRESHOLD:
10228 			if (checkonly)
10229 				break;
10230 
10231 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10232 			    *i1 > tcps->tcps_keepalive_interval_high) {
10233 				*outlenp = 0;
10234 				return (EINVAL);
10235 			}
10236 			if (*i1 != tcp->tcp_ka_interval) {
10237 				tcp->tcp_ka_interval = *i1;
10238 				/*
10239 				 * Check if we need to restart the
10240 				 * keepalive timer.
10241 				 */
10242 				if (tcp->tcp_ka_tid != 0) {
10243 					ASSERT(tcp->tcp_ka_enabled);
10244 					(void) TCP_TIMER_CANCEL(tcp,
10245 					    tcp->tcp_ka_tid);
10246 					tcp->tcp_ka_last_intrvl = 0;
10247 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10248 					    tcp_keepalive_killer,
10249 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10250 				}
10251 			}
10252 			break;
10253 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10254 			if (!checkonly) {
10255 				if (*i1 <
10256 				    tcps->tcps_keepalive_abort_interval_low ||
10257 				    *i1 >
10258 				    tcps->tcps_keepalive_abort_interval_high) {
10259 					*outlenp = 0;
10260 					return (EINVAL);
10261 				}
10262 				tcp->tcp_ka_abort_thres = *i1;
10263 			}
10264 			break;
10265 		case TCP_CORK:
10266 			if (!checkonly) {
10267 				/*
10268 				 * if tcp->tcp_cork was set and is now
10269 				 * being unset, we have to make sure that
10270 				 * the remaining data gets sent out. Also
10271 				 * unset tcp->tcp_cork so that tcp_wput_data()
10272 				 * can send data even if it is less than mss
10273 				 */
10274 				if (tcp->tcp_cork && onoff == 0 &&
10275 				    tcp->tcp_unsent > 0) {
10276 					tcp->tcp_cork = B_FALSE;
10277 					tcp_wput_data(tcp, NULL, B_FALSE);
10278 				}
10279 				tcp->tcp_cork = onoff;
10280 			}
10281 			break;
10282 		default:
10283 			*outlenp = 0;
10284 			return (EINVAL);
10285 		}
10286 		break;
10287 	case IPPROTO_IP:
10288 		if (tcp->tcp_family != AF_INET) {
10289 			*outlenp = 0;
10290 			return (ENOPROTOOPT);
10291 		}
10292 		switch (name) {
10293 		case IP_OPTIONS:
10294 		case T_IP_OPTIONS:
10295 			reterr = tcp_opt_set_header(tcp, checkonly,
10296 			    invalp, inlen);
10297 			if (reterr) {
10298 				*outlenp = 0;
10299 				return (reterr);
10300 			}
10301 			/* OK return - copy input buffer into output buffer */
10302 			if (invalp != outvalp) {
10303 				/* don't trust bcopy for identical src/dst */
10304 				bcopy(invalp, outvalp, inlen);
10305 			}
10306 			*outlenp = inlen;
10307 			return (0);
10308 		case IP_TOS:
10309 		case T_IP_TOS:
10310 			if (!checkonly) {
10311 				tcp->tcp_ipha->ipha_type_of_service =
10312 				    (uchar_t)*i1;
10313 				tcp->tcp_tos = (uchar_t)*i1;
10314 			}
10315 			break;
10316 		case IP_TTL:
10317 			if (!checkonly) {
10318 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10319 				tcp->tcp_ttl = (uchar_t)*i1;
10320 			}
10321 			break;
10322 		case IP_BOUND_IF:
10323 		case IP_NEXTHOP:
10324 			/* Handled at the IP level */
10325 			return (-EINVAL);
10326 		case IP_SEC_OPT:
10327 			/*
10328 			 * We should not allow policy setting after
10329 			 * we start listening for connections.
10330 			 */
10331 			if (tcp->tcp_state == TCPS_LISTEN) {
10332 				return (EINVAL);
10333 			} else {
10334 				/* Handled at the IP level */
10335 				return (-EINVAL);
10336 			}
10337 		default:
10338 			*outlenp = 0;
10339 			return (EINVAL);
10340 		}
10341 		break;
10342 	case IPPROTO_IPV6: {
10343 		ip6_pkt_t		*ipp;
10344 
10345 		/*
10346 		 * IPPROTO_IPV6 options are only supported for sockets
10347 		 * that are using IPv6 on the wire.
10348 		 */
10349 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10350 			*outlenp = 0;
10351 			return (ENOPROTOOPT);
10352 		}
10353 		/*
10354 		 * Only sticky options; no ancillary data
10355 		 */
10356 		ipp = &tcp->tcp_sticky_ipp;
10357 
10358 		switch (name) {
10359 		case IPV6_UNICAST_HOPS:
10360 			/* -1 means use default */
10361 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10362 				*outlenp = 0;
10363 				return (EINVAL);
10364 			}
10365 			if (!checkonly) {
10366 				if (*i1 == -1) {
10367 					tcp->tcp_ip6h->ip6_hops =
10368 					    ipp->ipp_unicast_hops =
10369 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10370 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10371 					/* Pass modified value to IP. */
10372 					*i1 = tcp->tcp_ip6h->ip6_hops;
10373 				} else {
10374 					tcp->tcp_ip6h->ip6_hops =
10375 					    ipp->ipp_unicast_hops =
10376 					    (uint8_t)*i1;
10377 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10378 				}
10379 				reterr = tcp_build_hdrs(tcp);
10380 				if (reterr != 0)
10381 					return (reterr);
10382 			}
10383 			break;
10384 		case IPV6_BOUND_IF:
10385 			if (!checkonly) {
10386 				tcp->tcp_bound_if = *i1;
10387 				PASS_OPT_TO_IP(connp);
10388 			}
10389 			break;
10390 		/*
10391 		 * Set boolean switches for ancillary data delivery
10392 		 */
10393 		case IPV6_RECVPKTINFO:
10394 			if (!checkonly) {
10395 				if (onoff)
10396 					tcp->tcp_ipv6_recvancillary |=
10397 					    TCP_IPV6_RECVPKTINFO;
10398 				else
10399 					tcp->tcp_ipv6_recvancillary &=
10400 					    ~TCP_IPV6_RECVPKTINFO;
10401 				/* Force it to be sent up with the next msg */
10402 				tcp->tcp_recvifindex = 0;
10403 				PASS_OPT_TO_IP(connp);
10404 			}
10405 			break;
10406 		case IPV6_RECVTCLASS:
10407 			if (!checkonly) {
10408 				if (onoff)
10409 					tcp->tcp_ipv6_recvancillary |=
10410 					    TCP_IPV6_RECVTCLASS;
10411 				else
10412 					tcp->tcp_ipv6_recvancillary &=
10413 					    ~TCP_IPV6_RECVTCLASS;
10414 				PASS_OPT_TO_IP(connp);
10415 			}
10416 			break;
10417 		case IPV6_RECVHOPLIMIT:
10418 			if (!checkonly) {
10419 				if (onoff)
10420 					tcp->tcp_ipv6_recvancillary |=
10421 					    TCP_IPV6_RECVHOPLIMIT;
10422 				else
10423 					tcp->tcp_ipv6_recvancillary &=
10424 					    ~TCP_IPV6_RECVHOPLIMIT;
10425 				/* Force it to be sent up with the next msg */
10426 				tcp->tcp_recvhops = 0xffffffffU;
10427 				PASS_OPT_TO_IP(connp);
10428 			}
10429 			break;
10430 		case IPV6_RECVHOPOPTS:
10431 			if (!checkonly) {
10432 				if (onoff)
10433 					tcp->tcp_ipv6_recvancillary |=
10434 					    TCP_IPV6_RECVHOPOPTS;
10435 				else
10436 					tcp->tcp_ipv6_recvancillary &=
10437 					    ~TCP_IPV6_RECVHOPOPTS;
10438 				PASS_OPT_TO_IP(connp);
10439 			}
10440 			break;
10441 		case IPV6_RECVDSTOPTS:
10442 			if (!checkonly) {
10443 				if (onoff)
10444 					tcp->tcp_ipv6_recvancillary |=
10445 					    TCP_IPV6_RECVDSTOPTS;
10446 				else
10447 					tcp->tcp_ipv6_recvancillary &=
10448 					    ~TCP_IPV6_RECVDSTOPTS;
10449 				PASS_OPT_TO_IP(connp);
10450 			}
10451 			break;
10452 		case _OLD_IPV6_RECVDSTOPTS:
10453 			if (!checkonly) {
10454 				if (onoff)
10455 					tcp->tcp_ipv6_recvancillary |=
10456 					    TCP_OLD_IPV6_RECVDSTOPTS;
10457 				else
10458 					tcp->tcp_ipv6_recvancillary &=
10459 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10460 			}
10461 			break;
10462 		case IPV6_RECVRTHDR:
10463 			if (!checkonly) {
10464 				if (onoff)
10465 					tcp->tcp_ipv6_recvancillary |=
10466 					    TCP_IPV6_RECVRTHDR;
10467 				else
10468 					tcp->tcp_ipv6_recvancillary &=
10469 					    ~TCP_IPV6_RECVRTHDR;
10470 				PASS_OPT_TO_IP(connp);
10471 			}
10472 			break;
10473 		case IPV6_RECVRTHDRDSTOPTS:
10474 			if (!checkonly) {
10475 				if (onoff)
10476 					tcp->tcp_ipv6_recvancillary |=
10477 					    TCP_IPV6_RECVRTDSTOPTS;
10478 				else
10479 					tcp->tcp_ipv6_recvancillary &=
10480 					    ~TCP_IPV6_RECVRTDSTOPTS;
10481 				PASS_OPT_TO_IP(connp);
10482 			}
10483 			break;
10484 		case IPV6_PKTINFO:
10485 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10486 				return (EINVAL);
10487 			if (checkonly)
10488 				break;
10489 
10490 			if (inlen == 0) {
10491 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10492 			} else {
10493 				struct in6_pktinfo *pkti;
10494 
10495 				pkti = (struct in6_pktinfo *)invalp;
10496 				/*
10497 				 * RFC 3542 states that ipi6_addr must be
10498 				 * the unspecified address when setting the
10499 				 * IPV6_PKTINFO sticky socket option on a
10500 				 * TCP socket.
10501 				 */
10502 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10503 					return (EINVAL);
10504 				/*
10505 				 * IP will validate the source address and
10506 				 * interface index.
10507 				 */
10508 				if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
10509 					reterr = ip_set_options(tcp->tcp_connp,
10510 					    level, name, invalp, inlen, cr);
10511 				} else {
10512 					reterr = ip6_set_pktinfo(cr,
10513 					    tcp->tcp_connp, pkti);
10514 				}
10515 				if (reterr != 0)
10516 					return (reterr);
10517 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10518 				ipp->ipp_addr = pkti->ipi6_addr;
10519 				if (ipp->ipp_ifindex != 0)
10520 					ipp->ipp_fields |= IPPF_IFINDEX;
10521 				else
10522 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10523 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10524 					ipp->ipp_fields |= IPPF_ADDR;
10525 				else
10526 					ipp->ipp_fields &= ~IPPF_ADDR;
10527 			}
10528 			reterr = tcp_build_hdrs(tcp);
10529 			if (reterr != 0)
10530 				return (reterr);
10531 			break;
10532 		case IPV6_TCLASS:
10533 			if (inlen != 0 && inlen != sizeof (int))
10534 				return (EINVAL);
10535 			if (checkonly)
10536 				break;
10537 
10538 			if (inlen == 0) {
10539 				ipp->ipp_fields &= ~IPPF_TCLASS;
10540 			} else {
10541 				if (*i1 > 255 || *i1 < -1)
10542 					return (EINVAL);
10543 				if (*i1 == -1) {
10544 					ipp->ipp_tclass = 0;
10545 					*i1 = 0;
10546 				} else {
10547 					ipp->ipp_tclass = *i1;
10548 				}
10549 				ipp->ipp_fields |= IPPF_TCLASS;
10550 			}
10551 			reterr = tcp_build_hdrs(tcp);
10552 			if (reterr != 0)
10553 				return (reterr);
10554 			break;
10555 		case IPV6_NEXTHOP:
10556 			/*
10557 			 * IP will verify that the nexthop is reachable
10558 			 * and fail for sticky options.
10559 			 */
10560 			if (inlen != 0 && inlen != sizeof (sin6_t))
10561 				return (EINVAL);
10562 			if (checkonly)
10563 				break;
10564 
10565 			if (inlen == 0) {
10566 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10567 			} else {
10568 				sin6_t *sin6 = (sin6_t *)invalp;
10569 
10570 				if (sin6->sin6_family != AF_INET6)
10571 					return (EAFNOSUPPORT);
10572 				if (IN6_IS_ADDR_V4MAPPED(
10573 				    &sin6->sin6_addr))
10574 					return (EADDRNOTAVAIL);
10575 				ipp->ipp_nexthop = sin6->sin6_addr;
10576 				if (!IN6_IS_ADDR_UNSPECIFIED(
10577 				    &ipp->ipp_nexthop))
10578 					ipp->ipp_fields |= IPPF_NEXTHOP;
10579 				else
10580 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10581 			}
10582 			reterr = tcp_build_hdrs(tcp);
10583 			if (reterr != 0)
10584 				return (reterr);
10585 			PASS_OPT_TO_IP(connp);
10586 			break;
10587 		case IPV6_HOPOPTS: {
10588 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10589 
10590 			/*
10591 			 * Sanity checks - minimum size, size a multiple of
10592 			 * eight bytes, and matching size passed in.
10593 			 */
10594 			if (inlen != 0 &&
10595 			    inlen != (8 * (hopts->ip6h_len + 1)))
10596 				return (EINVAL);
10597 
10598 			if (checkonly)
10599 				break;
10600 
10601 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10602 			    (uchar_t **)&ipp->ipp_hopopts,
10603 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10604 			if (reterr != 0)
10605 				return (reterr);
10606 			if (ipp->ipp_hopoptslen == 0)
10607 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10608 			else
10609 				ipp->ipp_fields |= IPPF_HOPOPTS;
10610 			reterr = tcp_build_hdrs(tcp);
10611 			if (reterr != 0)
10612 				return (reterr);
10613 			break;
10614 		}
10615 		case IPV6_RTHDRDSTOPTS: {
10616 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10617 
10618 			/*
10619 			 * Sanity checks - minimum size, size a multiple of
10620 			 * eight bytes, and matching size passed in.
10621 			 */
10622 			if (inlen != 0 &&
10623 			    inlen != (8 * (dopts->ip6d_len + 1)))
10624 				return (EINVAL);
10625 
10626 			if (checkonly)
10627 				break;
10628 
10629 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10630 			    (uchar_t **)&ipp->ipp_rtdstopts,
10631 			    &ipp->ipp_rtdstoptslen, 0);
10632 			if (reterr != 0)
10633 				return (reterr);
10634 			if (ipp->ipp_rtdstoptslen == 0)
10635 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10636 			else
10637 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10638 			reterr = tcp_build_hdrs(tcp);
10639 			if (reterr != 0)
10640 				return (reterr);
10641 			break;
10642 		}
10643 		case IPV6_DSTOPTS: {
10644 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10645 
10646 			/*
10647 			 * Sanity checks - minimum size, size a multiple of
10648 			 * eight bytes, and matching size passed in.
10649 			 */
10650 			if (inlen != 0 &&
10651 			    inlen != (8 * (dopts->ip6d_len + 1)))
10652 				return (EINVAL);
10653 
10654 			if (checkonly)
10655 				break;
10656 
10657 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10658 			    (uchar_t **)&ipp->ipp_dstopts,
10659 			    &ipp->ipp_dstoptslen, 0);
10660 			if (reterr != 0)
10661 				return (reterr);
10662 			if (ipp->ipp_dstoptslen == 0)
10663 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10664 			else
10665 				ipp->ipp_fields |= IPPF_DSTOPTS;
10666 			reterr = tcp_build_hdrs(tcp);
10667 			if (reterr != 0)
10668 				return (reterr);
10669 			break;
10670 		}
10671 		case IPV6_RTHDR: {
10672 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10673 
10674 			/*
10675 			 * Sanity checks - minimum size, size a multiple of
10676 			 * eight bytes, and matching size passed in.
10677 			 */
10678 			if (inlen != 0 &&
10679 			    inlen != (8 * (rt->ip6r_len + 1)))
10680 				return (EINVAL);
10681 
10682 			if (checkonly)
10683 				break;
10684 
10685 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10686 			    (uchar_t **)&ipp->ipp_rthdr,
10687 			    &ipp->ipp_rthdrlen, 0);
10688 			if (reterr != 0)
10689 				return (reterr);
10690 			if (ipp->ipp_rthdrlen == 0)
10691 				ipp->ipp_fields &= ~IPPF_RTHDR;
10692 			else
10693 				ipp->ipp_fields |= IPPF_RTHDR;
10694 			reterr = tcp_build_hdrs(tcp);
10695 			if (reterr != 0)
10696 				return (reterr);
10697 			break;
10698 		}
10699 		case IPV6_V6ONLY:
10700 			if (!checkonly) {
10701 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10702 			}
10703 			break;
10704 		case IPV6_USE_MIN_MTU:
10705 			if (inlen != sizeof (int))
10706 				return (EINVAL);
10707 
10708 			if (*i1 < -1 || *i1 > 1)
10709 				return (EINVAL);
10710 
10711 			if (checkonly)
10712 				break;
10713 
10714 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10715 			ipp->ipp_use_min_mtu = *i1;
10716 			break;
10717 		case IPV6_SEC_OPT:
10718 			/*
10719 			 * We should not allow policy setting after
10720 			 * we start listening for connections.
10721 			 */
10722 			if (tcp->tcp_state == TCPS_LISTEN) {
10723 				return (EINVAL);
10724 			} else {
10725 				/* Handled at the IP level */
10726 				return (-EINVAL);
10727 			}
10728 		case IPV6_SRC_PREFERENCES:
10729 			if (inlen != sizeof (uint32_t))
10730 				return (EINVAL);
10731 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10732 			    *(uint32_t *)invalp);
10733 			if (reterr != 0) {
10734 				*outlenp = 0;
10735 				return (reterr);
10736 			}
10737 			break;
10738 		default:
10739 			*outlenp = 0;
10740 			return (EINVAL);
10741 		}
10742 		break;
10743 	}		/* end IPPROTO_IPV6 */
10744 	default:
10745 		*outlenp = 0;
10746 		return (EINVAL);
10747 	}
10748 	/*
10749 	 * Common case of OK return with outval same as inval
10750 	 */
10751 	if (invalp != outvalp) {
10752 		/* don't trust bcopy for identical src/dst */
10753 		(void) bcopy(invalp, outvalp, inlen);
10754 	}
10755 	*outlenp = inlen;
10756 	return (0);
10757 }
10758 
10759 /* ARGSUSED */
10760 int
10761 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10762     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10763     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10764 {
10765 	conn_t	*connp =  Q_TO_CONN(q);
10766 
10767 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
10768 	    outlenp, outvalp, thisdg_attrs, cr, mblk));
10769 }
10770 
10771 int
10772 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
10773     const void *optvalp, socklen_t optlen, cred_t *cr)
10774 {
10775 	conn_t		*connp = (conn_t *)proto_handle;
10776 	squeue_t	*sqp = connp->conn_sqp;
10777 	int		error;
10778 
10779 	ASSERT(connp->conn_upper_handle != NULL);
10780 	/*
10781 	 * Entering the squeue synchronously can result in a context switch,
10782 	 * which can cause a rather sever performance degradation. So we try to
10783 	 * handle whatever options we can without entering the squeue.
10784 	 */
10785 	if (level == IPPROTO_TCP) {
10786 		switch (option_name) {
10787 		case TCP_NODELAY:
10788 			if (optlen != sizeof (int32_t))
10789 				return (EINVAL);
10790 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
10791 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
10792 			    connp->conn_tcp->tcp_mss;
10793 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
10794 			return (0);
10795 		default:
10796 			break;
10797 		}
10798 	}
10799 
10800 	error = squeue_synch_enter(sqp, connp, 0);
10801 	if (error == ENOMEM) {
10802 		return (ENOMEM);
10803 	}
10804 
10805 	error = proto_opt_check(level, option_name, optlen, NULL,
10806 	    tcp_opt_obj.odb_opt_des_arr,
10807 	    tcp_opt_obj.odb_opt_arr_cnt,
10808 	    tcp_opt_obj.odb_topmost_tpiprovider,
10809 	    B_TRUE, B_FALSE, cr);
10810 
10811 	if (error != 0) {
10812 		if (error < 0) {
10813 			error = proto_tlitosyserr(-error);
10814 		}
10815 		squeue_synch_exit(sqp, connp);
10816 		return (error);
10817 	}
10818 
10819 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
10820 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
10821 	    NULL, cr, NULL);
10822 	squeue_synch_exit(sqp, connp);
10823 
10824 	if (error < 0) {
10825 		/*
10826 		 * Pass on to ip
10827 		 */
10828 		error = ip_set_options(connp, level, option_name, optvalp,
10829 		    optlen, cr);
10830 	}
10831 	return (error);
10832 }
10833 
10834 /*
10835  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10836  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10837  * headers, and the maximum size tcp header (to avoid reallocation
10838  * on the fly for additional tcp options).
10839  * Returns failure if can't allocate memory.
10840  */
10841 static int
10842 tcp_build_hdrs(tcp_t *tcp)
10843 {
10844 	char	*hdrs;
10845 	uint_t	hdrs_len;
10846 	ip6i_t	*ip6i;
10847 	char	buf[TCP_MAX_HDR_LENGTH];
10848 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10849 	in6_addr_t src, dst;
10850 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10851 	conn_t *connp = tcp->tcp_connp;
10852 
10853 	/*
10854 	 * save the existing tcp header and source/dest IP addresses
10855 	 */
10856 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10857 	src = tcp->tcp_ip6h->ip6_src;
10858 	dst = tcp->tcp_ip6h->ip6_dst;
10859 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10860 	ASSERT(hdrs_len != 0);
10861 	if (hdrs_len > tcp->tcp_iphc_len) {
10862 		/* Need to reallocate */
10863 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10864 		if (hdrs == NULL)
10865 			return (ENOMEM);
10866 		if (tcp->tcp_iphc != NULL) {
10867 			if (tcp->tcp_hdr_grown) {
10868 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10869 			} else {
10870 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10871 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10872 			}
10873 			tcp->tcp_iphc_len = 0;
10874 		}
10875 		ASSERT(tcp->tcp_iphc_len == 0);
10876 		tcp->tcp_iphc = hdrs;
10877 		tcp->tcp_iphc_len = hdrs_len;
10878 		tcp->tcp_hdr_grown = B_TRUE;
10879 	}
10880 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10881 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10882 
10883 	/* Set header fields not in ipp */
10884 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10885 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10886 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10887 	} else {
10888 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10889 	}
10890 	/*
10891 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10892 	 *
10893 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10894 	 */
10895 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10896 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10897 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10898 
10899 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10900 
10901 	tcp->tcp_ip6h->ip6_src = src;
10902 	tcp->tcp_ip6h->ip6_dst = dst;
10903 
10904 	/*
10905 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10906 	 * the default value for TCP.
10907 	 */
10908 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10909 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
10910 
10911 	/*
10912 	 * If we're setting extension headers after a connection
10913 	 * has been established, and if we have a routing header
10914 	 * among the extension headers, call ip_massage_options_v6 to
10915 	 * manipulate the routing header/ip6_dst set the checksum
10916 	 * difference in the tcp header template.
10917 	 * (This happens in tcp_connect_ipv6 if the routing header
10918 	 * is set prior to the connect.)
10919 	 * Set the tcp_sum to zero first in case we've cleared a
10920 	 * routing header or don't have one at all.
10921 	 */
10922 	tcp->tcp_sum = 0;
10923 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10924 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10925 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10926 		    (uint8_t *)tcp->tcp_tcph);
10927 		if (rth != NULL) {
10928 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10929 			    rth, tcps->tcps_netstack);
10930 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10931 			    (tcp->tcp_sum >> 16));
10932 		}
10933 	}
10934 
10935 	/* Try to get everything in a single mblk */
10936 	(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
10937 	    hdrs_len + tcps->tcps_wroff_xtra);
10938 	return (0);
10939 }
10940 
10941 /*
10942  * Transfer any source route option from ipha to buf/dst in reversed form.
10943  */
10944 static int
10945 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10946 {
10947 	ipoptp_t	opts;
10948 	uchar_t		*opt;
10949 	uint8_t		optval;
10950 	uint8_t		optlen;
10951 	uint32_t	len = 0;
10952 
10953 	for (optval = ipoptp_first(&opts, ipha);
10954 	    optval != IPOPT_EOL;
10955 	    optval = ipoptp_next(&opts)) {
10956 		opt = opts.ipoptp_cur;
10957 		optlen = opts.ipoptp_len;
10958 		switch (optval) {
10959 			int	off1, off2;
10960 		case IPOPT_SSRR:
10961 		case IPOPT_LSRR:
10962 
10963 			/* Reverse source route */
10964 			/*
10965 			 * First entry should be the next to last one in the
10966 			 * current source route (the last entry is our
10967 			 * address.)
10968 			 * The last entry should be the final destination.
10969 			 */
10970 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10971 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10972 			off1 = IPOPT_MINOFF_SR - 1;
10973 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10974 			if (off2 < 0) {
10975 				/* No entries in source route */
10976 				break;
10977 			}
10978 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10979 			/*
10980 			 * Note: use src since ipha has not had its src
10981 			 * and dst reversed (it is in the state it was
10982 			 * received.
10983 			 */
10984 			bcopy(&ipha->ipha_src, buf + off2,
10985 			    IP_ADDR_LEN);
10986 			off2 -= IP_ADDR_LEN;
10987 
10988 			while (off2 > 0) {
10989 				bcopy(opt + off2, buf + off1,
10990 				    IP_ADDR_LEN);
10991 				off1 += IP_ADDR_LEN;
10992 				off2 -= IP_ADDR_LEN;
10993 			}
10994 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
10995 			buf += optlen;
10996 			len += optlen;
10997 			break;
10998 		}
10999 	}
11000 done:
11001 	/* Pad the resulting options */
11002 	while (len & 0x3) {
11003 		*buf++ = IPOPT_EOL;
11004 		len++;
11005 	}
11006 	return (len);
11007 }
11008 
11009 
11010 /*
11011  * Extract and revert a source route from ipha (if any)
11012  * and then update the relevant fields in both tcp_t and the standard header.
11013  */
11014 static void
11015 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11016 {
11017 	char	buf[TCP_MAX_HDR_LENGTH];
11018 	uint_t	tcph_len;
11019 	int	len;
11020 
11021 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11022 	len = IPH_HDR_LENGTH(ipha);
11023 	if (len == IP_SIMPLE_HDR_LENGTH)
11024 		/* Nothing to do */
11025 		return;
11026 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11027 	    (len & 0x3))
11028 		return;
11029 
11030 	tcph_len = tcp->tcp_tcp_hdr_len;
11031 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11032 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11033 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11034 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11035 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11036 	len += IP_SIMPLE_HDR_LENGTH;
11037 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11038 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11039 	if ((int)tcp->tcp_sum < 0)
11040 		tcp->tcp_sum--;
11041 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11042 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11043 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11044 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11045 	tcp->tcp_ip_hdr_len = len;
11046 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11047 	    (IP_VERSION << 4) | (len >> 2);
11048 	len += tcph_len;
11049 	tcp->tcp_hdr_len = len;
11050 }
11051 
11052 /*
11053  * Copy the standard header into its new location,
11054  * lay in the new options and then update the relevant
11055  * fields in both tcp_t and the standard header.
11056  */
11057 static int
11058 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11059 {
11060 	uint_t	tcph_len;
11061 	uint8_t	*ip_optp;
11062 	tcph_t	*new_tcph;
11063 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11064 	conn_t	*connp = tcp->tcp_connp;
11065 
11066 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11067 		return (EINVAL);
11068 
11069 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11070 		return (EINVAL);
11071 
11072 	if (checkonly) {
11073 		/*
11074 		 * do not really set, just pretend to - T_CHECK
11075 		 */
11076 		return (0);
11077 	}
11078 
11079 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11080 	if (tcp->tcp_label_len > 0) {
11081 		int padlen;
11082 		uint8_t opt;
11083 
11084 		/* convert list termination to no-ops */
11085 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11086 		ip_optp += ip_optp[IPOPT_OLEN];
11087 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11088 		while (--padlen >= 0)
11089 			*ip_optp++ = opt;
11090 	}
11091 	tcph_len = tcp->tcp_tcp_hdr_len;
11092 	new_tcph = (tcph_t *)(ip_optp + len);
11093 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11094 	tcp->tcp_tcph = new_tcph;
11095 	bcopy(ptr, ip_optp, len);
11096 
11097 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11098 
11099 	tcp->tcp_ip_hdr_len = len;
11100 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11101 	    (IP_VERSION << 4) | (len >> 2);
11102 	tcp->tcp_hdr_len = len + tcph_len;
11103 	if (!TCP_IS_DETACHED(tcp)) {
11104 		/* Always allocate room for all options. */
11105 		(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
11106 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11107 	}
11108 	return (0);
11109 }
11110 
11111 /* Get callback routine passed to nd_load by tcp_param_register */
11112 /* ARGSUSED */
11113 static int
11114 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11115 {
11116 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11117 
11118 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11119 	return (0);
11120 }
11121 
11122 /*
11123  * Walk through the param array specified registering each element with the
11124  * named dispatch handler.
11125  */
11126 static boolean_t
11127 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11128 {
11129 	for (; cnt-- > 0; tcppa++) {
11130 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11131 			if (!nd_load(ndp, tcppa->tcp_param_name,
11132 			    tcp_param_get, tcp_param_set,
11133 			    (caddr_t)tcppa)) {
11134 				nd_free(ndp);
11135 				return (B_FALSE);
11136 			}
11137 		}
11138 	}
11139 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11140 	    KM_SLEEP);
11141 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11142 	    sizeof (tcpparam_t));
11143 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11144 	    tcp_param_get, tcp_param_set_aligned,
11145 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11146 		nd_free(ndp);
11147 		return (B_FALSE);
11148 	}
11149 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11150 	    KM_SLEEP);
11151 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11152 	    sizeof (tcpparam_t));
11153 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11154 	    tcp_param_get, tcp_param_set_aligned,
11155 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11156 		nd_free(ndp);
11157 		return (B_FALSE);
11158 	}
11159 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11160 	    KM_SLEEP);
11161 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11162 	    sizeof (tcpparam_t));
11163 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11164 	    tcp_param_get, tcp_param_set_aligned,
11165 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11166 		nd_free(ndp);
11167 		return (B_FALSE);
11168 	}
11169 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11170 	    KM_SLEEP);
11171 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11172 	    sizeof (tcpparam_t));
11173 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11174 	    tcp_param_get, tcp_param_set_aligned,
11175 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11176 		nd_free(ndp);
11177 		return (B_FALSE);
11178 	}
11179 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11180 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11181 		nd_free(ndp);
11182 		return (B_FALSE);
11183 	}
11184 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11185 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11186 		nd_free(ndp);
11187 		return (B_FALSE);
11188 	}
11189 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11190 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11191 		nd_free(ndp);
11192 		return (B_FALSE);
11193 	}
11194 	if (!nd_load(ndp, "tcp_status", tcp_status_report, NULL,
11195 	    NULL)) {
11196 		nd_free(ndp);
11197 		return (B_FALSE);
11198 	}
11199 	if (!nd_load(ndp, "tcp_bind_hash", tcp_bind_hash_report,
11200 	    NULL, NULL)) {
11201 		nd_free(ndp);
11202 		return (B_FALSE);
11203 	}
11204 	if (!nd_load(ndp, "tcp_listen_hash",
11205 	    tcp_listen_hash_report, NULL, NULL)) {
11206 		nd_free(ndp);
11207 		return (B_FALSE);
11208 	}
11209 	if (!nd_load(ndp, "tcp_conn_hash", tcp_conn_hash_report,
11210 	    NULL, NULL)) {
11211 		nd_free(ndp);
11212 		return (B_FALSE);
11213 	}
11214 	if (!nd_load(ndp, "tcp_acceptor_hash",
11215 	    tcp_acceptor_hash_report, NULL, NULL)) {
11216 		nd_free(ndp);
11217 		return (B_FALSE);
11218 	}
11219 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11220 	    tcp_1948_phrase_set, NULL)) {
11221 		nd_free(ndp);
11222 		return (B_FALSE);
11223 	}
11224 	/*
11225 	 * Dummy ndd variables - only to convey obsolescence information
11226 	 * through printing of their name (no get or set routines)
11227 	 * XXX Remove in future releases ?
11228 	 */
11229 	if (!nd_load(ndp,
11230 	    "tcp_close_wait_interval(obsoleted - "
11231 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11232 		nd_free(ndp);
11233 		return (B_FALSE);
11234 	}
11235 	return (B_TRUE);
11236 }
11237 
11238 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11239 /* ARGSUSED */
11240 static int
11241 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11242     cred_t *cr)
11243 {
11244 	long new_value;
11245 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11246 
11247 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11248 	    new_value < tcppa->tcp_param_min ||
11249 	    new_value > tcppa->tcp_param_max) {
11250 		return (EINVAL);
11251 	}
11252 	/*
11253 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11254 	 * round it up.  For future 64 bit requirement, we actually make it
11255 	 * a multiple of 8.
11256 	 */
11257 	if (new_value & 0x7) {
11258 		new_value = (new_value & ~0x7) + 0x8;
11259 	}
11260 	tcppa->tcp_param_val = new_value;
11261 	return (0);
11262 }
11263 
11264 /* Set callback routine passed to nd_load by tcp_param_register */
11265 /* ARGSUSED */
11266 static int
11267 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11268 {
11269 	long	new_value;
11270 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11271 
11272 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11273 	    new_value < tcppa->tcp_param_min ||
11274 	    new_value > tcppa->tcp_param_max) {
11275 		return (EINVAL);
11276 	}
11277 	tcppa->tcp_param_val = new_value;
11278 	return (0);
11279 }
11280 
11281 /*
11282  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11283  * is filled, return as much as we can.  The message passed in may be
11284  * multi-part, chained using b_cont.  "start" is the starting sequence
11285  * number for this piece.
11286  */
11287 static mblk_t *
11288 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11289 {
11290 	uint32_t	end;
11291 	mblk_t		*mp1;
11292 	mblk_t		*mp2;
11293 	mblk_t		*next_mp;
11294 	uint32_t	u1;
11295 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11296 
11297 	/* Walk through all the new pieces. */
11298 	do {
11299 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11300 		    (uintptr_t)INT_MAX);
11301 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11302 		next_mp = mp->b_cont;
11303 		if (start == end) {
11304 			/* Empty.  Blast it. */
11305 			freeb(mp);
11306 			continue;
11307 		}
11308 		mp->b_cont = NULL;
11309 		TCP_REASS_SET_SEQ(mp, start);
11310 		TCP_REASS_SET_END(mp, end);
11311 		mp1 = tcp->tcp_reass_tail;
11312 		if (!mp1) {
11313 			tcp->tcp_reass_tail = mp;
11314 			tcp->tcp_reass_head = mp;
11315 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11316 			UPDATE_MIB(&tcps->tcps_mib,
11317 			    tcpInDataUnorderBytes, end - start);
11318 			continue;
11319 		}
11320 		/* New stuff completely beyond tail? */
11321 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11322 			/* Link it on end. */
11323 			mp1->b_cont = mp;
11324 			tcp->tcp_reass_tail = mp;
11325 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11326 			UPDATE_MIB(&tcps->tcps_mib,
11327 			    tcpInDataUnorderBytes, end - start);
11328 			continue;
11329 		}
11330 		mp1 = tcp->tcp_reass_head;
11331 		u1 = TCP_REASS_SEQ(mp1);
11332 		/* New stuff at the front? */
11333 		if (SEQ_LT(start, u1)) {
11334 			/* Yes... Check for overlap. */
11335 			mp->b_cont = mp1;
11336 			tcp->tcp_reass_head = mp;
11337 			tcp_reass_elim_overlap(tcp, mp);
11338 			continue;
11339 		}
11340 		/*
11341 		 * The new piece fits somewhere between the head and tail.
11342 		 * We find our slot, where mp1 precedes us and mp2 trails.
11343 		 */
11344 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11345 			u1 = TCP_REASS_SEQ(mp2);
11346 			if (SEQ_LEQ(start, u1))
11347 				break;
11348 		}
11349 		/* Link ourselves in */
11350 		mp->b_cont = mp2;
11351 		mp1->b_cont = mp;
11352 
11353 		/* Trim overlap with following mblk(s) first */
11354 		tcp_reass_elim_overlap(tcp, mp);
11355 
11356 		/* Trim overlap with preceding mblk */
11357 		tcp_reass_elim_overlap(tcp, mp1);
11358 
11359 	} while (start = end, mp = next_mp);
11360 	mp1 = tcp->tcp_reass_head;
11361 	/* Anything ready to go? */
11362 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11363 		return (NULL);
11364 	/* Eat what we can off the queue */
11365 	for (;;) {
11366 		mp = mp1->b_cont;
11367 		end = TCP_REASS_END(mp1);
11368 		TCP_REASS_SET_SEQ(mp1, 0);
11369 		TCP_REASS_SET_END(mp1, 0);
11370 		if (!mp) {
11371 			tcp->tcp_reass_tail = NULL;
11372 			break;
11373 		}
11374 		if (end != TCP_REASS_SEQ(mp)) {
11375 			mp1->b_cont = NULL;
11376 			break;
11377 		}
11378 		mp1 = mp;
11379 	}
11380 	mp1 = tcp->tcp_reass_head;
11381 	tcp->tcp_reass_head = mp;
11382 	return (mp1);
11383 }
11384 
11385 /* Eliminate any overlap that mp may have over later mblks */
11386 static void
11387 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11388 {
11389 	uint32_t	end;
11390 	mblk_t		*mp1;
11391 	uint32_t	u1;
11392 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11393 
11394 	end = TCP_REASS_END(mp);
11395 	while ((mp1 = mp->b_cont) != NULL) {
11396 		u1 = TCP_REASS_SEQ(mp1);
11397 		if (!SEQ_GT(end, u1))
11398 			break;
11399 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11400 			mp->b_wptr -= end - u1;
11401 			TCP_REASS_SET_END(mp, u1);
11402 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11403 			UPDATE_MIB(&tcps->tcps_mib,
11404 			    tcpInDataPartDupBytes, end - u1);
11405 			break;
11406 		}
11407 		mp->b_cont = mp1->b_cont;
11408 		TCP_REASS_SET_SEQ(mp1, 0);
11409 		TCP_REASS_SET_END(mp1, 0);
11410 		freeb(mp1);
11411 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11412 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11413 	}
11414 	if (!mp1)
11415 		tcp->tcp_reass_tail = mp;
11416 }
11417 
11418 static uint_t
11419 tcp_rwnd_reopen(tcp_t *tcp)
11420 {
11421 	uint_t ret = 0;
11422 	uint_t thwin;
11423 
11424 	/* Learn the latest rwnd information that we sent to the other side. */
11425 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11426 	    << tcp->tcp_rcv_ws;
11427 	/* This is peer's calculated send window (our receive window). */
11428 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11429 	/*
11430 	 * Increase the receive window to max.  But we need to do receiver
11431 	 * SWS avoidance.  This means that we need to check the increase of
11432 	 * of receive window is at least 1 MSS.
11433 	 */
11434 	if (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss) {
11435 		/*
11436 		 * If the window that the other side knows is less than max
11437 		 * deferred acks segments, send an update immediately.
11438 		 */
11439 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11440 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
11441 			ret = TH_ACK_NEEDED;
11442 		}
11443 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
11444 	}
11445 	return (ret);
11446 }
11447 
11448 /*
11449  * Send up all messages queued on tcp_rcv_list.
11450  */
11451 static uint_t
11452 tcp_rcv_drain(tcp_t *tcp)
11453 {
11454 	mblk_t *mp;
11455 	uint_t ret = 0;
11456 #ifdef DEBUG
11457 	uint_t cnt = 0;
11458 #endif
11459 	queue_t	*q = tcp->tcp_rq;
11460 
11461 	/* Can't drain on an eager connection */
11462 	if (tcp->tcp_listener != NULL)
11463 		return (ret);
11464 
11465 	/* Can't be a non-STREAMS connection or sodirect enabled */
11466 	ASSERT((!IPCL_IS_NONSTR(tcp->tcp_connp)) && SOD_NOT_ENABLED(tcp));
11467 
11468 	/* No need for the push timer now. */
11469 	if (tcp->tcp_push_tid != 0) {
11470 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11471 		tcp->tcp_push_tid = 0;
11472 	}
11473 
11474 	/*
11475 	 * Handle two cases here: we are currently fused or we were
11476 	 * previously fused and have some urgent data to be delivered
11477 	 * upstream.  The latter happens because we either ran out of
11478 	 * memory or were detached and therefore sending the SIGURG was
11479 	 * deferred until this point.  In either case we pass control
11480 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11481 	 * some work.
11482 	 */
11483 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11484 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
11485 		    tcp->tcp_fused_sigurg_mp != NULL);
11486 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11487 		    &tcp->tcp_fused_sigurg_mp))
11488 			return (ret);
11489 	}
11490 
11491 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11492 		tcp->tcp_rcv_list = mp->b_next;
11493 		mp->b_next = NULL;
11494 #ifdef DEBUG
11495 		cnt += msgdsize(mp);
11496 #endif
11497 		/* Does this need SSL processing first? */
11498 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11499 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11500 			    mblk_t *, mp);
11501 			tcp_kssl_input(tcp, mp);
11502 			continue;
11503 		}
11504 		putnext(q, mp);
11505 	}
11506 #ifdef DEBUG
11507 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11508 #endif
11509 	tcp->tcp_rcv_last_head = NULL;
11510 	tcp->tcp_rcv_last_tail = NULL;
11511 	tcp->tcp_rcv_cnt = 0;
11512 
11513 	if (canputnext(q))
11514 		return (tcp_rwnd_reopen(tcp));
11515 
11516 	return (ret);
11517 }
11518 
11519 /*
11520  * Queue data on tcp_rcv_list which is a b_next chain.
11521  * tcp_rcv_last_head/tail is the last element of this chain.
11522  * Each element of the chain is a b_cont chain.
11523  *
11524  * M_DATA messages are added to the current element.
11525  * Other messages are added as new (b_next) elements.
11526  */
11527 void
11528 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11529 {
11530 	ASSERT(seg_len == msgdsize(mp));
11531 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11532 
11533 	if (tcp->tcp_rcv_list == NULL) {
11534 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11535 		tcp->tcp_rcv_list = mp;
11536 		tcp->tcp_rcv_last_head = mp;
11537 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11538 		tcp->tcp_rcv_last_tail->b_cont = mp;
11539 	} else {
11540 		tcp->tcp_rcv_last_head->b_next = mp;
11541 		tcp->tcp_rcv_last_head = mp;
11542 	}
11543 
11544 	while (mp->b_cont)
11545 		mp = mp->b_cont;
11546 
11547 	tcp->tcp_rcv_last_tail = mp;
11548 	tcp->tcp_rcv_cnt += seg_len;
11549 	tcp->tcp_rwnd -= seg_len;
11550 }
11551 
11552 /*
11553  * The tcp_rcv_sod_XXX() functions enqueue data directly to the socket
11554  * above, in addition when uioa is enabled schedule an asynchronous uio
11555  * prior to enqueuing. They implement the combinhed semantics of the
11556  * tcp_rcv_XXX() functions, tcp_rcv_list push logic, and STREAMS putnext()
11557  * canputnext(), i.e. flow-control with backenable.
11558  *
11559  * tcp_sod_wakeup() is called where tcp_rcv_drain() would be called in the
11560  * non sodirect connection but as there are no tcp_tcv_list mblk_t's we deal
11561  * with the rcv_wnd and push timer and call the sodirect wakeup function.
11562  *
11563  * Must be called with sodp->sod_lockp held and will return with the lock
11564  * released.
11565  */
11566 static uint_t
11567 tcp_rcv_sod_wakeup(tcp_t *tcp, sodirect_t *sodp)
11568 {
11569 	queue_t		*q = tcp->tcp_rq;
11570 	uint_t		thwin;
11571 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11572 	uint_t		ret = 0;
11573 
11574 	/* Can't be an eager connection */
11575 	ASSERT(tcp->tcp_listener == NULL);
11576 
11577 	/* Caller must have lock held */
11578 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11579 
11580 	/* Sodirect mode so must not be a tcp_rcv_list */
11581 	ASSERT(tcp->tcp_rcv_list == NULL);
11582 
11583 	if (SOD_QFULL(sodp)) {
11584 		/* Q is full, mark Q for need backenable */
11585 		SOD_QSETBE(sodp);
11586 	}
11587 	/* Last advertised rwnd, i.e. rwnd last sent in a packet */
11588 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11589 	    << tcp->tcp_rcv_ws;
11590 	/* This is peer's calculated send window (our available rwnd). */
11591 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11592 	/*
11593 	 * Increase the receive window to max.  But we need to do receiver
11594 	 * SWS avoidance.  This means that we need to check the increase of
11595 	 * of receive window is at least 1 MSS.
11596 	 */
11597 	if (!SOD_QFULL(sodp) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11598 		/*
11599 		 * If the window that the other side knows is less than max
11600 		 * deferred acks segments, send an update immediately.
11601 		 */
11602 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11603 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11604 			ret = TH_ACK_NEEDED;
11605 		}
11606 		tcp->tcp_rwnd = q->q_hiwat;
11607 	}
11608 
11609 	if (!SOD_QEMPTY(sodp)) {
11610 		/* Wakeup to socket */
11611 		sodp->sod_state &= SOD_WAKE_CLR;
11612 		sodp->sod_state |= SOD_WAKE_DONE;
11613 		(sodp->sod_wakeup)(sodp);
11614 		/* wakeup() does the mutex_ext() */
11615 	} else {
11616 		/* Q is empty, no need to wake */
11617 		sodp->sod_state &= SOD_WAKE_CLR;
11618 		sodp->sod_state |= SOD_WAKE_NOT;
11619 		mutex_exit(sodp->sod_lockp);
11620 	}
11621 
11622 	/* No need for the push timer now. */
11623 	if (tcp->tcp_push_tid != 0) {
11624 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11625 		tcp->tcp_push_tid = 0;
11626 	}
11627 
11628 	return (ret);
11629 }
11630 
11631 /*
11632  * Called where tcp_rcv_enqueue()/putnext(RD(q)) would be. For M_DATA
11633  * mblk_t's if uioa enabled then start a uioa asynchronous copy directly
11634  * to the user-land buffer and flag the mblk_t as such.
11635  *
11636  * Also, handle tcp_rwnd.
11637  */
11638 uint_t
11639 tcp_rcv_sod_enqueue(tcp_t *tcp, sodirect_t *sodp, mblk_t *mp, uint_t seg_len)
11640 {
11641 	uioa_t		*uioap = &sodp->sod_uioa;
11642 	boolean_t	qfull;
11643 	uint_t		thwin;
11644 
11645 	/* Can't be an eager connection */
11646 	ASSERT(tcp->tcp_listener == NULL);
11647 
11648 	/* Caller must have lock held */
11649 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11650 
11651 	/* Sodirect mode so must not be a tcp_rcv_list */
11652 	ASSERT(tcp->tcp_rcv_list == NULL);
11653 
11654 	/* Passed in segment length must be equal to mblk_t chain data size */
11655 	ASSERT(seg_len == msgdsize(mp));
11656 
11657 	if (DB_TYPE(mp) != M_DATA) {
11658 		/* Only process M_DATA mblk_t's */
11659 		goto enq;
11660 	}
11661 	if (uioap->uioa_state & UIOA_ENABLED) {
11662 		/* Uioa is enabled */
11663 		mblk_t		*mp1 = mp;
11664 		mblk_t		*lmp = NULL;
11665 
11666 		if (seg_len > uioap->uio_resid) {
11667 			/*
11668 			 * There isn't enough uio space for the mblk_t chain
11669 			 * so disable uioa such that this and any additional
11670 			 * mblk_t data is handled by the socket and schedule
11671 			 * the socket for wakeup to finish this uioa.
11672 			 */
11673 			uioap->uioa_state &= UIOA_CLR;
11674 			uioap->uioa_state |= UIOA_FINI;
11675 			if (sodp->sod_state & SOD_WAKE_NOT) {
11676 				sodp->sod_state &= SOD_WAKE_CLR;
11677 				sodp->sod_state |= SOD_WAKE_NEED;
11678 			}
11679 			goto enq;
11680 		}
11681 		do {
11682 			uint32_t	len = MBLKL(mp1);
11683 
11684 			if (!uioamove(mp1->b_rptr, len, UIO_READ, uioap)) {
11685 				/* Scheduled, mark dblk_t as such */
11686 				DB_FLAGS(mp1) |= DBLK_UIOA;
11687 			} else {
11688 				/* Error, turn off async processing */
11689 				uioap->uioa_state &= UIOA_CLR;
11690 				uioap->uioa_state |= UIOA_FINI;
11691 				break;
11692 			}
11693 			lmp = mp1;
11694 		} while ((mp1 = mp1->b_cont) != NULL);
11695 
11696 		if (mp1 != NULL || uioap->uio_resid == 0) {
11697 			/*
11698 			 * Not all mblk_t(s) uioamoved (error) or all uio
11699 			 * space has been consumed so schedule the socket
11700 			 * for wakeup to finish this uio.
11701 			 */
11702 			sodp->sod_state &= SOD_WAKE_CLR;
11703 			sodp->sod_state |= SOD_WAKE_NEED;
11704 
11705 			/* Break the mblk chain if neccessary. */
11706 			if (mp1 != NULL && lmp != NULL) {
11707 				mp->b_next = mp1;
11708 				lmp->b_cont = NULL;
11709 			}
11710 		}
11711 	} else if (uioap->uioa_state & UIOA_FINI) {
11712 		/*
11713 		 * Post UIO_ENABLED waiting for socket to finish processing
11714 		 * so just enqueue and update tcp_rwnd.
11715 		 */
11716 		if (SOD_QFULL(sodp))
11717 			tcp->tcp_rwnd -= seg_len;
11718 	} else if (sodp->sod_want > 0) {
11719 		/*
11720 		 * Uioa isn't enabled but sodirect has a pending read().
11721 		 */
11722 		if (SOD_QCNT(sodp) + seg_len >= sodp->sod_want) {
11723 			if (sodp->sod_state & SOD_WAKE_NOT) {
11724 				/* Schedule socket for wakeup */
11725 				sodp->sod_state &= SOD_WAKE_CLR;
11726 				sodp->sod_state |= SOD_WAKE_NEED;
11727 			}
11728 			tcp->tcp_rwnd -= seg_len;
11729 		}
11730 	} else if (SOD_QCNT(sodp) + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
11731 		/*
11732 		 * No pending sodirect read() so used the default
11733 		 * TCP push logic to guess that a push is needed.
11734 		 */
11735 		if (sodp->sod_state & SOD_WAKE_NOT) {
11736 			/* Schedule socket for wakeup */
11737 			sodp->sod_state &= SOD_WAKE_CLR;
11738 			sodp->sod_state |= SOD_WAKE_NEED;
11739 		}
11740 		tcp->tcp_rwnd -= seg_len;
11741 	} else {
11742 		/* Just update tcp_rwnd */
11743 		tcp->tcp_rwnd -= seg_len;
11744 	}
11745 enq:
11746 	qfull = SOD_QFULL(sodp);
11747 
11748 	(sodp->sod_enqueue)(sodp, mp);
11749 
11750 	if (! qfull && SOD_QFULL(sodp)) {
11751 		/* Wasn't QFULL, now QFULL, need back-enable */
11752 		SOD_QSETBE(sodp);
11753 	}
11754 
11755 	/*
11756 	 * Check to see if remote avail swnd < mss due to delayed ACK,
11757 	 * first get advertised rwnd.
11758 	 */
11759 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win));
11760 	/* Minus delayed ACK count */
11761 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11762 	if (thwin < tcp->tcp_mss) {
11763 		/* Remote avail swnd < mss, need ACK now */
11764 		return (TH_ACK_NEEDED);
11765 	}
11766 
11767 	return (0);
11768 }
11769 
11770 /*
11771  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11772  *
11773  * This is the default entry function into TCP on the read side. TCP is
11774  * always entered via squeue i.e. using squeue's for mutual exclusion.
11775  * When classifier does a lookup to find the tcp, it also puts a reference
11776  * on the conn structure associated so the tcp is guaranteed to exist
11777  * when we come here. We still need to check the state because it might
11778  * as well has been closed. The squeue processing function i.e. squeue_enter,
11779  * is responsible for doing the CONN_DEC_REF.
11780  *
11781  * Apart from the default entry point, IP also sends packets directly to
11782  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11783  * connections.
11784  */
11785 boolean_t tcp_outbound_squeue_switch = B_FALSE;
11786 void
11787 tcp_input(void *arg, mblk_t *mp, void *arg2)
11788 {
11789 	conn_t	*connp = (conn_t *)arg;
11790 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11791 
11792 	/* arg2 is the sqp */
11793 	ASSERT(arg2 != NULL);
11794 	ASSERT(mp != NULL);
11795 
11796 	/*
11797 	 * Don't accept any input on a closed tcp as this TCP logically does
11798 	 * not exist on the system. Don't proceed further with this TCP.
11799 	 * For eg. this packet could trigger another close of this tcp
11800 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11801 	 * tcp_clean_death / tcp_closei_local must be called at most once
11802 	 * on a TCP. In this case we need to refeed the packet into the
11803 	 * classifier and figure out where the packet should go. Need to
11804 	 * preserve the recv_ill somehow. Until we figure that out, for
11805 	 * now just drop the packet if we can't classify the packet.
11806 	 */
11807 	if (tcp->tcp_state == TCPS_CLOSED ||
11808 	    tcp->tcp_state == TCPS_BOUND) {
11809 		conn_t	*new_connp;
11810 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11811 
11812 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11813 		if (new_connp != NULL) {
11814 			tcp_reinput(new_connp, mp, arg2);
11815 			return;
11816 		}
11817 		/* We failed to classify. For now just drop the packet */
11818 		freemsg(mp);
11819 		return;
11820 	}
11821 
11822 	if (DB_TYPE(mp) != M_DATA) {
11823 		tcp_rput_common(tcp, mp);
11824 		return;
11825 	}
11826 
11827 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
11828 		squeue_t	*final_sqp;
11829 
11830 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
11831 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
11832 		DB_CKSUMSTART(mp) = 0;
11833 		if (tcp->tcp_state == TCPS_SYN_SENT &&
11834 		    connp->conn_final_sqp == NULL &&
11835 		    tcp_outbound_squeue_switch) {
11836 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
11837 			connp->conn_final_sqp = final_sqp;
11838 			if (connp->conn_final_sqp != connp->conn_sqp) {
11839 				CONN_INC_REF(connp);
11840 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
11841 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
11842 				    tcp_rput_data, connp, ip_squeue_flag,
11843 				    SQTAG_CONNECT_FINISH);
11844 				return;
11845 			}
11846 		}
11847 	}
11848 	tcp_rput_data(connp, mp, arg2);
11849 }
11850 
11851 /*
11852  * The read side put procedure.
11853  * The packets passed up by ip are assume to be aligned according to
11854  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11855  */
11856 static void
11857 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11858 {
11859 	/*
11860 	 * tcp_rput_data() does not expect M_CTL except for the case
11861 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11862 	 * type. Need to make sure that any other M_CTLs don't make
11863 	 * it to tcp_rput_data since it is not expecting any and doesn't
11864 	 * check for it.
11865 	 */
11866 	if (DB_TYPE(mp) == M_CTL) {
11867 		switch (*(uint32_t *)(mp->b_rptr)) {
11868 		case TCP_IOC_ABORT_CONN:
11869 			/*
11870 			 * Handle connection abort request.
11871 			 */
11872 			tcp_ioctl_abort_handler(tcp, mp);
11873 			return;
11874 		case IPSEC_IN:
11875 			/*
11876 			 * Only secure icmp arrive in TCP and they
11877 			 * don't go through data path.
11878 			 */
11879 			tcp_icmp_error(tcp, mp);
11880 			return;
11881 		case IN_PKTINFO:
11882 			/*
11883 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11884 			 * sockets that are receiving IPv4 traffic. tcp
11885 			 */
11886 			ASSERT(tcp->tcp_family == AF_INET6);
11887 			ASSERT(tcp->tcp_ipv6_recvancillary &
11888 			    TCP_IPV6_RECVPKTINFO);
11889 			tcp_rput_data(tcp->tcp_connp, mp,
11890 			    tcp->tcp_connp->conn_sqp);
11891 			return;
11892 		case MDT_IOC_INFO_UPDATE:
11893 			/*
11894 			 * Handle Multidata information update; the
11895 			 * following routine will free the message.
11896 			 */
11897 			if (tcp->tcp_connp->conn_mdt_ok) {
11898 				tcp_mdt_update(tcp,
11899 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11900 				    B_FALSE);
11901 			}
11902 			freemsg(mp);
11903 			return;
11904 		case LSO_IOC_INFO_UPDATE:
11905 			/*
11906 			 * Handle LSO information update; the following
11907 			 * routine will free the message.
11908 			 */
11909 			if (tcp->tcp_connp->conn_lso_ok) {
11910 				tcp_lso_update(tcp,
11911 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11912 			}
11913 			freemsg(mp);
11914 			return;
11915 		default:
11916 			/*
11917 			 * tcp_icmp_err() will process the M_CTL packets.
11918 			 * Non-ICMP packets, if any, will be discarded in
11919 			 * tcp_icmp_err(). We will process the ICMP packet
11920 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11921 			 * incoming ICMP packet may result in changing
11922 			 * the tcp_mss, which we would need if we have
11923 			 * packets to retransmit.
11924 			 */
11925 			tcp_icmp_error(tcp, mp);
11926 			return;
11927 		}
11928 	}
11929 
11930 	/* No point processing the message if tcp is already closed */
11931 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11932 		freemsg(mp);
11933 		return;
11934 	}
11935 
11936 	tcp_rput_other(tcp, mp);
11937 }
11938 
11939 
11940 /* The minimum of smoothed mean deviation in RTO calculation. */
11941 #define	TCP_SD_MIN	400
11942 
11943 /*
11944  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11945  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11946  * are the same as those in Appendix A.2 of that paper.
11947  *
11948  * m = new measurement
11949  * sa = smoothed RTT average (8 * average estimates).
11950  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11951  */
11952 static void
11953 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11954 {
11955 	long m = TICK_TO_MSEC(rtt);
11956 	clock_t sa = tcp->tcp_rtt_sa;
11957 	clock_t sv = tcp->tcp_rtt_sd;
11958 	clock_t rto;
11959 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11960 
11961 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11962 	tcp->tcp_rtt_update++;
11963 
11964 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11965 	if (sa != 0) {
11966 		/*
11967 		 * Update average estimator:
11968 		 *	new rtt = 7/8 old rtt + 1/8 Error
11969 		 */
11970 
11971 		/* m is now Error in estimate. */
11972 		m -= sa >> 3;
11973 		if ((sa += m) <= 0) {
11974 			/*
11975 			 * Don't allow the smoothed average to be negative.
11976 			 * We use 0 to denote reinitialization of the
11977 			 * variables.
11978 			 */
11979 			sa = 1;
11980 		}
11981 
11982 		/*
11983 		 * Update deviation estimator:
11984 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11985 		 */
11986 		if (m < 0)
11987 			m = -m;
11988 		m -= sv >> 2;
11989 		sv += m;
11990 	} else {
11991 		/*
11992 		 * This follows BSD's implementation.  So the reinitialized
11993 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11994 		 * link is bandwidth dominated, doubling the window size
11995 		 * during slow start means doubling the RTT.  We want to be
11996 		 * more conservative when we reinitialize our estimates.  3
11997 		 * is just a convenient number.
11998 		 */
11999 		sa = m << 3;
12000 		sv = m << 1;
12001 	}
12002 	if (sv < TCP_SD_MIN) {
12003 		/*
12004 		 * We do not know that if sa captures the delay ACK
12005 		 * effect as in a long train of segments, a receiver
12006 		 * does not delay its ACKs.  So set the minimum of sv
12007 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
12008 		 * of BSD DATO.  That means the minimum of mean
12009 		 * deviation is 100 ms.
12010 		 *
12011 		 */
12012 		sv = TCP_SD_MIN;
12013 	}
12014 	tcp->tcp_rtt_sa = sa;
12015 	tcp->tcp_rtt_sd = sv;
12016 	/*
12017 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
12018 	 *
12019 	 * Add tcp_rexmit_interval extra in case of extreme environment
12020 	 * where the algorithm fails to work.  The default value of
12021 	 * tcp_rexmit_interval_extra should be 0.
12022 	 *
12023 	 * As we use a finer grained clock than BSD and update
12024 	 * RTO for every ACKs, add in another .25 of RTT to the
12025 	 * deviation of RTO to accomodate burstiness of 1/4 of
12026 	 * window size.
12027 	 */
12028 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
12029 
12030 	if (rto > tcps->tcps_rexmit_interval_max) {
12031 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
12032 	} else if (rto < tcps->tcps_rexmit_interval_min) {
12033 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
12034 	} else {
12035 		tcp->tcp_rto = rto;
12036 	}
12037 
12038 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12039 	tcp->tcp_timer_backoff = 0;
12040 }
12041 
12042 /*
12043  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12044  * send queue which starts at the given seq. no.
12045  *
12046  * Parameters:
12047  *	tcp_t *tcp: the tcp instance pointer.
12048  *	uint32_t seq: the starting seq. no of the requested segment.
12049  *	int32_t *off: after the execution, *off will be the offset to
12050  *		the returned mblk which points to the requested seq no.
12051  *		It is the caller's responsibility to send in a non-null off.
12052  *
12053  * Return:
12054  *	A mblk_t pointer pointing to the requested segment in send queue.
12055  */
12056 static mblk_t *
12057 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12058 {
12059 	int32_t	cnt;
12060 	mblk_t	*mp;
12061 
12062 	/* Defensive coding.  Make sure we don't send incorrect data. */
12063 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12064 		return (NULL);
12065 
12066 	cnt = seq - tcp->tcp_suna;
12067 	mp = tcp->tcp_xmit_head;
12068 	while (cnt > 0 && mp != NULL) {
12069 		cnt -= mp->b_wptr - mp->b_rptr;
12070 		if (cnt < 0) {
12071 			cnt += mp->b_wptr - mp->b_rptr;
12072 			break;
12073 		}
12074 		mp = mp->b_cont;
12075 	}
12076 	ASSERT(mp != NULL);
12077 	*off = cnt;
12078 	return (mp);
12079 }
12080 
12081 /*
12082  * This function handles all retransmissions if SACK is enabled for this
12083  * connection.  First it calculates how many segments can be retransmitted
12084  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12085  * segments.  A segment is eligible if sack_cnt for that segment is greater
12086  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12087  * all eligible segments, it checks to see if TCP can send some new segments
12088  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12089  *
12090  * Parameters:
12091  *	tcp_t *tcp: the tcp structure of the connection.
12092  *	uint_t *flags: in return, appropriate value will be set for
12093  *	tcp_rput_data().
12094  */
12095 static void
12096 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12097 {
12098 	notsack_blk_t	*notsack_blk;
12099 	int32_t		usable_swnd;
12100 	int32_t		mss;
12101 	uint32_t	seg_len;
12102 	mblk_t		*xmit_mp;
12103 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12104 
12105 	ASSERT(tcp->tcp_sack_info != NULL);
12106 	ASSERT(tcp->tcp_notsack_list != NULL);
12107 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12108 
12109 	/* Defensive coding in case there is a bug... */
12110 	if (tcp->tcp_notsack_list == NULL) {
12111 		return;
12112 	}
12113 	notsack_blk = tcp->tcp_notsack_list;
12114 	mss = tcp->tcp_mss;
12115 
12116 	/*
12117 	 * Limit the num of outstanding data in the network to be
12118 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12119 	 */
12120 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12121 
12122 	/* At least retransmit 1 MSS of data. */
12123 	if (usable_swnd <= 0) {
12124 		usable_swnd = mss;
12125 	}
12126 
12127 	/* Make sure no new RTT samples will be taken. */
12128 	tcp->tcp_csuna = tcp->tcp_snxt;
12129 
12130 	notsack_blk = tcp->tcp_notsack_list;
12131 	while (usable_swnd > 0) {
12132 		mblk_t		*snxt_mp, *tmp_mp;
12133 		tcp_seq		begin = tcp->tcp_sack_snxt;
12134 		tcp_seq		end;
12135 		int32_t		off;
12136 
12137 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12138 			if (SEQ_GT(notsack_blk->end, begin) &&
12139 			    (notsack_blk->sack_cnt >=
12140 			    tcps->tcps_dupack_fast_retransmit)) {
12141 				end = notsack_blk->end;
12142 				if (SEQ_LT(begin, notsack_blk->begin)) {
12143 					begin = notsack_blk->begin;
12144 				}
12145 				break;
12146 			}
12147 		}
12148 		/*
12149 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12150 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12151 		 * set to tcp_cwnd_ssthresh.
12152 		 */
12153 		if (notsack_blk == NULL) {
12154 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12155 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12156 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12157 				ASSERT(tcp->tcp_cwnd > 0);
12158 				return;
12159 			} else {
12160 				usable_swnd = usable_swnd / mss;
12161 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12162 				    MAX(usable_swnd * mss, mss);
12163 				*flags |= TH_XMIT_NEEDED;
12164 				return;
12165 			}
12166 		}
12167 
12168 		/*
12169 		 * Note that we may send more than usable_swnd allows here
12170 		 * because of round off, but no more than 1 MSS of data.
12171 		 */
12172 		seg_len = end - begin;
12173 		if (seg_len > mss)
12174 			seg_len = mss;
12175 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12176 		ASSERT(snxt_mp != NULL);
12177 		/* This should not happen.  Defensive coding again... */
12178 		if (snxt_mp == NULL) {
12179 			return;
12180 		}
12181 
12182 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12183 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12184 		if (xmit_mp == NULL)
12185 			return;
12186 
12187 		usable_swnd -= seg_len;
12188 		tcp->tcp_pipe += seg_len;
12189 		tcp->tcp_sack_snxt = begin + seg_len;
12190 
12191 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12192 
12193 		/*
12194 		 * Update the send timestamp to avoid false retransmission.
12195 		 */
12196 		snxt_mp->b_prev = (mblk_t *)lbolt;
12197 
12198 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12199 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12200 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12201 		/*
12202 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12203 		 * This happens when new data sent during fast recovery is
12204 		 * also lost.  If TCP retransmits those new data, it needs
12205 		 * to extend SACK recover phase to avoid starting another
12206 		 * fast retransmit/recovery unnecessarily.
12207 		 */
12208 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12209 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12210 		}
12211 	}
12212 }
12213 
12214 /*
12215  * This function handles policy checking at TCP level for non-hard_bound/
12216  * detached connections.
12217  */
12218 static boolean_t
12219 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12220     boolean_t secure, boolean_t mctl_present)
12221 {
12222 	ipsec_latch_t *ipl = NULL;
12223 	ipsec_action_t *act = NULL;
12224 	mblk_t *data_mp;
12225 	ipsec_in_t *ii;
12226 	const char *reason;
12227 	kstat_named_t *counter;
12228 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12229 	ipsec_stack_t	*ipss;
12230 	ip_stack_t	*ipst;
12231 
12232 	ASSERT(mctl_present || !secure);
12233 
12234 	ASSERT((ipha == NULL && ip6h != NULL) ||
12235 	    (ip6h == NULL && ipha != NULL));
12236 
12237 	/*
12238 	 * We don't necessarily have an ipsec_in_act action to verify
12239 	 * policy because of assymetrical policy where we have only
12240 	 * outbound policy and no inbound policy (possible with global
12241 	 * policy).
12242 	 */
12243 	if (!secure) {
12244 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12245 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12246 			return (B_TRUE);
12247 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12248 		    "tcp_check_policy", ipha, ip6h, secure,
12249 		    tcps->tcps_netstack);
12250 		ipss = tcps->tcps_netstack->netstack_ipsec;
12251 
12252 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12253 		    DROPPER(ipss, ipds_tcp_clear),
12254 		    &tcps->tcps_dropper);
12255 		return (B_FALSE);
12256 	}
12257 
12258 	/*
12259 	 * We have a secure packet.
12260 	 */
12261 	if (act == NULL) {
12262 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12263 		    "tcp_check_policy", ipha, ip6h, secure,
12264 		    tcps->tcps_netstack);
12265 		ipss = tcps->tcps_netstack->netstack_ipsec;
12266 
12267 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12268 		    DROPPER(ipss, ipds_tcp_secure),
12269 		    &tcps->tcps_dropper);
12270 		return (B_FALSE);
12271 	}
12272 
12273 	/*
12274 	 * XXX This whole routine is currently incorrect.  ipl should
12275 	 * be set to the latch pointer, but is currently not set, so
12276 	 * we initialize it to NULL to avoid picking up random garbage.
12277 	 */
12278 	if (ipl == NULL)
12279 		return (B_TRUE);
12280 
12281 	data_mp = first_mp->b_cont;
12282 
12283 	ii = (ipsec_in_t *)first_mp->b_rptr;
12284 
12285 	ipst = tcps->tcps_netstack->netstack_ip;
12286 
12287 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12288 	    &counter, tcp->tcp_connp)) {
12289 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12290 		return (B_TRUE);
12291 	}
12292 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12293 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12294 	    reason);
12295 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12296 
12297 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12298 	    &tcps->tcps_dropper);
12299 	return (B_FALSE);
12300 }
12301 
12302 /*
12303  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12304  * retransmission after a timeout.
12305  *
12306  * To limit the number of duplicate segments, we limit the number of segment
12307  * to be sent in one time to tcp_snd_burst, the burst variable.
12308  */
12309 static void
12310 tcp_ss_rexmit(tcp_t *tcp)
12311 {
12312 	uint32_t	snxt;
12313 	uint32_t	smax;
12314 	int32_t		win;
12315 	int32_t		mss;
12316 	int32_t		off;
12317 	int32_t		burst = tcp->tcp_snd_burst;
12318 	mblk_t		*snxt_mp;
12319 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12320 
12321 	/*
12322 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12323 	 * all unack'ed segments.
12324 	 */
12325 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12326 		smax = tcp->tcp_rexmit_max;
12327 		snxt = tcp->tcp_rexmit_nxt;
12328 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12329 			snxt = tcp->tcp_suna;
12330 		}
12331 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12332 		win -= snxt - tcp->tcp_suna;
12333 		mss = tcp->tcp_mss;
12334 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12335 
12336 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12337 		    (burst > 0) && (snxt_mp != NULL)) {
12338 			mblk_t	*xmit_mp;
12339 			mblk_t	*old_snxt_mp = snxt_mp;
12340 			uint32_t cnt = mss;
12341 
12342 			if (win < cnt) {
12343 				cnt = win;
12344 			}
12345 			if (SEQ_GT(snxt + cnt, smax)) {
12346 				cnt = smax - snxt;
12347 			}
12348 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12349 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12350 			if (xmit_mp == NULL)
12351 				return;
12352 
12353 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12354 
12355 			snxt += cnt;
12356 			win -= cnt;
12357 			/*
12358 			 * Update the send timestamp to avoid false
12359 			 * retransmission.
12360 			 */
12361 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12362 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12363 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12364 
12365 			tcp->tcp_rexmit_nxt = snxt;
12366 			burst--;
12367 		}
12368 		/*
12369 		 * If we have transmitted all we have at the time
12370 		 * we started the retranmission, we can leave
12371 		 * the rest of the job to tcp_wput_data().  But we
12372 		 * need to check the send window first.  If the
12373 		 * win is not 0, go on with tcp_wput_data().
12374 		 */
12375 		if (SEQ_LT(snxt, smax) || win == 0) {
12376 			return;
12377 		}
12378 	}
12379 	/* Only call tcp_wput_data() if there is data to be sent. */
12380 	if (tcp->tcp_unsent) {
12381 		tcp_wput_data(tcp, NULL, B_FALSE);
12382 	}
12383 }
12384 
12385 /*
12386  * Process all TCP option in SYN segment.  Note that this function should
12387  * be called after tcp_adapt_ire() is called so that the necessary info
12388  * from IRE is already set in the tcp structure.
12389  *
12390  * This function sets up the correct tcp_mss value according to the
12391  * MSS option value and our header size.  It also sets up the window scale
12392  * and timestamp values, and initialize SACK info blocks.  But it does not
12393  * change receive window size after setting the tcp_mss value.  The caller
12394  * should do the appropriate change.
12395  */
12396 void
12397 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12398 {
12399 	int options;
12400 	tcp_opt_t tcpopt;
12401 	uint32_t mss_max;
12402 	char *tmp_tcph;
12403 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12404 
12405 	tcpopt.tcp = NULL;
12406 	options = tcp_parse_options(tcph, &tcpopt);
12407 
12408 	/*
12409 	 * Process MSS option.  Note that MSS option value does not account
12410 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12411 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12412 	 * IPv6.
12413 	 */
12414 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12415 		if (tcp->tcp_ipversion == IPV4_VERSION)
12416 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12417 		else
12418 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12419 	} else {
12420 		if (tcp->tcp_ipversion == IPV4_VERSION)
12421 			mss_max = tcps->tcps_mss_max_ipv4;
12422 		else
12423 			mss_max = tcps->tcps_mss_max_ipv6;
12424 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12425 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12426 		else if (tcpopt.tcp_opt_mss > mss_max)
12427 			tcpopt.tcp_opt_mss = mss_max;
12428 	}
12429 
12430 	/* Process Window Scale option. */
12431 	if (options & TCP_OPT_WSCALE_PRESENT) {
12432 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12433 		tcp->tcp_snd_ws_ok = B_TRUE;
12434 	} else {
12435 		tcp->tcp_snd_ws = B_FALSE;
12436 		tcp->tcp_snd_ws_ok = B_FALSE;
12437 		tcp->tcp_rcv_ws = B_FALSE;
12438 	}
12439 
12440 	/* Process Timestamp option. */
12441 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12442 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12443 		tmp_tcph = (char *)tcp->tcp_tcph;
12444 
12445 		tcp->tcp_snd_ts_ok = B_TRUE;
12446 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12447 		tcp->tcp_last_rcv_lbolt = lbolt64;
12448 		ASSERT(OK_32PTR(tmp_tcph));
12449 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12450 
12451 		/* Fill in our template header with basic timestamp option. */
12452 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12453 		tmp_tcph[0] = TCPOPT_NOP;
12454 		tmp_tcph[1] = TCPOPT_NOP;
12455 		tmp_tcph[2] = TCPOPT_TSTAMP;
12456 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12457 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12458 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12459 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12460 	} else {
12461 		tcp->tcp_snd_ts_ok = B_FALSE;
12462 	}
12463 
12464 	/*
12465 	 * Process SACK options.  If SACK is enabled for this connection,
12466 	 * then allocate the SACK info structure.  Note the following ways
12467 	 * when tcp_snd_sack_ok is set to true.
12468 	 *
12469 	 * For active connection: in tcp_adapt_ire() called in
12470 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12471 	 * is checked.
12472 	 *
12473 	 * For passive connection: in tcp_adapt_ire() called in
12474 	 * tcp_accept_comm().
12475 	 *
12476 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12477 	 * That check makes sure that if we did not send a SACK OK option,
12478 	 * we will not enable SACK for this connection even though the other
12479 	 * side sends us SACK OK option.  For active connection, the SACK
12480 	 * info structure has already been allocated.  So we need to free
12481 	 * it if SACK is disabled.
12482 	 */
12483 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12484 	    (tcp->tcp_snd_sack_ok ||
12485 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12486 		/* This should be true only in the passive case. */
12487 		if (tcp->tcp_sack_info == NULL) {
12488 			ASSERT(TCP_IS_DETACHED(tcp));
12489 			tcp->tcp_sack_info =
12490 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12491 		}
12492 		if (tcp->tcp_sack_info == NULL) {
12493 			tcp->tcp_snd_sack_ok = B_FALSE;
12494 		} else {
12495 			tcp->tcp_snd_sack_ok = B_TRUE;
12496 			if (tcp->tcp_snd_ts_ok) {
12497 				tcp->tcp_max_sack_blk = 3;
12498 			} else {
12499 				tcp->tcp_max_sack_blk = 4;
12500 			}
12501 		}
12502 	} else {
12503 		/*
12504 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12505 		 * no SACK info will be used for this
12506 		 * connection.  This assumes that SACK usage
12507 		 * permission is negotiated.  This may need
12508 		 * to be changed once this is clarified.
12509 		 */
12510 		if (tcp->tcp_sack_info != NULL) {
12511 			ASSERT(tcp->tcp_notsack_list == NULL);
12512 			kmem_cache_free(tcp_sack_info_cache,
12513 			    tcp->tcp_sack_info);
12514 			tcp->tcp_sack_info = NULL;
12515 		}
12516 		tcp->tcp_snd_sack_ok = B_FALSE;
12517 	}
12518 
12519 	/*
12520 	 * Now we know the exact TCP/IP header length, subtract
12521 	 * that from tcp_mss to get our side's MSS.
12522 	 */
12523 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12524 	/*
12525 	 * Here we assume that the other side's header size will be equal to
12526 	 * our header size.  We calculate the real MSS accordingly.  Need to
12527 	 * take into additional stuffs IPsec puts in.
12528 	 *
12529 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12530 	 */
12531 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12532 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12533 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12534 
12535 	/*
12536 	 * Set MSS to the smaller one of both ends of the connection.
12537 	 * We should not have called tcp_mss_set() before, but our
12538 	 * side of the MSS should have been set to a proper value
12539 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12540 	 * STREAM head parameters properly.
12541 	 *
12542 	 * If we have a larger-than-16-bit window but the other side
12543 	 * didn't want to do window scale, tcp_rwnd_set() will take
12544 	 * care of that.
12545 	 */
12546 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12547 }
12548 
12549 /*
12550  * Sends the T_CONN_IND to the listener. The caller calls this
12551  * functions via squeue to get inside the listener's perimeter
12552  * once the 3 way hand shake is done a T_CONN_IND needs to be
12553  * sent. As an optimization, the caller can call this directly
12554  * if listener's perimeter is same as eager's.
12555  */
12556 /* ARGSUSED */
12557 void
12558 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12559 {
12560 	conn_t			*lconnp = (conn_t *)arg;
12561 	tcp_t			*listener = lconnp->conn_tcp;
12562 	tcp_t			*tcp;
12563 	struct T_conn_ind	*conn_ind;
12564 	ipaddr_t 		*addr_cache;
12565 	boolean_t		need_send_conn_ind = B_FALSE;
12566 	tcp_stack_t		*tcps = listener->tcp_tcps;
12567 
12568 	/* retrieve the eager */
12569 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12570 	ASSERT(conn_ind->OPT_offset != 0 &&
12571 	    conn_ind->OPT_length == sizeof (intptr_t));
12572 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12573 	    conn_ind->OPT_length);
12574 
12575 	/*
12576 	 * TLI/XTI applications will get confused by
12577 	 * sending eager as an option since it violates
12578 	 * the option semantics. So remove the eager as
12579 	 * option since TLI/XTI app doesn't need it anyway.
12580 	 */
12581 	if (!TCP_IS_SOCKET(listener)) {
12582 		conn_ind->OPT_length = 0;
12583 		conn_ind->OPT_offset = 0;
12584 	}
12585 	if (listener->tcp_state == TCPS_CLOSED ||
12586 	    TCP_IS_DETACHED(listener)) {
12587 		/*
12588 		 * If listener has closed, it would have caused a
12589 		 * a cleanup/blowoff to happen for the eager. We
12590 		 * just need to return.
12591 		 */
12592 		freemsg(mp);
12593 		return;
12594 	}
12595 
12596 
12597 	/*
12598 	 * if the conn_req_q is full defer passing up the
12599 	 * T_CONN_IND until space is availabe after t_accept()
12600 	 * processing
12601 	 */
12602 	mutex_enter(&listener->tcp_eager_lock);
12603 
12604 	/*
12605 	 * Take the eager out, if it is in the list of droppable eagers
12606 	 * as we are here because the 3W handshake is over.
12607 	 */
12608 	MAKE_UNDROPPABLE(tcp);
12609 
12610 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12611 		tcp_t *tail;
12612 
12613 		/*
12614 		 * The eager already has an extra ref put in tcp_rput_data
12615 		 * so that it stays till accept comes back even though it
12616 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12617 		 */
12618 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12619 		listener->tcp_conn_req_cnt_q0--;
12620 		listener->tcp_conn_req_cnt_q++;
12621 
12622 		/* Move from SYN_RCVD to ESTABLISHED list  */
12623 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12624 		    tcp->tcp_eager_prev_q0;
12625 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12626 		    tcp->tcp_eager_next_q0;
12627 		tcp->tcp_eager_prev_q0 = NULL;
12628 		tcp->tcp_eager_next_q0 = NULL;
12629 
12630 		/*
12631 		 * Insert at end of the queue because sockfs
12632 		 * sends down T_CONN_RES in chronological
12633 		 * order. Leaving the older conn indications
12634 		 * at front of the queue helps reducing search
12635 		 * time.
12636 		 */
12637 		tail = listener->tcp_eager_last_q;
12638 		if (tail != NULL)
12639 			tail->tcp_eager_next_q = tcp;
12640 		else
12641 			listener->tcp_eager_next_q = tcp;
12642 		listener->tcp_eager_last_q = tcp;
12643 		tcp->tcp_eager_next_q = NULL;
12644 		/*
12645 		 * Delay sending up the T_conn_ind until we are
12646 		 * done with the eager. Once we have have sent up
12647 		 * the T_conn_ind, the accept can potentially complete
12648 		 * any time and release the refhold we have on the eager.
12649 		 */
12650 		need_send_conn_ind = B_TRUE;
12651 	} else {
12652 		/*
12653 		 * Defer connection on q0 and set deferred
12654 		 * connection bit true
12655 		 */
12656 		tcp->tcp_conn_def_q0 = B_TRUE;
12657 
12658 		/* take tcp out of q0 ... */
12659 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12660 		    tcp->tcp_eager_next_q0;
12661 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12662 		    tcp->tcp_eager_prev_q0;
12663 
12664 		/* ... and place it at the end of q0 */
12665 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12666 		tcp->tcp_eager_next_q0 = listener;
12667 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12668 		listener->tcp_eager_prev_q0 = tcp;
12669 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12670 	}
12671 
12672 	/* we have timed out before */
12673 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12674 		tcp->tcp_syn_rcvd_timeout = 0;
12675 		listener->tcp_syn_rcvd_timeout--;
12676 		if (listener->tcp_syn_defense &&
12677 		    listener->tcp_syn_rcvd_timeout <=
12678 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12679 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12680 		    listener->tcp_last_rcv_lbolt)) {
12681 			/*
12682 			 * Turn off the defense mode if we
12683 			 * believe the SYN attack is over.
12684 			 */
12685 			listener->tcp_syn_defense = B_FALSE;
12686 			if (listener->tcp_ip_addr_cache) {
12687 				kmem_free((void *)listener->tcp_ip_addr_cache,
12688 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12689 				listener->tcp_ip_addr_cache = NULL;
12690 			}
12691 		}
12692 	}
12693 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12694 	if (addr_cache != NULL) {
12695 		/*
12696 		 * We have finished a 3-way handshake with this
12697 		 * remote host. This proves the IP addr is good.
12698 		 * Cache it!
12699 		 */
12700 		addr_cache[IP_ADDR_CACHE_HASH(
12701 		    tcp->tcp_remote)] = tcp->tcp_remote;
12702 	}
12703 	mutex_exit(&listener->tcp_eager_lock);
12704 	if (need_send_conn_ind)
12705 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
12706 }
12707 
12708 /*
12709  * Send the newconn notification to ulp. The eager is blown off if the
12710  * notification fails.
12711  */
12712 static void
12713 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
12714 {
12715 	if (IPCL_IS_NONSTR(lconnp)) {
12716 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
12717 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
12718 		    lconnp->conn_tcp);
12719 
12720 		/* Keep the message around in case of a fallback to TPI */
12721 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
12722 
12723 		/*
12724 		 * Notify the ULP about the newconn. It is guaranteed that no
12725 		 * tcp_accept() call will be made for the eager if the
12726 		 * notification fails, so it's safe to blow it off in that
12727 		 * case.
12728 		 *
12729 		 * The upper handle will be assigned when tcp_accept() is
12730 		 * called.
12731 		 */
12732 		if ((*lconnp->conn_upcalls->su_newconn)
12733 		    (lconnp->conn_upper_handle,
12734 		    (sock_lower_handle_t)econnp,
12735 		    &sock_tcp_downcalls, DB_CRED(mp), DB_CPID(mp),
12736 		    &econnp->conn_upcalls) == NULL) {
12737 			/* Failed to allocate a socket */
12738 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
12739 			    tcpEstabResets);
12740 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
12741 			    econnp->conn_tcp->tcp_conn_req_seqnum);
12742 		}
12743 	} else {
12744 		putnext(lconnp->conn_tcp->tcp_rq, mp);
12745 	}
12746 }
12747 
12748 mblk_t *
12749 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12750     uint_t *ifindexp, ip6_pkt_t *ippp)
12751 {
12752 	ip_pktinfo_t	*pinfo;
12753 	ip6_t		*ip6h;
12754 	uchar_t		*rptr;
12755 	mblk_t		*first_mp = mp;
12756 	boolean_t	mctl_present = B_FALSE;
12757 	uint_t 		ifindex = 0;
12758 	ip6_pkt_t	ipp;
12759 	uint_t		ipvers;
12760 	uint_t		ip_hdr_len;
12761 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12762 
12763 	rptr = mp->b_rptr;
12764 	ASSERT(OK_32PTR(rptr));
12765 	ASSERT(tcp != NULL);
12766 	ipp.ipp_fields = 0;
12767 
12768 	switch DB_TYPE(mp) {
12769 	case M_CTL:
12770 		mp = mp->b_cont;
12771 		if (mp == NULL) {
12772 			freemsg(first_mp);
12773 			return (NULL);
12774 		}
12775 		if (DB_TYPE(mp) != M_DATA) {
12776 			freemsg(first_mp);
12777 			return (NULL);
12778 		}
12779 		mctl_present = B_TRUE;
12780 		break;
12781 	case M_DATA:
12782 		break;
12783 	default:
12784 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12785 		freemsg(mp);
12786 		return (NULL);
12787 	}
12788 	ipvers = IPH_HDR_VERSION(rptr);
12789 	if (ipvers == IPV4_VERSION) {
12790 		if (tcp == NULL) {
12791 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12792 			goto done;
12793 		}
12794 
12795 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12796 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12797 
12798 		/*
12799 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12800 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12801 		 */
12802 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12803 		    mctl_present) {
12804 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12805 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12806 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12807 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12808 				ipp.ipp_fields |= IPPF_IFINDEX;
12809 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12810 				ifindex = pinfo->ip_pkt_ifindex;
12811 			}
12812 			freeb(first_mp);
12813 			mctl_present = B_FALSE;
12814 		}
12815 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12816 	} else {
12817 		ip6h = (ip6_t *)rptr;
12818 
12819 		ASSERT(ipvers == IPV6_VERSION);
12820 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12821 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12822 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12823 
12824 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12825 			uint8_t	nexthdrp;
12826 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12827 
12828 			/* Look for ifindex information */
12829 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12830 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12831 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12832 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12833 					freemsg(first_mp);
12834 					return (NULL);
12835 				}
12836 
12837 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12838 					ASSERT(ip6i->ip6i_ifindex != 0);
12839 					ipp.ipp_fields |= IPPF_IFINDEX;
12840 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12841 					ifindex = ip6i->ip6i_ifindex;
12842 				}
12843 				rptr = (uchar_t *)&ip6i[1];
12844 				mp->b_rptr = rptr;
12845 				if (rptr == mp->b_wptr) {
12846 					mblk_t *mp1;
12847 					mp1 = mp->b_cont;
12848 					freeb(mp);
12849 					mp = mp1;
12850 					rptr = mp->b_rptr;
12851 				}
12852 				if (MBLKL(mp) < IPV6_HDR_LEN +
12853 				    sizeof (tcph_t)) {
12854 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12855 					freemsg(first_mp);
12856 					return (NULL);
12857 				}
12858 				ip6h = (ip6_t *)rptr;
12859 			}
12860 
12861 			/*
12862 			 * Find any potentially interesting extension headers
12863 			 * as well as the length of the IPv6 + extension
12864 			 * headers.
12865 			 */
12866 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12867 			/* Verify if this is a TCP packet */
12868 			if (nexthdrp != IPPROTO_TCP) {
12869 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12870 				freemsg(first_mp);
12871 				return (NULL);
12872 			}
12873 		} else {
12874 			ip_hdr_len = IPV6_HDR_LEN;
12875 		}
12876 	}
12877 
12878 done:
12879 	if (ipversp != NULL)
12880 		*ipversp = ipvers;
12881 	if (ip_hdr_lenp != NULL)
12882 		*ip_hdr_lenp = ip_hdr_len;
12883 	if (ippp != NULL)
12884 		*ippp = ipp;
12885 	if (ifindexp != NULL)
12886 		*ifindexp = ifindex;
12887 	if (mctl_present) {
12888 		freeb(first_mp);
12889 	}
12890 	return (mp);
12891 }
12892 
12893 /*
12894  * Handle M_DATA messages from IP. Its called directly from IP via
12895  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12896  * in this path.
12897  *
12898  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12899  * v4 and v6), we are called through tcp_input() and a M_CTL can
12900  * be present for options but tcp_find_pktinfo() deals with it. We
12901  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12902  *
12903  * The first argument is always the connp/tcp to which the mp belongs.
12904  * There are no exceptions to this rule. The caller has already put
12905  * a reference on this connp/tcp and once tcp_rput_data() returns,
12906  * the squeue will do the refrele.
12907  *
12908  * The TH_SYN for the listener directly go to tcp_conn_request via
12909  * squeue.
12910  *
12911  * sqp: NULL = recursive, sqp != NULL means called from squeue
12912  */
12913 void
12914 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12915 {
12916 	int32_t		bytes_acked;
12917 	int32_t		gap;
12918 	mblk_t		*mp1;
12919 	uint_t		flags;
12920 	uint32_t	new_swnd = 0;
12921 	uchar_t		*iphdr;
12922 	uchar_t		*rptr;
12923 	int32_t		rgap;
12924 	uint32_t	seg_ack;
12925 	int		seg_len;
12926 	uint_t		ip_hdr_len;
12927 	uint32_t	seg_seq;
12928 	tcph_t		*tcph;
12929 	int		urp;
12930 	tcp_opt_t	tcpopt;
12931 	uint_t		ipvers;
12932 	ip6_pkt_t	ipp;
12933 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12934 	uint32_t	cwnd;
12935 	uint32_t	add;
12936 	int		npkt;
12937 	int		mss;
12938 	conn_t		*connp = (conn_t *)arg;
12939 	squeue_t	*sqp = (squeue_t *)arg2;
12940 	tcp_t		*tcp = connp->conn_tcp;
12941 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12942 
12943 	/*
12944 	 * RST from fused tcp loopback peer should trigger an unfuse.
12945 	 */
12946 	if (tcp->tcp_fused) {
12947 		TCP_STAT(tcps, tcp_fusion_aborted);
12948 		tcp_unfuse(tcp);
12949 	}
12950 
12951 	iphdr = mp->b_rptr;
12952 	rptr = mp->b_rptr;
12953 	ASSERT(OK_32PTR(rptr));
12954 
12955 	/*
12956 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12957 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12958 	 * necessary information.
12959 	 */
12960 	if (IPCL_IS_TCP4(connp)) {
12961 		ipvers = IPV4_VERSION;
12962 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12963 	} else {
12964 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12965 		    NULL, &ipp);
12966 		if (mp == NULL) {
12967 			TCP_STAT(tcps, tcp_rput_v6_error);
12968 			return;
12969 		}
12970 		iphdr = mp->b_rptr;
12971 		rptr = mp->b_rptr;
12972 	}
12973 	ASSERT(DB_TYPE(mp) == M_DATA);
12974 	ASSERT(mp->b_next == NULL);
12975 
12976 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12977 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12978 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12979 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12980 	seg_len = (int)(mp->b_wptr - rptr) -
12981 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12982 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12983 		do {
12984 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12985 			    (uintptr_t)INT_MAX);
12986 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12987 		} while ((mp1 = mp1->b_cont) != NULL &&
12988 		    mp1->b_datap->db_type == M_DATA);
12989 	}
12990 
12991 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12992 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12993 		    seg_len, tcph);
12994 		return;
12995 	}
12996 
12997 	if (sqp != NULL) {
12998 		/*
12999 		 * This is the correct place to update tcp_last_recv_time. Note
13000 		 * that it is also updated for tcp structure that belongs to
13001 		 * global and listener queues which do not really need updating.
13002 		 * But that should not cause any harm.  And it is updated for
13003 		 * all kinds of incoming segments, not only for data segments.
13004 		 */
13005 		tcp->tcp_last_recv_time = lbolt;
13006 	}
13007 
13008 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13009 
13010 	BUMP_LOCAL(tcp->tcp_ibsegs);
13011 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13012 
13013 	if ((flags & TH_URG) && sqp != NULL) {
13014 		/*
13015 		 * TCP can't handle urgent pointers that arrive before
13016 		 * the connection has been accept()ed since it can't
13017 		 * buffer OOB data.  Discard segment if this happens.
13018 		 *
13019 		 * We can't just rely on a non-null tcp_listener to indicate
13020 		 * that the accept() has completed since unlinking of the
13021 		 * eager and completion of the accept are not atomic.
13022 		 * tcp_detached, when it is not set (B_FALSE) indicates
13023 		 * that the accept() has completed.
13024 		 *
13025 		 * Nor can it reassemble urgent pointers, so discard
13026 		 * if it's not the next segment expected.
13027 		 *
13028 		 * Otherwise, collapse chain into one mblk (discard if
13029 		 * that fails).  This makes sure the headers, retransmitted
13030 		 * data, and new data all are in the same mblk.
13031 		 */
13032 		ASSERT(mp != NULL);
13033 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
13034 			freemsg(mp);
13035 			return;
13036 		}
13037 		/* Update pointers into message */
13038 		iphdr = rptr = mp->b_rptr;
13039 		tcph = (tcph_t *)&rptr[ip_hdr_len];
13040 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
13041 			/*
13042 			 * Since we can't handle any data with this urgent
13043 			 * pointer that is out of sequence, we expunge
13044 			 * the data.  This allows us to still register
13045 			 * the urgent mark and generate the M_PCSIG,
13046 			 * which we can do.
13047 			 */
13048 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13049 			seg_len = 0;
13050 		}
13051 	}
13052 
13053 	switch (tcp->tcp_state) {
13054 	case TCPS_SYN_SENT:
13055 		if (flags & TH_ACK) {
13056 			/*
13057 			 * Note that our stack cannot send data before a
13058 			 * connection is established, therefore the
13059 			 * following check is valid.  Otherwise, it has
13060 			 * to be changed.
13061 			 */
13062 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13063 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13064 				freemsg(mp);
13065 				if (flags & TH_RST)
13066 					return;
13067 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13068 				    tcp, seg_ack, 0, TH_RST);
13069 				return;
13070 			}
13071 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13072 		}
13073 		if (flags & TH_RST) {
13074 			freemsg(mp);
13075 			if (flags & TH_ACK)
13076 				(void) tcp_clean_death(tcp,
13077 				    ECONNREFUSED, 13);
13078 			return;
13079 		}
13080 		if (!(flags & TH_SYN)) {
13081 			freemsg(mp);
13082 			return;
13083 		}
13084 
13085 		/* Process all TCP options. */
13086 		tcp_process_options(tcp, tcph);
13087 		/*
13088 		 * The following changes our rwnd to be a multiple of the
13089 		 * MIN(peer MSS, our MSS) for performance reason.
13090 		 */
13091 		(void) tcp_rwnd_set(tcp,
13092 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
13093 
13094 		/* Is the other end ECN capable? */
13095 		if (tcp->tcp_ecn_ok) {
13096 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13097 				tcp->tcp_ecn_ok = B_FALSE;
13098 			}
13099 		}
13100 		/*
13101 		 * Clear ECN flags because it may interfere with later
13102 		 * processing.
13103 		 */
13104 		flags &= ~(TH_ECE|TH_CWR);
13105 
13106 		tcp->tcp_irs = seg_seq;
13107 		tcp->tcp_rack = seg_seq;
13108 		tcp->tcp_rnxt = seg_seq + 1;
13109 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13110 		if (!TCP_IS_DETACHED(tcp)) {
13111 			/* Allocate room for SACK options if needed. */
13112 			if (tcp->tcp_snd_sack_ok) {
13113 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13114 				    tcp->tcp_hdr_len +
13115 				    TCPOPT_MAX_SACK_LEN +
13116 				    (tcp->tcp_loopback ? 0 :
13117 				    tcps->tcps_wroff_xtra));
13118 			} else {
13119 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13120 				    tcp->tcp_hdr_len +
13121 				    (tcp->tcp_loopback ? 0 :
13122 				    tcps->tcps_wroff_xtra));
13123 			}
13124 		}
13125 		if (flags & TH_ACK) {
13126 			/*
13127 			 * If we can't get the confirmation upstream, pretend
13128 			 * we didn't even see this one.
13129 			 *
13130 			 * XXX: how can we pretend we didn't see it if we
13131 			 * have updated rnxt et. al.
13132 			 *
13133 			 * For loopback we defer sending up the T_CONN_CON
13134 			 * until after some checks below.
13135 			 */
13136 			mp1 = NULL;
13137 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13138 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13139 				freemsg(mp);
13140 				return;
13141 			}
13142 			/* SYN was acked - making progress */
13143 			if (tcp->tcp_ipversion == IPV6_VERSION)
13144 				tcp->tcp_ip_forward_progress = B_TRUE;
13145 
13146 			/* One for the SYN */
13147 			tcp->tcp_suna = tcp->tcp_iss + 1;
13148 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13149 			tcp->tcp_state = TCPS_ESTABLISHED;
13150 
13151 			/*
13152 			 * If SYN was retransmitted, need to reset all
13153 			 * retransmission info.  This is because this
13154 			 * segment will be treated as a dup ACK.
13155 			 */
13156 			if (tcp->tcp_rexmit) {
13157 				tcp->tcp_rexmit = B_FALSE;
13158 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13159 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13160 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13161 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13162 				tcp->tcp_ms_we_have_waited = 0;
13163 
13164 				/*
13165 				 * Set tcp_cwnd back to 1 MSS, per
13166 				 * recommendation from
13167 				 * draft-floyd-incr-init-win-01.txt,
13168 				 * Increasing TCP's Initial Window.
13169 				 */
13170 				tcp->tcp_cwnd = tcp->tcp_mss;
13171 			}
13172 
13173 			tcp->tcp_swl1 = seg_seq;
13174 			tcp->tcp_swl2 = seg_ack;
13175 
13176 			new_swnd = BE16_TO_U16(tcph->th_win);
13177 			tcp->tcp_swnd = new_swnd;
13178 			if (new_swnd > tcp->tcp_max_swnd)
13179 				tcp->tcp_max_swnd = new_swnd;
13180 
13181 			/*
13182 			 * Always send the three-way handshake ack immediately
13183 			 * in order to make the connection complete as soon as
13184 			 * possible on the accepting host.
13185 			 */
13186 			flags |= TH_ACK_NEEDED;
13187 
13188 			/*
13189 			 * Special case for loopback.  At this point we have
13190 			 * received SYN-ACK from the remote endpoint.  In
13191 			 * order to ensure that both endpoints reach the
13192 			 * fused state prior to any data exchange, the final
13193 			 * ACK needs to be sent before we indicate T_CONN_CON
13194 			 * to the module upstream.
13195 			 */
13196 			if (tcp->tcp_loopback) {
13197 				mblk_t *ack_mp;
13198 
13199 				ASSERT(!tcp->tcp_unfusable);
13200 				ASSERT(mp1 != NULL);
13201 				/*
13202 				 * For loopback, we always get a pure SYN-ACK
13203 				 * and only need to send back the final ACK
13204 				 * with no data (this is because the other
13205 				 * tcp is ours and we don't do T/TCP).  This
13206 				 * final ACK triggers the passive side to
13207 				 * perform fusion in ESTABLISHED state.
13208 				 */
13209 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13210 					if (tcp->tcp_ack_tid != 0) {
13211 						(void) TCP_TIMER_CANCEL(tcp,
13212 						    tcp->tcp_ack_tid);
13213 						tcp->tcp_ack_tid = 0;
13214 					}
13215 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13216 					BUMP_LOCAL(tcp->tcp_obsegs);
13217 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13218 
13219 					if (!IPCL_IS_NONSTR(connp)) {
13220 						/* Send up T_CONN_CON */
13221 						putnext(tcp->tcp_rq, mp1);
13222 					} else {
13223 						(*connp->conn_upcalls->
13224 						    su_connected)
13225 						    (connp->conn_upper_handle,
13226 						    tcp->tcp_connid,
13227 						    DB_CRED(mp1),
13228 						    DB_CPID(mp1));
13229 						freemsg(mp1);
13230 					}
13231 
13232 					freemsg(mp);
13233 					return;
13234 				}
13235 				/*
13236 				 * Forget fusion; we need to handle more
13237 				 * complex cases below.  Send the deferred
13238 				 * T_CONN_CON message upstream and proceed
13239 				 * as usual.  Mark this tcp as not capable
13240 				 * of fusion.
13241 				 */
13242 				TCP_STAT(tcps, tcp_fusion_unfusable);
13243 				tcp->tcp_unfusable = B_TRUE;
13244 				if (!IPCL_IS_NONSTR(connp)) {
13245 					putnext(tcp->tcp_rq, mp1);
13246 				} else {
13247 					(*connp->conn_upcalls->su_connected)
13248 					    (connp->conn_upper_handle,
13249 					    tcp->tcp_connid, DB_CRED(mp1),
13250 					    DB_CPID(mp1));
13251 					freemsg(mp1);
13252 				}
13253 			}
13254 
13255 			/*
13256 			 * Check to see if there is data to be sent.  If
13257 			 * yes, set the transmit flag.  Then check to see
13258 			 * if received data processing needs to be done.
13259 			 * If not, go straight to xmit_check.  This short
13260 			 * cut is OK as we don't support T/TCP.
13261 			 */
13262 			if (tcp->tcp_unsent)
13263 				flags |= TH_XMIT_NEEDED;
13264 
13265 			if (seg_len == 0 && !(flags & TH_URG)) {
13266 				freemsg(mp);
13267 				goto xmit_check;
13268 			}
13269 
13270 			flags &= ~TH_SYN;
13271 			seg_seq++;
13272 			break;
13273 		}
13274 		tcp->tcp_state = TCPS_SYN_RCVD;
13275 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13276 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13277 		if (mp1) {
13278 			DB_CPID(mp1) = tcp->tcp_cpid;
13279 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13280 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13281 		}
13282 		freemsg(mp);
13283 		return;
13284 	case TCPS_SYN_RCVD:
13285 		if (flags & TH_ACK) {
13286 			/*
13287 			 * In this state, a SYN|ACK packet is either bogus
13288 			 * because the other side must be ACKing our SYN which
13289 			 * indicates it has seen the ACK for their SYN and
13290 			 * shouldn't retransmit it or we're crossing SYNs
13291 			 * on active open.
13292 			 */
13293 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13294 				freemsg(mp);
13295 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13296 				    tcp, seg_ack, 0, TH_RST);
13297 				return;
13298 			}
13299 			/*
13300 			 * NOTE: RFC 793 pg. 72 says this should be
13301 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13302 			 * but that would mean we have an ack that ignored
13303 			 * our SYN.
13304 			 */
13305 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13306 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13307 				freemsg(mp);
13308 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13309 				    tcp, seg_ack, 0, TH_RST);
13310 				return;
13311 			}
13312 		}
13313 		break;
13314 	case TCPS_LISTEN:
13315 		/*
13316 		 * Only a TLI listener can come through this path when a
13317 		 * acceptor is going back to be a listener and a packet
13318 		 * for the acceptor hits the classifier. For a socket
13319 		 * listener, this can never happen because a listener
13320 		 * can never accept connection on itself and hence a
13321 		 * socket acceptor can not go back to being a listener.
13322 		 */
13323 		ASSERT(!TCP_IS_SOCKET(tcp));
13324 		/*FALLTHRU*/
13325 	case TCPS_CLOSED:
13326 	case TCPS_BOUND: {
13327 		conn_t	*new_connp;
13328 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13329 
13330 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13331 		if (new_connp != NULL) {
13332 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13333 			return;
13334 		}
13335 		/* We failed to classify. For now just drop the packet */
13336 		freemsg(mp);
13337 		return;
13338 	}
13339 	case TCPS_IDLE:
13340 		/*
13341 		 * Handle the case where the tcp_clean_death() has happened
13342 		 * on a connection (application hasn't closed yet) but a packet
13343 		 * was already queued on squeue before tcp_clean_death()
13344 		 * was processed. Calling tcp_clean_death() twice on same
13345 		 * connection can result in weird behaviour.
13346 		 */
13347 		freemsg(mp);
13348 		return;
13349 	default:
13350 		break;
13351 	}
13352 
13353 	/*
13354 	 * Already on the correct queue/perimeter.
13355 	 * If this is a detached connection and not an eager
13356 	 * connection hanging off a listener then new data
13357 	 * (past the FIN) will cause a reset.
13358 	 * We do a special check here where it
13359 	 * is out of the main line, rather than check
13360 	 * if we are detached every time we see new
13361 	 * data down below.
13362 	 */
13363 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13364 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13365 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13366 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13367 
13368 		freemsg(mp);
13369 		/*
13370 		 * This could be an SSL closure alert. We're detached so just
13371 		 * acknowledge it this last time.
13372 		 */
13373 		if (tcp->tcp_kssl_ctx != NULL) {
13374 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13375 			tcp->tcp_kssl_ctx = NULL;
13376 
13377 			tcp->tcp_rnxt += seg_len;
13378 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13379 			flags |= TH_ACK_NEEDED;
13380 			goto ack_check;
13381 		}
13382 
13383 		tcp_xmit_ctl("new data when detached", tcp,
13384 		    tcp->tcp_snxt, 0, TH_RST);
13385 		(void) tcp_clean_death(tcp, EPROTO, 12);
13386 		return;
13387 	}
13388 
13389 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13390 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13391 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13392 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13393 
13394 	if (tcp->tcp_snd_ts_ok) {
13395 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13396 			/*
13397 			 * This segment is not acceptable.
13398 			 * Drop it and send back an ACK.
13399 			 */
13400 			freemsg(mp);
13401 			flags |= TH_ACK_NEEDED;
13402 			goto ack_check;
13403 		}
13404 	} else if (tcp->tcp_snd_sack_ok) {
13405 		ASSERT(tcp->tcp_sack_info != NULL);
13406 		tcpopt.tcp = tcp;
13407 		/*
13408 		 * SACK info in already updated in tcp_parse_options.  Ignore
13409 		 * all other TCP options...
13410 		 */
13411 		(void) tcp_parse_options(tcph, &tcpopt);
13412 	}
13413 try_again:;
13414 	mss = tcp->tcp_mss;
13415 	gap = seg_seq - tcp->tcp_rnxt;
13416 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13417 	/*
13418 	 * gap is the amount of sequence space between what we expect to see
13419 	 * and what we got for seg_seq.  A positive value for gap means
13420 	 * something got lost.  A negative value means we got some old stuff.
13421 	 */
13422 	if (gap < 0) {
13423 		/* Old stuff present.  Is the SYN in there? */
13424 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13425 		    (seg_len != 0)) {
13426 			flags &= ~TH_SYN;
13427 			seg_seq++;
13428 			urp--;
13429 			/* Recompute the gaps after noting the SYN. */
13430 			goto try_again;
13431 		}
13432 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13433 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13434 		    (seg_len > -gap ? -gap : seg_len));
13435 		/* Remove the old stuff from seg_len. */
13436 		seg_len += gap;
13437 		/*
13438 		 * Anything left?
13439 		 * Make sure to check for unack'd FIN when rest of data
13440 		 * has been previously ack'd.
13441 		 */
13442 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13443 			/*
13444 			 * Resets are only valid if they lie within our offered
13445 			 * window.  If the RST bit is set, we just ignore this
13446 			 * segment.
13447 			 */
13448 			if (flags & TH_RST) {
13449 				freemsg(mp);
13450 				return;
13451 			}
13452 
13453 			/*
13454 			 * The arriving of dup data packets indicate that we
13455 			 * may have postponed an ack for too long, or the other
13456 			 * side's RTT estimate is out of shape. Start acking
13457 			 * more often.
13458 			 */
13459 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13460 			    tcp->tcp_rack_cnt >= 1 &&
13461 			    tcp->tcp_rack_abs_max > 2) {
13462 				tcp->tcp_rack_abs_max--;
13463 			}
13464 			tcp->tcp_rack_cur_max = 1;
13465 
13466 			/*
13467 			 * This segment is "unacceptable".  None of its
13468 			 * sequence space lies within our advertized window.
13469 			 *
13470 			 * Adjust seg_len to the original value for tracing.
13471 			 */
13472 			seg_len -= gap;
13473 			if (tcp->tcp_debug) {
13474 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13475 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13476 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13477 				    "seg_len %d, rnxt %u, snxt %u, %s",
13478 				    gap, rgap, flags, seg_seq, seg_ack,
13479 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13480 				    tcp_display(tcp, NULL,
13481 				    DISP_ADDR_AND_PORT));
13482 			}
13483 
13484 			/*
13485 			 * Arrange to send an ACK in response to the
13486 			 * unacceptable segment per RFC 793 page 69. There
13487 			 * is only one small difference between ours and the
13488 			 * acceptability test in the RFC - we accept ACK-only
13489 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13490 			 * will be generated.
13491 			 *
13492 			 * Note that we have to ACK an ACK-only packet at least
13493 			 * for stacks that send 0-length keep-alives with
13494 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13495 			 * section 4.2.3.6. As long as we don't ever generate
13496 			 * an unacceptable packet in response to an incoming
13497 			 * packet that is unacceptable, it should not cause
13498 			 * "ACK wars".
13499 			 */
13500 			flags |=  TH_ACK_NEEDED;
13501 
13502 			/*
13503 			 * Continue processing this segment in order to use the
13504 			 * ACK information it contains, but skip all other
13505 			 * sequence-number processing.	Processing the ACK
13506 			 * information is necessary in order to
13507 			 * re-synchronize connections that may have lost
13508 			 * synchronization.
13509 			 *
13510 			 * We clear seg_len and flag fields related to
13511 			 * sequence number processing as they are not
13512 			 * to be trusted for an unacceptable segment.
13513 			 */
13514 			seg_len = 0;
13515 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13516 			goto process_ack;
13517 		}
13518 
13519 		/* Fix seg_seq, and chew the gap off the front. */
13520 		seg_seq = tcp->tcp_rnxt;
13521 		urp += gap;
13522 		do {
13523 			mblk_t	*mp2;
13524 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13525 			    (uintptr_t)UINT_MAX);
13526 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13527 			if (gap > 0) {
13528 				mp->b_rptr = mp->b_wptr - gap;
13529 				break;
13530 			}
13531 			mp2 = mp;
13532 			mp = mp->b_cont;
13533 			freeb(mp2);
13534 		} while (gap < 0);
13535 		/*
13536 		 * If the urgent data has already been acknowledged, we
13537 		 * should ignore TH_URG below
13538 		 */
13539 		if (urp < 0)
13540 			flags &= ~TH_URG;
13541 	}
13542 	/*
13543 	 * rgap is the amount of stuff received out of window.  A negative
13544 	 * value is the amount out of window.
13545 	 */
13546 	if (rgap < 0) {
13547 		mblk_t	*mp2;
13548 
13549 		if (tcp->tcp_rwnd == 0) {
13550 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13551 		} else {
13552 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13553 			UPDATE_MIB(&tcps->tcps_mib,
13554 			    tcpInDataPastWinBytes, -rgap);
13555 		}
13556 
13557 		/*
13558 		 * seg_len does not include the FIN, so if more than
13559 		 * just the FIN is out of window, we act like we don't
13560 		 * see it.  (If just the FIN is out of window, rgap
13561 		 * will be zero and we will go ahead and acknowledge
13562 		 * the FIN.)
13563 		 */
13564 		flags &= ~TH_FIN;
13565 
13566 		/* Fix seg_len and make sure there is something left. */
13567 		seg_len += rgap;
13568 		if (seg_len <= 0) {
13569 			/*
13570 			 * Resets are only valid if they lie within our offered
13571 			 * window.  If the RST bit is set, we just ignore this
13572 			 * segment.
13573 			 */
13574 			if (flags & TH_RST) {
13575 				freemsg(mp);
13576 				return;
13577 			}
13578 
13579 			/* Per RFC 793, we need to send back an ACK. */
13580 			flags |= TH_ACK_NEEDED;
13581 
13582 			/*
13583 			 * Send SIGURG as soon as possible i.e. even
13584 			 * if the TH_URG was delivered in a window probe
13585 			 * packet (which will be unacceptable).
13586 			 *
13587 			 * We generate a signal if none has been generated
13588 			 * for this connection or if this is a new urgent
13589 			 * byte. Also send a zero-length "unmarked" message
13590 			 * to inform SIOCATMARK that this is not the mark.
13591 			 *
13592 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13593 			 * is sent up. This plus the check for old data
13594 			 * (gap >= 0) handles the wraparound of the sequence
13595 			 * number space without having to always track the
13596 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13597 			 * this max in its rcv_up variable).
13598 			 *
13599 			 * This prevents duplicate SIGURGS due to a "late"
13600 			 * zero-window probe when the T_EXDATA_IND has already
13601 			 * been sent up.
13602 			 */
13603 			if ((flags & TH_URG) &&
13604 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13605 			    tcp->tcp_urp_last))) {
13606 				if (IPCL_IS_NONSTR(connp)) {
13607 					if (!TCP_IS_DETACHED(tcp)) {
13608 						(*connp->conn_upcalls->
13609 						    su_signal_oob)
13610 						    (connp->conn_upper_handle,
13611 						    urp);
13612 					}
13613 				} else {
13614 					mp1 = allocb(0, BPRI_MED);
13615 					if (mp1 == NULL) {
13616 						freemsg(mp);
13617 						return;
13618 					}
13619 					if (!TCP_IS_DETACHED(tcp) &&
13620 					    !putnextctl1(tcp->tcp_rq,
13621 					    M_PCSIG, SIGURG)) {
13622 						/* Try again on the rexmit. */
13623 						freemsg(mp1);
13624 						freemsg(mp);
13625 						return;
13626 					}
13627 					/*
13628 					 * If the next byte would be the mark
13629 					 * then mark with MARKNEXT else mark
13630 					 * with NOTMARKNEXT.
13631 					 */
13632 					if (gap == 0 && urp == 0)
13633 						mp1->b_flag |= MSGMARKNEXT;
13634 					else
13635 						mp1->b_flag |= MSGNOTMARKNEXT;
13636 					freemsg(tcp->tcp_urp_mark_mp);
13637 					tcp->tcp_urp_mark_mp = mp1;
13638 					flags |= TH_SEND_URP_MARK;
13639 				}
13640 				tcp->tcp_urp_last_valid = B_TRUE;
13641 				tcp->tcp_urp_last = urp + seg_seq;
13642 			}
13643 			/*
13644 			 * If this is a zero window probe, continue to
13645 			 * process the ACK part.  But we need to set seg_len
13646 			 * to 0 to avoid data processing.  Otherwise just
13647 			 * drop the segment and send back an ACK.
13648 			 */
13649 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13650 				flags &= ~(TH_SYN | TH_URG);
13651 				seg_len = 0;
13652 				goto process_ack;
13653 			} else {
13654 				freemsg(mp);
13655 				goto ack_check;
13656 			}
13657 		}
13658 		/* Pitch out of window stuff off the end. */
13659 		rgap = seg_len;
13660 		mp2 = mp;
13661 		do {
13662 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13663 			    (uintptr_t)INT_MAX);
13664 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13665 			if (rgap < 0) {
13666 				mp2->b_wptr += rgap;
13667 				if ((mp1 = mp2->b_cont) != NULL) {
13668 					mp2->b_cont = NULL;
13669 					freemsg(mp1);
13670 				}
13671 				break;
13672 			}
13673 		} while ((mp2 = mp2->b_cont) != NULL);
13674 	}
13675 ok:;
13676 	/*
13677 	 * TCP should check ECN info for segments inside the window only.
13678 	 * Therefore the check should be done here.
13679 	 */
13680 	if (tcp->tcp_ecn_ok) {
13681 		if (flags & TH_CWR) {
13682 			tcp->tcp_ecn_echo_on = B_FALSE;
13683 		}
13684 		/*
13685 		 * Note that both ECN_CE and CWR can be set in the
13686 		 * same segment.  In this case, we once again turn
13687 		 * on ECN_ECHO.
13688 		 */
13689 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13690 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13691 
13692 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13693 				tcp->tcp_ecn_echo_on = B_TRUE;
13694 			}
13695 		} else {
13696 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13697 
13698 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13699 			    htonl(IPH_ECN_CE << 20)) {
13700 				tcp->tcp_ecn_echo_on = B_TRUE;
13701 			}
13702 		}
13703 	}
13704 
13705 	/*
13706 	 * Check whether we can update tcp_ts_recent.  This test is
13707 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13708 	 * Extensions for High Performance: An Update", Internet Draft.
13709 	 */
13710 	if (tcp->tcp_snd_ts_ok &&
13711 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13712 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13713 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13714 		tcp->tcp_last_rcv_lbolt = lbolt64;
13715 	}
13716 
13717 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13718 		/*
13719 		 * FIN in an out of order segment.  We record this in
13720 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13721 		 * Clear the FIN so that any check on FIN flag will fail.
13722 		 * Remember that FIN also counts in the sequence number
13723 		 * space.  So we need to ack out of order FIN only segments.
13724 		 */
13725 		if (flags & TH_FIN) {
13726 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13727 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13728 			flags &= ~TH_FIN;
13729 			flags |= TH_ACK_NEEDED;
13730 		}
13731 		if (seg_len > 0) {
13732 			/* Fill in the SACK blk list. */
13733 			if (tcp->tcp_snd_sack_ok) {
13734 				ASSERT(tcp->tcp_sack_info != NULL);
13735 				tcp_sack_insert(tcp->tcp_sack_list,
13736 				    seg_seq, seg_seq + seg_len,
13737 				    &(tcp->tcp_num_sack_blk));
13738 			}
13739 
13740 			/*
13741 			 * Attempt reassembly and see if we have something
13742 			 * ready to go.
13743 			 */
13744 			mp = tcp_reass(tcp, mp, seg_seq);
13745 			/* Always ack out of order packets */
13746 			flags |= TH_ACK_NEEDED | TH_PUSH;
13747 			if (mp) {
13748 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13749 				    (uintptr_t)INT_MAX);
13750 				seg_len = mp->b_cont ? msgdsize(mp) :
13751 				    (int)(mp->b_wptr - mp->b_rptr);
13752 				seg_seq = tcp->tcp_rnxt;
13753 				/*
13754 				 * A gap is filled and the seq num and len
13755 				 * of the gap match that of a previously
13756 				 * received FIN, 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 &=
13762 					    ~TCP_OFO_FIN_VALID;
13763 				}
13764 			} else {
13765 				/*
13766 				 * Keep going even with NULL mp.
13767 				 * There may be a useful ACK or something else
13768 				 * we don't want to miss.
13769 				 *
13770 				 * But TCP should not perform fast retransmit
13771 				 * because of the ack number.  TCP uses
13772 				 * seg_len == 0 to determine if it is a pure
13773 				 * ACK.  And this is not a pure ACK.
13774 				 */
13775 				seg_len = 0;
13776 				ofo_seg = B_TRUE;
13777 			}
13778 		}
13779 	} else if (seg_len > 0) {
13780 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13781 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13782 		/*
13783 		 * If an out of order FIN was received before, and the seq
13784 		 * num and len of the new segment match that of the FIN,
13785 		 * put the FIN flag back in.
13786 		 */
13787 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13788 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13789 			flags |= TH_FIN;
13790 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13791 		}
13792 	}
13793 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13794 	if (flags & TH_RST) {
13795 		freemsg(mp);
13796 		switch (tcp->tcp_state) {
13797 		case TCPS_SYN_RCVD:
13798 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13799 			break;
13800 		case TCPS_ESTABLISHED:
13801 		case TCPS_FIN_WAIT_1:
13802 		case TCPS_FIN_WAIT_2:
13803 		case TCPS_CLOSE_WAIT:
13804 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13805 			break;
13806 		case TCPS_CLOSING:
13807 		case TCPS_LAST_ACK:
13808 			(void) tcp_clean_death(tcp, 0, 16);
13809 			break;
13810 		default:
13811 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13812 			(void) tcp_clean_death(tcp, ENXIO, 17);
13813 			break;
13814 		}
13815 		return;
13816 	}
13817 	if (flags & TH_SYN) {
13818 		/*
13819 		 * See RFC 793, Page 71
13820 		 *
13821 		 * The seq number must be in the window as it should
13822 		 * be "fixed" above.  If it is outside window, it should
13823 		 * be already rejected.  Note that we allow seg_seq to be
13824 		 * rnxt + rwnd because we want to accept 0 window probe.
13825 		 */
13826 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13827 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13828 		freemsg(mp);
13829 		/*
13830 		 * If the ACK flag is not set, just use our snxt as the
13831 		 * seq number of the RST segment.
13832 		 */
13833 		if (!(flags & TH_ACK)) {
13834 			seg_ack = tcp->tcp_snxt;
13835 		}
13836 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13837 		    TH_RST|TH_ACK);
13838 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13839 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13840 		return;
13841 	}
13842 	/*
13843 	 * urp could be -1 when the urp field in the packet is 0
13844 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13845 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13846 	 */
13847 	if (flags & TH_URG && urp >= 0) {
13848 		if (!tcp->tcp_urp_last_valid ||
13849 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13850 			if (IPCL_IS_NONSTR(connp)) {
13851 				if (!TCP_IS_DETACHED(tcp)) {
13852 					(*connp->conn_upcalls->su_signal_oob)
13853 					    (connp->conn_upper_handle, urp);
13854 				}
13855 			} else {
13856 				/*
13857 				 * If we haven't generated the signal yet for
13858 				 * this urgent pointer value, do it now.  Also,
13859 				 * send up a zero-length M_DATA indicating
13860 				 * whether or not this is the mark. The latter
13861 				 * is not needed when a T_EXDATA_IND is sent up.
13862 				 * However, if there are allocation failures
13863 				 * this code relies on the sender retransmitting
13864 				 * and the socket code for determining the mark
13865 				 * should not block waiting for the peer to
13866 				 * transmit. Thus, for simplicity we always
13867 				 * send up the mark indication.
13868 				 */
13869 				mp1 = allocb(0, BPRI_MED);
13870 				if (mp1 == NULL) {
13871 					freemsg(mp);
13872 					return;
13873 				}
13874 				if (!TCP_IS_DETACHED(tcp) &&
13875 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13876 				    SIGURG)) {
13877 					/* Try again on the rexmit. */
13878 					freemsg(mp1);
13879 					freemsg(mp);
13880 					return;
13881 				}
13882 				/*
13883 				 * Mark with NOTMARKNEXT for now.
13884 				 * The code below will change this to MARKNEXT
13885 				 * if we are at the mark.
13886 				 *
13887 				 * If there are allocation failures (e.g. in
13888 				 * dupmsg below) the next time tcp_rput_data
13889 				 * sees the urgent segment it will send up the
13890 				 * MSGMARKNEXT message.
13891 				 */
13892 				mp1->b_flag |= MSGNOTMARKNEXT;
13893 				freemsg(tcp->tcp_urp_mark_mp);
13894 				tcp->tcp_urp_mark_mp = mp1;
13895 				flags |= TH_SEND_URP_MARK;
13896 #ifdef DEBUG
13897 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13898 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13899 				    "last %x, %s",
13900 				    seg_seq, urp, tcp->tcp_urp_last,
13901 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13902 #endif /* DEBUG */
13903 			}
13904 			tcp->tcp_urp_last_valid = B_TRUE;
13905 			tcp->tcp_urp_last = urp + seg_seq;
13906 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13907 			/*
13908 			 * An allocation failure prevented the previous
13909 			 * tcp_rput_data from sending up the allocated
13910 			 * MSG*MARKNEXT message - send it up this time
13911 			 * around.
13912 			 */
13913 			flags |= TH_SEND_URP_MARK;
13914 		}
13915 
13916 		/*
13917 		 * If the urgent byte is in this segment, make sure that it is
13918 		 * all by itself.  This makes it much easier to deal with the
13919 		 * possibility of an allocation failure on the T_exdata_ind.
13920 		 * Note that seg_len is the number of bytes in the segment, and
13921 		 * urp is the offset into the segment of the urgent byte.
13922 		 * urp < seg_len means that the urgent byte is in this segment.
13923 		 */
13924 		if (urp < seg_len) {
13925 			if (seg_len != 1) {
13926 				uint32_t  tmp_rnxt;
13927 				/*
13928 				 * Break it up and feed it back in.
13929 				 * Re-attach the IP header.
13930 				 */
13931 				mp->b_rptr = iphdr;
13932 				if (urp > 0) {
13933 					/*
13934 					 * There is stuff before the urgent
13935 					 * byte.
13936 					 */
13937 					mp1 = dupmsg(mp);
13938 					if (!mp1) {
13939 						/*
13940 						 * Trim from urgent byte on.
13941 						 * The rest will come back.
13942 						 */
13943 						(void) adjmsg(mp,
13944 						    urp - seg_len);
13945 						tcp_rput_data(connp,
13946 						    mp, NULL);
13947 						return;
13948 					}
13949 					(void) adjmsg(mp1, urp - seg_len);
13950 					/* Feed this piece back in. */
13951 					tmp_rnxt = tcp->tcp_rnxt;
13952 					tcp_rput_data(connp, mp1, NULL);
13953 					/*
13954 					 * If the data passed back in was not
13955 					 * processed (ie: bad ACK) sending
13956 					 * the remainder back in will cause a
13957 					 * loop. In this case, drop the
13958 					 * packet and let the sender try
13959 					 * sending a good packet.
13960 					 */
13961 					if (tmp_rnxt == tcp->tcp_rnxt) {
13962 						freemsg(mp);
13963 						return;
13964 					}
13965 				}
13966 				if (urp != seg_len - 1) {
13967 					uint32_t  tmp_rnxt;
13968 					/*
13969 					 * There is stuff after the urgent
13970 					 * byte.
13971 					 */
13972 					mp1 = dupmsg(mp);
13973 					if (!mp1) {
13974 						/*
13975 						 * Trim everything beyond the
13976 						 * urgent byte.  The rest will
13977 						 * come back.
13978 						 */
13979 						(void) adjmsg(mp,
13980 						    urp + 1 - seg_len);
13981 						tcp_rput_data(connp,
13982 						    mp, NULL);
13983 						return;
13984 					}
13985 					(void) adjmsg(mp1, urp + 1 - seg_len);
13986 					tmp_rnxt = tcp->tcp_rnxt;
13987 					tcp_rput_data(connp, mp1, NULL);
13988 					/*
13989 					 * If the data passed back in was not
13990 					 * processed (ie: bad ACK) sending
13991 					 * the remainder back in will cause a
13992 					 * loop. In this case, drop the
13993 					 * packet and let the sender try
13994 					 * sending a good packet.
13995 					 */
13996 					if (tmp_rnxt == tcp->tcp_rnxt) {
13997 						freemsg(mp);
13998 						return;
13999 					}
14000 				}
14001 				tcp_rput_data(connp, mp, NULL);
14002 				return;
14003 			}
14004 			/*
14005 			 * This segment contains only the urgent byte.  We
14006 			 * have to allocate the T_exdata_ind, if we can.
14007 			 */
14008 			if (IPCL_IS_NONSTR(connp)) {
14009 				int error;
14010 
14011 				(*connp->conn_upcalls->su_recv)
14012 				    (connp->conn_upper_handle, mp, seg_len,
14013 				    MSG_OOB, &error, NULL);
14014 				mp = NULL;
14015 				goto update_ack;
14016 			} else if (!tcp->tcp_urp_mp) {
14017 				struct T_exdata_ind *tei;
14018 				mp1 = allocb(sizeof (struct T_exdata_ind),
14019 				    BPRI_MED);
14020 				if (!mp1) {
14021 					/*
14022 					 * Sigh... It'll be back.
14023 					 * Generate any MSG*MARK message now.
14024 					 */
14025 					freemsg(mp);
14026 					seg_len = 0;
14027 					if (flags & TH_SEND_URP_MARK) {
14028 
14029 
14030 						ASSERT(tcp->tcp_urp_mark_mp);
14031 						tcp->tcp_urp_mark_mp->b_flag &=
14032 						    ~MSGNOTMARKNEXT;
14033 						tcp->tcp_urp_mark_mp->b_flag |=
14034 						    MSGMARKNEXT;
14035 					}
14036 					goto ack_check;
14037 				}
14038 				mp1->b_datap->db_type = M_PROTO;
14039 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14040 				tei->PRIM_type = T_EXDATA_IND;
14041 				tei->MORE_flag = 0;
14042 				mp1->b_wptr = (uchar_t *)&tei[1];
14043 				tcp->tcp_urp_mp = mp1;
14044 #ifdef DEBUG
14045 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14046 				    "tcp_rput: allocated exdata_ind %s",
14047 				    tcp_display(tcp, NULL,
14048 				    DISP_PORT_ONLY));
14049 #endif /* DEBUG */
14050 				/*
14051 				 * There is no need to send a separate MSG*MARK
14052 				 * message since the T_EXDATA_IND will be sent
14053 				 * now.
14054 				 */
14055 				flags &= ~TH_SEND_URP_MARK;
14056 				freemsg(tcp->tcp_urp_mark_mp);
14057 				tcp->tcp_urp_mark_mp = NULL;
14058 			}
14059 			/*
14060 			 * Now we are all set.  On the next putnext upstream,
14061 			 * tcp_urp_mp will be non-NULL and will get prepended
14062 			 * to what has to be this piece containing the urgent
14063 			 * byte.  If for any reason we abort this segment below,
14064 			 * if it comes back, we will have this ready, or it
14065 			 * will get blown off in close.
14066 			 */
14067 		} else if (urp == seg_len) {
14068 			/*
14069 			 * The urgent byte is the next byte after this sequence
14070 			 * number. If there is data it is marked with
14071 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14072 			 * since it is not needed. Otherwise, if the code
14073 			 * above just allocated a zero-length tcp_urp_mark_mp
14074 			 * message, that message is tagged with MSGMARKNEXT.
14075 			 * Sending up these MSGMARKNEXT messages makes
14076 			 * SIOCATMARK work correctly even though
14077 			 * the T_EXDATA_IND will not be sent up until the
14078 			 * urgent byte arrives.
14079 			 */
14080 			if (seg_len != 0) {
14081 				flags |= TH_MARKNEXT_NEEDED;
14082 				freemsg(tcp->tcp_urp_mark_mp);
14083 				tcp->tcp_urp_mark_mp = NULL;
14084 				flags &= ~TH_SEND_URP_MARK;
14085 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14086 				flags |= TH_SEND_URP_MARK;
14087 				tcp->tcp_urp_mark_mp->b_flag &=
14088 				    ~MSGNOTMARKNEXT;
14089 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14090 			}
14091 #ifdef DEBUG
14092 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14093 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14094 			    seg_len, flags,
14095 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14096 #endif /* DEBUG */
14097 		}
14098 #ifdef DEBUG
14099 		else {
14100 			/* Data left until we hit mark */
14101 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14102 			    "tcp_rput: URP %d bytes left, %s",
14103 			    urp - seg_len, tcp_display(tcp, NULL,
14104 			    DISP_PORT_ONLY));
14105 		}
14106 #endif /* DEBUG */
14107 	}
14108 
14109 process_ack:
14110 	if (!(flags & TH_ACK)) {
14111 		freemsg(mp);
14112 		goto xmit_check;
14113 	}
14114 	}
14115 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14116 
14117 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14118 		tcp->tcp_ip_forward_progress = B_TRUE;
14119 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14120 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
14121 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
14122 			/* 3-way handshake complete - pass up the T_CONN_IND */
14123 			tcp_t	*listener = tcp->tcp_listener;
14124 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14125 
14126 			tcp->tcp_tconnind_started = B_TRUE;
14127 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14128 			/*
14129 			 * We are here means eager is fine but it can
14130 			 * get a TH_RST at any point between now and till
14131 			 * accept completes and disappear. We need to
14132 			 * ensure that reference to eager is valid after
14133 			 * we get out of eager's perimeter. So we do
14134 			 * an extra refhold.
14135 			 */
14136 			CONN_INC_REF(connp);
14137 
14138 			/*
14139 			 * The listener also exists because of the refhold
14140 			 * done in tcp_conn_request. Its possible that it
14141 			 * might have closed. We will check that once we
14142 			 * get inside listeners context.
14143 			 */
14144 			CONN_INC_REF(listener->tcp_connp);
14145 			if (listener->tcp_connp->conn_sqp ==
14146 			    connp->conn_sqp) {
14147 				/*
14148 				 * We optimize by not calling an SQUEUE_ENTER
14149 				 * on the listener since we know that the
14150 				 * listener and eager squeues are the same.
14151 				 * We are able to make this check safely only
14152 				 * because neither the eager nor the listener
14153 				 * can change its squeue. Only an active connect
14154 				 * can change its squeue
14155 				 */
14156 				tcp_send_conn_ind(listener->tcp_connp, mp,
14157 				    listener->tcp_connp->conn_sqp);
14158 				CONN_DEC_REF(listener->tcp_connp);
14159 			} else if (!tcp->tcp_loopback) {
14160 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14161 				    mp, tcp_send_conn_ind,
14162 				    listener->tcp_connp, SQ_FILL,
14163 				    SQTAG_TCP_CONN_IND);
14164 			} else {
14165 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14166 				    mp, tcp_send_conn_ind,
14167 				    listener->tcp_connp, SQ_PROCESS,
14168 				    SQTAG_TCP_CONN_IND);
14169 			}
14170 		}
14171 
14172 		if (tcp->tcp_active_open) {
14173 			/*
14174 			 * We are seeing the final ack in the three way
14175 			 * hand shake of a active open'ed connection
14176 			 * so we must send up a T_CONN_CON
14177 			 */
14178 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14179 				freemsg(mp);
14180 				return;
14181 			}
14182 			/*
14183 			 * Don't fuse the loopback endpoints for
14184 			 * simultaneous active opens.
14185 			 */
14186 			if (tcp->tcp_loopback) {
14187 				TCP_STAT(tcps, tcp_fusion_unfusable);
14188 				tcp->tcp_unfusable = B_TRUE;
14189 			}
14190 		}
14191 
14192 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14193 		bytes_acked--;
14194 		/* SYN was acked - making progress */
14195 		if (tcp->tcp_ipversion == IPV6_VERSION)
14196 			tcp->tcp_ip_forward_progress = B_TRUE;
14197 
14198 		/*
14199 		 * If SYN was retransmitted, need to reset all
14200 		 * retransmission info as this segment will be
14201 		 * treated as a dup ACK.
14202 		 */
14203 		if (tcp->tcp_rexmit) {
14204 			tcp->tcp_rexmit = B_FALSE;
14205 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14206 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14207 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14208 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14209 			tcp->tcp_ms_we_have_waited = 0;
14210 			tcp->tcp_cwnd = mss;
14211 		}
14212 
14213 		/*
14214 		 * We set the send window to zero here.
14215 		 * This is needed if there is data to be
14216 		 * processed already on the queue.
14217 		 * Later (at swnd_update label), the
14218 		 * "new_swnd > tcp_swnd" condition is satisfied
14219 		 * the XMIT_NEEDED flag is set in the current
14220 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14221 		 * called if there is already data on queue in
14222 		 * this state.
14223 		 */
14224 		tcp->tcp_swnd = 0;
14225 
14226 		if (new_swnd > tcp->tcp_max_swnd)
14227 			tcp->tcp_max_swnd = new_swnd;
14228 		tcp->tcp_swl1 = seg_seq;
14229 		tcp->tcp_swl2 = seg_ack;
14230 		tcp->tcp_state = TCPS_ESTABLISHED;
14231 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14232 
14233 		/* Fuse when both sides are in ESTABLISHED state */
14234 		if (tcp->tcp_loopback && do_tcp_fusion)
14235 			tcp_fuse(tcp, iphdr, tcph);
14236 
14237 	}
14238 	/* This code follows 4.4BSD-Lite2 mostly. */
14239 	if (bytes_acked < 0)
14240 		goto est;
14241 
14242 	/*
14243 	 * If TCP is ECN capable and the congestion experience bit is
14244 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14245 	 * done once per window (or more loosely, per RTT).
14246 	 */
14247 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14248 		tcp->tcp_cwr = B_FALSE;
14249 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14250 		if (!tcp->tcp_cwr) {
14251 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14252 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14253 			tcp->tcp_cwnd = npkt * mss;
14254 			/*
14255 			 * If the cwnd is 0, use the timer to clock out
14256 			 * new segments.  This is required by the ECN spec.
14257 			 */
14258 			if (npkt == 0) {
14259 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14260 				/*
14261 				 * This makes sure that when the ACK comes
14262 				 * back, we will increase tcp_cwnd by 1 MSS.
14263 				 */
14264 				tcp->tcp_cwnd_cnt = 0;
14265 			}
14266 			tcp->tcp_cwr = B_TRUE;
14267 			/*
14268 			 * This marks the end of the current window of in
14269 			 * flight data.  That is why we don't use
14270 			 * tcp_suna + tcp_swnd.  Only data in flight can
14271 			 * provide ECN info.
14272 			 */
14273 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14274 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14275 		}
14276 	}
14277 
14278 	mp1 = tcp->tcp_xmit_head;
14279 	if (bytes_acked == 0) {
14280 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14281 			int dupack_cnt;
14282 
14283 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14284 			/*
14285 			 * Fast retransmit.  When we have seen exactly three
14286 			 * identical ACKs while we have unacked data
14287 			 * outstanding we take it as a hint that our peer
14288 			 * dropped something.
14289 			 *
14290 			 * If TCP is retransmitting, don't do fast retransmit.
14291 			 */
14292 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14293 			    ! tcp->tcp_rexmit) {
14294 				/* Do Limited Transmit */
14295 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14296 				    tcps->tcps_dupack_fast_retransmit) {
14297 					/*
14298 					 * RFC 3042
14299 					 *
14300 					 * What we need to do is temporarily
14301 					 * increase tcp_cwnd so that new
14302 					 * data can be sent if it is allowed
14303 					 * by the receive window (tcp_rwnd).
14304 					 * tcp_wput_data() will take care of
14305 					 * the rest.
14306 					 *
14307 					 * If the connection is SACK capable,
14308 					 * only do limited xmit when there
14309 					 * is SACK info.
14310 					 *
14311 					 * Note how tcp_cwnd is incremented.
14312 					 * The first dup ACK will increase
14313 					 * it by 1 MSS.  The second dup ACK
14314 					 * will increase it by 2 MSS.  This
14315 					 * means that only 1 new segment will
14316 					 * be sent for each dup ACK.
14317 					 */
14318 					if (tcp->tcp_unsent > 0 &&
14319 					    (!tcp->tcp_snd_sack_ok ||
14320 					    (tcp->tcp_snd_sack_ok &&
14321 					    tcp->tcp_notsack_list != NULL))) {
14322 						tcp->tcp_cwnd += mss <<
14323 						    (tcp->tcp_dupack_cnt - 1);
14324 						flags |= TH_LIMIT_XMIT;
14325 					}
14326 				} else if (dupack_cnt ==
14327 				    tcps->tcps_dupack_fast_retransmit) {
14328 
14329 				/*
14330 				 * If we have reduced tcp_ssthresh
14331 				 * because of ECN, do not reduce it again
14332 				 * unless it is already one window of data
14333 				 * away.  After one window of data, tcp_cwr
14334 				 * should then be cleared.  Note that
14335 				 * for non ECN capable connection, tcp_cwr
14336 				 * should always be false.
14337 				 *
14338 				 * Adjust cwnd since the duplicate
14339 				 * ack indicates that a packet was
14340 				 * dropped (due to congestion.)
14341 				 */
14342 				if (!tcp->tcp_cwr) {
14343 					npkt = ((tcp->tcp_snxt -
14344 					    tcp->tcp_suna) >> 1) / mss;
14345 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14346 					    mss;
14347 					tcp->tcp_cwnd = (npkt +
14348 					    tcp->tcp_dupack_cnt) * mss;
14349 				}
14350 				if (tcp->tcp_ecn_ok) {
14351 					tcp->tcp_cwr = B_TRUE;
14352 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14353 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14354 				}
14355 
14356 				/*
14357 				 * We do Hoe's algorithm.  Refer to her
14358 				 * paper "Improving the Start-up Behavior
14359 				 * of a Congestion Control Scheme for TCP,"
14360 				 * appeared in SIGCOMM'96.
14361 				 *
14362 				 * Save highest seq no we have sent so far.
14363 				 * Be careful about the invisible FIN byte.
14364 				 */
14365 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14366 				    (tcp->tcp_unsent == 0)) {
14367 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14368 				} else {
14369 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14370 				}
14371 
14372 				/*
14373 				 * Do not allow bursty traffic during.
14374 				 * fast recovery.  Refer to Fall and Floyd's
14375 				 * paper "Simulation-based Comparisons of
14376 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14377 				 * This is a best current practise.
14378 				 */
14379 				tcp->tcp_snd_burst = TCP_CWND_SS;
14380 
14381 				/*
14382 				 * For SACK:
14383 				 * Calculate tcp_pipe, which is the
14384 				 * estimated number of bytes in
14385 				 * network.
14386 				 *
14387 				 * tcp_fack is the highest sack'ed seq num
14388 				 * TCP has received.
14389 				 *
14390 				 * tcp_pipe is explained in the above quoted
14391 				 * Fall and Floyd's paper.  tcp_fack is
14392 				 * explained in Mathis and Mahdavi's
14393 				 * "Forward Acknowledgment: Refining TCP
14394 				 * Congestion Control" in SIGCOMM '96.
14395 				 */
14396 				if (tcp->tcp_snd_sack_ok) {
14397 					ASSERT(tcp->tcp_sack_info != NULL);
14398 					if (tcp->tcp_notsack_list != NULL) {
14399 						tcp->tcp_pipe = tcp->tcp_snxt -
14400 						    tcp->tcp_fack;
14401 						tcp->tcp_sack_snxt = seg_ack;
14402 						flags |= TH_NEED_SACK_REXMIT;
14403 					} else {
14404 						/*
14405 						 * Always initialize tcp_pipe
14406 						 * even though we don't have
14407 						 * any SACK info.  If later
14408 						 * we get SACK info and
14409 						 * tcp_pipe is not initialized,
14410 						 * funny things will happen.
14411 						 */
14412 						tcp->tcp_pipe =
14413 						    tcp->tcp_cwnd_ssthresh;
14414 					}
14415 				} else {
14416 					flags |= TH_REXMIT_NEEDED;
14417 				} /* tcp_snd_sack_ok */
14418 
14419 				} else {
14420 					/*
14421 					 * Here we perform congestion
14422 					 * avoidance, but NOT slow start.
14423 					 * This is known as the Fast
14424 					 * Recovery Algorithm.
14425 					 */
14426 					if (tcp->tcp_snd_sack_ok &&
14427 					    tcp->tcp_notsack_list != NULL) {
14428 						flags |= TH_NEED_SACK_REXMIT;
14429 						tcp->tcp_pipe -= mss;
14430 						if (tcp->tcp_pipe < 0)
14431 							tcp->tcp_pipe = 0;
14432 					} else {
14433 					/*
14434 					 * We know that one more packet has
14435 					 * left the pipe thus we can update
14436 					 * cwnd.
14437 					 */
14438 					cwnd = tcp->tcp_cwnd + mss;
14439 					if (cwnd > tcp->tcp_cwnd_max)
14440 						cwnd = tcp->tcp_cwnd_max;
14441 					tcp->tcp_cwnd = cwnd;
14442 					if (tcp->tcp_unsent > 0)
14443 						flags |= TH_XMIT_NEEDED;
14444 					}
14445 				}
14446 			}
14447 		} else if (tcp->tcp_zero_win_probe) {
14448 			/*
14449 			 * If the window has opened, need to arrange
14450 			 * to send additional data.
14451 			 */
14452 			if (new_swnd != 0) {
14453 				/* tcp_suna != tcp_snxt */
14454 				/* Packet contains a window update */
14455 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14456 				tcp->tcp_zero_win_probe = 0;
14457 				tcp->tcp_timer_backoff = 0;
14458 				tcp->tcp_ms_we_have_waited = 0;
14459 
14460 				/*
14461 				 * Transmit starting with tcp_suna since
14462 				 * the one byte probe is not ack'ed.
14463 				 * If TCP has sent more than one identical
14464 				 * probe, tcp_rexmit will be set.  That means
14465 				 * tcp_ss_rexmit() will send out the one
14466 				 * byte along with new data.  Otherwise,
14467 				 * fake the retransmission.
14468 				 */
14469 				flags |= TH_XMIT_NEEDED;
14470 				if (!tcp->tcp_rexmit) {
14471 					tcp->tcp_rexmit = B_TRUE;
14472 					tcp->tcp_dupack_cnt = 0;
14473 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14474 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14475 				}
14476 			}
14477 		}
14478 		goto swnd_update;
14479 	}
14480 
14481 	/*
14482 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14483 	 * If the ACK value acks something that we have not yet sent, it might
14484 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14485 	 * other side.
14486 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14487 	 * state is handled above, so we can always just drop the segment and
14488 	 * send an ACK here.
14489 	 *
14490 	 * Should we send ACKs in response to ACK only segments?
14491 	 */
14492 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14493 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14494 		/* drop the received segment */
14495 		freemsg(mp);
14496 
14497 		/*
14498 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14499 		 * greater than 0, check if the number of such
14500 		 * bogus ACks is greater than that count.  If yes,
14501 		 * don't send back any ACK.  This prevents TCP from
14502 		 * getting into an ACK storm if somehow an attacker
14503 		 * successfully spoofs an acceptable segment to our
14504 		 * peer.
14505 		 */
14506 		if (tcp_drop_ack_unsent_cnt > 0 &&
14507 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14508 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14509 			return;
14510 		}
14511 		mp = tcp_ack_mp(tcp);
14512 		if (mp != NULL) {
14513 			BUMP_LOCAL(tcp->tcp_obsegs);
14514 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14515 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14516 		}
14517 		return;
14518 	}
14519 
14520 	/*
14521 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14522 	 * blocks that are covered by this ACK.
14523 	 */
14524 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14525 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14526 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14527 	}
14528 
14529 	/*
14530 	 * If we got an ACK after fast retransmit, check to see
14531 	 * if it is a partial ACK.  If it is not and the congestion
14532 	 * window was inflated to account for the other side's
14533 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14534 	 */
14535 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14536 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14537 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14538 			tcp->tcp_dupack_cnt = 0;
14539 			/*
14540 			 * Restore the orig tcp_cwnd_ssthresh after
14541 			 * fast retransmit phase.
14542 			 */
14543 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14544 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14545 			}
14546 			tcp->tcp_rexmit_max = seg_ack;
14547 			tcp->tcp_cwnd_cnt = 0;
14548 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14549 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14550 
14551 			/*
14552 			 * Remove all notsack info to avoid confusion with
14553 			 * the next fast retrasnmit/recovery phase.
14554 			 */
14555 			if (tcp->tcp_snd_sack_ok &&
14556 			    tcp->tcp_notsack_list != NULL) {
14557 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14558 			}
14559 		} else {
14560 			if (tcp->tcp_snd_sack_ok &&
14561 			    tcp->tcp_notsack_list != NULL) {
14562 				flags |= TH_NEED_SACK_REXMIT;
14563 				tcp->tcp_pipe -= mss;
14564 				if (tcp->tcp_pipe < 0)
14565 					tcp->tcp_pipe = 0;
14566 			} else {
14567 				/*
14568 				 * Hoe's algorithm:
14569 				 *
14570 				 * Retransmit the unack'ed segment and
14571 				 * restart fast recovery.  Note that we
14572 				 * need to scale back tcp_cwnd to the
14573 				 * original value when we started fast
14574 				 * recovery.  This is to prevent overly
14575 				 * aggressive behaviour in sending new
14576 				 * segments.
14577 				 */
14578 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14579 				    tcps->tcps_dupack_fast_retransmit * mss;
14580 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14581 				flags |= TH_REXMIT_NEEDED;
14582 			}
14583 		}
14584 	} else {
14585 		tcp->tcp_dupack_cnt = 0;
14586 		if (tcp->tcp_rexmit) {
14587 			/*
14588 			 * TCP is retranmitting.  If the ACK ack's all
14589 			 * outstanding data, update tcp_rexmit_max and
14590 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14591 			 * to the correct value.
14592 			 *
14593 			 * Note that SEQ_LEQ() is used.  This is to avoid
14594 			 * unnecessary fast retransmit caused by dup ACKs
14595 			 * received when TCP does slow start retransmission
14596 			 * after a time out.  During this phase, TCP may
14597 			 * send out segments which are already received.
14598 			 * This causes dup ACKs to be sent back.
14599 			 */
14600 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14601 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14602 					tcp->tcp_rexmit_nxt = seg_ack;
14603 				}
14604 				if (seg_ack != tcp->tcp_rexmit_max) {
14605 					flags |= TH_XMIT_NEEDED;
14606 				}
14607 			} else {
14608 				tcp->tcp_rexmit = B_FALSE;
14609 				tcp->tcp_xmit_zc_clean = B_FALSE;
14610 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14611 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14612 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14613 			}
14614 			tcp->tcp_ms_we_have_waited = 0;
14615 		}
14616 	}
14617 
14618 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14619 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14620 	tcp->tcp_suna = seg_ack;
14621 	if (tcp->tcp_zero_win_probe != 0) {
14622 		tcp->tcp_zero_win_probe = 0;
14623 		tcp->tcp_timer_backoff = 0;
14624 	}
14625 
14626 	/*
14627 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14628 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14629 	 * will not reach here.
14630 	 */
14631 	if (mp1 == NULL) {
14632 		goto fin_acked;
14633 	}
14634 
14635 	/*
14636 	 * Update the congestion window.
14637 	 *
14638 	 * If TCP is not ECN capable or TCP is ECN capable but the
14639 	 * congestion experience bit is not set, increase the tcp_cwnd as
14640 	 * usual.
14641 	 */
14642 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14643 		cwnd = tcp->tcp_cwnd;
14644 		add = mss;
14645 
14646 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14647 			/*
14648 			 * This is to prevent an increase of less than 1 MSS of
14649 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14650 			 * may send out tinygrams in order to preserve mblk
14651 			 * boundaries.
14652 			 *
14653 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14654 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14655 			 * increased by 1 MSS for every RTTs.
14656 			 */
14657 			if (tcp->tcp_cwnd_cnt <= 0) {
14658 				tcp->tcp_cwnd_cnt = cwnd + add;
14659 			} else {
14660 				tcp->tcp_cwnd_cnt -= add;
14661 				add = 0;
14662 			}
14663 		}
14664 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14665 	}
14666 
14667 	/* See if the latest urgent data has been acknowledged */
14668 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14669 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14670 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14671 
14672 	/* Can we update the RTT estimates? */
14673 	if (tcp->tcp_snd_ts_ok) {
14674 		/* Ignore zero timestamp echo-reply. */
14675 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14676 			tcp_set_rto(tcp, (int32_t)lbolt -
14677 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14678 		}
14679 
14680 		/* If needed, restart the timer. */
14681 		if (tcp->tcp_set_timer == 1) {
14682 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14683 			tcp->tcp_set_timer = 0;
14684 		}
14685 		/*
14686 		 * Update tcp_csuna in case the other side stops sending
14687 		 * us timestamps.
14688 		 */
14689 		tcp->tcp_csuna = tcp->tcp_snxt;
14690 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14691 		/*
14692 		 * An ACK sequence we haven't seen before, so get the RTT
14693 		 * and update the RTO. But first check if the timestamp is
14694 		 * valid to use.
14695 		 */
14696 		if ((mp1->b_next != NULL) &&
14697 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14698 			tcp_set_rto(tcp, (int32_t)lbolt -
14699 			    (int32_t)(intptr_t)mp1->b_prev);
14700 		else
14701 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14702 
14703 		/* Remeber the last sequence to be ACKed */
14704 		tcp->tcp_csuna = seg_ack;
14705 		if (tcp->tcp_set_timer == 1) {
14706 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14707 			tcp->tcp_set_timer = 0;
14708 		}
14709 	} else {
14710 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14711 	}
14712 
14713 	/* Eat acknowledged bytes off the xmit queue. */
14714 	for (;;) {
14715 		mblk_t	*mp2;
14716 		uchar_t	*wptr;
14717 
14718 		wptr = mp1->b_wptr;
14719 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14720 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14721 		if (bytes_acked < 0) {
14722 			mp1->b_rptr = wptr + bytes_acked;
14723 			/*
14724 			 * Set a new timestamp if all the bytes timed by the
14725 			 * old timestamp have been ack'ed.
14726 			 */
14727 			if (SEQ_GT(seg_ack,
14728 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14729 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14730 				mp1->b_next = NULL;
14731 			}
14732 			break;
14733 		}
14734 		mp1->b_next = NULL;
14735 		mp1->b_prev = NULL;
14736 		mp2 = mp1;
14737 		mp1 = mp1->b_cont;
14738 
14739 		/*
14740 		 * This notification is required for some zero-copy
14741 		 * clients to maintain a copy semantic. After the data
14742 		 * is ack'ed, client is safe to modify or reuse the buffer.
14743 		 */
14744 		if (tcp->tcp_snd_zcopy_aware &&
14745 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14746 			tcp_zcopy_notify(tcp);
14747 		freeb(mp2);
14748 		if (bytes_acked == 0) {
14749 			if (mp1 == NULL) {
14750 				/* Everything is ack'ed, clear the tail. */
14751 				tcp->tcp_xmit_tail = NULL;
14752 				/*
14753 				 * Cancel the timer unless we are still
14754 				 * waiting for an ACK for the FIN packet.
14755 				 */
14756 				if (tcp->tcp_timer_tid != 0 &&
14757 				    tcp->tcp_snxt == tcp->tcp_suna) {
14758 					(void) TCP_TIMER_CANCEL(tcp,
14759 					    tcp->tcp_timer_tid);
14760 					tcp->tcp_timer_tid = 0;
14761 				}
14762 				goto pre_swnd_update;
14763 			}
14764 			if (mp2 != tcp->tcp_xmit_tail)
14765 				break;
14766 			tcp->tcp_xmit_tail = mp1;
14767 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14768 			    (uintptr_t)INT_MAX);
14769 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14770 			    mp1->b_rptr);
14771 			break;
14772 		}
14773 		if (mp1 == NULL) {
14774 			/*
14775 			 * More was acked but there is nothing more
14776 			 * outstanding.  This means that the FIN was
14777 			 * just acked or that we're talking to a clown.
14778 			 */
14779 fin_acked:
14780 			ASSERT(tcp->tcp_fin_sent);
14781 			tcp->tcp_xmit_tail = NULL;
14782 			if (tcp->tcp_fin_sent) {
14783 				/* FIN was acked - making progress */
14784 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14785 				    !tcp->tcp_fin_acked)
14786 					tcp->tcp_ip_forward_progress = B_TRUE;
14787 				tcp->tcp_fin_acked = B_TRUE;
14788 				if (tcp->tcp_linger_tid != 0 &&
14789 				    TCP_TIMER_CANCEL(tcp,
14790 				    tcp->tcp_linger_tid) >= 0) {
14791 					tcp_stop_lingering(tcp);
14792 					freemsg(mp);
14793 					mp = NULL;
14794 				}
14795 			} else {
14796 				/*
14797 				 * We should never get here because
14798 				 * we have already checked that the
14799 				 * number of bytes ack'ed should be
14800 				 * smaller than or equal to what we
14801 				 * have sent so far (it is the
14802 				 * acceptability check of the ACK).
14803 				 * We can only get here if the send
14804 				 * queue is corrupted.
14805 				 *
14806 				 * Terminate the connection and
14807 				 * panic the system.  It is better
14808 				 * for us to panic instead of
14809 				 * continuing to avoid other disaster.
14810 				 */
14811 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14812 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14813 				panic("Memory corruption "
14814 				    "detected for connection %s.",
14815 				    tcp_display(tcp, NULL,
14816 				    DISP_ADDR_AND_PORT));
14817 				/*NOTREACHED*/
14818 			}
14819 			goto pre_swnd_update;
14820 		}
14821 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14822 	}
14823 	if (tcp->tcp_unsent) {
14824 		flags |= TH_XMIT_NEEDED;
14825 	}
14826 pre_swnd_update:
14827 	tcp->tcp_xmit_head = mp1;
14828 swnd_update:
14829 	/*
14830 	 * The following check is different from most other implementations.
14831 	 * For bi-directional transfer, when segments are dropped, the
14832 	 * "normal" check will not accept a window update in those
14833 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14834 	 * segments which are outside receiver's window.  As TCP accepts
14835 	 * the ack in those retransmitted segments, if the window update in
14836 	 * the same segment is not accepted, TCP will incorrectly calculates
14837 	 * that it can send more segments.  This can create a deadlock
14838 	 * with the receiver if its window becomes zero.
14839 	 */
14840 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14841 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14842 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14843 		/*
14844 		 * The criteria for update is:
14845 		 *
14846 		 * 1. the segment acknowledges some data.  Or
14847 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14848 		 * 3. the segment is not old and the advertised window is
14849 		 * larger than the previous advertised window.
14850 		 */
14851 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14852 			flags |= TH_XMIT_NEEDED;
14853 		tcp->tcp_swnd = new_swnd;
14854 		if (new_swnd > tcp->tcp_max_swnd)
14855 			tcp->tcp_max_swnd = new_swnd;
14856 		tcp->tcp_swl1 = seg_seq;
14857 		tcp->tcp_swl2 = seg_ack;
14858 	}
14859 est:
14860 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14861 
14862 		switch (tcp->tcp_state) {
14863 		case TCPS_FIN_WAIT_1:
14864 			if (tcp->tcp_fin_acked) {
14865 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14866 				/*
14867 				 * We implement the non-standard BSD/SunOS
14868 				 * FIN_WAIT_2 flushing algorithm.
14869 				 * If there is no user attached to this
14870 				 * TCP endpoint, then this TCP struct
14871 				 * could hang around forever in FIN_WAIT_2
14872 				 * state if the peer forgets to send us
14873 				 * a FIN.  To prevent this, we wait only
14874 				 * 2*MSL (a convenient time value) for
14875 				 * the FIN to arrive.  If it doesn't show up,
14876 				 * we flush the TCP endpoint.  This algorithm,
14877 				 * though a violation of RFC-793, has worked
14878 				 * for over 10 years in BSD systems.
14879 				 * Note: SunOS 4.x waits 675 seconds before
14880 				 * flushing the FIN_WAIT_2 connection.
14881 				 */
14882 				TCP_TIMER_RESTART(tcp,
14883 				    tcps->tcps_fin_wait_2_flush_interval);
14884 			}
14885 			break;
14886 		case TCPS_FIN_WAIT_2:
14887 			break;	/* Shutdown hook? */
14888 		case TCPS_LAST_ACK:
14889 			freemsg(mp);
14890 			if (tcp->tcp_fin_acked) {
14891 				(void) tcp_clean_death(tcp, 0, 19);
14892 				return;
14893 			}
14894 			goto xmit_check;
14895 		case TCPS_CLOSING:
14896 			if (tcp->tcp_fin_acked) {
14897 				tcp->tcp_state = TCPS_TIME_WAIT;
14898 				/*
14899 				 * Unconditionally clear the exclusive binding
14900 				 * bit so this TIME-WAIT connection won't
14901 				 * interfere with new ones.
14902 				 */
14903 				tcp->tcp_exclbind = 0;
14904 				if (!TCP_IS_DETACHED(tcp)) {
14905 					TCP_TIMER_RESTART(tcp,
14906 					    tcps->tcps_time_wait_interval);
14907 				} else {
14908 					tcp_time_wait_append(tcp);
14909 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14910 				}
14911 			}
14912 			/*FALLTHRU*/
14913 		case TCPS_CLOSE_WAIT:
14914 			freemsg(mp);
14915 			goto xmit_check;
14916 		default:
14917 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14918 			break;
14919 		}
14920 	}
14921 	if (flags & TH_FIN) {
14922 		/* Make sure we ack the fin */
14923 		flags |= TH_ACK_NEEDED;
14924 		if (!tcp->tcp_fin_rcvd) {
14925 			tcp->tcp_fin_rcvd = B_TRUE;
14926 			tcp->tcp_rnxt++;
14927 			tcph = tcp->tcp_tcph;
14928 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14929 
14930 			/*
14931 			 * Generate the ordrel_ind at the end unless we
14932 			 * are an eager guy.
14933 			 * In the eager case tcp_rsrv will do this when run
14934 			 * after tcp_accept is done.
14935 			 */
14936 			if (tcp->tcp_listener == NULL &&
14937 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14938 				flags |= TH_ORDREL_NEEDED;
14939 			switch (tcp->tcp_state) {
14940 			case TCPS_SYN_RCVD:
14941 			case TCPS_ESTABLISHED:
14942 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14943 				/* Keepalive? */
14944 				break;
14945 			case TCPS_FIN_WAIT_1:
14946 				if (!tcp->tcp_fin_acked) {
14947 					tcp->tcp_state = TCPS_CLOSING;
14948 					break;
14949 				}
14950 				/* FALLTHRU */
14951 			case TCPS_FIN_WAIT_2:
14952 				tcp->tcp_state = TCPS_TIME_WAIT;
14953 				/*
14954 				 * Unconditionally clear the exclusive binding
14955 				 * bit so this TIME-WAIT connection won't
14956 				 * interfere with new ones.
14957 				 */
14958 				tcp->tcp_exclbind = 0;
14959 				if (!TCP_IS_DETACHED(tcp)) {
14960 					TCP_TIMER_RESTART(tcp,
14961 					    tcps->tcps_time_wait_interval);
14962 				} else {
14963 					tcp_time_wait_append(tcp);
14964 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14965 				}
14966 				if (seg_len) {
14967 					/*
14968 					 * implies data piggybacked on FIN.
14969 					 * break to handle data.
14970 					 */
14971 					break;
14972 				}
14973 				freemsg(mp);
14974 				goto ack_check;
14975 			}
14976 		}
14977 	}
14978 	if (mp == NULL)
14979 		goto xmit_check;
14980 	if (seg_len == 0) {
14981 		freemsg(mp);
14982 		goto xmit_check;
14983 	}
14984 	if (mp->b_rptr == mp->b_wptr) {
14985 		/*
14986 		 * The header has been consumed, so we remove the
14987 		 * zero-length mblk here.
14988 		 */
14989 		mp1 = mp;
14990 		mp = mp->b_cont;
14991 		freeb(mp1);
14992 	}
14993 update_ack:
14994 	tcph = tcp->tcp_tcph;
14995 	tcp->tcp_rack_cnt++;
14996 	{
14997 		uint32_t cur_max;
14998 
14999 		cur_max = tcp->tcp_rack_cur_max;
15000 		if (tcp->tcp_rack_cnt >= cur_max) {
15001 			/*
15002 			 * We have more unacked data than we should - send
15003 			 * an ACK now.
15004 			 */
15005 			flags |= TH_ACK_NEEDED;
15006 			cur_max++;
15007 			if (cur_max > tcp->tcp_rack_abs_max)
15008 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15009 			else
15010 				tcp->tcp_rack_cur_max = cur_max;
15011 		} else if (TCP_IS_DETACHED(tcp)) {
15012 			/* We don't have an ACK timer for detached TCP. */
15013 			flags |= TH_ACK_NEEDED;
15014 		} else if (seg_len < mss) {
15015 			/*
15016 			 * If we get a segment that is less than an mss, and we
15017 			 * already have unacknowledged data, and the amount
15018 			 * unacknowledged is not a multiple of mss, then we
15019 			 * better generate an ACK now.  Otherwise, this may be
15020 			 * the tail piece of a transaction, and we would rather
15021 			 * wait for the response.
15022 			 */
15023 			uint32_t udif;
15024 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
15025 			    (uintptr_t)INT_MAX);
15026 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
15027 			if (udif && (udif % mss))
15028 				flags |= TH_ACK_NEEDED;
15029 			else
15030 				flags |= TH_ACK_TIMER_NEEDED;
15031 		} else {
15032 			/* Start delayed ack timer */
15033 			flags |= TH_ACK_TIMER_NEEDED;
15034 		}
15035 	}
15036 	tcp->tcp_rnxt += seg_len;
15037 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15038 
15039 	if (mp == NULL)
15040 		goto xmit_check;
15041 
15042 	/* Update SACK list */
15043 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15044 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15045 		    &(tcp->tcp_num_sack_blk));
15046 	}
15047 
15048 	if (tcp->tcp_urp_mp) {
15049 		tcp->tcp_urp_mp->b_cont = mp;
15050 		mp = tcp->tcp_urp_mp;
15051 		tcp->tcp_urp_mp = NULL;
15052 		/* Ready for a new signal. */
15053 		tcp->tcp_urp_last_valid = B_FALSE;
15054 #ifdef DEBUG
15055 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15056 		    "tcp_rput: sending exdata_ind %s",
15057 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15058 #endif /* DEBUG */
15059 	}
15060 
15061 	/*
15062 	 * Check for ancillary data changes compared to last segment.
15063 	 */
15064 	if (tcp->tcp_ipv6_recvancillary != 0) {
15065 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15066 		ASSERT(mp != NULL);
15067 	}
15068 
15069 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15070 		/*
15071 		 * Side queue inbound data until the accept happens.
15072 		 * tcp_accept/tcp_rput drains this when the accept happens.
15073 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15074 		 * T_EXDATA_IND) it is queued on b_next.
15075 		 * XXX Make urgent data use this. Requires:
15076 		 *	Removing tcp_listener check for TH_URG
15077 		 *	Making M_PCPROTO and MARK messages skip the eager case
15078 		 */
15079 
15080 		if (tcp->tcp_kssl_pending) {
15081 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
15082 			    mblk_t *, mp);
15083 			tcp_kssl_input(tcp, mp);
15084 		} else {
15085 			tcp_rcv_enqueue(tcp, mp, seg_len);
15086 		}
15087 	} else {
15088 		sodirect_t	*sodp = tcp->tcp_sodirect;
15089 
15090 		/*
15091 		 * If an sodirect connection and an enabled sodirect_t then
15092 		 * sodp will be set to point to the tcp_t/sonode_t shared
15093 		 * sodirect_t and the sodirect_t's lock will be held.
15094 		 */
15095 		if (sodp != NULL) {
15096 			mutex_enter(sodp->sod_lockp);
15097 			if (!(sodp->sod_state & SOD_ENABLED) ||
15098 			    (tcp->tcp_kssl_ctx != NULL &&
15099 			    DB_TYPE(mp) == M_DATA)) {
15100 				sodp = NULL;
15101 			}
15102 			mutex_exit(sodp->sod_lockp);
15103 		}
15104 		if (mp->b_datap->db_type != M_DATA ||
15105 		    (flags & TH_MARKNEXT_NEEDED)) {
15106 			if (IPCL_IS_NONSTR(connp)) {
15107 				int error;
15108 
15109 				if ((*connp->conn_upcalls->su_recv)
15110 				    (connp->conn_upper_handle, mp,
15111 				    seg_len, 0, &error, NULL) <= 0) {
15112 					if (error == ENOSPC) {
15113 						tcp->tcp_rwnd -= seg_len;
15114 					} else if (error == EOPNOTSUPP) {
15115 						tcp_rcv_enqueue(tcp, mp,
15116 						    seg_len);
15117 					}
15118 				}
15119 			} else if (sodp != NULL) {
15120 				mutex_enter(sodp->sod_lockp);
15121 				SOD_UIOAFINI(sodp);
15122 				if (!SOD_QEMPTY(sodp) &&
15123 				    (sodp->sod_state & SOD_WAKE_NOT)) {
15124 					flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15125 					/* sod_wakeup() did the mutex_exit() */
15126 				} else {
15127 					mutex_exit(sodp->sod_lockp);
15128 				}
15129 			} else if (tcp->tcp_rcv_list != NULL) {
15130 				flags |= tcp_rcv_drain(tcp);
15131 			}
15132 			ASSERT(tcp->tcp_rcv_list == NULL ||
15133 			    tcp->tcp_fused_sigurg);
15134 
15135 			if (flags & TH_MARKNEXT_NEEDED) {
15136 #ifdef DEBUG
15137 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15138 				    "tcp_rput: sending MSGMARKNEXT %s",
15139 				    tcp_display(tcp, NULL,
15140 				    DISP_PORT_ONLY));
15141 #endif /* DEBUG */
15142 				mp->b_flag |= MSGMARKNEXT;
15143 				flags &= ~TH_MARKNEXT_NEEDED;
15144 			}
15145 
15146 			/* Does this need SSL processing first? */
15147 			if ((tcp->tcp_kssl_ctx != NULL) &&
15148 			    (DB_TYPE(mp) == M_DATA)) {
15149 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15150 				    mblk_t *, mp);
15151 				tcp_kssl_input(tcp, mp);
15152 			} else if (!IPCL_IS_NONSTR(connp)) {
15153 				/* Already handled non-STREAMS case. */
15154 				putnext(tcp->tcp_rq, mp);
15155 				if (!canputnext(tcp->tcp_rq))
15156 					tcp->tcp_rwnd -= seg_len;
15157 			}
15158 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15159 		    (DB_TYPE(mp) == M_DATA)) {
15160 			/* Does this need SSL processing first? */
15161 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
15162 			tcp_kssl_input(tcp, mp);
15163 		} else if (IPCL_IS_NONSTR(connp)) {
15164 			/* Non-STREAMS socket */
15165 			boolean_t push = flags & (TH_PUSH|TH_FIN);
15166 			int	error;
15167 
15168 			if ((*connp->conn_upcalls->su_recv)(
15169 			    connp->conn_upper_handle,
15170 			    mp, seg_len, 0, &error, &push) <= 0) {
15171 				if (error == ENOSPC) {
15172 					tcp->tcp_rwnd -= seg_len;
15173 				} else if (error == EOPNOTSUPP) {
15174 					tcp_rcv_enqueue(tcp, mp, seg_len);
15175 				}
15176 			} else if (push) {
15177 				/*
15178 				 * PUSH bit set and sockfs is not
15179 				 * flow controlled
15180 				 */
15181 				flags |= tcp_rwnd_reopen(tcp);
15182 			}
15183 		} else if (sodp != NULL) {
15184 			/*
15185 			 * Sodirect so all mblk_t's are queued on the
15186 			 * socket directly, check for wakeup of blocked
15187 			 * reader (if any), and last if flow-controled.
15188 			 */
15189 			mutex_enter(sodp->sod_lockp);
15190 			flags |= tcp_rcv_sod_enqueue(tcp, sodp, mp, seg_len);
15191 			if ((sodp->sod_state & SOD_WAKE_NEED) ||
15192 			    (flags & (TH_PUSH|TH_FIN))) {
15193 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15194 				/* sod_wakeup() did the mutex_exit() */
15195 			} else {
15196 				if (SOD_QFULL(sodp)) {
15197 					/* Q is full, need backenable */
15198 					SOD_QSETBE(sodp);
15199 				}
15200 				mutex_exit(sodp->sod_lockp);
15201 			}
15202 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15203 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_recv_hiwater >> 3) {
15204 			if (tcp->tcp_rcv_list != NULL) {
15205 				/*
15206 				 * Enqueue the new segment first and then
15207 				 * call tcp_rcv_drain() to send all data
15208 				 * up.  The other way to do this is to
15209 				 * send all queued data up and then call
15210 				 * putnext() to send the new segment up.
15211 				 * This way can remove the else part later
15212 				 * on.
15213 				 *
15214 				 * We don't do this to avoid one more call to
15215 				 * canputnext() as tcp_rcv_drain() needs to
15216 				 * call canputnext().
15217 				 */
15218 				tcp_rcv_enqueue(tcp, mp, seg_len);
15219 				flags |= tcp_rcv_drain(tcp);
15220 			} else {
15221 				putnext(tcp->tcp_rq, mp);
15222 				if (!canputnext(tcp->tcp_rq))
15223 					tcp->tcp_rwnd -= seg_len;
15224 			}
15225 		} else {
15226 			/*
15227 			 * Enqueue all packets when processing an mblk
15228 			 * from the co queue and also enqueue normal packets.
15229 			 * For packets which belong to SSL stream do SSL
15230 			 * processing first.
15231 			 */
15232 			tcp_rcv_enqueue(tcp, mp, seg_len);
15233 		}
15234 		/*
15235 		 * Make sure the timer is running if we have data waiting
15236 		 * for a push bit. This provides resiliency against
15237 		 * implementations that do not correctly generate push bits.
15238 		 *
15239 		 * Note, for sodirect if Q isn't empty and there's not a
15240 		 * pending wakeup then we need a timer. Also note that sodp
15241 		 * is assumed to be still valid after exit()ing the sod_lockp
15242 		 * above and while the SOD state can change it can only change
15243 		 * such that the Q is empty now even though data was added
15244 		 * above.
15245 		 */
15246 		if (!IPCL_IS_NONSTR(connp) &&
15247 		    ((sodp != NULL && !SOD_QEMPTY(sodp) &&
15248 		    (sodp->sod_state & SOD_WAKE_NOT)) ||
15249 		    (sodp == NULL && tcp->tcp_rcv_list != NULL)) &&
15250 		    tcp->tcp_push_tid == 0) {
15251 			/*
15252 			 * The connection may be closed at this point, so don't
15253 			 * do anything for a detached tcp.
15254 			 */
15255 			if (!TCP_IS_DETACHED(tcp))
15256 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15257 				    tcp_push_timer,
15258 				    MSEC_TO_TICK(
15259 				    tcps->tcps_push_timer_interval));
15260 		}
15261 	}
15262 
15263 xmit_check:
15264 	/* Is there anything left to do? */
15265 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15266 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15267 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15268 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15269 		goto done;
15270 
15271 	/* Any transmit work to do and a non-zero window? */
15272 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15273 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15274 		if (flags & TH_REXMIT_NEEDED) {
15275 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15276 
15277 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15278 			if (snd_size > mss)
15279 				snd_size = mss;
15280 			if (snd_size > tcp->tcp_swnd)
15281 				snd_size = tcp->tcp_swnd;
15282 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15283 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15284 			    B_TRUE);
15285 
15286 			if (mp1 != NULL) {
15287 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15288 				tcp->tcp_csuna = tcp->tcp_snxt;
15289 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15290 				UPDATE_MIB(&tcps->tcps_mib,
15291 				    tcpRetransBytes, snd_size);
15292 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15293 			}
15294 		}
15295 		if (flags & TH_NEED_SACK_REXMIT) {
15296 			tcp_sack_rxmit(tcp, &flags);
15297 		}
15298 		/*
15299 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15300 		 * out new segment.  Note that tcp_rexmit should not be
15301 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15302 		 */
15303 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15304 			if (!tcp->tcp_rexmit) {
15305 				tcp_wput_data(tcp, NULL, B_FALSE);
15306 			} else {
15307 				tcp_ss_rexmit(tcp);
15308 			}
15309 		}
15310 		/*
15311 		 * Adjust tcp_cwnd back to normal value after sending
15312 		 * new data segments.
15313 		 */
15314 		if (flags & TH_LIMIT_XMIT) {
15315 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15316 			/*
15317 			 * This will restart the timer.  Restarting the
15318 			 * timer is used to avoid a timeout before the
15319 			 * limited transmitted segment's ACK gets back.
15320 			 */
15321 			if (tcp->tcp_xmit_head != NULL)
15322 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15323 		}
15324 
15325 		/* Anything more to do? */
15326 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15327 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15328 			goto done;
15329 	}
15330 ack_check:
15331 	if (flags & TH_SEND_URP_MARK) {
15332 		ASSERT(tcp->tcp_urp_mark_mp);
15333 		ASSERT(!IPCL_IS_NONSTR(connp));
15334 		/*
15335 		 * Send up any queued data and then send the mark message
15336 		 */
15337 		sodirect_t *sodp;
15338 
15339 		SOD_PTR_ENTER(tcp, sodp);
15340 
15341 		mp1 = tcp->tcp_urp_mark_mp;
15342 		tcp->tcp_urp_mark_mp = NULL;
15343 		if (sodp != NULL) {
15344 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15345 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15346 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15347 			}
15348 			ASSERT(tcp->tcp_rcv_list == NULL);
15349 
15350 			flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15351 			/* sod_wakeup() does the mutex_exit() */
15352 		} else if (tcp->tcp_rcv_list != NULL) {
15353 			flags |= tcp_rcv_drain(tcp);
15354 
15355 			ASSERT(tcp->tcp_rcv_list == NULL ||
15356 			    tcp->tcp_fused_sigurg);
15357 
15358 		}
15359 		putnext(tcp->tcp_rq, mp1);
15360 #ifdef DEBUG
15361 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15362 		    "tcp_rput: sending zero-length %s %s",
15363 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15364 		    "MSGNOTMARKNEXT"),
15365 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15366 #endif /* DEBUG */
15367 		flags &= ~TH_SEND_URP_MARK;
15368 	}
15369 	if (flags & TH_ACK_NEEDED) {
15370 		/*
15371 		 * Time to send an ack for some reason.
15372 		 */
15373 		mp1 = tcp_ack_mp(tcp);
15374 
15375 		if (mp1 != NULL) {
15376 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15377 			BUMP_LOCAL(tcp->tcp_obsegs);
15378 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15379 		}
15380 		if (tcp->tcp_ack_tid != 0) {
15381 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15382 			tcp->tcp_ack_tid = 0;
15383 		}
15384 	}
15385 	if (flags & TH_ACK_TIMER_NEEDED) {
15386 		/*
15387 		 * Arrange for deferred ACK or push wait timeout.
15388 		 * Start timer if it is not already running.
15389 		 */
15390 		if (tcp->tcp_ack_tid == 0) {
15391 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15392 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15393 			    (clock_t)tcps->tcps_local_dack_interval :
15394 			    (clock_t)tcps->tcps_deferred_ack_interval));
15395 		}
15396 	}
15397 	if (flags & TH_ORDREL_NEEDED) {
15398 		/*
15399 		 * Send up the ordrel_ind unless we are an eager guy.
15400 		 * In the eager case tcp_rsrv will do this when run
15401 		 * after tcp_accept is done.
15402 		 */
15403 		sodirect_t *sodp;
15404 
15405 		ASSERT(tcp->tcp_listener == NULL);
15406 
15407 		if (IPCL_IS_NONSTR(connp)) {
15408 			ASSERT(tcp->tcp_ordrel_mp == NULL);
15409 			tcp->tcp_ordrel_done = B_TRUE;
15410 			(*connp->conn_upcalls->su_opctl)
15411 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
15412 			goto done;
15413 		}
15414 
15415 		SOD_PTR_ENTER(tcp, sodp);
15416 		if (sodp != NULL) {
15417 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15418 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15419 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15420 			}
15421 			/* No more sodirect */
15422 			tcp->tcp_sodirect = NULL;
15423 			if (!SOD_QEMPTY(sodp)) {
15424 				/* Mblk(s) to process, notify */
15425 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15426 				/* sod_wakeup() does the mutex_exit() */
15427 			} else {
15428 				/* Nothing to process */
15429 				mutex_exit(sodp->sod_lockp);
15430 			}
15431 		} else if (tcp->tcp_rcv_list != NULL) {
15432 			/*
15433 			 * Push any mblk(s) enqueued from co processing.
15434 			 */
15435 			flags |= tcp_rcv_drain(tcp);
15436 
15437 			ASSERT(tcp->tcp_rcv_list == NULL ||
15438 			    tcp->tcp_fused_sigurg);
15439 		}
15440 
15441 		mp1 = tcp->tcp_ordrel_mp;
15442 		tcp->tcp_ordrel_mp = NULL;
15443 		tcp->tcp_ordrel_done = B_TRUE;
15444 		putnext(tcp->tcp_rq, mp1);
15445 	}
15446 done:
15447 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15448 }
15449 
15450 /*
15451  * This function does PAWS protection check. Returns B_TRUE if the
15452  * segment passes the PAWS test, else returns B_FALSE.
15453  */
15454 boolean_t
15455 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15456 {
15457 	uint8_t	flags;
15458 	int	options;
15459 	uint8_t *up;
15460 
15461 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15462 	/*
15463 	 * If timestamp option is aligned nicely, get values inline,
15464 	 * otherwise call general routine to parse.  Only do that
15465 	 * if timestamp is the only option.
15466 	 */
15467 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15468 	    TCPOPT_REAL_TS_LEN &&
15469 	    OK_32PTR((up = ((uint8_t *)tcph) +
15470 	    TCP_MIN_HEADER_LENGTH)) &&
15471 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15472 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15473 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15474 
15475 		options = TCP_OPT_TSTAMP_PRESENT;
15476 	} else {
15477 		if (tcp->tcp_snd_sack_ok) {
15478 			tcpoptp->tcp = tcp;
15479 		} else {
15480 			tcpoptp->tcp = NULL;
15481 		}
15482 		options = tcp_parse_options(tcph, tcpoptp);
15483 	}
15484 
15485 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15486 		/*
15487 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15488 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15489 		 */
15490 		if ((flags & TH_RST) == 0 &&
15491 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15492 		    tcp->tcp_ts_recent)) {
15493 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15494 			    PAWS_TIMEOUT)) {
15495 				/* This segment is not acceptable. */
15496 				return (B_FALSE);
15497 			} else {
15498 				/*
15499 				 * Connection has been idle for
15500 				 * too long.  Reset the timestamp
15501 				 * and assume the segment is valid.
15502 				 */
15503 				tcp->tcp_ts_recent =
15504 				    tcpoptp->tcp_opt_ts_val;
15505 			}
15506 		}
15507 	} else {
15508 		/*
15509 		 * If we don't get a timestamp on every packet, we
15510 		 * figure we can't really trust 'em, so we stop sending
15511 		 * and parsing them.
15512 		 */
15513 		tcp->tcp_snd_ts_ok = B_FALSE;
15514 
15515 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15516 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15517 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15518 		/*
15519 		 * Adjust the tcp_mss accordingly. We also need to
15520 		 * adjust tcp_cwnd here in accordance with the new mss.
15521 		 * But we avoid doing a slow start here so as to not
15522 		 * to lose on the transfer rate built up so far.
15523 		 */
15524 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15525 		if (tcp->tcp_snd_sack_ok) {
15526 			ASSERT(tcp->tcp_sack_info != NULL);
15527 			tcp->tcp_max_sack_blk = 4;
15528 		}
15529 	}
15530 	return (B_TRUE);
15531 }
15532 
15533 /*
15534  * Attach ancillary data to a received TCP segments for the
15535  * ancillary pieces requested by the application that are
15536  * different than they were in the previous data segment.
15537  *
15538  * Save the "current" values once memory allocation is ok so that
15539  * when memory allocation fails we can just wait for the next data segment.
15540  */
15541 static mblk_t *
15542 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15543 {
15544 	struct T_optdata_ind *todi;
15545 	int optlen;
15546 	uchar_t *optptr;
15547 	struct T_opthdr *toh;
15548 	uint_t addflag;	/* Which pieces to add */
15549 	mblk_t *mp1;
15550 
15551 	optlen = 0;
15552 	addflag = 0;
15553 	/* If app asked for pktinfo and the index has changed ... */
15554 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15555 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15556 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15557 		optlen += sizeof (struct T_opthdr) +
15558 		    sizeof (struct in6_pktinfo);
15559 		addflag |= TCP_IPV6_RECVPKTINFO;
15560 	}
15561 	/* If app asked for hoplimit and it has changed ... */
15562 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15563 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15564 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15565 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15566 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15567 	}
15568 	/* If app asked for tclass and it has changed ... */
15569 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15570 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15571 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15572 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15573 		addflag |= TCP_IPV6_RECVTCLASS;
15574 	}
15575 	/*
15576 	 * If app asked for hopbyhop headers and it has changed ...
15577 	 * For security labels, note that (1) security labels can't change on
15578 	 * a connected socket at all, (2) we're connected to at most one peer,
15579 	 * (3) if anything changes, then it must be some other extra option.
15580 	 */
15581 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15582 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15583 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15584 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15585 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15586 		    tcp->tcp_label_len;
15587 		addflag |= TCP_IPV6_RECVHOPOPTS;
15588 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15589 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15590 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15591 			return (mp);
15592 	}
15593 	/* If app asked for dst headers before routing headers ... */
15594 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15595 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15596 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15597 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15598 		optlen += sizeof (struct T_opthdr) +
15599 		    ipp->ipp_rtdstoptslen;
15600 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15601 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15602 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15603 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15604 			return (mp);
15605 	}
15606 	/* If app asked for routing headers and it has changed ... */
15607 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15608 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15609 	    (ipp->ipp_fields & IPPF_RTHDR),
15610 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15611 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15612 		addflag |= TCP_IPV6_RECVRTHDR;
15613 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15614 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15615 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15616 			return (mp);
15617 	}
15618 	/* If app asked for dest headers and it has changed ... */
15619 	if ((tcp->tcp_ipv6_recvancillary &
15620 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15621 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15622 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15623 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15624 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15625 		addflag |= TCP_IPV6_RECVDSTOPTS;
15626 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15627 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15628 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15629 			return (mp);
15630 	}
15631 
15632 	if (optlen == 0) {
15633 		/* Nothing to add */
15634 		return (mp);
15635 	}
15636 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15637 	if (mp1 == NULL) {
15638 		/*
15639 		 * Defer sending ancillary data until the next TCP segment
15640 		 * arrives.
15641 		 */
15642 		return (mp);
15643 	}
15644 	mp1->b_cont = mp;
15645 	mp = mp1;
15646 	mp->b_wptr += sizeof (*todi) + optlen;
15647 	mp->b_datap->db_type = M_PROTO;
15648 	todi = (struct T_optdata_ind *)mp->b_rptr;
15649 	todi->PRIM_type = T_OPTDATA_IND;
15650 	todi->DATA_flag = 1;	/* MORE data */
15651 	todi->OPT_length = optlen;
15652 	todi->OPT_offset = sizeof (*todi);
15653 	optptr = (uchar_t *)&todi[1];
15654 	/*
15655 	 * If app asked for pktinfo and the index has changed ...
15656 	 * Note that the local address never changes for the connection.
15657 	 */
15658 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15659 		struct in6_pktinfo *pkti;
15660 
15661 		toh = (struct T_opthdr *)optptr;
15662 		toh->level = IPPROTO_IPV6;
15663 		toh->name = IPV6_PKTINFO;
15664 		toh->len = sizeof (*toh) + sizeof (*pkti);
15665 		toh->status = 0;
15666 		optptr += sizeof (*toh);
15667 		pkti = (struct in6_pktinfo *)optptr;
15668 		if (tcp->tcp_ipversion == IPV6_VERSION)
15669 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15670 		else
15671 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15672 			    &pkti->ipi6_addr);
15673 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15674 		optptr += sizeof (*pkti);
15675 		ASSERT(OK_32PTR(optptr));
15676 		/* Save as "last" value */
15677 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15678 	}
15679 	/* If app asked for hoplimit and it has changed ... */
15680 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15681 		toh = (struct T_opthdr *)optptr;
15682 		toh->level = IPPROTO_IPV6;
15683 		toh->name = IPV6_HOPLIMIT;
15684 		toh->len = sizeof (*toh) + sizeof (uint_t);
15685 		toh->status = 0;
15686 		optptr += sizeof (*toh);
15687 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15688 		optptr += sizeof (uint_t);
15689 		ASSERT(OK_32PTR(optptr));
15690 		/* Save as "last" value */
15691 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15692 	}
15693 	/* If app asked for tclass and it has changed ... */
15694 	if (addflag & TCP_IPV6_RECVTCLASS) {
15695 		toh = (struct T_opthdr *)optptr;
15696 		toh->level = IPPROTO_IPV6;
15697 		toh->name = IPV6_TCLASS;
15698 		toh->len = sizeof (*toh) + sizeof (uint_t);
15699 		toh->status = 0;
15700 		optptr += sizeof (*toh);
15701 		*(uint_t *)optptr = ipp->ipp_tclass;
15702 		optptr += sizeof (uint_t);
15703 		ASSERT(OK_32PTR(optptr));
15704 		/* Save as "last" value */
15705 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15706 	}
15707 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15708 		toh = (struct T_opthdr *)optptr;
15709 		toh->level = IPPROTO_IPV6;
15710 		toh->name = IPV6_HOPOPTS;
15711 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15712 		    tcp->tcp_label_len;
15713 		toh->status = 0;
15714 		optptr += sizeof (*toh);
15715 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15716 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15717 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15718 		ASSERT(OK_32PTR(optptr));
15719 		/* Save as last value */
15720 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15721 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15722 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15723 	}
15724 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15725 		toh = (struct T_opthdr *)optptr;
15726 		toh->level = IPPROTO_IPV6;
15727 		toh->name = IPV6_RTHDRDSTOPTS;
15728 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15729 		toh->status = 0;
15730 		optptr += sizeof (*toh);
15731 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15732 		optptr += ipp->ipp_rtdstoptslen;
15733 		ASSERT(OK_32PTR(optptr));
15734 		/* Save as last value */
15735 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15736 		    &tcp->tcp_rtdstoptslen,
15737 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15738 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15739 	}
15740 	if (addflag & TCP_IPV6_RECVRTHDR) {
15741 		toh = (struct T_opthdr *)optptr;
15742 		toh->level = IPPROTO_IPV6;
15743 		toh->name = IPV6_RTHDR;
15744 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15745 		toh->status = 0;
15746 		optptr += sizeof (*toh);
15747 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15748 		optptr += ipp->ipp_rthdrlen;
15749 		ASSERT(OK_32PTR(optptr));
15750 		/* Save as last value */
15751 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15752 		    (ipp->ipp_fields & IPPF_RTHDR),
15753 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15754 	}
15755 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15756 		toh = (struct T_opthdr *)optptr;
15757 		toh->level = IPPROTO_IPV6;
15758 		toh->name = IPV6_DSTOPTS;
15759 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15760 		toh->status = 0;
15761 		optptr += sizeof (*toh);
15762 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15763 		optptr += ipp->ipp_dstoptslen;
15764 		ASSERT(OK_32PTR(optptr));
15765 		/* Save as last value */
15766 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15767 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15768 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15769 	}
15770 	ASSERT(optptr == mp->b_wptr);
15771 	return (mp);
15772 }
15773 
15774 /*
15775  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15776  * messages.
15777  */
15778 void
15779 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15780 {
15781 	uchar_t	*rptr = mp->b_rptr;
15782 	queue_t	*q = tcp->tcp_rq;
15783 	struct T_error_ack *tea;
15784 
15785 	switch (mp->b_datap->db_type) {
15786 	case M_PROTO:
15787 	case M_PCPROTO:
15788 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15789 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15790 			break;
15791 		tea = (struct T_error_ack *)rptr;
15792 		ASSERT(tea->PRIM_type != T_BIND_ACK);
15793 		ASSERT(tea->ERROR_prim != O_T_BIND_REQ &&
15794 		    tea->ERROR_prim != T_BIND_REQ);
15795 		switch (tea->PRIM_type) {
15796 		case T_ERROR_ACK:
15797 			if (tcp->tcp_debug) {
15798 				(void) strlog(TCP_MOD_ID, 0, 1,
15799 				    SL_TRACE|SL_ERROR,
15800 				    "tcp_rput_other: case T_ERROR_ACK, "
15801 				    "ERROR_prim == %d",
15802 				    tea->ERROR_prim);
15803 			}
15804 			switch (tea->ERROR_prim) {
15805 			case T_SVR4_OPTMGMT_REQ:
15806 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15807 					/* T_OPTMGMT_REQ generated by TCP */
15808 					printf("T_SVR4_OPTMGMT_REQ failed "
15809 					    "%d/%d - dropped (cnt %d)\n",
15810 					    tea->TLI_error, tea->UNIX_error,
15811 					    tcp->tcp_drop_opt_ack_cnt);
15812 					freemsg(mp);
15813 					tcp->tcp_drop_opt_ack_cnt--;
15814 					return;
15815 				}
15816 				break;
15817 			}
15818 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15819 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15820 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15821 				    "- dropped (cnt %d)\n",
15822 				    tea->TLI_error, tea->UNIX_error,
15823 				    tcp->tcp_drop_opt_ack_cnt);
15824 				freemsg(mp);
15825 				tcp->tcp_drop_opt_ack_cnt--;
15826 				return;
15827 			}
15828 			break;
15829 		case T_OPTMGMT_ACK:
15830 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15831 				/* T_OPTMGMT_REQ generated by TCP */
15832 				freemsg(mp);
15833 				tcp->tcp_drop_opt_ack_cnt--;
15834 				return;
15835 			}
15836 			break;
15837 		default:
15838 			ASSERT(tea->ERROR_prim != T_UNBIND_REQ);
15839 			break;
15840 		}
15841 		break;
15842 	case M_FLUSH:
15843 		if (*rptr & FLUSHR)
15844 			flushq(q, FLUSHDATA);
15845 		break;
15846 	default:
15847 		/* M_CTL will be directly sent to tcp_icmp_error() */
15848 		ASSERT(DB_TYPE(mp) != M_CTL);
15849 		break;
15850 	}
15851 	/*
15852 	 * Make sure we set this bit before sending the ACK for
15853 	 * bind. Otherwise accept could possibly run and free
15854 	 * this tcp struct.
15855 	 */
15856 	ASSERT(q != NULL);
15857 	putnext(q, mp);
15858 }
15859 
15860 /* ARGSUSED */
15861 static void
15862 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15863 {
15864 	conn_t	*connp = (conn_t *)arg;
15865 	tcp_t	*tcp = connp->conn_tcp;
15866 	queue_t	*q = tcp->tcp_rq;
15867 	uint_t	thwin;
15868 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15869 	sodirect_t	*sodp;
15870 	boolean_t	fc;
15871 
15872 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15873 	tcp->tcp_rsrv_mp = mp;
15874 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15875 
15876 	TCP_STAT(tcps, tcp_rsrv_calls);
15877 
15878 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15879 		return;
15880 	}
15881 
15882 	if (tcp->tcp_fused) {
15883 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15884 
15885 		ASSERT(tcp->tcp_fused);
15886 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15887 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15888 		ASSERT(!TCP_IS_DETACHED(tcp));
15889 		ASSERT(tcp->tcp_connp->conn_sqp ==
15890 		    peer_tcp->tcp_connp->conn_sqp);
15891 
15892 		/*
15893 		 * Normally we would not get backenabled in synchronous
15894 		 * streams mode, but in case this happens, we need to plug
15895 		 * synchronous streams during our drain to prevent a race
15896 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
15897 		 */
15898 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
15899 		if (tcp->tcp_rcv_list != NULL)
15900 			(void) tcp_rcv_drain(tcp);
15901 
15902 		if (peer_tcp > tcp) {
15903 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15904 			mutex_enter(&tcp->tcp_non_sq_lock);
15905 		} else {
15906 			mutex_enter(&tcp->tcp_non_sq_lock);
15907 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15908 		}
15909 
15910 		if (peer_tcp->tcp_flow_stopped &&
15911 		    (TCP_UNSENT_BYTES(peer_tcp) <=
15912 		    peer_tcp->tcp_xmit_lowater)) {
15913 			tcp_clrqfull(peer_tcp);
15914 		}
15915 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
15916 		mutex_exit(&tcp->tcp_non_sq_lock);
15917 
15918 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
15919 		TCP_STAT(tcps, tcp_fusion_backenabled);
15920 		return;
15921 	}
15922 
15923 	SOD_PTR_ENTER(tcp, sodp);
15924 	if (sodp != NULL) {
15925 		/* An sodirect connection */
15926 		if (SOD_QFULL(sodp)) {
15927 			/* Flow-controlled, need another back-enable */
15928 			fc = B_TRUE;
15929 			SOD_QSETBE(sodp);
15930 		} else {
15931 			/* Not flow-controlled */
15932 			fc = B_FALSE;
15933 		}
15934 		mutex_exit(sodp->sod_lockp);
15935 	} else if (canputnext(q)) {
15936 		/* STREAMS, not flow-controlled */
15937 		fc = B_FALSE;
15938 	} else {
15939 		/* STREAMS, flow-controlled */
15940 		fc = B_TRUE;
15941 	}
15942 	if (!fc) {
15943 		/* Not flow-controlled, open rwnd */
15944 		tcp->tcp_rwnd = q->q_hiwat;
15945 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15946 		    << tcp->tcp_rcv_ws;
15947 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15948 		/*
15949 		 * Send back a window update immediately if TCP is above
15950 		 * ESTABLISHED state and the increase of the rcv window
15951 		 * that the other side knows is at least 1 MSS after flow
15952 		 * control is lifted.
15953 		 */
15954 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15955 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15956 			tcp_xmit_ctl(NULL, tcp,
15957 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15958 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15959 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
15960 		}
15961 	}
15962 }
15963 
15964 /*
15965  * The read side service routine is called mostly when we get back-enabled as a
15966  * result of flow control relief.  Since we don't actually queue anything in
15967  * TCP, we have no data to send out of here.  What we do is clear the receive
15968  * window, and send out a window update.
15969  */
15970 static void
15971 tcp_rsrv(queue_t *q)
15972 {
15973 	conn_t		*connp = Q_TO_CONN(q);
15974 	tcp_t		*tcp = connp->conn_tcp;
15975 	mblk_t		*mp;
15976 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15977 
15978 	/* No code does a putq on the read side */
15979 	ASSERT(q->q_first == NULL);
15980 
15981 	/* Nothing to do for the default queue */
15982 	if (q == tcps->tcps_g_q) {
15983 		return;
15984 	}
15985 
15986 	/*
15987 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
15988 	 * been run.  So just return.
15989 	 */
15990 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15991 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
15992 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
15993 		return;
15994 	}
15995 	tcp->tcp_rsrv_mp = NULL;
15996 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15997 
15998 	CONN_INC_REF(connp);
15999 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16000 	    SQ_PROCESS, SQTAG_TCP_RSRV);
16001 }
16002 
16003 /*
16004  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16005  * We do not allow the receive window to shrink.  After setting rwnd,
16006  * set the flow control hiwat of the stream.
16007  *
16008  * This function is called in 2 cases:
16009  *
16010  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16011  *    connection (passive open) and in tcp_rput_data() for active connect.
16012  *    This is called after tcp_mss_set() when the desired MSS value is known.
16013  *    This makes sure that our window size is a mutiple of the other side's
16014  *    MSS.
16015  * 2) Handling SO_RCVBUF option.
16016  *
16017  * It is ASSUMED that the requested size is a multiple of the current MSS.
16018  *
16019  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16020  * user requests so.
16021  */
16022 static int
16023 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16024 {
16025 	uint32_t	mss = tcp->tcp_mss;
16026 	uint32_t	old_max_rwnd;
16027 	uint32_t	max_transmittable_rwnd;
16028 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16029 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16030 
16031 	if (tcp->tcp_fused) {
16032 		size_t sth_hiwat;
16033 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16034 
16035 		ASSERT(peer_tcp != NULL);
16036 		/*
16037 		 * Record the stream head's high water mark for
16038 		 * this endpoint; this is used for flow-control
16039 		 * purposes in tcp_fuse_output().
16040 		 */
16041 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16042 		if (!tcp_detached) {
16043 			(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
16044 			    sth_hiwat);
16045 			if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
16046 				conn_t *connp = tcp->tcp_connp;
16047 				struct sock_proto_props sopp;
16048 
16049 				sopp.sopp_flags = SOCKOPT_RCVTHRESH;
16050 				sopp.sopp_rcvthresh = sth_hiwat >> 3;
16051 
16052 				(*connp->conn_upcalls->su_set_proto_props)
16053 				    (connp->conn_upper_handle, &sopp);
16054 			}
16055 		}
16056 
16057 		/*
16058 		 * In the fusion case, the maxpsz stream head value of
16059 		 * our peer is set according to its send buffer size
16060 		 * and our receive buffer size; since the latter may
16061 		 * have changed we need to update the peer's maxpsz.
16062 		 */
16063 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16064 		return (rwnd);
16065 	}
16066 
16067 	if (tcp_detached) {
16068 		old_max_rwnd = tcp->tcp_rwnd;
16069 	} else {
16070 		old_max_rwnd = tcp->tcp_recv_hiwater;
16071 	}
16072 
16073 	/*
16074 	 * Insist on a receive window that is at least
16075 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16076 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16077 	 * and delayed acknowledgement.
16078 	 */
16079 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16080 
16081 	/*
16082 	 * If window size info has already been exchanged, TCP should not
16083 	 * shrink the window.  Shrinking window is doable if done carefully.
16084 	 * We may add that support later.  But so far there is not a real
16085 	 * need to do that.
16086 	 */
16087 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16088 		/* MSS may have changed, do a round up again. */
16089 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16090 	}
16091 
16092 	/*
16093 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16094 	 * can be applied even before the window scale option is decided.
16095 	 */
16096 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16097 	if (rwnd > max_transmittable_rwnd) {
16098 		rwnd = max_transmittable_rwnd -
16099 		    (max_transmittable_rwnd % mss);
16100 		if (rwnd < mss)
16101 			rwnd = max_transmittable_rwnd;
16102 		/*
16103 		 * If we're over the limit we may have to back down tcp_rwnd.
16104 		 * The increment below won't work for us. So we set all three
16105 		 * here and the increment below will have no effect.
16106 		 */
16107 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16108 	}
16109 	if (tcp->tcp_localnet) {
16110 		tcp->tcp_rack_abs_max =
16111 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16112 	} else {
16113 		/*
16114 		 * For a remote host on a different subnet (through a router),
16115 		 * we ack every other packet to be conforming to RFC1122.
16116 		 * tcp_deferred_acks_max is default to 2.
16117 		 */
16118 		tcp->tcp_rack_abs_max =
16119 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16120 	}
16121 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16122 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16123 	else
16124 		tcp->tcp_rack_cur_max = 0;
16125 	/*
16126 	 * Increment the current rwnd by the amount the maximum grew (we
16127 	 * can not overwrite it since we might be in the middle of a
16128 	 * connection.)
16129 	 */
16130 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16131 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16132 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16133 		tcp->tcp_cwnd_max = rwnd;
16134 
16135 	if (tcp_detached)
16136 		return (rwnd);
16137 	/*
16138 	 * We set the maximum receive window into rq->q_hiwat if it is
16139 	 * a STREAMS socket.
16140 	 * This is not actually used for flow control.
16141 	 */
16142 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
16143 		tcp->tcp_rq->q_hiwat = rwnd;
16144 	tcp->tcp_recv_hiwater = rwnd;
16145 	/*
16146 	 * Set the STREAM head high water mark. This doesn't have to be
16147 	 * here, since we are simply using default values, but we would
16148 	 * prefer to choose these values algorithmically, with a likely
16149 	 * relationship to rwnd.
16150 	 */
16151 	(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
16152 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16153 	return (rwnd);
16154 }
16155 
16156 /*
16157  * Return SNMP stuff in buffer in mpdata.
16158  */
16159 mblk_t *
16160 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16161 {
16162 	mblk_t			*mpdata;
16163 	mblk_t			*mp_conn_ctl = NULL;
16164 	mblk_t			*mp_conn_tail;
16165 	mblk_t			*mp_attr_ctl = NULL;
16166 	mblk_t			*mp_attr_tail;
16167 	mblk_t			*mp6_conn_ctl = NULL;
16168 	mblk_t			*mp6_conn_tail;
16169 	mblk_t			*mp6_attr_ctl = NULL;
16170 	mblk_t			*mp6_attr_tail;
16171 	struct opthdr		*optp;
16172 	mib2_tcpConnEntry_t	tce;
16173 	mib2_tcp6ConnEntry_t	tce6;
16174 	mib2_transportMLPEntry_t mlp;
16175 	connf_t			*connfp;
16176 	int			i;
16177 	boolean_t 		ispriv;
16178 	zoneid_t 		zoneid;
16179 	int			v4_conn_idx;
16180 	int			v6_conn_idx;
16181 	conn_t			*connp = Q_TO_CONN(q);
16182 	tcp_stack_t		*tcps;
16183 	ip_stack_t		*ipst;
16184 	mblk_t			*mp2ctl;
16185 
16186 	/*
16187 	 * make a copy of the original message
16188 	 */
16189 	mp2ctl = copymsg(mpctl);
16190 
16191 	if (mpctl == NULL ||
16192 	    (mpdata = mpctl->b_cont) == NULL ||
16193 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16194 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16195 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16196 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16197 		freemsg(mp_conn_ctl);
16198 		freemsg(mp_attr_ctl);
16199 		freemsg(mp6_conn_ctl);
16200 		freemsg(mp6_attr_ctl);
16201 		freemsg(mpctl);
16202 		freemsg(mp2ctl);
16203 		return (NULL);
16204 	}
16205 
16206 	ipst = connp->conn_netstack->netstack_ip;
16207 	tcps = connp->conn_netstack->netstack_tcp;
16208 
16209 	/* build table of connections -- need count in fixed part */
16210 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16211 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16212 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16213 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16214 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16215 
16216 	ispriv =
16217 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16218 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16219 
16220 	v4_conn_idx = v6_conn_idx = 0;
16221 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16222 
16223 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16224 		ipst = tcps->tcps_netstack->netstack_ip;
16225 
16226 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16227 
16228 		connp = NULL;
16229 
16230 		while ((connp =
16231 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16232 			tcp_t *tcp;
16233 			boolean_t needattr;
16234 
16235 			if (connp->conn_zoneid != zoneid)
16236 				continue;	/* not in this zone */
16237 
16238 			tcp = connp->conn_tcp;
16239 			UPDATE_MIB(&tcps->tcps_mib,
16240 			    tcpHCInSegs, tcp->tcp_ibsegs);
16241 			tcp->tcp_ibsegs = 0;
16242 			UPDATE_MIB(&tcps->tcps_mib,
16243 			    tcpHCOutSegs, tcp->tcp_obsegs);
16244 			tcp->tcp_obsegs = 0;
16245 
16246 			tce6.tcp6ConnState = tce.tcpConnState =
16247 			    tcp_snmp_state(tcp);
16248 			if (tce.tcpConnState == MIB2_TCP_established ||
16249 			    tce.tcpConnState == MIB2_TCP_closeWait)
16250 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16251 
16252 			needattr = B_FALSE;
16253 			bzero(&mlp, sizeof (mlp));
16254 			if (connp->conn_mlp_type != mlptSingle) {
16255 				if (connp->conn_mlp_type == mlptShared ||
16256 				    connp->conn_mlp_type == mlptBoth)
16257 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16258 				if (connp->conn_mlp_type == mlptPrivate ||
16259 				    connp->conn_mlp_type == mlptBoth)
16260 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16261 				needattr = B_TRUE;
16262 			}
16263 			if (connp->conn_peercred != NULL) {
16264 				ts_label_t *tsl;
16265 
16266 				tsl = crgetlabel(connp->conn_peercred);
16267 				mlp.tme_doi = label2doi(tsl);
16268 				mlp.tme_label = *label2bslabel(tsl);
16269 				needattr = B_TRUE;
16270 			}
16271 
16272 			/* Create a message to report on IPv6 entries */
16273 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16274 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16275 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16276 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16277 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16278 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16279 			/* Don't want just anybody seeing these... */
16280 			if (ispriv) {
16281 				tce6.tcp6ConnEntryInfo.ce_snxt =
16282 				    tcp->tcp_snxt;
16283 				tce6.tcp6ConnEntryInfo.ce_suna =
16284 				    tcp->tcp_suna;
16285 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16286 				    tcp->tcp_rnxt;
16287 				tce6.tcp6ConnEntryInfo.ce_rack =
16288 				    tcp->tcp_rack;
16289 			} else {
16290 				/*
16291 				 * Netstat, unfortunately, uses this to
16292 				 * get send/receive queue sizes.  How to fix?
16293 				 * Why not compute the difference only?
16294 				 */
16295 				tce6.tcp6ConnEntryInfo.ce_snxt =
16296 				    tcp->tcp_snxt - tcp->tcp_suna;
16297 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16298 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16299 				    tcp->tcp_rnxt - tcp->tcp_rack;
16300 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16301 			}
16302 
16303 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16304 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16305 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16306 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16307 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16308 
16309 			tce6.tcp6ConnCreationProcess =
16310 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16311 			    tcp->tcp_cpid;
16312 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16313 
16314 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16315 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16316 
16317 			mlp.tme_connidx = v6_conn_idx++;
16318 			if (needattr)
16319 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16320 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16321 			}
16322 			/*
16323 			 * Create an IPv4 table entry for IPv4 entries and also
16324 			 * for IPv6 entries which are bound to in6addr_any
16325 			 * but don't have IPV6_V6ONLY set.
16326 			 * (i.e. anything an IPv4 peer could connect to)
16327 			 */
16328 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16329 			    (tcp->tcp_state <= TCPS_LISTEN &&
16330 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16331 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16332 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16333 					tce.tcpConnRemAddress = INADDR_ANY;
16334 					tce.tcpConnLocalAddress = INADDR_ANY;
16335 				} else {
16336 					tce.tcpConnRemAddress =
16337 					    tcp->tcp_remote;
16338 					tce.tcpConnLocalAddress =
16339 					    tcp->tcp_ip_src;
16340 				}
16341 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16342 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16343 				/* Don't want just anybody seeing these... */
16344 				if (ispriv) {
16345 					tce.tcpConnEntryInfo.ce_snxt =
16346 					    tcp->tcp_snxt;
16347 					tce.tcpConnEntryInfo.ce_suna =
16348 					    tcp->tcp_suna;
16349 					tce.tcpConnEntryInfo.ce_rnxt =
16350 					    tcp->tcp_rnxt;
16351 					tce.tcpConnEntryInfo.ce_rack =
16352 					    tcp->tcp_rack;
16353 				} else {
16354 					/*
16355 					 * Netstat, unfortunately, uses this to
16356 					 * get send/receive queue sizes.  How
16357 					 * to fix?
16358 					 * Why not compute the difference only?
16359 					 */
16360 					tce.tcpConnEntryInfo.ce_snxt =
16361 					    tcp->tcp_snxt - tcp->tcp_suna;
16362 					tce.tcpConnEntryInfo.ce_suna = 0;
16363 					tce.tcpConnEntryInfo.ce_rnxt =
16364 					    tcp->tcp_rnxt - tcp->tcp_rack;
16365 					tce.tcpConnEntryInfo.ce_rack = 0;
16366 				}
16367 
16368 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16369 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16370 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16371 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16372 				tce.tcpConnEntryInfo.ce_state =
16373 				    tcp->tcp_state;
16374 
16375 				tce.tcpConnCreationProcess =
16376 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16377 				    tcp->tcp_cpid;
16378 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16379 
16380 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16381 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16382 
16383 				mlp.tme_connidx = v4_conn_idx++;
16384 				if (needattr)
16385 					(void) snmp_append_data2(
16386 					    mp_attr_ctl->b_cont,
16387 					    &mp_attr_tail, (char *)&mlp,
16388 					    sizeof (mlp));
16389 			}
16390 		}
16391 	}
16392 
16393 	/* fixed length structure for IPv4 and IPv6 counters */
16394 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16395 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16396 	    sizeof (mib2_tcp6ConnEntry_t));
16397 	/* synchronize 32- and 64-bit counters */
16398 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16399 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16400 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16401 	optp->level = MIB2_TCP;
16402 	optp->name = 0;
16403 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16404 	    sizeof (tcps->tcps_mib));
16405 	optp->len = msgdsize(mpdata);
16406 	qreply(q, mpctl);
16407 
16408 	/* table of connections... */
16409 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16410 	    sizeof (struct T_optmgmt_ack)];
16411 	optp->level = MIB2_TCP;
16412 	optp->name = MIB2_TCP_CONN;
16413 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16414 	qreply(q, mp_conn_ctl);
16415 
16416 	/* table of MLP attributes... */
16417 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16418 	    sizeof (struct T_optmgmt_ack)];
16419 	optp->level = MIB2_TCP;
16420 	optp->name = EXPER_XPORT_MLP;
16421 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16422 	if (optp->len == 0)
16423 		freemsg(mp_attr_ctl);
16424 	else
16425 		qreply(q, mp_attr_ctl);
16426 
16427 	/* table of IPv6 connections... */
16428 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16429 	    sizeof (struct T_optmgmt_ack)];
16430 	optp->level = MIB2_TCP6;
16431 	optp->name = MIB2_TCP6_CONN;
16432 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16433 	qreply(q, mp6_conn_ctl);
16434 
16435 	/* table of IPv6 MLP attributes... */
16436 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16437 	    sizeof (struct T_optmgmt_ack)];
16438 	optp->level = MIB2_TCP6;
16439 	optp->name = EXPER_XPORT_MLP;
16440 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16441 	if (optp->len == 0)
16442 		freemsg(mp6_attr_ctl);
16443 	else
16444 		qreply(q, mp6_attr_ctl);
16445 	return (mp2ctl);
16446 }
16447 
16448 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16449 /* ARGSUSED */
16450 int
16451 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16452 {
16453 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16454 
16455 	switch (level) {
16456 	case MIB2_TCP:
16457 		switch (name) {
16458 		case 13:
16459 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16460 				return (0);
16461 			/* TODO: delete entry defined by tce */
16462 			return (1);
16463 		default:
16464 			return (0);
16465 		}
16466 	default:
16467 		return (1);
16468 	}
16469 }
16470 
16471 /* Translate TCP state to MIB2 TCP state. */
16472 static int
16473 tcp_snmp_state(tcp_t *tcp)
16474 {
16475 	if (tcp == NULL)
16476 		return (0);
16477 
16478 	switch (tcp->tcp_state) {
16479 	case TCPS_CLOSED:
16480 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16481 	case TCPS_BOUND:
16482 		return (MIB2_TCP_closed);
16483 	case TCPS_LISTEN:
16484 		return (MIB2_TCP_listen);
16485 	case TCPS_SYN_SENT:
16486 		return (MIB2_TCP_synSent);
16487 	case TCPS_SYN_RCVD:
16488 		return (MIB2_TCP_synReceived);
16489 	case TCPS_ESTABLISHED:
16490 		return (MIB2_TCP_established);
16491 	case TCPS_CLOSE_WAIT:
16492 		return (MIB2_TCP_closeWait);
16493 	case TCPS_FIN_WAIT_1:
16494 		return (MIB2_TCP_finWait1);
16495 	case TCPS_CLOSING:
16496 		return (MIB2_TCP_closing);
16497 	case TCPS_LAST_ACK:
16498 		return (MIB2_TCP_lastAck);
16499 	case TCPS_FIN_WAIT_2:
16500 		return (MIB2_TCP_finWait2);
16501 	case TCPS_TIME_WAIT:
16502 		return (MIB2_TCP_timeWait);
16503 	default:
16504 		return (0);
16505 	}
16506 }
16507 
16508 static char tcp_report_header[] =
16509 	"TCP     " MI_COL_HDRPAD_STR
16510 	"zone dest	    snxt     suna     "
16511 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16512 	"recent   [lport,fport] state";
16513 
16514 /*
16515  * TCP status report triggered via the Named Dispatch mechanism.
16516  */
16517 /* ARGSUSED */
16518 static void
16519 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16520     cred_t *cr)
16521 {
16522 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16523 	boolean_t ispriv = secpolicy_ip_config(cr, B_TRUE) == 0;
16524 	char cflag;
16525 	in6_addr_t	v6dst;
16526 	char buf[80];
16527 	uint_t print_len, buf_len;
16528 
16529 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16530 	if (buf_len <= 0)
16531 		return;
16532 
16533 	if (hashval >= 0)
16534 		(void) sprintf(hash, "%03d ", hashval);
16535 	else
16536 		hash[0] = '\0';
16537 
16538 	/*
16539 	 * Note that we use the remote address in the tcp_b  structure.
16540 	 * This means that it will print out the real destination address,
16541 	 * not the next hop's address if source routing is used.  This
16542 	 * avoid the confusion on the output because user may not
16543 	 * know that source routing is used for a connection.
16544 	 */
16545 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16546 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16547 	} else {
16548 		v6dst = tcp->tcp_remote_v6;
16549 	}
16550 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16551 	/*
16552 	 * the ispriv checks are so that normal users cannot determine
16553 	 * sequence number information using NDD.
16554 	 */
16555 
16556 	if (TCP_IS_DETACHED(tcp))
16557 		cflag = '*';
16558 	else
16559 		cflag = ' ';
16560 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16561 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16562 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16563 	    hash,
16564 	    (void *)tcp,
16565 	    tcp->tcp_connp->conn_zoneid,
16566 	    addrbuf,
16567 	    (ispriv) ? tcp->tcp_snxt : 0,
16568 	    (ispriv) ? tcp->tcp_suna : 0,
16569 	    tcp->tcp_swnd,
16570 	    (ispriv) ? tcp->tcp_rnxt : 0,
16571 	    (ispriv) ? tcp->tcp_rack : 0,
16572 	    tcp->tcp_rwnd,
16573 	    tcp->tcp_rto,
16574 	    tcp->tcp_mss,
16575 	    tcp->tcp_snd_ws_ok,
16576 	    tcp->tcp_snd_ws,
16577 	    tcp->tcp_rcv_ws,
16578 	    tcp->tcp_snd_ts_ok,
16579 	    tcp->tcp_ts_recent,
16580 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16581 	if (print_len < buf_len) {
16582 		((mblk_t *)mp)->b_wptr += print_len;
16583 	} else {
16584 		((mblk_t *)mp)->b_wptr += buf_len;
16585 	}
16586 }
16587 
16588 /*
16589  * TCP status report (for listeners only) triggered via the Named Dispatch
16590  * mechanism.
16591  */
16592 /* ARGSUSED */
16593 static void
16594 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16595 {
16596 	char addrbuf[INET6_ADDRSTRLEN];
16597 	in6_addr_t	v6dst;
16598 	uint_t print_len, buf_len;
16599 
16600 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16601 	if (buf_len <= 0)
16602 		return;
16603 
16604 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16605 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16606 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16607 	} else {
16608 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16609 		    addrbuf, sizeof (addrbuf));
16610 	}
16611 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16612 	    "%03d "
16613 	    MI_COL_PTRFMT_STR
16614 	    "%d %s %05u %08u %d/%d/%d%c\n",
16615 	    hashval, (void *)tcp,
16616 	    tcp->tcp_connp->conn_zoneid,
16617 	    addrbuf,
16618 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16619 	    tcp->tcp_conn_req_seqnum,
16620 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16621 	    tcp->tcp_conn_req_max,
16622 	    tcp->tcp_syn_defense ? '*' : ' ');
16623 	if (print_len < buf_len) {
16624 		((mblk_t *)mp)->b_wptr += print_len;
16625 	} else {
16626 		((mblk_t *)mp)->b_wptr += buf_len;
16627 	}
16628 }
16629 
16630 /* TCP status report triggered via the Named Dispatch mechanism. */
16631 /* ARGSUSED */
16632 static int
16633 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16634 {
16635 	tcp_t	*tcp;
16636 	int	i;
16637 	conn_t	*connp;
16638 	connf_t	*connfp;
16639 	zoneid_t zoneid;
16640 	tcp_stack_t *tcps;
16641 	ip_stack_t *ipst;
16642 
16643 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16644 	tcps = Q_TO_TCP(q)->tcp_tcps;
16645 
16646 	/*
16647 	 * Because of the ndd constraint, at most we can have 64K buffer
16648 	 * to put in all TCP info.  So to be more efficient, just
16649 	 * allocate a 64K buffer here, assuming we need that large buffer.
16650 	 * This may be a problem as any user can read tcp_status.  Therefore
16651 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16652 	 * This should be OK as normal users should not do this too often.
16653 	 */
16654 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16655 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16656 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16657 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16658 			return (0);
16659 		}
16660 	}
16661 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16662 		/* The following may work even if we cannot get a large buf. */
16663 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16664 		return (0);
16665 	}
16666 
16667 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16668 
16669 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16670 
16671 		ipst = tcps->tcps_netstack->netstack_ip;
16672 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16673 
16674 		connp = NULL;
16675 
16676 		while ((connp =
16677 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16678 			tcp = connp->conn_tcp;
16679 			if (zoneid != GLOBAL_ZONEID &&
16680 			    zoneid != connp->conn_zoneid)
16681 				continue;
16682 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16683 			    cr);
16684 		}
16685 
16686 	}
16687 
16688 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16689 	return (0);
16690 }
16691 
16692 /* TCP status report triggered via the Named Dispatch mechanism. */
16693 /* ARGSUSED */
16694 static int
16695 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16696 {
16697 	tf_t	*tbf;
16698 	tcp_t	*tcp, *ltcp;
16699 	int	i;
16700 	zoneid_t zoneid;
16701 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
16702 
16703 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16704 
16705 	/* Refer to comments in tcp_status_report(). */
16706 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16707 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16708 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16709 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16710 			return (0);
16711 		}
16712 	}
16713 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16714 		/* The following may work even if we cannot get a large buf. */
16715 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16716 		return (0);
16717 	}
16718 
16719 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16720 
16721 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
16722 		tbf = &tcps->tcps_bind_fanout[i];
16723 		mutex_enter(&tbf->tf_lock);
16724 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
16725 		    ltcp = ltcp->tcp_bind_hash) {
16726 			for (tcp = ltcp; tcp != NULL;
16727 			    tcp = tcp->tcp_bind_hash_port) {
16728 				if (zoneid != GLOBAL_ZONEID &&
16729 				    zoneid != tcp->tcp_connp->conn_zoneid)
16730 					continue;
16731 				CONN_INC_REF(tcp->tcp_connp);
16732 				tcp_report_item(mp->b_cont, tcp, i,
16733 				    Q_TO_TCP(q), cr);
16734 				CONN_DEC_REF(tcp->tcp_connp);
16735 			}
16736 		}
16737 		mutex_exit(&tbf->tf_lock);
16738 	}
16739 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16740 	return (0);
16741 }
16742 
16743 /* TCP status report triggered via the Named Dispatch mechanism. */
16744 /* ARGSUSED */
16745 static int
16746 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16747 {
16748 	connf_t	*connfp;
16749 	conn_t	*connp;
16750 	tcp_t	*tcp;
16751 	int	i;
16752 	zoneid_t zoneid;
16753 	tcp_stack_t *tcps;
16754 	ip_stack_t	*ipst;
16755 
16756 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16757 	tcps = Q_TO_TCP(q)->tcp_tcps;
16758 
16759 	/* Refer to comments in tcp_status_report(). */
16760 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16761 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16762 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16763 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16764 			return (0);
16765 		}
16766 	}
16767 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16768 		/* The following may work even if we cannot get a large buf. */
16769 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16770 		return (0);
16771 	}
16772 
16773 	(void) mi_mpprintf(mp,
16774 	    "    TCP    " MI_COL_HDRPAD_STR
16775 	    "zone IP addr	 port  seqnum   backlog (q0/q/max)");
16776 
16777 	ipst = tcps->tcps_netstack->netstack_ip;
16778 
16779 	for (i = 0; i < ipst->ips_ipcl_bind_fanout_size; i++) {
16780 		connfp = &ipst->ips_ipcl_bind_fanout[i];
16781 		connp = NULL;
16782 		while ((connp =
16783 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16784 			tcp = connp->conn_tcp;
16785 			if (zoneid != GLOBAL_ZONEID &&
16786 			    zoneid != connp->conn_zoneid)
16787 				continue;
16788 			tcp_report_listener(mp->b_cont, tcp, i);
16789 		}
16790 	}
16791 
16792 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16793 	return (0);
16794 }
16795 
16796 /* TCP status report triggered via the Named Dispatch mechanism. */
16797 /* ARGSUSED */
16798 static int
16799 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16800 {
16801 	connf_t	*connfp;
16802 	conn_t	*connp;
16803 	tcp_t	*tcp;
16804 	int	i;
16805 	zoneid_t zoneid;
16806 	tcp_stack_t *tcps;
16807 	ip_stack_t *ipst;
16808 
16809 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16810 	tcps = Q_TO_TCP(q)->tcp_tcps;
16811 	ipst = tcps->tcps_netstack->netstack_ip;
16812 
16813 	/* Refer to comments in tcp_status_report(). */
16814 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16815 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16816 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16817 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16818 			return (0);
16819 		}
16820 	}
16821 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16822 		/* The following may work even if we cannot get a large buf. */
16823 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16824 		return (0);
16825 	}
16826 
16827 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16828 	    ipst->ips_ipcl_conn_fanout_size);
16829 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16830 
16831 	for (i = 0; i < ipst->ips_ipcl_conn_fanout_size; i++) {
16832 		connfp =  &ipst->ips_ipcl_conn_fanout[i];
16833 		connp = NULL;
16834 		while ((connp =
16835 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16836 			tcp = connp->conn_tcp;
16837 			if (zoneid != GLOBAL_ZONEID &&
16838 			    zoneid != connp->conn_zoneid)
16839 				continue;
16840 			tcp_report_item(mp->b_cont, tcp, i,
16841 			    Q_TO_TCP(q), cr);
16842 		}
16843 	}
16844 
16845 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16846 	return (0);
16847 }
16848 
16849 /* TCP status report triggered via the Named Dispatch mechanism. */
16850 /* ARGSUSED */
16851 static int
16852 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16853 {
16854 	tf_t	*tf;
16855 	tcp_t	*tcp;
16856 	int	i;
16857 	zoneid_t zoneid;
16858 	tcp_stack_t	*tcps;
16859 
16860 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16861 	tcps = Q_TO_TCP(q)->tcp_tcps;
16862 
16863 	/* Refer to comments in tcp_status_report(). */
16864 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16865 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16866 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16867 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16868 			return (0);
16869 		}
16870 	}
16871 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16872 		/* The following may work even if we cannot get a large buf. */
16873 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16874 		return (0);
16875 	}
16876 
16877 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16878 
16879 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
16880 		tf = &tcps->tcps_acceptor_fanout[i];
16881 		mutex_enter(&tf->tf_lock);
16882 		for (tcp = tf->tf_tcp; tcp != NULL;
16883 		    tcp = tcp->tcp_acceptor_hash) {
16884 			if (zoneid != GLOBAL_ZONEID &&
16885 			    zoneid != tcp->tcp_connp->conn_zoneid)
16886 				continue;
16887 			tcp_report_item(mp->b_cont, tcp, i,
16888 			    Q_TO_TCP(q), cr);
16889 		}
16890 		mutex_exit(&tf->tf_lock);
16891 	}
16892 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16893 	return (0);
16894 }
16895 
16896 /*
16897  * tcp_timer is the timer service routine.  It handles the retransmission,
16898  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16899  * from the state of the tcp instance what kind of action needs to be done
16900  * at the time it is called.
16901  */
16902 static void
16903 tcp_timer(void *arg)
16904 {
16905 	mblk_t		*mp;
16906 	clock_t		first_threshold;
16907 	clock_t		second_threshold;
16908 	clock_t		ms;
16909 	uint32_t	mss;
16910 	conn_t		*connp = (conn_t *)arg;
16911 	tcp_t		*tcp = connp->conn_tcp;
16912 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16913 
16914 	tcp->tcp_timer_tid = 0;
16915 
16916 	if (tcp->tcp_fused)
16917 		return;
16918 
16919 	first_threshold =  tcp->tcp_first_timer_threshold;
16920 	second_threshold = tcp->tcp_second_timer_threshold;
16921 	switch (tcp->tcp_state) {
16922 	case TCPS_IDLE:
16923 	case TCPS_BOUND:
16924 	case TCPS_LISTEN:
16925 		return;
16926 	case TCPS_SYN_RCVD: {
16927 		tcp_t	*listener = tcp->tcp_listener;
16928 
16929 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16930 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16931 			/* it's our first timeout */
16932 			tcp->tcp_syn_rcvd_timeout = 1;
16933 			mutex_enter(&listener->tcp_eager_lock);
16934 			listener->tcp_syn_rcvd_timeout++;
16935 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16936 				/*
16937 				 * Make this eager available for drop if we
16938 				 * need to drop one to accomodate a new
16939 				 * incoming SYN request.
16940 				 */
16941 				MAKE_DROPPABLE(listener, tcp);
16942 			}
16943 			if (!listener->tcp_syn_defense &&
16944 			    (listener->tcp_syn_rcvd_timeout >
16945 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
16946 			    (tcps->tcps_conn_req_max_q0 > 200)) {
16947 				/* We may be under attack. Put on a defense. */
16948 				listener->tcp_syn_defense = B_TRUE;
16949 				cmn_err(CE_WARN, "High TCP connect timeout "
16950 				    "rate! System (port %d) may be under a "
16951 				    "SYN flood attack!",
16952 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16953 
16954 				listener->tcp_ip_addr_cache = kmem_zalloc(
16955 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16956 				    KM_NOSLEEP);
16957 			}
16958 			mutex_exit(&listener->tcp_eager_lock);
16959 		} else if (listener != NULL) {
16960 			mutex_enter(&listener->tcp_eager_lock);
16961 			tcp->tcp_syn_rcvd_timeout++;
16962 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
16963 			    !tcp->tcp_closemp_used) {
16964 				/*
16965 				 * This is our second timeout. Put the tcp in
16966 				 * the list of droppable eagers to allow it to
16967 				 * be dropped, if needed. We don't check
16968 				 * whether tcp_dontdrop is set or not to
16969 				 * protect ourselve from a SYN attack where a
16970 				 * remote host can spoof itself as one of the
16971 				 * good IP source and continue to hold
16972 				 * resources too long.
16973 				 */
16974 				MAKE_DROPPABLE(listener, tcp);
16975 			}
16976 			mutex_exit(&listener->tcp_eager_lock);
16977 		}
16978 	}
16979 		/* FALLTHRU */
16980 	case TCPS_SYN_SENT:
16981 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16982 		second_threshold = tcp->tcp_second_ctimer_threshold;
16983 		break;
16984 	case TCPS_ESTABLISHED:
16985 	case TCPS_FIN_WAIT_1:
16986 	case TCPS_CLOSING:
16987 	case TCPS_CLOSE_WAIT:
16988 	case TCPS_LAST_ACK:
16989 		/* If we have data to rexmit */
16990 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16991 			clock_t	time_to_wait;
16992 
16993 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
16994 			if (!tcp->tcp_xmit_head)
16995 				break;
16996 			time_to_wait = lbolt -
16997 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16998 			time_to_wait = tcp->tcp_rto -
16999 			    TICK_TO_MSEC(time_to_wait);
17000 			/*
17001 			 * If the timer fires too early, 1 clock tick earlier,
17002 			 * restart the timer.
17003 			 */
17004 			if (time_to_wait > msec_per_tick) {
17005 				TCP_STAT(tcps, tcp_timer_fire_early);
17006 				TCP_TIMER_RESTART(tcp, time_to_wait);
17007 				return;
17008 			}
17009 			/*
17010 			 * When we probe zero windows, we force the swnd open.
17011 			 * If our peer acks with a closed window swnd will be
17012 			 * set to zero by tcp_rput(). As long as we are
17013 			 * receiving acks tcp_rput will
17014 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
17015 			 * first and second interval actions.  NOTE: the timer
17016 			 * interval is allowed to continue its exponential
17017 			 * backoff.
17018 			 */
17019 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
17020 				if (tcp->tcp_debug) {
17021 					(void) strlog(TCP_MOD_ID, 0, 1,
17022 					    SL_TRACE, "tcp_timer: zero win");
17023 				}
17024 			} else {
17025 				/*
17026 				 * After retransmission, we need to do
17027 				 * slow start.  Set the ssthresh to one
17028 				 * half of current effective window and
17029 				 * cwnd to one MSS.  Also reset
17030 				 * tcp_cwnd_cnt.
17031 				 *
17032 				 * Note that if tcp_ssthresh is reduced because
17033 				 * of ECN, do not reduce it again unless it is
17034 				 * already one window of data away (tcp_cwr
17035 				 * should then be cleared) or this is a
17036 				 * timeout for a retransmitted segment.
17037 				 */
17038 				uint32_t npkt;
17039 
17040 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
17041 					npkt = ((tcp->tcp_timer_backoff ?
17042 					    tcp->tcp_cwnd_ssthresh :
17043 					    tcp->tcp_snxt -
17044 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
17045 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
17046 					    tcp->tcp_mss;
17047 				}
17048 				tcp->tcp_cwnd = tcp->tcp_mss;
17049 				tcp->tcp_cwnd_cnt = 0;
17050 				if (tcp->tcp_ecn_ok) {
17051 					tcp->tcp_cwr = B_TRUE;
17052 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17053 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17054 				}
17055 			}
17056 			break;
17057 		}
17058 		/*
17059 		 * We have something to send yet we cannot send.  The
17060 		 * reason can be:
17061 		 *
17062 		 * 1. Zero send window: we need to do zero window probe.
17063 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17064 		 * segments.
17065 		 * 3. SWS avoidance: receiver may have shrunk window,
17066 		 * reset our knowledge.
17067 		 *
17068 		 * Note that condition 2 can happen with either 1 or
17069 		 * 3.  But 1 and 3 are exclusive.
17070 		 */
17071 		if (tcp->tcp_unsent != 0) {
17072 			if (tcp->tcp_cwnd == 0) {
17073 				/*
17074 				 * Set tcp_cwnd to 1 MSS so that a
17075 				 * new segment can be sent out.  We
17076 				 * are "clocking out" new data when
17077 				 * the network is really congested.
17078 				 */
17079 				ASSERT(tcp->tcp_ecn_ok);
17080 				tcp->tcp_cwnd = tcp->tcp_mss;
17081 			}
17082 			if (tcp->tcp_swnd == 0) {
17083 				/* Extend window for zero window probe */
17084 				tcp->tcp_swnd++;
17085 				tcp->tcp_zero_win_probe = B_TRUE;
17086 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
17087 			} else {
17088 				/*
17089 				 * Handle timeout from sender SWS avoidance.
17090 				 * Reset our knowledge of the max send window
17091 				 * since the receiver might have reduced its
17092 				 * receive buffer.  Avoid setting tcp_max_swnd
17093 				 * to one since that will essentially disable
17094 				 * the SWS checks.
17095 				 *
17096 				 * Note that since we don't have a SWS
17097 				 * state variable, if the timeout is set
17098 				 * for ECN but not for SWS, this
17099 				 * code will also be executed.  This is
17100 				 * fine as tcp_max_swnd is updated
17101 				 * constantly and it will not affect
17102 				 * anything.
17103 				 */
17104 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17105 			}
17106 			tcp_wput_data(tcp, NULL, B_FALSE);
17107 			return;
17108 		}
17109 		/* Is there a FIN that needs to be to re retransmitted? */
17110 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17111 		    !tcp->tcp_fin_acked)
17112 			break;
17113 		/* Nothing to do, return without restarting timer. */
17114 		TCP_STAT(tcps, tcp_timer_fire_miss);
17115 		return;
17116 	case TCPS_FIN_WAIT_2:
17117 		/*
17118 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17119 		 * We waited some time for for peer's FIN, but it hasn't
17120 		 * arrived.  We flush the connection now to avoid
17121 		 * case where the peer has rebooted.
17122 		 */
17123 		if (TCP_IS_DETACHED(tcp)) {
17124 			(void) tcp_clean_death(tcp, 0, 23);
17125 		} else {
17126 			TCP_TIMER_RESTART(tcp,
17127 			    tcps->tcps_fin_wait_2_flush_interval);
17128 		}
17129 		return;
17130 	case TCPS_TIME_WAIT:
17131 		(void) tcp_clean_death(tcp, 0, 24);
17132 		return;
17133 	default:
17134 		if (tcp->tcp_debug) {
17135 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
17136 			    "tcp_timer: strange state (%d) %s",
17137 			    tcp->tcp_state, tcp_display(tcp, NULL,
17138 			    DISP_PORT_ONLY));
17139 		}
17140 		return;
17141 	}
17142 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17143 		/*
17144 		 * For zero window probe, we need to send indefinitely,
17145 		 * unless we have not heard from the other side for some
17146 		 * time...
17147 		 */
17148 		if ((tcp->tcp_zero_win_probe == 0) ||
17149 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17150 		    second_threshold)) {
17151 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
17152 			/*
17153 			 * If TCP is in SYN_RCVD state, send back a
17154 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17155 			 * should be zero in TCPS_SYN_RCVD state.
17156 			 */
17157 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17158 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17159 				    "in SYN_RCVD",
17160 				    tcp, tcp->tcp_snxt,
17161 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17162 			}
17163 			(void) tcp_clean_death(tcp,
17164 			    tcp->tcp_client_errno ?
17165 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17166 			return;
17167 		} else {
17168 			/*
17169 			 * Set tcp_ms_we_have_waited to second_threshold
17170 			 * so that in next timeout, we will do the above
17171 			 * check (lbolt - tcp_last_recv_time).  This is
17172 			 * also to avoid overflow.
17173 			 *
17174 			 * We don't need to decrement tcp_timer_backoff
17175 			 * to avoid overflow because it will be decremented
17176 			 * later if new timeout value is greater than
17177 			 * tcp_rexmit_interval_max.  In the case when
17178 			 * tcp_rexmit_interval_max is greater than
17179 			 * second_threshold, it means that we will wait
17180 			 * longer than second_threshold to send the next
17181 			 * window probe.
17182 			 */
17183 			tcp->tcp_ms_we_have_waited = second_threshold;
17184 		}
17185 	} else if (ms > first_threshold) {
17186 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17187 		    tcp->tcp_xmit_head != NULL) {
17188 			tcp->tcp_xmit_head =
17189 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17190 		}
17191 		/*
17192 		 * We have been retransmitting for too long...  The RTT
17193 		 * we calculated is probably incorrect.  Reinitialize it.
17194 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17195 		 * tcp_rtt_update so that we won't accidentally cache a
17196 		 * bad value.  But only do this if this is not a zero
17197 		 * window probe.
17198 		 */
17199 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17200 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17201 			    (tcp->tcp_rtt_sa >> 5);
17202 			tcp->tcp_rtt_sa = 0;
17203 			tcp_ip_notify(tcp);
17204 			tcp->tcp_rtt_update = 0;
17205 		}
17206 	}
17207 	tcp->tcp_timer_backoff++;
17208 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17209 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17210 	    tcps->tcps_rexmit_interval_min) {
17211 		/*
17212 		 * This means the original RTO is tcp_rexmit_interval_min.
17213 		 * So we will use tcp_rexmit_interval_min as the RTO value
17214 		 * and do the backoff.
17215 		 */
17216 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
17217 	} else {
17218 		ms <<= tcp->tcp_timer_backoff;
17219 	}
17220 	if (ms > tcps->tcps_rexmit_interval_max) {
17221 		ms = tcps->tcps_rexmit_interval_max;
17222 		/*
17223 		 * ms is at max, decrement tcp_timer_backoff to avoid
17224 		 * overflow.
17225 		 */
17226 		tcp->tcp_timer_backoff--;
17227 	}
17228 	tcp->tcp_ms_we_have_waited += ms;
17229 	if (tcp->tcp_zero_win_probe == 0) {
17230 		tcp->tcp_rto = ms;
17231 	}
17232 	TCP_TIMER_RESTART(tcp, ms);
17233 	/*
17234 	 * This is after a timeout and tcp_rto is backed off.  Set
17235 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17236 	 * restart the timer with a correct value.
17237 	 */
17238 	tcp->tcp_set_timer = 1;
17239 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17240 	if (mss > tcp->tcp_mss)
17241 		mss = tcp->tcp_mss;
17242 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17243 		mss = tcp->tcp_swnd;
17244 
17245 	if ((mp = tcp->tcp_xmit_head) != NULL)
17246 		mp->b_prev = (mblk_t *)lbolt;
17247 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17248 	    B_TRUE);
17249 
17250 	/*
17251 	 * When slow start after retransmission begins, start with
17252 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17253 	 * start phase.  tcp_snd_burst controls how many segments
17254 	 * can be sent because of an ack.
17255 	 */
17256 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17257 	tcp->tcp_snd_burst = TCP_CWND_SS;
17258 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17259 	    (tcp->tcp_unsent == 0)) {
17260 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17261 	} else {
17262 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17263 	}
17264 	tcp->tcp_rexmit = B_TRUE;
17265 	tcp->tcp_dupack_cnt = 0;
17266 
17267 	/*
17268 	 * Remove all rexmit SACK blk to start from fresh.
17269 	 */
17270 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17271 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17272 		tcp->tcp_num_notsack_blk = 0;
17273 		tcp->tcp_cnt_notsack_list = 0;
17274 	}
17275 	if (mp == NULL) {
17276 		return;
17277 	}
17278 	/* Attach credentials to retransmitted initial SYNs. */
17279 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17280 		mblk_setcred(mp, tcp->tcp_cred);
17281 		DB_CPID(mp) = tcp->tcp_cpid;
17282 	}
17283 
17284 	tcp->tcp_csuna = tcp->tcp_snxt;
17285 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17286 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17287 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17288 
17289 }
17290 
17291 static int
17292 tcp_do_unbind(conn_t *connp)
17293 {
17294 	tcp_t *tcp = connp->conn_tcp;
17295 	int error = 0;
17296 
17297 	switch (tcp->tcp_state) {
17298 	case TCPS_BOUND:
17299 	case TCPS_LISTEN:
17300 		break;
17301 	default:
17302 		return (-TOUTSTATE);
17303 	}
17304 
17305 	/*
17306 	 * Need to clean up all the eagers since after the unbind, segments
17307 	 * will no longer be delivered to this listener stream.
17308 	 */
17309 	mutex_enter(&tcp->tcp_eager_lock);
17310 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17311 		tcp_eager_cleanup(tcp, 0);
17312 	}
17313 	mutex_exit(&tcp->tcp_eager_lock);
17314 
17315 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17316 		tcp->tcp_ipha->ipha_src = 0;
17317 	} else {
17318 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17319 	}
17320 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17321 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17322 	tcp_bind_hash_remove(tcp);
17323 	tcp->tcp_state = TCPS_IDLE;
17324 	tcp->tcp_mdt = B_FALSE;
17325 
17326 	connp = tcp->tcp_connp;
17327 	connp->conn_mdt_ok = B_FALSE;
17328 	ipcl_hash_remove(connp);
17329 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17330 
17331 	return (error);
17332 }
17333 
17334 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17335 static void
17336 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
17337 {
17338 	int error = tcp_do_unbind(tcp->tcp_connp);
17339 
17340 	if (error > 0) {
17341 		tcp_err_ack(tcp, mp, TSYSERR, error);
17342 	} else if (error < 0) {
17343 		tcp_err_ack(tcp, mp, -error, 0);
17344 	} else {
17345 		/* Send M_FLUSH according to TPI */
17346 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17347 
17348 		mp = mi_tpi_ok_ack_alloc(mp);
17349 		putnext(tcp->tcp_rq, mp);
17350 	}
17351 }
17352 
17353 /*
17354  * Don't let port fall into the privileged range.
17355  * Since the extra privileged ports can be arbitrary we also
17356  * ensure that we exclude those from consideration.
17357  * tcp_g_epriv_ports is not sorted thus we loop over it until
17358  * there are no changes.
17359  *
17360  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17361  * but instead the code relies on:
17362  * - the fact that the address of the array and its size never changes
17363  * - the atomic assignment of the elements of the array
17364  *
17365  * Returns 0 if there are no more ports available.
17366  *
17367  * TS note: skip multilevel ports.
17368  */
17369 static in_port_t
17370 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17371 {
17372 	int i;
17373 	boolean_t restart = B_FALSE;
17374 	tcp_stack_t *tcps = tcp->tcp_tcps;
17375 
17376 	if (random && tcp_random_anon_port != 0) {
17377 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17378 		    sizeof (in_port_t));
17379 		/*
17380 		 * Unless changed by a sys admin, the smallest anon port
17381 		 * is 32768 and the largest anon port is 65535.  It is
17382 		 * very likely (50%) for the random port to be smaller
17383 		 * than the smallest anon port.  When that happens,
17384 		 * add port % (anon port range) to the smallest anon
17385 		 * port to get the random port.  It should fall into the
17386 		 * valid anon port range.
17387 		 */
17388 		if (port < tcps->tcps_smallest_anon_port) {
17389 			port = tcps->tcps_smallest_anon_port +
17390 			    port % (tcps->tcps_largest_anon_port -
17391 			    tcps->tcps_smallest_anon_port);
17392 		}
17393 	}
17394 
17395 retry:
17396 	if (port < tcps->tcps_smallest_anon_port)
17397 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17398 
17399 	if (port > tcps->tcps_largest_anon_port) {
17400 		if (restart)
17401 			return (0);
17402 		restart = B_TRUE;
17403 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17404 	}
17405 
17406 	if (port < tcps->tcps_smallest_nonpriv_port)
17407 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17408 
17409 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17410 		if (port == tcps->tcps_g_epriv_ports[i]) {
17411 			port++;
17412 			/*
17413 			 * Make sure whether the port is in the
17414 			 * valid range.
17415 			 */
17416 			goto retry;
17417 		}
17418 	}
17419 	if (is_system_labeled() &&
17420 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17421 	    IPPROTO_TCP, B_TRUE)) != 0) {
17422 		port = i;
17423 		goto retry;
17424 	}
17425 	return (port);
17426 }
17427 
17428 /*
17429  * Return the next anonymous port in the privileged port range for
17430  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17431  * downwards.  This is the same behavior as documented in the userland
17432  * library call rresvport(3N).
17433  *
17434  * TS note: skip multilevel ports.
17435  */
17436 static in_port_t
17437 tcp_get_next_priv_port(const tcp_t *tcp)
17438 {
17439 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17440 	in_port_t nextport;
17441 	boolean_t restart = B_FALSE;
17442 	tcp_stack_t *tcps = tcp->tcp_tcps;
17443 retry:
17444 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17445 	    next_priv_port >= IPPORT_RESERVED) {
17446 		next_priv_port = IPPORT_RESERVED - 1;
17447 		if (restart)
17448 			return (0);
17449 		restart = B_TRUE;
17450 	}
17451 	if (is_system_labeled() &&
17452 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17453 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17454 		next_priv_port = nextport;
17455 		goto retry;
17456 	}
17457 	return (next_priv_port--);
17458 }
17459 
17460 /* The write side r/w procedure. */
17461 
17462 #if CCS_STATS
17463 struct {
17464 	struct {
17465 		int64_t count, bytes;
17466 	} tot, hit;
17467 } wrw_stats;
17468 #endif
17469 
17470 /*
17471  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17472  * messages.
17473  */
17474 /* ARGSUSED */
17475 static void
17476 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17477 {
17478 	conn_t	*connp = (conn_t *)arg;
17479 	tcp_t	*tcp = connp->conn_tcp;
17480 	queue_t	*q = tcp->tcp_wq;
17481 
17482 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17483 	/*
17484 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17485 	 * Once the close starts, streamhead and sockfs will not let any data
17486 	 * packets come down (close ensures that there are no threads using the
17487 	 * queue and no new threads will come down) but since qprocsoff()
17488 	 * hasn't happened yet, a M_FLUSH or some non data message might
17489 	 * get reflected back (in response to our own FLUSHRW) and get
17490 	 * processed after tcp_close() is done. The conn would still be valid
17491 	 * because a ref would have added but we need to check the state
17492 	 * before actually processing the packet.
17493 	 */
17494 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17495 		freemsg(mp);
17496 		return;
17497 	}
17498 
17499 	switch (DB_TYPE(mp)) {
17500 	case M_IOCDATA:
17501 		tcp_wput_iocdata(tcp, mp);
17502 		break;
17503 	case M_FLUSH:
17504 		tcp_wput_flush(tcp, mp);
17505 		break;
17506 	default:
17507 		CALL_IP_WPUT(connp, q, mp);
17508 		break;
17509 	}
17510 }
17511 
17512 /*
17513  * The TCP fast path write put procedure.
17514  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17515  */
17516 /* ARGSUSED */
17517 void
17518 tcp_output(void *arg, mblk_t *mp, void *arg2)
17519 {
17520 	int		len;
17521 	int		hdrlen;
17522 	int		plen;
17523 	mblk_t		*mp1;
17524 	uchar_t		*rptr;
17525 	uint32_t	snxt;
17526 	tcph_t		*tcph;
17527 	struct datab	*db;
17528 	uint32_t	suna;
17529 	uint32_t	mss;
17530 	ipaddr_t	*dst;
17531 	ipaddr_t	*src;
17532 	uint32_t	sum;
17533 	int		usable;
17534 	conn_t		*connp = (conn_t *)arg;
17535 	tcp_t		*tcp = connp->conn_tcp;
17536 	uint32_t	msize;
17537 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17538 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17539 
17540 	/*
17541 	 * Try and ASSERT the minimum possible references on the
17542 	 * conn early enough. Since we are executing on write side,
17543 	 * the connection is obviously not detached and that means
17544 	 * there is a ref each for TCP and IP. Since we are behind
17545 	 * the squeue, the minimum references needed are 3. If the
17546 	 * conn is in classifier hash list, there should be an
17547 	 * extra ref for that (we check both the possibilities).
17548 	 */
17549 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17550 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17551 
17552 	ASSERT(DB_TYPE(mp) == M_DATA);
17553 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17554 
17555 	mutex_enter(&tcp->tcp_non_sq_lock);
17556 	tcp->tcp_squeue_bytes -= msize;
17557 	mutex_exit(&tcp->tcp_non_sq_lock);
17558 
17559 	/* Check to see if this connection wants to be re-fused. */
17560 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
17561 		if (tcp->tcp_ipversion == IPV4_VERSION) {
17562 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
17563 			    &tcp->tcp_saved_tcph);
17564 		} else {
17565 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
17566 			    &tcp->tcp_saved_tcph);
17567 		}
17568 	}
17569 	/* Bypass tcp protocol for fused tcp loopback */
17570 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17571 		return;
17572 
17573 	mss = tcp->tcp_mss;
17574 	if (tcp->tcp_xmit_zc_clean)
17575 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17576 
17577 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17578 	len = (int)(mp->b_wptr - mp->b_rptr);
17579 
17580 	/*
17581 	 * Criteria for fast path:
17582 	 *
17583 	 *   1. no unsent data
17584 	 *   2. single mblk in request
17585 	 *   3. connection established
17586 	 *   4. data in mblk
17587 	 *   5. len <= mss
17588 	 *   6. no tcp_valid bits
17589 	 */
17590 	if ((tcp->tcp_unsent != 0) ||
17591 	    (tcp->tcp_cork) ||
17592 	    (mp->b_cont != NULL) ||
17593 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17594 	    (len == 0) ||
17595 	    (len > mss) ||
17596 	    (tcp->tcp_valid_bits != 0)) {
17597 		tcp_wput_data(tcp, mp, B_FALSE);
17598 		return;
17599 	}
17600 
17601 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17602 	ASSERT(tcp->tcp_fin_sent == 0);
17603 
17604 	/* queue new packet onto retransmission queue */
17605 	if (tcp->tcp_xmit_head == NULL) {
17606 		tcp->tcp_xmit_head = mp;
17607 	} else {
17608 		tcp->tcp_xmit_last->b_cont = mp;
17609 	}
17610 	tcp->tcp_xmit_last = mp;
17611 	tcp->tcp_xmit_tail = mp;
17612 
17613 	/* find out how much we can send */
17614 	/* BEGIN CSTYLED */
17615 	/*
17616 	 *    un-acked	   usable
17617 	 *  |--------------|-----------------|
17618 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
17619 	 */
17620 	/* END CSTYLED */
17621 
17622 	/* start sending from tcp_snxt */
17623 	snxt = tcp->tcp_snxt;
17624 
17625 	/*
17626 	 * Check to see if this connection has been idled for some
17627 	 * time and no ACK is expected.  If it is, we need to slow
17628 	 * start again to get back the connection's "self-clock" as
17629 	 * described in VJ's paper.
17630 	 *
17631 	 * Refer to the comment in tcp_mss_set() for the calculation
17632 	 * of tcp_cwnd after idle.
17633 	 */
17634 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17635 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17636 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
17637 	}
17638 
17639 	usable = tcp->tcp_swnd;		/* tcp window size */
17640 	if (usable > tcp->tcp_cwnd)
17641 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17642 	usable -= snxt;		/* subtract stuff already sent */
17643 	suna = tcp->tcp_suna;
17644 	usable += suna;
17645 	/* usable can be < 0 if the congestion window is smaller */
17646 	if (len > usable) {
17647 		/* Can't send complete M_DATA in one shot */
17648 		goto slow;
17649 	}
17650 
17651 	mutex_enter(&tcp->tcp_non_sq_lock);
17652 	if (tcp->tcp_flow_stopped &&
17653 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17654 		tcp_clrqfull(tcp);
17655 	}
17656 	mutex_exit(&tcp->tcp_non_sq_lock);
17657 
17658 	/*
17659 	 * determine if anything to send (Nagle).
17660 	 *
17661 	 *   1. len < tcp_mss (i.e. small)
17662 	 *   2. unacknowledged data present
17663 	 *   3. len < nagle limit
17664 	 *   4. last packet sent < nagle limit (previous packet sent)
17665 	 */
17666 	if ((len < mss) && (snxt != suna) &&
17667 	    (len < (int)tcp->tcp_naglim) &&
17668 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17669 		/*
17670 		 * This was the first unsent packet and normally
17671 		 * mss < xmit_hiwater so there is no need to worry
17672 		 * about flow control. The next packet will go
17673 		 * through the flow control check in tcp_wput_data().
17674 		 */
17675 		/* leftover work from above */
17676 		tcp->tcp_unsent = len;
17677 		tcp->tcp_xmit_tail_unsent = len;
17678 
17679 		return;
17680 	}
17681 
17682 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17683 
17684 	if (snxt == suna) {
17685 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17686 	}
17687 
17688 	/* we have always sent something */
17689 	tcp->tcp_rack_cnt = 0;
17690 
17691 	tcp->tcp_snxt = snxt + len;
17692 	tcp->tcp_rack = tcp->tcp_rnxt;
17693 
17694 	if ((mp1 = dupb(mp)) == 0)
17695 		goto no_memory;
17696 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17697 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17698 
17699 	/* adjust tcp header information */
17700 	tcph = tcp->tcp_tcph;
17701 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17702 
17703 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17704 	sum = (sum >> 16) + (sum & 0xFFFF);
17705 	U16_TO_ABE16(sum, tcph->th_sum);
17706 
17707 	U32_TO_ABE32(snxt, tcph->th_seq);
17708 
17709 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17710 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17711 	BUMP_LOCAL(tcp->tcp_obsegs);
17712 
17713 	/* Update the latest receive window size in TCP header. */
17714 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17715 	    tcph->th_win);
17716 
17717 	tcp->tcp_last_sent_len = (ushort_t)len;
17718 
17719 	plen = len + tcp->tcp_hdr_len;
17720 
17721 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17722 		tcp->tcp_ipha->ipha_length = htons(plen);
17723 	} else {
17724 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17725 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17726 	}
17727 
17728 	/* see if we need to allocate a mblk for the headers */
17729 	hdrlen = tcp->tcp_hdr_len;
17730 	rptr = mp1->b_rptr - hdrlen;
17731 	db = mp1->b_datap;
17732 	if ((db->db_ref != 2) || rptr < db->db_base ||
17733 	    (!OK_32PTR(rptr))) {
17734 		/* NOTE: we assume allocb returns an OK_32PTR */
17735 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17736 		    tcps->tcps_wroff_xtra, BPRI_MED);
17737 		if (!mp) {
17738 			freemsg(mp1);
17739 			goto no_memory;
17740 		}
17741 		mp->b_cont = mp1;
17742 		mp1 = mp;
17743 		/* Leave room for Link Level header */
17744 		/* hdrlen = tcp->tcp_hdr_len; */
17745 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17746 		mp1->b_wptr = &rptr[hdrlen];
17747 	}
17748 	mp1->b_rptr = rptr;
17749 
17750 	/* Fill in the timestamp option. */
17751 	if (tcp->tcp_snd_ts_ok) {
17752 		U32_TO_BE32((uint32_t)lbolt,
17753 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17754 		U32_TO_BE32(tcp->tcp_ts_recent,
17755 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17756 	} else {
17757 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17758 	}
17759 
17760 	/* copy header into outgoing packet */
17761 	dst = (ipaddr_t *)rptr;
17762 	src = (ipaddr_t *)tcp->tcp_iphc;
17763 	dst[0] = src[0];
17764 	dst[1] = src[1];
17765 	dst[2] = src[2];
17766 	dst[3] = src[3];
17767 	dst[4] = src[4];
17768 	dst[5] = src[5];
17769 	dst[6] = src[6];
17770 	dst[7] = src[7];
17771 	dst[8] = src[8];
17772 	dst[9] = src[9];
17773 	if (hdrlen -= 40) {
17774 		hdrlen >>= 2;
17775 		dst += 10;
17776 		src += 10;
17777 		do {
17778 			*dst++ = *src++;
17779 		} while (--hdrlen);
17780 	}
17781 
17782 	/*
17783 	 * Set the ECN info in the TCP header.  Note that this
17784 	 * is not the template header.
17785 	 */
17786 	if (tcp->tcp_ecn_ok) {
17787 		SET_ECT(tcp, rptr);
17788 
17789 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17790 		if (tcp->tcp_ecn_echo_on)
17791 			tcph->th_flags[0] |= TH_ECE;
17792 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17793 			tcph->th_flags[0] |= TH_CWR;
17794 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17795 		}
17796 	}
17797 
17798 	if (tcp->tcp_ip_forward_progress) {
17799 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17800 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17801 		tcp->tcp_ip_forward_progress = B_FALSE;
17802 	}
17803 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17804 	return;
17805 
17806 	/*
17807 	 * If we ran out of memory, we pretend to have sent the packet
17808 	 * and that it was lost on the wire.
17809 	 */
17810 no_memory:
17811 	return;
17812 
17813 slow:
17814 	/* leftover work from above */
17815 	tcp->tcp_unsent = len;
17816 	tcp->tcp_xmit_tail_unsent = len;
17817 	tcp_wput_data(tcp, NULL, B_FALSE);
17818 }
17819 
17820 /* ARGSUSED */
17821 void
17822 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17823 {
17824 	conn_t			*connp = (conn_t *)arg;
17825 	tcp_t			*tcp = connp->conn_tcp;
17826 	queue_t			*q = tcp->tcp_rq;
17827 	struct tcp_options	*tcpopt;
17828 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17829 
17830 	/* socket options */
17831 	uint_t 			sopp_flags;
17832 	ssize_t			sopp_rxhiwat;
17833 	ssize_t			sopp_maxblk;
17834 	ushort_t		sopp_wroff;
17835 	ushort_t		sopp_tail;
17836 	ushort_t		sopp_copyopt;
17837 
17838 	tcpopt = (struct tcp_options *)mp->b_rptr;
17839 
17840 	/*
17841 	 * Drop the eager's ref on the listener, that was placed when
17842 	 * this eager began life in tcp_conn_request.
17843 	 */
17844 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17845 	if (IPCL_IS_NONSTR(connp)) {
17846 		/* Safe to free conn_ind message */
17847 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17848 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17849 	}
17850 
17851 	tcp->tcp_detached = B_FALSE;
17852 
17853 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17854 		/*
17855 		 * Someone blewoff the eager before we could finish
17856 		 * the accept.
17857 		 *
17858 		 * The only reason eager exists it because we put in
17859 		 * a ref on it when conn ind went up. We need to send
17860 		 * a disconnect indication up while the last reference
17861 		 * on the eager will be dropped by the squeue when we
17862 		 * return.
17863 		 */
17864 		ASSERT(tcp->tcp_listener == NULL);
17865 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17866 			if (IPCL_IS_NONSTR(connp)) {
17867 				ASSERT(tcp->tcp_issocket);
17868 				(*connp->conn_upcalls->su_disconnected)(
17869 				    connp->conn_upper_handle, tcp->tcp_connid,
17870 				    ECONNREFUSED);
17871 				freemsg(mp);
17872 			} else {
17873 				struct	T_discon_ind	*tdi;
17874 
17875 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17876 				/*
17877 				 * Let us reuse the incoming mblk to avoid
17878 				 * memory allocation failure problems. We know
17879 				 * that the size of the incoming mblk i.e.
17880 				 * stroptions is greater than sizeof
17881 				 * T_discon_ind. So the reallocb below can't
17882 				 * fail.
17883 				 */
17884 				freemsg(mp->b_cont);
17885 				mp->b_cont = NULL;
17886 				ASSERT(DB_REF(mp) == 1);
17887 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17888 				    B_FALSE);
17889 				ASSERT(mp != NULL);
17890 				DB_TYPE(mp) = M_PROTO;
17891 				((union T_primitives *)mp->b_rptr)->type =
17892 				    T_DISCON_IND;
17893 				tdi = (struct T_discon_ind *)mp->b_rptr;
17894 				if (tcp->tcp_issocket) {
17895 					tdi->DISCON_reason = ECONNREFUSED;
17896 					tdi->SEQ_number = 0;
17897 				} else {
17898 					tdi->DISCON_reason = ENOPROTOOPT;
17899 					tdi->SEQ_number =
17900 					    tcp->tcp_conn_req_seqnum;
17901 				}
17902 				mp->b_wptr = mp->b_rptr +
17903 				    sizeof (struct T_discon_ind);
17904 				putnext(q, mp);
17905 				return;
17906 			}
17907 		}
17908 		if (tcp->tcp_hard_binding) {
17909 			tcp->tcp_hard_binding = B_FALSE;
17910 			tcp->tcp_hard_bound = B_TRUE;
17911 		}
17912 		return;
17913 	}
17914 
17915 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
17916 		int boundif = tcpopt->to_boundif;
17917 		uint_t len = sizeof (int);
17918 
17919 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17920 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
17921 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred, NULL);
17922 	}
17923 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
17924 		uint_t on = 1;
17925 		uint_t len = sizeof (uint_t);
17926 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17927 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
17928 		    (uchar_t *)&on, NULL, tcp->tcp_cred, NULL);
17929 	}
17930 
17931 	/*
17932 	 * For a loopback connection with tcp_direct_sockfs on, note that
17933 	 * we don't have to protect tcp_rcv_list yet because synchronous
17934 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17935 	 * possibly race with us.
17936 	 */
17937 
17938 	/*
17939 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17940 	 * properly.  This is the first time we know of the acceptor'
17941 	 * queue.  So we do it here.
17942 	 *
17943 	 * XXX
17944 	 */
17945 	if (tcp->tcp_rcv_list == NULL) {
17946 		/*
17947 		 * Recv queue is empty, tcp_rwnd should not have changed.
17948 		 * That means it should be equal to the listener's tcp_rwnd.
17949 		 */
17950 		if (!IPCL_IS_NONSTR(connp))
17951 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17952 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
17953 	} else {
17954 #ifdef DEBUG
17955 		mblk_t *tmp;
17956 		mblk_t	*mp1;
17957 		uint_t	cnt = 0;
17958 
17959 		mp1 = tcp->tcp_rcv_list;
17960 		while ((tmp = mp1) != NULL) {
17961 			mp1 = tmp->b_next;
17962 			cnt += msgdsize(tmp);
17963 		}
17964 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17965 #endif
17966 		/* There is some data, add them back to get the max. */
17967 		if (!IPCL_IS_NONSTR(connp))
17968 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17969 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17970 	}
17971 	/*
17972 	 * This is the first time we run on the correct
17973 	 * queue after tcp_accept. So fix all the q parameters
17974 	 * here.
17975 	 */
17976 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
17977 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17978 
17979 	/*
17980 	 * Record the stream head's high water mark for this endpoint;
17981 	 * this is used for flow-control purposes.
17982 	 */
17983 	sopp_rxhiwat = tcp->tcp_fused ?
17984 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
17985 	    MAX(tcp->tcp_recv_hiwater, tcps->tcps_sth_rcv_hiwat);
17986 
17987 	/*
17988 	 * Determine what write offset value to use depending on SACK and
17989 	 * whether the endpoint is fused or not.
17990 	 */
17991 	if (tcp->tcp_fused) {
17992 		ASSERT(tcp->tcp_loopback);
17993 		ASSERT(tcp->tcp_loopback_peer != NULL);
17994 		/*
17995 		 * For fused tcp loopback, set the stream head's write
17996 		 * offset value to zero since we won't be needing any room
17997 		 * for TCP/IP headers.  This would also improve performance
17998 		 * since it would reduce the amount of work done by kmem.
17999 		 * Non-fused tcp loopback case is handled separately below.
18000 		 */
18001 		sopp_wroff = 0;
18002 		/*
18003 		 * Update the peer's transmit parameters according to
18004 		 * our recently calculated high water mark value.
18005 		 */
18006 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
18007 	} else if (tcp->tcp_snd_sack_ok) {
18008 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
18009 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
18010 	} else {
18011 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
18012 		    tcps->tcps_wroff_xtra);
18013 	}
18014 
18015 	/*
18016 	 * If this is endpoint is handling SSL, then reserve extra
18017 	 * offset and space at the end.
18018 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
18019 	 * overriding the previous setting. The extra cost of signing and
18020 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
18021 	 * instead of a single contiguous one by the stream head
18022 	 * largely outweighs the statistical reduction of ACKs, when
18023 	 * applicable. The peer will also save on decryption and verification
18024 	 * costs.
18025 	 */
18026 	if (tcp->tcp_kssl_ctx != NULL) {
18027 		sopp_wroff += SSL3_WROFFSET;
18028 
18029 		sopp_flags |= SOCKOPT_TAIL;
18030 		sopp_tail = SSL3_MAX_TAIL_LEN;
18031 
18032 		sopp_flags |= SOCKOPT_ZCOPY;
18033 		sopp_copyopt = ZCVMUNSAFE;
18034 
18035 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
18036 	}
18037 
18038 	/* Send the options up */
18039 	if (IPCL_IS_NONSTR(connp)) {
18040 		struct sock_proto_props sopp;
18041 
18042 		sopp.sopp_flags = sopp_flags;
18043 		sopp.sopp_wroff = sopp_wroff;
18044 		sopp.sopp_maxblk = sopp_maxblk;
18045 		sopp.sopp_rxhiwat = sopp_rxhiwat;
18046 		if (sopp_flags & SOCKOPT_TAIL) {
18047 			ASSERT(tcp->tcp_kssl_ctx != NULL);
18048 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
18049 			sopp.sopp_tail = sopp_tail;
18050 			sopp.sopp_zcopyflag = sopp_copyopt;
18051 		}
18052 		(*connp->conn_upcalls->su_set_proto_props)
18053 		    (connp->conn_upper_handle, &sopp);
18054 	} else {
18055 		struct stroptions *stropt;
18056 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18057 		if (stropt_mp == NULL) {
18058 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
18059 			return;
18060 		}
18061 		DB_TYPE(stropt_mp) = M_SETOPTS;
18062 		stropt = (struct stroptions *)stropt_mp->b_rptr;
18063 		stropt_mp->b_wptr += sizeof (struct stroptions);
18064 		stropt = (struct stroptions *)stropt_mp->b_rptr;
18065 		stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
18066 		stropt->so_hiwat = sopp_rxhiwat;
18067 		stropt->so_wroff = sopp_wroff;
18068 		stropt->so_maxblk = sopp_maxblk;
18069 
18070 		if (sopp_flags & SOCKOPT_TAIL) {
18071 			ASSERT(tcp->tcp_kssl_ctx != NULL);
18072 
18073 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
18074 			stropt->so_tail = sopp_tail;
18075 			stropt->so_copyopt = sopp_copyopt;
18076 		}
18077 
18078 		/* Send the options up */
18079 		putnext(q, stropt_mp);
18080 	}
18081 
18082 	freemsg(mp);
18083 	/*
18084 	 * Pass up any data and/or a fin that has been received.
18085 	 *
18086 	 * Adjust receive window in case it had decreased
18087 	 * (because there is data <=> tcp_rcv_list != NULL)
18088 	 * while the connection was detached. Note that
18089 	 * in case the eager was flow-controlled, w/o this
18090 	 * code, the rwnd may never open up again!
18091 	 */
18092 	if (tcp->tcp_rcv_list != NULL) {
18093 		if (IPCL_IS_NONSTR(connp)) {
18094 			mblk_t *mp;
18095 			int space_left;
18096 			int error;
18097 			boolean_t push = B_TRUE;
18098 
18099 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
18100 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
18101 			    &push) >= 0) {
18102 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
18103 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18104 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
18105 					tcp_xmit_ctl(NULL,
18106 					    tcp, (tcp->tcp_swnd == 0) ?
18107 					    tcp->tcp_suna : tcp->tcp_snxt,
18108 					    tcp->tcp_rnxt, TH_ACK);
18109 				}
18110 			}
18111 			while ((mp = tcp->tcp_rcv_list) != NULL) {
18112 				push = B_TRUE;
18113 				tcp->tcp_rcv_list = mp->b_next;
18114 				mp->b_next = NULL;
18115 				space_left = (*connp->conn_upcalls->su_recv)
18116 				    (connp->conn_upper_handle, mp, msgdsize(mp),
18117 				    0, &error, &push);
18118 				if (space_left < 0) {
18119 					/*
18120 					 * At this point the eager is not
18121 					 * visible to anyone, so fallback
18122 					 * can not happen.
18123 					 */
18124 					ASSERT(error != EOPNOTSUPP);
18125 				}
18126 			}
18127 			tcp->tcp_rcv_last_head = NULL;
18128 			tcp->tcp_rcv_last_tail = NULL;
18129 			tcp->tcp_rcv_cnt = 0;
18130 		} else {
18131 			/* We drain directly in case of fused tcp loopback */
18132 			sodirect_t *sodp;
18133 
18134 			if (!tcp->tcp_fused && canputnext(q)) {
18135 				tcp->tcp_rwnd = q->q_hiwat;
18136 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18137 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
18138 					tcp_xmit_ctl(NULL,
18139 					    tcp, (tcp->tcp_swnd == 0) ?
18140 					    tcp->tcp_suna : tcp->tcp_snxt,
18141 					    tcp->tcp_rnxt, TH_ACK);
18142 				}
18143 			}
18144 
18145 			SOD_PTR_ENTER(tcp, sodp);
18146 			if (sodp != NULL) {
18147 				/* Sodirect, move from rcv_list */
18148 				ASSERT(!tcp->tcp_fused);
18149 				while ((mp = tcp->tcp_rcv_list) != NULL) {
18150 					tcp->tcp_rcv_list = mp->b_next;
18151 					mp->b_next = NULL;
18152 					(void) tcp_rcv_sod_enqueue(tcp, sodp,
18153 					    mp, msgdsize(mp));
18154 				}
18155 				tcp->tcp_rcv_last_head = NULL;
18156 				tcp->tcp_rcv_last_tail = NULL;
18157 				tcp->tcp_rcv_cnt = 0;
18158 				(void) tcp_rcv_sod_wakeup(tcp, sodp);
18159 				/* sod_wakeup() did the mutex_exit() */
18160 			} else {
18161 				/* Not sodirect, drain */
18162 				(void) tcp_rcv_drain(tcp);
18163 			}
18164 		}
18165 
18166 		/*
18167 		 * For fused tcp loopback, back-enable peer endpoint
18168 		 * if it's currently flow-controlled.
18169 		 */
18170 		if (tcp->tcp_fused) {
18171 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18172 
18173 			ASSERT(peer_tcp != NULL);
18174 			ASSERT(peer_tcp->tcp_fused);
18175 			/*
18176 			 * In order to change the peer's tcp_flow_stopped,
18177 			 * we need to take locks for both end points. The
18178 			 * highest address is taken first.
18179 			 */
18180 			if (peer_tcp > tcp) {
18181 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18182 				mutex_enter(&tcp->tcp_non_sq_lock);
18183 			} else {
18184 				mutex_enter(&tcp->tcp_non_sq_lock);
18185 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18186 			}
18187 			if (peer_tcp->tcp_flow_stopped) {
18188 				tcp_clrqfull(peer_tcp);
18189 				TCP_STAT(tcps, tcp_fusion_backenabled);
18190 			}
18191 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18192 			mutex_exit(&tcp->tcp_non_sq_lock);
18193 		}
18194 	}
18195 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18196 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18197 		tcp->tcp_ordrel_done = B_TRUE;
18198 		if (IPCL_IS_NONSTR(connp)) {
18199 			ASSERT(tcp->tcp_ordrel_mp == NULL);
18200 			(*connp->conn_upcalls->su_opctl)(
18201 			    connp->conn_upper_handle,
18202 			    SOCK_OPCTL_SHUT_RECV, 0);
18203 		} else {
18204 			mp = tcp->tcp_ordrel_mp;
18205 			tcp->tcp_ordrel_mp = NULL;
18206 			putnext(q, mp);
18207 		}
18208 	}
18209 	if (tcp->tcp_hard_binding) {
18210 		tcp->tcp_hard_binding = B_FALSE;
18211 		tcp->tcp_hard_bound = B_TRUE;
18212 	}
18213 
18214 	/* We can enable synchronous streams for STREAMS tcp endpoint now */
18215 	if (tcp->tcp_fused && !IPCL_IS_NONSTR(connp) &&
18216 	    tcp->tcp_loopback_peer != NULL &&
18217 	    !IPCL_IS_NONSTR(tcp->tcp_loopback_peer->tcp_connp)) {
18218 		tcp_fuse_syncstr_enable_pair(tcp);
18219 	}
18220 
18221 	if (tcp->tcp_ka_enabled) {
18222 		tcp->tcp_ka_last_intrvl = 0;
18223 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18224 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18225 	}
18226 
18227 	/*
18228 	 * At this point, eager is fully established and will
18229 	 * have the following references -
18230 	 *
18231 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18232 	 * 1 reference for the squeue which will be dropped by the squeue as
18233 	 *	soon as this function returns.
18234 	 * There will be 1 additonal reference for being in classifier
18235 	 *	hash list provided something bad hasn't happened.
18236 	 */
18237 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18238 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18239 }
18240 
18241 /*
18242  * The function called through squeue to get behind listener's perimeter to
18243  * send a deffered conn_ind.
18244  */
18245 /* ARGSUSED */
18246 void
18247 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18248 {
18249 	conn_t	*connp = (conn_t *)arg;
18250 	tcp_t *listener = connp->conn_tcp;
18251 	struct T_conn_ind *conn_ind;
18252 	tcp_t *tcp;
18253 
18254 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
18255 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18256 	    conn_ind->OPT_length);
18257 
18258 	if (listener->tcp_state == TCPS_CLOSED ||
18259 	    TCP_IS_DETACHED(listener)) {
18260 		/*
18261 		 * If listener has closed, it would have caused a
18262 		 * a cleanup/blowoff to happen for the eager.
18263 		 *
18264 		 * We need to drop the ref on eager that was put
18265 		 * tcp_rput_data() before trying to send the conn_ind
18266 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18267 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18268 		 * listener is closed so we drop the ref.
18269 		 */
18270 		CONN_DEC_REF(tcp->tcp_connp);
18271 		freemsg(mp);
18272 		return;
18273 	}
18274 
18275 	tcp_ulp_newconn(connp, tcp->tcp_connp, mp);
18276 }
18277 
18278 /* ARGSUSED */
18279 static int
18280 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
18281 {
18282 	tcp_t *listener, *eager;
18283 	mblk_t *opt_mp;
18284 	struct tcp_options *tcpopt;
18285 
18286 	listener = lconnp->conn_tcp;
18287 	ASSERT(listener->tcp_state == TCPS_LISTEN);
18288 	eager = econnp->conn_tcp;
18289 	ASSERT(eager->tcp_listener != NULL);
18290 
18291 	ASSERT(eager->tcp_rq != NULL);
18292 
18293 	/* If tcp_fused and sodirect enabled disable it */
18294 	if (eager->tcp_fused && eager->tcp_sodirect != NULL) {
18295 		/* Fused, disable sodirect */
18296 		mutex_enter(eager->tcp_sodirect->sod_lockp);
18297 		SOD_DISABLE(eager->tcp_sodirect);
18298 		mutex_exit(eager->tcp_sodirect->sod_lockp);
18299 		eager->tcp_sodirect = NULL;
18300 	}
18301 
18302 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
18303 	if (opt_mp == NULL) {
18304 		return (-TPROTO);
18305 	}
18306 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
18307 	eager->tcp_issocket = B_TRUE;
18308 
18309 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18310 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18311 	ASSERT(econnp->conn_netstack ==
18312 	    listener->tcp_connp->conn_netstack);
18313 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18314 
18315 	/* Put the ref for IP */
18316 	CONN_INC_REF(econnp);
18317 
18318 	/*
18319 	 * We should have minimum of 3 references on the conn
18320 	 * at this point. One each for TCP and IP and one for
18321 	 * the T_conn_ind that was sent up when the 3-way handshake
18322 	 * completed. In the normal case we would also have another
18323 	 * reference (making a total of 4) for the conn being in the
18324 	 * classifier hash list. However the eager could have received
18325 	 * an RST subsequently and tcp_closei_local could have removed
18326 	 * the eager from the classifier hash list, hence we can't
18327 	 * assert that reference.
18328 	 */
18329 	ASSERT(econnp->conn_ref >= 3);
18330 
18331 	opt_mp->b_datap->db_type = M_SETOPTS;
18332 	opt_mp->b_wptr += sizeof (struct tcp_options);
18333 
18334 	/*
18335 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18336 	 * from listener to acceptor.
18337 	 */
18338 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
18339 	tcpopt->to_flags = 0;
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 	/*
18447 	 * It is OK to manipulate these fields outside the eager's squeue
18448 	 * because they will not start being used until tcp_accept_finish
18449 	 * has been called.
18450 	 */
18451 	ASSERT(lconnp->conn_upper_handle != NULL);
18452 	ASSERT(econnp->conn_upper_handle == NULL);
18453 	econnp->conn_upper_handle = sock_handle;
18454 	econnp->conn_upcalls = lconnp->conn_upcalls;
18455 	ASSERT(IPCL_IS_NONSTR(econnp));
18456 	/*
18457 	 * Create helper stream if it is a non-TPI TCP connection.
18458 	 */
18459 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
18460 		ip1dbg(("tcp_accept: create of IP helper stream"
18461 		    " failed\n"));
18462 		return (EPROTO);
18463 	}
18464 	eager->tcp_rq = econnp->conn_rq;
18465 	eager->tcp_wq = econnp->conn_wq;
18466 
18467 	ASSERT(eager->tcp_rq != NULL);
18468 
18469 	eager->tcp_sodirect = SOD_SOTOSODP(sock_handle);
18470 	return (tcp_accept_common(lconnp, econnp, cr));
18471 }
18472 
18473 
18474 /*
18475  * This is the STREAMS entry point for T_CONN_RES coming down on
18476  * Acceptor STREAM when  sockfs listener does accept processing.
18477  * Read the block comment on top of tcp_conn_request().
18478  */
18479 void
18480 tcp_tpi_accept(queue_t *q, mblk_t *mp)
18481 {
18482 	queue_t *rq = RD(q);
18483 	struct T_conn_res *conn_res;
18484 	tcp_t *eager;
18485 	tcp_t *listener;
18486 	struct T_ok_ack *ok;
18487 	t_scalar_t PRIM_type;
18488 	conn_t *econnp;
18489 
18490 	ASSERT(DB_TYPE(mp) == M_PROTO);
18491 
18492 	conn_res = (struct T_conn_res *)mp->b_rptr;
18493 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18494 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18495 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18496 		if (mp != NULL)
18497 			putnext(rq, mp);
18498 		return;
18499 	}
18500 	switch (conn_res->PRIM_type) {
18501 	case O_T_CONN_RES:
18502 	case T_CONN_RES:
18503 		/*
18504 		 * We pass up an err ack if allocb fails. This will
18505 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18506 		 * tcp_eager_blowoff to be called. sockfs will then call
18507 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18508 		 * we need to do the allocb up here because we have to
18509 		 * make sure rq->q_qinfo->qi_qclose still points to the
18510 		 * correct function (tcpclose_accept) in case allocb
18511 		 * fails.
18512 		 */
18513 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18514 		    &eager, conn_res->OPT_length);
18515 		PRIM_type = conn_res->PRIM_type;
18516 		mp->b_datap->db_type = M_PCPROTO;
18517 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18518 		ok = (struct T_ok_ack *)mp->b_rptr;
18519 		ok->PRIM_type = T_OK_ACK;
18520 		ok->CORRECT_prim = PRIM_type;
18521 		econnp = eager->tcp_connp;
18522 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
18523 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
18524 		eager->tcp_rq = rq;
18525 		eager->tcp_wq = q;
18526 		rq->q_ptr = econnp;
18527 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
18528 		q->q_ptr = econnp;
18529 		q->q_qinfo = &tcp_winit;
18530 		listener = eager->tcp_listener;
18531 
18532 		/*
18533 		 * TCP is _D_SODIRECT and sockfs is directly above so
18534 		 * save shared sodirect_t pointer (if any).
18535 		 */
18536 		eager->tcp_sodirect = SOD_QTOSODP(eager->tcp_rq);
18537 		if (tcp_accept_common(listener->tcp_connp,
18538 		    econnp, CRED()) < 0) {
18539 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18540 			if (mp != NULL)
18541 				putnext(rq, mp);
18542 			return;
18543 		}
18544 
18545 		/*
18546 		 * Send the new local address also up to sockfs. There
18547 		 * should already be enough space in the mp that came
18548 		 * down from soaccept().
18549 		 */
18550 		if (eager->tcp_family == AF_INET) {
18551 			sin_t *sin;
18552 
18553 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18554 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18555 			sin = (sin_t *)mp->b_wptr;
18556 			mp->b_wptr += sizeof (sin_t);
18557 			sin->sin_family = AF_INET;
18558 			sin->sin_port = eager->tcp_lport;
18559 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18560 		} else {
18561 			sin6_t *sin6;
18562 
18563 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18564 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18565 			sin6 = (sin6_t *)mp->b_wptr;
18566 			mp->b_wptr += sizeof (sin6_t);
18567 			sin6->sin6_family = AF_INET6;
18568 			sin6->sin6_port = eager->tcp_lport;
18569 			if (eager->tcp_ipversion == IPV4_VERSION) {
18570 				sin6->sin6_flowinfo = 0;
18571 				IN6_IPADDR_TO_V4MAPPED(
18572 				    eager->tcp_ipha->ipha_src,
18573 				    &sin6->sin6_addr);
18574 			} else {
18575 				ASSERT(eager->tcp_ip6h != NULL);
18576 				sin6->sin6_flowinfo =
18577 				    eager->tcp_ip6h->ip6_vcf &
18578 				    ~IPV6_VERS_AND_FLOW_MASK;
18579 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18580 			}
18581 			sin6->sin6_scope_id = 0;
18582 			sin6->__sin6_src_id = 0;
18583 		}
18584 
18585 		putnext(rq, mp);
18586 		return;
18587 	default:
18588 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18589 		if (mp != NULL)
18590 			putnext(rq, mp);
18591 		return;
18592 	}
18593 }
18594 
18595 static int
18596 tcp_do_getsockname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18597 {
18598 	sin_t *sin = (sin_t *)sa;
18599 	sin6_t *sin6 = (sin6_t *)sa;
18600 
18601 	switch (tcp->tcp_family) {
18602 	case AF_INET:
18603 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18604 
18605 		if (*salenp < sizeof (sin_t))
18606 			return (EINVAL);
18607 
18608 		*sin = sin_null;
18609 		sin->sin_family = AF_INET;
18610 		if (tcp->tcp_state >= TCPS_BOUND) {
18611 			sin->sin_port = tcp->tcp_lport;
18612 			sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
18613 		}
18614 		*salenp = sizeof (sin_t);
18615 		break;
18616 
18617 	case AF_INET6:
18618 		if (*salenp < sizeof (sin6_t))
18619 			return (EINVAL);
18620 
18621 		*sin6 = sin6_null;
18622 		sin6->sin6_family = AF_INET6;
18623 		if (tcp->tcp_state >= TCPS_BOUND) {
18624 			sin6->sin6_port = tcp->tcp_lport;
18625 			if (tcp->tcp_ipversion == IPV4_VERSION) {
18626 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
18627 				    &sin6->sin6_addr);
18628 			} else {
18629 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
18630 			}
18631 		}
18632 		*salenp = sizeof (sin6_t);
18633 		break;
18634 	}
18635 
18636 	return (0);
18637 }
18638 
18639 static int
18640 tcp_do_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18641 {
18642 	sin_t *sin = (sin_t *)sa;
18643 	sin6_t *sin6 = (sin6_t *)sa;
18644 
18645 	if (tcp->tcp_state < TCPS_SYN_RCVD)
18646 		return (ENOTCONN);
18647 
18648 	switch (tcp->tcp_family) {
18649 	case AF_INET:
18650 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18651 
18652 		if (*salenp < sizeof (sin_t))
18653 			return (EINVAL);
18654 
18655 		*sin = sin_null;
18656 		sin->sin_family = AF_INET;
18657 		sin->sin_port = tcp->tcp_fport;
18658 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
18659 		    sin->sin_addr.s_addr);
18660 		*salenp = sizeof (sin_t);
18661 		break;
18662 
18663 	case AF_INET6:
18664 		if (*salenp < sizeof (sin6_t))
18665 			return (EINVAL);
18666 
18667 		*sin6 = sin6_null;
18668 		sin6->sin6_family = AF_INET6;
18669 		sin6->sin6_port = tcp->tcp_fport;
18670 		sin6->sin6_addr = tcp->tcp_remote_v6;
18671 		if (tcp->tcp_ipversion == IPV6_VERSION) {
18672 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
18673 			    ~IPV6_VERS_AND_FLOW_MASK;
18674 		}
18675 		*salenp = sizeof (sin6_t);
18676 		break;
18677 	}
18678 
18679 	return (0);
18680 }
18681 
18682 /*
18683  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
18684  */
18685 static void
18686 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
18687 {
18688 	void	*data;
18689 	mblk_t	*datamp = mp->b_cont;
18690 	tcp_t	*tcp = Q_TO_TCP(q);
18691 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
18692 
18693 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
18694 		cmdp->cb_error = EPROTO;
18695 		qreply(q, mp);
18696 		return;
18697 	}
18698 
18699 	data = datamp->b_rptr;
18700 
18701 	switch (cmdp->cb_cmd) {
18702 	case TI_GETPEERNAME:
18703 		cmdp->cb_error = tcp_do_getpeername(tcp, data, &cmdp->cb_len);
18704 		break;
18705 	case TI_GETMYNAME:
18706 		cmdp->cb_error = tcp_do_getsockname(tcp, data, &cmdp->cb_len);
18707 		break;
18708 	default:
18709 		cmdp->cb_error = EINVAL;
18710 		break;
18711 	}
18712 
18713 	qreply(q, mp);
18714 }
18715 
18716 void
18717 tcp_wput(queue_t *q, mblk_t *mp)
18718 {
18719 	conn_t	*connp = Q_TO_CONN(q);
18720 	tcp_t	*tcp;
18721 	void (*output_proc)();
18722 	t_scalar_t type;
18723 	uchar_t *rptr;
18724 	struct iocblk	*iocp;
18725 	size_t size;
18726 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18727 
18728 	ASSERT(connp->conn_ref >= 2);
18729 
18730 	switch (DB_TYPE(mp)) {
18731 	case M_DATA:
18732 		tcp = connp->conn_tcp;
18733 		ASSERT(tcp != NULL);
18734 
18735 		size = msgdsize(mp);
18736 
18737 		mutex_enter(&tcp->tcp_non_sq_lock);
18738 		tcp->tcp_squeue_bytes += size;
18739 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18740 			tcp_setqfull(tcp);
18741 		}
18742 		mutex_exit(&tcp->tcp_non_sq_lock);
18743 
18744 		CONN_INC_REF(connp);
18745 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18746 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18747 		return;
18748 
18749 	case M_CMD:
18750 		tcp_wput_cmdblk(q, mp);
18751 		return;
18752 
18753 	case M_PROTO:
18754 	case M_PCPROTO:
18755 		/*
18756 		 * if it is a snmp message, don't get behind the squeue
18757 		 */
18758 		tcp = connp->conn_tcp;
18759 		rptr = mp->b_rptr;
18760 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18761 			type = ((union T_primitives *)rptr)->type;
18762 		} else {
18763 			if (tcp->tcp_debug) {
18764 				(void) strlog(TCP_MOD_ID, 0, 1,
18765 				    SL_ERROR|SL_TRACE,
18766 				    "tcp_wput_proto, dropping one...");
18767 			}
18768 			freemsg(mp);
18769 			return;
18770 		}
18771 		if (type == T_SVR4_OPTMGMT_REQ) {
18772 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
18773 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18774 			    cr)) {
18775 				/*
18776 				 * This was a SNMP request
18777 				 */
18778 				return;
18779 			} else {
18780 				output_proc = tcp_wput_proto;
18781 			}
18782 		} else {
18783 			output_proc = tcp_wput_proto;
18784 		}
18785 		break;
18786 	case M_IOCTL:
18787 		/*
18788 		 * Most ioctls can be processed right away without going via
18789 		 * squeues - process them right here. Those that do require
18790 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18791 		 * are processed by tcp_wput_ioctl().
18792 		 */
18793 		iocp = (struct iocblk *)mp->b_rptr;
18794 		tcp = connp->conn_tcp;
18795 
18796 		switch (iocp->ioc_cmd) {
18797 		case TCP_IOC_ABORT_CONN:
18798 			tcp_ioctl_abort_conn(q, mp);
18799 			return;
18800 		case TI_GETPEERNAME:
18801 		case TI_GETMYNAME:
18802 			mi_copyin(q, mp, NULL,
18803 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18804 			return;
18805 		case ND_SET:
18806 			/* nd_getset does the necessary checks */
18807 		case ND_GET:
18808 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18809 				CALL_IP_WPUT(connp, q, mp);
18810 				return;
18811 			}
18812 			qreply(q, mp);
18813 			return;
18814 		case TCP_IOC_DEFAULT_Q:
18815 			/*
18816 			 * Wants to be the default wq. Check the credentials
18817 			 * first, the rest is executed via squeue.
18818 			 */
18819 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18820 				iocp->ioc_error = EPERM;
18821 				iocp->ioc_count = 0;
18822 				mp->b_datap->db_type = M_IOCACK;
18823 				qreply(q, mp);
18824 				return;
18825 			}
18826 			output_proc = tcp_wput_ioctl;
18827 			break;
18828 		default:
18829 			output_proc = tcp_wput_ioctl;
18830 			break;
18831 		}
18832 		break;
18833 	default:
18834 		output_proc = tcp_wput_nondata;
18835 		break;
18836 	}
18837 
18838 	CONN_INC_REF(connp);
18839 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18840 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18841 }
18842 
18843 /*
18844  * Initial STREAMS write side put() procedure for sockets. It tries to
18845  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18846  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18847  * are handled by tcp_wput() as usual.
18848  *
18849  * All further messages will also be handled by tcp_wput() because we cannot
18850  * be sure that the above short cut is safe later.
18851  */
18852 static void
18853 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18854 {
18855 	conn_t			*connp = Q_TO_CONN(wq);
18856 	tcp_t			*tcp = connp->conn_tcp;
18857 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18858 
18859 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18860 	wq->q_qinfo = &tcp_winit;
18861 
18862 	ASSERT(IPCL_IS_TCP(connp));
18863 	ASSERT(TCP_IS_SOCKET(tcp));
18864 
18865 	if (DB_TYPE(mp) == M_PCPROTO &&
18866 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18867 	    car->PRIM_type == T_CAPABILITY_REQ) {
18868 		tcp_capability_req(tcp, mp);
18869 		return;
18870 	}
18871 
18872 	tcp_wput(wq, mp);
18873 }
18874 
18875 /* ARGSUSED */
18876 static void
18877 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18878 {
18879 #ifdef DEBUG
18880 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18881 #endif
18882 	freemsg(mp);
18883 }
18884 
18885 static boolean_t
18886 tcp_zcopy_check(tcp_t *tcp)
18887 {
18888 	conn_t	*connp = tcp->tcp_connp;
18889 	ire_t	*ire;
18890 	boolean_t	zc_enabled = B_FALSE;
18891 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18892 
18893 	if (do_tcpzcopy == 2)
18894 		zc_enabled = B_TRUE;
18895 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18896 	    IPCL_IS_CONNECTED(connp) &&
18897 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18898 	    connp->conn_dontroute == 0 &&
18899 	    !connp->conn_nexthop_set &&
18900 	    connp->conn_outgoing_ill == NULL &&
18901 	    do_tcpzcopy == 1) {
18902 		/*
18903 		 * the checks above  closely resemble the fast path checks
18904 		 * in tcp_send_data().
18905 		 */
18906 		mutex_enter(&connp->conn_lock);
18907 		ire = connp->conn_ire_cache;
18908 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18909 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18910 			IRE_REFHOLD(ire);
18911 			if (ire->ire_stq != NULL) {
18912 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18913 
18914 				zc_enabled = ill && (ill->ill_capabilities &
18915 				    ILL_CAPAB_ZEROCOPY) &&
18916 				    (ill->ill_zerocopy_capab->
18917 				    ill_zerocopy_flags != 0);
18918 			}
18919 			IRE_REFRELE(ire);
18920 		}
18921 		mutex_exit(&connp->conn_lock);
18922 	}
18923 	tcp->tcp_snd_zcopy_on = zc_enabled;
18924 	if (!TCP_IS_DETACHED(tcp)) {
18925 		if (zc_enabled) {
18926 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18927 			    ZCVMSAFE);
18928 			TCP_STAT(tcps, tcp_zcopy_on);
18929 		} else {
18930 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18931 			    ZCVMUNSAFE);
18932 			TCP_STAT(tcps, tcp_zcopy_off);
18933 		}
18934 	}
18935 	return (zc_enabled);
18936 }
18937 
18938 static mblk_t *
18939 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18940 {
18941 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18942 
18943 	if (do_tcpzcopy == 2)
18944 		return (bp);
18945 	else if (tcp->tcp_snd_zcopy_on) {
18946 		tcp->tcp_snd_zcopy_on = B_FALSE;
18947 		if (!TCP_IS_DETACHED(tcp)) {
18948 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
18949 			    ZCVMUNSAFE);
18950 			TCP_STAT(tcps, tcp_zcopy_disable);
18951 		}
18952 	}
18953 	return (tcp_zcopy_backoff(tcp, bp, 0));
18954 }
18955 
18956 /*
18957  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18958  * the original desballoca'ed segmapped mblk.
18959  */
18960 static mblk_t *
18961 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18962 {
18963 	mblk_t *head, *tail, *nbp;
18964 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18965 
18966 	if (IS_VMLOANED_MBLK(bp)) {
18967 		TCP_STAT(tcps, tcp_zcopy_backoff);
18968 		if ((head = copyb(bp)) == NULL) {
18969 			/* fail to backoff; leave it for the next backoff */
18970 			tcp->tcp_xmit_zc_clean = B_FALSE;
18971 			return (bp);
18972 		}
18973 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18974 			if (fix_xmitlist)
18975 				tcp_zcopy_notify(tcp);
18976 			else
18977 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18978 		}
18979 		nbp = bp->b_cont;
18980 		if (fix_xmitlist) {
18981 			head->b_prev = bp->b_prev;
18982 			head->b_next = bp->b_next;
18983 			if (tcp->tcp_xmit_tail == bp)
18984 				tcp->tcp_xmit_tail = head;
18985 		}
18986 		bp->b_next = NULL;
18987 		bp->b_prev = NULL;
18988 		freeb(bp);
18989 	} else {
18990 		head = bp;
18991 		nbp = bp->b_cont;
18992 	}
18993 	tail = head;
18994 	while (nbp) {
18995 		if (IS_VMLOANED_MBLK(nbp)) {
18996 			TCP_STAT(tcps, tcp_zcopy_backoff);
18997 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18998 				tcp->tcp_xmit_zc_clean = B_FALSE;
18999 				tail->b_cont = nbp;
19000 				return (head);
19001 			}
19002 			tail = tail->b_cont;
19003 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19004 				if (fix_xmitlist)
19005 					tcp_zcopy_notify(tcp);
19006 				else
19007 					tail->b_datap->db_struioflag |=
19008 					    STRUIO_ZCNOTIFY;
19009 			}
19010 			bp = nbp;
19011 			nbp = nbp->b_cont;
19012 			if (fix_xmitlist) {
19013 				tail->b_prev = bp->b_prev;
19014 				tail->b_next = bp->b_next;
19015 				if (tcp->tcp_xmit_tail == bp)
19016 					tcp->tcp_xmit_tail = tail;
19017 			}
19018 			bp->b_next = NULL;
19019 			bp->b_prev = NULL;
19020 			freeb(bp);
19021 		} else {
19022 			tail->b_cont = nbp;
19023 			tail = nbp;
19024 			nbp = nbp->b_cont;
19025 		}
19026 	}
19027 	if (fix_xmitlist) {
19028 		tcp->tcp_xmit_last = tail;
19029 		tcp->tcp_xmit_zc_clean = B_TRUE;
19030 	}
19031 	return (head);
19032 }
19033 
19034 static void
19035 tcp_zcopy_notify(tcp_t *tcp)
19036 {
19037 	struct stdata	*stp;
19038 	conn_t *connp;
19039 
19040 	if (tcp->tcp_detached)
19041 		return;
19042 	connp = tcp->tcp_connp;
19043 	if (IPCL_IS_NONSTR(connp)) {
19044 		(*connp->conn_upcalls->su_zcopy_notify)
19045 		    (connp->conn_upper_handle);
19046 		return;
19047 	}
19048 	stp = STREAM(tcp->tcp_rq);
19049 	mutex_enter(&stp->sd_lock);
19050 	stp->sd_flag |= STZCNOTIFY;
19051 	cv_broadcast(&stp->sd_zcopy_wait);
19052 	mutex_exit(&stp->sd_lock);
19053 }
19054 
19055 static boolean_t
19056 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
19057 {
19058 	ire_t	*ire;
19059 	conn_t	*connp = tcp->tcp_connp;
19060 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19061 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19062 
19063 	mutex_enter(&connp->conn_lock);
19064 	ire = connp->conn_ire_cache;
19065 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19066 
19067 	if ((ire != NULL) &&
19068 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
19069 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
19070 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19071 		IRE_REFHOLD(ire);
19072 		mutex_exit(&connp->conn_lock);
19073 	} else {
19074 		boolean_t cached = B_FALSE;
19075 		ts_label_t *tsl;
19076 
19077 		/* force a recheck later on */
19078 		tcp->tcp_ire_ill_check_done = B_FALSE;
19079 
19080 		TCP_DBGSTAT(tcps, tcp_ire_null1);
19081 		connp->conn_ire_cache = NULL;
19082 		mutex_exit(&connp->conn_lock);
19083 
19084 		if (ire != NULL)
19085 			IRE_REFRELE_NOTR(ire);
19086 
19087 		tsl = crgetlabel(CONN_CRED(connp));
19088 		ire = (dst ?
19089 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
19090 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19091 		    connp->conn_zoneid, tsl, ipst));
19092 
19093 		if (ire == NULL) {
19094 			TCP_STAT(tcps, tcp_ire_null);
19095 			return (B_FALSE);
19096 		}
19097 
19098 		IRE_REFHOLD_NOTR(ire);
19099 
19100 		mutex_enter(&connp->conn_lock);
19101 		if (CONN_CACHE_IRE(connp)) {
19102 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19103 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19104 				TCP_CHECK_IREINFO(tcp, ire);
19105 				connp->conn_ire_cache = ire;
19106 				cached = B_TRUE;
19107 			}
19108 			rw_exit(&ire->ire_bucket->irb_lock);
19109 		}
19110 		mutex_exit(&connp->conn_lock);
19111 
19112 		/*
19113 		 * We can continue to use the ire but since it was
19114 		 * not cached, we should drop the extra reference.
19115 		 */
19116 		if (!cached)
19117 			IRE_REFRELE_NOTR(ire);
19118 
19119 		/*
19120 		 * Rampart note: no need to select a new label here, since
19121 		 * labels are not allowed to change during the life of a TCP
19122 		 * connection.
19123 		 */
19124 	}
19125 
19126 	*irep = ire;
19127 
19128 	return (B_TRUE);
19129 }
19130 
19131 /*
19132  * Called from tcp_send() or tcp_send_data() to find workable IRE.
19133  *
19134  * 0 = success;
19135  * 1 = failed to find ire and ill.
19136  */
19137 static boolean_t
19138 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
19139 {
19140 	ipha_t		*ipha;
19141 	ipaddr_t	dst;
19142 	ire_t		*ire;
19143 	ill_t		*ill;
19144 	mblk_t		*ire_fp_mp;
19145 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19146 
19147 	if (mp != NULL)
19148 		ipha = (ipha_t *)mp->b_rptr;
19149 	else
19150 		ipha = tcp->tcp_ipha;
19151 	dst = ipha->ipha_dst;
19152 
19153 	if (!tcp_send_find_ire(tcp, &dst, &ire))
19154 		return (B_FALSE);
19155 
19156 	if ((ire->ire_flags & RTF_MULTIRT) ||
19157 	    (ire->ire_stq == NULL) ||
19158 	    (ire->ire_nce == NULL) ||
19159 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
19160 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
19161 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
19162 		TCP_STAT(tcps, tcp_ip_ire_send);
19163 		IRE_REFRELE(ire);
19164 		return (B_FALSE);
19165 	}
19166 
19167 	ill = ire_to_ill(ire);
19168 	ASSERT(ill != NULL);
19169 
19170 	if (!tcp->tcp_ire_ill_check_done) {
19171 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19172 		tcp->tcp_ire_ill_check_done = B_TRUE;
19173 	}
19174 
19175 	*irep = ire;
19176 	*illp = ill;
19177 
19178 	return (B_TRUE);
19179 }
19180 
19181 static void
19182 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
19183 {
19184 	ipha_t		*ipha;
19185 	ipaddr_t	src;
19186 	ipaddr_t	dst;
19187 	uint32_t	cksum;
19188 	ire_t		*ire;
19189 	uint16_t	*up;
19190 	ill_t		*ill;
19191 	conn_t		*connp = tcp->tcp_connp;
19192 	uint32_t	hcksum_txflags = 0;
19193 	mblk_t		*ire_fp_mp;
19194 	uint_t		ire_fp_mp_len;
19195 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19196 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19197 
19198 	ASSERT(DB_TYPE(mp) == M_DATA);
19199 
19200 	if (is_system_labeled() && DB_CRED(mp) == NULL)
19201 		mblk_setcred(mp, CONN_CRED(tcp->tcp_connp));
19202 
19203 	ipha = (ipha_t *)mp->b_rptr;
19204 	src = ipha->ipha_src;
19205 	dst = ipha->ipha_dst;
19206 
19207 	ASSERT(q != NULL);
19208 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
19209 
19210 	/*
19211 	 * Drop off fast path for IPv6 and also if options are present or
19212 	 * we need to resolve a TS label.
19213 	 */
19214 	if (tcp->tcp_ipversion != IPV4_VERSION ||
19215 	    !IPCL_IS_CONNECTED(connp) ||
19216 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
19217 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
19218 	    !connp->conn_ulp_labeled ||
19219 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
19220 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
19221 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
19222 		if (tcp->tcp_snd_zcopy_aware)
19223 			mp = tcp_zcopy_disable(tcp, mp);
19224 		TCP_STAT(tcps, tcp_ip_send);
19225 		CALL_IP_WPUT(connp, q, mp);
19226 		return;
19227 	}
19228 
19229 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
19230 		if (tcp->tcp_snd_zcopy_aware)
19231 			mp = tcp_zcopy_backoff(tcp, mp, 0);
19232 		CALL_IP_WPUT(connp, q, mp);
19233 		return;
19234 	}
19235 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
19236 	ire_fp_mp_len = MBLKL(ire_fp_mp);
19237 
19238 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19239 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19240 #ifndef _BIG_ENDIAN
19241 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19242 #endif
19243 
19244 	/*
19245 	 * Check to see if we need to re-enable LSO/MDT for this connection
19246 	 * because it was previously disabled due to changes in the ill;
19247 	 * note that by doing it here, this re-enabling only applies when
19248 	 * the packet is not dispatched through CALL_IP_WPUT().
19249 	 *
19250 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
19251 	 * case, since that's how we ended up here.  For IPv6, we do the
19252 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
19253 	 */
19254 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
19255 		/*
19256 		 * Restore LSO for this connection, so that next time around
19257 		 * it is eligible to go through tcp_lsosend() path again.
19258 		 */
19259 		TCP_STAT(tcps, tcp_lso_enabled);
19260 		tcp->tcp_lso = B_TRUE;
19261 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
19262 		    "interface %s\n", (void *)connp, ill->ill_name));
19263 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
19264 		/*
19265 		 * Restore MDT for this connection, so that next time around
19266 		 * it is eligible to go through tcp_multisend() path again.
19267 		 */
19268 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
19269 		tcp->tcp_mdt = B_TRUE;
19270 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
19271 		    "interface %s\n", (void *)connp, ill->ill_name));
19272 	}
19273 
19274 	if (tcp->tcp_snd_zcopy_aware) {
19275 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
19276 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
19277 			mp = tcp_zcopy_disable(tcp, mp);
19278 		/*
19279 		 * we shouldn't need to reset ipha as the mp containing
19280 		 * ipha should never be a zero-copy mp.
19281 		 */
19282 	}
19283 
19284 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
19285 		ASSERT(ill->ill_hcksum_capab != NULL);
19286 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
19287 	}
19288 
19289 	/* pseudo-header checksum (do it in parts for IP header checksum) */
19290 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19291 
19292 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
19293 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
19294 
19295 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
19296 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
19297 
19298 	/* Software checksum? */
19299 	if (DB_CKSUMFLAGS(mp) == 0) {
19300 		TCP_STAT(tcps, tcp_out_sw_cksum);
19301 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
19302 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
19303 	}
19304 
19305 	/* Calculate IP header checksum if hardware isn't capable */
19306 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
19307 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
19308 		    ((uint16_t *)ipha)[4]);
19309 	}
19310 
19311 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
19312 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
19313 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
19314 
19315 	UPDATE_OB_PKT_COUNT(ire);
19316 	ire->ire_last_used_time = lbolt;
19317 
19318 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
19319 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
19320 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
19321 	    ntohs(ipha->ipha_length));
19322 
19323 	DTRACE_PROBE4(ip4__physical__out__start,
19324 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
19325 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
19326 	    ipst->ips_ipv4firewall_physical_out,
19327 	    NULL, ill, ipha, mp, mp, 0, ipst);
19328 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19329 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
19330 
19331 	if (mp != NULL) {
19332 		if (ipst->ips_ipobs_enabled) {
19333 			zoneid_t szone;
19334 
19335 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
19336 			    ipst, ALL_ZONES);
19337 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
19338 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
19339 		}
19340 
19341 		ILL_SEND_TX(ill, ire, connp, mp, 0);
19342 	}
19343 
19344 	IRE_REFRELE(ire);
19345 }
19346 
19347 /*
19348  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19349  * if the receiver shrinks the window, i.e. moves the right window to the
19350  * left, the we should not send new data, but should retransmit normally the
19351  * old unacked data between suna and suna + swnd. We might has sent data
19352  * that is now outside the new window, pretend that we didn't send  it.
19353  */
19354 static void
19355 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19356 {
19357 	uint32_t	snxt = tcp->tcp_snxt;
19358 	mblk_t		*xmit_tail;
19359 	int32_t		offset;
19360 
19361 	ASSERT(shrunk_count > 0);
19362 
19363 	/* Pretend we didn't send the data outside the window */
19364 	snxt -= shrunk_count;
19365 
19366 	/* Get the mblk and the offset in it per the shrunk window */
19367 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19368 
19369 	ASSERT(xmit_tail != NULL);
19370 
19371 	/* Reset all the values per the now shrunk window */
19372 	tcp->tcp_snxt = snxt;
19373 	tcp->tcp_xmit_tail = xmit_tail;
19374 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19375 	    offset;
19376 	tcp->tcp_unsent += shrunk_count;
19377 
19378 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19379 		/*
19380 		 * Make sure the timer is running so that we will probe a zero
19381 		 * window.
19382 		 */
19383 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19384 }
19385 
19386 
19387 /*
19388  * The TCP normal data output path.
19389  * NOTE: the logic of the fast path is duplicated from this function.
19390  */
19391 static void
19392 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19393 {
19394 	int		len;
19395 	mblk_t		*local_time;
19396 	mblk_t		*mp1;
19397 	uint32_t	snxt;
19398 	int		tail_unsent;
19399 	int		tcpstate;
19400 	int		usable = 0;
19401 	mblk_t		*xmit_tail;
19402 	queue_t		*q = tcp->tcp_wq;
19403 	int32_t		mss;
19404 	int32_t		num_sack_blk = 0;
19405 	int32_t		tcp_hdr_len;
19406 	int32_t		tcp_tcp_hdr_len;
19407 	int		mdt_thres;
19408 	int		rc;
19409 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19410 	ip_stack_t	*ipst;
19411 
19412 	tcpstate = tcp->tcp_state;
19413 	if (mp == NULL) {
19414 		/*
19415 		 * tcp_wput_data() with NULL mp should only be called when
19416 		 * there is unsent data.
19417 		 */
19418 		ASSERT(tcp->tcp_unsent > 0);
19419 		/* Really tacky... but we need this for detached closes. */
19420 		len = tcp->tcp_unsent;
19421 		goto data_null;
19422 	}
19423 
19424 #if CCS_STATS
19425 	wrw_stats.tot.count++;
19426 	wrw_stats.tot.bytes += msgdsize(mp);
19427 #endif
19428 	ASSERT(mp->b_datap->db_type == M_DATA);
19429 	/*
19430 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19431 	 * or before a connection attempt has begun.
19432 	 */
19433 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19434 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19435 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19436 #ifdef DEBUG
19437 			cmn_err(CE_WARN,
19438 			    "tcp_wput_data: data after ordrel, %s",
19439 			    tcp_display(tcp, NULL,
19440 			    DISP_ADDR_AND_PORT));
19441 #else
19442 			if (tcp->tcp_debug) {
19443 				(void) strlog(TCP_MOD_ID, 0, 1,
19444 				    SL_TRACE|SL_ERROR,
19445 				    "tcp_wput_data: data after ordrel, %s\n",
19446 				    tcp_display(tcp, NULL,
19447 				    DISP_ADDR_AND_PORT));
19448 			}
19449 #endif /* DEBUG */
19450 		}
19451 		if (tcp->tcp_snd_zcopy_aware &&
19452 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19453 			tcp_zcopy_notify(tcp);
19454 		freemsg(mp);
19455 		mutex_enter(&tcp->tcp_non_sq_lock);
19456 		if (tcp->tcp_flow_stopped &&
19457 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19458 			tcp_clrqfull(tcp);
19459 		}
19460 		mutex_exit(&tcp->tcp_non_sq_lock);
19461 		return;
19462 	}
19463 
19464 	/* Strip empties */
19465 	for (;;) {
19466 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19467 		    (uintptr_t)INT_MAX);
19468 		len = (int)(mp->b_wptr - mp->b_rptr);
19469 		if (len > 0)
19470 			break;
19471 		mp1 = mp;
19472 		mp = mp->b_cont;
19473 		freeb(mp1);
19474 		if (!mp) {
19475 			return;
19476 		}
19477 	}
19478 
19479 	/* If we are the first on the list ... */
19480 	if (tcp->tcp_xmit_head == NULL) {
19481 		tcp->tcp_xmit_head = mp;
19482 		tcp->tcp_xmit_tail = mp;
19483 		tcp->tcp_xmit_tail_unsent = len;
19484 	} else {
19485 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19486 		struct datab *dp;
19487 
19488 		mp1 = tcp->tcp_xmit_last;
19489 		if (len < tcp_tx_pull_len &&
19490 		    (dp = mp1->b_datap)->db_ref == 1 &&
19491 		    dp->db_lim - mp1->b_wptr >= len) {
19492 			ASSERT(len > 0);
19493 			ASSERT(!mp1->b_cont);
19494 			if (len == 1) {
19495 				*mp1->b_wptr++ = *mp->b_rptr;
19496 			} else {
19497 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19498 				mp1->b_wptr += len;
19499 			}
19500 			if (mp1 == tcp->tcp_xmit_tail)
19501 				tcp->tcp_xmit_tail_unsent += len;
19502 			mp1->b_cont = mp->b_cont;
19503 			if (tcp->tcp_snd_zcopy_aware &&
19504 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19505 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19506 			freeb(mp);
19507 			mp = mp1;
19508 		} else {
19509 			tcp->tcp_xmit_last->b_cont = mp;
19510 		}
19511 		len += tcp->tcp_unsent;
19512 	}
19513 
19514 	/* Tack on however many more positive length mblks we have */
19515 	if ((mp1 = mp->b_cont) != NULL) {
19516 		do {
19517 			int tlen;
19518 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19519 			    (uintptr_t)INT_MAX);
19520 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19521 			if (tlen <= 0) {
19522 				mp->b_cont = mp1->b_cont;
19523 				freeb(mp1);
19524 			} else {
19525 				len += tlen;
19526 				mp = mp1;
19527 			}
19528 		} while ((mp1 = mp->b_cont) != NULL);
19529 	}
19530 	tcp->tcp_xmit_last = mp;
19531 	tcp->tcp_unsent = len;
19532 
19533 	if (urgent)
19534 		usable = 1;
19535 
19536 data_null:
19537 	snxt = tcp->tcp_snxt;
19538 	xmit_tail = tcp->tcp_xmit_tail;
19539 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19540 
19541 	/*
19542 	 * Note that tcp_mss has been adjusted to take into account the
19543 	 * timestamp option if applicable.  Because SACK options do not
19544 	 * appear in every TCP segments and they are of variable lengths,
19545 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19546 	 * the actual segment length when we need to send a segment which
19547 	 * includes SACK options.
19548 	 */
19549 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19550 		int32_t	opt_len;
19551 
19552 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19553 		    tcp->tcp_num_sack_blk);
19554 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19555 		    2 + TCPOPT_HEADER_LEN;
19556 		mss = tcp->tcp_mss - opt_len;
19557 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19558 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19559 	} else {
19560 		mss = tcp->tcp_mss;
19561 		tcp_hdr_len = tcp->tcp_hdr_len;
19562 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19563 	}
19564 
19565 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19566 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19567 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19568 	}
19569 	if (tcpstate == TCPS_SYN_RCVD) {
19570 		/*
19571 		 * The three-way connection establishment handshake is not
19572 		 * complete yet. We want to queue the data for transmission
19573 		 * after entering ESTABLISHED state (RFC793). A jump to
19574 		 * "done" label effectively leaves data on the queue.
19575 		 */
19576 		goto done;
19577 	} else {
19578 		int usable_r;
19579 
19580 		/*
19581 		 * In the special case when cwnd is zero, which can only
19582 		 * happen if the connection is ECN capable, return now.
19583 		 * New segments is sent using tcp_timer().  The timer
19584 		 * is set in tcp_rput_data().
19585 		 */
19586 		if (tcp->tcp_cwnd == 0) {
19587 			/*
19588 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19589 			 * finished.
19590 			 */
19591 			ASSERT(tcp->tcp_ecn_ok ||
19592 			    tcp->tcp_state < TCPS_ESTABLISHED);
19593 			return;
19594 		}
19595 
19596 		/* NOTE: trouble if xmitting while SYN not acked? */
19597 		usable_r = snxt - tcp->tcp_suna;
19598 		usable_r = tcp->tcp_swnd - usable_r;
19599 
19600 		/*
19601 		 * Check if the receiver has shrunk the window.  If
19602 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19603 		 * cannot be set as there is unsent data, so FIN cannot
19604 		 * be sent out.  Otherwise, we need to take into account
19605 		 * of FIN as it consumes an "invisible" sequence number.
19606 		 */
19607 		ASSERT(tcp->tcp_fin_sent == 0);
19608 		if (usable_r < 0) {
19609 			/*
19610 			 * The receiver has shrunk the window and we have sent
19611 			 * -usable_r date beyond the window, re-adjust.
19612 			 *
19613 			 * If TCP window scaling is enabled, there can be
19614 			 * round down error as the advertised receive window
19615 			 * is actually right shifted n bits.  This means that
19616 			 * the lower n bits info is wiped out.  It will look
19617 			 * like the window is shrunk.  Do a check here to
19618 			 * see if the shrunk amount is actually within the
19619 			 * error in window calculation.  If it is, just
19620 			 * return.  Note that this check is inside the
19621 			 * shrunk window check.  This makes sure that even
19622 			 * though tcp_process_shrunk_swnd() is not called,
19623 			 * we will stop further processing.
19624 			 */
19625 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19626 				tcp_process_shrunk_swnd(tcp, -usable_r);
19627 			}
19628 			return;
19629 		}
19630 
19631 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19632 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19633 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19634 
19635 		/* usable = MIN(usable, unsent) */
19636 		if (usable_r > len)
19637 			usable_r = len;
19638 
19639 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19640 		if (usable_r > 0) {
19641 			usable = usable_r;
19642 		} else {
19643 			/* Bypass all other unnecessary processing. */
19644 			goto done;
19645 		}
19646 	}
19647 
19648 	local_time = (mblk_t *)lbolt;
19649 
19650 	/*
19651 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19652 	 * BSD.  This is more in line with the true intent of Nagle.
19653 	 *
19654 	 * The conditions are:
19655 	 * 1. The amount of unsent data (or amount of data which can be
19656 	 *    sent, whichever is smaller) is less than Nagle limit.
19657 	 * 2. The last sent size is also less than Nagle limit.
19658 	 * 3. There is unack'ed data.
19659 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19660 	 *    Nagle algorithm.  This reduces the probability that urgent
19661 	 *    bytes get "merged" together.
19662 	 * 5. The app has not closed the connection.  This eliminates the
19663 	 *    wait time of the receiving side waiting for the last piece of
19664 	 *    (small) data.
19665 	 *
19666 	 * If all are satisified, exit without sending anything.  Note
19667 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19668 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19669 	 * 4095).
19670 	 */
19671 	if (usable < (int)tcp->tcp_naglim &&
19672 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19673 	    snxt != tcp->tcp_suna &&
19674 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19675 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19676 		goto done;
19677 	}
19678 
19679 	if (tcp->tcp_cork) {
19680 		/*
19681 		 * if the tcp->tcp_cork option is set, then we have to force
19682 		 * TCP not to send partial segment (smaller than MSS bytes).
19683 		 * We are calculating the usable now based on full mss and
19684 		 * will save the rest of remaining data for later.
19685 		 */
19686 		if (usable < mss)
19687 			goto done;
19688 		usable = (usable / mss) * mss;
19689 	}
19690 
19691 	/* Update the latest receive window size in TCP header. */
19692 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19693 	    tcp->tcp_tcph->th_win);
19694 
19695 	/*
19696 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19697 	 *
19698 	 * 1. Simple TCP/IP{v4,v6} (no options).
19699 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19700 	 * 3. If the TCP connection is in ESTABLISHED state.
19701 	 * 4. The TCP is not detached.
19702 	 *
19703 	 * If any of the above conditions have changed during the
19704 	 * connection, stop using LSO/MDT and restore the stream head
19705 	 * parameters accordingly.
19706 	 */
19707 	ipst = tcps->tcps_netstack->netstack_ip;
19708 
19709 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19710 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19711 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19712 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19713 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19714 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19715 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19716 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19717 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19718 		if (tcp->tcp_lso) {
19719 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19720 			tcp->tcp_lso = B_FALSE;
19721 		} else {
19722 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19723 			tcp->tcp_mdt = B_FALSE;
19724 		}
19725 
19726 		/* Anything other than detached is considered pathological */
19727 		if (!TCP_IS_DETACHED(tcp)) {
19728 			if (tcp->tcp_lso)
19729 				TCP_STAT(tcps, tcp_lso_disabled);
19730 			else
19731 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19732 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19733 		}
19734 	}
19735 
19736 	/* Use MDT if sendable amount is greater than the threshold */
19737 	if (tcp->tcp_mdt &&
19738 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19739 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19740 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19741 	    (tcp->tcp_valid_bits == 0 ||
19742 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19743 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19744 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19745 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19746 		    local_time, mdt_thres);
19747 	} else {
19748 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19749 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19750 		    local_time, INT_MAX);
19751 	}
19752 
19753 	/* Pretend that all we were trying to send really got sent */
19754 	if (rc < 0 && tail_unsent < 0) {
19755 		do {
19756 			xmit_tail = xmit_tail->b_cont;
19757 			xmit_tail->b_prev = local_time;
19758 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19759 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19760 			tail_unsent += (int)(xmit_tail->b_wptr -
19761 			    xmit_tail->b_rptr);
19762 		} while (tail_unsent < 0);
19763 	}
19764 done:;
19765 	tcp->tcp_xmit_tail = xmit_tail;
19766 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19767 	len = tcp->tcp_snxt - snxt;
19768 	if (len) {
19769 		/*
19770 		 * If new data was sent, need to update the notsack
19771 		 * list, which is, afterall, data blocks that have
19772 		 * not been sack'ed by the receiver.  New data is
19773 		 * not sack'ed.
19774 		 */
19775 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19776 			/* len is a negative value. */
19777 			tcp->tcp_pipe -= len;
19778 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19779 			    tcp->tcp_snxt, snxt,
19780 			    &(tcp->tcp_num_notsack_blk),
19781 			    &(tcp->tcp_cnt_notsack_list));
19782 		}
19783 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19784 		tcp->tcp_rack = tcp->tcp_rnxt;
19785 		tcp->tcp_rack_cnt = 0;
19786 		if ((snxt + len) == tcp->tcp_suna) {
19787 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19788 		}
19789 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19790 		/*
19791 		 * Didn't send anything. Make sure the timer is running
19792 		 * so that we will probe a zero window.
19793 		 */
19794 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19795 	}
19796 	/* Note that len is the amount we just sent but with a negative sign */
19797 	tcp->tcp_unsent += len;
19798 	mutex_enter(&tcp->tcp_non_sq_lock);
19799 	if (tcp->tcp_flow_stopped) {
19800 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19801 			tcp_clrqfull(tcp);
19802 		}
19803 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19804 		tcp_setqfull(tcp);
19805 	}
19806 	mutex_exit(&tcp->tcp_non_sq_lock);
19807 }
19808 
19809 /*
19810  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19811  * outgoing TCP header with the template header, as well as other
19812  * options such as time-stamp, ECN and/or SACK.
19813  */
19814 static void
19815 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19816 {
19817 	tcph_t *tcp_tmpl, *tcp_h;
19818 	uint32_t *dst, *src;
19819 	int hdrlen;
19820 
19821 	ASSERT(OK_32PTR(rptr));
19822 
19823 	/* Template header */
19824 	tcp_tmpl = tcp->tcp_tcph;
19825 
19826 	/* Header of outgoing packet */
19827 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19828 
19829 	/* dst and src are opaque 32-bit fields, used for copying */
19830 	dst = (uint32_t *)rptr;
19831 	src = (uint32_t *)tcp->tcp_iphc;
19832 	hdrlen = tcp->tcp_hdr_len;
19833 
19834 	/* Fill time-stamp option if needed */
19835 	if (tcp->tcp_snd_ts_ok) {
19836 		U32_TO_BE32((uint32_t)now,
19837 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19838 		U32_TO_BE32(tcp->tcp_ts_recent,
19839 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19840 	} else {
19841 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19842 	}
19843 
19844 	/*
19845 	 * Copy the template header; is this really more efficient than
19846 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19847 	 * but perhaps not for other scenarios.
19848 	 */
19849 	dst[0] = src[0];
19850 	dst[1] = src[1];
19851 	dst[2] = src[2];
19852 	dst[3] = src[3];
19853 	dst[4] = src[4];
19854 	dst[5] = src[5];
19855 	dst[6] = src[6];
19856 	dst[7] = src[7];
19857 	dst[8] = src[8];
19858 	dst[9] = src[9];
19859 	if (hdrlen -= 40) {
19860 		hdrlen >>= 2;
19861 		dst += 10;
19862 		src += 10;
19863 		do {
19864 			*dst++ = *src++;
19865 		} while (--hdrlen);
19866 	}
19867 
19868 	/*
19869 	 * Set the ECN info in the TCP header if it is not a zero
19870 	 * window probe.  Zero window probe is only sent in
19871 	 * tcp_wput_data() and tcp_timer().
19872 	 */
19873 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19874 		SET_ECT(tcp, rptr);
19875 
19876 		if (tcp->tcp_ecn_echo_on)
19877 			tcp_h->th_flags[0] |= TH_ECE;
19878 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19879 			tcp_h->th_flags[0] |= TH_CWR;
19880 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19881 		}
19882 	}
19883 
19884 	/* Fill in SACK options */
19885 	if (num_sack_blk > 0) {
19886 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19887 		sack_blk_t *tmp;
19888 		int32_t	i;
19889 
19890 		wptr[0] = TCPOPT_NOP;
19891 		wptr[1] = TCPOPT_NOP;
19892 		wptr[2] = TCPOPT_SACK;
19893 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19894 		    sizeof (sack_blk_t);
19895 		wptr += TCPOPT_REAL_SACK_LEN;
19896 
19897 		tmp = tcp->tcp_sack_list;
19898 		for (i = 0; i < num_sack_blk; i++) {
19899 			U32_TO_BE32(tmp[i].begin, wptr);
19900 			wptr += sizeof (tcp_seq);
19901 			U32_TO_BE32(tmp[i].end, wptr);
19902 			wptr += sizeof (tcp_seq);
19903 		}
19904 		tcp_h->th_offset_and_rsrvd[0] +=
19905 		    ((num_sack_blk * 2 + 1) << 4);
19906 	}
19907 }
19908 
19909 /*
19910  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19911  * the destination address and SAP attribute, and if necessary, the
19912  * hardware checksum offload attribute to a Multidata message.
19913  */
19914 static int
19915 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19916     const uint32_t start, const uint32_t stuff, const uint32_t end,
19917     const uint32_t flags, tcp_stack_t *tcps)
19918 {
19919 	/* Add global destination address & SAP attribute */
19920 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19921 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19922 		    "destination address+SAP\n"));
19923 
19924 		if (dlmp != NULL)
19925 			TCP_STAT(tcps, tcp_mdt_allocfail);
19926 		return (-1);
19927 	}
19928 
19929 	/* Add global hwcksum attribute */
19930 	if (hwcksum &&
19931 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19932 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19933 		    "checksum attribute\n"));
19934 
19935 		TCP_STAT(tcps, tcp_mdt_allocfail);
19936 		return (-1);
19937 	}
19938 
19939 	return (0);
19940 }
19941 
19942 /*
19943  * Smaller and private version of pdescinfo_t used specifically for TCP,
19944  * which allows for only two payload spans per packet.
19945  */
19946 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19947 
19948 /*
19949  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19950  * scheme, and returns one the following:
19951  *
19952  * -1 = failed allocation.
19953  *  0 = success; burst count reached, or usable send window is too small,
19954  *      and that we'd rather wait until later before sending again.
19955  */
19956 static int
19957 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19958     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19959     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19960     const int mdt_thres)
19961 {
19962 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19963 	multidata_t	*mmd;
19964 	uint_t		obsegs, obbytes, hdr_frag_sz;
19965 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19966 	int		num_burst_seg, max_pld;
19967 	pdesc_t		*pkt;
19968 	tcp_pdescinfo_t	tcp_pkt_info;
19969 	pdescinfo_t	*pkt_info;
19970 	int		pbuf_idx, pbuf_idx_nxt;
19971 	int		seg_len, len, spill, af;
19972 	boolean_t	add_buffer, zcopy, clusterwide;
19973 	boolean_t	rconfirm = B_FALSE;
19974 	boolean_t	done = B_FALSE;
19975 	uint32_t	cksum;
19976 	uint32_t	hwcksum_flags;
19977 	ire_t		*ire = NULL;
19978 	ill_t		*ill;
19979 	ipha_t		*ipha;
19980 	ip6_t		*ip6h;
19981 	ipaddr_t	src, dst;
19982 	ill_zerocopy_capab_t *zc_cap = NULL;
19983 	uint16_t	*up;
19984 	int		err;
19985 	conn_t		*connp;
19986 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19987 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19988 	int		usable_mmd, tail_unsent_mmd;
19989 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
19990 	mblk_t		*xmit_tail_mmd;
19991 	netstackid_t	stack_id;
19992 
19993 #ifdef	_BIG_ENDIAN
19994 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19995 #else
19996 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19997 #endif
19998 
19999 #define	PREP_NEW_MULTIDATA() {			\
20000 	mmd = NULL;				\
20001 	md_mp = md_hbuf = NULL;			\
20002 	cur_hdr_off = 0;			\
20003 	max_pld = tcp->tcp_mdt_max_pld;		\
20004 	pbuf_idx = pbuf_idx_nxt = -1;		\
20005 	add_buffer = B_TRUE;			\
20006 	zcopy = B_FALSE;			\
20007 }
20008 
20009 #define	PREP_NEW_PBUF() {			\
20010 	md_pbuf = md_pbuf_nxt = NULL;		\
20011 	pbuf_idx = pbuf_idx_nxt = -1;		\
20012 	cur_pld_off = 0;			\
20013 	first_snxt = *snxt;			\
20014 	ASSERT(*tail_unsent > 0);		\
20015 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
20016 }
20017 
20018 	ASSERT(mdt_thres >= mss);
20019 	ASSERT(*usable > 0 && *usable > mdt_thres);
20020 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20021 	ASSERT(!TCP_IS_DETACHED(tcp));
20022 	ASSERT(tcp->tcp_valid_bits == 0 ||
20023 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
20024 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
20025 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
20026 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20027 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
20028 
20029 	connp = tcp->tcp_connp;
20030 	ASSERT(connp != NULL);
20031 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
20032 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
20033 
20034 	stack_id = connp->conn_netstack->netstack_stackid;
20035 
20036 	usable_mmd = tail_unsent_mmd = 0;
20037 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
20038 	xmit_tail_mmd = NULL;
20039 	/*
20040 	 * Note that tcp will only declare at most 2 payload spans per
20041 	 * packet, which is much lower than the maximum allowable number
20042 	 * of packet spans per Multidata.  For this reason, we use the
20043 	 * privately declared and smaller descriptor info structure, in
20044 	 * order to save some stack space.
20045 	 */
20046 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
20047 
20048 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
20049 	if (af == AF_INET) {
20050 		dst = tcp->tcp_ipha->ipha_dst;
20051 		src = tcp->tcp_ipha->ipha_src;
20052 		ASSERT(!CLASSD(dst));
20053 	}
20054 	ASSERT(af == AF_INET ||
20055 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
20056 
20057 	obsegs = obbytes = 0;
20058 	num_burst_seg = tcp->tcp_snd_burst;
20059 	md_mp_head = NULL;
20060 	PREP_NEW_MULTIDATA();
20061 
20062 	/*
20063 	 * Before we go on further, make sure there is an IRE that we can
20064 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
20065 	 * in proceeding any further, and we should just hand everything
20066 	 * off to the legacy path.
20067 	 */
20068 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
20069 		goto legacy_send_no_md;
20070 
20071 	ASSERT(ire != NULL);
20072 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
20073 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
20074 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
20075 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
20076 	/*
20077 	 * If we do support loopback for MDT (which requires modifications
20078 	 * to the receiving paths), the following assertions should go away,
20079 	 * and we would be sending the Multidata to loopback conn later on.
20080 	 */
20081 	ASSERT(!IRE_IS_LOCAL(ire));
20082 	ASSERT(ire->ire_stq != NULL);
20083 
20084 	ill = ire_to_ill(ire);
20085 	ASSERT(ill != NULL);
20086 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
20087 
20088 	if (!tcp->tcp_ire_ill_check_done) {
20089 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
20090 		tcp->tcp_ire_ill_check_done = B_TRUE;
20091 	}
20092 
20093 	/*
20094 	 * If the underlying interface conditions have changed, or if the
20095 	 * new interface does not support MDT, go back to legacy path.
20096 	 */
20097 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
20098 		/* don't go through this path anymore for this connection */
20099 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
20100 		tcp->tcp_mdt = B_FALSE;
20101 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
20102 		    "interface %s\n", (void *)connp, ill->ill_name));
20103 		/* IRE will be released prior to returning */
20104 		goto legacy_send_no_md;
20105 	}
20106 
20107 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
20108 		zc_cap = ill->ill_zerocopy_capab;
20109 
20110 	/*
20111 	 * Check if we can take tcp fast-path. Note that "incomplete"
20112 	 * ire's (where the link-layer for next hop is not resolved
20113 	 * or where the fast-path header in nce_fp_mp is not available
20114 	 * yet) are sent down the legacy (slow) path.
20115 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
20116 	 */
20117 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
20118 		/* IRE will be released prior to returning */
20119 		goto legacy_send_no_md;
20120 	}
20121 
20122 	/* go to legacy path if interface doesn't support zerocopy */
20123 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
20124 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
20125 		/* IRE will be released prior to returning */
20126 		goto legacy_send_no_md;
20127 	}
20128 
20129 	/* does the interface support hardware checksum offload? */
20130 	hwcksum_flags = 0;
20131 	if (ILL_HCKSUM_CAPABLE(ill) &&
20132 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
20133 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
20134 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
20135 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20136 		    HCKSUM_IPHDRCKSUM)
20137 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
20138 
20139 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20140 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
20141 			hwcksum_flags |= HCK_FULLCKSUM;
20142 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20143 		    HCKSUM_INET_PARTIAL)
20144 			hwcksum_flags |= HCK_PARTIALCKSUM;
20145 	}
20146 
20147 	/*
20148 	 * Each header fragment consists of the leading extra space,
20149 	 * followed by the TCP/IP header, and the trailing extra space.
20150 	 * We make sure that each header fragment begins on a 32-bit
20151 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
20152 	 * aligned in tcp_mdt_update).
20153 	 */
20154 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
20155 	    tcp->tcp_mdt_hdr_tail), 4);
20156 
20157 	/* are we starting from the beginning of data block? */
20158 	if (*tail_unsent == 0) {
20159 		*xmit_tail = (*xmit_tail)->b_cont;
20160 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
20161 		*tail_unsent = (int)MBLKL(*xmit_tail);
20162 	}
20163 
20164 	/*
20165 	 * Here we create one or more Multidata messages, each made up of
20166 	 * one header buffer and up to N payload buffers.  This entire
20167 	 * operation is done within two loops:
20168 	 *
20169 	 * The outer loop mostly deals with creating the Multidata message,
20170 	 * as well as the header buffer that gets added to it.  It also
20171 	 * links the Multidata messages together such that all of them can
20172 	 * be sent down to the lower layer in a single putnext call; this
20173 	 * linking behavior depends on the tcp_mdt_chain tunable.
20174 	 *
20175 	 * The inner loop takes an existing Multidata message, and adds
20176 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
20177 	 * packetizes those buffers by filling up the corresponding header
20178 	 * buffer fragments with the proper IP and TCP headers, and by
20179 	 * describing the layout of each packet in the packet descriptors
20180 	 * that get added to the Multidata.
20181 	 */
20182 	do {
20183 		/*
20184 		 * If usable send window is too small, or data blocks in
20185 		 * transmit list are smaller than our threshold (i.e. app
20186 		 * performs large writes followed by small ones), we hand
20187 		 * off the control over to the legacy path.  Note that we'll
20188 		 * get back the control once it encounters a large block.
20189 		 */
20190 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
20191 		    (*xmit_tail)->b_cont != NULL &&
20192 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
20193 			/* send down what we've got so far */
20194 			if (md_mp_head != NULL) {
20195 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
20196 				    obsegs, obbytes, &rconfirm);
20197 			}
20198 			/*
20199 			 * Pass control over to tcp_send(), but tell it to
20200 			 * return to us once a large-size transmission is
20201 			 * possible.
20202 			 */
20203 			TCP_STAT(tcps, tcp_mdt_legacy_small);
20204 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
20205 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
20206 			    tail_unsent, xmit_tail, local_time,
20207 			    mdt_thres)) <= 0) {
20208 				/* burst count reached, or alloc failed */
20209 				IRE_REFRELE(ire);
20210 				return (err);
20211 			}
20212 
20213 			/* tcp_send() may have sent everything, so check */
20214 			if (*usable <= 0) {
20215 				IRE_REFRELE(ire);
20216 				return (0);
20217 			}
20218 
20219 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
20220 			/*
20221 			 * We may have delivered the Multidata, so make sure
20222 			 * to re-initialize before the next round.
20223 			 */
20224 			md_mp_head = NULL;
20225 			obsegs = obbytes = 0;
20226 			num_burst_seg = tcp->tcp_snd_burst;
20227 			PREP_NEW_MULTIDATA();
20228 
20229 			/* are we starting from the beginning of data block? */
20230 			if (*tail_unsent == 0) {
20231 				*xmit_tail = (*xmit_tail)->b_cont;
20232 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20233 				    (uintptr_t)INT_MAX);
20234 				*tail_unsent = (int)MBLKL(*xmit_tail);
20235 			}
20236 		}
20237 		/*
20238 		 * Record current values for parameters we may need to pass
20239 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
20240 		 * each iteration of the outer loop (each multidata message
20241 		 * creation). If we have a failure in the inner loop, we send
20242 		 * any complete multidata messages we have before reverting
20243 		 * to using the traditional non-md path.
20244 		 */
20245 		snxt_mmd = *snxt;
20246 		usable_mmd = *usable;
20247 		xmit_tail_mmd = *xmit_tail;
20248 		tail_unsent_mmd = *tail_unsent;
20249 		obsegs_mmd = obsegs;
20250 		obbytes_mmd = obbytes;
20251 
20252 		/*
20253 		 * max_pld limits the number of mblks in tcp's transmit
20254 		 * queue that can be added to a Multidata message.  Once
20255 		 * this counter reaches zero, no more additional mblks
20256 		 * can be added to it.  What happens afterwards depends
20257 		 * on whether or not we are set to chain the Multidata
20258 		 * messages.  If we are to link them together, reset
20259 		 * max_pld to its original value (tcp_mdt_max_pld) and
20260 		 * prepare to create a new Multidata message which will
20261 		 * get linked to md_mp_head.  Else, leave it alone and
20262 		 * let the inner loop break on its own.
20263 		 */
20264 		if (tcp_mdt_chain && max_pld == 0)
20265 			PREP_NEW_MULTIDATA();
20266 
20267 		/* adding a payload buffer; re-initialize values */
20268 		if (add_buffer)
20269 			PREP_NEW_PBUF();
20270 
20271 		/*
20272 		 * If we don't have a Multidata, either because we just
20273 		 * (re)entered this outer loop, or after we branched off
20274 		 * to tcp_send above, setup the Multidata and header
20275 		 * buffer to be used.
20276 		 */
20277 		if (md_mp == NULL) {
20278 			int md_hbuflen;
20279 			uint32_t start, stuff;
20280 
20281 			/*
20282 			 * Calculate Multidata header buffer size large enough
20283 			 * to hold all of the headers that can possibly be
20284 			 * sent at this moment.  We'd rather over-estimate
20285 			 * the size than running out of space; this is okay
20286 			 * since this buffer is small anyway.
20287 			 */
20288 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
20289 
20290 			/*
20291 			 * Start and stuff offset for partial hardware
20292 			 * checksum offload; these are currently for IPv4.
20293 			 * For full checksum offload, they are set to zero.
20294 			 */
20295 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
20296 				if (af == AF_INET) {
20297 					start = IP_SIMPLE_HDR_LENGTH;
20298 					stuff = IP_SIMPLE_HDR_LENGTH +
20299 					    TCP_CHECKSUM_OFFSET;
20300 				} else {
20301 					start = IPV6_HDR_LEN;
20302 					stuff = IPV6_HDR_LEN +
20303 					    TCP_CHECKSUM_OFFSET;
20304 				}
20305 			} else {
20306 				start = stuff = 0;
20307 			}
20308 
20309 			/*
20310 			 * Create the header buffer, Multidata, as well as
20311 			 * any necessary attributes (destination address,
20312 			 * SAP and hardware checksum offload) that should
20313 			 * be associated with the Multidata message.
20314 			 */
20315 			ASSERT(cur_hdr_off == 0);
20316 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
20317 			    ((md_hbuf->b_wptr += md_hbuflen),
20318 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
20319 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
20320 			    /* fastpath mblk */
20321 			    ire->ire_nce->nce_res_mp,
20322 			    /* hardware checksum enabled */
20323 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
20324 			    /* hardware checksum offsets */
20325 			    start, stuff, 0,
20326 			    /* hardware checksum flag */
20327 			    hwcksum_flags, tcps) != 0)) {
20328 legacy_send:
20329 				/*
20330 				 * We arrive here from a failure within the
20331 				 * inner (packetizer) loop or we fail one of
20332 				 * the conditionals above. We restore the
20333 				 * previously checkpointed values for:
20334 				 *    xmit_tail
20335 				 *    usable
20336 				 *    tail_unsent
20337 				 *    snxt
20338 				 *    obbytes
20339 				 *    obsegs
20340 				 * We should then be able to dispatch any
20341 				 * complete multidata before reverting to the
20342 				 * traditional path with consistent parameters
20343 				 * (the inner loop updates these as it
20344 				 * iterates).
20345 				 */
20346 				*xmit_tail = xmit_tail_mmd;
20347 				*usable = usable_mmd;
20348 				*tail_unsent = tail_unsent_mmd;
20349 				*snxt = snxt_mmd;
20350 				obbytes = obbytes_mmd;
20351 				obsegs = obsegs_mmd;
20352 				if (md_mp != NULL) {
20353 					/* Unlink message from the chain */
20354 					if (md_mp_head != NULL) {
20355 						err = (intptr_t)rmvb(md_mp_head,
20356 						    md_mp);
20357 						/*
20358 						 * We can't assert that rmvb
20359 						 * did not return -1, since we
20360 						 * may get here before linkb
20361 						 * happens.  We do, however,
20362 						 * check if we just removed the
20363 						 * only element in the list.
20364 						 */
20365 						if (err == 0)
20366 							md_mp_head = NULL;
20367 					}
20368 					/* md_hbuf gets freed automatically */
20369 					TCP_STAT(tcps, tcp_mdt_discarded);
20370 					freeb(md_mp);
20371 				} else {
20372 					/* Either allocb or mmd_alloc failed */
20373 					TCP_STAT(tcps, tcp_mdt_allocfail);
20374 					if (md_hbuf != NULL)
20375 						freeb(md_hbuf);
20376 				}
20377 
20378 				/* send down what we've got so far */
20379 				if (md_mp_head != NULL) {
20380 					tcp_multisend_data(tcp, ire, ill,
20381 					    md_mp_head, obsegs, obbytes,
20382 					    &rconfirm);
20383 				}
20384 legacy_send_no_md:
20385 				if (ire != NULL)
20386 					IRE_REFRELE(ire);
20387 				/*
20388 				 * Too bad; let the legacy path handle this.
20389 				 * We specify INT_MAX for the threshold, since
20390 				 * we gave up with the Multidata processings
20391 				 * and let the old path have it all.
20392 				 */
20393 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20394 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20395 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20396 				    snxt, tail_unsent, xmit_tail, local_time,
20397 				    INT_MAX));
20398 			}
20399 
20400 			/* link to any existing ones, if applicable */
20401 			TCP_STAT(tcps, tcp_mdt_allocd);
20402 			if (md_mp_head == NULL) {
20403 				md_mp_head = md_mp;
20404 			} else if (tcp_mdt_chain) {
20405 				TCP_STAT(tcps, tcp_mdt_linked);
20406 				linkb(md_mp_head, md_mp);
20407 			}
20408 		}
20409 
20410 		ASSERT(md_mp_head != NULL);
20411 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20412 		ASSERT(md_mp != NULL && mmd != NULL);
20413 		ASSERT(md_hbuf != NULL);
20414 
20415 		/*
20416 		 * Packetize the transmittable portion of the data block;
20417 		 * each data block is essentially added to the Multidata
20418 		 * as a payload buffer.  We also deal with adding more
20419 		 * than one payload buffers, which happens when the remaining
20420 		 * packetized portion of the current payload buffer is less
20421 		 * than MSS, while the next data block in transmit queue
20422 		 * has enough data to make up for one.  This "spillover"
20423 		 * case essentially creates a split-packet, where portions
20424 		 * of the packet's payload fragments may span across two
20425 		 * virtually discontiguous address blocks.
20426 		 */
20427 		seg_len = mss;
20428 		do {
20429 			len = seg_len;
20430 
20431 			/* one must remain NULL for DTRACE_IP_FASTPATH */
20432 			ipha = NULL;
20433 			ip6h = NULL;
20434 
20435 			ASSERT(len > 0);
20436 			ASSERT(max_pld >= 0);
20437 			ASSERT(!add_buffer || cur_pld_off == 0);
20438 
20439 			/*
20440 			 * First time around for this payload buffer; note
20441 			 * in the case of a spillover, the following has
20442 			 * been done prior to adding the split-packet
20443 			 * descriptor to Multidata, and we don't want to
20444 			 * repeat the process.
20445 			 */
20446 			if (add_buffer) {
20447 				ASSERT(mmd != NULL);
20448 				ASSERT(md_pbuf == NULL);
20449 				ASSERT(md_pbuf_nxt == NULL);
20450 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20451 
20452 				/*
20453 				 * Have we reached the limit?  We'd get to
20454 				 * this case when we're not chaining the
20455 				 * Multidata messages together, and since
20456 				 * we're done, terminate this loop.
20457 				 */
20458 				if (max_pld == 0)
20459 					break; /* done */
20460 
20461 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20462 					TCP_STAT(tcps, tcp_mdt_allocfail);
20463 					goto legacy_send; /* out_of_mem */
20464 				}
20465 
20466 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20467 				    zc_cap != NULL) {
20468 					if (!ip_md_zcopy_attr(mmd, NULL,
20469 					    zc_cap->ill_zerocopy_flags)) {
20470 						freeb(md_pbuf);
20471 						TCP_STAT(tcps,
20472 						    tcp_mdt_allocfail);
20473 						/* out_of_mem */
20474 						goto legacy_send;
20475 					}
20476 					zcopy = B_TRUE;
20477 				}
20478 
20479 				md_pbuf->b_rptr += base_pld_off;
20480 
20481 				/*
20482 				 * Add a payload buffer to the Multidata; this
20483 				 * operation must not fail, or otherwise our
20484 				 * logic in this routine is broken.  There
20485 				 * is no memory allocation done by the
20486 				 * routine, so any returned failure simply
20487 				 * tells us that we've done something wrong.
20488 				 *
20489 				 * A failure tells us that either we're adding
20490 				 * the same payload buffer more than once, or
20491 				 * we're trying to add more buffers than
20492 				 * allowed (max_pld calculation is wrong).
20493 				 * None of the above cases should happen, and
20494 				 * we panic because either there's horrible
20495 				 * heap corruption, and/or programming mistake.
20496 				 */
20497 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20498 				if (pbuf_idx < 0) {
20499 					cmn_err(CE_PANIC, "tcp_multisend: "
20500 					    "payload buffer logic error "
20501 					    "detected for tcp %p mmd %p "
20502 					    "pbuf %p (%d)\n",
20503 					    (void *)tcp, (void *)mmd,
20504 					    (void *)md_pbuf, pbuf_idx);
20505 				}
20506 
20507 				ASSERT(max_pld > 0);
20508 				--max_pld;
20509 				add_buffer = B_FALSE;
20510 			}
20511 
20512 			ASSERT(md_mp_head != NULL);
20513 			ASSERT(md_pbuf != NULL);
20514 			ASSERT(md_pbuf_nxt == NULL);
20515 			ASSERT(pbuf_idx != -1);
20516 			ASSERT(pbuf_idx_nxt == -1);
20517 			ASSERT(*usable > 0);
20518 
20519 			/*
20520 			 * We spillover to the next payload buffer only
20521 			 * if all of the following is true:
20522 			 *
20523 			 *   1. There is not enough data on the current
20524 			 *	payload buffer to make up `len',
20525 			 *   2. We are allowed to send `len',
20526 			 *   3. The next payload buffer length is large
20527 			 *	enough to accomodate `spill'.
20528 			 */
20529 			if ((spill = len - *tail_unsent) > 0 &&
20530 			    *usable >= len &&
20531 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20532 			    max_pld > 0) {
20533 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20534 				if (md_pbuf_nxt == NULL) {
20535 					TCP_STAT(tcps, tcp_mdt_allocfail);
20536 					goto legacy_send; /* out_of_mem */
20537 				}
20538 
20539 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20540 				    zc_cap != NULL) {
20541 					if (!ip_md_zcopy_attr(mmd, NULL,
20542 					    zc_cap->ill_zerocopy_flags)) {
20543 						freeb(md_pbuf_nxt);
20544 						TCP_STAT(tcps,
20545 						    tcp_mdt_allocfail);
20546 						/* out_of_mem */
20547 						goto legacy_send;
20548 					}
20549 					zcopy = B_TRUE;
20550 				}
20551 
20552 				/*
20553 				 * See comments above on the first call to
20554 				 * mmd_addpldbuf for explanation on the panic.
20555 				 */
20556 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20557 				if (pbuf_idx_nxt < 0) {
20558 					panic("tcp_multisend: "
20559 					    "next payload buffer logic error "
20560 					    "detected for tcp %p mmd %p "
20561 					    "pbuf %p (%d)\n",
20562 					    (void *)tcp, (void *)mmd,
20563 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20564 				}
20565 
20566 				ASSERT(max_pld > 0);
20567 				--max_pld;
20568 			} else if (spill > 0) {
20569 				/*
20570 				 * If there's a spillover, but the following
20571 				 * xmit_tail couldn't give us enough octets
20572 				 * to reach "len", then stop the current
20573 				 * Multidata creation and let the legacy
20574 				 * tcp_send() path take over.  We don't want
20575 				 * to send the tiny segment as part of this
20576 				 * Multidata for performance reasons; instead,
20577 				 * we let the legacy path deal with grouping
20578 				 * it with the subsequent small mblks.
20579 				 */
20580 				if (*usable >= len &&
20581 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20582 					max_pld = 0;
20583 					break;	/* done */
20584 				}
20585 
20586 				/*
20587 				 * We can't spillover, and we are near
20588 				 * the end of the current payload buffer,
20589 				 * so send what's left.
20590 				 */
20591 				ASSERT(*tail_unsent > 0);
20592 				len = *tail_unsent;
20593 			}
20594 
20595 			/* tail_unsent is negated if there is a spillover */
20596 			*tail_unsent -= len;
20597 			*usable -= len;
20598 			ASSERT(*usable >= 0);
20599 
20600 			if (*usable < mss)
20601 				seg_len = *usable;
20602 			/*
20603 			 * Sender SWS avoidance; see comments in tcp_send();
20604 			 * everything else is the same, except that we only
20605 			 * do this here if there is no more data to be sent
20606 			 * following the current xmit_tail.  We don't check
20607 			 * for 1-byte urgent data because we shouldn't get
20608 			 * here if TCP_URG_VALID is set.
20609 			 */
20610 			if (*usable > 0 && *usable < mss &&
20611 			    ((md_pbuf_nxt == NULL &&
20612 			    (*xmit_tail)->b_cont == NULL) ||
20613 			    (md_pbuf_nxt != NULL &&
20614 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20615 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20616 			    (tcp->tcp_unsent -
20617 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20618 			    !tcp->tcp_zero_win_probe) {
20619 				if ((*snxt + len) == tcp->tcp_snxt &&
20620 				    (*snxt + len) == tcp->tcp_suna) {
20621 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20622 				}
20623 				done = B_TRUE;
20624 			}
20625 
20626 			/*
20627 			 * Prime pump for IP's checksumming on our behalf;
20628 			 * include the adjustment for a source route if any.
20629 			 * Do this only for software/partial hardware checksum
20630 			 * offload, as this field gets zeroed out later for
20631 			 * the full hardware checksum offload case.
20632 			 */
20633 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20634 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20635 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20636 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20637 			}
20638 
20639 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20640 			*snxt += len;
20641 
20642 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20643 			/*
20644 			 * We set the PUSH bit only if TCP has no more buffered
20645 			 * data to be transmitted (or if sender SWS avoidance
20646 			 * takes place), as opposed to setting it for every
20647 			 * last packet in the burst.
20648 			 */
20649 			if (done ||
20650 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20651 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20652 
20653 			/*
20654 			 * Set FIN bit if this is our last segment; snxt
20655 			 * already includes its length, and it will not
20656 			 * be adjusted after this point.
20657 			 */
20658 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20659 			    *snxt == tcp->tcp_fss) {
20660 				if (!tcp->tcp_fin_acked) {
20661 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20662 					BUMP_MIB(&tcps->tcps_mib,
20663 					    tcpOutControl);
20664 				}
20665 				if (!tcp->tcp_fin_sent) {
20666 					tcp->tcp_fin_sent = B_TRUE;
20667 					/*
20668 					 * tcp state must be ESTABLISHED
20669 					 * in order for us to get here in
20670 					 * the first place.
20671 					 */
20672 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20673 
20674 					/*
20675 					 * Upon returning from this routine,
20676 					 * tcp_wput_data() will set tcp_snxt
20677 					 * to be equal to snxt + tcp_fin_sent.
20678 					 * This is essentially the same as
20679 					 * setting it to tcp_fss + 1.
20680 					 */
20681 				}
20682 			}
20683 
20684 			tcp->tcp_last_sent_len = (ushort_t)len;
20685 
20686 			len += tcp_hdr_len;
20687 			if (tcp->tcp_ipversion == IPV4_VERSION)
20688 				tcp->tcp_ipha->ipha_length = htons(len);
20689 			else
20690 				tcp->tcp_ip6h->ip6_plen = htons(len -
20691 				    ((char *)&tcp->tcp_ip6h[1] -
20692 				    tcp->tcp_iphc));
20693 
20694 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20695 
20696 			/* setup header fragment */
20697 			PDESC_HDR_ADD(pkt_info,
20698 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20699 			    tcp->tcp_mdt_hdr_head,		/* head room */
20700 			    tcp_hdr_len,			/* len */
20701 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20702 
20703 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20704 			    hdr_frag_sz);
20705 			ASSERT(MBLKIN(md_hbuf,
20706 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20707 			    PDESC_HDRSIZE(pkt_info)));
20708 
20709 			/* setup first payload fragment */
20710 			PDESC_PLD_INIT(pkt_info);
20711 			PDESC_PLD_SPAN_ADD(pkt_info,
20712 			    pbuf_idx,				/* index */
20713 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20714 			    tcp->tcp_last_sent_len);		/* len */
20715 
20716 			/* create a split-packet in case of a spillover */
20717 			if (md_pbuf_nxt != NULL) {
20718 				ASSERT(spill > 0);
20719 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20720 				ASSERT(!add_buffer);
20721 
20722 				md_pbuf = md_pbuf_nxt;
20723 				md_pbuf_nxt = NULL;
20724 				pbuf_idx = pbuf_idx_nxt;
20725 				pbuf_idx_nxt = -1;
20726 				cur_pld_off = spill;
20727 
20728 				/* trim out first payload fragment */
20729 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20730 
20731 				/* setup second payload fragment */
20732 				PDESC_PLD_SPAN_ADD(pkt_info,
20733 				    pbuf_idx,			/* index */
20734 				    md_pbuf->b_rptr,		/* start */
20735 				    spill);			/* len */
20736 
20737 				if ((*xmit_tail)->b_next == NULL) {
20738 					/*
20739 					 * Store the lbolt used for RTT
20740 					 * estimation. We can only record one
20741 					 * timestamp per mblk so we do it when
20742 					 * we reach the end of the payload
20743 					 * buffer.  Also we only take a new
20744 					 * timestamp sample when the previous
20745 					 * timed data from the same mblk has
20746 					 * been ack'ed.
20747 					 */
20748 					(*xmit_tail)->b_prev = local_time;
20749 					(*xmit_tail)->b_next =
20750 					    (mblk_t *)(uintptr_t)first_snxt;
20751 				}
20752 
20753 				first_snxt = *snxt - spill;
20754 
20755 				/*
20756 				 * Advance xmit_tail; usable could be 0 by
20757 				 * the time we got here, but we made sure
20758 				 * above that we would only spillover to
20759 				 * the next data block if usable includes
20760 				 * the spilled-over amount prior to the
20761 				 * subtraction.  Therefore, we are sure
20762 				 * that xmit_tail->b_cont can't be NULL.
20763 				 */
20764 				ASSERT((*xmit_tail)->b_cont != NULL);
20765 				*xmit_tail = (*xmit_tail)->b_cont;
20766 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20767 				    (uintptr_t)INT_MAX);
20768 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20769 			} else {
20770 				cur_pld_off += tcp->tcp_last_sent_len;
20771 			}
20772 
20773 			/*
20774 			 * Fill in the header using the template header, and
20775 			 * add options such as time-stamp, ECN and/or SACK,
20776 			 * as needed.
20777 			 */
20778 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20779 			    (clock_t)local_time, num_sack_blk);
20780 
20781 			/* take care of some IP header businesses */
20782 			if (af == AF_INET) {
20783 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20784 
20785 				ASSERT(OK_32PTR((uchar_t *)ipha));
20786 				ASSERT(PDESC_HDRL(pkt_info) >=
20787 				    IP_SIMPLE_HDR_LENGTH);
20788 				ASSERT(ipha->ipha_version_and_hdr_length ==
20789 				    IP_SIMPLE_HDR_VERSION);
20790 
20791 				/*
20792 				 * Assign ident value for current packet; see
20793 				 * related comments in ip_wput_ire() about the
20794 				 * contract private interface with clustering
20795 				 * group.
20796 				 */
20797 				clusterwide = B_FALSE;
20798 				if (cl_inet_ipident != NULL) {
20799 					ASSERT(cl_inet_isclusterwide != NULL);
20800 					if ((*cl_inet_isclusterwide)(stack_id,
20801 					    IPPROTO_IP, AF_INET,
20802 					    (uint8_t *)(uintptr_t)src, NULL)) {
20803 						ipha->ipha_ident =
20804 						    (*cl_inet_ipident)(stack_id,
20805 						    IPPROTO_IP, AF_INET,
20806 						    (uint8_t *)(uintptr_t)src,
20807 						    (uint8_t *)(uintptr_t)dst,
20808 						    NULL);
20809 						clusterwide = B_TRUE;
20810 					}
20811 				}
20812 
20813 				if (!clusterwide) {
20814 					ipha->ipha_ident = (uint16_t)
20815 					    atomic_add_32_nv(
20816 						&ire->ire_ident, 1);
20817 				}
20818 #ifndef _BIG_ENDIAN
20819 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20820 				    (ipha->ipha_ident >> 8);
20821 #endif
20822 			} else {
20823 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20824 
20825 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20826 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20827 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20828 				ASSERT(PDESC_HDRL(pkt_info) >=
20829 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20830 				    TCP_CHECKSUM_SIZE));
20831 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20832 
20833 				if (tcp->tcp_ip_forward_progress) {
20834 					rconfirm = B_TRUE;
20835 					tcp->tcp_ip_forward_progress = B_FALSE;
20836 				}
20837 			}
20838 
20839 			/* at least one payload span, and at most two */
20840 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20841 
20842 			/* add the packet descriptor to Multidata */
20843 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20844 			    KM_NOSLEEP)) == NULL) {
20845 				/*
20846 				 * Any failure other than ENOMEM indicates
20847 				 * that we have passed in invalid pkt_info
20848 				 * or parameters to mmd_addpdesc, which must
20849 				 * not happen.
20850 				 *
20851 				 * EINVAL is a result of failure on boundary
20852 				 * checks against the pkt_info contents.  It
20853 				 * should not happen, and we panic because
20854 				 * either there's horrible heap corruption,
20855 				 * and/or programming mistake.
20856 				 */
20857 				if (err != ENOMEM) {
20858 					cmn_err(CE_PANIC, "tcp_multisend: "
20859 					    "pdesc logic error detected for "
20860 					    "tcp %p mmd %p pinfo %p (%d)\n",
20861 					    (void *)tcp, (void *)mmd,
20862 					    (void *)pkt_info, err);
20863 				}
20864 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20865 				goto legacy_send; /* out_of_mem */
20866 			}
20867 			ASSERT(pkt != NULL);
20868 
20869 			/* calculate IP header and TCP checksums */
20870 			if (af == AF_INET) {
20871 				/* calculate pseudo-header checksum */
20872 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20873 				    (src >> 16) + (src & 0xFFFF);
20874 
20875 				/* offset for TCP header checksum */
20876 				up = IPH_TCPH_CHECKSUMP(ipha,
20877 				    IP_SIMPLE_HDR_LENGTH);
20878 			} else {
20879 				up = (uint16_t *)&ip6h->ip6_src;
20880 
20881 				/* calculate pseudo-header checksum */
20882 				cksum = up[0] + up[1] + up[2] + up[3] +
20883 				    up[4] + up[5] + up[6] + up[7] +
20884 				    up[8] + up[9] + up[10] + up[11] +
20885 				    up[12] + up[13] + up[14] + up[15];
20886 
20887 				/* Fold the initial sum */
20888 				cksum = (cksum & 0xffff) + (cksum >> 16);
20889 
20890 				up = (uint16_t *)(((uchar_t *)ip6h) +
20891 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20892 			}
20893 
20894 			if (hwcksum_flags & HCK_FULLCKSUM) {
20895 				/* clear checksum field for hardware */
20896 				*up = 0;
20897 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20898 				uint32_t sum;
20899 
20900 				/* pseudo-header checksumming */
20901 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20902 				sum = (sum & 0xFFFF) + (sum >> 16);
20903 				*up = (sum & 0xFFFF) + (sum >> 16);
20904 			} else {
20905 				/* software checksumming */
20906 				TCP_STAT(tcps, tcp_out_sw_cksum);
20907 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20908 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20909 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20910 				    cksum + IP_TCP_CSUM_COMP);
20911 				if (*up == 0)
20912 					*up = 0xFFFF;
20913 			}
20914 
20915 			/* IPv4 header checksum */
20916 			if (af == AF_INET) {
20917 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20918 					ipha->ipha_hdr_checksum = 0;
20919 				} else {
20920 					IP_HDR_CKSUM(ipha, cksum,
20921 					    ((uint32_t *)ipha)[0],
20922 					    ((uint16_t *)ipha)[4]);
20923 				}
20924 			}
20925 
20926 			if (af == AF_INET &&
20927 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20928 			    af == AF_INET6 &&
20929 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20930 				mblk_t	*mp, *mp1;
20931 				uchar_t	*hdr_rptr, *hdr_wptr;
20932 				uchar_t	*pld_rptr, *pld_wptr;
20933 
20934 				/*
20935 				 * We reconstruct a pseudo packet for the hooks
20936 				 * framework using mmd_transform_link().
20937 				 * If it is a split packet we pullup the
20938 				 * payload. FW_HOOKS expects a pkt comprising
20939 				 * of two mblks: a header and the payload.
20940 				 */
20941 				if ((mp = mmd_transform_link(pkt)) == NULL) {
20942 					TCP_STAT(tcps, tcp_mdt_allocfail);
20943 					goto legacy_send;
20944 				}
20945 
20946 				if (pkt_info->pld_cnt > 1) {
20947 					/* split payload, more than one pld */
20948 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
20949 					    NULL) {
20950 						freemsg(mp);
20951 						TCP_STAT(tcps,
20952 						    tcp_mdt_allocfail);
20953 						goto legacy_send;
20954 					}
20955 					freemsg(mp->b_cont);
20956 					mp->b_cont = mp1;
20957 				} else {
20958 					mp1 = mp->b_cont;
20959 				}
20960 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
20961 
20962 				/*
20963 				 * Remember the message offsets. This is so we
20964 				 * can detect changes when we return from the
20965 				 * FW_HOOKS callbacks.
20966 				 */
20967 				hdr_rptr = mp->b_rptr;
20968 				hdr_wptr = mp->b_wptr;
20969 				pld_rptr = mp->b_cont->b_rptr;
20970 				pld_wptr = mp->b_cont->b_wptr;
20971 
20972 				if (af == AF_INET) {
20973 					DTRACE_PROBE4(
20974 					    ip4__physical__out__start,
20975 					    ill_t *, NULL,
20976 					    ill_t *, ill,
20977 					    ipha_t *, ipha,
20978 					    mblk_t *, mp);
20979 					FW_HOOKS(
20980 					    ipst->ips_ip4_physical_out_event,
20981 					    ipst->ips_ipv4firewall_physical_out,
20982 					    NULL, ill, ipha, mp, mp, 0, ipst);
20983 					DTRACE_PROBE1(
20984 					    ip4__physical__out__end,
20985 					    mblk_t *, mp);
20986 				} else {
20987 					DTRACE_PROBE4(
20988 					    ip6__physical__out_start,
20989 					    ill_t *, NULL,
20990 					    ill_t *, ill,
20991 					    ip6_t *, ip6h,
20992 					    mblk_t *, mp);
20993 					FW_HOOKS6(
20994 					    ipst->ips_ip6_physical_out_event,
20995 					    ipst->ips_ipv6firewall_physical_out,
20996 					    NULL, ill, ip6h, mp, mp, 0, ipst);
20997 					DTRACE_PROBE1(
20998 					    ip6__physical__out__end,
20999 					    mblk_t *, mp);
21000 				}
21001 
21002 				if (mp == NULL ||
21003 				    (mp1 = mp->b_cont) == NULL ||
21004 				    mp->b_rptr != hdr_rptr ||
21005 				    mp->b_wptr != hdr_wptr ||
21006 				    mp1->b_rptr != pld_rptr ||
21007 				    mp1->b_wptr != pld_wptr ||
21008 				    mp1->b_cont != NULL) {
21009 					/*
21010 					 * We abandon multidata processing and
21011 					 * return to the normal path, either
21012 					 * when a packet is blocked, or when
21013 					 * the boundaries of header buffer or
21014 					 * payload buffer have been changed by
21015 					 * FW_HOOKS[6].
21016 					 */
21017 					if (mp != NULL)
21018 						freemsg(mp);
21019 					goto legacy_send;
21020 				}
21021 				/* Finished with the pseudo packet */
21022 				freemsg(mp);
21023 			}
21024 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
21025 			    ill, ipha, ip6h);
21026 			/* advance header offset */
21027 			cur_hdr_off += hdr_frag_sz;
21028 
21029 			obbytes += tcp->tcp_last_sent_len;
21030 			++obsegs;
21031 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
21032 		    *tail_unsent > 0);
21033 
21034 		if ((*xmit_tail)->b_next == NULL) {
21035 			/*
21036 			 * Store the lbolt used for RTT estimation. We can only
21037 			 * record one timestamp per mblk so we do it when we
21038 			 * reach the end of the payload buffer. Also we only
21039 			 * take a new timestamp sample when the previous timed
21040 			 * data from the same mblk has been ack'ed.
21041 			 */
21042 			(*xmit_tail)->b_prev = local_time;
21043 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
21044 		}
21045 
21046 		ASSERT(*tail_unsent >= 0);
21047 		if (*tail_unsent > 0) {
21048 			/*
21049 			 * We got here because we broke out of the above
21050 			 * loop due to of one of the following cases:
21051 			 *
21052 			 *   1. len < adjusted MSS (i.e. small),
21053 			 *   2. Sender SWS avoidance,
21054 			 *   3. max_pld is zero.
21055 			 *
21056 			 * We are done for this Multidata, so trim our
21057 			 * last payload buffer (if any) accordingly.
21058 			 */
21059 			if (md_pbuf != NULL)
21060 				md_pbuf->b_wptr -= *tail_unsent;
21061 		} else if (*usable > 0) {
21062 			*xmit_tail = (*xmit_tail)->b_cont;
21063 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
21064 			    (uintptr_t)INT_MAX);
21065 			*tail_unsent = (int)MBLKL(*xmit_tail);
21066 			add_buffer = B_TRUE;
21067 		}
21068 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
21069 	    (tcp_mdt_chain || max_pld > 0));
21070 
21071 	if (md_mp_head != NULL) {
21072 		/* send everything down */
21073 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
21074 		    &rconfirm);
21075 	}
21076 
21077 #undef PREP_NEW_MULTIDATA
21078 #undef PREP_NEW_PBUF
21079 #undef IPVER
21080 
21081 	IRE_REFRELE(ire);
21082 	return (0);
21083 }
21084 
21085 /*
21086  * A wrapper function for sending one or more Multidata messages down to
21087  * the module below ip; this routine does not release the reference of the
21088  * IRE (caller does that).  This routine is analogous to tcp_send_data().
21089  */
21090 static void
21091 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
21092     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
21093 {
21094 	uint64_t delta;
21095 	nce_t *nce;
21096 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21097 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21098 
21099 	ASSERT(ire != NULL && ill != NULL);
21100 	ASSERT(ire->ire_stq != NULL);
21101 	ASSERT(md_mp_head != NULL);
21102 	ASSERT(rconfirm != NULL);
21103 
21104 	/* adjust MIBs and IRE timestamp */
21105 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
21106 	tcp->tcp_obsegs += obsegs;
21107 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
21108 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
21109 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
21110 
21111 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21112 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
21113 	} else {
21114 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
21115 	}
21116 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
21117 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
21118 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
21119 
21120 	ire->ire_ob_pkt_count += obsegs;
21121 	if (ire->ire_ipif != NULL)
21122 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
21123 	ire->ire_last_used_time = lbolt;
21124 
21125 	if (ipst->ips_ipobs_enabled) {
21126 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
21127 		pdesc_t *dl_pkt;
21128 		pdescinfo_t pinfo;
21129 		mblk_t *nmp;
21130 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
21131 
21132 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
21133 		    (dl_pkt != NULL);
21134 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
21135 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
21136 				continue;
21137 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
21138 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
21139 			freemsg(nmp);
21140 		}
21141 	}
21142 
21143 	/* send it down */
21144 	putnext(ire->ire_stq, md_mp_head);
21145 
21146 	/* we're done for TCP/IPv4 */
21147 	if (tcp->tcp_ipversion == IPV4_VERSION)
21148 		return;
21149 
21150 	nce = ire->ire_nce;
21151 
21152 	ASSERT(nce != NULL);
21153 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
21154 	ASSERT(nce->nce_state != ND_INCOMPLETE);
21155 
21156 	/* reachability confirmation? */
21157 	if (*rconfirm) {
21158 		nce->nce_last = TICK_TO_MSEC(lbolt64);
21159 		if (nce->nce_state != ND_REACHABLE) {
21160 			mutex_enter(&nce->nce_lock);
21161 			nce->nce_state = ND_REACHABLE;
21162 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
21163 			mutex_exit(&nce->nce_lock);
21164 			(void) untimeout(nce->nce_timeout_id);
21165 			if (ip_debug > 2) {
21166 				/* ip1dbg */
21167 				pr_addr_dbg("tcp_multisend_data: state "
21168 				    "for %s changed to REACHABLE\n",
21169 				    AF_INET6, &ire->ire_addr_v6);
21170 			}
21171 		}
21172 		/* reset transport reachability confirmation */
21173 		*rconfirm = B_FALSE;
21174 	}
21175 
21176 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
21177 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
21178 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
21179 
21180 	if (delta > (uint64_t)ill->ill_reachable_time) {
21181 		mutex_enter(&nce->nce_lock);
21182 		switch (nce->nce_state) {
21183 		case ND_REACHABLE:
21184 		case ND_STALE:
21185 			/*
21186 			 * ND_REACHABLE is identical to ND_STALE in this
21187 			 * specific case. If reachable time has expired for
21188 			 * this neighbor (delta is greater than reachable
21189 			 * time), conceptually, the neighbor cache is no
21190 			 * longer in REACHABLE state, but already in STALE
21191 			 * state.  So the correct transition here is to
21192 			 * ND_DELAY.
21193 			 */
21194 			nce->nce_state = ND_DELAY;
21195 			mutex_exit(&nce->nce_lock);
21196 			NDP_RESTART_TIMER(nce,
21197 			    ipst->ips_delay_first_probe_time);
21198 			if (ip_debug > 3) {
21199 				/* ip2dbg */
21200 				pr_addr_dbg("tcp_multisend_data: state "
21201 				    "for %s changed to DELAY\n",
21202 				    AF_INET6, &ire->ire_addr_v6);
21203 			}
21204 			break;
21205 		case ND_DELAY:
21206 		case ND_PROBE:
21207 			mutex_exit(&nce->nce_lock);
21208 			/* Timers have already started */
21209 			break;
21210 		case ND_UNREACHABLE:
21211 			/*
21212 			 * ndp timer has detected that this nce is
21213 			 * unreachable and initiated deleting this nce
21214 			 * and all its associated IREs. This is a race
21215 			 * where we found the ire before it was deleted
21216 			 * and have just sent out a packet using this
21217 			 * unreachable nce.
21218 			 */
21219 			mutex_exit(&nce->nce_lock);
21220 			break;
21221 		default:
21222 			ASSERT(0);
21223 		}
21224 	}
21225 }
21226 
21227 /*
21228  * Derived from tcp_send_data().
21229  */
21230 static void
21231 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
21232     int num_lso_seg)
21233 {
21234 	ipha_t		*ipha;
21235 	mblk_t		*ire_fp_mp;
21236 	uint_t		ire_fp_mp_len;
21237 	uint32_t	hcksum_txflags = 0;
21238 	ipaddr_t	src;
21239 	ipaddr_t	dst;
21240 	uint32_t	cksum;
21241 	uint16_t	*up;
21242 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21243 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21244 
21245 	ASSERT(DB_TYPE(mp) == M_DATA);
21246 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
21247 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
21248 	ASSERT(tcp->tcp_connp != NULL);
21249 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
21250 
21251 	ipha = (ipha_t *)mp->b_rptr;
21252 	src = ipha->ipha_src;
21253 	dst = ipha->ipha_dst;
21254 
21255 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
21256 
21257 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21258 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
21259 	    num_lso_seg);
21260 #ifndef _BIG_ENDIAN
21261 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21262 #endif
21263 	if (tcp->tcp_snd_zcopy_aware) {
21264 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
21265 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
21266 			mp = tcp_zcopy_disable(tcp, mp);
21267 	}
21268 
21269 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
21270 		ASSERT(ill->ill_hcksum_capab != NULL);
21271 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
21272 	}
21273 
21274 	/*
21275 	 * Since the TCP checksum should be recalculated by h/w, we can just
21276 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
21277 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
21278 	 * The partial pseudo-header excludes TCP length, that was calculated
21279 	 * in tcp_send(), so to zero *up before further processing.
21280 	 */
21281 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21282 
21283 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
21284 	*up = 0;
21285 
21286 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
21287 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
21288 
21289 	/*
21290 	 * Append LSO flags and mss to the mp.
21291 	 */
21292 	lso_info_set(mp, mss, HW_LSO);
21293 
21294 	ipha->ipha_fragment_offset_and_flags |=
21295 	    (uint32_t)htons(ire->ire_frag_flag);
21296 
21297 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
21298 	ire_fp_mp_len = MBLKL(ire_fp_mp);
21299 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
21300 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
21301 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
21302 
21303 	UPDATE_OB_PKT_COUNT(ire);
21304 	ire->ire_last_used_time = lbolt;
21305 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
21306 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
21307 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
21308 	    ntohs(ipha->ipha_length));
21309 
21310 	DTRACE_PROBE4(ip4__physical__out__start,
21311 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
21312 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
21313 	    ipst->ips_ipv4firewall_physical_out, NULL,
21314 	    ill, ipha, mp, mp, 0, ipst);
21315 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21316 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
21317 
21318 	if (mp != NULL) {
21319 		if (ipst->ips_ipobs_enabled) {
21320 			zoneid_t szone;
21321 
21322 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
21323 			    ipst, ALL_ZONES);
21324 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
21325 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
21326 		}
21327 
21328 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0);
21329 	}
21330 }
21331 
21332 /*
21333  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
21334  * scheme, and returns one of the following:
21335  *
21336  * -1 = failed allocation.
21337  *  0 = success; burst count reached, or usable send window is too small,
21338  *      and that we'd rather wait until later before sending again.
21339  *  1 = success; we are called from tcp_multisend(), and both usable send
21340  *      window and tail_unsent are greater than the MDT threshold, and thus
21341  *      Multidata Transmit should be used instead.
21342  */
21343 static int
21344 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
21345     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
21346     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
21347     const int mdt_thres)
21348 {
21349 	int num_burst_seg = tcp->tcp_snd_burst;
21350 	ire_t		*ire = NULL;
21351 	ill_t		*ill = NULL;
21352 	mblk_t		*ire_fp_mp = NULL;
21353 	uint_t		ire_fp_mp_len = 0;
21354 	int		num_lso_seg = 1;
21355 	uint_t		lso_usable;
21356 	boolean_t	do_lso_send = B_FALSE;
21357 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21358 
21359 	/*
21360 	 * Check LSO capability before any further work. And the similar check
21361 	 * need to be done in for(;;) loop.
21362 	 * LSO will be deployed when therer is more than one mss of available
21363 	 * data and a burst transmission is allowed.
21364 	 */
21365 	if (tcp->tcp_lso &&
21366 	    (tcp->tcp_valid_bits == 0 ||
21367 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21368 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21369 		/*
21370 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21371 		 */
21372 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
21373 			/*
21374 			 * Enable LSO with this transmission.
21375 			 * Since IRE has been hold in
21376 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
21377 			 * should be called before return.
21378 			 */
21379 			do_lso_send = B_TRUE;
21380 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21381 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21382 			/* Round up to multiple of 4 */
21383 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21384 		} else {
21385 			do_lso_send = B_FALSE;
21386 			ill = NULL;
21387 		}
21388 	}
21389 
21390 	for (;;) {
21391 		struct datab	*db;
21392 		tcph_t		*tcph;
21393 		uint32_t	sum;
21394 		mblk_t		*mp, *mp1;
21395 		uchar_t		*rptr;
21396 		int		len;
21397 
21398 		/*
21399 		 * If we're called by tcp_multisend(), and the amount of
21400 		 * sendable data as well as the size of current xmit_tail
21401 		 * is beyond the MDT threshold, return to the caller and
21402 		 * let the large data transmit be done using MDT.
21403 		 */
21404 		if (*usable > 0 && *usable > mdt_thres &&
21405 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21406 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21407 			ASSERT(tcp->tcp_mdt);
21408 			return (1);	/* success; do large send */
21409 		}
21410 
21411 		if (num_burst_seg == 0)
21412 			break;		/* success; burst count reached */
21413 
21414 		/*
21415 		 * Calculate the maximum payload length we can send in *one*
21416 		 * time.
21417 		 */
21418 		if (do_lso_send) {
21419 			/*
21420 			 * Check whether need to do LSO any more.
21421 			 */
21422 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21423 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21424 				lso_usable = MIN(lso_usable,
21425 				    num_burst_seg * mss);
21426 
21427 				num_lso_seg = lso_usable / mss;
21428 				if (lso_usable % mss) {
21429 					num_lso_seg++;
21430 					tcp->tcp_last_sent_len = (ushort_t)
21431 					    (lso_usable % mss);
21432 				} else {
21433 					tcp->tcp_last_sent_len = (ushort_t)mss;
21434 				}
21435 			} else {
21436 				do_lso_send = B_FALSE;
21437 				num_lso_seg = 1;
21438 				lso_usable = mss;
21439 			}
21440 		}
21441 
21442 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21443 
21444 		/*
21445 		 * Adjust num_burst_seg here.
21446 		 */
21447 		num_burst_seg -= num_lso_seg;
21448 
21449 		len = mss;
21450 		if (len > *usable) {
21451 			ASSERT(do_lso_send == B_FALSE);
21452 
21453 			len = *usable;
21454 			if (len <= 0) {
21455 				/* Terminate the loop */
21456 				break;	/* success; too small */
21457 			}
21458 			/*
21459 			 * Sender silly-window avoidance.
21460 			 * Ignore this if we are going to send a
21461 			 * zero window probe out.
21462 			 *
21463 			 * TODO: force data into microscopic window?
21464 			 *	==> (!pushed || (unsent > usable))
21465 			 */
21466 			if (len < (tcp->tcp_max_swnd >> 1) &&
21467 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21468 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21469 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21470 				/*
21471 				 * If the retransmit timer is not running
21472 				 * we start it so that we will retransmit
21473 				 * in the case when the the receiver has
21474 				 * decremented the window.
21475 				 */
21476 				if (*snxt == tcp->tcp_snxt &&
21477 				    *snxt == tcp->tcp_suna) {
21478 					/*
21479 					 * We are not supposed to send
21480 					 * anything.  So let's wait a little
21481 					 * bit longer before breaking SWS
21482 					 * avoidance.
21483 					 *
21484 					 * What should the value be?
21485 					 * Suggestion: MAX(init rexmit time,
21486 					 * tcp->tcp_rto)
21487 					 */
21488 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21489 				}
21490 				break;	/* success; too small */
21491 			}
21492 		}
21493 
21494 		tcph = tcp->tcp_tcph;
21495 
21496 		/*
21497 		 * The reason to adjust len here is that we need to set flags
21498 		 * and calculate checksum.
21499 		 */
21500 		if (do_lso_send)
21501 			len = lso_usable;
21502 
21503 		*usable -= len; /* Approximate - can be adjusted later */
21504 		if (*usable > 0)
21505 			tcph->th_flags[0] = TH_ACK;
21506 		else
21507 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21508 
21509 		/*
21510 		 * Prime pump for IP's checksumming on our behalf
21511 		 * Include the adjustment for a source route if any.
21512 		 */
21513 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21514 		sum = (sum >> 16) + (sum & 0xFFFF);
21515 		U16_TO_ABE16(sum, tcph->th_sum);
21516 
21517 		U32_TO_ABE32(*snxt, tcph->th_seq);
21518 
21519 		/*
21520 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21521 		 * set.  For the case when TCP_FSS_VALID is the only valid
21522 		 * bit (normal active close), branch off only when we think
21523 		 * that the FIN flag needs to be set.  Note for this case,
21524 		 * that (snxt + len) may not reflect the actual seg_len,
21525 		 * as len may be further reduced in tcp_xmit_mp().  If len
21526 		 * gets modified, we will end up here again.
21527 		 */
21528 		if (tcp->tcp_valid_bits != 0 &&
21529 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21530 		    ((*snxt + len) == tcp->tcp_fss))) {
21531 			uchar_t		*prev_rptr;
21532 			uint32_t	prev_snxt = tcp->tcp_snxt;
21533 
21534 			if (*tail_unsent == 0) {
21535 				ASSERT((*xmit_tail)->b_cont != NULL);
21536 				*xmit_tail = (*xmit_tail)->b_cont;
21537 				prev_rptr = (*xmit_tail)->b_rptr;
21538 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21539 				    (*xmit_tail)->b_rptr);
21540 			} else {
21541 				prev_rptr = (*xmit_tail)->b_rptr;
21542 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21543 				    *tail_unsent;
21544 			}
21545 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21546 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21547 			/* Restore tcp_snxt so we get amount sent right. */
21548 			tcp->tcp_snxt = prev_snxt;
21549 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21550 				/*
21551 				 * If the previous timestamp is still in use,
21552 				 * don't stomp on it.
21553 				 */
21554 				if ((*xmit_tail)->b_next == NULL) {
21555 					(*xmit_tail)->b_prev = local_time;
21556 					(*xmit_tail)->b_next =
21557 					    (mblk_t *)(uintptr_t)(*snxt);
21558 				}
21559 			} else
21560 				(*xmit_tail)->b_rptr = prev_rptr;
21561 
21562 			if (mp == NULL) {
21563 				if (ire != NULL)
21564 					IRE_REFRELE(ire);
21565 				return (-1);
21566 			}
21567 			mp1 = mp->b_cont;
21568 
21569 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21570 				tcp->tcp_last_sent_len = (ushort_t)len;
21571 			while (mp1->b_cont) {
21572 				*xmit_tail = (*xmit_tail)->b_cont;
21573 				(*xmit_tail)->b_prev = local_time;
21574 				(*xmit_tail)->b_next =
21575 				    (mblk_t *)(uintptr_t)(*snxt);
21576 				mp1 = mp1->b_cont;
21577 			}
21578 			*snxt += len;
21579 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21580 			BUMP_LOCAL(tcp->tcp_obsegs);
21581 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21582 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21583 			tcp_send_data(tcp, q, mp);
21584 			continue;
21585 		}
21586 
21587 		*snxt += len;	/* Adjust later if we don't send all of len */
21588 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21589 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21590 
21591 		if (*tail_unsent) {
21592 			/* Are the bytes above us in flight? */
21593 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21594 			if (rptr != (*xmit_tail)->b_rptr) {
21595 				*tail_unsent -= len;
21596 				if (len <= mss) /* LSO is unusable */
21597 					tcp->tcp_last_sent_len = (ushort_t)len;
21598 				len += tcp_hdr_len;
21599 				if (tcp->tcp_ipversion == IPV4_VERSION)
21600 					tcp->tcp_ipha->ipha_length = htons(len);
21601 				else
21602 					tcp->tcp_ip6h->ip6_plen =
21603 					    htons(len -
21604 					    ((char *)&tcp->tcp_ip6h[1] -
21605 					    tcp->tcp_iphc));
21606 				mp = dupb(*xmit_tail);
21607 				if (mp == NULL) {
21608 					if (ire != NULL)
21609 						IRE_REFRELE(ire);
21610 					return (-1);	/* out_of_mem */
21611 				}
21612 				mp->b_rptr = rptr;
21613 				/*
21614 				 * If the old timestamp is no longer in use,
21615 				 * sample a new timestamp now.
21616 				 */
21617 				if ((*xmit_tail)->b_next == NULL) {
21618 					(*xmit_tail)->b_prev = local_time;
21619 					(*xmit_tail)->b_next =
21620 					    (mblk_t *)(uintptr_t)(*snxt-len);
21621 				}
21622 				goto must_alloc;
21623 			}
21624 		} else {
21625 			*xmit_tail = (*xmit_tail)->b_cont;
21626 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21627 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21628 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21629 			    (*xmit_tail)->b_rptr);
21630 		}
21631 
21632 		(*xmit_tail)->b_prev = local_time;
21633 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21634 
21635 		*tail_unsent -= len;
21636 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21637 			tcp->tcp_last_sent_len = (ushort_t)len;
21638 
21639 		len += tcp_hdr_len;
21640 		if (tcp->tcp_ipversion == IPV4_VERSION)
21641 			tcp->tcp_ipha->ipha_length = htons(len);
21642 		else
21643 			tcp->tcp_ip6h->ip6_plen = htons(len -
21644 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21645 
21646 		mp = dupb(*xmit_tail);
21647 		if (mp == NULL) {
21648 			if (ire != NULL)
21649 				IRE_REFRELE(ire);
21650 			return (-1);	/* out_of_mem */
21651 		}
21652 
21653 		len = tcp_hdr_len;
21654 		/*
21655 		 * There are four reasons to allocate a new hdr mblk:
21656 		 *  1) The bytes above us are in use by another packet
21657 		 *  2) We don't have good alignment
21658 		 *  3) The mblk is being shared
21659 		 *  4) We don't have enough room for a header
21660 		 */
21661 		rptr = mp->b_rptr - len;
21662 		if (!OK_32PTR(rptr) ||
21663 		    ((db = mp->b_datap), db->db_ref != 2) ||
21664 		    rptr < db->db_base + ire_fp_mp_len) {
21665 			/* NOTE: we assume allocb returns an OK_32PTR */
21666 
21667 		must_alloc:;
21668 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21669 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21670 			if (mp1 == NULL) {
21671 				freemsg(mp);
21672 				if (ire != NULL)
21673 					IRE_REFRELE(ire);
21674 				return (-1);	/* out_of_mem */
21675 			}
21676 			mp1->b_cont = mp;
21677 			mp = mp1;
21678 			/* Leave room for Link Level header */
21679 			len = tcp_hdr_len;
21680 			rptr =
21681 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21682 			mp->b_wptr = &rptr[len];
21683 		}
21684 
21685 		/*
21686 		 * Fill in the header using the template header, and add
21687 		 * options such as time-stamp, ECN and/or SACK, as needed.
21688 		 */
21689 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21690 
21691 		mp->b_rptr = rptr;
21692 
21693 		if (*tail_unsent) {
21694 			int spill = *tail_unsent;
21695 
21696 			mp1 = mp->b_cont;
21697 			if (mp1 == NULL)
21698 				mp1 = mp;
21699 
21700 			/*
21701 			 * If we're a little short, tack on more mblks until
21702 			 * there is no more spillover.
21703 			 */
21704 			while (spill < 0) {
21705 				mblk_t *nmp;
21706 				int nmpsz;
21707 
21708 				nmp = (*xmit_tail)->b_cont;
21709 				nmpsz = MBLKL(nmp);
21710 
21711 				/*
21712 				 * Excess data in mblk; can we split it?
21713 				 * If MDT is enabled for the connection,
21714 				 * keep on splitting as this is a transient
21715 				 * send path.
21716 				 */
21717 				if (!do_lso_send && !tcp->tcp_mdt &&
21718 				    (spill + nmpsz > 0)) {
21719 					/*
21720 					 * Don't split if stream head was
21721 					 * told to break up larger writes
21722 					 * into smaller ones.
21723 					 */
21724 					if (tcp->tcp_maxpsz > 0)
21725 						break;
21726 
21727 					/*
21728 					 * Next mblk is less than SMSS/2
21729 					 * rounded up to nearest 64-byte;
21730 					 * let it get sent as part of the
21731 					 * next segment.
21732 					 */
21733 					if (tcp->tcp_localnet &&
21734 					    !tcp->tcp_cork &&
21735 					    (nmpsz < roundup((mss >> 1), 64)))
21736 						break;
21737 				}
21738 
21739 				*xmit_tail = nmp;
21740 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21741 				/* Stash for rtt use later */
21742 				(*xmit_tail)->b_prev = local_time;
21743 				(*xmit_tail)->b_next =
21744 				    (mblk_t *)(uintptr_t)(*snxt - len);
21745 				mp1->b_cont = dupb(*xmit_tail);
21746 				mp1 = mp1->b_cont;
21747 
21748 				spill += nmpsz;
21749 				if (mp1 == NULL) {
21750 					*tail_unsent = spill;
21751 					freemsg(mp);
21752 					if (ire != NULL)
21753 						IRE_REFRELE(ire);
21754 					return (-1);	/* out_of_mem */
21755 				}
21756 			}
21757 
21758 			/* Trim back any surplus on the last mblk */
21759 			if (spill >= 0) {
21760 				mp1->b_wptr -= spill;
21761 				*tail_unsent = spill;
21762 			} else {
21763 				/*
21764 				 * We did not send everything we could in
21765 				 * order to remain within the b_cont limit.
21766 				 */
21767 				*usable -= spill;
21768 				*snxt += spill;
21769 				tcp->tcp_last_sent_len += spill;
21770 				UPDATE_MIB(&tcps->tcps_mib,
21771 				    tcpOutDataBytes, spill);
21772 				/*
21773 				 * Adjust the checksum
21774 				 */
21775 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21776 				sum += spill;
21777 				sum = (sum >> 16) + (sum & 0xFFFF);
21778 				U16_TO_ABE16(sum, tcph->th_sum);
21779 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21780 					sum = ntohs(
21781 					    ((ipha_t *)rptr)->ipha_length) +
21782 					    spill;
21783 					((ipha_t *)rptr)->ipha_length =
21784 					    htons(sum);
21785 				} else {
21786 					sum = ntohs(
21787 					    ((ip6_t *)rptr)->ip6_plen) +
21788 					    spill;
21789 					((ip6_t *)rptr)->ip6_plen =
21790 					    htons(sum);
21791 				}
21792 				*tail_unsent = 0;
21793 			}
21794 		}
21795 		if (tcp->tcp_ip_forward_progress) {
21796 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21797 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21798 			tcp->tcp_ip_forward_progress = B_FALSE;
21799 		}
21800 
21801 		if (do_lso_send) {
21802 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21803 			    num_lso_seg);
21804 			tcp->tcp_obsegs += num_lso_seg;
21805 
21806 			TCP_STAT(tcps, tcp_lso_times);
21807 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21808 		} else {
21809 			tcp_send_data(tcp, q, mp);
21810 			BUMP_LOCAL(tcp->tcp_obsegs);
21811 		}
21812 	}
21813 
21814 	if (ire != NULL)
21815 		IRE_REFRELE(ire);
21816 	return (0);
21817 }
21818 
21819 /* Unlink and return any mblk that looks like it contains a MDT info */
21820 static mblk_t *
21821 tcp_mdt_info_mp(mblk_t *mp)
21822 {
21823 	mblk_t	*prev_mp;
21824 
21825 	for (;;) {
21826 		prev_mp = mp;
21827 		/* no more to process? */
21828 		if ((mp = mp->b_cont) == NULL)
21829 			break;
21830 
21831 		switch (DB_TYPE(mp)) {
21832 		case M_CTL:
21833 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21834 				continue;
21835 			ASSERT(prev_mp != NULL);
21836 			prev_mp->b_cont = mp->b_cont;
21837 			mp->b_cont = NULL;
21838 			return (mp);
21839 		default:
21840 			break;
21841 		}
21842 	}
21843 	return (mp);
21844 }
21845 
21846 /* MDT info update routine, called when IP notifies us about MDT */
21847 static void
21848 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21849 {
21850 	boolean_t prev_state;
21851 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21852 
21853 	/*
21854 	 * IP is telling us to abort MDT on this connection?  We know
21855 	 * this because the capability is only turned off when IP
21856 	 * encounters some pathological cases, e.g. link-layer change
21857 	 * where the new driver doesn't support MDT, or in situation
21858 	 * where MDT usage on the link-layer has been switched off.
21859 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21860 	 * if the link-layer doesn't support MDT, and if it does, it
21861 	 * will indicate that the feature is to be turned on.
21862 	 */
21863 	prev_state = tcp->tcp_mdt;
21864 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21865 	if (!tcp->tcp_mdt && !first) {
21866 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21867 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21868 		    (void *)tcp->tcp_connp));
21869 	}
21870 
21871 	/*
21872 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21873 	 * so disable MDT otherwise.  The checks are done here
21874 	 * and in tcp_wput_data().
21875 	 */
21876 	if (tcp->tcp_mdt &&
21877 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21878 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21879 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21880 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21881 		tcp->tcp_mdt = B_FALSE;
21882 
21883 	if (tcp->tcp_mdt) {
21884 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21885 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21886 			    "version (%d), expected version is %d",
21887 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21888 			tcp->tcp_mdt = B_FALSE;
21889 			return;
21890 		}
21891 
21892 		/*
21893 		 * We need the driver to be able to handle at least three
21894 		 * spans per packet in order for tcp MDT to be utilized.
21895 		 * The first is for the header portion, while the rest are
21896 		 * needed to handle a packet that straddles across two
21897 		 * virtually non-contiguous buffers; a typical tcp packet
21898 		 * therefore consists of only two spans.  Note that we take
21899 		 * a zero as "don't care".
21900 		 */
21901 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21902 		    mdt_capab->ill_mdt_span_limit < 3) {
21903 			tcp->tcp_mdt = B_FALSE;
21904 			return;
21905 		}
21906 
21907 		/* a zero means driver wants default value */
21908 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21909 		    tcps->tcps_mdt_max_pbufs);
21910 		if (tcp->tcp_mdt_max_pld == 0)
21911 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21912 
21913 		/* ensure 32-bit alignment */
21914 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21915 		    mdt_capab->ill_mdt_hdr_head), 4);
21916 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21917 		    mdt_capab->ill_mdt_hdr_tail), 4);
21918 
21919 		if (!first && !prev_state) {
21920 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21921 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21922 			    (void *)tcp->tcp_connp));
21923 		}
21924 	}
21925 }
21926 
21927 /* Unlink and return any mblk that looks like it contains a LSO info */
21928 static mblk_t *
21929 tcp_lso_info_mp(mblk_t *mp)
21930 {
21931 	mblk_t	*prev_mp;
21932 
21933 	for (;;) {
21934 		prev_mp = mp;
21935 		/* no more to process? */
21936 		if ((mp = mp->b_cont) == NULL)
21937 			break;
21938 
21939 		switch (DB_TYPE(mp)) {
21940 		case M_CTL:
21941 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21942 				continue;
21943 			ASSERT(prev_mp != NULL);
21944 			prev_mp->b_cont = mp->b_cont;
21945 			mp->b_cont = NULL;
21946 			return (mp);
21947 		default:
21948 			break;
21949 		}
21950 	}
21951 
21952 	return (mp);
21953 }
21954 
21955 /* LSO info update routine, called when IP notifies us about LSO */
21956 static void
21957 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21958 {
21959 	tcp_stack_t *tcps = tcp->tcp_tcps;
21960 
21961 	/*
21962 	 * IP is telling us to abort LSO on this connection?  We know
21963 	 * this because the capability is only turned off when IP
21964 	 * encounters some pathological cases, e.g. link-layer change
21965 	 * where the new NIC/driver doesn't support LSO, or in situation
21966 	 * where LSO usage on the link-layer has been switched off.
21967 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21968 	 * if the link-layer doesn't support LSO, and if it does, it
21969 	 * will indicate that the feature is to be turned on.
21970 	 */
21971 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21972 	TCP_STAT(tcps, tcp_lso_enabled);
21973 
21974 	/*
21975 	 * We currently only support LSO on simple TCP/IPv4,
21976 	 * so disable LSO otherwise.  The checks are done here
21977 	 * and in tcp_wput_data().
21978 	 */
21979 	if (tcp->tcp_lso &&
21980 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21981 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21982 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21983 		tcp->tcp_lso = B_FALSE;
21984 		TCP_STAT(tcps, tcp_lso_disabled);
21985 	} else {
21986 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21987 		    lso_capab->ill_lso_max);
21988 	}
21989 }
21990 
21991 static void
21992 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21993 {
21994 	conn_t *connp = tcp->tcp_connp;
21995 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21996 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21997 
21998 	ASSERT(ire != NULL);
21999 
22000 	/*
22001 	 * We may be in the fastpath here, and although we essentially do
22002 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
22003 	 * we try to keep things as brief as possible.  After all, these
22004 	 * are only best-effort checks, and we do more thorough ones prior
22005 	 * to calling tcp_send()/tcp_multisend().
22006 	 */
22007 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
22008 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
22009 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
22010 	    !(ire->ire_flags & RTF_MULTIRT) &&
22011 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
22012 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
22013 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
22014 			/* Cache the result */
22015 			connp->conn_lso_ok = B_TRUE;
22016 
22017 			ASSERT(ill->ill_lso_capab != NULL);
22018 			if (!ill->ill_lso_capab->ill_lso_on) {
22019 				ill->ill_lso_capab->ill_lso_on = 1;
22020 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22021 				    "LSO for interface %s\n", (void *)connp,
22022 				    ill->ill_name));
22023 			}
22024 			tcp_lso_update(tcp, ill->ill_lso_capab);
22025 		} else if (ipst->ips_ip_multidata_outbound &&
22026 		    ILL_MDT_CAPABLE(ill)) {
22027 			/* Cache the result */
22028 			connp->conn_mdt_ok = B_TRUE;
22029 
22030 			ASSERT(ill->ill_mdt_capab != NULL);
22031 			if (!ill->ill_mdt_capab->ill_mdt_on) {
22032 				ill->ill_mdt_capab->ill_mdt_on = 1;
22033 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22034 				    "MDT for interface %s\n", (void *)connp,
22035 				    ill->ill_name));
22036 			}
22037 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
22038 		}
22039 	}
22040 
22041 	/*
22042 	 * The goal is to reduce the number of generated tcp segments by
22043 	 * setting the maxpsz multiplier to 0; this will have an affect on
22044 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
22045 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
22046 	 * of outbound segments and incoming ACKs, thus allowing for better
22047 	 * network and system performance.  In contrast the legacy behavior
22048 	 * may result in sending less than SMSS size, because the last mblk
22049 	 * for some packets may have more data than needed to make up SMSS,
22050 	 * and the legacy code refused to "split" it.
22051 	 *
22052 	 * We apply the new behavior on following situations:
22053 	 *
22054 	 *   1) Loopback connections,
22055 	 *   2) Connections in which the remote peer is not on local subnet,
22056 	 *   3) Local subnet connections over the bge interface (see below).
22057 	 *
22058 	 * Ideally, we would like this behavior to apply for interfaces other
22059 	 * than bge.  However, doing so would negatively impact drivers which
22060 	 * perform dynamic mapping and unmapping of DMA resources, which are
22061 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
22062 	 * packet will be generated by tcp).  The bge driver does not suffer
22063 	 * from this, as it copies the mblks into pre-mapped buffers, and
22064 	 * therefore does not require more I/O resources than before.
22065 	 *
22066 	 * Otherwise, this behavior is present on all network interfaces when
22067 	 * the destination endpoint is non-local, since reducing the number
22068 	 * of packets in general is good for the network.
22069 	 *
22070 	 * TODO We need to remove this hard-coded conditional for bge once
22071 	 *	a better "self-tuning" mechanism, or a way to comprehend
22072 	 *	the driver transmit strategy is devised.  Until the solution
22073 	 *	is found and well understood, we live with this hack.
22074 	 */
22075 	if (!tcp_static_maxpsz &&
22076 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
22077 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
22078 		/* override the default value */
22079 		tcp->tcp_maxpsz = 0;
22080 
22081 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
22082 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
22083 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
22084 	}
22085 
22086 	/* set the stream head parameters accordingly */
22087 	(void) tcp_maxpsz_set(tcp, B_TRUE);
22088 }
22089 
22090 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
22091 static void
22092 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
22093 {
22094 	uchar_t	fval = *mp->b_rptr;
22095 	mblk_t	*tail;
22096 	queue_t	*q = tcp->tcp_wq;
22097 
22098 	/* TODO: How should flush interact with urgent data? */
22099 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
22100 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
22101 		/*
22102 		 * Flush only data that has not yet been put on the wire.  If
22103 		 * we flush data that we have already transmitted, life, as we
22104 		 * know it, may come to an end.
22105 		 */
22106 		tail = tcp->tcp_xmit_tail;
22107 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
22108 		tcp->tcp_xmit_tail_unsent = 0;
22109 		tcp->tcp_unsent = 0;
22110 		if (tail->b_wptr != tail->b_rptr)
22111 			tail = tail->b_cont;
22112 		if (tail) {
22113 			mblk_t **excess = &tcp->tcp_xmit_head;
22114 			for (;;) {
22115 				mblk_t *mp1 = *excess;
22116 				if (mp1 == tail)
22117 					break;
22118 				tcp->tcp_xmit_tail = mp1;
22119 				tcp->tcp_xmit_last = mp1;
22120 				excess = &mp1->b_cont;
22121 			}
22122 			*excess = NULL;
22123 			tcp_close_mpp(&tail);
22124 			if (tcp->tcp_snd_zcopy_aware)
22125 				tcp_zcopy_notify(tcp);
22126 		}
22127 		/*
22128 		 * We have no unsent data, so unsent must be less than
22129 		 * tcp_xmit_lowater, so re-enable flow.
22130 		 */
22131 		mutex_enter(&tcp->tcp_non_sq_lock);
22132 		if (tcp->tcp_flow_stopped) {
22133 			tcp_clrqfull(tcp);
22134 		}
22135 		mutex_exit(&tcp->tcp_non_sq_lock);
22136 	}
22137 	/*
22138 	 * TODO: you can't just flush these, you have to increase rwnd for one
22139 	 * thing.  For another, how should urgent data interact?
22140 	 */
22141 	if (fval & FLUSHR) {
22142 		*mp->b_rptr = fval & ~FLUSHW;
22143 		/* XXX */
22144 		qreply(q, mp);
22145 		return;
22146 	}
22147 	freemsg(mp);
22148 }
22149 
22150 /*
22151  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
22152  * messages.
22153  */
22154 static void
22155 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
22156 {
22157 	mblk_t	*mp1;
22158 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
22159 	STRUCT_HANDLE(strbuf, sb);
22160 	queue_t *q = tcp->tcp_wq;
22161 	int	error;
22162 	uint_t	addrlen;
22163 
22164 	/* Make sure it is one of ours. */
22165 	switch (iocp->ioc_cmd) {
22166 	case TI_GETMYNAME:
22167 	case TI_GETPEERNAME:
22168 		break;
22169 	default:
22170 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
22171 		return;
22172 	}
22173 	switch (mi_copy_state(q, mp, &mp1)) {
22174 	case -1:
22175 		return;
22176 	case MI_COPY_CASE(MI_COPY_IN, 1):
22177 		break;
22178 	case MI_COPY_CASE(MI_COPY_OUT, 1):
22179 		/* Copy out the strbuf. */
22180 		mi_copyout(q, mp);
22181 		return;
22182 	case MI_COPY_CASE(MI_COPY_OUT, 2):
22183 		/* All done. */
22184 		mi_copy_done(q, mp, 0);
22185 		return;
22186 	default:
22187 		mi_copy_done(q, mp, EPROTO);
22188 		return;
22189 	}
22190 	/* Check alignment of the strbuf */
22191 	if (!OK_32PTR(mp1->b_rptr)) {
22192 		mi_copy_done(q, mp, EINVAL);
22193 		return;
22194 	}
22195 
22196 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
22197 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
22198 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
22199 		mi_copy_done(q, mp, EINVAL);
22200 		return;
22201 	}
22202 
22203 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
22204 	if (mp1 == NULL)
22205 		return;
22206 
22207 	switch (iocp->ioc_cmd) {
22208 	case TI_GETMYNAME:
22209 		error = tcp_do_getsockname(tcp, (void *)mp1->b_rptr, &addrlen);
22210 		break;
22211 	case TI_GETPEERNAME:
22212 		error = tcp_do_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
22213 		break;
22214 	}
22215 
22216 	if (error != 0) {
22217 		mi_copy_done(q, mp, error);
22218 	} else {
22219 		mp1->b_wptr += addrlen;
22220 		STRUCT_FSET(sb, len, addrlen);
22221 
22222 		/* Copy out the address */
22223 		mi_copyout(q, mp);
22224 	}
22225 }
22226 
22227 static void
22228 tcp_disable_direct_sockfs(tcp_t *tcp)
22229 {
22230 #ifdef	_ILP32
22231 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
22232 #else
22233 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
22234 #endif
22235 	/*
22236 	 * Insert this socket into the acceptor hash.
22237 	 * We might need it for T_CONN_RES message
22238 	 */
22239 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
22240 
22241 	if (tcp->tcp_fused) {
22242 		/*
22243 		 * This is a fused loopback tcp; disable
22244 		 * read-side synchronous streams interface
22245 		 * and drain any queued data.  It is okay
22246 		 * to do this for non-synchronous streams
22247 		 * fused tcp as well.
22248 		 */
22249 		tcp_fuse_disable_pair(tcp, B_FALSE);
22250 	}
22251 	tcp->tcp_issocket = B_FALSE;
22252 	tcp->tcp_sodirect = NULL;
22253 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
22254 }
22255 
22256 /*
22257  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
22258  * messages.
22259  */
22260 /* ARGSUSED */
22261 static void
22262 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
22263 {
22264 	conn_t 	*connp = (conn_t *)arg;
22265 	tcp_t	*tcp = connp->conn_tcp;
22266 	queue_t	*q = tcp->tcp_wq;
22267 	struct iocblk	*iocp;
22268 
22269 	ASSERT(DB_TYPE(mp) == M_IOCTL);
22270 	/*
22271 	 * Try and ASSERT the minimum possible references on the
22272 	 * conn early enough. Since we are executing on write side,
22273 	 * the connection is obviously not detached and that means
22274 	 * there is a ref each for TCP and IP. Since we are behind
22275 	 * the squeue, the minimum references needed are 3. If the
22276 	 * conn is in classifier hash list, there should be an
22277 	 * extra ref for that (we check both the possibilities).
22278 	 */
22279 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22280 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22281 
22282 	iocp = (struct iocblk *)mp->b_rptr;
22283 	switch (iocp->ioc_cmd) {
22284 	case TCP_IOC_DEFAULT_Q:
22285 		/* Wants to be the default wq. */
22286 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
22287 			iocp->ioc_error = EPERM;
22288 			iocp->ioc_count = 0;
22289 			mp->b_datap->db_type = M_IOCACK;
22290 			qreply(q, mp);
22291 			return;
22292 		}
22293 		tcp_def_q_set(tcp, mp);
22294 		return;
22295 	case _SIOCSOCKFALLBACK:
22296 		/*
22297 		 * Either sockmod is about to be popped and the socket
22298 		 * would now be treated as a plain stream, or a module
22299 		 * is about to be pushed so we could no longer use read-
22300 		 * side synchronous streams for fused loopback tcp.
22301 		 * Drain any queued data and disable direct sockfs
22302 		 * interface from now on.
22303 		 */
22304 		if (!tcp->tcp_issocket) {
22305 			DB_TYPE(mp) = M_IOCNAK;
22306 			iocp->ioc_error = EINVAL;
22307 		} else {
22308 			tcp_disable_direct_sockfs(tcp);
22309 			DB_TYPE(mp) = M_IOCACK;
22310 			iocp->ioc_error = 0;
22311 		}
22312 		iocp->ioc_count = 0;
22313 		iocp->ioc_rval = 0;
22314 		qreply(q, mp);
22315 		return;
22316 	}
22317 	CALL_IP_WPUT(connp, q, mp);
22318 }
22319 
22320 /*
22321  * This routine is called by tcp_wput() to handle all TPI requests.
22322  */
22323 /* ARGSUSED */
22324 static void
22325 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22326 {
22327 	conn_t 	*connp = (conn_t *)arg;
22328 	tcp_t	*tcp = connp->conn_tcp;
22329 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22330 	uchar_t *rptr;
22331 	t_scalar_t type;
22332 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
22333 
22334 	/*
22335 	 * Try and ASSERT the minimum possible references on the
22336 	 * conn early enough. Since we are executing on write side,
22337 	 * the connection is obviously not detached and that means
22338 	 * there is a ref each for TCP and IP. Since we are behind
22339 	 * the squeue, the minimum references needed are 3. If the
22340 	 * conn is in classifier hash list, there should be an
22341 	 * extra ref for that (we check both the possibilities).
22342 	 */
22343 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22344 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22345 
22346 	rptr = mp->b_rptr;
22347 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22348 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22349 		type = ((union T_primitives *)rptr)->type;
22350 		if (type == T_EXDATA_REQ) {
22351 			tcp_output_urgent(connp, mp->b_cont, arg2);
22352 			freeb(mp);
22353 		} else if (type != T_DATA_REQ) {
22354 			goto non_urgent_data;
22355 		} else {
22356 			/* TODO: options, flags, ... from user */
22357 			/* Set length to zero for reclamation below */
22358 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22359 			freeb(mp);
22360 		}
22361 		return;
22362 	} else {
22363 		if (tcp->tcp_debug) {
22364 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22365 			    "tcp_wput_proto, dropping one...");
22366 		}
22367 		freemsg(mp);
22368 		return;
22369 	}
22370 
22371 non_urgent_data:
22372 
22373 	switch ((int)tprim->type) {
22374 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22375 		/*
22376 		 * save the kssl_ent_t from the next block, and convert this
22377 		 * back to a normal bind_req.
22378 		 */
22379 		if (mp->b_cont != NULL) {
22380 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22381 
22382 			if (tcp->tcp_kssl_ent != NULL) {
22383 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22384 				    KSSL_NO_PROXY);
22385 				tcp->tcp_kssl_ent = NULL;
22386 			}
22387 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22388 			    sizeof (kssl_ent_t));
22389 			kssl_hold_ent(tcp->tcp_kssl_ent);
22390 			freemsg(mp->b_cont);
22391 			mp->b_cont = NULL;
22392 		}
22393 		tprim->type = T_BIND_REQ;
22394 
22395 	/* FALLTHROUGH */
22396 	case O_T_BIND_REQ:	/* bind request */
22397 	case T_BIND_REQ:	/* new semantics bind request */
22398 		tcp_tpi_bind(tcp, mp);
22399 		break;
22400 	case T_UNBIND_REQ:	/* unbind request */
22401 		tcp_tpi_unbind(tcp, mp);
22402 		break;
22403 	case O_T_CONN_RES:	/* old connection response XXX */
22404 	case T_CONN_RES:	/* connection response */
22405 		tcp_tli_accept(tcp, mp);
22406 		break;
22407 	case T_CONN_REQ:	/* connection request */
22408 		tcp_tpi_connect(tcp, mp);
22409 		break;
22410 	case T_DISCON_REQ:	/* disconnect request */
22411 		tcp_disconnect(tcp, mp);
22412 		break;
22413 	case T_CAPABILITY_REQ:
22414 		tcp_capability_req(tcp, mp);	/* capability request */
22415 		break;
22416 	case T_INFO_REQ:	/* information request */
22417 		tcp_info_req(tcp, mp);
22418 		break;
22419 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22420 		/*
22421 		 * If EINPROGRESS is returned, the request has been queued
22422 		 * for subsequent processing by ip_restart_optmgmt(), which
22423 		 * will do the CONN_DEC_REF().
22424 		 */
22425 		CONN_INC_REF(connp);
22426 		if (svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22427 		    B_TRUE) != EINPROGRESS) {
22428 			CONN_DEC_REF(connp);
22429 		}
22430 		break;
22431 	case T_OPTMGMT_REQ:
22432 		/*
22433 		 * Note:  no support for snmpcom_req() through new
22434 		 * T_OPTMGMT_REQ. See comments in ip.c
22435 		 *
22436 		 * see comments above in T_SVR4_OPTMGMT_REQ for conn
22437 		 * reference changes.
22438 		 */
22439 		CONN_INC_REF(connp);
22440 		if (tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22441 		    B_TRUE) != EINPROGRESS) {
22442 			CONN_DEC_REF(connp);
22443 		}
22444 		break;
22445 
22446 	case T_UNITDATA_REQ:	/* unitdata request */
22447 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22448 		break;
22449 	case T_ORDREL_REQ:	/* orderly release req */
22450 		freemsg(mp);
22451 
22452 		if (tcp->tcp_fused)
22453 			tcp_unfuse(tcp);
22454 
22455 		if (tcp_xmit_end(tcp) != 0) {
22456 			/*
22457 			 * We were crossing FINs and got a reset from
22458 			 * the other side. Just ignore it.
22459 			 */
22460 			if (tcp->tcp_debug) {
22461 				(void) strlog(TCP_MOD_ID, 0, 1,
22462 				    SL_ERROR|SL_TRACE,
22463 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22464 				    "state %s",
22465 				    tcp_display(tcp, NULL,
22466 				    DISP_ADDR_AND_PORT));
22467 			}
22468 		}
22469 		break;
22470 	case T_ADDR_REQ:
22471 		tcp_addr_req(tcp, mp);
22472 		break;
22473 	default:
22474 		if (tcp->tcp_debug) {
22475 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22476 			    "tcp_wput_proto, bogus TPI msg, type %d",
22477 			    tprim->type);
22478 		}
22479 		/*
22480 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22481 		 * to recover.
22482 		 */
22483 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22484 		break;
22485 	}
22486 }
22487 
22488 /*
22489  * The TCP write service routine should never be called...
22490  */
22491 /* ARGSUSED */
22492 static void
22493 tcp_wsrv(queue_t *q)
22494 {
22495 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22496 
22497 	TCP_STAT(tcps, tcp_wsrv_called);
22498 }
22499 
22500 /* Non overlapping byte exchanger */
22501 static void
22502 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22503 {
22504 	uchar_t	uch;
22505 
22506 	while (len-- > 0) {
22507 		uch = a[len];
22508 		a[len] = b[len];
22509 		b[len] = uch;
22510 	}
22511 }
22512 
22513 /*
22514  * Send out a control packet on the tcp connection specified.  This routine
22515  * is typically called where we need a simple ACK or RST generated.
22516  */
22517 static void
22518 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22519 {
22520 	uchar_t		*rptr;
22521 	tcph_t		*tcph;
22522 	ipha_t		*ipha = NULL;
22523 	ip6_t		*ip6h = NULL;
22524 	uint32_t	sum;
22525 	int		tcp_hdr_len;
22526 	int		tcp_ip_hdr_len;
22527 	mblk_t		*mp;
22528 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22529 
22530 	/*
22531 	 * Save sum for use in source route later.
22532 	 */
22533 	ASSERT(tcp != NULL);
22534 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22535 	tcp_hdr_len = tcp->tcp_hdr_len;
22536 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22537 
22538 	/* If a text string is passed in with the request, pass it to strlog. */
22539 	if (str != NULL && tcp->tcp_debug) {
22540 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22541 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22542 		    str, seq, ack, ctl);
22543 	}
22544 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22545 	    BPRI_MED);
22546 	if (mp == NULL) {
22547 		return;
22548 	}
22549 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22550 	mp->b_rptr = rptr;
22551 	mp->b_wptr = &rptr[tcp_hdr_len];
22552 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22553 
22554 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22555 		ipha = (ipha_t *)rptr;
22556 		ipha->ipha_length = htons(tcp_hdr_len);
22557 	} else {
22558 		ip6h = (ip6_t *)rptr;
22559 		ASSERT(tcp != NULL);
22560 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22561 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22562 	}
22563 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22564 	tcph->th_flags[0] = (uint8_t)ctl;
22565 	if (ctl & TH_RST) {
22566 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22567 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22568 		/*
22569 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22570 		 */
22571 		if (tcp->tcp_snd_ts_ok &&
22572 		    tcp->tcp_state > TCPS_SYN_SENT) {
22573 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22574 			*(mp->b_wptr) = TCPOPT_EOL;
22575 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22576 				ipha->ipha_length = htons(tcp_hdr_len -
22577 				    TCPOPT_REAL_TS_LEN);
22578 			} else {
22579 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22580 				    TCPOPT_REAL_TS_LEN);
22581 			}
22582 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22583 			sum -= TCPOPT_REAL_TS_LEN;
22584 		}
22585 	}
22586 	if (ctl & TH_ACK) {
22587 		if (tcp->tcp_snd_ts_ok) {
22588 			U32_TO_BE32(lbolt,
22589 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22590 			U32_TO_BE32(tcp->tcp_ts_recent,
22591 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22592 		}
22593 
22594 		/* Update the latest receive window size in TCP header. */
22595 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22596 		    tcph->th_win);
22597 		tcp->tcp_rack = ack;
22598 		tcp->tcp_rack_cnt = 0;
22599 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22600 	}
22601 	BUMP_LOCAL(tcp->tcp_obsegs);
22602 	U32_TO_BE32(seq, tcph->th_seq);
22603 	U32_TO_BE32(ack, tcph->th_ack);
22604 	/*
22605 	 * Include the adjustment for a source route if any.
22606 	 */
22607 	sum = (sum >> 16) + (sum & 0xFFFF);
22608 	U16_TO_BE16(sum, tcph->th_sum);
22609 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22610 }
22611 
22612 /*
22613  * If this routine returns B_TRUE, TCP can generate a RST in response
22614  * to a segment.  If it returns B_FALSE, TCP should not respond.
22615  */
22616 static boolean_t
22617 tcp_send_rst_chk(tcp_stack_t *tcps)
22618 {
22619 	clock_t	now;
22620 
22621 	/*
22622 	 * TCP needs to protect itself from generating too many RSTs.
22623 	 * This can be a DoS attack by sending us random segments
22624 	 * soliciting RSTs.
22625 	 *
22626 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22627 	 * in each 1 second interval.  In this way, TCP still generate
22628 	 * RSTs in normal cases but when under attack, the impact is
22629 	 * limited.
22630 	 */
22631 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22632 		now = lbolt;
22633 		/* lbolt can wrap around. */
22634 		if ((tcps->tcps_last_rst_intrvl > now) ||
22635 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22636 		    1*SECONDS)) {
22637 			tcps->tcps_last_rst_intrvl = now;
22638 			tcps->tcps_rst_cnt = 1;
22639 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22640 			return (B_FALSE);
22641 		}
22642 	}
22643 	return (B_TRUE);
22644 }
22645 
22646 /*
22647  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22648  */
22649 static void
22650 tcp_ip_ire_mark_advice(tcp_t *tcp)
22651 {
22652 	mblk_t *mp;
22653 	ipic_t *ipic;
22654 
22655 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22656 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22657 		    &ipic);
22658 	} else {
22659 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22660 		    &ipic);
22661 	}
22662 	if (mp == NULL)
22663 		return;
22664 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22665 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22666 }
22667 
22668 /*
22669  * Return an IP advice ioctl mblk and set ipic to be the pointer
22670  * to the advice structure.
22671  */
22672 static mblk_t *
22673 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22674 {
22675 	struct iocblk *ioc;
22676 	mblk_t *mp, *mp1;
22677 
22678 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22679 	if (mp == NULL)
22680 		return (NULL);
22681 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22682 	*ipic = (ipic_t *)mp->b_rptr;
22683 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22684 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22685 
22686 	bcopy(addr, *ipic + 1, addr_len);
22687 
22688 	(*ipic)->ipic_addr_length = addr_len;
22689 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22690 
22691 	mp1 = mkiocb(IP_IOCTL);
22692 	if (mp1 == NULL) {
22693 		freemsg(mp);
22694 		return (NULL);
22695 	}
22696 	mp1->b_cont = mp;
22697 	ioc = (struct iocblk *)mp1->b_rptr;
22698 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22699 
22700 	return (mp1);
22701 }
22702 
22703 /*
22704  * Generate a reset based on an inbound packet, connp is set by caller
22705  * when RST is in response to an unexpected inbound packet for which
22706  * there is active tcp state in the system.
22707  *
22708  * IPSEC NOTE : Try to send the reply with the same protection as it came
22709  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22710  * the packet will go out at the same level of protection as it came in by
22711  * converting the IPSEC_IN to IPSEC_OUT.
22712  */
22713 static void
22714 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22715     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22716     tcp_stack_t *tcps, conn_t *connp)
22717 {
22718 	ipha_t		*ipha = NULL;
22719 	ip6_t		*ip6h = NULL;
22720 	ushort_t	len;
22721 	tcph_t		*tcph;
22722 	int		i;
22723 	mblk_t		*ipsec_mp;
22724 	boolean_t	mctl_present;
22725 	ipic_t		*ipic;
22726 	ipaddr_t	v4addr;
22727 	in6_addr_t	v6addr;
22728 	int		addr_len;
22729 	void		*addr;
22730 	queue_t		*q = tcps->tcps_g_q;
22731 	tcp_t		*tcp;
22732 	cred_t		*cr;
22733 	mblk_t		*nmp;
22734 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22735 
22736 	if (tcps->tcps_g_q == NULL) {
22737 		/*
22738 		 * For non-zero stackids the default queue isn't created
22739 		 * until the first open, thus there can be a need to send
22740 		 * a reset before then. But we can't do that, hence we just
22741 		 * drop the packet. Later during boot, when the default queue
22742 		 * has been setup, a retransmitted packet from the peer
22743 		 * will result in a reset.
22744 		 */
22745 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22746 		    GLOBAL_NETSTACKID);
22747 		freemsg(mp);
22748 		return;
22749 	}
22750 
22751 	if (connp != NULL)
22752 		tcp = connp->conn_tcp;
22753 	else
22754 		tcp = Q_TO_TCP(q);
22755 
22756 	if (!tcp_send_rst_chk(tcps)) {
22757 		tcps->tcps_rst_unsent++;
22758 		freemsg(mp);
22759 		return;
22760 	}
22761 
22762 	if (mp->b_datap->db_type == M_CTL) {
22763 		ipsec_mp = mp;
22764 		mp = mp->b_cont;
22765 		mctl_present = B_TRUE;
22766 	} else {
22767 		ipsec_mp = mp;
22768 		mctl_present = B_FALSE;
22769 	}
22770 
22771 	if (str && q && tcps->tcps_dbg) {
22772 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22773 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22774 		    "flags 0x%x",
22775 		    str, seq, ack, ctl);
22776 	}
22777 	if (mp->b_datap->db_ref != 1) {
22778 		mblk_t *mp1 = copyb(mp);
22779 		freemsg(mp);
22780 		mp = mp1;
22781 		if (!mp) {
22782 			if (mctl_present)
22783 				freeb(ipsec_mp);
22784 			return;
22785 		} else {
22786 			if (mctl_present) {
22787 				ipsec_mp->b_cont = mp;
22788 			} else {
22789 				ipsec_mp = mp;
22790 			}
22791 		}
22792 	} else if (mp->b_cont) {
22793 		freemsg(mp->b_cont);
22794 		mp->b_cont = NULL;
22795 	}
22796 	/*
22797 	 * We skip reversing source route here.
22798 	 * (for now we replace all IP options with EOL)
22799 	 */
22800 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22801 		ipha = (ipha_t *)mp->b_rptr;
22802 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22803 			mp->b_rptr[i] = IPOPT_EOL;
22804 		/*
22805 		 * Make sure that src address isn't flagrantly invalid.
22806 		 * Not all broadcast address checking for the src address
22807 		 * is possible, since we don't know the netmask of the src
22808 		 * addr.  No check for destination address is done, since
22809 		 * IP will not pass up a packet with a broadcast dest
22810 		 * address to TCP.  Similar checks are done below for IPv6.
22811 		 */
22812 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22813 		    CLASSD(ipha->ipha_src)) {
22814 			freemsg(ipsec_mp);
22815 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22816 			return;
22817 		}
22818 	} else {
22819 		ip6h = (ip6_t *)mp->b_rptr;
22820 
22821 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22822 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22823 			freemsg(ipsec_mp);
22824 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22825 			return;
22826 		}
22827 
22828 		/* Remove any extension headers assuming partial overlay */
22829 		if (ip_hdr_len > IPV6_HDR_LEN) {
22830 			uint8_t *to;
22831 
22832 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22833 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22834 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22835 			ip_hdr_len = IPV6_HDR_LEN;
22836 			ip6h = (ip6_t *)mp->b_rptr;
22837 			ip6h->ip6_nxt = IPPROTO_TCP;
22838 		}
22839 	}
22840 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22841 	if (tcph->th_flags[0] & TH_RST) {
22842 		freemsg(ipsec_mp);
22843 		return;
22844 	}
22845 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22846 	len = ip_hdr_len + sizeof (tcph_t);
22847 	mp->b_wptr = &mp->b_rptr[len];
22848 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22849 		ipha->ipha_length = htons(len);
22850 		/* Swap addresses */
22851 		v4addr = ipha->ipha_src;
22852 		ipha->ipha_src = ipha->ipha_dst;
22853 		ipha->ipha_dst = v4addr;
22854 		ipha->ipha_ident = 0;
22855 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22856 		addr_len = IP_ADDR_LEN;
22857 		addr = &v4addr;
22858 	} else {
22859 		/* No ip6i_t in this case */
22860 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22861 		/* Swap addresses */
22862 		v6addr = ip6h->ip6_src;
22863 		ip6h->ip6_src = ip6h->ip6_dst;
22864 		ip6h->ip6_dst = v6addr;
22865 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22866 		addr_len = IPV6_ADDR_LEN;
22867 		addr = &v6addr;
22868 	}
22869 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22870 	U32_TO_BE32(ack, tcph->th_ack);
22871 	U32_TO_BE32(seq, tcph->th_seq);
22872 	U16_TO_BE16(0, tcph->th_win);
22873 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22874 	tcph->th_flags[0] = (uint8_t)ctl;
22875 	if (ctl & TH_RST) {
22876 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22877 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22878 	}
22879 
22880 	/* IP trusts us to set up labels when required. */
22881 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
22882 	    crgetlabel(cr) != NULL) {
22883 		int err;
22884 
22885 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22886 			err = tsol_check_label(cr, &mp,
22887 			    tcp->tcp_connp->conn_mac_exempt,
22888 			    tcps->tcps_netstack->netstack_ip);
22889 		else
22890 			err = tsol_check_label_v6(cr, &mp,
22891 			    tcp->tcp_connp->conn_mac_exempt,
22892 			    tcps->tcps_netstack->netstack_ip);
22893 		if (mctl_present)
22894 			ipsec_mp->b_cont = mp;
22895 		else
22896 			ipsec_mp = mp;
22897 		if (err != 0) {
22898 			freemsg(ipsec_mp);
22899 			return;
22900 		}
22901 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22902 			ipha = (ipha_t *)mp->b_rptr;
22903 		} else {
22904 			ip6h = (ip6_t *)mp->b_rptr;
22905 		}
22906 	}
22907 
22908 	if (mctl_present) {
22909 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22910 
22911 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22912 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22913 			return;
22914 		}
22915 	}
22916 	if (zoneid == ALL_ZONES)
22917 		zoneid = GLOBAL_ZONEID;
22918 
22919 	/* Add the zoneid so ip_output routes it properly */
22920 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22921 		freemsg(ipsec_mp);
22922 		return;
22923 	}
22924 	ipsec_mp = nmp;
22925 
22926 	/*
22927 	 * NOTE:  one might consider tracing a TCP packet here, but
22928 	 * this function has no active TCP state and no tcp structure
22929 	 * that has a trace buffer.  If we traced here, we would have
22930 	 * to keep a local trace buffer in tcp_record_trace().
22931 	 *
22932 	 * TSol note: The mblk that contains the incoming packet was
22933 	 * reused by tcp_xmit_listener_reset, so it already contains
22934 	 * the right credentials and we don't need to call mblk_setcred.
22935 	 * Also the conn's cred is not right since it is associated
22936 	 * with tcps_g_q.
22937 	 */
22938 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22939 
22940 	/*
22941 	 * Tell IP to mark the IRE used for this destination temporary.
22942 	 * This way, we can limit our exposure to DoS attack because IP
22943 	 * creates an IRE for each destination.  If there are too many,
22944 	 * the time to do any routing lookup will be extremely long.  And
22945 	 * the lookup can be in interrupt context.
22946 	 *
22947 	 * Note that in normal circumstances, this marking should not
22948 	 * affect anything.  It would be nice if only 1 message is
22949 	 * needed to inform IP that the IRE created for this RST should
22950 	 * not be added to the cache table.  But there is currently
22951 	 * not such communication mechanism between TCP and IP.  So
22952 	 * the best we can do now is to send the advice ioctl to IP
22953 	 * to mark the IRE temporary.
22954 	 */
22955 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22956 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22957 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22958 	}
22959 }
22960 
22961 /*
22962  * Initiate closedown sequence on an active connection.  (May be called as
22963  * writer.)  Return value zero for OK return, non-zero for error return.
22964  */
22965 static int
22966 tcp_xmit_end(tcp_t *tcp)
22967 {
22968 	ipic_t	*ipic;
22969 	mblk_t	*mp;
22970 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22971 
22972 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22973 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22974 		/*
22975 		 * Invalid state, only states TCPS_SYN_RCVD,
22976 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22977 		 */
22978 		return (-1);
22979 	}
22980 
22981 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22982 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22983 	/*
22984 	 * If there is nothing more unsent, send the FIN now.
22985 	 * Otherwise, it will go out with the last segment.
22986 	 */
22987 	if (tcp->tcp_unsent == 0) {
22988 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22989 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22990 
22991 		if (mp) {
22992 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22993 		} else {
22994 			/*
22995 			 * Couldn't allocate msg.  Pretend we got it out.
22996 			 * Wait for rexmit timeout.
22997 			 */
22998 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22999 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23000 		}
23001 
23002 		/*
23003 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
23004 		 * changed.
23005 		 */
23006 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
23007 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23008 		}
23009 	} else {
23010 		/*
23011 		 * If tcp->tcp_cork is set, then the data will not get sent,
23012 		 * so we have to check that and unset it first.
23013 		 */
23014 		if (tcp->tcp_cork)
23015 			tcp->tcp_cork = B_FALSE;
23016 		tcp_wput_data(tcp, NULL, B_FALSE);
23017 	}
23018 
23019 	/*
23020 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
23021 	 * is 0, don't update the cache.
23022 	 */
23023 	if (tcps->tcps_rtt_updates == 0 ||
23024 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
23025 		return (0);
23026 
23027 	/*
23028 	 * NOTE: should not update if source routes i.e. if tcp_remote if
23029 	 * different from the destination.
23030 	 */
23031 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23032 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
23033 			return (0);
23034 		}
23035 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
23036 		    &ipic);
23037 	} else {
23038 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
23039 		    &tcp->tcp_ip6h->ip6_dst))) {
23040 			return (0);
23041 		}
23042 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
23043 		    &ipic);
23044 	}
23045 
23046 	/* Record route attributes in the IRE for use by future connections. */
23047 	if (mp == NULL)
23048 		return (0);
23049 
23050 	/*
23051 	 * We do not have a good algorithm to update ssthresh at this time.
23052 	 * So don't do any update.
23053 	 */
23054 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
23055 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
23056 
23057 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23058 
23059 	return (0);
23060 }
23061 
23062 /*
23063  * Generate a "no listener here" RST in response to an "unknown" segment.
23064  * connp is set by caller when RST is in response to an unexpected
23065  * inbound packet for which there is active tcp state in the system.
23066  * Note that we are reusing the incoming mp to construct the outgoing RST.
23067  */
23068 void
23069 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
23070     tcp_stack_t *tcps, conn_t *connp)
23071 {
23072 	uchar_t		*rptr;
23073 	uint32_t	seg_len;
23074 	tcph_t		*tcph;
23075 	uint32_t	seg_seq;
23076 	uint32_t	seg_ack;
23077 	uint_t		flags;
23078 	mblk_t		*ipsec_mp;
23079 	ipha_t 		*ipha;
23080 	ip6_t 		*ip6h;
23081 	boolean_t	mctl_present = B_FALSE;
23082 	boolean_t	check = B_TRUE;
23083 	boolean_t	policy_present;
23084 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
23085 
23086 	TCP_STAT(tcps, tcp_no_listener);
23087 
23088 	ipsec_mp = mp;
23089 
23090 	if (mp->b_datap->db_type == M_CTL) {
23091 		ipsec_in_t *ii;
23092 
23093 		mctl_present = B_TRUE;
23094 		mp = mp->b_cont;
23095 
23096 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23097 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23098 		if (ii->ipsec_in_dont_check) {
23099 			check = B_FALSE;
23100 			if (!ii->ipsec_in_secure) {
23101 				freeb(ipsec_mp);
23102 				mctl_present = B_FALSE;
23103 				ipsec_mp = mp;
23104 			}
23105 		}
23106 	}
23107 
23108 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23109 		policy_present = ipss->ipsec_inbound_v4_policy_present;
23110 		ipha = (ipha_t *)mp->b_rptr;
23111 		ip6h = NULL;
23112 	} else {
23113 		policy_present = ipss->ipsec_inbound_v6_policy_present;
23114 		ipha = NULL;
23115 		ip6h = (ip6_t *)mp->b_rptr;
23116 	}
23117 
23118 	if (check && policy_present) {
23119 		/*
23120 		 * The conn_t parameter is NULL because we already know
23121 		 * nobody's home.
23122 		 */
23123 		ipsec_mp = ipsec_check_global_policy(
23124 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
23125 		    tcps->tcps_netstack);
23126 		if (ipsec_mp == NULL)
23127 			return;
23128 	}
23129 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
23130 		DTRACE_PROBE2(
23131 		    tx__ip__log__error__nolistener__tcp,
23132 		    char *, "Could not reply with RST to mp(1)",
23133 		    mblk_t *, mp);
23134 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
23135 		freemsg(ipsec_mp);
23136 		return;
23137 	}
23138 
23139 	rptr = mp->b_rptr;
23140 
23141 	tcph = (tcph_t *)&rptr[ip_hdr_len];
23142 	seg_seq = BE32_TO_U32(tcph->th_seq);
23143 	seg_ack = BE32_TO_U32(tcph->th_ack);
23144 	flags = tcph->th_flags[0];
23145 
23146 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
23147 	if (flags & TH_RST) {
23148 		freemsg(ipsec_mp);
23149 	} else if (flags & TH_ACK) {
23150 		tcp_xmit_early_reset("no tcp, reset",
23151 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
23152 		    connp);
23153 	} else {
23154 		if (flags & TH_SYN) {
23155 			seg_len++;
23156 		} else {
23157 			/*
23158 			 * Here we violate the RFC.  Note that a normal
23159 			 * TCP will never send a segment without the ACK
23160 			 * flag, except for RST or SYN segment.  This
23161 			 * segment is neither.  Just drop it on the
23162 			 * floor.
23163 			 */
23164 			freemsg(ipsec_mp);
23165 			tcps->tcps_rst_unsent++;
23166 			return;
23167 		}
23168 
23169 		tcp_xmit_early_reset("no tcp, reset/ack",
23170 		    ipsec_mp, 0, seg_seq + seg_len,
23171 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
23172 	}
23173 }
23174 
23175 /*
23176  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
23177  * ip and tcp header ready to pass down to IP.  If the mp passed in is
23178  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
23179  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
23180  * otherwise it will dup partial mblks.)
23181  * Otherwise, an appropriate ACK packet will be generated.  This
23182  * routine is not usually called to send new data for the first time.  It
23183  * is mostly called out of the timer for retransmits, and to generate ACKs.
23184  *
23185  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
23186  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
23187  * of the original mblk chain will be returned in *offset and *end_mp.
23188  */
23189 mblk_t *
23190 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
23191     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
23192     boolean_t rexmit)
23193 {
23194 	int	data_length;
23195 	int32_t	off = 0;
23196 	uint_t	flags;
23197 	mblk_t	*mp1;
23198 	mblk_t	*mp2;
23199 	uchar_t	*rptr;
23200 	tcph_t	*tcph;
23201 	int32_t	num_sack_blk = 0;
23202 	int32_t	sack_opt_len = 0;
23203 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23204 
23205 	/* Allocate for our maximum TCP header + link-level */
23206 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
23207 	    tcps->tcps_wroff_xtra, BPRI_MED);
23208 	if (!mp1)
23209 		return (NULL);
23210 	data_length = 0;
23211 
23212 	/*
23213 	 * Note that tcp_mss has been adjusted to take into account the
23214 	 * timestamp option if applicable.  Because SACK options do not
23215 	 * appear in every TCP segments and they are of variable lengths,
23216 	 * they cannot be included in tcp_mss.  Thus we need to calculate
23217 	 * the actual segment length when we need to send a segment which
23218 	 * includes SACK options.
23219 	 */
23220 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23221 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23222 		    tcp->tcp_num_sack_blk);
23223 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23224 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23225 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
23226 			max_to_send -= sack_opt_len;
23227 	}
23228 
23229 	if (offset != NULL) {
23230 		off = *offset;
23231 		/* We use offset as an indicator that end_mp is not NULL. */
23232 		*end_mp = NULL;
23233 	}
23234 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
23235 		/* This could be faster with cooperation from downstream */
23236 		if (mp2 != mp1 && !sendall &&
23237 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
23238 		    max_to_send)
23239 			/*
23240 			 * Don't send the next mblk since the whole mblk
23241 			 * does not fit.
23242 			 */
23243 			break;
23244 		mp2->b_cont = dupb(mp);
23245 		mp2 = mp2->b_cont;
23246 		if (!mp2) {
23247 			freemsg(mp1);
23248 			return (NULL);
23249 		}
23250 		mp2->b_rptr += off;
23251 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
23252 		    (uintptr_t)INT_MAX);
23253 
23254 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
23255 		if (data_length > max_to_send) {
23256 			mp2->b_wptr -= data_length - max_to_send;
23257 			data_length = max_to_send;
23258 			off = mp2->b_wptr - mp->b_rptr;
23259 			break;
23260 		} else {
23261 			off = 0;
23262 		}
23263 	}
23264 	if (offset != NULL) {
23265 		*offset = off;
23266 		*end_mp = mp;
23267 	}
23268 	if (seg_len != NULL) {
23269 		*seg_len = data_length;
23270 	}
23271 
23272 	/* Update the latest receive window size in TCP header. */
23273 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23274 	    tcp->tcp_tcph->th_win);
23275 
23276 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23277 	mp1->b_rptr = rptr;
23278 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
23279 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23280 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23281 	U32_TO_ABE32(seq, tcph->th_seq);
23282 
23283 	/*
23284 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
23285 	 * that this function was called from tcp_wput_data. Thus, when called
23286 	 * to retransmit data the setting of the PUSH bit may appear some
23287 	 * what random in that it might get set when it should not. This
23288 	 * should not pose any performance issues.
23289 	 */
23290 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
23291 	    tcp->tcp_unsent == data_length)) {
23292 		flags = TH_ACK | TH_PUSH;
23293 	} else {
23294 		flags = TH_ACK;
23295 	}
23296 
23297 	if (tcp->tcp_ecn_ok) {
23298 		if (tcp->tcp_ecn_echo_on)
23299 			flags |= TH_ECE;
23300 
23301 		/*
23302 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
23303 		 * There is no TCP flow control for non-data segments, and
23304 		 * only data segment is transmitted reliably.
23305 		 */
23306 		if (data_length > 0 && !rexmit) {
23307 			SET_ECT(tcp, rptr);
23308 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23309 				flags |= TH_CWR;
23310 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23311 			}
23312 		}
23313 	}
23314 
23315 	if (tcp->tcp_valid_bits) {
23316 		uint32_t u1;
23317 
23318 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23319 		    seq == tcp->tcp_iss) {
23320 			uchar_t	*wptr;
23321 
23322 			/*
23323 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23324 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23325 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23326 			 * our SYN is not ack'ed but the app closes this
23327 			 * TCP connection.
23328 			 */
23329 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23330 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23331 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23332 
23333 			/*
23334 			 * Tack on the MSS option.  It is always needed
23335 			 * for both active and passive open.
23336 			 *
23337 			 * MSS option value should be interface MTU - MIN
23338 			 * TCP/IP header according to RFC 793 as it means
23339 			 * the maximum segment size TCP can receive.  But
23340 			 * to get around some broken middle boxes/end hosts
23341 			 * out there, we allow the option value to be the
23342 			 * same as the MSS option size on the peer side.
23343 			 * In this way, the other side will not send
23344 			 * anything larger than they can receive.
23345 			 *
23346 			 * Note that for SYN_SENT state, the ndd param
23347 			 * tcp_use_smss_as_mss_opt has no effect as we
23348 			 * don't know the peer's MSS option value. So
23349 			 * the only case we need to take care of is in
23350 			 * SYN_RCVD state, which is done later.
23351 			 */
23352 			wptr = mp1->b_wptr;
23353 			wptr[0] = TCPOPT_MAXSEG;
23354 			wptr[1] = TCPOPT_MAXSEG_LEN;
23355 			wptr += 2;
23356 			u1 = tcp->tcp_if_mtu -
23357 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23358 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23359 			    TCP_MIN_HEADER_LENGTH;
23360 			U16_TO_BE16(u1, wptr);
23361 			mp1->b_wptr = wptr + 2;
23362 			/* Update the offset to cover the additional word */
23363 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23364 
23365 			/*
23366 			 * Note that the following way of filling in
23367 			 * TCP options are not optimal.  Some NOPs can
23368 			 * be saved.  But there is no need at this time
23369 			 * to optimize it.  When it is needed, we will
23370 			 * do it.
23371 			 */
23372 			switch (tcp->tcp_state) {
23373 			case TCPS_SYN_SENT:
23374 				flags = TH_SYN;
23375 
23376 				if (tcp->tcp_snd_ts_ok) {
23377 					uint32_t llbolt = (uint32_t)lbolt;
23378 
23379 					wptr = mp1->b_wptr;
23380 					wptr[0] = TCPOPT_NOP;
23381 					wptr[1] = TCPOPT_NOP;
23382 					wptr[2] = TCPOPT_TSTAMP;
23383 					wptr[3] = TCPOPT_TSTAMP_LEN;
23384 					wptr += 4;
23385 					U32_TO_BE32(llbolt, wptr);
23386 					wptr += 4;
23387 					ASSERT(tcp->tcp_ts_recent == 0);
23388 					U32_TO_BE32(0L, wptr);
23389 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23390 					tcph->th_offset_and_rsrvd[0] +=
23391 					    (3 << 4);
23392 				}
23393 
23394 				/*
23395 				 * Set up all the bits to tell other side
23396 				 * we are ECN capable.
23397 				 */
23398 				if (tcp->tcp_ecn_ok) {
23399 					flags |= (TH_ECE | TH_CWR);
23400 				}
23401 				break;
23402 			case TCPS_SYN_RCVD:
23403 				flags |= TH_SYN;
23404 
23405 				/*
23406 				 * Reset the MSS option value to be SMSS
23407 				 * We should probably add back the bytes
23408 				 * for timestamp option and IPsec.  We
23409 				 * don't do that as this is a workaround
23410 				 * for broken middle boxes/end hosts, it
23411 				 * is better for us to be more cautious.
23412 				 * They may not take these things into
23413 				 * account in their SMSS calculation.  Thus
23414 				 * the peer's calculated SMSS may be smaller
23415 				 * than what it can be.  This should be OK.
23416 				 */
23417 				if (tcps->tcps_use_smss_as_mss_opt) {
23418 					u1 = tcp->tcp_mss;
23419 					U16_TO_BE16(u1, wptr);
23420 				}
23421 
23422 				/*
23423 				 * If the other side is ECN capable, reply
23424 				 * that we are also ECN capable.
23425 				 */
23426 				if (tcp->tcp_ecn_ok)
23427 					flags |= TH_ECE;
23428 				break;
23429 			default:
23430 				/*
23431 				 * The above ASSERT() makes sure that this
23432 				 * must be FIN-WAIT-1 state.  Our SYN has
23433 				 * not been ack'ed so retransmit it.
23434 				 */
23435 				flags |= TH_SYN;
23436 				break;
23437 			}
23438 
23439 			if (tcp->tcp_snd_ws_ok) {
23440 				wptr = mp1->b_wptr;
23441 				wptr[0] =  TCPOPT_NOP;
23442 				wptr[1] =  TCPOPT_WSCALE;
23443 				wptr[2] =  TCPOPT_WS_LEN;
23444 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23445 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23446 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23447 			}
23448 
23449 			if (tcp->tcp_snd_sack_ok) {
23450 				wptr = mp1->b_wptr;
23451 				wptr[0] = TCPOPT_NOP;
23452 				wptr[1] = TCPOPT_NOP;
23453 				wptr[2] = TCPOPT_SACK_PERMITTED;
23454 				wptr[3] = TCPOPT_SACK_OK_LEN;
23455 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23456 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23457 			}
23458 
23459 			/* allocb() of adequate mblk assures space */
23460 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23461 			    (uintptr_t)INT_MAX);
23462 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23463 			/*
23464 			 * Get IP set to checksum on our behalf
23465 			 * Include the adjustment for a source route if any.
23466 			 */
23467 			u1 += tcp->tcp_sum;
23468 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23469 			U16_TO_BE16(u1, tcph->th_sum);
23470 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23471 		}
23472 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23473 		    (seq + data_length) == tcp->tcp_fss) {
23474 			if (!tcp->tcp_fin_acked) {
23475 				flags |= TH_FIN;
23476 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23477 			}
23478 			if (!tcp->tcp_fin_sent) {
23479 				tcp->tcp_fin_sent = B_TRUE;
23480 				switch (tcp->tcp_state) {
23481 				case TCPS_SYN_RCVD:
23482 				case TCPS_ESTABLISHED:
23483 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23484 					break;
23485 				case TCPS_CLOSE_WAIT:
23486 					tcp->tcp_state = TCPS_LAST_ACK;
23487 					break;
23488 				}
23489 				if (tcp->tcp_suna == tcp->tcp_snxt)
23490 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23491 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23492 			}
23493 		}
23494 		/*
23495 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23496 		 * is smaller than seq, u1 will become a very huge value.
23497 		 * So the comparison will fail.  Also note that tcp_urp
23498 		 * should be positive, see RFC 793 page 17.
23499 		 */
23500 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23501 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23502 		    u1 < (uint32_t)(64 * 1024)) {
23503 			flags |= TH_URG;
23504 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23505 			U32_TO_ABE16(u1, tcph->th_urp);
23506 		}
23507 	}
23508 	tcph->th_flags[0] = (uchar_t)flags;
23509 	tcp->tcp_rack = tcp->tcp_rnxt;
23510 	tcp->tcp_rack_cnt = 0;
23511 
23512 	if (tcp->tcp_snd_ts_ok) {
23513 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23514 			uint32_t llbolt = (uint32_t)lbolt;
23515 
23516 			U32_TO_BE32(llbolt,
23517 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23518 			U32_TO_BE32(tcp->tcp_ts_recent,
23519 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23520 		}
23521 	}
23522 
23523 	if (num_sack_blk > 0) {
23524 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23525 		sack_blk_t *tmp;
23526 		int32_t	i;
23527 
23528 		wptr[0] = TCPOPT_NOP;
23529 		wptr[1] = TCPOPT_NOP;
23530 		wptr[2] = TCPOPT_SACK;
23531 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23532 		    sizeof (sack_blk_t);
23533 		wptr += TCPOPT_REAL_SACK_LEN;
23534 
23535 		tmp = tcp->tcp_sack_list;
23536 		for (i = 0; i < num_sack_blk; i++) {
23537 			U32_TO_BE32(tmp[i].begin, wptr);
23538 			wptr += sizeof (tcp_seq);
23539 			U32_TO_BE32(tmp[i].end, wptr);
23540 			wptr += sizeof (tcp_seq);
23541 		}
23542 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23543 	}
23544 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23545 	data_length += (int)(mp1->b_wptr - rptr);
23546 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23547 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23548 	} else {
23549 		ip6_t *ip6 = (ip6_t *)(rptr +
23550 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23551 		    sizeof (ip6i_t) : 0));
23552 
23553 		ip6->ip6_plen = htons(data_length -
23554 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23555 	}
23556 
23557 	/*
23558 	 * Prime pump for IP
23559 	 * Include the adjustment for a source route if any.
23560 	 */
23561 	data_length -= tcp->tcp_ip_hdr_len;
23562 	data_length += tcp->tcp_sum;
23563 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23564 	U16_TO_ABE16(data_length, tcph->th_sum);
23565 	if (tcp->tcp_ip_forward_progress) {
23566 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23567 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23568 		tcp->tcp_ip_forward_progress = B_FALSE;
23569 	}
23570 	return (mp1);
23571 }
23572 
23573 /* This function handles the push timeout. */
23574 void
23575 tcp_push_timer(void *arg)
23576 {
23577 	conn_t	*connp = (conn_t *)arg;
23578 	tcp_t *tcp = connp->conn_tcp;
23579 	uint_t		flags;
23580 	sodirect_t	*sodp;
23581 
23582 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
23583 
23584 	ASSERT(tcp->tcp_listener == NULL);
23585 
23586 	ASSERT(!IPCL_IS_NONSTR(connp));
23587 
23588 	/*
23589 	 * We need to plug synchronous streams during our drain to prevent
23590 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23591 	 */
23592 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23593 	tcp->tcp_push_tid = 0;
23594 
23595 	SOD_PTR_ENTER(tcp, sodp);
23596 	if (sodp != NULL) {
23597 		flags = tcp_rcv_sod_wakeup(tcp, sodp);
23598 		/* sod_wakeup() does the mutex_exit() */
23599 	} else if (tcp->tcp_rcv_list != NULL) {
23600 		flags = tcp_rcv_drain(tcp);
23601 	}
23602 	if (flags == TH_ACK_NEEDED)
23603 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23604 
23605 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23606 }
23607 
23608 /*
23609  * This function handles delayed ACK timeout.
23610  */
23611 static void
23612 tcp_ack_timer(void *arg)
23613 {
23614 	conn_t	*connp = (conn_t *)arg;
23615 	tcp_t *tcp = connp->conn_tcp;
23616 	mblk_t *mp;
23617 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23618 
23619 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23620 
23621 	tcp->tcp_ack_tid = 0;
23622 
23623 	if (tcp->tcp_fused)
23624 		return;
23625 
23626 	/*
23627 	 * Do not send ACK if there is no outstanding unack'ed data.
23628 	 */
23629 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23630 		return;
23631 	}
23632 
23633 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23634 		/*
23635 		 * Make sure we don't allow deferred ACKs to result in
23636 		 * timer-based ACKing.  If we have held off an ACK
23637 		 * when there was more than an mss here, and the timer
23638 		 * goes off, we have to worry about the possibility
23639 		 * that the sender isn't doing slow-start, or is out
23640 		 * of step with us for some other reason.  We fall
23641 		 * permanently back in the direction of
23642 		 * ACK-every-other-packet as suggested in RFC 1122.
23643 		 */
23644 		if (tcp->tcp_rack_abs_max > 2)
23645 			tcp->tcp_rack_abs_max--;
23646 		tcp->tcp_rack_cur_max = 2;
23647 	}
23648 	mp = tcp_ack_mp(tcp);
23649 
23650 	if (mp != NULL) {
23651 		BUMP_LOCAL(tcp->tcp_obsegs);
23652 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23653 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23654 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23655 	}
23656 }
23657 
23658 
23659 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23660 static mblk_t *
23661 tcp_ack_mp(tcp_t *tcp)
23662 {
23663 	uint32_t	seq_no;
23664 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23665 
23666 	/*
23667 	 * There are a few cases to be considered while setting the sequence no.
23668 	 * Essentially, we can come here while processing an unacceptable pkt
23669 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23670 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23671 	 * If we are here for a zero window probe, stick with suna. In all
23672 	 * other cases, we check if suna + swnd encompasses snxt and set
23673 	 * the sequence number to snxt, if so. If snxt falls outside the
23674 	 * window (the receiver probably shrunk its window), we will go with
23675 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23676 	 * receiver.
23677 	 */
23678 	if (tcp->tcp_zero_win_probe) {
23679 		seq_no = tcp->tcp_suna;
23680 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23681 		ASSERT(tcp->tcp_swnd == 0);
23682 		seq_no = tcp->tcp_snxt;
23683 	} else {
23684 		seq_no = SEQ_GT(tcp->tcp_snxt,
23685 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23686 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23687 	}
23688 
23689 	if (tcp->tcp_valid_bits) {
23690 		/*
23691 		 * For the complex case where we have to send some
23692 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23693 		 */
23694 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23695 		    NULL, B_FALSE));
23696 	} else {
23697 		/* Generate a simple ACK */
23698 		int	data_length;
23699 		uchar_t	*rptr;
23700 		tcph_t	*tcph;
23701 		mblk_t	*mp1;
23702 		int32_t	tcp_hdr_len;
23703 		int32_t	tcp_tcp_hdr_len;
23704 		int32_t	num_sack_blk = 0;
23705 		int32_t sack_opt_len;
23706 
23707 		/*
23708 		 * Allocate space for TCP + IP headers
23709 		 * and link-level header
23710 		 */
23711 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23712 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23713 			    tcp->tcp_num_sack_blk);
23714 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23715 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23716 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23717 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23718 		} else {
23719 			tcp_hdr_len = tcp->tcp_hdr_len;
23720 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23721 		}
23722 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23723 		if (!mp1)
23724 			return (NULL);
23725 
23726 		/* Update the latest receive window size in TCP header. */
23727 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23728 		    tcp->tcp_tcph->th_win);
23729 		/* copy in prototype TCP + IP header */
23730 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23731 		mp1->b_rptr = rptr;
23732 		mp1->b_wptr = rptr + tcp_hdr_len;
23733 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23734 
23735 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23736 
23737 		/* Set the TCP sequence number. */
23738 		U32_TO_ABE32(seq_no, tcph->th_seq);
23739 
23740 		/* Set up the TCP flag field. */
23741 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23742 		if (tcp->tcp_ecn_echo_on)
23743 			tcph->th_flags[0] |= TH_ECE;
23744 
23745 		tcp->tcp_rack = tcp->tcp_rnxt;
23746 		tcp->tcp_rack_cnt = 0;
23747 
23748 		/* fill in timestamp option if in use */
23749 		if (tcp->tcp_snd_ts_ok) {
23750 			uint32_t llbolt = (uint32_t)lbolt;
23751 
23752 			U32_TO_BE32(llbolt,
23753 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23754 			U32_TO_BE32(tcp->tcp_ts_recent,
23755 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23756 		}
23757 
23758 		/* Fill in SACK options */
23759 		if (num_sack_blk > 0) {
23760 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23761 			sack_blk_t *tmp;
23762 			int32_t	i;
23763 
23764 			wptr[0] = TCPOPT_NOP;
23765 			wptr[1] = TCPOPT_NOP;
23766 			wptr[2] = TCPOPT_SACK;
23767 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23768 			    sizeof (sack_blk_t);
23769 			wptr += TCPOPT_REAL_SACK_LEN;
23770 
23771 			tmp = tcp->tcp_sack_list;
23772 			for (i = 0; i < num_sack_blk; i++) {
23773 				U32_TO_BE32(tmp[i].begin, wptr);
23774 				wptr += sizeof (tcp_seq);
23775 				U32_TO_BE32(tmp[i].end, wptr);
23776 				wptr += sizeof (tcp_seq);
23777 			}
23778 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23779 			    << 4);
23780 		}
23781 
23782 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23783 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23784 		} else {
23785 			/* Check for ip6i_t header in sticky hdrs */
23786 			ip6_t *ip6 = (ip6_t *)(rptr +
23787 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23788 			    sizeof (ip6i_t) : 0));
23789 
23790 			ip6->ip6_plen = htons(tcp_hdr_len -
23791 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23792 		}
23793 
23794 		/*
23795 		 * Prime pump for checksum calculation in IP.  Include the
23796 		 * adjustment for a source route if any.
23797 		 */
23798 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23799 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23800 		U16_TO_ABE16(data_length, tcph->th_sum);
23801 
23802 		if (tcp->tcp_ip_forward_progress) {
23803 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23804 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23805 			tcp->tcp_ip_forward_progress = B_FALSE;
23806 		}
23807 		return (mp1);
23808 	}
23809 }
23810 
23811 /*
23812  * Hash list insertion routine for tcp_t structures. Each hash bucket
23813  * contains a list of tcp_t entries, and each entry is bound to a unique
23814  * port. If there are multiple tcp_t's that are bound to the same port, then
23815  * one of them will be linked into the hash bucket list, and the rest will
23816  * hang off of that one entry. For each port, entries bound to a specific IP
23817  * address will be inserted before those those bound to INADDR_ANY.
23818  */
23819 static void
23820 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23821 {
23822 	tcp_t	**tcpp;
23823 	tcp_t	*tcpnext;
23824 	tcp_t	*tcphash;
23825 
23826 	if (tcp->tcp_ptpbhn != NULL) {
23827 		ASSERT(!caller_holds_lock);
23828 		tcp_bind_hash_remove(tcp);
23829 	}
23830 	tcpp = &tbf->tf_tcp;
23831 	if (!caller_holds_lock) {
23832 		mutex_enter(&tbf->tf_lock);
23833 	} else {
23834 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23835 	}
23836 	tcphash = tcpp[0];
23837 	tcpnext = NULL;
23838 	if (tcphash != NULL) {
23839 		/* Look for an entry using the same port */
23840 		while ((tcphash = tcpp[0]) != NULL &&
23841 		    tcp->tcp_lport != tcphash->tcp_lport)
23842 			tcpp = &(tcphash->tcp_bind_hash);
23843 
23844 		/* The port was not found, just add to the end */
23845 		if (tcphash == NULL)
23846 			goto insert;
23847 
23848 		/*
23849 		 * OK, there already exists an entry bound to the
23850 		 * same port.
23851 		 *
23852 		 * If the new tcp bound to the INADDR_ANY address
23853 		 * and the first one in the list is not bound to
23854 		 * INADDR_ANY we skip all entries until we find the
23855 		 * first one bound to INADDR_ANY.
23856 		 * This makes sure that applications binding to a
23857 		 * specific address get preference over those binding to
23858 		 * INADDR_ANY.
23859 		 */
23860 		tcpnext = tcphash;
23861 		tcphash = NULL;
23862 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23863 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23864 			while ((tcpnext = tcpp[0]) != NULL &&
23865 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23866 				tcpp = &(tcpnext->tcp_bind_hash_port);
23867 
23868 			if (tcpnext) {
23869 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23870 				tcphash = tcpnext->tcp_bind_hash;
23871 				if (tcphash != NULL) {
23872 					tcphash->tcp_ptpbhn =
23873 					    &(tcp->tcp_bind_hash);
23874 					tcpnext->tcp_bind_hash = NULL;
23875 				}
23876 			}
23877 		} else {
23878 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23879 			tcphash = tcpnext->tcp_bind_hash;
23880 			if (tcphash != NULL) {
23881 				tcphash->tcp_ptpbhn =
23882 				    &(tcp->tcp_bind_hash);
23883 				tcpnext->tcp_bind_hash = NULL;
23884 			}
23885 		}
23886 	}
23887 insert:
23888 	tcp->tcp_bind_hash_port = tcpnext;
23889 	tcp->tcp_bind_hash = tcphash;
23890 	tcp->tcp_ptpbhn = tcpp;
23891 	tcpp[0] = tcp;
23892 	if (!caller_holds_lock)
23893 		mutex_exit(&tbf->tf_lock);
23894 }
23895 
23896 /*
23897  * Hash list removal routine for tcp_t structures.
23898  */
23899 static void
23900 tcp_bind_hash_remove(tcp_t *tcp)
23901 {
23902 	tcp_t	*tcpnext;
23903 	kmutex_t *lockp;
23904 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23905 
23906 	if (tcp->tcp_ptpbhn == NULL)
23907 		return;
23908 
23909 	/*
23910 	 * Extract the lock pointer in case there are concurrent
23911 	 * hash_remove's for this instance.
23912 	 */
23913 	ASSERT(tcp->tcp_lport != 0);
23914 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23915 
23916 	ASSERT(lockp != NULL);
23917 	mutex_enter(lockp);
23918 	if (tcp->tcp_ptpbhn) {
23919 		tcpnext = tcp->tcp_bind_hash_port;
23920 		if (tcpnext != NULL) {
23921 			tcp->tcp_bind_hash_port = NULL;
23922 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23923 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
23924 			if (tcpnext->tcp_bind_hash != NULL) {
23925 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
23926 				    &(tcpnext->tcp_bind_hash);
23927 				tcp->tcp_bind_hash = NULL;
23928 			}
23929 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
23930 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23931 			tcp->tcp_bind_hash = NULL;
23932 		}
23933 		*tcp->tcp_ptpbhn = tcpnext;
23934 		tcp->tcp_ptpbhn = NULL;
23935 	}
23936 	mutex_exit(lockp);
23937 }
23938 
23939 
23940 /*
23941  * Hash list lookup routine for tcp_t structures.
23942  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23943  */
23944 static tcp_t *
23945 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23946 {
23947 	tf_t	*tf;
23948 	tcp_t	*tcp;
23949 
23950 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23951 	mutex_enter(&tf->tf_lock);
23952 	for (tcp = tf->tf_tcp; tcp != NULL;
23953 	    tcp = tcp->tcp_acceptor_hash) {
23954 		if (tcp->tcp_acceptor_id == id) {
23955 			CONN_INC_REF(tcp->tcp_connp);
23956 			mutex_exit(&tf->tf_lock);
23957 			return (tcp);
23958 		}
23959 	}
23960 	mutex_exit(&tf->tf_lock);
23961 	return (NULL);
23962 }
23963 
23964 
23965 /*
23966  * Hash list insertion routine for tcp_t structures.
23967  */
23968 void
23969 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23970 {
23971 	tf_t	*tf;
23972 	tcp_t	**tcpp;
23973 	tcp_t	*tcpnext;
23974 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23975 
23976 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23977 
23978 	if (tcp->tcp_ptpahn != NULL)
23979 		tcp_acceptor_hash_remove(tcp);
23980 	tcpp = &tf->tf_tcp;
23981 	mutex_enter(&tf->tf_lock);
23982 	tcpnext = tcpp[0];
23983 	if (tcpnext)
23984 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23985 	tcp->tcp_acceptor_hash = tcpnext;
23986 	tcp->tcp_ptpahn = tcpp;
23987 	tcpp[0] = tcp;
23988 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23989 	mutex_exit(&tf->tf_lock);
23990 }
23991 
23992 /*
23993  * Hash list removal routine for tcp_t structures.
23994  */
23995 static void
23996 tcp_acceptor_hash_remove(tcp_t *tcp)
23997 {
23998 	tcp_t	*tcpnext;
23999 	kmutex_t *lockp;
24000 
24001 	/*
24002 	 * Extract the lock pointer in case there are concurrent
24003 	 * hash_remove's for this instance.
24004 	 */
24005 	lockp = tcp->tcp_acceptor_lockp;
24006 
24007 	if (tcp->tcp_ptpahn == NULL)
24008 		return;
24009 
24010 	ASSERT(lockp != NULL);
24011 	mutex_enter(lockp);
24012 	if (tcp->tcp_ptpahn) {
24013 		tcpnext = tcp->tcp_acceptor_hash;
24014 		if (tcpnext) {
24015 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
24016 			tcp->tcp_acceptor_hash = NULL;
24017 		}
24018 		*tcp->tcp_ptpahn = tcpnext;
24019 		tcp->tcp_ptpahn = NULL;
24020 	}
24021 	mutex_exit(lockp);
24022 	tcp->tcp_acceptor_lockp = NULL;
24023 }
24024 
24025 /* Data for fast netmask macro used by tcp_hsp_lookup */
24026 
24027 static ipaddr_t netmasks[] = {
24028 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24029 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24030 };
24031 
24032 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24033 
24034 /*
24035  * XXX This routine should go away and instead we should use the metrics
24036  * associated with the routes to determine the default sndspace and rcvspace.
24037  */
24038 static tcp_hsp_t *
24039 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24040 {
24041 	tcp_hsp_t *hsp = NULL;
24042 
24043 	/* Quick check without acquiring the lock. */
24044 	if (tcps->tcps_hsp_hash == NULL)
24045 		return (NULL);
24046 
24047 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24048 
24049 	/* This routine finds the best-matching HSP for address addr. */
24050 
24051 	if (tcps->tcps_hsp_hash) {
24052 		int i;
24053 		ipaddr_t srchaddr;
24054 		tcp_hsp_t *hsp_net;
24055 
24056 		/* We do three passes: host, network, and subnet. */
24057 
24058 		srchaddr = addr;
24059 
24060 		for (i = 1; i <= 3; i++) {
24061 			/* Look for exact match on srchaddr */
24062 
24063 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24064 			while (hsp) {
24065 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24066 				    hsp->tcp_hsp_addr == srchaddr)
24067 					break;
24068 				hsp = hsp->tcp_hsp_next;
24069 			}
24070 			ASSERT(hsp == NULL ||
24071 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24072 
24073 			/*
24074 			 * If this is the first pass:
24075 			 *   If we found a match, great, return it.
24076 			 *   If not, search for the network on the second pass.
24077 			 */
24078 
24079 			if (i == 1)
24080 				if (hsp)
24081 					break;
24082 				else
24083 				{
24084 					srchaddr = addr & netmask(addr);
24085 					continue;
24086 				}
24087 
24088 			/*
24089 			 * If this is the second pass:
24090 			 *   If we found a match, but there's a subnet mask,
24091 			 *    save the match but try again using the subnet
24092 			 *    mask on the third pass.
24093 			 *   Otherwise, return whatever we found.
24094 			 */
24095 
24096 			if (i == 2) {
24097 				if (hsp && hsp->tcp_hsp_subnet) {
24098 					hsp_net = hsp;
24099 					srchaddr = addr & hsp->tcp_hsp_subnet;
24100 					continue;
24101 				} else {
24102 					break;
24103 				}
24104 			}
24105 
24106 			/*
24107 			 * This must be the third pass.  If we didn't find
24108 			 * anything, return the saved network HSP instead.
24109 			 */
24110 
24111 			if (!hsp)
24112 				hsp = hsp_net;
24113 		}
24114 	}
24115 
24116 	rw_exit(&tcps->tcps_hsp_lock);
24117 	return (hsp);
24118 }
24119 
24120 /*
24121  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24122  * match lookup.
24123  */
24124 static tcp_hsp_t *
24125 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
24126 {
24127 	tcp_hsp_t *hsp = NULL;
24128 
24129 	/* Quick check without acquiring the lock. */
24130 	if (tcps->tcps_hsp_hash == NULL)
24131 		return (NULL);
24132 
24133 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24134 
24135 	/* This routine finds the best-matching HSP for address addr. */
24136 
24137 	if (tcps->tcps_hsp_hash) {
24138 		int i;
24139 		in6_addr_t v6srchaddr;
24140 		tcp_hsp_t *hsp_net;
24141 
24142 		/* We do three passes: host, network, and subnet. */
24143 
24144 		v6srchaddr = *v6addr;
24145 
24146 		for (i = 1; i <= 3; i++) {
24147 			/* Look for exact match on srchaddr */
24148 
24149 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
24150 			    V4_PART_OF_V6(v6srchaddr))];
24151 			while (hsp) {
24152 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24153 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24154 				    &v6srchaddr))
24155 					break;
24156 				hsp = hsp->tcp_hsp_next;
24157 			}
24158 
24159 			/*
24160 			 * If this is the first pass:
24161 			 *   If we found a match, great, return it.
24162 			 *   If not, search for the network on the second pass.
24163 			 */
24164 
24165 			if (i == 1)
24166 				if (hsp)
24167 					break;
24168 				else {
24169 					/* Assume a 64 bit mask */
24170 					v6srchaddr.s6_addr32[0] =
24171 					    v6addr->s6_addr32[0];
24172 					v6srchaddr.s6_addr32[1] =
24173 					    v6addr->s6_addr32[1];
24174 					v6srchaddr.s6_addr32[2] = 0;
24175 					v6srchaddr.s6_addr32[3] = 0;
24176 					continue;
24177 				}
24178 
24179 			/*
24180 			 * If this is the second pass:
24181 			 *   If we found a match, but there's a subnet mask,
24182 			 *    save the match but try again using the subnet
24183 			 *    mask on the third pass.
24184 			 *   Otherwise, return whatever we found.
24185 			 */
24186 
24187 			if (i == 2) {
24188 				ASSERT(hsp == NULL ||
24189 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24190 				if (hsp &&
24191 				    !IN6_IS_ADDR_UNSPECIFIED(
24192 				    &hsp->tcp_hsp_subnet_v6)) {
24193 					hsp_net = hsp;
24194 					V6_MASK_COPY(*v6addr,
24195 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24196 					continue;
24197 				} else {
24198 					break;
24199 				}
24200 			}
24201 
24202 			/*
24203 			 * This must be the third pass.  If we didn't find
24204 			 * anything, return the saved network HSP instead.
24205 			 */
24206 
24207 			if (!hsp)
24208 				hsp = hsp_net;
24209 		}
24210 	}
24211 
24212 	rw_exit(&tcps->tcps_hsp_lock);
24213 	return (hsp);
24214 }
24215 
24216 /*
24217  * Type three generator adapted from the random() function in 4.4 BSD:
24218  */
24219 
24220 /*
24221  * Copyright (c) 1983, 1993
24222  *	The Regents of the University of California.  All rights reserved.
24223  *
24224  * Redistribution and use in source and binary forms, with or without
24225  * modification, are permitted provided that the following conditions
24226  * are met:
24227  * 1. Redistributions of source code must retain the above copyright
24228  *    notice, this list of conditions and the following disclaimer.
24229  * 2. Redistributions in binary form must reproduce the above copyright
24230  *    notice, this list of conditions and the following disclaimer in the
24231  *    documentation and/or other materials provided with the distribution.
24232  * 3. All advertising materials mentioning features or use of this software
24233  *    must display the following acknowledgement:
24234  *	This product includes software developed by the University of
24235  *	California, Berkeley and its contributors.
24236  * 4. Neither the name of the University nor the names of its contributors
24237  *    may be used to endorse or promote products derived from this software
24238  *    without specific prior written permission.
24239  *
24240  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24241  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24242  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24243  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24244  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24245  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24246  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24247  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24248  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24249  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24250  * SUCH DAMAGE.
24251  */
24252 
24253 /* Type 3 -- x**31 + x**3 + 1 */
24254 #define	DEG_3		31
24255 #define	SEP_3		3
24256 
24257 
24258 /* Protected by tcp_random_lock */
24259 static int tcp_randtbl[DEG_3 + 1];
24260 
24261 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24262 static int *tcp_random_rptr = &tcp_randtbl[1];
24263 
24264 static int *tcp_random_state = &tcp_randtbl[1];
24265 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24266 
24267 kmutex_t tcp_random_lock;
24268 
24269 void
24270 tcp_random_init(void)
24271 {
24272 	int i;
24273 	hrtime_t hrt;
24274 	time_t wallclock;
24275 	uint64_t result;
24276 
24277 	/*
24278 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24279 	 * a longlong, which may contain resolution down to nanoseconds.
24280 	 * The current time will either be a 32-bit or a 64-bit quantity.
24281 	 * XOR the two together in a 64-bit result variable.
24282 	 * Convert the result to a 32-bit value by multiplying the high-order
24283 	 * 32-bits by the low-order 32-bits.
24284 	 */
24285 
24286 	hrt = gethrtime();
24287 	(void) drv_getparm(TIME, &wallclock);
24288 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24289 	mutex_enter(&tcp_random_lock);
24290 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24291 	    (result & 0xffffffff);
24292 
24293 	for (i = 1; i < DEG_3; i++)
24294 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24295 		    + 12345;
24296 	tcp_random_fptr = &tcp_random_state[SEP_3];
24297 	tcp_random_rptr = &tcp_random_state[0];
24298 	mutex_exit(&tcp_random_lock);
24299 	for (i = 0; i < 10 * DEG_3; i++)
24300 		(void) tcp_random();
24301 }
24302 
24303 /*
24304  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24305  * This range is selected to be approximately centered on TCP_ISS / 2,
24306  * and easy to compute. We get this value by generating a 32-bit random
24307  * number, selecting out the high-order 17 bits, and then adding one so
24308  * that we never return zero.
24309  */
24310 int
24311 tcp_random(void)
24312 {
24313 	int i;
24314 
24315 	mutex_enter(&tcp_random_lock);
24316 	*tcp_random_fptr += *tcp_random_rptr;
24317 
24318 	/*
24319 	 * The high-order bits are more random than the low-order bits,
24320 	 * so we select out the high-order 17 bits and add one so that
24321 	 * we never return zero.
24322 	 */
24323 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24324 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24325 		tcp_random_fptr = tcp_random_state;
24326 		++tcp_random_rptr;
24327 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24328 		tcp_random_rptr = tcp_random_state;
24329 
24330 	mutex_exit(&tcp_random_lock);
24331 	return (i);
24332 }
24333 
24334 static int
24335 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24336     int *t_errorp, int *sys_errorp)
24337 {
24338 	int error;
24339 	int is_absreq_failure;
24340 	t_scalar_t *opt_lenp;
24341 	t_scalar_t opt_offset;
24342 	int prim_type;
24343 	struct T_conn_req *tcreqp;
24344 	struct T_conn_res *tcresp;
24345 	cred_t *cr;
24346 
24347 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
24348 
24349 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24350 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24351 	    prim_type == T_CONN_RES);
24352 
24353 	switch (prim_type) {
24354 	case T_CONN_REQ:
24355 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24356 		opt_offset = tcreqp->OPT_offset;
24357 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24358 		break;
24359 	case O_T_CONN_RES:
24360 	case T_CONN_RES:
24361 		tcresp = (struct T_conn_res *)mp->b_rptr;
24362 		opt_offset = tcresp->OPT_offset;
24363 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24364 		break;
24365 	}
24366 
24367 	*t_errorp = 0;
24368 	*sys_errorp = 0;
24369 	*do_disconnectp = 0;
24370 
24371 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24372 	    opt_offset, cr, &tcp_opt_obj,
24373 	    NULL, &is_absreq_failure);
24374 
24375 	switch (error) {
24376 	case  0:		/* no error */
24377 		ASSERT(is_absreq_failure == 0);
24378 		return (0);
24379 	case ENOPROTOOPT:
24380 		*t_errorp = TBADOPT;
24381 		break;
24382 	case EACCES:
24383 		*t_errorp = TACCES;
24384 		break;
24385 	default:
24386 		*t_errorp = TSYSERR; *sys_errorp = error;
24387 		break;
24388 	}
24389 	if (is_absreq_failure != 0) {
24390 		/*
24391 		 * The connection request should get the local ack
24392 		 * T_OK_ACK and then a T_DISCON_IND.
24393 		 */
24394 		*do_disconnectp = 1;
24395 	}
24396 	return (-1);
24397 }
24398 
24399 /*
24400  * Split this function out so that if the secret changes, I'm okay.
24401  *
24402  * Initialize the tcp_iss_cookie and tcp_iss_key.
24403  */
24404 
24405 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24406 
24407 static void
24408 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
24409 {
24410 	struct {
24411 		int32_t current_time;
24412 		uint32_t randnum;
24413 		uint16_t pad;
24414 		uint8_t ether[6];
24415 		uint8_t passwd[PASSWD_SIZE];
24416 	} tcp_iss_cookie;
24417 	time_t t;
24418 
24419 	/*
24420 	 * Start with the current absolute time.
24421 	 */
24422 	(void) drv_getparm(TIME, &t);
24423 	tcp_iss_cookie.current_time = t;
24424 
24425 	/*
24426 	 * XXX - Need a more random number per RFC 1750, not this crap.
24427 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24428 	 */
24429 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24430 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24431 
24432 	/*
24433 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24434 	 * as a good template.
24435 	 */
24436 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24437 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24438 
24439 	/*
24440 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24441 	 */
24442 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24443 
24444 	/*
24445 	 * See 4010593 if this section becomes a problem again,
24446 	 * but the local ethernet address is useful here.
24447 	 */
24448 	(void) localetheraddr(NULL,
24449 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24450 
24451 	/*
24452 	 * Hash 'em all together.  The MD5Final is called per-connection.
24453 	 */
24454 	mutex_enter(&tcps->tcps_iss_key_lock);
24455 	MD5Init(&tcps->tcps_iss_key);
24456 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
24457 	    sizeof (tcp_iss_cookie));
24458 	mutex_exit(&tcps->tcps_iss_key_lock);
24459 }
24460 
24461 /*
24462  * Set the RFC 1948 pass phrase
24463  */
24464 /* ARGSUSED */
24465 static int
24466 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24467     cred_t *cr)
24468 {
24469 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24470 
24471 	/*
24472 	 * Basically, value contains a new pass phrase.  Pass it along!
24473 	 */
24474 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
24475 	return (0);
24476 }
24477 
24478 /* ARGSUSED */
24479 static int
24480 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24481 {
24482 	bzero(buf, sizeof (tcp_sack_info_t));
24483 	return (0);
24484 }
24485 
24486 /* ARGSUSED */
24487 static int
24488 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24489 {
24490 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24491 	return (0);
24492 }
24493 
24494 /*
24495  * Make sure we wait until the default queue is setup, yet allow
24496  * tcp_g_q_create() to open a TCP stream.
24497  * We need to allow tcp_g_q_create() do do an open
24498  * of tcp, hence we compare curhread.
24499  * All others have to wait until the tcps_g_q has been
24500  * setup.
24501  */
24502 void
24503 tcp_g_q_setup(tcp_stack_t *tcps)
24504 {
24505 	mutex_enter(&tcps->tcps_g_q_lock);
24506 	if (tcps->tcps_g_q != NULL) {
24507 		mutex_exit(&tcps->tcps_g_q_lock);
24508 		return;
24509 	}
24510 	if (tcps->tcps_g_q_creator == NULL) {
24511 		/* This thread will set it up */
24512 		tcps->tcps_g_q_creator = curthread;
24513 		mutex_exit(&tcps->tcps_g_q_lock);
24514 		tcp_g_q_create(tcps);
24515 		mutex_enter(&tcps->tcps_g_q_lock);
24516 		ASSERT(tcps->tcps_g_q_creator == curthread);
24517 		tcps->tcps_g_q_creator = NULL;
24518 		cv_signal(&tcps->tcps_g_q_cv);
24519 		ASSERT(tcps->tcps_g_q != NULL);
24520 		mutex_exit(&tcps->tcps_g_q_lock);
24521 		return;
24522 	}
24523 	/* Everybody but the creator has to wait */
24524 	if (tcps->tcps_g_q_creator != curthread) {
24525 		while (tcps->tcps_g_q == NULL)
24526 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24527 	}
24528 	mutex_exit(&tcps->tcps_g_q_lock);
24529 }
24530 
24531 #define	IP	"ip"
24532 
24533 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24534 
24535 /*
24536  * Create a default tcp queue here instead of in strplumb
24537  */
24538 void
24539 tcp_g_q_create(tcp_stack_t *tcps)
24540 {
24541 	int error;
24542 	ldi_handle_t	lh = NULL;
24543 	ldi_ident_t	li = NULL;
24544 	int		rval;
24545 	cred_t		*cr;
24546 	major_t IP_MAJ;
24547 
24548 #ifdef NS_DEBUG
24549 	(void) printf("tcp_g_q_create()\n");
24550 #endif
24551 
24552 	IP_MAJ = ddi_name_to_major(IP);
24553 
24554 	ASSERT(tcps->tcps_g_q_creator == curthread);
24555 
24556 	error = ldi_ident_from_major(IP_MAJ, &li);
24557 	if (error) {
24558 #ifdef DEBUG
24559 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24560 		    error);
24561 #endif
24562 		return;
24563 	}
24564 
24565 	cr = zone_get_kcred(netstackid_to_zoneid(
24566 	    tcps->tcps_netstack->netstack_stackid));
24567 	ASSERT(cr != NULL);
24568 	/*
24569 	 * We set the tcp default queue to IPv6 because IPv4 falls
24570 	 * back to IPv6 when it can't find a client, but
24571 	 * IPv6 does not fall back to IPv4.
24572 	 */
24573 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24574 	if (error) {
24575 #ifdef DEBUG
24576 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24577 		    error);
24578 #endif
24579 		goto out;
24580 	}
24581 
24582 	/*
24583 	 * This ioctl causes the tcp framework to cache a pointer to
24584 	 * this stream, so we don't want to close the stream after
24585 	 * this operation.
24586 	 * Use the kernel credentials that are for the zone we're in.
24587 	 */
24588 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24589 	    (intptr_t)0, FKIOCTL, cr, &rval);
24590 	if (error) {
24591 #ifdef DEBUG
24592 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24593 		    "error %d\n", error);
24594 #endif
24595 		goto out;
24596 	}
24597 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24598 	lh = NULL;
24599 out:
24600 	/* Close layered handles */
24601 	if (li)
24602 		ldi_ident_release(li);
24603 	/* Keep cred around until _inactive needs it */
24604 	tcps->tcps_g_q_cr = cr;
24605 }
24606 
24607 /*
24608  * We keep tcp_g_q set until all other tcp_t's in the zone
24609  * has gone away, and then when tcp_g_q_inactive() is called
24610  * we clear it.
24611  */
24612 void
24613 tcp_g_q_destroy(tcp_stack_t *tcps)
24614 {
24615 #ifdef NS_DEBUG
24616 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24617 	    tcps->tcps_netstack->netstack_stackid);
24618 #endif
24619 
24620 	if (tcps->tcps_g_q == NULL) {
24621 		return;	/* Nothing to cleanup */
24622 	}
24623 	/*
24624 	 * Drop reference corresponding to the default queue.
24625 	 * This reference was added from tcp_open when the default queue
24626 	 * was created, hence we compensate for this extra drop in
24627 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24628 	 * the default queue was the last one to be open, in which
24629 	 * case, then tcp_g_q_inactive will be
24630 	 * called as a result of the refrele.
24631 	 */
24632 	TCPS_REFRELE(tcps);
24633 }
24634 
24635 /*
24636  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24637  * Run by tcp_q_q_inactive using a taskq.
24638  */
24639 static void
24640 tcp_g_q_close(void *arg)
24641 {
24642 	tcp_stack_t *tcps = arg;
24643 	int error;
24644 	ldi_handle_t	lh = NULL;
24645 	ldi_ident_t	li = NULL;
24646 	cred_t		*cr;
24647 	major_t IP_MAJ;
24648 
24649 	IP_MAJ = ddi_name_to_major(IP);
24650 
24651 #ifdef NS_DEBUG
24652 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24653 	    tcps->tcps_netstack->netstack_stackid,
24654 	    tcps->tcps_netstack->netstack_refcnt);
24655 #endif
24656 	lh = tcps->tcps_g_q_lh;
24657 	if (lh == NULL)
24658 		return;	/* Nothing to cleanup */
24659 
24660 	ASSERT(tcps->tcps_refcnt == 1);
24661 	ASSERT(tcps->tcps_g_q != NULL);
24662 
24663 	error = ldi_ident_from_major(IP_MAJ, &li);
24664 	if (error) {
24665 #ifdef DEBUG
24666 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
24667 		    error);
24668 #endif
24669 		return;
24670 	}
24671 
24672 	cr = tcps->tcps_g_q_cr;
24673 	tcps->tcps_g_q_cr = NULL;
24674 	ASSERT(cr != NULL);
24675 
24676 	/*
24677 	 * Make sure we can break the recursion when tcp_close decrements
24678 	 * the reference count causing g_q_inactive to be called again.
24679 	 */
24680 	tcps->tcps_g_q_lh = NULL;
24681 
24682 	/* close the default queue */
24683 	(void) ldi_close(lh, FREAD|FWRITE, cr);
24684 	/*
24685 	 * At this point in time tcps and the rest of netstack_t might
24686 	 * have been deleted.
24687 	 */
24688 	tcps = NULL;
24689 
24690 	/* Close layered handles */
24691 	ldi_ident_release(li);
24692 	crfree(cr);
24693 }
24694 
24695 /*
24696  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24697  *
24698  * Have to ensure that the ldi routines are not used by an
24699  * interrupt thread by using a taskq.
24700  */
24701 void
24702 tcp_g_q_inactive(tcp_stack_t *tcps)
24703 {
24704 	if (tcps->tcps_g_q_lh == NULL)
24705 		return;	/* Nothing to cleanup */
24706 
24707 	ASSERT(tcps->tcps_refcnt == 0);
24708 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
24709 
24710 	if (servicing_interrupt()) {
24711 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
24712 		    (void *) tcps, TQ_SLEEP);
24713 	} else {
24714 		tcp_g_q_close(tcps);
24715 	}
24716 }
24717 
24718 /*
24719  * Called by IP when IP is loaded into the kernel
24720  */
24721 void
24722 tcp_ddi_g_init(void)
24723 {
24724 	tcp_timercache = kmem_cache_create("tcp_timercache",
24725 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24726 	    NULL, NULL, NULL, NULL, NULL, 0);
24727 
24728 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24729 	    sizeof (tcp_sack_info_t), 0,
24730 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24731 
24732 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24733 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24734 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24735 
24736 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24737 
24738 	/* Initialize the random number generator */
24739 	tcp_random_init();
24740 
24741 	/* A single callback independently of how many netstacks we have */
24742 	ip_squeue_init(tcp_squeue_add);
24743 
24744 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
24745 
24746 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
24747 	    TASKQ_PREPOPULATE);
24748 
24749 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
24750 
24751 	/*
24752 	 * We want to be informed each time a stack is created or
24753 	 * destroyed in the kernel, so we can maintain the
24754 	 * set of tcp_stack_t's.
24755 	 */
24756 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
24757 	    tcp_stack_fini);
24758 }
24759 
24760 
24761 #define	INET_NAME	"ip"
24762 
24763 /*
24764  * Initialize the TCP stack instance.
24765  */
24766 static void *
24767 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
24768 {
24769 	tcp_stack_t	*tcps;
24770 	tcpparam_t	*pa;
24771 	int		i;
24772 	int		error = 0;
24773 	major_t		major;
24774 
24775 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
24776 	tcps->tcps_netstack = ns;
24777 
24778 	/* Initialize locks */
24779 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
24780 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24781 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
24782 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24783 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24784 
24785 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
24786 	tcps->tcps_g_epriv_ports[0] = 2049;
24787 	tcps->tcps_g_epriv_ports[1] = 4045;
24788 	tcps->tcps_min_anonpriv_port = 512;
24789 
24790 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
24791 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
24792 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
24793 	    TCP_FANOUT_SIZE, KM_SLEEP);
24794 
24795 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24796 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
24797 		    MUTEX_DEFAULT, NULL);
24798 	}
24799 
24800 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24801 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
24802 		    MUTEX_DEFAULT, NULL);
24803 	}
24804 
24805 	/* TCP's IPsec code calls the packet dropper. */
24806 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
24807 
24808 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
24809 	tcps->tcps_params = pa;
24810 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24811 
24812 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
24813 	    A_CNT(lcl_tcp_param_arr), tcps);
24814 
24815 	/*
24816 	 * Note: To really walk the device tree you need the devinfo
24817 	 * pointer to your device which is only available after probe/attach.
24818 	 * The following is safe only because it uses ddi_root_node()
24819 	 */
24820 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24821 	    tcp_opt_obj.odb_opt_arr_cnt);
24822 
24823 	/*
24824 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24825 	 * by the boot scripts.
24826 	 *
24827 	 * Use NULL name, as the name is caught by the new lockstats.
24828 	 *
24829 	 * Initialize with some random, non-guessable string, like the global
24830 	 * T_INFO_ACK.
24831 	 */
24832 
24833 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24834 	    sizeof (tcp_g_t_info_ack), tcps);
24835 
24836 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
24837 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
24838 
24839 	major = mod_name_to_major(INET_NAME);
24840 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
24841 	ASSERT(error == 0);
24842 	return (tcps);
24843 }
24844 
24845 /*
24846  * Called when the IP module is about to be unloaded.
24847  */
24848 void
24849 tcp_ddi_g_destroy(void)
24850 {
24851 	tcp_g_kstat_fini(tcp_g_kstat);
24852 	tcp_g_kstat = NULL;
24853 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
24854 
24855 	mutex_destroy(&tcp_random_lock);
24856 
24857 	kmem_cache_destroy(tcp_timercache);
24858 	kmem_cache_destroy(tcp_sack_info_cache);
24859 	kmem_cache_destroy(tcp_iphc_cache);
24860 
24861 	netstack_unregister(NS_TCP);
24862 	taskq_destroy(tcp_taskq);
24863 }
24864 
24865 /*
24866  * Shut down the TCP stack instance.
24867  */
24868 /* ARGSUSED */
24869 static void
24870 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24871 {
24872 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24873 
24874 	tcp_g_q_destroy(tcps);
24875 }
24876 
24877 /*
24878  * Free the TCP stack instance.
24879  */
24880 static void
24881 tcp_stack_fini(netstackid_t stackid, void *arg)
24882 {
24883 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24884 	int i;
24885 
24886 	nd_free(&tcps->tcps_g_nd);
24887 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24888 	tcps->tcps_params = NULL;
24889 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24890 	tcps->tcps_wroff_xtra_param = NULL;
24891 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24892 	tcps->tcps_mdt_head_param = NULL;
24893 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24894 	tcps->tcps_mdt_tail_param = NULL;
24895 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24896 	tcps->tcps_mdt_max_pbufs_param = NULL;
24897 
24898 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24899 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24900 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24901 	}
24902 
24903 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24904 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
24905 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
24906 	}
24907 
24908 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
24909 	tcps->tcps_bind_fanout = NULL;
24910 
24911 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
24912 	tcps->tcps_acceptor_fanout = NULL;
24913 
24914 	mutex_destroy(&tcps->tcps_iss_key_lock);
24915 	rw_destroy(&tcps->tcps_hsp_lock);
24916 	mutex_destroy(&tcps->tcps_g_q_lock);
24917 	cv_destroy(&tcps->tcps_g_q_cv);
24918 	mutex_destroy(&tcps->tcps_epriv_port_lock);
24919 
24920 	ip_drop_unregister(&tcps->tcps_dropper);
24921 
24922 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
24923 	tcps->tcps_kstat = NULL;
24924 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
24925 
24926 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
24927 	tcps->tcps_mibkp = NULL;
24928 
24929 	ldi_ident_release(tcps->tcps_ldi_ident);
24930 	kmem_free(tcps, sizeof (*tcps));
24931 }
24932 
24933 /*
24934  * Generate ISS, taking into account NDD changes may happen halfway through.
24935  * (If the iss is not zero, set it.)
24936  */
24937 
24938 static void
24939 tcp_iss_init(tcp_t *tcp)
24940 {
24941 	MD5_CTX context;
24942 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24943 	uint32_t answer[4];
24944 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24945 
24946 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
24947 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
24948 	switch (tcps->tcps_strong_iss) {
24949 	case 2:
24950 		mutex_enter(&tcps->tcps_iss_key_lock);
24951 		context = tcps->tcps_iss_key;
24952 		mutex_exit(&tcps->tcps_iss_key_lock);
24953 		arg.ports = tcp->tcp_ports;
24954 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24955 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24956 			    &arg.src);
24957 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24958 			    &arg.dst);
24959 		} else {
24960 			arg.src = tcp->tcp_ip6h->ip6_src;
24961 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24962 		}
24963 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24964 		MD5Final((uchar_t *)answer, &context);
24965 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24966 		/*
24967 		 * Now that we've hashed into a unique per-connection sequence
24968 		 * space, add a random increment per strong_iss == 1.  So I
24969 		 * guess we'll have to...
24970 		 */
24971 		/* FALLTHRU */
24972 	case 1:
24973 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24974 		break;
24975 	default:
24976 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24977 		break;
24978 	}
24979 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24980 	tcp->tcp_fss = tcp->tcp_iss - 1;
24981 	tcp->tcp_suna = tcp->tcp_iss;
24982 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24983 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24984 	tcp->tcp_csuna = tcp->tcp_snxt;
24985 }
24986 
24987 /*
24988  * Exported routine for extracting active tcp connection status.
24989  *
24990  * This is used by the Solaris Cluster Networking software to
24991  * gather a list of connections that need to be forwarded to
24992  * specific nodes in the cluster when configuration changes occur.
24993  *
24994  * The callback is invoked for each tcp_t structure from all netstacks,
24995  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
24996  * from the netstack with the specified stack_id. Returning
24997  * non-zero from the callback routine terminates the search.
24998  */
24999 int
25000 cl_tcp_walk_list(netstackid_t stack_id,
25001     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
25002 {
25003 	netstack_handle_t nh;
25004 	netstack_t *ns;
25005 	int ret = 0;
25006 
25007 	if (stack_id >= 0) {
25008 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
25009 			return (EINVAL);
25010 
25011 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25012 		    ns->netstack_tcp);
25013 		netstack_rele(ns);
25014 		return (ret);
25015 	}
25016 
25017 	netstack_next_init(&nh);
25018 	while ((ns = netstack_next(&nh)) != NULL) {
25019 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25020 		    ns->netstack_tcp);
25021 		netstack_rele(ns);
25022 	}
25023 	netstack_next_fini(&nh);
25024 	return (ret);
25025 }
25026 
25027 static int
25028 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25029     tcp_stack_t *tcps)
25030 {
25031 	tcp_t *tcp;
25032 	cl_tcp_info_t	cl_tcpi;
25033 	connf_t	*connfp;
25034 	conn_t	*connp;
25035 	int	i;
25036 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25037 
25038 	ASSERT(callback != NULL);
25039 
25040 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25041 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25042 		connp = NULL;
25043 
25044 		while ((connp =
25045 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25046 
25047 			tcp = connp->conn_tcp;
25048 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
25049 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
25050 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
25051 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
25052 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
25053 			/*
25054 			 * The macros tcp_laddr and tcp_faddr give the IPv4
25055 			 * addresses. They are copied implicitly below as
25056 			 * mapped addresses.
25057 			 */
25058 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
25059 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25060 				cl_tcpi.cl_tcpi_faddr =
25061 				    tcp->tcp_ipha->ipha_dst;
25062 			} else {
25063 				cl_tcpi.cl_tcpi_faddr_v6 =
25064 				    tcp->tcp_ip6h->ip6_dst;
25065 			}
25066 
25067 			/*
25068 			 * If the callback returns non-zero
25069 			 * we terminate the traversal.
25070 			 */
25071 			if ((*callback)(&cl_tcpi, arg) != 0) {
25072 				CONN_DEC_REF(tcp->tcp_connp);
25073 				return (1);
25074 			}
25075 		}
25076 	}
25077 
25078 	return (0);
25079 }
25080 
25081 /*
25082  * Macros used for accessing the different types of sockaddr
25083  * structures inside a tcp_ioc_abort_conn_t.
25084  */
25085 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
25086 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
25087 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
25088 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
25089 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
25090 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
25091 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
25092 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
25093 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
25094 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
25095 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
25096 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
25097 
25098 /*
25099  * Return the correct error code to mimic the behavior
25100  * of a connection reset.
25101  */
25102 #define	TCP_AC_GET_ERRCODE(state, err) {	\
25103 		switch ((state)) {		\
25104 		case TCPS_SYN_SENT:		\
25105 		case TCPS_SYN_RCVD:		\
25106 			(err) = ECONNREFUSED;	\
25107 			break;			\
25108 		case TCPS_ESTABLISHED:		\
25109 		case TCPS_FIN_WAIT_1:		\
25110 		case TCPS_FIN_WAIT_2:		\
25111 		case TCPS_CLOSE_WAIT:		\
25112 			(err) = ECONNRESET;	\
25113 			break;			\
25114 		case TCPS_CLOSING:		\
25115 		case TCPS_LAST_ACK:		\
25116 		case TCPS_TIME_WAIT:		\
25117 			(err) = 0;		\
25118 			break;			\
25119 		default:			\
25120 			(err) = ENXIO;		\
25121 		}				\
25122 	}
25123 
25124 /*
25125  * Check if a tcp structure matches the info in acp.
25126  */
25127 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
25128 	(((acp)->ac_local.ss_family == AF_INET) ?		\
25129 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
25130 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
25131 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
25132 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
25133 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
25134 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
25135 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
25136 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
25137 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25138 	(acp)->ac_end >= (tcp)->tcp_state) :		\
25139 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
25140 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
25141 	&(tcp)->tcp_ip_src_v6)) &&				\
25142 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
25143 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
25144 	&(tcp)->tcp_remote_v6)) &&				\
25145 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
25146 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
25147 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
25148 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
25149 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25150 	(acp)->ac_end >= (tcp)->tcp_state))
25151 
25152 #define	TCP_AC_MATCH(acp, tcp)					\
25153 	(((acp)->ac_zoneid == ALL_ZONES ||			\
25154 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
25155 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
25156 
25157 /*
25158  * Build a message containing a tcp_ioc_abort_conn_t structure
25159  * which is filled in with information from acp and tp.
25160  */
25161 static mblk_t *
25162 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
25163 {
25164 	mblk_t *mp;
25165 	tcp_ioc_abort_conn_t *tacp;
25166 
25167 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
25168 	if (mp == NULL)
25169 		return (NULL);
25170 
25171 	mp->b_datap->db_type = M_CTL;
25172 
25173 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
25174 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
25175 	    sizeof (uint32_t));
25176 
25177 	tacp->ac_start = acp->ac_start;
25178 	tacp->ac_end = acp->ac_end;
25179 	tacp->ac_zoneid = acp->ac_zoneid;
25180 
25181 	if (acp->ac_local.ss_family == AF_INET) {
25182 		tacp->ac_local.ss_family = AF_INET;
25183 		tacp->ac_remote.ss_family = AF_INET;
25184 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
25185 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
25186 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
25187 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
25188 	} else {
25189 		tacp->ac_local.ss_family = AF_INET6;
25190 		tacp->ac_remote.ss_family = AF_INET6;
25191 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
25192 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
25193 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
25194 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
25195 	}
25196 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
25197 	return (mp);
25198 }
25199 
25200 /*
25201  * Print a tcp_ioc_abort_conn_t structure.
25202  */
25203 static void
25204 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
25205 {
25206 	char lbuf[128];
25207 	char rbuf[128];
25208 	sa_family_t af;
25209 	in_port_t lport, rport;
25210 	ushort_t logflags;
25211 
25212 	af = acp->ac_local.ss_family;
25213 
25214 	if (af == AF_INET) {
25215 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
25216 		    lbuf, 128);
25217 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
25218 		    rbuf, 128);
25219 		lport = ntohs(TCP_AC_V4LPORT(acp));
25220 		rport = ntohs(TCP_AC_V4RPORT(acp));
25221 	} else {
25222 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
25223 		    lbuf, 128);
25224 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
25225 		    rbuf, 128);
25226 		lport = ntohs(TCP_AC_V6LPORT(acp));
25227 		rport = ntohs(TCP_AC_V6RPORT(acp));
25228 	}
25229 
25230 	logflags = SL_TRACE | SL_NOTE;
25231 	/*
25232 	 * Don't print this message to the console if the operation was done
25233 	 * to a non-global zone.
25234 	 */
25235 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25236 		logflags |= SL_CONSOLE;
25237 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
25238 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
25239 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
25240 	    acp->ac_start, acp->ac_end);
25241 }
25242 
25243 /*
25244  * Called inside tcp_rput when a message built using
25245  * tcp_ioctl_abort_build_msg is put into a queue.
25246  * Note that when we get here there is no wildcard in acp any more.
25247  */
25248 static void
25249 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
25250 {
25251 	tcp_ioc_abort_conn_t *acp;
25252 
25253 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
25254 	if (tcp->tcp_state <= acp->ac_end) {
25255 		/*
25256 		 * If we get here, we are already on the correct
25257 		 * squeue. This ioctl follows the following path
25258 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
25259 		 * ->tcp_ioctl_abort->squeue_enter (if on a
25260 		 * different squeue)
25261 		 */
25262 		int errcode;
25263 
25264 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
25265 		(void) tcp_clean_death(tcp, errcode, 26);
25266 	}
25267 	freemsg(mp);
25268 }
25269 
25270 /*
25271  * Abort all matching connections on a hash chain.
25272  */
25273 static int
25274 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
25275     boolean_t exact, tcp_stack_t *tcps)
25276 {
25277 	int nmatch, err = 0;
25278 	tcp_t *tcp;
25279 	MBLKP mp, last, listhead = NULL;
25280 	conn_t	*tconnp;
25281 	connf_t	*connfp;
25282 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25283 
25284 	connfp = &ipst->ips_ipcl_conn_fanout[index];
25285 
25286 startover:
25287 	nmatch = 0;
25288 
25289 	mutex_enter(&connfp->connf_lock);
25290 	for (tconnp = connfp->connf_head; tconnp != NULL;
25291 	    tconnp = tconnp->conn_next) {
25292 		tcp = tconnp->conn_tcp;
25293 		if (TCP_AC_MATCH(acp, tcp)) {
25294 			CONN_INC_REF(tcp->tcp_connp);
25295 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
25296 			if (mp == NULL) {
25297 				err = ENOMEM;
25298 				CONN_DEC_REF(tcp->tcp_connp);
25299 				break;
25300 			}
25301 			mp->b_prev = (mblk_t *)tcp;
25302 
25303 			if (listhead == NULL) {
25304 				listhead = mp;
25305 				last = mp;
25306 			} else {
25307 				last->b_next = mp;
25308 				last = mp;
25309 			}
25310 			nmatch++;
25311 			if (exact)
25312 				break;
25313 		}
25314 
25315 		/* Avoid holding lock for too long. */
25316 		if (nmatch >= 500)
25317 			break;
25318 	}
25319 	mutex_exit(&connfp->connf_lock);
25320 
25321 	/* Pass mp into the correct tcp */
25322 	while ((mp = listhead) != NULL) {
25323 		listhead = listhead->b_next;
25324 		tcp = (tcp_t *)mp->b_prev;
25325 		mp->b_next = mp->b_prev = NULL;
25326 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
25327 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
25328 	}
25329 
25330 	*count += nmatch;
25331 	if (nmatch >= 500 && err == 0)
25332 		goto startover;
25333 	return (err);
25334 }
25335 
25336 /*
25337  * Abort all connections that matches the attributes specified in acp.
25338  */
25339 static int
25340 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
25341 {
25342 	sa_family_t af;
25343 	uint32_t  ports;
25344 	uint16_t *pports;
25345 	int err = 0, count = 0;
25346 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25347 	int index = -1;
25348 	ushort_t logflags;
25349 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25350 
25351 	af = acp->ac_local.ss_family;
25352 
25353 	if (af == AF_INET) {
25354 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25355 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25356 			pports = (uint16_t *)&ports;
25357 			pports[1] = TCP_AC_V4LPORT(acp);
25358 			pports[0] = TCP_AC_V4RPORT(acp);
25359 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25360 		}
25361 	} else {
25362 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25363 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25364 			pports = (uint16_t *)&ports;
25365 			pports[1] = TCP_AC_V6LPORT(acp);
25366 			pports[0] = TCP_AC_V6RPORT(acp);
25367 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25368 		}
25369 	}
25370 
25371 	/*
25372 	 * For cases where remote addr, local port, and remote port are non-
25373 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25374 	 */
25375 	if (index != -1) {
25376 		err = tcp_ioctl_abort_bucket(acp, index,
25377 		    &count, exact, tcps);
25378 	} else {
25379 		/*
25380 		 * loop through all entries for wildcard case
25381 		 */
25382 		for (index = 0;
25383 		    index < ipst->ips_ipcl_conn_fanout_size;
25384 		    index++) {
25385 			err = tcp_ioctl_abort_bucket(acp, index,
25386 			    &count, exact, tcps);
25387 			if (err != 0)
25388 				break;
25389 		}
25390 	}
25391 
25392 	logflags = SL_TRACE | SL_NOTE;
25393 	/*
25394 	 * Don't print this message to the console if the operation was done
25395 	 * to a non-global zone.
25396 	 */
25397 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25398 		logflags |= SL_CONSOLE;
25399 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25400 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25401 	if (err == 0 && count == 0)
25402 		err = ENOENT;
25403 	return (err);
25404 }
25405 
25406 /*
25407  * Process the TCP_IOC_ABORT_CONN ioctl request.
25408  */
25409 static void
25410 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25411 {
25412 	int	err;
25413 	IOCP    iocp;
25414 	MBLKP   mp1;
25415 	sa_family_t laf, raf;
25416 	tcp_ioc_abort_conn_t *acp;
25417 	zone_t		*zptr;
25418 	conn_t		*connp = Q_TO_CONN(q);
25419 	zoneid_t	zoneid = connp->conn_zoneid;
25420 	tcp_t		*tcp = connp->conn_tcp;
25421 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25422 
25423 	iocp = (IOCP)mp->b_rptr;
25424 
25425 	if ((mp1 = mp->b_cont) == NULL ||
25426 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25427 		err = EINVAL;
25428 		goto out;
25429 	}
25430 
25431 	/* check permissions */
25432 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
25433 		err = EPERM;
25434 		goto out;
25435 	}
25436 
25437 	if (mp1->b_cont != NULL) {
25438 		freemsg(mp1->b_cont);
25439 		mp1->b_cont = NULL;
25440 	}
25441 
25442 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25443 	laf = acp->ac_local.ss_family;
25444 	raf = acp->ac_remote.ss_family;
25445 
25446 	/* check that a zone with the supplied zoneid exists */
25447 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25448 		zptr = zone_find_by_id(zoneid);
25449 		if (zptr != NULL) {
25450 			zone_rele(zptr);
25451 		} else {
25452 			err = EINVAL;
25453 			goto out;
25454 		}
25455 	}
25456 
25457 	/*
25458 	 * For exclusive stacks we set the zoneid to zero
25459 	 * to make TCP operate as if in the global zone.
25460 	 */
25461 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
25462 		acp->ac_zoneid = GLOBAL_ZONEID;
25463 
25464 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25465 	    acp->ac_start > acp->ac_end || laf != raf ||
25466 	    (laf != AF_INET && laf != AF_INET6)) {
25467 		err = EINVAL;
25468 		goto out;
25469 	}
25470 
25471 	tcp_ioctl_abort_dump(acp);
25472 	err = tcp_ioctl_abort(acp, tcps);
25473 
25474 out:
25475 	if (mp1 != NULL) {
25476 		freemsg(mp1);
25477 		mp->b_cont = NULL;
25478 	}
25479 
25480 	if (err != 0)
25481 		miocnak(q, mp, 0, err);
25482 	else
25483 		miocack(q, mp, 0, 0);
25484 }
25485 
25486 /*
25487  * tcp_time_wait_processing() handles processing of incoming packets when
25488  * the tcp is in the TIME_WAIT state.
25489  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25490  * on the time wait list.
25491  */
25492 void
25493 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25494     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25495 {
25496 	int32_t		bytes_acked;
25497 	int32_t		gap;
25498 	int32_t		rgap;
25499 	tcp_opt_t	tcpopt;
25500 	uint_t		flags;
25501 	uint32_t	new_swnd = 0;
25502 	conn_t		*connp;
25503 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25504 
25505 	BUMP_LOCAL(tcp->tcp_ibsegs);
25506 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
25507 
25508 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25509 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25510 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25511 	if (tcp->tcp_snd_ts_ok) {
25512 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25513 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25514 			    tcp->tcp_rnxt, TH_ACK);
25515 			goto done;
25516 		}
25517 	}
25518 	gap = seg_seq - tcp->tcp_rnxt;
25519 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25520 	if (gap < 0) {
25521 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25522 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25523 		    (seg_len > -gap ? -gap : seg_len));
25524 		seg_len += gap;
25525 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25526 			if (flags & TH_RST) {
25527 				goto done;
25528 			}
25529 			if ((flags & TH_FIN) && seg_len == -1) {
25530 				/*
25531 				 * When TCP receives a duplicate FIN in
25532 				 * TIME_WAIT state, restart the 2 MSL timer.
25533 				 * See page 73 in RFC 793. Make sure this TCP
25534 				 * is already on the TIME_WAIT list. If not,
25535 				 * just restart the timer.
25536 				 */
25537 				if (TCP_IS_DETACHED(tcp)) {
25538 					if (tcp_time_wait_remove(tcp, NULL) ==
25539 					    B_TRUE) {
25540 						tcp_time_wait_append(tcp);
25541 						TCP_DBGSTAT(tcps,
25542 						    tcp_rput_time_wait);
25543 					}
25544 				} else {
25545 					ASSERT(tcp != NULL);
25546 					TCP_TIMER_RESTART(tcp,
25547 					    tcps->tcps_time_wait_interval);
25548 				}
25549 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25550 				    tcp->tcp_rnxt, TH_ACK);
25551 				goto done;
25552 			}
25553 			flags |=  TH_ACK_NEEDED;
25554 			seg_len = 0;
25555 			goto process_ack;
25556 		}
25557 
25558 		/* Fix seg_seq, and chew the gap off the front. */
25559 		seg_seq = tcp->tcp_rnxt;
25560 	}
25561 
25562 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25563 		/*
25564 		 * Make sure that when we accept the connection, pick
25565 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25566 		 * old connection.
25567 		 *
25568 		 * The next ISS generated is equal to tcp_iss_incr_extra
25569 		 * + ISS_INCR/2 + other components depending on the
25570 		 * value of tcp_strong_iss.  We pre-calculate the new
25571 		 * ISS here and compare with tcp_snxt to determine if
25572 		 * we need to make adjustment to tcp_iss_incr_extra.
25573 		 *
25574 		 * The above calculation is ugly and is a
25575 		 * waste of CPU cycles...
25576 		 */
25577 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25578 		int32_t adj;
25579 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25580 
25581 		switch (tcps->tcps_strong_iss) {
25582 		case 2: {
25583 			/* Add time and MD5 components. */
25584 			uint32_t answer[4];
25585 			struct {
25586 				uint32_t ports;
25587 				in6_addr_t src;
25588 				in6_addr_t dst;
25589 			} arg;
25590 			MD5_CTX context;
25591 
25592 			mutex_enter(&tcps->tcps_iss_key_lock);
25593 			context = tcps->tcps_iss_key;
25594 			mutex_exit(&tcps->tcps_iss_key_lock);
25595 			arg.ports = tcp->tcp_ports;
25596 			/* We use MAPPED addresses in tcp_iss_init */
25597 			arg.src = tcp->tcp_ip_src_v6;
25598 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25599 				IN6_IPADDR_TO_V4MAPPED(
25600 				    tcp->tcp_ipha->ipha_dst,
25601 				    &arg.dst);
25602 			} else {
25603 				arg.dst =
25604 				    tcp->tcp_ip6h->ip6_dst;
25605 			}
25606 			MD5Update(&context, (uchar_t *)&arg,
25607 			    sizeof (arg));
25608 			MD5Final((uchar_t *)answer, &context);
25609 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25610 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25611 			break;
25612 		}
25613 		case 1:
25614 			/* Add time component and min random (i.e. 1). */
25615 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25616 			break;
25617 		default:
25618 			/* Add only time component. */
25619 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25620 			break;
25621 		}
25622 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25623 			/*
25624 			 * New ISS not guaranteed to be ISS_INCR/2
25625 			 * ahead of the current tcp_snxt, so add the
25626 			 * difference to tcp_iss_incr_extra.
25627 			 */
25628 			tcps->tcps_iss_incr_extra += adj;
25629 		}
25630 		/*
25631 		 * If tcp_clean_death() can not perform the task now,
25632 		 * drop the SYN packet and let the other side re-xmit.
25633 		 * Otherwise pass the SYN packet back in, since the
25634 		 * old tcp state has been cleaned up or freed.
25635 		 */
25636 		if (tcp_clean_death(tcp, 0, 27) == -1)
25637 			goto done;
25638 		/*
25639 		 * We will come back to tcp_rput_data
25640 		 * on the global queue. Packets destined
25641 		 * for the global queue will be checked
25642 		 * with global policy. But the policy for
25643 		 * this packet has already been checked as
25644 		 * this was destined for the detached
25645 		 * connection. We need to bypass policy
25646 		 * check this time by attaching a dummy
25647 		 * ipsec_in with ipsec_in_dont_check set.
25648 		 */
25649 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25650 		if (connp != NULL) {
25651 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25652 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25653 			return;
25654 		}
25655 		goto done;
25656 	}
25657 
25658 	/*
25659 	 * rgap is the amount of stuff received out of window.  A negative
25660 	 * value is the amount out of window.
25661 	 */
25662 	if (rgap < 0) {
25663 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25664 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
25665 		/* Fix seg_len and make sure there is something left. */
25666 		seg_len += rgap;
25667 		if (seg_len <= 0) {
25668 			if (flags & TH_RST) {
25669 				goto done;
25670 			}
25671 			flags |=  TH_ACK_NEEDED;
25672 			seg_len = 0;
25673 			goto process_ack;
25674 		}
25675 	}
25676 	/*
25677 	 * Check whether we can update tcp_ts_recent.  This test is
25678 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
25679 	 * Extensions for High Performance: An Update", Internet Draft.
25680 	 */
25681 	if (tcp->tcp_snd_ts_ok &&
25682 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
25683 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
25684 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
25685 		tcp->tcp_last_rcv_lbolt = lbolt64;
25686 	}
25687 
25688 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
25689 		/* Always ack out of order packets */
25690 		flags |= TH_ACK_NEEDED;
25691 		seg_len = 0;
25692 	} else if (seg_len > 0) {
25693 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
25694 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
25695 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
25696 	}
25697 	if (flags & TH_RST) {
25698 		(void) tcp_clean_death(tcp, 0, 28);
25699 		goto done;
25700 	}
25701 	if (flags & TH_SYN) {
25702 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
25703 		    TH_RST|TH_ACK);
25704 		/*
25705 		 * Do not delete the TCP structure if it is in
25706 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
25707 		 */
25708 		goto done;
25709 	}
25710 process_ack:
25711 	if (flags & TH_ACK) {
25712 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
25713 		if (bytes_acked <= 0) {
25714 			if (bytes_acked == 0 && seg_len == 0 &&
25715 			    new_swnd == tcp->tcp_swnd)
25716 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
25717 		} else {
25718 			/* Acks something not sent */
25719 			flags |= TH_ACK_NEEDED;
25720 		}
25721 	}
25722 	if (flags & TH_ACK_NEEDED) {
25723 		/*
25724 		 * Time to send an ack for some reason.
25725 		 */
25726 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25727 		    tcp->tcp_rnxt, TH_ACK);
25728 	}
25729 done:
25730 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25731 		DB_CKSUMSTART(mp) = 0;
25732 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
25733 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
25734 	}
25735 	freemsg(mp);
25736 }
25737 
25738 /*
25739  * TCP Timers Implementation.
25740  */
25741 timeout_id_t
25742 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25743 {
25744 	mblk_t *mp;
25745 	tcp_timer_t *tcpt;
25746 	tcp_t *tcp = connp->conn_tcp;
25747 
25748 	ASSERT(connp->conn_sqp != NULL);
25749 
25750 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
25751 
25752 	if (tcp->tcp_timercache == NULL) {
25753 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25754 	} else {
25755 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
25756 		mp = tcp->tcp_timercache;
25757 		tcp->tcp_timercache = mp->b_next;
25758 		mp->b_next = NULL;
25759 		ASSERT(mp->b_wptr == NULL);
25760 	}
25761 
25762 	CONN_INC_REF(connp);
25763 	tcpt = (tcp_timer_t *)mp->b_rptr;
25764 	tcpt->connp = connp;
25765 	tcpt->tcpt_proc = f;
25766 	/*
25767 	 * TCP timers are normal timeouts. Plus, they do not require more than
25768 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
25769 	 * rounding up the expiration to the next resolution boundary, we can
25770 	 * batch timers in the callout subsystem to make TCP timers more
25771 	 * efficient. The roundup also protects short timers from expiring too
25772 	 * early before they have a chance to be cancelled.
25773 	 */
25774 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
25775 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
25776 
25777 	return ((timeout_id_t)mp);
25778 }
25779 
25780 static void
25781 tcp_timer_callback(void *arg)
25782 {
25783 	mblk_t *mp = (mblk_t *)arg;
25784 	tcp_timer_t *tcpt;
25785 	conn_t	*connp;
25786 
25787 	tcpt = (tcp_timer_t *)mp->b_rptr;
25788 	connp = tcpt->connp;
25789 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
25790 	    SQ_FILL, SQTAG_TCP_TIMER);
25791 }
25792 
25793 static void
25794 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
25795 {
25796 	tcp_timer_t *tcpt;
25797 	conn_t *connp = (conn_t *)arg;
25798 	tcp_t *tcp = connp->conn_tcp;
25799 
25800 	tcpt = (tcp_timer_t *)mp->b_rptr;
25801 	ASSERT(connp == tcpt->connp);
25802 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
25803 
25804 	/*
25805 	 * If the TCP has reached the closed state, don't proceed any
25806 	 * further. This TCP logically does not exist on the system.
25807 	 * tcpt_proc could for example access queues, that have already
25808 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
25809 	 */
25810 	if (tcp->tcp_state != TCPS_CLOSED) {
25811 		(*tcpt->tcpt_proc)(connp);
25812 	} else {
25813 		tcp->tcp_timer_tid = 0;
25814 	}
25815 	tcp_timer_free(connp->conn_tcp, mp);
25816 }
25817 
25818 /*
25819  * There is potential race with untimeout and the handler firing at the same
25820  * time. The mblock may be freed by the handler while we are trying to use
25821  * it. But since both should execute on the same squeue, this race should not
25822  * occur.
25823  */
25824 clock_t
25825 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
25826 {
25827 	mblk_t	*mp = (mblk_t *)id;
25828 	tcp_timer_t *tcpt;
25829 	clock_t delta;
25830 
25831 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
25832 
25833 	if (mp == NULL)
25834 		return (-1);
25835 
25836 	tcpt = (tcp_timer_t *)mp->b_rptr;
25837 	ASSERT(tcpt->connp == connp);
25838 
25839 	delta = untimeout_default(tcpt->tcpt_tid, 0);
25840 
25841 	if (delta >= 0) {
25842 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
25843 		tcp_timer_free(connp->conn_tcp, mp);
25844 		CONN_DEC_REF(connp);
25845 	}
25846 
25847 	return (delta);
25848 }
25849 
25850 /*
25851  * Allocate space for the timer event. The allocation looks like mblk, but it is
25852  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25853  *
25854  * Dealing with failures: If we can't allocate from the timer cache we try
25855  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25856  * points to b_rptr.
25857  * If we can't allocate anything using allocb_tryhard(), we perform a last
25858  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25859  * save the actual allocation size in b_datap.
25860  */
25861 mblk_t *
25862 tcp_timermp_alloc(int kmflags)
25863 {
25864 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25865 	    kmflags & ~KM_PANIC);
25866 
25867 	if (mp != NULL) {
25868 		mp->b_next = mp->b_prev = NULL;
25869 		mp->b_rptr = (uchar_t *)(&mp[1]);
25870 		mp->b_wptr = NULL;
25871 		mp->b_datap = NULL;
25872 		mp->b_queue = NULL;
25873 		mp->b_cont = NULL;
25874 	} else if (kmflags & KM_PANIC) {
25875 		/*
25876 		 * Failed to allocate memory for the timer. Try allocating from
25877 		 * dblock caches.
25878 		 */
25879 		/* ipclassifier calls this from a constructor - hence no tcps */
25880 		TCP_G_STAT(tcp_timermp_allocfail);
25881 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25882 		if (mp == NULL) {
25883 			size_t size = 0;
25884 			/*
25885 			 * Memory is really low. Try tryhard allocation.
25886 			 *
25887 			 * ipclassifier calls this from a constructor -
25888 			 * hence no tcps
25889 			 */
25890 			TCP_G_STAT(tcp_timermp_allocdblfail);
25891 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25892 			    sizeof (tcp_timer_t), &size, kmflags);
25893 			mp->b_rptr = (uchar_t *)(&mp[1]);
25894 			mp->b_next = mp->b_prev = NULL;
25895 			mp->b_wptr = (uchar_t *)-1;
25896 			mp->b_datap = (dblk_t *)size;
25897 			mp->b_queue = NULL;
25898 			mp->b_cont = NULL;
25899 		}
25900 		ASSERT(mp->b_wptr != NULL);
25901 	}
25902 	/* ipclassifier calls this from a constructor - hence no tcps */
25903 	TCP_G_DBGSTAT(tcp_timermp_alloced);
25904 
25905 	return (mp);
25906 }
25907 
25908 /*
25909  * Free per-tcp timer cache.
25910  * It can only contain entries from tcp_timercache.
25911  */
25912 void
25913 tcp_timermp_free(tcp_t *tcp)
25914 {
25915 	mblk_t *mp;
25916 
25917 	while ((mp = tcp->tcp_timercache) != NULL) {
25918 		ASSERT(mp->b_wptr == NULL);
25919 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25920 		kmem_cache_free(tcp_timercache, mp);
25921 	}
25922 }
25923 
25924 /*
25925  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25926  * events there already (currently at most two events are cached).
25927  * If the event is not allocated from the timer cache, free it right away.
25928  */
25929 static void
25930 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25931 {
25932 	mblk_t *mp1 = tcp->tcp_timercache;
25933 
25934 	if (mp->b_wptr != NULL) {
25935 		/*
25936 		 * This allocation is not from a timer cache, free it right
25937 		 * away.
25938 		 */
25939 		if (mp->b_wptr != (uchar_t *)-1)
25940 			freeb(mp);
25941 		else
25942 			kmem_free(mp, (size_t)mp->b_datap);
25943 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25944 		/* Cache this timer block for future allocations */
25945 		mp->b_rptr = (uchar_t *)(&mp[1]);
25946 		mp->b_next = mp1;
25947 		tcp->tcp_timercache = mp;
25948 	} else {
25949 		kmem_cache_free(tcp_timercache, mp);
25950 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
25951 	}
25952 }
25953 
25954 /*
25955  * End of TCP Timers implementation.
25956  */
25957 
25958 /*
25959  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25960  * on the specified backing STREAMS q. Note, the caller may make the
25961  * decision to call based on the tcp_t.tcp_flow_stopped value which
25962  * when check outside the q's lock is only an advisory check ...
25963  */
25964 void
25965 tcp_setqfull(tcp_t *tcp)
25966 {
25967 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25968 	conn_t	*connp = tcp->tcp_connp;
25969 
25970 	if (tcp->tcp_closed)
25971 		return;
25972 
25973 	if (IPCL_IS_NONSTR(connp)) {
25974 		(*connp->conn_upcalls->su_txq_full)
25975 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
25976 		tcp->tcp_flow_stopped = B_TRUE;
25977 	} else {
25978 		queue_t *q = tcp->tcp_wq;
25979 
25980 		if (!(q->q_flag & QFULL)) {
25981 			mutex_enter(QLOCK(q));
25982 			if (!(q->q_flag & QFULL)) {
25983 				/* still need to set QFULL */
25984 				q->q_flag |= QFULL;
25985 				tcp->tcp_flow_stopped = B_TRUE;
25986 				mutex_exit(QLOCK(q));
25987 				TCP_STAT(tcps, tcp_flwctl_on);
25988 			} else {
25989 				mutex_exit(QLOCK(q));
25990 			}
25991 		}
25992 	}
25993 }
25994 
25995 void
25996 tcp_clrqfull(tcp_t *tcp)
25997 {
25998 	conn_t  *connp = tcp->tcp_connp;
25999 
26000 	if (tcp->tcp_closed)
26001 		return;
26002 
26003 	if (IPCL_IS_NONSTR(connp)) {
26004 		(*connp->conn_upcalls->su_txq_full)
26005 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
26006 		tcp->tcp_flow_stopped = B_FALSE;
26007 	} else {
26008 		queue_t *q = tcp->tcp_wq;
26009 
26010 		if (q->q_flag & QFULL) {
26011 			mutex_enter(QLOCK(q));
26012 			if (q->q_flag & QFULL) {
26013 				q->q_flag &= ~QFULL;
26014 				tcp->tcp_flow_stopped = B_FALSE;
26015 				mutex_exit(QLOCK(q));
26016 				if (q->q_flag & QWANTW)
26017 					qbackenable(q, 0);
26018 			} else {
26019 				mutex_exit(QLOCK(q));
26020 			}
26021 		}
26022 	}
26023 }
26024 
26025 /*
26026  * kstats related to squeues i.e. not per IP instance
26027  */
26028 static void *
26029 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26030 {
26031 	kstat_t *ksp;
26032 
26033 	tcp_g_stat_t template = {
26034 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26035 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
26036 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
26037 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
26038 	};
26039 
26040 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
26041 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26042 	    KSTAT_FLAG_VIRTUAL);
26043 
26044 	if (ksp == NULL)
26045 		return (NULL);
26046 
26047 	bcopy(&template, tcp_g_statp, sizeof (template));
26048 	ksp->ks_data = (void *)tcp_g_statp;
26049 
26050 	kstat_install(ksp);
26051 	return (ksp);
26052 }
26053 
26054 static void
26055 tcp_g_kstat_fini(kstat_t *ksp)
26056 {
26057 	if (ksp != NULL) {
26058 		kstat_delete(ksp);
26059 	}
26060 }
26061 
26062 
26063 static void *
26064 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
26065 {
26066 	kstat_t *ksp;
26067 
26068 	tcp_stat_t template = {
26069 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
26070 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
26071 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
26072 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
26073 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
26074 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
26075 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
26076 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
26077 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
26078 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
26079 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
26080 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
26081 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
26082 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
26083 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
26084 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
26085 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
26086 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
26087 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
26088 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
26089 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
26090 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
26091 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
26092 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
26093 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
26094 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
26095 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
26096 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
26097 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
26098 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
26099 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
26100 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
26101 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
26102 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
26103 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
26104 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
26105 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
26106 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
26107 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
26108 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
26109 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
26110 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
26111 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
26112 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
26113 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
26114 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
26115 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
26116 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
26117 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
26118 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
26119 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
26120 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
26121 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
26122 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
26123 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
26124 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
26125 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
26126 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
26127 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
26128 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
26129 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
26130 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
26131 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
26132 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
26133 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
26134 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
26135 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
26136 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
26137 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
26138 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
26139 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
26140 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
26141 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
26142 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
26143 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
26144 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
26145 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
26146 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
26147 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
26148 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
26149 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
26150 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
26151 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
26152 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
26153 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
26154 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
26155 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
26156 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
26157 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
26158 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
26159 	};
26160 
26161 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
26162 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26163 	    KSTAT_FLAG_VIRTUAL, stackid);
26164 
26165 	if (ksp == NULL)
26166 		return (NULL);
26167 
26168 	bcopy(&template, tcps_statisticsp, sizeof (template));
26169 	ksp->ks_data = (void *)tcps_statisticsp;
26170 	ksp->ks_private = (void *)(uintptr_t)stackid;
26171 
26172 	kstat_install(ksp);
26173 	return (ksp);
26174 }
26175 
26176 static void
26177 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
26178 {
26179 	if (ksp != NULL) {
26180 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26181 		kstat_delete_netstack(ksp, stackid);
26182 	}
26183 }
26184 
26185 /*
26186  * TCP Kstats implementation
26187  */
26188 static void *
26189 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
26190 {
26191 	kstat_t	*ksp;
26192 
26193 	tcp_named_kstat_t template = {
26194 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
26195 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
26196 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
26197 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
26198 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
26199 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
26200 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
26201 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
26202 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
26203 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
26204 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
26205 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
26206 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
26207 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
26208 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
26209 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
26210 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
26211 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
26212 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
26213 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
26214 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
26215 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
26216 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
26217 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
26218 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
26219 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
26220 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
26221 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
26222 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
26223 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
26224 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
26225 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
26226 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
26227 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
26228 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
26229 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
26230 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
26231 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
26232 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
26233 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
26234 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
26235 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
26236 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
26237 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
26238 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
26239 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
26240 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
26241 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
26242 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
26243 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
26244 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
26245 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
26246 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
26247 	};
26248 
26249 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
26250 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
26251 
26252 	if (ksp == NULL)
26253 		return (NULL);
26254 
26255 	template.rtoAlgorithm.value.ui32 = 4;
26256 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
26257 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
26258 	template.maxConn.value.i32 = -1;
26259 
26260 	bcopy(&template, ksp->ks_data, sizeof (template));
26261 	ksp->ks_update = tcp_kstat_update;
26262 	ksp->ks_private = (void *)(uintptr_t)stackid;
26263 
26264 	kstat_install(ksp);
26265 	return (ksp);
26266 }
26267 
26268 static void
26269 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
26270 {
26271 	if (ksp != NULL) {
26272 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26273 		kstat_delete_netstack(ksp, stackid);
26274 	}
26275 }
26276 
26277 static int
26278 tcp_kstat_update(kstat_t *kp, int rw)
26279 {
26280 	tcp_named_kstat_t *tcpkp;
26281 	tcp_t		*tcp;
26282 	connf_t		*connfp;
26283 	conn_t		*connp;
26284 	int 		i;
26285 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
26286 	netstack_t	*ns;
26287 	tcp_stack_t	*tcps;
26288 	ip_stack_t	*ipst;
26289 
26290 	if ((kp == NULL) || (kp->ks_data == NULL))
26291 		return (EIO);
26292 
26293 	if (rw == KSTAT_WRITE)
26294 		return (EACCES);
26295 
26296 	ns = netstack_find_by_stackid(stackid);
26297 	if (ns == NULL)
26298 		return (-1);
26299 	tcps = ns->netstack_tcp;
26300 	if (tcps == NULL) {
26301 		netstack_rele(ns);
26302 		return (-1);
26303 	}
26304 
26305 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
26306 
26307 	tcpkp->currEstab.value.ui32 = 0;
26308 
26309 	ipst = ns->netstack_ip;
26310 
26311 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
26312 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
26313 		connp = NULL;
26314 		while ((connp =
26315 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
26316 			tcp = connp->conn_tcp;
26317 			switch (tcp_snmp_state(tcp)) {
26318 			case MIB2_TCP_established:
26319 			case MIB2_TCP_closeWait:
26320 				tcpkp->currEstab.value.ui32++;
26321 				break;
26322 			}
26323 		}
26324 	}
26325 
26326 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
26327 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
26328 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
26329 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
26330 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
26331 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
26332 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
26333 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
26334 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
26335 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
26336 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
26337 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
26338 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
26339 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
26340 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
26341 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
26342 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
26343 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
26344 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
26345 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
26346 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
26347 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
26348 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
26349 	tcpkp->inDataInorderSegs.value.ui32 =
26350 	    tcps->tcps_mib.tcpInDataInorderSegs;
26351 	tcpkp->inDataInorderBytes.value.ui32 =
26352 	    tcps->tcps_mib.tcpInDataInorderBytes;
26353 	tcpkp->inDataUnorderSegs.value.ui32 =
26354 	    tcps->tcps_mib.tcpInDataUnorderSegs;
26355 	tcpkp->inDataUnorderBytes.value.ui32 =
26356 	    tcps->tcps_mib.tcpInDataUnorderBytes;
26357 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
26358 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
26359 	tcpkp->inDataPartDupSegs.value.ui32 =
26360 	    tcps->tcps_mib.tcpInDataPartDupSegs;
26361 	tcpkp->inDataPartDupBytes.value.ui32 =
26362 	    tcps->tcps_mib.tcpInDataPartDupBytes;
26363 	tcpkp->inDataPastWinSegs.value.ui32 =
26364 	    tcps->tcps_mib.tcpInDataPastWinSegs;
26365 	tcpkp->inDataPastWinBytes.value.ui32 =
26366 	    tcps->tcps_mib.tcpInDataPastWinBytes;
26367 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
26368 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
26369 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
26370 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
26371 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
26372 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
26373 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
26374 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
26375 	tcpkp->timKeepaliveProbe.value.ui32 =
26376 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
26377 	tcpkp->timKeepaliveDrop.value.ui32 =
26378 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
26379 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
26380 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
26381 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
26382 	tcpkp->outSackRetransSegs.value.ui32 =
26383 	    tcps->tcps_mib.tcpOutSackRetransSegs;
26384 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
26385 
26386 	netstack_rele(ns);
26387 	return (0);
26388 }
26389 
26390 void
26391 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
26392 {
26393 	uint16_t	hdr_len;
26394 	ipha_t		*ipha;
26395 	uint8_t		*nexthdrp;
26396 	tcph_t		*tcph;
26397 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26398 
26399 	/* Already has an eager */
26400 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26401 		TCP_STAT(tcps, tcp_reinput_syn);
26402 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26403 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
26404 		return;
26405 	}
26406 
26407 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
26408 	case IPV4_VERSION:
26409 		ipha = (ipha_t *)mp->b_rptr;
26410 		hdr_len = IPH_HDR_LENGTH(ipha);
26411 		break;
26412 	case IPV6_VERSION:
26413 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
26414 		    &hdr_len, &nexthdrp)) {
26415 			CONN_DEC_REF(connp);
26416 			freemsg(mp);
26417 			return;
26418 		}
26419 		break;
26420 	}
26421 
26422 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
26423 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
26424 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
26425 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
26426 	}
26427 
26428 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26429 	    SQ_FILL, SQTAG_TCP_REINPUT);
26430 }
26431 
26432 static int
26433 tcp_squeue_switch(int val)
26434 {
26435 	int rval = SQ_FILL;
26436 
26437 	switch (val) {
26438 	case 1:
26439 		rval = SQ_NODRAIN;
26440 		break;
26441 	case 2:
26442 		rval = SQ_PROCESS;
26443 		break;
26444 	default:
26445 		break;
26446 	}
26447 	return (rval);
26448 }
26449 
26450 /*
26451  * This is called once for each squeue - globally for all stack
26452  * instances.
26453  */
26454 static void
26455 tcp_squeue_add(squeue_t *sqp)
26456 {
26457 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
26458 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
26459 
26460 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
26461 	tcp_time_wait->tcp_time_wait_tid =
26462 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
26463 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
26464 	    CALLOUT_FLAG_ROUNDUP);
26465 	if (tcp_free_list_max_cnt == 0) {
26466 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
26467 		    max_ncpus : boot_max_ncpus);
26468 
26469 		/*
26470 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
26471 		 */
26472 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
26473 		    (tcp_ncpus * sizeof (tcp_t) * 100);
26474 	}
26475 	tcp_time_wait->tcp_free_list_cnt = 0;
26476 }
26477 
26478 static int
26479 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error, cred_t *cr, pid_t pid)
26480 {
26481 	mblk_t	*ire_mp = NULL;
26482 	mblk_t	*syn_mp;
26483 	mblk_t	*mdti;
26484 	mblk_t	*lsoi;
26485 	int	retval;
26486 	tcph_t	*tcph;
26487 	uint32_t	mss;
26488 	queue_t	*q = tcp->tcp_rq;
26489 	conn_t	*connp = tcp->tcp_connp;
26490 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26491 
26492 	if (error == 0) {
26493 		/*
26494 		 * Adapt Multidata information, if any.  The
26495 		 * following tcp_mdt_update routine will free
26496 		 * the message.
26497 		 */
26498 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
26499 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
26500 			    b_rptr)->mdt_capab, B_TRUE);
26501 			freemsg(mdti);
26502 		}
26503 
26504 		/*
26505 		 * Check to update LSO information with tcp, and
26506 		 * tcp_lso_update routine will free the message.
26507 		 */
26508 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
26509 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
26510 			    b_rptr)->lso_capab);
26511 			freemsg(lsoi);
26512 		}
26513 
26514 		/* Get the IRE, if we had requested for it */
26515 		if (mp != NULL)
26516 			ire_mp = tcp_ire_mp(&mp);
26517 
26518 		if (tcp->tcp_hard_binding) {
26519 			tcp->tcp_hard_binding = B_FALSE;
26520 			tcp->tcp_hard_bound = B_TRUE;
26521 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
26522 			if (retval != 0) {
26523 				error = EADDRINUSE;
26524 				goto bind_failed;
26525 			}
26526 		} else {
26527 			if (ire_mp != NULL)
26528 				freeb(ire_mp);
26529 			goto after_syn_sent;
26530 		}
26531 
26532 		retval = tcp_adapt_ire(tcp, ire_mp);
26533 		if (ire_mp != NULL)
26534 			freeb(ire_mp);
26535 		if (retval == 0) {
26536 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
26537 			    ENETUNREACH : EADDRNOTAVAIL);
26538 			goto ipcl_rm;
26539 		}
26540 		/*
26541 		 * Don't let an endpoint connect to itself.
26542 		 * Also checked in tcp_connect() but that
26543 		 * check can't handle the case when the
26544 		 * local IP address is INADDR_ANY.
26545 		 */
26546 		if (tcp->tcp_ipversion == IPV4_VERSION) {
26547 			if ((tcp->tcp_ipha->ipha_dst ==
26548 			    tcp->tcp_ipha->ipha_src) &&
26549 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26550 			    tcp->tcp_tcph->th_fport))) {
26551 				error = EADDRNOTAVAIL;
26552 				goto ipcl_rm;
26553 			}
26554 		} else {
26555 			if (IN6_ARE_ADDR_EQUAL(
26556 			    &tcp->tcp_ip6h->ip6_dst,
26557 			    &tcp->tcp_ip6h->ip6_src) &&
26558 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26559 			    tcp->tcp_tcph->th_fport))) {
26560 				error = EADDRNOTAVAIL;
26561 				goto ipcl_rm;
26562 			}
26563 		}
26564 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
26565 		/*
26566 		 * This should not be possible!  Just for
26567 		 * defensive coding...
26568 		 */
26569 		if (tcp->tcp_state != TCPS_SYN_SENT)
26570 			goto after_syn_sent;
26571 
26572 		if (is_system_labeled() &&
26573 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
26574 			error = EHOSTUNREACH;
26575 			goto ipcl_rm;
26576 		}
26577 
26578 		/*
26579 		 * tcp_adapt_ire() does not adjust
26580 		 * for TCP/IP header length.
26581 		 */
26582 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
26583 
26584 		/*
26585 		 * Just make sure our rwnd is at
26586 		 * least tcp_recv_hiwat_mss * MSS
26587 		 * large, and round up to the nearest
26588 		 * MSS.
26589 		 *
26590 		 * We do the round up here because
26591 		 * we need to get the interface
26592 		 * MTU first before we can do the
26593 		 * round up.
26594 		 */
26595 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
26596 		    tcps->tcps_recv_hiwat_minmss * mss);
26597 		if (!IPCL_IS_NONSTR(connp))
26598 			q->q_hiwat = tcp->tcp_rwnd;
26599 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
26600 		tcp_set_ws_value(tcp);
26601 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
26602 		    tcp->tcp_tcph->th_win);
26603 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
26604 			tcp->tcp_snd_ws_ok = B_TRUE;
26605 
26606 		/*
26607 		 * Set tcp_snd_ts_ok to true
26608 		 * so that tcp_xmit_mp will
26609 		 * include the timestamp
26610 		 * option in the SYN segment.
26611 		 */
26612 		if (tcps->tcps_tstamp_always ||
26613 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
26614 			tcp->tcp_snd_ts_ok = B_TRUE;
26615 		}
26616 
26617 		/*
26618 		 * tcp_snd_sack_ok can be set in
26619 		 * tcp_adapt_ire() if the sack metric
26620 		 * is set.  So check it here also.
26621 		 */
26622 		if (tcps->tcps_sack_permitted == 2 ||
26623 		    tcp->tcp_snd_sack_ok) {
26624 			if (tcp->tcp_sack_info == NULL) {
26625 				tcp->tcp_sack_info =
26626 				    kmem_cache_alloc(tcp_sack_info_cache,
26627 				    KM_SLEEP);
26628 			}
26629 			tcp->tcp_snd_sack_ok = B_TRUE;
26630 		}
26631 
26632 		/*
26633 		 * Should we use ECN?  Note that the current
26634 		 * default value (SunOS 5.9) of tcp_ecn_permitted
26635 		 * is 1.  The reason for doing this is that there
26636 		 * are equipments out there that will drop ECN
26637 		 * enabled IP packets.  Setting it to 1 avoids
26638 		 * compatibility problems.
26639 		 */
26640 		if (tcps->tcps_ecn_permitted == 2)
26641 			tcp->tcp_ecn_ok = B_TRUE;
26642 
26643 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
26644 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
26645 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
26646 		if (syn_mp) {
26647 			if (cr == NULL) {
26648 				cr = tcp->tcp_cred;
26649 				pid = tcp->tcp_cpid;
26650 			}
26651 			mblk_setcred(syn_mp, cr);
26652 			DB_CPID(syn_mp) = pid;
26653 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
26654 		}
26655 	after_syn_sent:
26656 		if (mp != NULL) {
26657 			ASSERT(mp->b_cont == NULL);
26658 			freeb(mp);
26659 		}
26660 		return (error);
26661 	} else {
26662 		/* error */
26663 		if (tcp->tcp_debug) {
26664 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
26665 			    "tcp_post_ip_bind: error == %d", error);
26666 		}
26667 		if (mp != NULL) {
26668 			freeb(mp);
26669 		}
26670 	}
26671 
26672 ipcl_rm:
26673 	/*
26674 	 * Need to unbind with classifier since we were just
26675 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
26676 	 */
26677 	tcp->tcp_hard_bound = B_FALSE;
26678 	tcp->tcp_hard_binding = B_FALSE;
26679 
26680 	ipcl_hash_remove(connp);
26681 
26682 bind_failed:
26683 	tcp->tcp_state = TCPS_IDLE;
26684 	if (tcp->tcp_ipversion == IPV4_VERSION)
26685 		tcp->tcp_ipha->ipha_src = 0;
26686 	else
26687 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
26688 	/*
26689 	 * Copy of the src addr. in tcp_t is needed since
26690 	 * the lookup funcs. can only look at tcp_t
26691 	 */
26692 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
26693 
26694 	tcph = tcp->tcp_tcph;
26695 	tcph->th_lport[0] = 0;
26696 	tcph->th_lport[1] = 0;
26697 	tcp_bind_hash_remove(tcp);
26698 	bzero(&connp->u_port, sizeof (connp->u_port));
26699 	/* blow away saved option results if any */
26700 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26701 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26702 
26703 	conn_delete_ire(tcp->tcp_connp, NULL);
26704 
26705 	return (error);
26706 }
26707 
26708 static int
26709 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
26710     boolean_t bind_to_req_port_only, cred_t *cr)
26711 {
26712 	in_port_t	mlp_port;
26713 	mlp_type_t 	addrtype, mlptype;
26714 	boolean_t	user_specified;
26715 	in_port_t	allocated_port;
26716 	in_port_t	requested_port = *requested_port_ptr;
26717 	conn_t		*connp;
26718 	zone_t		*zone;
26719 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26720 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
26721 
26722 	/*
26723 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
26724 	 */
26725 	if (cr == NULL)
26726 		cr = tcp->tcp_cred;
26727 	/*
26728 	 * Get a valid port (within the anonymous range and should not
26729 	 * be a privileged one) to use if the user has not given a port.
26730 	 * If multiple threads are here, they may all start with
26731 	 * with the same initial port. But, it should be fine as long as
26732 	 * tcp_bindi will ensure that no two threads will be assigned
26733 	 * the same port.
26734 	 *
26735 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
26736 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
26737 	 * unless TCP_ANONPRIVBIND option is set.
26738 	 */
26739 	mlptype = mlptSingle;
26740 	mlp_port = requested_port;
26741 	if (requested_port == 0) {
26742 		requested_port = tcp->tcp_anon_priv_bind ?
26743 		    tcp_get_next_priv_port(tcp) :
26744 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
26745 		    tcp, B_TRUE);
26746 		if (requested_port == 0) {
26747 			return (-TNOADDR);
26748 		}
26749 		user_specified = B_FALSE;
26750 
26751 		/*
26752 		 * If the user went through one of the RPC interfaces to create
26753 		 * this socket and RPC is MLP in this zone, then give him an
26754 		 * anonymous MLP.
26755 		 */
26756 		connp = tcp->tcp_connp;
26757 		if (connp->conn_anon_mlp && is_system_labeled()) {
26758 			zone = crgetzone(cr);
26759 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26760 			    IPV6_VERSION, &v6addr,
26761 			    tcps->tcps_netstack->netstack_ip);
26762 			if (addrtype == mlptSingle) {
26763 				return (-TNOADDR);
26764 			}
26765 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26766 			    PMAPPORT, addrtype);
26767 			mlp_port = PMAPPORT;
26768 		}
26769 	} else {
26770 		int i;
26771 		boolean_t priv = B_FALSE;
26772 
26773 		/*
26774 		 * If the requested_port is in the well-known privileged range,
26775 		 * verify that the stream was opened by a privileged user.
26776 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
26777 		 * but instead the code relies on:
26778 		 * - the fact that the address of the array and its size never
26779 		 *   changes
26780 		 * - the atomic assignment of the elements of the array
26781 		 */
26782 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
26783 			priv = B_TRUE;
26784 		} else {
26785 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
26786 				if (requested_port ==
26787 				    tcps->tcps_g_epriv_ports[i]) {
26788 					priv = B_TRUE;
26789 					break;
26790 				}
26791 			}
26792 		}
26793 		if (priv) {
26794 			if (secpolicy_net_privaddr(cr, requested_port,
26795 			    IPPROTO_TCP) != 0) {
26796 				if (tcp->tcp_debug) {
26797 					(void) strlog(TCP_MOD_ID, 0, 1,
26798 					    SL_ERROR|SL_TRACE,
26799 					    "tcp_bind: no priv for port %d",
26800 					    requested_port);
26801 				}
26802 				return (-TACCES);
26803 			}
26804 		}
26805 		user_specified = B_TRUE;
26806 
26807 		connp = tcp->tcp_connp;
26808 		if (is_system_labeled()) {
26809 			zone = crgetzone(cr);
26810 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26811 			    IPV6_VERSION, &v6addr,
26812 			    tcps->tcps_netstack->netstack_ip);
26813 			if (addrtype == mlptSingle) {
26814 				return (-TNOADDR);
26815 			}
26816 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26817 			    requested_port, addrtype);
26818 		}
26819 	}
26820 
26821 	if (mlptype != mlptSingle) {
26822 		if (secpolicy_net_bindmlp(cr) != 0) {
26823 			if (tcp->tcp_debug) {
26824 				(void) strlog(TCP_MOD_ID, 0, 1,
26825 				    SL_ERROR|SL_TRACE,
26826 				    "tcp_bind: no priv for multilevel port %d",
26827 				    requested_port);
26828 			}
26829 			return (-TACCES);
26830 		}
26831 
26832 		/*
26833 		 * If we're specifically binding a shared IP address and the
26834 		 * port is MLP on shared addresses, then check to see if this
26835 		 * zone actually owns the MLP.  Reject if not.
26836 		 */
26837 		if (mlptype == mlptShared && addrtype == mlptShared) {
26838 			/*
26839 			 * No need to handle exclusive-stack zones since
26840 			 * ALL_ZONES only applies to the shared stack.
26841 			 */
26842 			zoneid_t mlpzone;
26843 
26844 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26845 			    htons(mlp_port));
26846 			if (connp->conn_zoneid != mlpzone) {
26847 				if (tcp->tcp_debug) {
26848 					(void) strlog(TCP_MOD_ID, 0, 1,
26849 					    SL_ERROR|SL_TRACE,
26850 					    "tcp_bind: attempt to bind port "
26851 					    "%d on shared addr in zone %d "
26852 					    "(should be %d)",
26853 					    mlp_port, connp->conn_zoneid,
26854 					    mlpzone);
26855 				}
26856 				return (-TACCES);
26857 			}
26858 		}
26859 
26860 		if (!user_specified) {
26861 			int err;
26862 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26863 			    requested_port, B_TRUE);
26864 			if (err != 0) {
26865 				if (tcp->tcp_debug) {
26866 					(void) strlog(TCP_MOD_ID, 0, 1,
26867 					    SL_ERROR|SL_TRACE,
26868 					    "tcp_bind: cannot establish anon "
26869 					    "MLP for port %d",
26870 					    requested_port);
26871 				}
26872 				return (err);
26873 			}
26874 			connp->conn_anon_port = B_TRUE;
26875 		}
26876 		connp->conn_mlp_type = mlptype;
26877 	}
26878 
26879 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26880 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26881 
26882 	if (allocated_port == 0) {
26883 		connp->conn_mlp_type = mlptSingle;
26884 		if (connp->conn_anon_port) {
26885 			connp->conn_anon_port = B_FALSE;
26886 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26887 			    requested_port, B_FALSE);
26888 		}
26889 		if (bind_to_req_port_only) {
26890 			if (tcp->tcp_debug) {
26891 				(void) strlog(TCP_MOD_ID, 0, 1,
26892 				    SL_ERROR|SL_TRACE,
26893 				    "tcp_bind: requested addr busy");
26894 			}
26895 			return (-TADDRBUSY);
26896 		} else {
26897 			/* If we are out of ports, fail the bind. */
26898 			if (tcp->tcp_debug) {
26899 				(void) strlog(TCP_MOD_ID, 0, 1,
26900 				    SL_ERROR|SL_TRACE,
26901 				    "tcp_bind: out of ports?");
26902 			}
26903 			return (-TNOADDR);
26904 		}
26905 	}
26906 
26907 	/* Pass the allocated port back */
26908 	*requested_port_ptr = allocated_port;
26909 	return (0);
26910 }
26911 
26912 static int
26913 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26914     boolean_t bind_to_req_port_only)
26915 {
26916 	tcp_t	*tcp = connp->conn_tcp;
26917 
26918 	sin_t	*sin;
26919 	sin6_t  *sin6;
26920 	sin6_t		sin6addr;
26921 	in_port_t requested_port;
26922 	ipaddr_t	v4addr;
26923 	in6_addr_t	v6addr;
26924 	uint_t	origipversion;
26925 	int	error = 0;
26926 
26927 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
26928 
26929 	if (tcp->tcp_state == TCPS_BOUND) {
26930 		return (0);
26931 	} else if (tcp->tcp_state > TCPS_BOUND) {
26932 		if (tcp->tcp_debug) {
26933 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26934 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26935 		}
26936 		return (-TOUTSTATE);
26937 	}
26938 	origipversion = tcp->tcp_ipversion;
26939 
26940 	if (sa != NULL && !OK_32PTR((char *)sa)) {
26941 		if (tcp->tcp_debug) {
26942 			(void) strlog(TCP_MOD_ID, 0, 1,
26943 			    SL_ERROR|SL_TRACE,
26944 			    "tcp_bind: bad address parameter, "
26945 			    "address %p, len %d",
26946 			    (void *)sa, len);
26947 		}
26948 		return (-TPROTO);
26949 	}
26950 
26951 	switch (len) {
26952 	case 0:		/* request for a generic port */
26953 		if (tcp->tcp_family == AF_INET) {
26954 			sin = (sin_t *)&sin6addr;
26955 			*sin = sin_null;
26956 			sin->sin_family = AF_INET;
26957 			tcp->tcp_ipversion = IPV4_VERSION;
26958 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
26959 		} else {
26960 			ASSERT(tcp->tcp_family == AF_INET6);
26961 			sin6 = (sin6_t *)&sin6addr;
26962 			*sin6 = sin6_null;
26963 			sin6->sin6_family = AF_INET6;
26964 			tcp->tcp_ipversion = IPV6_VERSION;
26965 			V6_SET_ZERO(v6addr);
26966 		}
26967 		requested_port = 0;
26968 		break;
26969 
26970 	case sizeof (sin_t):	/* Complete IPv4 address */
26971 		sin = (sin_t *)sa;
26972 		/*
26973 		 * With sockets sockfs will accept bogus sin_family in
26974 		 * bind() and replace it with the family used in the socket
26975 		 * call.
26976 		 */
26977 		if (sin->sin_family != AF_INET ||
26978 		    tcp->tcp_family != AF_INET) {
26979 			return (EAFNOSUPPORT);
26980 		}
26981 		requested_port = ntohs(sin->sin_port);
26982 		tcp->tcp_ipversion = IPV4_VERSION;
26983 		v4addr = sin->sin_addr.s_addr;
26984 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
26985 		break;
26986 
26987 	case sizeof (sin6_t): /* Complete IPv6 address */
26988 		sin6 = (sin6_t *)sa;
26989 		if (sin6->sin6_family != AF_INET6 ||
26990 		    tcp->tcp_family != AF_INET6) {
26991 			return (EAFNOSUPPORT);
26992 		}
26993 		requested_port = ntohs(sin6->sin6_port);
26994 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
26995 		    IPV4_VERSION : IPV6_VERSION;
26996 		v6addr = sin6->sin6_addr;
26997 		break;
26998 
26999 	default:
27000 		if (tcp->tcp_debug) {
27001 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27002 			    "tcp_bind: bad address length, %d", len);
27003 		}
27004 		return (EAFNOSUPPORT);
27005 		/* return (-TBADADDR); */
27006 	}
27007 
27008 	tcp->tcp_bound_source_v6 = v6addr;
27009 
27010 	/* Check for change in ipversion */
27011 	if (origipversion != tcp->tcp_ipversion) {
27012 		ASSERT(tcp->tcp_family == AF_INET6);
27013 		error = tcp->tcp_ipversion == IPV6_VERSION ?
27014 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
27015 		if (error) {
27016 			return (ENOMEM);
27017 		}
27018 	}
27019 
27020 	/*
27021 	 * Initialize family specific fields. Copy of the src addr.
27022 	 * in tcp_t is needed for the lookup funcs.
27023 	 */
27024 	if (tcp->tcp_ipversion == IPV6_VERSION) {
27025 		tcp->tcp_ip6h->ip6_src = v6addr;
27026 	} else {
27027 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
27028 	}
27029 	tcp->tcp_ip_src_v6 = v6addr;
27030 
27031 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
27032 
27033 	error = tcp_bind_select_lport(tcp, &requested_port,
27034 	    bind_to_req_port_only, cr);
27035 
27036 	return (error);
27037 }
27038 
27039 /*
27040  * Return unix error is tli error is TSYSERR, otherwise return a negative
27041  * tli error.
27042  */
27043 int
27044 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
27045     boolean_t bind_to_req_port_only)
27046 {
27047 	int error;
27048 	tcp_t *tcp = connp->conn_tcp;
27049 
27050 	if (tcp->tcp_state >= TCPS_BOUND) {
27051 		if (tcp->tcp_debug) {
27052 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27053 			    "tcp_bind: bad state, %d", tcp->tcp_state);
27054 		}
27055 		return (-TOUTSTATE);
27056 	}
27057 
27058 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
27059 	if (error != 0)
27060 		return (error);
27061 
27062 	ASSERT(tcp->tcp_state == TCPS_BOUND);
27063 
27064 	tcp->tcp_conn_req_max = 0;
27065 
27066 	/*
27067 	 * We need to make sure that the conn_recv is set to a non-null
27068 	 * value before we insert the conn into the classifier table.
27069 	 * This is to avoid a race with an incoming packet which does an
27070 	 * ipcl_classify().
27071 	 */
27072 	connp->conn_recv = tcp_conn_request;
27073 
27074 	if (tcp->tcp_family == AF_INET6) {
27075 		ASSERT(tcp->tcp_connp->conn_af_isv6);
27076 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27077 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
27078 	} else {
27079 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
27080 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
27081 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
27082 	}
27083 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27084 }
27085 
27086 int
27087 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
27088     socklen_t len, cred_t *cr)
27089 {
27090 	int 		error;
27091 	conn_t		*connp = (conn_t *)proto_handle;
27092 	squeue_t	*sqp = connp->conn_sqp;
27093 
27094 	ASSERT(sqp != NULL);
27095 	ASSERT(connp->conn_upper_handle != NULL);
27096 
27097 	error = squeue_synch_enter(sqp, connp, 0);
27098 	if (error != 0) {
27099 		/* failed to enter */
27100 		return (ENOSR);
27101 	}
27102 
27103 	/* binding to a NULL address really means unbind */
27104 	if (sa == NULL) {
27105 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
27106 			error = tcp_do_unbind(connp);
27107 		else
27108 			error = EINVAL;
27109 	} else {
27110 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
27111 	}
27112 
27113 	squeue_synch_exit(sqp, connp);
27114 
27115 	if (error < 0) {
27116 		if (error == -TOUTSTATE)
27117 			error = EINVAL;
27118 		else
27119 			error = proto_tlitosyserr(-error);
27120 	}
27121 
27122 	return (error);
27123 }
27124 
27125 /*
27126  * If the return value from this function is positive, it's a UNIX error.
27127  * Otherwise, if it's negative, then the absolute value is a TLI error.
27128  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
27129  */
27130 int
27131 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
27132     cred_t *cr, pid_t pid)
27133 {
27134 	tcp_t		*tcp = connp->conn_tcp;
27135 	sin_t		*sin = (sin_t *)sa;
27136 	sin6_t		*sin6 = (sin6_t *)sa;
27137 	ipaddr_t	*dstaddrp;
27138 	in_port_t	dstport;
27139 	uint_t		srcid;
27140 	int		error = 0;
27141 
27142 	switch (len) {
27143 	default:
27144 		/*
27145 		 * Should never happen
27146 		 */
27147 		return (EINVAL);
27148 
27149 	case sizeof (sin_t):
27150 		sin = (sin_t *)sa;
27151 		if (sin->sin_port == 0) {
27152 			return (-TBADADDR);
27153 		}
27154 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
27155 			return (EAFNOSUPPORT);
27156 		}
27157 		break;
27158 
27159 	case sizeof (sin6_t):
27160 		sin6 = (sin6_t *)sa;
27161 		if (sin6->sin6_port == 0) {
27162 			return (-TBADADDR);
27163 		}
27164 		break;
27165 	}
27166 	/*
27167 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
27168 	 * make sure that the template IP header in the tcp structure is an
27169 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
27170 	 * need to this before we call tcp_bindi() so that the port lookup
27171 	 * code will look for ports in the correct port space (IPv4 and
27172 	 * IPv6 have separate port spaces).
27173 	 */
27174 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
27175 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
27176 		int err = 0;
27177 
27178 		err = tcp_header_init_ipv4(tcp);
27179 			if (err != 0) {
27180 				error = ENOMEM;
27181 				goto connect_failed;
27182 			}
27183 		if (tcp->tcp_lport != 0)
27184 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
27185 	}
27186 
27187 	switch (tcp->tcp_state) {
27188 	case TCPS_LISTEN:
27189 		/*
27190 		 * Listening sockets are not allowed to issue connect().
27191 		 */
27192 		if (IPCL_IS_NONSTR(connp))
27193 			return (EOPNOTSUPP);
27194 		/* FALLTHRU */
27195 	case TCPS_IDLE:
27196 		/*
27197 		 * We support quick connect, refer to comments in
27198 		 * tcp_connect_*()
27199 		 */
27200 		/* FALLTHRU */
27201 	case TCPS_BOUND:
27202 		/*
27203 		 * We must bump the generation before the operation start.
27204 		 * This is done to ensure that any upcall made later on sends
27205 		 * up the right generation to the socket.
27206 		 */
27207 		SOCK_CONNID_BUMP(tcp->tcp_connid);
27208 
27209 		if (tcp->tcp_family == AF_INET6) {
27210 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
27211 				return (tcp_connect_ipv6(tcp,
27212 				    &sin6->sin6_addr,
27213 				    sin6->sin6_port, sin6->sin6_flowinfo,
27214 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
27215 				    cr, pid));
27216 			}
27217 			/*
27218 			 * Destination adress is mapped IPv6 address.
27219 			 * Source bound address should be unspecified or
27220 			 * IPv6 mapped address as well.
27221 			 */
27222 			if (!IN6_IS_ADDR_UNSPECIFIED(
27223 			    &tcp->tcp_bound_source_v6) &&
27224 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
27225 				return (EADDRNOTAVAIL);
27226 			}
27227 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
27228 			dstport = sin6->sin6_port;
27229 			srcid = sin6->__sin6_src_id;
27230 		} else {
27231 			dstaddrp = &sin->sin_addr.s_addr;
27232 			dstport = sin->sin_port;
27233 			srcid = 0;
27234 		}
27235 
27236 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
27237 		    pid);
27238 		break;
27239 	default:
27240 		return (-TOUTSTATE);
27241 	}
27242 	/*
27243 	 * Note: Code below is the "failure" case
27244 	 */
27245 connect_failed:
27246 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
27247 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
27248 	return (error);
27249 }
27250 
27251 int
27252 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
27253     socklen_t len, sock_connid_t *id, cred_t *cr)
27254 {
27255 	conn_t		*connp = (conn_t *)proto_handle;
27256 	tcp_t		*tcp = connp->conn_tcp;
27257 	squeue_t	*sqp = connp->conn_sqp;
27258 	int		error;
27259 
27260 	ASSERT(connp->conn_upper_handle != NULL);
27261 
27262 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
27263 	if (error != 0) {
27264 		return (error);
27265 	}
27266 
27267 	error = squeue_synch_enter(sqp, connp, 0);
27268 	if (error != 0) {
27269 		/* failed to enter */
27270 		return (ENOSR);
27271 	}
27272 
27273 	/*
27274 	 * TCP supports quick connect, so no need to do an implicit bind
27275 	 */
27276 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
27277 	if (error == 0) {
27278 		*id = connp->conn_tcp->tcp_connid;
27279 	} else if (error < 0) {
27280 		if (error == -TOUTSTATE) {
27281 			switch (connp->conn_tcp->tcp_state) {
27282 			case TCPS_SYN_SENT:
27283 				error = EALREADY;
27284 				break;
27285 			case TCPS_ESTABLISHED:
27286 				error = EISCONN;
27287 				break;
27288 			case TCPS_LISTEN:
27289 				error = EOPNOTSUPP;
27290 				break;
27291 			default:
27292 				error = EINVAL;
27293 				break;
27294 			}
27295 		} else {
27296 			error = proto_tlitosyserr(-error);
27297 		}
27298 	}
27299 done:
27300 	squeue_synch_exit(sqp, connp);
27301 
27302 	return ((error == 0) ? EINPROGRESS : error);
27303 }
27304 
27305 /* ARGSUSED */
27306 sock_lower_handle_t
27307 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
27308     uint_t *smodep, int *errorp, int flags, cred_t *credp)
27309 {
27310 	conn_t		*connp;
27311 	boolean_t	isv6 = family == AF_INET6;
27312 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
27313 	    (proto != 0 && proto != IPPROTO_TCP)) {
27314 		*errorp = EPROTONOSUPPORT;
27315 		return (NULL);
27316 	}
27317 
27318 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
27319 	if (connp == NULL) {
27320 		return (NULL);
27321 	}
27322 
27323 	/*
27324 	 * Put the ref for TCP. Ref for IP was already put
27325 	 * by ipcl_conn_create. Also Make the conn_t globally
27326 	 * visible to walkers
27327 	 */
27328 	mutex_enter(&connp->conn_lock);
27329 	CONN_INC_REF_LOCKED(connp);
27330 	ASSERT(connp->conn_ref == 2);
27331 	connp->conn_state_flags &= ~CONN_INCIPIENT;
27332 
27333 	connp->conn_flags |= IPCL_NONSTR;
27334 	mutex_exit(&connp->conn_lock);
27335 
27336 	ASSERT(errorp != NULL);
27337 	*errorp = 0;
27338 	*sock_downcalls = &sock_tcp_downcalls;
27339 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
27340 	    SM_SENDFILESUPP;
27341 
27342 	return ((sock_lower_handle_t)connp);
27343 }
27344 
27345 /* ARGSUSED */
27346 void
27347 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
27348     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
27349 {
27350 	conn_t *connp = (conn_t *)proto_handle;
27351 	struct sock_proto_props sopp;
27352 
27353 	ASSERT(connp->conn_upper_handle == NULL);
27354 
27355 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
27356 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
27357 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
27358 
27359 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
27360 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
27361 	sopp.sopp_maxpsz = INFPSZ;
27362 	sopp.sopp_maxblk = INFPSZ;
27363 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
27364 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
27365 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
27366 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
27367 	    tcp_rinfo.mi_minpsz;
27368 
27369 	connp->conn_upcalls = sock_upcalls;
27370 	connp->conn_upper_handle = sock_handle;
27371 
27372 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
27373 }
27374 
27375 /* ARGSUSED */
27376 int
27377 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
27378 {
27379 	conn_t *connp = (conn_t *)proto_handle;
27380 
27381 	ASSERT(connp->conn_upper_handle != NULL);
27382 
27383 	tcp_close_common(connp, flags);
27384 
27385 	ip_free_helper_stream(connp);
27386 
27387 	/*
27388 	 * Drop IP's reference on the conn. This is the last reference
27389 	 * on the connp if the state was less than established. If the
27390 	 * connection has gone into timewait state, then we will have
27391 	 * one ref for the TCP and one more ref (total of two) for the
27392 	 * classifier connected hash list (a timewait connections stays
27393 	 * in connected hash till closed).
27394 	 *
27395 	 * We can't assert the references because there might be other
27396 	 * transient reference places because of some walkers or queued
27397 	 * packets in squeue for the timewait state.
27398 	 */
27399 	CONN_DEC_REF(connp);
27400 	return (0);
27401 }
27402 
27403 /* ARGSUSED */
27404 int
27405 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
27406     cred_t *cr)
27407 {
27408 	tcp_t		*tcp;
27409 	uint32_t	msize;
27410 	conn_t *connp = (conn_t *)proto_handle;
27411 	int32_t		tcpstate;
27412 
27413 	ASSERT(connp->conn_ref >= 2);
27414 	ASSERT(connp->conn_upper_handle != NULL);
27415 
27416 	if (msg->msg_controllen != 0) {
27417 		return (EOPNOTSUPP);
27418 
27419 	}
27420 	switch (DB_TYPE(mp)) {
27421 	case M_DATA:
27422 		tcp = connp->conn_tcp;
27423 		ASSERT(tcp != NULL);
27424 
27425 		tcpstate = tcp->tcp_state;
27426 		if (tcpstate < TCPS_ESTABLISHED) {
27427 			freemsg(mp);
27428 			return (ENOTCONN);
27429 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
27430 			freemsg(mp);
27431 			return (EPIPE);
27432 		}
27433 
27434 		msize = msgdsize(mp);
27435 
27436 		mutex_enter(&tcp->tcp_non_sq_lock);
27437 		tcp->tcp_squeue_bytes += msize;
27438 		/*
27439 		 * Squeue Flow Control
27440 		 */
27441 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
27442 			tcp_setqfull(tcp);
27443 		}
27444 		mutex_exit(&tcp->tcp_non_sq_lock);
27445 
27446 		/*
27447 		 * The application may pass in an address in the msghdr, but
27448 		 * we ignore the address on connection-oriented sockets.
27449 		 * Just like BSD this code does not generate an error for
27450 		 * TCP (a CONNREQUIRED socket) when sending to an address
27451 		 * passed in with sendto/sendmsg. Instead the data is
27452 		 * delivered on the connection as if no address had been
27453 		 * supplied.
27454 		 */
27455 		CONN_INC_REF(connp);
27456 
27457 		if (msg != NULL && msg->msg_flags & MSG_OOB) {
27458 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
27459 			    tcp_output_urgent, connp, tcp_squeue_flag,
27460 			    SQTAG_TCP_OUTPUT);
27461 		} else {
27462 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
27463 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
27464 		}
27465 
27466 		return (0);
27467 
27468 	default:
27469 		ASSERT(0);
27470 	}
27471 
27472 	freemsg(mp);
27473 	return (0);
27474 }
27475 
27476 /* ARGSUSED */
27477 void
27478 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
27479 {
27480 	int len;
27481 	uint32_t msize;
27482 	conn_t *connp = (conn_t *)arg;
27483 	tcp_t *tcp = connp->conn_tcp;
27484 
27485 	msize = msgdsize(mp);
27486 
27487 	len = msize - 1;
27488 	if (len < 0) {
27489 		freemsg(mp);
27490 		return;
27491 	}
27492 
27493 	/*
27494 	 * Try to force urgent data out on the wire.
27495 	 * Even if we have unsent data this will
27496 	 * at least send the urgent flag.
27497 	 * XXX does not handle more flag correctly.
27498 	 */
27499 	len += tcp->tcp_unsent;
27500 	len += tcp->tcp_snxt;
27501 	tcp->tcp_urg = len;
27502 	tcp->tcp_valid_bits |= TCP_URG_VALID;
27503 
27504 	/* Bypass tcp protocol for fused tcp loopback */
27505 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
27506 		return;
27507 	tcp_wput_data(tcp, mp, B_TRUE);
27508 }
27509 
27510 /* ARGSUSED */
27511 int
27512 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27513     socklen_t *addrlenp, cred_t *cr)
27514 {
27515 	conn_t	*connp = (conn_t *)proto_handle;
27516 	tcp_t	*tcp = connp->conn_tcp;
27517 
27518 	ASSERT(connp->conn_upper_handle != NULL);
27519 	ASSERT(tcp != NULL);
27520 
27521 	return (tcp_do_getpeername(tcp, addr, addrlenp));
27522 }
27523 
27524 /* ARGSUSED */
27525 int
27526 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27527     socklen_t *addrlenp, cred_t *cr)
27528 {
27529 	conn_t	*connp = (conn_t *)proto_handle;
27530 	tcp_t	*tcp = connp->conn_tcp;
27531 
27532 	ASSERT(connp->conn_upper_handle != NULL);
27533 
27534 	return (tcp_do_getsockname(tcp, addr, addrlenp));
27535 }
27536 
27537 /*
27538  * tcp_fallback
27539  *
27540  * A direct socket is falling back to using STREAMS. Hanging
27541  * off of the queue is a temporary tcp_t, which was created using
27542  * tcp_open(). The tcp_open() was called as part of the regular
27543  * sockfs create path, i.e., the SO_SOCKSTR flag is passed down,
27544  * and therefore the temporary tcp_t is marked to be a socket
27545  * (i.e., IPCL_SOCKET, tcp_issocket). So the optimizations
27546  * introduced by FireEngine will be used.
27547  *
27548  * The tcp_t associated with the socket falling back will
27549  * still be marked as a socket, although the direct socket flag
27550  * (IPCL_NONSTR) is removed. A fall back to true TPI semantics
27551  * will not take place until a _SIOCSOCKFALLBACK ioctl is issued.
27552  *
27553  * If the above mentioned behavior, i.e., the tmp tcp_t is created
27554  * as a STREAMS/TPI endpoint, then we will need to do more work here.
27555  * Such as inserting the direct socket into the acceptor hash.
27556  */
27557 void
27558 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
27559     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
27560 {
27561 	tcp_t			*tcp, *eager;
27562 	conn_t 			*connp = (conn_t *)proto_handle;
27563 	int			error;
27564 	struct T_capability_ack tca;
27565 	struct sockaddr_in6	laddr, faddr;
27566 	socklen_t 		laddrlen, faddrlen;
27567 	short			opts;
27568 	struct stroptions	*stropt;
27569 	mblk_t			*stropt_mp;
27570 	mblk_t			*mp;
27571 	mblk_t			*conn_ind_head = NULL;
27572 	mblk_t			*conn_ind_tail = NULL;
27573 	mblk_t			*ordrel_mp;
27574 	mblk_t			*fused_sigurp_mp;
27575 
27576 	tcp = connp->conn_tcp;
27577 	/*
27578 	 * No support for acceptor fallback
27579 	 */
27580 	ASSERT(q->q_qinfo != &tcp_acceptor_rinit);
27581 
27582 	stropt_mp = allocb_wait(sizeof (*stropt), BPRI_HI, STR_NOSIG, NULL);
27583 
27584 	/* Pre-allocate the T_ordrel_ind mblk. */
27585 	ASSERT(tcp->tcp_ordrel_mp == NULL);
27586 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
27587 	    STR_NOSIG, NULL);
27588 	ordrel_mp->b_datap->db_type = M_PROTO;
27589 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
27590 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
27591 
27592 	/* Pre-allocate the M_PCSIG anyway */
27593 	fused_sigurp_mp = allocb_wait(1, BPRI_HI, STR_NOSIG, NULL);
27594 
27595 	/*
27596 	 * Enter the squeue so that no new packets can come in
27597 	 */
27598 	error = squeue_synch_enter(connp->conn_sqp, connp, 0);
27599 	if (error != 0) {
27600 		/* failed to enter, free all the pre-allocated messages. */
27601 		freeb(stropt_mp);
27602 		freeb(ordrel_mp);
27603 		freeb(fused_sigurp_mp);
27604 		return;
27605 	}
27606 
27607 	/* Disable I/OAT during fallback */
27608 	tcp->tcp_sodirect = NULL;
27609 
27610 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
27611 	connp->conn_minor_arena = WR(q)->q_ptr;
27612 
27613 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
27614 
27615 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
27616 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
27617 
27618 	WR(q)->q_qinfo = &tcp_sock_winit;
27619 
27620 	if (!direct_sockfs)
27621 		tcp_disable_direct_sockfs(tcp);
27622 
27623 	/*
27624 	 * free the helper stream
27625 	 */
27626 	ip_free_helper_stream(connp);
27627 
27628 	/*
27629 	 * Notify the STREAM head about options
27630 	 */
27631 	DB_TYPE(stropt_mp) = M_SETOPTS;
27632 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27633 	stropt_mp->b_wptr += sizeof (struct stroptions);
27634 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27635 	stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
27636 
27637 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
27638 	    tcp->tcp_tcps->tcps_wroff_xtra);
27639 	if (tcp->tcp_snd_sack_ok)
27640 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
27641 	stropt->so_hiwat = tcp->tcp_fused ?
27642 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
27643 	    MAX(tcp->tcp_recv_hiwater, tcp->tcp_tcps->tcps_sth_rcv_hiwat);
27644 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
27645 
27646 	putnext(RD(q), stropt_mp);
27647 
27648 	/*
27649 	 * Collect the information needed to sync with the sonode
27650 	 */
27651 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
27652 
27653 	laddrlen = faddrlen = sizeof (sin6_t);
27654 	(void) tcp_getsockname(proto_handle, (struct sockaddr *)&laddr,
27655 	    &laddrlen, CRED());
27656 	error = tcp_getpeername(proto_handle, (struct sockaddr *)&faddr,
27657 	    &faddrlen, CRED());
27658 	if (error != 0)
27659 		faddrlen = 0;
27660 
27661 	opts = 0;
27662 	if (tcp->tcp_oobinline)
27663 		opts |= SO_OOBINLINE;
27664 	if (tcp->tcp_dontroute)
27665 		opts |= SO_DONTROUTE;
27666 
27667 	/*
27668 	 * Notify the socket that the protocol is now quiescent,
27669 	 * and it's therefore safe move data from the socket
27670 	 * to the stream head.
27671 	 */
27672 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
27673 	    (struct sockaddr *)&laddr, laddrlen,
27674 	    (struct sockaddr *)&faddr, faddrlen, opts);
27675 
27676 	while ((mp = tcp->tcp_rcv_list) != NULL) {
27677 		tcp->tcp_rcv_list = mp->b_next;
27678 		mp->b_next = NULL;
27679 		putnext(q, mp);
27680 	}
27681 	tcp->tcp_rcv_last_head = NULL;
27682 	tcp->tcp_rcv_last_tail = NULL;
27683 	tcp->tcp_rcv_cnt = 0;
27684 
27685 	/*
27686 	 * No longer a direct socket
27687 	 */
27688 	connp->conn_flags &= ~IPCL_NONSTR;
27689 
27690 	tcp->tcp_ordrel_mp = ordrel_mp;
27691 
27692 	if (tcp->tcp_fused) {
27693 		ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
27694 		tcp->tcp_fused_sigurg_mp = fused_sigurp_mp;
27695 	} else {
27696 		freeb(fused_sigurp_mp);
27697 	}
27698 
27699 	/*
27700 	 * Send T_CONN_IND messages for all ESTABLISHED connections.
27701 	 */
27702 	mutex_enter(&tcp->tcp_eager_lock);
27703 	for (eager = tcp->tcp_eager_next_q; eager != NULL;
27704 	    eager = eager->tcp_eager_next_q) {
27705 		mp = eager->tcp_conn.tcp_eager_conn_ind;
27706 
27707 		eager->tcp_conn.tcp_eager_conn_ind = NULL;
27708 		ASSERT(mp != NULL);
27709 		/*
27710 		 * TLI/XTI applications will get confused by
27711 		 * sending eager as an option since it violates
27712 		 * the option semantics. So remove the eager as
27713 		 * option since TLI/XTI app doesn't need it anyway.
27714 		 */
27715 		if (!TCP_IS_SOCKET(tcp)) {
27716 			struct T_conn_ind *conn_ind;
27717 
27718 			conn_ind = (struct T_conn_ind *)mp->b_rptr;
27719 			conn_ind->OPT_length = 0;
27720 			conn_ind->OPT_offset = 0;
27721 		}
27722 		if (conn_ind_head == NULL) {
27723 			conn_ind_head = mp;
27724 		} else {
27725 			conn_ind_tail->b_next = mp;
27726 		}
27727 		conn_ind_tail = mp;
27728 	}
27729 	mutex_exit(&tcp->tcp_eager_lock);
27730 
27731 	mp = conn_ind_head;
27732 	while (mp != NULL) {
27733 		mblk_t *nmp = mp->b_next;
27734 		mp->b_next = NULL;
27735 
27736 		putnext(tcp->tcp_rq, mp);
27737 		mp = nmp;
27738 	}
27739 
27740 	/*
27741 	 * There should be atleast two ref's (IP + TCP)
27742 	 */
27743 	ASSERT(connp->conn_ref >= 2);
27744 	squeue_synch_exit(connp->conn_sqp, connp);
27745 }
27746 
27747 /* ARGSUSED */
27748 static void
27749 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
27750 {
27751 	conn_t 	*connp = (conn_t *)arg;
27752 	tcp_t	*tcp = connp->conn_tcp;
27753 
27754 	freemsg(mp);
27755 
27756 	if (tcp->tcp_fused)
27757 		tcp_unfuse(tcp);
27758 
27759 	if (tcp_xmit_end(tcp) != 0) {
27760 		/*
27761 		 * We were crossing FINs and got a reset from
27762 		 * the other side. Just ignore it.
27763 		 */
27764 		if (tcp->tcp_debug) {
27765 			(void) strlog(TCP_MOD_ID, 0, 1,
27766 			    SL_ERROR|SL_TRACE,
27767 			    "tcp_shutdown_output() out of state %s",
27768 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
27769 		}
27770 	}
27771 }
27772 
27773 /* ARGSUSED */
27774 int
27775 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
27776 {
27777 	conn_t  *connp = (conn_t *)proto_handle;
27778 	tcp_t   *tcp = connp->conn_tcp;
27779 
27780 	ASSERT(connp->conn_upper_handle != NULL);
27781 
27782 	/*
27783 	 * X/Open requires that we check the connected state.
27784 	 */
27785 	if (tcp->tcp_state < TCPS_SYN_SENT)
27786 		return (ENOTCONN);
27787 
27788 	/* shutdown the send side */
27789 	if (how != SHUT_RD) {
27790 		mblk_t *bp;
27791 
27792 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
27793 		CONN_INC_REF(connp);
27794 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
27795 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
27796 
27797 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27798 		    SOCK_OPCTL_SHUT_SEND, 0);
27799 	}
27800 
27801 	/* shutdown the recv side */
27802 	if (how != SHUT_WR)
27803 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27804 		    SOCK_OPCTL_SHUT_RECV, 0);
27805 
27806 	return (0);
27807 }
27808 
27809 /*
27810  * SOP_LISTEN() calls into tcp_listen().
27811  */
27812 /* ARGSUSED */
27813 int
27814 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27815 {
27816 	conn_t	*connp = (conn_t *)proto_handle;
27817 	int 	error;
27818 	squeue_t *sqp = connp->conn_sqp;
27819 
27820 	ASSERT(connp->conn_upper_handle != NULL);
27821 
27822 	error = squeue_synch_enter(sqp, connp, 0);
27823 	if (error != 0) {
27824 		/* failed to enter */
27825 		return (ENOBUFS);
27826 	}
27827 
27828 	error = tcp_do_listen(connp, backlog, cr);
27829 	if (error == 0) {
27830 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27831 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
27832 	} else if (error < 0) {
27833 		if (error == -TOUTSTATE)
27834 			error = EINVAL;
27835 		else
27836 			error = proto_tlitosyserr(-error);
27837 	}
27838 	squeue_synch_exit(sqp, connp);
27839 	return (error);
27840 }
27841 
27842 static int
27843 tcp_do_listen(conn_t *connp, int backlog, cred_t *cr)
27844 {
27845 	tcp_t		*tcp = connp->conn_tcp;
27846 	sin_t		*sin;
27847 	sin6_t  	*sin6;
27848 	int		error = 0;
27849 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27850 
27851 	if (tcp->tcp_state >= TCPS_BOUND) {
27852 		if ((tcp->tcp_state == TCPS_BOUND ||
27853 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
27854 			/*
27855 			 * Handle listen() increasing backlog.
27856 			 * This is more "liberal" then what the TPI spec
27857 			 * requires but is needed to avoid a t_unbind
27858 			 * when handling listen() since the port number
27859 			 * might be "stolen" between the unbind and bind.
27860 			 */
27861 			goto do_listen;
27862 		}
27863 		if (tcp->tcp_debug) {
27864 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27865 			    "tcp_listen: bad state, %d", tcp->tcp_state);
27866 		}
27867 		return (-TOUTSTATE);
27868 	} else {
27869 		int32_t len;
27870 		sin6_t	addr;
27871 
27872 		/* Do an implicit bind: Request for a generic port. */
27873 		if (tcp->tcp_family == AF_INET) {
27874 			len = sizeof (sin_t);
27875 			sin = (sin_t *)&addr;
27876 			*sin = sin_null;
27877 			sin->sin_family = AF_INET;
27878 			tcp->tcp_ipversion = IPV4_VERSION;
27879 		} else {
27880 			ASSERT(tcp->tcp_family == AF_INET6);
27881 			len = sizeof (sin6_t);
27882 			sin6 = (sin6_t *)&addr;
27883 			*sin6 = sin6_null;
27884 			sin6->sin6_family = AF_INET6;
27885 			tcp->tcp_ipversion = IPV6_VERSION;
27886 		}
27887 
27888 		error = tcp_bind_check(connp, (struct sockaddr *)&addr, len,
27889 		    cr, B_FALSE);
27890 		if (error)
27891 			return (error);
27892 		/* Fall through and do the fanout insertion */
27893 	}
27894 
27895 do_listen:
27896 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
27897 	tcp->tcp_conn_req_max = backlog;
27898 	if (tcp->tcp_conn_req_max) {
27899 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
27900 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
27901 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
27902 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
27903 		/*
27904 		 * If this is a listener, do not reset the eager list
27905 		 * and other stuffs.  Note that we don't check if the
27906 		 * existing eager list meets the new tcp_conn_req_max
27907 		 * requirement.
27908 		 */
27909 		if (tcp->tcp_state != TCPS_LISTEN) {
27910 			tcp->tcp_state = TCPS_LISTEN;
27911 			/* Initialize the chain. Don't need the eager_lock */
27912 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
27913 			tcp->tcp_eager_next_drop_q0 = tcp;
27914 			tcp->tcp_eager_prev_drop_q0 = tcp;
27915 			tcp->tcp_second_ctimer_threshold =
27916 			    tcps->tcps_ip_abort_linterval;
27917 		}
27918 	}
27919 
27920 	/*
27921 	 * We can call ip_bind directly, the processing continues
27922 	 * in tcp_post_ip_bind().
27923 	 *
27924 	 * We need to make sure that the conn_recv is set to a non-null
27925 	 * value before we insert the conn into the classifier table.
27926 	 * This is to avoid a race with an incoming packet which does an
27927 	 * ipcl_classify().
27928 	 */
27929 	connp->conn_recv = tcp_conn_request;
27930 	if (tcp->tcp_family == AF_INET) {
27931 		error = ip_proto_bind_laddr_v4(connp, NULL,
27932 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
27933 	} else {
27934 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27935 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
27936 	}
27937 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27938 }
27939 
27940 void
27941 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
27942 {
27943 	conn_t  *connp = (conn_t *)proto_handle;
27944 	tcp_t	*tcp = connp->conn_tcp;
27945 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27946 	uint_t thwin;
27947 
27948 	ASSERT(connp->conn_upper_handle != NULL);
27949 
27950 	(void) squeue_synch_enter(connp->conn_sqp, connp, 0);
27951 
27952 	/* Flow control condition has been removed. */
27953 	tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
27954 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
27955 	    << tcp->tcp_rcv_ws;
27956 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
27957 	/*
27958 	 * Send back a window update immediately if TCP is above
27959 	 * ESTABLISHED state and the increase of the rcv window
27960 	 * that the other side knows is at least 1 MSS after flow
27961 	 * control is lifted.
27962 	 */
27963 	if (tcp->tcp_state >= TCPS_ESTABLISHED &&
27964 	    (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss)) {
27965 		tcp_xmit_ctl(NULL, tcp,
27966 		    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
27967 		    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
27968 		BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
27969 	}
27970 
27971 	squeue_synch_exit(connp->conn_sqp, connp);
27972 }
27973 
27974 /* ARGSUSED */
27975 int
27976 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
27977     int mode, int32_t *rvalp, cred_t *cr)
27978 {
27979 	conn_t  	*connp = (conn_t *)proto_handle;
27980 	int		error;
27981 
27982 	ASSERT(connp->conn_upper_handle != NULL);
27983 
27984 	switch (cmd) {
27985 		case ND_SET:
27986 		case ND_GET:
27987 		case TCP_IOC_DEFAULT_Q:
27988 		case _SIOCSOCKFALLBACK:
27989 		case TCP_IOC_ABORT_CONN:
27990 		case TI_GETPEERNAME:
27991 		case TI_GETMYNAME:
27992 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
27993 			    cmd));
27994 			error = EINVAL;
27995 			break;
27996 		default:
27997 			/*
27998 			 * Pass on to IP using helper stream
27999 			 */
28000 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
28001 			    cmd, arg, mode, cr, rvalp);
28002 			break;
28003 	}
28004 	return (error);
28005 }
28006 
28007 sock_downcalls_t sock_tcp_downcalls = {
28008 	tcp_activate,
28009 	tcp_accept,
28010 	tcp_bind,
28011 	tcp_listen,
28012 	tcp_connect,
28013 	tcp_getpeername,
28014 	tcp_getsockname,
28015 	tcp_getsockopt,
28016 	tcp_setsockopt,
28017 	tcp_sendmsg,
28018 	NULL,
28019 	NULL,
28020 	NULL,
28021 	tcp_shutdown,
28022 	tcp_clr_flowctrl,
28023 	tcp_ioctl,
28024 	tcp_close,
28025 };
28026