xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision 7ce76caa61769eef87a2368b9ef90e4661e3f193)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/strsun.h>
31 #include <sys/strsubr.h>
32 #include <sys/stropts.h>
33 #include <sys/strlog.h>
34 #include <sys/strsun.h>
35 #define	_SUN_TPI_VERSION 2
36 #include <sys/tihdr.h>
37 #include <sys/timod.h>
38 #include <sys/ddi.h>
39 #include <sys/sunddi.h>
40 #include <sys/suntpi.h>
41 #include <sys/xti_inet.h>
42 #include <sys/cmn_err.h>
43 #include <sys/debug.h>
44 #include <sys/sdt.h>
45 #include <sys/vtrace.h>
46 #include <sys/kmem.h>
47 #include <sys/ethernet.h>
48 #include <sys/cpuvar.h>
49 #include <sys/dlpi.h>
50 #include <sys/multidata.h>
51 #include <sys/multidata_impl.h>
52 #include <sys/pattr.h>
53 #include <sys/policy.h>
54 #include <sys/priv.h>
55 #include <sys/zone.h>
56 #include <sys/sunldi.h>
57 
58 #include <sys/errno.h>
59 #include <sys/signal.h>
60 #include <sys/socket.h>
61 #include <sys/socketvar.h>
62 #include <sys/sockio.h>
63 #include <sys/isa_defs.h>
64 #include <sys/md5.h>
65 #include <sys/random.h>
66 #include <sys/sodirect.h>
67 #include <sys/uio.h>
68 #include <sys/systm.h>
69 #include <netinet/in.h>
70 #include <netinet/tcp.h>
71 #include <netinet/ip6.h>
72 #include <netinet/icmp6.h>
73 #include <net/if.h>
74 #include <net/route.h>
75 #include <inet/ipsec_impl.h>
76 
77 #include <inet/common.h>
78 #include <inet/ip.h>
79 #include <inet/ip_impl.h>
80 #include <inet/ip6.h>
81 #include <inet/ip_ndp.h>
82 #include <inet/proto_set.h>
83 #include <inet/mib2.h>
84 #include <inet/nd.h>
85 #include <inet/optcom.h>
86 #include <inet/snmpcom.h>
87 #include <inet/kstatcom.h>
88 #include <inet/tcp.h>
89 #include <inet/tcp_impl.h>
90 #include <net/pfkeyv2.h>
91 #include <inet/ipsec_info.h>
92 #include <inet/ipdrop.h>
93 
94 #include <inet/ipclassifier.h>
95 #include <inet/ip_ire.h>
96 #include <inet/ip_ftable.h>
97 #include <inet/ip_if.h>
98 #include <inet/ipp_common.h>
99 #include <inet/ip_netinfo.h>
100 #include <sys/squeue_impl.h>
101 #include <sys/squeue.h>
102 #include <inet/kssl/ksslapi.h>
103 #include <sys/tsol/label.h>
104 #include <sys/tsol/tnet.h>
105 #include <rpc/pmap_prot.h>
106 #include <sys/callo.h>
107 
108 /*
109  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
110  *
111  * (Read the detailed design doc in PSARC case directory)
112  *
113  * The entire tcp state is contained in tcp_t and conn_t structure
114  * which are allocated in tandem using ipcl_conn_create() and passing
115  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
116  * the references on the tcp_t. The tcp_t structure is never compressed
117  * and packets always land on the correct TCP perimeter from the time
118  * eager is created till the time tcp_t dies (as such the old mentat
119  * TCP global queue is not used for detached state and no IPSEC checking
120  * is required). The global queue is still allocated to send out resets
121  * for connection which have no listeners and IP directly calls
122  * tcp_xmit_listeners_reset() which does any policy check.
123  *
124  * Protection and Synchronisation mechanism:
125  *
126  * The tcp data structure does not use any kind of lock for protecting
127  * its state but instead uses 'squeues' for mutual exclusion from various
128  * read and write side threads. To access a tcp member, the thread should
129  * always be behind squeue (via squeue_enter with flags as SQ_FILL, SQ_PROCESS,
130  * or SQ_NODRAIN). Since the squeues allow a direct function call, caller
131  * can pass any tcp function having prototype of edesc_t as argument
132  * (different from traditional STREAMs model where packets come in only
133  * designated entry points). The list of functions that can be directly
134  * called via squeue are listed before the usual function prototype.
135  *
136  * Referencing:
137  *
138  * TCP is MT-Hot and we use a reference based scheme to make sure that the
139  * tcp structure doesn't disappear when its needed. When the application
140  * creates an outgoing connection or accepts an incoming connection, we
141  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
142  * The IP reference is just a symbolic reference since ip_tcpclose()
143  * looks at tcp structure after tcp_close_output() returns which could
144  * have dropped the last TCP reference. So as long as the connection is
145  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
146  * conn_t. The classifier puts its own reference when the connection is
147  * inserted in listen or connected hash. Anytime a thread needs to enter
148  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
149  * on write side or by doing a classify on read side and then puts a
150  * reference on the conn before doing squeue_enter/tryenter/fill. For
151  * read side, the classifier itself puts the reference under fanout lock
152  * to make sure that tcp can't disappear before it gets processed. The
153  * squeue will drop this reference automatically so the called function
154  * doesn't have to do a DEC_REF.
155  *
156  * Opening a new connection:
157  *
158  * The outgoing connection open is pretty simple. tcp_open() does the
159  * work in creating the conn/tcp structure and initializing it. The
160  * squeue assignment is done based on the CPU the application
161  * is running on. So for outbound connections, processing is always done
162  * on application CPU which might be different from the incoming CPU
163  * being interrupted by the NIC. An optimal way would be to figure out
164  * the NIC <-> CPU binding at listen time, and assign the outgoing
165  * connection to the squeue attached to the CPU that will be interrupted
166  * for incoming packets (we know the NIC based on the bind IP address).
167  * This might seem like a problem if more data is going out but the
168  * fact is that in most cases the transmit is ACK driven transmit where
169  * the outgoing data normally sits on TCP's xmit queue waiting to be
170  * transmitted.
171  *
172  * Accepting a connection:
173  *
174  * This is a more interesting case because of various races involved in
175  * establishing a eager in its own perimeter. Read the meta comment on
176  * top of tcp_conn_request(). But briefly, the squeue is picked by
177  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
178  *
179  * Closing a connection:
180  *
181  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
182  * via squeue to do the close and mark the tcp as detached if the connection
183  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
184  * reference but tcp_close() drop IP's reference always. So if tcp was
185  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
186  * and 1 because it is in classifier's connected hash. This is the condition
187  * we use to determine that its OK to clean up the tcp outside of squeue
188  * when time wait expires (check the ref under fanout and conn_lock and
189  * if it is 2, remove it from fanout hash and kill it).
190  *
191  * Although close just drops the necessary references and marks the
192  * tcp_detached state, tcp_close needs to know the tcp_detached has been
193  * set (under squeue) before letting the STREAM go away (because a
194  * inbound packet might attempt to go up the STREAM while the close
195  * has happened and tcp_detached is not set). So a special lock and
196  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
197  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
198  * tcp_detached.
199  *
200  * Special provisions and fast paths:
201  *
202  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
203  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
204  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
205  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
206  * check to send packets directly to tcp_rput_data via squeue. Everyone
207  * else comes through tcp_input() on the read side.
208  *
209  * We also make special provisions for sockfs by marking tcp_issocket
210  * whenever we have only sockfs on top of TCP. This allows us to skip
211  * putting the tcp in acceptor hash since a sockfs listener can never
212  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
213  * since eager has already been allocated and the accept now happens
214  * on acceptor STREAM. There is a big blob of comment on top of
215  * tcp_conn_request explaining the new accept. When socket is POP'd,
216  * sockfs sends us an ioctl to mark the fact and we go back to old
217  * behaviour. Once tcp_issocket is unset, its never set for the
218  * life of that connection.
219  *
220  * In support of on-board asynchronous DMA hardware (e.g. Intel I/OAT)
221  * two consoldiation private KAPIs are used to enqueue M_DATA mblk_t's
222  * directly to the socket (sodirect) and start an asynchronous copyout
223  * to a user-land receive-side buffer (uioa) when a blocking socket read
224  * (e.g. read, recv, ...) is pending.
225  *
226  * This is accomplished when tcp_issocket is set and tcp_sodirect is not
227  * NULL so points to an sodirect_t and if marked enabled then we enqueue
228  * all mblk_t's directly to the socket.
229  *
230  * Further, if the sodirect_t sod_uioa and if marked enabled (due to a
231  * blocking socket read, e.g. user-land read, recv, ...) then an asynchronous
232  * copyout will be started directly to the user-land uio buffer. Also, as we
233  * have a pending read, TCP's push logic can take into account the number of
234  * bytes to be received and only awake the blocked read()er when the uioa_t
235  * byte count has been satisfied.
236  *
237  * IPsec notes :
238  *
239  * Since a packet is always executed on the correct TCP perimeter
240  * all IPsec processing is defered to IP including checking new
241  * connections and setting IPSEC policies for new connection. The
242  * only exception is tcp_xmit_listeners_reset() which is called
243  * directly from IP and needs to policy check to see if TH_RST
244  * can be sent out.
245  *
246  * PFHooks notes :
247  *
248  * For mdt case, one meta buffer contains multiple packets. Mblks for every
249  * packet are assembled and passed to the hooks. When packets are blocked,
250  * or boundary of any packet is changed, the mdt processing is stopped, and
251  * packets of the meta buffer are send to the IP path one by one.
252  */
253 
254 /*
255  * Values for squeue switch:
256  * 1: SQ_NODRAIN
257  * 2: SQ_PROCESS
258  * 3: SQ_FILL
259  */
260 int tcp_squeue_wput = 2;	/* /etc/systems */
261 int tcp_squeue_flag;
262 
263 /*
264  * Macros for sodirect:
265  *
266  * SOD_PTR_ENTER(tcp, sodp) - for the tcp_t pointer "tcp" set the
267  * sodirect_t pointer "sodp" to the socket/tcp shared sodirect_t
268  * if it exists and is enabled, else to NULL. Note, in the current
269  * sodirect implementation the sod_lockp must not be held across any
270  * STREAMS call (e.g. putnext) else a "recursive mutex_enter" PANIC
271  * will result as sod_lockp is the streamhead stdata.sd_lock.
272  *
273  * SOD_NOT_ENABLED(tcp) - return true if not a sodirect tcp_t or the
274  * sodirect_t isn't enabled, usefull for ASSERT()ing that a recieve
275  * side tcp code path dealing with a tcp_rcv_list or putnext() isn't
276  * being used when sodirect code paths should be.
277  */
278 
279 #define	SOD_PTR_ENTER(tcp, sodp)					\
280 	(sodp) = (tcp)->tcp_sodirect;					\
281 									\
282 	if ((sodp) != NULL) {						\
283 		mutex_enter((sodp)->sod_lockp);				\
284 		if (!((sodp)->sod_state & SOD_ENABLED)) {		\
285 			mutex_exit((sodp)->sod_lockp);			\
286 			(sodp) = NULL;					\
287 		}							\
288 	}
289 
290 #define	SOD_NOT_ENABLED(tcp)						\
291 	((tcp)->tcp_sodirect == NULL ||					\
292 	    !((tcp)->tcp_sodirect->sod_state & SOD_ENABLED))
293 
294 /*
295  * This controls how tiny a write must be before we try to copy it
296  * into the the mblk on the tail of the transmit queue.  Not much
297  * speedup is observed for values larger than sixteen.  Zero will
298  * disable the optimisation.
299  */
300 int tcp_tx_pull_len = 16;
301 
302 /*
303  * TCP Statistics.
304  *
305  * How TCP statistics work.
306  *
307  * There are two types of statistics invoked by two macros.
308  *
309  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
310  * supposed to be used in non MT-hot paths of the code.
311  *
312  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
313  * supposed to be used for DEBUG purposes and may be used on a hot path.
314  *
315  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
316  * (use "kstat tcp" to get them).
317  *
318  * There is also additional debugging facility that marks tcp_clean_death()
319  * instances and saves them in tcp_t structure. It is triggered by
320  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
321  * tcp_clean_death() calls that counts the number of times each tag was hit. It
322  * is triggered by TCP_CLD_COUNTERS define.
323  *
324  * How to add new counters.
325  *
326  * 1) Add a field in the tcp_stat structure describing your counter.
327  * 2) Add a line in the template in tcp_kstat2_init() with the name
328  *    of the counter.
329  *
330  *    IMPORTANT!! - make sure that both are in sync !!
331  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
332  *
333  * Please avoid using private counters which are not kstat-exported.
334  *
335  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
336  * in tcp_t structure.
337  *
338  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
339  */
340 
341 #ifndef TCP_DEBUG_COUNTER
342 #ifdef DEBUG
343 #define	TCP_DEBUG_COUNTER 1
344 #else
345 #define	TCP_DEBUG_COUNTER 0
346 #endif
347 #endif
348 
349 #define	TCP_CLD_COUNTERS 0
350 
351 #define	TCP_TAG_CLEAN_DEATH 1
352 #define	TCP_MAX_CLEAN_DEATH_TAG 32
353 
354 #ifdef lint
355 static int _lint_dummy_;
356 #endif
357 
358 #if TCP_CLD_COUNTERS
359 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
360 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
361 #elif defined(lint)
362 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
363 #else
364 #define	TCP_CLD_STAT(x)
365 #endif
366 
367 #if TCP_DEBUG_COUNTER
368 #define	TCP_DBGSTAT(tcps, x)	\
369 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
370 #define	TCP_G_DBGSTAT(x)	\
371 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
372 #elif defined(lint)
373 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
374 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
375 #else
376 #define	TCP_DBGSTAT(tcps, x)
377 #define	TCP_G_DBGSTAT(x)
378 #endif
379 
380 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
381 
382 tcp_g_stat_t	tcp_g_statistics;
383 kstat_t		*tcp_g_kstat;
384 
385 /*
386  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
387  * tcp write side.
388  */
389 #define	CALL_IP_WPUT(connp, q, mp) {					\
390 	ASSERT(((q)->q_flag & QREADR) == 0);				\
391 	TCP_DBGSTAT(connp->conn_netstack->netstack_tcp, tcp_ip_output);	\
392 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
393 }
394 
395 /* Macros for timestamp comparisons */
396 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
397 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
398 
399 /*
400  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
401  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
402  * by adding three components: a time component which grows by 1 every 4096
403  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
404  * a per-connection component which grows by 125000 for every new connection;
405  * and an "extra" component that grows by a random amount centered
406  * approximately on 64000.  This causes the the ISS generator to cycle every
407  * 4.89 hours if no TCP connections are made, and faster if connections are
408  * made.
409  *
410  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
411  * components: a time component which grows by 250000 every second; and
412  * a per-connection component which grows by 125000 for every new connections.
413  *
414  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
415  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
416  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
417  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
418  * password.
419  */
420 #define	ISS_INCR	250000
421 #define	ISS_NSEC_SHT	12
422 
423 static sin_t	sin_null;	/* Zero address for quick clears */
424 static sin6_t	sin6_null;	/* Zero address for quick clears */
425 
426 /*
427  * This implementation follows the 4.3BSD interpretation of the urgent
428  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
429  * incompatible changes in protocols like telnet and rlogin.
430  */
431 #define	TCP_OLD_URP_INTERPRETATION	1
432 
433 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
434 	(TCP_IS_DETACHED(tcp) && \
435 	    (!(tcp)->tcp_hard_binding))
436 
437 /*
438  * TCP reassembly macros.  We hide starting and ending sequence numbers in
439  * b_next and b_prev of messages on the reassembly queue.  The messages are
440  * chained using b_cont.  These macros are used in tcp_reass() so we don't
441  * have to see the ugly casts and assignments.
442  */
443 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
444 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
445 					(mblk_t *)(uintptr_t)(u))
446 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
447 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
448 					(mblk_t *)(uintptr_t)(u))
449 
450 /*
451  * Implementation of TCP Timers.
452  * =============================
453  *
454  * INTERFACE:
455  *
456  * There are two basic functions dealing with tcp timers:
457  *
458  *	timeout_id_t	tcp_timeout(connp, func, time)
459  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
460  *	TCP_TIMER_RESTART(tcp, intvl)
461  *
462  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
463  * after 'time' ticks passed. The function called by timeout() must adhere to
464  * the same restrictions as a driver soft interrupt handler - it must not sleep
465  * or call other functions that might sleep. The value returned is the opaque
466  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
467  * cancel the request. The call to tcp_timeout() may fail in which case it
468  * returns zero. This is different from the timeout(9F) function which never
469  * fails.
470  *
471  * The call-back function 'func' always receives 'connp' as its single
472  * argument. It is always executed in the squeue corresponding to the tcp
473  * structure. The tcp structure is guaranteed to be present at the time the
474  * call-back is called.
475  *
476  * NOTE: The call-back function 'func' is never called if tcp is in
477  * 	the TCPS_CLOSED state.
478  *
479  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
480  * request. locks acquired by the call-back routine should not be held across
481  * the call to tcp_timeout_cancel() or a deadlock may result.
482  *
483  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
484  * Otherwise, it returns an integer value greater than or equal to 0. In
485  * particular, if the call-back function is already placed on the squeue, it can
486  * not be canceled.
487  *
488  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
489  * 	within squeue context corresponding to the tcp instance. Since the
490  *	call-back is also called via the same squeue, there are no race
491  *	conditions described in untimeout(9F) manual page since all calls are
492  *	strictly serialized.
493  *
494  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
495  *	stored in tcp_timer_tid and starts a new one using
496  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
497  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
498  *	field.
499  *
500  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
501  *	call-back may still be called, so it is possible tcp_timer() will be
502  *	called several times. This should not be a problem since tcp_timer()
503  *	should always check the tcp instance state.
504  *
505  *
506  * IMPLEMENTATION:
507  *
508  * TCP timers are implemented using three-stage process. The call to
509  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
510  * when the timer expires. The tcp_timer_callback() arranges the call of the
511  * tcp_timer_handler() function via squeue corresponding to the tcp
512  * instance. The tcp_timer_handler() calls actual requested timeout call-back
513  * and passes tcp instance as an argument to it. Information is passed between
514  * stages using the tcp_timer_t structure which contains the connp pointer, the
515  * tcp call-back to call and the timeout id returned by the timeout(9F).
516  *
517  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
518  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
519  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
520  * returns the pointer to this mblk.
521  *
522  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
523  * looks like a normal mblk without actual dblk attached to it.
524  *
525  * To optimize performance each tcp instance holds a small cache of timer
526  * mblocks. In the current implementation it caches up to two timer mblocks per
527  * tcp instance. The cache is preserved over tcp frees and is only freed when
528  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
529  * timer processing happens on a corresponding squeue, the cache manipulation
530  * does not require any locks. Experiments show that majority of timer mblocks
531  * allocations are satisfied from the tcp cache and do not involve kmem calls.
532  *
533  * The tcp_timeout() places a refhold on the connp instance which guarantees
534  * that it will be present at the time the call-back function fires. The
535  * tcp_timer_handler() drops the reference after calling the call-back, so the
536  * call-back function does not need to manipulate the references explicitly.
537  */
538 
539 typedef struct tcp_timer_s {
540 	conn_t	*connp;
541 	void 	(*tcpt_proc)(void *);
542 	callout_id_t   tcpt_tid;
543 } tcp_timer_t;
544 
545 static kmem_cache_t *tcp_timercache;
546 kmem_cache_t	*tcp_sack_info_cache;
547 kmem_cache_t	*tcp_iphc_cache;
548 
549 /*
550  * For scalability, we must not run a timer for every TCP connection
551  * in TIME_WAIT state.  To see why, consider (for time wait interval of
552  * 4 minutes):
553  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
554  *
555  * This list is ordered by time, so you need only delete from the head
556  * until you get to entries which aren't old enough to delete yet.
557  * The list consists of only the detached TIME_WAIT connections.
558  *
559  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
560  * becomes detached TIME_WAIT (either by changing the state and already
561  * being detached or the other way around). This means that the TIME_WAIT
562  * state can be extended (up to doubled) if the connection doesn't become
563  * detached for a long time.
564  *
565  * The list manipulations (including tcp_time_wait_next/prev)
566  * are protected by the tcp_time_wait_lock. The content of the
567  * detached TIME_WAIT connections is protected by the normal perimeters.
568  *
569  * This list is per squeue and squeues are shared across the tcp_stack_t's.
570  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
571  * and conn_netstack.
572  * The tcp_t's that are added to tcp_free_list are disassociated and
573  * have NULL tcp_tcps and conn_netstack pointers.
574  */
575 typedef struct tcp_squeue_priv_s {
576 	kmutex_t	tcp_time_wait_lock;
577 	callout_id_t	tcp_time_wait_tid;
578 	tcp_t		*tcp_time_wait_head;
579 	tcp_t		*tcp_time_wait_tail;
580 	tcp_t		*tcp_free_list;
581 	uint_t		tcp_free_list_cnt;
582 } tcp_squeue_priv_t;
583 
584 /*
585  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
586  * Running it every 5 seconds seems to give the best results.
587  */
588 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
589 
590 /*
591  * To prevent memory hog, limit the number of entries in tcp_free_list
592  * to 1% of available memory / number of cpus
593  */
594 uint_t tcp_free_list_max_cnt = 0;
595 
596 #define	TCP_XMIT_LOWATER	4096
597 #define	TCP_XMIT_HIWATER	49152
598 #define	TCP_RECV_LOWATER	2048
599 #define	TCP_RECV_HIWATER	49152
600 
601 /*
602  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
603  */
604 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
605 
606 #define	TIDUSZ	4096	/* transport interface data unit size */
607 
608 /*
609  * Bind hash list size and has function.  It has to be a power of 2 for
610  * hashing.
611  */
612 #define	TCP_BIND_FANOUT_SIZE	512
613 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
614 /*
615  * Size of listen and acceptor hash list.  It has to be a power of 2 for
616  * hashing.
617  */
618 #define	TCP_FANOUT_SIZE		256
619 
620 #ifdef	_ILP32
621 #define	TCP_ACCEPTOR_HASH(accid)					\
622 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
623 #else
624 #define	TCP_ACCEPTOR_HASH(accid)					\
625 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
626 #endif	/* _ILP32 */
627 
628 #define	IP_ADDR_CACHE_SIZE	2048
629 #define	IP_ADDR_CACHE_HASH(faddr)					\
630 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
631 
632 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
633 #define	TCP_HSP_HASH_SIZE 256
634 
635 #define	TCP_HSP_HASH(addr)					\
636 	(((addr>>24) ^ (addr >>16) ^			\
637 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
638 
639 /*
640  * TCP options struct returned from tcp_parse_options.
641  */
642 typedef struct tcp_opt_s {
643 	uint32_t	tcp_opt_mss;
644 	uint32_t	tcp_opt_wscale;
645 	uint32_t	tcp_opt_ts_val;
646 	uint32_t	tcp_opt_ts_ecr;
647 	tcp_t		*tcp;
648 } tcp_opt_t;
649 
650 /*
651  * TCP option struct passing information b/w lisenter and eager.
652  */
653 struct tcp_options {
654 	uint_t			to_flags;
655 	ssize_t			to_boundif;	/* IPV6_BOUND_IF */
656 	sock_upper_handle_t	to_handle;
657 };
658 
659 #define	TCPOPT_BOUNDIF		0x00000001	/* set IPV6_BOUND_IF */
660 #define	TCPOPT_RECVPKTINFO	0x00000002	/* set IPV6_RECVPKTINFO */
661 #define	TCPOPT_UPPERHANDLE	0x00000004	/* set upper handle */
662 
663 /*
664  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
665  */
666 
667 #ifdef _BIG_ENDIAN
668 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
669 	(TCPOPT_TSTAMP << 8) | 10)
670 #else
671 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
672 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
673 #endif
674 
675 /*
676  * Flags returned from tcp_parse_options.
677  */
678 #define	TCP_OPT_MSS_PRESENT	1
679 #define	TCP_OPT_WSCALE_PRESENT	2
680 #define	TCP_OPT_TSTAMP_PRESENT	4
681 #define	TCP_OPT_SACK_OK_PRESENT	8
682 #define	TCP_OPT_SACK_PRESENT	16
683 
684 /* TCP option length */
685 #define	TCPOPT_NOP_LEN		1
686 #define	TCPOPT_MAXSEG_LEN	4
687 #define	TCPOPT_WS_LEN		3
688 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
689 #define	TCPOPT_TSTAMP_LEN	10
690 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
691 #define	TCPOPT_SACK_OK_LEN	2
692 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
693 #define	TCPOPT_REAL_SACK_LEN	4
694 #define	TCPOPT_MAX_SACK_LEN	36
695 #define	TCPOPT_HEADER_LEN	2
696 
697 /* TCP cwnd burst factor. */
698 #define	TCP_CWND_INFINITE	65535
699 #define	TCP_CWND_SS		3
700 #define	TCP_CWND_NORMAL		5
701 
702 /* Maximum TCP initial cwin (start/restart). */
703 #define	TCP_MAX_INIT_CWND	8
704 
705 /*
706  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
707  * either tcp_slow_start_initial or tcp_slow_start_after idle
708  * depending on the caller.  If the upper layer has not used the
709  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
710  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
711  * If the upper layer has changed set the tcp_init_cwnd, just use
712  * it to calculate the tcp_cwnd.
713  */
714 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
715 {									\
716 	if ((tcp)->tcp_init_cwnd == 0) {				\
717 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
718 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
719 	} else {							\
720 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
721 	}								\
722 	tcp->tcp_cwnd_cnt = 0;						\
723 }
724 
725 /* TCP Timer control structure */
726 typedef struct tcpt_s {
727 	pfv_t	tcpt_pfv;	/* The routine we are to call */
728 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
729 } tcpt_t;
730 
731 /* Host Specific Parameter structure */
732 typedef struct tcp_hsp {
733 	struct tcp_hsp	*tcp_hsp_next;
734 	in6_addr_t	tcp_hsp_addr_v6;
735 	in6_addr_t	tcp_hsp_subnet_v6;
736 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
737 	int32_t		tcp_hsp_sendspace;
738 	int32_t		tcp_hsp_recvspace;
739 	int32_t		tcp_hsp_tstamp;
740 } tcp_hsp_t;
741 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
742 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
743 
744 /*
745  * Functions called directly via squeue having a prototype of edesc_t.
746  */
747 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
748 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
749 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
750 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
751 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
752 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
753 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
754 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
755 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
756 void		tcp_output_urgent(void *arg, mblk_t *mp, void *arg2);
757 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
758 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
759 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
760 
761 
762 /* Prototype for TCP functions */
763 static void	tcp_random_init(void);
764 int		tcp_random(void);
765 static void	tcp_tli_accept(tcp_t *tcp, mblk_t *mp);
766 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
767 		    tcp_t *eager);
768 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
769 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
770     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
771     boolean_t user_specified);
772 static void	tcp_closei_local(tcp_t *tcp);
773 static void	tcp_close_detached(tcp_t *tcp);
774 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
775 			mblk_t *idmp, mblk_t **defermp);
776 static void	tcp_tpi_connect(tcp_t *tcp, mblk_t *mp);
777 static int	tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
778 		    in_port_t dstport, uint_t srcid, cred_t *cr, pid_t pid);
779 static int 	tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
780 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
781 		    uint32_t scope_id, cred_t *cr, pid_t pid);
782 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
783 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
784 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
785 static char	*tcp_display(tcp_t *tcp, char *, char);
786 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
787 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
788 static void	tcp_eager_unlink(tcp_t *tcp);
789 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
790 		    int unixerr);
791 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
792 		    int tlierr, int unixerr);
793 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
794 		    cred_t *cr);
795 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
796 		    char *value, caddr_t cp, cred_t *cr);
797 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
798 		    char *value, caddr_t cp, cred_t *cr);
799 static int	tcp_tpistate(tcp_t *tcp);
800 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
801     int caller_holds_lock);
802 static void	tcp_bind_hash_remove(tcp_t *tcp);
803 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
804 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
805 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
806 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
807 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
808 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
809 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
810 void		tcp_g_q_setup(tcp_stack_t *);
811 void		tcp_g_q_create(tcp_stack_t *);
812 void		tcp_g_q_destroy(tcp_stack_t *);
813 static int	tcp_header_init_ipv4(tcp_t *tcp);
814 static int	tcp_header_init_ipv6(tcp_t *tcp);
815 int		tcp_init(tcp_t *tcp, queue_t *q);
816 static int	tcp_init_values(tcp_t *tcp);
817 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
818 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
819 static void	tcp_ip_notify(tcp_t *tcp);
820 static mblk_t	*tcp_ire_mp(mblk_t **mpp);
821 static void	tcp_iss_init(tcp_t *tcp);
822 static void	tcp_keepalive_killer(void *arg);
823 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
824 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
825 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
826 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
827 static boolean_t tcp_allow_connopt_set(int level, int name);
828 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
829 int		tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
830 int		tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level,
831 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
832 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
833 		    mblk_t *mblk);
834 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
835 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
836 		    uchar_t *ptr, uint_t len);
837 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
838 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
839     tcp_stack_t *);
840 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
841 		    caddr_t cp, cred_t *cr);
842 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
843 		    caddr_t cp, cred_t *cr);
844 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
845 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
846 		    caddr_t cp, cred_t *cr);
847 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
848 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
849 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
850 static void	tcp_reinit(tcp_t *tcp);
851 static void	tcp_reinit_values(tcp_t *tcp);
852 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
853 		    tcp_t *thisstream, cred_t *cr);
854 
855 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
856 static uint_t	tcp_rcv_drain(tcp_t *tcp);
857 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
858 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
859 static void	tcp_ss_rexmit(tcp_t *tcp);
860 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
861 static void	tcp_process_options(tcp_t *, tcph_t *);
862 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
863 static void	tcp_rsrv(queue_t *q);
864 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
865 static int	tcp_snmp_state(tcp_t *tcp);
866 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
867 		    cred_t *cr);
868 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
869 		    cred_t *cr);
870 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
871 		    cred_t *cr);
872 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
873 		    cred_t *cr);
874 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
875 		    cred_t *cr);
876 static void	tcp_timer(void *arg);
877 static void	tcp_timer_callback(void *);
878 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
879     boolean_t random);
880 static in_port_t tcp_get_next_priv_port(const tcp_t *);
881 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
882 static void	tcp_wput_fallback(queue_t *q, mblk_t *mp);
883 void		tcp_tpi_accept(queue_t *q, mblk_t *mp);
884 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
885 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
886 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
887 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
888 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
889 		    const int num_sack_blk, int *usable, uint_t *snxt,
890 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
891 		    const int mdt_thres);
892 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
893 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
894 		    const int num_sack_blk, int *usable, uint_t *snxt,
895 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
896 		    const int mdt_thres);
897 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
898 		    int num_sack_blk);
899 static void	tcp_wsrv(queue_t *q);
900 static int	tcp_xmit_end(tcp_t *tcp);
901 static void	tcp_ack_timer(void *arg);
902 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
903 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
904 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
905 		    zoneid_t zoneid, tcp_stack_t *, conn_t *connp);
906 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
907 		    uint32_t ack, int ctl);
908 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *);
909 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr, tcp_stack_t *);
910 static int	setmaxps(queue_t *q, int maxpsz);
911 static void	tcp_set_rto(tcp_t *, time_t);
912 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
913 		    boolean_t, boolean_t);
914 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
915 		    boolean_t ipsec_mctl);
916 static int	tcp_build_hdrs(tcp_t *);
917 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
918 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
919 		    tcph_t *tcph);
920 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
921 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
922 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
923 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
924 		    const boolean_t, const uint32_t, const uint32_t,
925 		    const uint32_t, const uint32_t, tcp_stack_t *);
926 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
927 		    const uint_t, const uint_t, boolean_t *);
928 static mblk_t	*tcp_lso_info_mp(mblk_t *);
929 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
930 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
931 extern mblk_t	*tcp_timermp_alloc(int);
932 extern void	tcp_timermp_free(tcp_t *);
933 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
934 static void	tcp_stop_lingering(tcp_t *tcp);
935 static void	tcp_close_linger_timeout(void *arg);
936 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
937 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
938 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
939 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
940 static void	tcp_g_kstat_fini(kstat_t *);
941 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
942 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
943 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
944 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
945 static int	tcp_kstat_update(kstat_t *kp, int rw);
946 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
947 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
948 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
949 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
950 			tcph_t *tcph, mblk_t *idmp);
951 static int	tcp_squeue_switch(int);
952 
953 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
954 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
955 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
956 static int	tcp_tpi_close(queue_t *, int);
957 static int	tcpclose_accept(queue_t *);
958 
959 static void	tcp_squeue_add(squeue_t *);
960 static boolean_t tcp_zcopy_check(tcp_t *);
961 static void	tcp_zcopy_notify(tcp_t *);
962 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
963 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
964 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
965 
966 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
967 
968 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
969 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
970 
971 static int tcp_accept(sock_lower_handle_t, sock_lower_handle_t,
972 	    sock_upper_handle_t, cred_t *);
973 static int tcp_listen(sock_lower_handle_t, int, cred_t *);
974 static int tcp_post_ip_bind(tcp_t *, mblk_t *, int);
975 static int tcp_do_listen(conn_t *, int, cred_t *);
976 static int tcp_do_connect(conn_t *, const struct sockaddr *, socklen_t,
977     cred_t *, pid_t);
978 static int tcp_do_bind(conn_t *, struct sockaddr *, socklen_t, cred_t *,
979     boolean_t);
980 static int tcp_do_unbind(conn_t *);
981 static int tcp_bind_check(conn_t *, struct sockaddr *, socklen_t, cred_t *,
982     boolean_t);
983 
984 /*
985  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
986  *
987  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
988  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
989  * (defined in tcp.h) needs to be filled in and passed into the kernel
990  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
991  * structure contains the four-tuple of a TCP connection and a range of TCP
992  * states (specified by ac_start and ac_end). The use of wildcard addresses
993  * and ports is allowed. Connections with a matching four tuple and a state
994  * within the specified range will be aborted. The valid states for the
995  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
996  * inclusive.
997  *
998  * An application which has its connection aborted by this ioctl will receive
999  * an error that is dependent on the connection state at the time of the abort.
1000  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
1001  * though a RST packet has been received.  If the connection state is equal to
1002  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
1003  * and all resources associated with the connection will be freed.
1004  */
1005 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
1006 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
1007 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
1008 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
1009 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
1010 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
1011     boolean_t, tcp_stack_t *);
1012 
1013 static struct module_info tcp_rinfo =  {
1014 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
1015 };
1016 
1017 static struct module_info tcp_winfo =  {
1018 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
1019 };
1020 
1021 /*
1022  * Entry points for TCP as a device. The normal case which supports
1023  * the TCP functionality.
1024  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
1025  */
1026 struct qinit tcp_rinitv4 = {
1027 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, NULL, &tcp_rinfo
1028 };
1029 
1030 struct qinit tcp_rinitv6 = {
1031 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_tpi_close, NULL, &tcp_rinfo
1032 };
1033 
1034 struct qinit tcp_winit = {
1035 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1036 };
1037 
1038 /* Initial entry point for TCP in socket mode. */
1039 struct qinit tcp_sock_winit = {
1040 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1041 };
1042 
1043 /* TCP entry point during fallback */
1044 struct qinit tcp_fallback_sock_winit = {
1045 	(pfi_t)tcp_wput_fallback, NULL, NULL, NULL, NULL, &tcp_winfo
1046 };
1047 
1048 /*
1049  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1050  * an accept. Avoid allocating data structures since eager has already
1051  * been created.
1052  */
1053 struct qinit tcp_acceptor_rinit = {
1054 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1055 };
1056 
1057 struct qinit tcp_acceptor_winit = {
1058 	(pfi_t)tcp_tpi_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1059 };
1060 
1061 /*
1062  * Entry points for TCP loopback (read side only)
1063  * The open routine is only used for reopens, thus no need to
1064  * have a separate one for tcp_openv6.
1065  */
1066 struct qinit tcp_loopback_rinit = {
1067 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, (pfi_t)0,
1068 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1069 };
1070 
1071 /* For AF_INET aka /dev/tcp */
1072 struct streamtab tcpinfov4 = {
1073 	&tcp_rinitv4, &tcp_winit
1074 };
1075 
1076 /* For AF_INET6 aka /dev/tcp6 */
1077 struct streamtab tcpinfov6 = {
1078 	&tcp_rinitv6, &tcp_winit
1079 };
1080 
1081 sock_downcalls_t sock_tcp_downcalls;
1082 
1083 /*
1084  * Have to ensure that tcp_g_q_close is not done by an
1085  * interrupt thread.
1086  */
1087 static taskq_t *tcp_taskq;
1088 
1089 /* Setable only in /etc/system. Move to ndd? */
1090 boolean_t tcp_icmp_source_quench = B_FALSE;
1091 
1092 /*
1093  * Following assumes TPI alignment requirements stay along 32 bit
1094  * boundaries
1095  */
1096 #define	ROUNDUP32(x) \
1097 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1098 
1099 /* Template for response to info request. */
1100 static struct T_info_ack tcp_g_t_info_ack = {
1101 	T_INFO_ACK,		/* PRIM_type */
1102 	0,			/* TSDU_size */
1103 	T_INFINITE,		/* ETSDU_size */
1104 	T_INVALID,		/* CDATA_size */
1105 	T_INVALID,		/* DDATA_size */
1106 	sizeof (sin_t),		/* ADDR_size */
1107 	0,			/* OPT_size - not initialized here */
1108 	TIDUSZ,			/* TIDU_size */
1109 	T_COTS_ORD,		/* SERV_type */
1110 	TCPS_IDLE,		/* CURRENT_state */
1111 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1112 };
1113 
1114 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1115 	T_INFO_ACK,		/* PRIM_type */
1116 	0,			/* TSDU_size */
1117 	T_INFINITE,		/* ETSDU_size */
1118 	T_INVALID,		/* CDATA_size */
1119 	T_INVALID,		/* DDATA_size */
1120 	sizeof (sin6_t),	/* ADDR_size */
1121 	0,			/* OPT_size - not initialized here */
1122 	TIDUSZ,		/* TIDU_size */
1123 	T_COTS_ORD,		/* SERV_type */
1124 	TCPS_IDLE,		/* CURRENT_state */
1125 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1126 };
1127 
1128 #define	MS	1L
1129 #define	SECONDS	(1000 * MS)
1130 #define	MINUTES	(60 * SECONDS)
1131 #define	HOURS	(60 * MINUTES)
1132 #define	DAYS	(24 * HOURS)
1133 
1134 #define	PARAM_MAX (~(uint32_t)0)
1135 
1136 /* Max size IP datagram is 64k - 1 */
1137 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1138 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1139 /* Max of the above */
1140 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1141 
1142 /* Largest TCP port number */
1143 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1144 
1145 /*
1146  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1147  * layer header.  It has to be a multiple of 4.
1148  */
1149 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1150 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1151 
1152 /*
1153  * All of these are alterable, within the min/max values given, at run time.
1154  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1155  * per the TCP spec.
1156  */
1157 /* BEGIN CSTYLED */
1158 static tcpparam_t	lcl_tcp_param_arr[] = {
1159  /*min		max		value		name */
1160  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1161  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1162  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1163  { 1,		1024,		1,		"tcp_conn_req_min" },
1164  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1165  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1166  { 0,		10,		0,		"tcp_debug" },
1167  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1168  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1169  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1170  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1171  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1172  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1173  { 1,		255,		64,		"tcp_ipv4_ttl"},
1174  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1175  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1176  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1177  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1178  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1179  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1180  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1181  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1182  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1183  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1184  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1185  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1186  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1187  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1188  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1189  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1190  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1191  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1192  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1193  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1194  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1195  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1196  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1197 /*
1198  * Question:  What default value should I set for tcp_strong_iss?
1199  */
1200  { 0,		2,		1,		"tcp_strong_iss"},
1201  { 0,		65536,		20,		"tcp_rtt_updates"},
1202  { 0,		1,		1,		"tcp_wscale_always"},
1203  { 0,		1,		0,		"tcp_tstamp_always"},
1204  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1205  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1206  { 0,		16,		2,		"tcp_deferred_acks_max"},
1207  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1208  { 1,		4,		4,		"tcp_slow_start_initial"},
1209  { 0,		2,		2,		"tcp_sack_permitted"},
1210  { 0,		1,		1,		"tcp_compression_enabled"},
1211  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1212  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1213  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1214  { 0,		1,		0,		"tcp_rev_src_routes"},
1215  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1216  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1217  { 0,		16,		8,		"tcp_local_dacks_max"},
1218  { 0,		2,		1,		"tcp_ecn_permitted"},
1219  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1220  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1221  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1222  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1223  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1224 };
1225 /* END CSTYLED */
1226 
1227 /*
1228  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1229  * each header fragment in the header buffer.  Each parameter value has
1230  * to be a multiple of 4 (32-bit aligned).
1231  */
1232 static tcpparam_t lcl_tcp_mdt_head_param =
1233 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1234 static tcpparam_t lcl_tcp_mdt_tail_param =
1235 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1236 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1237 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1238 
1239 /*
1240  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1241  * the maximum number of payload buffers associated per Multidata.
1242  */
1243 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1244 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1245 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1246 
1247 /* Round up the value to the nearest mss. */
1248 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1249 
1250 /*
1251  * Set ECN capable transport (ECT) code point in IP header.
1252  *
1253  * Note that there are 2 ECT code points '01' and '10', which are called
1254  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1255  * point ECT(0) for TCP as described in RFC 2481.
1256  */
1257 #define	SET_ECT(tcp, iph) \
1258 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1259 		/* We need to clear the code point first. */ \
1260 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1261 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1262 	} else { \
1263 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1264 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1265 	}
1266 
1267 /*
1268  * The format argument to pass to tcp_display().
1269  * DISP_PORT_ONLY means that the returned string has only port info.
1270  * DISP_ADDR_AND_PORT means that the returned string also contains the
1271  * remote and local IP address.
1272  */
1273 #define	DISP_PORT_ONLY		1
1274 #define	DISP_ADDR_AND_PORT	2
1275 
1276 #define	NDD_TOO_QUICK_MSG \
1277 	"ndd get info rate too high for non-privileged users, try again " \
1278 	"later.\n"
1279 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1280 
1281 #define	IS_VMLOANED_MBLK(mp) \
1282 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1283 
1284 
1285 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1286 boolean_t tcp_mdt_chain = B_TRUE;
1287 
1288 /*
1289  * MDT threshold in the form of effective send MSS multiplier; we take
1290  * the MDT path if the amount of unsent data exceeds the threshold value
1291  * (default threshold is 1*SMSS).
1292  */
1293 uint_t tcp_mdt_smss_threshold = 1;
1294 
1295 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1296 
1297 /*
1298  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1299  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1300  * determined dynamically during tcp_adapt_ire(), which is the default.
1301  */
1302 boolean_t tcp_static_maxpsz = B_FALSE;
1303 
1304 /* Setable in /etc/system */
1305 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1306 uint32_t tcp_random_anon_port = 1;
1307 
1308 /*
1309  * To reach to an eager in Q0 which can be dropped due to an incoming
1310  * new SYN request when Q0 is full, a new doubly linked list is
1311  * introduced. This list allows to select an eager from Q0 in O(1) time.
1312  * This is needed to avoid spending too much time walking through the
1313  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1314  * this new list has to be a member of Q0.
1315  * This list is headed by listener's tcp_t. When the list is empty,
1316  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1317  * of listener's tcp_t point to listener's tcp_t itself.
1318  *
1319  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1320  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1321  * These macros do not affect the eager's membership to Q0.
1322  */
1323 
1324 
1325 #define	MAKE_DROPPABLE(listener, eager)					\
1326 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1327 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1328 		    = (eager);						\
1329 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1330 		(eager)->tcp_eager_next_drop_q0 =			\
1331 		    (listener)->tcp_eager_next_drop_q0;			\
1332 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1333 	}
1334 
1335 #define	MAKE_UNDROPPABLE(eager)						\
1336 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1337 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1338 		    = (eager)->tcp_eager_prev_drop_q0;			\
1339 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1340 		    = (eager)->tcp_eager_next_drop_q0;			\
1341 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1342 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1343 	}
1344 
1345 /*
1346  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1347  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1348  * data, TCP will not respond with an ACK.  RFC 793 requires that
1349  * TCP responds with an ACK for such a bogus ACK.  By not following
1350  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1351  * an attacker successfully spoofs an acceptable segment to our
1352  * peer; or when our peer is "confused."
1353  */
1354 uint32_t tcp_drop_ack_unsent_cnt = 10;
1355 
1356 /*
1357  * Hook functions to enable cluster networking
1358  * On non-clustered systems these vectors must always be NULL.
1359  */
1360 
1361 void (*cl_inet_listen)(netstackid_t stack_id, uint8_t protocol,
1362 			    sa_family_t addr_family, uint8_t *laddrp,
1363 			    in_port_t lport, void *args) = NULL;
1364 void (*cl_inet_unlisten)(netstackid_t stack_id, uint8_t protocol,
1365 			    sa_family_t addr_family, uint8_t *laddrp,
1366 			    in_port_t lport, void *args) = NULL;
1367 
1368 int (*cl_inet_connect2)(netstackid_t stack_id, uint8_t protocol,
1369 			    boolean_t is_outgoing,
1370 			    sa_family_t addr_family,
1371 			    uint8_t *laddrp, in_port_t lport,
1372 			    uint8_t *faddrp, in_port_t fport,
1373 			    void *args) = NULL;
1374 
1375 void (*cl_inet_disconnect)(netstackid_t stack_id, uint8_t protocol,
1376 			    sa_family_t addr_family, uint8_t *laddrp,
1377 			    in_port_t lport, uint8_t *faddrp,
1378 			    in_port_t fport, void *args) = NULL;
1379 
1380 /*
1381  * The following are defined in ip.c
1382  */
1383 extern int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
1384 			    sa_family_t addr_family, uint8_t *laddrp,
1385 			    void *args);
1386 extern uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
1387 			    sa_family_t addr_family, uint8_t *laddrp,
1388 			    uint8_t *faddrp, void *args);
1389 
1390 
1391 /*
1392  * int CL_INET_CONNECT(conn_t *cp, tcp_t *tcp, boolean_t is_outgoing, int err)
1393  */
1394 #define	CL_INET_CONNECT(connp, tcp, is_outgoing, err) {		\
1395 	(err) = 0;						\
1396 	if (cl_inet_connect2 != NULL) {				\
1397 		/*						\
1398 		 * Running in cluster mode - register active connection	\
1399 		 * information						\
1400 		 */							\
1401 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1402 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1403 				(err) = (*cl_inet_connect2)(		\
1404 				    (connp)->conn_netstack->netstack_stackid,\
1405 				    IPPROTO_TCP, is_outgoing, AF_INET,	\
1406 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1407 				    (in_port_t)(tcp)->tcp_lport,	\
1408 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1409 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1410 			}						\
1411 		} else {						\
1412 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1413 			    &(tcp)->tcp_ip6h->ip6_src)) {		\
1414 				(err) = (*cl_inet_connect2)(		\
1415 				    (connp)->conn_netstack->netstack_stackid,\
1416 				    IPPROTO_TCP, is_outgoing, AF_INET6,	\
1417 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1418 				    (in_port_t)(tcp)->tcp_lport,	\
1419 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1420 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1421 			}						\
1422 		}							\
1423 	}								\
1424 }
1425 
1426 #define	CL_INET_DISCONNECT(connp, tcp)	{				\
1427 	if (cl_inet_disconnect != NULL) {				\
1428 		/*							\
1429 		 * Running in cluster mode - deregister active		\
1430 		 * connection information				\
1431 		 */							\
1432 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1433 			if ((tcp)->tcp_ip_src != 0) {			\
1434 				(*cl_inet_disconnect)(			\
1435 				    (connp)->conn_netstack->netstack_stackid,\
1436 				    IPPROTO_TCP, AF_INET,		\
1437 				    (uint8_t *)(&((tcp)->tcp_ip_src)),	\
1438 				    (in_port_t)(tcp)->tcp_lport,	\
1439 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1440 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1441 			}						\
1442 		} else {						\
1443 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1444 			    &(tcp)->tcp_ip_src_v6)) {			\
1445 				(*cl_inet_disconnect)(			\
1446 				    (connp)->conn_netstack->netstack_stackid,\
1447 				    IPPROTO_TCP, AF_INET6,		\
1448 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1449 				    (in_port_t)(tcp)->tcp_lport,	\
1450 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1451 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1452 			}						\
1453 		}							\
1454 	}								\
1455 }
1456 
1457 /*
1458  * Cluster networking hook for traversing current connection list.
1459  * This routine is used to extract the current list of live connections
1460  * which must continue to to be dispatched to this node.
1461  */
1462 int cl_tcp_walk_list(netstackid_t stack_id,
1463     int (*callback)(cl_tcp_info_t *, void *), void *arg);
1464 
1465 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1466     void *arg, tcp_stack_t *tcps);
1467 
1468 #define	DTRACE_IP_FASTPATH(mp, iph, ill, ipha, ip6h) 			\
1469 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,	\
1470 	    iph, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha,		\
1471 	    ip6_t *, ip6h, int, 0);
1472 
1473 /*
1474  * Figure out the value of window scale opton.  Note that the rwnd is
1475  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1476  * We cannot find the scale value and then do a round up of tcp_rwnd
1477  * because the scale value may not be correct after that.
1478  *
1479  * Set the compiler flag to make this function inline.
1480  */
1481 static void
1482 tcp_set_ws_value(tcp_t *tcp)
1483 {
1484 	int i;
1485 	uint32_t rwnd = tcp->tcp_rwnd;
1486 
1487 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1488 	    i++, rwnd >>= 1)
1489 		;
1490 	tcp->tcp_rcv_ws = i;
1491 }
1492 
1493 /*
1494  * Remove a connection from the list of detached TIME_WAIT connections.
1495  * It returns B_FALSE if it can't remove the connection from the list
1496  * as the connection has already been removed from the list due to an
1497  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1498  */
1499 static boolean_t
1500 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1501 {
1502 	boolean_t	locked = B_FALSE;
1503 
1504 	if (tcp_time_wait == NULL) {
1505 		tcp_time_wait = *((tcp_squeue_priv_t **)
1506 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1507 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1508 		locked = B_TRUE;
1509 	} else {
1510 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1511 	}
1512 
1513 	if (tcp->tcp_time_wait_expire == 0) {
1514 		ASSERT(tcp->tcp_time_wait_next == NULL);
1515 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1516 		if (locked)
1517 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1518 		return (B_FALSE);
1519 	}
1520 	ASSERT(TCP_IS_DETACHED(tcp));
1521 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1522 
1523 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1524 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1525 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1526 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1527 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1528 			    NULL;
1529 		} else {
1530 			tcp_time_wait->tcp_time_wait_tail = NULL;
1531 		}
1532 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1533 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1534 		ASSERT(tcp->tcp_time_wait_next == NULL);
1535 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1536 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1537 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1538 	} else {
1539 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1540 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1541 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1542 		    tcp->tcp_time_wait_next;
1543 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1544 		    tcp->tcp_time_wait_prev;
1545 	}
1546 	tcp->tcp_time_wait_next = NULL;
1547 	tcp->tcp_time_wait_prev = NULL;
1548 	tcp->tcp_time_wait_expire = 0;
1549 
1550 	if (locked)
1551 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1552 	return (B_TRUE);
1553 }
1554 
1555 /*
1556  * Add a connection to the list of detached TIME_WAIT connections
1557  * and set its time to expire.
1558  */
1559 static void
1560 tcp_time_wait_append(tcp_t *tcp)
1561 {
1562 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1563 	tcp_squeue_priv_t *tcp_time_wait =
1564 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1565 	    SQPRIVATE_TCP));
1566 
1567 	tcp_timers_stop(tcp);
1568 
1569 	/* Freed above */
1570 	ASSERT(tcp->tcp_timer_tid == 0);
1571 	ASSERT(tcp->tcp_ack_tid == 0);
1572 
1573 	/* must have happened at the time of detaching the tcp */
1574 	ASSERT(tcp->tcp_ptpahn == NULL);
1575 	ASSERT(tcp->tcp_flow_stopped == 0);
1576 	ASSERT(tcp->tcp_time_wait_next == NULL);
1577 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1578 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1579 	ASSERT(tcp->tcp_listener == NULL);
1580 
1581 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1582 	/*
1583 	 * The value computed below in tcp->tcp_time_wait_expire may
1584 	 * appear negative or wrap around. That is ok since our
1585 	 * interest is only in the difference between the current lbolt
1586 	 * value and tcp->tcp_time_wait_expire. But the value should not
1587 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1588 	 * The corresponding comparison in tcp_time_wait_collector() uses
1589 	 * modular arithmetic.
1590 	 */
1591 	tcp->tcp_time_wait_expire +=
1592 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1593 	if (tcp->tcp_time_wait_expire == 0)
1594 		tcp->tcp_time_wait_expire = 1;
1595 
1596 	ASSERT(TCP_IS_DETACHED(tcp));
1597 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1598 	ASSERT(tcp->tcp_time_wait_next == NULL);
1599 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1600 	TCP_DBGSTAT(tcps, tcp_time_wait);
1601 
1602 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1603 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1604 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1605 		tcp_time_wait->tcp_time_wait_head = tcp;
1606 	} else {
1607 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1608 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1609 		    TCPS_TIME_WAIT);
1610 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1611 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1612 	}
1613 	tcp_time_wait->tcp_time_wait_tail = tcp;
1614 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1615 }
1616 
1617 /* ARGSUSED */
1618 void
1619 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1620 {
1621 	conn_t	*connp = (conn_t *)arg;
1622 	tcp_t	*tcp = connp->conn_tcp;
1623 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1624 
1625 	ASSERT(tcp != NULL);
1626 	if (tcp->tcp_state == TCPS_CLOSED) {
1627 		return;
1628 	}
1629 
1630 	ASSERT((tcp->tcp_family == AF_INET &&
1631 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1632 	    (tcp->tcp_family == AF_INET6 &&
1633 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1634 	    tcp->tcp_ipversion == IPV6_VERSION)));
1635 	ASSERT(!tcp->tcp_listener);
1636 
1637 	TCP_STAT(tcps, tcp_time_wait_reap);
1638 	ASSERT(TCP_IS_DETACHED(tcp));
1639 
1640 	/*
1641 	 * Because they have no upstream client to rebind or tcp_close()
1642 	 * them later, we axe the connection here and now.
1643 	 */
1644 	tcp_close_detached(tcp);
1645 }
1646 
1647 /*
1648  * Remove cached/latched IPsec references.
1649  */
1650 void
1651 tcp_ipsec_cleanup(tcp_t *tcp)
1652 {
1653 	conn_t		*connp = tcp->tcp_connp;
1654 
1655 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1656 
1657 	if (connp->conn_latch != NULL) {
1658 		IPLATCH_REFRELE(connp->conn_latch,
1659 		    connp->conn_netstack);
1660 		connp->conn_latch = NULL;
1661 	}
1662 	if (connp->conn_policy != NULL) {
1663 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1664 		connp->conn_policy = NULL;
1665 	}
1666 }
1667 
1668 /*
1669  * Cleaup before placing on free list.
1670  * Disassociate from the netstack/tcp_stack_t since the freelist
1671  * is per squeue and not per netstack.
1672  */
1673 void
1674 tcp_cleanup(tcp_t *tcp)
1675 {
1676 	mblk_t		*mp;
1677 	char		*tcp_iphc;
1678 	int		tcp_iphc_len;
1679 	int		tcp_hdr_grown;
1680 	tcp_sack_info_t	*tcp_sack_info;
1681 	conn_t		*connp = tcp->tcp_connp;
1682 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1683 	netstack_t	*ns = tcps->tcps_netstack;
1684 	mblk_t		*tcp_rsrv_mp;
1685 
1686 	tcp_bind_hash_remove(tcp);
1687 
1688 	/* Cleanup that which needs the netstack first */
1689 	tcp_ipsec_cleanup(tcp);
1690 
1691 	tcp_free(tcp);
1692 
1693 	/* Release any SSL context */
1694 	if (tcp->tcp_kssl_ent != NULL) {
1695 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1696 		tcp->tcp_kssl_ent = NULL;
1697 	}
1698 
1699 	if (tcp->tcp_kssl_ctx != NULL) {
1700 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1701 		tcp->tcp_kssl_ctx = NULL;
1702 	}
1703 	tcp->tcp_kssl_pending = B_FALSE;
1704 
1705 	conn_delete_ire(connp, NULL);
1706 
1707 	/*
1708 	 * Since we will bzero the entire structure, we need to
1709 	 * remove it and reinsert it in global hash list. We
1710 	 * know the walkers can't get to this conn because we
1711 	 * had set CONDEMNED flag earlier and checked reference
1712 	 * under conn_lock so walker won't pick it and when we
1713 	 * go the ipcl_globalhash_remove() below, no walker
1714 	 * can get to it.
1715 	 */
1716 	ipcl_globalhash_remove(connp);
1717 
1718 	/*
1719 	 * Now it is safe to decrement the reference counts.
1720 	 * This might be the last reference on the netstack and TCPS
1721 	 * in which case it will cause the tcp_g_q_close and
1722 	 * the freeing of the IP Instance.
1723 	 */
1724 	connp->conn_netstack = NULL;
1725 	netstack_rele(ns);
1726 	ASSERT(tcps != NULL);
1727 	tcp->tcp_tcps = NULL;
1728 	TCPS_REFRELE(tcps);
1729 
1730 	/* Save some state */
1731 	mp = tcp->tcp_timercache;
1732 
1733 	tcp_sack_info = tcp->tcp_sack_info;
1734 	tcp_iphc = tcp->tcp_iphc;
1735 	tcp_iphc_len = tcp->tcp_iphc_len;
1736 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1737 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1738 
1739 	if (connp->conn_cred != NULL) {
1740 		crfree(connp->conn_cred);
1741 		connp->conn_cred = NULL;
1742 	}
1743 	if (connp->conn_peercred != NULL) {
1744 		crfree(connp->conn_peercred);
1745 		connp->conn_peercred = NULL;
1746 	}
1747 	ipcl_conn_cleanup(connp);
1748 	connp->conn_flags = IPCL_TCPCONN;
1749 	bzero(tcp, sizeof (tcp_t));
1750 
1751 	/* restore the state */
1752 	tcp->tcp_timercache = mp;
1753 
1754 	tcp->tcp_sack_info = tcp_sack_info;
1755 	tcp->tcp_iphc = tcp_iphc;
1756 	tcp->tcp_iphc_len = tcp_iphc_len;
1757 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1758 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1759 
1760 	tcp->tcp_connp = connp;
1761 
1762 	ASSERT(connp->conn_tcp == tcp);
1763 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1764 	connp->conn_state_flags = CONN_INCIPIENT;
1765 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1766 	ASSERT(connp->conn_ref == 1);
1767 }
1768 
1769 /*
1770  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1771  * is done forwards from the head.
1772  * This walks all stack instances since
1773  * tcp_time_wait remains global across all stacks.
1774  */
1775 /* ARGSUSED */
1776 void
1777 tcp_time_wait_collector(void *arg)
1778 {
1779 	tcp_t *tcp;
1780 	clock_t now;
1781 	mblk_t *mp;
1782 	conn_t *connp;
1783 	kmutex_t *lock;
1784 	boolean_t removed;
1785 
1786 	squeue_t *sqp = (squeue_t *)arg;
1787 	tcp_squeue_priv_t *tcp_time_wait =
1788 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1789 
1790 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1791 	tcp_time_wait->tcp_time_wait_tid = 0;
1792 
1793 	if (tcp_time_wait->tcp_free_list != NULL &&
1794 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1795 		TCP_G_STAT(tcp_freelist_cleanup);
1796 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1797 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1798 			tcp->tcp_time_wait_next = NULL;
1799 			tcp_time_wait->tcp_free_list_cnt--;
1800 			ASSERT(tcp->tcp_tcps == NULL);
1801 			CONN_DEC_REF(tcp->tcp_connp);
1802 		}
1803 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1804 	}
1805 
1806 	/*
1807 	 * In order to reap time waits reliably, we should use a
1808 	 * source of time that is not adjustable by the user -- hence
1809 	 * the call to ddi_get_lbolt().
1810 	 */
1811 	now = ddi_get_lbolt();
1812 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1813 		/*
1814 		 * Compare times using modular arithmetic, since
1815 		 * lbolt can wrapover.
1816 		 */
1817 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1818 			break;
1819 		}
1820 
1821 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1822 		ASSERT(removed);
1823 
1824 		connp = tcp->tcp_connp;
1825 		ASSERT(connp->conn_fanout != NULL);
1826 		lock = &connp->conn_fanout->connf_lock;
1827 		/*
1828 		 * This is essentially a TW reclaim fast path optimization for
1829 		 * performance where the timewait collector checks under the
1830 		 * fanout lock (so that no one else can get access to the
1831 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1832 		 * the classifier hash list. If ref count is indeed 2, we can
1833 		 * just remove the conn under the fanout lock and avoid
1834 		 * cleaning up the conn under the squeue, provided that
1835 		 * clustering callbacks are not enabled. If clustering is
1836 		 * enabled, we need to make the clustering callback before
1837 		 * setting the CONDEMNED flag and after dropping all locks and
1838 		 * so we forego this optimization and fall back to the slow
1839 		 * path. Also please see the comments in tcp_closei_local
1840 		 * regarding the refcnt logic.
1841 		 *
1842 		 * Since we are holding the tcp_time_wait_lock, its better
1843 		 * not to block on the fanout_lock because other connections
1844 		 * can't add themselves to time_wait list. So we do a
1845 		 * tryenter instead of mutex_enter.
1846 		 */
1847 		if (mutex_tryenter(lock)) {
1848 			mutex_enter(&connp->conn_lock);
1849 			if ((connp->conn_ref == 2) &&
1850 			    (cl_inet_disconnect == NULL)) {
1851 				ipcl_hash_remove_locked(connp,
1852 				    connp->conn_fanout);
1853 				/*
1854 				 * Set the CONDEMNED flag now itself so that
1855 				 * the refcnt cannot increase due to any
1856 				 * walker. But we have still not cleaned up
1857 				 * conn_ire_cache. This is still ok since
1858 				 * we are going to clean it up in tcp_cleanup
1859 				 * immediately and any interface unplumb
1860 				 * thread will wait till the ire is blown away
1861 				 */
1862 				connp->conn_state_flags |= CONN_CONDEMNED;
1863 				mutex_exit(lock);
1864 				mutex_exit(&connp->conn_lock);
1865 				if (tcp_time_wait->tcp_free_list_cnt <
1866 				    tcp_free_list_max_cnt) {
1867 					/* Add to head of tcp_free_list */
1868 					mutex_exit(
1869 					    &tcp_time_wait->tcp_time_wait_lock);
1870 					tcp_cleanup(tcp);
1871 					ASSERT(connp->conn_latch == NULL);
1872 					ASSERT(connp->conn_policy == NULL);
1873 					ASSERT(tcp->tcp_tcps == NULL);
1874 					ASSERT(connp->conn_netstack == NULL);
1875 
1876 					mutex_enter(
1877 					    &tcp_time_wait->tcp_time_wait_lock);
1878 					tcp->tcp_time_wait_next =
1879 					    tcp_time_wait->tcp_free_list;
1880 					tcp_time_wait->tcp_free_list = tcp;
1881 					tcp_time_wait->tcp_free_list_cnt++;
1882 					continue;
1883 				} else {
1884 					/* Do not add to tcp_free_list */
1885 					mutex_exit(
1886 					    &tcp_time_wait->tcp_time_wait_lock);
1887 					tcp_bind_hash_remove(tcp);
1888 					conn_delete_ire(tcp->tcp_connp, NULL);
1889 					tcp_ipsec_cleanup(tcp);
1890 					CONN_DEC_REF(tcp->tcp_connp);
1891 				}
1892 			} else {
1893 				CONN_INC_REF_LOCKED(connp);
1894 				mutex_exit(lock);
1895 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1896 				mutex_exit(&connp->conn_lock);
1897 				/*
1898 				 * We can reuse the closemp here since conn has
1899 				 * detached (otherwise we wouldn't even be in
1900 				 * time_wait list). tcp_closemp_used can safely
1901 				 * be changed without taking a lock as no other
1902 				 * thread can concurrently access it at this
1903 				 * point in the connection lifecycle.
1904 				 */
1905 
1906 				if (tcp->tcp_closemp.b_prev == NULL)
1907 					tcp->tcp_closemp_used = B_TRUE;
1908 				else
1909 					cmn_err(CE_PANIC,
1910 					    "tcp_timewait_collector: "
1911 					    "concurrent use of tcp_closemp: "
1912 					    "connp %p tcp %p\n", (void *)connp,
1913 					    (void *)tcp);
1914 
1915 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1916 				mp = &tcp->tcp_closemp;
1917 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1918 				    tcp_timewait_output, connp,
1919 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1920 			}
1921 		} else {
1922 			mutex_enter(&connp->conn_lock);
1923 			CONN_INC_REF_LOCKED(connp);
1924 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1925 			mutex_exit(&connp->conn_lock);
1926 			/*
1927 			 * We can reuse the closemp here since conn has
1928 			 * detached (otherwise we wouldn't even be in
1929 			 * time_wait list). tcp_closemp_used can safely
1930 			 * be changed without taking a lock as no other
1931 			 * thread can concurrently access it at this
1932 			 * point in the connection lifecycle.
1933 			 */
1934 
1935 			if (tcp->tcp_closemp.b_prev == NULL)
1936 				tcp->tcp_closemp_used = B_TRUE;
1937 			else
1938 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1939 				    "concurrent use of tcp_closemp: "
1940 				    "connp %p tcp %p\n", (void *)connp,
1941 				    (void *)tcp);
1942 
1943 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1944 			mp = &tcp->tcp_closemp;
1945 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1946 			    tcp_timewait_output, connp,
1947 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1948 		}
1949 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1950 	}
1951 
1952 	if (tcp_time_wait->tcp_free_list != NULL)
1953 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1954 
1955 	tcp_time_wait->tcp_time_wait_tid =
1956 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1957 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1958 	    CALLOUT_FLAG_ROUNDUP);
1959 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1960 }
1961 
1962 /*
1963  * Reply to a clients T_CONN_RES TPI message. This function
1964  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1965  * on the acceptor STREAM and processed in tcp_wput_accept().
1966  * Read the block comment on top of tcp_conn_request().
1967  */
1968 static void
1969 tcp_tli_accept(tcp_t *listener, mblk_t *mp)
1970 {
1971 	tcp_t	*acceptor;
1972 	tcp_t	*eager;
1973 	tcp_t   *tcp;
1974 	struct T_conn_res	*tcr;
1975 	t_uscalar_t	acceptor_id;
1976 	t_scalar_t	seqnum;
1977 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1978 	struct tcp_options *tcpopt;
1979 	mblk_t	*ok_mp;
1980 	mblk_t	*mp1;
1981 	tcp_stack_t	*tcps = listener->tcp_tcps;
1982 
1983 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1984 		tcp_err_ack(listener, mp, TPROTO, 0);
1985 		return;
1986 	}
1987 	tcr = (struct T_conn_res *)mp->b_rptr;
1988 
1989 	/*
1990 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1991 	 * read side queue of the streams device underneath us i.e. the
1992 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1993 	 * look it up in the queue_hash.  Under LP64 it sends down the
1994 	 * minor_t of the accepting endpoint.
1995 	 *
1996 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1997 	 * fanout hash lock is held.
1998 	 * This prevents any thread from entering the acceptor queue from
1999 	 * below (since it has not been hard bound yet i.e. any inbound
2000 	 * packets will arrive on the listener or default tcp queue and
2001 	 * go through tcp_lookup).
2002 	 * The CONN_INC_REF will prevent the acceptor from closing.
2003 	 *
2004 	 * XXX It is still possible for a tli application to send down data
2005 	 * on the accepting stream while another thread calls t_accept.
2006 	 * This should not be a problem for well-behaved applications since
2007 	 * the T_OK_ACK is sent after the queue swapping is completed.
2008 	 *
2009 	 * If the accepting fd is the same as the listening fd, avoid
2010 	 * queue hash lookup since that will return an eager listener in a
2011 	 * already established state.
2012 	 */
2013 	acceptor_id = tcr->ACCEPTOR_id;
2014 	mutex_enter(&listener->tcp_eager_lock);
2015 	if (listener->tcp_acceptor_id == acceptor_id) {
2016 		eager = listener->tcp_eager_next_q;
2017 		/* only count how many T_CONN_INDs so don't count q0 */
2018 		if ((listener->tcp_conn_req_cnt_q != 1) ||
2019 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
2020 			mutex_exit(&listener->tcp_eager_lock);
2021 			tcp_err_ack(listener, mp, TBADF, 0);
2022 			return;
2023 		}
2024 		if (listener->tcp_conn_req_cnt_q0 != 0) {
2025 			/* Throw away all the eagers on q0. */
2026 			tcp_eager_cleanup(listener, 1);
2027 		}
2028 		if (listener->tcp_syn_defense) {
2029 			listener->tcp_syn_defense = B_FALSE;
2030 			if (listener->tcp_ip_addr_cache != NULL) {
2031 				kmem_free(listener->tcp_ip_addr_cache,
2032 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
2033 				listener->tcp_ip_addr_cache = NULL;
2034 			}
2035 		}
2036 		/*
2037 		 * Transfer tcp_conn_req_max to the eager so that when
2038 		 * a disconnect occurs we can revert the endpoint to the
2039 		 * listen state.
2040 		 */
2041 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
2042 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
2043 		/*
2044 		 * Get a reference on the acceptor just like the
2045 		 * tcp_acceptor_hash_lookup below.
2046 		 */
2047 		acceptor = listener;
2048 		CONN_INC_REF(acceptor->tcp_connp);
2049 	} else {
2050 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
2051 		if (acceptor == NULL) {
2052 			if (listener->tcp_debug) {
2053 				(void) strlog(TCP_MOD_ID, 0, 1,
2054 				    SL_ERROR|SL_TRACE,
2055 				    "tcp_accept: did not find acceptor 0x%x\n",
2056 				    acceptor_id);
2057 			}
2058 			mutex_exit(&listener->tcp_eager_lock);
2059 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2060 			return;
2061 		}
2062 		/*
2063 		 * Verify acceptor state. The acceptable states for an acceptor
2064 		 * include TCPS_IDLE and TCPS_BOUND.
2065 		 */
2066 		switch (acceptor->tcp_state) {
2067 		case TCPS_IDLE:
2068 			/* FALLTHRU */
2069 		case TCPS_BOUND:
2070 			break;
2071 		default:
2072 			CONN_DEC_REF(acceptor->tcp_connp);
2073 			mutex_exit(&listener->tcp_eager_lock);
2074 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2075 			return;
2076 		}
2077 	}
2078 
2079 	/* The listener must be in TCPS_LISTEN */
2080 	if (listener->tcp_state != TCPS_LISTEN) {
2081 		CONN_DEC_REF(acceptor->tcp_connp);
2082 		mutex_exit(&listener->tcp_eager_lock);
2083 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2084 		return;
2085 	}
2086 
2087 	/*
2088 	 * Rendezvous with an eager connection request packet hanging off
2089 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2090 	 * tcp structure when the connection packet arrived in
2091 	 * tcp_conn_request().
2092 	 */
2093 	seqnum = tcr->SEQ_number;
2094 	eager = listener;
2095 	do {
2096 		eager = eager->tcp_eager_next_q;
2097 		if (eager == NULL) {
2098 			CONN_DEC_REF(acceptor->tcp_connp);
2099 			mutex_exit(&listener->tcp_eager_lock);
2100 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2101 			return;
2102 		}
2103 	} while (eager->tcp_conn_req_seqnum != seqnum);
2104 	mutex_exit(&listener->tcp_eager_lock);
2105 
2106 	/*
2107 	 * At this point, both acceptor and listener have 2 ref
2108 	 * that they begin with. Acceptor has one additional ref
2109 	 * we placed in lookup while listener has 3 additional
2110 	 * ref for being behind the squeue (tcp_accept() is
2111 	 * done on listener's squeue); being in classifier hash;
2112 	 * and eager's ref on listener.
2113 	 */
2114 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2115 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2116 
2117 	/*
2118 	 * The eager at this point is set in its own squeue and
2119 	 * could easily have been killed (tcp_accept_finish will
2120 	 * deal with that) because of a TH_RST so we can only
2121 	 * ASSERT for a single ref.
2122 	 */
2123 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2124 
2125 	/* Pre allocate the stroptions mblk also */
2126 	opt_mp = allocb(MAX(sizeof (struct tcp_options),
2127 	    sizeof (struct T_conn_res)), BPRI_HI);
2128 	if (opt_mp == NULL) {
2129 		CONN_DEC_REF(acceptor->tcp_connp);
2130 		CONN_DEC_REF(eager->tcp_connp);
2131 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2132 		return;
2133 	}
2134 	DB_TYPE(opt_mp) = M_SETOPTS;
2135 	opt_mp->b_wptr += sizeof (struct tcp_options);
2136 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
2137 	tcpopt->to_flags = 0;
2138 
2139 	/*
2140 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2141 	 * from listener to acceptor.
2142 	 */
2143 	if (listener->tcp_bound_if != 0) {
2144 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
2145 		tcpopt->to_boundif = listener->tcp_bound_if;
2146 	}
2147 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2148 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
2149 	}
2150 
2151 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2152 	if ((mp1 = copymsg(mp)) == NULL) {
2153 		CONN_DEC_REF(acceptor->tcp_connp);
2154 		CONN_DEC_REF(eager->tcp_connp);
2155 		freemsg(opt_mp);
2156 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2157 		return;
2158 	}
2159 
2160 	tcr = (struct T_conn_res *)mp1->b_rptr;
2161 
2162 	/*
2163 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2164 	 * which allocates a larger mblk and appends the new
2165 	 * local address to the ok_ack.  The address is copied by
2166 	 * soaccept() for getsockname().
2167 	 */
2168 	{
2169 		int extra;
2170 
2171 		extra = (eager->tcp_family == AF_INET) ?
2172 		    sizeof (sin_t) : sizeof (sin6_t);
2173 
2174 		/*
2175 		 * Try to re-use mp, if possible.  Otherwise, allocate
2176 		 * an mblk and return it as ok_mp.  In any case, mp
2177 		 * is no longer usable upon return.
2178 		 */
2179 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2180 			CONN_DEC_REF(acceptor->tcp_connp);
2181 			CONN_DEC_REF(eager->tcp_connp);
2182 			freemsg(opt_mp);
2183 			/* Original mp has been freed by now, so use mp1 */
2184 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2185 			return;
2186 		}
2187 
2188 		mp = NULL;	/* We should never use mp after this point */
2189 
2190 		switch (extra) {
2191 		case sizeof (sin_t): {
2192 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2193 
2194 				ok_mp->b_wptr += extra;
2195 				sin->sin_family = AF_INET;
2196 				sin->sin_port = eager->tcp_lport;
2197 				sin->sin_addr.s_addr =
2198 				    eager->tcp_ipha->ipha_src;
2199 				break;
2200 			}
2201 		case sizeof (sin6_t): {
2202 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2203 
2204 				ok_mp->b_wptr += extra;
2205 				sin6->sin6_family = AF_INET6;
2206 				sin6->sin6_port = eager->tcp_lport;
2207 				if (eager->tcp_ipversion == IPV4_VERSION) {
2208 					sin6->sin6_flowinfo = 0;
2209 					IN6_IPADDR_TO_V4MAPPED(
2210 					    eager->tcp_ipha->ipha_src,
2211 					    &sin6->sin6_addr);
2212 				} else {
2213 					ASSERT(eager->tcp_ip6h != NULL);
2214 					sin6->sin6_flowinfo =
2215 					    eager->tcp_ip6h->ip6_vcf &
2216 					    ~IPV6_VERS_AND_FLOW_MASK;
2217 					sin6->sin6_addr =
2218 					    eager->tcp_ip6h->ip6_src;
2219 				}
2220 				sin6->sin6_scope_id = 0;
2221 				sin6->__sin6_src_id = 0;
2222 				break;
2223 			}
2224 		default:
2225 			break;
2226 		}
2227 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2228 	}
2229 
2230 	/*
2231 	 * If there are no options we know that the T_CONN_RES will
2232 	 * succeed. However, we can't send the T_OK_ACK upstream until
2233 	 * the tcp_accept_swap is done since it would be dangerous to
2234 	 * let the application start using the new fd prior to the swap.
2235 	 */
2236 	tcp_accept_swap(listener, acceptor, eager);
2237 
2238 	/*
2239 	 * tcp_accept_swap unlinks eager from listener but does not drop
2240 	 * the eager's reference on the listener.
2241 	 */
2242 	ASSERT(eager->tcp_listener == NULL);
2243 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2244 
2245 	/*
2246 	 * The eager is now associated with its own queue. Insert in
2247 	 * the hash so that the connection can be reused for a future
2248 	 * T_CONN_RES.
2249 	 */
2250 	tcp_acceptor_hash_insert(acceptor_id, eager);
2251 
2252 	/*
2253 	 * We now do the processing of options with T_CONN_RES.
2254 	 * We delay till now since we wanted to have queue to pass to
2255 	 * option processing routines that points back to the right
2256 	 * instance structure which does not happen until after
2257 	 * tcp_accept_swap().
2258 	 *
2259 	 * Note:
2260 	 * The sanity of the logic here assumes that whatever options
2261 	 * are appropriate to inherit from listner=>eager are done
2262 	 * before this point, and whatever were to be overridden (or not)
2263 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2264 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2265 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2266 	 * This may not be true at this point in time but can be fixed
2267 	 * independently. This option processing code starts with
2268 	 * the instantiated acceptor instance and the final queue at
2269 	 * this point.
2270 	 */
2271 
2272 	if (tcr->OPT_length != 0) {
2273 		/* Options to process */
2274 		int t_error = 0;
2275 		int sys_error = 0;
2276 		int do_disconnect = 0;
2277 
2278 		if (tcp_conprim_opt_process(eager, mp1,
2279 		    &do_disconnect, &t_error, &sys_error) < 0) {
2280 			eager->tcp_accept_error = 1;
2281 			if (do_disconnect) {
2282 				/*
2283 				 * An option failed which does not allow
2284 				 * connection to be accepted.
2285 				 *
2286 				 * We allow T_CONN_RES to succeed and
2287 				 * put a T_DISCON_IND on the eager queue.
2288 				 */
2289 				ASSERT(t_error == 0 && sys_error == 0);
2290 				eager->tcp_send_discon_ind = 1;
2291 			} else {
2292 				ASSERT(t_error != 0);
2293 				freemsg(ok_mp);
2294 				/*
2295 				 * Original mp was either freed or set
2296 				 * to ok_mp above, so use mp1 instead.
2297 				 */
2298 				tcp_err_ack(listener, mp1, t_error, sys_error);
2299 				goto finish;
2300 			}
2301 		}
2302 		/*
2303 		 * Most likely success in setting options (except if
2304 		 * eager->tcp_send_discon_ind set).
2305 		 * mp1 option buffer represented by OPT_length/offset
2306 		 * potentially modified and contains results of setting
2307 		 * options at this point
2308 		 */
2309 	}
2310 
2311 	/* We no longer need mp1, since all options processing has passed */
2312 	freemsg(mp1);
2313 
2314 	putnext(listener->tcp_rq, ok_mp);
2315 
2316 	mutex_enter(&listener->tcp_eager_lock);
2317 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2318 		tcp_t	*tail;
2319 		mblk_t	*conn_ind;
2320 
2321 		/*
2322 		 * This path should not be executed if listener and
2323 		 * acceptor streams are the same.
2324 		 */
2325 		ASSERT(listener != acceptor);
2326 
2327 		tcp = listener->tcp_eager_prev_q0;
2328 		/*
2329 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2330 		 * deferred T_conn_ind queue. We need to get to the head of
2331 		 * the queue in order to send up T_conn_ind the same order as
2332 		 * how the 3WHS is completed.
2333 		 */
2334 		while (tcp != listener) {
2335 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2336 				break;
2337 			else
2338 				tcp = tcp->tcp_eager_prev_q0;
2339 		}
2340 		ASSERT(tcp != listener);
2341 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2342 		ASSERT(conn_ind != NULL);
2343 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2344 
2345 		/* Move from q0 to q */
2346 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2347 		listener->tcp_conn_req_cnt_q0--;
2348 		listener->tcp_conn_req_cnt_q++;
2349 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2350 		    tcp->tcp_eager_prev_q0;
2351 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2352 		    tcp->tcp_eager_next_q0;
2353 		tcp->tcp_eager_prev_q0 = NULL;
2354 		tcp->tcp_eager_next_q0 = NULL;
2355 		tcp->tcp_conn_def_q0 = B_FALSE;
2356 
2357 		/* Make sure the tcp isn't in the list of droppables */
2358 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2359 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2360 
2361 		/*
2362 		 * Insert at end of the queue because sockfs sends
2363 		 * down T_CONN_RES in chronological order. Leaving
2364 		 * the older conn indications at front of the queue
2365 		 * helps reducing search time.
2366 		 */
2367 		tail = listener->tcp_eager_last_q;
2368 		if (tail != NULL)
2369 			tail->tcp_eager_next_q = tcp;
2370 		else
2371 			listener->tcp_eager_next_q = tcp;
2372 		listener->tcp_eager_last_q = tcp;
2373 		tcp->tcp_eager_next_q = NULL;
2374 		mutex_exit(&listener->tcp_eager_lock);
2375 		putnext(tcp->tcp_rq, conn_ind);
2376 	} else {
2377 		mutex_exit(&listener->tcp_eager_lock);
2378 	}
2379 
2380 	/*
2381 	 * Done with the acceptor - free it
2382 	 *
2383 	 * Note: from this point on, no access to listener should be made
2384 	 * as listener can be equal to acceptor.
2385 	 */
2386 finish:
2387 	ASSERT(acceptor->tcp_detached);
2388 	ASSERT(tcps->tcps_g_q != NULL);
2389 	ASSERT(!IPCL_IS_NONSTR(acceptor->tcp_connp));
2390 	acceptor->tcp_rq = tcps->tcps_g_q;
2391 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2392 	(void) tcp_clean_death(acceptor, 0, 2);
2393 	CONN_DEC_REF(acceptor->tcp_connp);
2394 
2395 	/*
2396 	 * In case we already received a FIN we have to make tcp_rput send
2397 	 * the ordrel_ind. This will also send up a window update if the window
2398 	 * has opened up.
2399 	 *
2400 	 * In the normal case of a successful connection acceptance
2401 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2402 	 * indication that this was just accepted. This tells tcp_rput to
2403 	 * pass up any data queued in tcp_rcv_list.
2404 	 *
2405 	 * In the fringe case where options sent with T_CONN_RES failed and
2406 	 * we required, we would be indicating a T_DISCON_IND to blow
2407 	 * away this connection.
2408 	 */
2409 
2410 	/*
2411 	 * XXX: we currently have a problem if XTI application closes the
2412 	 * acceptor stream in between. This problem exists in on10-gate also
2413 	 * and is well know but nothing can be done short of major rewrite
2414 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2415 	 * eager same squeue as listener (we can distinguish non socket
2416 	 * listeners at the time of handling a SYN in tcp_conn_request)
2417 	 * and do most of the work that tcp_accept_finish does here itself
2418 	 * and then get behind the acceptor squeue to access the acceptor
2419 	 * queue.
2420 	 */
2421 	/*
2422 	 * We already have a ref on tcp so no need to do one before squeue_enter
2423 	 */
2424 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, opt_mp, tcp_accept_finish,
2425 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_ACCEPT_FINISH);
2426 }
2427 
2428 /*
2429  * Swap information between the eager and acceptor for a TLI/XTI client.
2430  * The sockfs accept is done on the acceptor stream and control goes
2431  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2432  * called. In either case, both the eager and listener are in their own
2433  * perimeter (squeue) and the code has to deal with potential race.
2434  *
2435  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2436  */
2437 static void
2438 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2439 {
2440 	conn_t	*econnp, *aconnp;
2441 
2442 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2443 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2444 	ASSERT(!eager->tcp_hard_bound);
2445 	ASSERT(!TCP_IS_SOCKET(acceptor));
2446 	ASSERT(!TCP_IS_SOCKET(eager));
2447 	ASSERT(!TCP_IS_SOCKET(listener));
2448 
2449 	acceptor->tcp_detached = B_TRUE;
2450 	/*
2451 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2452 	 * the acceptor id.
2453 	 */
2454 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2455 
2456 	/* remove eager from listen list... */
2457 	mutex_enter(&listener->tcp_eager_lock);
2458 	tcp_eager_unlink(eager);
2459 	ASSERT(eager->tcp_eager_next_q == NULL &&
2460 	    eager->tcp_eager_last_q == NULL);
2461 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2462 	    eager->tcp_eager_prev_q0 == NULL);
2463 	mutex_exit(&listener->tcp_eager_lock);
2464 	eager->tcp_rq = acceptor->tcp_rq;
2465 	eager->tcp_wq = acceptor->tcp_wq;
2466 
2467 	econnp = eager->tcp_connp;
2468 	aconnp = acceptor->tcp_connp;
2469 
2470 	eager->tcp_rq->q_ptr = econnp;
2471 	eager->tcp_wq->q_ptr = econnp;
2472 
2473 	/*
2474 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2475 	 * which might be a different squeue from our peer TCP instance.
2476 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2477 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2478 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2479 	 * above reach global visibility prior to the clearing of tcp_detached.
2480 	 */
2481 	membar_producer();
2482 	eager->tcp_detached = B_FALSE;
2483 
2484 	ASSERT(eager->tcp_ack_tid == 0);
2485 
2486 	econnp->conn_dev = aconnp->conn_dev;
2487 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2488 	ASSERT(econnp->conn_minor_arena != NULL);
2489 	if (eager->tcp_cred != NULL)
2490 		crfree(eager->tcp_cred);
2491 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2492 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2493 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2494 
2495 	aconnp->conn_cred = NULL;
2496 
2497 	econnp->conn_zoneid = aconnp->conn_zoneid;
2498 	econnp->conn_allzones = aconnp->conn_allzones;
2499 
2500 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2501 	aconnp->conn_mac_exempt = B_FALSE;
2502 
2503 	ASSERT(aconnp->conn_peercred == NULL);
2504 
2505 	/* Do the IPC initialization */
2506 	CONN_INC_REF(econnp);
2507 
2508 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2509 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2510 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2511 
2512 	/* Done with old IPC. Drop its ref on its connp */
2513 	CONN_DEC_REF(aconnp);
2514 }
2515 
2516 
2517 /*
2518  * Adapt to the information, such as rtt and rtt_sd, provided from the
2519  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2520  *
2521  * Checks for multicast and broadcast destination address.
2522  * Returns zero on failure; non-zero if ok.
2523  *
2524  * Note that the MSS calculation here is based on the info given in
2525  * the IRE.  We do not do any calculation based on TCP options.  They
2526  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2527  * knows which options to use.
2528  *
2529  * Note on how TCP gets its parameters for a connection.
2530  *
2531  * When a tcp_t structure is allocated, it gets all the default parameters.
2532  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2533  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2534  * default.
2535  *
2536  * An incoming SYN with a multicast or broadcast destination address, is dropped
2537  * in 1 of 2 places.
2538  *
2539  * 1. If the packet was received over the wire it is dropped in
2540  * ip_rput_process_broadcast()
2541  *
2542  * 2. If the packet was received through internal IP loopback, i.e. the packet
2543  * was generated and received on the same machine, it is dropped in
2544  * ip_wput_local()
2545  *
2546  * An incoming SYN with a multicast or broadcast source address is always
2547  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2548  * reject an attempt to connect to a broadcast or multicast (destination)
2549  * address.
2550  */
2551 static int
2552 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2553 {
2554 	tcp_hsp_t	*hsp;
2555 	ire_t		*ire;
2556 	ire_t		*sire = NULL;
2557 	iulp_t		*ire_uinfo = NULL;
2558 	uint32_t	mss_max;
2559 	uint32_t	mss;
2560 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2561 	conn_t		*connp = tcp->tcp_connp;
2562 	boolean_t	ire_cacheable = B_FALSE;
2563 	zoneid_t	zoneid = connp->conn_zoneid;
2564 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2565 	    MATCH_IRE_SECATTR;
2566 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2567 	ill_t		*ill = NULL;
2568 	boolean_t	incoming = (ire_mp == NULL);
2569 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2570 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2571 
2572 	ASSERT(connp->conn_ire_cache == NULL);
2573 
2574 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2575 
2576 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2577 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2578 			return (0);
2579 		}
2580 		/*
2581 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2582 		 * for the destination with the nexthop as gateway.
2583 		 * ire_ctable_lookup() is used because this particular
2584 		 * ire, if it exists, will be marked private.
2585 		 * If that is not available, use the interface ire
2586 		 * for the nexthop.
2587 		 *
2588 		 * TSol: tcp_update_label will detect label mismatches based
2589 		 * only on the destination's label, but that would not
2590 		 * detect label mismatches based on the security attributes
2591 		 * of routes or next hop gateway. Hence we need to pass the
2592 		 * label to ire_ftable_lookup below in order to locate the
2593 		 * right prefix (and/or) ire cache. Similarly we also need
2594 		 * pass the label to the ire_cache_lookup below to locate
2595 		 * the right ire that also matches on the label.
2596 		 */
2597 		if (tcp->tcp_connp->conn_nexthop_set) {
2598 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2599 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2600 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2601 			    ipst);
2602 			if (ire == NULL) {
2603 				ire = ire_ftable_lookup(
2604 				    tcp->tcp_connp->conn_nexthop_v4,
2605 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2606 				    tsl, match_flags, ipst);
2607 				if (ire == NULL)
2608 					return (0);
2609 			} else {
2610 				ire_uinfo = &ire->ire_uinfo;
2611 			}
2612 		} else {
2613 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2614 			    zoneid, tsl, ipst);
2615 			if (ire != NULL) {
2616 				ire_cacheable = B_TRUE;
2617 				ire_uinfo = (ire_mp != NULL) ?
2618 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2619 				    &ire->ire_uinfo;
2620 
2621 			} else {
2622 				if (ire_mp == NULL) {
2623 					ire = ire_ftable_lookup(
2624 					    tcp->tcp_connp->conn_rem,
2625 					    0, 0, 0, NULL, &sire, zoneid, 0,
2626 					    tsl, (MATCH_IRE_RECURSIVE |
2627 					    MATCH_IRE_DEFAULT), ipst);
2628 					if (ire == NULL)
2629 						return (0);
2630 					ire_uinfo = (sire != NULL) ?
2631 					    &sire->ire_uinfo :
2632 					    &ire->ire_uinfo;
2633 				} else {
2634 					ire = (ire_t *)ire_mp->b_rptr;
2635 					ire_uinfo =
2636 					    &((ire_t *)
2637 					    ire_mp->b_rptr)->ire_uinfo;
2638 				}
2639 			}
2640 		}
2641 		ASSERT(ire != NULL);
2642 
2643 		if ((ire->ire_src_addr == INADDR_ANY) ||
2644 		    (ire->ire_type & IRE_BROADCAST)) {
2645 			/*
2646 			 * ire->ire_mp is non null when ire_mp passed in is used
2647 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2648 			 */
2649 			if (ire->ire_mp == NULL)
2650 				ire_refrele(ire);
2651 			if (sire != NULL)
2652 				ire_refrele(sire);
2653 			return (0);
2654 		}
2655 
2656 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2657 			ipaddr_t src_addr;
2658 
2659 			/*
2660 			 * ip_bind_connected() has stored the correct source
2661 			 * address in conn_src.
2662 			 */
2663 			src_addr = tcp->tcp_connp->conn_src;
2664 			tcp->tcp_ipha->ipha_src = src_addr;
2665 			/*
2666 			 * Copy of the src addr. in tcp_t is needed
2667 			 * for the lookup funcs.
2668 			 */
2669 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2670 		}
2671 		/*
2672 		 * Set the fragment bit so that IP will tell us if the MTU
2673 		 * should change. IP tells us the latest setting of
2674 		 * ip_path_mtu_discovery through ire_frag_flag.
2675 		 */
2676 		if (ipst->ips_ip_path_mtu_discovery) {
2677 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2678 			    htons(IPH_DF);
2679 		}
2680 		/*
2681 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2682 		 * for IP_NEXTHOP. No cache ire has been found for the
2683 		 * destination and we are working with the nexthop's
2684 		 * interface ire. Since we need to forward all packets
2685 		 * to the nexthop first, we "blindly" set tcp_localnet
2686 		 * to false, eventhough the destination may also be
2687 		 * onlink.
2688 		 */
2689 		if (ire_uinfo == NULL)
2690 			tcp->tcp_localnet = 0;
2691 		else
2692 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2693 	} else {
2694 		/*
2695 		 * For incoming connection ire_mp = NULL
2696 		 * For outgoing connection ire_mp != NULL
2697 		 * Technically we should check conn_incoming_ill
2698 		 * when ire_mp is NULL and conn_outgoing_ill when
2699 		 * ire_mp is non-NULL. But this is performance
2700 		 * critical path and for IPV*_BOUND_IF, outgoing
2701 		 * and incoming ill are always set to the same value.
2702 		 */
2703 		ill_t	*dst_ill = NULL;
2704 		ipif_t  *dst_ipif = NULL;
2705 
2706 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2707 
2708 		if (connp->conn_outgoing_ill != NULL) {
2709 			/* Outgoing or incoming path */
2710 			int   err;
2711 
2712 			dst_ill = conn_get_held_ill(connp,
2713 			    &connp->conn_outgoing_ill, &err);
2714 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2715 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2716 				return (0);
2717 			}
2718 			match_flags |= MATCH_IRE_ILL;
2719 			dst_ipif = dst_ill->ill_ipif;
2720 		}
2721 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2722 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2723 
2724 		if (ire != NULL) {
2725 			ire_cacheable = B_TRUE;
2726 			ire_uinfo = (ire_mp != NULL) ?
2727 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2728 			    &ire->ire_uinfo;
2729 		} else {
2730 			if (ire_mp == NULL) {
2731 				ire = ire_ftable_lookup_v6(
2732 				    &tcp->tcp_connp->conn_remv6,
2733 				    0, 0, 0, dst_ipif, &sire, zoneid,
2734 				    0, tsl, match_flags, ipst);
2735 				if (ire == NULL) {
2736 					if (dst_ill != NULL)
2737 						ill_refrele(dst_ill);
2738 					return (0);
2739 				}
2740 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2741 				    &ire->ire_uinfo;
2742 			} else {
2743 				ire = (ire_t *)ire_mp->b_rptr;
2744 				ire_uinfo =
2745 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2746 			}
2747 		}
2748 		if (dst_ill != NULL)
2749 			ill_refrele(dst_ill);
2750 
2751 		ASSERT(ire != NULL);
2752 		ASSERT(ire_uinfo != NULL);
2753 
2754 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2755 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2756 			/*
2757 			 * ire->ire_mp is non null when ire_mp passed in is used
2758 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2759 			 */
2760 			if (ire->ire_mp == NULL)
2761 				ire_refrele(ire);
2762 			if (sire != NULL)
2763 				ire_refrele(sire);
2764 			return (0);
2765 		}
2766 
2767 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2768 			in6_addr_t	src_addr;
2769 
2770 			/*
2771 			 * ip_bind_connected_v6() has stored the correct source
2772 			 * address per IPv6 addr. selection policy in
2773 			 * conn_src_v6.
2774 			 */
2775 			src_addr = tcp->tcp_connp->conn_srcv6;
2776 
2777 			tcp->tcp_ip6h->ip6_src = src_addr;
2778 			/*
2779 			 * Copy of the src addr. in tcp_t is needed
2780 			 * for the lookup funcs.
2781 			 */
2782 			tcp->tcp_ip_src_v6 = src_addr;
2783 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2784 			    &connp->conn_srcv6));
2785 		}
2786 		tcp->tcp_localnet =
2787 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2788 	}
2789 
2790 	/*
2791 	 * This allows applications to fail quickly when connections are made
2792 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2793 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2794 	 */
2795 	if ((ire->ire_flags & RTF_REJECT) &&
2796 	    (ire->ire_flags & RTF_PRIVATE))
2797 		goto error;
2798 
2799 	/*
2800 	 * Make use of the cached rtt and rtt_sd values to calculate the
2801 	 * initial RTO.  Note that they are already initialized in
2802 	 * tcp_init_values().
2803 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2804 	 * IP_NEXTHOP, but instead are using the interface ire for the
2805 	 * nexthop, then we do not use the ire_uinfo from that ire to
2806 	 * do any initializations.
2807 	 */
2808 	if (ire_uinfo != NULL) {
2809 		if (ire_uinfo->iulp_rtt != 0) {
2810 			clock_t	rto;
2811 
2812 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2813 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2814 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2815 			    tcps->tcps_rexmit_interval_extra +
2816 			    (tcp->tcp_rtt_sa >> 5);
2817 
2818 			if (rto > tcps->tcps_rexmit_interval_max) {
2819 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2820 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2821 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2822 			} else {
2823 				tcp->tcp_rto = rto;
2824 			}
2825 		}
2826 		if (ire_uinfo->iulp_ssthresh != 0)
2827 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2828 		else
2829 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2830 		if (ire_uinfo->iulp_spipe > 0) {
2831 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2832 			    tcps->tcps_max_buf);
2833 			if (tcps->tcps_snd_lowat_fraction != 0)
2834 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2835 				    tcps->tcps_snd_lowat_fraction;
2836 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2837 		}
2838 		/*
2839 		 * Note that up till now, acceptor always inherits receive
2840 		 * window from the listener.  But if there is a metrics
2841 		 * associated with a host, we should use that instead of
2842 		 * inheriting it from listener. Thus we need to pass this
2843 		 * info back to the caller.
2844 		 */
2845 		if (ire_uinfo->iulp_rpipe > 0) {
2846 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2847 			    tcps->tcps_max_buf);
2848 		}
2849 
2850 		if (ire_uinfo->iulp_rtomax > 0) {
2851 			tcp->tcp_second_timer_threshold =
2852 			    ire_uinfo->iulp_rtomax;
2853 		}
2854 
2855 		/*
2856 		 * Use the metric option settings, iulp_tstamp_ok and
2857 		 * iulp_wscale_ok, only for active open. What this means
2858 		 * is that if the other side uses timestamp or window
2859 		 * scale option, TCP will also use those options. That
2860 		 * is for passive open.  If the application sets a
2861 		 * large window, window scale is enabled regardless of
2862 		 * the value in iulp_wscale_ok.  This is the behavior
2863 		 * since 2.6.  So we keep it.
2864 		 * The only case left in passive open processing is the
2865 		 * check for SACK.
2866 		 * For ECN, it should probably be like SACK.  But the
2867 		 * current value is binary, so we treat it like the other
2868 		 * cases.  The metric only controls active open.For passive
2869 		 * open, the ndd param, tcp_ecn_permitted, controls the
2870 		 * behavior.
2871 		 */
2872 		if (!tcp_detached) {
2873 			/*
2874 			 * The if check means that the following can only
2875 			 * be turned on by the metrics only IRE, but not off.
2876 			 */
2877 			if (ire_uinfo->iulp_tstamp_ok)
2878 				tcp->tcp_snd_ts_ok = B_TRUE;
2879 			if (ire_uinfo->iulp_wscale_ok)
2880 				tcp->tcp_snd_ws_ok = B_TRUE;
2881 			if (ire_uinfo->iulp_sack == 2)
2882 				tcp->tcp_snd_sack_ok = B_TRUE;
2883 			if (ire_uinfo->iulp_ecn_ok)
2884 				tcp->tcp_ecn_ok = B_TRUE;
2885 		} else {
2886 			/*
2887 			 * Passive open.
2888 			 *
2889 			 * As above, the if check means that SACK can only be
2890 			 * turned on by the metric only IRE.
2891 			 */
2892 			if (ire_uinfo->iulp_sack > 0) {
2893 				tcp->tcp_snd_sack_ok = B_TRUE;
2894 			}
2895 		}
2896 	}
2897 
2898 
2899 	/*
2900 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2901 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2902 	 * length of all those options exceeds 28 bytes.  But because
2903 	 * of the tcp_mss_min check below, we may not have a problem if
2904 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2905 	 * the negative problem still exists.  And the check defeats PMTUd.
2906 	 * In fact, if PMTUd finds that the MSS should be smaller than
2907 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2908 	 * value.
2909 	 *
2910 	 * We do not deal with that now.  All those problems related to
2911 	 * PMTUd will be fixed later.
2912 	 */
2913 	ASSERT(ire->ire_max_frag != 0);
2914 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2915 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2916 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2917 			mss = MIN(mss, IPV6_MIN_MTU);
2918 		}
2919 	}
2920 
2921 	/* Sanity check for MSS value. */
2922 	if (tcp->tcp_ipversion == IPV4_VERSION)
2923 		mss_max = tcps->tcps_mss_max_ipv4;
2924 	else
2925 		mss_max = tcps->tcps_mss_max_ipv6;
2926 
2927 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2928 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2929 		/*
2930 		 * After receiving an ICMPv6 "packet too big" message with a
2931 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2932 		 * will insert a 8-byte fragment header in every packet; we
2933 		 * reduce the MSS by that amount here.
2934 		 */
2935 		mss -= sizeof (ip6_frag_t);
2936 	}
2937 
2938 	if (tcp->tcp_ipsec_overhead == 0)
2939 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2940 
2941 	mss -= tcp->tcp_ipsec_overhead;
2942 
2943 	if (mss < tcps->tcps_mss_min)
2944 		mss = tcps->tcps_mss_min;
2945 	if (mss > mss_max)
2946 		mss = mss_max;
2947 
2948 	/* Note that this is the maximum MSS, excluding all options. */
2949 	tcp->tcp_mss = mss;
2950 
2951 	/*
2952 	 * Initialize the ISS here now that we have the full connection ID.
2953 	 * The RFC 1948 method of initial sequence number generation requires
2954 	 * knowledge of the full connection ID before setting the ISS.
2955 	 */
2956 
2957 	tcp_iss_init(tcp);
2958 
2959 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2960 		tcp->tcp_loopback = B_TRUE;
2961 
2962 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2963 		hsp = tcp_hsp_lookup(tcp->tcp_remote, tcps);
2964 	} else {
2965 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6, tcps);
2966 	}
2967 
2968 	if (hsp != NULL) {
2969 		/* Only modify if we're going to make them bigger */
2970 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2971 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2972 			if (tcps->tcps_snd_lowat_fraction != 0)
2973 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2974 				    tcps->tcps_snd_lowat_fraction;
2975 		}
2976 
2977 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2978 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2979 		}
2980 
2981 		/* Copy timestamp flag only for active open */
2982 		if (!tcp_detached)
2983 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2984 	}
2985 
2986 	if (sire != NULL)
2987 		IRE_REFRELE(sire);
2988 
2989 	/*
2990 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2991 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2992 	 */
2993 	if (tcp->tcp_loopback ||
2994 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2995 		/*
2996 		 * For incoming, see if this tcp may be MDT-capable.  For
2997 		 * outgoing, this process has been taken care of through
2998 		 * tcp_rput_other.
2999 		 */
3000 		tcp_ire_ill_check(tcp, ire, ill, incoming);
3001 		tcp->tcp_ire_ill_check_done = B_TRUE;
3002 	}
3003 
3004 	mutex_enter(&connp->conn_lock);
3005 	/*
3006 	 * Make sure that conn is not marked incipient
3007 	 * for incoming connections. A blind
3008 	 * removal of incipient flag is cheaper than
3009 	 * check and removal.
3010 	 */
3011 	connp->conn_state_flags &= ~CONN_INCIPIENT;
3012 
3013 	/*
3014 	 * Must not cache forwarding table routes
3015 	 * or recache an IRE after the conn_t has
3016 	 * had conn_ire_cache cleared and is flagged
3017 	 * unusable, (see the CONN_CACHE_IRE() macro).
3018 	 */
3019 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
3020 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
3021 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
3022 			connp->conn_ire_cache = ire;
3023 			IRE_UNTRACE_REF(ire);
3024 			rw_exit(&ire->ire_bucket->irb_lock);
3025 			mutex_exit(&connp->conn_lock);
3026 			return (1);
3027 		}
3028 		rw_exit(&ire->ire_bucket->irb_lock);
3029 	}
3030 	mutex_exit(&connp->conn_lock);
3031 
3032 	if (ire->ire_mp == NULL)
3033 		ire_refrele(ire);
3034 	return (1);
3035 
3036 error:
3037 	if (ire->ire_mp == NULL)
3038 		ire_refrele(ire);
3039 	if (sire != NULL)
3040 		ire_refrele(sire);
3041 	return (0);
3042 }
3043 
3044 static void
3045 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
3046 {
3047 	int	error;
3048 	conn_t	*connp = tcp->tcp_connp;
3049 	struct sockaddr	*sa;
3050 	mblk_t  *mp1;
3051 	struct T_bind_req *tbr;
3052 	int	backlog;
3053 	socklen_t	len;
3054 	sin_t	*sin;
3055 	sin6_t	*sin6;
3056 
3057 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3058 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3059 		if (tcp->tcp_debug) {
3060 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3061 			    "tcp_tpi_bind: bad req, len %u",
3062 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3063 		}
3064 		tcp_err_ack(tcp, mp, TPROTO, 0);
3065 		return;
3066 	}
3067 	/* Make sure the largest address fits */
3068 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3069 	if (mp1 == NULL) {
3070 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3071 		return;
3072 	}
3073 	mp = mp1;
3074 	tbr = (struct T_bind_req *)mp->b_rptr;
3075 
3076 	backlog = tbr->CONIND_number;
3077 	len = tbr->ADDR_length;
3078 
3079 	switch (len) {
3080 	case 0:		/* request for a generic port */
3081 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3082 		if (tcp->tcp_family == AF_INET) {
3083 			tbr->ADDR_length = sizeof (sin_t);
3084 			sin = (sin_t *)&tbr[1];
3085 			*sin = sin_null;
3086 			sin->sin_family = AF_INET;
3087 			sa = (struct sockaddr *)sin;
3088 			len = sizeof (sin_t);
3089 			mp->b_wptr = (uchar_t *)&sin[1];
3090 		} else {
3091 			ASSERT(tcp->tcp_family == AF_INET6);
3092 			tbr->ADDR_length = sizeof (sin6_t);
3093 			sin6 = (sin6_t *)&tbr[1];
3094 			*sin6 = sin6_null;
3095 			sin6->sin6_family = AF_INET6;
3096 			sa = (struct sockaddr *)sin6;
3097 			len = sizeof (sin6_t);
3098 			mp->b_wptr = (uchar_t *)&sin6[1];
3099 		}
3100 		break;
3101 
3102 	case sizeof (sin_t):    /* Complete IPv4 address */
3103 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
3104 		    sizeof (sin_t));
3105 		break;
3106 
3107 	case sizeof (sin6_t): /* Complete IPv6 address */
3108 		sa = (struct sockaddr *)mi_offset_param(mp,
3109 		    tbr->ADDR_offset, sizeof (sin6_t));
3110 		break;
3111 
3112 	default:
3113 		if (tcp->tcp_debug) {
3114 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3115 			    "tcp_tpi_bind: bad address length, %d",
3116 			    tbr->ADDR_length);
3117 		}
3118 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3119 		return;
3120 	}
3121 
3122 	error = tcp_bind_check(connp, sa, len, DB_CRED(mp),
3123 	    tbr->PRIM_type != O_T_BIND_REQ);
3124 	if (error == 0) {
3125 		if (tcp->tcp_family == AF_INET) {
3126 			sin = (sin_t *)sa;
3127 			sin->sin_port = tcp->tcp_lport;
3128 		} else {
3129 			sin6 = (sin6_t *)sa;
3130 			sin6->sin6_port = tcp->tcp_lport;
3131 		}
3132 
3133 		if (backlog > 0) {
3134 			error = tcp_do_listen(connp, backlog, DB_CRED(mp));
3135 		}
3136 	}
3137 done:
3138 	if (error > 0) {
3139 		tcp_err_ack(tcp, mp, TSYSERR, error);
3140 	} else if (error < 0) {
3141 		tcp_err_ack(tcp, mp, -error, 0);
3142 	} else {
3143 		mp->b_datap->db_type = M_PCPROTO;
3144 		tbr->PRIM_type = T_BIND_ACK;
3145 		putnext(tcp->tcp_rq, mp);
3146 	}
3147 }
3148 
3149 /*
3150  * If the "bind_to_req_port_only" parameter is set, if the requested port
3151  * number is available, return it, If not return 0
3152  *
3153  * If "bind_to_req_port_only" parameter is not set and
3154  * If the requested port number is available, return it.  If not, return
3155  * the first anonymous port we happen across.  If no anonymous ports are
3156  * available, return 0. addr is the requested local address, if any.
3157  *
3158  * In either case, when succeeding update the tcp_t to record the port number
3159  * and insert it in the bind hash table.
3160  *
3161  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3162  * without setting SO_REUSEADDR. This is needed so that they
3163  * can be viewed as two independent transport protocols.
3164  */
3165 static in_port_t
3166 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3167     int reuseaddr, boolean_t quick_connect,
3168     boolean_t bind_to_req_port_only, boolean_t user_specified)
3169 {
3170 	/* number of times we have run around the loop */
3171 	int count = 0;
3172 	/* maximum number of times to run around the loop */
3173 	int loopmax;
3174 	conn_t *connp = tcp->tcp_connp;
3175 	zoneid_t zoneid = connp->conn_zoneid;
3176 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3177 
3178 	/*
3179 	 * Lookup for free addresses is done in a loop and "loopmax"
3180 	 * influences how long we spin in the loop
3181 	 */
3182 	if (bind_to_req_port_only) {
3183 		/*
3184 		 * If the requested port is busy, don't bother to look
3185 		 * for a new one. Setting loop maximum count to 1 has
3186 		 * that effect.
3187 		 */
3188 		loopmax = 1;
3189 	} else {
3190 		/*
3191 		 * If the requested port is busy, look for a free one
3192 		 * in the anonymous port range.
3193 		 * Set loopmax appropriately so that one does not look
3194 		 * forever in the case all of the anonymous ports are in use.
3195 		 */
3196 		if (tcp->tcp_anon_priv_bind) {
3197 			/*
3198 			 * loopmax =
3199 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3200 			 */
3201 			loopmax = IPPORT_RESERVED -
3202 			    tcps->tcps_min_anonpriv_port;
3203 		} else {
3204 			loopmax = (tcps->tcps_largest_anon_port -
3205 			    tcps->tcps_smallest_anon_port + 1);
3206 		}
3207 	}
3208 	do {
3209 		uint16_t	lport;
3210 		tf_t		*tbf;
3211 		tcp_t		*ltcp;
3212 		conn_t		*lconnp;
3213 
3214 		lport = htons(port);
3215 
3216 		/*
3217 		 * Ensure that the tcp_t is not currently in the bind hash.
3218 		 * Hold the lock on the hash bucket to ensure that
3219 		 * the duplicate check plus the insertion is an atomic
3220 		 * operation.
3221 		 *
3222 		 * This function does an inline lookup on the bind hash list
3223 		 * Make sure that we access only members of tcp_t
3224 		 * and that we don't look at tcp_tcp, since we are not
3225 		 * doing a CONN_INC_REF.
3226 		 */
3227 		tcp_bind_hash_remove(tcp);
3228 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3229 		mutex_enter(&tbf->tf_lock);
3230 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3231 		    ltcp = ltcp->tcp_bind_hash) {
3232 			if (lport == ltcp->tcp_lport)
3233 				break;
3234 		}
3235 
3236 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
3237 			boolean_t not_socket;
3238 			boolean_t exclbind;
3239 
3240 			lconnp = ltcp->tcp_connp;
3241 
3242 			/*
3243 			 * On a labeled system, we must treat bindings to ports
3244 			 * on shared IP addresses by sockets with MAC exemption
3245 			 * privilege as being in all zones, as there's
3246 			 * otherwise no way to identify the right receiver.
3247 			 */
3248 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3249 			    IPCL_ZONE_MATCH(connp,
3250 			    ltcp->tcp_connp->conn_zoneid)) &&
3251 			    !lconnp->conn_mac_exempt &&
3252 			    !connp->conn_mac_exempt)
3253 				continue;
3254 
3255 			/*
3256 			 * If TCP_EXCLBIND is set for either the bound or
3257 			 * binding endpoint, the semantics of bind
3258 			 * is changed according to the following.
3259 			 *
3260 			 * spec = specified address (v4 or v6)
3261 			 * unspec = unspecified address (v4 or v6)
3262 			 * A = specified addresses are different for endpoints
3263 			 *
3264 			 * bound	bind to		allowed
3265 			 * -------------------------------------
3266 			 * unspec	unspec		no
3267 			 * unspec	spec		no
3268 			 * spec		unspec		no
3269 			 * spec		spec		yes if A
3270 			 *
3271 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3272 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3273 			 *
3274 			 * Note:
3275 			 *
3276 			 * 1. Because of TLI semantics, an endpoint can go
3277 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3278 			 * TCPS_BOUND, depending on whether it is originally
3279 			 * a listener or not.  That is why we need to check
3280 			 * for states greater than or equal to TCPS_BOUND
3281 			 * here.
3282 			 *
3283 			 * 2. Ideally, we should only check for state equals
3284 			 * to TCPS_LISTEN. And the following check should be
3285 			 * added.
3286 			 *
3287 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3288 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3289 			 *		...
3290 			 * }
3291 			 *
3292 			 * The semantics will be changed to this.  If the
3293 			 * endpoint on the list is in state not equal to
3294 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3295 			 * set, let the bind succeed.
3296 			 *
3297 			 * Because of (1), we cannot do that for TLI
3298 			 * endpoints.  But we can do that for socket endpoints.
3299 			 * If in future, we can change this going back
3300 			 * semantics, we can use the above check for TLI also.
3301 			 */
3302 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3303 			    TCP_IS_SOCKET(tcp));
3304 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3305 
3306 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3307 			    (exclbind && (not_socket ||
3308 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3309 				if (V6_OR_V4_INADDR_ANY(
3310 				    ltcp->tcp_bound_source_v6) ||
3311 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3312 				    IN6_ARE_ADDR_EQUAL(laddr,
3313 				    &ltcp->tcp_bound_source_v6)) {
3314 					break;
3315 				}
3316 				continue;
3317 			}
3318 
3319 			/*
3320 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3321 			 * have disjoint port number spaces, if *_EXCLBIND
3322 			 * is not set and only if the application binds to a
3323 			 * specific port. We use the same autoassigned port
3324 			 * number space for IPv4 and IPv6 sockets.
3325 			 */
3326 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3327 			    bind_to_req_port_only)
3328 				continue;
3329 
3330 			/*
3331 			 * Ideally, we should make sure that the source
3332 			 * address, remote address, and remote port in the
3333 			 * four tuple for this tcp-connection is unique.
3334 			 * However, trying to find out the local source
3335 			 * address would require too much code duplication
3336 			 * with IP, since IP needs needs to have that code
3337 			 * to support userland TCP implementations.
3338 			 */
3339 			if (quick_connect &&
3340 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3341 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3342 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3343 			    &ltcp->tcp_remote_v6)))
3344 				continue;
3345 
3346 			if (!reuseaddr) {
3347 				/*
3348 				 * No socket option SO_REUSEADDR.
3349 				 * If existing port is bound to
3350 				 * a non-wildcard IP address
3351 				 * and the requesting stream is
3352 				 * bound to a distinct
3353 				 * different IP addresses
3354 				 * (non-wildcard, also), keep
3355 				 * going.
3356 				 */
3357 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3358 				    !V6_OR_V4_INADDR_ANY(
3359 				    ltcp->tcp_bound_source_v6) &&
3360 				    !IN6_ARE_ADDR_EQUAL(laddr,
3361 				    &ltcp->tcp_bound_source_v6))
3362 					continue;
3363 				if (ltcp->tcp_state >= TCPS_BOUND) {
3364 					/*
3365 					 * This port is being used and
3366 					 * its state is >= TCPS_BOUND,
3367 					 * so we can't bind to it.
3368 					 */
3369 					break;
3370 				}
3371 			} else {
3372 				/*
3373 				 * socket option SO_REUSEADDR is set on the
3374 				 * binding tcp_t.
3375 				 *
3376 				 * If two streams are bound to
3377 				 * same IP address or both addr
3378 				 * and bound source are wildcards
3379 				 * (INADDR_ANY), we want to stop
3380 				 * searching.
3381 				 * We have found a match of IP source
3382 				 * address and source port, which is
3383 				 * refused regardless of the
3384 				 * SO_REUSEADDR setting, so we break.
3385 				 */
3386 				if (IN6_ARE_ADDR_EQUAL(laddr,
3387 				    &ltcp->tcp_bound_source_v6) &&
3388 				    (ltcp->tcp_state == TCPS_LISTEN ||
3389 				    ltcp->tcp_state == TCPS_BOUND))
3390 					break;
3391 			}
3392 		}
3393 		if (ltcp != NULL) {
3394 			/* The port number is busy */
3395 			mutex_exit(&tbf->tf_lock);
3396 		} else {
3397 			/*
3398 			 * This port is ours. Insert in fanout and mark as
3399 			 * bound to prevent others from getting the port
3400 			 * number.
3401 			 */
3402 			tcp->tcp_state = TCPS_BOUND;
3403 			tcp->tcp_lport = htons(port);
3404 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3405 
3406 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3407 			    tcp->tcp_lport)] == tbf);
3408 			tcp_bind_hash_insert(tbf, tcp, 1);
3409 
3410 			mutex_exit(&tbf->tf_lock);
3411 
3412 			/*
3413 			 * We don't want tcp_next_port_to_try to "inherit"
3414 			 * a port number supplied by the user in a bind.
3415 			 */
3416 			if (user_specified)
3417 				return (port);
3418 
3419 			/*
3420 			 * This is the only place where tcp_next_port_to_try
3421 			 * is updated. After the update, it may or may not
3422 			 * be in the valid range.
3423 			 */
3424 			if (!tcp->tcp_anon_priv_bind)
3425 				tcps->tcps_next_port_to_try = port + 1;
3426 			return (port);
3427 		}
3428 
3429 		if (tcp->tcp_anon_priv_bind) {
3430 			port = tcp_get_next_priv_port(tcp);
3431 		} else {
3432 			if (count == 0 && user_specified) {
3433 				/*
3434 				 * We may have to return an anonymous port. So
3435 				 * get one to start with.
3436 				 */
3437 				port =
3438 				    tcp_update_next_port(
3439 				    tcps->tcps_next_port_to_try,
3440 				    tcp, B_TRUE);
3441 				user_specified = B_FALSE;
3442 			} else {
3443 				port = tcp_update_next_port(port + 1, tcp,
3444 				    B_FALSE);
3445 			}
3446 		}
3447 		if (port == 0)
3448 			break;
3449 
3450 		/*
3451 		 * Don't let this loop run forever in the case where
3452 		 * all of the anonymous ports are in use.
3453 		 */
3454 	} while (++count < loopmax);
3455 	return (0);
3456 }
3457 
3458 /*
3459  * tcp_clean_death / tcp_close_detached must not be called more than once
3460  * on a tcp. Thus every function that potentially calls tcp_clean_death
3461  * must check for the tcp state before calling tcp_clean_death.
3462  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3463  * tcp_timer_handler, all check for the tcp state.
3464  */
3465 /* ARGSUSED */
3466 void
3467 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3468 {
3469 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3470 
3471 	freemsg(mp);
3472 	if (tcp->tcp_state > TCPS_BOUND)
3473 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3474 		    ETIMEDOUT, 5);
3475 }
3476 
3477 /*
3478  * We are dying for some reason.  Try to do it gracefully.  (May be called
3479  * as writer.)
3480  *
3481  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3482  * done by a service procedure).
3483  * TBD - Should the return value distinguish between the tcp_t being
3484  * freed and it being reinitialized?
3485  */
3486 static int
3487 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3488 {
3489 	mblk_t	*mp;
3490 	queue_t	*q;
3491 	conn_t	*connp = tcp->tcp_connp;
3492 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3493 	sodirect_t	*sodp;
3494 
3495 	TCP_CLD_STAT(tag);
3496 
3497 #if TCP_TAG_CLEAN_DEATH
3498 	tcp->tcp_cleandeathtag = tag;
3499 #endif
3500 
3501 	if (tcp->tcp_fused)
3502 		tcp_unfuse(tcp);
3503 
3504 	if (tcp->tcp_linger_tid != 0 &&
3505 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3506 		tcp_stop_lingering(tcp);
3507 	}
3508 
3509 	ASSERT(tcp != NULL);
3510 	ASSERT((tcp->tcp_family == AF_INET &&
3511 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3512 	    (tcp->tcp_family == AF_INET6 &&
3513 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3514 	    tcp->tcp_ipversion == IPV6_VERSION)));
3515 
3516 	if (TCP_IS_DETACHED(tcp)) {
3517 		if (tcp->tcp_hard_binding) {
3518 			/*
3519 			 * Its an eager that we are dealing with. We close the
3520 			 * eager but in case a conn_ind has already gone to the
3521 			 * listener, let tcp_accept_finish() send a discon_ind
3522 			 * to the listener and drop the last reference. If the
3523 			 * listener doesn't even know about the eager i.e. the
3524 			 * conn_ind hasn't gone up, blow away the eager and drop
3525 			 * the last reference as well. If the conn_ind has gone
3526 			 * up, state should be BOUND. tcp_accept_finish
3527 			 * will figure out that the connection has received a
3528 			 * RST and will send a DISCON_IND to the application.
3529 			 */
3530 			tcp_closei_local(tcp);
3531 			if (!tcp->tcp_tconnind_started) {
3532 				CONN_DEC_REF(connp);
3533 			} else {
3534 				tcp->tcp_state = TCPS_BOUND;
3535 			}
3536 		} else {
3537 			tcp_close_detached(tcp);
3538 		}
3539 		return (0);
3540 	}
3541 
3542 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3543 
3544 	/* If sodirect, not anymore */
3545 	SOD_PTR_ENTER(tcp, sodp);
3546 	if (sodp != NULL) {
3547 		tcp->tcp_sodirect = NULL;
3548 		mutex_exit(sodp->sod_lockp);
3549 	}
3550 
3551 	q = tcp->tcp_rq;
3552 
3553 	/* Trash all inbound data */
3554 	if (!IPCL_IS_NONSTR(connp)) {
3555 		ASSERT(q != NULL);
3556 		flushq(q, FLUSHALL);
3557 	}
3558 
3559 	/*
3560 	 * If we are at least part way open and there is error
3561 	 * (err==0 implies no error)
3562 	 * notify our client by a T_DISCON_IND.
3563 	 */
3564 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3565 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3566 		    !TCP_IS_SOCKET(tcp)) {
3567 			/*
3568 			 * Send M_FLUSH according to TPI. Because sockets will
3569 			 * (and must) ignore FLUSHR we do that only for TPI
3570 			 * endpoints and sockets in STREAMS mode.
3571 			 */
3572 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3573 		}
3574 		if (tcp->tcp_debug) {
3575 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3576 			    "tcp_clean_death: discon err %d", err);
3577 		}
3578 		if (IPCL_IS_NONSTR(connp)) {
3579 			/* Direct socket, use upcall */
3580 			(*connp->conn_upcalls->su_disconnected)(
3581 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3582 		} else {
3583 			mp = mi_tpi_discon_ind(NULL, err, 0);
3584 			if (mp != NULL) {
3585 				putnext(q, mp);
3586 			} else {
3587 				if (tcp->tcp_debug) {
3588 					(void) strlog(TCP_MOD_ID, 0, 1,
3589 					    SL_ERROR|SL_TRACE,
3590 					    "tcp_clean_death, sending M_ERROR");
3591 				}
3592 				(void) putnextctl1(q, M_ERROR, EPROTO);
3593 			}
3594 		}
3595 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3596 			/* SYN_SENT or SYN_RCVD */
3597 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3598 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3599 			/* ESTABLISHED or CLOSE_WAIT */
3600 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3601 		}
3602 	}
3603 
3604 	tcp_reinit(tcp);
3605 	if (IPCL_IS_NONSTR(connp))
3606 		(void) tcp_do_unbind(connp);
3607 
3608 	return (-1);
3609 }
3610 
3611 /*
3612  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3613  * to expire, stop the wait and finish the close.
3614  */
3615 static void
3616 tcp_stop_lingering(tcp_t *tcp)
3617 {
3618 	clock_t	delta = 0;
3619 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3620 
3621 	tcp->tcp_linger_tid = 0;
3622 	if (tcp->tcp_state > TCPS_LISTEN) {
3623 		tcp_acceptor_hash_remove(tcp);
3624 		mutex_enter(&tcp->tcp_non_sq_lock);
3625 		if (tcp->tcp_flow_stopped) {
3626 			tcp_clrqfull(tcp);
3627 		}
3628 		mutex_exit(&tcp->tcp_non_sq_lock);
3629 
3630 		if (tcp->tcp_timer_tid != 0) {
3631 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3632 			tcp->tcp_timer_tid = 0;
3633 		}
3634 		/*
3635 		 * Need to cancel those timers which will not be used when
3636 		 * TCP is detached.  This has to be done before the tcp_wq
3637 		 * is set to the global queue.
3638 		 */
3639 		tcp_timers_stop(tcp);
3640 
3641 		tcp->tcp_detached = B_TRUE;
3642 		ASSERT(tcps->tcps_g_q != NULL);
3643 		tcp->tcp_rq = tcps->tcps_g_q;
3644 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3645 
3646 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3647 			tcp_time_wait_append(tcp);
3648 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3649 			goto finish;
3650 		}
3651 
3652 		/*
3653 		 * If delta is zero the timer event wasn't executed and was
3654 		 * successfully canceled. In this case we need to restart it
3655 		 * with the minimal delta possible.
3656 		 */
3657 		if (delta >= 0) {
3658 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3659 			    delta ? delta : 1);
3660 		}
3661 	} else {
3662 		tcp_closei_local(tcp);
3663 		CONN_DEC_REF(tcp->tcp_connp);
3664 	}
3665 finish:
3666 	/* Signal closing thread that it can complete close */
3667 	mutex_enter(&tcp->tcp_closelock);
3668 	tcp->tcp_detached = B_TRUE;
3669 	ASSERT(tcps->tcps_g_q != NULL);
3670 
3671 	tcp->tcp_rq = tcps->tcps_g_q;
3672 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3673 
3674 	tcp->tcp_closed = 1;
3675 	cv_signal(&tcp->tcp_closecv);
3676 	mutex_exit(&tcp->tcp_closelock);
3677 }
3678 
3679 /*
3680  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3681  * expires.
3682  */
3683 static void
3684 tcp_close_linger_timeout(void *arg)
3685 {
3686 	conn_t	*connp = (conn_t *)arg;
3687 	tcp_t 	*tcp = connp->conn_tcp;
3688 
3689 	tcp->tcp_client_errno = ETIMEDOUT;
3690 	tcp_stop_lingering(tcp);
3691 }
3692 
3693 static void
3694 tcp_close_common(conn_t *connp, int flags)
3695 {
3696 	tcp_t		*tcp = connp->conn_tcp;
3697 	mblk_t 		*mp = &tcp->tcp_closemp;
3698 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3699 	mblk_t		*bp;
3700 
3701 	ASSERT(connp->conn_ref >= 2);
3702 
3703 	/*
3704 	 * Mark the conn as closing. ill_pending_mp_add will not
3705 	 * add any mp to the pending mp list, after this conn has
3706 	 * started closing. Same for sq_pending_mp_add
3707 	 */
3708 	mutex_enter(&connp->conn_lock);
3709 	connp->conn_state_flags |= CONN_CLOSING;
3710 	if (connp->conn_oper_pending_ill != NULL)
3711 		conn_ioctl_cleanup_reqd = B_TRUE;
3712 	CONN_INC_REF_LOCKED(connp);
3713 	mutex_exit(&connp->conn_lock);
3714 	tcp->tcp_closeflags = (uint8_t)flags;
3715 	ASSERT(connp->conn_ref >= 3);
3716 
3717 	/*
3718 	 * tcp_closemp_used is used below without any protection of a lock
3719 	 * as we don't expect any one else to use it concurrently at this
3720 	 * point otherwise it would be a major defect.
3721 	 */
3722 
3723 	if (mp->b_prev == NULL)
3724 		tcp->tcp_closemp_used = B_TRUE;
3725 	else
3726 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3727 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3728 
3729 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3730 
3731 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3732 	    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3733 
3734 	mutex_enter(&tcp->tcp_closelock);
3735 	while (!tcp->tcp_closed) {
3736 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3737 			/*
3738 			 * The cv_wait_sig() was interrupted. We now do the
3739 			 * following:
3740 			 *
3741 			 * 1) If the endpoint was lingering, we allow this
3742 			 * to be interrupted by cancelling the linger timeout
3743 			 * and closing normally.
3744 			 *
3745 			 * 2) Revert to calling cv_wait()
3746 			 *
3747 			 * We revert to using cv_wait() to avoid an
3748 			 * infinite loop which can occur if the calling
3749 			 * thread is higher priority than the squeue worker
3750 			 * thread and is bound to the same cpu.
3751 			 */
3752 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
3753 				mutex_exit(&tcp->tcp_closelock);
3754 				/* Entering squeue, bump ref count. */
3755 				CONN_INC_REF(connp);
3756 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3757 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3758 				    tcp_linger_interrupted, connp,
3759 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3760 				mutex_enter(&tcp->tcp_closelock);
3761 			}
3762 			break;
3763 		}
3764 	}
3765 	while (!tcp->tcp_closed)
3766 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3767 	mutex_exit(&tcp->tcp_closelock);
3768 
3769 	/*
3770 	 * In the case of listener streams that have eagers in the q or q0
3771 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3772 	 * tcp_wq of the eagers point to our queues. By waiting for the
3773 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3774 	 * up their queue pointers and also dropped their references to us.
3775 	 */
3776 	if (tcp->tcp_wait_for_eagers) {
3777 		mutex_enter(&connp->conn_lock);
3778 		while (connp->conn_ref != 1) {
3779 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3780 		}
3781 		mutex_exit(&connp->conn_lock);
3782 	}
3783 	/*
3784 	 * ioctl cleanup. The mp is queued in the
3785 	 * ill_pending_mp or in the sq_pending_mp.
3786 	 */
3787 	if (conn_ioctl_cleanup_reqd)
3788 		conn_ioctl_cleanup(connp);
3789 
3790 	tcp->tcp_cpid = -1;
3791 }
3792 
3793 static int
3794 tcp_tpi_close(queue_t *q, int flags)
3795 {
3796 	conn_t		*connp;
3797 
3798 	ASSERT(WR(q)->q_next == NULL);
3799 
3800 	if (flags & SO_FALLBACK) {
3801 		/*
3802 		 * stream is being closed while in fallback
3803 		 * simply free the resources that were allocated
3804 		 */
3805 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3806 		qprocsoff(q);
3807 		goto done;
3808 	}
3809 
3810 	connp = Q_TO_CONN(q);
3811 	/*
3812 	 * We are being closed as /dev/tcp or /dev/tcp6.
3813 	 */
3814 	tcp_close_common(connp, flags);
3815 
3816 	qprocsoff(q);
3817 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3818 
3819 	/*
3820 	 * Drop IP's reference on the conn. This is the last reference
3821 	 * on the connp if the state was less than established. If the
3822 	 * connection has gone into timewait state, then we will have
3823 	 * one ref for the TCP and one more ref (total of two) for the
3824 	 * classifier connected hash list (a timewait connections stays
3825 	 * in connected hash till closed).
3826 	 *
3827 	 * We can't assert the references because there might be other
3828 	 * transient reference places because of some walkers or queued
3829 	 * packets in squeue for the timewait state.
3830 	 */
3831 	CONN_DEC_REF(connp);
3832 done:
3833 	q->q_ptr = WR(q)->q_ptr = NULL;
3834 	return (0);
3835 }
3836 
3837 static int
3838 tcpclose_accept(queue_t *q)
3839 {
3840 	vmem_t	*minor_arena;
3841 	dev_t	conn_dev;
3842 
3843 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3844 
3845 	/*
3846 	 * We had opened an acceptor STREAM for sockfs which is
3847 	 * now being closed due to some error.
3848 	 */
3849 	qprocsoff(q);
3850 
3851 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3852 	conn_dev = (dev_t)RD(q)->q_ptr;
3853 	ASSERT(minor_arena != NULL);
3854 	ASSERT(conn_dev != 0);
3855 	inet_minor_free(minor_arena, conn_dev);
3856 	q->q_ptr = WR(q)->q_ptr = NULL;
3857 	return (0);
3858 }
3859 
3860 /*
3861  * Called by tcp_close() routine via squeue when lingering is
3862  * interrupted by a signal.
3863  */
3864 
3865 /* ARGSUSED */
3866 static void
3867 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
3868 {
3869 	conn_t	*connp = (conn_t *)arg;
3870 	tcp_t	*tcp = connp->conn_tcp;
3871 
3872 	freeb(mp);
3873 	if (tcp->tcp_linger_tid != 0 &&
3874 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3875 		tcp_stop_lingering(tcp);
3876 		tcp->tcp_client_errno = EINTR;
3877 	}
3878 }
3879 
3880 /*
3881  * Called by streams close routine via squeues when our client blows off her
3882  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3883  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3884  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3885  * acked.
3886  *
3887  * NOTE: tcp_close potentially returns error when lingering.
3888  * However, the stream head currently does not pass these errors
3889  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3890  * errors to the application (from tsleep()) and not errors
3891  * like ECONNRESET caused by receiving a reset packet.
3892  */
3893 
3894 /* ARGSUSED */
3895 static void
3896 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3897 {
3898 	char	*msg;
3899 	conn_t	*connp = (conn_t *)arg;
3900 	tcp_t	*tcp = connp->conn_tcp;
3901 	clock_t	delta = 0;
3902 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3903 
3904 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3905 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3906 
3907 	mutex_enter(&tcp->tcp_eager_lock);
3908 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3909 		/* Cleanup for listener */
3910 		tcp_eager_cleanup(tcp, 0);
3911 		tcp->tcp_wait_for_eagers = 1;
3912 	}
3913 	mutex_exit(&tcp->tcp_eager_lock);
3914 
3915 	connp->conn_mdt_ok = B_FALSE;
3916 	tcp->tcp_mdt = B_FALSE;
3917 
3918 	connp->conn_lso_ok = B_FALSE;
3919 	tcp->tcp_lso = B_FALSE;
3920 
3921 	msg = NULL;
3922 	switch (tcp->tcp_state) {
3923 	case TCPS_CLOSED:
3924 	case TCPS_IDLE:
3925 	case TCPS_BOUND:
3926 	case TCPS_LISTEN:
3927 		break;
3928 	case TCPS_SYN_SENT:
3929 		msg = "tcp_close, during connect";
3930 		break;
3931 	case TCPS_SYN_RCVD:
3932 		/*
3933 		 * Close during the connect 3-way handshake
3934 		 * but here there may or may not be pending data
3935 		 * already on queue. Process almost same as in
3936 		 * the ESTABLISHED state.
3937 		 */
3938 		/* FALLTHRU */
3939 	default:
3940 		if (tcp->tcp_sodirect != NULL) {
3941 			/* Ok, no more sodirect */
3942 			tcp->tcp_sodirect = NULL;
3943 		}
3944 
3945 		if (tcp->tcp_fused)
3946 			tcp_unfuse(tcp);
3947 
3948 		/*
3949 		 * If SO_LINGER has set a zero linger time, abort the
3950 		 * connection with a reset.
3951 		 */
3952 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3953 			msg = "tcp_close, zero lingertime";
3954 			break;
3955 		}
3956 
3957 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3958 		/*
3959 		 * Abort connection if there is unread data queued.
3960 		 */
3961 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3962 			msg = "tcp_close, unread data";
3963 			break;
3964 		}
3965 		/*
3966 		 * tcp_hard_bound is now cleared thus all packets go through
3967 		 * tcp_lookup. This fact is used by tcp_detach below.
3968 		 *
3969 		 * We have done a qwait() above which could have possibly
3970 		 * drained more messages in turn causing transition to a
3971 		 * different state. Check whether we have to do the rest
3972 		 * of the processing or not.
3973 		 */
3974 		if (tcp->tcp_state <= TCPS_LISTEN)
3975 			break;
3976 
3977 		/*
3978 		 * Transmit the FIN before detaching the tcp_t.
3979 		 * After tcp_detach returns this queue/perimeter
3980 		 * no longer owns the tcp_t thus others can modify it.
3981 		 */
3982 		(void) tcp_xmit_end(tcp);
3983 
3984 		/*
3985 		 * If lingering on close then wait until the fin is acked,
3986 		 * the SO_LINGER time passes, or a reset is sent/received.
3987 		 */
3988 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
3989 		    !(tcp->tcp_fin_acked) &&
3990 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3991 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3992 				tcp->tcp_client_errno = EWOULDBLOCK;
3993 			} else if (tcp->tcp_client_errno == 0) {
3994 
3995 				ASSERT(tcp->tcp_linger_tid == 0);
3996 
3997 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3998 				    tcp_close_linger_timeout,
3999 				    tcp->tcp_lingertime * hz);
4000 
4001 				/* tcp_close_linger_timeout will finish close */
4002 				if (tcp->tcp_linger_tid == 0)
4003 					tcp->tcp_client_errno = ENOSR;
4004 				else
4005 					return;
4006 			}
4007 
4008 			/*
4009 			 * Check if we need to detach or just close
4010 			 * the instance.
4011 			 */
4012 			if (tcp->tcp_state <= TCPS_LISTEN)
4013 				break;
4014 		}
4015 
4016 		/*
4017 		 * Make sure that no other thread will access the tcp_rq of
4018 		 * this instance (through lookups etc.) as tcp_rq will go
4019 		 * away shortly.
4020 		 */
4021 		tcp_acceptor_hash_remove(tcp);
4022 
4023 		mutex_enter(&tcp->tcp_non_sq_lock);
4024 		if (tcp->tcp_flow_stopped) {
4025 			tcp_clrqfull(tcp);
4026 		}
4027 		mutex_exit(&tcp->tcp_non_sq_lock);
4028 
4029 		if (tcp->tcp_timer_tid != 0) {
4030 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4031 			tcp->tcp_timer_tid = 0;
4032 		}
4033 		/*
4034 		 * Need to cancel those timers which will not be used when
4035 		 * TCP is detached.  This has to be done before the tcp_wq
4036 		 * is set to the global queue.
4037 		 */
4038 		tcp_timers_stop(tcp);
4039 
4040 		tcp->tcp_detached = B_TRUE;
4041 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4042 			tcp_time_wait_append(tcp);
4043 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
4044 			ASSERT(connp->conn_ref >= 3);
4045 			goto finish;
4046 		}
4047 
4048 		/*
4049 		 * If delta is zero the timer event wasn't executed and was
4050 		 * successfully canceled. In this case we need to restart it
4051 		 * with the minimal delta possible.
4052 		 */
4053 		if (delta >= 0)
4054 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4055 			    delta ? delta : 1);
4056 
4057 		ASSERT(connp->conn_ref >= 3);
4058 		goto finish;
4059 	}
4060 
4061 	/* Detach did not complete. Still need to remove q from stream. */
4062 	if (msg) {
4063 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4064 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4065 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4066 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4067 		    tcp->tcp_state == TCPS_SYN_RCVD)
4068 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4069 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4070 	}
4071 
4072 	tcp_closei_local(tcp);
4073 	CONN_DEC_REF(connp);
4074 	ASSERT(connp->conn_ref >= 2);
4075 
4076 finish:
4077 	/*
4078 	 * Although packets are always processed on the correct
4079 	 * tcp's perimeter and access is serialized via squeue's,
4080 	 * IP still needs a queue when sending packets in time_wait
4081 	 * state so use WR(tcps_g_q) till ip_output() can be
4082 	 * changed to deal with just connp. For read side, we
4083 	 * could have set tcp_rq to NULL but there are some cases
4084 	 * in tcp_rput_data() from early days of this code which
4085 	 * do a putnext without checking if tcp is closed. Those
4086 	 * need to be identified before both tcp_rq and tcp_wq
4087 	 * can be set to NULL and tcps_g_q can disappear forever.
4088 	 */
4089 	mutex_enter(&tcp->tcp_closelock);
4090 	/*
4091 	 * Don't change the queues in the case of a listener that has
4092 	 * eagers in its q or q0. It could surprise the eagers.
4093 	 * Instead wait for the eagers outside the squeue.
4094 	 */
4095 	if (!tcp->tcp_wait_for_eagers) {
4096 		tcp->tcp_detached = B_TRUE;
4097 		/*
4098 		 * When default queue is closing we set tcps_g_q to NULL
4099 		 * after the close is done.
4100 		 */
4101 		ASSERT(tcps->tcps_g_q != NULL);
4102 		tcp->tcp_rq = tcps->tcps_g_q;
4103 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4104 	}
4105 
4106 	/* Signal tcp_close() to finish closing. */
4107 	tcp->tcp_closed = 1;
4108 	cv_signal(&tcp->tcp_closecv);
4109 	mutex_exit(&tcp->tcp_closelock);
4110 }
4111 
4112 
4113 /*
4114  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4115  * Some stream heads get upset if they see these later on as anything but NULL.
4116  */
4117 static void
4118 tcp_close_mpp(mblk_t **mpp)
4119 {
4120 	mblk_t	*mp;
4121 
4122 	if ((mp = *mpp) != NULL) {
4123 		do {
4124 			mp->b_next = NULL;
4125 			mp->b_prev = NULL;
4126 		} while ((mp = mp->b_cont) != NULL);
4127 
4128 		mp = *mpp;
4129 		*mpp = NULL;
4130 		freemsg(mp);
4131 	}
4132 }
4133 
4134 /* Do detached close. */
4135 static void
4136 tcp_close_detached(tcp_t *tcp)
4137 {
4138 	if (tcp->tcp_fused)
4139 		tcp_unfuse(tcp);
4140 
4141 	/*
4142 	 * Clustering code serializes TCP disconnect callbacks and
4143 	 * cluster tcp list walks by blocking a TCP disconnect callback
4144 	 * if a cluster tcp list walk is in progress. This ensures
4145 	 * accurate accounting of TCPs in the cluster code even though
4146 	 * the TCP list walk itself is not atomic.
4147 	 */
4148 	tcp_closei_local(tcp);
4149 	CONN_DEC_REF(tcp->tcp_connp);
4150 }
4151 
4152 /*
4153  * Stop all TCP timers, and free the timer mblks if requested.
4154  */
4155 void
4156 tcp_timers_stop(tcp_t *tcp)
4157 {
4158 	if (tcp->tcp_timer_tid != 0) {
4159 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4160 		tcp->tcp_timer_tid = 0;
4161 	}
4162 	if (tcp->tcp_ka_tid != 0) {
4163 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4164 		tcp->tcp_ka_tid = 0;
4165 	}
4166 	if (tcp->tcp_ack_tid != 0) {
4167 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4168 		tcp->tcp_ack_tid = 0;
4169 	}
4170 	if (tcp->tcp_push_tid != 0) {
4171 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4172 		tcp->tcp_push_tid = 0;
4173 	}
4174 }
4175 
4176 /*
4177  * The tcp_t is going away. Remove it from all lists and set it
4178  * to TCPS_CLOSED. The freeing up of memory is deferred until
4179  * tcp_inactive. This is needed since a thread in tcp_rput might have
4180  * done a CONN_INC_REF on this structure before it was removed from the
4181  * hashes.
4182  */
4183 static void
4184 tcp_closei_local(tcp_t *tcp)
4185 {
4186 	ire_t 	*ire;
4187 	conn_t	*connp = tcp->tcp_connp;
4188 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4189 
4190 	if (!TCP_IS_SOCKET(tcp))
4191 		tcp_acceptor_hash_remove(tcp);
4192 
4193 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4194 	tcp->tcp_ibsegs = 0;
4195 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4196 	tcp->tcp_obsegs = 0;
4197 
4198 	/*
4199 	 * If we are an eager connection hanging off a listener that
4200 	 * hasn't formally accepted the connection yet, get off his
4201 	 * list and blow off any data that we have accumulated.
4202 	 */
4203 	if (tcp->tcp_listener != NULL) {
4204 		tcp_t	*listener = tcp->tcp_listener;
4205 		mutex_enter(&listener->tcp_eager_lock);
4206 		/*
4207 		 * tcp_tconnind_started == B_TRUE means that the
4208 		 * conn_ind has already gone to listener. At
4209 		 * this point, eager will be closed but we
4210 		 * leave it in listeners eager list so that
4211 		 * if listener decides to close without doing
4212 		 * accept, we can clean this up. In tcp_wput_accept
4213 		 * we take care of the case of accept on closed
4214 		 * eager.
4215 		 */
4216 		if (!tcp->tcp_tconnind_started) {
4217 			tcp_eager_unlink(tcp);
4218 			mutex_exit(&listener->tcp_eager_lock);
4219 			/*
4220 			 * We don't want to have any pointers to the
4221 			 * listener queue, after we have released our
4222 			 * reference on the listener
4223 			 */
4224 			ASSERT(tcps->tcps_g_q != NULL);
4225 			tcp->tcp_rq = tcps->tcps_g_q;
4226 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4227 			CONN_DEC_REF(listener->tcp_connp);
4228 		} else {
4229 			mutex_exit(&listener->tcp_eager_lock);
4230 		}
4231 	}
4232 
4233 	/* Stop all the timers */
4234 	tcp_timers_stop(tcp);
4235 
4236 	if (tcp->tcp_state == TCPS_LISTEN) {
4237 		if (tcp->tcp_ip_addr_cache) {
4238 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4239 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4240 			tcp->tcp_ip_addr_cache = NULL;
4241 		}
4242 	}
4243 	mutex_enter(&tcp->tcp_non_sq_lock);
4244 	if (tcp->tcp_flow_stopped)
4245 		tcp_clrqfull(tcp);
4246 	mutex_exit(&tcp->tcp_non_sq_lock);
4247 
4248 	tcp_bind_hash_remove(tcp);
4249 	/*
4250 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4251 	 * is trying to remove this tcp from the time wait list, we will
4252 	 * block in tcp_time_wait_remove while trying to acquire the
4253 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4254 	 * requires the ipcl_hash_remove to be ordered after the
4255 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4256 	 */
4257 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4258 		(void) tcp_time_wait_remove(tcp, NULL);
4259 	CL_INET_DISCONNECT(connp, tcp);
4260 	ipcl_hash_remove(connp);
4261 
4262 	/*
4263 	 * Delete the cached ire in conn_ire_cache and also mark
4264 	 * the conn as CONDEMNED
4265 	 */
4266 	mutex_enter(&connp->conn_lock);
4267 	connp->conn_state_flags |= CONN_CONDEMNED;
4268 	ire = connp->conn_ire_cache;
4269 	connp->conn_ire_cache = NULL;
4270 	mutex_exit(&connp->conn_lock);
4271 	if (ire != NULL)
4272 		IRE_REFRELE_NOTR(ire);
4273 
4274 	/* Need to cleanup any pending ioctls */
4275 	ASSERT(tcp->tcp_time_wait_next == NULL);
4276 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4277 	ASSERT(tcp->tcp_time_wait_expire == 0);
4278 	tcp->tcp_state = TCPS_CLOSED;
4279 
4280 	/* Release any SSL context */
4281 	if (tcp->tcp_kssl_ent != NULL) {
4282 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4283 		tcp->tcp_kssl_ent = NULL;
4284 	}
4285 	if (tcp->tcp_kssl_ctx != NULL) {
4286 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4287 		tcp->tcp_kssl_ctx = NULL;
4288 	}
4289 	tcp->tcp_kssl_pending = B_FALSE;
4290 
4291 	tcp_ipsec_cleanup(tcp);
4292 }
4293 
4294 /*
4295  * tcp is dying (called from ipcl_conn_destroy and error cases).
4296  * Free the tcp_t in either case.
4297  */
4298 void
4299 tcp_free(tcp_t *tcp)
4300 {
4301 	mblk_t	*mp;
4302 	ip6_pkt_t	*ipp;
4303 
4304 	ASSERT(tcp != NULL);
4305 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4306 
4307 	tcp->tcp_rq = NULL;
4308 	tcp->tcp_wq = NULL;
4309 
4310 	tcp_close_mpp(&tcp->tcp_xmit_head);
4311 	tcp_close_mpp(&tcp->tcp_reass_head);
4312 	if (tcp->tcp_rcv_list != NULL) {
4313 		/* Free b_next chain */
4314 		tcp_close_mpp(&tcp->tcp_rcv_list);
4315 	}
4316 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4317 		freemsg(mp);
4318 	}
4319 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4320 		freemsg(mp);
4321 	}
4322 
4323 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4324 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4325 		freeb(tcp->tcp_fused_sigurg_mp);
4326 		tcp->tcp_fused_sigurg_mp = NULL;
4327 	}
4328 
4329 	if (tcp->tcp_ordrel_mp != NULL) {
4330 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4331 		freeb(tcp->tcp_ordrel_mp);
4332 		tcp->tcp_ordrel_mp = NULL;
4333 	}
4334 
4335 	if (tcp->tcp_sack_info != NULL) {
4336 		if (tcp->tcp_notsack_list != NULL) {
4337 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4338 		}
4339 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4340 	}
4341 
4342 	if (tcp->tcp_hopopts != NULL) {
4343 		mi_free(tcp->tcp_hopopts);
4344 		tcp->tcp_hopopts = NULL;
4345 		tcp->tcp_hopoptslen = 0;
4346 	}
4347 	ASSERT(tcp->tcp_hopoptslen == 0);
4348 	if (tcp->tcp_dstopts != NULL) {
4349 		mi_free(tcp->tcp_dstopts);
4350 		tcp->tcp_dstopts = NULL;
4351 		tcp->tcp_dstoptslen = 0;
4352 	}
4353 	ASSERT(tcp->tcp_dstoptslen == 0);
4354 	if (tcp->tcp_rtdstopts != NULL) {
4355 		mi_free(tcp->tcp_rtdstopts);
4356 		tcp->tcp_rtdstopts = NULL;
4357 		tcp->tcp_rtdstoptslen = 0;
4358 	}
4359 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4360 	if (tcp->tcp_rthdr != NULL) {
4361 		mi_free(tcp->tcp_rthdr);
4362 		tcp->tcp_rthdr = NULL;
4363 		tcp->tcp_rthdrlen = 0;
4364 	}
4365 	ASSERT(tcp->tcp_rthdrlen == 0);
4366 
4367 	ipp = &tcp->tcp_sticky_ipp;
4368 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4369 	    IPPF_RTHDR))
4370 		ip6_pkt_free(ipp);
4371 
4372 	/*
4373 	 * Free memory associated with the tcp/ip header template.
4374 	 */
4375 
4376 	if (tcp->tcp_iphc != NULL)
4377 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4378 
4379 	/*
4380 	 * Following is really a blowing away a union.
4381 	 * It happens to have exactly two members of identical size
4382 	 * the following code is enough.
4383 	 */
4384 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4385 }
4386 
4387 
4388 /*
4389  * Put a connection confirmation message upstream built from the
4390  * address information within 'iph' and 'tcph'.  Report our success or failure.
4391  */
4392 static boolean_t
4393 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4394     mblk_t **defermp)
4395 {
4396 	sin_t	sin;
4397 	sin6_t	sin6;
4398 	mblk_t	*mp;
4399 	char	*optp = NULL;
4400 	int	optlen = 0;
4401 	cred_t	*cr;
4402 
4403 	if (defermp != NULL)
4404 		*defermp = NULL;
4405 
4406 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4407 		/*
4408 		 * Return in T_CONN_CON results of option negotiation through
4409 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4410 		 * negotiation, then what is received from remote end needs
4411 		 * to be taken into account but there is no such thing (yet?)
4412 		 * in our TCP/IP.
4413 		 * Note: We do not use mi_offset_param() here as
4414 		 * tcp_opts_conn_req contents do not directly come from
4415 		 * an application and are either generated in kernel or
4416 		 * from user input that was already verified.
4417 		 */
4418 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4419 		optp = (char *)(mp->b_rptr +
4420 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4421 		optlen = (int)
4422 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4423 	}
4424 
4425 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4426 		ipha_t *ipha = (ipha_t *)iphdr;
4427 
4428 		/* packet is IPv4 */
4429 		if (tcp->tcp_family == AF_INET) {
4430 			sin = sin_null;
4431 			sin.sin_addr.s_addr = ipha->ipha_src;
4432 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4433 			sin.sin_family = AF_INET;
4434 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4435 			    (int)sizeof (sin_t), optp, optlen);
4436 		} else {
4437 			sin6 = sin6_null;
4438 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4439 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4440 			sin6.sin6_family = AF_INET6;
4441 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4442 			    (int)sizeof (sin6_t), optp, optlen);
4443 
4444 		}
4445 	} else {
4446 		ip6_t	*ip6h = (ip6_t *)iphdr;
4447 
4448 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4449 		ASSERT(tcp->tcp_family == AF_INET6);
4450 		sin6 = sin6_null;
4451 		sin6.sin6_addr = ip6h->ip6_src;
4452 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4453 		sin6.sin6_family = AF_INET6;
4454 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4455 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4456 		    (int)sizeof (sin6_t), optp, optlen);
4457 	}
4458 
4459 	if (!mp)
4460 		return (B_FALSE);
4461 
4462 	if ((cr = DB_CRED(idmp)) != NULL) {
4463 		mblk_setcred(mp, cr);
4464 		DB_CPID(mp) = DB_CPID(idmp);
4465 	}
4466 
4467 	if (defermp == NULL) {
4468 		conn_t *connp = tcp->tcp_connp;
4469 		if (IPCL_IS_NONSTR(connp)) {
4470 			(*connp->conn_upcalls->su_connected)
4471 			    (connp->conn_upper_handle, tcp->tcp_connid, cr,
4472 			    DB_CPID(mp));
4473 			freemsg(mp);
4474 		} else {
4475 			putnext(tcp->tcp_rq, mp);
4476 		}
4477 	} else {
4478 		*defermp = mp;
4479 	}
4480 
4481 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4482 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4483 	return (B_TRUE);
4484 }
4485 
4486 /*
4487  * Defense for the SYN attack -
4488  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4489  *    one from the list of droppable eagers. This list is a subset of q0.
4490  *    see comments before the definition of MAKE_DROPPABLE().
4491  * 2. Don't drop a SYN request before its first timeout. This gives every
4492  *    request at least til the first timeout to complete its 3-way handshake.
4493  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4494  *    requests currently on the queue that has timed out. This will be used
4495  *    as an indicator of whether an attack is under way, so that appropriate
4496  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4497  *    either when eager goes into ESTABLISHED, or gets freed up.)
4498  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4499  *    # of timeout drops back to <= q0len/32 => SYN alert off
4500  */
4501 static boolean_t
4502 tcp_drop_q0(tcp_t *tcp)
4503 {
4504 	tcp_t	*eager;
4505 	mblk_t	*mp;
4506 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4507 
4508 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4509 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4510 
4511 	/* Pick oldest eager from the list of droppable eagers */
4512 	eager = tcp->tcp_eager_prev_drop_q0;
4513 
4514 	/* If list is empty. return B_FALSE */
4515 	if (eager == tcp) {
4516 		return (B_FALSE);
4517 	}
4518 
4519 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4520 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4521 		return (B_FALSE);
4522 
4523 	/*
4524 	 * Take this eager out from the list of droppable eagers since we are
4525 	 * going to drop it.
4526 	 */
4527 	MAKE_UNDROPPABLE(eager);
4528 
4529 	if (tcp->tcp_debug) {
4530 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4531 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4532 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4533 		    tcp->tcp_conn_req_cnt_q0,
4534 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4535 	}
4536 
4537 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4538 
4539 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4540 	CONN_INC_REF(eager->tcp_connp);
4541 
4542 	/* Mark the IRE created for this SYN request temporary */
4543 	tcp_ip_ire_mark_advice(eager);
4544 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4545 	    tcp_clean_death_wrapper, eager->tcp_connp,
4546 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4547 
4548 	return (B_TRUE);
4549 }
4550 
4551 int
4552 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4553     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4554 {
4555 	tcp_t 		*ltcp = lconnp->conn_tcp;
4556 	tcp_t		*tcp = connp->conn_tcp;
4557 	mblk_t		*tpi_mp;
4558 	ipha_t		*ipha;
4559 	ip6_t		*ip6h;
4560 	sin6_t 		sin6;
4561 	in6_addr_t 	v6dst;
4562 	int		err;
4563 	int		ifindex = 0;
4564 	cred_t		*cr;
4565 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4566 
4567 	if (ipvers == IPV4_VERSION) {
4568 		ipha = (ipha_t *)mp->b_rptr;
4569 
4570 		connp->conn_send = ip_output;
4571 		connp->conn_recv = tcp_input;
4572 
4573 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4574 		    &connp->conn_bound_source_v6);
4575 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4576 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4577 
4578 		sin6 = sin6_null;
4579 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4580 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4581 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4582 		sin6.sin6_family = AF_INET6;
4583 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4584 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4585 		if (tcp->tcp_recvdstaddr) {
4586 			sin6_t	sin6d;
4587 
4588 			sin6d = sin6_null;
4589 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4590 			    &sin6d.sin6_addr);
4591 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4592 			sin6d.sin6_family = AF_INET;
4593 			tpi_mp = mi_tpi_extconn_ind(NULL,
4594 			    (char *)&sin6d, sizeof (sin6_t),
4595 			    (char *)&tcp,
4596 			    (t_scalar_t)sizeof (intptr_t),
4597 			    (char *)&sin6d, sizeof (sin6_t),
4598 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4599 		} else {
4600 			tpi_mp = mi_tpi_conn_ind(NULL,
4601 			    (char *)&sin6, sizeof (sin6_t),
4602 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4603 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4604 		}
4605 	} else {
4606 		ip6h = (ip6_t *)mp->b_rptr;
4607 
4608 		connp->conn_send = ip_output_v6;
4609 		connp->conn_recv = tcp_input;
4610 
4611 		connp->conn_bound_source_v6 = ip6h->ip6_dst;
4612 		connp->conn_srcv6 = ip6h->ip6_dst;
4613 		connp->conn_remv6 = ip6h->ip6_src;
4614 
4615 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4616 		ifindex = (int)DB_CKSUMSTUFF(mp);
4617 		DB_CKSUMSTUFF(mp) = 0;
4618 
4619 		sin6 = sin6_null;
4620 		sin6.sin6_addr = ip6h->ip6_src;
4621 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4622 		sin6.sin6_family = AF_INET6;
4623 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4624 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4625 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4626 
4627 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4628 			/* Pass up the scope_id of remote addr */
4629 			sin6.sin6_scope_id = ifindex;
4630 		} else {
4631 			sin6.sin6_scope_id = 0;
4632 		}
4633 		if (tcp->tcp_recvdstaddr) {
4634 			sin6_t	sin6d;
4635 
4636 			sin6d = sin6_null;
4637 			sin6.sin6_addr = ip6h->ip6_dst;
4638 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4639 			sin6d.sin6_family = AF_INET;
4640 			tpi_mp = mi_tpi_extconn_ind(NULL,
4641 			    (char *)&sin6d, sizeof (sin6_t),
4642 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4643 			    (char *)&sin6d, sizeof (sin6_t),
4644 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4645 		} else {
4646 			tpi_mp = mi_tpi_conn_ind(NULL,
4647 			    (char *)&sin6, sizeof (sin6_t),
4648 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4649 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4650 		}
4651 	}
4652 
4653 	if (tpi_mp == NULL)
4654 		return (ENOMEM);
4655 
4656 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4657 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4658 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4659 	connp->conn_fully_bound = B_FALSE;
4660 
4661 	/* Inherit information from the "parent" */
4662 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4663 	tcp->tcp_family = ltcp->tcp_family;
4664 
4665 	tcp->tcp_wq = ltcp->tcp_wq;
4666 	tcp->tcp_rq = ltcp->tcp_rq;
4667 
4668 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4669 	tcp->tcp_detached = B_TRUE;
4670 	SOCK_CONNID_INIT(tcp->tcp_connid);
4671 	if ((err = tcp_init_values(tcp)) != 0) {
4672 		freemsg(tpi_mp);
4673 		return (err);
4674 	}
4675 
4676 	if (ipvers == IPV4_VERSION) {
4677 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4678 			freemsg(tpi_mp);
4679 			return (err);
4680 		}
4681 		ASSERT(tcp->tcp_ipha != NULL);
4682 	} else {
4683 		/* ifindex must be already set */
4684 		ASSERT(ifindex != 0);
4685 
4686 		if (ltcp->tcp_bound_if != 0) {
4687 			/*
4688 			 * Set newtcp's bound_if equal to
4689 			 * listener's value. If ifindex is
4690 			 * not the same as ltcp->tcp_bound_if,
4691 			 * it must be a packet for the ipmp group
4692 			 * of interfaces
4693 			 */
4694 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4695 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4696 			tcp->tcp_bound_if = ifindex;
4697 		}
4698 
4699 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4700 		tcp->tcp_recvifindex = 0;
4701 		tcp->tcp_recvhops = 0xffffffffU;
4702 		ASSERT(tcp->tcp_ip6h != NULL);
4703 	}
4704 
4705 	tcp->tcp_lport = ltcp->tcp_lport;
4706 
4707 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4708 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4709 			/*
4710 			 * Listener had options of some sort; eager inherits.
4711 			 * Free up the eager template and allocate one
4712 			 * of the right size.
4713 			 */
4714 			if (tcp->tcp_hdr_grown) {
4715 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4716 			} else {
4717 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4718 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4719 			}
4720 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4721 			    KM_NOSLEEP);
4722 			if (tcp->tcp_iphc == NULL) {
4723 				tcp->tcp_iphc_len = 0;
4724 				freemsg(tpi_mp);
4725 				return (ENOMEM);
4726 			}
4727 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4728 			tcp->tcp_hdr_grown = B_TRUE;
4729 		}
4730 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4731 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4732 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4733 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4734 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4735 
4736 		/*
4737 		 * Copy the IP+TCP header template from listener to eager
4738 		 */
4739 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4740 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4741 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4742 			    IPPROTO_RAW) {
4743 				tcp->tcp_ip6h =
4744 				    (ip6_t *)(tcp->tcp_iphc +
4745 				    sizeof (ip6i_t));
4746 			} else {
4747 				tcp->tcp_ip6h =
4748 				    (ip6_t *)(tcp->tcp_iphc);
4749 			}
4750 			tcp->tcp_ipha = NULL;
4751 		} else {
4752 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4753 			tcp->tcp_ip6h = NULL;
4754 		}
4755 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4756 		    tcp->tcp_ip_hdr_len);
4757 	} else {
4758 		/*
4759 		 * only valid case when ipversion of listener and
4760 		 * eager differ is when listener is IPv6 and
4761 		 * eager is IPv4.
4762 		 * Eager header template has been initialized to the
4763 		 * maximum v4 header sizes, which includes space for
4764 		 * TCP and IP options.
4765 		 */
4766 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4767 		    (tcp->tcp_ipversion == IPV4_VERSION));
4768 		ASSERT(tcp->tcp_iphc_len >=
4769 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4770 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4771 		/* copy IP header fields individually */
4772 		tcp->tcp_ipha->ipha_ttl =
4773 		    ltcp->tcp_ip6h->ip6_hops;
4774 		bcopy(ltcp->tcp_tcph->th_lport,
4775 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4776 	}
4777 
4778 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4779 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4780 	    sizeof (in_port_t));
4781 
4782 	if (ltcp->tcp_lport == 0) {
4783 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4784 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4785 		    sizeof (in_port_t));
4786 	}
4787 
4788 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4789 		ASSERT(ipha != NULL);
4790 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4791 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4792 
4793 		/* Source routing option copyover (reverse it) */
4794 		if (tcps->tcps_rev_src_routes)
4795 			tcp_opt_reverse(tcp, ipha);
4796 	} else {
4797 		ASSERT(ip6h != NULL);
4798 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4799 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4800 	}
4801 
4802 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4803 	ASSERT(!tcp->tcp_tconnind_started);
4804 	/*
4805 	 * If the SYN contains a credential, it's a loopback packet; attach
4806 	 * the credential to the TPI message.
4807 	 */
4808 	if ((cr = DB_CRED(idmp)) != NULL) {
4809 		mblk_setcred(tpi_mp, cr);
4810 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4811 	}
4812 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4813 
4814 	/* Inherit the listener's SSL protection state */
4815 
4816 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4817 		kssl_hold_ent(tcp->tcp_kssl_ent);
4818 		tcp->tcp_kssl_pending = B_TRUE;
4819 	}
4820 
4821 	/* Inherit the listener's non-STREAMS flag */
4822 	if (IPCL_IS_NONSTR(lconnp)) {
4823 		connp->conn_flags |= IPCL_NONSTR;
4824 		connp->conn_upcalls = lconnp->conn_upcalls;
4825 	}
4826 
4827 	return (0);
4828 }
4829 
4830 
4831 int
4832 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4833     tcph_t *tcph, mblk_t *idmp)
4834 {
4835 	tcp_t 		*ltcp = lconnp->conn_tcp;
4836 	tcp_t		*tcp = connp->conn_tcp;
4837 	sin_t		sin;
4838 	mblk_t		*tpi_mp = NULL;
4839 	int		err;
4840 	cred_t		*cr;
4841 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4842 
4843 	sin = sin_null;
4844 	sin.sin_addr.s_addr = ipha->ipha_src;
4845 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4846 	sin.sin_family = AF_INET;
4847 	if (ltcp->tcp_recvdstaddr) {
4848 		sin_t	sind;
4849 
4850 		sind = sin_null;
4851 		sind.sin_addr.s_addr = ipha->ipha_dst;
4852 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4853 		sind.sin_family = AF_INET;
4854 		tpi_mp = mi_tpi_extconn_ind(NULL,
4855 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4856 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4857 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4858 	} else {
4859 		tpi_mp = mi_tpi_conn_ind(NULL,
4860 		    (char *)&sin, sizeof (sin_t),
4861 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4862 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4863 	}
4864 
4865 	if (tpi_mp == NULL) {
4866 		return (ENOMEM);
4867 	}
4868 
4869 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4870 	connp->conn_send = ip_output;
4871 	connp->conn_recv = tcp_input;
4872 	connp->conn_fully_bound = B_FALSE;
4873 
4874 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_bound_source_v6);
4875 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4876 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4877 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4878 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4879 
4880 	/* Inherit information from the "parent" */
4881 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4882 	tcp->tcp_family = ltcp->tcp_family;
4883 	tcp->tcp_wq = ltcp->tcp_wq;
4884 	tcp->tcp_rq = ltcp->tcp_rq;
4885 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4886 	tcp->tcp_detached = B_TRUE;
4887 	SOCK_CONNID_INIT(tcp->tcp_connid);
4888 	if ((err = tcp_init_values(tcp)) != 0) {
4889 		freemsg(tpi_mp);
4890 		return (err);
4891 	}
4892 
4893 	/*
4894 	 * Let's make sure that eager tcp template has enough space to
4895 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4896 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4897 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4898 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4899 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4900 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4901 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4902 	 */
4903 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4904 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4905 
4906 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4907 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4908 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4909 	tcp->tcp_ttl = ltcp->tcp_ttl;
4910 	tcp->tcp_tos = ltcp->tcp_tos;
4911 
4912 	/* Copy the IP+TCP header template from listener to eager */
4913 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4914 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4915 	tcp->tcp_ip6h = NULL;
4916 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4917 	    tcp->tcp_ip_hdr_len);
4918 
4919 	/* Initialize the IP addresses and Ports */
4920 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4921 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4922 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4923 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4924 
4925 	/* Source routing option copyover (reverse it) */
4926 	if (tcps->tcps_rev_src_routes)
4927 		tcp_opt_reverse(tcp, ipha);
4928 
4929 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4930 	ASSERT(!tcp->tcp_tconnind_started);
4931 
4932 	/*
4933 	 * If the SYN contains a credential, it's a loopback packet; attach
4934 	 * the credential to the TPI message.
4935 	 */
4936 	if ((cr = DB_CRED(idmp)) != NULL) {
4937 		mblk_setcred(tpi_mp, cr);
4938 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4939 	}
4940 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4941 
4942 	/* Inherit the listener's SSL protection state */
4943 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4944 		kssl_hold_ent(tcp->tcp_kssl_ent);
4945 		tcp->tcp_kssl_pending = B_TRUE;
4946 	}
4947 
4948 	/* Inherit the listener's non-STREAMS flag */
4949 	if (IPCL_IS_NONSTR(lconnp)) {
4950 		connp->conn_flags |= IPCL_NONSTR;
4951 		connp->conn_upcalls = lconnp->conn_upcalls;
4952 	}
4953 
4954 	return (0);
4955 }
4956 
4957 /*
4958  * sets up conn for ipsec.
4959  * if the first mblk is M_CTL it is consumed and mpp is updated.
4960  * in case of error mpp is freed.
4961  */
4962 conn_t *
4963 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4964 {
4965 	conn_t 		*connp = tcp->tcp_connp;
4966 	conn_t 		*econnp;
4967 	squeue_t 	*new_sqp;
4968 	mblk_t 		*first_mp = *mpp;
4969 	mblk_t		*mp = *mpp;
4970 	boolean_t	mctl_present = B_FALSE;
4971 	uint_t		ipvers;
4972 
4973 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
4974 	if (econnp == NULL) {
4975 		freemsg(first_mp);
4976 		return (NULL);
4977 	}
4978 	if (DB_TYPE(mp) == M_CTL) {
4979 		if (mp->b_cont == NULL ||
4980 		    mp->b_cont->b_datap->db_type != M_DATA) {
4981 			freemsg(first_mp);
4982 			return (NULL);
4983 		}
4984 		mp = mp->b_cont;
4985 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4986 			freemsg(first_mp);
4987 			return (NULL);
4988 		}
4989 
4990 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4991 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4992 		mctl_present = B_TRUE;
4993 	} else {
4994 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4995 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4996 	}
4997 
4998 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4999 	DB_CKSUMSTART(mp) = 0;
5000 
5001 	ASSERT(OK_32PTR(mp->b_rptr));
5002 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5003 	if (ipvers == IPV4_VERSION) {
5004 		uint16_t  	*up;
5005 		uint32_t	ports;
5006 		ipha_t		*ipha;
5007 
5008 		ipha = (ipha_t *)mp->b_rptr;
5009 		up = (uint16_t *)((uchar_t *)ipha +
5010 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5011 		ports = *(uint32_t *)up;
5012 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5013 		    ipha->ipha_dst, ipha->ipha_src, ports);
5014 	} else {
5015 		uint16_t  	*up;
5016 		uint32_t	ports;
5017 		uint16_t	ip_hdr_len;
5018 		uint8_t		*nexthdrp;
5019 		ip6_t 		*ip6h;
5020 		tcph_t		*tcph;
5021 
5022 		ip6h = (ip6_t *)mp->b_rptr;
5023 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5024 			ip_hdr_len = IPV6_HDR_LEN;
5025 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5026 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5027 			CONN_DEC_REF(econnp);
5028 			freemsg(first_mp);
5029 			return (NULL);
5030 		}
5031 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5032 		up = (uint16_t *)tcph->th_lport;
5033 		ports = *(uint32_t *)up;
5034 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5035 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5036 	}
5037 
5038 	/*
5039 	 * The caller already ensured that there is a sqp present.
5040 	 */
5041 	econnp->conn_sqp = new_sqp;
5042 	econnp->conn_initial_sqp = new_sqp;
5043 
5044 	if (connp->conn_policy != NULL) {
5045 		ipsec_in_t *ii;
5046 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5047 		ASSERT(ii->ipsec_in_policy == NULL);
5048 		IPPH_REFHOLD(connp->conn_policy);
5049 		ii->ipsec_in_policy = connp->conn_policy;
5050 
5051 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5052 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5053 			CONN_DEC_REF(econnp);
5054 			freemsg(first_mp);
5055 			return (NULL);
5056 		}
5057 	}
5058 
5059 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5060 		CONN_DEC_REF(econnp);
5061 		freemsg(first_mp);
5062 		return (NULL);
5063 	}
5064 
5065 	/*
5066 	 * If we know we have some policy, pass the "IPSEC"
5067 	 * options size TCP uses this adjust the MSS.
5068 	 */
5069 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5070 	if (mctl_present) {
5071 		freeb(first_mp);
5072 		*mpp = mp;
5073 	}
5074 
5075 	return (econnp);
5076 }
5077 
5078 /*
5079  * tcp_get_conn/tcp_free_conn
5080  *
5081  * tcp_get_conn is used to get a clean tcp connection structure.
5082  * It tries to reuse the connections put on the freelist by the
5083  * time_wait_collector failing which it goes to kmem_cache. This
5084  * way has two benefits compared to just allocating from and
5085  * freeing to kmem_cache.
5086  * 1) The time_wait_collector can free (which includes the cleanup)
5087  * outside the squeue. So when the interrupt comes, we have a clean
5088  * connection sitting in the freelist. Obviously, this buys us
5089  * performance.
5090  *
5091  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5092  * has multiple disadvantages - tying up the squeue during alloc, and the
5093  * fact that IPSec policy initialization has to happen here which
5094  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5095  * But allocating the conn/tcp in IP land is also not the best since
5096  * we can't check the 'q' and 'q0' which are protected by squeue and
5097  * blindly allocate memory which might have to be freed here if we are
5098  * not allowed to accept the connection. By using the freelist and
5099  * putting the conn/tcp back in freelist, we don't pay a penalty for
5100  * allocating memory without checking 'q/q0' and freeing it if we can't
5101  * accept the connection.
5102  *
5103  * Care should be taken to put the conn back in the same squeue's freelist
5104  * from which it was allocated. Best results are obtained if conn is
5105  * allocated from listener's squeue and freed to the same. Time wait
5106  * collector will free up the freelist is the connection ends up sitting
5107  * there for too long.
5108  */
5109 void *
5110 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5111 {
5112 	tcp_t			*tcp = NULL;
5113 	conn_t			*connp = NULL;
5114 	squeue_t		*sqp = (squeue_t *)arg;
5115 	tcp_squeue_priv_t 	*tcp_time_wait;
5116 	netstack_t		*ns;
5117 
5118 	tcp_time_wait =
5119 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5120 
5121 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5122 	tcp = tcp_time_wait->tcp_free_list;
5123 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5124 	if (tcp != NULL) {
5125 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5126 		tcp_time_wait->tcp_free_list_cnt--;
5127 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5128 		tcp->tcp_time_wait_next = NULL;
5129 		connp = tcp->tcp_connp;
5130 		connp->conn_flags |= IPCL_REUSED;
5131 
5132 		ASSERT(tcp->tcp_tcps == NULL);
5133 		ASSERT(connp->conn_netstack == NULL);
5134 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5135 		ns = tcps->tcps_netstack;
5136 		netstack_hold(ns);
5137 		connp->conn_netstack = ns;
5138 		tcp->tcp_tcps = tcps;
5139 		TCPS_REFHOLD(tcps);
5140 		ipcl_globalhash_insert(connp);
5141 		return ((void *)connp);
5142 	}
5143 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5144 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5145 	    tcps->tcps_netstack)) == NULL)
5146 		return (NULL);
5147 	tcp = connp->conn_tcp;
5148 	/*
5149 	 * Pre-allocate the tcp_rsrv_mp.  This mblk will not be freed
5150 	 * until this conn_t/tcp_t is freed at ipcl_conn_destroy().
5151 	 */
5152 	if ((tcp->tcp_rsrv_mp = allocb(0, BPRI_HI)) == NULL) {
5153 		ipcl_conn_destroy(connp);
5154 		return (NULL);
5155 	}
5156 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5157 	tcp->tcp_tcps = tcps;
5158 	TCPS_REFHOLD(tcps);
5159 
5160 	return ((void *)connp);
5161 }
5162 
5163 /*
5164  * Update the cached label for the given tcp_t.  This should be called once per
5165  * connection, and before any packets are sent or tcp_process_options is
5166  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5167  */
5168 static boolean_t
5169 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5170 {
5171 	conn_t *connp = tcp->tcp_connp;
5172 
5173 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5174 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5175 		int added;
5176 
5177 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5178 		    connp->conn_mac_exempt,
5179 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5180 			return (B_FALSE);
5181 
5182 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5183 		if (added == -1)
5184 			return (B_FALSE);
5185 		tcp->tcp_hdr_len += added;
5186 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5187 		tcp->tcp_ip_hdr_len += added;
5188 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5189 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5190 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5191 			    tcp->tcp_hdr_len);
5192 			if (added == -1)
5193 				return (B_FALSE);
5194 			tcp->tcp_hdr_len += added;
5195 			tcp->tcp_tcph = (tcph_t *)
5196 			    ((uchar_t *)tcp->tcp_tcph + added);
5197 			tcp->tcp_ip_hdr_len += added;
5198 		}
5199 	} else {
5200 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5201 
5202 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5203 		    connp->conn_mac_exempt,
5204 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5205 			return (B_FALSE);
5206 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5207 		    &tcp->tcp_label_len, optbuf) != 0)
5208 			return (B_FALSE);
5209 		if (tcp_build_hdrs(tcp) != 0)
5210 			return (B_FALSE);
5211 	}
5212 
5213 	connp->conn_ulp_labeled = 1;
5214 
5215 	return (B_TRUE);
5216 }
5217 
5218 /* BEGIN CSTYLED */
5219 /*
5220  *
5221  * The sockfs ACCEPT path:
5222  * =======================
5223  *
5224  * The eager is now established in its own perimeter as soon as SYN is
5225  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5226  * completes the accept processing on the acceptor STREAM. The sending
5227  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5228  * listener but a TLI/XTI listener completes the accept processing
5229  * on the listener perimeter.
5230  *
5231  * Common control flow for 3 way handshake:
5232  * ----------------------------------------
5233  *
5234  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5235  *					-> tcp_conn_request()
5236  *
5237  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5238  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5239  *
5240  * Sockfs ACCEPT Path:
5241  * -------------------
5242  *
5243  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5244  * as STREAM entry point)
5245  *
5246  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5247  *
5248  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5249  * association (we are not behind eager's squeue but sockfs is protecting us
5250  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5251  * is changed to point at tcp_wput().
5252  *
5253  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5254  * listener (done on listener's perimeter).
5255  *
5256  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5257  * accept.
5258  *
5259  * TLI/XTI client ACCEPT path:
5260  * ---------------------------
5261  *
5262  * soaccept() sends T_CONN_RES on the listener STREAM.
5263  *
5264  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5265  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5266  *
5267  * Locks:
5268  * ======
5269  *
5270  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5271  * and listeners->tcp_eager_next_q.
5272  *
5273  * Referencing:
5274  * ============
5275  *
5276  * 1) We start out in tcp_conn_request by eager placing a ref on
5277  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5278  *
5279  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5280  * doing so we place a ref on the eager. This ref is finally dropped at the
5281  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5282  * reference is dropped by the squeue framework.
5283  *
5284  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5285  *
5286  * The reference must be released by the same entity that added the reference
5287  * In the above scheme, the eager is the entity that adds and releases the
5288  * references. Note that tcp_accept_finish executes in the squeue of the eager
5289  * (albeit after it is attached to the acceptor stream). Though 1. executes
5290  * in the listener's squeue, the eager is nascent at this point and the
5291  * reference can be considered to have been added on behalf of the eager.
5292  *
5293  * Eager getting a Reset or listener closing:
5294  * ==========================================
5295  *
5296  * Once the listener and eager are linked, the listener never does the unlink.
5297  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5298  * a message on all eager perimeter. The eager then does the unlink, clears
5299  * any pointers to the listener's queue and drops the reference to the
5300  * listener. The listener waits in tcp_close outside the squeue until its
5301  * refcount has dropped to 1. This ensures that the listener has waited for
5302  * all eagers to clear their association with the listener.
5303  *
5304  * Similarly, if eager decides to go away, it can unlink itself and close.
5305  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5306  * the reference to eager is still valid because of the extra ref we put
5307  * in tcp_send_conn_ind.
5308  *
5309  * Listener can always locate the eager under the protection
5310  * of the listener->tcp_eager_lock, and then do a refhold
5311  * on the eager during the accept processing.
5312  *
5313  * The acceptor stream accesses the eager in the accept processing
5314  * based on the ref placed on eager before sending T_conn_ind.
5315  * The only entity that can negate this refhold is a listener close
5316  * which is mutually exclusive with an active acceptor stream.
5317  *
5318  * Eager's reference on the listener
5319  * ===================================
5320  *
5321  * If the accept happens (even on a closed eager) the eager drops its
5322  * reference on the listener at the start of tcp_accept_finish. If the
5323  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5324  * the reference is dropped in tcp_closei_local. If the listener closes,
5325  * the reference is dropped in tcp_eager_kill. In all cases the reference
5326  * is dropped while executing in the eager's context (squeue).
5327  */
5328 /* END CSTYLED */
5329 
5330 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5331 
5332 /*
5333  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5334  * tcp_rput_data will not see any SYN packets.
5335  */
5336 /* ARGSUSED */
5337 void
5338 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5339 {
5340 	tcph_t		*tcph;
5341 	uint32_t	seg_seq;
5342 	tcp_t		*eager;
5343 	uint_t		ipvers;
5344 	ipha_t		*ipha;
5345 	ip6_t		*ip6h;
5346 	int		err;
5347 	conn_t		*econnp = NULL;
5348 	squeue_t	*new_sqp;
5349 	mblk_t		*mp1;
5350 	uint_t 		ip_hdr_len;
5351 	conn_t		*connp = (conn_t *)arg;
5352 	tcp_t		*tcp = connp->conn_tcp;
5353 	cred_t		*credp;
5354 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5355 	ip_stack_t	*ipst;
5356 
5357 	if (tcp->tcp_state != TCPS_LISTEN)
5358 		goto error2;
5359 
5360 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5361 
5362 	mutex_enter(&tcp->tcp_eager_lock);
5363 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5364 		mutex_exit(&tcp->tcp_eager_lock);
5365 		TCP_STAT(tcps, tcp_listendrop);
5366 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5367 		if (tcp->tcp_debug) {
5368 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5369 			    "tcp_conn_request: listen backlog (max=%d) "
5370 			    "overflow (%d pending) on %s",
5371 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5372 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5373 		}
5374 		goto error2;
5375 	}
5376 
5377 	if (tcp->tcp_conn_req_cnt_q0 >=
5378 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5379 		/*
5380 		 * Q0 is full. Drop a pending half-open req from the queue
5381 		 * to make room for the new SYN req. Also mark the time we
5382 		 * drop a SYN.
5383 		 *
5384 		 * A more aggressive defense against SYN attack will
5385 		 * be to set the "tcp_syn_defense" flag now.
5386 		 */
5387 		TCP_STAT(tcps, tcp_listendropq0);
5388 		tcp->tcp_last_rcv_lbolt = lbolt64;
5389 		if (!tcp_drop_q0(tcp)) {
5390 			mutex_exit(&tcp->tcp_eager_lock);
5391 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5392 			if (tcp->tcp_debug) {
5393 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5394 				    "tcp_conn_request: listen half-open queue "
5395 				    "(max=%d) full (%d pending) on %s",
5396 				    tcps->tcps_conn_req_max_q0,
5397 				    tcp->tcp_conn_req_cnt_q0,
5398 				    tcp_display(tcp, NULL,
5399 				    DISP_PORT_ONLY));
5400 			}
5401 			goto error2;
5402 		}
5403 	}
5404 	mutex_exit(&tcp->tcp_eager_lock);
5405 
5406 	/*
5407 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5408 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5409 	 * link local address.  If IPSec is enabled, db_struioflag has
5410 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5411 	 * otherwise an error case if neither of them is set.
5412 	 */
5413 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5414 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5415 		DB_CKSUMSTART(mp) = 0;
5416 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5417 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5418 		if (econnp == NULL)
5419 			goto error2;
5420 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5421 		econnp->conn_sqp = new_sqp;
5422 		econnp->conn_initial_sqp = new_sqp;
5423 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5424 		/*
5425 		 * mp is updated in tcp_get_ipsec_conn().
5426 		 */
5427 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5428 		if (econnp == NULL) {
5429 			/*
5430 			 * mp freed by tcp_get_ipsec_conn.
5431 			 */
5432 			return;
5433 		}
5434 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5435 	} else {
5436 		goto error2;
5437 	}
5438 
5439 	ASSERT(DB_TYPE(mp) == M_DATA);
5440 
5441 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5442 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5443 	ASSERT(OK_32PTR(mp->b_rptr));
5444 	if (ipvers == IPV4_VERSION) {
5445 		ipha = (ipha_t *)mp->b_rptr;
5446 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5447 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5448 	} else {
5449 		ip6h = (ip6_t *)mp->b_rptr;
5450 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5451 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5452 	}
5453 
5454 	if (tcp->tcp_family == AF_INET) {
5455 		ASSERT(ipvers == IPV4_VERSION);
5456 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5457 	} else {
5458 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5459 	}
5460 
5461 	if (err)
5462 		goto error3;
5463 
5464 	eager = econnp->conn_tcp;
5465 
5466 	/*
5467 	 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that at close
5468 	 * time, we will always have that to send up.  Otherwise, we need to do
5469 	 * special handling in case the allocation fails at that time.
5470 	 */
5471 	ASSERT(eager->tcp_ordrel_mp == NULL);
5472 	if (!IPCL_IS_NONSTR(econnp) &&
5473 	    (eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5474 		goto error3;
5475 
5476 	/* Inherit various TCP parameters from the listener */
5477 	eager->tcp_naglim = tcp->tcp_naglim;
5478 	eager->tcp_first_timer_threshold =
5479 	    tcp->tcp_first_timer_threshold;
5480 	eager->tcp_second_timer_threshold =
5481 	    tcp->tcp_second_timer_threshold;
5482 
5483 	eager->tcp_first_ctimer_threshold =
5484 	    tcp->tcp_first_ctimer_threshold;
5485 	eager->tcp_second_ctimer_threshold =
5486 	    tcp->tcp_second_ctimer_threshold;
5487 
5488 	/*
5489 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5490 	 * If it does not, the eager's receive window will be set to the
5491 	 * listener's receive window later in this function.
5492 	 */
5493 	eager->tcp_rwnd = 0;
5494 
5495 	/*
5496 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5497 	 * calling tcp_process_options() where tcp_mss_set() is called
5498 	 * to set the initial cwnd.
5499 	 */
5500 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5501 
5502 	/*
5503 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5504 	 * zone id before the accept is completed in tcp_wput_accept().
5505 	 */
5506 	econnp->conn_zoneid = connp->conn_zoneid;
5507 	econnp->conn_allzones = connp->conn_allzones;
5508 
5509 	/* Copy nexthop information from listener to eager */
5510 	if (connp->conn_nexthop_set) {
5511 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5512 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5513 	}
5514 
5515 	/*
5516 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5517 	 * eager is accepted
5518 	 */
5519 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5520 	crhold(credp);
5521 
5522 	/*
5523 	 * If the caller has the process-wide flag set, then default to MAC
5524 	 * exempt mode.  This allows read-down to unlabeled hosts.
5525 	 */
5526 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5527 		econnp->conn_mac_exempt = B_TRUE;
5528 
5529 	if (is_system_labeled()) {
5530 		cred_t *cr;
5531 
5532 		if (connp->conn_mlp_type != mlptSingle) {
5533 			cr = econnp->conn_peercred = DB_CRED(mp);
5534 			if (cr != NULL)
5535 				crhold(cr);
5536 			else
5537 				cr = econnp->conn_cred;
5538 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5539 			    econnp, cred_t *, cr)
5540 		} else {
5541 			cr = econnp->conn_cred;
5542 			DTRACE_PROBE2(syn_accept, conn_t *,
5543 			    econnp, cred_t *, cr)
5544 		}
5545 
5546 		if (!tcp_update_label(eager, cr)) {
5547 			DTRACE_PROBE3(
5548 			    tx__ip__log__error__connrequest__tcp,
5549 			    char *, "eager connp(1) label on SYN mp(2) failed",
5550 			    conn_t *, econnp, mblk_t *, mp);
5551 			goto error3;
5552 		}
5553 	}
5554 
5555 	eager->tcp_hard_binding = B_TRUE;
5556 
5557 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5558 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5559 
5560 	CL_INET_CONNECT(connp, eager, B_FALSE, err);
5561 	if (err != 0) {
5562 		tcp_bind_hash_remove(eager);
5563 		goto error3;
5564 	}
5565 
5566 	/*
5567 	 * No need to check for multicast destination since ip will only pass
5568 	 * up multicasts to those that have expressed interest
5569 	 * TODO: what about rejecting broadcasts?
5570 	 * Also check that source is not a multicast or broadcast address.
5571 	 */
5572 	eager->tcp_state = TCPS_SYN_RCVD;
5573 
5574 
5575 	/*
5576 	 * There should be no ire in the mp as we are being called after
5577 	 * receiving the SYN.
5578 	 */
5579 	ASSERT(tcp_ire_mp(&mp) == NULL);
5580 
5581 	/*
5582 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5583 	 */
5584 
5585 	if (tcp_adapt_ire(eager, NULL) == 0) {
5586 		/* Undo the bind_hash_insert */
5587 		tcp_bind_hash_remove(eager);
5588 		goto error3;
5589 	}
5590 
5591 	/* Process all TCP options. */
5592 	tcp_process_options(eager, tcph);
5593 
5594 	/* Is the other end ECN capable? */
5595 	if (tcps->tcps_ecn_permitted >= 1 &&
5596 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5597 		eager->tcp_ecn_ok = B_TRUE;
5598 	}
5599 
5600 	/*
5601 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5602 	 * window size changed via SO_RCVBUF option.  First round up the
5603 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5604 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5605 	 * setting.
5606 	 *
5607 	 * Note if there is a rpipe metric associated with the remote host,
5608 	 * we should not inherit receive window size from listener.
5609 	 */
5610 	eager->tcp_rwnd = MSS_ROUNDUP(
5611 	    (eager->tcp_rwnd == 0 ? tcp->tcp_recv_hiwater:
5612 	    eager->tcp_rwnd), eager->tcp_mss);
5613 	if (eager->tcp_snd_ws_ok)
5614 		tcp_set_ws_value(eager);
5615 	/*
5616 	 * Note that this is the only place tcp_rwnd_set() is called for
5617 	 * accepting a connection.  We need to call it here instead of
5618 	 * after the 3-way handshake because we need to tell the other
5619 	 * side our rwnd in the SYN-ACK segment.
5620 	 */
5621 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5622 
5623 	/*
5624 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5625 	 * via soaccept()->soinheritoptions() which essentially applies
5626 	 * all the listener options to the new STREAM. The options that we
5627 	 * need to take care of are:
5628 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5629 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5630 	 * SO_SNDBUF, SO_RCVBUF.
5631 	 *
5632 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5633 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5634 	 *		tcp_maxpsz_set() gets called later from
5635 	 *		tcp_accept_finish(), the option takes effect.
5636 	 *
5637 	 */
5638 	/* Set the TCP options */
5639 	eager->tcp_recv_hiwater = tcp->tcp_recv_hiwater;
5640 	eager->tcp_recv_lowater = tcp->tcp_recv_lowater;
5641 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5642 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5643 	eager->tcp_oobinline = tcp->tcp_oobinline;
5644 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5645 	eager->tcp_broadcast = tcp->tcp_broadcast;
5646 	eager->tcp_useloopback = tcp->tcp_useloopback;
5647 	eager->tcp_dontroute = tcp->tcp_dontroute;
5648 	eager->tcp_debug = tcp->tcp_debug;
5649 	eager->tcp_linger = tcp->tcp_linger;
5650 	eager->tcp_lingertime = tcp->tcp_lingertime;
5651 	if (tcp->tcp_ka_enabled)
5652 		eager->tcp_ka_enabled = 1;
5653 
5654 	/* Set the IP options */
5655 	econnp->conn_broadcast = connp->conn_broadcast;
5656 	econnp->conn_loopback = connp->conn_loopback;
5657 	econnp->conn_dontroute = connp->conn_dontroute;
5658 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5659 
5660 	/* Put a ref on the listener for the eager. */
5661 	CONN_INC_REF(connp);
5662 	mutex_enter(&tcp->tcp_eager_lock);
5663 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5664 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5665 	tcp->tcp_eager_next_q0 = eager;
5666 	eager->tcp_eager_prev_q0 = tcp;
5667 
5668 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5669 	eager->tcp_listener = tcp;
5670 	eager->tcp_saved_listener = tcp;
5671 
5672 	/*
5673 	 * Tag this detached tcp vector for later retrieval
5674 	 * by our listener client in tcp_accept().
5675 	 */
5676 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5677 	tcp->tcp_conn_req_cnt_q0++;
5678 	if (++tcp->tcp_conn_req_seqnum == -1) {
5679 		/*
5680 		 * -1 is "special" and defined in TPI as something
5681 		 * that should never be used in T_CONN_IND
5682 		 */
5683 		++tcp->tcp_conn_req_seqnum;
5684 	}
5685 	mutex_exit(&tcp->tcp_eager_lock);
5686 
5687 	if (tcp->tcp_syn_defense) {
5688 		/* Don't drop the SYN that comes from a good IP source */
5689 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5690 		if (addr_cache != NULL && eager->tcp_remote ==
5691 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5692 			eager->tcp_dontdrop = B_TRUE;
5693 		}
5694 	}
5695 
5696 	/*
5697 	 * We need to insert the eager in its own perimeter but as soon
5698 	 * as we do that, we expose the eager to the classifier and
5699 	 * should not touch any field outside the eager's perimeter.
5700 	 * So do all the work necessary before inserting the eager
5701 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5702 	 * will succeed but undo everything if it fails.
5703 	 */
5704 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5705 	eager->tcp_irs = seg_seq;
5706 	eager->tcp_rack = seg_seq;
5707 	eager->tcp_rnxt = seg_seq + 1;
5708 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5709 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5710 	eager->tcp_state = TCPS_SYN_RCVD;
5711 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5712 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5713 	if (mp1 == NULL) {
5714 		/*
5715 		 * Increment the ref count as we are going to
5716 		 * enqueueing an mp in squeue
5717 		 */
5718 		CONN_INC_REF(econnp);
5719 		goto error;
5720 	}
5721 	DB_CPID(mp1) = tcp->tcp_cpid;
5722 	mblk_setcred(mp1, tcp->tcp_cred);
5723 	eager->tcp_cpid = tcp->tcp_cpid;
5724 	eager->tcp_open_time = lbolt64;
5725 
5726 	/*
5727 	 * We need to start the rto timer. In normal case, we start
5728 	 * the timer after sending the packet on the wire (or at
5729 	 * least believing that packet was sent by waiting for
5730 	 * CALL_IP_WPUT() to return). Since this is the first packet
5731 	 * being sent on the wire for the eager, our initial tcp_rto
5732 	 * is at least tcp_rexmit_interval_min which is a fairly
5733 	 * large value to allow the algorithm to adjust slowly to large
5734 	 * fluctuations of RTT during first few transmissions.
5735 	 *
5736 	 * Starting the timer first and then sending the packet in this
5737 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5738 	 * is of the order of several 100ms and starting the timer
5739 	 * first and then sending the packet will result in difference
5740 	 * of few micro seconds.
5741 	 *
5742 	 * Without this optimization, we are forced to hold the fanout
5743 	 * lock across the ipcl_bind_insert() and sending the packet
5744 	 * so that we don't race against an incoming packet (maybe RST)
5745 	 * for this eager.
5746 	 *
5747 	 * It is necessary to acquire an extra reference on the eager
5748 	 * at this point and hold it until after tcp_send_data() to
5749 	 * ensure against an eager close race.
5750 	 */
5751 
5752 	CONN_INC_REF(eager->tcp_connp);
5753 
5754 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5755 
5756 	/*
5757 	 * Insert the eager in its own perimeter now. We are ready to deal
5758 	 * with any packets on eager.
5759 	 */
5760 	if (eager->tcp_ipversion == IPV4_VERSION) {
5761 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5762 			goto error;
5763 		}
5764 	} else {
5765 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5766 			goto error;
5767 		}
5768 	}
5769 
5770 	/* mark conn as fully-bound */
5771 	econnp->conn_fully_bound = B_TRUE;
5772 
5773 	/* Send the SYN-ACK */
5774 	tcp_send_data(eager, eager->tcp_wq, mp1);
5775 	CONN_DEC_REF(eager->tcp_connp);
5776 	freemsg(mp);
5777 
5778 	return;
5779 error:
5780 	freemsg(mp1);
5781 	eager->tcp_closemp_used = B_TRUE;
5782 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5783 	mp1 = &eager->tcp_closemp;
5784 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5785 	    econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5786 
5787 	/*
5788 	 * If a connection already exists, send the mp to that connections so
5789 	 * that it can be appropriately dealt with.
5790 	 */
5791 	ipst = tcps->tcps_netstack->netstack_ip;
5792 
5793 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
5794 		if (!IPCL_IS_CONNECTED(econnp)) {
5795 			/*
5796 			 * Something bad happened. ipcl_conn_insert()
5797 			 * failed because a connection already existed
5798 			 * in connected hash but we can't find it
5799 			 * anymore (someone blew it away). Just
5800 			 * free this message and hopefully remote
5801 			 * will retransmit at which time the SYN can be
5802 			 * treated as a new connection or dealth with
5803 			 * a TH_RST if a connection already exists.
5804 			 */
5805 			CONN_DEC_REF(econnp);
5806 			freemsg(mp);
5807 		} else {
5808 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp,
5809 			    tcp_input, econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5810 		}
5811 	} else {
5812 		/* Nobody wants this packet */
5813 		freemsg(mp);
5814 	}
5815 	return;
5816 error3:
5817 	CONN_DEC_REF(econnp);
5818 error2:
5819 	freemsg(mp);
5820 }
5821 
5822 /*
5823  * In an ideal case of vertical partition in NUMA architecture, its
5824  * beneficial to have the listener and all the incoming connections
5825  * tied to the same squeue. The other constraint is that incoming
5826  * connections should be tied to the squeue attached to interrupted
5827  * CPU for obvious locality reason so this leaves the listener to
5828  * be tied to the same squeue. Our only problem is that when listener
5829  * is binding, the CPU that will get interrupted by the NIC whose
5830  * IP address the listener is binding to is not even known. So
5831  * the code below allows us to change that binding at the time the
5832  * CPU is interrupted by virtue of incoming connection's squeue.
5833  *
5834  * This is usefull only in case of a listener bound to a specific IP
5835  * address. For other kind of listeners, they get bound the
5836  * very first time and there is no attempt to rebind them.
5837  */
5838 void
5839 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5840 {
5841 	conn_t		*connp = (conn_t *)arg;
5842 	squeue_t	*sqp = (squeue_t *)arg2;
5843 	squeue_t	*new_sqp;
5844 	uint32_t	conn_flags;
5845 
5846 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5847 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5848 	} else {
5849 		goto done;
5850 	}
5851 
5852 	if (connp->conn_fanout == NULL)
5853 		goto done;
5854 
5855 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5856 		mutex_enter(&connp->conn_fanout->connf_lock);
5857 		mutex_enter(&connp->conn_lock);
5858 		/*
5859 		 * No one from read or write side can access us now
5860 		 * except for already queued packets on this squeue.
5861 		 * But since we haven't changed the squeue yet, they
5862 		 * can't execute. If they are processed after we have
5863 		 * changed the squeue, they are sent back to the
5864 		 * correct squeue down below.
5865 		 * But a listner close can race with processing of
5866 		 * incoming SYN. If incoming SYN processing changes
5867 		 * the squeue then the listener close which is waiting
5868 		 * to enter the squeue would operate on the wrong
5869 		 * squeue. Hence we don't change the squeue here unless
5870 		 * the refcount is exactly the minimum refcount. The
5871 		 * minimum refcount of 4 is counted as - 1 each for
5872 		 * TCP and IP, 1 for being in the classifier hash, and
5873 		 * 1 for the mblk being processed.
5874 		 */
5875 
5876 		if (connp->conn_ref != 4 ||
5877 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5878 			mutex_exit(&connp->conn_lock);
5879 			mutex_exit(&connp->conn_fanout->connf_lock);
5880 			goto done;
5881 		}
5882 		if (connp->conn_sqp != new_sqp) {
5883 			while (connp->conn_sqp != new_sqp)
5884 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5885 		}
5886 
5887 		do {
5888 			conn_flags = connp->conn_flags;
5889 			conn_flags |= IPCL_FULLY_BOUND;
5890 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5891 			    conn_flags);
5892 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5893 
5894 		mutex_exit(&connp->conn_fanout->connf_lock);
5895 		mutex_exit(&connp->conn_lock);
5896 	}
5897 
5898 done:
5899 	if (connp->conn_sqp != sqp) {
5900 		CONN_INC_REF(connp);
5901 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5902 		    SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5903 	} else {
5904 		tcp_conn_request(connp, mp, sqp);
5905 	}
5906 }
5907 
5908 /*
5909  * Successful connect request processing begins when our client passes
5910  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5911  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5912  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_tpi_connect() -> IP
5913  *   upstream <- tcp_rput()		<- IP
5914  * After various error checks are completed, tcp_tpi_connect() lays
5915  * the target address and port into the composite header template,
5916  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5917  * request followed by an IRE request, and passes the three mblk message
5918  * down to IP looking like this:
5919  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5920  * Processing continues in tcp_rput() when we receive the following message:
5921  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5922  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5923  * to fire off the connection request, and then passes the T_OK_ACK mblk
5924  * upstream that we filled in below.  There are, of course, numerous
5925  * error conditions along the way which truncate the processing described
5926  * above.
5927  */
5928 static void
5929 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5930 {
5931 	sin_t		*sin;
5932 	queue_t		*q = tcp->tcp_wq;
5933 	struct T_conn_req	*tcr;
5934 	struct sockaddr	*sa;
5935 	socklen_t	len;
5936 	int		error;
5937 
5938 	tcr = (struct T_conn_req *)mp->b_rptr;
5939 
5940 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5941 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5942 		tcp_err_ack(tcp, mp, TPROTO, 0);
5943 		return;
5944 	}
5945 
5946 	/*
5947 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5948 	 * will always have that to send up.  Otherwise, we need to do
5949 	 * special handling in case the allocation fails at that time.
5950 	 * If the end point is TPI, the tcp_t can be reused and the
5951 	 * tcp_ordrel_mp may be allocated already.
5952 	 */
5953 	if (tcp->tcp_ordrel_mp == NULL) {
5954 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5955 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5956 			return;
5957 		}
5958 	}
5959 
5960 	/*
5961 	 * Determine packet type based on type of address passed in
5962 	 * the request should contain an IPv4 or IPv6 address.
5963 	 * Make sure that address family matches the type of
5964 	 * family of the the address passed down
5965 	 */
5966 	switch (tcr->DEST_length) {
5967 	default:
5968 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5969 		return;
5970 
5971 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5972 		/*
5973 		 * XXX: The check for valid DEST_length was not there
5974 		 * in earlier releases and some buggy
5975 		 * TLI apps (e.g Sybase) got away with not feeding
5976 		 * in sin_zero part of address.
5977 		 * We allow that bug to keep those buggy apps humming.
5978 		 * Test suites require the check on DEST_length.
5979 		 * We construct a new mblk with valid DEST_length
5980 		 * free the original so the rest of the code does
5981 		 * not have to keep track of this special shorter
5982 		 * length address case.
5983 		 */
5984 		mblk_t *nmp;
5985 		struct T_conn_req *ntcr;
5986 		sin_t *nsin;
5987 
5988 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5989 		    tcr->OPT_length, BPRI_HI);
5990 		if (nmp == NULL) {
5991 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5992 			return;
5993 		}
5994 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5995 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5996 		ntcr->PRIM_type = T_CONN_REQ;
5997 		ntcr->DEST_length = sizeof (sin_t);
5998 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5999 
6000 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6001 		*nsin = sin_null;
6002 		/* Get pointer to shorter address to copy from original mp */
6003 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6004 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6005 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6006 			freemsg(nmp);
6007 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6008 			return;
6009 		}
6010 		nsin->sin_family = sin->sin_family;
6011 		nsin->sin_port = sin->sin_port;
6012 		nsin->sin_addr = sin->sin_addr;
6013 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6014 		nmp->b_wptr = (uchar_t *)&nsin[1];
6015 		if (tcr->OPT_length != 0) {
6016 			ntcr->OPT_length = tcr->OPT_length;
6017 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6018 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6019 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6020 			    tcr->OPT_length);
6021 			nmp->b_wptr += tcr->OPT_length;
6022 		}
6023 		freemsg(mp);	/* original mp freed */
6024 		mp = nmp;	/* re-initialize original variables */
6025 		tcr = ntcr;
6026 	}
6027 	/* FALLTHRU */
6028 
6029 	case sizeof (sin_t):
6030 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6031 		    sizeof (sin_t));
6032 		len = sizeof (sin_t);
6033 		break;
6034 
6035 	case sizeof (sin6_t):
6036 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6037 		    sizeof (sin6_t));
6038 		len = sizeof (sin6_t);
6039 		break;
6040 	}
6041 
6042 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
6043 	if (error != 0) {
6044 		tcp_err_ack(tcp, mp, TSYSERR, error);
6045 		return;
6046 	}
6047 
6048 	/*
6049 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6050 	 * should key on their sequence number and cut them loose.
6051 	 */
6052 
6053 	/*
6054 	 * If options passed in, feed it for verification and handling
6055 	 */
6056 	if (tcr->OPT_length != 0) {
6057 		mblk_t	*ok_mp;
6058 		mblk_t	*discon_mp;
6059 		mblk_t  *conn_opts_mp;
6060 		int t_error, sys_error, do_disconnect;
6061 
6062 		conn_opts_mp = NULL;
6063 
6064 		if (tcp_conprim_opt_process(tcp, mp,
6065 		    &do_disconnect, &t_error, &sys_error) < 0) {
6066 			if (do_disconnect) {
6067 				ASSERT(t_error == 0 && sys_error == 0);
6068 				discon_mp = mi_tpi_discon_ind(NULL,
6069 				    ECONNREFUSED, 0);
6070 				if (!discon_mp) {
6071 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6072 					    TSYSERR, ENOMEM);
6073 					return;
6074 				}
6075 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6076 				if (!ok_mp) {
6077 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6078 					    TSYSERR, ENOMEM);
6079 					return;
6080 				}
6081 				qreply(q, ok_mp);
6082 				qreply(q, discon_mp); /* no flush! */
6083 			} else {
6084 				ASSERT(t_error != 0);
6085 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6086 				    sys_error);
6087 			}
6088 			return;
6089 		}
6090 		/*
6091 		 * Success in setting options, the mp option buffer represented
6092 		 * by OPT_length/offset has been potentially modified and
6093 		 * contains results of option processing. We copy it in
6094 		 * another mp to save it for potentially influencing returning
6095 		 * it in T_CONN_CONN.
6096 		 */
6097 		if (tcr->OPT_length != 0) { /* there are resulting options */
6098 			conn_opts_mp = copyb(mp);
6099 			if (!conn_opts_mp) {
6100 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6101 				    TSYSERR, ENOMEM);
6102 				return;
6103 			}
6104 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6105 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6106 			/*
6107 			 * Note:
6108 			 * These resulting option negotiation can include any
6109 			 * end-to-end negotiation options but there no such
6110 			 * thing (yet?) in our TCP/IP.
6111 			 */
6112 		}
6113 	}
6114 
6115 	/* call the non-TPI version */
6116 	error = tcp_do_connect(tcp->tcp_connp, sa, len, DB_CRED(mp),
6117 	    DB_CPID(mp));
6118 	if (error < 0) {
6119 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
6120 	} else if (error > 0) {
6121 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
6122 	} else {
6123 		mp = mi_tpi_ok_ack_alloc(mp);
6124 	}
6125 
6126 	/*
6127 	 * Note: Code below is the "failure" case
6128 	 */
6129 	/* return error ack and blow away saved option results if any */
6130 connect_failed:
6131 	if (mp != NULL)
6132 		putnext(tcp->tcp_rq, mp);
6133 	else {
6134 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6135 		    TSYSERR, ENOMEM);
6136 	}
6137 }
6138 
6139 /*
6140  * Handle connect to IPv4 destinations, including connections for AF_INET6
6141  * sockets connecting to IPv4 mapped IPv6 destinations.
6142  */
6143 static int
6144 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
6145     uint_t srcid, cred_t *cr, pid_t pid)
6146 {
6147 	tcph_t	*tcph;
6148 	mblk_t	*mp;
6149 	ipaddr_t dstaddr = *dstaddrp;
6150 	int32_t	oldstate;
6151 	uint16_t lport;
6152 	int	error = 0;
6153 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6154 
6155 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6156 
6157 	/* Check for attempt to connect to INADDR_ANY */
6158 	if (dstaddr == INADDR_ANY)  {
6159 		/*
6160 		 * SunOS 4.x and 4.3 BSD allow an application
6161 		 * to connect a TCP socket to INADDR_ANY.
6162 		 * When they do this, the kernel picks the
6163 		 * address of one interface and uses it
6164 		 * instead.  The kernel usually ends up
6165 		 * picking the address of the loopback
6166 		 * interface.  This is an undocumented feature.
6167 		 * However, we provide the same thing here
6168 		 * in order to have source and binary
6169 		 * compatibility with SunOS 4.x.
6170 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6171 		 * generate the T_CONN_CON.
6172 		 */
6173 		dstaddr = htonl(INADDR_LOOPBACK);
6174 		*dstaddrp = dstaddr;
6175 	}
6176 
6177 	/* Handle __sin6_src_id if socket not bound to an IP address */
6178 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6179 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6180 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6181 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6182 		    tcp->tcp_ipha->ipha_src);
6183 	}
6184 
6185 	/*
6186 	 * Don't let an endpoint connect to itself.  Note that
6187 	 * the test here does not catch the case where the
6188 	 * source IP addr was left unspecified by the user. In
6189 	 * this case, the source addr is set in tcp_adapt_ire()
6190 	 * using the reply to the T_BIND message that we send
6191 	 * down to IP here and the check is repeated in tcp_rput_other.
6192 	 */
6193 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6194 	    dstport == tcp->tcp_lport) {
6195 		error = -TBADADDR;
6196 		goto failed;
6197 	}
6198 
6199 	tcp->tcp_ipha->ipha_dst = dstaddr;
6200 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6201 
6202 	/*
6203 	 * Massage a source route if any putting the first hop
6204 	 * in iph_dst. Compute a starting value for the checksum which
6205 	 * takes into account that the original iph_dst should be
6206 	 * included in the checksum but that ip will include the
6207 	 * first hop in the source route in the tcp checksum.
6208 	 */
6209 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6210 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6211 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6212 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6213 	if ((int)tcp->tcp_sum < 0)
6214 		tcp->tcp_sum--;
6215 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6216 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6217 	    (tcp->tcp_sum >> 16));
6218 	tcph = tcp->tcp_tcph;
6219 	*(uint16_t *)tcph->th_fport = dstport;
6220 	tcp->tcp_fport = dstport;
6221 
6222 	oldstate = tcp->tcp_state;
6223 	/*
6224 	 * At this point the remote destination address and remote port fields
6225 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6226 	 * have to see which state tcp was in so we can take apropriate action.
6227 	 */
6228 	if (oldstate == TCPS_IDLE) {
6229 		/*
6230 		 * We support a quick connect capability here, allowing
6231 		 * clients to transition directly from IDLE to SYN_SENT
6232 		 * tcp_bindi will pick an unused port, insert the connection
6233 		 * in the bind hash and transition to BOUND state.
6234 		 */
6235 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6236 		    tcp, B_TRUE);
6237 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6238 		    B_FALSE, B_FALSE);
6239 		if (lport == 0) {
6240 			error = -TNOADDR;
6241 			goto failed;
6242 		}
6243 	}
6244 	tcp->tcp_state = TCPS_SYN_SENT;
6245 
6246 	mp = allocb(sizeof (ire_t), BPRI_HI);
6247 	if (mp == NULL) {
6248 		tcp->tcp_state = oldstate;
6249 		error = ENOMEM;
6250 		goto failed;
6251 	}
6252 	mp->b_wptr += sizeof (ire_t);
6253 	mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6254 	tcp->tcp_hard_binding = 1;
6255 	if (cr == NULL) {
6256 		cr = tcp->tcp_cred;
6257 		pid = tcp->tcp_cpid;
6258 	}
6259 	mblk_setcred(mp, cr);
6260 	DB_CPID(mp) = pid;
6261 
6262 	/*
6263 	 * We need to make sure that the conn_recv is set to a non-null
6264 	 * value before we insert the conn_t into the classifier table.
6265 	 * This is to avoid a race with an incoming packet which does
6266 	 * an ipcl_classify().
6267 	 */
6268 	tcp->tcp_connp->conn_recv = tcp_input;
6269 
6270 	if (tcp->tcp_family == AF_INET) {
6271 		error = ip_proto_bind_connected_v4(tcp->tcp_connp, &mp,
6272 		    IPPROTO_TCP, &tcp->tcp_ipha->ipha_src, tcp->tcp_lport,
6273 		    tcp->tcp_remote, tcp->tcp_fport, B_TRUE, B_TRUE);
6274 	} else {
6275 		in6_addr_t v6src;
6276 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6277 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6278 		} else {
6279 			v6src = tcp->tcp_ip6h->ip6_src;
6280 		}
6281 		error = ip_proto_bind_connected_v6(tcp->tcp_connp, &mp,
6282 		    IPPROTO_TCP, &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6283 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE);
6284 	}
6285 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6286 	tcp->tcp_active_open = 1;
6287 
6288 	return (tcp_post_ip_bind(tcp, mp, error));
6289 failed:
6290 	/* return error ack and blow away saved option results if any */
6291 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6292 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6293 	return (error);
6294 }
6295 
6296 /*
6297  * Handle connect to IPv6 destinations.
6298  */
6299 static int
6300 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
6301     uint32_t flowinfo, uint_t srcid, uint32_t scope_id, cred_t *cr, pid_t pid)
6302 {
6303 	tcph_t	*tcph;
6304 	mblk_t	*mp;
6305 	ip6_rthdr_t *rth;
6306 	int32_t  oldstate;
6307 	uint16_t lport;
6308 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6309 	int	error = 0;
6310 	conn_t	*connp = tcp->tcp_connp;
6311 
6312 	ASSERT(tcp->tcp_family == AF_INET6);
6313 
6314 	/*
6315 	 * If we're here, it means that the destination address is a native
6316 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6317 	 * reason why it might not be IPv6 is if the socket was bound to an
6318 	 * IPv4-mapped IPv6 address.
6319 	 */
6320 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6321 		return (-TBADADDR);
6322 	}
6323 
6324 	/*
6325 	 * Interpret a zero destination to mean loopback.
6326 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6327 	 * generate the T_CONN_CON.
6328 	 */
6329 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6330 		*dstaddrp = ipv6_loopback;
6331 	}
6332 
6333 	/* Handle __sin6_src_id if socket not bound to an IP address */
6334 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6335 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6336 		    connp->conn_zoneid, tcps->tcps_netstack);
6337 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6338 	}
6339 
6340 	/*
6341 	 * Take care of the scope_id now and add ip6i_t
6342 	 * if ip6i_t is not already allocated through TCP
6343 	 * sticky options. At this point tcp_ip6h does not
6344 	 * have dst info, thus use dstaddrp.
6345 	 */
6346 	if (scope_id != 0 &&
6347 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6348 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6349 		ip6i_t  *ip6i;
6350 
6351 		ipp->ipp_ifindex = scope_id;
6352 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6353 
6354 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6355 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6356 			/* Already allocated */
6357 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6358 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6359 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6360 		} else {
6361 			int reterr;
6362 
6363 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6364 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6365 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6366 			reterr = tcp_build_hdrs(tcp);
6367 			if (reterr != 0)
6368 				goto failed;
6369 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6370 		}
6371 	}
6372 
6373 	/*
6374 	 * Don't let an endpoint connect to itself.  Note that
6375 	 * the test here does not catch the case where the
6376 	 * source IP addr was left unspecified by the user. In
6377 	 * this case, the source addr is set in tcp_adapt_ire()
6378 	 * using the reply to the T_BIND message that we send
6379 	 * down to IP here and the check is repeated in tcp_rput_other.
6380 	 */
6381 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6382 	    (dstport == tcp->tcp_lport)) {
6383 		error = -TBADADDR;
6384 		goto failed;
6385 	}
6386 
6387 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6388 	tcp->tcp_remote_v6 = *dstaddrp;
6389 	tcp->tcp_ip6h->ip6_vcf =
6390 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6391 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6392 
6393 	/*
6394 	 * Massage a routing header (if present) putting the first hop
6395 	 * in ip6_dst. Compute a starting value for the checksum which
6396 	 * takes into account that the original ip6_dst should be
6397 	 * included in the checksum but that ip will include the
6398 	 * first hop in the source route in the tcp checksum.
6399 	 */
6400 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6401 	if (rth != NULL) {
6402 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6403 		    tcps->tcps_netstack);
6404 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6405 		    (tcp->tcp_sum >> 16));
6406 	} else {
6407 		tcp->tcp_sum = 0;
6408 	}
6409 
6410 	tcph = tcp->tcp_tcph;
6411 	*(uint16_t *)tcph->th_fport = dstport;
6412 	tcp->tcp_fport = dstport;
6413 
6414 	oldstate = tcp->tcp_state;
6415 	/*
6416 	 * At this point the remote destination address and remote port fields
6417 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6418 	 * have to see which state tcp was in so we can take apropriate action.
6419 	 */
6420 	if (oldstate == TCPS_IDLE) {
6421 		/*
6422 		 * We support a quick connect capability here, allowing
6423 		 * clients to transition directly from IDLE to SYN_SENT
6424 		 * tcp_bindi will pick an unused port, insert the connection
6425 		 * in the bind hash and transition to BOUND state.
6426 		 */
6427 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6428 		    tcp, B_TRUE);
6429 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6430 		    B_FALSE, B_FALSE);
6431 		if (lport == 0) {
6432 			error = -TNOADDR;
6433 			goto failed;
6434 		}
6435 	}
6436 	tcp->tcp_state = TCPS_SYN_SENT;
6437 
6438 	mp = allocb(sizeof (ire_t), BPRI_HI);
6439 	if (mp != NULL) {
6440 		in6_addr_t v6src;
6441 
6442 		mp->b_wptr += sizeof (ire_t);
6443 		mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6444 		if (cr == NULL) {
6445 			cr = tcp->tcp_cred;
6446 			pid = tcp->tcp_cpid;
6447 		}
6448 		mblk_setcred(mp, cr);
6449 		DB_CPID(mp) = pid;
6450 		tcp->tcp_hard_binding = 1;
6451 
6452 		/*
6453 		 * We need to make sure that the conn_recv is set to a non-null
6454 		 * value before we insert the conn_t into the classifier table.
6455 		 * This is to avoid a race with an incoming packet which does
6456 		 * an ipcl_classify().
6457 		 */
6458 		tcp->tcp_connp->conn_recv = tcp_input;
6459 
6460 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6461 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6462 		} else {
6463 			v6src = tcp->tcp_ip6h->ip6_src;
6464 		}
6465 		error = ip_proto_bind_connected_v6(connp, &mp, IPPROTO_TCP,
6466 		    &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6467 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE);
6468 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6469 		tcp->tcp_active_open = 1;
6470 
6471 		return (tcp_post_ip_bind(tcp, mp, error));
6472 	}
6473 	/* Error case */
6474 	tcp->tcp_state = oldstate;
6475 	error = ENOMEM;
6476 
6477 failed:
6478 	/* return error ack and blow away saved option results if any */
6479 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6480 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6481 	return (error);
6482 }
6483 
6484 /*
6485  * We need a stream q for detached closing tcp connections
6486  * to use.  Our client hereby indicates that this q is the
6487  * one to use.
6488  */
6489 static void
6490 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6491 {
6492 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6493 	queue_t	*q = tcp->tcp_wq;
6494 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6495 
6496 #ifdef NS_DEBUG
6497 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6498 	    tcps->tcps_netstack->netstack_stackid);
6499 #endif
6500 	mp->b_datap->db_type = M_IOCACK;
6501 	iocp->ioc_count = 0;
6502 	mutex_enter(&tcps->tcps_g_q_lock);
6503 	if (tcps->tcps_g_q != NULL) {
6504 		mutex_exit(&tcps->tcps_g_q_lock);
6505 		iocp->ioc_error = EALREADY;
6506 	} else {
6507 		int error = 0;
6508 		conn_t *connp = tcp->tcp_connp;
6509 		ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
6510 
6511 		tcps->tcps_g_q = tcp->tcp_rq;
6512 		mutex_exit(&tcps->tcps_g_q_lock);
6513 		iocp->ioc_error = 0;
6514 		iocp->ioc_rval = 0;
6515 		/*
6516 		 * We are passing tcp_sticky_ipp as NULL
6517 		 * as it is not useful for tcp_default queue
6518 		 *
6519 		 * Set conn_recv just in case.
6520 		 */
6521 		tcp->tcp_connp->conn_recv = tcp_conn_request;
6522 
6523 		ASSERT(connp->conn_af_isv6);
6524 		connp->conn_ulp = IPPROTO_TCP;
6525 
6526 		if (ipst->ips_ipcl_proto_fanout_v6[IPPROTO_TCP].connf_head !=
6527 		    NULL || connp->conn_mac_exempt) {
6528 			error = -TBADADDR;
6529 		} else {
6530 			connp->conn_srcv6 = ipv6_all_zeros;
6531 			ipcl_proto_insert_v6(connp, IPPROTO_TCP);
6532 		}
6533 
6534 		(void) tcp_post_ip_bind(tcp, NULL, error);
6535 	}
6536 	qreply(q, mp);
6537 }
6538 
6539 static int
6540 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
6541 {
6542 	tcp_t	*ltcp = NULL;
6543 	conn_t	*connp;
6544 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6545 
6546 	/*
6547 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6548 	 * when the stream is in BOUND state. Do not send a reset,
6549 	 * since the destination IP address is not valid, and it can
6550 	 * be the initialized value of all zeros (broadcast address).
6551 	 *
6552 	 * XXX There won't be any pending bind request to IP.
6553 	 */
6554 	if (tcp->tcp_state <= TCPS_BOUND) {
6555 		if (tcp->tcp_debug) {
6556 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6557 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6558 		}
6559 		return (TOUTSTATE);
6560 	}
6561 
6562 
6563 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6564 
6565 		/*
6566 		 * According to TPI, for non-listeners, ignore seqnum
6567 		 * and disconnect.
6568 		 * Following interpretation of -1 seqnum is historical
6569 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6570 		 * a valid seqnum should not be -1).
6571 		 *
6572 		 *	-1 means disconnect everything
6573 		 *	regardless even on a listener.
6574 		 */
6575 
6576 		int old_state = tcp->tcp_state;
6577 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6578 
6579 		/*
6580 		 * The connection can't be on the tcp_time_wait_head list
6581 		 * since it is not detached.
6582 		 */
6583 		ASSERT(tcp->tcp_time_wait_next == NULL);
6584 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6585 		ASSERT(tcp->tcp_time_wait_expire == 0);
6586 		ltcp = NULL;
6587 		/*
6588 		 * If it used to be a listener, check to make sure no one else
6589 		 * has taken the port before switching back to LISTEN state.
6590 		 */
6591 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6592 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6593 			    tcp->tcp_ipha->ipha_src,
6594 			    tcp->tcp_connp->conn_zoneid, ipst);
6595 			if (connp != NULL)
6596 				ltcp = connp->conn_tcp;
6597 		} else {
6598 			/* Allow tcp_bound_if listeners? */
6599 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6600 			    &tcp->tcp_ip6h->ip6_src, 0,
6601 			    tcp->tcp_connp->conn_zoneid, ipst);
6602 			if (connp != NULL)
6603 				ltcp = connp->conn_tcp;
6604 		}
6605 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6606 			tcp->tcp_state = TCPS_LISTEN;
6607 		} else if (old_state > TCPS_BOUND) {
6608 			tcp->tcp_conn_req_max = 0;
6609 			tcp->tcp_state = TCPS_BOUND;
6610 		}
6611 		if (ltcp != NULL)
6612 			CONN_DEC_REF(ltcp->tcp_connp);
6613 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6614 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6615 		} else if (old_state == TCPS_ESTABLISHED ||
6616 		    old_state == TCPS_CLOSE_WAIT) {
6617 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6618 		}
6619 
6620 		if (tcp->tcp_fused)
6621 			tcp_unfuse(tcp);
6622 
6623 		mutex_enter(&tcp->tcp_eager_lock);
6624 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6625 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6626 			tcp_eager_cleanup(tcp, 0);
6627 		}
6628 		mutex_exit(&tcp->tcp_eager_lock);
6629 
6630 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6631 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6632 
6633 		tcp_reinit(tcp);
6634 
6635 		return (0);
6636 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6637 		return (TBADSEQ);
6638 	}
6639 	return (0);
6640 }
6641 
6642 /*
6643  * Our client hereby directs us to reject the connection request
6644  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6645  * of sending the appropriate RST, not an ICMP error.
6646  */
6647 static void
6648 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6649 {
6650 	t_scalar_t seqnum;
6651 	int	error;
6652 
6653 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6654 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6655 		tcp_err_ack(tcp, mp, TPROTO, 0);
6656 		return;
6657 	}
6658 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6659 	error = tcp_disconnect_common(tcp, seqnum);
6660 	if (error != 0)
6661 		tcp_err_ack(tcp, mp, error, 0);
6662 	else {
6663 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6664 			/* Send M_FLUSH according to TPI */
6665 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6666 		}
6667 		mp = mi_tpi_ok_ack_alloc(mp);
6668 		if (mp)
6669 			putnext(tcp->tcp_rq, mp);
6670 	}
6671 }
6672 
6673 /*
6674  * Diagnostic routine used to return a string associated with the tcp state.
6675  * Note that if the caller does not supply a buffer, it will use an internal
6676  * static string.  This means that if multiple threads call this function at
6677  * the same time, output can be corrupted...  Note also that this function
6678  * does not check the size of the supplied buffer.  The caller has to make
6679  * sure that it is big enough.
6680  */
6681 static char *
6682 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6683 {
6684 	char		buf1[30];
6685 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6686 	char		*buf;
6687 	char		*cp;
6688 	in6_addr_t	local, remote;
6689 	char		local_addrbuf[INET6_ADDRSTRLEN];
6690 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6691 
6692 	if (sup_buf != NULL)
6693 		buf = sup_buf;
6694 	else
6695 		buf = priv_buf;
6696 
6697 	if (tcp == NULL)
6698 		return ("NULL_TCP");
6699 	switch (tcp->tcp_state) {
6700 	case TCPS_CLOSED:
6701 		cp = "TCP_CLOSED";
6702 		break;
6703 	case TCPS_IDLE:
6704 		cp = "TCP_IDLE";
6705 		break;
6706 	case TCPS_BOUND:
6707 		cp = "TCP_BOUND";
6708 		break;
6709 	case TCPS_LISTEN:
6710 		cp = "TCP_LISTEN";
6711 		break;
6712 	case TCPS_SYN_SENT:
6713 		cp = "TCP_SYN_SENT";
6714 		break;
6715 	case TCPS_SYN_RCVD:
6716 		cp = "TCP_SYN_RCVD";
6717 		break;
6718 	case TCPS_ESTABLISHED:
6719 		cp = "TCP_ESTABLISHED";
6720 		break;
6721 	case TCPS_CLOSE_WAIT:
6722 		cp = "TCP_CLOSE_WAIT";
6723 		break;
6724 	case TCPS_FIN_WAIT_1:
6725 		cp = "TCP_FIN_WAIT_1";
6726 		break;
6727 	case TCPS_CLOSING:
6728 		cp = "TCP_CLOSING";
6729 		break;
6730 	case TCPS_LAST_ACK:
6731 		cp = "TCP_LAST_ACK";
6732 		break;
6733 	case TCPS_FIN_WAIT_2:
6734 		cp = "TCP_FIN_WAIT_2";
6735 		break;
6736 	case TCPS_TIME_WAIT:
6737 		cp = "TCP_TIME_WAIT";
6738 		break;
6739 	default:
6740 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6741 		cp = buf1;
6742 		break;
6743 	}
6744 	switch (format) {
6745 	case DISP_ADDR_AND_PORT:
6746 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6747 			/*
6748 			 * Note that we use the remote address in the tcp_b
6749 			 * structure.  This means that it will print out
6750 			 * the real destination address, not the next hop's
6751 			 * address if source routing is used.
6752 			 */
6753 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6754 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6755 
6756 		} else {
6757 			local = tcp->tcp_ip_src_v6;
6758 			remote = tcp->tcp_remote_v6;
6759 		}
6760 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6761 		    sizeof (local_addrbuf));
6762 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6763 		    sizeof (remote_addrbuf));
6764 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6765 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6766 		    ntohs(tcp->tcp_fport), cp);
6767 		break;
6768 	case DISP_PORT_ONLY:
6769 	default:
6770 		(void) mi_sprintf(buf, "[%u, %u] %s",
6771 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6772 		break;
6773 	}
6774 
6775 	return (buf);
6776 }
6777 
6778 /*
6779  * Called via squeue to get on to eager's perimeter. It sends a
6780  * TH_RST if eager is in the fanout table. The listener wants the
6781  * eager to disappear either by means of tcp_eager_blowoff() or
6782  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
6783  * called (via squeue) if the eager cannot be inserted in the
6784  * fanout table in tcp_conn_request().
6785  */
6786 /* ARGSUSED */
6787 void
6788 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6789 {
6790 	conn_t	*econnp = (conn_t *)arg;
6791 	tcp_t	*eager = econnp->conn_tcp;
6792 	tcp_t	*listener = eager->tcp_listener;
6793 	tcp_stack_t	*tcps = eager->tcp_tcps;
6794 
6795 	/*
6796 	 * We could be called because listener is closing. Since
6797 	 * the eager is using listener's queue's, its not safe.
6798 	 * Better use the default queue just to send the TH_RST
6799 	 * out.
6800 	 */
6801 	ASSERT(tcps->tcps_g_q != NULL);
6802 	eager->tcp_rq = tcps->tcps_g_q;
6803 	eager->tcp_wq = WR(tcps->tcps_g_q);
6804 
6805 	/*
6806 	 * An eager's conn_fanout will be NULL if it's a duplicate
6807 	 * for an existing 4-tuples in the conn fanout table.
6808 	 * We don't want to send an RST out in such case.
6809 	 */
6810 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
6811 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6812 		    eager, eager->tcp_snxt, 0, TH_RST);
6813 	}
6814 
6815 	/* We are here because listener wants this eager gone */
6816 	if (listener != NULL) {
6817 		mutex_enter(&listener->tcp_eager_lock);
6818 		tcp_eager_unlink(eager);
6819 		if (eager->tcp_tconnind_started) {
6820 			/*
6821 			 * The eager has sent a conn_ind up to the
6822 			 * listener but listener decides to close
6823 			 * instead. We need to drop the extra ref
6824 			 * placed on eager in tcp_rput_data() before
6825 			 * sending the conn_ind to listener.
6826 			 */
6827 			CONN_DEC_REF(econnp);
6828 		}
6829 		mutex_exit(&listener->tcp_eager_lock);
6830 		CONN_DEC_REF(listener->tcp_connp);
6831 	}
6832 
6833 	if (eager->tcp_state > TCPS_BOUND)
6834 		tcp_close_detached(eager);
6835 }
6836 
6837 /*
6838  * Reset any eager connection hanging off this listener marked
6839  * with 'seqnum' and then reclaim it's resources.
6840  */
6841 static boolean_t
6842 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6843 {
6844 	tcp_t	*eager;
6845 	mblk_t 	*mp;
6846 	tcp_stack_t	*tcps = listener->tcp_tcps;
6847 
6848 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
6849 	eager = listener;
6850 	mutex_enter(&listener->tcp_eager_lock);
6851 	do {
6852 		eager = eager->tcp_eager_next_q;
6853 		if (eager == NULL) {
6854 			mutex_exit(&listener->tcp_eager_lock);
6855 			return (B_FALSE);
6856 		}
6857 	} while (eager->tcp_conn_req_seqnum != seqnum);
6858 
6859 	if (eager->tcp_closemp_used) {
6860 		mutex_exit(&listener->tcp_eager_lock);
6861 		return (B_TRUE);
6862 	}
6863 	eager->tcp_closemp_used = B_TRUE;
6864 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6865 	CONN_INC_REF(eager->tcp_connp);
6866 	mutex_exit(&listener->tcp_eager_lock);
6867 	mp = &eager->tcp_closemp;
6868 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6869 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
6870 	return (B_TRUE);
6871 }
6872 
6873 /*
6874  * Reset any eager connection hanging off this listener
6875  * and then reclaim it's resources.
6876  */
6877 static void
6878 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6879 {
6880 	tcp_t	*eager;
6881 	mblk_t	*mp;
6882 	tcp_stack_t	*tcps = listener->tcp_tcps;
6883 
6884 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6885 
6886 	if (!q0_only) {
6887 		/* First cleanup q */
6888 		TCP_STAT(tcps, tcp_eager_blowoff_q);
6889 		eager = listener->tcp_eager_next_q;
6890 		while (eager != NULL) {
6891 			if (!eager->tcp_closemp_used) {
6892 				eager->tcp_closemp_used = B_TRUE;
6893 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6894 				CONN_INC_REF(eager->tcp_connp);
6895 				mp = &eager->tcp_closemp;
6896 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6897 				    tcp_eager_kill, eager->tcp_connp,
6898 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
6899 			}
6900 			eager = eager->tcp_eager_next_q;
6901 		}
6902 	}
6903 	/* Then cleanup q0 */
6904 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6905 	eager = listener->tcp_eager_next_q0;
6906 	while (eager != listener) {
6907 		if (!eager->tcp_closemp_used) {
6908 			eager->tcp_closemp_used = B_TRUE;
6909 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6910 			CONN_INC_REF(eager->tcp_connp);
6911 			mp = &eager->tcp_closemp;
6912 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6913 			    tcp_eager_kill, eager->tcp_connp, SQ_FILL,
6914 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6915 		}
6916 		eager = eager->tcp_eager_next_q0;
6917 	}
6918 }
6919 
6920 /*
6921  * If we are an eager connection hanging off a listener that hasn't
6922  * formally accepted the connection yet, get off his list and blow off
6923  * any data that we have accumulated.
6924  */
6925 static void
6926 tcp_eager_unlink(tcp_t *tcp)
6927 {
6928 	tcp_t	*listener = tcp->tcp_listener;
6929 
6930 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6931 	ASSERT(listener != NULL);
6932 	if (tcp->tcp_eager_next_q0 != NULL) {
6933 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6934 
6935 		/* Remove the eager tcp from q0 */
6936 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6937 		    tcp->tcp_eager_prev_q0;
6938 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6939 		    tcp->tcp_eager_next_q0;
6940 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6941 		listener->tcp_conn_req_cnt_q0--;
6942 
6943 		tcp->tcp_eager_next_q0 = NULL;
6944 		tcp->tcp_eager_prev_q0 = NULL;
6945 
6946 		/*
6947 		 * Take the eager out, if it is in the list of droppable
6948 		 * eagers.
6949 		 */
6950 		MAKE_UNDROPPABLE(tcp);
6951 
6952 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6953 			/* we have timed out before */
6954 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6955 			listener->tcp_syn_rcvd_timeout--;
6956 		}
6957 	} else {
6958 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6959 		tcp_t	*prev = NULL;
6960 
6961 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6962 			if (tcpp[0] == tcp) {
6963 				if (listener->tcp_eager_last_q == tcp) {
6964 					/*
6965 					 * If we are unlinking the last
6966 					 * element on the list, adjust
6967 					 * tail pointer. Set tail pointer
6968 					 * to nil when list is empty.
6969 					 */
6970 					ASSERT(tcp->tcp_eager_next_q == NULL);
6971 					if (listener->tcp_eager_last_q ==
6972 					    listener->tcp_eager_next_q) {
6973 						listener->tcp_eager_last_q =
6974 						    NULL;
6975 					} else {
6976 						/*
6977 						 * We won't get here if there
6978 						 * is only one eager in the
6979 						 * list.
6980 						 */
6981 						ASSERT(prev != NULL);
6982 						listener->tcp_eager_last_q =
6983 						    prev;
6984 					}
6985 				}
6986 				tcpp[0] = tcp->tcp_eager_next_q;
6987 				tcp->tcp_eager_next_q = NULL;
6988 				tcp->tcp_eager_last_q = NULL;
6989 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6990 				listener->tcp_conn_req_cnt_q--;
6991 				break;
6992 			}
6993 			prev = tcpp[0];
6994 		}
6995 	}
6996 	tcp->tcp_listener = NULL;
6997 }
6998 
6999 /* Shorthand to generate and send TPI error acks to our client */
7000 static void
7001 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7002 {
7003 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7004 		putnext(tcp->tcp_rq, mp);
7005 }
7006 
7007 /* Shorthand to generate and send TPI error acks to our client */
7008 static void
7009 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7010     int t_error, int sys_error)
7011 {
7012 	struct T_error_ack	*teackp;
7013 
7014 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7015 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7016 		teackp = (struct T_error_ack *)mp->b_rptr;
7017 		teackp->ERROR_prim = primitive;
7018 		teackp->TLI_error = t_error;
7019 		teackp->UNIX_error = sys_error;
7020 		putnext(tcp->tcp_rq, mp);
7021 	}
7022 }
7023 
7024 /*
7025  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7026  * but instead the code relies on:
7027  * - the fact that the address of the array and its size never changes
7028  * - the atomic assignment of the elements of the array
7029  */
7030 /* ARGSUSED */
7031 static int
7032 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7033 {
7034 	int i;
7035 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7036 
7037 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7038 		if (tcps->tcps_g_epriv_ports[i] != 0)
7039 			(void) mi_mpprintf(mp, "%d ",
7040 			    tcps->tcps_g_epriv_ports[i]);
7041 	}
7042 	return (0);
7043 }
7044 
7045 /*
7046  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7047  * threads from changing it at the same time.
7048  */
7049 /* ARGSUSED */
7050 static int
7051 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7052     cred_t *cr)
7053 {
7054 	long	new_value;
7055 	int	i;
7056 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7057 
7058 	/*
7059 	 * Fail the request if the new value does not lie within the
7060 	 * port number limits.
7061 	 */
7062 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7063 	    new_value <= 0 || new_value >= 65536) {
7064 		return (EINVAL);
7065 	}
7066 
7067 	mutex_enter(&tcps->tcps_epriv_port_lock);
7068 	/* Check if the value is already in the list */
7069 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7070 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7071 			mutex_exit(&tcps->tcps_epriv_port_lock);
7072 			return (EEXIST);
7073 		}
7074 	}
7075 	/* Find an empty slot */
7076 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7077 		if (tcps->tcps_g_epriv_ports[i] == 0)
7078 			break;
7079 	}
7080 	if (i == tcps->tcps_g_num_epriv_ports) {
7081 		mutex_exit(&tcps->tcps_epriv_port_lock);
7082 		return (EOVERFLOW);
7083 	}
7084 	/* Set the new value */
7085 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7086 	mutex_exit(&tcps->tcps_epriv_port_lock);
7087 	return (0);
7088 }
7089 
7090 /*
7091  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7092  * threads from changing it at the same time.
7093  */
7094 /* ARGSUSED */
7095 static int
7096 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7097     cred_t *cr)
7098 {
7099 	long	new_value;
7100 	int	i;
7101 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7102 
7103 	/*
7104 	 * Fail the request if the new value does not lie within the
7105 	 * port number limits.
7106 	 */
7107 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7108 	    new_value >= 65536) {
7109 		return (EINVAL);
7110 	}
7111 
7112 	mutex_enter(&tcps->tcps_epriv_port_lock);
7113 	/* Check that the value is already in the list */
7114 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7115 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7116 			break;
7117 	}
7118 	if (i == tcps->tcps_g_num_epriv_ports) {
7119 		mutex_exit(&tcps->tcps_epriv_port_lock);
7120 		return (ESRCH);
7121 	}
7122 	/* Clear the value */
7123 	tcps->tcps_g_epriv_ports[i] = 0;
7124 	mutex_exit(&tcps->tcps_epriv_port_lock);
7125 	return (0);
7126 }
7127 
7128 /* Return the TPI/TLI equivalent of our current tcp_state */
7129 static int
7130 tcp_tpistate(tcp_t *tcp)
7131 {
7132 	switch (tcp->tcp_state) {
7133 	case TCPS_IDLE:
7134 		return (TS_UNBND);
7135 	case TCPS_LISTEN:
7136 		/*
7137 		 * Return whether there are outstanding T_CONN_IND waiting
7138 		 * for the matching T_CONN_RES. Therefore don't count q0.
7139 		 */
7140 		if (tcp->tcp_conn_req_cnt_q > 0)
7141 			return (TS_WRES_CIND);
7142 		else
7143 			return (TS_IDLE);
7144 	case TCPS_BOUND:
7145 		return (TS_IDLE);
7146 	case TCPS_SYN_SENT:
7147 		return (TS_WCON_CREQ);
7148 	case TCPS_SYN_RCVD:
7149 		/*
7150 		 * Note: assumption: this has to the active open SYN_RCVD.
7151 		 * The passive instance is detached in SYN_RCVD stage of
7152 		 * incoming connection processing so we cannot get request
7153 		 * for T_info_ack on it.
7154 		 */
7155 		return (TS_WACK_CRES);
7156 	case TCPS_ESTABLISHED:
7157 		return (TS_DATA_XFER);
7158 	case TCPS_CLOSE_WAIT:
7159 		return (TS_WREQ_ORDREL);
7160 	case TCPS_FIN_WAIT_1:
7161 		return (TS_WIND_ORDREL);
7162 	case TCPS_FIN_WAIT_2:
7163 		return (TS_WIND_ORDREL);
7164 
7165 	case TCPS_CLOSING:
7166 	case TCPS_LAST_ACK:
7167 	case TCPS_TIME_WAIT:
7168 	case TCPS_CLOSED:
7169 		/*
7170 		 * Following TS_WACK_DREQ7 is a rendition of "not
7171 		 * yet TS_IDLE" TPI state. There is no best match to any
7172 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7173 		 * choose a value chosen that will map to TLI/XTI level
7174 		 * state of TSTATECHNG (state is process of changing) which
7175 		 * captures what this dummy state represents.
7176 		 */
7177 		return (TS_WACK_DREQ7);
7178 	default:
7179 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7180 		    tcp->tcp_state, tcp_display(tcp, NULL,
7181 		    DISP_PORT_ONLY));
7182 		return (TS_UNBND);
7183 	}
7184 }
7185 
7186 static void
7187 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7188 {
7189 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7190 
7191 	if (tcp->tcp_family == AF_INET6)
7192 		*tia = tcp_g_t_info_ack_v6;
7193 	else
7194 		*tia = tcp_g_t_info_ack;
7195 	tia->CURRENT_state = tcp_tpistate(tcp);
7196 	tia->OPT_size = tcp_max_optsize;
7197 	if (tcp->tcp_mss == 0) {
7198 		/* Not yet set - tcp_open does not set mss */
7199 		if (tcp->tcp_ipversion == IPV4_VERSION)
7200 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7201 		else
7202 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7203 	} else {
7204 		tia->TIDU_size = tcp->tcp_mss;
7205 	}
7206 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7207 }
7208 
7209 static void
7210 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
7211     t_uscalar_t cap_bits1)
7212 {
7213 	tcap->CAP_bits1 = 0;
7214 
7215 	if (cap_bits1 & TC1_INFO) {
7216 		tcp_copy_info(&tcap->INFO_ack, tcp);
7217 		tcap->CAP_bits1 |= TC1_INFO;
7218 	}
7219 
7220 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7221 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7222 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7223 	}
7224 
7225 }
7226 
7227 /*
7228  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7229  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7230  * tcp_g_t_info_ack.  The current state of the stream is copied from
7231  * tcp_state.
7232  */
7233 static void
7234 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7235 {
7236 	t_uscalar_t		cap_bits1;
7237 	struct T_capability_ack	*tcap;
7238 
7239 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7240 		freemsg(mp);
7241 		return;
7242 	}
7243 
7244 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7245 
7246 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7247 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7248 	if (mp == NULL)
7249 		return;
7250 
7251 	tcap = (struct T_capability_ack *)mp->b_rptr;
7252 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
7253 
7254 	putnext(tcp->tcp_rq, mp);
7255 }
7256 
7257 /*
7258  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7259  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7260  * The current state of the stream is copied from tcp_state.
7261  */
7262 static void
7263 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7264 {
7265 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7266 	    T_INFO_ACK);
7267 	if (!mp) {
7268 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7269 		return;
7270 	}
7271 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7272 	putnext(tcp->tcp_rq, mp);
7273 }
7274 
7275 /* Respond to the TPI addr request */
7276 static void
7277 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7278 {
7279 	sin_t	*sin;
7280 	mblk_t	*ackmp;
7281 	struct T_addr_ack *taa;
7282 
7283 	/* Make it large enough for worst case */
7284 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7285 	    2 * sizeof (sin6_t), 1);
7286 	if (ackmp == NULL) {
7287 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7288 		return;
7289 	}
7290 
7291 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7292 		tcp_addr_req_ipv6(tcp, ackmp);
7293 		return;
7294 	}
7295 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7296 
7297 	bzero(taa, sizeof (struct T_addr_ack));
7298 	ackmp->b_wptr = (uchar_t *)&taa[1];
7299 
7300 	taa->PRIM_type = T_ADDR_ACK;
7301 	ackmp->b_datap->db_type = M_PCPROTO;
7302 
7303 	/*
7304 	 * Note: Following code assumes 32 bit alignment of basic
7305 	 * data structures like sin_t and struct T_addr_ack.
7306 	 */
7307 	if (tcp->tcp_state >= TCPS_BOUND) {
7308 		/*
7309 		 * Fill in local address
7310 		 */
7311 		taa->LOCADDR_length = sizeof (sin_t);
7312 		taa->LOCADDR_offset = sizeof (*taa);
7313 
7314 		sin = (sin_t *)&taa[1];
7315 
7316 		/* Fill zeroes and then intialize non-zero fields */
7317 		*sin = sin_null;
7318 
7319 		sin->sin_family = AF_INET;
7320 
7321 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7322 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7323 
7324 		ackmp->b_wptr = (uchar_t *)&sin[1];
7325 
7326 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7327 			/*
7328 			 * Fill in Remote address
7329 			 */
7330 			taa->REMADDR_length = sizeof (sin_t);
7331 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7332 			    taa->LOCADDR_length);
7333 
7334 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7335 			*sin = sin_null;
7336 			sin->sin_family = AF_INET;
7337 			sin->sin_addr.s_addr = tcp->tcp_remote;
7338 			sin->sin_port = tcp->tcp_fport;
7339 
7340 			ackmp->b_wptr = (uchar_t *)&sin[1];
7341 		}
7342 	}
7343 	putnext(tcp->tcp_rq, ackmp);
7344 }
7345 
7346 /* Assumes that tcp_addr_req gets enough space and alignment */
7347 static void
7348 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7349 {
7350 	sin6_t	*sin6;
7351 	struct T_addr_ack *taa;
7352 
7353 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7354 	ASSERT(OK_32PTR(ackmp->b_rptr));
7355 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7356 	    2 * sizeof (sin6_t));
7357 
7358 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7359 
7360 	bzero(taa, sizeof (struct T_addr_ack));
7361 	ackmp->b_wptr = (uchar_t *)&taa[1];
7362 
7363 	taa->PRIM_type = T_ADDR_ACK;
7364 	ackmp->b_datap->db_type = M_PCPROTO;
7365 
7366 	/*
7367 	 * Note: Following code assumes 32 bit alignment of basic
7368 	 * data structures like sin6_t and struct T_addr_ack.
7369 	 */
7370 	if (tcp->tcp_state >= TCPS_BOUND) {
7371 		/*
7372 		 * Fill in local address
7373 		 */
7374 		taa->LOCADDR_length = sizeof (sin6_t);
7375 		taa->LOCADDR_offset = sizeof (*taa);
7376 
7377 		sin6 = (sin6_t *)&taa[1];
7378 		*sin6 = sin6_null;
7379 
7380 		sin6->sin6_family = AF_INET6;
7381 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7382 		sin6->sin6_port = tcp->tcp_lport;
7383 
7384 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7385 
7386 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7387 			/*
7388 			 * Fill in Remote address
7389 			 */
7390 			taa->REMADDR_length = sizeof (sin6_t);
7391 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7392 			    taa->LOCADDR_length);
7393 
7394 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7395 			*sin6 = sin6_null;
7396 			sin6->sin6_family = AF_INET6;
7397 			sin6->sin6_flowinfo =
7398 			    tcp->tcp_ip6h->ip6_vcf &
7399 			    ~IPV6_VERS_AND_FLOW_MASK;
7400 			sin6->sin6_addr = tcp->tcp_remote_v6;
7401 			sin6->sin6_port = tcp->tcp_fport;
7402 
7403 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7404 		}
7405 	}
7406 	putnext(tcp->tcp_rq, ackmp);
7407 }
7408 
7409 /*
7410  * Handle reinitialization of a tcp structure.
7411  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7412  */
7413 static void
7414 tcp_reinit(tcp_t *tcp)
7415 {
7416 	mblk_t	*mp;
7417 	int 	err;
7418 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7419 
7420 	TCP_STAT(tcps, tcp_reinit_calls);
7421 
7422 	/* tcp_reinit should never be called for detached tcp_t's */
7423 	ASSERT(tcp->tcp_listener == NULL);
7424 	ASSERT((tcp->tcp_family == AF_INET &&
7425 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7426 	    (tcp->tcp_family == AF_INET6 &&
7427 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7428 	    tcp->tcp_ipversion == IPV6_VERSION)));
7429 
7430 	/* Cancel outstanding timers */
7431 	tcp_timers_stop(tcp);
7432 
7433 	/*
7434 	 * Reset everything in the state vector, after updating global
7435 	 * MIB data from instance counters.
7436 	 */
7437 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7438 	tcp->tcp_ibsegs = 0;
7439 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7440 	tcp->tcp_obsegs = 0;
7441 
7442 	tcp_close_mpp(&tcp->tcp_xmit_head);
7443 	if (tcp->tcp_snd_zcopy_aware)
7444 		tcp_zcopy_notify(tcp);
7445 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7446 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7447 	mutex_enter(&tcp->tcp_non_sq_lock);
7448 	if (tcp->tcp_flow_stopped &&
7449 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7450 		tcp_clrqfull(tcp);
7451 	}
7452 	mutex_exit(&tcp->tcp_non_sq_lock);
7453 	tcp_close_mpp(&tcp->tcp_reass_head);
7454 	tcp->tcp_reass_tail = NULL;
7455 	if (tcp->tcp_rcv_list != NULL) {
7456 		/* Free b_next chain */
7457 		tcp_close_mpp(&tcp->tcp_rcv_list);
7458 		tcp->tcp_rcv_last_head = NULL;
7459 		tcp->tcp_rcv_last_tail = NULL;
7460 		tcp->tcp_rcv_cnt = 0;
7461 	}
7462 	tcp->tcp_rcv_last_tail = NULL;
7463 
7464 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7465 		freemsg(mp);
7466 		tcp->tcp_urp_mp = NULL;
7467 	}
7468 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7469 		freemsg(mp);
7470 		tcp->tcp_urp_mark_mp = NULL;
7471 	}
7472 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7473 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7474 		freeb(tcp->tcp_fused_sigurg_mp);
7475 		tcp->tcp_fused_sigurg_mp = NULL;
7476 	}
7477 	if (tcp->tcp_ordrel_mp != NULL) {
7478 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7479 		freeb(tcp->tcp_ordrel_mp);
7480 		tcp->tcp_ordrel_mp = NULL;
7481 	}
7482 
7483 	/*
7484 	 * Following is a union with two members which are
7485 	 * identical types and size so the following cleanup
7486 	 * is enough.
7487 	 */
7488 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7489 
7490 	CL_INET_DISCONNECT(tcp->tcp_connp, tcp);
7491 
7492 	/*
7493 	 * The connection can't be on the tcp_time_wait_head list
7494 	 * since it is not detached.
7495 	 */
7496 	ASSERT(tcp->tcp_time_wait_next == NULL);
7497 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7498 	ASSERT(tcp->tcp_time_wait_expire == 0);
7499 
7500 	if (tcp->tcp_kssl_pending) {
7501 		tcp->tcp_kssl_pending = B_FALSE;
7502 
7503 		/* Don't reset if the initialized by bind. */
7504 		if (tcp->tcp_kssl_ent != NULL) {
7505 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7506 			    KSSL_NO_PROXY);
7507 		}
7508 	}
7509 	if (tcp->tcp_kssl_ctx != NULL) {
7510 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7511 		tcp->tcp_kssl_ctx = NULL;
7512 	}
7513 
7514 	/*
7515 	 * Reset/preserve other values
7516 	 */
7517 	tcp_reinit_values(tcp);
7518 	ipcl_hash_remove(tcp->tcp_connp);
7519 	conn_delete_ire(tcp->tcp_connp, NULL);
7520 	tcp_ipsec_cleanup(tcp);
7521 
7522 	if (tcp->tcp_conn_req_max != 0) {
7523 		/*
7524 		 * This is the case when a TLI program uses the same
7525 		 * transport end point to accept a connection.  This
7526 		 * makes the TCP both a listener and acceptor.  When
7527 		 * this connection is closed, we need to set the state
7528 		 * back to TCPS_LISTEN.  Make sure that the eager list
7529 		 * is reinitialized.
7530 		 *
7531 		 * Note that this stream is still bound to the four
7532 		 * tuples of the previous connection in IP.  If a new
7533 		 * SYN with different foreign address comes in, IP will
7534 		 * not find it and will send it to the global queue.  In
7535 		 * the global queue, TCP will do a tcp_lookup_listener()
7536 		 * to find this stream.  This works because this stream
7537 		 * is only removed from connected hash.
7538 		 *
7539 		 */
7540 		tcp->tcp_state = TCPS_LISTEN;
7541 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7542 		tcp->tcp_eager_next_drop_q0 = tcp;
7543 		tcp->tcp_eager_prev_drop_q0 = tcp;
7544 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7545 		if (tcp->tcp_family == AF_INET6) {
7546 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7547 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7548 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7549 		} else {
7550 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7551 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7552 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7553 		}
7554 	} else {
7555 		tcp->tcp_state = TCPS_BOUND;
7556 	}
7557 
7558 	/*
7559 	 * Initialize to default values
7560 	 * Can't fail since enough header template space already allocated
7561 	 * at open().
7562 	 */
7563 	err = tcp_init_values(tcp);
7564 	ASSERT(err == 0);
7565 	/* Restore state in tcp_tcph */
7566 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7567 	if (tcp->tcp_ipversion == IPV4_VERSION)
7568 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7569 	else
7570 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7571 	/*
7572 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7573 	 * since the lookup funcs can only lookup on tcp_t
7574 	 */
7575 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7576 
7577 	ASSERT(tcp->tcp_ptpbhn != NULL);
7578 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
7579 		tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7580 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
7581 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
7582 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7583 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7584 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7585 }
7586 
7587 /*
7588  * Force values to zero that need be zero.
7589  * Do not touch values asociated with the BOUND or LISTEN state
7590  * since the connection will end up in that state after the reinit.
7591  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7592  * structure!
7593  */
7594 static void
7595 tcp_reinit_values(tcp)
7596 	tcp_t *tcp;
7597 {
7598 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7599 
7600 #ifndef	lint
7601 #define	DONTCARE(x)
7602 #define	PRESERVE(x)
7603 #else
7604 #define	DONTCARE(x)	((x) = (x))
7605 #define	PRESERVE(x)	((x) = (x))
7606 #endif	/* lint */
7607 
7608 	PRESERVE(tcp->tcp_bind_hash_port);
7609 	PRESERVE(tcp->tcp_bind_hash);
7610 	PRESERVE(tcp->tcp_ptpbhn);
7611 	PRESERVE(tcp->tcp_acceptor_hash);
7612 	PRESERVE(tcp->tcp_ptpahn);
7613 
7614 	/* Should be ASSERT NULL on these with new code! */
7615 	ASSERT(tcp->tcp_time_wait_next == NULL);
7616 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7617 	ASSERT(tcp->tcp_time_wait_expire == 0);
7618 	PRESERVE(tcp->tcp_state);
7619 	PRESERVE(tcp->tcp_rq);
7620 	PRESERVE(tcp->tcp_wq);
7621 
7622 	ASSERT(tcp->tcp_xmit_head == NULL);
7623 	ASSERT(tcp->tcp_xmit_last == NULL);
7624 	ASSERT(tcp->tcp_unsent == 0);
7625 	ASSERT(tcp->tcp_xmit_tail == NULL);
7626 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7627 
7628 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7629 	tcp->tcp_suna = 0;			/* Displayed in mib */
7630 	tcp->tcp_swnd = 0;
7631 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7632 
7633 	ASSERT(tcp->tcp_ibsegs == 0);
7634 	ASSERT(tcp->tcp_obsegs == 0);
7635 
7636 	if (tcp->tcp_iphc != NULL) {
7637 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7638 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7639 	}
7640 
7641 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7642 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7643 	DONTCARE(tcp->tcp_ipha);
7644 	DONTCARE(tcp->tcp_ip6h);
7645 	DONTCARE(tcp->tcp_ip_hdr_len);
7646 	DONTCARE(tcp->tcp_tcph);
7647 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7648 	tcp->tcp_valid_bits = 0;
7649 
7650 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7651 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7652 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7653 	tcp->tcp_last_rcv_lbolt = 0;
7654 
7655 	tcp->tcp_init_cwnd = 0;
7656 
7657 	tcp->tcp_urp_last_valid = 0;
7658 	tcp->tcp_hard_binding = 0;
7659 	tcp->tcp_hard_bound = 0;
7660 	PRESERVE(tcp->tcp_cred);
7661 	PRESERVE(tcp->tcp_cpid);
7662 	PRESERVE(tcp->tcp_open_time);
7663 	PRESERVE(tcp->tcp_exclbind);
7664 
7665 	tcp->tcp_fin_acked = 0;
7666 	tcp->tcp_fin_rcvd = 0;
7667 	tcp->tcp_fin_sent = 0;
7668 	tcp->tcp_ordrel_done = 0;
7669 
7670 	tcp->tcp_debug = 0;
7671 	tcp->tcp_dontroute = 0;
7672 	tcp->tcp_broadcast = 0;
7673 
7674 	tcp->tcp_useloopback = 0;
7675 	tcp->tcp_reuseaddr = 0;
7676 	tcp->tcp_oobinline = 0;
7677 	tcp->tcp_dgram_errind = 0;
7678 
7679 	tcp->tcp_detached = 0;
7680 	tcp->tcp_bind_pending = 0;
7681 	tcp->tcp_unbind_pending = 0;
7682 
7683 	tcp->tcp_snd_ws_ok = B_FALSE;
7684 	tcp->tcp_snd_ts_ok = B_FALSE;
7685 	tcp->tcp_linger = 0;
7686 	tcp->tcp_ka_enabled = 0;
7687 	tcp->tcp_zero_win_probe = 0;
7688 
7689 	tcp->tcp_loopback = 0;
7690 	tcp->tcp_refuse = 0;
7691 	tcp->tcp_localnet = 0;
7692 	tcp->tcp_syn_defense = 0;
7693 	tcp->tcp_set_timer = 0;
7694 
7695 	tcp->tcp_active_open = 0;
7696 	tcp->tcp_rexmit = B_FALSE;
7697 	tcp->tcp_xmit_zc_clean = B_FALSE;
7698 
7699 	tcp->tcp_snd_sack_ok = B_FALSE;
7700 	PRESERVE(tcp->tcp_recvdstaddr);
7701 	tcp->tcp_hwcksum = B_FALSE;
7702 
7703 	tcp->tcp_ire_ill_check_done = B_FALSE;
7704 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7705 
7706 	tcp->tcp_mdt = B_FALSE;
7707 	tcp->tcp_mdt_hdr_head = 0;
7708 	tcp->tcp_mdt_hdr_tail = 0;
7709 
7710 	tcp->tcp_conn_def_q0 = 0;
7711 	tcp->tcp_ip_forward_progress = B_FALSE;
7712 	tcp->tcp_anon_priv_bind = 0;
7713 	tcp->tcp_ecn_ok = B_FALSE;
7714 
7715 	tcp->tcp_cwr = B_FALSE;
7716 	tcp->tcp_ecn_echo_on = B_FALSE;
7717 
7718 	if (tcp->tcp_sack_info != NULL) {
7719 		if (tcp->tcp_notsack_list != NULL) {
7720 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7721 		}
7722 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7723 		tcp->tcp_sack_info = NULL;
7724 	}
7725 
7726 	tcp->tcp_rcv_ws = 0;
7727 	tcp->tcp_snd_ws = 0;
7728 	tcp->tcp_ts_recent = 0;
7729 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7730 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7731 	tcp->tcp_if_mtu = 0;
7732 
7733 	ASSERT(tcp->tcp_reass_head == NULL);
7734 	ASSERT(tcp->tcp_reass_tail == NULL);
7735 
7736 	tcp->tcp_cwnd_cnt = 0;
7737 
7738 	ASSERT(tcp->tcp_rcv_list == NULL);
7739 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7740 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7741 	ASSERT(tcp->tcp_rcv_cnt == 0);
7742 
7743 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7744 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7745 	tcp->tcp_csuna = 0;
7746 
7747 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7748 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7749 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7750 	tcp->tcp_rtt_update = 0;
7751 
7752 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7753 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7754 
7755 	tcp->tcp_rack = 0;			/* Displayed in mib */
7756 	tcp->tcp_rack_cnt = 0;
7757 	tcp->tcp_rack_cur_max = 0;
7758 	tcp->tcp_rack_abs_max = 0;
7759 
7760 	tcp->tcp_max_swnd = 0;
7761 
7762 	ASSERT(tcp->tcp_listener == NULL);
7763 
7764 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7765 
7766 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7767 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7768 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7769 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7770 
7771 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7772 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7773 	PRESERVE(tcp->tcp_conn_req_max);
7774 	PRESERVE(tcp->tcp_conn_req_seqnum);
7775 
7776 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7777 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7778 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7779 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7780 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7781 
7782 	tcp->tcp_lingertime = 0;
7783 
7784 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7785 	ASSERT(tcp->tcp_urp_mp == NULL);
7786 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7787 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7788 
7789 	ASSERT(tcp->tcp_eager_next_q == NULL);
7790 	ASSERT(tcp->tcp_eager_last_q == NULL);
7791 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7792 	    tcp->tcp_eager_prev_q0 == NULL) ||
7793 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7794 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7795 
7796 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
7797 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
7798 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
7799 
7800 	tcp->tcp_client_errno = 0;
7801 
7802 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7803 
7804 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7805 
7806 	PRESERVE(tcp->tcp_bound_source_v6);
7807 	tcp->tcp_last_sent_len = 0;
7808 	tcp->tcp_dupack_cnt = 0;
7809 
7810 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7811 	PRESERVE(tcp->tcp_lport);
7812 
7813 	PRESERVE(tcp->tcp_acceptor_lockp);
7814 
7815 	ASSERT(tcp->tcp_ordrel_mp == NULL);
7816 	PRESERVE(tcp->tcp_acceptor_id);
7817 	DONTCARE(tcp->tcp_ipsec_overhead);
7818 
7819 	PRESERVE(tcp->tcp_family);
7820 	if (tcp->tcp_family == AF_INET6) {
7821 		tcp->tcp_ipversion = IPV6_VERSION;
7822 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7823 	} else {
7824 		tcp->tcp_ipversion = IPV4_VERSION;
7825 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7826 	}
7827 
7828 	tcp->tcp_bound_if = 0;
7829 	tcp->tcp_ipv6_recvancillary = 0;
7830 	tcp->tcp_recvifindex = 0;
7831 	tcp->tcp_recvhops = 0;
7832 	tcp->tcp_closed = 0;
7833 	tcp->tcp_cleandeathtag = 0;
7834 	if (tcp->tcp_hopopts != NULL) {
7835 		mi_free(tcp->tcp_hopopts);
7836 		tcp->tcp_hopopts = NULL;
7837 		tcp->tcp_hopoptslen = 0;
7838 	}
7839 	ASSERT(tcp->tcp_hopoptslen == 0);
7840 	if (tcp->tcp_dstopts != NULL) {
7841 		mi_free(tcp->tcp_dstopts);
7842 		tcp->tcp_dstopts = NULL;
7843 		tcp->tcp_dstoptslen = 0;
7844 	}
7845 	ASSERT(tcp->tcp_dstoptslen == 0);
7846 	if (tcp->tcp_rtdstopts != NULL) {
7847 		mi_free(tcp->tcp_rtdstopts);
7848 		tcp->tcp_rtdstopts = NULL;
7849 		tcp->tcp_rtdstoptslen = 0;
7850 	}
7851 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7852 	if (tcp->tcp_rthdr != NULL) {
7853 		mi_free(tcp->tcp_rthdr);
7854 		tcp->tcp_rthdr = NULL;
7855 		tcp->tcp_rthdrlen = 0;
7856 	}
7857 	ASSERT(tcp->tcp_rthdrlen == 0);
7858 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7859 
7860 	/* Reset fusion-related fields */
7861 	tcp->tcp_fused = B_FALSE;
7862 	tcp->tcp_unfusable = B_FALSE;
7863 	tcp->tcp_fused_sigurg = B_FALSE;
7864 	tcp->tcp_direct_sockfs = B_FALSE;
7865 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7866 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7867 	tcp->tcp_loopback_peer = NULL;
7868 	tcp->tcp_fuse_rcv_hiwater = 0;
7869 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7870 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7871 
7872 	tcp->tcp_lso = B_FALSE;
7873 
7874 	tcp->tcp_in_ack_unsent = 0;
7875 	tcp->tcp_cork = B_FALSE;
7876 	tcp->tcp_tconnind_started = B_FALSE;
7877 
7878 	PRESERVE(tcp->tcp_squeue_bytes);
7879 
7880 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7881 	ASSERT(!tcp->tcp_kssl_pending);
7882 	PRESERVE(tcp->tcp_kssl_ent);
7883 
7884 	/* Sodirect */
7885 	tcp->tcp_sodirect = NULL;
7886 
7887 	tcp->tcp_closemp_used = B_FALSE;
7888 
7889 	PRESERVE(tcp->tcp_rsrv_mp);
7890 	PRESERVE(tcp->tcp_rsrv_mp_lock);
7891 
7892 #ifdef DEBUG
7893 	DONTCARE(tcp->tcmp_stk[0]);
7894 #endif
7895 
7896 	PRESERVE(tcp->tcp_connid);
7897 
7898 
7899 #undef	DONTCARE
7900 #undef	PRESERVE
7901 }
7902 
7903 /*
7904  * Allocate necessary resources and initialize state vector.
7905  * Guaranteed not to fail so that when an error is returned,
7906  * the caller doesn't need to do any additional cleanup.
7907  */
7908 int
7909 tcp_init(tcp_t *tcp, queue_t *q)
7910 {
7911 	int	err;
7912 
7913 	tcp->tcp_rq = q;
7914 	tcp->tcp_wq = WR(q);
7915 	tcp->tcp_state = TCPS_IDLE;
7916 	if ((err = tcp_init_values(tcp)) != 0)
7917 		tcp_timers_stop(tcp);
7918 	return (err);
7919 }
7920 
7921 static int
7922 tcp_init_values(tcp_t *tcp)
7923 {
7924 	int	err;
7925 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7926 
7927 	ASSERT((tcp->tcp_family == AF_INET &&
7928 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7929 	    (tcp->tcp_family == AF_INET6 &&
7930 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7931 	    tcp->tcp_ipversion == IPV6_VERSION)));
7932 
7933 	/*
7934 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7935 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7936 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7937 	 * during first few transmissions of a connection as seen in slow
7938 	 * links.
7939 	 */
7940 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
7941 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
7942 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7943 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7944 	    tcps->tcps_conn_grace_period;
7945 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
7946 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
7947 	tcp->tcp_timer_backoff = 0;
7948 	tcp->tcp_ms_we_have_waited = 0;
7949 	tcp->tcp_last_recv_time = lbolt;
7950 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
7951 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7952 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7953 
7954 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
7955 
7956 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
7957 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
7958 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
7959 	/*
7960 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7961 	 * passive open.
7962 	 */
7963 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
7964 
7965 	tcp->tcp_naglim = tcps->tcps_naglim_def;
7966 
7967 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7968 
7969 	tcp->tcp_mdt_hdr_head = 0;
7970 	tcp->tcp_mdt_hdr_tail = 0;
7971 
7972 	/* Reset fusion-related fields */
7973 	tcp->tcp_fused = B_FALSE;
7974 	tcp->tcp_unfusable = B_FALSE;
7975 	tcp->tcp_fused_sigurg = B_FALSE;
7976 	tcp->tcp_direct_sockfs = B_FALSE;
7977 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7978 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7979 	tcp->tcp_loopback_peer = NULL;
7980 	tcp->tcp_fuse_rcv_hiwater = 0;
7981 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7982 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7983 
7984 	/* Sodirect */
7985 	tcp->tcp_sodirect = NULL;
7986 
7987 	/* Initialize the header template */
7988 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7989 		err = tcp_header_init_ipv4(tcp);
7990 	} else {
7991 		err = tcp_header_init_ipv6(tcp);
7992 	}
7993 	if (err)
7994 		return (err);
7995 
7996 	/*
7997 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7998 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7999 	 */
8000 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
8001 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
8002 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
8003 
8004 	tcp->tcp_cork = B_FALSE;
8005 	/*
8006 	 * Init the tcp_debug option.  This value determines whether TCP
8007 	 * calls strlog() to print out debug messages.  Doing this
8008 	 * initialization here means that this value is not inherited thru
8009 	 * tcp_reinit().
8010 	 */
8011 	tcp->tcp_debug = tcps->tcps_dbg;
8012 
8013 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8014 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8015 
8016 	return (0);
8017 }
8018 
8019 /*
8020  * Initialize the IPv4 header. Loses any record of any IP options.
8021  */
8022 static int
8023 tcp_header_init_ipv4(tcp_t *tcp)
8024 {
8025 	tcph_t		*tcph;
8026 	uint32_t	sum;
8027 	conn_t		*connp;
8028 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8029 
8030 	/*
8031 	 * This is a simple initialization. If there's
8032 	 * already a template, it should never be too small,
8033 	 * so reuse it.  Otherwise, allocate space for the new one.
8034 	 */
8035 	if (tcp->tcp_iphc == NULL) {
8036 		ASSERT(tcp->tcp_iphc_len == 0);
8037 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8038 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8039 		if (tcp->tcp_iphc == NULL) {
8040 			tcp->tcp_iphc_len = 0;
8041 			return (ENOMEM);
8042 		}
8043 	}
8044 
8045 	/* options are gone; may need a new label */
8046 	connp = tcp->tcp_connp;
8047 	connp->conn_mlp_type = mlptSingle;
8048 	connp->conn_ulp_labeled = !is_system_labeled();
8049 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8050 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8051 	tcp->tcp_ip6h = NULL;
8052 	tcp->tcp_ipversion = IPV4_VERSION;
8053 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8054 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8055 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8056 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8057 	tcp->tcp_ipha->ipha_version_and_hdr_length
8058 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8059 	tcp->tcp_ipha->ipha_ident = 0;
8060 
8061 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8062 	tcp->tcp_tos = 0;
8063 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8064 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8065 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8066 
8067 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8068 	tcp->tcp_tcph = tcph;
8069 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8070 	/*
8071 	 * IP wants our header length in the checksum field to
8072 	 * allow it to perform a single pseudo-header+checksum
8073 	 * calculation on behalf of TCP.
8074 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8075 	 */
8076 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8077 	sum = (sum >> 16) + (sum & 0xFFFF);
8078 	U16_TO_ABE16(sum, tcph->th_sum);
8079 	return (0);
8080 }
8081 
8082 /*
8083  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8084  */
8085 static int
8086 tcp_header_init_ipv6(tcp_t *tcp)
8087 {
8088 	tcph_t	*tcph;
8089 	uint32_t	sum;
8090 	conn_t	*connp;
8091 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8092 
8093 	/*
8094 	 * This is a simple initialization. If there's
8095 	 * already a template, it should never be too small,
8096 	 * so reuse it. Otherwise, allocate space for the new one.
8097 	 * Ensure that there is enough space to "downgrade" the tcp_t
8098 	 * to an IPv4 tcp_t. This requires having space for a full load
8099 	 * of IPv4 options, as well as a full load of TCP options
8100 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8101 	 * than a v6 header and a TCP header with a full load of TCP options
8102 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8103 	 * We want to avoid reallocation in the "downgraded" case when
8104 	 * processing outbound IPv4 options.
8105 	 */
8106 	if (tcp->tcp_iphc == NULL) {
8107 		ASSERT(tcp->tcp_iphc_len == 0);
8108 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8109 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8110 		if (tcp->tcp_iphc == NULL) {
8111 			tcp->tcp_iphc_len = 0;
8112 			return (ENOMEM);
8113 		}
8114 	}
8115 
8116 	/* options are gone; may need a new label */
8117 	connp = tcp->tcp_connp;
8118 	connp->conn_mlp_type = mlptSingle;
8119 	connp->conn_ulp_labeled = !is_system_labeled();
8120 
8121 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8122 	tcp->tcp_ipversion = IPV6_VERSION;
8123 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8124 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8125 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8126 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8127 	tcp->tcp_ipha = NULL;
8128 
8129 	/* Initialize the header template */
8130 
8131 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8132 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8133 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8134 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8135 
8136 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8137 	tcp->tcp_tcph = tcph;
8138 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8139 	/*
8140 	 * IP wants our header length in the checksum field to
8141 	 * allow it to perform a single psuedo-header+checksum
8142 	 * calculation on behalf of TCP.
8143 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8144 	 */
8145 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8146 	sum = (sum >> 16) + (sum & 0xFFFF);
8147 	U16_TO_ABE16(sum, tcph->th_sum);
8148 	return (0);
8149 }
8150 
8151 /* At minimum we need 8 bytes in the TCP header for the lookup */
8152 #define	ICMP_MIN_TCP_HDR	8
8153 
8154 /*
8155  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8156  * passed up by IP. The message is always received on the correct tcp_t.
8157  * Assumes that IP has pulled up everything up to and including the ICMP header.
8158  */
8159 void
8160 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8161 {
8162 	icmph_t *icmph;
8163 	ipha_t	*ipha;
8164 	int	iph_hdr_length;
8165 	tcph_t	*tcph;
8166 	boolean_t ipsec_mctl = B_FALSE;
8167 	boolean_t secure;
8168 	mblk_t *first_mp = mp;
8169 	int32_t new_mss;
8170 	uint32_t ratio;
8171 	size_t mp_size = MBLKL(mp);
8172 	uint32_t seg_seq;
8173 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8174 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8175 
8176 	/* Assume IP provides aligned packets - otherwise toss */
8177 	if (!OK_32PTR(mp->b_rptr)) {
8178 		freemsg(mp);
8179 		return;
8180 	}
8181 
8182 	/*
8183 	 * Since ICMP errors are normal data marked with M_CTL when sent
8184 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8185 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8186 	 */
8187 	if ((mp_size == sizeof (ipsec_info_t)) &&
8188 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8189 		ASSERT(mp->b_cont != NULL);
8190 		mp = mp->b_cont;
8191 		/* IP should have done this */
8192 		ASSERT(OK_32PTR(mp->b_rptr));
8193 		mp_size = MBLKL(mp);
8194 		ipsec_mctl = B_TRUE;
8195 	}
8196 
8197 	/*
8198 	 * Verify that we have a complete outer IP header. If not, drop it.
8199 	 */
8200 	if (mp_size < sizeof (ipha_t)) {
8201 noticmpv4:
8202 		freemsg(first_mp);
8203 		return;
8204 	}
8205 
8206 	ipha = (ipha_t *)mp->b_rptr;
8207 	/*
8208 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8209 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8210 	 */
8211 	switch (IPH_HDR_VERSION(ipha)) {
8212 	case IPV6_VERSION:
8213 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8214 		return;
8215 	case IPV4_VERSION:
8216 		break;
8217 	default:
8218 		goto noticmpv4;
8219 	}
8220 
8221 	/* Skip past the outer IP and ICMP headers */
8222 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8223 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8224 	/*
8225 	 * If we don't have the correct outer IP header length or if the ULP
8226 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8227 	 * send it upstream.
8228 	 */
8229 	if (iph_hdr_length < sizeof (ipha_t) ||
8230 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8231 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8232 		goto noticmpv4;
8233 	}
8234 	ipha = (ipha_t *)&icmph[1];
8235 
8236 	/* Skip past the inner IP and find the ULP header */
8237 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8238 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8239 	/*
8240 	 * If we don't have the correct inner IP header length or if the ULP
8241 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8242 	 * bytes of TCP header, drop it.
8243 	 */
8244 	if (iph_hdr_length < sizeof (ipha_t) ||
8245 	    ipha->ipha_protocol != IPPROTO_TCP ||
8246 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8247 		goto noticmpv4;
8248 	}
8249 
8250 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8251 		if (ipsec_mctl) {
8252 			secure = ipsec_in_is_secure(first_mp);
8253 		} else {
8254 			secure = B_FALSE;
8255 		}
8256 		if (secure) {
8257 			/*
8258 			 * If we are willing to accept this in clear
8259 			 * we don't have to verify policy.
8260 			 */
8261 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8262 				if (!tcp_check_policy(tcp, first_mp,
8263 				    ipha, NULL, secure, ipsec_mctl)) {
8264 					/*
8265 					 * tcp_check_policy called
8266 					 * ip_drop_packet() on failure.
8267 					 */
8268 					return;
8269 				}
8270 			}
8271 		}
8272 	} else if (ipsec_mctl) {
8273 		/*
8274 		 * This is a hard_bound connection. IP has already
8275 		 * verified policy. We don't have to do it again.
8276 		 */
8277 		freeb(first_mp);
8278 		first_mp = mp;
8279 		ipsec_mctl = B_FALSE;
8280 	}
8281 
8282 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8283 	/*
8284 	 * TCP SHOULD check that the TCP sequence number contained in
8285 	 * payload of the ICMP error message is within the range
8286 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8287 	 */
8288 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8289 		/*
8290 		 * The ICMP message is bogus, just drop it.  But if this is
8291 		 * an ICMP too big message, IP has already changed
8292 		 * the ire_max_frag to the bogus value.  We need to change
8293 		 * it back.
8294 		 */
8295 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8296 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8297 			conn_t *connp = tcp->tcp_connp;
8298 			ire_t *ire;
8299 			int flag;
8300 
8301 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8302 				flag = tcp->tcp_ipha->
8303 				    ipha_fragment_offset_and_flags;
8304 			} else {
8305 				flag = 0;
8306 			}
8307 			mutex_enter(&connp->conn_lock);
8308 			if ((ire = connp->conn_ire_cache) != NULL) {
8309 				mutex_enter(&ire->ire_lock);
8310 				mutex_exit(&connp->conn_lock);
8311 				ire->ire_max_frag = tcp->tcp_if_mtu;
8312 				ire->ire_frag_flag |= flag;
8313 				mutex_exit(&ire->ire_lock);
8314 			} else {
8315 				mutex_exit(&connp->conn_lock);
8316 			}
8317 		}
8318 		goto noticmpv4;
8319 	}
8320 
8321 	switch (icmph->icmph_type) {
8322 	case ICMP_DEST_UNREACHABLE:
8323 		switch (icmph->icmph_code) {
8324 		case ICMP_FRAGMENTATION_NEEDED:
8325 			/*
8326 			 * Reduce the MSS based on the new MTU.  This will
8327 			 * eliminate any fragmentation locally.
8328 			 * N.B.  There may well be some funny side-effects on
8329 			 * the local send policy and the remote receive policy.
8330 			 * Pending further research, we provide
8331 			 * tcp_ignore_path_mtu just in case this proves
8332 			 * disastrous somewhere.
8333 			 *
8334 			 * After updating the MSS, retransmit part of the
8335 			 * dropped segment using the new mss by calling
8336 			 * tcp_wput_data().  Need to adjust all those
8337 			 * params to make sure tcp_wput_data() work properly.
8338 			 */
8339 			if (tcps->tcps_ignore_path_mtu ||
8340 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8341 				break;
8342 
8343 			/*
8344 			 * Decrease the MSS by time stamp options
8345 			 * IP options and IPSEC options. tcp_hdr_len
8346 			 * includes time stamp option and IP option
8347 			 * length.  Note that new_mss may be negative
8348 			 * if tcp_ipsec_overhead is large and the
8349 			 * icmph_du_mtu is the minimum value, which is 68.
8350 			 */
8351 			new_mss = ntohs(icmph->icmph_du_mtu) -
8352 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8353 
8354 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8355 			    new_mss);
8356 
8357 			/*
8358 			 * Only update the MSS if the new one is
8359 			 * smaller than the previous one.  This is
8360 			 * to avoid problems when getting multiple
8361 			 * ICMP errors for the same MTU.
8362 			 */
8363 			if (new_mss >= tcp->tcp_mss)
8364 				break;
8365 
8366 			/*
8367 			 * Note that we are using the template header's DF
8368 			 * bit in the fast path sending.  So we need to compare
8369 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8370 			 * And stop doing IPv4 PMTUd if new_mss is less than
8371 			 * MAX(tcps_mss_min, ip_pmtu_min).
8372 			 */
8373 			if (new_mss < tcps->tcps_mss_min ||
8374 			    new_mss < ipst->ips_ip_pmtu_min) {
8375 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8376 				    0;
8377 			}
8378 
8379 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8380 			ASSERT(ratio >= 1);
8381 			tcp_mss_set(tcp, new_mss, B_TRUE);
8382 
8383 			/*
8384 			 * Make sure we have something to
8385 			 * send.
8386 			 */
8387 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8388 			    (tcp->tcp_xmit_head != NULL)) {
8389 				/*
8390 				 * Shrink tcp_cwnd in
8391 				 * proportion to the old MSS/new MSS.
8392 				 */
8393 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8394 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8395 				    (tcp->tcp_unsent == 0)) {
8396 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8397 				} else {
8398 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8399 				}
8400 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8401 				tcp->tcp_rexmit = B_TRUE;
8402 				tcp->tcp_dupack_cnt = 0;
8403 				tcp->tcp_snd_burst = TCP_CWND_SS;
8404 				tcp_ss_rexmit(tcp);
8405 			}
8406 			break;
8407 		case ICMP_PORT_UNREACHABLE:
8408 		case ICMP_PROTOCOL_UNREACHABLE:
8409 			switch (tcp->tcp_state) {
8410 			case TCPS_SYN_SENT:
8411 			case TCPS_SYN_RCVD:
8412 				/*
8413 				 * ICMP can snipe away incipient
8414 				 * TCP connections as long as
8415 				 * seq number is same as initial
8416 				 * send seq number.
8417 				 */
8418 				if (seg_seq == tcp->tcp_iss) {
8419 					(void) tcp_clean_death(tcp,
8420 					    ECONNREFUSED, 6);
8421 				}
8422 				break;
8423 			}
8424 			break;
8425 		case ICMP_HOST_UNREACHABLE:
8426 		case ICMP_NET_UNREACHABLE:
8427 			/* Record the error in case we finally time out. */
8428 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8429 				tcp->tcp_client_errno = EHOSTUNREACH;
8430 			else
8431 				tcp->tcp_client_errno = ENETUNREACH;
8432 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8433 				if (tcp->tcp_listener != NULL &&
8434 				    tcp->tcp_listener->tcp_syn_defense) {
8435 					/*
8436 					 * Ditch the half-open connection if we
8437 					 * suspect a SYN attack is under way.
8438 					 */
8439 					tcp_ip_ire_mark_advice(tcp);
8440 					(void) tcp_clean_death(tcp,
8441 					    tcp->tcp_client_errno, 7);
8442 				}
8443 			}
8444 			break;
8445 		default:
8446 			break;
8447 		}
8448 		break;
8449 	case ICMP_SOURCE_QUENCH: {
8450 		/*
8451 		 * use a global boolean to control
8452 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8453 		 * The default is false.
8454 		 */
8455 		if (tcp_icmp_source_quench) {
8456 			/*
8457 			 * Reduce the sending rate as if we got a
8458 			 * retransmit timeout
8459 			 */
8460 			uint32_t npkt;
8461 
8462 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8463 			    tcp->tcp_mss;
8464 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8465 			tcp->tcp_cwnd = tcp->tcp_mss;
8466 			tcp->tcp_cwnd_cnt = 0;
8467 		}
8468 		break;
8469 	}
8470 	}
8471 	freemsg(first_mp);
8472 }
8473 
8474 /*
8475  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8476  * error messages passed up by IP.
8477  * Assumes that IP has pulled up all the extension headers as well
8478  * as the ICMPv6 header.
8479  */
8480 static void
8481 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8482 {
8483 	icmp6_t *icmp6;
8484 	ip6_t	*ip6h;
8485 	uint16_t	iph_hdr_length;
8486 	tcpha_t	*tcpha;
8487 	uint8_t	*nexthdrp;
8488 	uint32_t new_mss;
8489 	uint32_t ratio;
8490 	boolean_t secure;
8491 	mblk_t *first_mp = mp;
8492 	size_t mp_size;
8493 	uint32_t seg_seq;
8494 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8495 
8496 	/*
8497 	 * The caller has determined if this is an IPSEC_IN packet and
8498 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8499 	 */
8500 	if (ipsec_mctl)
8501 		mp = mp->b_cont;
8502 
8503 	mp_size = MBLKL(mp);
8504 
8505 	/*
8506 	 * Verify that we have a complete IP header. If not, send it upstream.
8507 	 */
8508 	if (mp_size < sizeof (ip6_t)) {
8509 noticmpv6:
8510 		freemsg(first_mp);
8511 		return;
8512 	}
8513 
8514 	/*
8515 	 * Verify this is an ICMPV6 packet, else send it upstream.
8516 	 */
8517 	ip6h = (ip6_t *)mp->b_rptr;
8518 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8519 		iph_hdr_length = IPV6_HDR_LEN;
8520 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8521 	    &nexthdrp) ||
8522 	    *nexthdrp != IPPROTO_ICMPV6) {
8523 		goto noticmpv6;
8524 	}
8525 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8526 	ip6h = (ip6_t *)&icmp6[1];
8527 	/*
8528 	 * Verify if we have a complete ICMP and inner IP header.
8529 	 */
8530 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8531 		goto noticmpv6;
8532 
8533 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8534 		goto noticmpv6;
8535 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8536 	/*
8537 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8538 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8539 	 * packet.
8540 	 */
8541 	if ((*nexthdrp != IPPROTO_TCP) ||
8542 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8543 		goto noticmpv6;
8544 	}
8545 
8546 	/*
8547 	 * ICMP errors come on the right queue or come on
8548 	 * listener/global queue for detached connections and
8549 	 * get switched to the right queue. If it comes on the
8550 	 * right queue, policy check has already been done by IP
8551 	 * and thus free the first_mp without verifying the policy.
8552 	 * If it has come for a non-hard bound connection, we need
8553 	 * to verify policy as IP may not have done it.
8554 	 */
8555 	if (!tcp->tcp_hard_bound) {
8556 		if (ipsec_mctl) {
8557 			secure = ipsec_in_is_secure(first_mp);
8558 		} else {
8559 			secure = B_FALSE;
8560 		}
8561 		if (secure) {
8562 			/*
8563 			 * If we are willing to accept this in clear
8564 			 * we don't have to verify policy.
8565 			 */
8566 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8567 				if (!tcp_check_policy(tcp, first_mp,
8568 				    NULL, ip6h, secure, ipsec_mctl)) {
8569 					/*
8570 					 * tcp_check_policy called
8571 					 * ip_drop_packet() on failure.
8572 					 */
8573 					return;
8574 				}
8575 			}
8576 		}
8577 	} else if (ipsec_mctl) {
8578 		/*
8579 		 * This is a hard_bound connection. IP has already
8580 		 * verified policy. We don't have to do it again.
8581 		 */
8582 		freeb(first_mp);
8583 		first_mp = mp;
8584 		ipsec_mctl = B_FALSE;
8585 	}
8586 
8587 	seg_seq = ntohl(tcpha->tha_seq);
8588 	/*
8589 	 * TCP SHOULD check that the TCP sequence number contained in
8590 	 * payload of the ICMP error message is within the range
8591 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8592 	 */
8593 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8594 		/*
8595 		 * If the ICMP message is bogus, should we kill the
8596 		 * connection, or should we just drop the bogus ICMP
8597 		 * message? It would probably make more sense to just
8598 		 * drop the message so that if this one managed to get
8599 		 * in, the real connection should not suffer.
8600 		 */
8601 		goto noticmpv6;
8602 	}
8603 
8604 	switch (icmp6->icmp6_type) {
8605 	case ICMP6_PACKET_TOO_BIG:
8606 		/*
8607 		 * Reduce the MSS based on the new MTU.  This will
8608 		 * eliminate any fragmentation locally.
8609 		 * N.B.  There may well be some funny side-effects on
8610 		 * the local send policy and the remote receive policy.
8611 		 * Pending further research, we provide
8612 		 * tcp_ignore_path_mtu just in case this proves
8613 		 * disastrous somewhere.
8614 		 *
8615 		 * After updating the MSS, retransmit part of the
8616 		 * dropped segment using the new mss by calling
8617 		 * tcp_wput_data().  Need to adjust all those
8618 		 * params to make sure tcp_wput_data() work properly.
8619 		 */
8620 		if (tcps->tcps_ignore_path_mtu)
8621 			break;
8622 
8623 		/*
8624 		 * Decrease the MSS by time stamp options
8625 		 * IP options and IPSEC options. tcp_hdr_len
8626 		 * includes time stamp option and IP option
8627 		 * length.
8628 		 */
8629 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8630 		    tcp->tcp_ipsec_overhead;
8631 
8632 		/*
8633 		 * Only update the MSS if the new one is
8634 		 * smaller than the previous one.  This is
8635 		 * to avoid problems when getting multiple
8636 		 * ICMP errors for the same MTU.
8637 		 */
8638 		if (new_mss >= tcp->tcp_mss)
8639 			break;
8640 
8641 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8642 		ASSERT(ratio >= 1);
8643 		tcp_mss_set(tcp, new_mss, B_TRUE);
8644 
8645 		/*
8646 		 * Make sure we have something to
8647 		 * send.
8648 		 */
8649 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8650 		    (tcp->tcp_xmit_head != NULL)) {
8651 			/*
8652 			 * Shrink tcp_cwnd in
8653 			 * proportion to the old MSS/new MSS.
8654 			 */
8655 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8656 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8657 			    (tcp->tcp_unsent == 0)) {
8658 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8659 			} else {
8660 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8661 			}
8662 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8663 			tcp->tcp_rexmit = B_TRUE;
8664 			tcp->tcp_dupack_cnt = 0;
8665 			tcp->tcp_snd_burst = TCP_CWND_SS;
8666 			tcp_ss_rexmit(tcp);
8667 		}
8668 		break;
8669 
8670 	case ICMP6_DST_UNREACH:
8671 		switch (icmp6->icmp6_code) {
8672 		case ICMP6_DST_UNREACH_NOPORT:
8673 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8674 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8675 			    (seg_seq == tcp->tcp_iss)) {
8676 				(void) tcp_clean_death(tcp,
8677 				    ECONNREFUSED, 8);
8678 			}
8679 			break;
8680 
8681 		case ICMP6_DST_UNREACH_ADMIN:
8682 		case ICMP6_DST_UNREACH_NOROUTE:
8683 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8684 		case ICMP6_DST_UNREACH_ADDR:
8685 			/* Record the error in case we finally time out. */
8686 			tcp->tcp_client_errno = EHOSTUNREACH;
8687 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8688 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8689 			    (seg_seq == tcp->tcp_iss)) {
8690 				if (tcp->tcp_listener != NULL &&
8691 				    tcp->tcp_listener->tcp_syn_defense) {
8692 					/*
8693 					 * Ditch the half-open connection if we
8694 					 * suspect a SYN attack is under way.
8695 					 */
8696 					tcp_ip_ire_mark_advice(tcp);
8697 					(void) tcp_clean_death(tcp,
8698 					    tcp->tcp_client_errno, 9);
8699 				}
8700 			}
8701 
8702 
8703 			break;
8704 		default:
8705 			break;
8706 		}
8707 		break;
8708 
8709 	case ICMP6_PARAM_PROB:
8710 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8711 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8712 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8713 		    (uchar_t *)nexthdrp) {
8714 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8715 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8716 				(void) tcp_clean_death(tcp,
8717 				    ECONNREFUSED, 10);
8718 			}
8719 			break;
8720 		}
8721 		break;
8722 
8723 	case ICMP6_TIME_EXCEEDED:
8724 	default:
8725 		break;
8726 	}
8727 	freemsg(first_mp);
8728 }
8729 
8730 /*
8731  * Notify IP that we are having trouble with this connection.  IP should
8732  * blow the IRE away and start over.
8733  */
8734 static void
8735 tcp_ip_notify(tcp_t *tcp)
8736 {
8737 	struct iocblk	*iocp;
8738 	ipid_t	*ipid;
8739 	mblk_t	*mp;
8740 
8741 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8742 	if (tcp->tcp_ipversion == IPV6_VERSION)
8743 		return;
8744 
8745 	mp = mkiocb(IP_IOCTL);
8746 	if (mp == NULL)
8747 		return;
8748 
8749 	iocp = (struct iocblk *)mp->b_rptr;
8750 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8751 
8752 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8753 	if (!mp->b_cont) {
8754 		freeb(mp);
8755 		return;
8756 	}
8757 
8758 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8759 	mp->b_cont->b_wptr += iocp->ioc_count;
8760 	bzero(ipid, sizeof (*ipid));
8761 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8762 	ipid->ipid_ire_type = IRE_CACHE;
8763 	ipid->ipid_addr_offset = sizeof (ipid_t);
8764 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8765 	/*
8766 	 * Note: in the case of source routing we want to blow away the
8767 	 * route to the first source route hop.
8768 	 */
8769 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8770 	    sizeof (tcp->tcp_ipha->ipha_dst));
8771 
8772 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8773 }
8774 
8775 /* Unlink and return any mblk that looks like it contains an ire */
8776 static mblk_t *
8777 tcp_ire_mp(mblk_t **mpp)
8778 {
8779 	mblk_t 	*mp = *mpp;
8780 	mblk_t	*prev_mp = NULL;
8781 
8782 	for (;;) {
8783 		switch (DB_TYPE(mp)) {
8784 		case IRE_DB_TYPE:
8785 		case IRE_DB_REQ_TYPE:
8786 			if (mp == *mpp) {
8787 				*mpp = mp->b_cont;
8788 			} else {
8789 				prev_mp->b_cont = mp->b_cont;
8790 			}
8791 			mp->b_cont = NULL;
8792 			return (mp);
8793 		default:
8794 			break;
8795 		}
8796 		prev_mp = mp;
8797 		mp = mp->b_cont;
8798 		if (mp == NULL)
8799 			break;
8800 	}
8801 	return (mp);
8802 }
8803 
8804 /*
8805  * Timer callback routine for keepalive probe.  We do a fake resend of
8806  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8807  * check to see if we have heard anything from the other end for the last
8808  * RTO period.  If we have, set the timer to expire for another
8809  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8810  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8811  * the timeout if we have not heard from the other side.  If for more than
8812  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8813  * kill the connection unless the keepalive abort threshold is 0.  In
8814  * that case, we will probe "forever."
8815  */
8816 static void
8817 tcp_keepalive_killer(void *arg)
8818 {
8819 	mblk_t	*mp;
8820 	conn_t	*connp = (conn_t *)arg;
8821 	tcp_t  	*tcp = connp->conn_tcp;
8822 	int32_t	firetime;
8823 	int32_t	idletime;
8824 	int32_t	ka_intrvl;
8825 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8826 
8827 	tcp->tcp_ka_tid = 0;
8828 
8829 	if (tcp->tcp_fused)
8830 		return;
8831 
8832 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
8833 	ka_intrvl = tcp->tcp_ka_interval;
8834 
8835 	/*
8836 	 * Keepalive probe should only be sent if the application has not
8837 	 * done a close on the connection.
8838 	 */
8839 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8840 		return;
8841 	}
8842 	/* Timer fired too early, restart it. */
8843 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8844 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8845 		    MSEC_TO_TICK(ka_intrvl));
8846 		return;
8847 	}
8848 
8849 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8850 	/*
8851 	 * If we have not heard from the other side for a long
8852 	 * time, kill the connection unless the keepalive abort
8853 	 * threshold is 0.  In that case, we will probe "forever."
8854 	 */
8855 	if (tcp->tcp_ka_abort_thres != 0 &&
8856 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8857 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
8858 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8859 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8860 		return;
8861 	}
8862 
8863 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8864 	    idletime >= ka_intrvl) {
8865 		/* Fake resend of last ACKed byte. */
8866 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8867 
8868 		if (mp1 != NULL) {
8869 			*mp1->b_wptr++ = '\0';
8870 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8871 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8872 			freeb(mp1);
8873 			/*
8874 			 * if allocation failed, fall through to start the
8875 			 * timer back.
8876 			 */
8877 			if (mp != NULL) {
8878 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8879 				BUMP_MIB(&tcps->tcps_mib,
8880 				    tcpTimKeepaliveProbe);
8881 				if (tcp->tcp_ka_last_intrvl != 0) {
8882 					int max;
8883 					/*
8884 					 * We should probe again at least
8885 					 * in ka_intrvl, but not more than
8886 					 * tcp_rexmit_interval_max.
8887 					 */
8888 					max = tcps->tcps_rexmit_interval_max;
8889 					firetime = MIN(ka_intrvl - 1,
8890 					    tcp->tcp_ka_last_intrvl << 1);
8891 					if (firetime > max)
8892 						firetime = max;
8893 				} else {
8894 					firetime = tcp->tcp_rto;
8895 				}
8896 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8897 				    tcp_keepalive_killer,
8898 				    MSEC_TO_TICK(firetime));
8899 				tcp->tcp_ka_last_intrvl = firetime;
8900 				return;
8901 			}
8902 		}
8903 	} else {
8904 		tcp->tcp_ka_last_intrvl = 0;
8905 	}
8906 
8907 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8908 	if ((firetime = ka_intrvl - idletime) < 0) {
8909 		firetime = ka_intrvl;
8910 	}
8911 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8912 	    MSEC_TO_TICK(firetime));
8913 }
8914 
8915 int
8916 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8917 {
8918 	queue_t	*q = tcp->tcp_rq;
8919 	int32_t	mss = tcp->tcp_mss;
8920 	int	maxpsz;
8921 	conn_t	*connp = tcp->tcp_connp;
8922 
8923 	if (TCP_IS_DETACHED(tcp))
8924 		return (mss);
8925 	if (tcp->tcp_fused) {
8926 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8927 		mss = INFPSZ;
8928 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
8929 		/*
8930 		 * Set the sd_qn_maxpsz according to the socket send buffer
8931 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8932 		 * instruct the stream head to copyin user data into contiguous
8933 		 * kernel-allocated buffers without breaking it up into smaller
8934 		 * chunks.  We round up the buffer size to the nearest SMSS.
8935 		 */
8936 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8937 		if (tcp->tcp_kssl_ctx == NULL)
8938 			mss = INFPSZ;
8939 		else
8940 			mss = SSL3_MAX_RECORD_LEN;
8941 	} else {
8942 		/*
8943 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8944 		 * (and a multiple of the mss).  This instructs the stream
8945 		 * head to break down larger than SMSS writes into SMSS-
8946 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8947 		 */
8948 		/* XXX tune this with ndd tcp_maxpsz_multiplier */
8949 		maxpsz = tcp->tcp_maxpsz * mss;
8950 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8951 			maxpsz = tcp->tcp_xmit_hiwater/2;
8952 			/* Round up to nearest mss */
8953 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8954 		}
8955 	}
8956 
8957 	(void) proto_set_maxpsz(q, connp, maxpsz);
8958 	if (!(IPCL_IS_NONSTR(connp))) {
8959 		/* XXX do it in set_maxpsz()? */
8960 		tcp->tcp_wq->q_maxpsz = maxpsz;
8961 	}
8962 
8963 	if (set_maxblk)
8964 		(void) proto_set_tx_maxblk(q, connp, mss);
8965 	return (mss);
8966 }
8967 
8968 /*
8969  * Extract option values from a tcp header.  We put any found values into the
8970  * tcpopt struct and return a bitmask saying which options were found.
8971  */
8972 static int
8973 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8974 {
8975 	uchar_t		*endp;
8976 	int		len;
8977 	uint32_t	mss;
8978 	uchar_t		*up = (uchar_t *)tcph;
8979 	int		found = 0;
8980 	int32_t		sack_len;
8981 	tcp_seq		sack_begin, sack_end;
8982 	tcp_t		*tcp;
8983 
8984 	endp = up + TCP_HDR_LENGTH(tcph);
8985 	up += TCP_MIN_HEADER_LENGTH;
8986 	while (up < endp) {
8987 		len = endp - up;
8988 		switch (*up) {
8989 		case TCPOPT_EOL:
8990 			break;
8991 
8992 		case TCPOPT_NOP:
8993 			up++;
8994 			continue;
8995 
8996 		case TCPOPT_MAXSEG:
8997 			if (len < TCPOPT_MAXSEG_LEN ||
8998 			    up[1] != TCPOPT_MAXSEG_LEN)
8999 				break;
9000 
9001 			mss = BE16_TO_U16(up+2);
9002 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9003 			tcpopt->tcp_opt_mss = mss;
9004 			found |= TCP_OPT_MSS_PRESENT;
9005 
9006 			up += TCPOPT_MAXSEG_LEN;
9007 			continue;
9008 
9009 		case TCPOPT_WSCALE:
9010 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9011 				break;
9012 
9013 			if (up[2] > TCP_MAX_WINSHIFT)
9014 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9015 			else
9016 				tcpopt->tcp_opt_wscale = up[2];
9017 			found |= TCP_OPT_WSCALE_PRESENT;
9018 
9019 			up += TCPOPT_WS_LEN;
9020 			continue;
9021 
9022 		case TCPOPT_SACK_PERMITTED:
9023 			if (len < TCPOPT_SACK_OK_LEN ||
9024 			    up[1] != TCPOPT_SACK_OK_LEN)
9025 				break;
9026 			found |= TCP_OPT_SACK_OK_PRESENT;
9027 			up += TCPOPT_SACK_OK_LEN;
9028 			continue;
9029 
9030 		case TCPOPT_SACK:
9031 			if (len <= 2 || up[1] <= 2 || len < up[1])
9032 				break;
9033 
9034 			/* If TCP is not interested in SACK blks... */
9035 			if ((tcp = tcpopt->tcp) == NULL) {
9036 				up += up[1];
9037 				continue;
9038 			}
9039 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9040 			up += TCPOPT_HEADER_LEN;
9041 
9042 			/*
9043 			 * If the list is empty, allocate one and assume
9044 			 * nothing is sack'ed.
9045 			 */
9046 			ASSERT(tcp->tcp_sack_info != NULL);
9047 			if (tcp->tcp_notsack_list == NULL) {
9048 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9049 				    tcp->tcp_suna, tcp->tcp_snxt,
9050 				    &(tcp->tcp_num_notsack_blk),
9051 				    &(tcp->tcp_cnt_notsack_list));
9052 
9053 				/*
9054 				 * Make sure tcp_notsack_list is not NULL.
9055 				 * This happens when kmem_alloc(KM_NOSLEEP)
9056 				 * returns NULL.
9057 				 */
9058 				if (tcp->tcp_notsack_list == NULL) {
9059 					up += sack_len;
9060 					continue;
9061 				}
9062 				tcp->tcp_fack = tcp->tcp_suna;
9063 			}
9064 
9065 			while (sack_len > 0) {
9066 				if (up + 8 > endp) {
9067 					up = endp;
9068 					break;
9069 				}
9070 				sack_begin = BE32_TO_U32(up);
9071 				up += 4;
9072 				sack_end = BE32_TO_U32(up);
9073 				up += 4;
9074 				sack_len -= 8;
9075 				/*
9076 				 * Bounds checking.  Make sure the SACK
9077 				 * info is within tcp_suna and tcp_snxt.
9078 				 * If this SACK blk is out of bound, ignore
9079 				 * it but continue to parse the following
9080 				 * blks.
9081 				 */
9082 				if (SEQ_LEQ(sack_end, sack_begin) ||
9083 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9084 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9085 					continue;
9086 				}
9087 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9088 				    sack_begin, sack_end,
9089 				    &(tcp->tcp_num_notsack_blk),
9090 				    &(tcp->tcp_cnt_notsack_list));
9091 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9092 					tcp->tcp_fack = sack_end;
9093 				}
9094 			}
9095 			found |= TCP_OPT_SACK_PRESENT;
9096 			continue;
9097 
9098 		case TCPOPT_TSTAMP:
9099 			if (len < TCPOPT_TSTAMP_LEN ||
9100 			    up[1] != TCPOPT_TSTAMP_LEN)
9101 				break;
9102 
9103 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9104 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9105 
9106 			found |= TCP_OPT_TSTAMP_PRESENT;
9107 
9108 			up += TCPOPT_TSTAMP_LEN;
9109 			continue;
9110 
9111 		default:
9112 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9113 				break;
9114 			up += up[1];
9115 			continue;
9116 		}
9117 		break;
9118 	}
9119 	return (found);
9120 }
9121 
9122 /*
9123  * Set the mss associated with a particular tcp based on its current value,
9124  * and a new one passed in. Observe minimums and maximums, and reset
9125  * other state variables that we want to view as multiples of mss.
9126  *
9127  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9128  * highwater marks etc. need to be initialized or adjusted.
9129  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9130  *    packet arrives.
9131  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9132  *    ICMP6_PACKET_TOO_BIG arrives.
9133  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9134  *    to increase the MSS to use the extra bytes available.
9135  *
9136  * Callers except tcp_paws_check() ensure that they only reduce mss.
9137  */
9138 static void
9139 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9140 {
9141 	uint32_t	mss_max;
9142 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9143 
9144 	if (tcp->tcp_ipversion == IPV4_VERSION)
9145 		mss_max = tcps->tcps_mss_max_ipv4;
9146 	else
9147 		mss_max = tcps->tcps_mss_max_ipv6;
9148 
9149 	if (mss < tcps->tcps_mss_min)
9150 		mss = tcps->tcps_mss_min;
9151 	if (mss > mss_max)
9152 		mss = mss_max;
9153 	/*
9154 	 * Unless naglim has been set by our client to
9155 	 * a non-mss value, force naglim to track mss.
9156 	 * This can help to aggregate small writes.
9157 	 */
9158 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9159 		tcp->tcp_naglim = mss;
9160 	/*
9161 	 * TCP should be able to buffer at least 4 MSS data for obvious
9162 	 * performance reason.
9163 	 */
9164 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9165 		tcp->tcp_xmit_hiwater = mss << 2;
9166 
9167 	if (do_ss) {
9168 		/*
9169 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9170 		 * changing due to a reduction in MTU, presumably as a
9171 		 * result of a new path component, reset cwnd to its
9172 		 * "initial" value, as a multiple of the new mss.
9173 		 */
9174 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9175 	} else {
9176 		/*
9177 		 * Called by tcp_paws_check(), the mss increased
9178 		 * marginally to allow use of space previously taken
9179 		 * by the timestamp option. It would be inappropriate
9180 		 * to apply slow start or tcp_init_cwnd values to
9181 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9182 		 */
9183 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9184 		tcp->tcp_cwnd_cnt = 0;
9185 	}
9186 	tcp->tcp_mss = mss;
9187 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9188 }
9189 
9190 /* For /dev/tcp aka AF_INET open */
9191 static int
9192 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9193 {
9194 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9195 }
9196 
9197 /* For /dev/tcp6 aka AF_INET6 open */
9198 static int
9199 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9200 {
9201 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9202 }
9203 
9204 static conn_t *
9205 tcp_create_common(queue_t *q, cred_t *credp, boolean_t isv6,
9206     boolean_t issocket, int *errorp)
9207 {
9208 	tcp_t		*tcp = NULL;
9209 	conn_t		*connp;
9210 	int		err;
9211 	zoneid_t	zoneid;
9212 	tcp_stack_t	*tcps;
9213 	squeue_t	*sqp;
9214 
9215 	ASSERT(errorp != NULL);
9216 	/*
9217 	 * Find the proper zoneid and netstack.
9218 	 */
9219 	/*
9220 	 * Special case for install: miniroot needs to be able to
9221 	 * access files via NFS as though it were always in the
9222 	 * global zone.
9223 	 */
9224 	if (credp == kcred && nfs_global_client_only != 0) {
9225 		zoneid = GLOBAL_ZONEID;
9226 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9227 		    netstack_tcp;
9228 		ASSERT(tcps != NULL);
9229 	} else {
9230 		netstack_t *ns;
9231 
9232 		ns = netstack_find_by_cred(credp);
9233 		ASSERT(ns != NULL);
9234 		tcps = ns->netstack_tcp;
9235 		ASSERT(tcps != NULL);
9236 
9237 		/*
9238 		 * For exclusive stacks we set the zoneid to zero
9239 		 * to make TCP operate as if in the global zone.
9240 		 */
9241 		if (tcps->tcps_netstack->netstack_stackid !=
9242 		    GLOBAL_NETSTACKID)
9243 			zoneid = GLOBAL_ZONEID;
9244 		else
9245 			zoneid = crgetzoneid(credp);
9246 	}
9247 	/*
9248 	 * For stackid zero this is done from strplumb.c, but
9249 	 * non-zero stackids are handled here.
9250 	 */
9251 	if (tcps->tcps_g_q == NULL &&
9252 	    tcps->tcps_netstack->netstack_stackid !=
9253 	    GLOBAL_NETSTACKID) {
9254 		tcp_g_q_setup(tcps);
9255 	}
9256 
9257 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
9258 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
9259 	/*
9260 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9261 	 * so we drop it by one.
9262 	 */
9263 	netstack_rele(tcps->tcps_netstack);
9264 	if (connp == NULL) {
9265 		*errorp = ENOSR;
9266 		return (NULL);
9267 	}
9268 	connp->conn_sqp = sqp;
9269 	connp->conn_initial_sqp = connp->conn_sqp;
9270 	tcp = connp->conn_tcp;
9271 
9272 	if (isv6) {
9273 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9274 		connp->conn_send = ip_output_v6;
9275 		connp->conn_af_isv6 = B_TRUE;
9276 		connp->conn_pkt_isv6 = B_TRUE;
9277 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9278 		tcp->tcp_ipversion = IPV6_VERSION;
9279 		tcp->tcp_family = AF_INET6;
9280 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9281 	} else {
9282 		connp->conn_flags |= IPCL_TCP4;
9283 		connp->conn_send = ip_output;
9284 		connp->conn_af_isv6 = B_FALSE;
9285 		connp->conn_pkt_isv6 = B_FALSE;
9286 		tcp->tcp_ipversion = IPV4_VERSION;
9287 		tcp->tcp_family = AF_INET;
9288 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9289 	}
9290 
9291 	/*
9292 	 * TCP keeps a copy of cred for cache locality reasons but
9293 	 * we put a reference only once. If connp->conn_cred
9294 	 * becomes invalid, tcp_cred should also be set to NULL.
9295 	 */
9296 	tcp->tcp_cred = connp->conn_cred = credp;
9297 	crhold(connp->conn_cred);
9298 	tcp->tcp_cpid = curproc->p_pid;
9299 	tcp->tcp_open_time = lbolt64;
9300 	connp->conn_zoneid = zoneid;
9301 	connp->conn_mlp_type = mlptSingle;
9302 	connp->conn_ulp_labeled = !is_system_labeled();
9303 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9304 	ASSERT(tcp->tcp_tcps == tcps);
9305 
9306 	/*
9307 	 * If the caller has the process-wide flag set, then default to MAC
9308 	 * exempt mode.  This allows read-down to unlabeled hosts.
9309 	 */
9310 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9311 		connp->conn_mac_exempt = B_TRUE;
9312 
9313 	connp->conn_dev = NULL;
9314 	if (issocket) {
9315 		connp->conn_flags |= IPCL_SOCKET;
9316 		tcp->tcp_issocket = 1;
9317 	}
9318 
9319 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
9320 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9321 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
9322 
9323 	/* Non-zero default values */
9324 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9325 
9326 	if (q == NULL) {
9327 		/*
9328 		 * Create a helper stream for non-STREAMS socket.
9329 		 */
9330 		err = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
9331 		if (err != 0) {
9332 			ip1dbg(("tcp_create: create of IP helper stream "
9333 			    "failed\n"));
9334 			CONN_DEC_REF(connp);
9335 			*errorp = err;
9336 			return (NULL);
9337 		}
9338 		q = connp->conn_rq;
9339 	} else {
9340 		RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9341 	}
9342 
9343 	SOCK_CONNID_INIT(tcp->tcp_connid);
9344 	err = tcp_init(tcp, q);
9345 	if (err != 0) {
9346 		CONN_DEC_REF(connp);
9347 		*errorp = err;
9348 		return (NULL);
9349 	}
9350 
9351 	return (connp);
9352 }
9353 
9354 static int
9355 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9356     boolean_t isv6)
9357 {
9358 	tcp_t		*tcp = NULL;
9359 	conn_t		*connp = NULL;
9360 	int		err;
9361 	vmem_t		*minor_arena = NULL;
9362 	dev_t		conn_dev;
9363 	boolean_t	issocket;
9364 
9365 	if (q->q_ptr != NULL)
9366 		return (0);
9367 
9368 	if (sflag == MODOPEN)
9369 		return (EINVAL);
9370 
9371 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9372 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9373 		minor_arena = ip_minor_arena_la;
9374 	} else {
9375 		/*
9376 		 * Either minor numbers in the large arena were exhausted
9377 		 * or a non socket application is doing the open.
9378 		 * Try to allocate from the small arena.
9379 		 */
9380 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9381 			return (EBUSY);
9382 		}
9383 		minor_arena = ip_minor_arena_sa;
9384 	}
9385 
9386 	ASSERT(minor_arena != NULL);
9387 
9388 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
9389 
9390 	if (flag & SO_FALLBACK) {
9391 		/*
9392 		 * Non streams socket needs a stream to fallback to
9393 		 */
9394 		RD(q)->q_ptr = (void *)conn_dev;
9395 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
9396 		WR(q)->q_ptr = (void *)minor_arena;
9397 		qprocson(q);
9398 		return (0);
9399 	} else if (flag & SO_ACCEPTOR) {
9400 		q->q_qinfo = &tcp_acceptor_rinit;
9401 		/*
9402 		 * the conn_dev and minor_arena will be subsequently used by
9403 		 * tcp_wput_accept() and tcpclose_accept() to figure out the
9404 		 * minor device number for this connection from the q_ptr.
9405 		 */
9406 		RD(q)->q_ptr = (void *)conn_dev;
9407 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9408 		WR(q)->q_ptr = (void *)minor_arena;
9409 		qprocson(q);
9410 		return (0);
9411 	}
9412 
9413 	issocket = flag & SO_SOCKSTR;
9414 	connp = tcp_create_common(q, credp, isv6, issocket, &err);
9415 
9416 	if (connp == NULL) {
9417 		inet_minor_free(minor_arena, conn_dev);
9418 		q->q_ptr = WR(q)->q_ptr = NULL;
9419 		return (err);
9420 	}
9421 
9422 	q->q_ptr = WR(q)->q_ptr = connp;
9423 
9424 	connp->conn_dev = conn_dev;
9425 	connp->conn_minor_arena = minor_arena;
9426 
9427 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9428 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9429 
9430 	if (issocket) {
9431 		WR(q)->q_qinfo = &tcp_sock_winit;
9432 	} else {
9433 		tcp = connp->conn_tcp;
9434 #ifdef  _ILP32
9435 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9436 #else
9437 		tcp->tcp_acceptor_id = conn_dev;
9438 #endif  /* _ILP32 */
9439 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9440 	}
9441 
9442 	/*
9443 	 * Put the ref for TCP. Ref for IP was already put
9444 	 * by ipcl_conn_create. Also Make the conn_t globally
9445 	 * visible to walkers
9446 	 */
9447 	mutex_enter(&connp->conn_lock);
9448 	CONN_INC_REF_LOCKED(connp);
9449 	ASSERT(connp->conn_ref == 2);
9450 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9451 	mutex_exit(&connp->conn_lock);
9452 
9453 	qprocson(q);
9454 	return (0);
9455 }
9456 
9457 /*
9458  * Some TCP options can be "set" by requesting them in the option
9459  * buffer. This is needed for XTI feature test though we do not
9460  * allow it in general. We interpret that this mechanism is more
9461  * applicable to OSI protocols and need not be allowed in general.
9462  * This routine filters out options for which it is not allowed (most)
9463  * and lets through those (few) for which it is. [ The XTI interface
9464  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9465  * ever implemented will have to be allowed here ].
9466  */
9467 static boolean_t
9468 tcp_allow_connopt_set(int level, int name)
9469 {
9470 
9471 	switch (level) {
9472 	case IPPROTO_TCP:
9473 		switch (name) {
9474 		case TCP_NODELAY:
9475 			return (B_TRUE);
9476 		default:
9477 			return (B_FALSE);
9478 		}
9479 		/*NOTREACHED*/
9480 	default:
9481 		return (B_FALSE);
9482 	}
9483 	/*NOTREACHED*/
9484 }
9485 
9486 /*
9487  * this routine gets default values of certain options whose default
9488  * values are maintained by protocol specific code
9489  */
9490 /* ARGSUSED */
9491 int
9492 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9493 {
9494 	int32_t	*i1 = (int32_t *)ptr;
9495 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9496 
9497 	switch (level) {
9498 	case IPPROTO_TCP:
9499 		switch (name) {
9500 		case TCP_NOTIFY_THRESHOLD:
9501 			*i1 = tcps->tcps_ip_notify_interval;
9502 			break;
9503 		case TCP_ABORT_THRESHOLD:
9504 			*i1 = tcps->tcps_ip_abort_interval;
9505 			break;
9506 		case TCP_CONN_NOTIFY_THRESHOLD:
9507 			*i1 = tcps->tcps_ip_notify_cinterval;
9508 			break;
9509 		case TCP_CONN_ABORT_THRESHOLD:
9510 			*i1 = tcps->tcps_ip_abort_cinterval;
9511 			break;
9512 		default:
9513 			return (-1);
9514 		}
9515 		break;
9516 	case IPPROTO_IP:
9517 		switch (name) {
9518 		case IP_TTL:
9519 			*i1 = tcps->tcps_ipv4_ttl;
9520 			break;
9521 		default:
9522 			return (-1);
9523 		}
9524 		break;
9525 	case IPPROTO_IPV6:
9526 		switch (name) {
9527 		case IPV6_UNICAST_HOPS:
9528 			*i1 = tcps->tcps_ipv6_hoplimit;
9529 			break;
9530 		default:
9531 			return (-1);
9532 		}
9533 		break;
9534 	default:
9535 		return (-1);
9536 	}
9537 	return (sizeof (int));
9538 }
9539 
9540 static int
9541 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
9542 {
9543 	int		*i1 = (int *)ptr;
9544 	tcp_t		*tcp = connp->conn_tcp;
9545 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9546 
9547 	switch (level) {
9548 	case SOL_SOCKET:
9549 		switch (name) {
9550 		case SO_LINGER:	{
9551 			struct linger *lgr = (struct linger *)ptr;
9552 
9553 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9554 			lgr->l_linger = tcp->tcp_lingertime;
9555 			}
9556 			return (sizeof (struct linger));
9557 		case SO_DEBUG:
9558 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9559 			break;
9560 		case SO_KEEPALIVE:
9561 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9562 			break;
9563 		case SO_DONTROUTE:
9564 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9565 			break;
9566 		case SO_USELOOPBACK:
9567 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9568 			break;
9569 		case SO_BROADCAST:
9570 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9571 			break;
9572 		case SO_REUSEADDR:
9573 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9574 			break;
9575 		case SO_OOBINLINE:
9576 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9577 			break;
9578 		case SO_DGRAM_ERRIND:
9579 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9580 			break;
9581 		case SO_TYPE:
9582 			*i1 = SOCK_STREAM;
9583 			break;
9584 		case SO_SNDBUF:
9585 			*i1 = tcp->tcp_xmit_hiwater;
9586 			break;
9587 		case SO_RCVBUF:
9588 			*i1 = tcp->tcp_recv_hiwater;
9589 			break;
9590 		case SO_SND_COPYAVOID:
9591 			*i1 = tcp->tcp_snd_zcopy_on ?
9592 			    SO_SND_COPYAVOID : 0;
9593 			break;
9594 		case SO_ALLZONES:
9595 			*i1 = connp->conn_allzones ? 1 : 0;
9596 			break;
9597 		case SO_ANON_MLP:
9598 			*i1 = connp->conn_anon_mlp;
9599 			break;
9600 		case SO_MAC_EXEMPT:
9601 			*i1 = connp->conn_mac_exempt;
9602 			break;
9603 		case SO_EXCLBIND:
9604 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9605 			break;
9606 		case SO_PROTOTYPE:
9607 			*i1 = IPPROTO_TCP;
9608 			break;
9609 		case SO_DOMAIN:
9610 			*i1 = tcp->tcp_family;
9611 			break;
9612 		case SO_ACCEPTCONN:
9613 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
9614 		default:
9615 			return (-1);
9616 		}
9617 		break;
9618 	case IPPROTO_TCP:
9619 		switch (name) {
9620 		case TCP_NODELAY:
9621 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9622 			break;
9623 		case TCP_MAXSEG:
9624 			*i1 = tcp->tcp_mss;
9625 			break;
9626 		case TCP_NOTIFY_THRESHOLD:
9627 			*i1 = (int)tcp->tcp_first_timer_threshold;
9628 			break;
9629 		case TCP_ABORT_THRESHOLD:
9630 			*i1 = tcp->tcp_second_timer_threshold;
9631 			break;
9632 		case TCP_CONN_NOTIFY_THRESHOLD:
9633 			*i1 = tcp->tcp_first_ctimer_threshold;
9634 			break;
9635 		case TCP_CONN_ABORT_THRESHOLD:
9636 			*i1 = tcp->tcp_second_ctimer_threshold;
9637 			break;
9638 		case TCP_RECVDSTADDR:
9639 			*i1 = tcp->tcp_recvdstaddr;
9640 			break;
9641 		case TCP_ANONPRIVBIND:
9642 			*i1 = tcp->tcp_anon_priv_bind;
9643 			break;
9644 		case TCP_EXCLBIND:
9645 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9646 			break;
9647 		case TCP_INIT_CWND:
9648 			*i1 = tcp->tcp_init_cwnd;
9649 			break;
9650 		case TCP_KEEPALIVE_THRESHOLD:
9651 			*i1 = tcp->tcp_ka_interval;
9652 			break;
9653 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9654 			*i1 = tcp->tcp_ka_abort_thres;
9655 			break;
9656 		case TCP_CORK:
9657 			*i1 = tcp->tcp_cork;
9658 			break;
9659 		default:
9660 			return (-1);
9661 		}
9662 		break;
9663 	case IPPROTO_IP:
9664 		if (tcp->tcp_family != AF_INET)
9665 			return (-1);
9666 		switch (name) {
9667 		case IP_OPTIONS:
9668 		case T_IP_OPTIONS: {
9669 			/*
9670 			 * This is compatible with BSD in that in only return
9671 			 * the reverse source route with the final destination
9672 			 * as the last entry. The first 4 bytes of the option
9673 			 * will contain the final destination.
9674 			 */
9675 			int	opt_len;
9676 
9677 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9678 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9679 			ASSERT(opt_len >= 0);
9680 			/* Caller ensures enough space */
9681 			if (opt_len > 0) {
9682 				/*
9683 				 * TODO: Do we have to handle getsockopt on an
9684 				 * initiator as well?
9685 				 */
9686 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9687 			}
9688 			return (0);
9689 			}
9690 		case IP_TOS:
9691 		case T_IP_TOS:
9692 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9693 			break;
9694 		case IP_TTL:
9695 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9696 			break;
9697 		case IP_NEXTHOP:
9698 			/* Handled at IP level */
9699 			return (-EINVAL);
9700 		default:
9701 			return (-1);
9702 		}
9703 		break;
9704 	case IPPROTO_IPV6:
9705 		/*
9706 		 * IPPROTO_IPV6 options are only supported for sockets
9707 		 * that are using IPv6 on the wire.
9708 		 */
9709 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9710 			return (-1);
9711 		}
9712 		switch (name) {
9713 		case IPV6_UNICAST_HOPS:
9714 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9715 			break;	/* goto sizeof (int) option return */
9716 		case IPV6_BOUND_IF:
9717 			/* Zero if not set */
9718 			*i1 = tcp->tcp_bound_if;
9719 			break;	/* goto sizeof (int) option return */
9720 		case IPV6_RECVPKTINFO:
9721 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9722 				*i1 = 1;
9723 			else
9724 				*i1 = 0;
9725 			break;	/* goto sizeof (int) option return */
9726 		case IPV6_RECVTCLASS:
9727 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9728 				*i1 = 1;
9729 			else
9730 				*i1 = 0;
9731 			break;	/* goto sizeof (int) option return */
9732 		case IPV6_RECVHOPLIMIT:
9733 			if (tcp->tcp_ipv6_recvancillary &
9734 			    TCP_IPV6_RECVHOPLIMIT)
9735 				*i1 = 1;
9736 			else
9737 				*i1 = 0;
9738 			break;	/* goto sizeof (int) option return */
9739 		case IPV6_RECVHOPOPTS:
9740 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9741 				*i1 = 1;
9742 			else
9743 				*i1 = 0;
9744 			break;	/* goto sizeof (int) option return */
9745 		case IPV6_RECVDSTOPTS:
9746 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9747 				*i1 = 1;
9748 			else
9749 				*i1 = 0;
9750 			break;	/* goto sizeof (int) option return */
9751 		case _OLD_IPV6_RECVDSTOPTS:
9752 			if (tcp->tcp_ipv6_recvancillary &
9753 			    TCP_OLD_IPV6_RECVDSTOPTS)
9754 				*i1 = 1;
9755 			else
9756 				*i1 = 0;
9757 			break;	/* goto sizeof (int) option return */
9758 		case IPV6_RECVRTHDR:
9759 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9760 				*i1 = 1;
9761 			else
9762 				*i1 = 0;
9763 			break;	/* goto sizeof (int) option return */
9764 		case IPV6_RECVRTHDRDSTOPTS:
9765 			if (tcp->tcp_ipv6_recvancillary &
9766 			    TCP_IPV6_RECVRTDSTOPTS)
9767 				*i1 = 1;
9768 			else
9769 				*i1 = 0;
9770 			break;	/* goto sizeof (int) option return */
9771 		case IPV6_PKTINFO: {
9772 			/* XXX assumes that caller has room for max size! */
9773 			struct in6_pktinfo *pkti;
9774 
9775 			pkti = (struct in6_pktinfo *)ptr;
9776 			if (ipp->ipp_fields & IPPF_IFINDEX)
9777 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9778 			else
9779 				pkti->ipi6_ifindex = 0;
9780 			if (ipp->ipp_fields & IPPF_ADDR)
9781 				pkti->ipi6_addr = ipp->ipp_addr;
9782 			else
9783 				pkti->ipi6_addr = ipv6_all_zeros;
9784 			return (sizeof (struct in6_pktinfo));
9785 		}
9786 		case IPV6_TCLASS:
9787 			if (ipp->ipp_fields & IPPF_TCLASS)
9788 				*i1 = ipp->ipp_tclass;
9789 			else
9790 				*i1 = IPV6_FLOW_TCLASS(
9791 				    IPV6_DEFAULT_VERS_AND_FLOW);
9792 			break;	/* goto sizeof (int) option return */
9793 		case IPV6_NEXTHOP: {
9794 			sin6_t *sin6 = (sin6_t *)ptr;
9795 
9796 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9797 				return (0);
9798 			*sin6 = sin6_null;
9799 			sin6->sin6_family = AF_INET6;
9800 			sin6->sin6_addr = ipp->ipp_nexthop;
9801 			return (sizeof (sin6_t));
9802 		}
9803 		case IPV6_HOPOPTS:
9804 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9805 				return (0);
9806 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9807 				return (0);
9808 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9809 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9810 			if (tcp->tcp_label_len > 0) {
9811 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9812 				ptr[1] = (ipp->ipp_hopoptslen -
9813 				    tcp->tcp_label_len + 7) / 8 - 1;
9814 			}
9815 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9816 		case IPV6_RTHDRDSTOPTS:
9817 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9818 				return (0);
9819 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9820 			return (ipp->ipp_rtdstoptslen);
9821 		case IPV6_RTHDR:
9822 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9823 				return (0);
9824 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9825 			return (ipp->ipp_rthdrlen);
9826 		case IPV6_DSTOPTS:
9827 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9828 				return (0);
9829 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9830 			return (ipp->ipp_dstoptslen);
9831 		case IPV6_SRC_PREFERENCES:
9832 			return (ip6_get_src_preferences(connp,
9833 			    (uint32_t *)ptr));
9834 		case IPV6_PATHMTU: {
9835 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9836 
9837 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9838 				return (-1);
9839 
9840 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9841 			    connp->conn_fport, mtuinfo,
9842 			    connp->conn_netstack));
9843 		}
9844 		default:
9845 			return (-1);
9846 		}
9847 		break;
9848 	default:
9849 		return (-1);
9850 	}
9851 	return (sizeof (int));
9852 }
9853 
9854 /*
9855  * TCP routine to get the values of options.
9856  */
9857 int
9858 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
9859 {
9860 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
9861 }
9862 
9863 /* returns UNIX error, the optlen is a value-result arg */
9864 int
9865 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
9866     void *optvalp, socklen_t *optlen, cred_t *cr)
9867 {
9868 	conn_t		*connp = (conn_t *)proto_handle;
9869 	squeue_t	*sqp = connp->conn_sqp;
9870 	int		error;
9871 	t_uscalar_t	max_optbuf_len;
9872 	void		*optvalp_buf;
9873 	int		len;
9874 
9875 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
9876 	    tcp_opt_obj.odb_opt_des_arr,
9877 	    tcp_opt_obj.odb_opt_arr_cnt,
9878 	    tcp_opt_obj.odb_topmost_tpiprovider,
9879 	    B_FALSE, B_TRUE, cr);
9880 	if (error != 0) {
9881 		if (error < 0) {
9882 			error = proto_tlitosyserr(-error);
9883 		}
9884 		return (error);
9885 	}
9886 
9887 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
9888 
9889 	error = squeue_synch_enter(sqp, connp, 0);
9890 	if (error == ENOMEM) {
9891 		return (ENOMEM);
9892 	}
9893 
9894 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
9895 	squeue_synch_exit(sqp, connp);
9896 
9897 	if (len < 0) {
9898 		/*
9899 		 * Pass on to IP
9900 		 */
9901 		kmem_free(optvalp_buf, max_optbuf_len);
9902 		return (ip_get_options(connp, level, option_name,
9903 		    optvalp, optlen, cr));
9904 	} else {
9905 		/*
9906 		 * update optlen and copy option value
9907 		 */
9908 		t_uscalar_t size = MIN(len, *optlen);
9909 		bcopy(optvalp_buf, optvalp, size);
9910 		bcopy(&size, optlen, sizeof (size));
9911 
9912 		kmem_free(optvalp_buf, max_optbuf_len);
9913 		return (0);
9914 	}
9915 }
9916 
9917 /*
9918  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9919  * Parameters are assumed to be verified by the caller.
9920  */
9921 /* ARGSUSED */
9922 int
9923 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
9924     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9925     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9926 {
9927 	tcp_t	*tcp = connp->conn_tcp;
9928 	int	*i1 = (int *)invalp;
9929 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9930 	boolean_t checkonly;
9931 	int	reterr;
9932 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9933 
9934 	switch (optset_context) {
9935 	case SETFN_OPTCOM_CHECKONLY:
9936 		checkonly = B_TRUE;
9937 		/*
9938 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9939 		 * inlen != 0 implies value supplied and
9940 		 * 	we have to "pretend" to set it.
9941 		 * inlen == 0 implies that there is no
9942 		 * 	value part in T_CHECK request and just validation
9943 		 * done elsewhere should be enough, we just return here.
9944 		 */
9945 		if (inlen == 0) {
9946 			*outlenp = 0;
9947 			return (0);
9948 		}
9949 		break;
9950 	case SETFN_OPTCOM_NEGOTIATE:
9951 		checkonly = B_FALSE;
9952 		break;
9953 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9954 	case SETFN_CONN_NEGOTIATE:
9955 		checkonly = B_FALSE;
9956 		/*
9957 		 * Negotiating local and "association-related" options
9958 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9959 		 * primitives is allowed by XTI, but we choose
9960 		 * to not implement this style negotiation for Internet
9961 		 * protocols (We interpret it is a must for OSI world but
9962 		 * optional for Internet protocols) for all options.
9963 		 * [ Will do only for the few options that enable test
9964 		 * suites that our XTI implementation of this feature
9965 		 * works for transports that do allow it ]
9966 		 */
9967 		if (!tcp_allow_connopt_set(level, name)) {
9968 			*outlenp = 0;
9969 			return (EINVAL);
9970 		}
9971 		break;
9972 	default:
9973 		/*
9974 		 * We should never get here
9975 		 */
9976 		*outlenp = 0;
9977 		return (EINVAL);
9978 	}
9979 
9980 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9981 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9982 
9983 	/*
9984 	 * For TCP, we should have no ancillary data sent down
9985 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9986 	 * has to be zero.
9987 	 */
9988 	ASSERT(thisdg_attrs == NULL);
9989 
9990 	/*
9991 	 * For fixed length options, no sanity check
9992 	 * of passed in length is done. It is assumed *_optcom_req()
9993 	 * routines do the right thing.
9994 	 */
9995 	switch (level) {
9996 	case SOL_SOCKET:
9997 		switch (name) {
9998 		case SO_LINGER: {
9999 			struct linger *lgr = (struct linger *)invalp;
10000 
10001 			if (!checkonly) {
10002 				if (lgr->l_onoff) {
10003 					tcp->tcp_linger = 1;
10004 					tcp->tcp_lingertime = lgr->l_linger;
10005 				} else {
10006 					tcp->tcp_linger = 0;
10007 					tcp->tcp_lingertime = 0;
10008 				}
10009 				/* struct copy */
10010 				*(struct linger *)outvalp = *lgr;
10011 			} else {
10012 				if (!lgr->l_onoff) {
10013 					((struct linger *)
10014 					    outvalp)->l_onoff = 0;
10015 					((struct linger *)
10016 					    outvalp)->l_linger = 0;
10017 				} else {
10018 					/* struct copy */
10019 					*(struct linger *)outvalp = *lgr;
10020 				}
10021 			}
10022 			*outlenp = sizeof (struct linger);
10023 			return (0);
10024 		}
10025 		case SO_DEBUG:
10026 			if (!checkonly)
10027 				tcp->tcp_debug = onoff;
10028 			break;
10029 		case SO_KEEPALIVE:
10030 			if (checkonly) {
10031 				/* check only case */
10032 				break;
10033 			}
10034 
10035 			if (!onoff) {
10036 				if (tcp->tcp_ka_enabled) {
10037 					if (tcp->tcp_ka_tid != 0) {
10038 						(void) TCP_TIMER_CANCEL(tcp,
10039 						    tcp->tcp_ka_tid);
10040 						tcp->tcp_ka_tid = 0;
10041 					}
10042 					tcp->tcp_ka_enabled = 0;
10043 				}
10044 				break;
10045 			}
10046 			if (!tcp->tcp_ka_enabled) {
10047 				/* Crank up the keepalive timer */
10048 				tcp->tcp_ka_last_intrvl = 0;
10049 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10050 				    tcp_keepalive_killer,
10051 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10052 				tcp->tcp_ka_enabled = 1;
10053 			}
10054 			break;
10055 		case SO_DONTROUTE:
10056 			/*
10057 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10058 			 * only of interest to IP.  We track them here only so
10059 			 * that we can report their current value.
10060 			 */
10061 			if (!checkonly) {
10062 				tcp->tcp_dontroute = onoff;
10063 				tcp->tcp_connp->conn_dontroute = onoff;
10064 			}
10065 			break;
10066 		case SO_USELOOPBACK:
10067 			if (!checkonly) {
10068 				tcp->tcp_useloopback = onoff;
10069 				tcp->tcp_connp->conn_loopback = onoff;
10070 			}
10071 			break;
10072 		case SO_BROADCAST:
10073 			if (!checkonly) {
10074 				tcp->tcp_broadcast = onoff;
10075 				tcp->tcp_connp->conn_broadcast = onoff;
10076 			}
10077 			break;
10078 		case SO_REUSEADDR:
10079 			if (!checkonly) {
10080 				tcp->tcp_reuseaddr = onoff;
10081 				tcp->tcp_connp->conn_reuseaddr = onoff;
10082 			}
10083 			break;
10084 		case SO_OOBINLINE:
10085 			if (!checkonly) {
10086 				tcp->tcp_oobinline = onoff;
10087 				if (IPCL_IS_NONSTR(tcp->tcp_connp))
10088 					proto_set_rx_oob_opt(connp, onoff);
10089 			}
10090 			break;
10091 		case SO_DGRAM_ERRIND:
10092 			if (!checkonly)
10093 				tcp->tcp_dgram_errind = onoff;
10094 			break;
10095 		case SO_SNDBUF: {
10096 			if (*i1 > tcps->tcps_max_buf) {
10097 				*outlenp = 0;
10098 				return (ENOBUFS);
10099 			}
10100 			if (checkonly)
10101 				break;
10102 
10103 			tcp->tcp_xmit_hiwater = *i1;
10104 			if (tcps->tcps_snd_lowat_fraction != 0)
10105 				tcp->tcp_xmit_lowater =
10106 				    tcp->tcp_xmit_hiwater /
10107 				    tcps->tcps_snd_lowat_fraction;
10108 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10109 			/*
10110 			 * If we are flow-controlled, recheck the condition.
10111 			 * There are apps that increase SO_SNDBUF size when
10112 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10113 			 * control condition to be lifted right away.
10114 			 */
10115 			mutex_enter(&tcp->tcp_non_sq_lock);
10116 			if (tcp->tcp_flow_stopped &&
10117 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10118 				tcp_clrqfull(tcp);
10119 			}
10120 			mutex_exit(&tcp->tcp_non_sq_lock);
10121 			break;
10122 		}
10123 		case SO_RCVBUF:
10124 			if (*i1 > tcps->tcps_max_buf) {
10125 				*outlenp = 0;
10126 				return (ENOBUFS);
10127 			}
10128 			/* Silently ignore zero */
10129 			if (!checkonly && *i1 != 0) {
10130 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10131 				(void) tcp_rwnd_set(tcp, *i1);
10132 			}
10133 			/*
10134 			 * XXX should we return the rwnd here
10135 			 * and tcp_opt_get ?
10136 			 */
10137 			break;
10138 		case SO_SND_COPYAVOID:
10139 			if (!checkonly) {
10140 				/* we only allow enable at most once for now */
10141 				if (tcp->tcp_loopback ||
10142 				    (tcp->tcp_kssl_ctx != NULL) ||
10143 				    (!tcp->tcp_snd_zcopy_aware &&
10144 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10145 					*outlenp = 0;
10146 					return (EOPNOTSUPP);
10147 				}
10148 				tcp->tcp_snd_zcopy_aware = 1;
10149 			}
10150 			break;
10151 		case SO_ALLZONES:
10152 			/* Pass option along to IP level for handling */
10153 			return (-EINVAL);
10154 		case SO_ANON_MLP:
10155 			/* Pass option along to IP level for handling */
10156 			return (-EINVAL);
10157 		case SO_MAC_EXEMPT:
10158 			/* Pass option along to IP level for handling */
10159 			return (-EINVAL);
10160 		case SO_EXCLBIND:
10161 			if (!checkonly)
10162 				tcp->tcp_exclbind = onoff;
10163 			break;
10164 		default:
10165 			*outlenp = 0;
10166 			return (EINVAL);
10167 		}
10168 		break;
10169 	case IPPROTO_TCP:
10170 		switch (name) {
10171 		case TCP_NODELAY:
10172 			if (!checkonly)
10173 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10174 			break;
10175 		case TCP_NOTIFY_THRESHOLD:
10176 			if (!checkonly)
10177 				tcp->tcp_first_timer_threshold = *i1;
10178 			break;
10179 		case TCP_ABORT_THRESHOLD:
10180 			if (!checkonly)
10181 				tcp->tcp_second_timer_threshold = *i1;
10182 			break;
10183 		case TCP_CONN_NOTIFY_THRESHOLD:
10184 			if (!checkonly)
10185 				tcp->tcp_first_ctimer_threshold = *i1;
10186 			break;
10187 		case TCP_CONN_ABORT_THRESHOLD:
10188 			if (!checkonly)
10189 				tcp->tcp_second_ctimer_threshold = *i1;
10190 			break;
10191 		case TCP_RECVDSTADDR:
10192 			if (tcp->tcp_state > TCPS_LISTEN)
10193 				return (EOPNOTSUPP);
10194 			if (!checkonly)
10195 				tcp->tcp_recvdstaddr = onoff;
10196 			break;
10197 		case TCP_ANONPRIVBIND:
10198 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10199 			    IPPROTO_TCP)) != 0) {
10200 				*outlenp = 0;
10201 				return (reterr);
10202 			}
10203 			if (!checkonly) {
10204 				tcp->tcp_anon_priv_bind = onoff;
10205 			}
10206 			break;
10207 		case TCP_EXCLBIND:
10208 			if (!checkonly)
10209 				tcp->tcp_exclbind = onoff;
10210 			break;	/* goto sizeof (int) option return */
10211 		case TCP_INIT_CWND: {
10212 			uint32_t init_cwnd = *((uint32_t *)invalp);
10213 
10214 			if (checkonly)
10215 				break;
10216 
10217 			/*
10218 			 * Only allow socket with network configuration
10219 			 * privilege to set the initial cwnd to be larger
10220 			 * than allowed by RFC 3390.
10221 			 */
10222 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10223 				tcp->tcp_init_cwnd = init_cwnd;
10224 				break;
10225 			}
10226 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10227 				*outlenp = 0;
10228 				return (reterr);
10229 			}
10230 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10231 				*outlenp = 0;
10232 				return (EINVAL);
10233 			}
10234 			tcp->tcp_init_cwnd = init_cwnd;
10235 			break;
10236 		}
10237 		case TCP_KEEPALIVE_THRESHOLD:
10238 			if (checkonly)
10239 				break;
10240 
10241 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10242 			    *i1 > tcps->tcps_keepalive_interval_high) {
10243 				*outlenp = 0;
10244 				return (EINVAL);
10245 			}
10246 			if (*i1 != tcp->tcp_ka_interval) {
10247 				tcp->tcp_ka_interval = *i1;
10248 				/*
10249 				 * Check if we need to restart the
10250 				 * keepalive timer.
10251 				 */
10252 				if (tcp->tcp_ka_tid != 0) {
10253 					ASSERT(tcp->tcp_ka_enabled);
10254 					(void) TCP_TIMER_CANCEL(tcp,
10255 					    tcp->tcp_ka_tid);
10256 					tcp->tcp_ka_last_intrvl = 0;
10257 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10258 					    tcp_keepalive_killer,
10259 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10260 				}
10261 			}
10262 			break;
10263 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10264 			if (!checkonly) {
10265 				if (*i1 <
10266 				    tcps->tcps_keepalive_abort_interval_low ||
10267 				    *i1 >
10268 				    tcps->tcps_keepalive_abort_interval_high) {
10269 					*outlenp = 0;
10270 					return (EINVAL);
10271 				}
10272 				tcp->tcp_ka_abort_thres = *i1;
10273 			}
10274 			break;
10275 		case TCP_CORK:
10276 			if (!checkonly) {
10277 				/*
10278 				 * if tcp->tcp_cork was set and is now
10279 				 * being unset, we have to make sure that
10280 				 * the remaining data gets sent out. Also
10281 				 * unset tcp->tcp_cork so that tcp_wput_data()
10282 				 * can send data even if it is less than mss
10283 				 */
10284 				if (tcp->tcp_cork && onoff == 0 &&
10285 				    tcp->tcp_unsent > 0) {
10286 					tcp->tcp_cork = B_FALSE;
10287 					tcp_wput_data(tcp, NULL, B_FALSE);
10288 				}
10289 				tcp->tcp_cork = onoff;
10290 			}
10291 			break;
10292 		default:
10293 			*outlenp = 0;
10294 			return (EINVAL);
10295 		}
10296 		break;
10297 	case IPPROTO_IP:
10298 		if (tcp->tcp_family != AF_INET) {
10299 			*outlenp = 0;
10300 			return (ENOPROTOOPT);
10301 		}
10302 		switch (name) {
10303 		case IP_OPTIONS:
10304 		case T_IP_OPTIONS:
10305 			reterr = tcp_opt_set_header(tcp, checkonly,
10306 			    invalp, inlen);
10307 			if (reterr) {
10308 				*outlenp = 0;
10309 				return (reterr);
10310 			}
10311 			/* OK return - copy input buffer into output buffer */
10312 			if (invalp != outvalp) {
10313 				/* don't trust bcopy for identical src/dst */
10314 				bcopy(invalp, outvalp, inlen);
10315 			}
10316 			*outlenp = inlen;
10317 			return (0);
10318 		case IP_TOS:
10319 		case T_IP_TOS:
10320 			if (!checkonly) {
10321 				tcp->tcp_ipha->ipha_type_of_service =
10322 				    (uchar_t)*i1;
10323 				tcp->tcp_tos = (uchar_t)*i1;
10324 			}
10325 			break;
10326 		case IP_TTL:
10327 			if (!checkonly) {
10328 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10329 				tcp->tcp_ttl = (uchar_t)*i1;
10330 			}
10331 			break;
10332 		case IP_BOUND_IF:
10333 		case IP_NEXTHOP:
10334 			/* Handled at the IP level */
10335 			return (-EINVAL);
10336 		case IP_SEC_OPT:
10337 			/*
10338 			 * We should not allow policy setting after
10339 			 * we start listening for connections.
10340 			 */
10341 			if (tcp->tcp_state == TCPS_LISTEN) {
10342 				return (EINVAL);
10343 			} else {
10344 				/* Handled at the IP level */
10345 				return (-EINVAL);
10346 			}
10347 		default:
10348 			*outlenp = 0;
10349 			return (EINVAL);
10350 		}
10351 		break;
10352 	case IPPROTO_IPV6: {
10353 		ip6_pkt_t		*ipp;
10354 
10355 		/*
10356 		 * IPPROTO_IPV6 options are only supported for sockets
10357 		 * that are using IPv6 on the wire.
10358 		 */
10359 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10360 			*outlenp = 0;
10361 			return (ENOPROTOOPT);
10362 		}
10363 		/*
10364 		 * Only sticky options; no ancillary data
10365 		 */
10366 		ipp = &tcp->tcp_sticky_ipp;
10367 
10368 		switch (name) {
10369 		case IPV6_UNICAST_HOPS:
10370 			/* -1 means use default */
10371 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10372 				*outlenp = 0;
10373 				return (EINVAL);
10374 			}
10375 			if (!checkonly) {
10376 				if (*i1 == -1) {
10377 					tcp->tcp_ip6h->ip6_hops =
10378 					    ipp->ipp_unicast_hops =
10379 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10380 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10381 					/* Pass modified value to IP. */
10382 					*i1 = tcp->tcp_ip6h->ip6_hops;
10383 				} else {
10384 					tcp->tcp_ip6h->ip6_hops =
10385 					    ipp->ipp_unicast_hops =
10386 					    (uint8_t)*i1;
10387 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10388 				}
10389 				reterr = tcp_build_hdrs(tcp);
10390 				if (reterr != 0)
10391 					return (reterr);
10392 			}
10393 			break;
10394 		case IPV6_BOUND_IF:
10395 			if (!checkonly) {
10396 				tcp->tcp_bound_if = *i1;
10397 				PASS_OPT_TO_IP(connp);
10398 			}
10399 			break;
10400 		/*
10401 		 * Set boolean switches for ancillary data delivery
10402 		 */
10403 		case IPV6_RECVPKTINFO:
10404 			if (!checkonly) {
10405 				if (onoff)
10406 					tcp->tcp_ipv6_recvancillary |=
10407 					    TCP_IPV6_RECVPKTINFO;
10408 				else
10409 					tcp->tcp_ipv6_recvancillary &=
10410 					    ~TCP_IPV6_RECVPKTINFO;
10411 				/* Force it to be sent up with the next msg */
10412 				tcp->tcp_recvifindex = 0;
10413 				PASS_OPT_TO_IP(connp);
10414 			}
10415 			break;
10416 		case IPV6_RECVTCLASS:
10417 			if (!checkonly) {
10418 				if (onoff)
10419 					tcp->tcp_ipv6_recvancillary |=
10420 					    TCP_IPV6_RECVTCLASS;
10421 				else
10422 					tcp->tcp_ipv6_recvancillary &=
10423 					    ~TCP_IPV6_RECVTCLASS;
10424 				PASS_OPT_TO_IP(connp);
10425 			}
10426 			break;
10427 		case IPV6_RECVHOPLIMIT:
10428 			if (!checkonly) {
10429 				if (onoff)
10430 					tcp->tcp_ipv6_recvancillary |=
10431 					    TCP_IPV6_RECVHOPLIMIT;
10432 				else
10433 					tcp->tcp_ipv6_recvancillary &=
10434 					    ~TCP_IPV6_RECVHOPLIMIT;
10435 				/* Force it to be sent up with the next msg */
10436 				tcp->tcp_recvhops = 0xffffffffU;
10437 				PASS_OPT_TO_IP(connp);
10438 			}
10439 			break;
10440 		case IPV6_RECVHOPOPTS:
10441 			if (!checkonly) {
10442 				if (onoff)
10443 					tcp->tcp_ipv6_recvancillary |=
10444 					    TCP_IPV6_RECVHOPOPTS;
10445 				else
10446 					tcp->tcp_ipv6_recvancillary &=
10447 					    ~TCP_IPV6_RECVHOPOPTS;
10448 				PASS_OPT_TO_IP(connp);
10449 			}
10450 			break;
10451 		case IPV6_RECVDSTOPTS:
10452 			if (!checkonly) {
10453 				if (onoff)
10454 					tcp->tcp_ipv6_recvancillary |=
10455 					    TCP_IPV6_RECVDSTOPTS;
10456 				else
10457 					tcp->tcp_ipv6_recvancillary &=
10458 					    ~TCP_IPV6_RECVDSTOPTS;
10459 				PASS_OPT_TO_IP(connp);
10460 			}
10461 			break;
10462 		case _OLD_IPV6_RECVDSTOPTS:
10463 			if (!checkonly) {
10464 				if (onoff)
10465 					tcp->tcp_ipv6_recvancillary |=
10466 					    TCP_OLD_IPV6_RECVDSTOPTS;
10467 				else
10468 					tcp->tcp_ipv6_recvancillary &=
10469 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10470 			}
10471 			break;
10472 		case IPV6_RECVRTHDR:
10473 			if (!checkonly) {
10474 				if (onoff)
10475 					tcp->tcp_ipv6_recvancillary |=
10476 					    TCP_IPV6_RECVRTHDR;
10477 				else
10478 					tcp->tcp_ipv6_recvancillary &=
10479 					    ~TCP_IPV6_RECVRTHDR;
10480 				PASS_OPT_TO_IP(connp);
10481 			}
10482 			break;
10483 		case IPV6_RECVRTHDRDSTOPTS:
10484 			if (!checkonly) {
10485 				if (onoff)
10486 					tcp->tcp_ipv6_recvancillary |=
10487 					    TCP_IPV6_RECVRTDSTOPTS;
10488 				else
10489 					tcp->tcp_ipv6_recvancillary &=
10490 					    ~TCP_IPV6_RECVRTDSTOPTS;
10491 				PASS_OPT_TO_IP(connp);
10492 			}
10493 			break;
10494 		case IPV6_PKTINFO:
10495 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10496 				return (EINVAL);
10497 			if (checkonly)
10498 				break;
10499 
10500 			if (inlen == 0) {
10501 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10502 			} else {
10503 				struct in6_pktinfo *pkti;
10504 
10505 				pkti = (struct in6_pktinfo *)invalp;
10506 				/*
10507 				 * RFC 3542 states that ipi6_addr must be
10508 				 * the unspecified address when setting the
10509 				 * IPV6_PKTINFO sticky socket option on a
10510 				 * TCP socket.
10511 				 */
10512 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10513 					return (EINVAL);
10514 				/*
10515 				 * IP will validate the source address and
10516 				 * interface index.
10517 				 */
10518 				if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
10519 					reterr = ip_set_options(tcp->tcp_connp,
10520 					    level, name, invalp, inlen, cr);
10521 				} else {
10522 					reterr = ip6_set_pktinfo(cr,
10523 					    tcp->tcp_connp, pkti, mblk);
10524 				}
10525 				if (reterr != 0)
10526 					return (reterr);
10527 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10528 				ipp->ipp_addr = pkti->ipi6_addr;
10529 				if (ipp->ipp_ifindex != 0)
10530 					ipp->ipp_fields |= IPPF_IFINDEX;
10531 				else
10532 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10533 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10534 					ipp->ipp_fields |= IPPF_ADDR;
10535 				else
10536 					ipp->ipp_fields &= ~IPPF_ADDR;
10537 			}
10538 			reterr = tcp_build_hdrs(tcp);
10539 			if (reterr != 0)
10540 				return (reterr);
10541 			break;
10542 		case IPV6_TCLASS:
10543 			if (inlen != 0 && inlen != sizeof (int))
10544 				return (EINVAL);
10545 			if (checkonly)
10546 				break;
10547 
10548 			if (inlen == 0) {
10549 				ipp->ipp_fields &= ~IPPF_TCLASS;
10550 			} else {
10551 				if (*i1 > 255 || *i1 < -1)
10552 					return (EINVAL);
10553 				if (*i1 == -1) {
10554 					ipp->ipp_tclass = 0;
10555 					*i1 = 0;
10556 				} else {
10557 					ipp->ipp_tclass = *i1;
10558 				}
10559 				ipp->ipp_fields |= IPPF_TCLASS;
10560 			}
10561 			reterr = tcp_build_hdrs(tcp);
10562 			if (reterr != 0)
10563 				return (reterr);
10564 			break;
10565 		case IPV6_NEXTHOP:
10566 			/*
10567 			 * IP will verify that the nexthop is reachable
10568 			 * and fail for sticky options.
10569 			 */
10570 			if (inlen != 0 && inlen != sizeof (sin6_t))
10571 				return (EINVAL);
10572 			if (checkonly)
10573 				break;
10574 
10575 			if (inlen == 0) {
10576 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10577 			} else {
10578 				sin6_t *sin6 = (sin6_t *)invalp;
10579 
10580 				if (sin6->sin6_family != AF_INET6)
10581 					return (EAFNOSUPPORT);
10582 				if (IN6_IS_ADDR_V4MAPPED(
10583 				    &sin6->sin6_addr))
10584 					return (EADDRNOTAVAIL);
10585 				ipp->ipp_nexthop = sin6->sin6_addr;
10586 				if (!IN6_IS_ADDR_UNSPECIFIED(
10587 				    &ipp->ipp_nexthop))
10588 					ipp->ipp_fields |= IPPF_NEXTHOP;
10589 				else
10590 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10591 			}
10592 			reterr = tcp_build_hdrs(tcp);
10593 			if (reterr != 0)
10594 				return (reterr);
10595 			PASS_OPT_TO_IP(connp);
10596 			break;
10597 		case IPV6_HOPOPTS: {
10598 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10599 
10600 			/*
10601 			 * Sanity checks - minimum size, size a multiple of
10602 			 * eight bytes, and matching size passed in.
10603 			 */
10604 			if (inlen != 0 &&
10605 			    inlen != (8 * (hopts->ip6h_len + 1)))
10606 				return (EINVAL);
10607 
10608 			if (checkonly)
10609 				break;
10610 
10611 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10612 			    (uchar_t **)&ipp->ipp_hopopts,
10613 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10614 			if (reterr != 0)
10615 				return (reterr);
10616 			if (ipp->ipp_hopoptslen == 0)
10617 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10618 			else
10619 				ipp->ipp_fields |= IPPF_HOPOPTS;
10620 			reterr = tcp_build_hdrs(tcp);
10621 			if (reterr != 0)
10622 				return (reterr);
10623 			break;
10624 		}
10625 		case IPV6_RTHDRDSTOPTS: {
10626 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10627 
10628 			/*
10629 			 * Sanity checks - minimum size, size a multiple of
10630 			 * eight bytes, and matching size passed in.
10631 			 */
10632 			if (inlen != 0 &&
10633 			    inlen != (8 * (dopts->ip6d_len + 1)))
10634 				return (EINVAL);
10635 
10636 			if (checkonly)
10637 				break;
10638 
10639 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10640 			    (uchar_t **)&ipp->ipp_rtdstopts,
10641 			    &ipp->ipp_rtdstoptslen, 0);
10642 			if (reterr != 0)
10643 				return (reterr);
10644 			if (ipp->ipp_rtdstoptslen == 0)
10645 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10646 			else
10647 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10648 			reterr = tcp_build_hdrs(tcp);
10649 			if (reterr != 0)
10650 				return (reterr);
10651 			break;
10652 		}
10653 		case IPV6_DSTOPTS: {
10654 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10655 
10656 			/*
10657 			 * Sanity checks - minimum size, size a multiple of
10658 			 * eight bytes, and matching size passed in.
10659 			 */
10660 			if (inlen != 0 &&
10661 			    inlen != (8 * (dopts->ip6d_len + 1)))
10662 				return (EINVAL);
10663 
10664 			if (checkonly)
10665 				break;
10666 
10667 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10668 			    (uchar_t **)&ipp->ipp_dstopts,
10669 			    &ipp->ipp_dstoptslen, 0);
10670 			if (reterr != 0)
10671 				return (reterr);
10672 			if (ipp->ipp_dstoptslen == 0)
10673 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10674 			else
10675 				ipp->ipp_fields |= IPPF_DSTOPTS;
10676 			reterr = tcp_build_hdrs(tcp);
10677 			if (reterr != 0)
10678 				return (reterr);
10679 			break;
10680 		}
10681 		case IPV6_RTHDR: {
10682 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10683 
10684 			/*
10685 			 * Sanity checks - minimum size, size a multiple of
10686 			 * eight bytes, and matching size passed in.
10687 			 */
10688 			if (inlen != 0 &&
10689 			    inlen != (8 * (rt->ip6r_len + 1)))
10690 				return (EINVAL);
10691 
10692 			if (checkonly)
10693 				break;
10694 
10695 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10696 			    (uchar_t **)&ipp->ipp_rthdr,
10697 			    &ipp->ipp_rthdrlen, 0);
10698 			if (reterr != 0)
10699 				return (reterr);
10700 			if (ipp->ipp_rthdrlen == 0)
10701 				ipp->ipp_fields &= ~IPPF_RTHDR;
10702 			else
10703 				ipp->ipp_fields |= IPPF_RTHDR;
10704 			reterr = tcp_build_hdrs(tcp);
10705 			if (reterr != 0)
10706 				return (reterr);
10707 			break;
10708 		}
10709 		case IPV6_V6ONLY:
10710 			if (!checkonly) {
10711 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10712 			}
10713 			break;
10714 		case IPV6_USE_MIN_MTU:
10715 			if (inlen != sizeof (int))
10716 				return (EINVAL);
10717 
10718 			if (*i1 < -1 || *i1 > 1)
10719 				return (EINVAL);
10720 
10721 			if (checkonly)
10722 				break;
10723 
10724 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10725 			ipp->ipp_use_min_mtu = *i1;
10726 			break;
10727 		case IPV6_BOUND_PIF:
10728 			/* Handled at the IP level */
10729 			return (-EINVAL);
10730 		case IPV6_SEC_OPT:
10731 			/*
10732 			 * We should not allow policy setting after
10733 			 * we start listening for connections.
10734 			 */
10735 			if (tcp->tcp_state == TCPS_LISTEN) {
10736 				return (EINVAL);
10737 			} else {
10738 				/* Handled at the IP level */
10739 				return (-EINVAL);
10740 			}
10741 		case IPV6_SRC_PREFERENCES:
10742 			if (inlen != sizeof (uint32_t))
10743 				return (EINVAL);
10744 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10745 			    *(uint32_t *)invalp);
10746 			if (reterr != 0) {
10747 				*outlenp = 0;
10748 				return (reterr);
10749 			}
10750 			break;
10751 		default:
10752 			*outlenp = 0;
10753 			return (EINVAL);
10754 		}
10755 		break;
10756 	}		/* end IPPROTO_IPV6 */
10757 	default:
10758 		*outlenp = 0;
10759 		return (EINVAL);
10760 	}
10761 	/*
10762 	 * Common case of OK return with outval same as inval
10763 	 */
10764 	if (invalp != outvalp) {
10765 		/* don't trust bcopy for identical src/dst */
10766 		(void) bcopy(invalp, outvalp, inlen);
10767 	}
10768 	*outlenp = inlen;
10769 	return (0);
10770 }
10771 
10772 /* ARGSUSED */
10773 int
10774 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10775     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10776     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10777 {
10778 	conn_t	*connp =  Q_TO_CONN(q);
10779 
10780 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
10781 	    outlenp, outvalp, thisdg_attrs, cr, mblk));
10782 }
10783 
10784 int
10785 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
10786     const void *optvalp, socklen_t optlen, cred_t *cr)
10787 {
10788 	conn_t		*connp = (conn_t *)proto_handle;
10789 	squeue_t	*sqp = connp->conn_sqp;
10790 	int		error;
10791 
10792 	/*
10793 	 * Entering the squeue synchronously can result in a context switch,
10794 	 * which can cause a rather sever performance degradation. So we try to
10795 	 * handle whatever options we can without entering the squeue.
10796 	 */
10797 	if (level == IPPROTO_TCP) {
10798 		switch (option_name) {
10799 		case TCP_NODELAY:
10800 			if (optlen != sizeof (int32_t))
10801 				return (EINVAL);
10802 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
10803 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
10804 			    connp->conn_tcp->tcp_mss;
10805 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
10806 			return (0);
10807 		default:
10808 			break;
10809 		}
10810 	}
10811 
10812 	error = squeue_synch_enter(sqp, connp, 0);
10813 	if (error == ENOMEM) {
10814 		return (ENOMEM);
10815 	}
10816 
10817 	error = proto_opt_check(level, option_name, optlen, NULL,
10818 	    tcp_opt_obj.odb_opt_des_arr,
10819 	    tcp_opt_obj.odb_opt_arr_cnt,
10820 	    tcp_opt_obj.odb_topmost_tpiprovider,
10821 	    B_TRUE, B_FALSE, cr);
10822 
10823 	if (error != 0) {
10824 		if (error < 0) {
10825 			error = proto_tlitosyserr(-error);
10826 		}
10827 		squeue_synch_exit(sqp, connp);
10828 		return (error);
10829 	}
10830 
10831 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
10832 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
10833 	    NULL, cr, NULL);
10834 	squeue_synch_exit(sqp, connp);
10835 
10836 	if (error < 0) {
10837 		/*
10838 		 * Pass on to ip
10839 		 */
10840 		error = ip_set_options(connp, level, option_name, optvalp,
10841 		    optlen, cr);
10842 	}
10843 	return (error);
10844 }
10845 
10846 /*
10847  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10848  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10849  * headers, and the maximum size tcp header (to avoid reallocation
10850  * on the fly for additional tcp options).
10851  * Returns failure if can't allocate memory.
10852  */
10853 static int
10854 tcp_build_hdrs(tcp_t *tcp)
10855 {
10856 	char	*hdrs;
10857 	uint_t	hdrs_len;
10858 	ip6i_t	*ip6i;
10859 	char	buf[TCP_MAX_HDR_LENGTH];
10860 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10861 	in6_addr_t src, dst;
10862 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10863 	conn_t *connp = tcp->tcp_connp;
10864 
10865 	/*
10866 	 * save the existing tcp header and source/dest IP addresses
10867 	 */
10868 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10869 	src = tcp->tcp_ip6h->ip6_src;
10870 	dst = tcp->tcp_ip6h->ip6_dst;
10871 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10872 	ASSERT(hdrs_len != 0);
10873 	if (hdrs_len > tcp->tcp_iphc_len) {
10874 		/* Need to reallocate */
10875 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10876 		if (hdrs == NULL)
10877 			return (ENOMEM);
10878 		if (tcp->tcp_iphc != NULL) {
10879 			if (tcp->tcp_hdr_grown) {
10880 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10881 			} else {
10882 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10883 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10884 			}
10885 			tcp->tcp_iphc_len = 0;
10886 		}
10887 		ASSERT(tcp->tcp_iphc_len == 0);
10888 		tcp->tcp_iphc = hdrs;
10889 		tcp->tcp_iphc_len = hdrs_len;
10890 		tcp->tcp_hdr_grown = B_TRUE;
10891 	}
10892 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10893 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10894 
10895 	/* Set header fields not in ipp */
10896 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10897 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10898 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10899 	} else {
10900 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10901 	}
10902 	/*
10903 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10904 	 *
10905 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10906 	 */
10907 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10908 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10909 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10910 
10911 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10912 
10913 	tcp->tcp_ip6h->ip6_src = src;
10914 	tcp->tcp_ip6h->ip6_dst = dst;
10915 
10916 	/*
10917 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10918 	 * the default value for TCP.
10919 	 */
10920 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10921 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
10922 
10923 	/*
10924 	 * If we're setting extension headers after a connection
10925 	 * has been established, and if we have a routing header
10926 	 * among the extension headers, call ip_massage_options_v6 to
10927 	 * manipulate the routing header/ip6_dst set the checksum
10928 	 * difference in the tcp header template.
10929 	 * (This happens in tcp_connect_ipv6 if the routing header
10930 	 * is set prior to the connect.)
10931 	 * Set the tcp_sum to zero first in case we've cleared a
10932 	 * routing header or don't have one at all.
10933 	 */
10934 	tcp->tcp_sum = 0;
10935 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10936 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10937 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10938 		    (uint8_t *)tcp->tcp_tcph);
10939 		if (rth != NULL) {
10940 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10941 			    rth, tcps->tcps_netstack);
10942 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10943 			    (tcp->tcp_sum >> 16));
10944 		}
10945 	}
10946 
10947 	/* Try to get everything in a single mblk */
10948 	(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
10949 	    hdrs_len + tcps->tcps_wroff_xtra);
10950 	return (0);
10951 }
10952 
10953 /*
10954  * Transfer any source route option from ipha to buf/dst in reversed form.
10955  */
10956 static int
10957 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10958 {
10959 	ipoptp_t	opts;
10960 	uchar_t		*opt;
10961 	uint8_t		optval;
10962 	uint8_t		optlen;
10963 	uint32_t	len = 0;
10964 
10965 	for (optval = ipoptp_first(&opts, ipha);
10966 	    optval != IPOPT_EOL;
10967 	    optval = ipoptp_next(&opts)) {
10968 		opt = opts.ipoptp_cur;
10969 		optlen = opts.ipoptp_len;
10970 		switch (optval) {
10971 			int	off1, off2;
10972 		case IPOPT_SSRR:
10973 		case IPOPT_LSRR:
10974 
10975 			/* Reverse source route */
10976 			/*
10977 			 * First entry should be the next to last one in the
10978 			 * current source route (the last entry is our
10979 			 * address.)
10980 			 * The last entry should be the final destination.
10981 			 */
10982 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10983 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10984 			off1 = IPOPT_MINOFF_SR - 1;
10985 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10986 			if (off2 < 0) {
10987 				/* No entries in source route */
10988 				break;
10989 			}
10990 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10991 			/*
10992 			 * Note: use src since ipha has not had its src
10993 			 * and dst reversed (it is in the state it was
10994 			 * received.
10995 			 */
10996 			bcopy(&ipha->ipha_src, buf + off2,
10997 			    IP_ADDR_LEN);
10998 			off2 -= IP_ADDR_LEN;
10999 
11000 			while (off2 > 0) {
11001 				bcopy(opt + off2, buf + off1,
11002 				    IP_ADDR_LEN);
11003 				off1 += IP_ADDR_LEN;
11004 				off2 -= IP_ADDR_LEN;
11005 			}
11006 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11007 			buf += optlen;
11008 			len += optlen;
11009 			break;
11010 		}
11011 	}
11012 done:
11013 	/* Pad the resulting options */
11014 	while (len & 0x3) {
11015 		*buf++ = IPOPT_EOL;
11016 		len++;
11017 	}
11018 	return (len);
11019 }
11020 
11021 
11022 /*
11023  * Extract and revert a source route from ipha (if any)
11024  * and then update the relevant fields in both tcp_t and the standard header.
11025  */
11026 static void
11027 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11028 {
11029 	char	buf[TCP_MAX_HDR_LENGTH];
11030 	uint_t	tcph_len;
11031 	int	len;
11032 
11033 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11034 	len = IPH_HDR_LENGTH(ipha);
11035 	if (len == IP_SIMPLE_HDR_LENGTH)
11036 		/* Nothing to do */
11037 		return;
11038 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11039 	    (len & 0x3))
11040 		return;
11041 
11042 	tcph_len = tcp->tcp_tcp_hdr_len;
11043 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11044 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11045 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11046 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11047 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11048 	len += IP_SIMPLE_HDR_LENGTH;
11049 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11050 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11051 	if ((int)tcp->tcp_sum < 0)
11052 		tcp->tcp_sum--;
11053 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11054 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11055 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11056 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11057 	tcp->tcp_ip_hdr_len = len;
11058 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11059 	    (IP_VERSION << 4) | (len >> 2);
11060 	len += tcph_len;
11061 	tcp->tcp_hdr_len = len;
11062 }
11063 
11064 /*
11065  * Copy the standard header into its new location,
11066  * lay in the new options and then update the relevant
11067  * fields in both tcp_t and the standard header.
11068  */
11069 static int
11070 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11071 {
11072 	uint_t	tcph_len;
11073 	uint8_t	*ip_optp;
11074 	tcph_t	*new_tcph;
11075 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11076 	conn_t	*connp = tcp->tcp_connp;
11077 
11078 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11079 		return (EINVAL);
11080 
11081 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11082 		return (EINVAL);
11083 
11084 	if (checkonly) {
11085 		/*
11086 		 * do not really set, just pretend to - T_CHECK
11087 		 */
11088 		return (0);
11089 	}
11090 
11091 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11092 	if (tcp->tcp_label_len > 0) {
11093 		int padlen;
11094 		uint8_t opt;
11095 
11096 		/* convert list termination to no-ops */
11097 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11098 		ip_optp += ip_optp[IPOPT_OLEN];
11099 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11100 		while (--padlen >= 0)
11101 			*ip_optp++ = opt;
11102 	}
11103 	tcph_len = tcp->tcp_tcp_hdr_len;
11104 	new_tcph = (tcph_t *)(ip_optp + len);
11105 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11106 	tcp->tcp_tcph = new_tcph;
11107 	bcopy(ptr, ip_optp, len);
11108 
11109 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11110 
11111 	tcp->tcp_ip_hdr_len = len;
11112 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11113 	    (IP_VERSION << 4) | (len >> 2);
11114 	tcp->tcp_hdr_len = len + tcph_len;
11115 	if (!TCP_IS_DETACHED(tcp)) {
11116 		/* Always allocate room for all options. */
11117 		(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
11118 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11119 	}
11120 	return (0);
11121 }
11122 
11123 /* Get callback routine passed to nd_load by tcp_param_register */
11124 /* ARGSUSED */
11125 static int
11126 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11127 {
11128 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11129 
11130 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11131 	return (0);
11132 }
11133 
11134 /*
11135  * Walk through the param array specified registering each element with the
11136  * named dispatch handler.
11137  */
11138 static boolean_t
11139 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11140 {
11141 	for (; cnt-- > 0; tcppa++) {
11142 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11143 			if (!nd_load(ndp, tcppa->tcp_param_name,
11144 			    tcp_param_get, tcp_param_set,
11145 			    (caddr_t)tcppa)) {
11146 				nd_free(ndp);
11147 				return (B_FALSE);
11148 			}
11149 		}
11150 	}
11151 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11152 	    KM_SLEEP);
11153 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11154 	    sizeof (tcpparam_t));
11155 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11156 	    tcp_param_get, tcp_param_set_aligned,
11157 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11158 		nd_free(ndp);
11159 		return (B_FALSE);
11160 	}
11161 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11162 	    KM_SLEEP);
11163 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11164 	    sizeof (tcpparam_t));
11165 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11166 	    tcp_param_get, tcp_param_set_aligned,
11167 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11168 		nd_free(ndp);
11169 		return (B_FALSE);
11170 	}
11171 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11172 	    KM_SLEEP);
11173 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11174 	    sizeof (tcpparam_t));
11175 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11176 	    tcp_param_get, tcp_param_set_aligned,
11177 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11178 		nd_free(ndp);
11179 		return (B_FALSE);
11180 	}
11181 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11182 	    KM_SLEEP);
11183 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11184 	    sizeof (tcpparam_t));
11185 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11186 	    tcp_param_get, tcp_param_set_aligned,
11187 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11188 		nd_free(ndp);
11189 		return (B_FALSE);
11190 	}
11191 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11192 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11193 		nd_free(ndp);
11194 		return (B_FALSE);
11195 	}
11196 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11197 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11198 		nd_free(ndp);
11199 		return (B_FALSE);
11200 	}
11201 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11202 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11203 		nd_free(ndp);
11204 		return (B_FALSE);
11205 	}
11206 	if (!nd_load(ndp, "tcp_status", tcp_status_report, NULL,
11207 	    NULL)) {
11208 		nd_free(ndp);
11209 		return (B_FALSE);
11210 	}
11211 	if (!nd_load(ndp, "tcp_bind_hash", tcp_bind_hash_report,
11212 	    NULL, NULL)) {
11213 		nd_free(ndp);
11214 		return (B_FALSE);
11215 	}
11216 	if (!nd_load(ndp, "tcp_listen_hash",
11217 	    tcp_listen_hash_report, NULL, NULL)) {
11218 		nd_free(ndp);
11219 		return (B_FALSE);
11220 	}
11221 	if (!nd_load(ndp, "tcp_conn_hash", tcp_conn_hash_report,
11222 	    NULL, NULL)) {
11223 		nd_free(ndp);
11224 		return (B_FALSE);
11225 	}
11226 	if (!nd_load(ndp, "tcp_acceptor_hash",
11227 	    tcp_acceptor_hash_report, NULL, NULL)) {
11228 		nd_free(ndp);
11229 		return (B_FALSE);
11230 	}
11231 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11232 	    tcp_1948_phrase_set, NULL)) {
11233 		nd_free(ndp);
11234 		return (B_FALSE);
11235 	}
11236 	/*
11237 	 * Dummy ndd variables - only to convey obsolescence information
11238 	 * through printing of their name (no get or set routines)
11239 	 * XXX Remove in future releases ?
11240 	 */
11241 	if (!nd_load(ndp,
11242 	    "tcp_close_wait_interval(obsoleted - "
11243 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11244 		nd_free(ndp);
11245 		return (B_FALSE);
11246 	}
11247 	return (B_TRUE);
11248 }
11249 
11250 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11251 /* ARGSUSED */
11252 static int
11253 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11254     cred_t *cr)
11255 {
11256 	long new_value;
11257 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11258 
11259 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11260 	    new_value < tcppa->tcp_param_min ||
11261 	    new_value > tcppa->tcp_param_max) {
11262 		return (EINVAL);
11263 	}
11264 	/*
11265 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11266 	 * round it up.  For future 64 bit requirement, we actually make it
11267 	 * a multiple of 8.
11268 	 */
11269 	if (new_value & 0x7) {
11270 		new_value = (new_value & ~0x7) + 0x8;
11271 	}
11272 	tcppa->tcp_param_val = new_value;
11273 	return (0);
11274 }
11275 
11276 /* Set callback routine passed to nd_load by tcp_param_register */
11277 /* ARGSUSED */
11278 static int
11279 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11280 {
11281 	long	new_value;
11282 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11283 
11284 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11285 	    new_value < tcppa->tcp_param_min ||
11286 	    new_value > tcppa->tcp_param_max) {
11287 		return (EINVAL);
11288 	}
11289 	tcppa->tcp_param_val = new_value;
11290 	return (0);
11291 }
11292 
11293 /*
11294  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11295  * is filled, return as much as we can.  The message passed in may be
11296  * multi-part, chained using b_cont.  "start" is the starting sequence
11297  * number for this piece.
11298  */
11299 static mblk_t *
11300 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11301 {
11302 	uint32_t	end;
11303 	mblk_t		*mp1;
11304 	mblk_t		*mp2;
11305 	mblk_t		*next_mp;
11306 	uint32_t	u1;
11307 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11308 
11309 	/* Walk through all the new pieces. */
11310 	do {
11311 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11312 		    (uintptr_t)INT_MAX);
11313 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11314 		next_mp = mp->b_cont;
11315 		if (start == end) {
11316 			/* Empty.  Blast it. */
11317 			freeb(mp);
11318 			continue;
11319 		}
11320 		mp->b_cont = NULL;
11321 		TCP_REASS_SET_SEQ(mp, start);
11322 		TCP_REASS_SET_END(mp, end);
11323 		mp1 = tcp->tcp_reass_tail;
11324 		if (!mp1) {
11325 			tcp->tcp_reass_tail = mp;
11326 			tcp->tcp_reass_head = mp;
11327 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11328 			UPDATE_MIB(&tcps->tcps_mib,
11329 			    tcpInDataUnorderBytes, end - start);
11330 			continue;
11331 		}
11332 		/* New stuff completely beyond tail? */
11333 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11334 			/* Link it on end. */
11335 			mp1->b_cont = mp;
11336 			tcp->tcp_reass_tail = mp;
11337 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11338 			UPDATE_MIB(&tcps->tcps_mib,
11339 			    tcpInDataUnorderBytes, end - start);
11340 			continue;
11341 		}
11342 		mp1 = tcp->tcp_reass_head;
11343 		u1 = TCP_REASS_SEQ(mp1);
11344 		/* New stuff at the front? */
11345 		if (SEQ_LT(start, u1)) {
11346 			/* Yes... Check for overlap. */
11347 			mp->b_cont = mp1;
11348 			tcp->tcp_reass_head = mp;
11349 			tcp_reass_elim_overlap(tcp, mp);
11350 			continue;
11351 		}
11352 		/*
11353 		 * The new piece fits somewhere between the head and tail.
11354 		 * We find our slot, where mp1 precedes us and mp2 trails.
11355 		 */
11356 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11357 			u1 = TCP_REASS_SEQ(mp2);
11358 			if (SEQ_LEQ(start, u1))
11359 				break;
11360 		}
11361 		/* Link ourselves in */
11362 		mp->b_cont = mp2;
11363 		mp1->b_cont = mp;
11364 
11365 		/* Trim overlap with following mblk(s) first */
11366 		tcp_reass_elim_overlap(tcp, mp);
11367 
11368 		/* Trim overlap with preceding mblk */
11369 		tcp_reass_elim_overlap(tcp, mp1);
11370 
11371 	} while (start = end, mp = next_mp);
11372 	mp1 = tcp->tcp_reass_head;
11373 	/* Anything ready to go? */
11374 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11375 		return (NULL);
11376 	/* Eat what we can off the queue */
11377 	for (;;) {
11378 		mp = mp1->b_cont;
11379 		end = TCP_REASS_END(mp1);
11380 		TCP_REASS_SET_SEQ(mp1, 0);
11381 		TCP_REASS_SET_END(mp1, 0);
11382 		if (!mp) {
11383 			tcp->tcp_reass_tail = NULL;
11384 			break;
11385 		}
11386 		if (end != TCP_REASS_SEQ(mp)) {
11387 			mp1->b_cont = NULL;
11388 			break;
11389 		}
11390 		mp1 = mp;
11391 	}
11392 	mp1 = tcp->tcp_reass_head;
11393 	tcp->tcp_reass_head = mp;
11394 	return (mp1);
11395 }
11396 
11397 /* Eliminate any overlap that mp may have over later mblks */
11398 static void
11399 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11400 {
11401 	uint32_t	end;
11402 	mblk_t		*mp1;
11403 	uint32_t	u1;
11404 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11405 
11406 	end = TCP_REASS_END(mp);
11407 	while ((mp1 = mp->b_cont) != NULL) {
11408 		u1 = TCP_REASS_SEQ(mp1);
11409 		if (!SEQ_GT(end, u1))
11410 			break;
11411 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11412 			mp->b_wptr -= end - u1;
11413 			TCP_REASS_SET_END(mp, u1);
11414 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11415 			UPDATE_MIB(&tcps->tcps_mib,
11416 			    tcpInDataPartDupBytes, end - u1);
11417 			break;
11418 		}
11419 		mp->b_cont = mp1->b_cont;
11420 		TCP_REASS_SET_SEQ(mp1, 0);
11421 		TCP_REASS_SET_END(mp1, 0);
11422 		freeb(mp1);
11423 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11424 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11425 	}
11426 	if (!mp1)
11427 		tcp->tcp_reass_tail = mp;
11428 }
11429 
11430 static uint_t
11431 tcp_rwnd_reopen(tcp_t *tcp)
11432 {
11433 	uint_t ret = 0;
11434 	uint_t thwin;
11435 
11436 	/* Learn the latest rwnd information that we sent to the other side. */
11437 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11438 	    << tcp->tcp_rcv_ws;
11439 	/* This is peer's calculated send window (our receive window). */
11440 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11441 	/*
11442 	 * Increase the receive window to max.  But we need to do receiver
11443 	 * SWS avoidance.  This means that we need to check the increase of
11444 	 * of receive window is at least 1 MSS.
11445 	 */
11446 	if (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss) {
11447 		/*
11448 		 * If the window that the other side knows is less than max
11449 		 * deferred acks segments, send an update immediately.
11450 		 */
11451 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11452 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
11453 			ret = TH_ACK_NEEDED;
11454 		}
11455 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
11456 	}
11457 	return (ret);
11458 }
11459 
11460 /*
11461  * Send up all messages queued on tcp_rcv_list.
11462  */
11463 static uint_t
11464 tcp_rcv_drain(tcp_t *tcp)
11465 {
11466 	mblk_t *mp;
11467 	uint_t ret = 0;
11468 #ifdef DEBUG
11469 	uint_t cnt = 0;
11470 #endif
11471 	queue_t	*q = tcp->tcp_rq;
11472 
11473 	/* Can't drain on an eager connection */
11474 	if (tcp->tcp_listener != NULL)
11475 		return (ret);
11476 
11477 	/* Can't be a non-STREAMS connection or sodirect enabled */
11478 	ASSERT((!IPCL_IS_NONSTR(tcp->tcp_connp)) && SOD_NOT_ENABLED(tcp));
11479 
11480 	/* No need for the push timer now. */
11481 	if (tcp->tcp_push_tid != 0) {
11482 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11483 		tcp->tcp_push_tid = 0;
11484 	}
11485 
11486 	/*
11487 	 * Handle two cases here: we are currently fused or we were
11488 	 * previously fused and have some urgent data to be delivered
11489 	 * upstream.  The latter happens because we either ran out of
11490 	 * memory or were detached and therefore sending the SIGURG was
11491 	 * deferred until this point.  In either case we pass control
11492 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11493 	 * some work.
11494 	 */
11495 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11496 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
11497 		    tcp->tcp_fused_sigurg_mp != NULL);
11498 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11499 		    &tcp->tcp_fused_sigurg_mp))
11500 			return (ret);
11501 	}
11502 
11503 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11504 		tcp->tcp_rcv_list = mp->b_next;
11505 		mp->b_next = NULL;
11506 #ifdef DEBUG
11507 		cnt += msgdsize(mp);
11508 #endif
11509 		/* Does this need SSL processing first? */
11510 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11511 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11512 			    mblk_t *, mp);
11513 			tcp_kssl_input(tcp, mp);
11514 			continue;
11515 		}
11516 		putnext(q, mp);
11517 	}
11518 #ifdef DEBUG
11519 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11520 #endif
11521 	tcp->tcp_rcv_last_head = NULL;
11522 	tcp->tcp_rcv_last_tail = NULL;
11523 	tcp->tcp_rcv_cnt = 0;
11524 
11525 	if (canputnext(q))
11526 		return (tcp_rwnd_reopen(tcp));
11527 
11528 	return (ret);
11529 }
11530 
11531 /*
11532  * Queue data on tcp_rcv_list which is a b_next chain.
11533  * tcp_rcv_last_head/tail is the last element of this chain.
11534  * Each element of the chain is a b_cont chain.
11535  *
11536  * M_DATA messages are added to the current element.
11537  * Other messages are added as new (b_next) elements.
11538  */
11539 void
11540 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11541 {
11542 	ASSERT(seg_len == msgdsize(mp));
11543 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11544 
11545 	if (tcp->tcp_rcv_list == NULL) {
11546 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11547 		tcp->tcp_rcv_list = mp;
11548 		tcp->tcp_rcv_last_head = mp;
11549 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11550 		tcp->tcp_rcv_last_tail->b_cont = mp;
11551 	} else {
11552 		tcp->tcp_rcv_last_head->b_next = mp;
11553 		tcp->tcp_rcv_last_head = mp;
11554 	}
11555 
11556 	while (mp->b_cont)
11557 		mp = mp->b_cont;
11558 
11559 	tcp->tcp_rcv_last_tail = mp;
11560 	tcp->tcp_rcv_cnt += seg_len;
11561 	tcp->tcp_rwnd -= seg_len;
11562 }
11563 
11564 /*
11565  * The tcp_rcv_sod_XXX() functions enqueue data directly to the socket
11566  * above, in addition when uioa is enabled schedule an asynchronous uio
11567  * prior to enqueuing. They implement the combinhed semantics of the
11568  * tcp_rcv_XXX() functions, tcp_rcv_list push logic, and STREAMS putnext()
11569  * canputnext(), i.e. flow-control with backenable.
11570  *
11571  * tcp_sod_wakeup() is called where tcp_rcv_drain() would be called in the
11572  * non sodirect connection but as there are no tcp_tcv_list mblk_t's we deal
11573  * with the rcv_wnd and push timer and call the sodirect wakeup function.
11574  *
11575  * Must be called with sodp->sod_lockp held and will return with the lock
11576  * released.
11577  */
11578 static uint_t
11579 tcp_rcv_sod_wakeup(tcp_t *tcp, sodirect_t *sodp)
11580 {
11581 	queue_t		*q = tcp->tcp_rq;
11582 	uint_t		thwin;
11583 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11584 	uint_t		ret = 0;
11585 
11586 	/* Can't be an eager connection */
11587 	ASSERT(tcp->tcp_listener == NULL);
11588 
11589 	/* Caller must have lock held */
11590 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11591 
11592 	/* Sodirect mode so must not be a tcp_rcv_list */
11593 	ASSERT(tcp->tcp_rcv_list == NULL);
11594 
11595 	if (SOD_QFULL(sodp)) {
11596 		/* Q is full, mark Q for need backenable */
11597 		SOD_QSETBE(sodp);
11598 	}
11599 	/* Last advertised rwnd, i.e. rwnd last sent in a packet */
11600 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11601 	    << tcp->tcp_rcv_ws;
11602 	/* This is peer's calculated send window (our available rwnd). */
11603 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11604 	/*
11605 	 * Increase the receive window to max.  But we need to do receiver
11606 	 * SWS avoidance.  This means that we need to check the increase of
11607 	 * of receive window is at least 1 MSS.
11608 	 */
11609 	if (!SOD_QFULL(sodp) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11610 		/*
11611 		 * If the window that the other side knows is less than max
11612 		 * deferred acks segments, send an update immediately.
11613 		 */
11614 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11615 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11616 			ret = TH_ACK_NEEDED;
11617 		}
11618 		tcp->tcp_rwnd = q->q_hiwat;
11619 	}
11620 
11621 	if (!SOD_QEMPTY(sodp)) {
11622 		/* Wakeup to socket */
11623 		sodp->sod_state &= SOD_WAKE_CLR;
11624 		sodp->sod_state |= SOD_WAKE_DONE;
11625 		(sodp->sod_wakeup)(sodp);
11626 		/* wakeup() does the mutex_ext() */
11627 	} else {
11628 		/* Q is empty, no need to wake */
11629 		sodp->sod_state &= SOD_WAKE_CLR;
11630 		sodp->sod_state |= SOD_WAKE_NOT;
11631 		mutex_exit(sodp->sod_lockp);
11632 	}
11633 
11634 	/* No need for the push timer now. */
11635 	if (tcp->tcp_push_tid != 0) {
11636 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11637 		tcp->tcp_push_tid = 0;
11638 	}
11639 
11640 	return (ret);
11641 }
11642 
11643 /*
11644  * Called where tcp_rcv_enqueue()/putnext(RD(q)) would be. For M_DATA
11645  * mblk_t's if uioa enabled then start a uioa asynchronous copy directly
11646  * to the user-land buffer and flag the mblk_t as such.
11647  *
11648  * Also, handle tcp_rwnd.
11649  */
11650 uint_t
11651 tcp_rcv_sod_enqueue(tcp_t *tcp, sodirect_t *sodp, mblk_t *mp, uint_t seg_len)
11652 {
11653 	uioa_t		*uioap = &sodp->sod_uioa;
11654 	boolean_t	qfull;
11655 	uint_t		thwin;
11656 
11657 	/* Can't be an eager connection */
11658 	ASSERT(tcp->tcp_listener == NULL);
11659 
11660 	/* Caller must have lock held */
11661 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11662 
11663 	/* Sodirect mode so must not be a tcp_rcv_list */
11664 	ASSERT(tcp->tcp_rcv_list == NULL);
11665 
11666 	/* Passed in segment length must be equal to mblk_t chain data size */
11667 	ASSERT(seg_len == msgdsize(mp));
11668 
11669 	if (DB_TYPE(mp) != M_DATA) {
11670 		/* Only process M_DATA mblk_t's */
11671 		goto enq;
11672 	}
11673 	if (uioap->uioa_state & UIOA_ENABLED) {
11674 		/* Uioa is enabled */
11675 		mblk_t		*mp1 = mp;
11676 		mblk_t		*lmp = NULL;
11677 
11678 		if (seg_len > uioap->uio_resid) {
11679 			/*
11680 			 * There isn't enough uio space for the mblk_t chain
11681 			 * so disable uioa such that this and any additional
11682 			 * mblk_t data is handled by the socket and schedule
11683 			 * the socket for wakeup to finish this uioa.
11684 			 */
11685 			uioap->uioa_state &= UIOA_CLR;
11686 			uioap->uioa_state |= UIOA_FINI;
11687 			if (sodp->sod_state & SOD_WAKE_NOT) {
11688 				sodp->sod_state &= SOD_WAKE_CLR;
11689 				sodp->sod_state |= SOD_WAKE_NEED;
11690 			}
11691 			goto enq;
11692 		}
11693 		do {
11694 			uint32_t	len = MBLKL(mp1);
11695 
11696 			if (!uioamove(mp1->b_rptr, len, UIO_READ, uioap)) {
11697 				/* Scheduled, mark dblk_t as such */
11698 				DB_FLAGS(mp1) |= DBLK_UIOA;
11699 			} else {
11700 				/* Error, turn off async processing */
11701 				uioap->uioa_state &= UIOA_CLR;
11702 				uioap->uioa_state |= UIOA_FINI;
11703 				break;
11704 			}
11705 			lmp = mp1;
11706 		} while ((mp1 = mp1->b_cont) != NULL);
11707 
11708 		if (mp1 != NULL || uioap->uio_resid == 0) {
11709 			/*
11710 			 * Not all mblk_t(s) uioamoved (error) or all uio
11711 			 * space has been consumed so schedule the socket
11712 			 * for wakeup to finish this uio.
11713 			 */
11714 			sodp->sod_state &= SOD_WAKE_CLR;
11715 			sodp->sod_state |= SOD_WAKE_NEED;
11716 
11717 			/* Break the mblk chain if neccessary. */
11718 			if (mp1 != NULL && lmp != NULL) {
11719 				mp->b_next = mp1;
11720 				lmp->b_cont = NULL;
11721 			}
11722 		}
11723 	} else if (uioap->uioa_state & UIOA_FINI) {
11724 		/*
11725 		 * Post UIO_ENABLED waiting for socket to finish processing
11726 		 * so just enqueue and update tcp_rwnd.
11727 		 */
11728 		if (SOD_QFULL(sodp))
11729 			tcp->tcp_rwnd -= seg_len;
11730 	} else if (sodp->sod_want > 0) {
11731 		/*
11732 		 * Uioa isn't enabled but sodirect has a pending read().
11733 		 */
11734 		if (SOD_QCNT(sodp) + seg_len >= sodp->sod_want) {
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 		}
11742 	} else if (SOD_QCNT(sodp) + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
11743 		/*
11744 		 * No pending sodirect read() so used the default
11745 		 * TCP push logic to guess that a push is needed.
11746 		 */
11747 		if (sodp->sod_state & SOD_WAKE_NOT) {
11748 			/* Schedule socket for wakeup */
11749 			sodp->sod_state &= SOD_WAKE_CLR;
11750 			sodp->sod_state |= SOD_WAKE_NEED;
11751 		}
11752 		tcp->tcp_rwnd -= seg_len;
11753 	} else {
11754 		/* Just update tcp_rwnd */
11755 		tcp->tcp_rwnd -= seg_len;
11756 	}
11757 enq:
11758 	qfull = SOD_QFULL(sodp);
11759 
11760 	(sodp->sod_enqueue)(sodp, mp);
11761 
11762 	if (! qfull && SOD_QFULL(sodp)) {
11763 		/* Wasn't QFULL, now QFULL, need back-enable */
11764 		SOD_QSETBE(sodp);
11765 	}
11766 
11767 	/*
11768 	 * Check to see if remote avail swnd < mss due to delayed ACK,
11769 	 * first get advertised rwnd.
11770 	 */
11771 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win));
11772 	/* Minus delayed ACK count */
11773 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11774 	if (thwin < tcp->tcp_mss) {
11775 		/* Remote avail swnd < mss, need ACK now */
11776 		return (TH_ACK_NEEDED);
11777 	}
11778 
11779 	return (0);
11780 }
11781 
11782 /*
11783  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11784  *
11785  * This is the default entry function into TCP on the read side. TCP is
11786  * always entered via squeue i.e. using squeue's for mutual exclusion.
11787  * When classifier does a lookup to find the tcp, it also puts a reference
11788  * on the conn structure associated so the tcp is guaranteed to exist
11789  * when we come here. We still need to check the state because it might
11790  * as well has been closed. The squeue processing function i.e. squeue_enter,
11791  * is responsible for doing the CONN_DEC_REF.
11792  *
11793  * Apart from the default entry point, IP also sends packets directly to
11794  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11795  * connections.
11796  */
11797 boolean_t tcp_outbound_squeue_switch = B_FALSE;
11798 void
11799 tcp_input(void *arg, mblk_t *mp, void *arg2)
11800 {
11801 	conn_t	*connp = (conn_t *)arg;
11802 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11803 
11804 	/* arg2 is the sqp */
11805 	ASSERT(arg2 != NULL);
11806 	ASSERT(mp != NULL);
11807 
11808 	/*
11809 	 * Don't accept any input on a closed tcp as this TCP logically does
11810 	 * not exist on the system. Don't proceed further with this TCP.
11811 	 * For eg. this packet could trigger another close of this tcp
11812 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11813 	 * tcp_clean_death / tcp_closei_local must be called at most once
11814 	 * on a TCP. In this case we need to refeed the packet into the
11815 	 * classifier and figure out where the packet should go. Need to
11816 	 * preserve the recv_ill somehow. Until we figure that out, for
11817 	 * now just drop the packet if we can't classify the packet.
11818 	 */
11819 	if (tcp->tcp_state == TCPS_CLOSED ||
11820 	    tcp->tcp_state == TCPS_BOUND) {
11821 		conn_t	*new_connp;
11822 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11823 
11824 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11825 		if (new_connp != NULL) {
11826 			tcp_reinput(new_connp, mp, arg2);
11827 			return;
11828 		}
11829 		/* We failed to classify. For now just drop the packet */
11830 		freemsg(mp);
11831 		return;
11832 	}
11833 
11834 	if (DB_TYPE(mp) != M_DATA) {
11835 		tcp_rput_common(tcp, mp);
11836 		return;
11837 	}
11838 
11839 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
11840 		squeue_t	*final_sqp;
11841 
11842 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
11843 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
11844 		DB_CKSUMSTART(mp) = 0;
11845 		if (tcp->tcp_state == TCPS_SYN_SENT &&
11846 		    connp->conn_final_sqp == NULL &&
11847 		    tcp_outbound_squeue_switch) {
11848 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
11849 			connp->conn_final_sqp = final_sqp;
11850 			if (connp->conn_final_sqp != connp->conn_sqp) {
11851 				CONN_INC_REF(connp);
11852 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
11853 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
11854 				    tcp_rput_data, connp, ip_squeue_flag,
11855 				    SQTAG_CONNECT_FINISH);
11856 				return;
11857 			}
11858 		}
11859 	}
11860 	tcp_rput_data(connp, mp, arg2);
11861 }
11862 
11863 /*
11864  * The read side put procedure.
11865  * The packets passed up by ip are assume to be aligned according to
11866  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11867  */
11868 static void
11869 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11870 {
11871 	/*
11872 	 * tcp_rput_data() does not expect M_CTL except for the case
11873 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11874 	 * type. Need to make sure that any other M_CTLs don't make
11875 	 * it to tcp_rput_data since it is not expecting any and doesn't
11876 	 * check for it.
11877 	 */
11878 	if (DB_TYPE(mp) == M_CTL) {
11879 		switch (*(uint32_t *)(mp->b_rptr)) {
11880 		case TCP_IOC_ABORT_CONN:
11881 			/*
11882 			 * Handle connection abort request.
11883 			 */
11884 			tcp_ioctl_abort_handler(tcp, mp);
11885 			return;
11886 		case IPSEC_IN:
11887 			/*
11888 			 * Only secure icmp arrive in TCP and they
11889 			 * don't go through data path.
11890 			 */
11891 			tcp_icmp_error(tcp, mp);
11892 			return;
11893 		case IN_PKTINFO:
11894 			/*
11895 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11896 			 * sockets that are receiving IPv4 traffic. tcp
11897 			 */
11898 			ASSERT(tcp->tcp_family == AF_INET6);
11899 			ASSERT(tcp->tcp_ipv6_recvancillary &
11900 			    TCP_IPV6_RECVPKTINFO);
11901 			tcp_rput_data(tcp->tcp_connp, mp,
11902 			    tcp->tcp_connp->conn_sqp);
11903 			return;
11904 		case MDT_IOC_INFO_UPDATE:
11905 			/*
11906 			 * Handle Multidata information update; the
11907 			 * following routine will free the message.
11908 			 */
11909 			if (tcp->tcp_connp->conn_mdt_ok) {
11910 				tcp_mdt_update(tcp,
11911 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11912 				    B_FALSE);
11913 			}
11914 			freemsg(mp);
11915 			return;
11916 		case LSO_IOC_INFO_UPDATE:
11917 			/*
11918 			 * Handle LSO information update; the following
11919 			 * routine will free the message.
11920 			 */
11921 			if (tcp->tcp_connp->conn_lso_ok) {
11922 				tcp_lso_update(tcp,
11923 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11924 			}
11925 			freemsg(mp);
11926 			return;
11927 		default:
11928 			/*
11929 			 * tcp_icmp_err() will process the M_CTL packets.
11930 			 * Non-ICMP packets, if any, will be discarded in
11931 			 * tcp_icmp_err(). We will process the ICMP packet
11932 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11933 			 * incoming ICMP packet may result in changing
11934 			 * the tcp_mss, which we would need if we have
11935 			 * packets to retransmit.
11936 			 */
11937 			tcp_icmp_error(tcp, mp);
11938 			return;
11939 		}
11940 	}
11941 
11942 	/* No point processing the message if tcp is already closed */
11943 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11944 		freemsg(mp);
11945 		return;
11946 	}
11947 
11948 	tcp_rput_other(tcp, mp);
11949 }
11950 
11951 
11952 /* The minimum of smoothed mean deviation in RTO calculation. */
11953 #define	TCP_SD_MIN	400
11954 
11955 /*
11956  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11957  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11958  * are the same as those in Appendix A.2 of that paper.
11959  *
11960  * m = new measurement
11961  * sa = smoothed RTT average (8 * average estimates).
11962  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11963  */
11964 static void
11965 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11966 {
11967 	long m = TICK_TO_MSEC(rtt);
11968 	clock_t sa = tcp->tcp_rtt_sa;
11969 	clock_t sv = tcp->tcp_rtt_sd;
11970 	clock_t rto;
11971 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11972 
11973 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11974 	tcp->tcp_rtt_update++;
11975 
11976 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11977 	if (sa != 0) {
11978 		/*
11979 		 * Update average estimator:
11980 		 *	new rtt = 7/8 old rtt + 1/8 Error
11981 		 */
11982 
11983 		/* m is now Error in estimate. */
11984 		m -= sa >> 3;
11985 		if ((sa += m) <= 0) {
11986 			/*
11987 			 * Don't allow the smoothed average to be negative.
11988 			 * We use 0 to denote reinitialization of the
11989 			 * variables.
11990 			 */
11991 			sa = 1;
11992 		}
11993 
11994 		/*
11995 		 * Update deviation estimator:
11996 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11997 		 */
11998 		if (m < 0)
11999 			m = -m;
12000 		m -= sv >> 2;
12001 		sv += m;
12002 	} else {
12003 		/*
12004 		 * This follows BSD's implementation.  So the reinitialized
12005 		 * RTO is 3 * m.  We cannot go less than 2 because if the
12006 		 * link is bandwidth dominated, doubling the window size
12007 		 * during slow start means doubling the RTT.  We want to be
12008 		 * more conservative when we reinitialize our estimates.  3
12009 		 * is just a convenient number.
12010 		 */
12011 		sa = m << 3;
12012 		sv = m << 1;
12013 	}
12014 	if (sv < TCP_SD_MIN) {
12015 		/*
12016 		 * We do not know that if sa captures the delay ACK
12017 		 * effect as in a long train of segments, a receiver
12018 		 * does not delay its ACKs.  So set the minimum of sv
12019 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
12020 		 * of BSD DATO.  That means the minimum of mean
12021 		 * deviation is 100 ms.
12022 		 *
12023 		 */
12024 		sv = TCP_SD_MIN;
12025 	}
12026 	tcp->tcp_rtt_sa = sa;
12027 	tcp->tcp_rtt_sd = sv;
12028 	/*
12029 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
12030 	 *
12031 	 * Add tcp_rexmit_interval extra in case of extreme environment
12032 	 * where the algorithm fails to work.  The default value of
12033 	 * tcp_rexmit_interval_extra should be 0.
12034 	 *
12035 	 * As we use a finer grained clock than BSD and update
12036 	 * RTO for every ACKs, add in another .25 of RTT to the
12037 	 * deviation of RTO to accomodate burstiness of 1/4 of
12038 	 * window size.
12039 	 */
12040 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
12041 
12042 	if (rto > tcps->tcps_rexmit_interval_max) {
12043 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
12044 	} else if (rto < tcps->tcps_rexmit_interval_min) {
12045 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
12046 	} else {
12047 		tcp->tcp_rto = rto;
12048 	}
12049 
12050 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12051 	tcp->tcp_timer_backoff = 0;
12052 }
12053 
12054 /*
12055  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12056  * send queue which starts at the given seq. no.
12057  *
12058  * Parameters:
12059  *	tcp_t *tcp: the tcp instance pointer.
12060  *	uint32_t seq: the starting seq. no of the requested segment.
12061  *	int32_t *off: after the execution, *off will be the offset to
12062  *		the returned mblk which points to the requested seq no.
12063  *		It is the caller's responsibility to send in a non-null off.
12064  *
12065  * Return:
12066  *	A mblk_t pointer pointing to the requested segment in send queue.
12067  */
12068 static mblk_t *
12069 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12070 {
12071 	int32_t	cnt;
12072 	mblk_t	*mp;
12073 
12074 	/* Defensive coding.  Make sure we don't send incorrect data. */
12075 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12076 		return (NULL);
12077 
12078 	cnt = seq - tcp->tcp_suna;
12079 	mp = tcp->tcp_xmit_head;
12080 	while (cnt > 0 && mp != NULL) {
12081 		cnt -= mp->b_wptr - mp->b_rptr;
12082 		if (cnt < 0) {
12083 			cnt += mp->b_wptr - mp->b_rptr;
12084 			break;
12085 		}
12086 		mp = mp->b_cont;
12087 	}
12088 	ASSERT(mp != NULL);
12089 	*off = cnt;
12090 	return (mp);
12091 }
12092 
12093 /*
12094  * This function handles all retransmissions if SACK is enabled for this
12095  * connection.  First it calculates how many segments can be retransmitted
12096  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12097  * segments.  A segment is eligible if sack_cnt for that segment is greater
12098  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12099  * all eligible segments, it checks to see if TCP can send some new segments
12100  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12101  *
12102  * Parameters:
12103  *	tcp_t *tcp: the tcp structure of the connection.
12104  *	uint_t *flags: in return, appropriate value will be set for
12105  *	tcp_rput_data().
12106  */
12107 static void
12108 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12109 {
12110 	notsack_blk_t	*notsack_blk;
12111 	int32_t		usable_swnd;
12112 	int32_t		mss;
12113 	uint32_t	seg_len;
12114 	mblk_t		*xmit_mp;
12115 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12116 
12117 	ASSERT(tcp->tcp_sack_info != NULL);
12118 	ASSERT(tcp->tcp_notsack_list != NULL);
12119 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12120 
12121 	/* Defensive coding in case there is a bug... */
12122 	if (tcp->tcp_notsack_list == NULL) {
12123 		return;
12124 	}
12125 	notsack_blk = tcp->tcp_notsack_list;
12126 	mss = tcp->tcp_mss;
12127 
12128 	/*
12129 	 * Limit the num of outstanding data in the network to be
12130 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12131 	 */
12132 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12133 
12134 	/* At least retransmit 1 MSS of data. */
12135 	if (usable_swnd <= 0) {
12136 		usable_swnd = mss;
12137 	}
12138 
12139 	/* Make sure no new RTT samples will be taken. */
12140 	tcp->tcp_csuna = tcp->tcp_snxt;
12141 
12142 	notsack_blk = tcp->tcp_notsack_list;
12143 	while (usable_swnd > 0) {
12144 		mblk_t		*snxt_mp, *tmp_mp;
12145 		tcp_seq		begin = tcp->tcp_sack_snxt;
12146 		tcp_seq		end;
12147 		int32_t		off;
12148 
12149 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12150 			if (SEQ_GT(notsack_blk->end, begin) &&
12151 			    (notsack_blk->sack_cnt >=
12152 			    tcps->tcps_dupack_fast_retransmit)) {
12153 				end = notsack_blk->end;
12154 				if (SEQ_LT(begin, notsack_blk->begin)) {
12155 					begin = notsack_blk->begin;
12156 				}
12157 				break;
12158 			}
12159 		}
12160 		/*
12161 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12162 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12163 		 * set to tcp_cwnd_ssthresh.
12164 		 */
12165 		if (notsack_blk == NULL) {
12166 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12167 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12168 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12169 				ASSERT(tcp->tcp_cwnd > 0);
12170 				return;
12171 			} else {
12172 				usable_swnd = usable_swnd / mss;
12173 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12174 				    MAX(usable_swnd * mss, mss);
12175 				*flags |= TH_XMIT_NEEDED;
12176 				return;
12177 			}
12178 		}
12179 
12180 		/*
12181 		 * Note that we may send more than usable_swnd allows here
12182 		 * because of round off, but no more than 1 MSS of data.
12183 		 */
12184 		seg_len = end - begin;
12185 		if (seg_len > mss)
12186 			seg_len = mss;
12187 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12188 		ASSERT(snxt_mp != NULL);
12189 		/* This should not happen.  Defensive coding again... */
12190 		if (snxt_mp == NULL) {
12191 			return;
12192 		}
12193 
12194 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12195 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12196 		if (xmit_mp == NULL)
12197 			return;
12198 
12199 		usable_swnd -= seg_len;
12200 		tcp->tcp_pipe += seg_len;
12201 		tcp->tcp_sack_snxt = begin + seg_len;
12202 
12203 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12204 
12205 		/*
12206 		 * Update the send timestamp to avoid false retransmission.
12207 		 */
12208 		snxt_mp->b_prev = (mblk_t *)lbolt;
12209 
12210 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12211 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12212 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12213 		/*
12214 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12215 		 * This happens when new data sent during fast recovery is
12216 		 * also lost.  If TCP retransmits those new data, it needs
12217 		 * to extend SACK recover phase to avoid starting another
12218 		 * fast retransmit/recovery unnecessarily.
12219 		 */
12220 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12221 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12222 		}
12223 	}
12224 }
12225 
12226 /*
12227  * This function handles policy checking at TCP level for non-hard_bound/
12228  * detached connections.
12229  */
12230 static boolean_t
12231 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12232     boolean_t secure, boolean_t mctl_present)
12233 {
12234 	ipsec_latch_t *ipl = NULL;
12235 	ipsec_action_t *act = NULL;
12236 	mblk_t *data_mp;
12237 	ipsec_in_t *ii;
12238 	const char *reason;
12239 	kstat_named_t *counter;
12240 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12241 	ipsec_stack_t	*ipss;
12242 	ip_stack_t	*ipst;
12243 
12244 	ASSERT(mctl_present || !secure);
12245 
12246 	ASSERT((ipha == NULL && ip6h != NULL) ||
12247 	    (ip6h == NULL && ipha != NULL));
12248 
12249 	/*
12250 	 * We don't necessarily have an ipsec_in_act action to verify
12251 	 * policy because of assymetrical policy where we have only
12252 	 * outbound policy and no inbound policy (possible with global
12253 	 * policy).
12254 	 */
12255 	if (!secure) {
12256 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12257 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12258 			return (B_TRUE);
12259 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12260 		    "tcp_check_policy", ipha, ip6h, secure,
12261 		    tcps->tcps_netstack);
12262 		ipss = tcps->tcps_netstack->netstack_ipsec;
12263 
12264 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12265 		    DROPPER(ipss, ipds_tcp_clear),
12266 		    &tcps->tcps_dropper);
12267 		return (B_FALSE);
12268 	}
12269 
12270 	/*
12271 	 * We have a secure packet.
12272 	 */
12273 	if (act == NULL) {
12274 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12275 		    "tcp_check_policy", ipha, ip6h, secure,
12276 		    tcps->tcps_netstack);
12277 		ipss = tcps->tcps_netstack->netstack_ipsec;
12278 
12279 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12280 		    DROPPER(ipss, ipds_tcp_secure),
12281 		    &tcps->tcps_dropper);
12282 		return (B_FALSE);
12283 	}
12284 
12285 	/*
12286 	 * XXX This whole routine is currently incorrect.  ipl should
12287 	 * be set to the latch pointer, but is currently not set, so
12288 	 * we initialize it to NULL to avoid picking up random garbage.
12289 	 */
12290 	if (ipl == NULL)
12291 		return (B_TRUE);
12292 
12293 	data_mp = first_mp->b_cont;
12294 
12295 	ii = (ipsec_in_t *)first_mp->b_rptr;
12296 
12297 	ipst = tcps->tcps_netstack->netstack_ip;
12298 
12299 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12300 	    &counter, tcp->tcp_connp)) {
12301 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12302 		return (B_TRUE);
12303 	}
12304 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12305 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12306 	    reason);
12307 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12308 
12309 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12310 	    &tcps->tcps_dropper);
12311 	return (B_FALSE);
12312 }
12313 
12314 /*
12315  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12316  * retransmission after a timeout.
12317  *
12318  * To limit the number of duplicate segments, we limit the number of segment
12319  * to be sent in one time to tcp_snd_burst, the burst variable.
12320  */
12321 static void
12322 tcp_ss_rexmit(tcp_t *tcp)
12323 {
12324 	uint32_t	snxt;
12325 	uint32_t	smax;
12326 	int32_t		win;
12327 	int32_t		mss;
12328 	int32_t		off;
12329 	int32_t		burst = tcp->tcp_snd_burst;
12330 	mblk_t		*snxt_mp;
12331 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12332 
12333 	/*
12334 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12335 	 * all unack'ed segments.
12336 	 */
12337 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12338 		smax = tcp->tcp_rexmit_max;
12339 		snxt = tcp->tcp_rexmit_nxt;
12340 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12341 			snxt = tcp->tcp_suna;
12342 		}
12343 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12344 		win -= snxt - tcp->tcp_suna;
12345 		mss = tcp->tcp_mss;
12346 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12347 
12348 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12349 		    (burst > 0) && (snxt_mp != NULL)) {
12350 			mblk_t	*xmit_mp;
12351 			mblk_t	*old_snxt_mp = snxt_mp;
12352 			uint32_t cnt = mss;
12353 
12354 			if (win < cnt) {
12355 				cnt = win;
12356 			}
12357 			if (SEQ_GT(snxt + cnt, smax)) {
12358 				cnt = smax - snxt;
12359 			}
12360 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12361 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12362 			if (xmit_mp == NULL)
12363 				return;
12364 
12365 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12366 
12367 			snxt += cnt;
12368 			win -= cnt;
12369 			/*
12370 			 * Update the send timestamp to avoid false
12371 			 * retransmission.
12372 			 */
12373 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12374 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12375 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12376 
12377 			tcp->tcp_rexmit_nxt = snxt;
12378 			burst--;
12379 		}
12380 		/*
12381 		 * If we have transmitted all we have at the time
12382 		 * we started the retranmission, we can leave
12383 		 * the rest of the job to tcp_wput_data().  But we
12384 		 * need to check the send window first.  If the
12385 		 * win is not 0, go on with tcp_wput_data().
12386 		 */
12387 		if (SEQ_LT(snxt, smax) || win == 0) {
12388 			return;
12389 		}
12390 	}
12391 	/* Only call tcp_wput_data() if there is data to be sent. */
12392 	if (tcp->tcp_unsent) {
12393 		tcp_wput_data(tcp, NULL, B_FALSE);
12394 	}
12395 }
12396 
12397 /*
12398  * Process all TCP option in SYN segment.  Note that this function should
12399  * be called after tcp_adapt_ire() is called so that the necessary info
12400  * from IRE is already set in the tcp structure.
12401  *
12402  * This function sets up the correct tcp_mss value according to the
12403  * MSS option value and our header size.  It also sets up the window scale
12404  * and timestamp values, and initialize SACK info blocks.  But it does not
12405  * change receive window size after setting the tcp_mss value.  The caller
12406  * should do the appropriate change.
12407  */
12408 void
12409 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12410 {
12411 	int options;
12412 	tcp_opt_t tcpopt;
12413 	uint32_t mss_max;
12414 	char *tmp_tcph;
12415 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12416 
12417 	tcpopt.tcp = NULL;
12418 	options = tcp_parse_options(tcph, &tcpopt);
12419 
12420 	/*
12421 	 * Process MSS option.  Note that MSS option value does not account
12422 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12423 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12424 	 * IPv6.
12425 	 */
12426 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12427 		if (tcp->tcp_ipversion == IPV4_VERSION)
12428 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12429 		else
12430 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12431 	} else {
12432 		if (tcp->tcp_ipversion == IPV4_VERSION)
12433 			mss_max = tcps->tcps_mss_max_ipv4;
12434 		else
12435 			mss_max = tcps->tcps_mss_max_ipv6;
12436 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12437 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12438 		else if (tcpopt.tcp_opt_mss > mss_max)
12439 			tcpopt.tcp_opt_mss = mss_max;
12440 	}
12441 
12442 	/* Process Window Scale option. */
12443 	if (options & TCP_OPT_WSCALE_PRESENT) {
12444 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12445 		tcp->tcp_snd_ws_ok = B_TRUE;
12446 	} else {
12447 		tcp->tcp_snd_ws = B_FALSE;
12448 		tcp->tcp_snd_ws_ok = B_FALSE;
12449 		tcp->tcp_rcv_ws = B_FALSE;
12450 	}
12451 
12452 	/* Process Timestamp option. */
12453 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12454 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12455 		tmp_tcph = (char *)tcp->tcp_tcph;
12456 
12457 		tcp->tcp_snd_ts_ok = B_TRUE;
12458 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12459 		tcp->tcp_last_rcv_lbolt = lbolt64;
12460 		ASSERT(OK_32PTR(tmp_tcph));
12461 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12462 
12463 		/* Fill in our template header with basic timestamp option. */
12464 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12465 		tmp_tcph[0] = TCPOPT_NOP;
12466 		tmp_tcph[1] = TCPOPT_NOP;
12467 		tmp_tcph[2] = TCPOPT_TSTAMP;
12468 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12469 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12470 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12471 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12472 	} else {
12473 		tcp->tcp_snd_ts_ok = B_FALSE;
12474 	}
12475 
12476 	/*
12477 	 * Process SACK options.  If SACK is enabled for this connection,
12478 	 * then allocate the SACK info structure.  Note the following ways
12479 	 * when tcp_snd_sack_ok is set to true.
12480 	 *
12481 	 * For active connection: in tcp_adapt_ire() called in
12482 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12483 	 * is checked.
12484 	 *
12485 	 * For passive connection: in tcp_adapt_ire() called in
12486 	 * tcp_accept_comm().
12487 	 *
12488 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12489 	 * That check makes sure that if we did not send a SACK OK option,
12490 	 * we will not enable SACK for this connection even though the other
12491 	 * side sends us SACK OK option.  For active connection, the SACK
12492 	 * info structure has already been allocated.  So we need to free
12493 	 * it if SACK is disabled.
12494 	 */
12495 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12496 	    (tcp->tcp_snd_sack_ok ||
12497 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12498 		/* This should be true only in the passive case. */
12499 		if (tcp->tcp_sack_info == NULL) {
12500 			ASSERT(TCP_IS_DETACHED(tcp));
12501 			tcp->tcp_sack_info =
12502 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12503 		}
12504 		if (tcp->tcp_sack_info == NULL) {
12505 			tcp->tcp_snd_sack_ok = B_FALSE;
12506 		} else {
12507 			tcp->tcp_snd_sack_ok = B_TRUE;
12508 			if (tcp->tcp_snd_ts_ok) {
12509 				tcp->tcp_max_sack_blk = 3;
12510 			} else {
12511 				tcp->tcp_max_sack_blk = 4;
12512 			}
12513 		}
12514 	} else {
12515 		/*
12516 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12517 		 * no SACK info will be used for this
12518 		 * connection.  This assumes that SACK usage
12519 		 * permission is negotiated.  This may need
12520 		 * to be changed once this is clarified.
12521 		 */
12522 		if (tcp->tcp_sack_info != NULL) {
12523 			ASSERT(tcp->tcp_notsack_list == NULL);
12524 			kmem_cache_free(tcp_sack_info_cache,
12525 			    tcp->tcp_sack_info);
12526 			tcp->tcp_sack_info = NULL;
12527 		}
12528 		tcp->tcp_snd_sack_ok = B_FALSE;
12529 	}
12530 
12531 	/*
12532 	 * Now we know the exact TCP/IP header length, subtract
12533 	 * that from tcp_mss to get our side's MSS.
12534 	 */
12535 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12536 	/*
12537 	 * Here we assume that the other side's header size will be equal to
12538 	 * our header size.  We calculate the real MSS accordingly.  Need to
12539 	 * take into additional stuffs IPsec puts in.
12540 	 *
12541 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12542 	 */
12543 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12544 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12545 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12546 
12547 	/*
12548 	 * Set MSS to the smaller one of both ends of the connection.
12549 	 * We should not have called tcp_mss_set() before, but our
12550 	 * side of the MSS should have been set to a proper value
12551 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12552 	 * STREAM head parameters properly.
12553 	 *
12554 	 * If we have a larger-than-16-bit window but the other side
12555 	 * didn't want to do window scale, tcp_rwnd_set() will take
12556 	 * care of that.
12557 	 */
12558 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12559 }
12560 
12561 /*
12562  * Sends the T_CONN_IND to the listener. The caller calls this
12563  * functions via squeue to get inside the listener's perimeter
12564  * once the 3 way hand shake is done a T_CONN_IND needs to be
12565  * sent. As an optimization, the caller can call this directly
12566  * if listener's perimeter is same as eager's.
12567  */
12568 /* ARGSUSED */
12569 void
12570 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12571 {
12572 	conn_t			*lconnp = (conn_t *)arg;
12573 	tcp_t			*listener = lconnp->conn_tcp;
12574 	tcp_t			*tcp;
12575 	struct T_conn_ind	*conn_ind;
12576 	ipaddr_t 		*addr_cache;
12577 	boolean_t		need_send_conn_ind = B_FALSE;
12578 	tcp_stack_t		*tcps = listener->tcp_tcps;
12579 
12580 	/* retrieve the eager */
12581 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12582 	ASSERT(conn_ind->OPT_offset != 0 &&
12583 	    conn_ind->OPT_length == sizeof (intptr_t));
12584 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12585 	    conn_ind->OPT_length);
12586 
12587 	/*
12588 	 * TLI/XTI applications will get confused by
12589 	 * sending eager as an option since it violates
12590 	 * the option semantics. So remove the eager as
12591 	 * option since TLI/XTI app doesn't need it anyway.
12592 	 */
12593 	if (!TCP_IS_SOCKET(listener)) {
12594 		conn_ind->OPT_length = 0;
12595 		conn_ind->OPT_offset = 0;
12596 	}
12597 	if (listener->tcp_state == TCPS_CLOSED ||
12598 	    TCP_IS_DETACHED(listener)) {
12599 		/*
12600 		 * If listener has closed, it would have caused a
12601 		 * a cleanup/blowoff to happen for the eager. We
12602 		 * just need to return.
12603 		 */
12604 		freemsg(mp);
12605 		return;
12606 	}
12607 
12608 
12609 	/*
12610 	 * if the conn_req_q is full defer passing up the
12611 	 * T_CONN_IND until space is availabe after t_accept()
12612 	 * processing
12613 	 */
12614 	mutex_enter(&listener->tcp_eager_lock);
12615 
12616 	/*
12617 	 * Take the eager out, if it is in the list of droppable eagers
12618 	 * as we are here because the 3W handshake is over.
12619 	 */
12620 	MAKE_UNDROPPABLE(tcp);
12621 
12622 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12623 		tcp_t *tail;
12624 
12625 		/*
12626 		 * The eager already has an extra ref put in tcp_rput_data
12627 		 * so that it stays till accept comes back even though it
12628 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12629 		 */
12630 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12631 		listener->tcp_conn_req_cnt_q0--;
12632 		listener->tcp_conn_req_cnt_q++;
12633 
12634 		/* Move from SYN_RCVD to ESTABLISHED list  */
12635 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12636 		    tcp->tcp_eager_prev_q0;
12637 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12638 		    tcp->tcp_eager_next_q0;
12639 		tcp->tcp_eager_prev_q0 = NULL;
12640 		tcp->tcp_eager_next_q0 = NULL;
12641 
12642 		/*
12643 		 * Insert at end of the queue because sockfs
12644 		 * sends down T_CONN_RES in chronological
12645 		 * order. Leaving the older conn indications
12646 		 * at front of the queue helps reducing search
12647 		 * time.
12648 		 */
12649 		tail = listener->tcp_eager_last_q;
12650 		if (tail != NULL)
12651 			tail->tcp_eager_next_q = tcp;
12652 		else
12653 			listener->tcp_eager_next_q = tcp;
12654 		listener->tcp_eager_last_q = tcp;
12655 		tcp->tcp_eager_next_q = NULL;
12656 		/*
12657 		 * Delay sending up the T_conn_ind until we are
12658 		 * done with the eager. Once we have have sent up
12659 		 * the T_conn_ind, the accept can potentially complete
12660 		 * any time and release the refhold we have on the eager.
12661 		 */
12662 		need_send_conn_ind = B_TRUE;
12663 	} else {
12664 		/*
12665 		 * Defer connection on q0 and set deferred
12666 		 * connection bit true
12667 		 */
12668 		tcp->tcp_conn_def_q0 = B_TRUE;
12669 
12670 		/* take tcp out of q0 ... */
12671 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12672 		    tcp->tcp_eager_next_q0;
12673 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12674 		    tcp->tcp_eager_prev_q0;
12675 
12676 		/* ... and place it at the end of q0 */
12677 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12678 		tcp->tcp_eager_next_q0 = listener;
12679 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12680 		listener->tcp_eager_prev_q0 = tcp;
12681 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12682 	}
12683 
12684 	/* we have timed out before */
12685 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12686 		tcp->tcp_syn_rcvd_timeout = 0;
12687 		listener->tcp_syn_rcvd_timeout--;
12688 		if (listener->tcp_syn_defense &&
12689 		    listener->tcp_syn_rcvd_timeout <=
12690 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12691 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12692 		    listener->tcp_last_rcv_lbolt)) {
12693 			/*
12694 			 * Turn off the defense mode if we
12695 			 * believe the SYN attack is over.
12696 			 */
12697 			listener->tcp_syn_defense = B_FALSE;
12698 			if (listener->tcp_ip_addr_cache) {
12699 				kmem_free((void *)listener->tcp_ip_addr_cache,
12700 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12701 				listener->tcp_ip_addr_cache = NULL;
12702 			}
12703 		}
12704 	}
12705 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12706 	if (addr_cache != NULL) {
12707 		/*
12708 		 * We have finished a 3-way handshake with this
12709 		 * remote host. This proves the IP addr is good.
12710 		 * Cache it!
12711 		 */
12712 		addr_cache[IP_ADDR_CACHE_HASH(
12713 		    tcp->tcp_remote)] = tcp->tcp_remote;
12714 	}
12715 	mutex_exit(&listener->tcp_eager_lock);
12716 	if (need_send_conn_ind) {
12717 		if (IPCL_IS_NONSTR(lconnp)) {
12718 			ASSERT(tcp->tcp_listener == listener);
12719 			ASSERT(tcp->tcp_saved_listener == listener);
12720 			if ((*lconnp->conn_upcalls->su_newconn)
12721 			    (lconnp->conn_upper_handle,
12722 			    (sock_lower_handle_t)tcp->tcp_connp,
12723 			    &sock_tcp_downcalls, DB_CRED(mp), DB_CPID(mp),
12724 			    &tcp->tcp_connp->conn_upcalls) != NULL) {
12725 				/*
12726 				 * Keep the message around
12727 				 * in case of fallback
12728 				 */
12729 				tcp->tcp_conn.tcp_eager_conn_ind = mp;
12730 			} else {
12731 				freemsg(mp);
12732 			}
12733 		} else {
12734 			putnext(listener->tcp_rq, mp);
12735 		}
12736 	}
12737 }
12738 
12739 mblk_t *
12740 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12741     uint_t *ifindexp, ip6_pkt_t *ippp)
12742 {
12743 	ip_pktinfo_t	*pinfo;
12744 	ip6_t		*ip6h;
12745 	uchar_t		*rptr;
12746 	mblk_t		*first_mp = mp;
12747 	boolean_t	mctl_present = B_FALSE;
12748 	uint_t 		ifindex = 0;
12749 	ip6_pkt_t	ipp;
12750 	uint_t		ipvers;
12751 	uint_t		ip_hdr_len;
12752 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12753 
12754 	rptr = mp->b_rptr;
12755 	ASSERT(OK_32PTR(rptr));
12756 	ASSERT(tcp != NULL);
12757 	ipp.ipp_fields = 0;
12758 
12759 	switch DB_TYPE(mp) {
12760 	case M_CTL:
12761 		mp = mp->b_cont;
12762 		if (mp == NULL) {
12763 			freemsg(first_mp);
12764 			return (NULL);
12765 		}
12766 		if (DB_TYPE(mp) != M_DATA) {
12767 			freemsg(first_mp);
12768 			return (NULL);
12769 		}
12770 		mctl_present = B_TRUE;
12771 		break;
12772 	case M_DATA:
12773 		break;
12774 	default:
12775 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12776 		freemsg(mp);
12777 		return (NULL);
12778 	}
12779 	ipvers = IPH_HDR_VERSION(rptr);
12780 	if (ipvers == IPV4_VERSION) {
12781 		if (tcp == NULL) {
12782 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12783 			goto done;
12784 		}
12785 
12786 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12787 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12788 
12789 		/*
12790 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12791 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12792 		 */
12793 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12794 		    mctl_present) {
12795 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12796 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12797 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12798 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12799 				ipp.ipp_fields |= IPPF_IFINDEX;
12800 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12801 				ifindex = pinfo->ip_pkt_ifindex;
12802 			}
12803 			freeb(first_mp);
12804 			mctl_present = B_FALSE;
12805 		}
12806 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12807 	} else {
12808 		ip6h = (ip6_t *)rptr;
12809 
12810 		ASSERT(ipvers == IPV6_VERSION);
12811 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12812 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12813 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12814 
12815 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12816 			uint8_t	nexthdrp;
12817 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12818 
12819 			/* Look for ifindex information */
12820 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12821 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12822 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12823 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12824 					freemsg(first_mp);
12825 					return (NULL);
12826 				}
12827 
12828 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12829 					ASSERT(ip6i->ip6i_ifindex != 0);
12830 					ipp.ipp_fields |= IPPF_IFINDEX;
12831 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12832 					ifindex = ip6i->ip6i_ifindex;
12833 				}
12834 				rptr = (uchar_t *)&ip6i[1];
12835 				mp->b_rptr = rptr;
12836 				if (rptr == mp->b_wptr) {
12837 					mblk_t *mp1;
12838 					mp1 = mp->b_cont;
12839 					freeb(mp);
12840 					mp = mp1;
12841 					rptr = mp->b_rptr;
12842 				}
12843 				if (MBLKL(mp) < IPV6_HDR_LEN +
12844 				    sizeof (tcph_t)) {
12845 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12846 					freemsg(first_mp);
12847 					return (NULL);
12848 				}
12849 				ip6h = (ip6_t *)rptr;
12850 			}
12851 
12852 			/*
12853 			 * Find any potentially interesting extension headers
12854 			 * as well as the length of the IPv6 + extension
12855 			 * headers.
12856 			 */
12857 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12858 			/* Verify if this is a TCP packet */
12859 			if (nexthdrp != IPPROTO_TCP) {
12860 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12861 				freemsg(first_mp);
12862 				return (NULL);
12863 			}
12864 		} else {
12865 			ip_hdr_len = IPV6_HDR_LEN;
12866 		}
12867 	}
12868 
12869 done:
12870 	if (ipversp != NULL)
12871 		*ipversp = ipvers;
12872 	if (ip_hdr_lenp != NULL)
12873 		*ip_hdr_lenp = ip_hdr_len;
12874 	if (ippp != NULL)
12875 		*ippp = ipp;
12876 	if (ifindexp != NULL)
12877 		*ifindexp = ifindex;
12878 	if (mctl_present) {
12879 		freeb(first_mp);
12880 	}
12881 	return (mp);
12882 }
12883 
12884 /*
12885  * Handle M_DATA messages from IP. Its called directly from IP via
12886  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12887  * in this path.
12888  *
12889  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12890  * v4 and v6), we are called through tcp_input() and a M_CTL can
12891  * be present for options but tcp_find_pktinfo() deals with it. We
12892  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12893  *
12894  * The first argument is always the connp/tcp to which the mp belongs.
12895  * There are no exceptions to this rule. The caller has already put
12896  * a reference on this connp/tcp and once tcp_rput_data() returns,
12897  * the squeue will do the refrele.
12898  *
12899  * The TH_SYN for the listener directly go to tcp_conn_request via
12900  * squeue.
12901  *
12902  * sqp: NULL = recursive, sqp != NULL means called from squeue
12903  */
12904 void
12905 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12906 {
12907 	int32_t		bytes_acked;
12908 	int32_t		gap;
12909 	mblk_t		*mp1;
12910 	uint_t		flags;
12911 	uint32_t	new_swnd = 0;
12912 	uchar_t		*iphdr;
12913 	uchar_t		*rptr;
12914 	int32_t		rgap;
12915 	uint32_t	seg_ack;
12916 	int		seg_len;
12917 	uint_t		ip_hdr_len;
12918 	uint32_t	seg_seq;
12919 	tcph_t		*tcph;
12920 	int		urp;
12921 	tcp_opt_t	tcpopt;
12922 	uint_t		ipvers;
12923 	ip6_pkt_t	ipp;
12924 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12925 	uint32_t	cwnd;
12926 	uint32_t	add;
12927 	int		npkt;
12928 	int		mss;
12929 	conn_t		*connp = (conn_t *)arg;
12930 	squeue_t	*sqp = (squeue_t *)arg2;
12931 	tcp_t		*tcp = connp->conn_tcp;
12932 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12933 
12934 	/*
12935 	 * RST from fused tcp loopback peer should trigger an unfuse.
12936 	 */
12937 	if (tcp->tcp_fused) {
12938 		TCP_STAT(tcps, tcp_fusion_aborted);
12939 		tcp_unfuse(tcp);
12940 	}
12941 
12942 	iphdr = mp->b_rptr;
12943 	rptr = mp->b_rptr;
12944 	ASSERT(OK_32PTR(rptr));
12945 
12946 	/*
12947 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12948 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12949 	 * necessary information.
12950 	 */
12951 	if (IPCL_IS_TCP4(connp)) {
12952 		ipvers = IPV4_VERSION;
12953 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12954 	} else {
12955 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12956 		    NULL, &ipp);
12957 		if (mp == NULL) {
12958 			TCP_STAT(tcps, tcp_rput_v6_error);
12959 			return;
12960 		}
12961 		iphdr = mp->b_rptr;
12962 		rptr = mp->b_rptr;
12963 	}
12964 	ASSERT(DB_TYPE(mp) == M_DATA);
12965 	ASSERT(mp->b_next == NULL);
12966 
12967 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12968 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12969 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12970 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12971 	seg_len = (int)(mp->b_wptr - rptr) -
12972 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12973 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12974 		do {
12975 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12976 			    (uintptr_t)INT_MAX);
12977 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12978 		} while ((mp1 = mp1->b_cont) != NULL &&
12979 		    mp1->b_datap->db_type == M_DATA);
12980 	}
12981 
12982 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12983 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12984 		    seg_len, tcph);
12985 		return;
12986 	}
12987 
12988 	if (sqp != NULL) {
12989 		/*
12990 		 * This is the correct place to update tcp_last_recv_time. Note
12991 		 * that it is also updated for tcp structure that belongs to
12992 		 * global and listener queues which do not really need updating.
12993 		 * But that should not cause any harm.  And it is updated for
12994 		 * all kinds of incoming segments, not only for data segments.
12995 		 */
12996 		tcp->tcp_last_recv_time = lbolt;
12997 	}
12998 
12999 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13000 
13001 	BUMP_LOCAL(tcp->tcp_ibsegs);
13002 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13003 
13004 	if ((flags & TH_URG) && sqp != NULL) {
13005 		/*
13006 		 * TCP can't handle urgent pointers that arrive before
13007 		 * the connection has been accept()ed since it can't
13008 		 * buffer OOB data.  Discard segment if this happens.
13009 		 *
13010 		 * We can't just rely on a non-null tcp_listener to indicate
13011 		 * that the accept() has completed since unlinking of the
13012 		 * eager and completion of the accept are not atomic.
13013 		 * tcp_detached, when it is not set (B_FALSE) indicates
13014 		 * that the accept() has completed.
13015 		 *
13016 		 * Nor can it reassemble urgent pointers, so discard
13017 		 * if it's not the next segment expected.
13018 		 *
13019 		 * Otherwise, collapse chain into one mblk (discard if
13020 		 * that fails).  This makes sure the headers, retransmitted
13021 		 * data, and new data all are in the same mblk.
13022 		 */
13023 		ASSERT(mp != NULL);
13024 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
13025 			freemsg(mp);
13026 			return;
13027 		}
13028 		/* Update pointers into message */
13029 		iphdr = rptr = mp->b_rptr;
13030 		tcph = (tcph_t *)&rptr[ip_hdr_len];
13031 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
13032 			/*
13033 			 * Since we can't handle any data with this urgent
13034 			 * pointer that is out of sequence, we expunge
13035 			 * the data.  This allows us to still register
13036 			 * the urgent mark and generate the M_PCSIG,
13037 			 * which we can do.
13038 			 */
13039 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13040 			seg_len = 0;
13041 		}
13042 	}
13043 
13044 	switch (tcp->tcp_state) {
13045 	case TCPS_SYN_SENT:
13046 		if (flags & TH_ACK) {
13047 			/*
13048 			 * Note that our stack cannot send data before a
13049 			 * connection is established, therefore the
13050 			 * following check is valid.  Otherwise, it has
13051 			 * to be changed.
13052 			 */
13053 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13054 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13055 				freemsg(mp);
13056 				if (flags & TH_RST)
13057 					return;
13058 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13059 				    tcp, seg_ack, 0, TH_RST);
13060 				return;
13061 			}
13062 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13063 		}
13064 		if (flags & TH_RST) {
13065 			freemsg(mp);
13066 			if (flags & TH_ACK)
13067 				(void) tcp_clean_death(tcp,
13068 				    ECONNREFUSED, 13);
13069 			return;
13070 		}
13071 		if (!(flags & TH_SYN)) {
13072 			freemsg(mp);
13073 			return;
13074 		}
13075 
13076 		/* Process all TCP options. */
13077 		tcp_process_options(tcp, tcph);
13078 		/*
13079 		 * The following changes our rwnd to be a multiple of the
13080 		 * MIN(peer MSS, our MSS) for performance reason.
13081 		 */
13082 		(void) tcp_rwnd_set(tcp,
13083 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
13084 
13085 		/* Is the other end ECN capable? */
13086 		if (tcp->tcp_ecn_ok) {
13087 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13088 				tcp->tcp_ecn_ok = B_FALSE;
13089 			}
13090 		}
13091 		/*
13092 		 * Clear ECN flags because it may interfere with later
13093 		 * processing.
13094 		 */
13095 		flags &= ~(TH_ECE|TH_CWR);
13096 
13097 		tcp->tcp_irs = seg_seq;
13098 		tcp->tcp_rack = seg_seq;
13099 		tcp->tcp_rnxt = seg_seq + 1;
13100 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13101 		if (!TCP_IS_DETACHED(tcp)) {
13102 			/* Allocate room for SACK options if needed. */
13103 			if (tcp->tcp_snd_sack_ok) {
13104 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13105 				    tcp->tcp_hdr_len +
13106 				    TCPOPT_MAX_SACK_LEN +
13107 				    (tcp->tcp_loopback ? 0 :
13108 				    tcps->tcps_wroff_xtra));
13109 			} else {
13110 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13111 				    tcp->tcp_hdr_len +
13112 				    (tcp->tcp_loopback ? 0 :
13113 				    tcps->tcps_wroff_xtra));
13114 			}
13115 		}
13116 		if (flags & TH_ACK) {
13117 			/*
13118 			 * If we can't get the confirmation upstream, pretend
13119 			 * we didn't even see this one.
13120 			 *
13121 			 * XXX: how can we pretend we didn't see it if we
13122 			 * have updated rnxt et. al.
13123 			 *
13124 			 * For loopback we defer sending up the T_CONN_CON
13125 			 * until after some checks below.
13126 			 */
13127 			mp1 = NULL;
13128 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13129 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13130 				freemsg(mp);
13131 				return;
13132 			}
13133 			/* SYN was acked - making progress */
13134 			if (tcp->tcp_ipversion == IPV6_VERSION)
13135 				tcp->tcp_ip_forward_progress = B_TRUE;
13136 
13137 			/* One for the SYN */
13138 			tcp->tcp_suna = tcp->tcp_iss + 1;
13139 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13140 			tcp->tcp_state = TCPS_ESTABLISHED;
13141 
13142 			/*
13143 			 * If SYN was retransmitted, need to reset all
13144 			 * retransmission info.  This is because this
13145 			 * segment will be treated as a dup ACK.
13146 			 */
13147 			if (tcp->tcp_rexmit) {
13148 				tcp->tcp_rexmit = B_FALSE;
13149 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13150 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13151 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13152 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13153 				tcp->tcp_ms_we_have_waited = 0;
13154 
13155 				/*
13156 				 * Set tcp_cwnd back to 1 MSS, per
13157 				 * recommendation from
13158 				 * draft-floyd-incr-init-win-01.txt,
13159 				 * Increasing TCP's Initial Window.
13160 				 */
13161 				tcp->tcp_cwnd = tcp->tcp_mss;
13162 			}
13163 
13164 			tcp->tcp_swl1 = seg_seq;
13165 			tcp->tcp_swl2 = seg_ack;
13166 
13167 			new_swnd = BE16_TO_U16(tcph->th_win);
13168 			tcp->tcp_swnd = new_swnd;
13169 			if (new_swnd > tcp->tcp_max_swnd)
13170 				tcp->tcp_max_swnd = new_swnd;
13171 
13172 			/*
13173 			 * Always send the three-way handshake ack immediately
13174 			 * in order to make the connection complete as soon as
13175 			 * possible on the accepting host.
13176 			 */
13177 			flags |= TH_ACK_NEEDED;
13178 
13179 			/*
13180 			 * Special case for loopback.  At this point we have
13181 			 * received SYN-ACK from the remote endpoint.  In
13182 			 * order to ensure that both endpoints reach the
13183 			 * fused state prior to any data exchange, the final
13184 			 * ACK needs to be sent before we indicate T_CONN_CON
13185 			 * to the module upstream.
13186 			 */
13187 			if (tcp->tcp_loopback) {
13188 				mblk_t *ack_mp;
13189 
13190 				ASSERT(!tcp->tcp_unfusable);
13191 				ASSERT(mp1 != NULL);
13192 				/*
13193 				 * For loopback, we always get a pure SYN-ACK
13194 				 * and only need to send back the final ACK
13195 				 * with no data (this is because the other
13196 				 * tcp is ours and we don't do T/TCP).  This
13197 				 * final ACK triggers the passive side to
13198 				 * perform fusion in ESTABLISHED state.
13199 				 */
13200 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13201 					if (tcp->tcp_ack_tid != 0) {
13202 						(void) TCP_TIMER_CANCEL(tcp,
13203 						    tcp->tcp_ack_tid);
13204 						tcp->tcp_ack_tid = 0;
13205 					}
13206 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13207 					BUMP_LOCAL(tcp->tcp_obsegs);
13208 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13209 
13210 					if (!IPCL_IS_NONSTR(connp)) {
13211 						/* Send up T_CONN_CON */
13212 						putnext(tcp->tcp_rq, mp1);
13213 					} else {
13214 						(*connp->conn_upcalls->
13215 						    su_connected)
13216 						    (connp->conn_upper_handle,
13217 						    tcp->tcp_connid,
13218 						    DB_CRED(mp1),
13219 						    DB_CPID(mp1));
13220 						freemsg(mp1);
13221 					}
13222 
13223 					freemsg(mp);
13224 					return;
13225 				}
13226 				/*
13227 				 * Forget fusion; we need to handle more
13228 				 * complex cases below.  Send the deferred
13229 				 * T_CONN_CON message upstream and proceed
13230 				 * as usual.  Mark this tcp as not capable
13231 				 * of fusion.
13232 				 */
13233 				TCP_STAT(tcps, tcp_fusion_unfusable);
13234 				tcp->tcp_unfusable = B_TRUE;
13235 				if (!IPCL_IS_NONSTR(connp)) {
13236 					putnext(tcp->tcp_rq, mp1);
13237 				} else {
13238 					(*connp->conn_upcalls->su_connected)
13239 					    (connp->conn_upper_handle,
13240 					    tcp->tcp_connid, DB_CRED(mp1),
13241 					    DB_CPID(mp1));
13242 					freemsg(mp1);
13243 				}
13244 			}
13245 
13246 			/*
13247 			 * Check to see if there is data to be sent.  If
13248 			 * yes, set the transmit flag.  Then check to see
13249 			 * if received data processing needs to be done.
13250 			 * If not, go straight to xmit_check.  This short
13251 			 * cut is OK as we don't support T/TCP.
13252 			 */
13253 			if (tcp->tcp_unsent)
13254 				flags |= TH_XMIT_NEEDED;
13255 
13256 			if (seg_len == 0 && !(flags & TH_URG)) {
13257 				freemsg(mp);
13258 				goto xmit_check;
13259 			}
13260 
13261 			flags &= ~TH_SYN;
13262 			seg_seq++;
13263 			break;
13264 		}
13265 		tcp->tcp_state = TCPS_SYN_RCVD;
13266 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13267 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13268 		if (mp1) {
13269 			DB_CPID(mp1) = tcp->tcp_cpid;
13270 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13271 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13272 		}
13273 		freemsg(mp);
13274 		return;
13275 	case TCPS_SYN_RCVD:
13276 		if (flags & TH_ACK) {
13277 			/*
13278 			 * In this state, a SYN|ACK packet is either bogus
13279 			 * because the other side must be ACKing our SYN which
13280 			 * indicates it has seen the ACK for their SYN and
13281 			 * shouldn't retransmit it or we're crossing SYNs
13282 			 * on active open.
13283 			 */
13284 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13285 				freemsg(mp);
13286 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13287 				    tcp, seg_ack, 0, TH_RST);
13288 				return;
13289 			}
13290 			/*
13291 			 * NOTE: RFC 793 pg. 72 says this should be
13292 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13293 			 * but that would mean we have an ack that ignored
13294 			 * our SYN.
13295 			 */
13296 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13297 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13298 				freemsg(mp);
13299 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13300 				    tcp, seg_ack, 0, TH_RST);
13301 				return;
13302 			}
13303 		}
13304 		break;
13305 	case TCPS_LISTEN:
13306 		/*
13307 		 * Only a TLI listener can come through this path when a
13308 		 * acceptor is going back to be a listener and a packet
13309 		 * for the acceptor hits the classifier. For a socket
13310 		 * listener, this can never happen because a listener
13311 		 * can never accept connection on itself and hence a
13312 		 * socket acceptor can not go back to being a listener.
13313 		 */
13314 		ASSERT(!TCP_IS_SOCKET(tcp));
13315 		/*FALLTHRU*/
13316 	case TCPS_CLOSED:
13317 	case TCPS_BOUND: {
13318 		conn_t	*new_connp;
13319 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13320 
13321 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13322 		if (new_connp != NULL) {
13323 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13324 			return;
13325 		}
13326 		/* We failed to classify. For now just drop the packet */
13327 		freemsg(mp);
13328 		return;
13329 	}
13330 	case TCPS_IDLE:
13331 		/*
13332 		 * Handle the case where the tcp_clean_death() has happened
13333 		 * on a connection (application hasn't closed yet) but a packet
13334 		 * was already queued on squeue before tcp_clean_death()
13335 		 * was processed. Calling tcp_clean_death() twice on same
13336 		 * connection can result in weird behaviour.
13337 		 */
13338 		freemsg(mp);
13339 		return;
13340 	default:
13341 		break;
13342 	}
13343 
13344 	/*
13345 	 * Already on the correct queue/perimeter.
13346 	 * If this is a detached connection and not an eager
13347 	 * connection hanging off a listener then new data
13348 	 * (past the FIN) will cause a reset.
13349 	 * We do a special check here where it
13350 	 * is out of the main line, rather than check
13351 	 * if we are detached every time we see new
13352 	 * data down below.
13353 	 */
13354 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13355 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13356 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13357 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13358 
13359 		freemsg(mp);
13360 		/*
13361 		 * This could be an SSL closure alert. We're detached so just
13362 		 * acknowledge it this last time.
13363 		 */
13364 		if (tcp->tcp_kssl_ctx != NULL) {
13365 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13366 			tcp->tcp_kssl_ctx = NULL;
13367 
13368 			tcp->tcp_rnxt += seg_len;
13369 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13370 			flags |= TH_ACK_NEEDED;
13371 			goto ack_check;
13372 		}
13373 
13374 		tcp_xmit_ctl("new data when detached", tcp,
13375 		    tcp->tcp_snxt, 0, TH_RST);
13376 		(void) tcp_clean_death(tcp, EPROTO, 12);
13377 		return;
13378 	}
13379 
13380 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13381 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13382 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13383 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13384 
13385 	if (tcp->tcp_snd_ts_ok) {
13386 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13387 			/*
13388 			 * This segment is not acceptable.
13389 			 * Drop it and send back an ACK.
13390 			 */
13391 			freemsg(mp);
13392 			flags |= TH_ACK_NEEDED;
13393 			goto ack_check;
13394 		}
13395 	} else if (tcp->tcp_snd_sack_ok) {
13396 		ASSERT(tcp->tcp_sack_info != NULL);
13397 		tcpopt.tcp = tcp;
13398 		/*
13399 		 * SACK info in already updated in tcp_parse_options.  Ignore
13400 		 * all other TCP options...
13401 		 */
13402 		(void) tcp_parse_options(tcph, &tcpopt);
13403 	}
13404 try_again:;
13405 	mss = tcp->tcp_mss;
13406 	gap = seg_seq - tcp->tcp_rnxt;
13407 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13408 	/*
13409 	 * gap is the amount of sequence space between what we expect to see
13410 	 * and what we got for seg_seq.  A positive value for gap means
13411 	 * something got lost.  A negative value means we got some old stuff.
13412 	 */
13413 	if (gap < 0) {
13414 		/* Old stuff present.  Is the SYN in there? */
13415 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13416 		    (seg_len != 0)) {
13417 			flags &= ~TH_SYN;
13418 			seg_seq++;
13419 			urp--;
13420 			/* Recompute the gaps after noting the SYN. */
13421 			goto try_again;
13422 		}
13423 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13424 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13425 		    (seg_len > -gap ? -gap : seg_len));
13426 		/* Remove the old stuff from seg_len. */
13427 		seg_len += gap;
13428 		/*
13429 		 * Anything left?
13430 		 * Make sure to check for unack'd FIN when rest of data
13431 		 * has been previously ack'd.
13432 		 */
13433 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13434 			/*
13435 			 * Resets are only valid if they lie within our offered
13436 			 * window.  If the RST bit is set, we just ignore this
13437 			 * segment.
13438 			 */
13439 			if (flags & TH_RST) {
13440 				freemsg(mp);
13441 				return;
13442 			}
13443 
13444 			/*
13445 			 * The arriving of dup data packets indicate that we
13446 			 * may have postponed an ack for too long, or the other
13447 			 * side's RTT estimate is out of shape. Start acking
13448 			 * more often.
13449 			 */
13450 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13451 			    tcp->tcp_rack_cnt >= 1 &&
13452 			    tcp->tcp_rack_abs_max > 2) {
13453 				tcp->tcp_rack_abs_max--;
13454 			}
13455 			tcp->tcp_rack_cur_max = 1;
13456 
13457 			/*
13458 			 * This segment is "unacceptable".  None of its
13459 			 * sequence space lies within our advertized window.
13460 			 *
13461 			 * Adjust seg_len to the original value for tracing.
13462 			 */
13463 			seg_len -= gap;
13464 			if (tcp->tcp_debug) {
13465 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13466 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13467 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13468 				    "seg_len %d, rnxt %u, snxt %u, %s",
13469 				    gap, rgap, flags, seg_seq, seg_ack,
13470 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13471 				    tcp_display(tcp, NULL,
13472 				    DISP_ADDR_AND_PORT));
13473 			}
13474 
13475 			/*
13476 			 * Arrange to send an ACK in response to the
13477 			 * unacceptable segment per RFC 793 page 69. There
13478 			 * is only one small difference between ours and the
13479 			 * acceptability test in the RFC - we accept ACK-only
13480 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13481 			 * will be generated.
13482 			 *
13483 			 * Note that we have to ACK an ACK-only packet at least
13484 			 * for stacks that send 0-length keep-alives with
13485 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13486 			 * section 4.2.3.6. As long as we don't ever generate
13487 			 * an unacceptable packet in response to an incoming
13488 			 * packet that is unacceptable, it should not cause
13489 			 * "ACK wars".
13490 			 */
13491 			flags |=  TH_ACK_NEEDED;
13492 
13493 			/*
13494 			 * Continue processing this segment in order to use the
13495 			 * ACK information it contains, but skip all other
13496 			 * sequence-number processing.	Processing the ACK
13497 			 * information is necessary in order to
13498 			 * re-synchronize connections that may have lost
13499 			 * synchronization.
13500 			 *
13501 			 * We clear seg_len and flag fields related to
13502 			 * sequence number processing as they are not
13503 			 * to be trusted for an unacceptable segment.
13504 			 */
13505 			seg_len = 0;
13506 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13507 			goto process_ack;
13508 		}
13509 
13510 		/* Fix seg_seq, and chew the gap off the front. */
13511 		seg_seq = tcp->tcp_rnxt;
13512 		urp += gap;
13513 		do {
13514 			mblk_t	*mp2;
13515 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13516 			    (uintptr_t)UINT_MAX);
13517 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13518 			if (gap > 0) {
13519 				mp->b_rptr = mp->b_wptr - gap;
13520 				break;
13521 			}
13522 			mp2 = mp;
13523 			mp = mp->b_cont;
13524 			freeb(mp2);
13525 		} while (gap < 0);
13526 		/*
13527 		 * If the urgent data has already been acknowledged, we
13528 		 * should ignore TH_URG below
13529 		 */
13530 		if (urp < 0)
13531 			flags &= ~TH_URG;
13532 	}
13533 	/*
13534 	 * rgap is the amount of stuff received out of window.  A negative
13535 	 * value is the amount out of window.
13536 	 */
13537 	if (rgap < 0) {
13538 		mblk_t	*mp2;
13539 
13540 		if (tcp->tcp_rwnd == 0) {
13541 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13542 		} else {
13543 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13544 			UPDATE_MIB(&tcps->tcps_mib,
13545 			    tcpInDataPastWinBytes, -rgap);
13546 		}
13547 
13548 		/*
13549 		 * seg_len does not include the FIN, so if more than
13550 		 * just the FIN is out of window, we act like we don't
13551 		 * see it.  (If just the FIN is out of window, rgap
13552 		 * will be zero and we will go ahead and acknowledge
13553 		 * the FIN.)
13554 		 */
13555 		flags &= ~TH_FIN;
13556 
13557 		/* Fix seg_len and make sure there is something left. */
13558 		seg_len += rgap;
13559 		if (seg_len <= 0) {
13560 			/*
13561 			 * Resets are only valid if they lie within our offered
13562 			 * window.  If the RST bit is set, we just ignore this
13563 			 * segment.
13564 			 */
13565 			if (flags & TH_RST) {
13566 				freemsg(mp);
13567 				return;
13568 			}
13569 
13570 			/* Per RFC 793, we need to send back an ACK. */
13571 			flags |= TH_ACK_NEEDED;
13572 
13573 			/*
13574 			 * Send SIGURG as soon as possible i.e. even
13575 			 * if the TH_URG was delivered in a window probe
13576 			 * packet (which will be unacceptable).
13577 			 *
13578 			 * We generate a signal if none has been generated
13579 			 * for this connection or if this is a new urgent
13580 			 * byte. Also send a zero-length "unmarked" message
13581 			 * to inform SIOCATMARK that this is not the mark.
13582 			 *
13583 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13584 			 * is sent up. This plus the check for old data
13585 			 * (gap >= 0) handles the wraparound of the sequence
13586 			 * number space without having to always track the
13587 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13588 			 * this max in its rcv_up variable).
13589 			 *
13590 			 * This prevents duplicate SIGURGS due to a "late"
13591 			 * zero-window probe when the T_EXDATA_IND has already
13592 			 * been sent up.
13593 			 */
13594 			if ((flags & TH_URG) &&
13595 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13596 			    tcp->tcp_urp_last))) {
13597 				if (IPCL_IS_NONSTR(connp)) {
13598 					if (!TCP_IS_DETACHED(tcp)) {
13599 						(*connp->conn_upcalls->
13600 						    su_signal_oob)
13601 						    (connp->conn_upper_handle,
13602 						    urp);
13603 					}
13604 				} else {
13605 					mp1 = allocb(0, BPRI_MED);
13606 					if (mp1 == NULL) {
13607 						freemsg(mp);
13608 						return;
13609 					}
13610 					if (!TCP_IS_DETACHED(tcp) &&
13611 					    !putnextctl1(tcp->tcp_rq,
13612 					    M_PCSIG, SIGURG)) {
13613 						/* Try again on the rexmit. */
13614 						freemsg(mp1);
13615 						freemsg(mp);
13616 						return;
13617 					}
13618 					/*
13619 					 * If the next byte would be the mark
13620 					 * then mark with MARKNEXT else mark
13621 					 * with NOTMARKNEXT.
13622 					 */
13623 					if (gap == 0 && urp == 0)
13624 						mp1->b_flag |= MSGMARKNEXT;
13625 					else
13626 						mp1->b_flag |= MSGNOTMARKNEXT;
13627 					freemsg(tcp->tcp_urp_mark_mp);
13628 					tcp->tcp_urp_mark_mp = mp1;
13629 					flags |= TH_SEND_URP_MARK;
13630 				}
13631 				tcp->tcp_urp_last_valid = B_TRUE;
13632 				tcp->tcp_urp_last = urp + seg_seq;
13633 			}
13634 			/*
13635 			 * If this is a zero window probe, continue to
13636 			 * process the ACK part.  But we need to set seg_len
13637 			 * to 0 to avoid data processing.  Otherwise just
13638 			 * drop the segment and send back an ACK.
13639 			 */
13640 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13641 				flags &= ~(TH_SYN | TH_URG);
13642 				seg_len = 0;
13643 				goto process_ack;
13644 			} else {
13645 				freemsg(mp);
13646 				goto ack_check;
13647 			}
13648 		}
13649 		/* Pitch out of window stuff off the end. */
13650 		rgap = seg_len;
13651 		mp2 = mp;
13652 		do {
13653 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13654 			    (uintptr_t)INT_MAX);
13655 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13656 			if (rgap < 0) {
13657 				mp2->b_wptr += rgap;
13658 				if ((mp1 = mp2->b_cont) != NULL) {
13659 					mp2->b_cont = NULL;
13660 					freemsg(mp1);
13661 				}
13662 				break;
13663 			}
13664 		} while ((mp2 = mp2->b_cont) != NULL);
13665 	}
13666 ok:;
13667 	/*
13668 	 * TCP should check ECN info for segments inside the window only.
13669 	 * Therefore the check should be done here.
13670 	 */
13671 	if (tcp->tcp_ecn_ok) {
13672 		if (flags & TH_CWR) {
13673 			tcp->tcp_ecn_echo_on = B_FALSE;
13674 		}
13675 		/*
13676 		 * Note that both ECN_CE and CWR can be set in the
13677 		 * same segment.  In this case, we once again turn
13678 		 * on ECN_ECHO.
13679 		 */
13680 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13681 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13682 
13683 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13684 				tcp->tcp_ecn_echo_on = B_TRUE;
13685 			}
13686 		} else {
13687 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13688 
13689 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13690 			    htonl(IPH_ECN_CE << 20)) {
13691 				tcp->tcp_ecn_echo_on = B_TRUE;
13692 			}
13693 		}
13694 	}
13695 
13696 	/*
13697 	 * Check whether we can update tcp_ts_recent.  This test is
13698 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13699 	 * Extensions for High Performance: An Update", Internet Draft.
13700 	 */
13701 	if (tcp->tcp_snd_ts_ok &&
13702 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13703 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13704 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13705 		tcp->tcp_last_rcv_lbolt = lbolt64;
13706 	}
13707 
13708 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13709 		/*
13710 		 * FIN in an out of order segment.  We record this in
13711 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13712 		 * Clear the FIN so that any check on FIN flag will fail.
13713 		 * Remember that FIN also counts in the sequence number
13714 		 * space.  So we need to ack out of order FIN only segments.
13715 		 */
13716 		if (flags & TH_FIN) {
13717 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13718 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13719 			flags &= ~TH_FIN;
13720 			flags |= TH_ACK_NEEDED;
13721 		}
13722 		if (seg_len > 0) {
13723 			/* Fill in the SACK blk list. */
13724 			if (tcp->tcp_snd_sack_ok) {
13725 				ASSERT(tcp->tcp_sack_info != NULL);
13726 				tcp_sack_insert(tcp->tcp_sack_list,
13727 				    seg_seq, seg_seq + seg_len,
13728 				    &(tcp->tcp_num_sack_blk));
13729 			}
13730 
13731 			/*
13732 			 * Attempt reassembly and see if we have something
13733 			 * ready to go.
13734 			 */
13735 			mp = tcp_reass(tcp, mp, seg_seq);
13736 			/* Always ack out of order packets */
13737 			flags |= TH_ACK_NEEDED | TH_PUSH;
13738 			if (mp) {
13739 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13740 				    (uintptr_t)INT_MAX);
13741 				seg_len = mp->b_cont ? msgdsize(mp) :
13742 				    (int)(mp->b_wptr - mp->b_rptr);
13743 				seg_seq = tcp->tcp_rnxt;
13744 				/*
13745 				 * A gap is filled and the seq num and len
13746 				 * of the gap match that of a previously
13747 				 * received FIN, put the FIN flag back in.
13748 				 */
13749 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13750 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13751 					flags |= TH_FIN;
13752 					tcp->tcp_valid_bits &=
13753 					    ~TCP_OFO_FIN_VALID;
13754 				}
13755 			} else {
13756 				/*
13757 				 * Keep going even with NULL mp.
13758 				 * There may be a useful ACK or something else
13759 				 * we don't want to miss.
13760 				 *
13761 				 * But TCP should not perform fast retransmit
13762 				 * because of the ack number.  TCP uses
13763 				 * seg_len == 0 to determine if it is a pure
13764 				 * ACK.  And this is not a pure ACK.
13765 				 */
13766 				seg_len = 0;
13767 				ofo_seg = B_TRUE;
13768 			}
13769 		}
13770 	} else if (seg_len > 0) {
13771 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13772 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13773 		/*
13774 		 * If an out of order FIN was received before, and the seq
13775 		 * num and len of the new segment match that of the FIN,
13776 		 * put the FIN flag back in.
13777 		 */
13778 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13779 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13780 			flags |= TH_FIN;
13781 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13782 		}
13783 	}
13784 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13785 	if (flags & TH_RST) {
13786 		freemsg(mp);
13787 		switch (tcp->tcp_state) {
13788 		case TCPS_SYN_RCVD:
13789 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13790 			break;
13791 		case TCPS_ESTABLISHED:
13792 		case TCPS_FIN_WAIT_1:
13793 		case TCPS_FIN_WAIT_2:
13794 		case TCPS_CLOSE_WAIT:
13795 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13796 			break;
13797 		case TCPS_CLOSING:
13798 		case TCPS_LAST_ACK:
13799 			(void) tcp_clean_death(tcp, 0, 16);
13800 			break;
13801 		default:
13802 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13803 			(void) tcp_clean_death(tcp, ENXIO, 17);
13804 			break;
13805 		}
13806 		return;
13807 	}
13808 	if (flags & TH_SYN) {
13809 		/*
13810 		 * See RFC 793, Page 71
13811 		 *
13812 		 * The seq number must be in the window as it should
13813 		 * be "fixed" above.  If it is outside window, it should
13814 		 * be already rejected.  Note that we allow seg_seq to be
13815 		 * rnxt + rwnd because we want to accept 0 window probe.
13816 		 */
13817 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13818 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13819 		freemsg(mp);
13820 		/*
13821 		 * If the ACK flag is not set, just use our snxt as the
13822 		 * seq number of the RST segment.
13823 		 */
13824 		if (!(flags & TH_ACK)) {
13825 			seg_ack = tcp->tcp_snxt;
13826 		}
13827 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13828 		    TH_RST|TH_ACK);
13829 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13830 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13831 		return;
13832 	}
13833 	/*
13834 	 * urp could be -1 when the urp field in the packet is 0
13835 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13836 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13837 	 */
13838 	if (flags & TH_URG && urp >= 0) {
13839 		if (!tcp->tcp_urp_last_valid ||
13840 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13841 			if (IPCL_IS_NONSTR(connp)) {
13842 				if (!TCP_IS_DETACHED(tcp)) {
13843 					(*connp->conn_upcalls->su_signal_oob)
13844 					    (connp->conn_upper_handle, urp);
13845 				}
13846 			} else {
13847 				/*
13848 				 * If we haven't generated the signal yet for
13849 				 * this urgent pointer value, do it now.  Also,
13850 				 * send up a zero-length M_DATA indicating
13851 				 * whether or not this is the mark. The latter
13852 				 * is not needed when a T_EXDATA_IND is sent up.
13853 				 * However, if there are allocation failures
13854 				 * this code relies on the sender retransmitting
13855 				 * and the socket code for determining the mark
13856 				 * should not block waiting for the peer to
13857 				 * transmit. Thus, for simplicity we always
13858 				 * send up the mark indication.
13859 				 */
13860 				mp1 = allocb(0, BPRI_MED);
13861 				if (mp1 == NULL) {
13862 					freemsg(mp);
13863 					return;
13864 				}
13865 				if (!TCP_IS_DETACHED(tcp) &&
13866 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13867 				    SIGURG)) {
13868 					/* Try again on the rexmit. */
13869 					freemsg(mp1);
13870 					freemsg(mp);
13871 					return;
13872 				}
13873 				/*
13874 				 * Mark with NOTMARKNEXT for now.
13875 				 * The code below will change this to MARKNEXT
13876 				 * if we are at the mark.
13877 				 *
13878 				 * If there are allocation failures (e.g. in
13879 				 * dupmsg below) the next time tcp_rput_data
13880 				 * sees the urgent segment it will send up the
13881 				 * MSGMARKNEXT message.
13882 				 */
13883 				mp1->b_flag |= MSGNOTMARKNEXT;
13884 				freemsg(tcp->tcp_urp_mark_mp);
13885 				tcp->tcp_urp_mark_mp = mp1;
13886 				flags |= TH_SEND_URP_MARK;
13887 #ifdef DEBUG
13888 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13889 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13890 				    "last %x, %s",
13891 				    seg_seq, urp, tcp->tcp_urp_last,
13892 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13893 #endif /* DEBUG */
13894 			}
13895 			tcp->tcp_urp_last_valid = B_TRUE;
13896 			tcp->tcp_urp_last = urp + seg_seq;
13897 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13898 			/*
13899 			 * An allocation failure prevented the previous
13900 			 * tcp_rput_data from sending up the allocated
13901 			 * MSG*MARKNEXT message - send it up this time
13902 			 * around.
13903 			 */
13904 			flags |= TH_SEND_URP_MARK;
13905 		}
13906 
13907 		/*
13908 		 * If the urgent byte is in this segment, make sure that it is
13909 		 * all by itself.  This makes it much easier to deal with the
13910 		 * possibility of an allocation failure on the T_exdata_ind.
13911 		 * Note that seg_len is the number of bytes in the segment, and
13912 		 * urp is the offset into the segment of the urgent byte.
13913 		 * urp < seg_len means that the urgent byte is in this segment.
13914 		 */
13915 		if (urp < seg_len) {
13916 			if (seg_len != 1) {
13917 				uint32_t  tmp_rnxt;
13918 				/*
13919 				 * Break it up and feed it back in.
13920 				 * Re-attach the IP header.
13921 				 */
13922 				mp->b_rptr = iphdr;
13923 				if (urp > 0) {
13924 					/*
13925 					 * There is stuff before the urgent
13926 					 * byte.
13927 					 */
13928 					mp1 = dupmsg(mp);
13929 					if (!mp1) {
13930 						/*
13931 						 * Trim from urgent byte on.
13932 						 * The rest will come back.
13933 						 */
13934 						(void) adjmsg(mp,
13935 						    urp - seg_len);
13936 						tcp_rput_data(connp,
13937 						    mp, NULL);
13938 						return;
13939 					}
13940 					(void) adjmsg(mp1, urp - seg_len);
13941 					/* Feed this piece back in. */
13942 					tmp_rnxt = tcp->tcp_rnxt;
13943 					tcp_rput_data(connp, mp1, NULL);
13944 					/*
13945 					 * If the data passed back in was not
13946 					 * processed (ie: bad ACK) sending
13947 					 * the remainder back in will cause a
13948 					 * loop. In this case, drop the
13949 					 * packet and let the sender try
13950 					 * sending a good packet.
13951 					 */
13952 					if (tmp_rnxt == tcp->tcp_rnxt) {
13953 						freemsg(mp);
13954 						return;
13955 					}
13956 				}
13957 				if (urp != seg_len - 1) {
13958 					uint32_t  tmp_rnxt;
13959 					/*
13960 					 * There is stuff after the urgent
13961 					 * byte.
13962 					 */
13963 					mp1 = dupmsg(mp);
13964 					if (!mp1) {
13965 						/*
13966 						 * Trim everything beyond the
13967 						 * urgent byte.  The rest will
13968 						 * come back.
13969 						 */
13970 						(void) adjmsg(mp,
13971 						    urp + 1 - seg_len);
13972 						tcp_rput_data(connp,
13973 						    mp, NULL);
13974 						return;
13975 					}
13976 					(void) adjmsg(mp1, urp + 1 - seg_len);
13977 					tmp_rnxt = tcp->tcp_rnxt;
13978 					tcp_rput_data(connp, mp1, NULL);
13979 					/*
13980 					 * If the data passed back in was not
13981 					 * processed (ie: bad ACK) sending
13982 					 * the remainder back in will cause a
13983 					 * loop. In this case, drop the
13984 					 * packet and let the sender try
13985 					 * sending a good packet.
13986 					 */
13987 					if (tmp_rnxt == tcp->tcp_rnxt) {
13988 						freemsg(mp);
13989 						return;
13990 					}
13991 				}
13992 				tcp_rput_data(connp, mp, NULL);
13993 				return;
13994 			}
13995 			/*
13996 			 * This segment contains only the urgent byte.  We
13997 			 * have to allocate the T_exdata_ind, if we can.
13998 			 */
13999 			if (IPCL_IS_NONSTR(connp)) {
14000 				int error;
14001 
14002 				(*connp->conn_upcalls->su_recv)
14003 				    (connp->conn_upper_handle, mp, seg_len,
14004 				    MSG_OOB, &error, NULL);
14005 				mp = NULL;
14006 				goto update_ack;
14007 			} else if (!tcp->tcp_urp_mp) {
14008 				struct T_exdata_ind *tei;
14009 				mp1 = allocb(sizeof (struct T_exdata_ind),
14010 				    BPRI_MED);
14011 				if (!mp1) {
14012 					/*
14013 					 * Sigh... It'll be back.
14014 					 * Generate any MSG*MARK message now.
14015 					 */
14016 					freemsg(mp);
14017 					seg_len = 0;
14018 					if (flags & TH_SEND_URP_MARK) {
14019 
14020 
14021 						ASSERT(tcp->tcp_urp_mark_mp);
14022 						tcp->tcp_urp_mark_mp->b_flag &=
14023 						    ~MSGNOTMARKNEXT;
14024 						tcp->tcp_urp_mark_mp->b_flag |=
14025 						    MSGMARKNEXT;
14026 					}
14027 					goto ack_check;
14028 				}
14029 				mp1->b_datap->db_type = M_PROTO;
14030 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14031 				tei->PRIM_type = T_EXDATA_IND;
14032 				tei->MORE_flag = 0;
14033 				mp1->b_wptr = (uchar_t *)&tei[1];
14034 				tcp->tcp_urp_mp = mp1;
14035 #ifdef DEBUG
14036 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14037 				    "tcp_rput: allocated exdata_ind %s",
14038 				    tcp_display(tcp, NULL,
14039 				    DISP_PORT_ONLY));
14040 #endif /* DEBUG */
14041 				/*
14042 				 * There is no need to send a separate MSG*MARK
14043 				 * message since the T_EXDATA_IND will be sent
14044 				 * now.
14045 				 */
14046 				flags &= ~TH_SEND_URP_MARK;
14047 				freemsg(tcp->tcp_urp_mark_mp);
14048 				tcp->tcp_urp_mark_mp = NULL;
14049 			}
14050 			/*
14051 			 * Now we are all set.  On the next putnext upstream,
14052 			 * tcp_urp_mp will be non-NULL and will get prepended
14053 			 * to what has to be this piece containing the urgent
14054 			 * byte.  If for any reason we abort this segment below,
14055 			 * if it comes back, we will have this ready, or it
14056 			 * will get blown off in close.
14057 			 */
14058 		} else if (urp == seg_len) {
14059 			/*
14060 			 * The urgent byte is the next byte after this sequence
14061 			 * number. If there is data it is marked with
14062 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14063 			 * since it is not needed. Otherwise, if the code
14064 			 * above just allocated a zero-length tcp_urp_mark_mp
14065 			 * message, that message is tagged with MSGMARKNEXT.
14066 			 * Sending up these MSGMARKNEXT messages makes
14067 			 * SIOCATMARK work correctly even though
14068 			 * the T_EXDATA_IND will not be sent up until the
14069 			 * urgent byte arrives.
14070 			 */
14071 			if (seg_len != 0) {
14072 				flags |= TH_MARKNEXT_NEEDED;
14073 				freemsg(tcp->tcp_urp_mark_mp);
14074 				tcp->tcp_urp_mark_mp = NULL;
14075 				flags &= ~TH_SEND_URP_MARK;
14076 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14077 				flags |= TH_SEND_URP_MARK;
14078 				tcp->tcp_urp_mark_mp->b_flag &=
14079 				    ~MSGNOTMARKNEXT;
14080 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14081 			}
14082 #ifdef DEBUG
14083 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14084 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14085 			    seg_len, flags,
14086 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14087 #endif /* DEBUG */
14088 		}
14089 #ifdef DEBUG
14090 		else {
14091 			/* Data left until we hit mark */
14092 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14093 			    "tcp_rput: URP %d bytes left, %s",
14094 			    urp - seg_len, tcp_display(tcp, NULL,
14095 			    DISP_PORT_ONLY));
14096 		}
14097 #endif /* DEBUG */
14098 	}
14099 
14100 process_ack:
14101 	if (!(flags & TH_ACK)) {
14102 		freemsg(mp);
14103 		goto xmit_check;
14104 	}
14105 	}
14106 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14107 
14108 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14109 		tcp->tcp_ip_forward_progress = B_TRUE;
14110 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14111 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
14112 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
14113 			/* 3-way handshake complete - pass up the T_CONN_IND */
14114 			tcp_t	*listener = tcp->tcp_listener;
14115 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14116 
14117 			tcp->tcp_tconnind_started = B_TRUE;
14118 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14119 			/*
14120 			 * We are here means eager is fine but it can
14121 			 * get a TH_RST at any point between now and till
14122 			 * accept completes and disappear. We need to
14123 			 * ensure that reference to eager is valid after
14124 			 * we get out of eager's perimeter. So we do
14125 			 * an extra refhold.
14126 			 */
14127 			CONN_INC_REF(connp);
14128 
14129 			/*
14130 			 * The listener also exists because of the refhold
14131 			 * done in tcp_conn_request. Its possible that it
14132 			 * might have closed. We will check that once we
14133 			 * get inside listeners context.
14134 			 */
14135 			CONN_INC_REF(listener->tcp_connp);
14136 			if (listener->tcp_connp->conn_sqp ==
14137 			    connp->conn_sqp) {
14138 				/*
14139 				 * We optimize by not calling an SQUEUE_ENTER
14140 				 * on the listener since we know that the
14141 				 * listener and eager squeues are the same.
14142 				 * We are able to make this check safely only
14143 				 * because neither the eager nor the listener
14144 				 * can change its squeue. Only an active connect
14145 				 * can change its squeue
14146 				 */
14147 				tcp_send_conn_ind(listener->tcp_connp, mp,
14148 				    listener->tcp_connp->conn_sqp);
14149 				CONN_DEC_REF(listener->tcp_connp);
14150 			} else if (!tcp->tcp_loopback) {
14151 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14152 				    mp, tcp_send_conn_ind,
14153 				    listener->tcp_connp, SQ_FILL,
14154 				    SQTAG_TCP_CONN_IND);
14155 			} else {
14156 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14157 				    mp, tcp_send_conn_ind,
14158 				    listener->tcp_connp, SQ_PROCESS,
14159 				    SQTAG_TCP_CONN_IND);
14160 			}
14161 		}
14162 
14163 		if (tcp->tcp_active_open) {
14164 			/*
14165 			 * We are seeing the final ack in the three way
14166 			 * hand shake of a active open'ed connection
14167 			 * so we must send up a T_CONN_CON
14168 			 */
14169 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14170 				freemsg(mp);
14171 				return;
14172 			}
14173 			/*
14174 			 * Don't fuse the loopback endpoints for
14175 			 * simultaneous active opens.
14176 			 */
14177 			if (tcp->tcp_loopback) {
14178 				TCP_STAT(tcps, tcp_fusion_unfusable);
14179 				tcp->tcp_unfusable = B_TRUE;
14180 			}
14181 		}
14182 
14183 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14184 		bytes_acked--;
14185 		/* SYN was acked - making progress */
14186 		if (tcp->tcp_ipversion == IPV6_VERSION)
14187 			tcp->tcp_ip_forward_progress = B_TRUE;
14188 
14189 		/*
14190 		 * If SYN was retransmitted, need to reset all
14191 		 * retransmission info as this segment will be
14192 		 * treated as a dup ACK.
14193 		 */
14194 		if (tcp->tcp_rexmit) {
14195 			tcp->tcp_rexmit = B_FALSE;
14196 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14197 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14198 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14199 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14200 			tcp->tcp_ms_we_have_waited = 0;
14201 			tcp->tcp_cwnd = mss;
14202 		}
14203 
14204 		/*
14205 		 * We set the send window to zero here.
14206 		 * This is needed if there is data to be
14207 		 * processed already on the queue.
14208 		 * Later (at swnd_update label), the
14209 		 * "new_swnd > tcp_swnd" condition is satisfied
14210 		 * the XMIT_NEEDED flag is set in the current
14211 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14212 		 * called if there is already data on queue in
14213 		 * this state.
14214 		 */
14215 		tcp->tcp_swnd = 0;
14216 
14217 		if (new_swnd > tcp->tcp_max_swnd)
14218 			tcp->tcp_max_swnd = new_swnd;
14219 		tcp->tcp_swl1 = seg_seq;
14220 		tcp->tcp_swl2 = seg_ack;
14221 		tcp->tcp_state = TCPS_ESTABLISHED;
14222 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14223 
14224 		/* Fuse when both sides are in ESTABLISHED state */
14225 		if (tcp->tcp_loopback && do_tcp_fusion)
14226 			tcp_fuse(tcp, iphdr, tcph);
14227 
14228 	}
14229 	/* This code follows 4.4BSD-Lite2 mostly. */
14230 	if (bytes_acked < 0)
14231 		goto est;
14232 
14233 	/*
14234 	 * If TCP is ECN capable and the congestion experience bit is
14235 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14236 	 * done once per window (or more loosely, per RTT).
14237 	 */
14238 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14239 		tcp->tcp_cwr = B_FALSE;
14240 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14241 		if (!tcp->tcp_cwr) {
14242 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14243 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14244 			tcp->tcp_cwnd = npkt * mss;
14245 			/*
14246 			 * If the cwnd is 0, use the timer to clock out
14247 			 * new segments.  This is required by the ECN spec.
14248 			 */
14249 			if (npkt == 0) {
14250 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14251 				/*
14252 				 * This makes sure that when the ACK comes
14253 				 * back, we will increase tcp_cwnd by 1 MSS.
14254 				 */
14255 				tcp->tcp_cwnd_cnt = 0;
14256 			}
14257 			tcp->tcp_cwr = B_TRUE;
14258 			/*
14259 			 * This marks the end of the current window of in
14260 			 * flight data.  That is why we don't use
14261 			 * tcp_suna + tcp_swnd.  Only data in flight can
14262 			 * provide ECN info.
14263 			 */
14264 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14265 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14266 		}
14267 	}
14268 
14269 	mp1 = tcp->tcp_xmit_head;
14270 	if (bytes_acked == 0) {
14271 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14272 			int dupack_cnt;
14273 
14274 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14275 			/*
14276 			 * Fast retransmit.  When we have seen exactly three
14277 			 * identical ACKs while we have unacked data
14278 			 * outstanding we take it as a hint that our peer
14279 			 * dropped something.
14280 			 *
14281 			 * If TCP is retransmitting, don't do fast retransmit.
14282 			 */
14283 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14284 			    ! tcp->tcp_rexmit) {
14285 				/* Do Limited Transmit */
14286 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14287 				    tcps->tcps_dupack_fast_retransmit) {
14288 					/*
14289 					 * RFC 3042
14290 					 *
14291 					 * What we need to do is temporarily
14292 					 * increase tcp_cwnd so that new
14293 					 * data can be sent if it is allowed
14294 					 * by the receive window (tcp_rwnd).
14295 					 * tcp_wput_data() will take care of
14296 					 * the rest.
14297 					 *
14298 					 * If the connection is SACK capable,
14299 					 * only do limited xmit when there
14300 					 * is SACK info.
14301 					 *
14302 					 * Note how tcp_cwnd is incremented.
14303 					 * The first dup ACK will increase
14304 					 * it by 1 MSS.  The second dup ACK
14305 					 * will increase it by 2 MSS.  This
14306 					 * means that only 1 new segment will
14307 					 * be sent for each dup ACK.
14308 					 */
14309 					if (tcp->tcp_unsent > 0 &&
14310 					    (!tcp->tcp_snd_sack_ok ||
14311 					    (tcp->tcp_snd_sack_ok &&
14312 					    tcp->tcp_notsack_list != NULL))) {
14313 						tcp->tcp_cwnd += mss <<
14314 						    (tcp->tcp_dupack_cnt - 1);
14315 						flags |= TH_LIMIT_XMIT;
14316 					}
14317 				} else if (dupack_cnt ==
14318 				    tcps->tcps_dupack_fast_retransmit) {
14319 
14320 				/*
14321 				 * If we have reduced tcp_ssthresh
14322 				 * because of ECN, do not reduce it again
14323 				 * unless it is already one window of data
14324 				 * away.  After one window of data, tcp_cwr
14325 				 * should then be cleared.  Note that
14326 				 * for non ECN capable connection, tcp_cwr
14327 				 * should always be false.
14328 				 *
14329 				 * Adjust cwnd since the duplicate
14330 				 * ack indicates that a packet was
14331 				 * dropped (due to congestion.)
14332 				 */
14333 				if (!tcp->tcp_cwr) {
14334 					npkt = ((tcp->tcp_snxt -
14335 					    tcp->tcp_suna) >> 1) / mss;
14336 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14337 					    mss;
14338 					tcp->tcp_cwnd = (npkt +
14339 					    tcp->tcp_dupack_cnt) * mss;
14340 				}
14341 				if (tcp->tcp_ecn_ok) {
14342 					tcp->tcp_cwr = B_TRUE;
14343 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14344 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14345 				}
14346 
14347 				/*
14348 				 * We do Hoe's algorithm.  Refer to her
14349 				 * paper "Improving the Start-up Behavior
14350 				 * of a Congestion Control Scheme for TCP,"
14351 				 * appeared in SIGCOMM'96.
14352 				 *
14353 				 * Save highest seq no we have sent so far.
14354 				 * Be careful about the invisible FIN byte.
14355 				 */
14356 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14357 				    (tcp->tcp_unsent == 0)) {
14358 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14359 				} else {
14360 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14361 				}
14362 
14363 				/*
14364 				 * Do not allow bursty traffic during.
14365 				 * fast recovery.  Refer to Fall and Floyd's
14366 				 * paper "Simulation-based Comparisons of
14367 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14368 				 * This is a best current practise.
14369 				 */
14370 				tcp->tcp_snd_burst = TCP_CWND_SS;
14371 
14372 				/*
14373 				 * For SACK:
14374 				 * Calculate tcp_pipe, which is the
14375 				 * estimated number of bytes in
14376 				 * network.
14377 				 *
14378 				 * tcp_fack is the highest sack'ed seq num
14379 				 * TCP has received.
14380 				 *
14381 				 * tcp_pipe is explained in the above quoted
14382 				 * Fall and Floyd's paper.  tcp_fack is
14383 				 * explained in Mathis and Mahdavi's
14384 				 * "Forward Acknowledgment: Refining TCP
14385 				 * Congestion Control" in SIGCOMM '96.
14386 				 */
14387 				if (tcp->tcp_snd_sack_ok) {
14388 					ASSERT(tcp->tcp_sack_info != NULL);
14389 					if (tcp->tcp_notsack_list != NULL) {
14390 						tcp->tcp_pipe = tcp->tcp_snxt -
14391 						    tcp->tcp_fack;
14392 						tcp->tcp_sack_snxt = seg_ack;
14393 						flags |= TH_NEED_SACK_REXMIT;
14394 					} else {
14395 						/*
14396 						 * Always initialize tcp_pipe
14397 						 * even though we don't have
14398 						 * any SACK info.  If later
14399 						 * we get SACK info and
14400 						 * tcp_pipe is not initialized,
14401 						 * funny things will happen.
14402 						 */
14403 						tcp->tcp_pipe =
14404 						    tcp->tcp_cwnd_ssthresh;
14405 					}
14406 				} else {
14407 					flags |= TH_REXMIT_NEEDED;
14408 				} /* tcp_snd_sack_ok */
14409 
14410 				} else {
14411 					/*
14412 					 * Here we perform congestion
14413 					 * avoidance, but NOT slow start.
14414 					 * This is known as the Fast
14415 					 * Recovery Algorithm.
14416 					 */
14417 					if (tcp->tcp_snd_sack_ok &&
14418 					    tcp->tcp_notsack_list != NULL) {
14419 						flags |= TH_NEED_SACK_REXMIT;
14420 						tcp->tcp_pipe -= mss;
14421 						if (tcp->tcp_pipe < 0)
14422 							tcp->tcp_pipe = 0;
14423 					} else {
14424 					/*
14425 					 * We know that one more packet has
14426 					 * left the pipe thus we can update
14427 					 * cwnd.
14428 					 */
14429 					cwnd = tcp->tcp_cwnd + mss;
14430 					if (cwnd > tcp->tcp_cwnd_max)
14431 						cwnd = tcp->tcp_cwnd_max;
14432 					tcp->tcp_cwnd = cwnd;
14433 					if (tcp->tcp_unsent > 0)
14434 						flags |= TH_XMIT_NEEDED;
14435 					}
14436 				}
14437 			}
14438 		} else if (tcp->tcp_zero_win_probe) {
14439 			/*
14440 			 * If the window has opened, need to arrange
14441 			 * to send additional data.
14442 			 */
14443 			if (new_swnd != 0) {
14444 				/* tcp_suna != tcp_snxt */
14445 				/* Packet contains a window update */
14446 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14447 				tcp->tcp_zero_win_probe = 0;
14448 				tcp->tcp_timer_backoff = 0;
14449 				tcp->tcp_ms_we_have_waited = 0;
14450 
14451 				/*
14452 				 * Transmit starting with tcp_suna since
14453 				 * the one byte probe is not ack'ed.
14454 				 * If TCP has sent more than one identical
14455 				 * probe, tcp_rexmit will be set.  That means
14456 				 * tcp_ss_rexmit() will send out the one
14457 				 * byte along with new data.  Otherwise,
14458 				 * fake the retransmission.
14459 				 */
14460 				flags |= TH_XMIT_NEEDED;
14461 				if (!tcp->tcp_rexmit) {
14462 					tcp->tcp_rexmit = B_TRUE;
14463 					tcp->tcp_dupack_cnt = 0;
14464 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14465 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14466 				}
14467 			}
14468 		}
14469 		goto swnd_update;
14470 	}
14471 
14472 	/*
14473 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14474 	 * If the ACK value acks something that we have not yet sent, it might
14475 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14476 	 * other side.
14477 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14478 	 * state is handled above, so we can always just drop the segment and
14479 	 * send an ACK here.
14480 	 *
14481 	 * Should we send ACKs in response to ACK only segments?
14482 	 */
14483 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14484 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14485 		/* drop the received segment */
14486 		freemsg(mp);
14487 
14488 		/*
14489 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14490 		 * greater than 0, check if the number of such
14491 		 * bogus ACks is greater than that count.  If yes,
14492 		 * don't send back any ACK.  This prevents TCP from
14493 		 * getting into an ACK storm if somehow an attacker
14494 		 * successfully spoofs an acceptable segment to our
14495 		 * peer.
14496 		 */
14497 		if (tcp_drop_ack_unsent_cnt > 0 &&
14498 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14499 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14500 			return;
14501 		}
14502 		mp = tcp_ack_mp(tcp);
14503 		if (mp != NULL) {
14504 			BUMP_LOCAL(tcp->tcp_obsegs);
14505 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14506 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14507 		}
14508 		return;
14509 	}
14510 
14511 	/*
14512 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14513 	 * blocks that are covered by this ACK.
14514 	 */
14515 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14516 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14517 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14518 	}
14519 
14520 	/*
14521 	 * If we got an ACK after fast retransmit, check to see
14522 	 * if it is a partial ACK.  If it is not and the congestion
14523 	 * window was inflated to account for the other side's
14524 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14525 	 */
14526 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14527 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14528 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14529 			tcp->tcp_dupack_cnt = 0;
14530 			/*
14531 			 * Restore the orig tcp_cwnd_ssthresh after
14532 			 * fast retransmit phase.
14533 			 */
14534 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14535 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14536 			}
14537 			tcp->tcp_rexmit_max = seg_ack;
14538 			tcp->tcp_cwnd_cnt = 0;
14539 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14540 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14541 
14542 			/*
14543 			 * Remove all notsack info to avoid confusion with
14544 			 * the next fast retrasnmit/recovery phase.
14545 			 */
14546 			if (tcp->tcp_snd_sack_ok &&
14547 			    tcp->tcp_notsack_list != NULL) {
14548 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14549 			}
14550 		} else {
14551 			if (tcp->tcp_snd_sack_ok &&
14552 			    tcp->tcp_notsack_list != NULL) {
14553 				flags |= TH_NEED_SACK_REXMIT;
14554 				tcp->tcp_pipe -= mss;
14555 				if (tcp->tcp_pipe < 0)
14556 					tcp->tcp_pipe = 0;
14557 			} else {
14558 				/*
14559 				 * Hoe's algorithm:
14560 				 *
14561 				 * Retransmit the unack'ed segment and
14562 				 * restart fast recovery.  Note that we
14563 				 * need to scale back tcp_cwnd to the
14564 				 * original value when we started fast
14565 				 * recovery.  This is to prevent overly
14566 				 * aggressive behaviour in sending new
14567 				 * segments.
14568 				 */
14569 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14570 				    tcps->tcps_dupack_fast_retransmit * mss;
14571 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14572 				flags |= TH_REXMIT_NEEDED;
14573 			}
14574 		}
14575 	} else {
14576 		tcp->tcp_dupack_cnt = 0;
14577 		if (tcp->tcp_rexmit) {
14578 			/*
14579 			 * TCP is retranmitting.  If the ACK ack's all
14580 			 * outstanding data, update tcp_rexmit_max and
14581 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14582 			 * to the correct value.
14583 			 *
14584 			 * Note that SEQ_LEQ() is used.  This is to avoid
14585 			 * unnecessary fast retransmit caused by dup ACKs
14586 			 * received when TCP does slow start retransmission
14587 			 * after a time out.  During this phase, TCP may
14588 			 * send out segments which are already received.
14589 			 * This causes dup ACKs to be sent back.
14590 			 */
14591 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14592 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14593 					tcp->tcp_rexmit_nxt = seg_ack;
14594 				}
14595 				if (seg_ack != tcp->tcp_rexmit_max) {
14596 					flags |= TH_XMIT_NEEDED;
14597 				}
14598 			} else {
14599 				tcp->tcp_rexmit = B_FALSE;
14600 				tcp->tcp_xmit_zc_clean = B_FALSE;
14601 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14602 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14603 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14604 			}
14605 			tcp->tcp_ms_we_have_waited = 0;
14606 		}
14607 	}
14608 
14609 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14610 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14611 	tcp->tcp_suna = seg_ack;
14612 	if (tcp->tcp_zero_win_probe != 0) {
14613 		tcp->tcp_zero_win_probe = 0;
14614 		tcp->tcp_timer_backoff = 0;
14615 	}
14616 
14617 	/*
14618 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14619 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14620 	 * will not reach here.
14621 	 */
14622 	if (mp1 == NULL) {
14623 		goto fin_acked;
14624 	}
14625 
14626 	/*
14627 	 * Update the congestion window.
14628 	 *
14629 	 * If TCP is not ECN capable or TCP is ECN capable but the
14630 	 * congestion experience bit is not set, increase the tcp_cwnd as
14631 	 * usual.
14632 	 */
14633 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14634 		cwnd = tcp->tcp_cwnd;
14635 		add = mss;
14636 
14637 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14638 			/*
14639 			 * This is to prevent an increase of less than 1 MSS of
14640 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14641 			 * may send out tinygrams in order to preserve mblk
14642 			 * boundaries.
14643 			 *
14644 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14645 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14646 			 * increased by 1 MSS for every RTTs.
14647 			 */
14648 			if (tcp->tcp_cwnd_cnt <= 0) {
14649 				tcp->tcp_cwnd_cnt = cwnd + add;
14650 			} else {
14651 				tcp->tcp_cwnd_cnt -= add;
14652 				add = 0;
14653 			}
14654 		}
14655 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14656 	}
14657 
14658 	/* See if the latest urgent data has been acknowledged */
14659 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14660 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14661 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14662 
14663 	/* Can we update the RTT estimates? */
14664 	if (tcp->tcp_snd_ts_ok) {
14665 		/* Ignore zero timestamp echo-reply. */
14666 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14667 			tcp_set_rto(tcp, (int32_t)lbolt -
14668 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14669 		}
14670 
14671 		/* If needed, restart the timer. */
14672 		if (tcp->tcp_set_timer == 1) {
14673 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14674 			tcp->tcp_set_timer = 0;
14675 		}
14676 		/*
14677 		 * Update tcp_csuna in case the other side stops sending
14678 		 * us timestamps.
14679 		 */
14680 		tcp->tcp_csuna = tcp->tcp_snxt;
14681 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14682 		/*
14683 		 * An ACK sequence we haven't seen before, so get the RTT
14684 		 * and update the RTO. But first check if the timestamp is
14685 		 * valid to use.
14686 		 */
14687 		if ((mp1->b_next != NULL) &&
14688 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14689 			tcp_set_rto(tcp, (int32_t)lbolt -
14690 			    (int32_t)(intptr_t)mp1->b_prev);
14691 		else
14692 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14693 
14694 		/* Remeber the last sequence to be ACKed */
14695 		tcp->tcp_csuna = seg_ack;
14696 		if (tcp->tcp_set_timer == 1) {
14697 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14698 			tcp->tcp_set_timer = 0;
14699 		}
14700 	} else {
14701 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14702 	}
14703 
14704 	/* Eat acknowledged bytes off the xmit queue. */
14705 	for (;;) {
14706 		mblk_t	*mp2;
14707 		uchar_t	*wptr;
14708 
14709 		wptr = mp1->b_wptr;
14710 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14711 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14712 		if (bytes_acked < 0) {
14713 			mp1->b_rptr = wptr + bytes_acked;
14714 			/*
14715 			 * Set a new timestamp if all the bytes timed by the
14716 			 * old timestamp have been ack'ed.
14717 			 */
14718 			if (SEQ_GT(seg_ack,
14719 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14720 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14721 				mp1->b_next = NULL;
14722 			}
14723 			break;
14724 		}
14725 		mp1->b_next = NULL;
14726 		mp1->b_prev = NULL;
14727 		mp2 = mp1;
14728 		mp1 = mp1->b_cont;
14729 
14730 		/*
14731 		 * This notification is required for some zero-copy
14732 		 * clients to maintain a copy semantic. After the data
14733 		 * is ack'ed, client is safe to modify or reuse the buffer.
14734 		 */
14735 		if (tcp->tcp_snd_zcopy_aware &&
14736 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14737 			tcp_zcopy_notify(tcp);
14738 		freeb(mp2);
14739 		if (bytes_acked == 0) {
14740 			if (mp1 == NULL) {
14741 				/* Everything is ack'ed, clear the tail. */
14742 				tcp->tcp_xmit_tail = NULL;
14743 				/*
14744 				 * Cancel the timer unless we are still
14745 				 * waiting for an ACK for the FIN packet.
14746 				 */
14747 				if (tcp->tcp_timer_tid != 0 &&
14748 				    tcp->tcp_snxt == tcp->tcp_suna) {
14749 					(void) TCP_TIMER_CANCEL(tcp,
14750 					    tcp->tcp_timer_tid);
14751 					tcp->tcp_timer_tid = 0;
14752 				}
14753 				goto pre_swnd_update;
14754 			}
14755 			if (mp2 != tcp->tcp_xmit_tail)
14756 				break;
14757 			tcp->tcp_xmit_tail = mp1;
14758 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14759 			    (uintptr_t)INT_MAX);
14760 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14761 			    mp1->b_rptr);
14762 			break;
14763 		}
14764 		if (mp1 == NULL) {
14765 			/*
14766 			 * More was acked but there is nothing more
14767 			 * outstanding.  This means that the FIN was
14768 			 * just acked or that we're talking to a clown.
14769 			 */
14770 fin_acked:
14771 			ASSERT(tcp->tcp_fin_sent);
14772 			tcp->tcp_xmit_tail = NULL;
14773 			if (tcp->tcp_fin_sent) {
14774 				/* FIN was acked - making progress */
14775 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14776 				    !tcp->tcp_fin_acked)
14777 					tcp->tcp_ip_forward_progress = B_TRUE;
14778 				tcp->tcp_fin_acked = B_TRUE;
14779 				if (tcp->tcp_linger_tid != 0 &&
14780 				    TCP_TIMER_CANCEL(tcp,
14781 				    tcp->tcp_linger_tid) >= 0) {
14782 					tcp_stop_lingering(tcp);
14783 					freemsg(mp);
14784 					mp = NULL;
14785 				}
14786 			} else {
14787 				/*
14788 				 * We should never get here because
14789 				 * we have already checked that the
14790 				 * number of bytes ack'ed should be
14791 				 * smaller than or equal to what we
14792 				 * have sent so far (it is the
14793 				 * acceptability check of the ACK).
14794 				 * We can only get here if the send
14795 				 * queue is corrupted.
14796 				 *
14797 				 * Terminate the connection and
14798 				 * panic the system.  It is better
14799 				 * for us to panic instead of
14800 				 * continuing to avoid other disaster.
14801 				 */
14802 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14803 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14804 				panic("Memory corruption "
14805 				    "detected for connection %s.",
14806 				    tcp_display(tcp, NULL,
14807 				    DISP_ADDR_AND_PORT));
14808 				/*NOTREACHED*/
14809 			}
14810 			goto pre_swnd_update;
14811 		}
14812 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14813 	}
14814 	if (tcp->tcp_unsent) {
14815 		flags |= TH_XMIT_NEEDED;
14816 	}
14817 pre_swnd_update:
14818 	tcp->tcp_xmit_head = mp1;
14819 swnd_update:
14820 	/*
14821 	 * The following check is different from most other implementations.
14822 	 * For bi-directional transfer, when segments are dropped, the
14823 	 * "normal" check will not accept a window update in those
14824 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14825 	 * segments which are outside receiver's window.  As TCP accepts
14826 	 * the ack in those retransmitted segments, if the window update in
14827 	 * the same segment is not accepted, TCP will incorrectly calculates
14828 	 * that it can send more segments.  This can create a deadlock
14829 	 * with the receiver if its window becomes zero.
14830 	 */
14831 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14832 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14833 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14834 		/*
14835 		 * The criteria for update is:
14836 		 *
14837 		 * 1. the segment acknowledges some data.  Or
14838 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14839 		 * 3. the segment is not old and the advertised window is
14840 		 * larger than the previous advertised window.
14841 		 */
14842 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14843 			flags |= TH_XMIT_NEEDED;
14844 		tcp->tcp_swnd = new_swnd;
14845 		if (new_swnd > tcp->tcp_max_swnd)
14846 			tcp->tcp_max_swnd = new_swnd;
14847 		tcp->tcp_swl1 = seg_seq;
14848 		tcp->tcp_swl2 = seg_ack;
14849 	}
14850 est:
14851 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14852 
14853 		switch (tcp->tcp_state) {
14854 		case TCPS_FIN_WAIT_1:
14855 			if (tcp->tcp_fin_acked) {
14856 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14857 				/*
14858 				 * We implement the non-standard BSD/SunOS
14859 				 * FIN_WAIT_2 flushing algorithm.
14860 				 * If there is no user attached to this
14861 				 * TCP endpoint, then this TCP struct
14862 				 * could hang around forever in FIN_WAIT_2
14863 				 * state if the peer forgets to send us
14864 				 * a FIN.  To prevent this, we wait only
14865 				 * 2*MSL (a convenient time value) for
14866 				 * the FIN to arrive.  If it doesn't show up,
14867 				 * we flush the TCP endpoint.  This algorithm,
14868 				 * though a violation of RFC-793, has worked
14869 				 * for over 10 years in BSD systems.
14870 				 * Note: SunOS 4.x waits 675 seconds before
14871 				 * flushing the FIN_WAIT_2 connection.
14872 				 */
14873 				TCP_TIMER_RESTART(tcp,
14874 				    tcps->tcps_fin_wait_2_flush_interval);
14875 			}
14876 			break;
14877 		case TCPS_FIN_WAIT_2:
14878 			break;	/* Shutdown hook? */
14879 		case TCPS_LAST_ACK:
14880 			freemsg(mp);
14881 			if (tcp->tcp_fin_acked) {
14882 				(void) tcp_clean_death(tcp, 0, 19);
14883 				return;
14884 			}
14885 			goto xmit_check;
14886 		case TCPS_CLOSING:
14887 			if (tcp->tcp_fin_acked) {
14888 				tcp->tcp_state = TCPS_TIME_WAIT;
14889 				/*
14890 				 * Unconditionally clear the exclusive binding
14891 				 * bit so this TIME-WAIT connection won't
14892 				 * interfere with new ones.
14893 				 */
14894 				tcp->tcp_exclbind = 0;
14895 				if (!TCP_IS_DETACHED(tcp)) {
14896 					TCP_TIMER_RESTART(tcp,
14897 					    tcps->tcps_time_wait_interval);
14898 				} else {
14899 					tcp_time_wait_append(tcp);
14900 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14901 				}
14902 			}
14903 			/*FALLTHRU*/
14904 		case TCPS_CLOSE_WAIT:
14905 			freemsg(mp);
14906 			goto xmit_check;
14907 		default:
14908 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14909 			break;
14910 		}
14911 	}
14912 	if (flags & TH_FIN) {
14913 		/* Make sure we ack the fin */
14914 		flags |= TH_ACK_NEEDED;
14915 		if (!tcp->tcp_fin_rcvd) {
14916 			tcp->tcp_fin_rcvd = B_TRUE;
14917 			tcp->tcp_rnxt++;
14918 			tcph = tcp->tcp_tcph;
14919 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14920 
14921 			/*
14922 			 * Generate the ordrel_ind at the end unless we
14923 			 * are an eager guy.
14924 			 * In the eager case tcp_rsrv will do this when run
14925 			 * after tcp_accept is done.
14926 			 */
14927 			if (tcp->tcp_listener == NULL &&
14928 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14929 				flags |= TH_ORDREL_NEEDED;
14930 			switch (tcp->tcp_state) {
14931 			case TCPS_SYN_RCVD:
14932 			case TCPS_ESTABLISHED:
14933 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14934 				/* Keepalive? */
14935 				break;
14936 			case TCPS_FIN_WAIT_1:
14937 				if (!tcp->tcp_fin_acked) {
14938 					tcp->tcp_state = TCPS_CLOSING;
14939 					break;
14940 				}
14941 				/* FALLTHRU */
14942 			case TCPS_FIN_WAIT_2:
14943 				tcp->tcp_state = TCPS_TIME_WAIT;
14944 				/*
14945 				 * Unconditionally clear the exclusive binding
14946 				 * bit so this TIME-WAIT connection won't
14947 				 * interfere with new ones.
14948 				 */
14949 				tcp->tcp_exclbind = 0;
14950 				if (!TCP_IS_DETACHED(tcp)) {
14951 					TCP_TIMER_RESTART(tcp,
14952 					    tcps->tcps_time_wait_interval);
14953 				} else {
14954 					tcp_time_wait_append(tcp);
14955 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14956 				}
14957 				if (seg_len) {
14958 					/*
14959 					 * implies data piggybacked on FIN.
14960 					 * break to handle data.
14961 					 */
14962 					break;
14963 				}
14964 				freemsg(mp);
14965 				goto ack_check;
14966 			}
14967 		}
14968 	}
14969 	if (mp == NULL)
14970 		goto xmit_check;
14971 	if (seg_len == 0) {
14972 		freemsg(mp);
14973 		goto xmit_check;
14974 	}
14975 	if (mp->b_rptr == mp->b_wptr) {
14976 		/*
14977 		 * The header has been consumed, so we remove the
14978 		 * zero-length mblk here.
14979 		 */
14980 		mp1 = mp;
14981 		mp = mp->b_cont;
14982 		freeb(mp1);
14983 	}
14984 update_ack:
14985 	tcph = tcp->tcp_tcph;
14986 	tcp->tcp_rack_cnt++;
14987 	{
14988 		uint32_t cur_max;
14989 
14990 		cur_max = tcp->tcp_rack_cur_max;
14991 		if (tcp->tcp_rack_cnt >= cur_max) {
14992 			/*
14993 			 * We have more unacked data than we should - send
14994 			 * an ACK now.
14995 			 */
14996 			flags |= TH_ACK_NEEDED;
14997 			cur_max++;
14998 			if (cur_max > tcp->tcp_rack_abs_max)
14999 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15000 			else
15001 				tcp->tcp_rack_cur_max = cur_max;
15002 		} else if (TCP_IS_DETACHED(tcp)) {
15003 			/* We don't have an ACK timer for detached TCP. */
15004 			flags |= TH_ACK_NEEDED;
15005 		} else if (seg_len < mss) {
15006 			/*
15007 			 * If we get a segment that is less than an mss, and we
15008 			 * already have unacknowledged data, and the amount
15009 			 * unacknowledged is not a multiple of mss, then we
15010 			 * better generate an ACK now.  Otherwise, this may be
15011 			 * the tail piece of a transaction, and we would rather
15012 			 * wait for the response.
15013 			 */
15014 			uint32_t udif;
15015 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
15016 			    (uintptr_t)INT_MAX);
15017 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
15018 			if (udif && (udif % mss))
15019 				flags |= TH_ACK_NEEDED;
15020 			else
15021 				flags |= TH_ACK_TIMER_NEEDED;
15022 		} else {
15023 			/* Start delayed ack timer */
15024 			flags |= TH_ACK_TIMER_NEEDED;
15025 		}
15026 	}
15027 	tcp->tcp_rnxt += seg_len;
15028 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15029 
15030 	if (mp == NULL)
15031 		goto xmit_check;
15032 
15033 	/* Update SACK list */
15034 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15035 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15036 		    &(tcp->tcp_num_sack_blk));
15037 	}
15038 
15039 	if (tcp->tcp_urp_mp) {
15040 		tcp->tcp_urp_mp->b_cont = mp;
15041 		mp = tcp->tcp_urp_mp;
15042 		tcp->tcp_urp_mp = NULL;
15043 		/* Ready for a new signal. */
15044 		tcp->tcp_urp_last_valid = B_FALSE;
15045 #ifdef DEBUG
15046 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15047 		    "tcp_rput: sending exdata_ind %s",
15048 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15049 #endif /* DEBUG */
15050 	}
15051 
15052 	/*
15053 	 * Check for ancillary data changes compared to last segment.
15054 	 */
15055 	if (tcp->tcp_ipv6_recvancillary != 0) {
15056 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15057 		ASSERT(mp != NULL);
15058 	}
15059 
15060 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15061 		/*
15062 		 * Side queue inbound data until the accept happens.
15063 		 * tcp_accept/tcp_rput drains this when the accept happens.
15064 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15065 		 * T_EXDATA_IND) it is queued on b_next.
15066 		 * XXX Make urgent data use this. Requires:
15067 		 *	Removing tcp_listener check for TH_URG
15068 		 *	Making M_PCPROTO and MARK messages skip the eager case
15069 		 */
15070 
15071 		if (tcp->tcp_kssl_pending) {
15072 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
15073 			    mblk_t *, mp);
15074 			tcp_kssl_input(tcp, mp);
15075 		} else {
15076 			tcp_rcv_enqueue(tcp, mp, seg_len);
15077 		}
15078 	} else {
15079 		sodirect_t	*sodp = tcp->tcp_sodirect;
15080 
15081 		/*
15082 		 * If an sodirect connection and an enabled sodirect_t then
15083 		 * sodp will be set to point to the tcp_t/sonode_t shared
15084 		 * sodirect_t and the sodirect_t's lock will be held.
15085 		 */
15086 		if (sodp != NULL) {
15087 			mutex_enter(sodp->sod_lockp);
15088 			if (!(sodp->sod_state & SOD_ENABLED) ||
15089 			    (tcp->tcp_kssl_ctx != NULL &&
15090 			    DB_TYPE(mp) == M_DATA)) {
15091 				sodp = NULL;
15092 			}
15093 			mutex_exit(sodp->sod_lockp);
15094 		}
15095 		if (mp->b_datap->db_type != M_DATA ||
15096 		    (flags & TH_MARKNEXT_NEEDED)) {
15097 			if (IPCL_IS_NONSTR(connp)) {
15098 				int error;
15099 
15100 				if ((*connp->conn_upcalls->su_recv)
15101 				    (connp->conn_upper_handle, mp,
15102 				    seg_len, 0, &error, NULL) <= 0) {
15103 					if (error == ENOSPC) {
15104 						tcp->tcp_rwnd -= seg_len;
15105 					} else if (error == EOPNOTSUPP) {
15106 						tcp_rcv_enqueue(tcp, mp,
15107 						    seg_len);
15108 					}
15109 				}
15110 			} else if (sodp != NULL) {
15111 				mutex_enter(sodp->sod_lockp);
15112 				SOD_UIOAFINI(sodp);
15113 				if (!SOD_QEMPTY(sodp) &&
15114 				    (sodp->sod_state & SOD_WAKE_NOT)) {
15115 					flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15116 					/* sod_wakeup() did the mutex_exit() */
15117 				} else {
15118 					mutex_exit(sodp->sod_lockp);
15119 				}
15120 			} else if (tcp->tcp_rcv_list != NULL) {
15121 				flags |= tcp_rcv_drain(tcp);
15122 			}
15123 			ASSERT(tcp->tcp_rcv_list == NULL ||
15124 			    tcp->tcp_fused_sigurg);
15125 
15126 			if (flags & TH_MARKNEXT_NEEDED) {
15127 #ifdef DEBUG
15128 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15129 				    "tcp_rput: sending MSGMARKNEXT %s",
15130 				    tcp_display(tcp, NULL,
15131 				    DISP_PORT_ONLY));
15132 #endif /* DEBUG */
15133 				mp->b_flag |= MSGMARKNEXT;
15134 				flags &= ~TH_MARKNEXT_NEEDED;
15135 			}
15136 
15137 			/* Does this need SSL processing first? */
15138 			if ((tcp->tcp_kssl_ctx != NULL) &&
15139 			    (DB_TYPE(mp) == M_DATA)) {
15140 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15141 				    mblk_t *, mp);
15142 				tcp_kssl_input(tcp, mp);
15143 			} else if (!IPCL_IS_NONSTR(connp)) {
15144 				/* Already handled non-STREAMS case. */
15145 				putnext(tcp->tcp_rq, mp);
15146 				if (!canputnext(tcp->tcp_rq))
15147 					tcp->tcp_rwnd -= seg_len;
15148 			}
15149 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15150 		    (DB_TYPE(mp) == M_DATA)) {
15151 			/* Does this need SSL processing first? */
15152 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
15153 			tcp_kssl_input(tcp, mp);
15154 		} else if (IPCL_IS_NONSTR(connp)) {
15155 			/* Non-STREAMS socket */
15156 			boolean_t push = flags & (TH_PUSH|TH_FIN);
15157 			int	error;
15158 
15159 			if ((*connp->conn_upcalls->su_recv)(
15160 			    connp->conn_upper_handle,
15161 			    mp, seg_len, 0, &error, &push) <= 0) {
15162 				if (error == ENOSPC) {
15163 					tcp->tcp_rwnd -= seg_len;
15164 				} else if (error == EOPNOTSUPP) {
15165 					tcp_rcv_enqueue(tcp, mp, seg_len);
15166 				}
15167 			} else if (push) {
15168 				/*
15169 				 * PUSH bit set and sockfs is not
15170 				 * flow controlled
15171 				 */
15172 				flags |= tcp_rwnd_reopen(tcp);
15173 			}
15174 		} else if (sodp != NULL) {
15175 			/*
15176 			 * Sodirect so all mblk_t's are queued on the
15177 			 * socket directly, check for wakeup of blocked
15178 			 * reader (if any), and last if flow-controled.
15179 			 */
15180 			mutex_enter(sodp->sod_lockp);
15181 			flags |= tcp_rcv_sod_enqueue(tcp, sodp, mp, seg_len);
15182 			if ((sodp->sod_state & SOD_WAKE_NEED) ||
15183 			    (flags & (TH_PUSH|TH_FIN))) {
15184 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15185 				/* sod_wakeup() did the mutex_exit() */
15186 			} else {
15187 				if (SOD_QFULL(sodp)) {
15188 					/* Q is full, need backenable */
15189 					SOD_QSETBE(sodp);
15190 				}
15191 				mutex_exit(sodp->sod_lockp);
15192 			}
15193 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15194 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_recv_hiwater >> 3) {
15195 			if (tcp->tcp_rcv_list != NULL) {
15196 				/*
15197 				 * Enqueue the new segment first and then
15198 				 * call tcp_rcv_drain() to send all data
15199 				 * up.  The other way to do this is to
15200 				 * send all queued data up and then call
15201 				 * putnext() to send the new segment up.
15202 				 * This way can remove the else part later
15203 				 * on.
15204 				 *
15205 				 * We don't do this to avoid one more call to
15206 				 * canputnext() as tcp_rcv_drain() needs to
15207 				 * call canputnext().
15208 				 */
15209 				tcp_rcv_enqueue(tcp, mp, seg_len);
15210 				flags |= tcp_rcv_drain(tcp);
15211 			} else {
15212 				putnext(tcp->tcp_rq, mp);
15213 				if (!canputnext(tcp->tcp_rq))
15214 					tcp->tcp_rwnd -= seg_len;
15215 			}
15216 		} else {
15217 			/*
15218 			 * Enqueue all packets when processing an mblk
15219 			 * from the co queue and also enqueue normal packets.
15220 			 * For packets which belong to SSL stream do SSL
15221 			 * processing first.
15222 			 */
15223 			tcp_rcv_enqueue(tcp, mp, seg_len);
15224 		}
15225 		/*
15226 		 * Make sure the timer is running if we have data waiting
15227 		 * for a push bit. This provides resiliency against
15228 		 * implementations that do not correctly generate push bits.
15229 		 *
15230 		 * Note, for sodirect if Q isn't empty and there's not a
15231 		 * pending wakeup then we need a timer. Also note that sodp
15232 		 * is assumed to be still valid after exit()ing the sod_lockp
15233 		 * above and while the SOD state can change it can only change
15234 		 * such that the Q is empty now even though data was added
15235 		 * above.
15236 		 */
15237 		if (!IPCL_IS_NONSTR(connp) &&
15238 		    ((sodp != NULL && !SOD_QEMPTY(sodp) &&
15239 		    (sodp->sod_state & SOD_WAKE_NOT)) ||
15240 		    (sodp == NULL && tcp->tcp_rcv_list != NULL)) &&
15241 		    tcp->tcp_push_tid == 0) {
15242 			/*
15243 			 * The connection may be closed at this point, so don't
15244 			 * do anything for a detached tcp.
15245 			 */
15246 			if (!TCP_IS_DETACHED(tcp))
15247 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15248 				    tcp_push_timer,
15249 				    MSEC_TO_TICK(
15250 				    tcps->tcps_push_timer_interval));
15251 		}
15252 	}
15253 
15254 xmit_check:
15255 	/* Is there anything left to do? */
15256 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15257 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15258 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15259 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15260 		goto done;
15261 
15262 	/* Any transmit work to do and a non-zero window? */
15263 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15264 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15265 		if (flags & TH_REXMIT_NEEDED) {
15266 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15267 
15268 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15269 			if (snd_size > mss)
15270 				snd_size = mss;
15271 			if (snd_size > tcp->tcp_swnd)
15272 				snd_size = tcp->tcp_swnd;
15273 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15274 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15275 			    B_TRUE);
15276 
15277 			if (mp1 != NULL) {
15278 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15279 				tcp->tcp_csuna = tcp->tcp_snxt;
15280 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15281 				UPDATE_MIB(&tcps->tcps_mib,
15282 				    tcpRetransBytes, snd_size);
15283 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15284 			}
15285 		}
15286 		if (flags & TH_NEED_SACK_REXMIT) {
15287 			tcp_sack_rxmit(tcp, &flags);
15288 		}
15289 		/*
15290 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15291 		 * out new segment.  Note that tcp_rexmit should not be
15292 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15293 		 */
15294 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15295 			if (!tcp->tcp_rexmit) {
15296 				tcp_wput_data(tcp, NULL, B_FALSE);
15297 			} else {
15298 				tcp_ss_rexmit(tcp);
15299 			}
15300 		}
15301 		/*
15302 		 * Adjust tcp_cwnd back to normal value after sending
15303 		 * new data segments.
15304 		 */
15305 		if (flags & TH_LIMIT_XMIT) {
15306 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15307 			/*
15308 			 * This will restart the timer.  Restarting the
15309 			 * timer is used to avoid a timeout before the
15310 			 * limited transmitted segment's ACK gets back.
15311 			 */
15312 			if (tcp->tcp_xmit_head != NULL)
15313 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15314 		}
15315 
15316 		/* Anything more to do? */
15317 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15318 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15319 			goto done;
15320 	}
15321 ack_check:
15322 	if (flags & TH_SEND_URP_MARK) {
15323 		ASSERT(tcp->tcp_urp_mark_mp);
15324 		ASSERT(!IPCL_IS_NONSTR(connp));
15325 		/*
15326 		 * Send up any queued data and then send the mark message
15327 		 */
15328 		sodirect_t *sodp;
15329 
15330 		SOD_PTR_ENTER(tcp, sodp);
15331 
15332 		mp1 = tcp->tcp_urp_mark_mp;
15333 		tcp->tcp_urp_mark_mp = NULL;
15334 		if (sodp != NULL) {
15335 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15336 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15337 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15338 			}
15339 			ASSERT(tcp->tcp_rcv_list == NULL);
15340 
15341 			flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15342 			/* sod_wakeup() does the mutex_exit() */
15343 		} else if (tcp->tcp_rcv_list != NULL) {
15344 			flags |= tcp_rcv_drain(tcp);
15345 
15346 			ASSERT(tcp->tcp_rcv_list == NULL ||
15347 			    tcp->tcp_fused_sigurg);
15348 
15349 		}
15350 		putnext(tcp->tcp_rq, mp1);
15351 #ifdef DEBUG
15352 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15353 		    "tcp_rput: sending zero-length %s %s",
15354 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15355 		    "MSGNOTMARKNEXT"),
15356 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15357 #endif /* DEBUG */
15358 		flags &= ~TH_SEND_URP_MARK;
15359 	}
15360 	if (flags & TH_ACK_NEEDED) {
15361 		/*
15362 		 * Time to send an ack for some reason.
15363 		 */
15364 		mp1 = tcp_ack_mp(tcp);
15365 
15366 		if (mp1 != NULL) {
15367 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15368 			BUMP_LOCAL(tcp->tcp_obsegs);
15369 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15370 		}
15371 		if (tcp->tcp_ack_tid != 0) {
15372 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15373 			tcp->tcp_ack_tid = 0;
15374 		}
15375 	}
15376 	if (flags & TH_ACK_TIMER_NEEDED) {
15377 		/*
15378 		 * Arrange for deferred ACK or push wait timeout.
15379 		 * Start timer if it is not already running.
15380 		 */
15381 		if (tcp->tcp_ack_tid == 0) {
15382 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15383 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15384 			    (clock_t)tcps->tcps_local_dack_interval :
15385 			    (clock_t)tcps->tcps_deferred_ack_interval));
15386 		}
15387 	}
15388 	if (flags & TH_ORDREL_NEEDED) {
15389 		/*
15390 		 * Send up the ordrel_ind unless we are an eager guy.
15391 		 * In the eager case tcp_rsrv will do this when run
15392 		 * after tcp_accept is done.
15393 		 */
15394 		sodirect_t *sodp;
15395 
15396 		ASSERT(tcp->tcp_listener == NULL);
15397 
15398 		if (IPCL_IS_NONSTR(connp)) {
15399 			ASSERT(tcp->tcp_ordrel_mp == NULL);
15400 			tcp->tcp_ordrel_done = B_TRUE;
15401 			(*connp->conn_upcalls->su_opctl)
15402 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
15403 			goto done;
15404 		}
15405 
15406 		SOD_PTR_ENTER(tcp, sodp);
15407 		if (sodp != NULL) {
15408 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15409 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15410 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15411 			}
15412 			/* No more sodirect */
15413 			tcp->tcp_sodirect = NULL;
15414 			if (!SOD_QEMPTY(sodp)) {
15415 				/* Mblk(s) to process, notify */
15416 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15417 				/* sod_wakeup() does the mutex_exit() */
15418 			} else {
15419 				/* Nothing to process */
15420 				mutex_exit(sodp->sod_lockp);
15421 			}
15422 		} else if (tcp->tcp_rcv_list != NULL) {
15423 			/*
15424 			 * Push any mblk(s) enqueued from co processing.
15425 			 */
15426 			flags |= tcp_rcv_drain(tcp);
15427 
15428 			ASSERT(tcp->tcp_rcv_list == NULL ||
15429 			    tcp->tcp_fused_sigurg);
15430 		}
15431 
15432 		mp1 = tcp->tcp_ordrel_mp;
15433 		tcp->tcp_ordrel_mp = NULL;
15434 		tcp->tcp_ordrel_done = B_TRUE;
15435 		putnext(tcp->tcp_rq, mp1);
15436 	}
15437 done:
15438 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15439 }
15440 
15441 /*
15442  * This function does PAWS protection check. Returns B_TRUE if the
15443  * segment passes the PAWS test, else returns B_FALSE.
15444  */
15445 boolean_t
15446 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15447 {
15448 	uint8_t	flags;
15449 	int	options;
15450 	uint8_t *up;
15451 
15452 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15453 	/*
15454 	 * If timestamp option is aligned nicely, get values inline,
15455 	 * otherwise call general routine to parse.  Only do that
15456 	 * if timestamp is the only option.
15457 	 */
15458 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15459 	    TCPOPT_REAL_TS_LEN &&
15460 	    OK_32PTR((up = ((uint8_t *)tcph) +
15461 	    TCP_MIN_HEADER_LENGTH)) &&
15462 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15463 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15464 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15465 
15466 		options = TCP_OPT_TSTAMP_PRESENT;
15467 	} else {
15468 		if (tcp->tcp_snd_sack_ok) {
15469 			tcpoptp->tcp = tcp;
15470 		} else {
15471 			tcpoptp->tcp = NULL;
15472 		}
15473 		options = tcp_parse_options(tcph, tcpoptp);
15474 	}
15475 
15476 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15477 		/*
15478 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15479 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15480 		 */
15481 		if ((flags & TH_RST) == 0 &&
15482 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15483 		    tcp->tcp_ts_recent)) {
15484 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15485 			    PAWS_TIMEOUT)) {
15486 				/* This segment is not acceptable. */
15487 				return (B_FALSE);
15488 			} else {
15489 				/*
15490 				 * Connection has been idle for
15491 				 * too long.  Reset the timestamp
15492 				 * and assume the segment is valid.
15493 				 */
15494 				tcp->tcp_ts_recent =
15495 				    tcpoptp->tcp_opt_ts_val;
15496 			}
15497 		}
15498 	} else {
15499 		/*
15500 		 * If we don't get a timestamp on every packet, we
15501 		 * figure we can't really trust 'em, so we stop sending
15502 		 * and parsing them.
15503 		 */
15504 		tcp->tcp_snd_ts_ok = B_FALSE;
15505 
15506 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15507 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15508 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15509 		/*
15510 		 * Adjust the tcp_mss accordingly. We also need to
15511 		 * adjust tcp_cwnd here in accordance with the new mss.
15512 		 * But we avoid doing a slow start here so as to not
15513 		 * to lose on the transfer rate built up so far.
15514 		 */
15515 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15516 		if (tcp->tcp_snd_sack_ok) {
15517 			ASSERT(tcp->tcp_sack_info != NULL);
15518 			tcp->tcp_max_sack_blk = 4;
15519 		}
15520 	}
15521 	return (B_TRUE);
15522 }
15523 
15524 /*
15525  * Attach ancillary data to a received TCP segments for the
15526  * ancillary pieces requested by the application that are
15527  * different than they were in the previous data segment.
15528  *
15529  * Save the "current" values once memory allocation is ok so that
15530  * when memory allocation fails we can just wait for the next data segment.
15531  */
15532 static mblk_t *
15533 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15534 {
15535 	struct T_optdata_ind *todi;
15536 	int optlen;
15537 	uchar_t *optptr;
15538 	struct T_opthdr *toh;
15539 	uint_t addflag;	/* Which pieces to add */
15540 	mblk_t *mp1;
15541 
15542 	optlen = 0;
15543 	addflag = 0;
15544 	/* If app asked for pktinfo and the index has changed ... */
15545 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15546 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15547 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15548 		optlen += sizeof (struct T_opthdr) +
15549 		    sizeof (struct in6_pktinfo);
15550 		addflag |= TCP_IPV6_RECVPKTINFO;
15551 	}
15552 	/* If app asked for hoplimit and it has changed ... */
15553 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15554 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15555 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15556 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15557 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15558 	}
15559 	/* If app asked for tclass and it has changed ... */
15560 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15561 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15562 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15563 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15564 		addflag |= TCP_IPV6_RECVTCLASS;
15565 	}
15566 	/*
15567 	 * If app asked for hopbyhop headers and it has changed ...
15568 	 * For security labels, note that (1) security labels can't change on
15569 	 * a connected socket at all, (2) we're connected to at most one peer,
15570 	 * (3) if anything changes, then it must be some other extra option.
15571 	 */
15572 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15573 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15574 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15575 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15576 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15577 		    tcp->tcp_label_len;
15578 		addflag |= TCP_IPV6_RECVHOPOPTS;
15579 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15580 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15581 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15582 			return (mp);
15583 	}
15584 	/* If app asked for dst headers before routing headers ... */
15585 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15586 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15587 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15588 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15589 		optlen += sizeof (struct T_opthdr) +
15590 		    ipp->ipp_rtdstoptslen;
15591 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15592 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15593 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15594 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15595 			return (mp);
15596 	}
15597 	/* If app asked for routing headers and it has changed ... */
15598 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15599 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15600 	    (ipp->ipp_fields & IPPF_RTHDR),
15601 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15602 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15603 		addflag |= TCP_IPV6_RECVRTHDR;
15604 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15605 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15606 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15607 			return (mp);
15608 	}
15609 	/* If app asked for dest headers and it has changed ... */
15610 	if ((tcp->tcp_ipv6_recvancillary &
15611 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15612 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15613 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15614 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15615 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15616 		addflag |= TCP_IPV6_RECVDSTOPTS;
15617 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15618 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15619 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15620 			return (mp);
15621 	}
15622 
15623 	if (optlen == 0) {
15624 		/* Nothing to add */
15625 		return (mp);
15626 	}
15627 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15628 	if (mp1 == NULL) {
15629 		/*
15630 		 * Defer sending ancillary data until the next TCP segment
15631 		 * arrives.
15632 		 */
15633 		return (mp);
15634 	}
15635 	mp1->b_cont = mp;
15636 	mp = mp1;
15637 	mp->b_wptr += sizeof (*todi) + optlen;
15638 	mp->b_datap->db_type = M_PROTO;
15639 	todi = (struct T_optdata_ind *)mp->b_rptr;
15640 	todi->PRIM_type = T_OPTDATA_IND;
15641 	todi->DATA_flag = 1;	/* MORE data */
15642 	todi->OPT_length = optlen;
15643 	todi->OPT_offset = sizeof (*todi);
15644 	optptr = (uchar_t *)&todi[1];
15645 	/*
15646 	 * If app asked for pktinfo and the index has changed ...
15647 	 * Note that the local address never changes for the connection.
15648 	 */
15649 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15650 		struct in6_pktinfo *pkti;
15651 
15652 		toh = (struct T_opthdr *)optptr;
15653 		toh->level = IPPROTO_IPV6;
15654 		toh->name = IPV6_PKTINFO;
15655 		toh->len = sizeof (*toh) + sizeof (*pkti);
15656 		toh->status = 0;
15657 		optptr += sizeof (*toh);
15658 		pkti = (struct in6_pktinfo *)optptr;
15659 		if (tcp->tcp_ipversion == IPV6_VERSION)
15660 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15661 		else
15662 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15663 			    &pkti->ipi6_addr);
15664 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15665 		optptr += sizeof (*pkti);
15666 		ASSERT(OK_32PTR(optptr));
15667 		/* Save as "last" value */
15668 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15669 	}
15670 	/* If app asked for hoplimit and it has changed ... */
15671 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15672 		toh = (struct T_opthdr *)optptr;
15673 		toh->level = IPPROTO_IPV6;
15674 		toh->name = IPV6_HOPLIMIT;
15675 		toh->len = sizeof (*toh) + sizeof (uint_t);
15676 		toh->status = 0;
15677 		optptr += sizeof (*toh);
15678 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15679 		optptr += sizeof (uint_t);
15680 		ASSERT(OK_32PTR(optptr));
15681 		/* Save as "last" value */
15682 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15683 	}
15684 	/* If app asked for tclass and it has changed ... */
15685 	if (addflag & TCP_IPV6_RECVTCLASS) {
15686 		toh = (struct T_opthdr *)optptr;
15687 		toh->level = IPPROTO_IPV6;
15688 		toh->name = IPV6_TCLASS;
15689 		toh->len = sizeof (*toh) + sizeof (uint_t);
15690 		toh->status = 0;
15691 		optptr += sizeof (*toh);
15692 		*(uint_t *)optptr = ipp->ipp_tclass;
15693 		optptr += sizeof (uint_t);
15694 		ASSERT(OK_32PTR(optptr));
15695 		/* Save as "last" value */
15696 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15697 	}
15698 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15699 		toh = (struct T_opthdr *)optptr;
15700 		toh->level = IPPROTO_IPV6;
15701 		toh->name = IPV6_HOPOPTS;
15702 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15703 		    tcp->tcp_label_len;
15704 		toh->status = 0;
15705 		optptr += sizeof (*toh);
15706 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15707 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15708 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15709 		ASSERT(OK_32PTR(optptr));
15710 		/* Save as last value */
15711 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15712 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15713 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15714 	}
15715 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15716 		toh = (struct T_opthdr *)optptr;
15717 		toh->level = IPPROTO_IPV6;
15718 		toh->name = IPV6_RTHDRDSTOPTS;
15719 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15720 		toh->status = 0;
15721 		optptr += sizeof (*toh);
15722 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15723 		optptr += ipp->ipp_rtdstoptslen;
15724 		ASSERT(OK_32PTR(optptr));
15725 		/* Save as last value */
15726 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15727 		    &tcp->tcp_rtdstoptslen,
15728 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15729 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15730 	}
15731 	if (addflag & TCP_IPV6_RECVRTHDR) {
15732 		toh = (struct T_opthdr *)optptr;
15733 		toh->level = IPPROTO_IPV6;
15734 		toh->name = IPV6_RTHDR;
15735 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15736 		toh->status = 0;
15737 		optptr += sizeof (*toh);
15738 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15739 		optptr += ipp->ipp_rthdrlen;
15740 		ASSERT(OK_32PTR(optptr));
15741 		/* Save as last value */
15742 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15743 		    (ipp->ipp_fields & IPPF_RTHDR),
15744 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15745 	}
15746 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15747 		toh = (struct T_opthdr *)optptr;
15748 		toh->level = IPPROTO_IPV6;
15749 		toh->name = IPV6_DSTOPTS;
15750 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15751 		toh->status = 0;
15752 		optptr += sizeof (*toh);
15753 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15754 		optptr += ipp->ipp_dstoptslen;
15755 		ASSERT(OK_32PTR(optptr));
15756 		/* Save as last value */
15757 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15758 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15759 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15760 	}
15761 	ASSERT(optptr == mp->b_wptr);
15762 	return (mp);
15763 }
15764 
15765 /*
15766  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15767  * or a "bad" IRE detected by tcp_adapt_ire.
15768  * We can't tell if the failure was due to the laddr or the faddr
15769  * thus we clear out all addresses and ports.
15770  */
15771 static void
15772 tcp_tpi_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15773 {
15774 	queue_t	*q = tcp->tcp_rq;
15775 	tcph_t	*tcph;
15776 	struct T_error_ack *tea;
15777 	conn_t	*connp = tcp->tcp_connp;
15778 
15779 
15780 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15781 
15782 	if (mp->b_cont) {
15783 		freemsg(mp->b_cont);
15784 		mp->b_cont = NULL;
15785 	}
15786 	tea = (struct T_error_ack *)mp->b_rptr;
15787 	switch (tea->PRIM_type) {
15788 	case T_BIND_ACK:
15789 		/*
15790 		 * Need to unbind with classifier since we were just told that
15791 		 * our bind succeeded.
15792 		 */
15793 		tcp->tcp_hard_bound = B_FALSE;
15794 		tcp->tcp_hard_binding = B_FALSE;
15795 
15796 		ipcl_hash_remove(connp);
15797 		/* Reuse the mblk if possible */
15798 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15799 		    sizeof (*tea));
15800 		mp->b_rptr = mp->b_datap->db_base;
15801 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15802 		tea = (struct T_error_ack *)mp->b_rptr;
15803 		tea->PRIM_type = T_ERROR_ACK;
15804 		tea->TLI_error = TSYSERR;
15805 		tea->UNIX_error = error;
15806 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15807 			tea->ERROR_prim = T_CONN_REQ;
15808 		} else {
15809 			tea->ERROR_prim = O_T_BIND_REQ;
15810 		}
15811 		break;
15812 
15813 	case T_ERROR_ACK:
15814 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15815 			tea->ERROR_prim = T_CONN_REQ;
15816 		break;
15817 	default:
15818 		panic("tcp_tpi_bind_failed: unexpected TPI type");
15819 		/*NOTREACHED*/
15820 	}
15821 
15822 	tcp->tcp_state = TCPS_IDLE;
15823 	if (tcp->tcp_ipversion == IPV4_VERSION)
15824 		tcp->tcp_ipha->ipha_src = 0;
15825 	else
15826 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15827 	/*
15828 	 * Copy of the src addr. in tcp_t is needed since
15829 	 * the lookup funcs. can only look at tcp_t
15830 	 */
15831 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15832 
15833 	tcph = tcp->tcp_tcph;
15834 	tcph->th_lport[0] = 0;
15835 	tcph->th_lport[1] = 0;
15836 	tcp_bind_hash_remove(tcp);
15837 	bzero(&connp->u_port, sizeof (connp->u_port));
15838 	/* blow away saved option results if any */
15839 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15840 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15841 
15842 	conn_delete_ire(tcp->tcp_connp, NULL);
15843 	putnext(q, mp);
15844 }
15845 
15846 /*
15847  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15848  * messages.
15849  */
15850 void
15851 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15852 {
15853 	uchar_t	*rptr = mp->b_rptr;
15854 	queue_t	*q = tcp->tcp_rq;
15855 	struct T_error_ack *tea;
15856 
15857 	switch (mp->b_datap->db_type) {
15858 	case M_PROTO:
15859 	case M_PCPROTO:
15860 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15861 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15862 			break;
15863 		tea = (struct T_error_ack *)rptr;
15864 		switch (tea->PRIM_type) {
15865 		case T_BIND_ACK:
15866 			/*
15867 			 * AF_INET socket should not be here.
15868 			 */
15869 			ASSERT(tcp->tcp_family != AF_INET &&
15870 			    tcp->tcp_family != AF_INET6);
15871 			(void) tcp_post_ip_bind(tcp, mp->b_cont, 0);
15872 			return;
15873 		case T_ERROR_ACK:
15874 			if (tcp->tcp_debug) {
15875 				(void) strlog(TCP_MOD_ID, 0, 1,
15876 				    SL_TRACE|SL_ERROR,
15877 				    "tcp_rput_other: case T_ERROR_ACK, "
15878 				    "ERROR_prim == %d",
15879 				    tea->ERROR_prim);
15880 			}
15881 			switch (tea->ERROR_prim) {
15882 			case O_T_BIND_REQ:
15883 			case T_BIND_REQ:
15884 				ASSERT(tcp->tcp_family != AF_INET);
15885 				tcp_tpi_bind_failed(tcp, mp,
15886 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15887 				    ENETUNREACH : EADDRNOTAVAIL));
15888 				return;
15889 			case T_SVR4_OPTMGMT_REQ:
15890 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15891 					/* T_OPTMGMT_REQ generated by TCP */
15892 					printf("T_SVR4_OPTMGMT_REQ failed "
15893 					    "%d/%d - dropped (cnt %d)\n",
15894 					    tea->TLI_error, tea->UNIX_error,
15895 					    tcp->tcp_drop_opt_ack_cnt);
15896 					freemsg(mp);
15897 					tcp->tcp_drop_opt_ack_cnt--;
15898 					return;
15899 				}
15900 				break;
15901 			}
15902 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15903 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15904 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15905 				    "- dropped (cnt %d)\n",
15906 				    tea->TLI_error, tea->UNIX_error,
15907 				    tcp->tcp_drop_opt_ack_cnt);
15908 				freemsg(mp);
15909 				tcp->tcp_drop_opt_ack_cnt--;
15910 				return;
15911 			}
15912 			break;
15913 		case T_OPTMGMT_ACK:
15914 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15915 				/* T_OPTMGMT_REQ generated by TCP */
15916 				freemsg(mp);
15917 				tcp->tcp_drop_opt_ack_cnt--;
15918 				return;
15919 			}
15920 			break;
15921 		default:
15922 			ASSERT(tea->ERROR_prim != T_UNBIND_REQ);
15923 			break;
15924 		}
15925 		break;
15926 	case M_FLUSH:
15927 		if (*rptr & FLUSHR)
15928 			flushq(q, FLUSHDATA);
15929 		break;
15930 	default:
15931 		/* M_CTL will be directly sent to tcp_icmp_error() */
15932 		ASSERT(DB_TYPE(mp) != M_CTL);
15933 		break;
15934 	}
15935 	/*
15936 	 * Make sure we set this bit before sending the ACK for
15937 	 * bind. Otherwise accept could possibly run and free
15938 	 * this tcp struct.
15939 	 */
15940 	ASSERT(q != NULL);
15941 	putnext(q, mp);
15942 }
15943 
15944 /* ARGSUSED */
15945 static void
15946 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15947 {
15948 	conn_t	*connp = (conn_t *)arg;
15949 	tcp_t	*tcp = connp->conn_tcp;
15950 	queue_t	*q = tcp->tcp_rq;
15951 	uint_t	thwin;
15952 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15953 	sodirect_t	*sodp;
15954 	boolean_t	fc;
15955 
15956 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15957 	tcp->tcp_rsrv_mp = mp;
15958 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15959 
15960 	TCP_STAT(tcps, tcp_rsrv_calls);
15961 
15962 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15963 		return;
15964 	}
15965 
15966 	if (tcp->tcp_fused) {
15967 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15968 
15969 		ASSERT(tcp->tcp_fused);
15970 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15971 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15972 		ASSERT(!TCP_IS_DETACHED(tcp));
15973 		ASSERT(tcp->tcp_connp->conn_sqp ==
15974 		    peer_tcp->tcp_connp->conn_sqp);
15975 
15976 		/*
15977 		 * Normally we would not get backenabled in synchronous
15978 		 * streams mode, but in case this happens, we need to plug
15979 		 * synchronous streams during our drain to prevent a race
15980 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
15981 		 */
15982 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
15983 		if (tcp->tcp_rcv_list != NULL)
15984 			(void) tcp_rcv_drain(tcp);
15985 
15986 		if (peer_tcp > tcp) {
15987 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15988 			mutex_enter(&tcp->tcp_non_sq_lock);
15989 		} else {
15990 			mutex_enter(&tcp->tcp_non_sq_lock);
15991 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15992 		}
15993 
15994 		if (peer_tcp->tcp_flow_stopped &&
15995 		    (TCP_UNSENT_BYTES(peer_tcp) <=
15996 		    peer_tcp->tcp_xmit_lowater)) {
15997 			tcp_clrqfull(peer_tcp);
15998 		}
15999 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
16000 		mutex_exit(&tcp->tcp_non_sq_lock);
16001 
16002 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
16003 		TCP_STAT(tcps, tcp_fusion_backenabled);
16004 		return;
16005 	}
16006 
16007 	SOD_PTR_ENTER(tcp, sodp);
16008 	if (sodp != NULL) {
16009 		/* An sodirect connection */
16010 		if (SOD_QFULL(sodp)) {
16011 			/* Flow-controlled, need another back-enable */
16012 			fc = B_TRUE;
16013 			SOD_QSETBE(sodp);
16014 		} else {
16015 			/* Not flow-controlled */
16016 			fc = B_FALSE;
16017 		}
16018 		mutex_exit(sodp->sod_lockp);
16019 	} else if (canputnext(q)) {
16020 		/* STREAMS, not flow-controlled */
16021 		fc = B_FALSE;
16022 	} else {
16023 		/* STREAMS, flow-controlled */
16024 		fc = B_TRUE;
16025 	}
16026 	if (!fc) {
16027 		/* Not flow-controlled, open rwnd */
16028 		tcp->tcp_rwnd = q->q_hiwat;
16029 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
16030 		    << tcp->tcp_rcv_ws;
16031 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
16032 		/*
16033 		 * Send back a window update immediately if TCP is above
16034 		 * ESTABLISHED state and the increase of the rcv window
16035 		 * that the other side knows is at least 1 MSS after flow
16036 		 * control is lifted.
16037 		 */
16038 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
16039 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
16040 			tcp_xmit_ctl(NULL, tcp,
16041 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
16042 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
16043 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
16044 		}
16045 	}
16046 }
16047 
16048 /*
16049  * The read side service routine is called mostly when we get back-enabled as a
16050  * result of flow control relief.  Since we don't actually queue anything in
16051  * TCP, we have no data to send out of here.  What we do is clear the receive
16052  * window, and send out a window update.
16053  */
16054 static void
16055 tcp_rsrv(queue_t *q)
16056 {
16057 	conn_t		*connp = Q_TO_CONN(q);
16058 	tcp_t		*tcp = connp->conn_tcp;
16059 	mblk_t		*mp;
16060 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16061 
16062 	/* No code does a putq on the read side */
16063 	ASSERT(q->q_first == NULL);
16064 
16065 	/* Nothing to do for the default queue */
16066 	if (q == tcps->tcps_g_q) {
16067 		return;
16068 	}
16069 
16070 	/*
16071 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
16072 	 * been run.  So just return.
16073 	 */
16074 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
16075 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
16076 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
16077 		return;
16078 	}
16079 	tcp->tcp_rsrv_mp = NULL;
16080 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
16081 
16082 	CONN_INC_REF(connp);
16083 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16084 	    SQ_PROCESS, SQTAG_TCP_RSRV);
16085 }
16086 
16087 /*
16088  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16089  * We do not allow the receive window to shrink.  After setting rwnd,
16090  * set the flow control hiwat of the stream.
16091  *
16092  * This function is called in 2 cases:
16093  *
16094  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16095  *    connection (passive open) and in tcp_rput_data() for active connect.
16096  *    This is called after tcp_mss_set() when the desired MSS value is known.
16097  *    This makes sure that our window size is a mutiple of the other side's
16098  *    MSS.
16099  * 2) Handling SO_RCVBUF option.
16100  *
16101  * It is ASSUMED that the requested size is a multiple of the current MSS.
16102  *
16103  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16104  * user requests so.
16105  */
16106 static int
16107 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16108 {
16109 	uint32_t	mss = tcp->tcp_mss;
16110 	uint32_t	old_max_rwnd;
16111 	uint32_t	max_transmittable_rwnd;
16112 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16113 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16114 
16115 	if (tcp->tcp_fused) {
16116 		size_t sth_hiwat;
16117 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16118 
16119 		ASSERT(peer_tcp != NULL);
16120 		/*
16121 		 * Record the stream head's high water mark for
16122 		 * this endpoint; this is used for flow-control
16123 		 * purposes in tcp_fuse_output().
16124 		 */
16125 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16126 		if (!tcp_detached) {
16127 			(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
16128 			    sth_hiwat);
16129 			if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
16130 				conn_t *connp = tcp->tcp_connp;
16131 				struct sock_proto_props sopp;
16132 
16133 				sopp.sopp_flags = SOCKOPT_RCVTHRESH;
16134 				sopp.sopp_rcvthresh = sth_hiwat >> 3;
16135 
16136 				(*connp->conn_upcalls->su_set_proto_props)
16137 				    (connp->conn_upper_handle, &sopp);
16138 			}
16139 		}
16140 
16141 		/*
16142 		 * In the fusion case, the maxpsz stream head value of
16143 		 * our peer is set according to its send buffer size
16144 		 * and our receive buffer size; since the latter may
16145 		 * have changed we need to update the peer's maxpsz.
16146 		 */
16147 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16148 		return (rwnd);
16149 	}
16150 
16151 	if (tcp_detached) {
16152 		old_max_rwnd = tcp->tcp_rwnd;
16153 	} else {
16154 		old_max_rwnd = tcp->tcp_recv_hiwater;
16155 	}
16156 
16157 	/*
16158 	 * Insist on a receive window that is at least
16159 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16160 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16161 	 * and delayed acknowledgement.
16162 	 */
16163 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16164 
16165 	/*
16166 	 * If window size info has already been exchanged, TCP should not
16167 	 * shrink the window.  Shrinking window is doable if done carefully.
16168 	 * We may add that support later.  But so far there is not a real
16169 	 * need to do that.
16170 	 */
16171 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16172 		/* MSS may have changed, do a round up again. */
16173 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16174 	}
16175 
16176 	/*
16177 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16178 	 * can be applied even before the window scale option is decided.
16179 	 */
16180 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16181 	if (rwnd > max_transmittable_rwnd) {
16182 		rwnd = max_transmittable_rwnd -
16183 		    (max_transmittable_rwnd % mss);
16184 		if (rwnd < mss)
16185 			rwnd = max_transmittable_rwnd;
16186 		/*
16187 		 * If we're over the limit we may have to back down tcp_rwnd.
16188 		 * The increment below won't work for us. So we set all three
16189 		 * here and the increment below will have no effect.
16190 		 */
16191 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16192 	}
16193 	if (tcp->tcp_localnet) {
16194 		tcp->tcp_rack_abs_max =
16195 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16196 	} else {
16197 		/*
16198 		 * For a remote host on a different subnet (through a router),
16199 		 * we ack every other packet to be conforming to RFC1122.
16200 		 * tcp_deferred_acks_max is default to 2.
16201 		 */
16202 		tcp->tcp_rack_abs_max =
16203 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16204 	}
16205 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16206 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16207 	else
16208 		tcp->tcp_rack_cur_max = 0;
16209 	/*
16210 	 * Increment the current rwnd by the amount the maximum grew (we
16211 	 * can not overwrite it since we might be in the middle of a
16212 	 * connection.)
16213 	 */
16214 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16215 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16216 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16217 		tcp->tcp_cwnd_max = rwnd;
16218 
16219 	if (tcp_detached)
16220 		return (rwnd);
16221 	/*
16222 	 * We set the maximum receive window into rq->q_hiwat if it is
16223 	 * a STREAMS socket.
16224 	 * This is not actually used for flow control.
16225 	 */
16226 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
16227 		tcp->tcp_rq->q_hiwat = rwnd;
16228 	tcp->tcp_recv_hiwater = rwnd;
16229 	/*
16230 	 * Set the STREAM head high water mark. This doesn't have to be
16231 	 * here, since we are simply using default values, but we would
16232 	 * prefer to choose these values algorithmically, with a likely
16233 	 * relationship to rwnd.
16234 	 */
16235 	(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
16236 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16237 	return (rwnd);
16238 }
16239 
16240 /*
16241  * Return SNMP stuff in buffer in mpdata.
16242  */
16243 mblk_t *
16244 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16245 {
16246 	mblk_t			*mpdata;
16247 	mblk_t			*mp_conn_ctl = NULL;
16248 	mblk_t			*mp_conn_tail;
16249 	mblk_t			*mp_attr_ctl = NULL;
16250 	mblk_t			*mp_attr_tail;
16251 	mblk_t			*mp6_conn_ctl = NULL;
16252 	mblk_t			*mp6_conn_tail;
16253 	mblk_t			*mp6_attr_ctl = NULL;
16254 	mblk_t			*mp6_attr_tail;
16255 	struct opthdr		*optp;
16256 	mib2_tcpConnEntry_t	tce;
16257 	mib2_tcp6ConnEntry_t	tce6;
16258 	mib2_transportMLPEntry_t mlp;
16259 	connf_t			*connfp;
16260 	int			i;
16261 	boolean_t 		ispriv;
16262 	zoneid_t 		zoneid;
16263 	int			v4_conn_idx;
16264 	int			v6_conn_idx;
16265 	conn_t			*connp = Q_TO_CONN(q);
16266 	tcp_stack_t		*tcps;
16267 	ip_stack_t		*ipst;
16268 	mblk_t			*mp2ctl;
16269 
16270 	/*
16271 	 * make a copy of the original message
16272 	 */
16273 	mp2ctl = copymsg(mpctl);
16274 
16275 	if (mpctl == NULL ||
16276 	    (mpdata = mpctl->b_cont) == NULL ||
16277 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16278 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16279 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16280 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16281 		freemsg(mp_conn_ctl);
16282 		freemsg(mp_attr_ctl);
16283 		freemsg(mp6_conn_ctl);
16284 		freemsg(mp6_attr_ctl);
16285 		freemsg(mpctl);
16286 		freemsg(mp2ctl);
16287 		return (NULL);
16288 	}
16289 
16290 	ipst = connp->conn_netstack->netstack_ip;
16291 	tcps = connp->conn_netstack->netstack_tcp;
16292 
16293 	/* build table of connections -- need count in fixed part */
16294 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16295 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16296 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16297 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16298 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16299 
16300 	ispriv =
16301 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16302 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16303 
16304 	v4_conn_idx = v6_conn_idx = 0;
16305 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16306 
16307 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16308 		ipst = tcps->tcps_netstack->netstack_ip;
16309 
16310 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16311 
16312 		connp = NULL;
16313 
16314 		while ((connp =
16315 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16316 			tcp_t *tcp;
16317 			boolean_t needattr;
16318 
16319 			if (connp->conn_zoneid != zoneid)
16320 				continue;	/* not in this zone */
16321 
16322 			tcp = connp->conn_tcp;
16323 			UPDATE_MIB(&tcps->tcps_mib,
16324 			    tcpHCInSegs, tcp->tcp_ibsegs);
16325 			tcp->tcp_ibsegs = 0;
16326 			UPDATE_MIB(&tcps->tcps_mib,
16327 			    tcpHCOutSegs, tcp->tcp_obsegs);
16328 			tcp->tcp_obsegs = 0;
16329 
16330 			tce6.tcp6ConnState = tce.tcpConnState =
16331 			    tcp_snmp_state(tcp);
16332 			if (tce.tcpConnState == MIB2_TCP_established ||
16333 			    tce.tcpConnState == MIB2_TCP_closeWait)
16334 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16335 
16336 			needattr = B_FALSE;
16337 			bzero(&mlp, sizeof (mlp));
16338 			if (connp->conn_mlp_type != mlptSingle) {
16339 				if (connp->conn_mlp_type == mlptShared ||
16340 				    connp->conn_mlp_type == mlptBoth)
16341 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16342 				if (connp->conn_mlp_type == mlptPrivate ||
16343 				    connp->conn_mlp_type == mlptBoth)
16344 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16345 				needattr = B_TRUE;
16346 			}
16347 			if (connp->conn_peercred != NULL) {
16348 				ts_label_t *tsl;
16349 
16350 				tsl = crgetlabel(connp->conn_peercred);
16351 				mlp.tme_doi = label2doi(tsl);
16352 				mlp.tme_label = *label2bslabel(tsl);
16353 				needattr = B_TRUE;
16354 			}
16355 
16356 			/* Create a message to report on IPv6 entries */
16357 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16358 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16359 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16360 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16361 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16362 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16363 			/* Don't want just anybody seeing these... */
16364 			if (ispriv) {
16365 				tce6.tcp6ConnEntryInfo.ce_snxt =
16366 				    tcp->tcp_snxt;
16367 				tce6.tcp6ConnEntryInfo.ce_suna =
16368 				    tcp->tcp_suna;
16369 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16370 				    tcp->tcp_rnxt;
16371 				tce6.tcp6ConnEntryInfo.ce_rack =
16372 				    tcp->tcp_rack;
16373 			} else {
16374 				/*
16375 				 * Netstat, unfortunately, uses this to
16376 				 * get send/receive queue sizes.  How to fix?
16377 				 * Why not compute the difference only?
16378 				 */
16379 				tce6.tcp6ConnEntryInfo.ce_snxt =
16380 				    tcp->tcp_snxt - tcp->tcp_suna;
16381 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16382 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16383 				    tcp->tcp_rnxt - tcp->tcp_rack;
16384 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16385 			}
16386 
16387 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16388 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16389 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16390 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16391 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16392 
16393 			tce6.tcp6ConnCreationProcess =
16394 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16395 			    tcp->tcp_cpid;
16396 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16397 
16398 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16399 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16400 
16401 			mlp.tme_connidx = v6_conn_idx++;
16402 			if (needattr)
16403 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16404 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16405 			}
16406 			/*
16407 			 * Create an IPv4 table entry for IPv4 entries and also
16408 			 * for IPv6 entries which are bound to in6addr_any
16409 			 * but don't have IPV6_V6ONLY set.
16410 			 * (i.e. anything an IPv4 peer could connect to)
16411 			 */
16412 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16413 			    (tcp->tcp_state <= TCPS_LISTEN &&
16414 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16415 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16416 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16417 					tce.tcpConnRemAddress = INADDR_ANY;
16418 					tce.tcpConnLocalAddress = INADDR_ANY;
16419 				} else {
16420 					tce.tcpConnRemAddress =
16421 					    tcp->tcp_remote;
16422 					tce.tcpConnLocalAddress =
16423 					    tcp->tcp_ip_src;
16424 				}
16425 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16426 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16427 				/* Don't want just anybody seeing these... */
16428 				if (ispriv) {
16429 					tce.tcpConnEntryInfo.ce_snxt =
16430 					    tcp->tcp_snxt;
16431 					tce.tcpConnEntryInfo.ce_suna =
16432 					    tcp->tcp_suna;
16433 					tce.tcpConnEntryInfo.ce_rnxt =
16434 					    tcp->tcp_rnxt;
16435 					tce.tcpConnEntryInfo.ce_rack =
16436 					    tcp->tcp_rack;
16437 				} else {
16438 					/*
16439 					 * Netstat, unfortunately, uses this to
16440 					 * get send/receive queue sizes.  How
16441 					 * to fix?
16442 					 * Why not compute the difference only?
16443 					 */
16444 					tce.tcpConnEntryInfo.ce_snxt =
16445 					    tcp->tcp_snxt - tcp->tcp_suna;
16446 					tce.tcpConnEntryInfo.ce_suna = 0;
16447 					tce.tcpConnEntryInfo.ce_rnxt =
16448 					    tcp->tcp_rnxt - tcp->tcp_rack;
16449 					tce.tcpConnEntryInfo.ce_rack = 0;
16450 				}
16451 
16452 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16453 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16454 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16455 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16456 				tce.tcpConnEntryInfo.ce_state =
16457 				    tcp->tcp_state;
16458 
16459 				tce.tcpConnCreationProcess =
16460 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16461 				    tcp->tcp_cpid;
16462 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16463 
16464 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16465 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16466 
16467 				mlp.tme_connidx = v4_conn_idx++;
16468 				if (needattr)
16469 					(void) snmp_append_data2(
16470 					    mp_attr_ctl->b_cont,
16471 					    &mp_attr_tail, (char *)&mlp,
16472 					    sizeof (mlp));
16473 			}
16474 		}
16475 	}
16476 
16477 	/* fixed length structure for IPv4 and IPv6 counters */
16478 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16479 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16480 	    sizeof (mib2_tcp6ConnEntry_t));
16481 	/* synchronize 32- and 64-bit counters */
16482 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16483 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16484 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16485 	optp->level = MIB2_TCP;
16486 	optp->name = 0;
16487 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16488 	    sizeof (tcps->tcps_mib));
16489 	optp->len = msgdsize(mpdata);
16490 	qreply(q, mpctl);
16491 
16492 	/* table of connections... */
16493 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16494 	    sizeof (struct T_optmgmt_ack)];
16495 	optp->level = MIB2_TCP;
16496 	optp->name = MIB2_TCP_CONN;
16497 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16498 	qreply(q, mp_conn_ctl);
16499 
16500 	/* table of MLP attributes... */
16501 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16502 	    sizeof (struct T_optmgmt_ack)];
16503 	optp->level = MIB2_TCP;
16504 	optp->name = EXPER_XPORT_MLP;
16505 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16506 	if (optp->len == 0)
16507 		freemsg(mp_attr_ctl);
16508 	else
16509 		qreply(q, mp_attr_ctl);
16510 
16511 	/* table of IPv6 connections... */
16512 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16513 	    sizeof (struct T_optmgmt_ack)];
16514 	optp->level = MIB2_TCP6;
16515 	optp->name = MIB2_TCP6_CONN;
16516 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16517 	qreply(q, mp6_conn_ctl);
16518 
16519 	/* table of IPv6 MLP attributes... */
16520 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16521 	    sizeof (struct T_optmgmt_ack)];
16522 	optp->level = MIB2_TCP6;
16523 	optp->name = EXPER_XPORT_MLP;
16524 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16525 	if (optp->len == 0)
16526 		freemsg(mp6_attr_ctl);
16527 	else
16528 		qreply(q, mp6_attr_ctl);
16529 	return (mp2ctl);
16530 }
16531 
16532 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16533 /* ARGSUSED */
16534 int
16535 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16536 {
16537 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16538 
16539 	switch (level) {
16540 	case MIB2_TCP:
16541 		switch (name) {
16542 		case 13:
16543 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16544 				return (0);
16545 			/* TODO: delete entry defined by tce */
16546 			return (1);
16547 		default:
16548 			return (0);
16549 		}
16550 	default:
16551 		return (1);
16552 	}
16553 }
16554 
16555 /* Translate TCP state to MIB2 TCP state. */
16556 static int
16557 tcp_snmp_state(tcp_t *tcp)
16558 {
16559 	if (tcp == NULL)
16560 		return (0);
16561 
16562 	switch (tcp->tcp_state) {
16563 	case TCPS_CLOSED:
16564 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16565 	case TCPS_BOUND:
16566 		return (MIB2_TCP_closed);
16567 	case TCPS_LISTEN:
16568 		return (MIB2_TCP_listen);
16569 	case TCPS_SYN_SENT:
16570 		return (MIB2_TCP_synSent);
16571 	case TCPS_SYN_RCVD:
16572 		return (MIB2_TCP_synReceived);
16573 	case TCPS_ESTABLISHED:
16574 		return (MIB2_TCP_established);
16575 	case TCPS_CLOSE_WAIT:
16576 		return (MIB2_TCP_closeWait);
16577 	case TCPS_FIN_WAIT_1:
16578 		return (MIB2_TCP_finWait1);
16579 	case TCPS_CLOSING:
16580 		return (MIB2_TCP_closing);
16581 	case TCPS_LAST_ACK:
16582 		return (MIB2_TCP_lastAck);
16583 	case TCPS_FIN_WAIT_2:
16584 		return (MIB2_TCP_finWait2);
16585 	case TCPS_TIME_WAIT:
16586 		return (MIB2_TCP_timeWait);
16587 	default:
16588 		return (0);
16589 	}
16590 }
16591 
16592 static char tcp_report_header[] =
16593 	"TCP     " MI_COL_HDRPAD_STR
16594 	"zone dest	    snxt     suna     "
16595 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16596 	"recent   [lport,fport] state";
16597 
16598 /*
16599  * TCP status report triggered via the Named Dispatch mechanism.
16600  */
16601 /* ARGSUSED */
16602 static void
16603 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16604     cred_t *cr)
16605 {
16606 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16607 	boolean_t ispriv = secpolicy_ip_config(cr, B_TRUE) == 0;
16608 	char cflag;
16609 	in6_addr_t	v6dst;
16610 	char buf[80];
16611 	uint_t print_len, buf_len;
16612 
16613 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16614 	if (buf_len <= 0)
16615 		return;
16616 
16617 	if (hashval >= 0)
16618 		(void) sprintf(hash, "%03d ", hashval);
16619 	else
16620 		hash[0] = '\0';
16621 
16622 	/*
16623 	 * Note that we use the remote address in the tcp_b  structure.
16624 	 * This means that it will print out the real destination address,
16625 	 * not the next hop's address if source routing is used.  This
16626 	 * avoid the confusion on the output because user may not
16627 	 * know that source routing is used for a connection.
16628 	 */
16629 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16630 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16631 	} else {
16632 		v6dst = tcp->tcp_remote_v6;
16633 	}
16634 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16635 	/*
16636 	 * the ispriv checks are so that normal users cannot determine
16637 	 * sequence number information using NDD.
16638 	 */
16639 
16640 	if (TCP_IS_DETACHED(tcp))
16641 		cflag = '*';
16642 	else
16643 		cflag = ' ';
16644 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16645 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16646 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16647 	    hash,
16648 	    (void *)tcp,
16649 	    tcp->tcp_connp->conn_zoneid,
16650 	    addrbuf,
16651 	    (ispriv) ? tcp->tcp_snxt : 0,
16652 	    (ispriv) ? tcp->tcp_suna : 0,
16653 	    tcp->tcp_swnd,
16654 	    (ispriv) ? tcp->tcp_rnxt : 0,
16655 	    (ispriv) ? tcp->tcp_rack : 0,
16656 	    tcp->tcp_rwnd,
16657 	    tcp->tcp_rto,
16658 	    tcp->tcp_mss,
16659 	    tcp->tcp_snd_ws_ok,
16660 	    tcp->tcp_snd_ws,
16661 	    tcp->tcp_rcv_ws,
16662 	    tcp->tcp_snd_ts_ok,
16663 	    tcp->tcp_ts_recent,
16664 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16665 	if (print_len < buf_len) {
16666 		((mblk_t *)mp)->b_wptr += print_len;
16667 	} else {
16668 		((mblk_t *)mp)->b_wptr += buf_len;
16669 	}
16670 }
16671 
16672 /*
16673  * TCP status report (for listeners only) triggered via the Named Dispatch
16674  * mechanism.
16675  */
16676 /* ARGSUSED */
16677 static void
16678 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16679 {
16680 	char addrbuf[INET6_ADDRSTRLEN];
16681 	in6_addr_t	v6dst;
16682 	uint_t print_len, buf_len;
16683 
16684 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16685 	if (buf_len <= 0)
16686 		return;
16687 
16688 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16689 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16690 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16691 	} else {
16692 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16693 		    addrbuf, sizeof (addrbuf));
16694 	}
16695 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16696 	    "%03d "
16697 	    MI_COL_PTRFMT_STR
16698 	    "%d %s %05u %08u %d/%d/%d%c\n",
16699 	    hashval, (void *)tcp,
16700 	    tcp->tcp_connp->conn_zoneid,
16701 	    addrbuf,
16702 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16703 	    tcp->tcp_conn_req_seqnum,
16704 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16705 	    tcp->tcp_conn_req_max,
16706 	    tcp->tcp_syn_defense ? '*' : ' ');
16707 	if (print_len < buf_len) {
16708 		((mblk_t *)mp)->b_wptr += print_len;
16709 	} else {
16710 		((mblk_t *)mp)->b_wptr += buf_len;
16711 	}
16712 }
16713 
16714 /* TCP status report triggered via the Named Dispatch mechanism. */
16715 /* ARGSUSED */
16716 static int
16717 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16718 {
16719 	tcp_t	*tcp;
16720 	int	i;
16721 	conn_t	*connp;
16722 	connf_t	*connfp;
16723 	zoneid_t zoneid;
16724 	tcp_stack_t *tcps;
16725 	ip_stack_t *ipst;
16726 
16727 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16728 	tcps = Q_TO_TCP(q)->tcp_tcps;
16729 
16730 	/*
16731 	 * Because of the ndd constraint, at most we can have 64K buffer
16732 	 * to put in all TCP info.  So to be more efficient, just
16733 	 * allocate a 64K buffer here, assuming we need that large buffer.
16734 	 * This may be a problem as any user can read tcp_status.  Therefore
16735 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16736 	 * This should be OK as normal users should not do this too often.
16737 	 */
16738 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16739 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16740 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16741 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16742 			return (0);
16743 		}
16744 	}
16745 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16746 		/* The following may work even if we cannot get a large buf. */
16747 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16748 		return (0);
16749 	}
16750 
16751 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16752 
16753 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16754 
16755 		ipst = tcps->tcps_netstack->netstack_ip;
16756 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16757 
16758 		connp = NULL;
16759 
16760 		while ((connp =
16761 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16762 			tcp = connp->conn_tcp;
16763 			if (zoneid != GLOBAL_ZONEID &&
16764 			    zoneid != connp->conn_zoneid)
16765 				continue;
16766 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16767 			    cr);
16768 		}
16769 
16770 	}
16771 
16772 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16773 	return (0);
16774 }
16775 
16776 /* TCP status report triggered via the Named Dispatch mechanism. */
16777 /* ARGSUSED */
16778 static int
16779 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16780 {
16781 	tf_t	*tbf;
16782 	tcp_t	*tcp, *ltcp;
16783 	int	i;
16784 	zoneid_t zoneid;
16785 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
16786 
16787 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16788 
16789 	/* Refer to comments in tcp_status_report(). */
16790 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16791 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16792 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16793 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16794 			return (0);
16795 		}
16796 	}
16797 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16798 		/* The following may work even if we cannot get a large buf. */
16799 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16800 		return (0);
16801 	}
16802 
16803 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16804 
16805 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
16806 		tbf = &tcps->tcps_bind_fanout[i];
16807 		mutex_enter(&tbf->tf_lock);
16808 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
16809 		    ltcp = ltcp->tcp_bind_hash) {
16810 			for (tcp = ltcp; tcp != NULL;
16811 			    tcp = tcp->tcp_bind_hash_port) {
16812 				if (zoneid != GLOBAL_ZONEID &&
16813 				    zoneid != tcp->tcp_connp->conn_zoneid)
16814 					continue;
16815 				CONN_INC_REF(tcp->tcp_connp);
16816 				tcp_report_item(mp->b_cont, tcp, i,
16817 				    Q_TO_TCP(q), cr);
16818 				CONN_DEC_REF(tcp->tcp_connp);
16819 			}
16820 		}
16821 		mutex_exit(&tbf->tf_lock);
16822 	}
16823 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16824 	return (0);
16825 }
16826 
16827 /* TCP status report triggered via the Named Dispatch mechanism. */
16828 /* ARGSUSED */
16829 static int
16830 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16831 {
16832 	connf_t	*connfp;
16833 	conn_t	*connp;
16834 	tcp_t	*tcp;
16835 	int	i;
16836 	zoneid_t zoneid;
16837 	tcp_stack_t *tcps;
16838 	ip_stack_t	*ipst;
16839 
16840 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16841 	tcps = Q_TO_TCP(q)->tcp_tcps;
16842 
16843 	/* Refer to comments in tcp_status_report(). */
16844 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16845 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16846 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16847 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16848 			return (0);
16849 		}
16850 	}
16851 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16852 		/* The following may work even if we cannot get a large buf. */
16853 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16854 		return (0);
16855 	}
16856 
16857 	(void) mi_mpprintf(mp,
16858 	    "    TCP    " MI_COL_HDRPAD_STR
16859 	    "zone IP addr	 port  seqnum   backlog (q0/q/max)");
16860 
16861 	ipst = tcps->tcps_netstack->netstack_ip;
16862 
16863 	for (i = 0; i < ipst->ips_ipcl_bind_fanout_size; i++) {
16864 		connfp = &ipst->ips_ipcl_bind_fanout[i];
16865 		connp = NULL;
16866 		while ((connp =
16867 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16868 			tcp = connp->conn_tcp;
16869 			if (zoneid != GLOBAL_ZONEID &&
16870 			    zoneid != connp->conn_zoneid)
16871 				continue;
16872 			tcp_report_listener(mp->b_cont, tcp, i);
16873 		}
16874 	}
16875 
16876 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16877 	return (0);
16878 }
16879 
16880 /* TCP status report triggered via the Named Dispatch mechanism. */
16881 /* ARGSUSED */
16882 static int
16883 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16884 {
16885 	connf_t	*connfp;
16886 	conn_t	*connp;
16887 	tcp_t	*tcp;
16888 	int	i;
16889 	zoneid_t zoneid;
16890 	tcp_stack_t *tcps;
16891 	ip_stack_t *ipst;
16892 
16893 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16894 	tcps = Q_TO_TCP(q)->tcp_tcps;
16895 	ipst = tcps->tcps_netstack->netstack_ip;
16896 
16897 	/* Refer to comments in tcp_status_report(). */
16898 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16899 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16900 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16901 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16902 			return (0);
16903 		}
16904 	}
16905 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16906 		/* The following may work even if we cannot get a large buf. */
16907 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16908 		return (0);
16909 	}
16910 
16911 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16912 	    ipst->ips_ipcl_conn_fanout_size);
16913 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16914 
16915 	for (i = 0; i < ipst->ips_ipcl_conn_fanout_size; i++) {
16916 		connfp =  &ipst->ips_ipcl_conn_fanout[i];
16917 		connp = NULL;
16918 		while ((connp =
16919 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16920 			tcp = connp->conn_tcp;
16921 			if (zoneid != GLOBAL_ZONEID &&
16922 			    zoneid != connp->conn_zoneid)
16923 				continue;
16924 			tcp_report_item(mp->b_cont, tcp, i,
16925 			    Q_TO_TCP(q), cr);
16926 		}
16927 	}
16928 
16929 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16930 	return (0);
16931 }
16932 
16933 /* TCP status report triggered via the Named Dispatch mechanism. */
16934 /* ARGSUSED */
16935 static int
16936 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16937 {
16938 	tf_t	*tf;
16939 	tcp_t	*tcp;
16940 	int	i;
16941 	zoneid_t zoneid;
16942 	tcp_stack_t	*tcps;
16943 
16944 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16945 	tcps = Q_TO_TCP(q)->tcp_tcps;
16946 
16947 	/* Refer to comments in tcp_status_report(). */
16948 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16949 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16950 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16951 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16952 			return (0);
16953 		}
16954 	}
16955 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16956 		/* The following may work even if we cannot get a large buf. */
16957 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16958 		return (0);
16959 	}
16960 
16961 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16962 
16963 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
16964 		tf = &tcps->tcps_acceptor_fanout[i];
16965 		mutex_enter(&tf->tf_lock);
16966 		for (tcp = tf->tf_tcp; tcp != NULL;
16967 		    tcp = tcp->tcp_acceptor_hash) {
16968 			if (zoneid != GLOBAL_ZONEID &&
16969 			    zoneid != tcp->tcp_connp->conn_zoneid)
16970 				continue;
16971 			tcp_report_item(mp->b_cont, tcp, i,
16972 			    Q_TO_TCP(q), cr);
16973 		}
16974 		mutex_exit(&tf->tf_lock);
16975 	}
16976 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16977 	return (0);
16978 }
16979 
16980 /*
16981  * tcp_timer is the timer service routine.  It handles the retransmission,
16982  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16983  * from the state of the tcp instance what kind of action needs to be done
16984  * at the time it is called.
16985  */
16986 static void
16987 tcp_timer(void *arg)
16988 {
16989 	mblk_t		*mp;
16990 	clock_t		first_threshold;
16991 	clock_t		second_threshold;
16992 	clock_t		ms;
16993 	uint32_t	mss;
16994 	conn_t		*connp = (conn_t *)arg;
16995 	tcp_t		*tcp = connp->conn_tcp;
16996 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16997 
16998 	tcp->tcp_timer_tid = 0;
16999 
17000 	if (tcp->tcp_fused)
17001 		return;
17002 
17003 	first_threshold =  tcp->tcp_first_timer_threshold;
17004 	second_threshold = tcp->tcp_second_timer_threshold;
17005 	switch (tcp->tcp_state) {
17006 	case TCPS_IDLE:
17007 	case TCPS_BOUND:
17008 	case TCPS_LISTEN:
17009 		return;
17010 	case TCPS_SYN_RCVD: {
17011 		tcp_t	*listener = tcp->tcp_listener;
17012 
17013 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
17014 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
17015 			/* it's our first timeout */
17016 			tcp->tcp_syn_rcvd_timeout = 1;
17017 			mutex_enter(&listener->tcp_eager_lock);
17018 			listener->tcp_syn_rcvd_timeout++;
17019 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
17020 				/*
17021 				 * Make this eager available for drop if we
17022 				 * need to drop one to accomodate a new
17023 				 * incoming SYN request.
17024 				 */
17025 				MAKE_DROPPABLE(listener, tcp);
17026 			}
17027 			if (!listener->tcp_syn_defense &&
17028 			    (listener->tcp_syn_rcvd_timeout >
17029 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
17030 			    (tcps->tcps_conn_req_max_q0 > 200)) {
17031 				/* We may be under attack. Put on a defense. */
17032 				listener->tcp_syn_defense = B_TRUE;
17033 				cmn_err(CE_WARN, "High TCP connect timeout "
17034 				    "rate! System (port %d) may be under a "
17035 				    "SYN flood attack!",
17036 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
17037 
17038 				listener->tcp_ip_addr_cache = kmem_zalloc(
17039 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
17040 				    KM_NOSLEEP);
17041 			}
17042 			mutex_exit(&listener->tcp_eager_lock);
17043 		} else if (listener != NULL) {
17044 			mutex_enter(&listener->tcp_eager_lock);
17045 			tcp->tcp_syn_rcvd_timeout++;
17046 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
17047 			    !tcp->tcp_closemp_used) {
17048 				/*
17049 				 * This is our second timeout. Put the tcp in
17050 				 * the list of droppable eagers to allow it to
17051 				 * be dropped, if needed. We don't check
17052 				 * whether tcp_dontdrop is set or not to
17053 				 * protect ourselve from a SYN attack where a
17054 				 * remote host can spoof itself as one of the
17055 				 * good IP source and continue to hold
17056 				 * resources too long.
17057 				 */
17058 				MAKE_DROPPABLE(listener, tcp);
17059 			}
17060 			mutex_exit(&listener->tcp_eager_lock);
17061 		}
17062 	}
17063 		/* FALLTHRU */
17064 	case TCPS_SYN_SENT:
17065 		first_threshold =  tcp->tcp_first_ctimer_threshold;
17066 		second_threshold = tcp->tcp_second_ctimer_threshold;
17067 		break;
17068 	case TCPS_ESTABLISHED:
17069 	case TCPS_FIN_WAIT_1:
17070 	case TCPS_CLOSING:
17071 	case TCPS_CLOSE_WAIT:
17072 	case TCPS_LAST_ACK:
17073 		/* If we have data to rexmit */
17074 		if (tcp->tcp_suna != tcp->tcp_snxt) {
17075 			clock_t	time_to_wait;
17076 
17077 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
17078 			if (!tcp->tcp_xmit_head)
17079 				break;
17080 			time_to_wait = lbolt -
17081 			    (clock_t)tcp->tcp_xmit_head->b_prev;
17082 			time_to_wait = tcp->tcp_rto -
17083 			    TICK_TO_MSEC(time_to_wait);
17084 			/*
17085 			 * If the timer fires too early, 1 clock tick earlier,
17086 			 * restart the timer.
17087 			 */
17088 			if (time_to_wait > msec_per_tick) {
17089 				TCP_STAT(tcps, tcp_timer_fire_early);
17090 				TCP_TIMER_RESTART(tcp, time_to_wait);
17091 				return;
17092 			}
17093 			/*
17094 			 * When we probe zero windows, we force the swnd open.
17095 			 * If our peer acks with a closed window swnd will be
17096 			 * set to zero by tcp_rput(). As long as we are
17097 			 * receiving acks tcp_rput will
17098 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
17099 			 * first and second interval actions.  NOTE: the timer
17100 			 * interval is allowed to continue its exponential
17101 			 * backoff.
17102 			 */
17103 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
17104 				if (tcp->tcp_debug) {
17105 					(void) strlog(TCP_MOD_ID, 0, 1,
17106 					    SL_TRACE, "tcp_timer: zero win");
17107 				}
17108 			} else {
17109 				/*
17110 				 * After retransmission, we need to do
17111 				 * slow start.  Set the ssthresh to one
17112 				 * half of current effective window and
17113 				 * cwnd to one MSS.  Also reset
17114 				 * tcp_cwnd_cnt.
17115 				 *
17116 				 * Note that if tcp_ssthresh is reduced because
17117 				 * of ECN, do not reduce it again unless it is
17118 				 * already one window of data away (tcp_cwr
17119 				 * should then be cleared) or this is a
17120 				 * timeout for a retransmitted segment.
17121 				 */
17122 				uint32_t npkt;
17123 
17124 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
17125 					npkt = ((tcp->tcp_timer_backoff ?
17126 					    tcp->tcp_cwnd_ssthresh :
17127 					    tcp->tcp_snxt -
17128 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
17129 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
17130 					    tcp->tcp_mss;
17131 				}
17132 				tcp->tcp_cwnd = tcp->tcp_mss;
17133 				tcp->tcp_cwnd_cnt = 0;
17134 				if (tcp->tcp_ecn_ok) {
17135 					tcp->tcp_cwr = B_TRUE;
17136 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17137 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17138 				}
17139 			}
17140 			break;
17141 		}
17142 		/*
17143 		 * We have something to send yet we cannot send.  The
17144 		 * reason can be:
17145 		 *
17146 		 * 1. Zero send window: we need to do zero window probe.
17147 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17148 		 * segments.
17149 		 * 3. SWS avoidance: receiver may have shrunk window,
17150 		 * reset our knowledge.
17151 		 *
17152 		 * Note that condition 2 can happen with either 1 or
17153 		 * 3.  But 1 and 3 are exclusive.
17154 		 */
17155 		if (tcp->tcp_unsent != 0) {
17156 			if (tcp->tcp_cwnd == 0) {
17157 				/*
17158 				 * Set tcp_cwnd to 1 MSS so that a
17159 				 * new segment can be sent out.  We
17160 				 * are "clocking out" new data when
17161 				 * the network is really congested.
17162 				 */
17163 				ASSERT(tcp->tcp_ecn_ok);
17164 				tcp->tcp_cwnd = tcp->tcp_mss;
17165 			}
17166 			if (tcp->tcp_swnd == 0) {
17167 				/* Extend window for zero window probe */
17168 				tcp->tcp_swnd++;
17169 				tcp->tcp_zero_win_probe = B_TRUE;
17170 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
17171 			} else {
17172 				/*
17173 				 * Handle timeout from sender SWS avoidance.
17174 				 * Reset our knowledge of the max send window
17175 				 * since the receiver might have reduced its
17176 				 * receive buffer.  Avoid setting tcp_max_swnd
17177 				 * to one since that will essentially disable
17178 				 * the SWS checks.
17179 				 *
17180 				 * Note that since we don't have a SWS
17181 				 * state variable, if the timeout is set
17182 				 * for ECN but not for SWS, this
17183 				 * code will also be executed.  This is
17184 				 * fine as tcp_max_swnd is updated
17185 				 * constantly and it will not affect
17186 				 * anything.
17187 				 */
17188 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17189 			}
17190 			tcp_wput_data(tcp, NULL, B_FALSE);
17191 			return;
17192 		}
17193 		/* Is there a FIN that needs to be to re retransmitted? */
17194 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17195 		    !tcp->tcp_fin_acked)
17196 			break;
17197 		/* Nothing to do, return without restarting timer. */
17198 		TCP_STAT(tcps, tcp_timer_fire_miss);
17199 		return;
17200 	case TCPS_FIN_WAIT_2:
17201 		/*
17202 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17203 		 * We waited some time for for peer's FIN, but it hasn't
17204 		 * arrived.  We flush the connection now to avoid
17205 		 * case where the peer has rebooted.
17206 		 */
17207 		if (TCP_IS_DETACHED(tcp)) {
17208 			(void) tcp_clean_death(tcp, 0, 23);
17209 		} else {
17210 			TCP_TIMER_RESTART(tcp,
17211 			    tcps->tcps_fin_wait_2_flush_interval);
17212 		}
17213 		return;
17214 	case TCPS_TIME_WAIT:
17215 		(void) tcp_clean_death(tcp, 0, 24);
17216 		return;
17217 	default:
17218 		if (tcp->tcp_debug) {
17219 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
17220 			    "tcp_timer: strange state (%d) %s",
17221 			    tcp->tcp_state, tcp_display(tcp, NULL,
17222 			    DISP_PORT_ONLY));
17223 		}
17224 		return;
17225 	}
17226 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17227 		/*
17228 		 * For zero window probe, we need to send indefinitely,
17229 		 * unless we have not heard from the other side for some
17230 		 * time...
17231 		 */
17232 		if ((tcp->tcp_zero_win_probe == 0) ||
17233 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17234 		    second_threshold)) {
17235 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
17236 			/*
17237 			 * If TCP is in SYN_RCVD state, send back a
17238 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17239 			 * should be zero in TCPS_SYN_RCVD state.
17240 			 */
17241 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17242 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17243 				    "in SYN_RCVD",
17244 				    tcp, tcp->tcp_snxt,
17245 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17246 			}
17247 			(void) tcp_clean_death(tcp,
17248 			    tcp->tcp_client_errno ?
17249 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17250 			return;
17251 		} else {
17252 			/*
17253 			 * Set tcp_ms_we_have_waited to second_threshold
17254 			 * so that in next timeout, we will do the above
17255 			 * check (lbolt - tcp_last_recv_time).  This is
17256 			 * also to avoid overflow.
17257 			 *
17258 			 * We don't need to decrement tcp_timer_backoff
17259 			 * to avoid overflow because it will be decremented
17260 			 * later if new timeout value is greater than
17261 			 * tcp_rexmit_interval_max.  In the case when
17262 			 * tcp_rexmit_interval_max is greater than
17263 			 * second_threshold, it means that we will wait
17264 			 * longer than second_threshold to send the next
17265 			 * window probe.
17266 			 */
17267 			tcp->tcp_ms_we_have_waited = second_threshold;
17268 		}
17269 	} else if (ms > first_threshold) {
17270 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17271 		    tcp->tcp_xmit_head != NULL) {
17272 			tcp->tcp_xmit_head =
17273 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17274 		}
17275 		/*
17276 		 * We have been retransmitting for too long...  The RTT
17277 		 * we calculated is probably incorrect.  Reinitialize it.
17278 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17279 		 * tcp_rtt_update so that we won't accidentally cache a
17280 		 * bad value.  But only do this if this is not a zero
17281 		 * window probe.
17282 		 */
17283 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17284 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17285 			    (tcp->tcp_rtt_sa >> 5);
17286 			tcp->tcp_rtt_sa = 0;
17287 			tcp_ip_notify(tcp);
17288 			tcp->tcp_rtt_update = 0;
17289 		}
17290 	}
17291 	tcp->tcp_timer_backoff++;
17292 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17293 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17294 	    tcps->tcps_rexmit_interval_min) {
17295 		/*
17296 		 * This means the original RTO is tcp_rexmit_interval_min.
17297 		 * So we will use tcp_rexmit_interval_min as the RTO value
17298 		 * and do the backoff.
17299 		 */
17300 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
17301 	} else {
17302 		ms <<= tcp->tcp_timer_backoff;
17303 	}
17304 	if (ms > tcps->tcps_rexmit_interval_max) {
17305 		ms = tcps->tcps_rexmit_interval_max;
17306 		/*
17307 		 * ms is at max, decrement tcp_timer_backoff to avoid
17308 		 * overflow.
17309 		 */
17310 		tcp->tcp_timer_backoff--;
17311 	}
17312 	tcp->tcp_ms_we_have_waited += ms;
17313 	if (tcp->tcp_zero_win_probe == 0) {
17314 		tcp->tcp_rto = ms;
17315 	}
17316 	TCP_TIMER_RESTART(tcp, ms);
17317 	/*
17318 	 * This is after a timeout and tcp_rto is backed off.  Set
17319 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17320 	 * restart the timer with a correct value.
17321 	 */
17322 	tcp->tcp_set_timer = 1;
17323 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17324 	if (mss > tcp->tcp_mss)
17325 		mss = tcp->tcp_mss;
17326 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17327 		mss = tcp->tcp_swnd;
17328 
17329 	if ((mp = tcp->tcp_xmit_head) != NULL)
17330 		mp->b_prev = (mblk_t *)lbolt;
17331 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17332 	    B_TRUE);
17333 
17334 	/*
17335 	 * When slow start after retransmission begins, start with
17336 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17337 	 * start phase.  tcp_snd_burst controls how many segments
17338 	 * can be sent because of an ack.
17339 	 */
17340 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17341 	tcp->tcp_snd_burst = TCP_CWND_SS;
17342 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17343 	    (tcp->tcp_unsent == 0)) {
17344 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17345 	} else {
17346 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17347 	}
17348 	tcp->tcp_rexmit = B_TRUE;
17349 	tcp->tcp_dupack_cnt = 0;
17350 
17351 	/*
17352 	 * Remove all rexmit SACK blk to start from fresh.
17353 	 */
17354 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17355 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17356 		tcp->tcp_num_notsack_blk = 0;
17357 		tcp->tcp_cnt_notsack_list = 0;
17358 	}
17359 	if (mp == NULL) {
17360 		return;
17361 	}
17362 	/* Attach credentials to retransmitted initial SYNs. */
17363 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17364 		mblk_setcred(mp, tcp->tcp_cred);
17365 		DB_CPID(mp) = tcp->tcp_cpid;
17366 	}
17367 
17368 	tcp->tcp_csuna = tcp->tcp_snxt;
17369 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17370 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17371 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17372 
17373 }
17374 
17375 static int
17376 tcp_do_unbind(conn_t *connp)
17377 {
17378 	tcp_t *tcp = connp->conn_tcp;
17379 	int error = 0;
17380 
17381 	switch (tcp->tcp_state) {
17382 	case TCPS_BOUND:
17383 	case TCPS_LISTEN:
17384 		break;
17385 	default:
17386 		return (-TOUTSTATE);
17387 	}
17388 
17389 	/*
17390 	 * Need to clean up all the eagers since after the unbind, segments
17391 	 * will no longer be delivered to this listener stream.
17392 	 */
17393 	mutex_enter(&tcp->tcp_eager_lock);
17394 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17395 		tcp_eager_cleanup(tcp, 0);
17396 	}
17397 	mutex_exit(&tcp->tcp_eager_lock);
17398 
17399 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17400 		tcp->tcp_ipha->ipha_src = 0;
17401 	} else {
17402 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17403 	}
17404 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17405 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17406 	tcp_bind_hash_remove(tcp);
17407 	tcp->tcp_state = TCPS_IDLE;
17408 	tcp->tcp_mdt = B_FALSE;
17409 
17410 	connp = tcp->tcp_connp;
17411 	connp->conn_mdt_ok = B_FALSE;
17412 	ipcl_hash_remove(connp);
17413 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17414 
17415 	return (error);
17416 }
17417 
17418 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17419 static void
17420 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
17421 {
17422 	int error = tcp_do_unbind(tcp->tcp_connp);
17423 
17424 	if (error > 0) {
17425 		tcp_err_ack(tcp, mp, TSYSERR, error);
17426 	} else if (error < 0) {
17427 		tcp_err_ack(tcp, mp, -error, 0);
17428 	} else {
17429 		/* Send M_FLUSH according to TPI */
17430 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17431 
17432 		mp = mi_tpi_ok_ack_alloc(mp);
17433 		putnext(tcp->tcp_rq, mp);
17434 	}
17435 }
17436 
17437 /*
17438  * Don't let port fall into the privileged range.
17439  * Since the extra privileged ports can be arbitrary we also
17440  * ensure that we exclude those from consideration.
17441  * tcp_g_epriv_ports is not sorted thus we loop over it until
17442  * there are no changes.
17443  *
17444  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17445  * but instead the code relies on:
17446  * - the fact that the address of the array and its size never changes
17447  * - the atomic assignment of the elements of the array
17448  *
17449  * Returns 0 if there are no more ports available.
17450  *
17451  * TS note: skip multilevel ports.
17452  */
17453 static in_port_t
17454 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17455 {
17456 	int i;
17457 	boolean_t restart = B_FALSE;
17458 	tcp_stack_t *tcps = tcp->tcp_tcps;
17459 
17460 	if (random && tcp_random_anon_port != 0) {
17461 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17462 		    sizeof (in_port_t));
17463 		/*
17464 		 * Unless changed by a sys admin, the smallest anon port
17465 		 * is 32768 and the largest anon port is 65535.  It is
17466 		 * very likely (50%) for the random port to be smaller
17467 		 * than the smallest anon port.  When that happens,
17468 		 * add port % (anon port range) to the smallest anon
17469 		 * port to get the random port.  It should fall into the
17470 		 * valid anon port range.
17471 		 */
17472 		if (port < tcps->tcps_smallest_anon_port) {
17473 			port = tcps->tcps_smallest_anon_port +
17474 			    port % (tcps->tcps_largest_anon_port -
17475 			    tcps->tcps_smallest_anon_port);
17476 		}
17477 	}
17478 
17479 retry:
17480 	if (port < tcps->tcps_smallest_anon_port)
17481 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17482 
17483 	if (port > tcps->tcps_largest_anon_port) {
17484 		if (restart)
17485 			return (0);
17486 		restart = B_TRUE;
17487 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17488 	}
17489 
17490 	if (port < tcps->tcps_smallest_nonpriv_port)
17491 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17492 
17493 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17494 		if (port == tcps->tcps_g_epriv_ports[i]) {
17495 			port++;
17496 			/*
17497 			 * Make sure whether the port is in the
17498 			 * valid range.
17499 			 */
17500 			goto retry;
17501 		}
17502 	}
17503 	if (is_system_labeled() &&
17504 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17505 	    IPPROTO_TCP, B_TRUE)) != 0) {
17506 		port = i;
17507 		goto retry;
17508 	}
17509 	return (port);
17510 }
17511 
17512 /*
17513  * Return the next anonymous port in the privileged port range for
17514  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17515  * downwards.  This is the same behavior as documented in the userland
17516  * library call rresvport(3N).
17517  *
17518  * TS note: skip multilevel ports.
17519  */
17520 static in_port_t
17521 tcp_get_next_priv_port(const tcp_t *tcp)
17522 {
17523 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17524 	in_port_t nextport;
17525 	boolean_t restart = B_FALSE;
17526 	tcp_stack_t *tcps = tcp->tcp_tcps;
17527 retry:
17528 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17529 	    next_priv_port >= IPPORT_RESERVED) {
17530 		next_priv_port = IPPORT_RESERVED - 1;
17531 		if (restart)
17532 			return (0);
17533 		restart = B_TRUE;
17534 	}
17535 	if (is_system_labeled() &&
17536 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17537 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17538 		next_priv_port = nextport;
17539 		goto retry;
17540 	}
17541 	return (next_priv_port--);
17542 }
17543 
17544 /* The write side r/w procedure. */
17545 
17546 #if CCS_STATS
17547 struct {
17548 	struct {
17549 		int64_t count, bytes;
17550 	} tot, hit;
17551 } wrw_stats;
17552 #endif
17553 
17554 /*
17555  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17556  * messages.
17557  */
17558 /* ARGSUSED */
17559 static void
17560 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17561 {
17562 	conn_t	*connp = (conn_t *)arg;
17563 	tcp_t	*tcp = connp->conn_tcp;
17564 	queue_t	*q = tcp->tcp_wq;
17565 
17566 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17567 	/*
17568 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17569 	 * Once the close starts, streamhead and sockfs will not let any data
17570 	 * packets come down (close ensures that there are no threads using the
17571 	 * queue and no new threads will come down) but since qprocsoff()
17572 	 * hasn't happened yet, a M_FLUSH or some non data message might
17573 	 * get reflected back (in response to our own FLUSHRW) and get
17574 	 * processed after tcp_close() is done. The conn would still be valid
17575 	 * because a ref would have added but we need to check the state
17576 	 * before actually processing the packet.
17577 	 */
17578 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17579 		freemsg(mp);
17580 		return;
17581 	}
17582 
17583 	switch (DB_TYPE(mp)) {
17584 	case M_IOCDATA:
17585 		tcp_wput_iocdata(tcp, mp);
17586 		break;
17587 	case M_FLUSH:
17588 		tcp_wput_flush(tcp, mp);
17589 		break;
17590 	default:
17591 		CALL_IP_WPUT(connp, q, mp);
17592 		break;
17593 	}
17594 }
17595 
17596 /*
17597  * The TCP fast path write put procedure.
17598  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17599  */
17600 /* ARGSUSED */
17601 void
17602 tcp_output(void *arg, mblk_t *mp, void *arg2)
17603 {
17604 	int		len;
17605 	int		hdrlen;
17606 	int		plen;
17607 	mblk_t		*mp1;
17608 	uchar_t		*rptr;
17609 	uint32_t	snxt;
17610 	tcph_t		*tcph;
17611 	struct datab	*db;
17612 	uint32_t	suna;
17613 	uint32_t	mss;
17614 	ipaddr_t	*dst;
17615 	ipaddr_t	*src;
17616 	uint32_t	sum;
17617 	int		usable;
17618 	conn_t		*connp = (conn_t *)arg;
17619 	tcp_t		*tcp = connp->conn_tcp;
17620 	uint32_t	msize;
17621 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17622 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17623 
17624 	/*
17625 	 * Try and ASSERT the minimum possible references on the
17626 	 * conn early enough. Since we are executing on write side,
17627 	 * the connection is obviously not detached and that means
17628 	 * there is a ref each for TCP and IP. Since we are behind
17629 	 * the squeue, the minimum references needed are 3. If the
17630 	 * conn is in classifier hash list, there should be an
17631 	 * extra ref for that (we check both the possibilities).
17632 	 */
17633 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17634 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17635 
17636 	ASSERT(DB_TYPE(mp) == M_DATA);
17637 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17638 
17639 	mutex_enter(&tcp->tcp_non_sq_lock);
17640 	tcp->tcp_squeue_bytes -= msize;
17641 	mutex_exit(&tcp->tcp_non_sq_lock);
17642 
17643 	/* Check to see if this connection wants to be re-fused. */
17644 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
17645 		if (tcp->tcp_ipversion == IPV4_VERSION) {
17646 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
17647 			    &tcp->tcp_saved_tcph);
17648 		} else {
17649 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
17650 			    &tcp->tcp_saved_tcph);
17651 		}
17652 	}
17653 	/* Bypass tcp protocol for fused tcp loopback */
17654 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17655 		return;
17656 
17657 	mss = tcp->tcp_mss;
17658 	if (tcp->tcp_xmit_zc_clean)
17659 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17660 
17661 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17662 	len = (int)(mp->b_wptr - mp->b_rptr);
17663 
17664 	/*
17665 	 * Criteria for fast path:
17666 	 *
17667 	 *   1. no unsent data
17668 	 *   2. single mblk in request
17669 	 *   3. connection established
17670 	 *   4. data in mblk
17671 	 *   5. len <= mss
17672 	 *   6. no tcp_valid bits
17673 	 */
17674 	if ((tcp->tcp_unsent != 0) ||
17675 	    (tcp->tcp_cork) ||
17676 	    (mp->b_cont != NULL) ||
17677 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17678 	    (len == 0) ||
17679 	    (len > mss) ||
17680 	    (tcp->tcp_valid_bits != 0)) {
17681 		tcp_wput_data(tcp, mp, B_FALSE);
17682 		return;
17683 	}
17684 
17685 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17686 	ASSERT(tcp->tcp_fin_sent == 0);
17687 
17688 	/* queue new packet onto retransmission queue */
17689 	if (tcp->tcp_xmit_head == NULL) {
17690 		tcp->tcp_xmit_head = mp;
17691 	} else {
17692 		tcp->tcp_xmit_last->b_cont = mp;
17693 	}
17694 	tcp->tcp_xmit_last = mp;
17695 	tcp->tcp_xmit_tail = mp;
17696 
17697 	/* find out how much we can send */
17698 	/* BEGIN CSTYLED */
17699 	/*
17700 	 *    un-acked	   usable
17701 	 *  |--------------|-----------------|
17702 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
17703 	 */
17704 	/* END CSTYLED */
17705 
17706 	/* start sending from tcp_snxt */
17707 	snxt = tcp->tcp_snxt;
17708 
17709 	/*
17710 	 * Check to see if this connection has been idled for some
17711 	 * time and no ACK is expected.  If it is, we need to slow
17712 	 * start again to get back the connection's "self-clock" as
17713 	 * described in VJ's paper.
17714 	 *
17715 	 * Refer to the comment in tcp_mss_set() for the calculation
17716 	 * of tcp_cwnd after idle.
17717 	 */
17718 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17719 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17720 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
17721 	}
17722 
17723 	usable = tcp->tcp_swnd;		/* tcp window size */
17724 	if (usable > tcp->tcp_cwnd)
17725 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17726 	usable -= snxt;		/* subtract stuff already sent */
17727 	suna = tcp->tcp_suna;
17728 	usable += suna;
17729 	/* usable can be < 0 if the congestion window is smaller */
17730 	if (len > usable) {
17731 		/* Can't send complete M_DATA in one shot */
17732 		goto slow;
17733 	}
17734 
17735 	mutex_enter(&tcp->tcp_non_sq_lock);
17736 	if (tcp->tcp_flow_stopped &&
17737 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17738 		tcp_clrqfull(tcp);
17739 	}
17740 	mutex_exit(&tcp->tcp_non_sq_lock);
17741 
17742 	/*
17743 	 * determine if anything to send (Nagle).
17744 	 *
17745 	 *   1. len < tcp_mss (i.e. small)
17746 	 *   2. unacknowledged data present
17747 	 *   3. len < nagle limit
17748 	 *   4. last packet sent < nagle limit (previous packet sent)
17749 	 */
17750 	if ((len < mss) && (snxt != suna) &&
17751 	    (len < (int)tcp->tcp_naglim) &&
17752 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17753 		/*
17754 		 * This was the first unsent packet and normally
17755 		 * mss < xmit_hiwater so there is no need to worry
17756 		 * about flow control. The next packet will go
17757 		 * through the flow control check in tcp_wput_data().
17758 		 */
17759 		/* leftover work from above */
17760 		tcp->tcp_unsent = len;
17761 		tcp->tcp_xmit_tail_unsent = len;
17762 
17763 		return;
17764 	}
17765 
17766 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17767 
17768 	if (snxt == suna) {
17769 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17770 	}
17771 
17772 	/* we have always sent something */
17773 	tcp->tcp_rack_cnt = 0;
17774 
17775 	tcp->tcp_snxt = snxt + len;
17776 	tcp->tcp_rack = tcp->tcp_rnxt;
17777 
17778 	if ((mp1 = dupb(mp)) == 0)
17779 		goto no_memory;
17780 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17781 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17782 
17783 	/* adjust tcp header information */
17784 	tcph = tcp->tcp_tcph;
17785 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17786 
17787 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17788 	sum = (sum >> 16) + (sum & 0xFFFF);
17789 	U16_TO_ABE16(sum, tcph->th_sum);
17790 
17791 	U32_TO_ABE32(snxt, tcph->th_seq);
17792 
17793 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17794 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17795 	BUMP_LOCAL(tcp->tcp_obsegs);
17796 
17797 	/* Update the latest receive window size in TCP header. */
17798 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17799 	    tcph->th_win);
17800 
17801 	tcp->tcp_last_sent_len = (ushort_t)len;
17802 
17803 	plen = len + tcp->tcp_hdr_len;
17804 
17805 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17806 		tcp->tcp_ipha->ipha_length = htons(plen);
17807 	} else {
17808 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17809 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17810 	}
17811 
17812 	/* see if we need to allocate a mblk for the headers */
17813 	hdrlen = tcp->tcp_hdr_len;
17814 	rptr = mp1->b_rptr - hdrlen;
17815 	db = mp1->b_datap;
17816 	if ((db->db_ref != 2) || rptr < db->db_base ||
17817 	    (!OK_32PTR(rptr))) {
17818 		/* NOTE: we assume allocb returns an OK_32PTR */
17819 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17820 		    tcps->tcps_wroff_xtra, BPRI_MED);
17821 		if (!mp) {
17822 			freemsg(mp1);
17823 			goto no_memory;
17824 		}
17825 		mp->b_cont = mp1;
17826 		mp1 = mp;
17827 		/* Leave room for Link Level header */
17828 		/* hdrlen = tcp->tcp_hdr_len; */
17829 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17830 		mp1->b_wptr = &rptr[hdrlen];
17831 	}
17832 	mp1->b_rptr = rptr;
17833 
17834 	/* Fill in the timestamp option. */
17835 	if (tcp->tcp_snd_ts_ok) {
17836 		U32_TO_BE32((uint32_t)lbolt,
17837 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17838 		U32_TO_BE32(tcp->tcp_ts_recent,
17839 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17840 	} else {
17841 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17842 	}
17843 
17844 	/* copy header into outgoing packet */
17845 	dst = (ipaddr_t *)rptr;
17846 	src = (ipaddr_t *)tcp->tcp_iphc;
17847 	dst[0] = src[0];
17848 	dst[1] = src[1];
17849 	dst[2] = src[2];
17850 	dst[3] = src[3];
17851 	dst[4] = src[4];
17852 	dst[5] = src[5];
17853 	dst[6] = src[6];
17854 	dst[7] = src[7];
17855 	dst[8] = src[8];
17856 	dst[9] = src[9];
17857 	if (hdrlen -= 40) {
17858 		hdrlen >>= 2;
17859 		dst += 10;
17860 		src += 10;
17861 		do {
17862 			*dst++ = *src++;
17863 		} while (--hdrlen);
17864 	}
17865 
17866 	/*
17867 	 * Set the ECN info in the TCP header.  Note that this
17868 	 * is not the template header.
17869 	 */
17870 	if (tcp->tcp_ecn_ok) {
17871 		SET_ECT(tcp, rptr);
17872 
17873 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17874 		if (tcp->tcp_ecn_echo_on)
17875 			tcph->th_flags[0] |= TH_ECE;
17876 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17877 			tcph->th_flags[0] |= TH_CWR;
17878 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17879 		}
17880 	}
17881 
17882 	if (tcp->tcp_ip_forward_progress) {
17883 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17884 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17885 		tcp->tcp_ip_forward_progress = B_FALSE;
17886 	}
17887 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17888 	return;
17889 
17890 	/*
17891 	 * If we ran out of memory, we pretend to have sent the packet
17892 	 * and that it was lost on the wire.
17893 	 */
17894 no_memory:
17895 	return;
17896 
17897 slow:
17898 	/* leftover work from above */
17899 	tcp->tcp_unsent = len;
17900 	tcp->tcp_xmit_tail_unsent = len;
17901 	tcp_wput_data(tcp, NULL, B_FALSE);
17902 }
17903 
17904 /* ARGSUSED */
17905 void
17906 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17907 {
17908 	conn_t			*connp = (conn_t *)arg;
17909 	tcp_t			*tcp = connp->conn_tcp;
17910 	queue_t			*q = tcp->tcp_rq;
17911 	struct tcp_options	*tcpopt;
17912 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17913 
17914 	/* socket options */
17915 	uint_t 			sopp_flags;
17916 	ssize_t			sopp_rxhiwat;
17917 	ssize_t			sopp_maxblk;
17918 	ushort_t		sopp_wroff;
17919 	ushort_t		sopp_tail;
17920 	ushort_t		sopp_copyopt;
17921 
17922 	tcpopt = (struct tcp_options *)mp->b_rptr;
17923 
17924 	/*
17925 	 * Drop the eager's ref on the listener, that was placed when
17926 	 * this eager began life in tcp_conn_request.
17927 	 */
17928 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17929 	if (IPCL_IS_NONSTR(connp)) {
17930 		/* Safe to free conn_ind message */
17931 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17932 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17933 
17934 		/* The listener tells us which upper handle to use */
17935 		ASSERT(tcpopt->to_flags & TCPOPT_UPPERHANDLE);
17936 		connp->conn_upper_handle = tcpopt->to_handle;
17937 	}
17938 
17939 	tcp->tcp_detached = B_FALSE;
17940 
17941 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17942 		/*
17943 		 * Someone blewoff the eager before we could finish
17944 		 * the accept.
17945 		 *
17946 		 * The only reason eager exists it because we put in
17947 		 * a ref on it when conn ind went up. We need to send
17948 		 * a disconnect indication up while the last reference
17949 		 * on the eager will be dropped by the squeue when we
17950 		 * return.
17951 		 */
17952 		ASSERT(tcp->tcp_listener == NULL);
17953 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17954 			if (IPCL_IS_NONSTR(connp)) {
17955 				ASSERT(tcp->tcp_issocket);
17956 				(*connp->conn_upcalls->su_disconnected)(
17957 				    connp->conn_upper_handle, tcp->tcp_connid,
17958 				    ECONNREFUSED);
17959 				freemsg(mp);
17960 			} else {
17961 				struct	T_discon_ind	*tdi;
17962 
17963 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17964 				/*
17965 				 * Let us reuse the incoming mblk to avoid
17966 				 * memory allocation failure problems. We know
17967 				 * that the size of the incoming mblk i.e.
17968 				 * stroptions is greater than sizeof
17969 				 * T_discon_ind. So the reallocb below can't
17970 				 * fail.
17971 				 */
17972 				freemsg(mp->b_cont);
17973 				mp->b_cont = NULL;
17974 				ASSERT(DB_REF(mp) == 1);
17975 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17976 				    B_FALSE);
17977 				ASSERT(mp != NULL);
17978 				DB_TYPE(mp) = M_PROTO;
17979 				((union T_primitives *)mp->b_rptr)->type =
17980 				    T_DISCON_IND;
17981 				tdi = (struct T_discon_ind *)mp->b_rptr;
17982 				if (tcp->tcp_issocket) {
17983 					tdi->DISCON_reason = ECONNREFUSED;
17984 					tdi->SEQ_number = 0;
17985 				} else {
17986 					tdi->DISCON_reason = ENOPROTOOPT;
17987 					tdi->SEQ_number =
17988 					    tcp->tcp_conn_req_seqnum;
17989 				}
17990 				mp->b_wptr = mp->b_rptr +
17991 				    sizeof (struct T_discon_ind);
17992 				putnext(q, mp);
17993 				return;
17994 			}
17995 		}
17996 		if (tcp->tcp_hard_binding) {
17997 			tcp->tcp_hard_binding = B_FALSE;
17998 			tcp->tcp_hard_bound = B_TRUE;
17999 		}
18000 		return;
18001 	}
18002 
18003 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
18004 		int boundif = tcpopt->to_boundif;
18005 		uint_t len = sizeof (int);
18006 
18007 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
18008 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
18009 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred, NULL);
18010 	}
18011 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
18012 		uint_t on = 1;
18013 		uint_t len = sizeof (uint_t);
18014 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
18015 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
18016 		    (uchar_t *)&on, NULL, tcp->tcp_cred, NULL);
18017 	}
18018 
18019 	/*
18020 	 * For a loopback connection with tcp_direct_sockfs on, note that
18021 	 * we don't have to protect tcp_rcv_list yet because synchronous
18022 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
18023 	 * possibly race with us.
18024 	 */
18025 
18026 	/*
18027 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
18028 	 * properly.  This is the first time we know of the acceptor'
18029 	 * queue.  So we do it here.
18030 	 *
18031 	 * XXX
18032 	 */
18033 	if (tcp->tcp_rcv_list == NULL) {
18034 		/*
18035 		 * Recv queue is empty, tcp_rwnd should not have changed.
18036 		 * That means it should be equal to the listener's tcp_rwnd.
18037 		 */
18038 		if (!IPCL_IS_NONSTR(connp))
18039 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
18040 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
18041 	} else {
18042 #ifdef DEBUG
18043 		mblk_t *tmp;
18044 		mblk_t	*mp1;
18045 		uint_t	cnt = 0;
18046 
18047 		mp1 = tcp->tcp_rcv_list;
18048 		while ((tmp = mp1) != NULL) {
18049 			mp1 = tmp->b_next;
18050 			cnt += msgdsize(tmp);
18051 		}
18052 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
18053 #endif
18054 		/* There is some data, add them back to get the max. */
18055 		if (!IPCL_IS_NONSTR(connp))
18056 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
18057 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
18058 	}
18059 	/*
18060 	 * This is the first time we run on the correct
18061 	 * queue after tcp_accept. So fix all the q parameters
18062 	 * here.
18063 	 */
18064 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
18065 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
18066 
18067 	/*
18068 	 * Record the stream head's high water mark for this endpoint;
18069 	 * this is used for flow-control purposes.
18070 	 */
18071 	sopp_rxhiwat = tcp->tcp_fused ?
18072 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
18073 	    MAX(tcp->tcp_recv_hiwater, tcps->tcps_sth_rcv_hiwat);
18074 
18075 	/*
18076 	 * Determine what write offset value to use depending on SACK and
18077 	 * whether the endpoint is fused or not.
18078 	 */
18079 	if (tcp->tcp_fused) {
18080 		ASSERT(tcp->tcp_loopback);
18081 		ASSERT(tcp->tcp_loopback_peer != NULL);
18082 		/*
18083 		 * For fused tcp loopback, set the stream head's write
18084 		 * offset value to zero since we won't be needing any room
18085 		 * for TCP/IP headers.  This would also improve performance
18086 		 * since it would reduce the amount of work done by kmem.
18087 		 * Non-fused tcp loopback case is handled separately below.
18088 		 */
18089 		sopp_wroff = 0;
18090 		/*
18091 		 * Update the peer's transmit parameters according to
18092 		 * our recently calculated high water mark value.
18093 		 */
18094 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
18095 	} else if (tcp->tcp_snd_sack_ok) {
18096 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
18097 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
18098 	} else {
18099 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
18100 		    tcps->tcps_wroff_xtra);
18101 	}
18102 
18103 	/*
18104 	 * If this is endpoint is handling SSL, then reserve extra
18105 	 * offset and space at the end.
18106 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
18107 	 * overriding the previous setting. The extra cost of signing and
18108 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
18109 	 * instead of a single contiguous one by the stream head
18110 	 * largely outweighs the statistical reduction of ACKs, when
18111 	 * applicable. The peer will also save on decryption and verification
18112 	 * costs.
18113 	 */
18114 	if (tcp->tcp_kssl_ctx != NULL) {
18115 		sopp_wroff += SSL3_WROFFSET;
18116 
18117 		sopp_flags |= SOCKOPT_TAIL;
18118 		sopp_tail = SSL3_MAX_TAIL_LEN;
18119 
18120 		sopp_flags |= SOCKOPT_ZCOPY;
18121 		sopp_copyopt = ZCVMUNSAFE;
18122 
18123 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
18124 	}
18125 
18126 	/* Send the options up */
18127 	if (IPCL_IS_NONSTR(connp)) {
18128 		struct sock_proto_props sopp;
18129 
18130 		sopp.sopp_flags = sopp_flags;
18131 		sopp.sopp_wroff = sopp_wroff;
18132 		sopp.sopp_maxblk = sopp_maxblk;
18133 		sopp.sopp_rxhiwat = sopp_rxhiwat;
18134 		if (sopp_flags & SOCKOPT_TAIL) {
18135 			ASSERT(tcp->tcp_kssl_ctx != NULL);
18136 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
18137 			sopp.sopp_tail = sopp_tail;
18138 			sopp.sopp_zcopyflag = sopp_copyopt;
18139 		}
18140 		(*connp->conn_upcalls->su_set_proto_props)
18141 		    (connp->conn_upper_handle, &sopp);
18142 	} else {
18143 		struct stroptions *stropt;
18144 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18145 		if (stropt_mp == NULL) {
18146 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
18147 			return;
18148 		}
18149 		DB_TYPE(stropt_mp) = M_SETOPTS;
18150 		stropt = (struct stroptions *)stropt_mp->b_rptr;
18151 		stropt_mp->b_wptr += sizeof (struct stroptions);
18152 		stropt = (struct stroptions *)stropt_mp->b_rptr;
18153 		stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
18154 		stropt->so_hiwat = sopp_rxhiwat;
18155 		stropt->so_wroff = sopp_wroff;
18156 		stropt->so_maxblk = sopp_maxblk;
18157 
18158 		if (sopp_flags & SOCKOPT_TAIL) {
18159 			ASSERT(tcp->tcp_kssl_ctx != NULL);
18160 
18161 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
18162 			stropt->so_tail = sopp_tail;
18163 			stropt->so_copyopt = sopp_copyopt;
18164 		}
18165 
18166 		/* Send the options up */
18167 		putnext(q, stropt_mp);
18168 	}
18169 
18170 	freemsg(mp);
18171 	/*
18172 	 * Pass up any data and/or a fin that has been received.
18173 	 *
18174 	 * Adjust receive window in case it had decreased
18175 	 * (because there is data <=> tcp_rcv_list != NULL)
18176 	 * while the connection was detached. Note that
18177 	 * in case the eager was flow-controlled, w/o this
18178 	 * code, the rwnd may never open up again!
18179 	 */
18180 	if (tcp->tcp_rcv_list != NULL) {
18181 		if (IPCL_IS_NONSTR(connp)) {
18182 			mblk_t *mp;
18183 			int space_left;
18184 			int error;
18185 			boolean_t push = B_TRUE;
18186 
18187 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
18188 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
18189 			    &push) >= 0) {
18190 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
18191 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18192 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
18193 					tcp_xmit_ctl(NULL,
18194 					    tcp, (tcp->tcp_swnd == 0) ?
18195 					    tcp->tcp_suna : tcp->tcp_snxt,
18196 					    tcp->tcp_rnxt, TH_ACK);
18197 				}
18198 			}
18199 			while ((mp = tcp->tcp_rcv_list) != NULL) {
18200 				push = B_TRUE;
18201 				tcp->tcp_rcv_list = mp->b_next;
18202 				mp->b_next = NULL;
18203 				space_left = (*connp->conn_upcalls->su_recv)
18204 				    (connp->conn_upper_handle, mp, msgdsize(mp),
18205 				    0, &error, &push);
18206 				if (space_left < 0) {
18207 					/*
18208 					 * At this point the eager is not
18209 					 * visible to anyone, so fallback
18210 					 * can not happen.
18211 					 */
18212 					ASSERT(error != EOPNOTSUPP);
18213 				}
18214 			}
18215 			tcp->tcp_rcv_last_head = NULL;
18216 			tcp->tcp_rcv_last_tail = NULL;
18217 			tcp->tcp_rcv_cnt = 0;
18218 		} else {
18219 			/* We drain directly in case of fused tcp loopback */
18220 			sodirect_t *sodp;
18221 
18222 			if (!tcp->tcp_fused && canputnext(q)) {
18223 				tcp->tcp_rwnd = q->q_hiwat;
18224 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18225 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
18226 					tcp_xmit_ctl(NULL,
18227 					    tcp, (tcp->tcp_swnd == 0) ?
18228 					    tcp->tcp_suna : tcp->tcp_snxt,
18229 					    tcp->tcp_rnxt, TH_ACK);
18230 				}
18231 			}
18232 
18233 			SOD_PTR_ENTER(tcp, sodp);
18234 			if (sodp != NULL) {
18235 				/* Sodirect, move from rcv_list */
18236 				ASSERT(!tcp->tcp_fused);
18237 				while ((mp = tcp->tcp_rcv_list) != NULL) {
18238 					tcp->tcp_rcv_list = mp->b_next;
18239 					mp->b_next = NULL;
18240 					(void) tcp_rcv_sod_enqueue(tcp, sodp,
18241 					    mp, msgdsize(mp));
18242 				}
18243 				tcp->tcp_rcv_last_head = NULL;
18244 				tcp->tcp_rcv_last_tail = NULL;
18245 				tcp->tcp_rcv_cnt = 0;
18246 				(void) tcp_rcv_sod_wakeup(tcp, sodp);
18247 				/* sod_wakeup() did the mutex_exit() */
18248 			} else {
18249 				/* Not sodirect, drain */
18250 				(void) tcp_rcv_drain(tcp);
18251 			}
18252 		}
18253 
18254 		/*
18255 		 * For fused tcp loopback, back-enable peer endpoint
18256 		 * if it's currently flow-controlled.
18257 		 */
18258 		if (tcp->tcp_fused) {
18259 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18260 
18261 			ASSERT(peer_tcp != NULL);
18262 			ASSERT(peer_tcp->tcp_fused);
18263 			/*
18264 			 * In order to change the peer's tcp_flow_stopped,
18265 			 * we need to take locks for both end points. The
18266 			 * highest address is taken first.
18267 			 */
18268 			if (peer_tcp > tcp) {
18269 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18270 				mutex_enter(&tcp->tcp_non_sq_lock);
18271 			} else {
18272 				mutex_enter(&tcp->tcp_non_sq_lock);
18273 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18274 			}
18275 			if (peer_tcp->tcp_flow_stopped) {
18276 				tcp_clrqfull(peer_tcp);
18277 				TCP_STAT(tcps, tcp_fusion_backenabled);
18278 			}
18279 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18280 			mutex_exit(&tcp->tcp_non_sq_lock);
18281 		}
18282 	}
18283 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18284 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18285 		tcp->tcp_ordrel_done = B_TRUE;
18286 		if (IPCL_IS_NONSTR(connp)) {
18287 			ASSERT(tcp->tcp_ordrel_mp == NULL);
18288 			(*connp->conn_upcalls->su_opctl)(
18289 			    connp->conn_upper_handle,
18290 			    SOCK_OPCTL_SHUT_RECV, 0);
18291 		} else {
18292 			mp = tcp->tcp_ordrel_mp;
18293 			tcp->tcp_ordrel_mp = NULL;
18294 			putnext(q, mp);
18295 		}
18296 	}
18297 	if (tcp->tcp_hard_binding) {
18298 		tcp->tcp_hard_binding = B_FALSE;
18299 		tcp->tcp_hard_bound = B_TRUE;
18300 	}
18301 
18302 	/* We can enable synchronous streams for STREAMS tcp endpoint now */
18303 	if (tcp->tcp_fused && !IPCL_IS_NONSTR(connp) &&
18304 	    tcp->tcp_loopback_peer != NULL &&
18305 	    !IPCL_IS_NONSTR(tcp->tcp_loopback_peer->tcp_connp)) {
18306 		tcp_fuse_syncstr_enable_pair(tcp);
18307 	}
18308 
18309 	if (tcp->tcp_ka_enabled) {
18310 		tcp->tcp_ka_last_intrvl = 0;
18311 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18312 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18313 	}
18314 
18315 	/*
18316 	 * At this point, eager is fully established and will
18317 	 * have the following references -
18318 	 *
18319 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18320 	 * 1 reference for the squeue which will be dropped by the squeue as
18321 	 *	soon as this function returns.
18322 	 * There will be 1 additonal reference for being in classifier
18323 	 *	hash list provided something bad hasn't happened.
18324 	 */
18325 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18326 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18327 }
18328 
18329 /*
18330  * The function called through squeue to get behind listener's perimeter to
18331  * send a deffered conn_ind.
18332  */
18333 /* ARGSUSED */
18334 void
18335 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18336 {
18337 	conn_t	*connp = (conn_t *)arg;
18338 	tcp_t *listener = connp->conn_tcp;
18339 	struct T_conn_ind *conn_ind;
18340 	tcp_t *tcp;
18341 
18342 	if (listener->tcp_state == TCPS_CLOSED ||
18343 	    TCP_IS_DETACHED(listener)) {
18344 		/*
18345 		 * If listener has closed, it would have caused a
18346 		 * a cleanup/blowoff to happen for the eager.
18347 		 */
18348 
18349 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18350 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18351 		    conn_ind->OPT_length);
18352 		/*
18353 		 * We need to drop the ref on eager that was put
18354 		 * tcp_rput_data() before trying to send the conn_ind
18355 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18356 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18357 		 * listener is closed so we drop the ref.
18358 		 */
18359 		CONN_DEC_REF(tcp->tcp_connp);
18360 		freemsg(mp);
18361 		return;
18362 	}
18363 	if (IPCL_IS_NONSTR(connp)) {
18364 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18365 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18366 		    conn_ind->OPT_length);
18367 
18368 		if ((*connp->conn_upcalls->su_newconn)
18369 		    (connp->conn_upper_handle,
18370 		    (sock_lower_handle_t)tcp->tcp_connp,
18371 		    &sock_tcp_downcalls, DB_CRED(mp), DB_CPID(mp),
18372 		    &tcp->tcp_connp->conn_upcalls) != NULL) {
18373 			/* Keep the message around in case of fallback */
18374 			tcp->tcp_conn.tcp_eager_conn_ind = mp;
18375 		} else {
18376 			freemsg(mp);
18377 		}
18378 	} else {
18379 		putnext(listener->tcp_rq, mp);
18380 	}
18381 }
18382 
18383 /* ARGSUSED */
18384 static int
18385 tcp_accept_common(conn_t *lconnp, conn_t *econnp,
18386     sock_upper_handle_t sock_handle, cred_t *cr)
18387 {
18388 	tcp_t *listener, *eager;
18389 	mblk_t *opt_mp;
18390 	struct tcp_options *tcpopt;
18391 
18392 	listener = lconnp->conn_tcp;
18393 	ASSERT(listener->tcp_state == TCPS_LISTEN);
18394 	eager = econnp->conn_tcp;
18395 	ASSERT(eager->tcp_listener != NULL);
18396 
18397 	ASSERT(eager->tcp_rq != NULL);
18398 
18399 	/* If tcp_fused and sodirect enabled disable it */
18400 	if (eager->tcp_fused && eager->tcp_sodirect != NULL) {
18401 		/* Fused, disable sodirect */
18402 		mutex_enter(eager->tcp_sodirect->sod_lockp);
18403 		SOD_DISABLE(eager->tcp_sodirect);
18404 		mutex_exit(eager->tcp_sodirect->sod_lockp);
18405 		eager->tcp_sodirect = NULL;
18406 	}
18407 
18408 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
18409 	if (opt_mp == NULL) {
18410 		return (-TPROTO);
18411 	}
18412 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
18413 	eager->tcp_issocket = B_TRUE;
18414 
18415 	econnp->conn_upcalls = lconnp->conn_upcalls;
18416 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18417 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18418 	ASSERT(econnp->conn_netstack ==
18419 	    listener->tcp_connp->conn_netstack);
18420 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18421 
18422 	/* Put the ref for IP */
18423 	CONN_INC_REF(econnp);
18424 
18425 	/*
18426 	 * We should have minimum of 3 references on the conn
18427 	 * at this point. One each for TCP and IP and one for
18428 	 * the T_conn_ind that was sent up when the 3-way handshake
18429 	 * completed. In the normal case we would also have another
18430 	 * reference (making a total of 4) for the conn being in the
18431 	 * classifier hash list. However the eager could have received
18432 	 * an RST subsequently and tcp_closei_local could have removed
18433 	 * the eager from the classifier hash list, hence we can't
18434 	 * assert that reference.
18435 	 */
18436 	ASSERT(econnp->conn_ref >= 3);
18437 
18438 	opt_mp->b_datap->db_type = M_SETOPTS;
18439 	opt_mp->b_wptr += sizeof (struct tcp_options);
18440 
18441 	/*
18442 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18443 	 * from listener to acceptor. In case of non-STREAMS sockets,
18444 	 * we also need to pass the upper handle along.
18445 	 */
18446 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
18447 	tcpopt->to_flags = 0;
18448 
18449 	if (IPCL_IS_NONSTR(econnp)) {
18450 		ASSERT(sock_handle != NULL);
18451 		tcpopt->to_flags |= TCPOPT_UPPERHANDLE;
18452 		tcpopt->to_handle = sock_handle;
18453 	}
18454 	if (listener->tcp_bound_if != 0) {
18455 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
18456 		tcpopt->to_boundif = listener->tcp_bound_if;
18457 	}
18458 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18459 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
18460 	}
18461 
18462 	mutex_enter(&listener->tcp_eager_lock);
18463 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18464 
18465 		tcp_t *tail;
18466 		tcp_t *tcp;
18467 		mblk_t *mp1;
18468 
18469 		tcp = listener->tcp_eager_prev_q0;
18470 		/*
18471 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
18472 		 * deferred T_conn_ind queue. We need to get to the head
18473 		 * of the queue in order to send up T_conn_ind the same
18474 		 * order as how the 3WHS is completed.
18475 		 */
18476 		while (tcp != listener) {
18477 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18478 			    !tcp->tcp_kssl_pending)
18479 				break;
18480 			else
18481 				tcp = tcp->tcp_eager_prev_q0;
18482 		}
18483 		/* None of the pending eagers can be sent up now */
18484 		if (tcp == listener)
18485 			goto no_more_eagers;
18486 
18487 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18488 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18489 		/* Move from q0 to q */
18490 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18491 		listener->tcp_conn_req_cnt_q0--;
18492 		listener->tcp_conn_req_cnt_q++;
18493 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18494 		    tcp->tcp_eager_prev_q0;
18495 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18496 		    tcp->tcp_eager_next_q0;
18497 		tcp->tcp_eager_prev_q0 = NULL;
18498 		tcp->tcp_eager_next_q0 = NULL;
18499 		tcp->tcp_conn_def_q0 = B_FALSE;
18500 
18501 		/* Make sure the tcp isn't in the list of droppables */
18502 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18503 		    tcp->tcp_eager_prev_drop_q0 == NULL);
18504 
18505 		/*
18506 		 * Insert at end of the queue because sockfs sends
18507 		 * down T_CONN_RES in chronological order. Leaving
18508 		 * the older conn indications at front of the queue
18509 		 * helps reducing search time.
18510 		 */
18511 		tail = listener->tcp_eager_last_q;
18512 		if (tail != NULL) {
18513 			tail->tcp_eager_next_q = tcp;
18514 		} else {
18515 			listener->tcp_eager_next_q = tcp;
18516 		}
18517 		listener->tcp_eager_last_q = tcp;
18518 		tcp->tcp_eager_next_q = NULL;
18519 
18520 		/* Need to get inside the listener perimeter */
18521 		CONN_INC_REF(listener->tcp_connp);
18522 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
18523 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
18524 		    SQTAG_TCP_SEND_PENDING);
18525 	}
18526 no_more_eagers:
18527 	tcp_eager_unlink(eager);
18528 	mutex_exit(&listener->tcp_eager_lock);
18529 
18530 	/*
18531 	 * At this point, the eager is detached from the listener
18532 	 * but we still have an extra refs on eager (apart from the
18533 	 * usual tcp references). The ref was placed in tcp_rput_data
18534 	 * before sending the conn_ind in tcp_send_conn_ind.
18535 	 * The ref will be dropped in tcp_accept_finish().
18536 	 */
18537 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
18538 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
18539 	return (0);
18540 }
18541 
18542 int
18543 tcp_accept(sock_lower_handle_t lproto_handle,
18544     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
18545     cred_t *cr)
18546 {
18547 	conn_t *lconnp, *econnp;
18548 	tcp_t *listener, *eager;
18549 	tcp_stack_t	*tcps;
18550 
18551 	lconnp = (conn_t *)lproto_handle;
18552 	listener = lconnp->conn_tcp;
18553 	ASSERT(listener->tcp_state == TCPS_LISTEN);
18554 	econnp = (conn_t *)eproto_handle;
18555 	eager = econnp->conn_tcp;
18556 	ASSERT(eager->tcp_listener != NULL);
18557 	tcps = eager->tcp_tcps;
18558 
18559 	ASSERT(IPCL_IS_NONSTR(econnp));
18560 	/*
18561 	 * Create helper stream if it is a non-TPI TCP connection.
18562 	 */
18563 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
18564 		ip1dbg(("tcp_accept: create of IP helper stream"
18565 		    " failed\n"));
18566 		return (EPROTO);
18567 	}
18568 	eager->tcp_rq = econnp->conn_rq;
18569 	eager->tcp_wq = econnp->conn_wq;
18570 
18571 	ASSERT(eager->tcp_rq != NULL);
18572 
18573 	eager->tcp_sodirect = SOD_SOTOSODP(sock_handle);
18574 	return (tcp_accept_common(lconnp, econnp, sock_handle, cr));
18575 }
18576 
18577 
18578 /*
18579  * This is the STREAMS entry point for T_CONN_RES coming down on
18580  * Acceptor STREAM when  sockfs listener does accept processing.
18581  * Read the block comment on top of tcp_conn_request().
18582  */
18583 void
18584 tcp_tpi_accept(queue_t *q, mblk_t *mp)
18585 {
18586 	queue_t *rq = RD(q);
18587 	struct T_conn_res *conn_res;
18588 	tcp_t *eager;
18589 	tcp_t *listener;
18590 	struct T_ok_ack *ok;
18591 	t_scalar_t PRIM_type;
18592 	conn_t *econnp;
18593 
18594 	ASSERT(DB_TYPE(mp) == M_PROTO);
18595 
18596 	conn_res = (struct T_conn_res *)mp->b_rptr;
18597 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18598 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18599 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18600 		if (mp != NULL)
18601 			putnext(rq, mp);
18602 		return;
18603 	}
18604 	switch (conn_res->PRIM_type) {
18605 	case O_T_CONN_RES:
18606 	case T_CONN_RES:
18607 		/*
18608 		 * We pass up an err ack if allocb fails. This will
18609 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18610 		 * tcp_eager_blowoff to be called. sockfs will then call
18611 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18612 		 * we need to do the allocb up here because we have to
18613 		 * make sure rq->q_qinfo->qi_qclose still points to the
18614 		 * correct function (tcpclose_accept) in case allocb
18615 		 * fails.
18616 		 */
18617 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18618 		    &eager, conn_res->OPT_length);
18619 		PRIM_type = conn_res->PRIM_type;
18620 		mp->b_datap->db_type = M_PCPROTO;
18621 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18622 		ok = (struct T_ok_ack *)mp->b_rptr;
18623 		ok->PRIM_type = T_OK_ACK;
18624 		ok->CORRECT_prim = PRIM_type;
18625 		econnp = eager->tcp_connp;
18626 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
18627 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
18628 		eager->tcp_rq = rq;
18629 		eager->tcp_wq = q;
18630 		rq->q_ptr = econnp;
18631 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
18632 		q->q_ptr = econnp;
18633 		q->q_qinfo = &tcp_winit;
18634 		listener = eager->tcp_listener;
18635 
18636 		/*
18637 		 * TCP is _D_SODIRECT and sockfs is directly above so
18638 		 * save shared sodirect_t pointer (if any).
18639 		 */
18640 		eager->tcp_sodirect = SOD_QTOSODP(eager->tcp_rq);
18641 		if (tcp_accept_common(listener->tcp_connp,
18642 		    econnp, NULL, CRED()) < 0) {
18643 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18644 			if (mp != NULL)
18645 				putnext(rq, mp);
18646 			return;
18647 		}
18648 
18649 		/*
18650 		 * Send the new local address also up to sockfs. There
18651 		 * should already be enough space in the mp that came
18652 		 * down from soaccept().
18653 		 */
18654 		if (eager->tcp_family == AF_INET) {
18655 			sin_t *sin;
18656 
18657 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18658 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18659 			sin = (sin_t *)mp->b_wptr;
18660 			mp->b_wptr += sizeof (sin_t);
18661 			sin->sin_family = AF_INET;
18662 			sin->sin_port = eager->tcp_lport;
18663 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18664 		} else {
18665 			sin6_t *sin6;
18666 
18667 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18668 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18669 			sin6 = (sin6_t *)mp->b_wptr;
18670 			mp->b_wptr += sizeof (sin6_t);
18671 			sin6->sin6_family = AF_INET6;
18672 			sin6->sin6_port = eager->tcp_lport;
18673 			if (eager->tcp_ipversion == IPV4_VERSION) {
18674 				sin6->sin6_flowinfo = 0;
18675 				IN6_IPADDR_TO_V4MAPPED(
18676 				    eager->tcp_ipha->ipha_src,
18677 				    &sin6->sin6_addr);
18678 			} else {
18679 				ASSERT(eager->tcp_ip6h != NULL);
18680 				sin6->sin6_flowinfo =
18681 				    eager->tcp_ip6h->ip6_vcf &
18682 				    ~IPV6_VERS_AND_FLOW_MASK;
18683 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18684 			}
18685 			sin6->sin6_scope_id = 0;
18686 			sin6->__sin6_src_id = 0;
18687 		}
18688 
18689 		putnext(rq, mp);
18690 		return;
18691 	default:
18692 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18693 		if (mp != NULL)
18694 			putnext(rq, mp);
18695 		return;
18696 	}
18697 }
18698 
18699 static int
18700 tcp_getmyname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18701 {
18702 	sin_t *sin = (sin_t *)sa;
18703 	sin6_t *sin6 = (sin6_t *)sa;
18704 
18705 	switch (tcp->tcp_family) {
18706 	case AF_INET:
18707 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18708 
18709 		if (*salenp < sizeof (sin_t))
18710 			return (EINVAL);
18711 
18712 		*sin = sin_null;
18713 		sin->sin_family = AF_INET;
18714 		sin->sin_port = tcp->tcp_lport;
18715 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
18716 		break;
18717 
18718 	case AF_INET6:
18719 		if (*salenp < sizeof (sin6_t))
18720 			return (EINVAL);
18721 
18722 		*sin6 = sin6_null;
18723 		sin6->sin6_family = AF_INET6;
18724 		sin6->sin6_port = tcp->tcp_lport;
18725 		if (tcp->tcp_ipversion == IPV4_VERSION) {
18726 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
18727 			    &sin6->sin6_addr);
18728 		} else {
18729 			sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
18730 		}
18731 		break;
18732 	}
18733 
18734 	return (0);
18735 }
18736 
18737 static int
18738 i_tcp_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18739 {
18740 	sin_t *sin = (sin_t *)sa;
18741 	sin6_t *sin6 = (sin6_t *)sa;
18742 
18743 	if (tcp->tcp_state < TCPS_SYN_RCVD)
18744 		return (ENOTCONN);
18745 
18746 	switch (tcp->tcp_family) {
18747 	case AF_INET:
18748 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18749 
18750 		if (*salenp < sizeof (sin_t))
18751 			return (EINVAL);
18752 
18753 		*sin = sin_null;
18754 		sin->sin_family = AF_INET;
18755 		sin->sin_port = tcp->tcp_fport;
18756 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
18757 		    sin->sin_addr.s_addr);
18758 		*salenp = sizeof (sin_t);
18759 		break;
18760 
18761 	case AF_INET6:
18762 		if (*salenp < sizeof (sin6_t))
18763 			return (EINVAL);
18764 
18765 		*sin6 = sin6_null;
18766 		sin6->sin6_family = AF_INET6;
18767 		sin6->sin6_port = tcp->tcp_fport;
18768 		sin6->sin6_addr = tcp->tcp_remote_v6;
18769 		if (tcp->tcp_ipversion == IPV6_VERSION) {
18770 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
18771 			    ~IPV6_VERS_AND_FLOW_MASK;
18772 		}
18773 		*salenp = sizeof (sin6_t);
18774 		break;
18775 	}
18776 
18777 	return (0);
18778 }
18779 
18780 /*
18781  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
18782  */
18783 static void
18784 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
18785 {
18786 	void	*data;
18787 	mblk_t	*datamp = mp->b_cont;
18788 	tcp_t	*tcp = Q_TO_TCP(q);
18789 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
18790 
18791 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
18792 		cmdp->cb_error = EPROTO;
18793 		qreply(q, mp);
18794 		return;
18795 	}
18796 
18797 	data = datamp->b_rptr;
18798 
18799 	switch (cmdp->cb_cmd) {
18800 	case TI_GETPEERNAME:
18801 		cmdp->cb_error = i_tcp_getpeername(tcp, data, &cmdp->cb_len);
18802 		break;
18803 	case TI_GETMYNAME:
18804 		cmdp->cb_error = tcp_getmyname(tcp, data, &cmdp->cb_len);
18805 		break;
18806 	default:
18807 		cmdp->cb_error = EINVAL;
18808 		break;
18809 	}
18810 
18811 	qreply(q, mp);
18812 }
18813 
18814 void
18815 tcp_wput(queue_t *q, mblk_t *mp)
18816 {
18817 	conn_t	*connp = Q_TO_CONN(q);
18818 	tcp_t	*tcp;
18819 	void (*output_proc)();
18820 	t_scalar_t type;
18821 	uchar_t *rptr;
18822 	struct iocblk	*iocp;
18823 	size_t size;
18824 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18825 
18826 	ASSERT(connp->conn_ref >= 2);
18827 
18828 	switch (DB_TYPE(mp)) {
18829 	case M_DATA:
18830 		tcp = connp->conn_tcp;
18831 		ASSERT(tcp != NULL);
18832 
18833 		size = msgdsize(mp);
18834 
18835 		mutex_enter(&tcp->tcp_non_sq_lock);
18836 		tcp->tcp_squeue_bytes += size;
18837 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18838 			tcp_setqfull(tcp);
18839 		}
18840 		mutex_exit(&tcp->tcp_non_sq_lock);
18841 
18842 		if (DB_CRED(mp) == NULL && is_system_labeled())
18843 			msg_setcredpid(mp, CONN_CRED(connp), curproc->p_pid);
18844 
18845 		CONN_INC_REF(connp);
18846 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18847 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18848 		return;
18849 
18850 	case M_CMD:
18851 		tcp_wput_cmdblk(q, mp);
18852 		return;
18853 
18854 	case M_PROTO:
18855 	case M_PCPROTO:
18856 		/*
18857 		 * if it is a snmp message, don't get behind the squeue
18858 		 */
18859 		tcp = connp->conn_tcp;
18860 		rptr = mp->b_rptr;
18861 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18862 			type = ((union T_primitives *)rptr)->type;
18863 		} else {
18864 			if (tcp->tcp_debug) {
18865 				(void) strlog(TCP_MOD_ID, 0, 1,
18866 				    SL_ERROR|SL_TRACE,
18867 				    "tcp_wput_proto, dropping one...");
18868 			}
18869 			freemsg(mp);
18870 			return;
18871 		}
18872 		if (type == T_SVR4_OPTMGMT_REQ) {
18873 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
18874 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18875 			    cr)) {
18876 				/*
18877 				 * This was a SNMP request
18878 				 */
18879 				return;
18880 			} else {
18881 				output_proc = tcp_wput_proto;
18882 			}
18883 		} else {
18884 			output_proc = tcp_wput_proto;
18885 		}
18886 		break;
18887 	case M_IOCTL:
18888 		/*
18889 		 * Most ioctls can be processed right away without going via
18890 		 * squeues - process them right here. Those that do require
18891 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18892 		 * are processed by tcp_wput_ioctl().
18893 		 */
18894 		iocp = (struct iocblk *)mp->b_rptr;
18895 		tcp = connp->conn_tcp;
18896 
18897 		switch (iocp->ioc_cmd) {
18898 		case TCP_IOC_ABORT_CONN:
18899 			tcp_ioctl_abort_conn(q, mp);
18900 			return;
18901 		case TI_GETPEERNAME:
18902 		case TI_GETMYNAME:
18903 			mi_copyin(q, mp, NULL,
18904 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18905 			return;
18906 		case ND_SET:
18907 			/* nd_getset does the necessary checks */
18908 		case ND_GET:
18909 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18910 				CALL_IP_WPUT(connp, q, mp);
18911 				return;
18912 			}
18913 			qreply(q, mp);
18914 			return;
18915 		case TCP_IOC_DEFAULT_Q:
18916 			/*
18917 			 * Wants to be the default wq. Check the credentials
18918 			 * first, the rest is executed via squeue.
18919 			 */
18920 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18921 				iocp->ioc_error = EPERM;
18922 				iocp->ioc_count = 0;
18923 				mp->b_datap->db_type = M_IOCACK;
18924 				qreply(q, mp);
18925 				return;
18926 			}
18927 			output_proc = tcp_wput_ioctl;
18928 			break;
18929 		default:
18930 			output_proc = tcp_wput_ioctl;
18931 			break;
18932 		}
18933 		break;
18934 	default:
18935 		output_proc = tcp_wput_nondata;
18936 		break;
18937 	}
18938 
18939 	CONN_INC_REF(connp);
18940 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18941 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18942 }
18943 
18944 /*
18945  * Initial STREAMS write side put() procedure for sockets. It tries to
18946  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18947  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18948  * are handled by tcp_wput() as usual.
18949  *
18950  * All further messages will also be handled by tcp_wput() because we cannot
18951  * be sure that the above short cut is safe later.
18952  */
18953 static void
18954 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18955 {
18956 	conn_t			*connp = Q_TO_CONN(wq);
18957 	tcp_t			*tcp = connp->conn_tcp;
18958 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18959 
18960 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18961 	wq->q_qinfo = &tcp_winit;
18962 
18963 	ASSERT(IPCL_IS_TCP(connp));
18964 	ASSERT(TCP_IS_SOCKET(tcp));
18965 
18966 	if (DB_TYPE(mp) == M_PCPROTO &&
18967 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18968 	    car->PRIM_type == T_CAPABILITY_REQ) {
18969 		tcp_capability_req(tcp, mp);
18970 		return;
18971 	}
18972 
18973 	tcp_wput(wq, mp);
18974 }
18975 
18976 /* ARGSUSED */
18977 static void
18978 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18979 {
18980 #ifdef DEBUG
18981 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18982 #endif
18983 	freemsg(mp);
18984 }
18985 
18986 static boolean_t
18987 tcp_zcopy_check(tcp_t *tcp)
18988 {
18989 	conn_t	*connp = tcp->tcp_connp;
18990 	ire_t	*ire;
18991 	boolean_t	zc_enabled = B_FALSE;
18992 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18993 
18994 	if (do_tcpzcopy == 2)
18995 		zc_enabled = B_TRUE;
18996 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18997 	    IPCL_IS_CONNECTED(connp) &&
18998 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18999 	    connp->conn_dontroute == 0 &&
19000 	    !connp->conn_nexthop_set &&
19001 	    connp->conn_outgoing_ill == NULL &&
19002 	    connp->conn_nofailover_ill == NULL &&
19003 	    do_tcpzcopy == 1) {
19004 		/*
19005 		 * the checks above  closely resemble the fast path checks
19006 		 * in tcp_send_data().
19007 		 */
19008 		mutex_enter(&connp->conn_lock);
19009 		ire = connp->conn_ire_cache;
19010 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19011 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19012 			IRE_REFHOLD(ire);
19013 			if (ire->ire_stq != NULL) {
19014 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
19015 
19016 				zc_enabled = ill && (ill->ill_capabilities &
19017 				    ILL_CAPAB_ZEROCOPY) &&
19018 				    (ill->ill_zerocopy_capab->
19019 				    ill_zerocopy_flags != 0);
19020 			}
19021 			IRE_REFRELE(ire);
19022 		}
19023 		mutex_exit(&connp->conn_lock);
19024 	}
19025 	tcp->tcp_snd_zcopy_on = zc_enabled;
19026 	if (!TCP_IS_DETACHED(tcp)) {
19027 		if (zc_enabled) {
19028 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
19029 			    ZCVMSAFE);
19030 			TCP_STAT(tcps, tcp_zcopy_on);
19031 		} else {
19032 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
19033 			    ZCVMUNSAFE);
19034 			TCP_STAT(tcps, tcp_zcopy_off);
19035 		}
19036 	}
19037 	return (zc_enabled);
19038 }
19039 
19040 static mblk_t *
19041 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
19042 {
19043 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19044 
19045 	if (do_tcpzcopy == 2)
19046 		return (bp);
19047 	else if (tcp->tcp_snd_zcopy_on) {
19048 		tcp->tcp_snd_zcopy_on = B_FALSE;
19049 		if (!TCP_IS_DETACHED(tcp)) {
19050 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
19051 			    ZCVMUNSAFE);
19052 			TCP_STAT(tcps, tcp_zcopy_disable);
19053 		}
19054 	}
19055 	return (tcp_zcopy_backoff(tcp, bp, 0));
19056 }
19057 
19058 /*
19059  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
19060  * the original desballoca'ed segmapped mblk.
19061  */
19062 static mblk_t *
19063 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
19064 {
19065 	mblk_t *head, *tail, *nbp;
19066 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19067 
19068 	if (IS_VMLOANED_MBLK(bp)) {
19069 		TCP_STAT(tcps, tcp_zcopy_backoff);
19070 		if ((head = copyb(bp)) == NULL) {
19071 			/* fail to backoff; leave it for the next backoff */
19072 			tcp->tcp_xmit_zc_clean = B_FALSE;
19073 			return (bp);
19074 		}
19075 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19076 			if (fix_xmitlist)
19077 				tcp_zcopy_notify(tcp);
19078 			else
19079 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19080 		}
19081 		nbp = bp->b_cont;
19082 		if (fix_xmitlist) {
19083 			head->b_prev = bp->b_prev;
19084 			head->b_next = bp->b_next;
19085 			if (tcp->tcp_xmit_tail == bp)
19086 				tcp->tcp_xmit_tail = head;
19087 		}
19088 		bp->b_next = NULL;
19089 		bp->b_prev = NULL;
19090 		freeb(bp);
19091 	} else {
19092 		head = bp;
19093 		nbp = bp->b_cont;
19094 	}
19095 	tail = head;
19096 	while (nbp) {
19097 		if (IS_VMLOANED_MBLK(nbp)) {
19098 			TCP_STAT(tcps, tcp_zcopy_backoff);
19099 			if ((tail->b_cont = copyb(nbp)) == NULL) {
19100 				tcp->tcp_xmit_zc_clean = B_FALSE;
19101 				tail->b_cont = nbp;
19102 				return (head);
19103 			}
19104 			tail = tail->b_cont;
19105 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19106 				if (fix_xmitlist)
19107 					tcp_zcopy_notify(tcp);
19108 				else
19109 					tail->b_datap->db_struioflag |=
19110 					    STRUIO_ZCNOTIFY;
19111 			}
19112 			bp = nbp;
19113 			nbp = nbp->b_cont;
19114 			if (fix_xmitlist) {
19115 				tail->b_prev = bp->b_prev;
19116 				tail->b_next = bp->b_next;
19117 				if (tcp->tcp_xmit_tail == bp)
19118 					tcp->tcp_xmit_tail = tail;
19119 			}
19120 			bp->b_next = NULL;
19121 			bp->b_prev = NULL;
19122 			freeb(bp);
19123 		} else {
19124 			tail->b_cont = nbp;
19125 			tail = nbp;
19126 			nbp = nbp->b_cont;
19127 		}
19128 	}
19129 	if (fix_xmitlist) {
19130 		tcp->tcp_xmit_last = tail;
19131 		tcp->tcp_xmit_zc_clean = B_TRUE;
19132 	}
19133 	return (head);
19134 }
19135 
19136 static void
19137 tcp_zcopy_notify(tcp_t *tcp)
19138 {
19139 	struct stdata	*stp;
19140 	conn_t *connp;
19141 
19142 	if (tcp->tcp_detached)
19143 		return;
19144 	connp = tcp->tcp_connp;
19145 	if (IPCL_IS_NONSTR(connp)) {
19146 		(*connp->conn_upcalls->su_zcopy_notify)
19147 		    (connp->conn_upper_handle);
19148 		return;
19149 	}
19150 	stp = STREAM(tcp->tcp_rq);
19151 	mutex_enter(&stp->sd_lock);
19152 	stp->sd_flag |= STZCNOTIFY;
19153 	cv_broadcast(&stp->sd_zcopy_wait);
19154 	mutex_exit(&stp->sd_lock);
19155 }
19156 
19157 static boolean_t
19158 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
19159 {
19160 	ire_t	*ire;
19161 	conn_t	*connp = tcp->tcp_connp;
19162 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19163 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19164 
19165 	mutex_enter(&connp->conn_lock);
19166 	ire = connp->conn_ire_cache;
19167 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19168 
19169 	if ((ire != NULL) &&
19170 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
19171 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
19172 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19173 		IRE_REFHOLD(ire);
19174 		mutex_exit(&connp->conn_lock);
19175 	} else {
19176 		boolean_t cached = B_FALSE;
19177 		ts_label_t *tsl;
19178 
19179 		/* force a recheck later on */
19180 		tcp->tcp_ire_ill_check_done = B_FALSE;
19181 
19182 		TCP_DBGSTAT(tcps, tcp_ire_null1);
19183 		connp->conn_ire_cache = NULL;
19184 		mutex_exit(&connp->conn_lock);
19185 
19186 		if (ire != NULL)
19187 			IRE_REFRELE_NOTR(ire);
19188 
19189 		tsl = crgetlabel(CONN_CRED(connp));
19190 		ire = (dst ?
19191 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
19192 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19193 		    connp->conn_zoneid, tsl, ipst));
19194 
19195 		if (ire == NULL) {
19196 			TCP_STAT(tcps, tcp_ire_null);
19197 			return (B_FALSE);
19198 		}
19199 
19200 		IRE_REFHOLD_NOTR(ire);
19201 
19202 		mutex_enter(&connp->conn_lock);
19203 		if (CONN_CACHE_IRE(connp)) {
19204 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19205 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19206 				TCP_CHECK_IREINFO(tcp, ire);
19207 				connp->conn_ire_cache = ire;
19208 				cached = B_TRUE;
19209 			}
19210 			rw_exit(&ire->ire_bucket->irb_lock);
19211 		}
19212 		mutex_exit(&connp->conn_lock);
19213 
19214 		/*
19215 		 * We can continue to use the ire but since it was
19216 		 * not cached, we should drop the extra reference.
19217 		 */
19218 		if (!cached)
19219 			IRE_REFRELE_NOTR(ire);
19220 
19221 		/*
19222 		 * Rampart note: no need to select a new label here, since
19223 		 * labels are not allowed to change during the life of a TCP
19224 		 * connection.
19225 		 */
19226 	}
19227 
19228 	*irep = ire;
19229 
19230 	return (B_TRUE);
19231 }
19232 
19233 /*
19234  * Called from tcp_send() or tcp_send_data() to find workable IRE.
19235  *
19236  * 0 = success;
19237  * 1 = failed to find ire and ill.
19238  */
19239 static boolean_t
19240 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
19241 {
19242 	ipha_t		*ipha;
19243 	ipaddr_t	dst;
19244 	ire_t		*ire;
19245 	ill_t		*ill;
19246 	conn_t		*connp = tcp->tcp_connp;
19247 	mblk_t		*ire_fp_mp;
19248 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19249 
19250 	if (mp != NULL)
19251 		ipha = (ipha_t *)mp->b_rptr;
19252 	else
19253 		ipha = tcp->tcp_ipha;
19254 	dst = ipha->ipha_dst;
19255 
19256 	if (!tcp_send_find_ire(tcp, &dst, &ire))
19257 		return (B_FALSE);
19258 
19259 	if ((ire->ire_flags & RTF_MULTIRT) ||
19260 	    (ire->ire_stq == NULL) ||
19261 	    (ire->ire_nce == NULL) ||
19262 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
19263 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
19264 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
19265 		TCP_STAT(tcps, tcp_ip_ire_send);
19266 		IRE_REFRELE(ire);
19267 		return (B_FALSE);
19268 	}
19269 
19270 	ill = ire_to_ill(ire);
19271 	if (connp->conn_outgoing_ill != NULL) {
19272 		ill_t *conn_outgoing_ill = NULL;
19273 		/*
19274 		 * Choose a good ill in the group to send the packets on.
19275 		 */
19276 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
19277 		ill = ire_to_ill(ire);
19278 	}
19279 	ASSERT(ill != NULL);
19280 
19281 	if (!tcp->tcp_ire_ill_check_done) {
19282 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19283 		tcp->tcp_ire_ill_check_done = B_TRUE;
19284 	}
19285 
19286 	*irep = ire;
19287 	*illp = ill;
19288 
19289 	return (B_TRUE);
19290 }
19291 
19292 static void
19293 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
19294 {
19295 	ipha_t		*ipha;
19296 	ipaddr_t	src;
19297 	ipaddr_t	dst;
19298 	uint32_t	cksum;
19299 	ire_t		*ire;
19300 	uint16_t	*up;
19301 	ill_t		*ill;
19302 	conn_t		*connp = tcp->tcp_connp;
19303 	uint32_t	hcksum_txflags = 0;
19304 	mblk_t		*ire_fp_mp;
19305 	uint_t		ire_fp_mp_len;
19306 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19307 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19308 
19309 	ASSERT(DB_TYPE(mp) == M_DATA);
19310 
19311 	if (is_system_labeled() && DB_CRED(mp) == NULL)
19312 		mblk_setcred(mp, CONN_CRED(tcp->tcp_connp));
19313 
19314 	ipha = (ipha_t *)mp->b_rptr;
19315 	src = ipha->ipha_src;
19316 	dst = ipha->ipha_dst;
19317 
19318 	ASSERT(q != NULL);
19319 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
19320 
19321 	/*
19322 	 * Drop off fast path for IPv6 and also if options are present or
19323 	 * we need to resolve a TS label.
19324 	 */
19325 	if (tcp->tcp_ipversion != IPV4_VERSION ||
19326 	    !IPCL_IS_CONNECTED(connp) ||
19327 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
19328 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
19329 	    !connp->conn_ulp_labeled ||
19330 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
19331 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
19332 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
19333 		if (tcp->tcp_snd_zcopy_aware)
19334 			mp = tcp_zcopy_disable(tcp, mp);
19335 		TCP_STAT(tcps, tcp_ip_send);
19336 		CALL_IP_WPUT(connp, q, mp);
19337 		return;
19338 	}
19339 
19340 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
19341 		if (tcp->tcp_snd_zcopy_aware)
19342 			mp = tcp_zcopy_backoff(tcp, mp, 0);
19343 		CALL_IP_WPUT(connp, q, mp);
19344 		return;
19345 	}
19346 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
19347 	ire_fp_mp_len = MBLKL(ire_fp_mp);
19348 
19349 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19350 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19351 #ifndef _BIG_ENDIAN
19352 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19353 #endif
19354 
19355 	/*
19356 	 * Check to see if we need to re-enable LSO/MDT for this connection
19357 	 * because it was previously disabled due to changes in the ill;
19358 	 * note that by doing it here, this re-enabling only applies when
19359 	 * the packet is not dispatched through CALL_IP_WPUT().
19360 	 *
19361 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
19362 	 * case, since that's how we ended up here.  For IPv6, we do the
19363 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
19364 	 */
19365 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
19366 		/*
19367 		 * Restore LSO for this connection, so that next time around
19368 		 * it is eligible to go through tcp_lsosend() path again.
19369 		 */
19370 		TCP_STAT(tcps, tcp_lso_enabled);
19371 		tcp->tcp_lso = B_TRUE;
19372 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
19373 		    "interface %s\n", (void *)connp, ill->ill_name));
19374 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
19375 		/*
19376 		 * Restore MDT for this connection, so that next time around
19377 		 * it is eligible to go through tcp_multisend() path again.
19378 		 */
19379 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
19380 		tcp->tcp_mdt = B_TRUE;
19381 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
19382 		    "interface %s\n", (void *)connp, ill->ill_name));
19383 	}
19384 
19385 	if (tcp->tcp_snd_zcopy_aware) {
19386 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
19387 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
19388 			mp = tcp_zcopy_disable(tcp, mp);
19389 		/*
19390 		 * we shouldn't need to reset ipha as the mp containing
19391 		 * ipha should never be a zero-copy mp.
19392 		 */
19393 	}
19394 
19395 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
19396 		ASSERT(ill->ill_hcksum_capab != NULL);
19397 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
19398 	}
19399 
19400 	/* pseudo-header checksum (do it in parts for IP header checksum) */
19401 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19402 
19403 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
19404 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
19405 
19406 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
19407 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
19408 
19409 	/* Software checksum? */
19410 	if (DB_CKSUMFLAGS(mp) == 0) {
19411 		TCP_STAT(tcps, tcp_out_sw_cksum);
19412 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
19413 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
19414 	}
19415 
19416 	/* Calculate IP header checksum if hardware isn't capable */
19417 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
19418 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
19419 		    ((uint16_t *)ipha)[4]);
19420 	}
19421 
19422 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
19423 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
19424 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
19425 
19426 	UPDATE_OB_PKT_COUNT(ire);
19427 	ire->ire_last_used_time = lbolt;
19428 
19429 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
19430 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
19431 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
19432 	    ntohs(ipha->ipha_length));
19433 
19434 	DTRACE_PROBE4(ip4__physical__out__start,
19435 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
19436 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
19437 	    ipst->ips_ipv4firewall_physical_out,
19438 	    NULL, ill, ipha, mp, mp, 0, ipst);
19439 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19440 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
19441 
19442 	if (mp != NULL) {
19443 		if (ipst->ips_ipobs_enabled) {
19444 			zoneid_t szone;
19445 
19446 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
19447 			    ipst, ALL_ZONES);
19448 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
19449 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
19450 		}
19451 
19452 		ILL_SEND_TX(ill, ire, connp, mp, 0);
19453 	}
19454 
19455 	IRE_REFRELE(ire);
19456 }
19457 
19458 /*
19459  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19460  * if the receiver shrinks the window, i.e. moves the right window to the
19461  * left, the we should not send new data, but should retransmit normally the
19462  * old unacked data between suna and suna + swnd. We might has sent data
19463  * that is now outside the new window, pretend that we didn't send  it.
19464  */
19465 static void
19466 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19467 {
19468 	uint32_t	snxt = tcp->tcp_snxt;
19469 	mblk_t		*xmit_tail;
19470 	int32_t		offset;
19471 
19472 	ASSERT(shrunk_count > 0);
19473 
19474 	/* Pretend we didn't send the data outside the window */
19475 	snxt -= shrunk_count;
19476 
19477 	/* Get the mblk and the offset in it per the shrunk window */
19478 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19479 
19480 	ASSERT(xmit_tail != NULL);
19481 
19482 	/* Reset all the values per the now shrunk window */
19483 	tcp->tcp_snxt = snxt;
19484 	tcp->tcp_xmit_tail = xmit_tail;
19485 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19486 	    offset;
19487 	tcp->tcp_unsent += shrunk_count;
19488 
19489 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19490 		/*
19491 		 * Make sure the timer is running so that we will probe a zero
19492 		 * window.
19493 		 */
19494 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19495 }
19496 
19497 
19498 /*
19499  * The TCP normal data output path.
19500  * NOTE: the logic of the fast path is duplicated from this function.
19501  */
19502 static void
19503 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19504 {
19505 	int		len;
19506 	mblk_t		*local_time;
19507 	mblk_t		*mp1;
19508 	uint32_t	snxt;
19509 	int		tail_unsent;
19510 	int		tcpstate;
19511 	int		usable = 0;
19512 	mblk_t		*xmit_tail;
19513 	queue_t		*q = tcp->tcp_wq;
19514 	int32_t		mss;
19515 	int32_t		num_sack_blk = 0;
19516 	int32_t		tcp_hdr_len;
19517 	int32_t		tcp_tcp_hdr_len;
19518 	int		mdt_thres;
19519 	int		rc;
19520 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19521 	ip_stack_t	*ipst;
19522 
19523 	tcpstate = tcp->tcp_state;
19524 	if (mp == NULL) {
19525 		/*
19526 		 * tcp_wput_data() with NULL mp should only be called when
19527 		 * there is unsent data.
19528 		 */
19529 		ASSERT(tcp->tcp_unsent > 0);
19530 		/* Really tacky... but we need this for detached closes. */
19531 		len = tcp->tcp_unsent;
19532 		goto data_null;
19533 	}
19534 
19535 #if CCS_STATS
19536 	wrw_stats.tot.count++;
19537 	wrw_stats.tot.bytes += msgdsize(mp);
19538 #endif
19539 	ASSERT(mp->b_datap->db_type == M_DATA);
19540 	/*
19541 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19542 	 * or before a connection attempt has begun.
19543 	 */
19544 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19545 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19546 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19547 #ifdef DEBUG
19548 			cmn_err(CE_WARN,
19549 			    "tcp_wput_data: data after ordrel, %s",
19550 			    tcp_display(tcp, NULL,
19551 			    DISP_ADDR_AND_PORT));
19552 #else
19553 			if (tcp->tcp_debug) {
19554 				(void) strlog(TCP_MOD_ID, 0, 1,
19555 				    SL_TRACE|SL_ERROR,
19556 				    "tcp_wput_data: data after ordrel, %s\n",
19557 				    tcp_display(tcp, NULL,
19558 				    DISP_ADDR_AND_PORT));
19559 			}
19560 #endif /* DEBUG */
19561 		}
19562 		if (tcp->tcp_snd_zcopy_aware &&
19563 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19564 			tcp_zcopy_notify(tcp);
19565 		freemsg(mp);
19566 		mutex_enter(&tcp->tcp_non_sq_lock);
19567 		if (tcp->tcp_flow_stopped &&
19568 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19569 			tcp_clrqfull(tcp);
19570 		}
19571 		mutex_exit(&tcp->tcp_non_sq_lock);
19572 		return;
19573 	}
19574 
19575 	/* Strip empties */
19576 	for (;;) {
19577 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19578 		    (uintptr_t)INT_MAX);
19579 		len = (int)(mp->b_wptr - mp->b_rptr);
19580 		if (len > 0)
19581 			break;
19582 		mp1 = mp;
19583 		mp = mp->b_cont;
19584 		freeb(mp1);
19585 		if (!mp) {
19586 			return;
19587 		}
19588 	}
19589 
19590 	/* If we are the first on the list ... */
19591 	if (tcp->tcp_xmit_head == NULL) {
19592 		tcp->tcp_xmit_head = mp;
19593 		tcp->tcp_xmit_tail = mp;
19594 		tcp->tcp_xmit_tail_unsent = len;
19595 	} else {
19596 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19597 		struct datab *dp;
19598 
19599 		mp1 = tcp->tcp_xmit_last;
19600 		if (len < tcp_tx_pull_len &&
19601 		    (dp = mp1->b_datap)->db_ref == 1 &&
19602 		    dp->db_lim - mp1->b_wptr >= len) {
19603 			ASSERT(len > 0);
19604 			ASSERT(!mp1->b_cont);
19605 			if (len == 1) {
19606 				*mp1->b_wptr++ = *mp->b_rptr;
19607 			} else {
19608 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19609 				mp1->b_wptr += len;
19610 			}
19611 			if (mp1 == tcp->tcp_xmit_tail)
19612 				tcp->tcp_xmit_tail_unsent += len;
19613 			mp1->b_cont = mp->b_cont;
19614 			if (tcp->tcp_snd_zcopy_aware &&
19615 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19616 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19617 			freeb(mp);
19618 			mp = mp1;
19619 		} else {
19620 			tcp->tcp_xmit_last->b_cont = mp;
19621 		}
19622 		len += tcp->tcp_unsent;
19623 	}
19624 
19625 	/* Tack on however many more positive length mblks we have */
19626 	if ((mp1 = mp->b_cont) != NULL) {
19627 		do {
19628 			int tlen;
19629 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19630 			    (uintptr_t)INT_MAX);
19631 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19632 			if (tlen <= 0) {
19633 				mp->b_cont = mp1->b_cont;
19634 				freeb(mp1);
19635 			} else {
19636 				len += tlen;
19637 				mp = mp1;
19638 			}
19639 		} while ((mp1 = mp->b_cont) != NULL);
19640 	}
19641 	tcp->tcp_xmit_last = mp;
19642 	tcp->tcp_unsent = len;
19643 
19644 	if (urgent)
19645 		usable = 1;
19646 
19647 data_null:
19648 	snxt = tcp->tcp_snxt;
19649 	xmit_tail = tcp->tcp_xmit_tail;
19650 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19651 
19652 	/*
19653 	 * Note that tcp_mss has been adjusted to take into account the
19654 	 * timestamp option if applicable.  Because SACK options do not
19655 	 * appear in every TCP segments and they are of variable lengths,
19656 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19657 	 * the actual segment length when we need to send a segment which
19658 	 * includes SACK options.
19659 	 */
19660 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19661 		int32_t	opt_len;
19662 
19663 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19664 		    tcp->tcp_num_sack_blk);
19665 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19666 		    2 + TCPOPT_HEADER_LEN;
19667 		mss = tcp->tcp_mss - opt_len;
19668 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19669 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19670 	} else {
19671 		mss = tcp->tcp_mss;
19672 		tcp_hdr_len = tcp->tcp_hdr_len;
19673 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19674 	}
19675 
19676 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19677 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19678 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19679 	}
19680 	if (tcpstate == TCPS_SYN_RCVD) {
19681 		/*
19682 		 * The three-way connection establishment handshake is not
19683 		 * complete yet. We want to queue the data for transmission
19684 		 * after entering ESTABLISHED state (RFC793). A jump to
19685 		 * "done" label effectively leaves data on the queue.
19686 		 */
19687 		goto done;
19688 	} else {
19689 		int usable_r;
19690 
19691 		/*
19692 		 * In the special case when cwnd is zero, which can only
19693 		 * happen if the connection is ECN capable, return now.
19694 		 * New segments is sent using tcp_timer().  The timer
19695 		 * is set in tcp_rput_data().
19696 		 */
19697 		if (tcp->tcp_cwnd == 0) {
19698 			/*
19699 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19700 			 * finished.
19701 			 */
19702 			ASSERT(tcp->tcp_ecn_ok ||
19703 			    tcp->tcp_state < TCPS_ESTABLISHED);
19704 			return;
19705 		}
19706 
19707 		/* NOTE: trouble if xmitting while SYN not acked? */
19708 		usable_r = snxt - tcp->tcp_suna;
19709 		usable_r = tcp->tcp_swnd - usable_r;
19710 
19711 		/*
19712 		 * Check if the receiver has shrunk the window.  If
19713 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19714 		 * cannot be set as there is unsent data, so FIN cannot
19715 		 * be sent out.  Otherwise, we need to take into account
19716 		 * of FIN as it consumes an "invisible" sequence number.
19717 		 */
19718 		ASSERT(tcp->tcp_fin_sent == 0);
19719 		if (usable_r < 0) {
19720 			/*
19721 			 * The receiver has shrunk the window and we have sent
19722 			 * -usable_r date beyond the window, re-adjust.
19723 			 *
19724 			 * If TCP window scaling is enabled, there can be
19725 			 * round down error as the advertised receive window
19726 			 * is actually right shifted n bits.  This means that
19727 			 * the lower n bits info is wiped out.  It will look
19728 			 * like the window is shrunk.  Do a check here to
19729 			 * see if the shrunk amount is actually within the
19730 			 * error in window calculation.  If it is, just
19731 			 * return.  Note that this check is inside the
19732 			 * shrunk window check.  This makes sure that even
19733 			 * though tcp_process_shrunk_swnd() is not called,
19734 			 * we will stop further processing.
19735 			 */
19736 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19737 				tcp_process_shrunk_swnd(tcp, -usable_r);
19738 			}
19739 			return;
19740 		}
19741 
19742 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19743 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19744 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19745 
19746 		/* usable = MIN(usable, unsent) */
19747 		if (usable_r > len)
19748 			usable_r = len;
19749 
19750 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19751 		if (usable_r > 0) {
19752 			usable = usable_r;
19753 		} else {
19754 			/* Bypass all other unnecessary processing. */
19755 			goto done;
19756 		}
19757 	}
19758 
19759 	local_time = (mblk_t *)lbolt;
19760 
19761 	/*
19762 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19763 	 * BSD.  This is more in line with the true intent of Nagle.
19764 	 *
19765 	 * The conditions are:
19766 	 * 1. The amount of unsent data (or amount of data which can be
19767 	 *    sent, whichever is smaller) is less than Nagle limit.
19768 	 * 2. The last sent size is also less than Nagle limit.
19769 	 * 3. There is unack'ed data.
19770 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19771 	 *    Nagle algorithm.  This reduces the probability that urgent
19772 	 *    bytes get "merged" together.
19773 	 * 5. The app has not closed the connection.  This eliminates the
19774 	 *    wait time of the receiving side waiting for the last piece of
19775 	 *    (small) data.
19776 	 *
19777 	 * If all are satisified, exit without sending anything.  Note
19778 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19779 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19780 	 * 4095).
19781 	 */
19782 	if (usable < (int)tcp->tcp_naglim &&
19783 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19784 	    snxt != tcp->tcp_suna &&
19785 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19786 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19787 		goto done;
19788 	}
19789 
19790 	if (tcp->tcp_cork) {
19791 		/*
19792 		 * if the tcp->tcp_cork option is set, then we have to force
19793 		 * TCP not to send partial segment (smaller than MSS bytes).
19794 		 * We are calculating the usable now based on full mss and
19795 		 * will save the rest of remaining data for later.
19796 		 */
19797 		if (usable < mss)
19798 			goto done;
19799 		usable = (usable / mss) * mss;
19800 	}
19801 
19802 	/* Update the latest receive window size in TCP header. */
19803 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19804 	    tcp->tcp_tcph->th_win);
19805 
19806 	/*
19807 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19808 	 *
19809 	 * 1. Simple TCP/IP{v4,v6} (no options).
19810 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19811 	 * 3. If the TCP connection is in ESTABLISHED state.
19812 	 * 4. The TCP is not detached.
19813 	 *
19814 	 * If any of the above conditions have changed during the
19815 	 * connection, stop using LSO/MDT and restore the stream head
19816 	 * parameters accordingly.
19817 	 */
19818 	ipst = tcps->tcps_netstack->netstack_ip;
19819 
19820 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19821 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19822 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19823 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19824 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19825 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19826 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19827 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19828 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19829 		if (tcp->tcp_lso) {
19830 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19831 			tcp->tcp_lso = B_FALSE;
19832 		} else {
19833 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19834 			tcp->tcp_mdt = B_FALSE;
19835 		}
19836 
19837 		/* Anything other than detached is considered pathological */
19838 		if (!TCP_IS_DETACHED(tcp)) {
19839 			if (tcp->tcp_lso)
19840 				TCP_STAT(tcps, tcp_lso_disabled);
19841 			else
19842 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19843 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19844 		}
19845 	}
19846 
19847 	/* Use MDT if sendable amount is greater than the threshold */
19848 	if (tcp->tcp_mdt &&
19849 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19850 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19851 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19852 	    (tcp->tcp_valid_bits == 0 ||
19853 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19854 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19855 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19856 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19857 		    local_time, mdt_thres);
19858 	} else {
19859 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19860 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19861 		    local_time, INT_MAX);
19862 	}
19863 
19864 	/* Pretend that all we were trying to send really got sent */
19865 	if (rc < 0 && tail_unsent < 0) {
19866 		do {
19867 			xmit_tail = xmit_tail->b_cont;
19868 			xmit_tail->b_prev = local_time;
19869 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19870 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19871 			tail_unsent += (int)(xmit_tail->b_wptr -
19872 			    xmit_tail->b_rptr);
19873 		} while (tail_unsent < 0);
19874 	}
19875 done:;
19876 	tcp->tcp_xmit_tail = xmit_tail;
19877 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19878 	len = tcp->tcp_snxt - snxt;
19879 	if (len) {
19880 		/*
19881 		 * If new data was sent, need to update the notsack
19882 		 * list, which is, afterall, data blocks that have
19883 		 * not been sack'ed by the receiver.  New data is
19884 		 * not sack'ed.
19885 		 */
19886 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19887 			/* len is a negative value. */
19888 			tcp->tcp_pipe -= len;
19889 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19890 			    tcp->tcp_snxt, snxt,
19891 			    &(tcp->tcp_num_notsack_blk),
19892 			    &(tcp->tcp_cnt_notsack_list));
19893 		}
19894 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19895 		tcp->tcp_rack = tcp->tcp_rnxt;
19896 		tcp->tcp_rack_cnt = 0;
19897 		if ((snxt + len) == tcp->tcp_suna) {
19898 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19899 		}
19900 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19901 		/*
19902 		 * Didn't send anything. Make sure the timer is running
19903 		 * so that we will probe a zero window.
19904 		 */
19905 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19906 	}
19907 	/* Note that len is the amount we just sent but with a negative sign */
19908 	tcp->tcp_unsent += len;
19909 	mutex_enter(&tcp->tcp_non_sq_lock);
19910 	if (tcp->tcp_flow_stopped) {
19911 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19912 			tcp_clrqfull(tcp);
19913 		}
19914 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19915 		tcp_setqfull(tcp);
19916 	}
19917 	mutex_exit(&tcp->tcp_non_sq_lock);
19918 }
19919 
19920 /*
19921  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19922  * outgoing TCP header with the template header, as well as other
19923  * options such as time-stamp, ECN and/or SACK.
19924  */
19925 static void
19926 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19927 {
19928 	tcph_t *tcp_tmpl, *tcp_h;
19929 	uint32_t *dst, *src;
19930 	int hdrlen;
19931 
19932 	ASSERT(OK_32PTR(rptr));
19933 
19934 	/* Template header */
19935 	tcp_tmpl = tcp->tcp_tcph;
19936 
19937 	/* Header of outgoing packet */
19938 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19939 
19940 	/* dst and src are opaque 32-bit fields, used for copying */
19941 	dst = (uint32_t *)rptr;
19942 	src = (uint32_t *)tcp->tcp_iphc;
19943 	hdrlen = tcp->tcp_hdr_len;
19944 
19945 	/* Fill time-stamp option if needed */
19946 	if (tcp->tcp_snd_ts_ok) {
19947 		U32_TO_BE32((uint32_t)now,
19948 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19949 		U32_TO_BE32(tcp->tcp_ts_recent,
19950 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19951 	} else {
19952 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19953 	}
19954 
19955 	/*
19956 	 * Copy the template header; is this really more efficient than
19957 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19958 	 * but perhaps not for other scenarios.
19959 	 */
19960 	dst[0] = src[0];
19961 	dst[1] = src[1];
19962 	dst[2] = src[2];
19963 	dst[3] = src[3];
19964 	dst[4] = src[4];
19965 	dst[5] = src[5];
19966 	dst[6] = src[6];
19967 	dst[7] = src[7];
19968 	dst[8] = src[8];
19969 	dst[9] = src[9];
19970 	if (hdrlen -= 40) {
19971 		hdrlen >>= 2;
19972 		dst += 10;
19973 		src += 10;
19974 		do {
19975 			*dst++ = *src++;
19976 		} while (--hdrlen);
19977 	}
19978 
19979 	/*
19980 	 * Set the ECN info in the TCP header if it is not a zero
19981 	 * window probe.  Zero window probe is only sent in
19982 	 * tcp_wput_data() and tcp_timer().
19983 	 */
19984 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19985 		SET_ECT(tcp, rptr);
19986 
19987 		if (tcp->tcp_ecn_echo_on)
19988 			tcp_h->th_flags[0] |= TH_ECE;
19989 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19990 			tcp_h->th_flags[0] |= TH_CWR;
19991 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19992 		}
19993 	}
19994 
19995 	/* Fill in SACK options */
19996 	if (num_sack_blk > 0) {
19997 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19998 		sack_blk_t *tmp;
19999 		int32_t	i;
20000 
20001 		wptr[0] = TCPOPT_NOP;
20002 		wptr[1] = TCPOPT_NOP;
20003 		wptr[2] = TCPOPT_SACK;
20004 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
20005 		    sizeof (sack_blk_t);
20006 		wptr += TCPOPT_REAL_SACK_LEN;
20007 
20008 		tmp = tcp->tcp_sack_list;
20009 		for (i = 0; i < num_sack_blk; i++) {
20010 			U32_TO_BE32(tmp[i].begin, wptr);
20011 			wptr += sizeof (tcp_seq);
20012 			U32_TO_BE32(tmp[i].end, wptr);
20013 			wptr += sizeof (tcp_seq);
20014 		}
20015 		tcp_h->th_offset_and_rsrvd[0] +=
20016 		    ((num_sack_blk * 2 + 1) << 4);
20017 	}
20018 }
20019 
20020 /*
20021  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
20022  * the destination address and SAP attribute, and if necessary, the
20023  * hardware checksum offload attribute to a Multidata message.
20024  */
20025 static int
20026 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
20027     const uint32_t start, const uint32_t stuff, const uint32_t end,
20028     const uint32_t flags, tcp_stack_t *tcps)
20029 {
20030 	/* Add global destination address & SAP attribute */
20031 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
20032 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
20033 		    "destination address+SAP\n"));
20034 
20035 		if (dlmp != NULL)
20036 			TCP_STAT(tcps, tcp_mdt_allocfail);
20037 		return (-1);
20038 	}
20039 
20040 	/* Add global hwcksum attribute */
20041 	if (hwcksum &&
20042 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
20043 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
20044 		    "checksum attribute\n"));
20045 
20046 		TCP_STAT(tcps, tcp_mdt_allocfail);
20047 		return (-1);
20048 	}
20049 
20050 	return (0);
20051 }
20052 
20053 /*
20054  * Smaller and private version of pdescinfo_t used specifically for TCP,
20055  * which allows for only two payload spans per packet.
20056  */
20057 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
20058 
20059 /*
20060  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
20061  * scheme, and returns one the following:
20062  *
20063  * -1 = failed allocation.
20064  *  0 = success; burst count reached, or usable send window is too small,
20065  *      and that we'd rather wait until later before sending again.
20066  */
20067 static int
20068 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20069     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20070     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20071     const int mdt_thres)
20072 {
20073 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
20074 	multidata_t	*mmd;
20075 	uint_t		obsegs, obbytes, hdr_frag_sz;
20076 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
20077 	int		num_burst_seg, max_pld;
20078 	pdesc_t		*pkt;
20079 	tcp_pdescinfo_t	tcp_pkt_info;
20080 	pdescinfo_t	*pkt_info;
20081 	int		pbuf_idx, pbuf_idx_nxt;
20082 	int		seg_len, len, spill, af;
20083 	boolean_t	add_buffer, zcopy, clusterwide;
20084 	boolean_t	rconfirm = B_FALSE;
20085 	boolean_t	done = B_FALSE;
20086 	uint32_t	cksum;
20087 	uint32_t	hwcksum_flags;
20088 	ire_t		*ire = NULL;
20089 	ill_t		*ill;
20090 	ipha_t		*ipha;
20091 	ip6_t		*ip6h;
20092 	ipaddr_t	src, dst;
20093 	ill_zerocopy_capab_t *zc_cap = NULL;
20094 	uint16_t	*up;
20095 	int		err;
20096 	conn_t		*connp;
20097 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20098 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
20099 	int		usable_mmd, tail_unsent_mmd;
20100 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
20101 	mblk_t		*xmit_tail_mmd;
20102 	netstackid_t	stack_id;
20103 
20104 #ifdef	_BIG_ENDIAN
20105 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
20106 #else
20107 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
20108 #endif
20109 
20110 #define	PREP_NEW_MULTIDATA() {			\
20111 	mmd = NULL;				\
20112 	md_mp = md_hbuf = NULL;			\
20113 	cur_hdr_off = 0;			\
20114 	max_pld = tcp->tcp_mdt_max_pld;		\
20115 	pbuf_idx = pbuf_idx_nxt = -1;		\
20116 	add_buffer = B_TRUE;			\
20117 	zcopy = B_FALSE;			\
20118 }
20119 
20120 #define	PREP_NEW_PBUF() {			\
20121 	md_pbuf = md_pbuf_nxt = NULL;		\
20122 	pbuf_idx = pbuf_idx_nxt = -1;		\
20123 	cur_pld_off = 0;			\
20124 	first_snxt = *snxt;			\
20125 	ASSERT(*tail_unsent > 0);		\
20126 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
20127 }
20128 
20129 	ASSERT(mdt_thres >= mss);
20130 	ASSERT(*usable > 0 && *usable > mdt_thres);
20131 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20132 	ASSERT(!TCP_IS_DETACHED(tcp));
20133 	ASSERT(tcp->tcp_valid_bits == 0 ||
20134 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
20135 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
20136 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
20137 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20138 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
20139 
20140 	connp = tcp->tcp_connp;
20141 	ASSERT(connp != NULL);
20142 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
20143 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
20144 
20145 	stack_id = connp->conn_netstack->netstack_stackid;
20146 
20147 	usable_mmd = tail_unsent_mmd = 0;
20148 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
20149 	xmit_tail_mmd = NULL;
20150 	/*
20151 	 * Note that tcp will only declare at most 2 payload spans per
20152 	 * packet, which is much lower than the maximum allowable number
20153 	 * of packet spans per Multidata.  For this reason, we use the
20154 	 * privately declared and smaller descriptor info structure, in
20155 	 * order to save some stack space.
20156 	 */
20157 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
20158 
20159 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
20160 	if (af == AF_INET) {
20161 		dst = tcp->tcp_ipha->ipha_dst;
20162 		src = tcp->tcp_ipha->ipha_src;
20163 		ASSERT(!CLASSD(dst));
20164 	}
20165 	ASSERT(af == AF_INET ||
20166 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
20167 
20168 	obsegs = obbytes = 0;
20169 	num_burst_seg = tcp->tcp_snd_burst;
20170 	md_mp_head = NULL;
20171 	PREP_NEW_MULTIDATA();
20172 
20173 	/*
20174 	 * Before we go on further, make sure there is an IRE that we can
20175 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
20176 	 * in proceeding any further, and we should just hand everything
20177 	 * off to the legacy path.
20178 	 */
20179 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
20180 		goto legacy_send_no_md;
20181 
20182 	ASSERT(ire != NULL);
20183 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
20184 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
20185 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
20186 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
20187 	/*
20188 	 * If we do support loopback for MDT (which requires modifications
20189 	 * to the receiving paths), the following assertions should go away,
20190 	 * and we would be sending the Multidata to loopback conn later on.
20191 	 */
20192 	ASSERT(!IRE_IS_LOCAL(ire));
20193 	ASSERT(ire->ire_stq != NULL);
20194 
20195 	ill = ire_to_ill(ire);
20196 	ASSERT(ill != NULL);
20197 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
20198 
20199 	if (!tcp->tcp_ire_ill_check_done) {
20200 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
20201 		tcp->tcp_ire_ill_check_done = B_TRUE;
20202 	}
20203 
20204 	/*
20205 	 * If the underlying interface conditions have changed, or if the
20206 	 * new interface does not support MDT, go back to legacy path.
20207 	 */
20208 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
20209 		/* don't go through this path anymore for this connection */
20210 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
20211 		tcp->tcp_mdt = B_FALSE;
20212 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
20213 		    "interface %s\n", (void *)connp, ill->ill_name));
20214 		/* IRE will be released prior to returning */
20215 		goto legacy_send_no_md;
20216 	}
20217 
20218 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
20219 		zc_cap = ill->ill_zerocopy_capab;
20220 
20221 	/*
20222 	 * Check if we can take tcp fast-path. Note that "incomplete"
20223 	 * ire's (where the link-layer for next hop is not resolved
20224 	 * or where the fast-path header in nce_fp_mp is not available
20225 	 * yet) are sent down the legacy (slow) path.
20226 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
20227 	 */
20228 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
20229 		/* IRE will be released prior to returning */
20230 		goto legacy_send_no_md;
20231 	}
20232 
20233 	/* go to legacy path if interface doesn't support zerocopy */
20234 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
20235 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
20236 		/* IRE will be released prior to returning */
20237 		goto legacy_send_no_md;
20238 	}
20239 
20240 	/* does the interface support hardware checksum offload? */
20241 	hwcksum_flags = 0;
20242 	if (ILL_HCKSUM_CAPABLE(ill) &&
20243 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
20244 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
20245 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
20246 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20247 		    HCKSUM_IPHDRCKSUM)
20248 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
20249 
20250 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20251 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
20252 			hwcksum_flags |= HCK_FULLCKSUM;
20253 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20254 		    HCKSUM_INET_PARTIAL)
20255 			hwcksum_flags |= HCK_PARTIALCKSUM;
20256 	}
20257 
20258 	/*
20259 	 * Each header fragment consists of the leading extra space,
20260 	 * followed by the TCP/IP header, and the trailing extra space.
20261 	 * We make sure that each header fragment begins on a 32-bit
20262 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
20263 	 * aligned in tcp_mdt_update).
20264 	 */
20265 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
20266 	    tcp->tcp_mdt_hdr_tail), 4);
20267 
20268 	/* are we starting from the beginning of data block? */
20269 	if (*tail_unsent == 0) {
20270 		*xmit_tail = (*xmit_tail)->b_cont;
20271 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
20272 		*tail_unsent = (int)MBLKL(*xmit_tail);
20273 	}
20274 
20275 	/*
20276 	 * Here we create one or more Multidata messages, each made up of
20277 	 * one header buffer and up to N payload buffers.  This entire
20278 	 * operation is done within two loops:
20279 	 *
20280 	 * The outer loop mostly deals with creating the Multidata message,
20281 	 * as well as the header buffer that gets added to it.  It also
20282 	 * links the Multidata messages together such that all of them can
20283 	 * be sent down to the lower layer in a single putnext call; this
20284 	 * linking behavior depends on the tcp_mdt_chain tunable.
20285 	 *
20286 	 * The inner loop takes an existing Multidata message, and adds
20287 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
20288 	 * packetizes those buffers by filling up the corresponding header
20289 	 * buffer fragments with the proper IP and TCP headers, and by
20290 	 * describing the layout of each packet in the packet descriptors
20291 	 * that get added to the Multidata.
20292 	 */
20293 	do {
20294 		/*
20295 		 * If usable send window is too small, or data blocks in
20296 		 * transmit list are smaller than our threshold (i.e. app
20297 		 * performs large writes followed by small ones), we hand
20298 		 * off the control over to the legacy path.  Note that we'll
20299 		 * get back the control once it encounters a large block.
20300 		 */
20301 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
20302 		    (*xmit_tail)->b_cont != NULL &&
20303 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
20304 			/* send down what we've got so far */
20305 			if (md_mp_head != NULL) {
20306 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
20307 				    obsegs, obbytes, &rconfirm);
20308 			}
20309 			/*
20310 			 * Pass control over to tcp_send(), but tell it to
20311 			 * return to us once a large-size transmission is
20312 			 * possible.
20313 			 */
20314 			TCP_STAT(tcps, tcp_mdt_legacy_small);
20315 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
20316 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
20317 			    tail_unsent, xmit_tail, local_time,
20318 			    mdt_thres)) <= 0) {
20319 				/* burst count reached, or alloc failed */
20320 				IRE_REFRELE(ire);
20321 				return (err);
20322 			}
20323 
20324 			/* tcp_send() may have sent everything, so check */
20325 			if (*usable <= 0) {
20326 				IRE_REFRELE(ire);
20327 				return (0);
20328 			}
20329 
20330 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
20331 			/*
20332 			 * We may have delivered the Multidata, so make sure
20333 			 * to re-initialize before the next round.
20334 			 */
20335 			md_mp_head = NULL;
20336 			obsegs = obbytes = 0;
20337 			num_burst_seg = tcp->tcp_snd_burst;
20338 			PREP_NEW_MULTIDATA();
20339 
20340 			/* are we starting from the beginning of data block? */
20341 			if (*tail_unsent == 0) {
20342 				*xmit_tail = (*xmit_tail)->b_cont;
20343 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20344 				    (uintptr_t)INT_MAX);
20345 				*tail_unsent = (int)MBLKL(*xmit_tail);
20346 			}
20347 		}
20348 		/*
20349 		 * Record current values for parameters we may need to pass
20350 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
20351 		 * each iteration of the outer loop (each multidata message
20352 		 * creation). If we have a failure in the inner loop, we send
20353 		 * any complete multidata messages we have before reverting
20354 		 * to using the traditional non-md path.
20355 		 */
20356 		snxt_mmd = *snxt;
20357 		usable_mmd = *usable;
20358 		xmit_tail_mmd = *xmit_tail;
20359 		tail_unsent_mmd = *tail_unsent;
20360 		obsegs_mmd = obsegs;
20361 		obbytes_mmd = obbytes;
20362 
20363 		/*
20364 		 * max_pld limits the number of mblks in tcp's transmit
20365 		 * queue that can be added to a Multidata message.  Once
20366 		 * this counter reaches zero, no more additional mblks
20367 		 * can be added to it.  What happens afterwards depends
20368 		 * on whether or not we are set to chain the Multidata
20369 		 * messages.  If we are to link them together, reset
20370 		 * max_pld to its original value (tcp_mdt_max_pld) and
20371 		 * prepare to create a new Multidata message which will
20372 		 * get linked to md_mp_head.  Else, leave it alone and
20373 		 * let the inner loop break on its own.
20374 		 */
20375 		if (tcp_mdt_chain && max_pld == 0)
20376 			PREP_NEW_MULTIDATA();
20377 
20378 		/* adding a payload buffer; re-initialize values */
20379 		if (add_buffer)
20380 			PREP_NEW_PBUF();
20381 
20382 		/*
20383 		 * If we don't have a Multidata, either because we just
20384 		 * (re)entered this outer loop, or after we branched off
20385 		 * to tcp_send above, setup the Multidata and header
20386 		 * buffer to be used.
20387 		 */
20388 		if (md_mp == NULL) {
20389 			int md_hbuflen;
20390 			uint32_t start, stuff;
20391 
20392 			/*
20393 			 * Calculate Multidata header buffer size large enough
20394 			 * to hold all of the headers that can possibly be
20395 			 * sent at this moment.  We'd rather over-estimate
20396 			 * the size than running out of space; this is okay
20397 			 * since this buffer is small anyway.
20398 			 */
20399 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
20400 
20401 			/*
20402 			 * Start and stuff offset for partial hardware
20403 			 * checksum offload; these are currently for IPv4.
20404 			 * For full checksum offload, they are set to zero.
20405 			 */
20406 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
20407 				if (af == AF_INET) {
20408 					start = IP_SIMPLE_HDR_LENGTH;
20409 					stuff = IP_SIMPLE_HDR_LENGTH +
20410 					    TCP_CHECKSUM_OFFSET;
20411 				} else {
20412 					start = IPV6_HDR_LEN;
20413 					stuff = IPV6_HDR_LEN +
20414 					    TCP_CHECKSUM_OFFSET;
20415 				}
20416 			} else {
20417 				start = stuff = 0;
20418 			}
20419 
20420 			/*
20421 			 * Create the header buffer, Multidata, as well as
20422 			 * any necessary attributes (destination address,
20423 			 * SAP and hardware checksum offload) that should
20424 			 * be associated with the Multidata message.
20425 			 */
20426 			ASSERT(cur_hdr_off == 0);
20427 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
20428 			    ((md_hbuf->b_wptr += md_hbuflen),
20429 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
20430 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
20431 			    /* fastpath mblk */
20432 			    ire->ire_nce->nce_res_mp,
20433 			    /* hardware checksum enabled */
20434 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
20435 			    /* hardware checksum offsets */
20436 			    start, stuff, 0,
20437 			    /* hardware checksum flag */
20438 			    hwcksum_flags, tcps) != 0)) {
20439 legacy_send:
20440 				/*
20441 				 * We arrive here from a failure within the
20442 				 * inner (packetizer) loop or we fail one of
20443 				 * the conditionals above. We restore the
20444 				 * previously checkpointed values for:
20445 				 *    xmit_tail
20446 				 *    usable
20447 				 *    tail_unsent
20448 				 *    snxt
20449 				 *    obbytes
20450 				 *    obsegs
20451 				 * We should then be able to dispatch any
20452 				 * complete multidata before reverting to the
20453 				 * traditional path with consistent parameters
20454 				 * (the inner loop updates these as it
20455 				 * iterates).
20456 				 */
20457 				*xmit_tail = xmit_tail_mmd;
20458 				*usable = usable_mmd;
20459 				*tail_unsent = tail_unsent_mmd;
20460 				*snxt = snxt_mmd;
20461 				obbytes = obbytes_mmd;
20462 				obsegs = obsegs_mmd;
20463 				if (md_mp != NULL) {
20464 					/* Unlink message from the chain */
20465 					if (md_mp_head != NULL) {
20466 						err = (intptr_t)rmvb(md_mp_head,
20467 						    md_mp);
20468 						/*
20469 						 * We can't assert that rmvb
20470 						 * did not return -1, since we
20471 						 * may get here before linkb
20472 						 * happens.  We do, however,
20473 						 * check if we just removed the
20474 						 * only element in the list.
20475 						 */
20476 						if (err == 0)
20477 							md_mp_head = NULL;
20478 					}
20479 					/* md_hbuf gets freed automatically */
20480 					TCP_STAT(tcps, tcp_mdt_discarded);
20481 					freeb(md_mp);
20482 				} else {
20483 					/* Either allocb or mmd_alloc failed */
20484 					TCP_STAT(tcps, tcp_mdt_allocfail);
20485 					if (md_hbuf != NULL)
20486 						freeb(md_hbuf);
20487 				}
20488 
20489 				/* send down what we've got so far */
20490 				if (md_mp_head != NULL) {
20491 					tcp_multisend_data(tcp, ire, ill,
20492 					    md_mp_head, obsegs, obbytes,
20493 					    &rconfirm);
20494 				}
20495 legacy_send_no_md:
20496 				if (ire != NULL)
20497 					IRE_REFRELE(ire);
20498 				/*
20499 				 * Too bad; let the legacy path handle this.
20500 				 * We specify INT_MAX for the threshold, since
20501 				 * we gave up with the Multidata processings
20502 				 * and let the old path have it all.
20503 				 */
20504 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20505 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20506 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20507 				    snxt, tail_unsent, xmit_tail, local_time,
20508 				    INT_MAX));
20509 			}
20510 
20511 			/* link to any existing ones, if applicable */
20512 			TCP_STAT(tcps, tcp_mdt_allocd);
20513 			if (md_mp_head == NULL) {
20514 				md_mp_head = md_mp;
20515 			} else if (tcp_mdt_chain) {
20516 				TCP_STAT(tcps, tcp_mdt_linked);
20517 				linkb(md_mp_head, md_mp);
20518 			}
20519 		}
20520 
20521 		ASSERT(md_mp_head != NULL);
20522 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20523 		ASSERT(md_mp != NULL && mmd != NULL);
20524 		ASSERT(md_hbuf != NULL);
20525 
20526 		/*
20527 		 * Packetize the transmittable portion of the data block;
20528 		 * each data block is essentially added to the Multidata
20529 		 * as a payload buffer.  We also deal with adding more
20530 		 * than one payload buffers, which happens when the remaining
20531 		 * packetized portion of the current payload buffer is less
20532 		 * than MSS, while the next data block in transmit queue
20533 		 * has enough data to make up for one.  This "spillover"
20534 		 * case essentially creates a split-packet, where portions
20535 		 * of the packet's payload fragments may span across two
20536 		 * virtually discontiguous address blocks.
20537 		 */
20538 		seg_len = mss;
20539 		do {
20540 			len = seg_len;
20541 
20542 			/* one must remain NULL for DTRACE_IP_FASTPATH */
20543 			ipha = NULL;
20544 			ip6h = NULL;
20545 
20546 			ASSERT(len > 0);
20547 			ASSERT(max_pld >= 0);
20548 			ASSERT(!add_buffer || cur_pld_off == 0);
20549 
20550 			/*
20551 			 * First time around for this payload buffer; note
20552 			 * in the case of a spillover, the following has
20553 			 * been done prior to adding the split-packet
20554 			 * descriptor to Multidata, and we don't want to
20555 			 * repeat the process.
20556 			 */
20557 			if (add_buffer) {
20558 				ASSERT(mmd != NULL);
20559 				ASSERT(md_pbuf == NULL);
20560 				ASSERT(md_pbuf_nxt == NULL);
20561 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20562 
20563 				/*
20564 				 * Have we reached the limit?  We'd get to
20565 				 * this case when we're not chaining the
20566 				 * Multidata messages together, and since
20567 				 * we're done, terminate this loop.
20568 				 */
20569 				if (max_pld == 0)
20570 					break; /* done */
20571 
20572 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20573 					TCP_STAT(tcps, tcp_mdt_allocfail);
20574 					goto legacy_send; /* out_of_mem */
20575 				}
20576 
20577 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20578 				    zc_cap != NULL) {
20579 					if (!ip_md_zcopy_attr(mmd, NULL,
20580 					    zc_cap->ill_zerocopy_flags)) {
20581 						freeb(md_pbuf);
20582 						TCP_STAT(tcps,
20583 						    tcp_mdt_allocfail);
20584 						/* out_of_mem */
20585 						goto legacy_send;
20586 					}
20587 					zcopy = B_TRUE;
20588 				}
20589 
20590 				md_pbuf->b_rptr += base_pld_off;
20591 
20592 				/*
20593 				 * Add a payload buffer to the Multidata; this
20594 				 * operation must not fail, or otherwise our
20595 				 * logic in this routine is broken.  There
20596 				 * is no memory allocation done by the
20597 				 * routine, so any returned failure simply
20598 				 * tells us that we've done something wrong.
20599 				 *
20600 				 * A failure tells us that either we're adding
20601 				 * the same payload buffer more than once, or
20602 				 * we're trying to add more buffers than
20603 				 * allowed (max_pld calculation is wrong).
20604 				 * None of the above cases should happen, and
20605 				 * we panic because either there's horrible
20606 				 * heap corruption, and/or programming mistake.
20607 				 */
20608 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20609 				if (pbuf_idx < 0) {
20610 					cmn_err(CE_PANIC, "tcp_multisend: "
20611 					    "payload buffer logic error "
20612 					    "detected for tcp %p mmd %p "
20613 					    "pbuf %p (%d)\n",
20614 					    (void *)tcp, (void *)mmd,
20615 					    (void *)md_pbuf, pbuf_idx);
20616 				}
20617 
20618 				ASSERT(max_pld > 0);
20619 				--max_pld;
20620 				add_buffer = B_FALSE;
20621 			}
20622 
20623 			ASSERT(md_mp_head != NULL);
20624 			ASSERT(md_pbuf != NULL);
20625 			ASSERT(md_pbuf_nxt == NULL);
20626 			ASSERT(pbuf_idx != -1);
20627 			ASSERT(pbuf_idx_nxt == -1);
20628 			ASSERT(*usable > 0);
20629 
20630 			/*
20631 			 * We spillover to the next payload buffer only
20632 			 * if all of the following is true:
20633 			 *
20634 			 *   1. There is not enough data on the current
20635 			 *	payload buffer to make up `len',
20636 			 *   2. We are allowed to send `len',
20637 			 *   3. The next payload buffer length is large
20638 			 *	enough to accomodate `spill'.
20639 			 */
20640 			if ((spill = len - *tail_unsent) > 0 &&
20641 			    *usable >= len &&
20642 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20643 			    max_pld > 0) {
20644 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20645 				if (md_pbuf_nxt == NULL) {
20646 					TCP_STAT(tcps, tcp_mdt_allocfail);
20647 					goto legacy_send; /* out_of_mem */
20648 				}
20649 
20650 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20651 				    zc_cap != NULL) {
20652 					if (!ip_md_zcopy_attr(mmd, NULL,
20653 					    zc_cap->ill_zerocopy_flags)) {
20654 						freeb(md_pbuf_nxt);
20655 						TCP_STAT(tcps,
20656 						    tcp_mdt_allocfail);
20657 						/* out_of_mem */
20658 						goto legacy_send;
20659 					}
20660 					zcopy = B_TRUE;
20661 				}
20662 
20663 				/*
20664 				 * See comments above on the first call to
20665 				 * mmd_addpldbuf for explanation on the panic.
20666 				 */
20667 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20668 				if (pbuf_idx_nxt < 0) {
20669 					panic("tcp_multisend: "
20670 					    "next payload buffer logic error "
20671 					    "detected for tcp %p mmd %p "
20672 					    "pbuf %p (%d)\n",
20673 					    (void *)tcp, (void *)mmd,
20674 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20675 				}
20676 
20677 				ASSERT(max_pld > 0);
20678 				--max_pld;
20679 			} else if (spill > 0) {
20680 				/*
20681 				 * If there's a spillover, but the following
20682 				 * xmit_tail couldn't give us enough octets
20683 				 * to reach "len", then stop the current
20684 				 * Multidata creation and let the legacy
20685 				 * tcp_send() path take over.  We don't want
20686 				 * to send the tiny segment as part of this
20687 				 * Multidata for performance reasons; instead,
20688 				 * we let the legacy path deal with grouping
20689 				 * it with the subsequent small mblks.
20690 				 */
20691 				if (*usable >= len &&
20692 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20693 					max_pld = 0;
20694 					break;	/* done */
20695 				}
20696 
20697 				/*
20698 				 * We can't spillover, and we are near
20699 				 * the end of the current payload buffer,
20700 				 * so send what's left.
20701 				 */
20702 				ASSERT(*tail_unsent > 0);
20703 				len = *tail_unsent;
20704 			}
20705 
20706 			/* tail_unsent is negated if there is a spillover */
20707 			*tail_unsent -= len;
20708 			*usable -= len;
20709 			ASSERT(*usable >= 0);
20710 
20711 			if (*usable < mss)
20712 				seg_len = *usable;
20713 			/*
20714 			 * Sender SWS avoidance; see comments in tcp_send();
20715 			 * everything else is the same, except that we only
20716 			 * do this here if there is no more data to be sent
20717 			 * following the current xmit_tail.  We don't check
20718 			 * for 1-byte urgent data because we shouldn't get
20719 			 * here if TCP_URG_VALID is set.
20720 			 */
20721 			if (*usable > 0 && *usable < mss &&
20722 			    ((md_pbuf_nxt == NULL &&
20723 			    (*xmit_tail)->b_cont == NULL) ||
20724 			    (md_pbuf_nxt != NULL &&
20725 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20726 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20727 			    (tcp->tcp_unsent -
20728 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20729 			    !tcp->tcp_zero_win_probe) {
20730 				if ((*snxt + len) == tcp->tcp_snxt &&
20731 				    (*snxt + len) == tcp->tcp_suna) {
20732 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20733 				}
20734 				done = B_TRUE;
20735 			}
20736 
20737 			/*
20738 			 * Prime pump for IP's checksumming on our behalf;
20739 			 * include the adjustment for a source route if any.
20740 			 * Do this only for software/partial hardware checksum
20741 			 * offload, as this field gets zeroed out later for
20742 			 * the full hardware checksum offload case.
20743 			 */
20744 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20745 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20746 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20747 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20748 			}
20749 
20750 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20751 			*snxt += len;
20752 
20753 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20754 			/*
20755 			 * We set the PUSH bit only if TCP has no more buffered
20756 			 * data to be transmitted (or if sender SWS avoidance
20757 			 * takes place), as opposed to setting it for every
20758 			 * last packet in the burst.
20759 			 */
20760 			if (done ||
20761 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20762 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20763 
20764 			/*
20765 			 * Set FIN bit if this is our last segment; snxt
20766 			 * already includes its length, and it will not
20767 			 * be adjusted after this point.
20768 			 */
20769 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20770 			    *snxt == tcp->tcp_fss) {
20771 				if (!tcp->tcp_fin_acked) {
20772 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20773 					BUMP_MIB(&tcps->tcps_mib,
20774 					    tcpOutControl);
20775 				}
20776 				if (!tcp->tcp_fin_sent) {
20777 					tcp->tcp_fin_sent = B_TRUE;
20778 					/*
20779 					 * tcp state must be ESTABLISHED
20780 					 * in order for us to get here in
20781 					 * the first place.
20782 					 */
20783 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20784 
20785 					/*
20786 					 * Upon returning from this routine,
20787 					 * tcp_wput_data() will set tcp_snxt
20788 					 * to be equal to snxt + tcp_fin_sent.
20789 					 * This is essentially the same as
20790 					 * setting it to tcp_fss + 1.
20791 					 */
20792 				}
20793 			}
20794 
20795 			tcp->tcp_last_sent_len = (ushort_t)len;
20796 
20797 			len += tcp_hdr_len;
20798 			if (tcp->tcp_ipversion == IPV4_VERSION)
20799 				tcp->tcp_ipha->ipha_length = htons(len);
20800 			else
20801 				tcp->tcp_ip6h->ip6_plen = htons(len -
20802 				    ((char *)&tcp->tcp_ip6h[1] -
20803 				    tcp->tcp_iphc));
20804 
20805 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20806 
20807 			/* setup header fragment */
20808 			PDESC_HDR_ADD(pkt_info,
20809 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20810 			    tcp->tcp_mdt_hdr_head,		/* head room */
20811 			    tcp_hdr_len,			/* len */
20812 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20813 
20814 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20815 			    hdr_frag_sz);
20816 			ASSERT(MBLKIN(md_hbuf,
20817 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20818 			    PDESC_HDRSIZE(pkt_info)));
20819 
20820 			/* setup first payload fragment */
20821 			PDESC_PLD_INIT(pkt_info);
20822 			PDESC_PLD_SPAN_ADD(pkt_info,
20823 			    pbuf_idx,				/* index */
20824 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20825 			    tcp->tcp_last_sent_len);		/* len */
20826 
20827 			/* create a split-packet in case of a spillover */
20828 			if (md_pbuf_nxt != NULL) {
20829 				ASSERT(spill > 0);
20830 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20831 				ASSERT(!add_buffer);
20832 
20833 				md_pbuf = md_pbuf_nxt;
20834 				md_pbuf_nxt = NULL;
20835 				pbuf_idx = pbuf_idx_nxt;
20836 				pbuf_idx_nxt = -1;
20837 				cur_pld_off = spill;
20838 
20839 				/* trim out first payload fragment */
20840 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20841 
20842 				/* setup second payload fragment */
20843 				PDESC_PLD_SPAN_ADD(pkt_info,
20844 				    pbuf_idx,			/* index */
20845 				    md_pbuf->b_rptr,		/* start */
20846 				    spill);			/* len */
20847 
20848 				if ((*xmit_tail)->b_next == NULL) {
20849 					/*
20850 					 * Store the lbolt used for RTT
20851 					 * estimation. We can only record one
20852 					 * timestamp per mblk so we do it when
20853 					 * we reach the end of the payload
20854 					 * buffer.  Also we only take a new
20855 					 * timestamp sample when the previous
20856 					 * timed data from the same mblk has
20857 					 * been ack'ed.
20858 					 */
20859 					(*xmit_tail)->b_prev = local_time;
20860 					(*xmit_tail)->b_next =
20861 					    (mblk_t *)(uintptr_t)first_snxt;
20862 				}
20863 
20864 				first_snxt = *snxt - spill;
20865 
20866 				/*
20867 				 * Advance xmit_tail; usable could be 0 by
20868 				 * the time we got here, but we made sure
20869 				 * above that we would only spillover to
20870 				 * the next data block if usable includes
20871 				 * the spilled-over amount prior to the
20872 				 * subtraction.  Therefore, we are sure
20873 				 * that xmit_tail->b_cont can't be NULL.
20874 				 */
20875 				ASSERT((*xmit_tail)->b_cont != NULL);
20876 				*xmit_tail = (*xmit_tail)->b_cont;
20877 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20878 				    (uintptr_t)INT_MAX);
20879 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20880 			} else {
20881 				cur_pld_off += tcp->tcp_last_sent_len;
20882 			}
20883 
20884 			/*
20885 			 * Fill in the header using the template header, and
20886 			 * add options such as time-stamp, ECN and/or SACK,
20887 			 * as needed.
20888 			 */
20889 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20890 			    (clock_t)local_time, num_sack_blk);
20891 
20892 			/* take care of some IP header businesses */
20893 			if (af == AF_INET) {
20894 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20895 
20896 				ASSERT(OK_32PTR((uchar_t *)ipha));
20897 				ASSERT(PDESC_HDRL(pkt_info) >=
20898 				    IP_SIMPLE_HDR_LENGTH);
20899 				ASSERT(ipha->ipha_version_and_hdr_length ==
20900 				    IP_SIMPLE_HDR_VERSION);
20901 
20902 				/*
20903 				 * Assign ident value for current packet; see
20904 				 * related comments in ip_wput_ire() about the
20905 				 * contract private interface with clustering
20906 				 * group.
20907 				 */
20908 				clusterwide = B_FALSE;
20909 				if (cl_inet_ipident != NULL) {
20910 					ASSERT(cl_inet_isclusterwide != NULL);
20911 					if ((*cl_inet_isclusterwide)(stack_id,
20912 					    IPPROTO_IP, AF_INET,
20913 					    (uint8_t *)(uintptr_t)src, NULL)) {
20914 						ipha->ipha_ident =
20915 						    (*cl_inet_ipident)(stack_id,
20916 						    IPPROTO_IP, AF_INET,
20917 						    (uint8_t *)(uintptr_t)src,
20918 						    (uint8_t *)(uintptr_t)dst,
20919 						    NULL);
20920 						clusterwide = B_TRUE;
20921 					}
20922 				}
20923 
20924 				if (!clusterwide) {
20925 					ipha->ipha_ident = (uint16_t)
20926 					    atomic_add_32_nv(
20927 						&ire->ire_ident, 1);
20928 				}
20929 #ifndef _BIG_ENDIAN
20930 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20931 				    (ipha->ipha_ident >> 8);
20932 #endif
20933 			} else {
20934 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20935 
20936 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20937 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20938 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20939 				ASSERT(PDESC_HDRL(pkt_info) >=
20940 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20941 				    TCP_CHECKSUM_SIZE));
20942 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20943 
20944 				if (tcp->tcp_ip_forward_progress) {
20945 					rconfirm = B_TRUE;
20946 					tcp->tcp_ip_forward_progress = B_FALSE;
20947 				}
20948 			}
20949 
20950 			/* at least one payload span, and at most two */
20951 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20952 
20953 			/* add the packet descriptor to Multidata */
20954 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20955 			    KM_NOSLEEP)) == NULL) {
20956 				/*
20957 				 * Any failure other than ENOMEM indicates
20958 				 * that we have passed in invalid pkt_info
20959 				 * or parameters to mmd_addpdesc, which must
20960 				 * not happen.
20961 				 *
20962 				 * EINVAL is a result of failure on boundary
20963 				 * checks against the pkt_info contents.  It
20964 				 * should not happen, and we panic because
20965 				 * either there's horrible heap corruption,
20966 				 * and/or programming mistake.
20967 				 */
20968 				if (err != ENOMEM) {
20969 					cmn_err(CE_PANIC, "tcp_multisend: "
20970 					    "pdesc logic error detected for "
20971 					    "tcp %p mmd %p pinfo %p (%d)\n",
20972 					    (void *)tcp, (void *)mmd,
20973 					    (void *)pkt_info, err);
20974 				}
20975 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20976 				goto legacy_send; /* out_of_mem */
20977 			}
20978 			ASSERT(pkt != NULL);
20979 
20980 			/* calculate IP header and TCP checksums */
20981 			if (af == AF_INET) {
20982 				/* calculate pseudo-header checksum */
20983 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20984 				    (src >> 16) + (src & 0xFFFF);
20985 
20986 				/* offset for TCP header checksum */
20987 				up = IPH_TCPH_CHECKSUMP(ipha,
20988 				    IP_SIMPLE_HDR_LENGTH);
20989 			} else {
20990 				up = (uint16_t *)&ip6h->ip6_src;
20991 
20992 				/* calculate pseudo-header checksum */
20993 				cksum = up[0] + up[1] + up[2] + up[3] +
20994 				    up[4] + up[5] + up[6] + up[7] +
20995 				    up[8] + up[9] + up[10] + up[11] +
20996 				    up[12] + up[13] + up[14] + up[15];
20997 
20998 				/* Fold the initial sum */
20999 				cksum = (cksum & 0xffff) + (cksum >> 16);
21000 
21001 				up = (uint16_t *)(((uchar_t *)ip6h) +
21002 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
21003 			}
21004 
21005 			if (hwcksum_flags & HCK_FULLCKSUM) {
21006 				/* clear checksum field for hardware */
21007 				*up = 0;
21008 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
21009 				uint32_t sum;
21010 
21011 				/* pseudo-header checksumming */
21012 				sum = *up + cksum + IP_TCP_CSUM_COMP;
21013 				sum = (sum & 0xFFFF) + (sum >> 16);
21014 				*up = (sum & 0xFFFF) + (sum >> 16);
21015 			} else {
21016 				/* software checksumming */
21017 				TCP_STAT(tcps, tcp_out_sw_cksum);
21018 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
21019 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
21020 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
21021 				    cksum + IP_TCP_CSUM_COMP);
21022 				if (*up == 0)
21023 					*up = 0xFFFF;
21024 			}
21025 
21026 			/* IPv4 header checksum */
21027 			if (af == AF_INET) {
21028 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
21029 					ipha->ipha_hdr_checksum = 0;
21030 				} else {
21031 					IP_HDR_CKSUM(ipha, cksum,
21032 					    ((uint32_t *)ipha)[0],
21033 					    ((uint16_t *)ipha)[4]);
21034 				}
21035 			}
21036 
21037 			if (af == AF_INET &&
21038 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
21039 			    af == AF_INET6 &&
21040 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
21041 				mblk_t	*mp, *mp1;
21042 				uchar_t	*hdr_rptr, *hdr_wptr;
21043 				uchar_t	*pld_rptr, *pld_wptr;
21044 
21045 				/*
21046 				 * We reconstruct a pseudo packet for the hooks
21047 				 * framework using mmd_transform_link().
21048 				 * If it is a split packet we pullup the
21049 				 * payload. FW_HOOKS expects a pkt comprising
21050 				 * of two mblks: a header and the payload.
21051 				 */
21052 				if ((mp = mmd_transform_link(pkt)) == NULL) {
21053 					TCP_STAT(tcps, tcp_mdt_allocfail);
21054 					goto legacy_send;
21055 				}
21056 
21057 				if (pkt_info->pld_cnt > 1) {
21058 					/* split payload, more than one pld */
21059 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
21060 					    NULL) {
21061 						freemsg(mp);
21062 						TCP_STAT(tcps,
21063 						    tcp_mdt_allocfail);
21064 						goto legacy_send;
21065 					}
21066 					freemsg(mp->b_cont);
21067 					mp->b_cont = mp1;
21068 				} else {
21069 					mp1 = mp->b_cont;
21070 				}
21071 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
21072 
21073 				/*
21074 				 * Remember the message offsets. This is so we
21075 				 * can detect changes when we return from the
21076 				 * FW_HOOKS callbacks.
21077 				 */
21078 				hdr_rptr = mp->b_rptr;
21079 				hdr_wptr = mp->b_wptr;
21080 				pld_rptr = mp->b_cont->b_rptr;
21081 				pld_wptr = mp->b_cont->b_wptr;
21082 
21083 				if (af == AF_INET) {
21084 					DTRACE_PROBE4(
21085 					    ip4__physical__out__start,
21086 					    ill_t *, NULL,
21087 					    ill_t *, ill,
21088 					    ipha_t *, ipha,
21089 					    mblk_t *, mp);
21090 					FW_HOOKS(
21091 					    ipst->ips_ip4_physical_out_event,
21092 					    ipst->ips_ipv4firewall_physical_out,
21093 					    NULL, ill, ipha, mp, mp, 0, ipst);
21094 					DTRACE_PROBE1(
21095 					    ip4__physical__out__end,
21096 					    mblk_t *, mp);
21097 				} else {
21098 					DTRACE_PROBE4(
21099 					    ip6__physical__out_start,
21100 					    ill_t *, NULL,
21101 					    ill_t *, ill,
21102 					    ip6_t *, ip6h,
21103 					    mblk_t *, mp);
21104 					FW_HOOKS6(
21105 					    ipst->ips_ip6_physical_out_event,
21106 					    ipst->ips_ipv6firewall_physical_out,
21107 					    NULL, ill, ip6h, mp, mp, 0, ipst);
21108 					DTRACE_PROBE1(
21109 					    ip6__physical__out__end,
21110 					    mblk_t *, mp);
21111 				}
21112 
21113 				if (mp == NULL ||
21114 				    (mp1 = mp->b_cont) == NULL ||
21115 				    mp->b_rptr != hdr_rptr ||
21116 				    mp->b_wptr != hdr_wptr ||
21117 				    mp1->b_rptr != pld_rptr ||
21118 				    mp1->b_wptr != pld_wptr ||
21119 				    mp1->b_cont != NULL) {
21120 					/*
21121 					 * We abandon multidata processing and
21122 					 * return to the normal path, either
21123 					 * when a packet is blocked, or when
21124 					 * the boundaries of header buffer or
21125 					 * payload buffer have been changed by
21126 					 * FW_HOOKS[6].
21127 					 */
21128 					if (mp != NULL)
21129 						freemsg(mp);
21130 					goto legacy_send;
21131 				}
21132 				/* Finished with the pseudo packet */
21133 				freemsg(mp);
21134 			}
21135 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
21136 			    ill, ipha, ip6h);
21137 			/* advance header offset */
21138 			cur_hdr_off += hdr_frag_sz;
21139 
21140 			obbytes += tcp->tcp_last_sent_len;
21141 			++obsegs;
21142 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
21143 		    *tail_unsent > 0);
21144 
21145 		if ((*xmit_tail)->b_next == NULL) {
21146 			/*
21147 			 * Store the lbolt used for RTT estimation. We can only
21148 			 * record one timestamp per mblk so we do it when we
21149 			 * reach the end of the payload buffer. Also we only
21150 			 * take a new timestamp sample when the previous timed
21151 			 * data from the same mblk has been ack'ed.
21152 			 */
21153 			(*xmit_tail)->b_prev = local_time;
21154 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
21155 		}
21156 
21157 		ASSERT(*tail_unsent >= 0);
21158 		if (*tail_unsent > 0) {
21159 			/*
21160 			 * We got here because we broke out of the above
21161 			 * loop due to of one of the following cases:
21162 			 *
21163 			 *   1. len < adjusted MSS (i.e. small),
21164 			 *   2. Sender SWS avoidance,
21165 			 *   3. max_pld is zero.
21166 			 *
21167 			 * We are done for this Multidata, so trim our
21168 			 * last payload buffer (if any) accordingly.
21169 			 */
21170 			if (md_pbuf != NULL)
21171 				md_pbuf->b_wptr -= *tail_unsent;
21172 		} else if (*usable > 0) {
21173 			*xmit_tail = (*xmit_tail)->b_cont;
21174 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
21175 			    (uintptr_t)INT_MAX);
21176 			*tail_unsent = (int)MBLKL(*xmit_tail);
21177 			add_buffer = B_TRUE;
21178 		}
21179 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
21180 	    (tcp_mdt_chain || max_pld > 0));
21181 
21182 	if (md_mp_head != NULL) {
21183 		/* send everything down */
21184 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
21185 		    &rconfirm);
21186 	}
21187 
21188 #undef PREP_NEW_MULTIDATA
21189 #undef PREP_NEW_PBUF
21190 #undef IPVER
21191 
21192 	IRE_REFRELE(ire);
21193 	return (0);
21194 }
21195 
21196 /*
21197  * A wrapper function for sending one or more Multidata messages down to
21198  * the module below ip; this routine does not release the reference of the
21199  * IRE (caller does that).  This routine is analogous to tcp_send_data().
21200  */
21201 static void
21202 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
21203     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
21204 {
21205 	uint64_t delta;
21206 	nce_t *nce;
21207 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21208 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21209 
21210 	ASSERT(ire != NULL && ill != NULL);
21211 	ASSERT(ire->ire_stq != NULL);
21212 	ASSERT(md_mp_head != NULL);
21213 	ASSERT(rconfirm != NULL);
21214 
21215 	/* adjust MIBs and IRE timestamp */
21216 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
21217 	tcp->tcp_obsegs += obsegs;
21218 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
21219 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
21220 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
21221 
21222 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21223 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
21224 	} else {
21225 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
21226 	}
21227 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
21228 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
21229 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
21230 
21231 	ire->ire_ob_pkt_count += obsegs;
21232 	if (ire->ire_ipif != NULL)
21233 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
21234 	ire->ire_last_used_time = lbolt;
21235 
21236 	if (ipst->ips_ipobs_enabled) {
21237 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
21238 		pdesc_t *dl_pkt;
21239 		pdescinfo_t pinfo;
21240 		mblk_t *nmp;
21241 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
21242 
21243 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
21244 		    (dl_pkt != NULL);
21245 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
21246 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
21247 				continue;
21248 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
21249 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
21250 			freemsg(nmp);
21251 		}
21252 	}
21253 
21254 	/* send it down */
21255 	putnext(ire->ire_stq, md_mp_head);
21256 
21257 	/* we're done for TCP/IPv4 */
21258 	if (tcp->tcp_ipversion == IPV4_VERSION)
21259 		return;
21260 
21261 	nce = ire->ire_nce;
21262 
21263 	ASSERT(nce != NULL);
21264 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
21265 	ASSERT(nce->nce_state != ND_INCOMPLETE);
21266 
21267 	/* reachability confirmation? */
21268 	if (*rconfirm) {
21269 		nce->nce_last = TICK_TO_MSEC(lbolt64);
21270 		if (nce->nce_state != ND_REACHABLE) {
21271 			mutex_enter(&nce->nce_lock);
21272 			nce->nce_state = ND_REACHABLE;
21273 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
21274 			mutex_exit(&nce->nce_lock);
21275 			(void) untimeout(nce->nce_timeout_id);
21276 			if (ip_debug > 2) {
21277 				/* ip1dbg */
21278 				pr_addr_dbg("tcp_multisend_data: state "
21279 				    "for %s changed to REACHABLE\n",
21280 				    AF_INET6, &ire->ire_addr_v6);
21281 			}
21282 		}
21283 		/* reset transport reachability confirmation */
21284 		*rconfirm = B_FALSE;
21285 	}
21286 
21287 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
21288 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
21289 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
21290 
21291 	if (delta > (uint64_t)ill->ill_reachable_time) {
21292 		mutex_enter(&nce->nce_lock);
21293 		switch (nce->nce_state) {
21294 		case ND_REACHABLE:
21295 		case ND_STALE:
21296 			/*
21297 			 * ND_REACHABLE is identical to ND_STALE in this
21298 			 * specific case. If reachable time has expired for
21299 			 * this neighbor (delta is greater than reachable
21300 			 * time), conceptually, the neighbor cache is no
21301 			 * longer in REACHABLE state, but already in STALE
21302 			 * state.  So the correct transition here is to
21303 			 * ND_DELAY.
21304 			 */
21305 			nce->nce_state = ND_DELAY;
21306 			mutex_exit(&nce->nce_lock);
21307 			NDP_RESTART_TIMER(nce,
21308 			    ipst->ips_delay_first_probe_time);
21309 			if (ip_debug > 3) {
21310 				/* ip2dbg */
21311 				pr_addr_dbg("tcp_multisend_data: state "
21312 				    "for %s changed to DELAY\n",
21313 				    AF_INET6, &ire->ire_addr_v6);
21314 			}
21315 			break;
21316 		case ND_DELAY:
21317 		case ND_PROBE:
21318 			mutex_exit(&nce->nce_lock);
21319 			/* Timers have already started */
21320 			break;
21321 		case ND_UNREACHABLE:
21322 			/*
21323 			 * ndp timer has detected that this nce is
21324 			 * unreachable and initiated deleting this nce
21325 			 * and all its associated IREs. This is a race
21326 			 * where we found the ire before it was deleted
21327 			 * and have just sent out a packet using this
21328 			 * unreachable nce.
21329 			 */
21330 			mutex_exit(&nce->nce_lock);
21331 			break;
21332 		default:
21333 			ASSERT(0);
21334 		}
21335 	}
21336 }
21337 
21338 /*
21339  * Derived from tcp_send_data().
21340  */
21341 static void
21342 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
21343     int num_lso_seg)
21344 {
21345 	ipha_t		*ipha;
21346 	mblk_t		*ire_fp_mp;
21347 	uint_t		ire_fp_mp_len;
21348 	uint32_t	hcksum_txflags = 0;
21349 	ipaddr_t	src;
21350 	ipaddr_t	dst;
21351 	uint32_t	cksum;
21352 	uint16_t	*up;
21353 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21354 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21355 
21356 	ASSERT(DB_TYPE(mp) == M_DATA);
21357 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
21358 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
21359 	ASSERT(tcp->tcp_connp != NULL);
21360 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
21361 
21362 	ipha = (ipha_t *)mp->b_rptr;
21363 	src = ipha->ipha_src;
21364 	dst = ipha->ipha_dst;
21365 
21366 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
21367 
21368 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21369 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
21370 	    num_lso_seg);
21371 #ifndef _BIG_ENDIAN
21372 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21373 #endif
21374 	if (tcp->tcp_snd_zcopy_aware) {
21375 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
21376 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
21377 			mp = tcp_zcopy_disable(tcp, mp);
21378 	}
21379 
21380 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
21381 		ASSERT(ill->ill_hcksum_capab != NULL);
21382 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
21383 	}
21384 
21385 	/*
21386 	 * Since the TCP checksum should be recalculated by h/w, we can just
21387 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
21388 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
21389 	 * The partial pseudo-header excludes TCP length, that was calculated
21390 	 * in tcp_send(), so to zero *up before further processing.
21391 	 */
21392 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21393 
21394 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
21395 	*up = 0;
21396 
21397 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
21398 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
21399 
21400 	/*
21401 	 * Append LSO flags and mss to the mp.
21402 	 */
21403 	lso_info_set(mp, mss, HW_LSO);
21404 
21405 	ipha->ipha_fragment_offset_and_flags |=
21406 	    (uint32_t)htons(ire->ire_frag_flag);
21407 
21408 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
21409 	ire_fp_mp_len = MBLKL(ire_fp_mp);
21410 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
21411 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
21412 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
21413 
21414 	UPDATE_OB_PKT_COUNT(ire);
21415 	ire->ire_last_used_time = lbolt;
21416 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
21417 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
21418 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
21419 	    ntohs(ipha->ipha_length));
21420 
21421 	DTRACE_PROBE4(ip4__physical__out__start,
21422 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
21423 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
21424 	    ipst->ips_ipv4firewall_physical_out, NULL,
21425 	    ill, ipha, mp, mp, 0, ipst);
21426 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21427 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
21428 
21429 	if (mp != NULL) {
21430 		if (ipst->ips_ipobs_enabled) {
21431 			zoneid_t szone;
21432 
21433 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
21434 			    ipst, ALL_ZONES);
21435 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
21436 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
21437 		}
21438 
21439 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0);
21440 	}
21441 }
21442 
21443 /*
21444  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
21445  * scheme, and returns one of the following:
21446  *
21447  * -1 = failed allocation.
21448  *  0 = success; burst count reached, or usable send window is too small,
21449  *      and that we'd rather wait until later before sending again.
21450  *  1 = success; we are called from tcp_multisend(), and both usable send
21451  *      window and tail_unsent are greater than the MDT threshold, and thus
21452  *      Multidata Transmit should be used instead.
21453  */
21454 static int
21455 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
21456     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
21457     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
21458     const int mdt_thres)
21459 {
21460 	int num_burst_seg = tcp->tcp_snd_burst;
21461 	ire_t		*ire = NULL;
21462 	ill_t		*ill = NULL;
21463 	mblk_t		*ire_fp_mp = NULL;
21464 	uint_t		ire_fp_mp_len = 0;
21465 	int		num_lso_seg = 1;
21466 	uint_t		lso_usable;
21467 	boolean_t	do_lso_send = B_FALSE;
21468 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21469 
21470 	/*
21471 	 * Check LSO capability before any further work. And the similar check
21472 	 * need to be done in for(;;) loop.
21473 	 * LSO will be deployed when therer is more than one mss of available
21474 	 * data and a burst transmission is allowed.
21475 	 */
21476 	if (tcp->tcp_lso &&
21477 	    (tcp->tcp_valid_bits == 0 ||
21478 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21479 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21480 		/*
21481 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21482 		 */
21483 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
21484 			/*
21485 			 * Enable LSO with this transmission.
21486 			 * Since IRE has been hold in
21487 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
21488 			 * should be called before return.
21489 			 */
21490 			do_lso_send = B_TRUE;
21491 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21492 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21493 			/* Round up to multiple of 4 */
21494 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21495 		} else {
21496 			do_lso_send = B_FALSE;
21497 			ill = NULL;
21498 		}
21499 	}
21500 
21501 	for (;;) {
21502 		struct datab	*db;
21503 		tcph_t		*tcph;
21504 		uint32_t	sum;
21505 		mblk_t		*mp, *mp1;
21506 		uchar_t		*rptr;
21507 		int		len;
21508 
21509 		/*
21510 		 * If we're called by tcp_multisend(), and the amount of
21511 		 * sendable data as well as the size of current xmit_tail
21512 		 * is beyond the MDT threshold, return to the caller and
21513 		 * let the large data transmit be done using MDT.
21514 		 */
21515 		if (*usable > 0 && *usable > mdt_thres &&
21516 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21517 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21518 			ASSERT(tcp->tcp_mdt);
21519 			return (1);	/* success; do large send */
21520 		}
21521 
21522 		if (num_burst_seg == 0)
21523 			break;		/* success; burst count reached */
21524 
21525 		/*
21526 		 * Calculate the maximum payload length we can send in *one*
21527 		 * time.
21528 		 */
21529 		if (do_lso_send) {
21530 			/*
21531 			 * Check whether need to do LSO any more.
21532 			 */
21533 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21534 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21535 				lso_usable = MIN(lso_usable,
21536 				    num_burst_seg * mss);
21537 
21538 				num_lso_seg = lso_usable / mss;
21539 				if (lso_usable % mss) {
21540 					num_lso_seg++;
21541 					tcp->tcp_last_sent_len = (ushort_t)
21542 					    (lso_usable % mss);
21543 				} else {
21544 					tcp->tcp_last_sent_len = (ushort_t)mss;
21545 				}
21546 			} else {
21547 				do_lso_send = B_FALSE;
21548 				num_lso_seg = 1;
21549 				lso_usable = mss;
21550 			}
21551 		}
21552 
21553 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21554 
21555 		/*
21556 		 * Adjust num_burst_seg here.
21557 		 */
21558 		num_burst_seg -= num_lso_seg;
21559 
21560 		len = mss;
21561 		if (len > *usable) {
21562 			ASSERT(do_lso_send == B_FALSE);
21563 
21564 			len = *usable;
21565 			if (len <= 0) {
21566 				/* Terminate the loop */
21567 				break;	/* success; too small */
21568 			}
21569 			/*
21570 			 * Sender silly-window avoidance.
21571 			 * Ignore this if we are going to send a
21572 			 * zero window probe out.
21573 			 *
21574 			 * TODO: force data into microscopic window?
21575 			 *	==> (!pushed || (unsent > usable))
21576 			 */
21577 			if (len < (tcp->tcp_max_swnd >> 1) &&
21578 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21579 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21580 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21581 				/*
21582 				 * If the retransmit timer is not running
21583 				 * we start it so that we will retransmit
21584 				 * in the case when the the receiver has
21585 				 * decremented the window.
21586 				 */
21587 				if (*snxt == tcp->tcp_snxt &&
21588 				    *snxt == tcp->tcp_suna) {
21589 					/*
21590 					 * We are not supposed to send
21591 					 * anything.  So let's wait a little
21592 					 * bit longer before breaking SWS
21593 					 * avoidance.
21594 					 *
21595 					 * What should the value be?
21596 					 * Suggestion: MAX(init rexmit time,
21597 					 * tcp->tcp_rto)
21598 					 */
21599 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21600 				}
21601 				break;	/* success; too small */
21602 			}
21603 		}
21604 
21605 		tcph = tcp->tcp_tcph;
21606 
21607 		/*
21608 		 * The reason to adjust len here is that we need to set flags
21609 		 * and calculate checksum.
21610 		 */
21611 		if (do_lso_send)
21612 			len = lso_usable;
21613 
21614 		*usable -= len; /* Approximate - can be adjusted later */
21615 		if (*usable > 0)
21616 			tcph->th_flags[0] = TH_ACK;
21617 		else
21618 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21619 
21620 		/*
21621 		 * Prime pump for IP's checksumming on our behalf
21622 		 * Include the adjustment for a source route if any.
21623 		 */
21624 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21625 		sum = (sum >> 16) + (sum & 0xFFFF);
21626 		U16_TO_ABE16(sum, tcph->th_sum);
21627 
21628 		U32_TO_ABE32(*snxt, tcph->th_seq);
21629 
21630 		/*
21631 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21632 		 * set.  For the case when TCP_FSS_VALID is the only valid
21633 		 * bit (normal active close), branch off only when we think
21634 		 * that the FIN flag needs to be set.  Note for this case,
21635 		 * that (snxt + len) may not reflect the actual seg_len,
21636 		 * as len may be further reduced in tcp_xmit_mp().  If len
21637 		 * gets modified, we will end up here again.
21638 		 */
21639 		if (tcp->tcp_valid_bits != 0 &&
21640 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21641 		    ((*snxt + len) == tcp->tcp_fss))) {
21642 			uchar_t		*prev_rptr;
21643 			uint32_t	prev_snxt = tcp->tcp_snxt;
21644 
21645 			if (*tail_unsent == 0) {
21646 				ASSERT((*xmit_tail)->b_cont != NULL);
21647 				*xmit_tail = (*xmit_tail)->b_cont;
21648 				prev_rptr = (*xmit_tail)->b_rptr;
21649 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21650 				    (*xmit_tail)->b_rptr);
21651 			} else {
21652 				prev_rptr = (*xmit_tail)->b_rptr;
21653 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21654 				    *tail_unsent;
21655 			}
21656 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21657 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21658 			/* Restore tcp_snxt so we get amount sent right. */
21659 			tcp->tcp_snxt = prev_snxt;
21660 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21661 				/*
21662 				 * If the previous timestamp is still in use,
21663 				 * don't stomp on it.
21664 				 */
21665 				if ((*xmit_tail)->b_next == NULL) {
21666 					(*xmit_tail)->b_prev = local_time;
21667 					(*xmit_tail)->b_next =
21668 					    (mblk_t *)(uintptr_t)(*snxt);
21669 				}
21670 			} else
21671 				(*xmit_tail)->b_rptr = prev_rptr;
21672 
21673 			if (mp == NULL) {
21674 				if (ire != NULL)
21675 					IRE_REFRELE(ire);
21676 				return (-1);
21677 			}
21678 			mp1 = mp->b_cont;
21679 
21680 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21681 				tcp->tcp_last_sent_len = (ushort_t)len;
21682 			while (mp1->b_cont) {
21683 				*xmit_tail = (*xmit_tail)->b_cont;
21684 				(*xmit_tail)->b_prev = local_time;
21685 				(*xmit_tail)->b_next =
21686 				    (mblk_t *)(uintptr_t)(*snxt);
21687 				mp1 = mp1->b_cont;
21688 			}
21689 			*snxt += len;
21690 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21691 			BUMP_LOCAL(tcp->tcp_obsegs);
21692 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21693 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21694 			tcp_send_data(tcp, q, mp);
21695 			continue;
21696 		}
21697 
21698 		*snxt += len;	/* Adjust later if we don't send all of len */
21699 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21700 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21701 
21702 		if (*tail_unsent) {
21703 			/* Are the bytes above us in flight? */
21704 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21705 			if (rptr != (*xmit_tail)->b_rptr) {
21706 				*tail_unsent -= len;
21707 				if (len <= mss) /* LSO is unusable */
21708 					tcp->tcp_last_sent_len = (ushort_t)len;
21709 				len += tcp_hdr_len;
21710 				if (tcp->tcp_ipversion == IPV4_VERSION)
21711 					tcp->tcp_ipha->ipha_length = htons(len);
21712 				else
21713 					tcp->tcp_ip6h->ip6_plen =
21714 					    htons(len -
21715 					    ((char *)&tcp->tcp_ip6h[1] -
21716 					    tcp->tcp_iphc));
21717 				mp = dupb(*xmit_tail);
21718 				if (mp == NULL) {
21719 					if (ire != NULL)
21720 						IRE_REFRELE(ire);
21721 					return (-1);	/* out_of_mem */
21722 				}
21723 				mp->b_rptr = rptr;
21724 				/*
21725 				 * If the old timestamp is no longer in use,
21726 				 * sample a new timestamp now.
21727 				 */
21728 				if ((*xmit_tail)->b_next == NULL) {
21729 					(*xmit_tail)->b_prev = local_time;
21730 					(*xmit_tail)->b_next =
21731 					    (mblk_t *)(uintptr_t)(*snxt-len);
21732 				}
21733 				goto must_alloc;
21734 			}
21735 		} else {
21736 			*xmit_tail = (*xmit_tail)->b_cont;
21737 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21738 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21739 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21740 			    (*xmit_tail)->b_rptr);
21741 		}
21742 
21743 		(*xmit_tail)->b_prev = local_time;
21744 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21745 
21746 		*tail_unsent -= len;
21747 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21748 			tcp->tcp_last_sent_len = (ushort_t)len;
21749 
21750 		len += tcp_hdr_len;
21751 		if (tcp->tcp_ipversion == IPV4_VERSION)
21752 			tcp->tcp_ipha->ipha_length = htons(len);
21753 		else
21754 			tcp->tcp_ip6h->ip6_plen = htons(len -
21755 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21756 
21757 		mp = dupb(*xmit_tail);
21758 		if (mp == NULL) {
21759 			if (ire != NULL)
21760 				IRE_REFRELE(ire);
21761 			return (-1);	/* out_of_mem */
21762 		}
21763 
21764 		len = tcp_hdr_len;
21765 		/*
21766 		 * There are four reasons to allocate a new hdr mblk:
21767 		 *  1) The bytes above us are in use by another packet
21768 		 *  2) We don't have good alignment
21769 		 *  3) The mblk is being shared
21770 		 *  4) We don't have enough room for a header
21771 		 */
21772 		rptr = mp->b_rptr - len;
21773 		if (!OK_32PTR(rptr) ||
21774 		    ((db = mp->b_datap), db->db_ref != 2) ||
21775 		    rptr < db->db_base + ire_fp_mp_len) {
21776 			/* NOTE: we assume allocb returns an OK_32PTR */
21777 
21778 		must_alloc:;
21779 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21780 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21781 			if (mp1 == NULL) {
21782 				freemsg(mp);
21783 				if (ire != NULL)
21784 					IRE_REFRELE(ire);
21785 				return (-1);	/* out_of_mem */
21786 			}
21787 			mp1->b_cont = mp;
21788 			mp = mp1;
21789 			/* Leave room for Link Level header */
21790 			len = tcp_hdr_len;
21791 			rptr =
21792 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21793 			mp->b_wptr = &rptr[len];
21794 		}
21795 
21796 		/*
21797 		 * Fill in the header using the template header, and add
21798 		 * options such as time-stamp, ECN and/or SACK, as needed.
21799 		 */
21800 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21801 
21802 		mp->b_rptr = rptr;
21803 
21804 		if (*tail_unsent) {
21805 			int spill = *tail_unsent;
21806 
21807 			mp1 = mp->b_cont;
21808 			if (mp1 == NULL)
21809 				mp1 = mp;
21810 
21811 			/*
21812 			 * If we're a little short, tack on more mblks until
21813 			 * there is no more spillover.
21814 			 */
21815 			while (spill < 0) {
21816 				mblk_t *nmp;
21817 				int nmpsz;
21818 
21819 				nmp = (*xmit_tail)->b_cont;
21820 				nmpsz = MBLKL(nmp);
21821 
21822 				/*
21823 				 * Excess data in mblk; can we split it?
21824 				 * If MDT is enabled for the connection,
21825 				 * keep on splitting as this is a transient
21826 				 * send path.
21827 				 */
21828 				if (!do_lso_send && !tcp->tcp_mdt &&
21829 				    (spill + nmpsz > 0)) {
21830 					/*
21831 					 * Don't split if stream head was
21832 					 * told to break up larger writes
21833 					 * into smaller ones.
21834 					 */
21835 					if (tcp->tcp_maxpsz > 0)
21836 						break;
21837 
21838 					/*
21839 					 * Next mblk is less than SMSS/2
21840 					 * rounded up to nearest 64-byte;
21841 					 * let it get sent as part of the
21842 					 * next segment.
21843 					 */
21844 					if (tcp->tcp_localnet &&
21845 					    !tcp->tcp_cork &&
21846 					    (nmpsz < roundup((mss >> 1), 64)))
21847 						break;
21848 				}
21849 
21850 				*xmit_tail = nmp;
21851 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21852 				/* Stash for rtt use later */
21853 				(*xmit_tail)->b_prev = local_time;
21854 				(*xmit_tail)->b_next =
21855 				    (mblk_t *)(uintptr_t)(*snxt - len);
21856 				mp1->b_cont = dupb(*xmit_tail);
21857 				mp1 = mp1->b_cont;
21858 
21859 				spill += nmpsz;
21860 				if (mp1 == NULL) {
21861 					*tail_unsent = spill;
21862 					freemsg(mp);
21863 					if (ire != NULL)
21864 						IRE_REFRELE(ire);
21865 					return (-1);	/* out_of_mem */
21866 				}
21867 			}
21868 
21869 			/* Trim back any surplus on the last mblk */
21870 			if (spill >= 0) {
21871 				mp1->b_wptr -= spill;
21872 				*tail_unsent = spill;
21873 			} else {
21874 				/*
21875 				 * We did not send everything we could in
21876 				 * order to remain within the b_cont limit.
21877 				 */
21878 				*usable -= spill;
21879 				*snxt += spill;
21880 				tcp->tcp_last_sent_len += spill;
21881 				UPDATE_MIB(&tcps->tcps_mib,
21882 				    tcpOutDataBytes, spill);
21883 				/*
21884 				 * Adjust the checksum
21885 				 */
21886 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21887 				sum += spill;
21888 				sum = (sum >> 16) + (sum & 0xFFFF);
21889 				U16_TO_ABE16(sum, tcph->th_sum);
21890 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21891 					sum = ntohs(
21892 					    ((ipha_t *)rptr)->ipha_length) +
21893 					    spill;
21894 					((ipha_t *)rptr)->ipha_length =
21895 					    htons(sum);
21896 				} else {
21897 					sum = ntohs(
21898 					    ((ip6_t *)rptr)->ip6_plen) +
21899 					    spill;
21900 					((ip6_t *)rptr)->ip6_plen =
21901 					    htons(sum);
21902 				}
21903 				*tail_unsent = 0;
21904 			}
21905 		}
21906 		if (tcp->tcp_ip_forward_progress) {
21907 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21908 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21909 			tcp->tcp_ip_forward_progress = B_FALSE;
21910 		}
21911 
21912 		if (do_lso_send) {
21913 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21914 			    num_lso_seg);
21915 			tcp->tcp_obsegs += num_lso_seg;
21916 
21917 			TCP_STAT(tcps, tcp_lso_times);
21918 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21919 		} else {
21920 			tcp_send_data(tcp, q, mp);
21921 			BUMP_LOCAL(tcp->tcp_obsegs);
21922 		}
21923 	}
21924 
21925 	if (ire != NULL)
21926 		IRE_REFRELE(ire);
21927 	return (0);
21928 }
21929 
21930 /* Unlink and return any mblk that looks like it contains a MDT info */
21931 static mblk_t *
21932 tcp_mdt_info_mp(mblk_t *mp)
21933 {
21934 	mblk_t	*prev_mp;
21935 
21936 	for (;;) {
21937 		prev_mp = mp;
21938 		/* no more to process? */
21939 		if ((mp = mp->b_cont) == NULL)
21940 			break;
21941 
21942 		switch (DB_TYPE(mp)) {
21943 		case M_CTL:
21944 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21945 				continue;
21946 			ASSERT(prev_mp != NULL);
21947 			prev_mp->b_cont = mp->b_cont;
21948 			mp->b_cont = NULL;
21949 			return (mp);
21950 		default:
21951 			break;
21952 		}
21953 	}
21954 	return (mp);
21955 }
21956 
21957 /* MDT info update routine, called when IP notifies us about MDT */
21958 static void
21959 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21960 {
21961 	boolean_t prev_state;
21962 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21963 
21964 	/*
21965 	 * IP is telling us to abort MDT on this connection?  We know
21966 	 * this because the capability is only turned off when IP
21967 	 * encounters some pathological cases, e.g. link-layer change
21968 	 * where the new driver doesn't support MDT, or in situation
21969 	 * where MDT usage on the link-layer has been switched off.
21970 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21971 	 * if the link-layer doesn't support MDT, and if it does, it
21972 	 * will indicate that the feature is to be turned on.
21973 	 */
21974 	prev_state = tcp->tcp_mdt;
21975 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21976 	if (!tcp->tcp_mdt && !first) {
21977 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21978 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21979 		    (void *)tcp->tcp_connp));
21980 	}
21981 
21982 	/*
21983 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21984 	 * so disable MDT otherwise.  The checks are done here
21985 	 * and in tcp_wput_data().
21986 	 */
21987 	if (tcp->tcp_mdt &&
21988 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21989 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21990 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21991 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21992 		tcp->tcp_mdt = B_FALSE;
21993 
21994 	if (tcp->tcp_mdt) {
21995 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21996 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21997 			    "version (%d), expected version is %d",
21998 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21999 			tcp->tcp_mdt = B_FALSE;
22000 			return;
22001 		}
22002 
22003 		/*
22004 		 * We need the driver to be able to handle at least three
22005 		 * spans per packet in order for tcp MDT to be utilized.
22006 		 * The first is for the header portion, while the rest are
22007 		 * needed to handle a packet that straddles across two
22008 		 * virtually non-contiguous buffers; a typical tcp packet
22009 		 * therefore consists of only two spans.  Note that we take
22010 		 * a zero as "don't care".
22011 		 */
22012 		if (mdt_capab->ill_mdt_span_limit > 0 &&
22013 		    mdt_capab->ill_mdt_span_limit < 3) {
22014 			tcp->tcp_mdt = B_FALSE;
22015 			return;
22016 		}
22017 
22018 		/* a zero means driver wants default value */
22019 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
22020 		    tcps->tcps_mdt_max_pbufs);
22021 		if (tcp->tcp_mdt_max_pld == 0)
22022 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
22023 
22024 		/* ensure 32-bit alignment */
22025 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
22026 		    mdt_capab->ill_mdt_hdr_head), 4);
22027 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
22028 		    mdt_capab->ill_mdt_hdr_tail), 4);
22029 
22030 		if (!first && !prev_state) {
22031 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
22032 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
22033 			    (void *)tcp->tcp_connp));
22034 		}
22035 	}
22036 }
22037 
22038 /* Unlink and return any mblk that looks like it contains a LSO info */
22039 static mblk_t *
22040 tcp_lso_info_mp(mblk_t *mp)
22041 {
22042 	mblk_t	*prev_mp;
22043 
22044 	for (;;) {
22045 		prev_mp = mp;
22046 		/* no more to process? */
22047 		if ((mp = mp->b_cont) == NULL)
22048 			break;
22049 
22050 		switch (DB_TYPE(mp)) {
22051 		case M_CTL:
22052 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
22053 				continue;
22054 			ASSERT(prev_mp != NULL);
22055 			prev_mp->b_cont = mp->b_cont;
22056 			mp->b_cont = NULL;
22057 			return (mp);
22058 		default:
22059 			break;
22060 		}
22061 	}
22062 
22063 	return (mp);
22064 }
22065 
22066 /* LSO info update routine, called when IP notifies us about LSO */
22067 static void
22068 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
22069 {
22070 	tcp_stack_t *tcps = tcp->tcp_tcps;
22071 
22072 	/*
22073 	 * IP is telling us to abort LSO on this connection?  We know
22074 	 * this because the capability is only turned off when IP
22075 	 * encounters some pathological cases, e.g. link-layer change
22076 	 * where the new NIC/driver doesn't support LSO, or in situation
22077 	 * where LSO usage on the link-layer has been switched off.
22078 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
22079 	 * if the link-layer doesn't support LSO, and if it does, it
22080 	 * will indicate that the feature is to be turned on.
22081 	 */
22082 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
22083 	TCP_STAT(tcps, tcp_lso_enabled);
22084 
22085 	/*
22086 	 * We currently only support LSO on simple TCP/IPv4,
22087 	 * so disable LSO otherwise.  The checks are done here
22088 	 * and in tcp_wput_data().
22089 	 */
22090 	if (tcp->tcp_lso &&
22091 	    (tcp->tcp_ipversion == IPV4_VERSION &&
22092 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
22093 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
22094 		tcp->tcp_lso = B_FALSE;
22095 		TCP_STAT(tcps, tcp_lso_disabled);
22096 	} else {
22097 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
22098 		    lso_capab->ill_lso_max);
22099 	}
22100 }
22101 
22102 static void
22103 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
22104 {
22105 	conn_t *connp = tcp->tcp_connp;
22106 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22107 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22108 
22109 	ASSERT(ire != NULL);
22110 
22111 	/*
22112 	 * We may be in the fastpath here, and although we essentially do
22113 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
22114 	 * we try to keep things as brief as possible.  After all, these
22115 	 * are only best-effort checks, and we do more thorough ones prior
22116 	 * to calling tcp_send()/tcp_multisend().
22117 	 */
22118 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
22119 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
22120 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
22121 	    !(ire->ire_flags & RTF_MULTIRT) &&
22122 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
22123 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
22124 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
22125 			/* Cache the result */
22126 			connp->conn_lso_ok = B_TRUE;
22127 
22128 			ASSERT(ill->ill_lso_capab != NULL);
22129 			if (!ill->ill_lso_capab->ill_lso_on) {
22130 				ill->ill_lso_capab->ill_lso_on = 1;
22131 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22132 				    "LSO for interface %s\n", (void *)connp,
22133 				    ill->ill_name));
22134 			}
22135 			tcp_lso_update(tcp, ill->ill_lso_capab);
22136 		} else if (ipst->ips_ip_multidata_outbound &&
22137 		    ILL_MDT_CAPABLE(ill)) {
22138 			/* Cache the result */
22139 			connp->conn_mdt_ok = B_TRUE;
22140 
22141 			ASSERT(ill->ill_mdt_capab != NULL);
22142 			if (!ill->ill_mdt_capab->ill_mdt_on) {
22143 				ill->ill_mdt_capab->ill_mdt_on = 1;
22144 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22145 				    "MDT for interface %s\n", (void *)connp,
22146 				    ill->ill_name));
22147 			}
22148 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
22149 		}
22150 	}
22151 
22152 	/*
22153 	 * The goal is to reduce the number of generated tcp segments by
22154 	 * setting the maxpsz multiplier to 0; this will have an affect on
22155 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
22156 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
22157 	 * of outbound segments and incoming ACKs, thus allowing for better
22158 	 * network and system performance.  In contrast the legacy behavior
22159 	 * may result in sending less than SMSS size, because the last mblk
22160 	 * for some packets may have more data than needed to make up SMSS,
22161 	 * and the legacy code refused to "split" it.
22162 	 *
22163 	 * We apply the new behavior on following situations:
22164 	 *
22165 	 *   1) Loopback connections,
22166 	 *   2) Connections in which the remote peer is not on local subnet,
22167 	 *   3) Local subnet connections over the bge interface (see below).
22168 	 *
22169 	 * Ideally, we would like this behavior to apply for interfaces other
22170 	 * than bge.  However, doing so would negatively impact drivers which
22171 	 * perform dynamic mapping and unmapping of DMA resources, which are
22172 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
22173 	 * packet will be generated by tcp).  The bge driver does not suffer
22174 	 * from this, as it copies the mblks into pre-mapped buffers, and
22175 	 * therefore does not require more I/O resources than before.
22176 	 *
22177 	 * Otherwise, this behavior is present on all network interfaces when
22178 	 * the destination endpoint is non-local, since reducing the number
22179 	 * of packets in general is good for the network.
22180 	 *
22181 	 * TODO We need to remove this hard-coded conditional for bge once
22182 	 *	a better "self-tuning" mechanism, or a way to comprehend
22183 	 *	the driver transmit strategy is devised.  Until the solution
22184 	 *	is found and well understood, we live with this hack.
22185 	 */
22186 	if (!tcp_static_maxpsz &&
22187 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
22188 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
22189 		/* override the default value */
22190 		tcp->tcp_maxpsz = 0;
22191 
22192 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
22193 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
22194 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
22195 	}
22196 
22197 	/* set the stream head parameters accordingly */
22198 	(void) tcp_maxpsz_set(tcp, B_TRUE);
22199 }
22200 
22201 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
22202 static void
22203 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
22204 {
22205 	uchar_t	fval = *mp->b_rptr;
22206 	mblk_t	*tail;
22207 	queue_t	*q = tcp->tcp_wq;
22208 
22209 	/* TODO: How should flush interact with urgent data? */
22210 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
22211 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
22212 		/*
22213 		 * Flush only data that has not yet been put on the wire.  If
22214 		 * we flush data that we have already transmitted, life, as we
22215 		 * know it, may come to an end.
22216 		 */
22217 		tail = tcp->tcp_xmit_tail;
22218 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
22219 		tcp->tcp_xmit_tail_unsent = 0;
22220 		tcp->tcp_unsent = 0;
22221 		if (tail->b_wptr != tail->b_rptr)
22222 			tail = tail->b_cont;
22223 		if (tail) {
22224 			mblk_t **excess = &tcp->tcp_xmit_head;
22225 			for (;;) {
22226 				mblk_t *mp1 = *excess;
22227 				if (mp1 == tail)
22228 					break;
22229 				tcp->tcp_xmit_tail = mp1;
22230 				tcp->tcp_xmit_last = mp1;
22231 				excess = &mp1->b_cont;
22232 			}
22233 			*excess = NULL;
22234 			tcp_close_mpp(&tail);
22235 			if (tcp->tcp_snd_zcopy_aware)
22236 				tcp_zcopy_notify(tcp);
22237 		}
22238 		/*
22239 		 * We have no unsent data, so unsent must be less than
22240 		 * tcp_xmit_lowater, so re-enable flow.
22241 		 */
22242 		mutex_enter(&tcp->tcp_non_sq_lock);
22243 		if (tcp->tcp_flow_stopped) {
22244 			tcp_clrqfull(tcp);
22245 		}
22246 		mutex_exit(&tcp->tcp_non_sq_lock);
22247 	}
22248 	/*
22249 	 * TODO: you can't just flush these, you have to increase rwnd for one
22250 	 * thing.  For another, how should urgent data interact?
22251 	 */
22252 	if (fval & FLUSHR) {
22253 		*mp->b_rptr = fval & ~FLUSHW;
22254 		/* XXX */
22255 		qreply(q, mp);
22256 		return;
22257 	}
22258 	freemsg(mp);
22259 }
22260 
22261 /*
22262  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
22263  * messages.
22264  */
22265 static void
22266 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
22267 {
22268 	mblk_t	*mp1;
22269 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
22270 	STRUCT_HANDLE(strbuf, sb);
22271 	queue_t *q = tcp->tcp_wq;
22272 	int	error;
22273 	uint_t	addrlen;
22274 
22275 	/* Make sure it is one of ours. */
22276 	switch (iocp->ioc_cmd) {
22277 	case TI_GETMYNAME:
22278 	case TI_GETPEERNAME:
22279 		break;
22280 	default:
22281 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
22282 		return;
22283 	}
22284 	switch (mi_copy_state(q, mp, &mp1)) {
22285 	case -1:
22286 		return;
22287 	case MI_COPY_CASE(MI_COPY_IN, 1):
22288 		break;
22289 	case MI_COPY_CASE(MI_COPY_OUT, 1):
22290 		/* Copy out the strbuf. */
22291 		mi_copyout(q, mp);
22292 		return;
22293 	case MI_COPY_CASE(MI_COPY_OUT, 2):
22294 		/* All done. */
22295 		mi_copy_done(q, mp, 0);
22296 		return;
22297 	default:
22298 		mi_copy_done(q, mp, EPROTO);
22299 		return;
22300 	}
22301 	/* Check alignment of the strbuf */
22302 	if (!OK_32PTR(mp1->b_rptr)) {
22303 		mi_copy_done(q, mp, EINVAL);
22304 		return;
22305 	}
22306 
22307 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
22308 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
22309 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
22310 		mi_copy_done(q, mp, EINVAL);
22311 		return;
22312 	}
22313 
22314 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
22315 	if (mp1 == NULL)
22316 		return;
22317 
22318 	switch (iocp->ioc_cmd) {
22319 	case TI_GETMYNAME:
22320 		error = tcp_getmyname(tcp, (void *)mp1->b_rptr, &addrlen);
22321 		break;
22322 	case TI_GETPEERNAME:
22323 		error = i_tcp_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
22324 		break;
22325 	}
22326 
22327 	if (error != 0) {
22328 		mi_copy_done(q, mp, error);
22329 	} else {
22330 		mp1->b_wptr += addrlen;
22331 		STRUCT_FSET(sb, len, addrlen);
22332 
22333 		/* Copy out the address */
22334 		mi_copyout(q, mp);
22335 	}
22336 }
22337 
22338 static void
22339 tcp_disable_direct_sockfs(tcp_t *tcp)
22340 {
22341 #ifdef	_ILP32
22342 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
22343 #else
22344 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
22345 #endif
22346 	/*
22347 	 * Insert this socket into the acceptor hash.
22348 	 * We might need it for T_CONN_RES message
22349 	 */
22350 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
22351 
22352 	if (tcp->tcp_fused) {
22353 		/*
22354 		 * This is a fused loopback tcp; disable
22355 		 * read-side synchronous streams interface
22356 		 * and drain any queued data.  It is okay
22357 		 * to do this for non-synchronous streams
22358 		 * fused tcp as well.
22359 		 */
22360 		tcp_fuse_disable_pair(tcp, B_FALSE);
22361 	}
22362 	tcp->tcp_issocket = B_FALSE;
22363 	tcp->tcp_sodirect = NULL;
22364 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
22365 }
22366 
22367 /*
22368  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
22369  * messages.
22370  */
22371 /* ARGSUSED */
22372 static void
22373 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
22374 {
22375 	conn_t 	*connp = (conn_t *)arg;
22376 	tcp_t	*tcp = connp->conn_tcp;
22377 	queue_t	*q = tcp->tcp_wq;
22378 	struct iocblk	*iocp;
22379 
22380 	ASSERT(DB_TYPE(mp) == M_IOCTL);
22381 	/*
22382 	 * Try and ASSERT the minimum possible references on the
22383 	 * conn early enough. Since we are executing on write side,
22384 	 * the connection is obviously not detached and that means
22385 	 * there is a ref each for TCP and IP. Since we are behind
22386 	 * the squeue, the minimum references needed are 3. If the
22387 	 * conn is in classifier hash list, there should be an
22388 	 * extra ref for that (we check both the possibilities).
22389 	 */
22390 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22391 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22392 
22393 	iocp = (struct iocblk *)mp->b_rptr;
22394 	switch (iocp->ioc_cmd) {
22395 	case TCP_IOC_DEFAULT_Q:
22396 		/* Wants to be the default wq. */
22397 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
22398 			iocp->ioc_error = EPERM;
22399 			iocp->ioc_count = 0;
22400 			mp->b_datap->db_type = M_IOCACK;
22401 			qreply(q, mp);
22402 			return;
22403 		}
22404 		tcp_def_q_set(tcp, mp);
22405 		return;
22406 	case _SIOCSOCKFALLBACK:
22407 		/*
22408 		 * Either sockmod is about to be popped and the socket
22409 		 * would now be treated as a plain stream, or a module
22410 		 * is about to be pushed so we could no longer use read-
22411 		 * side synchronous streams for fused loopback tcp.
22412 		 * Drain any queued data and disable direct sockfs
22413 		 * interface from now on.
22414 		 */
22415 		if (!tcp->tcp_issocket) {
22416 			DB_TYPE(mp) = M_IOCNAK;
22417 			iocp->ioc_error = EINVAL;
22418 		} else {
22419 			tcp_disable_direct_sockfs(tcp);
22420 			DB_TYPE(mp) = M_IOCACK;
22421 			iocp->ioc_error = 0;
22422 		}
22423 		iocp->ioc_count = 0;
22424 		iocp->ioc_rval = 0;
22425 		qreply(q, mp);
22426 		return;
22427 	}
22428 	CALL_IP_WPUT(connp, q, mp);
22429 }
22430 
22431 /*
22432  * This routine is called by tcp_wput() to handle all TPI requests.
22433  */
22434 /* ARGSUSED */
22435 static void
22436 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22437 {
22438 	conn_t 	*connp = (conn_t *)arg;
22439 	tcp_t	*tcp = connp->conn_tcp;
22440 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22441 	uchar_t *rptr;
22442 	t_scalar_t type;
22443 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
22444 
22445 	/*
22446 	 * Try and ASSERT the minimum possible references on the
22447 	 * conn early enough. Since we are executing on write side,
22448 	 * the connection is obviously not detached and that means
22449 	 * there is a ref each for TCP and IP. Since we are behind
22450 	 * the squeue, the minimum references needed are 3. If the
22451 	 * conn is in classifier hash list, there should be an
22452 	 * extra ref for that (we check both the possibilities).
22453 	 */
22454 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22455 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22456 
22457 	rptr = mp->b_rptr;
22458 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22459 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22460 		type = ((union T_primitives *)rptr)->type;
22461 		if (type == T_EXDATA_REQ) {
22462 			tcp_output_urgent(connp, mp->b_cont, arg2);
22463 			freeb(mp);
22464 		} else if (type != T_DATA_REQ) {
22465 			goto non_urgent_data;
22466 		} else {
22467 			/* TODO: options, flags, ... from user */
22468 			/* Set length to zero for reclamation below */
22469 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22470 			freeb(mp);
22471 		}
22472 		return;
22473 	} else {
22474 		if (tcp->tcp_debug) {
22475 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22476 			    "tcp_wput_proto, dropping one...");
22477 		}
22478 		freemsg(mp);
22479 		return;
22480 	}
22481 
22482 non_urgent_data:
22483 
22484 	switch ((int)tprim->type) {
22485 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22486 		/*
22487 		 * save the kssl_ent_t from the next block, and convert this
22488 		 * back to a normal bind_req.
22489 		 */
22490 		if (mp->b_cont != NULL) {
22491 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22492 
22493 			if (tcp->tcp_kssl_ent != NULL) {
22494 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22495 				    KSSL_NO_PROXY);
22496 				tcp->tcp_kssl_ent = NULL;
22497 			}
22498 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22499 			    sizeof (kssl_ent_t));
22500 			kssl_hold_ent(tcp->tcp_kssl_ent);
22501 			freemsg(mp->b_cont);
22502 			mp->b_cont = NULL;
22503 		}
22504 		tprim->type = T_BIND_REQ;
22505 
22506 	/* FALLTHROUGH */
22507 	case O_T_BIND_REQ:	/* bind request */
22508 	case T_BIND_REQ:	/* new semantics bind request */
22509 		tcp_tpi_bind(tcp, mp);
22510 		break;
22511 	case T_UNBIND_REQ:	/* unbind request */
22512 		tcp_tpi_unbind(tcp, mp);
22513 		break;
22514 	case O_T_CONN_RES:	/* old connection response XXX */
22515 	case T_CONN_RES:	/* connection response */
22516 		tcp_tli_accept(tcp, mp);
22517 		break;
22518 	case T_CONN_REQ:	/* connection request */
22519 		tcp_tpi_connect(tcp, mp);
22520 		break;
22521 	case T_DISCON_REQ:	/* disconnect request */
22522 		tcp_disconnect(tcp, mp);
22523 		break;
22524 	case T_CAPABILITY_REQ:
22525 		tcp_capability_req(tcp, mp);	/* capability request */
22526 		break;
22527 	case T_INFO_REQ:	/* information request */
22528 		tcp_info_req(tcp, mp);
22529 		break;
22530 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22531 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr,
22532 		    &tcp_opt_obj, B_TRUE);
22533 		break;
22534 	case T_OPTMGMT_REQ:
22535 		/*
22536 		 * Note:  no support for snmpcom_req() through new
22537 		 * T_OPTMGMT_REQ. See comments in ip.c
22538 		 */
22539 		/* Only IP is allowed to return meaningful value */
22540 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22541 		    B_TRUE);
22542 		break;
22543 
22544 	case T_UNITDATA_REQ:	/* unitdata request */
22545 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22546 		break;
22547 	case T_ORDREL_REQ:	/* orderly release req */
22548 		freemsg(mp);
22549 
22550 		if (tcp->tcp_fused)
22551 			tcp_unfuse(tcp);
22552 
22553 		if (tcp_xmit_end(tcp) != 0) {
22554 			/*
22555 			 * We were crossing FINs and got a reset from
22556 			 * the other side. Just ignore it.
22557 			 */
22558 			if (tcp->tcp_debug) {
22559 				(void) strlog(TCP_MOD_ID, 0, 1,
22560 				    SL_ERROR|SL_TRACE,
22561 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22562 				    "state %s",
22563 				    tcp_display(tcp, NULL,
22564 				    DISP_ADDR_AND_PORT));
22565 			}
22566 		}
22567 		break;
22568 	case T_ADDR_REQ:
22569 		tcp_addr_req(tcp, mp);
22570 		break;
22571 	default:
22572 		if (tcp->tcp_debug) {
22573 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22574 			    "tcp_wput_proto, bogus TPI msg, type %d",
22575 			    tprim->type);
22576 		}
22577 		/*
22578 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22579 		 * to recover.
22580 		 */
22581 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22582 		break;
22583 	}
22584 }
22585 
22586 /*
22587  * The TCP write service routine should never be called...
22588  */
22589 /* ARGSUSED */
22590 static void
22591 tcp_wsrv(queue_t *q)
22592 {
22593 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22594 
22595 	TCP_STAT(tcps, tcp_wsrv_called);
22596 }
22597 
22598 /* Non overlapping byte exchanger */
22599 static void
22600 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22601 {
22602 	uchar_t	uch;
22603 
22604 	while (len-- > 0) {
22605 		uch = a[len];
22606 		a[len] = b[len];
22607 		b[len] = uch;
22608 	}
22609 }
22610 
22611 /*
22612  * Send out a control packet on the tcp connection specified.  This routine
22613  * is typically called where we need a simple ACK or RST generated.
22614  */
22615 static void
22616 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22617 {
22618 	uchar_t		*rptr;
22619 	tcph_t		*tcph;
22620 	ipha_t		*ipha = NULL;
22621 	ip6_t		*ip6h = NULL;
22622 	uint32_t	sum;
22623 	int		tcp_hdr_len;
22624 	int		tcp_ip_hdr_len;
22625 	mblk_t		*mp;
22626 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22627 
22628 	/*
22629 	 * Save sum for use in source route later.
22630 	 */
22631 	ASSERT(tcp != NULL);
22632 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22633 	tcp_hdr_len = tcp->tcp_hdr_len;
22634 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22635 
22636 	/* If a text string is passed in with the request, pass it to strlog. */
22637 	if (str != NULL && tcp->tcp_debug) {
22638 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22639 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22640 		    str, seq, ack, ctl);
22641 	}
22642 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22643 	    BPRI_MED);
22644 	if (mp == NULL) {
22645 		return;
22646 	}
22647 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22648 	mp->b_rptr = rptr;
22649 	mp->b_wptr = &rptr[tcp_hdr_len];
22650 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22651 
22652 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22653 		ipha = (ipha_t *)rptr;
22654 		ipha->ipha_length = htons(tcp_hdr_len);
22655 	} else {
22656 		ip6h = (ip6_t *)rptr;
22657 		ASSERT(tcp != NULL);
22658 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22659 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22660 	}
22661 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22662 	tcph->th_flags[0] = (uint8_t)ctl;
22663 	if (ctl & TH_RST) {
22664 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22665 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22666 		/*
22667 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22668 		 */
22669 		if (tcp->tcp_snd_ts_ok &&
22670 		    tcp->tcp_state > TCPS_SYN_SENT) {
22671 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22672 			*(mp->b_wptr) = TCPOPT_EOL;
22673 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22674 				ipha->ipha_length = htons(tcp_hdr_len -
22675 				    TCPOPT_REAL_TS_LEN);
22676 			} else {
22677 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22678 				    TCPOPT_REAL_TS_LEN);
22679 			}
22680 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22681 			sum -= TCPOPT_REAL_TS_LEN;
22682 		}
22683 	}
22684 	if (ctl & TH_ACK) {
22685 		if (tcp->tcp_snd_ts_ok) {
22686 			U32_TO_BE32(lbolt,
22687 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22688 			U32_TO_BE32(tcp->tcp_ts_recent,
22689 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22690 		}
22691 
22692 		/* Update the latest receive window size in TCP header. */
22693 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22694 		    tcph->th_win);
22695 		tcp->tcp_rack = ack;
22696 		tcp->tcp_rack_cnt = 0;
22697 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22698 	}
22699 	BUMP_LOCAL(tcp->tcp_obsegs);
22700 	U32_TO_BE32(seq, tcph->th_seq);
22701 	U32_TO_BE32(ack, tcph->th_ack);
22702 	/*
22703 	 * Include the adjustment for a source route if any.
22704 	 */
22705 	sum = (sum >> 16) + (sum & 0xFFFF);
22706 	U16_TO_BE16(sum, tcph->th_sum);
22707 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22708 }
22709 
22710 /*
22711  * If this routine returns B_TRUE, TCP can generate a RST in response
22712  * to a segment.  If it returns B_FALSE, TCP should not respond.
22713  */
22714 static boolean_t
22715 tcp_send_rst_chk(tcp_stack_t *tcps)
22716 {
22717 	clock_t	now;
22718 
22719 	/*
22720 	 * TCP needs to protect itself from generating too many RSTs.
22721 	 * This can be a DoS attack by sending us random segments
22722 	 * soliciting RSTs.
22723 	 *
22724 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22725 	 * in each 1 second interval.  In this way, TCP still generate
22726 	 * RSTs in normal cases but when under attack, the impact is
22727 	 * limited.
22728 	 */
22729 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22730 		now = lbolt;
22731 		/* lbolt can wrap around. */
22732 		if ((tcps->tcps_last_rst_intrvl > now) ||
22733 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22734 		    1*SECONDS)) {
22735 			tcps->tcps_last_rst_intrvl = now;
22736 			tcps->tcps_rst_cnt = 1;
22737 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22738 			return (B_FALSE);
22739 		}
22740 	}
22741 	return (B_TRUE);
22742 }
22743 
22744 /*
22745  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22746  */
22747 static void
22748 tcp_ip_ire_mark_advice(tcp_t *tcp)
22749 {
22750 	mblk_t *mp;
22751 	ipic_t *ipic;
22752 
22753 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22754 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22755 		    &ipic);
22756 	} else {
22757 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22758 		    &ipic);
22759 	}
22760 	if (mp == NULL)
22761 		return;
22762 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22763 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22764 }
22765 
22766 /*
22767  * Return an IP advice ioctl mblk and set ipic to be the pointer
22768  * to the advice structure.
22769  */
22770 static mblk_t *
22771 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22772 {
22773 	struct iocblk *ioc;
22774 	mblk_t *mp, *mp1;
22775 
22776 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22777 	if (mp == NULL)
22778 		return (NULL);
22779 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22780 	*ipic = (ipic_t *)mp->b_rptr;
22781 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22782 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22783 
22784 	bcopy(addr, *ipic + 1, addr_len);
22785 
22786 	(*ipic)->ipic_addr_length = addr_len;
22787 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22788 
22789 	mp1 = mkiocb(IP_IOCTL);
22790 	if (mp1 == NULL) {
22791 		freemsg(mp);
22792 		return (NULL);
22793 	}
22794 	mp1->b_cont = mp;
22795 	ioc = (struct iocblk *)mp1->b_rptr;
22796 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22797 
22798 	return (mp1);
22799 }
22800 
22801 /*
22802  * Generate a reset based on an inbound packet, connp is set by caller
22803  * when RST is in response to an unexpected inbound packet for which
22804  * there is active tcp state in the system.
22805  *
22806  * IPSEC NOTE : Try to send the reply with the same protection as it came
22807  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22808  * the packet will go out at the same level of protection as it came in by
22809  * converting the IPSEC_IN to IPSEC_OUT.
22810  */
22811 static void
22812 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22813     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22814     tcp_stack_t *tcps, conn_t *connp)
22815 {
22816 	ipha_t		*ipha = NULL;
22817 	ip6_t		*ip6h = NULL;
22818 	ushort_t	len;
22819 	tcph_t		*tcph;
22820 	int		i;
22821 	mblk_t		*ipsec_mp;
22822 	boolean_t	mctl_present;
22823 	ipic_t		*ipic;
22824 	ipaddr_t	v4addr;
22825 	in6_addr_t	v6addr;
22826 	int		addr_len;
22827 	void		*addr;
22828 	queue_t		*q = tcps->tcps_g_q;
22829 	tcp_t		*tcp;
22830 	cred_t		*cr;
22831 	mblk_t		*nmp;
22832 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22833 
22834 	if (tcps->tcps_g_q == NULL) {
22835 		/*
22836 		 * For non-zero stackids the default queue isn't created
22837 		 * until the first open, thus there can be a need to send
22838 		 * a reset before then. But we can't do that, hence we just
22839 		 * drop the packet. Later during boot, when the default queue
22840 		 * has been setup, a retransmitted packet from the peer
22841 		 * will result in a reset.
22842 		 */
22843 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22844 		    GLOBAL_NETSTACKID);
22845 		freemsg(mp);
22846 		return;
22847 	}
22848 
22849 	if (connp != NULL)
22850 		tcp = connp->conn_tcp;
22851 	else
22852 		tcp = Q_TO_TCP(q);
22853 
22854 	if (!tcp_send_rst_chk(tcps)) {
22855 		tcps->tcps_rst_unsent++;
22856 		freemsg(mp);
22857 		return;
22858 	}
22859 
22860 	if (mp->b_datap->db_type == M_CTL) {
22861 		ipsec_mp = mp;
22862 		mp = mp->b_cont;
22863 		mctl_present = B_TRUE;
22864 	} else {
22865 		ipsec_mp = mp;
22866 		mctl_present = B_FALSE;
22867 	}
22868 
22869 	if (str && q && tcps->tcps_dbg) {
22870 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22871 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22872 		    "flags 0x%x",
22873 		    str, seq, ack, ctl);
22874 	}
22875 	if (mp->b_datap->db_ref != 1) {
22876 		mblk_t *mp1 = copyb(mp);
22877 		freemsg(mp);
22878 		mp = mp1;
22879 		if (!mp) {
22880 			if (mctl_present)
22881 				freeb(ipsec_mp);
22882 			return;
22883 		} else {
22884 			if (mctl_present) {
22885 				ipsec_mp->b_cont = mp;
22886 			} else {
22887 				ipsec_mp = mp;
22888 			}
22889 		}
22890 	} else if (mp->b_cont) {
22891 		freemsg(mp->b_cont);
22892 		mp->b_cont = NULL;
22893 	}
22894 	/*
22895 	 * We skip reversing source route here.
22896 	 * (for now we replace all IP options with EOL)
22897 	 */
22898 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22899 		ipha = (ipha_t *)mp->b_rptr;
22900 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22901 			mp->b_rptr[i] = IPOPT_EOL;
22902 		/*
22903 		 * Make sure that src address isn't flagrantly invalid.
22904 		 * Not all broadcast address checking for the src address
22905 		 * is possible, since we don't know the netmask of the src
22906 		 * addr.  No check for destination address is done, since
22907 		 * IP will not pass up a packet with a broadcast dest
22908 		 * address to TCP.  Similar checks are done below for IPv6.
22909 		 */
22910 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22911 		    CLASSD(ipha->ipha_src)) {
22912 			freemsg(ipsec_mp);
22913 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22914 			return;
22915 		}
22916 	} else {
22917 		ip6h = (ip6_t *)mp->b_rptr;
22918 
22919 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22920 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22921 			freemsg(ipsec_mp);
22922 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22923 			return;
22924 		}
22925 
22926 		/* Remove any extension headers assuming partial overlay */
22927 		if (ip_hdr_len > IPV6_HDR_LEN) {
22928 			uint8_t *to;
22929 
22930 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22931 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22932 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22933 			ip_hdr_len = IPV6_HDR_LEN;
22934 			ip6h = (ip6_t *)mp->b_rptr;
22935 			ip6h->ip6_nxt = IPPROTO_TCP;
22936 		}
22937 	}
22938 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22939 	if (tcph->th_flags[0] & TH_RST) {
22940 		freemsg(ipsec_mp);
22941 		return;
22942 	}
22943 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22944 	len = ip_hdr_len + sizeof (tcph_t);
22945 	mp->b_wptr = &mp->b_rptr[len];
22946 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22947 		ipha->ipha_length = htons(len);
22948 		/* Swap addresses */
22949 		v4addr = ipha->ipha_src;
22950 		ipha->ipha_src = ipha->ipha_dst;
22951 		ipha->ipha_dst = v4addr;
22952 		ipha->ipha_ident = 0;
22953 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22954 		addr_len = IP_ADDR_LEN;
22955 		addr = &v4addr;
22956 	} else {
22957 		/* No ip6i_t in this case */
22958 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22959 		/* Swap addresses */
22960 		v6addr = ip6h->ip6_src;
22961 		ip6h->ip6_src = ip6h->ip6_dst;
22962 		ip6h->ip6_dst = v6addr;
22963 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22964 		addr_len = IPV6_ADDR_LEN;
22965 		addr = &v6addr;
22966 	}
22967 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22968 	U32_TO_BE32(ack, tcph->th_ack);
22969 	U32_TO_BE32(seq, tcph->th_seq);
22970 	U16_TO_BE16(0, tcph->th_win);
22971 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22972 	tcph->th_flags[0] = (uint8_t)ctl;
22973 	if (ctl & TH_RST) {
22974 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22975 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22976 	}
22977 
22978 	/* IP trusts us to set up labels when required. */
22979 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
22980 	    crgetlabel(cr) != NULL) {
22981 		int err;
22982 
22983 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22984 			err = tsol_check_label(cr, &mp,
22985 			    tcp->tcp_connp->conn_mac_exempt,
22986 			    tcps->tcps_netstack->netstack_ip);
22987 		else
22988 			err = tsol_check_label_v6(cr, &mp,
22989 			    tcp->tcp_connp->conn_mac_exempt,
22990 			    tcps->tcps_netstack->netstack_ip);
22991 		if (mctl_present)
22992 			ipsec_mp->b_cont = mp;
22993 		else
22994 			ipsec_mp = mp;
22995 		if (err != 0) {
22996 			freemsg(ipsec_mp);
22997 			return;
22998 		}
22999 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23000 			ipha = (ipha_t *)mp->b_rptr;
23001 		} else {
23002 			ip6h = (ip6_t *)mp->b_rptr;
23003 		}
23004 	}
23005 
23006 	if (mctl_present) {
23007 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23008 
23009 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23010 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
23011 			return;
23012 		}
23013 	}
23014 	if (zoneid == ALL_ZONES)
23015 		zoneid = GLOBAL_ZONEID;
23016 
23017 	/* Add the zoneid so ip_output routes it properly */
23018 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
23019 		freemsg(ipsec_mp);
23020 		return;
23021 	}
23022 	ipsec_mp = nmp;
23023 
23024 	/*
23025 	 * NOTE:  one might consider tracing a TCP packet here, but
23026 	 * this function has no active TCP state and no tcp structure
23027 	 * that has a trace buffer.  If we traced here, we would have
23028 	 * to keep a local trace buffer in tcp_record_trace().
23029 	 *
23030 	 * TSol note: The mblk that contains the incoming packet was
23031 	 * reused by tcp_xmit_listener_reset, so it already contains
23032 	 * the right credentials and we don't need to call mblk_setcred.
23033 	 * Also the conn's cred is not right since it is associated
23034 	 * with tcps_g_q.
23035 	 */
23036 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
23037 
23038 	/*
23039 	 * Tell IP to mark the IRE used for this destination temporary.
23040 	 * This way, we can limit our exposure to DoS attack because IP
23041 	 * creates an IRE for each destination.  If there are too many,
23042 	 * the time to do any routing lookup will be extremely long.  And
23043 	 * the lookup can be in interrupt context.
23044 	 *
23045 	 * Note that in normal circumstances, this marking should not
23046 	 * affect anything.  It would be nice if only 1 message is
23047 	 * needed to inform IP that the IRE created for this RST should
23048 	 * not be added to the cache table.  But there is currently
23049 	 * not such communication mechanism between TCP and IP.  So
23050 	 * the best we can do now is to send the advice ioctl to IP
23051 	 * to mark the IRE temporary.
23052 	 */
23053 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
23054 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
23055 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23056 	}
23057 }
23058 
23059 /*
23060  * Initiate closedown sequence on an active connection.  (May be called as
23061  * writer.)  Return value zero for OK return, non-zero for error return.
23062  */
23063 static int
23064 tcp_xmit_end(tcp_t *tcp)
23065 {
23066 	ipic_t	*ipic;
23067 	mblk_t	*mp;
23068 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23069 
23070 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
23071 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
23072 		/*
23073 		 * Invalid state, only states TCPS_SYN_RCVD,
23074 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
23075 		 */
23076 		return (-1);
23077 	}
23078 
23079 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
23080 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
23081 	/*
23082 	 * If there is nothing more unsent, send the FIN now.
23083 	 * Otherwise, it will go out with the last segment.
23084 	 */
23085 	if (tcp->tcp_unsent == 0) {
23086 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
23087 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
23088 
23089 		if (mp) {
23090 			tcp_send_data(tcp, tcp->tcp_wq, mp);
23091 		} else {
23092 			/*
23093 			 * Couldn't allocate msg.  Pretend we got it out.
23094 			 * Wait for rexmit timeout.
23095 			 */
23096 			tcp->tcp_snxt = tcp->tcp_fss + 1;
23097 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23098 		}
23099 
23100 		/*
23101 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
23102 		 * changed.
23103 		 */
23104 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
23105 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23106 		}
23107 	} else {
23108 		/*
23109 		 * If tcp->tcp_cork is set, then the data will not get sent,
23110 		 * so we have to check that and unset it first.
23111 		 */
23112 		if (tcp->tcp_cork)
23113 			tcp->tcp_cork = B_FALSE;
23114 		tcp_wput_data(tcp, NULL, B_FALSE);
23115 	}
23116 
23117 	/*
23118 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
23119 	 * is 0, don't update the cache.
23120 	 */
23121 	if (tcps->tcps_rtt_updates == 0 ||
23122 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
23123 		return (0);
23124 
23125 	/*
23126 	 * NOTE: should not update if source routes i.e. if tcp_remote if
23127 	 * different from the destination.
23128 	 */
23129 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23130 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
23131 			return (0);
23132 		}
23133 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
23134 		    &ipic);
23135 	} else {
23136 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
23137 		    &tcp->tcp_ip6h->ip6_dst))) {
23138 			return (0);
23139 		}
23140 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
23141 		    &ipic);
23142 	}
23143 
23144 	/* Record route attributes in the IRE for use by future connections. */
23145 	if (mp == NULL)
23146 		return (0);
23147 
23148 	/*
23149 	 * We do not have a good algorithm to update ssthresh at this time.
23150 	 * So don't do any update.
23151 	 */
23152 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
23153 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
23154 
23155 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23156 
23157 	return (0);
23158 }
23159 
23160 /*
23161  * Generate a "no listener here" RST in response to an "unknown" segment.
23162  * connp is set by caller when RST is in response to an unexpected
23163  * inbound packet for which there is active tcp state in the system.
23164  * Note that we are reusing the incoming mp to construct the outgoing RST.
23165  */
23166 void
23167 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
23168     tcp_stack_t *tcps, conn_t *connp)
23169 {
23170 	uchar_t		*rptr;
23171 	uint32_t	seg_len;
23172 	tcph_t		*tcph;
23173 	uint32_t	seg_seq;
23174 	uint32_t	seg_ack;
23175 	uint_t		flags;
23176 	mblk_t		*ipsec_mp;
23177 	ipha_t 		*ipha;
23178 	ip6_t 		*ip6h;
23179 	boolean_t	mctl_present = B_FALSE;
23180 	boolean_t	check = B_TRUE;
23181 	boolean_t	policy_present;
23182 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
23183 
23184 	TCP_STAT(tcps, tcp_no_listener);
23185 
23186 	ipsec_mp = mp;
23187 
23188 	if (mp->b_datap->db_type == M_CTL) {
23189 		ipsec_in_t *ii;
23190 
23191 		mctl_present = B_TRUE;
23192 		mp = mp->b_cont;
23193 
23194 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23195 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23196 		if (ii->ipsec_in_dont_check) {
23197 			check = B_FALSE;
23198 			if (!ii->ipsec_in_secure) {
23199 				freeb(ipsec_mp);
23200 				mctl_present = B_FALSE;
23201 				ipsec_mp = mp;
23202 			}
23203 		}
23204 	}
23205 
23206 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23207 		policy_present = ipss->ipsec_inbound_v4_policy_present;
23208 		ipha = (ipha_t *)mp->b_rptr;
23209 		ip6h = NULL;
23210 	} else {
23211 		policy_present = ipss->ipsec_inbound_v6_policy_present;
23212 		ipha = NULL;
23213 		ip6h = (ip6_t *)mp->b_rptr;
23214 	}
23215 
23216 	if (check && policy_present) {
23217 		/*
23218 		 * The conn_t parameter is NULL because we already know
23219 		 * nobody's home.
23220 		 */
23221 		ipsec_mp = ipsec_check_global_policy(
23222 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
23223 		    tcps->tcps_netstack);
23224 		if (ipsec_mp == NULL)
23225 			return;
23226 	}
23227 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
23228 		DTRACE_PROBE2(
23229 		    tx__ip__log__error__nolistener__tcp,
23230 		    char *, "Could not reply with RST to mp(1)",
23231 		    mblk_t *, mp);
23232 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
23233 		freemsg(ipsec_mp);
23234 		return;
23235 	}
23236 
23237 	rptr = mp->b_rptr;
23238 
23239 	tcph = (tcph_t *)&rptr[ip_hdr_len];
23240 	seg_seq = BE32_TO_U32(tcph->th_seq);
23241 	seg_ack = BE32_TO_U32(tcph->th_ack);
23242 	flags = tcph->th_flags[0];
23243 
23244 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
23245 	if (flags & TH_RST) {
23246 		freemsg(ipsec_mp);
23247 	} else if (flags & TH_ACK) {
23248 		tcp_xmit_early_reset("no tcp, reset",
23249 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
23250 		    connp);
23251 	} else {
23252 		if (flags & TH_SYN) {
23253 			seg_len++;
23254 		} else {
23255 			/*
23256 			 * Here we violate the RFC.  Note that a normal
23257 			 * TCP will never send a segment without the ACK
23258 			 * flag, except for RST or SYN segment.  This
23259 			 * segment is neither.  Just drop it on the
23260 			 * floor.
23261 			 */
23262 			freemsg(ipsec_mp);
23263 			tcps->tcps_rst_unsent++;
23264 			return;
23265 		}
23266 
23267 		tcp_xmit_early_reset("no tcp, reset/ack",
23268 		    ipsec_mp, 0, seg_seq + seg_len,
23269 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
23270 	}
23271 }
23272 
23273 /*
23274  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
23275  * ip and tcp header ready to pass down to IP.  If the mp passed in is
23276  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
23277  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
23278  * otherwise it will dup partial mblks.)
23279  * Otherwise, an appropriate ACK packet will be generated.  This
23280  * routine is not usually called to send new data for the first time.  It
23281  * is mostly called out of the timer for retransmits, and to generate ACKs.
23282  *
23283  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
23284  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
23285  * of the original mblk chain will be returned in *offset and *end_mp.
23286  */
23287 mblk_t *
23288 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
23289     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
23290     boolean_t rexmit)
23291 {
23292 	int	data_length;
23293 	int32_t	off = 0;
23294 	uint_t	flags;
23295 	mblk_t	*mp1;
23296 	mblk_t	*mp2;
23297 	uchar_t	*rptr;
23298 	tcph_t	*tcph;
23299 	int32_t	num_sack_blk = 0;
23300 	int32_t	sack_opt_len = 0;
23301 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23302 
23303 	/* Allocate for our maximum TCP header + link-level */
23304 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
23305 	    tcps->tcps_wroff_xtra, BPRI_MED);
23306 	if (!mp1)
23307 		return (NULL);
23308 	data_length = 0;
23309 
23310 	/*
23311 	 * Note that tcp_mss has been adjusted to take into account the
23312 	 * timestamp option if applicable.  Because SACK options do not
23313 	 * appear in every TCP segments and they are of variable lengths,
23314 	 * they cannot be included in tcp_mss.  Thus we need to calculate
23315 	 * the actual segment length when we need to send a segment which
23316 	 * includes SACK options.
23317 	 */
23318 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23319 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23320 		    tcp->tcp_num_sack_blk);
23321 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23322 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23323 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
23324 			max_to_send -= sack_opt_len;
23325 	}
23326 
23327 	if (offset != NULL) {
23328 		off = *offset;
23329 		/* We use offset as an indicator that end_mp is not NULL. */
23330 		*end_mp = NULL;
23331 	}
23332 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
23333 		/* This could be faster with cooperation from downstream */
23334 		if (mp2 != mp1 && !sendall &&
23335 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
23336 		    max_to_send)
23337 			/*
23338 			 * Don't send the next mblk since the whole mblk
23339 			 * does not fit.
23340 			 */
23341 			break;
23342 		mp2->b_cont = dupb(mp);
23343 		mp2 = mp2->b_cont;
23344 		if (!mp2) {
23345 			freemsg(mp1);
23346 			return (NULL);
23347 		}
23348 		mp2->b_rptr += off;
23349 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
23350 		    (uintptr_t)INT_MAX);
23351 
23352 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
23353 		if (data_length > max_to_send) {
23354 			mp2->b_wptr -= data_length - max_to_send;
23355 			data_length = max_to_send;
23356 			off = mp2->b_wptr - mp->b_rptr;
23357 			break;
23358 		} else {
23359 			off = 0;
23360 		}
23361 	}
23362 	if (offset != NULL) {
23363 		*offset = off;
23364 		*end_mp = mp;
23365 	}
23366 	if (seg_len != NULL) {
23367 		*seg_len = data_length;
23368 	}
23369 
23370 	/* Update the latest receive window size in TCP header. */
23371 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23372 	    tcp->tcp_tcph->th_win);
23373 
23374 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23375 	mp1->b_rptr = rptr;
23376 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
23377 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23378 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23379 	U32_TO_ABE32(seq, tcph->th_seq);
23380 
23381 	/*
23382 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
23383 	 * that this function was called from tcp_wput_data. Thus, when called
23384 	 * to retransmit data the setting of the PUSH bit may appear some
23385 	 * what random in that it might get set when it should not. This
23386 	 * should not pose any performance issues.
23387 	 */
23388 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
23389 	    tcp->tcp_unsent == data_length)) {
23390 		flags = TH_ACK | TH_PUSH;
23391 	} else {
23392 		flags = TH_ACK;
23393 	}
23394 
23395 	if (tcp->tcp_ecn_ok) {
23396 		if (tcp->tcp_ecn_echo_on)
23397 			flags |= TH_ECE;
23398 
23399 		/*
23400 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
23401 		 * There is no TCP flow control for non-data segments, and
23402 		 * only data segment is transmitted reliably.
23403 		 */
23404 		if (data_length > 0 && !rexmit) {
23405 			SET_ECT(tcp, rptr);
23406 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23407 				flags |= TH_CWR;
23408 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23409 			}
23410 		}
23411 	}
23412 
23413 	if (tcp->tcp_valid_bits) {
23414 		uint32_t u1;
23415 
23416 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23417 		    seq == tcp->tcp_iss) {
23418 			uchar_t	*wptr;
23419 
23420 			/*
23421 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23422 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23423 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23424 			 * our SYN is not ack'ed but the app closes this
23425 			 * TCP connection.
23426 			 */
23427 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23428 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23429 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23430 
23431 			/*
23432 			 * Tack on the MSS option.  It is always needed
23433 			 * for both active and passive open.
23434 			 *
23435 			 * MSS option value should be interface MTU - MIN
23436 			 * TCP/IP header according to RFC 793 as it means
23437 			 * the maximum segment size TCP can receive.  But
23438 			 * to get around some broken middle boxes/end hosts
23439 			 * out there, we allow the option value to be the
23440 			 * same as the MSS option size on the peer side.
23441 			 * In this way, the other side will not send
23442 			 * anything larger than they can receive.
23443 			 *
23444 			 * Note that for SYN_SENT state, the ndd param
23445 			 * tcp_use_smss_as_mss_opt has no effect as we
23446 			 * don't know the peer's MSS option value. So
23447 			 * the only case we need to take care of is in
23448 			 * SYN_RCVD state, which is done later.
23449 			 */
23450 			wptr = mp1->b_wptr;
23451 			wptr[0] = TCPOPT_MAXSEG;
23452 			wptr[1] = TCPOPT_MAXSEG_LEN;
23453 			wptr += 2;
23454 			u1 = tcp->tcp_if_mtu -
23455 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23456 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23457 			    TCP_MIN_HEADER_LENGTH;
23458 			U16_TO_BE16(u1, wptr);
23459 			mp1->b_wptr = wptr + 2;
23460 			/* Update the offset to cover the additional word */
23461 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23462 
23463 			/*
23464 			 * Note that the following way of filling in
23465 			 * TCP options are not optimal.  Some NOPs can
23466 			 * be saved.  But there is no need at this time
23467 			 * to optimize it.  When it is needed, we will
23468 			 * do it.
23469 			 */
23470 			switch (tcp->tcp_state) {
23471 			case TCPS_SYN_SENT:
23472 				flags = TH_SYN;
23473 
23474 				if (tcp->tcp_snd_ts_ok) {
23475 					uint32_t llbolt = (uint32_t)lbolt;
23476 
23477 					wptr = mp1->b_wptr;
23478 					wptr[0] = TCPOPT_NOP;
23479 					wptr[1] = TCPOPT_NOP;
23480 					wptr[2] = TCPOPT_TSTAMP;
23481 					wptr[3] = TCPOPT_TSTAMP_LEN;
23482 					wptr += 4;
23483 					U32_TO_BE32(llbolt, wptr);
23484 					wptr += 4;
23485 					ASSERT(tcp->tcp_ts_recent == 0);
23486 					U32_TO_BE32(0L, wptr);
23487 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23488 					tcph->th_offset_and_rsrvd[0] +=
23489 					    (3 << 4);
23490 				}
23491 
23492 				/*
23493 				 * Set up all the bits to tell other side
23494 				 * we are ECN capable.
23495 				 */
23496 				if (tcp->tcp_ecn_ok) {
23497 					flags |= (TH_ECE | TH_CWR);
23498 				}
23499 				break;
23500 			case TCPS_SYN_RCVD:
23501 				flags |= TH_SYN;
23502 
23503 				/*
23504 				 * Reset the MSS option value to be SMSS
23505 				 * We should probably add back the bytes
23506 				 * for timestamp option and IPsec.  We
23507 				 * don't do that as this is a workaround
23508 				 * for broken middle boxes/end hosts, it
23509 				 * is better for us to be more cautious.
23510 				 * They may not take these things into
23511 				 * account in their SMSS calculation.  Thus
23512 				 * the peer's calculated SMSS may be smaller
23513 				 * than what it can be.  This should be OK.
23514 				 */
23515 				if (tcps->tcps_use_smss_as_mss_opt) {
23516 					u1 = tcp->tcp_mss;
23517 					U16_TO_BE16(u1, wptr);
23518 				}
23519 
23520 				/*
23521 				 * If the other side is ECN capable, reply
23522 				 * that we are also ECN capable.
23523 				 */
23524 				if (tcp->tcp_ecn_ok)
23525 					flags |= TH_ECE;
23526 				break;
23527 			default:
23528 				/*
23529 				 * The above ASSERT() makes sure that this
23530 				 * must be FIN-WAIT-1 state.  Our SYN has
23531 				 * not been ack'ed so retransmit it.
23532 				 */
23533 				flags |= TH_SYN;
23534 				break;
23535 			}
23536 
23537 			if (tcp->tcp_snd_ws_ok) {
23538 				wptr = mp1->b_wptr;
23539 				wptr[0] =  TCPOPT_NOP;
23540 				wptr[1] =  TCPOPT_WSCALE;
23541 				wptr[2] =  TCPOPT_WS_LEN;
23542 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23543 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23544 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23545 			}
23546 
23547 			if (tcp->tcp_snd_sack_ok) {
23548 				wptr = mp1->b_wptr;
23549 				wptr[0] = TCPOPT_NOP;
23550 				wptr[1] = TCPOPT_NOP;
23551 				wptr[2] = TCPOPT_SACK_PERMITTED;
23552 				wptr[3] = TCPOPT_SACK_OK_LEN;
23553 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23554 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23555 			}
23556 
23557 			/* allocb() of adequate mblk assures space */
23558 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23559 			    (uintptr_t)INT_MAX);
23560 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23561 			/*
23562 			 * Get IP set to checksum on our behalf
23563 			 * Include the adjustment for a source route if any.
23564 			 */
23565 			u1 += tcp->tcp_sum;
23566 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23567 			U16_TO_BE16(u1, tcph->th_sum);
23568 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23569 		}
23570 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23571 		    (seq + data_length) == tcp->tcp_fss) {
23572 			if (!tcp->tcp_fin_acked) {
23573 				flags |= TH_FIN;
23574 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23575 			}
23576 			if (!tcp->tcp_fin_sent) {
23577 				tcp->tcp_fin_sent = B_TRUE;
23578 				switch (tcp->tcp_state) {
23579 				case TCPS_SYN_RCVD:
23580 				case TCPS_ESTABLISHED:
23581 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23582 					break;
23583 				case TCPS_CLOSE_WAIT:
23584 					tcp->tcp_state = TCPS_LAST_ACK;
23585 					break;
23586 				}
23587 				if (tcp->tcp_suna == tcp->tcp_snxt)
23588 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23589 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23590 			}
23591 		}
23592 		/*
23593 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23594 		 * is smaller than seq, u1 will become a very huge value.
23595 		 * So the comparison will fail.  Also note that tcp_urp
23596 		 * should be positive, see RFC 793 page 17.
23597 		 */
23598 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23599 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23600 		    u1 < (uint32_t)(64 * 1024)) {
23601 			flags |= TH_URG;
23602 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23603 			U32_TO_ABE16(u1, tcph->th_urp);
23604 		}
23605 	}
23606 	tcph->th_flags[0] = (uchar_t)flags;
23607 	tcp->tcp_rack = tcp->tcp_rnxt;
23608 	tcp->tcp_rack_cnt = 0;
23609 
23610 	if (tcp->tcp_snd_ts_ok) {
23611 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23612 			uint32_t llbolt = (uint32_t)lbolt;
23613 
23614 			U32_TO_BE32(llbolt,
23615 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23616 			U32_TO_BE32(tcp->tcp_ts_recent,
23617 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23618 		}
23619 	}
23620 
23621 	if (num_sack_blk > 0) {
23622 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23623 		sack_blk_t *tmp;
23624 		int32_t	i;
23625 
23626 		wptr[0] = TCPOPT_NOP;
23627 		wptr[1] = TCPOPT_NOP;
23628 		wptr[2] = TCPOPT_SACK;
23629 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23630 		    sizeof (sack_blk_t);
23631 		wptr += TCPOPT_REAL_SACK_LEN;
23632 
23633 		tmp = tcp->tcp_sack_list;
23634 		for (i = 0; i < num_sack_blk; i++) {
23635 			U32_TO_BE32(tmp[i].begin, wptr);
23636 			wptr += sizeof (tcp_seq);
23637 			U32_TO_BE32(tmp[i].end, wptr);
23638 			wptr += sizeof (tcp_seq);
23639 		}
23640 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23641 	}
23642 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23643 	data_length += (int)(mp1->b_wptr - rptr);
23644 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23645 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23646 	} else {
23647 		ip6_t *ip6 = (ip6_t *)(rptr +
23648 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23649 		    sizeof (ip6i_t) : 0));
23650 
23651 		ip6->ip6_plen = htons(data_length -
23652 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23653 	}
23654 
23655 	/*
23656 	 * Prime pump for IP
23657 	 * Include the adjustment for a source route if any.
23658 	 */
23659 	data_length -= tcp->tcp_ip_hdr_len;
23660 	data_length += tcp->tcp_sum;
23661 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23662 	U16_TO_ABE16(data_length, tcph->th_sum);
23663 	if (tcp->tcp_ip_forward_progress) {
23664 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23665 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23666 		tcp->tcp_ip_forward_progress = B_FALSE;
23667 	}
23668 	return (mp1);
23669 }
23670 
23671 /* This function handles the push timeout. */
23672 void
23673 tcp_push_timer(void *arg)
23674 {
23675 	conn_t	*connp = (conn_t *)arg;
23676 	tcp_t *tcp = connp->conn_tcp;
23677 	uint_t		flags;
23678 	sodirect_t	*sodp;
23679 
23680 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
23681 
23682 	ASSERT(tcp->tcp_listener == NULL);
23683 
23684 	ASSERT(!IPCL_IS_NONSTR(connp));
23685 
23686 	/*
23687 	 * We need to plug synchronous streams during our drain to prevent
23688 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23689 	 */
23690 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23691 	tcp->tcp_push_tid = 0;
23692 
23693 	SOD_PTR_ENTER(tcp, sodp);
23694 	if (sodp != NULL) {
23695 		flags = tcp_rcv_sod_wakeup(tcp, sodp);
23696 		/* sod_wakeup() does the mutex_exit() */
23697 	} else if (tcp->tcp_rcv_list != NULL) {
23698 		flags = tcp_rcv_drain(tcp);
23699 	}
23700 	if (flags == TH_ACK_NEEDED)
23701 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23702 
23703 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23704 }
23705 
23706 /*
23707  * This function handles delayed ACK timeout.
23708  */
23709 static void
23710 tcp_ack_timer(void *arg)
23711 {
23712 	conn_t	*connp = (conn_t *)arg;
23713 	tcp_t *tcp = connp->conn_tcp;
23714 	mblk_t *mp;
23715 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23716 
23717 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23718 
23719 	tcp->tcp_ack_tid = 0;
23720 
23721 	if (tcp->tcp_fused)
23722 		return;
23723 
23724 	/*
23725 	 * Do not send ACK if there is no outstanding unack'ed data.
23726 	 */
23727 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23728 		return;
23729 	}
23730 
23731 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23732 		/*
23733 		 * Make sure we don't allow deferred ACKs to result in
23734 		 * timer-based ACKing.  If we have held off an ACK
23735 		 * when there was more than an mss here, and the timer
23736 		 * goes off, we have to worry about the possibility
23737 		 * that the sender isn't doing slow-start, or is out
23738 		 * of step with us for some other reason.  We fall
23739 		 * permanently back in the direction of
23740 		 * ACK-every-other-packet as suggested in RFC 1122.
23741 		 */
23742 		if (tcp->tcp_rack_abs_max > 2)
23743 			tcp->tcp_rack_abs_max--;
23744 		tcp->tcp_rack_cur_max = 2;
23745 	}
23746 	mp = tcp_ack_mp(tcp);
23747 
23748 	if (mp != NULL) {
23749 		BUMP_LOCAL(tcp->tcp_obsegs);
23750 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23751 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23752 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23753 	}
23754 }
23755 
23756 
23757 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23758 static mblk_t *
23759 tcp_ack_mp(tcp_t *tcp)
23760 {
23761 	uint32_t	seq_no;
23762 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23763 
23764 	/*
23765 	 * There are a few cases to be considered while setting the sequence no.
23766 	 * Essentially, we can come here while processing an unacceptable pkt
23767 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23768 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23769 	 * If we are here for a zero window probe, stick with suna. In all
23770 	 * other cases, we check if suna + swnd encompasses snxt and set
23771 	 * the sequence number to snxt, if so. If snxt falls outside the
23772 	 * window (the receiver probably shrunk its window), we will go with
23773 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23774 	 * receiver.
23775 	 */
23776 	if (tcp->tcp_zero_win_probe) {
23777 		seq_no = tcp->tcp_suna;
23778 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23779 		ASSERT(tcp->tcp_swnd == 0);
23780 		seq_no = tcp->tcp_snxt;
23781 	} else {
23782 		seq_no = SEQ_GT(tcp->tcp_snxt,
23783 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23784 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23785 	}
23786 
23787 	if (tcp->tcp_valid_bits) {
23788 		/*
23789 		 * For the complex case where we have to send some
23790 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23791 		 */
23792 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23793 		    NULL, B_FALSE));
23794 	} else {
23795 		/* Generate a simple ACK */
23796 		int	data_length;
23797 		uchar_t	*rptr;
23798 		tcph_t	*tcph;
23799 		mblk_t	*mp1;
23800 		int32_t	tcp_hdr_len;
23801 		int32_t	tcp_tcp_hdr_len;
23802 		int32_t	num_sack_blk = 0;
23803 		int32_t sack_opt_len;
23804 
23805 		/*
23806 		 * Allocate space for TCP + IP headers
23807 		 * and link-level header
23808 		 */
23809 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23810 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23811 			    tcp->tcp_num_sack_blk);
23812 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23813 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23814 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23815 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23816 		} else {
23817 			tcp_hdr_len = tcp->tcp_hdr_len;
23818 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23819 		}
23820 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23821 		if (!mp1)
23822 			return (NULL);
23823 
23824 		/* Update the latest receive window size in TCP header. */
23825 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23826 		    tcp->tcp_tcph->th_win);
23827 		/* copy in prototype TCP + IP header */
23828 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23829 		mp1->b_rptr = rptr;
23830 		mp1->b_wptr = rptr + tcp_hdr_len;
23831 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23832 
23833 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23834 
23835 		/* Set the TCP sequence number. */
23836 		U32_TO_ABE32(seq_no, tcph->th_seq);
23837 
23838 		/* Set up the TCP flag field. */
23839 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23840 		if (tcp->tcp_ecn_echo_on)
23841 			tcph->th_flags[0] |= TH_ECE;
23842 
23843 		tcp->tcp_rack = tcp->tcp_rnxt;
23844 		tcp->tcp_rack_cnt = 0;
23845 
23846 		/* fill in timestamp option if in use */
23847 		if (tcp->tcp_snd_ts_ok) {
23848 			uint32_t llbolt = (uint32_t)lbolt;
23849 
23850 			U32_TO_BE32(llbolt,
23851 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23852 			U32_TO_BE32(tcp->tcp_ts_recent,
23853 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23854 		}
23855 
23856 		/* Fill in SACK options */
23857 		if (num_sack_blk > 0) {
23858 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23859 			sack_blk_t *tmp;
23860 			int32_t	i;
23861 
23862 			wptr[0] = TCPOPT_NOP;
23863 			wptr[1] = TCPOPT_NOP;
23864 			wptr[2] = TCPOPT_SACK;
23865 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23866 			    sizeof (sack_blk_t);
23867 			wptr += TCPOPT_REAL_SACK_LEN;
23868 
23869 			tmp = tcp->tcp_sack_list;
23870 			for (i = 0; i < num_sack_blk; i++) {
23871 				U32_TO_BE32(tmp[i].begin, wptr);
23872 				wptr += sizeof (tcp_seq);
23873 				U32_TO_BE32(tmp[i].end, wptr);
23874 				wptr += sizeof (tcp_seq);
23875 			}
23876 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23877 			    << 4);
23878 		}
23879 
23880 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23881 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23882 		} else {
23883 			/* Check for ip6i_t header in sticky hdrs */
23884 			ip6_t *ip6 = (ip6_t *)(rptr +
23885 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23886 			    sizeof (ip6i_t) : 0));
23887 
23888 			ip6->ip6_plen = htons(tcp_hdr_len -
23889 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23890 		}
23891 
23892 		/*
23893 		 * Prime pump for checksum calculation in IP.  Include the
23894 		 * adjustment for a source route if any.
23895 		 */
23896 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23897 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23898 		U16_TO_ABE16(data_length, tcph->th_sum);
23899 
23900 		if (tcp->tcp_ip_forward_progress) {
23901 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23902 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23903 			tcp->tcp_ip_forward_progress = B_FALSE;
23904 		}
23905 		return (mp1);
23906 	}
23907 }
23908 
23909 /*
23910  * Hash list insertion routine for tcp_t structures. Each hash bucket
23911  * contains a list of tcp_t entries, and each entry is bound to a unique
23912  * port. If there are multiple tcp_t's that are bound to the same port, then
23913  * one of them will be linked into the hash bucket list, and the rest will
23914  * hang off of that one entry. For each port, entries bound to a specific IP
23915  * address will be inserted before those those bound to INADDR_ANY.
23916  */
23917 static void
23918 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23919 {
23920 	tcp_t	**tcpp;
23921 	tcp_t	*tcpnext;
23922 	tcp_t	*tcphash;
23923 
23924 	if (tcp->tcp_ptpbhn != NULL) {
23925 		ASSERT(!caller_holds_lock);
23926 		tcp_bind_hash_remove(tcp);
23927 	}
23928 	tcpp = &tbf->tf_tcp;
23929 	if (!caller_holds_lock) {
23930 		mutex_enter(&tbf->tf_lock);
23931 	} else {
23932 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23933 	}
23934 	tcphash = tcpp[0];
23935 	tcpnext = NULL;
23936 	if (tcphash != NULL) {
23937 		/* Look for an entry using the same port */
23938 		while ((tcphash = tcpp[0]) != NULL &&
23939 		    tcp->tcp_lport != tcphash->tcp_lport)
23940 			tcpp = &(tcphash->tcp_bind_hash);
23941 
23942 		/* The port was not found, just add to the end */
23943 		if (tcphash == NULL)
23944 			goto insert;
23945 
23946 		/*
23947 		 * OK, there already exists an entry bound to the
23948 		 * same port.
23949 		 *
23950 		 * If the new tcp bound to the INADDR_ANY address
23951 		 * and the first one in the list is not bound to
23952 		 * INADDR_ANY we skip all entries until we find the
23953 		 * first one bound to INADDR_ANY.
23954 		 * This makes sure that applications binding to a
23955 		 * specific address get preference over those binding to
23956 		 * INADDR_ANY.
23957 		 */
23958 		tcpnext = tcphash;
23959 		tcphash = NULL;
23960 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23961 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23962 			while ((tcpnext = tcpp[0]) != NULL &&
23963 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23964 				tcpp = &(tcpnext->tcp_bind_hash_port);
23965 
23966 			if (tcpnext) {
23967 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23968 				tcphash = tcpnext->tcp_bind_hash;
23969 				if (tcphash != NULL) {
23970 					tcphash->tcp_ptpbhn =
23971 					    &(tcp->tcp_bind_hash);
23972 					tcpnext->tcp_bind_hash = NULL;
23973 				}
23974 			}
23975 		} else {
23976 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23977 			tcphash = tcpnext->tcp_bind_hash;
23978 			if (tcphash != NULL) {
23979 				tcphash->tcp_ptpbhn =
23980 				    &(tcp->tcp_bind_hash);
23981 				tcpnext->tcp_bind_hash = NULL;
23982 			}
23983 		}
23984 	}
23985 insert:
23986 	tcp->tcp_bind_hash_port = tcpnext;
23987 	tcp->tcp_bind_hash = tcphash;
23988 	tcp->tcp_ptpbhn = tcpp;
23989 	tcpp[0] = tcp;
23990 	if (!caller_holds_lock)
23991 		mutex_exit(&tbf->tf_lock);
23992 }
23993 
23994 /*
23995  * Hash list removal routine for tcp_t structures.
23996  */
23997 static void
23998 tcp_bind_hash_remove(tcp_t *tcp)
23999 {
24000 	tcp_t	*tcpnext;
24001 	kmutex_t *lockp;
24002 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24003 
24004 	if (tcp->tcp_ptpbhn == NULL)
24005 		return;
24006 
24007 	/*
24008 	 * Extract the lock pointer in case there are concurrent
24009 	 * hash_remove's for this instance.
24010 	 */
24011 	ASSERT(tcp->tcp_lport != 0);
24012 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
24013 
24014 	ASSERT(lockp != NULL);
24015 	mutex_enter(lockp);
24016 	if (tcp->tcp_ptpbhn) {
24017 		tcpnext = tcp->tcp_bind_hash_port;
24018 		if (tcpnext != NULL) {
24019 			tcp->tcp_bind_hash_port = NULL;
24020 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
24021 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
24022 			if (tcpnext->tcp_bind_hash != NULL) {
24023 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
24024 				    &(tcpnext->tcp_bind_hash);
24025 				tcp->tcp_bind_hash = NULL;
24026 			}
24027 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
24028 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
24029 			tcp->tcp_bind_hash = NULL;
24030 		}
24031 		*tcp->tcp_ptpbhn = tcpnext;
24032 		tcp->tcp_ptpbhn = NULL;
24033 	}
24034 	mutex_exit(lockp);
24035 }
24036 
24037 
24038 /*
24039  * Hash list lookup routine for tcp_t structures.
24040  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
24041  */
24042 static tcp_t *
24043 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
24044 {
24045 	tf_t	*tf;
24046 	tcp_t	*tcp;
24047 
24048 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24049 	mutex_enter(&tf->tf_lock);
24050 	for (tcp = tf->tf_tcp; tcp != NULL;
24051 	    tcp = tcp->tcp_acceptor_hash) {
24052 		if (tcp->tcp_acceptor_id == id) {
24053 			CONN_INC_REF(tcp->tcp_connp);
24054 			mutex_exit(&tf->tf_lock);
24055 			return (tcp);
24056 		}
24057 	}
24058 	mutex_exit(&tf->tf_lock);
24059 	return (NULL);
24060 }
24061 
24062 
24063 /*
24064  * Hash list insertion routine for tcp_t structures.
24065  */
24066 void
24067 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
24068 {
24069 	tf_t	*tf;
24070 	tcp_t	**tcpp;
24071 	tcp_t	*tcpnext;
24072 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24073 
24074 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24075 
24076 	if (tcp->tcp_ptpahn != NULL)
24077 		tcp_acceptor_hash_remove(tcp);
24078 	tcpp = &tf->tf_tcp;
24079 	mutex_enter(&tf->tf_lock);
24080 	tcpnext = tcpp[0];
24081 	if (tcpnext)
24082 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
24083 	tcp->tcp_acceptor_hash = tcpnext;
24084 	tcp->tcp_ptpahn = tcpp;
24085 	tcpp[0] = tcp;
24086 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
24087 	mutex_exit(&tf->tf_lock);
24088 }
24089 
24090 /*
24091  * Hash list removal routine for tcp_t structures.
24092  */
24093 static void
24094 tcp_acceptor_hash_remove(tcp_t *tcp)
24095 {
24096 	tcp_t	*tcpnext;
24097 	kmutex_t *lockp;
24098 
24099 	/*
24100 	 * Extract the lock pointer in case there are concurrent
24101 	 * hash_remove's for this instance.
24102 	 */
24103 	lockp = tcp->tcp_acceptor_lockp;
24104 
24105 	if (tcp->tcp_ptpahn == NULL)
24106 		return;
24107 
24108 	ASSERT(lockp != NULL);
24109 	mutex_enter(lockp);
24110 	if (tcp->tcp_ptpahn) {
24111 		tcpnext = tcp->tcp_acceptor_hash;
24112 		if (tcpnext) {
24113 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
24114 			tcp->tcp_acceptor_hash = NULL;
24115 		}
24116 		*tcp->tcp_ptpahn = tcpnext;
24117 		tcp->tcp_ptpahn = NULL;
24118 	}
24119 	mutex_exit(lockp);
24120 	tcp->tcp_acceptor_lockp = NULL;
24121 }
24122 
24123 /* Data for fast netmask macro used by tcp_hsp_lookup */
24124 
24125 static ipaddr_t netmasks[] = {
24126 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24127 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24128 };
24129 
24130 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24131 
24132 /*
24133  * XXX This routine should go away and instead we should use the metrics
24134  * associated with the routes to determine the default sndspace and rcvspace.
24135  */
24136 static tcp_hsp_t *
24137 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24138 {
24139 	tcp_hsp_t *hsp = NULL;
24140 
24141 	/* Quick check without acquiring the lock. */
24142 	if (tcps->tcps_hsp_hash == NULL)
24143 		return (NULL);
24144 
24145 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24146 
24147 	/* This routine finds the best-matching HSP for address addr. */
24148 
24149 	if (tcps->tcps_hsp_hash) {
24150 		int i;
24151 		ipaddr_t srchaddr;
24152 		tcp_hsp_t *hsp_net;
24153 
24154 		/* We do three passes: host, network, and subnet. */
24155 
24156 		srchaddr = addr;
24157 
24158 		for (i = 1; i <= 3; i++) {
24159 			/* Look for exact match on srchaddr */
24160 
24161 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24162 			while (hsp) {
24163 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24164 				    hsp->tcp_hsp_addr == srchaddr)
24165 					break;
24166 				hsp = hsp->tcp_hsp_next;
24167 			}
24168 			ASSERT(hsp == NULL ||
24169 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24170 
24171 			/*
24172 			 * If this is the first pass:
24173 			 *   If we found a match, great, return it.
24174 			 *   If not, search for the network on the second pass.
24175 			 */
24176 
24177 			if (i == 1)
24178 				if (hsp)
24179 					break;
24180 				else
24181 				{
24182 					srchaddr = addr & netmask(addr);
24183 					continue;
24184 				}
24185 
24186 			/*
24187 			 * If this is the second pass:
24188 			 *   If we found a match, but there's a subnet mask,
24189 			 *    save the match but try again using the subnet
24190 			 *    mask on the third pass.
24191 			 *   Otherwise, return whatever we found.
24192 			 */
24193 
24194 			if (i == 2) {
24195 				if (hsp && hsp->tcp_hsp_subnet) {
24196 					hsp_net = hsp;
24197 					srchaddr = addr & hsp->tcp_hsp_subnet;
24198 					continue;
24199 				} else {
24200 					break;
24201 				}
24202 			}
24203 
24204 			/*
24205 			 * This must be the third pass.  If we didn't find
24206 			 * anything, return the saved network HSP instead.
24207 			 */
24208 
24209 			if (!hsp)
24210 				hsp = hsp_net;
24211 		}
24212 	}
24213 
24214 	rw_exit(&tcps->tcps_hsp_lock);
24215 	return (hsp);
24216 }
24217 
24218 /*
24219  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24220  * match lookup.
24221  */
24222 static tcp_hsp_t *
24223 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
24224 {
24225 	tcp_hsp_t *hsp = NULL;
24226 
24227 	/* Quick check without acquiring the lock. */
24228 	if (tcps->tcps_hsp_hash == NULL)
24229 		return (NULL);
24230 
24231 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24232 
24233 	/* This routine finds the best-matching HSP for address addr. */
24234 
24235 	if (tcps->tcps_hsp_hash) {
24236 		int i;
24237 		in6_addr_t v6srchaddr;
24238 		tcp_hsp_t *hsp_net;
24239 
24240 		/* We do three passes: host, network, and subnet. */
24241 
24242 		v6srchaddr = *v6addr;
24243 
24244 		for (i = 1; i <= 3; i++) {
24245 			/* Look for exact match on srchaddr */
24246 
24247 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
24248 			    V4_PART_OF_V6(v6srchaddr))];
24249 			while (hsp) {
24250 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24251 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24252 				    &v6srchaddr))
24253 					break;
24254 				hsp = hsp->tcp_hsp_next;
24255 			}
24256 
24257 			/*
24258 			 * If this is the first pass:
24259 			 *   If we found a match, great, return it.
24260 			 *   If not, search for the network on the second pass.
24261 			 */
24262 
24263 			if (i == 1)
24264 				if (hsp)
24265 					break;
24266 				else {
24267 					/* Assume a 64 bit mask */
24268 					v6srchaddr.s6_addr32[0] =
24269 					    v6addr->s6_addr32[0];
24270 					v6srchaddr.s6_addr32[1] =
24271 					    v6addr->s6_addr32[1];
24272 					v6srchaddr.s6_addr32[2] = 0;
24273 					v6srchaddr.s6_addr32[3] = 0;
24274 					continue;
24275 				}
24276 
24277 			/*
24278 			 * If this is the second pass:
24279 			 *   If we found a match, but there's a subnet mask,
24280 			 *    save the match but try again using the subnet
24281 			 *    mask on the third pass.
24282 			 *   Otherwise, return whatever we found.
24283 			 */
24284 
24285 			if (i == 2) {
24286 				ASSERT(hsp == NULL ||
24287 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24288 				if (hsp &&
24289 				    !IN6_IS_ADDR_UNSPECIFIED(
24290 				    &hsp->tcp_hsp_subnet_v6)) {
24291 					hsp_net = hsp;
24292 					V6_MASK_COPY(*v6addr,
24293 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24294 					continue;
24295 				} else {
24296 					break;
24297 				}
24298 			}
24299 
24300 			/*
24301 			 * This must be the third pass.  If we didn't find
24302 			 * anything, return the saved network HSP instead.
24303 			 */
24304 
24305 			if (!hsp)
24306 				hsp = hsp_net;
24307 		}
24308 	}
24309 
24310 	rw_exit(&tcps->tcps_hsp_lock);
24311 	return (hsp);
24312 }
24313 
24314 /*
24315  * Type three generator adapted from the random() function in 4.4 BSD:
24316  */
24317 
24318 /*
24319  * Copyright (c) 1983, 1993
24320  *	The Regents of the University of California.  All rights reserved.
24321  *
24322  * Redistribution and use in source and binary forms, with or without
24323  * modification, are permitted provided that the following conditions
24324  * are met:
24325  * 1. Redistributions of source code must retain the above copyright
24326  *    notice, this list of conditions and the following disclaimer.
24327  * 2. Redistributions in binary form must reproduce the above copyright
24328  *    notice, this list of conditions and the following disclaimer in the
24329  *    documentation and/or other materials provided with the distribution.
24330  * 3. All advertising materials mentioning features or use of this software
24331  *    must display the following acknowledgement:
24332  *	This product includes software developed by the University of
24333  *	California, Berkeley and its contributors.
24334  * 4. Neither the name of the University nor the names of its contributors
24335  *    may be used to endorse or promote products derived from this software
24336  *    without specific prior written permission.
24337  *
24338  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24339  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24340  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24341  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24342  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24343  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24344  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24345  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24346  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24347  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24348  * SUCH DAMAGE.
24349  */
24350 
24351 /* Type 3 -- x**31 + x**3 + 1 */
24352 #define	DEG_3		31
24353 #define	SEP_3		3
24354 
24355 
24356 /* Protected by tcp_random_lock */
24357 static int tcp_randtbl[DEG_3 + 1];
24358 
24359 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24360 static int *tcp_random_rptr = &tcp_randtbl[1];
24361 
24362 static int *tcp_random_state = &tcp_randtbl[1];
24363 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24364 
24365 kmutex_t tcp_random_lock;
24366 
24367 void
24368 tcp_random_init(void)
24369 {
24370 	int i;
24371 	hrtime_t hrt;
24372 	time_t wallclock;
24373 	uint64_t result;
24374 
24375 	/*
24376 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24377 	 * a longlong, which may contain resolution down to nanoseconds.
24378 	 * The current time will either be a 32-bit or a 64-bit quantity.
24379 	 * XOR the two together in a 64-bit result variable.
24380 	 * Convert the result to a 32-bit value by multiplying the high-order
24381 	 * 32-bits by the low-order 32-bits.
24382 	 */
24383 
24384 	hrt = gethrtime();
24385 	(void) drv_getparm(TIME, &wallclock);
24386 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24387 	mutex_enter(&tcp_random_lock);
24388 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24389 	    (result & 0xffffffff);
24390 
24391 	for (i = 1; i < DEG_3; i++)
24392 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24393 		    + 12345;
24394 	tcp_random_fptr = &tcp_random_state[SEP_3];
24395 	tcp_random_rptr = &tcp_random_state[0];
24396 	mutex_exit(&tcp_random_lock);
24397 	for (i = 0; i < 10 * DEG_3; i++)
24398 		(void) tcp_random();
24399 }
24400 
24401 /*
24402  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24403  * This range is selected to be approximately centered on TCP_ISS / 2,
24404  * and easy to compute. We get this value by generating a 32-bit random
24405  * number, selecting out the high-order 17 bits, and then adding one so
24406  * that we never return zero.
24407  */
24408 int
24409 tcp_random(void)
24410 {
24411 	int i;
24412 
24413 	mutex_enter(&tcp_random_lock);
24414 	*tcp_random_fptr += *tcp_random_rptr;
24415 
24416 	/*
24417 	 * The high-order bits are more random than the low-order bits,
24418 	 * so we select out the high-order 17 bits and add one so that
24419 	 * we never return zero.
24420 	 */
24421 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24422 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24423 		tcp_random_fptr = tcp_random_state;
24424 		++tcp_random_rptr;
24425 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24426 		tcp_random_rptr = tcp_random_state;
24427 
24428 	mutex_exit(&tcp_random_lock);
24429 	return (i);
24430 }
24431 
24432 static int
24433 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24434     int *t_errorp, int *sys_errorp)
24435 {
24436 	int error;
24437 	int is_absreq_failure;
24438 	t_scalar_t *opt_lenp;
24439 	t_scalar_t opt_offset;
24440 	int prim_type;
24441 	struct T_conn_req *tcreqp;
24442 	struct T_conn_res *tcresp;
24443 	cred_t *cr;
24444 
24445 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
24446 
24447 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24448 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24449 	    prim_type == T_CONN_RES);
24450 
24451 	switch (prim_type) {
24452 	case T_CONN_REQ:
24453 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24454 		opt_offset = tcreqp->OPT_offset;
24455 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24456 		break;
24457 	case O_T_CONN_RES:
24458 	case T_CONN_RES:
24459 		tcresp = (struct T_conn_res *)mp->b_rptr;
24460 		opt_offset = tcresp->OPT_offset;
24461 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24462 		break;
24463 	}
24464 
24465 	*t_errorp = 0;
24466 	*sys_errorp = 0;
24467 	*do_disconnectp = 0;
24468 
24469 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24470 	    opt_offset, cr, &tcp_opt_obj,
24471 	    NULL, &is_absreq_failure);
24472 
24473 	switch (error) {
24474 	case  0:		/* no error */
24475 		ASSERT(is_absreq_failure == 0);
24476 		return (0);
24477 	case ENOPROTOOPT:
24478 		*t_errorp = TBADOPT;
24479 		break;
24480 	case EACCES:
24481 		*t_errorp = TACCES;
24482 		break;
24483 	default:
24484 		*t_errorp = TSYSERR; *sys_errorp = error;
24485 		break;
24486 	}
24487 	if (is_absreq_failure != 0) {
24488 		/*
24489 		 * The connection request should get the local ack
24490 		 * T_OK_ACK and then a T_DISCON_IND.
24491 		 */
24492 		*do_disconnectp = 1;
24493 	}
24494 	return (-1);
24495 }
24496 
24497 /*
24498  * Split this function out so that if the secret changes, I'm okay.
24499  *
24500  * Initialize the tcp_iss_cookie and tcp_iss_key.
24501  */
24502 
24503 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24504 
24505 static void
24506 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
24507 {
24508 	struct {
24509 		int32_t current_time;
24510 		uint32_t randnum;
24511 		uint16_t pad;
24512 		uint8_t ether[6];
24513 		uint8_t passwd[PASSWD_SIZE];
24514 	} tcp_iss_cookie;
24515 	time_t t;
24516 
24517 	/*
24518 	 * Start with the current absolute time.
24519 	 */
24520 	(void) drv_getparm(TIME, &t);
24521 	tcp_iss_cookie.current_time = t;
24522 
24523 	/*
24524 	 * XXX - Need a more random number per RFC 1750, not this crap.
24525 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24526 	 */
24527 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24528 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24529 
24530 	/*
24531 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24532 	 * as a good template.
24533 	 */
24534 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24535 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24536 
24537 	/*
24538 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24539 	 */
24540 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24541 
24542 	/*
24543 	 * See 4010593 if this section becomes a problem again,
24544 	 * but the local ethernet address is useful here.
24545 	 */
24546 	(void) localetheraddr(NULL,
24547 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24548 
24549 	/*
24550 	 * Hash 'em all together.  The MD5Final is called per-connection.
24551 	 */
24552 	mutex_enter(&tcps->tcps_iss_key_lock);
24553 	MD5Init(&tcps->tcps_iss_key);
24554 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
24555 	    sizeof (tcp_iss_cookie));
24556 	mutex_exit(&tcps->tcps_iss_key_lock);
24557 }
24558 
24559 /*
24560  * Set the RFC 1948 pass phrase
24561  */
24562 /* ARGSUSED */
24563 static int
24564 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24565     cred_t *cr)
24566 {
24567 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24568 
24569 	/*
24570 	 * Basically, value contains a new pass phrase.  Pass it along!
24571 	 */
24572 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
24573 	return (0);
24574 }
24575 
24576 /* ARGSUSED */
24577 static int
24578 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24579 {
24580 	bzero(buf, sizeof (tcp_sack_info_t));
24581 	return (0);
24582 }
24583 
24584 /* ARGSUSED */
24585 static int
24586 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24587 {
24588 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24589 	return (0);
24590 }
24591 
24592 /*
24593  * Make sure we wait until the default queue is setup, yet allow
24594  * tcp_g_q_create() to open a TCP stream.
24595  * We need to allow tcp_g_q_create() do do an open
24596  * of tcp, hence we compare curhread.
24597  * All others have to wait until the tcps_g_q has been
24598  * setup.
24599  */
24600 void
24601 tcp_g_q_setup(tcp_stack_t *tcps)
24602 {
24603 	mutex_enter(&tcps->tcps_g_q_lock);
24604 	if (tcps->tcps_g_q != NULL) {
24605 		mutex_exit(&tcps->tcps_g_q_lock);
24606 		return;
24607 	}
24608 	if (tcps->tcps_g_q_creator == NULL) {
24609 		/* This thread will set it up */
24610 		tcps->tcps_g_q_creator = curthread;
24611 		mutex_exit(&tcps->tcps_g_q_lock);
24612 		tcp_g_q_create(tcps);
24613 		mutex_enter(&tcps->tcps_g_q_lock);
24614 		ASSERT(tcps->tcps_g_q_creator == curthread);
24615 		tcps->tcps_g_q_creator = NULL;
24616 		cv_signal(&tcps->tcps_g_q_cv);
24617 		ASSERT(tcps->tcps_g_q != NULL);
24618 		mutex_exit(&tcps->tcps_g_q_lock);
24619 		return;
24620 	}
24621 	/* Everybody but the creator has to wait */
24622 	if (tcps->tcps_g_q_creator != curthread) {
24623 		while (tcps->tcps_g_q == NULL)
24624 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24625 	}
24626 	mutex_exit(&tcps->tcps_g_q_lock);
24627 }
24628 
24629 #define	IP	"ip"
24630 
24631 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24632 
24633 /*
24634  * Create a default tcp queue here instead of in strplumb
24635  */
24636 void
24637 tcp_g_q_create(tcp_stack_t *tcps)
24638 {
24639 	int error;
24640 	ldi_handle_t	lh = NULL;
24641 	ldi_ident_t	li = NULL;
24642 	int		rval;
24643 	cred_t		*cr;
24644 	major_t IP_MAJ;
24645 
24646 #ifdef NS_DEBUG
24647 	(void) printf("tcp_g_q_create()\n");
24648 #endif
24649 
24650 	IP_MAJ = ddi_name_to_major(IP);
24651 
24652 	ASSERT(tcps->tcps_g_q_creator == curthread);
24653 
24654 	error = ldi_ident_from_major(IP_MAJ, &li);
24655 	if (error) {
24656 #ifdef DEBUG
24657 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24658 		    error);
24659 #endif
24660 		return;
24661 	}
24662 
24663 	cr = zone_get_kcred(netstackid_to_zoneid(
24664 	    tcps->tcps_netstack->netstack_stackid));
24665 	ASSERT(cr != NULL);
24666 	/*
24667 	 * We set the tcp default queue to IPv6 because IPv4 falls
24668 	 * back to IPv6 when it can't find a client, but
24669 	 * IPv6 does not fall back to IPv4.
24670 	 */
24671 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24672 	if (error) {
24673 #ifdef DEBUG
24674 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24675 		    error);
24676 #endif
24677 		goto out;
24678 	}
24679 
24680 	/*
24681 	 * This ioctl causes the tcp framework to cache a pointer to
24682 	 * this stream, so we don't want to close the stream after
24683 	 * this operation.
24684 	 * Use the kernel credentials that are for the zone we're in.
24685 	 */
24686 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24687 	    (intptr_t)0, FKIOCTL, cr, &rval);
24688 	if (error) {
24689 #ifdef DEBUG
24690 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24691 		    "error %d\n", error);
24692 #endif
24693 		goto out;
24694 	}
24695 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24696 	lh = NULL;
24697 out:
24698 	/* Close layered handles */
24699 	if (li)
24700 		ldi_ident_release(li);
24701 	/* Keep cred around until _inactive needs it */
24702 	tcps->tcps_g_q_cr = cr;
24703 }
24704 
24705 /*
24706  * We keep tcp_g_q set until all other tcp_t's in the zone
24707  * has gone away, and then when tcp_g_q_inactive() is called
24708  * we clear it.
24709  */
24710 void
24711 tcp_g_q_destroy(tcp_stack_t *tcps)
24712 {
24713 #ifdef NS_DEBUG
24714 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24715 	    tcps->tcps_netstack->netstack_stackid);
24716 #endif
24717 
24718 	if (tcps->tcps_g_q == NULL) {
24719 		return;	/* Nothing to cleanup */
24720 	}
24721 	/*
24722 	 * Drop reference corresponding to the default queue.
24723 	 * This reference was added from tcp_open when the default queue
24724 	 * was created, hence we compensate for this extra drop in
24725 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24726 	 * the default queue was the last one to be open, in which
24727 	 * case, then tcp_g_q_inactive will be
24728 	 * called as a result of the refrele.
24729 	 */
24730 	TCPS_REFRELE(tcps);
24731 }
24732 
24733 /*
24734  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24735  * Run by tcp_q_q_inactive using a taskq.
24736  */
24737 static void
24738 tcp_g_q_close(void *arg)
24739 {
24740 	tcp_stack_t *tcps = arg;
24741 	int error;
24742 	ldi_handle_t	lh = NULL;
24743 	ldi_ident_t	li = NULL;
24744 	cred_t		*cr;
24745 	major_t IP_MAJ;
24746 
24747 	IP_MAJ = ddi_name_to_major(IP);
24748 
24749 #ifdef NS_DEBUG
24750 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24751 	    tcps->tcps_netstack->netstack_stackid,
24752 	    tcps->tcps_netstack->netstack_refcnt);
24753 #endif
24754 	lh = tcps->tcps_g_q_lh;
24755 	if (lh == NULL)
24756 		return;	/* Nothing to cleanup */
24757 
24758 	ASSERT(tcps->tcps_refcnt == 1);
24759 	ASSERT(tcps->tcps_g_q != NULL);
24760 
24761 	error = ldi_ident_from_major(IP_MAJ, &li);
24762 	if (error) {
24763 #ifdef DEBUG
24764 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
24765 		    error);
24766 #endif
24767 		return;
24768 	}
24769 
24770 	cr = tcps->tcps_g_q_cr;
24771 	tcps->tcps_g_q_cr = NULL;
24772 	ASSERT(cr != NULL);
24773 
24774 	/*
24775 	 * Make sure we can break the recursion when tcp_close decrements
24776 	 * the reference count causing g_q_inactive to be called again.
24777 	 */
24778 	tcps->tcps_g_q_lh = NULL;
24779 
24780 	/* close the default queue */
24781 	(void) ldi_close(lh, FREAD|FWRITE, cr);
24782 	/*
24783 	 * At this point in time tcps and the rest of netstack_t might
24784 	 * have been deleted.
24785 	 */
24786 	tcps = NULL;
24787 
24788 	/* Close layered handles */
24789 	ldi_ident_release(li);
24790 	crfree(cr);
24791 }
24792 
24793 /*
24794  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24795  *
24796  * Have to ensure that the ldi routines are not used by an
24797  * interrupt thread by using a taskq.
24798  */
24799 void
24800 tcp_g_q_inactive(tcp_stack_t *tcps)
24801 {
24802 	if (tcps->tcps_g_q_lh == NULL)
24803 		return;	/* Nothing to cleanup */
24804 
24805 	ASSERT(tcps->tcps_refcnt == 0);
24806 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
24807 
24808 	if (servicing_interrupt()) {
24809 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
24810 		    (void *) tcps, TQ_SLEEP);
24811 	} else {
24812 		tcp_g_q_close(tcps);
24813 	}
24814 }
24815 
24816 /*
24817  * Called by IP when IP is loaded into the kernel
24818  */
24819 void
24820 tcp_ddi_g_init(void)
24821 {
24822 	tcp_timercache = kmem_cache_create("tcp_timercache",
24823 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24824 	    NULL, NULL, NULL, NULL, NULL, 0);
24825 
24826 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24827 	    sizeof (tcp_sack_info_t), 0,
24828 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24829 
24830 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24831 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24832 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24833 
24834 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24835 
24836 	/* Initialize the random number generator */
24837 	tcp_random_init();
24838 
24839 	/* A single callback independently of how many netstacks we have */
24840 	ip_squeue_init(tcp_squeue_add);
24841 
24842 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
24843 
24844 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
24845 	    TASKQ_PREPOPULATE);
24846 
24847 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
24848 
24849 	/*
24850 	 * We want to be informed each time a stack is created or
24851 	 * destroyed in the kernel, so we can maintain the
24852 	 * set of tcp_stack_t's.
24853 	 */
24854 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
24855 	    tcp_stack_fini);
24856 }
24857 
24858 
24859 #define	INET_NAME	"ip"
24860 
24861 /*
24862  * Initialize the TCP stack instance.
24863  */
24864 static void *
24865 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
24866 {
24867 	tcp_stack_t	*tcps;
24868 	tcpparam_t	*pa;
24869 	int		i;
24870 	int		error = 0;
24871 	major_t		major;
24872 
24873 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
24874 	tcps->tcps_netstack = ns;
24875 
24876 	/* Initialize locks */
24877 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
24878 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24879 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
24880 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24881 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24882 
24883 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
24884 	tcps->tcps_g_epriv_ports[0] = 2049;
24885 	tcps->tcps_g_epriv_ports[1] = 4045;
24886 	tcps->tcps_min_anonpriv_port = 512;
24887 
24888 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
24889 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
24890 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
24891 	    TCP_FANOUT_SIZE, KM_SLEEP);
24892 
24893 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24894 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
24895 		    MUTEX_DEFAULT, NULL);
24896 	}
24897 
24898 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24899 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
24900 		    MUTEX_DEFAULT, NULL);
24901 	}
24902 
24903 	/* TCP's IPsec code calls the packet dropper. */
24904 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
24905 
24906 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
24907 	tcps->tcps_params = pa;
24908 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24909 
24910 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
24911 	    A_CNT(lcl_tcp_param_arr), tcps);
24912 
24913 	/*
24914 	 * Note: To really walk the device tree you need the devinfo
24915 	 * pointer to your device which is only available after probe/attach.
24916 	 * The following is safe only because it uses ddi_root_node()
24917 	 */
24918 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24919 	    tcp_opt_obj.odb_opt_arr_cnt);
24920 
24921 	/*
24922 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24923 	 * by the boot scripts.
24924 	 *
24925 	 * Use NULL name, as the name is caught by the new lockstats.
24926 	 *
24927 	 * Initialize with some random, non-guessable string, like the global
24928 	 * T_INFO_ACK.
24929 	 */
24930 
24931 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24932 	    sizeof (tcp_g_t_info_ack), tcps);
24933 
24934 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
24935 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
24936 
24937 	major = mod_name_to_major(INET_NAME);
24938 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
24939 	ASSERT(error == 0);
24940 	return (tcps);
24941 }
24942 
24943 /*
24944  * Called when the IP module is about to be unloaded.
24945  */
24946 void
24947 tcp_ddi_g_destroy(void)
24948 {
24949 	tcp_g_kstat_fini(tcp_g_kstat);
24950 	tcp_g_kstat = NULL;
24951 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
24952 
24953 	mutex_destroy(&tcp_random_lock);
24954 
24955 	kmem_cache_destroy(tcp_timercache);
24956 	kmem_cache_destroy(tcp_sack_info_cache);
24957 	kmem_cache_destroy(tcp_iphc_cache);
24958 
24959 	netstack_unregister(NS_TCP);
24960 	taskq_destroy(tcp_taskq);
24961 }
24962 
24963 /*
24964  * Shut down the TCP stack instance.
24965  */
24966 /* ARGSUSED */
24967 static void
24968 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24969 {
24970 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24971 
24972 	tcp_g_q_destroy(tcps);
24973 }
24974 
24975 /*
24976  * Free the TCP stack instance.
24977  */
24978 static void
24979 tcp_stack_fini(netstackid_t stackid, void *arg)
24980 {
24981 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24982 	int i;
24983 
24984 	nd_free(&tcps->tcps_g_nd);
24985 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24986 	tcps->tcps_params = NULL;
24987 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24988 	tcps->tcps_wroff_xtra_param = NULL;
24989 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24990 	tcps->tcps_mdt_head_param = NULL;
24991 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24992 	tcps->tcps_mdt_tail_param = NULL;
24993 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24994 	tcps->tcps_mdt_max_pbufs_param = NULL;
24995 
24996 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24997 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24998 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24999 	}
25000 
25001 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25002 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
25003 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
25004 	}
25005 
25006 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
25007 	tcps->tcps_bind_fanout = NULL;
25008 
25009 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
25010 	tcps->tcps_acceptor_fanout = NULL;
25011 
25012 	mutex_destroy(&tcps->tcps_iss_key_lock);
25013 	rw_destroy(&tcps->tcps_hsp_lock);
25014 	mutex_destroy(&tcps->tcps_g_q_lock);
25015 	cv_destroy(&tcps->tcps_g_q_cv);
25016 	mutex_destroy(&tcps->tcps_epriv_port_lock);
25017 
25018 	ip_drop_unregister(&tcps->tcps_dropper);
25019 
25020 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
25021 	tcps->tcps_kstat = NULL;
25022 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
25023 
25024 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
25025 	tcps->tcps_mibkp = NULL;
25026 
25027 	ldi_ident_release(tcps->tcps_ldi_ident);
25028 	kmem_free(tcps, sizeof (*tcps));
25029 }
25030 
25031 /*
25032  * Generate ISS, taking into account NDD changes may happen halfway through.
25033  * (If the iss is not zero, set it.)
25034  */
25035 
25036 static void
25037 tcp_iss_init(tcp_t *tcp)
25038 {
25039 	MD5_CTX context;
25040 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
25041 	uint32_t answer[4];
25042 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25043 
25044 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
25045 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
25046 	switch (tcps->tcps_strong_iss) {
25047 	case 2:
25048 		mutex_enter(&tcps->tcps_iss_key_lock);
25049 		context = tcps->tcps_iss_key;
25050 		mutex_exit(&tcps->tcps_iss_key_lock);
25051 		arg.ports = tcp->tcp_ports;
25052 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25053 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
25054 			    &arg.src);
25055 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
25056 			    &arg.dst);
25057 		} else {
25058 			arg.src = tcp->tcp_ip6h->ip6_src;
25059 			arg.dst = tcp->tcp_ip6h->ip6_dst;
25060 		}
25061 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
25062 		MD5Final((uchar_t *)answer, &context);
25063 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
25064 		/*
25065 		 * Now that we've hashed into a unique per-connection sequence
25066 		 * space, add a random increment per strong_iss == 1.  So I
25067 		 * guess we'll have to...
25068 		 */
25069 		/* FALLTHRU */
25070 	case 1:
25071 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
25072 		break;
25073 	default:
25074 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25075 		break;
25076 	}
25077 	tcp->tcp_valid_bits = TCP_ISS_VALID;
25078 	tcp->tcp_fss = tcp->tcp_iss - 1;
25079 	tcp->tcp_suna = tcp->tcp_iss;
25080 	tcp->tcp_snxt = tcp->tcp_iss + 1;
25081 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
25082 	tcp->tcp_csuna = tcp->tcp_snxt;
25083 }
25084 
25085 /*
25086  * Exported routine for extracting active tcp connection status.
25087  *
25088  * This is used by the Solaris Cluster Networking software to
25089  * gather a list of connections that need to be forwarded to
25090  * specific nodes in the cluster when configuration changes occur.
25091  *
25092  * The callback is invoked for each tcp_t structure from all netstacks,
25093  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
25094  * from the netstack with the specified stack_id. Returning
25095  * non-zero from the callback routine terminates the search.
25096  */
25097 int
25098 cl_tcp_walk_list(netstackid_t stack_id,
25099     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
25100 {
25101 	netstack_handle_t nh;
25102 	netstack_t *ns;
25103 	int ret = 0;
25104 
25105 	if (stack_id >= 0) {
25106 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
25107 			return (EINVAL);
25108 
25109 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25110 		    ns->netstack_tcp);
25111 		netstack_rele(ns);
25112 		return (ret);
25113 	}
25114 
25115 	netstack_next_init(&nh);
25116 	while ((ns = netstack_next(&nh)) != NULL) {
25117 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25118 		    ns->netstack_tcp);
25119 		netstack_rele(ns);
25120 	}
25121 	netstack_next_fini(&nh);
25122 	return (ret);
25123 }
25124 
25125 static int
25126 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25127     tcp_stack_t *tcps)
25128 {
25129 	tcp_t *tcp;
25130 	cl_tcp_info_t	cl_tcpi;
25131 	connf_t	*connfp;
25132 	conn_t	*connp;
25133 	int	i;
25134 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25135 
25136 	ASSERT(callback != NULL);
25137 
25138 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25139 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25140 		connp = NULL;
25141 
25142 		while ((connp =
25143 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25144 
25145 			tcp = connp->conn_tcp;
25146 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
25147 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
25148 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
25149 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
25150 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
25151 			/*
25152 			 * The macros tcp_laddr and tcp_faddr give the IPv4
25153 			 * addresses. They are copied implicitly below as
25154 			 * mapped addresses.
25155 			 */
25156 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
25157 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25158 				cl_tcpi.cl_tcpi_faddr =
25159 				    tcp->tcp_ipha->ipha_dst;
25160 			} else {
25161 				cl_tcpi.cl_tcpi_faddr_v6 =
25162 				    tcp->tcp_ip6h->ip6_dst;
25163 			}
25164 
25165 			/*
25166 			 * If the callback returns non-zero
25167 			 * we terminate the traversal.
25168 			 */
25169 			if ((*callback)(&cl_tcpi, arg) != 0) {
25170 				CONN_DEC_REF(tcp->tcp_connp);
25171 				return (1);
25172 			}
25173 		}
25174 	}
25175 
25176 	return (0);
25177 }
25178 
25179 /*
25180  * Macros used for accessing the different types of sockaddr
25181  * structures inside a tcp_ioc_abort_conn_t.
25182  */
25183 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
25184 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
25185 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
25186 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
25187 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
25188 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
25189 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
25190 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
25191 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
25192 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
25193 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
25194 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
25195 
25196 /*
25197  * Return the correct error code to mimic the behavior
25198  * of a connection reset.
25199  */
25200 #define	TCP_AC_GET_ERRCODE(state, err) {	\
25201 		switch ((state)) {		\
25202 		case TCPS_SYN_SENT:		\
25203 		case TCPS_SYN_RCVD:		\
25204 			(err) = ECONNREFUSED;	\
25205 			break;			\
25206 		case TCPS_ESTABLISHED:		\
25207 		case TCPS_FIN_WAIT_1:		\
25208 		case TCPS_FIN_WAIT_2:		\
25209 		case TCPS_CLOSE_WAIT:		\
25210 			(err) = ECONNRESET;	\
25211 			break;			\
25212 		case TCPS_CLOSING:		\
25213 		case TCPS_LAST_ACK:		\
25214 		case TCPS_TIME_WAIT:		\
25215 			(err) = 0;		\
25216 			break;			\
25217 		default:			\
25218 			(err) = ENXIO;		\
25219 		}				\
25220 	}
25221 
25222 /*
25223  * Check if a tcp structure matches the info in acp.
25224  */
25225 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
25226 	(((acp)->ac_local.ss_family == AF_INET) ?		\
25227 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
25228 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
25229 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
25230 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
25231 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
25232 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
25233 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
25234 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
25235 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25236 	(acp)->ac_end >= (tcp)->tcp_state) :		\
25237 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
25238 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
25239 	&(tcp)->tcp_ip_src_v6)) &&				\
25240 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
25241 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
25242 	&(tcp)->tcp_remote_v6)) &&				\
25243 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
25244 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
25245 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
25246 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
25247 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25248 	(acp)->ac_end >= (tcp)->tcp_state))
25249 
25250 #define	TCP_AC_MATCH(acp, tcp)					\
25251 	(((acp)->ac_zoneid == ALL_ZONES ||			\
25252 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
25253 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
25254 
25255 /*
25256  * Build a message containing a tcp_ioc_abort_conn_t structure
25257  * which is filled in with information from acp and tp.
25258  */
25259 static mblk_t *
25260 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
25261 {
25262 	mblk_t *mp;
25263 	tcp_ioc_abort_conn_t *tacp;
25264 
25265 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
25266 	if (mp == NULL)
25267 		return (NULL);
25268 
25269 	mp->b_datap->db_type = M_CTL;
25270 
25271 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
25272 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
25273 	    sizeof (uint32_t));
25274 
25275 	tacp->ac_start = acp->ac_start;
25276 	tacp->ac_end = acp->ac_end;
25277 	tacp->ac_zoneid = acp->ac_zoneid;
25278 
25279 	if (acp->ac_local.ss_family == AF_INET) {
25280 		tacp->ac_local.ss_family = AF_INET;
25281 		tacp->ac_remote.ss_family = AF_INET;
25282 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
25283 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
25284 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
25285 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
25286 	} else {
25287 		tacp->ac_local.ss_family = AF_INET6;
25288 		tacp->ac_remote.ss_family = AF_INET6;
25289 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
25290 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
25291 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
25292 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
25293 	}
25294 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
25295 	return (mp);
25296 }
25297 
25298 /*
25299  * Print a tcp_ioc_abort_conn_t structure.
25300  */
25301 static void
25302 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
25303 {
25304 	char lbuf[128];
25305 	char rbuf[128];
25306 	sa_family_t af;
25307 	in_port_t lport, rport;
25308 	ushort_t logflags;
25309 
25310 	af = acp->ac_local.ss_family;
25311 
25312 	if (af == AF_INET) {
25313 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
25314 		    lbuf, 128);
25315 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
25316 		    rbuf, 128);
25317 		lport = ntohs(TCP_AC_V4LPORT(acp));
25318 		rport = ntohs(TCP_AC_V4RPORT(acp));
25319 	} else {
25320 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
25321 		    lbuf, 128);
25322 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
25323 		    rbuf, 128);
25324 		lport = ntohs(TCP_AC_V6LPORT(acp));
25325 		rport = ntohs(TCP_AC_V6RPORT(acp));
25326 	}
25327 
25328 	logflags = SL_TRACE | SL_NOTE;
25329 	/*
25330 	 * Don't print this message to the console if the operation was done
25331 	 * to a non-global zone.
25332 	 */
25333 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25334 		logflags |= SL_CONSOLE;
25335 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
25336 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
25337 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
25338 	    acp->ac_start, acp->ac_end);
25339 }
25340 
25341 /*
25342  * Called inside tcp_rput when a message built using
25343  * tcp_ioctl_abort_build_msg is put into a queue.
25344  * Note that when we get here there is no wildcard in acp any more.
25345  */
25346 static void
25347 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
25348 {
25349 	tcp_ioc_abort_conn_t *acp;
25350 
25351 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
25352 	if (tcp->tcp_state <= acp->ac_end) {
25353 		/*
25354 		 * If we get here, we are already on the correct
25355 		 * squeue. This ioctl follows the following path
25356 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
25357 		 * ->tcp_ioctl_abort->squeue_enter (if on a
25358 		 * different squeue)
25359 		 */
25360 		int errcode;
25361 
25362 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
25363 		(void) tcp_clean_death(tcp, errcode, 26);
25364 	}
25365 	freemsg(mp);
25366 }
25367 
25368 /*
25369  * Abort all matching connections on a hash chain.
25370  */
25371 static int
25372 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
25373     boolean_t exact, tcp_stack_t *tcps)
25374 {
25375 	int nmatch, err = 0;
25376 	tcp_t *tcp;
25377 	MBLKP mp, last, listhead = NULL;
25378 	conn_t	*tconnp;
25379 	connf_t	*connfp;
25380 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25381 
25382 	connfp = &ipst->ips_ipcl_conn_fanout[index];
25383 
25384 startover:
25385 	nmatch = 0;
25386 
25387 	mutex_enter(&connfp->connf_lock);
25388 	for (tconnp = connfp->connf_head; tconnp != NULL;
25389 	    tconnp = tconnp->conn_next) {
25390 		tcp = tconnp->conn_tcp;
25391 		if (TCP_AC_MATCH(acp, tcp)) {
25392 			CONN_INC_REF(tcp->tcp_connp);
25393 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
25394 			if (mp == NULL) {
25395 				err = ENOMEM;
25396 				CONN_DEC_REF(tcp->tcp_connp);
25397 				break;
25398 			}
25399 			mp->b_prev = (mblk_t *)tcp;
25400 
25401 			if (listhead == NULL) {
25402 				listhead = mp;
25403 				last = mp;
25404 			} else {
25405 				last->b_next = mp;
25406 				last = mp;
25407 			}
25408 			nmatch++;
25409 			if (exact)
25410 				break;
25411 		}
25412 
25413 		/* Avoid holding lock for too long. */
25414 		if (nmatch >= 500)
25415 			break;
25416 	}
25417 	mutex_exit(&connfp->connf_lock);
25418 
25419 	/* Pass mp into the correct tcp */
25420 	while ((mp = listhead) != NULL) {
25421 		listhead = listhead->b_next;
25422 		tcp = (tcp_t *)mp->b_prev;
25423 		mp->b_next = mp->b_prev = NULL;
25424 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
25425 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
25426 	}
25427 
25428 	*count += nmatch;
25429 	if (nmatch >= 500 && err == 0)
25430 		goto startover;
25431 	return (err);
25432 }
25433 
25434 /*
25435  * Abort all connections that matches the attributes specified in acp.
25436  */
25437 static int
25438 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
25439 {
25440 	sa_family_t af;
25441 	uint32_t  ports;
25442 	uint16_t *pports;
25443 	int err = 0, count = 0;
25444 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25445 	int index = -1;
25446 	ushort_t logflags;
25447 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25448 
25449 	af = acp->ac_local.ss_family;
25450 
25451 	if (af == AF_INET) {
25452 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25453 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25454 			pports = (uint16_t *)&ports;
25455 			pports[1] = TCP_AC_V4LPORT(acp);
25456 			pports[0] = TCP_AC_V4RPORT(acp);
25457 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25458 		}
25459 	} else {
25460 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25461 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25462 			pports = (uint16_t *)&ports;
25463 			pports[1] = TCP_AC_V6LPORT(acp);
25464 			pports[0] = TCP_AC_V6RPORT(acp);
25465 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25466 		}
25467 	}
25468 
25469 	/*
25470 	 * For cases where remote addr, local port, and remote port are non-
25471 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25472 	 */
25473 	if (index != -1) {
25474 		err = tcp_ioctl_abort_bucket(acp, index,
25475 		    &count, exact, tcps);
25476 	} else {
25477 		/*
25478 		 * loop through all entries for wildcard case
25479 		 */
25480 		for (index = 0;
25481 		    index < ipst->ips_ipcl_conn_fanout_size;
25482 		    index++) {
25483 			err = tcp_ioctl_abort_bucket(acp, index,
25484 			    &count, exact, tcps);
25485 			if (err != 0)
25486 				break;
25487 		}
25488 	}
25489 
25490 	logflags = SL_TRACE | SL_NOTE;
25491 	/*
25492 	 * Don't print this message to the console if the operation was done
25493 	 * to a non-global zone.
25494 	 */
25495 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25496 		logflags |= SL_CONSOLE;
25497 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25498 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25499 	if (err == 0 && count == 0)
25500 		err = ENOENT;
25501 	return (err);
25502 }
25503 
25504 /*
25505  * Process the TCP_IOC_ABORT_CONN ioctl request.
25506  */
25507 static void
25508 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25509 {
25510 	int	err;
25511 	IOCP    iocp;
25512 	MBLKP   mp1;
25513 	sa_family_t laf, raf;
25514 	tcp_ioc_abort_conn_t *acp;
25515 	zone_t		*zptr;
25516 	conn_t		*connp = Q_TO_CONN(q);
25517 	zoneid_t	zoneid = connp->conn_zoneid;
25518 	tcp_t		*tcp = connp->conn_tcp;
25519 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25520 
25521 	iocp = (IOCP)mp->b_rptr;
25522 
25523 	if ((mp1 = mp->b_cont) == NULL ||
25524 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25525 		err = EINVAL;
25526 		goto out;
25527 	}
25528 
25529 	/* check permissions */
25530 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
25531 		err = EPERM;
25532 		goto out;
25533 	}
25534 
25535 	if (mp1->b_cont != NULL) {
25536 		freemsg(mp1->b_cont);
25537 		mp1->b_cont = NULL;
25538 	}
25539 
25540 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25541 	laf = acp->ac_local.ss_family;
25542 	raf = acp->ac_remote.ss_family;
25543 
25544 	/* check that a zone with the supplied zoneid exists */
25545 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25546 		zptr = zone_find_by_id(zoneid);
25547 		if (zptr != NULL) {
25548 			zone_rele(zptr);
25549 		} else {
25550 			err = EINVAL;
25551 			goto out;
25552 		}
25553 	}
25554 
25555 	/*
25556 	 * For exclusive stacks we set the zoneid to zero
25557 	 * to make TCP operate as if in the global zone.
25558 	 */
25559 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
25560 		acp->ac_zoneid = GLOBAL_ZONEID;
25561 
25562 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25563 	    acp->ac_start > acp->ac_end || laf != raf ||
25564 	    (laf != AF_INET && laf != AF_INET6)) {
25565 		err = EINVAL;
25566 		goto out;
25567 	}
25568 
25569 	tcp_ioctl_abort_dump(acp);
25570 	err = tcp_ioctl_abort(acp, tcps);
25571 
25572 out:
25573 	if (mp1 != NULL) {
25574 		freemsg(mp1);
25575 		mp->b_cont = NULL;
25576 	}
25577 
25578 	if (err != 0)
25579 		miocnak(q, mp, 0, err);
25580 	else
25581 		miocack(q, mp, 0, 0);
25582 }
25583 
25584 /*
25585  * tcp_time_wait_processing() handles processing of incoming packets when
25586  * the tcp is in the TIME_WAIT state.
25587  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25588  * on the time wait list.
25589  */
25590 void
25591 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25592     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25593 {
25594 	int32_t		bytes_acked;
25595 	int32_t		gap;
25596 	int32_t		rgap;
25597 	tcp_opt_t	tcpopt;
25598 	uint_t		flags;
25599 	uint32_t	new_swnd = 0;
25600 	conn_t		*connp;
25601 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25602 
25603 	BUMP_LOCAL(tcp->tcp_ibsegs);
25604 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
25605 
25606 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25607 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25608 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25609 	if (tcp->tcp_snd_ts_ok) {
25610 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25611 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25612 			    tcp->tcp_rnxt, TH_ACK);
25613 			goto done;
25614 		}
25615 	}
25616 	gap = seg_seq - tcp->tcp_rnxt;
25617 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25618 	if (gap < 0) {
25619 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25620 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25621 		    (seg_len > -gap ? -gap : seg_len));
25622 		seg_len += gap;
25623 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25624 			if (flags & TH_RST) {
25625 				goto done;
25626 			}
25627 			if ((flags & TH_FIN) && seg_len == -1) {
25628 				/*
25629 				 * When TCP receives a duplicate FIN in
25630 				 * TIME_WAIT state, restart the 2 MSL timer.
25631 				 * See page 73 in RFC 793. Make sure this TCP
25632 				 * is already on the TIME_WAIT list. If not,
25633 				 * just restart the timer.
25634 				 */
25635 				if (TCP_IS_DETACHED(tcp)) {
25636 					if (tcp_time_wait_remove(tcp, NULL) ==
25637 					    B_TRUE) {
25638 						tcp_time_wait_append(tcp);
25639 						TCP_DBGSTAT(tcps,
25640 						    tcp_rput_time_wait);
25641 					}
25642 				} else {
25643 					ASSERT(tcp != NULL);
25644 					TCP_TIMER_RESTART(tcp,
25645 					    tcps->tcps_time_wait_interval);
25646 				}
25647 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25648 				    tcp->tcp_rnxt, TH_ACK);
25649 				goto done;
25650 			}
25651 			flags |=  TH_ACK_NEEDED;
25652 			seg_len = 0;
25653 			goto process_ack;
25654 		}
25655 
25656 		/* Fix seg_seq, and chew the gap off the front. */
25657 		seg_seq = tcp->tcp_rnxt;
25658 	}
25659 
25660 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25661 		/*
25662 		 * Make sure that when we accept the connection, pick
25663 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25664 		 * old connection.
25665 		 *
25666 		 * The next ISS generated is equal to tcp_iss_incr_extra
25667 		 * + ISS_INCR/2 + other components depending on the
25668 		 * value of tcp_strong_iss.  We pre-calculate the new
25669 		 * ISS here and compare with tcp_snxt to determine if
25670 		 * we need to make adjustment to tcp_iss_incr_extra.
25671 		 *
25672 		 * The above calculation is ugly and is a
25673 		 * waste of CPU cycles...
25674 		 */
25675 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25676 		int32_t adj;
25677 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25678 
25679 		switch (tcps->tcps_strong_iss) {
25680 		case 2: {
25681 			/* Add time and MD5 components. */
25682 			uint32_t answer[4];
25683 			struct {
25684 				uint32_t ports;
25685 				in6_addr_t src;
25686 				in6_addr_t dst;
25687 			} arg;
25688 			MD5_CTX context;
25689 
25690 			mutex_enter(&tcps->tcps_iss_key_lock);
25691 			context = tcps->tcps_iss_key;
25692 			mutex_exit(&tcps->tcps_iss_key_lock);
25693 			arg.ports = tcp->tcp_ports;
25694 			/* We use MAPPED addresses in tcp_iss_init */
25695 			arg.src = tcp->tcp_ip_src_v6;
25696 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25697 				IN6_IPADDR_TO_V4MAPPED(
25698 				    tcp->tcp_ipha->ipha_dst,
25699 				    &arg.dst);
25700 			} else {
25701 				arg.dst =
25702 				    tcp->tcp_ip6h->ip6_dst;
25703 			}
25704 			MD5Update(&context, (uchar_t *)&arg,
25705 			    sizeof (arg));
25706 			MD5Final((uchar_t *)answer, &context);
25707 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25708 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25709 			break;
25710 		}
25711 		case 1:
25712 			/* Add time component and min random (i.e. 1). */
25713 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25714 			break;
25715 		default:
25716 			/* Add only time component. */
25717 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25718 			break;
25719 		}
25720 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25721 			/*
25722 			 * New ISS not guaranteed to be ISS_INCR/2
25723 			 * ahead of the current tcp_snxt, so add the
25724 			 * difference to tcp_iss_incr_extra.
25725 			 */
25726 			tcps->tcps_iss_incr_extra += adj;
25727 		}
25728 		/*
25729 		 * If tcp_clean_death() can not perform the task now,
25730 		 * drop the SYN packet and let the other side re-xmit.
25731 		 * Otherwise pass the SYN packet back in, since the
25732 		 * old tcp state has been cleaned up or freed.
25733 		 */
25734 		if (tcp_clean_death(tcp, 0, 27) == -1)
25735 			goto done;
25736 		/*
25737 		 * We will come back to tcp_rput_data
25738 		 * on the global queue. Packets destined
25739 		 * for the global queue will be checked
25740 		 * with global policy. But the policy for
25741 		 * this packet has already been checked as
25742 		 * this was destined for the detached
25743 		 * connection. We need to bypass policy
25744 		 * check this time by attaching a dummy
25745 		 * ipsec_in with ipsec_in_dont_check set.
25746 		 */
25747 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25748 		if (connp != NULL) {
25749 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25750 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25751 			return;
25752 		}
25753 		goto done;
25754 	}
25755 
25756 	/*
25757 	 * rgap is the amount of stuff received out of window.  A negative
25758 	 * value is the amount out of window.
25759 	 */
25760 	if (rgap < 0) {
25761 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25762 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
25763 		/* Fix seg_len and make sure there is something left. */
25764 		seg_len += rgap;
25765 		if (seg_len <= 0) {
25766 			if (flags & TH_RST) {
25767 				goto done;
25768 			}
25769 			flags |=  TH_ACK_NEEDED;
25770 			seg_len = 0;
25771 			goto process_ack;
25772 		}
25773 	}
25774 	/*
25775 	 * Check whether we can update tcp_ts_recent.  This test is
25776 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
25777 	 * Extensions for High Performance: An Update", Internet Draft.
25778 	 */
25779 	if (tcp->tcp_snd_ts_ok &&
25780 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
25781 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
25782 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
25783 		tcp->tcp_last_rcv_lbolt = lbolt64;
25784 	}
25785 
25786 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
25787 		/* Always ack out of order packets */
25788 		flags |= TH_ACK_NEEDED;
25789 		seg_len = 0;
25790 	} else if (seg_len > 0) {
25791 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
25792 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
25793 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
25794 	}
25795 	if (flags & TH_RST) {
25796 		(void) tcp_clean_death(tcp, 0, 28);
25797 		goto done;
25798 	}
25799 	if (flags & TH_SYN) {
25800 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
25801 		    TH_RST|TH_ACK);
25802 		/*
25803 		 * Do not delete the TCP structure if it is in
25804 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
25805 		 */
25806 		goto done;
25807 	}
25808 process_ack:
25809 	if (flags & TH_ACK) {
25810 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
25811 		if (bytes_acked <= 0) {
25812 			if (bytes_acked == 0 && seg_len == 0 &&
25813 			    new_swnd == tcp->tcp_swnd)
25814 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
25815 		} else {
25816 			/* Acks something not sent */
25817 			flags |= TH_ACK_NEEDED;
25818 		}
25819 	}
25820 	if (flags & TH_ACK_NEEDED) {
25821 		/*
25822 		 * Time to send an ack for some reason.
25823 		 */
25824 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25825 		    tcp->tcp_rnxt, TH_ACK);
25826 	}
25827 done:
25828 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25829 		DB_CKSUMSTART(mp) = 0;
25830 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
25831 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
25832 	}
25833 	freemsg(mp);
25834 }
25835 
25836 /*
25837  * TCP Timers Implementation.
25838  */
25839 timeout_id_t
25840 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25841 {
25842 	mblk_t *mp;
25843 	tcp_timer_t *tcpt;
25844 	tcp_t *tcp = connp->conn_tcp;
25845 
25846 	ASSERT(connp->conn_sqp != NULL);
25847 
25848 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
25849 
25850 	if (tcp->tcp_timercache == NULL) {
25851 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25852 	} else {
25853 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
25854 		mp = tcp->tcp_timercache;
25855 		tcp->tcp_timercache = mp->b_next;
25856 		mp->b_next = NULL;
25857 		ASSERT(mp->b_wptr == NULL);
25858 	}
25859 
25860 	CONN_INC_REF(connp);
25861 	tcpt = (tcp_timer_t *)mp->b_rptr;
25862 	tcpt->connp = connp;
25863 	tcpt->tcpt_proc = f;
25864 	/*
25865 	 * TCP timers are normal timeouts. Plus, they do not require more than
25866 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
25867 	 * rounding up the expiration to the next resolution boundary, we can
25868 	 * batch timers in the callout subsystem to make TCP timers more
25869 	 * efficient. The roundup also protects short timers from expiring too
25870 	 * early before they have a chance to be cancelled.
25871 	 */
25872 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
25873 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
25874 
25875 	return ((timeout_id_t)mp);
25876 }
25877 
25878 static void
25879 tcp_timer_callback(void *arg)
25880 {
25881 	mblk_t *mp = (mblk_t *)arg;
25882 	tcp_timer_t *tcpt;
25883 	conn_t	*connp;
25884 
25885 	tcpt = (tcp_timer_t *)mp->b_rptr;
25886 	connp = tcpt->connp;
25887 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
25888 	    SQ_FILL, SQTAG_TCP_TIMER);
25889 }
25890 
25891 static void
25892 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
25893 {
25894 	tcp_timer_t *tcpt;
25895 	conn_t *connp = (conn_t *)arg;
25896 	tcp_t *tcp = connp->conn_tcp;
25897 
25898 	tcpt = (tcp_timer_t *)mp->b_rptr;
25899 	ASSERT(connp == tcpt->connp);
25900 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
25901 
25902 	/*
25903 	 * If the TCP has reached the closed state, don't proceed any
25904 	 * further. This TCP logically does not exist on the system.
25905 	 * tcpt_proc could for example access queues, that have already
25906 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
25907 	 */
25908 	if (tcp->tcp_state != TCPS_CLOSED) {
25909 		(*tcpt->tcpt_proc)(connp);
25910 	} else {
25911 		tcp->tcp_timer_tid = 0;
25912 	}
25913 	tcp_timer_free(connp->conn_tcp, mp);
25914 }
25915 
25916 /*
25917  * There is potential race with untimeout and the handler firing at the same
25918  * time. The mblock may be freed by the handler while we are trying to use
25919  * it. But since both should execute on the same squeue, this race should not
25920  * occur.
25921  */
25922 clock_t
25923 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
25924 {
25925 	mblk_t	*mp = (mblk_t *)id;
25926 	tcp_timer_t *tcpt;
25927 	clock_t delta;
25928 
25929 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
25930 
25931 	if (mp == NULL)
25932 		return (-1);
25933 
25934 	tcpt = (tcp_timer_t *)mp->b_rptr;
25935 	ASSERT(tcpt->connp == connp);
25936 
25937 	delta = untimeout_default(tcpt->tcpt_tid, 0);
25938 
25939 	if (delta >= 0) {
25940 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
25941 		tcp_timer_free(connp->conn_tcp, mp);
25942 		CONN_DEC_REF(connp);
25943 	}
25944 
25945 	return (delta);
25946 }
25947 
25948 /*
25949  * Allocate space for the timer event. The allocation looks like mblk, but it is
25950  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25951  *
25952  * Dealing with failures: If we can't allocate from the timer cache we try
25953  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25954  * points to b_rptr.
25955  * If we can't allocate anything using allocb_tryhard(), we perform a last
25956  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25957  * save the actual allocation size in b_datap.
25958  */
25959 mblk_t *
25960 tcp_timermp_alloc(int kmflags)
25961 {
25962 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25963 	    kmflags & ~KM_PANIC);
25964 
25965 	if (mp != NULL) {
25966 		mp->b_next = mp->b_prev = NULL;
25967 		mp->b_rptr = (uchar_t *)(&mp[1]);
25968 		mp->b_wptr = NULL;
25969 		mp->b_datap = NULL;
25970 		mp->b_queue = NULL;
25971 		mp->b_cont = NULL;
25972 	} else if (kmflags & KM_PANIC) {
25973 		/*
25974 		 * Failed to allocate memory for the timer. Try allocating from
25975 		 * dblock caches.
25976 		 */
25977 		/* ipclassifier calls this from a constructor - hence no tcps */
25978 		TCP_G_STAT(tcp_timermp_allocfail);
25979 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25980 		if (mp == NULL) {
25981 			size_t size = 0;
25982 			/*
25983 			 * Memory is really low. Try tryhard allocation.
25984 			 *
25985 			 * ipclassifier calls this from a constructor -
25986 			 * hence no tcps
25987 			 */
25988 			TCP_G_STAT(tcp_timermp_allocdblfail);
25989 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25990 			    sizeof (tcp_timer_t), &size, kmflags);
25991 			mp->b_rptr = (uchar_t *)(&mp[1]);
25992 			mp->b_next = mp->b_prev = NULL;
25993 			mp->b_wptr = (uchar_t *)-1;
25994 			mp->b_datap = (dblk_t *)size;
25995 			mp->b_queue = NULL;
25996 			mp->b_cont = NULL;
25997 		}
25998 		ASSERT(mp->b_wptr != NULL);
25999 	}
26000 	/* ipclassifier calls this from a constructor - hence no tcps */
26001 	TCP_G_DBGSTAT(tcp_timermp_alloced);
26002 
26003 	return (mp);
26004 }
26005 
26006 /*
26007  * Free per-tcp timer cache.
26008  * It can only contain entries from tcp_timercache.
26009  */
26010 void
26011 tcp_timermp_free(tcp_t *tcp)
26012 {
26013 	mblk_t *mp;
26014 
26015 	while ((mp = tcp->tcp_timercache) != NULL) {
26016 		ASSERT(mp->b_wptr == NULL);
26017 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
26018 		kmem_cache_free(tcp_timercache, mp);
26019 	}
26020 }
26021 
26022 /*
26023  * Free timer event. Put it on the per-tcp timer cache if there is not too many
26024  * events there already (currently at most two events are cached).
26025  * If the event is not allocated from the timer cache, free it right away.
26026  */
26027 static void
26028 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
26029 {
26030 	mblk_t *mp1 = tcp->tcp_timercache;
26031 
26032 	if (mp->b_wptr != NULL) {
26033 		/*
26034 		 * This allocation is not from a timer cache, free it right
26035 		 * away.
26036 		 */
26037 		if (mp->b_wptr != (uchar_t *)-1)
26038 			freeb(mp);
26039 		else
26040 			kmem_free(mp, (size_t)mp->b_datap);
26041 	} else if (mp1 == NULL || mp1->b_next == NULL) {
26042 		/* Cache this timer block for future allocations */
26043 		mp->b_rptr = (uchar_t *)(&mp[1]);
26044 		mp->b_next = mp1;
26045 		tcp->tcp_timercache = mp;
26046 	} else {
26047 		kmem_cache_free(tcp_timercache, mp);
26048 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
26049 	}
26050 }
26051 
26052 /*
26053  * End of TCP Timers implementation.
26054  */
26055 
26056 /*
26057  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
26058  * on the specified backing STREAMS q. Note, the caller may make the
26059  * decision to call based on the tcp_t.tcp_flow_stopped value which
26060  * when check outside the q's lock is only an advisory check ...
26061  */
26062 void
26063 tcp_setqfull(tcp_t *tcp)
26064 {
26065 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26066 	conn_t	*connp = tcp->tcp_connp;
26067 
26068 	if (tcp->tcp_closed)
26069 		return;
26070 
26071 	if (IPCL_IS_NONSTR(connp)) {
26072 		(*connp->conn_upcalls->su_txq_full)
26073 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
26074 		tcp->tcp_flow_stopped = B_TRUE;
26075 	} else {
26076 		queue_t *q = tcp->tcp_wq;
26077 
26078 		if (!(q->q_flag & QFULL)) {
26079 			mutex_enter(QLOCK(q));
26080 			if (!(q->q_flag & QFULL)) {
26081 				/* still need to set QFULL */
26082 				q->q_flag |= QFULL;
26083 				tcp->tcp_flow_stopped = B_TRUE;
26084 				mutex_exit(QLOCK(q));
26085 				TCP_STAT(tcps, tcp_flwctl_on);
26086 			} else {
26087 				mutex_exit(QLOCK(q));
26088 			}
26089 		}
26090 	}
26091 }
26092 
26093 void
26094 tcp_clrqfull(tcp_t *tcp)
26095 {
26096 	conn_t  *connp = tcp->tcp_connp;
26097 
26098 	if (tcp->tcp_closed)
26099 		return;
26100 
26101 	if (IPCL_IS_NONSTR(connp)) {
26102 		(*connp->conn_upcalls->su_txq_full)
26103 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
26104 		tcp->tcp_flow_stopped = B_FALSE;
26105 	} else {
26106 		queue_t *q = tcp->tcp_wq;
26107 
26108 		if (q->q_flag & QFULL) {
26109 			mutex_enter(QLOCK(q));
26110 			if (q->q_flag & QFULL) {
26111 				q->q_flag &= ~QFULL;
26112 				tcp->tcp_flow_stopped = B_FALSE;
26113 				mutex_exit(QLOCK(q));
26114 				if (q->q_flag & QWANTW)
26115 					qbackenable(q, 0);
26116 			} else {
26117 				mutex_exit(QLOCK(q));
26118 			}
26119 		}
26120 	}
26121 }
26122 
26123 /*
26124  * kstats related to squeues i.e. not per IP instance
26125  */
26126 static void *
26127 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26128 {
26129 	kstat_t *ksp;
26130 
26131 	tcp_g_stat_t template = {
26132 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26133 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
26134 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
26135 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
26136 	};
26137 
26138 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
26139 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26140 	    KSTAT_FLAG_VIRTUAL);
26141 
26142 	if (ksp == NULL)
26143 		return (NULL);
26144 
26145 	bcopy(&template, tcp_g_statp, sizeof (template));
26146 	ksp->ks_data = (void *)tcp_g_statp;
26147 
26148 	kstat_install(ksp);
26149 	return (ksp);
26150 }
26151 
26152 static void
26153 tcp_g_kstat_fini(kstat_t *ksp)
26154 {
26155 	if (ksp != NULL) {
26156 		kstat_delete(ksp);
26157 	}
26158 }
26159 
26160 
26161 static void *
26162 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
26163 {
26164 	kstat_t *ksp;
26165 
26166 	tcp_stat_t template = {
26167 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
26168 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
26169 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
26170 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
26171 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
26172 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
26173 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
26174 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
26175 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
26176 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
26177 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
26178 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
26179 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
26180 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
26181 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
26182 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
26183 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
26184 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
26185 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
26186 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
26187 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
26188 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
26189 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
26190 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
26191 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
26192 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
26193 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
26194 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
26195 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
26196 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
26197 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
26198 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
26199 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
26200 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
26201 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
26202 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
26203 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
26204 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
26205 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
26206 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
26207 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
26208 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
26209 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
26210 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
26211 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
26212 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
26213 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
26214 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
26215 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
26216 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
26217 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
26218 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
26219 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
26220 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
26221 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
26222 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
26223 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
26224 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
26225 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
26226 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
26227 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
26228 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
26229 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
26230 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
26231 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
26232 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
26233 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
26234 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
26235 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
26236 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
26237 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
26238 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
26239 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
26240 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
26241 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
26242 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
26243 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
26244 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
26245 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
26246 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
26247 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
26248 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
26249 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
26250 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
26251 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
26252 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
26253 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
26254 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
26255 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
26256 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
26257 	};
26258 
26259 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
26260 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26261 	    KSTAT_FLAG_VIRTUAL, stackid);
26262 
26263 	if (ksp == NULL)
26264 		return (NULL);
26265 
26266 	bcopy(&template, tcps_statisticsp, sizeof (template));
26267 	ksp->ks_data = (void *)tcps_statisticsp;
26268 	ksp->ks_private = (void *)(uintptr_t)stackid;
26269 
26270 	kstat_install(ksp);
26271 	return (ksp);
26272 }
26273 
26274 static void
26275 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
26276 {
26277 	if (ksp != NULL) {
26278 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26279 		kstat_delete_netstack(ksp, stackid);
26280 	}
26281 }
26282 
26283 /*
26284  * TCP Kstats implementation
26285  */
26286 static void *
26287 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
26288 {
26289 	kstat_t	*ksp;
26290 
26291 	tcp_named_kstat_t template = {
26292 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
26293 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
26294 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
26295 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
26296 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
26297 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
26298 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
26299 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
26300 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
26301 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
26302 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
26303 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
26304 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
26305 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
26306 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
26307 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
26308 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
26309 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
26310 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
26311 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
26312 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
26313 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
26314 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
26315 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
26316 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
26317 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
26318 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
26319 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
26320 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
26321 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
26322 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
26323 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
26324 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
26325 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
26326 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
26327 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
26328 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
26329 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
26330 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
26331 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
26332 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
26333 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
26334 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
26335 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
26336 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
26337 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
26338 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
26339 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
26340 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
26341 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
26342 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
26343 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
26344 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
26345 	};
26346 
26347 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
26348 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
26349 
26350 	if (ksp == NULL)
26351 		return (NULL);
26352 
26353 	template.rtoAlgorithm.value.ui32 = 4;
26354 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
26355 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
26356 	template.maxConn.value.i32 = -1;
26357 
26358 	bcopy(&template, ksp->ks_data, sizeof (template));
26359 	ksp->ks_update = tcp_kstat_update;
26360 	ksp->ks_private = (void *)(uintptr_t)stackid;
26361 
26362 	kstat_install(ksp);
26363 	return (ksp);
26364 }
26365 
26366 static void
26367 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
26368 {
26369 	if (ksp != NULL) {
26370 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26371 		kstat_delete_netstack(ksp, stackid);
26372 	}
26373 }
26374 
26375 static int
26376 tcp_kstat_update(kstat_t *kp, int rw)
26377 {
26378 	tcp_named_kstat_t *tcpkp;
26379 	tcp_t		*tcp;
26380 	connf_t		*connfp;
26381 	conn_t		*connp;
26382 	int 		i;
26383 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
26384 	netstack_t	*ns;
26385 	tcp_stack_t	*tcps;
26386 	ip_stack_t	*ipst;
26387 
26388 	if ((kp == NULL) || (kp->ks_data == NULL))
26389 		return (EIO);
26390 
26391 	if (rw == KSTAT_WRITE)
26392 		return (EACCES);
26393 
26394 	ns = netstack_find_by_stackid(stackid);
26395 	if (ns == NULL)
26396 		return (-1);
26397 	tcps = ns->netstack_tcp;
26398 	if (tcps == NULL) {
26399 		netstack_rele(ns);
26400 		return (-1);
26401 	}
26402 
26403 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
26404 
26405 	tcpkp->currEstab.value.ui32 = 0;
26406 
26407 	ipst = ns->netstack_ip;
26408 
26409 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
26410 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
26411 		connp = NULL;
26412 		while ((connp =
26413 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
26414 			tcp = connp->conn_tcp;
26415 			switch (tcp_snmp_state(tcp)) {
26416 			case MIB2_TCP_established:
26417 			case MIB2_TCP_closeWait:
26418 				tcpkp->currEstab.value.ui32++;
26419 				break;
26420 			}
26421 		}
26422 	}
26423 
26424 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
26425 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
26426 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
26427 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
26428 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
26429 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
26430 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
26431 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
26432 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
26433 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
26434 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
26435 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
26436 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
26437 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
26438 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
26439 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
26440 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
26441 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
26442 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
26443 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
26444 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
26445 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
26446 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
26447 	tcpkp->inDataInorderSegs.value.ui32 =
26448 	    tcps->tcps_mib.tcpInDataInorderSegs;
26449 	tcpkp->inDataInorderBytes.value.ui32 =
26450 	    tcps->tcps_mib.tcpInDataInorderBytes;
26451 	tcpkp->inDataUnorderSegs.value.ui32 =
26452 	    tcps->tcps_mib.tcpInDataUnorderSegs;
26453 	tcpkp->inDataUnorderBytes.value.ui32 =
26454 	    tcps->tcps_mib.tcpInDataUnorderBytes;
26455 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
26456 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
26457 	tcpkp->inDataPartDupSegs.value.ui32 =
26458 	    tcps->tcps_mib.tcpInDataPartDupSegs;
26459 	tcpkp->inDataPartDupBytes.value.ui32 =
26460 	    tcps->tcps_mib.tcpInDataPartDupBytes;
26461 	tcpkp->inDataPastWinSegs.value.ui32 =
26462 	    tcps->tcps_mib.tcpInDataPastWinSegs;
26463 	tcpkp->inDataPastWinBytes.value.ui32 =
26464 	    tcps->tcps_mib.tcpInDataPastWinBytes;
26465 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
26466 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
26467 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
26468 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
26469 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
26470 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
26471 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
26472 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
26473 	tcpkp->timKeepaliveProbe.value.ui32 =
26474 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
26475 	tcpkp->timKeepaliveDrop.value.ui32 =
26476 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
26477 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
26478 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
26479 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
26480 	tcpkp->outSackRetransSegs.value.ui32 =
26481 	    tcps->tcps_mib.tcpOutSackRetransSegs;
26482 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
26483 
26484 	netstack_rele(ns);
26485 	return (0);
26486 }
26487 
26488 void
26489 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
26490 {
26491 	uint16_t	hdr_len;
26492 	ipha_t		*ipha;
26493 	uint8_t		*nexthdrp;
26494 	tcph_t		*tcph;
26495 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26496 
26497 	/* Already has an eager */
26498 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26499 		TCP_STAT(tcps, tcp_reinput_syn);
26500 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26501 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
26502 		return;
26503 	}
26504 
26505 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
26506 	case IPV4_VERSION:
26507 		ipha = (ipha_t *)mp->b_rptr;
26508 		hdr_len = IPH_HDR_LENGTH(ipha);
26509 		break;
26510 	case IPV6_VERSION:
26511 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
26512 		    &hdr_len, &nexthdrp)) {
26513 			CONN_DEC_REF(connp);
26514 			freemsg(mp);
26515 			return;
26516 		}
26517 		break;
26518 	}
26519 
26520 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
26521 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
26522 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
26523 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
26524 	}
26525 
26526 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26527 	    SQ_FILL, SQTAG_TCP_REINPUT);
26528 }
26529 
26530 static int
26531 tcp_squeue_switch(int val)
26532 {
26533 	int rval = SQ_FILL;
26534 
26535 	switch (val) {
26536 	case 1:
26537 		rval = SQ_NODRAIN;
26538 		break;
26539 	case 2:
26540 		rval = SQ_PROCESS;
26541 		break;
26542 	default:
26543 		break;
26544 	}
26545 	return (rval);
26546 }
26547 
26548 /*
26549  * This is called once for each squeue - globally for all stack
26550  * instances.
26551  */
26552 static void
26553 tcp_squeue_add(squeue_t *sqp)
26554 {
26555 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
26556 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
26557 
26558 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
26559 	tcp_time_wait->tcp_time_wait_tid =
26560 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
26561 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
26562 	    CALLOUT_FLAG_ROUNDUP);
26563 	if (tcp_free_list_max_cnt == 0) {
26564 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
26565 		    max_ncpus : boot_max_ncpus);
26566 
26567 		/*
26568 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
26569 		 */
26570 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
26571 		    (tcp_ncpus * sizeof (tcp_t) * 100);
26572 	}
26573 	tcp_time_wait->tcp_free_list_cnt = 0;
26574 }
26575 
26576 static int
26577 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error)
26578 {
26579 	mblk_t	*ire_mp = NULL;
26580 	mblk_t	*syn_mp;
26581 	mblk_t	*mdti;
26582 	mblk_t	*lsoi;
26583 	int	retval;
26584 	tcph_t	*tcph;
26585 	uint32_t	mss;
26586 	queue_t	*q = tcp->tcp_rq;
26587 	conn_t	*connp = tcp->tcp_connp;
26588 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26589 
26590 	if (error == 0) {
26591 		/*
26592 		 * Adapt Multidata information, if any.  The
26593 		 * following tcp_mdt_update routine will free
26594 		 * the message.
26595 		 */
26596 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
26597 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
26598 			    b_rptr)->mdt_capab, B_TRUE);
26599 			freemsg(mdti);
26600 		}
26601 
26602 		/*
26603 		 * Check to update LSO information with tcp, and
26604 		 * tcp_lso_update routine will free the message.
26605 		 */
26606 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
26607 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
26608 			    b_rptr)->lso_capab);
26609 			freemsg(lsoi);
26610 		}
26611 
26612 		/* Get the IRE, if we had requested for it */
26613 		if (mp != NULL)
26614 			ire_mp = tcp_ire_mp(&mp);
26615 
26616 		if (tcp->tcp_hard_binding) {
26617 			tcp->tcp_hard_binding = B_FALSE;
26618 			tcp->tcp_hard_bound = B_TRUE;
26619 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
26620 			if (retval != 0) {
26621 				error = EADDRINUSE;
26622 				goto bind_failed;
26623 			}
26624 		} else {
26625 			if (ire_mp != NULL)
26626 				freeb(ire_mp);
26627 			goto after_syn_sent;
26628 		}
26629 
26630 		retval = tcp_adapt_ire(tcp, ire_mp);
26631 		if (ire_mp != NULL)
26632 			freeb(ire_mp);
26633 		if (retval == 0) {
26634 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
26635 			    ENETUNREACH : EADDRNOTAVAIL);
26636 			goto ipcl_rm;
26637 		}
26638 		/*
26639 		 * Don't let an endpoint connect to itself.
26640 		 * Also checked in tcp_connect() but that
26641 		 * check can't handle the case when the
26642 		 * local IP address is INADDR_ANY.
26643 		 */
26644 		if (tcp->tcp_ipversion == IPV4_VERSION) {
26645 			if ((tcp->tcp_ipha->ipha_dst ==
26646 			    tcp->tcp_ipha->ipha_src) &&
26647 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26648 			    tcp->tcp_tcph->th_fport))) {
26649 				error = EADDRNOTAVAIL;
26650 				goto ipcl_rm;
26651 			}
26652 		} else {
26653 			if (IN6_ARE_ADDR_EQUAL(
26654 			    &tcp->tcp_ip6h->ip6_dst,
26655 			    &tcp->tcp_ip6h->ip6_src) &&
26656 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26657 			    tcp->tcp_tcph->th_fport))) {
26658 				error = EADDRNOTAVAIL;
26659 				goto ipcl_rm;
26660 			}
26661 		}
26662 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
26663 		/*
26664 		 * This should not be possible!  Just for
26665 		 * defensive coding...
26666 		 */
26667 		if (tcp->tcp_state != TCPS_SYN_SENT)
26668 			goto after_syn_sent;
26669 
26670 		if (is_system_labeled() &&
26671 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
26672 			error = EHOSTUNREACH;
26673 			goto ipcl_rm;
26674 		}
26675 
26676 		/*
26677 		 * tcp_adapt_ire() does not adjust
26678 		 * for TCP/IP header length.
26679 		 */
26680 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
26681 
26682 		/*
26683 		 * Just make sure our rwnd is at
26684 		 * least tcp_recv_hiwat_mss * MSS
26685 		 * large, and round up to the nearest
26686 		 * MSS.
26687 		 *
26688 		 * We do the round up here because
26689 		 * we need to get the interface
26690 		 * MTU first before we can do the
26691 		 * round up.
26692 		 */
26693 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
26694 		    tcps->tcps_recv_hiwat_minmss * mss);
26695 		if (!IPCL_IS_NONSTR(connp))
26696 			q->q_hiwat = tcp->tcp_rwnd;
26697 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
26698 		tcp_set_ws_value(tcp);
26699 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
26700 		    tcp->tcp_tcph->th_win);
26701 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
26702 			tcp->tcp_snd_ws_ok = B_TRUE;
26703 
26704 		/*
26705 		 * Set tcp_snd_ts_ok to true
26706 		 * so that tcp_xmit_mp will
26707 		 * include the timestamp
26708 		 * option in the SYN segment.
26709 		 */
26710 		if (tcps->tcps_tstamp_always ||
26711 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
26712 			tcp->tcp_snd_ts_ok = B_TRUE;
26713 		}
26714 
26715 		/*
26716 		 * tcp_snd_sack_ok can be set in
26717 		 * tcp_adapt_ire() if the sack metric
26718 		 * is set.  So check it here also.
26719 		 */
26720 		if (tcps->tcps_sack_permitted == 2 ||
26721 		    tcp->tcp_snd_sack_ok) {
26722 			if (tcp->tcp_sack_info == NULL) {
26723 				tcp->tcp_sack_info =
26724 				    kmem_cache_alloc(tcp_sack_info_cache,
26725 				    KM_SLEEP);
26726 			}
26727 			tcp->tcp_snd_sack_ok = B_TRUE;
26728 		}
26729 
26730 		/*
26731 		 * Should we use ECN?  Note that the current
26732 		 * default value (SunOS 5.9) of tcp_ecn_permitted
26733 		 * is 1.  The reason for doing this is that there
26734 		 * are equipments out there that will drop ECN
26735 		 * enabled IP packets.  Setting it to 1 avoids
26736 		 * compatibility problems.
26737 		 */
26738 		if (tcps->tcps_ecn_permitted == 2)
26739 			tcp->tcp_ecn_ok = B_TRUE;
26740 
26741 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
26742 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
26743 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
26744 		if (syn_mp) {
26745 			cred_t *cr;
26746 			pid_t pid;
26747 
26748 			/*
26749 			 * Obtain the credential from the
26750 			 * thread calling connect().
26751 			 * If none can be found, default to
26752 			 * the creator  of the socket.
26753 			 */
26754 			if (mp == NULL ||
26755 			    (cr = DB_CRED(mp)) == NULL) {
26756 				cr = tcp->tcp_cred;
26757 				pid = tcp->tcp_cpid;
26758 			} else {
26759 				pid = DB_CPID(mp);
26760 			}
26761 
26762 			mblk_setcred(syn_mp, cr);
26763 			DB_CPID(syn_mp) = pid;
26764 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
26765 		}
26766 	after_syn_sent:
26767 		/*
26768 		 * A trailer mblk indicates a waiting client upstream.
26769 		 * We complete here the processing begun in
26770 		 * either tcp_bind() or tcp_connect() by passing
26771 		 * upstream the reply message they supplied.
26772 		 */
26773 		if (mp != NULL) {
26774 			ASSERT(mp->b_cont == NULL);
26775 			freeb(mp);
26776 		}
26777 		return (error);
26778 	} else {
26779 		/* error */
26780 		if (tcp->tcp_debug) {
26781 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
26782 			    "tcp_post_ip_bind: error == %d", error);
26783 		}
26784 		if (mp != NULL) {
26785 			freeb(mp);
26786 		}
26787 	}
26788 
26789 ipcl_rm:
26790 	/*
26791 	 * Need to unbind with classifier since we were just
26792 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
26793 	 */
26794 	tcp->tcp_hard_bound = B_FALSE;
26795 	tcp->tcp_hard_binding = B_FALSE;
26796 
26797 	ipcl_hash_remove(connp);
26798 
26799 bind_failed:
26800 	tcp->tcp_state = TCPS_IDLE;
26801 	if (tcp->tcp_ipversion == IPV4_VERSION)
26802 		tcp->tcp_ipha->ipha_src = 0;
26803 	else
26804 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
26805 	/*
26806 	 * Copy of the src addr. in tcp_t is needed since
26807 	 * the lookup funcs. can only look at tcp_t
26808 	 */
26809 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
26810 
26811 	tcph = tcp->tcp_tcph;
26812 	tcph->th_lport[0] = 0;
26813 	tcph->th_lport[1] = 0;
26814 	tcp_bind_hash_remove(tcp);
26815 	bzero(&connp->u_port, sizeof (connp->u_port));
26816 	/* blow away saved option results if any */
26817 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26818 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26819 
26820 	conn_delete_ire(tcp->tcp_connp, NULL);
26821 
26822 	return (error);
26823 }
26824 
26825 static int
26826 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
26827     boolean_t bind_to_req_port_only, cred_t *cr)
26828 {
26829 	in_port_t	mlp_port;
26830 	mlp_type_t 	addrtype, mlptype;
26831 	boolean_t	user_specified;
26832 	in_port_t	allocated_port;
26833 	in_port_t	requested_port = *requested_port_ptr;
26834 	conn_t		*connp;
26835 	zone_t		*zone;
26836 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26837 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
26838 
26839 	/*
26840 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
26841 	 */
26842 	if (cr == NULL)
26843 		cr = tcp->tcp_cred;
26844 	/*
26845 	 * Get a valid port (within the anonymous range and should not
26846 	 * be a privileged one) to use if the user has not given a port.
26847 	 * If multiple threads are here, they may all start with
26848 	 * with the same initial port. But, it should be fine as long as
26849 	 * tcp_bindi will ensure that no two threads will be assigned
26850 	 * the same port.
26851 	 *
26852 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
26853 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
26854 	 * unless TCP_ANONPRIVBIND option is set.
26855 	 */
26856 	mlptype = mlptSingle;
26857 	mlp_port = requested_port;
26858 	if (requested_port == 0) {
26859 		requested_port = tcp->tcp_anon_priv_bind ?
26860 		    tcp_get_next_priv_port(tcp) :
26861 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
26862 		    tcp, B_TRUE);
26863 		if (requested_port == 0) {
26864 			return (-TNOADDR);
26865 		}
26866 		user_specified = B_FALSE;
26867 
26868 		/*
26869 		 * If the user went through one of the RPC interfaces to create
26870 		 * this socket and RPC is MLP in this zone, then give him an
26871 		 * anonymous MLP.
26872 		 */
26873 		connp = tcp->tcp_connp;
26874 		if (connp->conn_anon_mlp && is_system_labeled()) {
26875 			zone = crgetzone(cr);
26876 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26877 			    IPV6_VERSION, &v6addr,
26878 			    tcps->tcps_netstack->netstack_ip);
26879 			if (addrtype == mlptSingle) {
26880 				return (-TNOADDR);
26881 			}
26882 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26883 			    PMAPPORT, addrtype);
26884 			mlp_port = PMAPPORT;
26885 		}
26886 	} else {
26887 		int i;
26888 		boolean_t priv = B_FALSE;
26889 
26890 		/*
26891 		 * If the requested_port is in the well-known privileged range,
26892 		 * verify that the stream was opened by a privileged user.
26893 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
26894 		 * but instead the code relies on:
26895 		 * - the fact that the address of the array and its size never
26896 		 *   changes
26897 		 * - the atomic assignment of the elements of the array
26898 		 */
26899 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
26900 			priv = B_TRUE;
26901 		} else {
26902 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
26903 				if (requested_port ==
26904 				    tcps->tcps_g_epriv_ports[i]) {
26905 					priv = B_TRUE;
26906 					break;
26907 				}
26908 			}
26909 		}
26910 		if (priv) {
26911 			if (secpolicy_net_privaddr(cr, requested_port,
26912 			    IPPROTO_TCP) != 0) {
26913 				if (tcp->tcp_debug) {
26914 					(void) strlog(TCP_MOD_ID, 0, 1,
26915 					    SL_ERROR|SL_TRACE,
26916 					    "tcp_bind: no priv for port %d",
26917 					    requested_port);
26918 				}
26919 				return (-TACCES);
26920 			}
26921 		}
26922 		user_specified = B_TRUE;
26923 
26924 		connp = tcp->tcp_connp;
26925 		if (is_system_labeled()) {
26926 			zone = crgetzone(cr);
26927 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26928 			    IPV6_VERSION, &v6addr,
26929 			    tcps->tcps_netstack->netstack_ip);
26930 			if (addrtype == mlptSingle) {
26931 				return (-TNOADDR);
26932 			}
26933 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26934 			    requested_port, addrtype);
26935 		}
26936 	}
26937 
26938 	if (mlptype != mlptSingle) {
26939 		if (secpolicy_net_bindmlp(cr) != 0) {
26940 			if (tcp->tcp_debug) {
26941 				(void) strlog(TCP_MOD_ID, 0, 1,
26942 				    SL_ERROR|SL_TRACE,
26943 				    "tcp_bind: no priv for multilevel port %d",
26944 				    requested_port);
26945 			}
26946 			return (-TACCES);
26947 		}
26948 
26949 		/*
26950 		 * If we're specifically binding a shared IP address and the
26951 		 * port is MLP on shared addresses, then check to see if this
26952 		 * zone actually owns the MLP.  Reject if not.
26953 		 */
26954 		if (mlptype == mlptShared && addrtype == mlptShared) {
26955 			/*
26956 			 * No need to handle exclusive-stack zones since
26957 			 * ALL_ZONES only applies to the shared stack.
26958 			 */
26959 			zoneid_t mlpzone;
26960 
26961 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26962 			    htons(mlp_port));
26963 			if (connp->conn_zoneid != mlpzone) {
26964 				if (tcp->tcp_debug) {
26965 					(void) strlog(TCP_MOD_ID, 0, 1,
26966 					    SL_ERROR|SL_TRACE,
26967 					    "tcp_bind: attempt to bind port "
26968 					    "%d on shared addr in zone %d "
26969 					    "(should be %d)",
26970 					    mlp_port, connp->conn_zoneid,
26971 					    mlpzone);
26972 				}
26973 				return (-TACCES);
26974 			}
26975 		}
26976 
26977 		if (!user_specified) {
26978 			int err;
26979 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26980 			    requested_port, B_TRUE);
26981 			if (err != 0) {
26982 				if (tcp->tcp_debug) {
26983 					(void) strlog(TCP_MOD_ID, 0, 1,
26984 					    SL_ERROR|SL_TRACE,
26985 					    "tcp_bind: cannot establish anon "
26986 					    "MLP for port %d",
26987 					    requested_port);
26988 				}
26989 				return (err);
26990 			}
26991 			connp->conn_anon_port = B_TRUE;
26992 		}
26993 		connp->conn_mlp_type = mlptype;
26994 	}
26995 
26996 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26997 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26998 
26999 	if (allocated_port == 0) {
27000 		connp->conn_mlp_type = mlptSingle;
27001 		if (connp->conn_anon_port) {
27002 			connp->conn_anon_port = B_FALSE;
27003 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
27004 			    requested_port, B_FALSE);
27005 		}
27006 		if (bind_to_req_port_only) {
27007 			if (tcp->tcp_debug) {
27008 				(void) strlog(TCP_MOD_ID, 0, 1,
27009 				    SL_ERROR|SL_TRACE,
27010 				    "tcp_bind: requested addr busy");
27011 			}
27012 			return (-TADDRBUSY);
27013 		} else {
27014 			/* If we are out of ports, fail the bind. */
27015 			if (tcp->tcp_debug) {
27016 				(void) strlog(TCP_MOD_ID, 0, 1,
27017 				    SL_ERROR|SL_TRACE,
27018 				    "tcp_bind: out of ports?");
27019 			}
27020 			return (-TNOADDR);
27021 		}
27022 	}
27023 
27024 	/* Pass the allocated port back */
27025 	*requested_port_ptr = allocated_port;
27026 	return (0);
27027 }
27028 
27029 static int
27030 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
27031     boolean_t bind_to_req_port_only)
27032 {
27033 	tcp_t	*tcp = connp->conn_tcp;
27034 
27035 	sin_t	*sin;
27036 	sin6_t  *sin6;
27037 	sin6_t		sin6addr;
27038 	in_port_t requested_port;
27039 	ipaddr_t	v4addr;
27040 	in6_addr_t	v6addr;
27041 	uint_t	origipversion;
27042 	int	error = 0;
27043 
27044 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
27045 
27046 	if (tcp->tcp_state == TCPS_BOUND) {
27047 		return (0);
27048 	} else if (tcp->tcp_state > TCPS_BOUND) {
27049 		if (tcp->tcp_debug) {
27050 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27051 			    "tcp_bind: bad state, %d", tcp->tcp_state);
27052 		}
27053 		return (-TOUTSTATE);
27054 	}
27055 	origipversion = tcp->tcp_ipversion;
27056 
27057 	if (sa != NULL && !OK_32PTR((char *)sa)) {
27058 		if (tcp->tcp_debug) {
27059 			(void) strlog(TCP_MOD_ID, 0, 1,
27060 			    SL_ERROR|SL_TRACE,
27061 			    "tcp_bind: bad address parameter, "
27062 			    "address %p, len %d",
27063 			    (void *)sa, len);
27064 		}
27065 		return (-TPROTO);
27066 	}
27067 
27068 	switch (len) {
27069 	case 0:		/* request for a generic port */
27070 		if (tcp->tcp_family == AF_INET) {
27071 			sin = (sin_t *)&sin6addr;
27072 			*sin = sin_null;
27073 			sin->sin_family = AF_INET;
27074 			tcp->tcp_ipversion = IPV4_VERSION;
27075 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
27076 		} else {
27077 			ASSERT(tcp->tcp_family == AF_INET6);
27078 			sin6 = (sin6_t *)&sin6addr;
27079 			*sin6 = sin6_null;
27080 			sin6->sin6_family = AF_INET6;
27081 			tcp->tcp_ipversion = IPV6_VERSION;
27082 			V6_SET_ZERO(v6addr);
27083 		}
27084 		requested_port = 0;
27085 		break;
27086 
27087 	case sizeof (sin_t):	/* Complete IPv4 address */
27088 		sin = (sin_t *)sa;
27089 		/*
27090 		 * With sockets sockfs will accept bogus sin_family in
27091 		 * bind() and replace it with the family used in the socket
27092 		 * call.
27093 		 */
27094 		if (sin->sin_family != AF_INET ||
27095 		    tcp->tcp_family != AF_INET) {
27096 			return (EAFNOSUPPORT);
27097 		}
27098 		requested_port = ntohs(sin->sin_port);
27099 		tcp->tcp_ipversion = IPV4_VERSION;
27100 		v4addr = sin->sin_addr.s_addr;
27101 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
27102 		break;
27103 
27104 	case sizeof (sin6_t): /* Complete IPv6 address */
27105 		sin6 = (sin6_t *)sa;
27106 		if (sin6->sin6_family != AF_INET6 ||
27107 		    tcp->tcp_family != AF_INET6) {
27108 			return (EAFNOSUPPORT);
27109 		}
27110 		requested_port = ntohs(sin6->sin6_port);
27111 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
27112 		    IPV4_VERSION : IPV6_VERSION;
27113 		v6addr = sin6->sin6_addr;
27114 		break;
27115 
27116 	default:
27117 		if (tcp->tcp_debug) {
27118 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27119 			    "tcp_bind: bad address length, %d", len);
27120 		}
27121 		return (EAFNOSUPPORT);
27122 		/* return (-TBADADDR); */
27123 	}
27124 
27125 	tcp->tcp_bound_source_v6 = v6addr;
27126 
27127 	/* Check for change in ipversion */
27128 	if (origipversion != tcp->tcp_ipversion) {
27129 		ASSERT(tcp->tcp_family == AF_INET6);
27130 		error = tcp->tcp_ipversion == IPV6_VERSION ?
27131 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
27132 		if (error) {
27133 			return (ENOMEM);
27134 		}
27135 	}
27136 
27137 	/*
27138 	 * Initialize family specific fields. Copy of the src addr.
27139 	 * in tcp_t is needed for the lookup funcs.
27140 	 */
27141 	if (tcp->tcp_ipversion == IPV6_VERSION) {
27142 		tcp->tcp_ip6h->ip6_src = v6addr;
27143 	} else {
27144 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
27145 	}
27146 	tcp->tcp_ip_src_v6 = v6addr;
27147 
27148 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
27149 
27150 	error = tcp_bind_select_lport(tcp, &requested_port,
27151 	    bind_to_req_port_only, cr);
27152 
27153 	return (error);
27154 }
27155 
27156 /*
27157  * Return unix error is tli error is TSYSERR, otherwise return a negative
27158  * tli error.
27159  */
27160 int
27161 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
27162     boolean_t bind_to_req_port_only)
27163 {
27164 	int error;
27165 	tcp_t *tcp = connp->conn_tcp;
27166 
27167 	if (tcp->tcp_state >= TCPS_BOUND) {
27168 		if (tcp->tcp_debug) {
27169 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27170 			    "tcp_bind: bad state, %d", tcp->tcp_state);
27171 		}
27172 		return (-TOUTSTATE);
27173 	}
27174 
27175 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
27176 	if (error != 0)
27177 		return (error);
27178 
27179 	ASSERT(tcp->tcp_state == TCPS_BOUND);
27180 
27181 	tcp->tcp_conn_req_max = 0;
27182 
27183 	/*
27184 	 * We need to make sure that the conn_recv is set to a non-null
27185 	 * value before we insert the conn into the classifier table.
27186 	 * This is to avoid a race with an incoming packet which does an
27187 	 * ipcl_classify().
27188 	 */
27189 	connp->conn_recv = tcp_conn_request;
27190 
27191 	if (tcp->tcp_family == AF_INET6) {
27192 		ASSERT(tcp->tcp_connp->conn_af_isv6);
27193 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27194 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
27195 	} else {
27196 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
27197 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
27198 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
27199 	}
27200 	return (tcp_post_ip_bind(tcp, NULL, error));
27201 }
27202 
27203 int
27204 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
27205     socklen_t len, cred_t *cr)
27206 {
27207 	int 		error;
27208 	conn_t		*connp = (conn_t *)proto_handle;
27209 	squeue_t	*sqp = connp->conn_sqp;
27210 
27211 	ASSERT(sqp != NULL);
27212 
27213 	error = squeue_synch_enter(sqp, connp, 0);
27214 	if (error != 0) {
27215 		/* failed to enter */
27216 		return (ENOSR);
27217 	}
27218 
27219 	/* binding to a NULL address really means unbind */
27220 	if (sa == NULL) {
27221 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
27222 			error = tcp_do_unbind(connp);
27223 		else
27224 			error = EINVAL;
27225 	} else {
27226 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
27227 	}
27228 
27229 	squeue_synch_exit(sqp, connp);
27230 
27231 	if (error < 0) {
27232 		if (error == -TOUTSTATE)
27233 			error = EINVAL;
27234 		else
27235 			error = proto_tlitosyserr(-error);
27236 	}
27237 
27238 	return (error);
27239 }
27240 
27241 /*
27242  * If the return value from this function is positive, it's a UNIX error.
27243  * Otherwise, if it's negative, then the absolute value is a TLI error.
27244  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
27245  */
27246 int
27247 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
27248     cred_t *cr, pid_t pid)
27249 {
27250 	tcp_t		*tcp = connp->conn_tcp;
27251 	sin_t		*sin = (sin_t *)sa;
27252 	sin6_t		*sin6 = (sin6_t *)sa;
27253 	ipaddr_t	*dstaddrp;
27254 	in_port_t	dstport;
27255 	uint_t		srcid;
27256 	int		error = 0;
27257 
27258 	switch (len) {
27259 	default:
27260 		/*
27261 		 * Should never happen
27262 		 */
27263 		return (EINVAL);
27264 
27265 	case sizeof (sin_t):
27266 		sin = (sin_t *)sa;
27267 		if (sin->sin_port == 0) {
27268 			return (-TBADADDR);
27269 		}
27270 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
27271 			return (EAFNOSUPPORT);
27272 		}
27273 		break;
27274 
27275 	case sizeof (sin6_t):
27276 		sin6 = (sin6_t *)sa;
27277 		if (sin6->sin6_port == 0) {
27278 			return (-TBADADDR);
27279 		}
27280 		break;
27281 	}
27282 	/*
27283 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
27284 	 * make sure that the template IP header in the tcp structure is an
27285 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
27286 	 * need to this before we call tcp_bindi() so that the port lookup
27287 	 * code will look for ports in the correct port space (IPv4 and
27288 	 * IPv6 have separate port spaces).
27289 	 */
27290 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
27291 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
27292 		int err = 0;
27293 
27294 		err = tcp_header_init_ipv4(tcp);
27295 			if (err != 0) {
27296 				error = ENOMEM;
27297 				goto connect_failed;
27298 			}
27299 		if (tcp->tcp_lport != 0)
27300 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
27301 	}
27302 
27303 	switch (tcp->tcp_state) {
27304 	case TCPS_LISTEN:
27305 		/*
27306 		 * Listening sockets are not allowed to issue connect().
27307 		 */
27308 		if (IPCL_IS_NONSTR(connp))
27309 			return (EOPNOTSUPP);
27310 		/* FALLTHRU */
27311 	case TCPS_IDLE:
27312 		/*
27313 		 * We support quick connect, refer to comments in
27314 		 * tcp_connect_*()
27315 		 */
27316 		/* FALLTHRU */
27317 	case TCPS_BOUND:
27318 		/*
27319 		 * We must bump the generation before the operation start.
27320 		 * This is done to ensure that any upcall made later on sends
27321 		 * up the right generation to the socket.
27322 		 */
27323 		SOCK_CONNID_BUMP(tcp->tcp_connid);
27324 
27325 		if (tcp->tcp_family == AF_INET6) {
27326 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
27327 				return (tcp_connect_ipv6(tcp,
27328 				    &sin6->sin6_addr,
27329 				    sin6->sin6_port, sin6->sin6_flowinfo,
27330 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
27331 				    cr, pid));
27332 			}
27333 			/*
27334 			 * Destination adress is mapped IPv6 address.
27335 			 * Source bound address should be unspecified or
27336 			 * IPv6 mapped address as well.
27337 			 */
27338 			if (!IN6_IS_ADDR_UNSPECIFIED(
27339 			    &tcp->tcp_bound_source_v6) &&
27340 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
27341 				return (EADDRNOTAVAIL);
27342 			}
27343 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
27344 			dstport = sin6->sin6_port;
27345 			srcid = sin6->__sin6_src_id;
27346 		} else {
27347 			dstaddrp = &sin->sin_addr.s_addr;
27348 			dstport = sin->sin_port;
27349 			srcid = 0;
27350 		}
27351 
27352 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
27353 		    pid);
27354 		break;
27355 	default:
27356 		return (-TOUTSTATE);
27357 	}
27358 	/*
27359 	 * Note: Code below is the "failure" case
27360 	 */
27361 connect_failed:
27362 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
27363 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
27364 	return (error);
27365 }
27366 
27367 int
27368 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
27369     socklen_t len, sock_connid_t *id, cred_t *cr)
27370 {
27371 	conn_t		*connp = (conn_t *)proto_handle;
27372 	tcp_t		*tcp = connp->conn_tcp;
27373 	squeue_t	*sqp = connp->conn_sqp;
27374 	int		error;
27375 
27376 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
27377 	if (error != 0) {
27378 		return (error);
27379 	}
27380 
27381 	error = squeue_synch_enter(sqp, connp, 0);
27382 	if (error != 0) {
27383 		/* failed to enter */
27384 		return (ENOSR);
27385 	}
27386 
27387 	/*
27388 	 * TCP supports quick connect, so no need to do an implicit bind
27389 	 */
27390 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
27391 	if (error == 0) {
27392 		*id = connp->conn_tcp->tcp_connid;
27393 	} else if (error < 0) {
27394 		if (error == -TOUTSTATE) {
27395 			switch (connp->conn_tcp->tcp_state) {
27396 			case TCPS_SYN_SENT:
27397 				error = EALREADY;
27398 				break;
27399 			case TCPS_ESTABLISHED:
27400 				error = EISCONN;
27401 				break;
27402 			case TCPS_LISTEN:
27403 				error = EOPNOTSUPP;
27404 				break;
27405 			default:
27406 				error = EINVAL;
27407 				break;
27408 			}
27409 		} else {
27410 			error = proto_tlitosyserr(-error);
27411 		}
27412 	}
27413 done:
27414 	squeue_synch_exit(sqp, connp);
27415 
27416 	return ((error == 0) ? EINPROGRESS : error);
27417 }
27418 
27419 /* ARGSUSED */
27420 sock_lower_handle_t
27421 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
27422     uint_t *smodep, int *errorp, int flags, cred_t *credp)
27423 {
27424 	conn_t		*connp;
27425 	boolean_t	isv6 = family == AF_INET6;
27426 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
27427 	    (proto != 0 && proto != IPPROTO_TCP)) {
27428 		*errorp = EPROTONOSUPPORT;
27429 		return (NULL);
27430 	}
27431 
27432 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
27433 	if (connp == NULL) {
27434 		return (NULL);
27435 	}
27436 
27437 	/*
27438 	 * Put the ref for TCP. Ref for IP was already put
27439 	 * by ipcl_conn_create. Also Make the conn_t globally
27440 	 * visible to walkers
27441 	 */
27442 	mutex_enter(&connp->conn_lock);
27443 	CONN_INC_REF_LOCKED(connp);
27444 	ASSERT(connp->conn_ref == 2);
27445 	connp->conn_state_flags &= ~CONN_INCIPIENT;
27446 
27447 	connp->conn_flags |= IPCL_NONSTR;
27448 	mutex_exit(&connp->conn_lock);
27449 
27450 	ASSERT(errorp != NULL);
27451 	*errorp = 0;
27452 	*sock_downcalls = &sock_tcp_downcalls;
27453 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
27454 	    SM_SENDFILESUPP;
27455 
27456 	return ((sock_lower_handle_t)connp);
27457 }
27458 
27459 /* ARGSUSED */
27460 void
27461 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
27462     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
27463 {
27464 	conn_t *connp = (conn_t *)proto_handle;
27465 	struct sock_proto_props sopp;
27466 
27467 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
27468 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
27469 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
27470 
27471 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
27472 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
27473 	sopp.sopp_maxpsz = INFPSZ;
27474 	sopp.sopp_maxblk = INFPSZ;
27475 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
27476 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
27477 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
27478 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
27479 	    tcp_rinfo.mi_minpsz;
27480 
27481 	connp->conn_upcalls = sock_upcalls;
27482 	connp->conn_upper_handle = sock_handle;
27483 
27484 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
27485 }
27486 
27487 /* ARGSUSED */
27488 int
27489 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
27490 {
27491 	conn_t *connp = (conn_t *)proto_handle;
27492 
27493 	tcp_close_common(connp, flags);
27494 
27495 	ip_close_helper_stream(connp);
27496 
27497 	/*
27498 	 * Drop IP's reference on the conn. This is the last reference
27499 	 * on the connp if the state was less than established. If the
27500 	 * connection has gone into timewait state, then we will have
27501 	 * one ref for the TCP and one more ref (total of two) for the
27502 	 * classifier connected hash list (a timewait connections stays
27503 	 * in connected hash till closed).
27504 	 *
27505 	 * We can't assert the references because there might be other
27506 	 * transient reference places because of some walkers or queued
27507 	 * packets in squeue for the timewait state.
27508 	 */
27509 	CONN_DEC_REF(connp);
27510 	return (0);
27511 }
27512 
27513 /* ARGSUSED */
27514 int
27515 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
27516     cred_t *cr)
27517 {
27518 	tcp_t		*tcp;
27519 	uint32_t	msize;
27520 	conn_t *connp = (conn_t *)proto_handle;
27521 	int32_t		tcpstate;
27522 
27523 	ASSERT(connp->conn_ref >= 2);
27524 
27525 	if (msg->msg_controllen != 0) {
27526 		return (EOPNOTSUPP);
27527 
27528 	}
27529 	switch (DB_TYPE(mp)) {
27530 	case M_DATA:
27531 		tcp = connp->conn_tcp;
27532 		ASSERT(tcp != NULL);
27533 
27534 		tcpstate = tcp->tcp_state;
27535 		if (tcpstate < TCPS_ESTABLISHED) {
27536 			freemsg(mp);
27537 			return (ENOTCONN);
27538 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
27539 			freemsg(mp);
27540 			return (EPIPE);
27541 		}
27542 
27543 		if (is_system_labeled())
27544 			msg_setcredpid(mp, cr, curproc->p_pid);
27545 
27546 		/* XXX pass the size down and to the squeue */
27547 		msize = msgdsize(mp);
27548 
27549 		mutex_enter(&tcp->tcp_non_sq_lock);
27550 		tcp->tcp_squeue_bytes += msize;
27551 		/*
27552 		 * Squeue Flow Control
27553 		 */
27554 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
27555 			tcp_setqfull(tcp);
27556 		}
27557 		mutex_exit(&tcp->tcp_non_sq_lock);
27558 
27559 		/*
27560 		 * The application may pass in an address in the msghdr, but
27561 		 * we ignore the address on connection-oriented sockets.
27562 		 * Just like BSD this code does not generate an error for
27563 		 * TCP (a CONNREQUIRED socket) when sending to an address
27564 		 * passed in with sendto/sendmsg. Instead the data is
27565 		 * delivered on the connection as if no address had been
27566 		 * supplied.
27567 		 */
27568 		CONN_INC_REF(connp);
27569 
27570 		if (msg != NULL && msg->msg_flags & MSG_OOB) {
27571 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
27572 			    tcp_output_urgent, connp, tcp_squeue_flag,
27573 			    SQTAG_TCP_OUTPUT);
27574 		} else {
27575 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
27576 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
27577 		}
27578 
27579 		return (0);
27580 
27581 	default:
27582 		ASSERT(0);
27583 	}
27584 
27585 	freemsg(mp);
27586 	return (0);
27587 }
27588 
27589 /* ARGSUSED */
27590 void
27591 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
27592 {
27593 	int len;
27594 	uint32_t msize;
27595 	conn_t *connp = (conn_t *)arg;
27596 	tcp_t *tcp = connp->conn_tcp;
27597 
27598 	msize = msgdsize(mp);
27599 
27600 	len = msize - 1;
27601 	if (len < 0) {
27602 		freemsg(mp);
27603 		return;
27604 	}
27605 
27606 	/*
27607 	 * Try to force urgent data out on the wire.
27608 	 * Even if we have unsent data this will
27609 	 * at least send the urgent flag.
27610 	 * XXX does not handle more flag correctly.
27611 	 */
27612 	len += tcp->tcp_unsent;
27613 	len += tcp->tcp_snxt;
27614 	tcp->tcp_urg = len;
27615 	tcp->tcp_valid_bits |= TCP_URG_VALID;
27616 
27617 	/* Bypass tcp protocol for fused tcp loopback */
27618 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
27619 		return;
27620 	tcp_wput_data(tcp, mp, B_TRUE);
27621 }
27622 
27623 /* ARGSUSED */
27624 int
27625 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27626     socklen_t *addrlen, cred_t *cr)
27627 {
27628 	sin_t   *sin;
27629 	sin6_t  *sin6;
27630 	conn_t	*connp = (conn_t *)proto_handle;
27631 	tcp_t	*tcp = connp->conn_tcp;
27632 
27633 	ASSERT(tcp != NULL);
27634 	if (tcp->tcp_state < TCPS_SYN_RCVD)
27635 		return (ENOTCONN);
27636 
27637 	addr->sa_family = tcp->tcp_family;
27638 	switch (tcp->tcp_family) {
27639 	case AF_INET:
27640 		if (*addrlen < sizeof (sin_t))
27641 			return (EINVAL);
27642 
27643 		sin = (sin_t *)addr;
27644 		*sin = sin_null;
27645 		sin->sin_family = AF_INET;
27646 		if (tcp->tcp_ipversion == IPV4_VERSION) {
27647 			IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
27648 			    sin->sin_addr.s_addr);
27649 		}
27650 		sin->sin_port = tcp->tcp_fport;
27651 		*addrlen = sizeof (struct sockaddr_in);
27652 		break;
27653 	case AF_INET6:
27654 		sin6 = (sin6_t *)addr;
27655 		*sin6 = sin6_null;
27656 		sin6->sin6_family = AF_INET6;
27657 
27658 		if (*addrlen < sizeof (struct sockaddr_in6))
27659 			return (EINVAL);
27660 
27661 		if (tcp->tcp_ipversion == IPV6_VERSION) {
27662 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
27663 			    ~IPV6_VERS_AND_FLOW_MASK;
27664 		}
27665 
27666 		sin6->sin6_addr = tcp->tcp_remote_v6;
27667 		sin6->sin6_port = tcp->tcp_fport;
27668 		*addrlen = sizeof (struct sockaddr_in6);
27669 		break;
27670 	}
27671 	return (0);
27672 }
27673 
27674 /* ARGSUSED */
27675 int
27676 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27677     socklen_t *addrlenp, cred_t *cr)
27678 {
27679 	sin_t   *sin;
27680 	sin6_t  *sin6;
27681 	conn_t	*connp = (conn_t *)proto_handle;
27682 	tcp_t	*tcp = connp->conn_tcp;
27683 
27684 	switch (tcp->tcp_family) {
27685 	case AF_INET:
27686 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
27687 		if (*addrlenp < sizeof (sin_t))
27688 			return (EINVAL);
27689 		sin = (sin_t *)addr;
27690 		*sin = sin_null;
27691 		sin->sin_family = AF_INET;
27692 		*addrlenp = sizeof (sin_t);
27693 		if (tcp->tcp_state >= TCPS_BOUND) {
27694 			sin->sin_addr.s_addr =  tcp->tcp_ipha->ipha_src;
27695 			sin->sin_port = tcp->tcp_lport;
27696 		}
27697 		break;
27698 
27699 	case AF_INET6:
27700 		if (*addrlenp < sizeof (sin6_t))
27701 			return (EINVAL);
27702 		sin6 = (sin6_t *)addr;
27703 		*sin6 = sin6_null;
27704 		sin6->sin6_family = AF_INET6;
27705 		*addrlenp = sizeof (sin6_t);
27706 		if (tcp->tcp_state >= TCPS_BOUND) {
27707 			sin6->sin6_port = tcp->tcp_lport;
27708 			if (tcp->tcp_ipversion == IPV4_VERSION) {
27709 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
27710 				    &sin6->sin6_addr);
27711 			} else {
27712 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
27713 			}
27714 		}
27715 		break;
27716 	}
27717 	return (0);
27718 }
27719 
27720 /*
27721  * tcp_fallback
27722  *
27723  * A direct socket is falling back to using STREAMS. Hanging
27724  * off of the queue is a temporary tcp_t, which was created using
27725  * tcp_open(). The tcp_open() was called as part of the regular
27726  * sockfs create path, i.e., the SO_SOCKSTR flag is passed down,
27727  * and therefore the temporary tcp_t is marked to be a socket
27728  * (i.e., IPCL_SOCKET, tcp_issocket). So the optimizations
27729  * introduced by FireEngine will be used.
27730  *
27731  * The tcp_t associated with the socket falling back will
27732  * still be marked as a socket, although the direct socket flag
27733  * (IPCL_NONSTR) is removed. A fall back to true TPI semantics
27734  * will not take place until a _SIOCSOCKFALLBACK ioctl is issued.
27735  *
27736  * If the above mentioned behavior, i.e., the tmp tcp_t is created
27737  * as a STREAMS/TPI endpoint, then we will need to do more work here.
27738  * Such as inserting the direct socket into the acceptor hash.
27739  */
27740 void
27741 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
27742     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
27743 {
27744 	tcp_t			*tcp, *eager;
27745 	conn_t 			*connp = (conn_t *)proto_handle;
27746 	int			error;
27747 	struct T_capability_ack tca;
27748 	struct sockaddr_in6	laddr, faddr;
27749 	socklen_t 		laddrlen, faddrlen;
27750 	short			opts;
27751 	struct stroptions	*stropt;
27752 	mblk_t			*stropt_mp;
27753 	mblk_t			*mp;
27754 	mblk_t			*conn_ind_head = NULL;
27755 	mblk_t			*conn_ind_tail = NULL;
27756 	mblk_t			*ordrel_mp;
27757 	mblk_t			*fused_sigurp_mp;
27758 
27759 	tcp = connp->conn_tcp;
27760 	/*
27761 	 * No support for acceptor fallback
27762 	 */
27763 	ASSERT(q->q_qinfo != &tcp_acceptor_rinit);
27764 
27765 	stropt_mp = allocb_wait(sizeof (*stropt), BPRI_HI, STR_NOSIG, NULL);
27766 
27767 	/* Pre-allocate the T_ordrel_ind mblk. */
27768 	ASSERT(tcp->tcp_ordrel_mp == NULL);
27769 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
27770 	    STR_NOSIG, NULL);
27771 	ordrel_mp->b_datap->db_type = M_PROTO;
27772 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
27773 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
27774 
27775 	/* Pre-allocate the M_PCSIG anyway */
27776 	fused_sigurp_mp = allocb_wait(1, BPRI_HI, STR_NOSIG, NULL);
27777 
27778 	/*
27779 	 * Enter the squeue so that no new packets can come in
27780 	 */
27781 	error = squeue_synch_enter(connp->conn_sqp, connp, 0);
27782 	if (error != 0) {
27783 		/* failed to enter, free all the pre-allocated messages. */
27784 		freeb(stropt_mp);
27785 		freeb(ordrel_mp);
27786 		freeb(fused_sigurp_mp);
27787 		return;
27788 	}
27789 
27790 	/* Disable I/OAT during fallback */
27791 	tcp->tcp_sodirect = NULL;
27792 
27793 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
27794 	connp->conn_minor_arena = WR(q)->q_ptr;
27795 
27796 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
27797 
27798 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
27799 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
27800 
27801 	WR(q)->q_qinfo = &tcp_sock_winit;
27802 
27803 	if (!direct_sockfs)
27804 		tcp_disable_direct_sockfs(tcp);
27805 
27806 	/*
27807 	 * free the helper stream
27808 	 */
27809 	ip_close_helper_stream(connp);
27810 
27811 	/*
27812 	 * Notify the STREAM head about options
27813 	 */
27814 	DB_TYPE(stropt_mp) = M_SETOPTS;
27815 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27816 	stropt_mp->b_wptr += sizeof (struct stroptions);
27817 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27818 	stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
27819 
27820 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
27821 	    tcp->tcp_tcps->tcps_wroff_xtra);
27822 	if (tcp->tcp_snd_sack_ok)
27823 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
27824 	stropt->so_hiwat = tcp->tcp_fused ?
27825 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
27826 	    MAX(tcp->tcp_recv_hiwater, tcp->tcp_tcps->tcps_sth_rcv_hiwat);
27827 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
27828 
27829 	putnext(RD(q), stropt_mp);
27830 
27831 	/*
27832 	 * Collect the information needed to sync with the sonode
27833 	 */
27834 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
27835 
27836 	laddrlen = faddrlen = sizeof (sin6_t);
27837 	(void) tcp_getsockname(proto_handle, (struct sockaddr *)&laddr,
27838 	    &laddrlen, CRED());
27839 	error = tcp_getpeername(proto_handle, (struct sockaddr *)&faddr,
27840 	    &faddrlen, CRED());
27841 	if (error != 0)
27842 		faddrlen = 0;
27843 
27844 	opts = 0;
27845 	if (tcp->tcp_oobinline)
27846 		opts |= SO_OOBINLINE;
27847 	if (tcp->tcp_dontroute)
27848 		opts |= SO_DONTROUTE;
27849 
27850 	/*
27851 	 * Notify the socket that the protocol is now quiescent,
27852 	 * and it's therefore safe move data from the socket
27853 	 * to the stream head.
27854 	 */
27855 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
27856 	    (struct sockaddr *)&laddr, laddrlen,
27857 	    (struct sockaddr *)&faddr, faddrlen, opts);
27858 
27859 	while ((mp = tcp->tcp_rcv_list) != NULL) {
27860 		tcp->tcp_rcv_list = mp->b_next;
27861 		mp->b_next = NULL;
27862 		putnext(q, mp);
27863 	}
27864 	tcp->tcp_rcv_last_head = NULL;
27865 	tcp->tcp_rcv_last_tail = NULL;
27866 	tcp->tcp_rcv_cnt = 0;
27867 
27868 	/*
27869 	 * No longer a direct socket
27870 	 */
27871 	connp->conn_flags &= ~IPCL_NONSTR;
27872 
27873 	tcp->tcp_ordrel_mp = ordrel_mp;
27874 
27875 	if (tcp->tcp_fused) {
27876 		ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
27877 		tcp->tcp_fused_sigurg_mp = fused_sigurp_mp;
27878 	} else {
27879 		freeb(fused_sigurp_mp);
27880 	}
27881 
27882 	/*
27883 	 * Send T_CONN_IND messages for all ESTABLISHED connections.
27884 	 */
27885 	mutex_enter(&tcp->tcp_eager_lock);
27886 	for (eager = tcp->tcp_eager_next_q; eager != NULL;
27887 	    eager = eager->tcp_eager_next_q) {
27888 		mp = eager->tcp_conn.tcp_eager_conn_ind;
27889 
27890 		eager->tcp_conn.tcp_eager_conn_ind = NULL;
27891 		ASSERT(mp != NULL);
27892 		/*
27893 		 * TLI/XTI applications will get confused by
27894 		 * sending eager as an option since it violates
27895 		 * the option semantics. So remove the eager as
27896 		 * option since TLI/XTI app doesn't need it anyway.
27897 		 */
27898 		if (!TCP_IS_SOCKET(tcp)) {
27899 			struct T_conn_ind *conn_ind;
27900 
27901 			conn_ind = (struct T_conn_ind *)mp->b_rptr;
27902 			conn_ind->OPT_length = 0;
27903 			conn_ind->OPT_offset = 0;
27904 		}
27905 		if (conn_ind_head == NULL) {
27906 			conn_ind_head = mp;
27907 		} else {
27908 			conn_ind_tail->b_next = mp;
27909 		}
27910 		conn_ind_tail = mp;
27911 	}
27912 	mutex_exit(&tcp->tcp_eager_lock);
27913 
27914 	mp = conn_ind_head;
27915 	while (mp != NULL) {
27916 		mblk_t *nmp = mp->b_next;
27917 		mp->b_next = NULL;
27918 
27919 		putnext(tcp->tcp_rq, mp);
27920 		mp = nmp;
27921 	}
27922 
27923 	/*
27924 	 * There should be atleast two ref's (IP + TCP)
27925 	 */
27926 	ASSERT(connp->conn_ref >= 2);
27927 	squeue_synch_exit(connp->conn_sqp, connp);
27928 }
27929 
27930 /* ARGSUSED */
27931 static void
27932 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
27933 {
27934 	conn_t 	*connp = (conn_t *)arg;
27935 	tcp_t	*tcp = connp->conn_tcp;
27936 
27937 	freemsg(mp);
27938 
27939 	if (tcp->tcp_fused)
27940 		tcp_unfuse(tcp);
27941 
27942 	if (tcp_xmit_end(tcp) != 0) {
27943 		/*
27944 		 * We were crossing FINs and got a reset from
27945 		 * the other side. Just ignore it.
27946 		 */
27947 		if (tcp->tcp_debug) {
27948 			(void) strlog(TCP_MOD_ID, 0, 1,
27949 			    SL_ERROR|SL_TRACE,
27950 			    "tcp_shutdown_output() out of state %s",
27951 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
27952 		}
27953 	}
27954 }
27955 
27956 /* ARGSUSED */
27957 int
27958 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
27959 {
27960 	conn_t  *connp = (conn_t *)proto_handle;
27961 	tcp_t   *tcp = connp->conn_tcp;
27962 
27963 	/*
27964 	 * X/Open requires that we check the connected state.
27965 	 */
27966 	if (tcp->tcp_state < TCPS_SYN_SENT)
27967 		return (ENOTCONN);
27968 
27969 	/* shutdown the send side */
27970 	if (how != SHUT_RD) {
27971 		mblk_t *bp;
27972 
27973 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
27974 		CONN_INC_REF(connp);
27975 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
27976 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
27977 
27978 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27979 		    SOCK_OPCTL_SHUT_SEND, 0);
27980 	}
27981 
27982 	/* shutdown the recv side */
27983 	if (how != SHUT_WR)
27984 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27985 		    SOCK_OPCTL_SHUT_RECV, 0);
27986 
27987 	return (0);
27988 }
27989 
27990 /*
27991  * SOP_LISTEN() calls into tcp_listen().
27992  */
27993 /* ARGSUSED */
27994 int
27995 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27996 {
27997 	conn_t	*connp = (conn_t *)proto_handle;
27998 	int 	error;
27999 	squeue_t *sqp = connp->conn_sqp;
28000 
28001 	error = squeue_synch_enter(sqp, connp, 0);
28002 	if (error != 0) {
28003 		/* failed to enter */
28004 		return (ENOBUFS);
28005 	}
28006 
28007 	error = tcp_do_listen(connp, backlog, cr);
28008 	if (error == 0) {
28009 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
28010 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
28011 	} else if (error < 0) {
28012 		if (error == -TOUTSTATE)
28013 			error = EINVAL;
28014 		else
28015 			error = proto_tlitosyserr(-error);
28016 	}
28017 	squeue_synch_exit(sqp, connp);
28018 	return (error);
28019 }
28020 
28021 static int
28022 tcp_do_listen(conn_t *connp, int backlog, cred_t *cr)
28023 {
28024 	tcp_t		*tcp = connp->conn_tcp;
28025 	sin_t		*sin;
28026 	sin6_t  	*sin6;
28027 	int		error = 0;
28028 	tcp_stack_t	*tcps = tcp->tcp_tcps;
28029 
28030 	if (tcp->tcp_state >= TCPS_BOUND) {
28031 		if ((tcp->tcp_state == TCPS_BOUND ||
28032 		    tcp->tcp_state == TCPS_LISTEN) &&
28033 		    backlog > 0) {
28034 			/*
28035 			 * Handle listen() increasing backlog.
28036 			 * This is more "liberal" then what the TPI spec
28037 			 * requires but is needed to avoid a t_unbind
28038 			 * when handling listen() since the port number
28039 			 * might be "stolen" between the unbind and bind.
28040 			 */
28041 			goto do_listen;
28042 		}
28043 		if (tcp->tcp_debug) {
28044 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
28045 			    "tcp_bind: bad state, %d", tcp->tcp_state);
28046 		}
28047 		return (-TOUTSTATE);
28048 	} else {
28049 		int32_t len;
28050 		sin6_t	addr;
28051 
28052 		/* Do an implicit bind: Request for a generic port. */
28053 		if (tcp->tcp_family == AF_INET) {
28054 			len = sizeof (sin_t);
28055 			sin = (sin_t *)&addr;
28056 			*sin = sin_null;
28057 			sin->sin_family = AF_INET;
28058 			tcp->tcp_ipversion = IPV4_VERSION;
28059 		} else {
28060 			ASSERT(tcp->tcp_family == AF_INET6);
28061 			len = sizeof (sin6_t);
28062 			sin6 = (sin6_t *)&addr;
28063 			*sin6 = sin6_null;
28064 			sin6->sin6_family = AF_INET6;
28065 			tcp->tcp_ipversion = IPV6_VERSION;
28066 		}
28067 
28068 		error = tcp_bind_check(connp, (struct sockaddr *)&addr, len,
28069 		    cr, B_FALSE);
28070 		if (error)
28071 			return (error);
28072 		/* Fall through and do the fanout insertion */
28073 	}
28074 
28075 do_listen:
28076 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
28077 	tcp->tcp_conn_req_max = backlog;
28078 	if (tcp->tcp_conn_req_max) {
28079 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
28080 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
28081 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
28082 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
28083 		/*
28084 		 * If this is a listener, do not reset the eager list
28085 		 * and other stuffs.  Note that we don't check if the
28086 		 * existing eager list meets the new tcp_conn_req_max
28087 		 * requirement.
28088 		 */
28089 		if (tcp->tcp_state != TCPS_LISTEN) {
28090 			tcp->tcp_state = TCPS_LISTEN;
28091 			/* Initialize the chain. Don't need the eager_lock */
28092 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
28093 			tcp->tcp_eager_next_drop_q0 = tcp;
28094 			tcp->tcp_eager_prev_drop_q0 = tcp;
28095 			tcp->tcp_second_ctimer_threshold =
28096 			    tcps->tcps_ip_abort_linterval;
28097 		}
28098 	}
28099 
28100 	/*
28101 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
28102 	 * processing continues in tcp_rput_other().
28103 	 *
28104 	 * We need to make sure that the conn_recv is set to a non-null
28105 	 * value before we insert the conn into the classifier table.
28106 	 * This is to avoid a race with an incoming packet which does an
28107 	 * ipcl_classify().
28108 	 */
28109 	connp->conn_recv = tcp_conn_request;
28110 	if (tcp->tcp_family == AF_INET) {
28111 		error = ip_proto_bind_laddr_v4(connp, NULL,
28112 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
28113 	} else {
28114 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
28115 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
28116 	}
28117 	return (tcp_post_ip_bind(tcp, NULL, error));
28118 }
28119 
28120 void
28121 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
28122 {
28123 	conn_t  *connp = (conn_t *)proto_handle;
28124 	tcp_t	*tcp = connp->conn_tcp;
28125 	tcp_stack_t	*tcps = tcp->tcp_tcps;
28126 	uint_t thwin;
28127 
28128 	(void) squeue_synch_enter(connp->conn_sqp, connp, 0);
28129 
28130 	/* Flow control condition has been removed. */
28131 	tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
28132 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
28133 	    << tcp->tcp_rcv_ws;
28134 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
28135 	/*
28136 	 * Send back a window update immediately if TCP is above
28137 	 * ESTABLISHED state and the increase of the rcv window
28138 	 * that the other side knows is at least 1 MSS after flow
28139 	 * control is lifted.
28140 	 */
28141 	if (tcp->tcp_state >= TCPS_ESTABLISHED &&
28142 	    (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss)) {
28143 		tcp_xmit_ctl(NULL, tcp,
28144 		    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
28145 		    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
28146 		BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
28147 	}
28148 
28149 	squeue_synch_exit(connp->conn_sqp, connp);
28150 }
28151 
28152 /* ARGSUSED */
28153 int
28154 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
28155     int mode, int32_t *rvalp, cred_t *cr)
28156 {
28157 	conn_t  	*connp = (conn_t *)proto_handle;
28158 	int		error;
28159 
28160 	switch (cmd) {
28161 		case ND_SET:
28162 		case ND_GET:
28163 		case TCP_IOC_DEFAULT_Q:
28164 		case _SIOCSOCKFALLBACK:
28165 		case TCP_IOC_ABORT_CONN:
28166 		case TI_GETPEERNAME:
28167 		case TI_GETMYNAME:
28168 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
28169 			    cmd));
28170 			error = EINVAL;
28171 			break;
28172 		default:
28173 			/*
28174 			 * Pass on to IP using helper stream
28175 			 */
28176 			error = ldi_ioctl(
28177 			    connp->conn_helper_info->ip_helper_stream_handle,
28178 			    cmd, arg, mode, cr, rvalp);
28179 			break;
28180 	}
28181 	return (error);
28182 }
28183 
28184 sock_downcalls_t sock_tcp_downcalls = {
28185 	tcp_activate,
28186 	tcp_accept,
28187 	tcp_bind,
28188 	tcp_listen,
28189 	tcp_connect,
28190 	tcp_getpeername,
28191 	tcp_getsockname,
28192 	tcp_getsockopt,
28193 	tcp_setsockopt,
28194 	tcp_sendmsg,
28195 	NULL,
28196 	NULL,
28197 	NULL,
28198 	tcp_shutdown,
28199 	tcp_clr_flowctrl,
28200 	tcp_ioctl,
28201 	tcp_close,
28202 };
28203