xref: /titanic_52/usr/src/uts/common/inet/tcp/tcp.c (revision a9489f613f667faf21ee68381b627b28ddb22188)
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, &connp->conn_srcv6);
4574 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4575 
4576 		sin6 = sin6_null;
4577 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4578 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4579 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4580 		sin6.sin6_family = AF_INET6;
4581 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4582 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4583 		if (tcp->tcp_recvdstaddr) {
4584 			sin6_t	sin6d;
4585 
4586 			sin6d = sin6_null;
4587 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4588 			    &sin6d.sin6_addr);
4589 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4590 			sin6d.sin6_family = AF_INET;
4591 			tpi_mp = mi_tpi_extconn_ind(NULL,
4592 			    (char *)&sin6d, sizeof (sin6_t),
4593 			    (char *)&tcp,
4594 			    (t_scalar_t)sizeof (intptr_t),
4595 			    (char *)&sin6d, sizeof (sin6_t),
4596 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4597 		} else {
4598 			tpi_mp = mi_tpi_conn_ind(NULL,
4599 			    (char *)&sin6, sizeof (sin6_t),
4600 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4601 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4602 		}
4603 	} else {
4604 		ip6h = (ip6_t *)mp->b_rptr;
4605 
4606 		connp->conn_send = ip_output_v6;
4607 		connp->conn_recv = tcp_input;
4608 
4609 		connp->conn_srcv6 = ip6h->ip6_dst;
4610 		connp->conn_remv6 = ip6h->ip6_src;
4611 
4612 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4613 		ifindex = (int)DB_CKSUMSTUFF(mp);
4614 		DB_CKSUMSTUFF(mp) = 0;
4615 
4616 		sin6 = sin6_null;
4617 		sin6.sin6_addr = ip6h->ip6_src;
4618 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4619 		sin6.sin6_family = AF_INET6;
4620 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4621 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4622 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4623 
4624 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4625 			/* Pass up the scope_id of remote addr */
4626 			sin6.sin6_scope_id = ifindex;
4627 		} else {
4628 			sin6.sin6_scope_id = 0;
4629 		}
4630 		if (tcp->tcp_recvdstaddr) {
4631 			sin6_t	sin6d;
4632 
4633 			sin6d = sin6_null;
4634 			sin6.sin6_addr = ip6h->ip6_dst;
4635 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4636 			sin6d.sin6_family = AF_INET;
4637 			tpi_mp = mi_tpi_extconn_ind(NULL,
4638 			    (char *)&sin6d, sizeof (sin6_t),
4639 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4640 			    (char *)&sin6d, sizeof (sin6_t),
4641 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4642 		} else {
4643 			tpi_mp = mi_tpi_conn_ind(NULL,
4644 			    (char *)&sin6, sizeof (sin6_t),
4645 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4646 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4647 		}
4648 	}
4649 
4650 	if (tpi_mp == NULL)
4651 		return (ENOMEM);
4652 
4653 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4654 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4655 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4656 	connp->conn_fully_bound = B_FALSE;
4657 
4658 	/* Inherit information from the "parent" */
4659 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4660 	tcp->tcp_family = ltcp->tcp_family;
4661 
4662 	tcp->tcp_wq = ltcp->tcp_wq;
4663 	tcp->tcp_rq = ltcp->tcp_rq;
4664 
4665 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4666 	tcp->tcp_detached = B_TRUE;
4667 	SOCK_CONNID_INIT(tcp->tcp_connid);
4668 	if ((err = tcp_init_values(tcp)) != 0) {
4669 		freemsg(tpi_mp);
4670 		return (err);
4671 	}
4672 
4673 	if (ipvers == IPV4_VERSION) {
4674 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4675 			freemsg(tpi_mp);
4676 			return (err);
4677 		}
4678 		ASSERT(tcp->tcp_ipha != NULL);
4679 	} else {
4680 		/* ifindex must be already set */
4681 		ASSERT(ifindex != 0);
4682 
4683 		if (ltcp->tcp_bound_if != 0) {
4684 			/*
4685 			 * Set newtcp's bound_if equal to
4686 			 * listener's value. If ifindex is
4687 			 * not the same as ltcp->tcp_bound_if,
4688 			 * it must be a packet for the ipmp group
4689 			 * of interfaces
4690 			 */
4691 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4692 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4693 			tcp->tcp_bound_if = ifindex;
4694 		}
4695 
4696 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4697 		tcp->tcp_recvifindex = 0;
4698 		tcp->tcp_recvhops = 0xffffffffU;
4699 		ASSERT(tcp->tcp_ip6h != NULL);
4700 	}
4701 
4702 	tcp->tcp_lport = ltcp->tcp_lport;
4703 
4704 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4705 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4706 			/*
4707 			 * Listener had options of some sort; eager inherits.
4708 			 * Free up the eager template and allocate one
4709 			 * of the right size.
4710 			 */
4711 			if (tcp->tcp_hdr_grown) {
4712 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4713 			} else {
4714 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4715 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4716 			}
4717 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4718 			    KM_NOSLEEP);
4719 			if (tcp->tcp_iphc == NULL) {
4720 				tcp->tcp_iphc_len = 0;
4721 				freemsg(tpi_mp);
4722 				return (ENOMEM);
4723 			}
4724 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4725 			tcp->tcp_hdr_grown = B_TRUE;
4726 		}
4727 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4728 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4729 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4730 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4731 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4732 
4733 		/*
4734 		 * Copy the IP+TCP header template from listener to eager
4735 		 */
4736 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4737 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4738 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4739 			    IPPROTO_RAW) {
4740 				tcp->tcp_ip6h =
4741 				    (ip6_t *)(tcp->tcp_iphc +
4742 				    sizeof (ip6i_t));
4743 			} else {
4744 				tcp->tcp_ip6h =
4745 				    (ip6_t *)(tcp->tcp_iphc);
4746 			}
4747 			tcp->tcp_ipha = NULL;
4748 		} else {
4749 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4750 			tcp->tcp_ip6h = NULL;
4751 		}
4752 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4753 		    tcp->tcp_ip_hdr_len);
4754 	} else {
4755 		/*
4756 		 * only valid case when ipversion of listener and
4757 		 * eager differ is when listener is IPv6 and
4758 		 * eager is IPv4.
4759 		 * Eager header template has been initialized to the
4760 		 * maximum v4 header sizes, which includes space for
4761 		 * TCP and IP options.
4762 		 */
4763 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4764 		    (tcp->tcp_ipversion == IPV4_VERSION));
4765 		ASSERT(tcp->tcp_iphc_len >=
4766 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4767 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4768 		/* copy IP header fields individually */
4769 		tcp->tcp_ipha->ipha_ttl =
4770 		    ltcp->tcp_ip6h->ip6_hops;
4771 		bcopy(ltcp->tcp_tcph->th_lport,
4772 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4773 	}
4774 
4775 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4776 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4777 	    sizeof (in_port_t));
4778 
4779 	if (ltcp->tcp_lport == 0) {
4780 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4781 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4782 		    sizeof (in_port_t));
4783 	}
4784 
4785 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4786 		ASSERT(ipha != NULL);
4787 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4788 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4789 
4790 		/* Source routing option copyover (reverse it) */
4791 		if (tcps->tcps_rev_src_routes)
4792 			tcp_opt_reverse(tcp, ipha);
4793 	} else {
4794 		ASSERT(ip6h != NULL);
4795 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4796 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4797 	}
4798 
4799 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4800 	ASSERT(!tcp->tcp_tconnind_started);
4801 	/*
4802 	 * If the SYN contains a credential, it's a loopback packet; attach
4803 	 * the credential to the TPI message.
4804 	 */
4805 	if ((cr = DB_CRED(idmp)) != NULL) {
4806 		mblk_setcred(tpi_mp, cr);
4807 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4808 	}
4809 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4810 
4811 	/* Inherit the listener's SSL protection state */
4812 
4813 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4814 		kssl_hold_ent(tcp->tcp_kssl_ent);
4815 		tcp->tcp_kssl_pending = B_TRUE;
4816 	}
4817 
4818 	/* Inherit the listener's non-STREAMS flag */
4819 	if (IPCL_IS_NONSTR(lconnp)) {
4820 		connp->conn_flags |= IPCL_NONSTR;
4821 		connp->conn_upcalls = lconnp->conn_upcalls;
4822 	}
4823 
4824 	return (0);
4825 }
4826 
4827 
4828 int
4829 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4830     tcph_t *tcph, mblk_t *idmp)
4831 {
4832 	tcp_t 		*ltcp = lconnp->conn_tcp;
4833 	tcp_t		*tcp = connp->conn_tcp;
4834 	sin_t		sin;
4835 	mblk_t		*tpi_mp = NULL;
4836 	int		err;
4837 	cred_t		*cr;
4838 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4839 
4840 	sin = sin_null;
4841 	sin.sin_addr.s_addr = ipha->ipha_src;
4842 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4843 	sin.sin_family = AF_INET;
4844 	if (ltcp->tcp_recvdstaddr) {
4845 		sin_t	sind;
4846 
4847 		sind = sin_null;
4848 		sind.sin_addr.s_addr = ipha->ipha_dst;
4849 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4850 		sind.sin_family = AF_INET;
4851 		tpi_mp = mi_tpi_extconn_ind(NULL,
4852 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4853 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4854 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4855 	} else {
4856 		tpi_mp = mi_tpi_conn_ind(NULL,
4857 		    (char *)&sin, sizeof (sin_t),
4858 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4859 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4860 	}
4861 
4862 	if (tpi_mp == NULL) {
4863 		return (ENOMEM);
4864 	}
4865 
4866 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4867 	connp->conn_send = ip_output;
4868 	connp->conn_recv = tcp_input;
4869 	connp->conn_fully_bound = B_FALSE;
4870 
4871 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4872 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4873 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4874 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4875 
4876 	/* Inherit information from the "parent" */
4877 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4878 	tcp->tcp_family = ltcp->tcp_family;
4879 	tcp->tcp_wq = ltcp->tcp_wq;
4880 	tcp->tcp_rq = ltcp->tcp_rq;
4881 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4882 	tcp->tcp_detached = B_TRUE;
4883 	SOCK_CONNID_INIT(tcp->tcp_connid);
4884 	if ((err = tcp_init_values(tcp)) != 0) {
4885 		freemsg(tpi_mp);
4886 		return (err);
4887 	}
4888 
4889 	/*
4890 	 * Let's make sure that eager tcp template has enough space to
4891 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4892 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4893 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4894 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4895 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4896 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4897 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4898 	 */
4899 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4900 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4901 
4902 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4903 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4904 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4905 	tcp->tcp_ttl = ltcp->tcp_ttl;
4906 	tcp->tcp_tos = ltcp->tcp_tos;
4907 
4908 	/* Copy the IP+TCP header template from listener to eager */
4909 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4910 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4911 	tcp->tcp_ip6h = NULL;
4912 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4913 	    tcp->tcp_ip_hdr_len);
4914 
4915 	/* Initialize the IP addresses and Ports */
4916 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4917 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4918 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4919 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4920 
4921 	/* Source routing option copyover (reverse it) */
4922 	if (tcps->tcps_rev_src_routes)
4923 		tcp_opt_reverse(tcp, ipha);
4924 
4925 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4926 	ASSERT(!tcp->tcp_tconnind_started);
4927 
4928 	/*
4929 	 * If the SYN contains a credential, it's a loopback packet; attach
4930 	 * the credential to the TPI message.
4931 	 */
4932 	if ((cr = DB_CRED(idmp)) != NULL) {
4933 		mblk_setcred(tpi_mp, cr);
4934 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4935 	}
4936 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4937 
4938 	/* Inherit the listener's SSL protection state */
4939 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4940 		kssl_hold_ent(tcp->tcp_kssl_ent);
4941 		tcp->tcp_kssl_pending = B_TRUE;
4942 	}
4943 
4944 	/* Inherit the listener's non-STREAMS flag */
4945 	if (IPCL_IS_NONSTR(lconnp)) {
4946 		connp->conn_flags |= IPCL_NONSTR;
4947 		connp->conn_upcalls = lconnp->conn_upcalls;
4948 	}
4949 
4950 	return (0);
4951 }
4952 
4953 /*
4954  * sets up conn for ipsec.
4955  * if the first mblk is M_CTL it is consumed and mpp is updated.
4956  * in case of error mpp is freed.
4957  */
4958 conn_t *
4959 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4960 {
4961 	conn_t 		*connp = tcp->tcp_connp;
4962 	conn_t 		*econnp;
4963 	squeue_t 	*new_sqp;
4964 	mblk_t 		*first_mp = *mpp;
4965 	mblk_t		*mp = *mpp;
4966 	boolean_t	mctl_present = B_FALSE;
4967 	uint_t		ipvers;
4968 
4969 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
4970 	if (econnp == NULL) {
4971 		freemsg(first_mp);
4972 		return (NULL);
4973 	}
4974 	if (DB_TYPE(mp) == M_CTL) {
4975 		if (mp->b_cont == NULL ||
4976 		    mp->b_cont->b_datap->db_type != M_DATA) {
4977 			freemsg(first_mp);
4978 			return (NULL);
4979 		}
4980 		mp = mp->b_cont;
4981 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4982 			freemsg(first_mp);
4983 			return (NULL);
4984 		}
4985 
4986 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4987 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4988 		mctl_present = B_TRUE;
4989 	} else {
4990 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4991 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4992 	}
4993 
4994 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4995 	DB_CKSUMSTART(mp) = 0;
4996 
4997 	ASSERT(OK_32PTR(mp->b_rptr));
4998 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
4999 	if (ipvers == IPV4_VERSION) {
5000 		uint16_t  	*up;
5001 		uint32_t	ports;
5002 		ipha_t		*ipha;
5003 
5004 		ipha = (ipha_t *)mp->b_rptr;
5005 		up = (uint16_t *)((uchar_t *)ipha +
5006 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5007 		ports = *(uint32_t *)up;
5008 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5009 		    ipha->ipha_dst, ipha->ipha_src, ports);
5010 	} else {
5011 		uint16_t  	*up;
5012 		uint32_t	ports;
5013 		uint16_t	ip_hdr_len;
5014 		uint8_t		*nexthdrp;
5015 		ip6_t 		*ip6h;
5016 		tcph_t		*tcph;
5017 
5018 		ip6h = (ip6_t *)mp->b_rptr;
5019 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5020 			ip_hdr_len = IPV6_HDR_LEN;
5021 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5022 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5023 			CONN_DEC_REF(econnp);
5024 			freemsg(first_mp);
5025 			return (NULL);
5026 		}
5027 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5028 		up = (uint16_t *)tcph->th_lport;
5029 		ports = *(uint32_t *)up;
5030 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5031 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5032 	}
5033 
5034 	/*
5035 	 * The caller already ensured that there is a sqp present.
5036 	 */
5037 	econnp->conn_sqp = new_sqp;
5038 	econnp->conn_initial_sqp = new_sqp;
5039 
5040 	if (connp->conn_policy != NULL) {
5041 		ipsec_in_t *ii;
5042 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5043 		ASSERT(ii->ipsec_in_policy == NULL);
5044 		IPPH_REFHOLD(connp->conn_policy);
5045 		ii->ipsec_in_policy = connp->conn_policy;
5046 
5047 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5048 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5049 			CONN_DEC_REF(econnp);
5050 			freemsg(first_mp);
5051 			return (NULL);
5052 		}
5053 	}
5054 
5055 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5056 		CONN_DEC_REF(econnp);
5057 		freemsg(first_mp);
5058 		return (NULL);
5059 	}
5060 
5061 	/*
5062 	 * If we know we have some policy, pass the "IPSEC"
5063 	 * options size TCP uses this adjust the MSS.
5064 	 */
5065 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5066 	if (mctl_present) {
5067 		freeb(first_mp);
5068 		*mpp = mp;
5069 	}
5070 
5071 	return (econnp);
5072 }
5073 
5074 /*
5075  * tcp_get_conn/tcp_free_conn
5076  *
5077  * tcp_get_conn is used to get a clean tcp connection structure.
5078  * It tries to reuse the connections put on the freelist by the
5079  * time_wait_collector failing which it goes to kmem_cache. This
5080  * way has two benefits compared to just allocating from and
5081  * freeing to kmem_cache.
5082  * 1) The time_wait_collector can free (which includes the cleanup)
5083  * outside the squeue. So when the interrupt comes, we have a clean
5084  * connection sitting in the freelist. Obviously, this buys us
5085  * performance.
5086  *
5087  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5088  * has multiple disadvantages - tying up the squeue during alloc, and the
5089  * fact that IPSec policy initialization has to happen here which
5090  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5091  * But allocating the conn/tcp in IP land is also not the best since
5092  * we can't check the 'q' and 'q0' which are protected by squeue and
5093  * blindly allocate memory which might have to be freed here if we are
5094  * not allowed to accept the connection. By using the freelist and
5095  * putting the conn/tcp back in freelist, we don't pay a penalty for
5096  * allocating memory without checking 'q/q0' and freeing it if we can't
5097  * accept the connection.
5098  *
5099  * Care should be taken to put the conn back in the same squeue's freelist
5100  * from which it was allocated. Best results are obtained if conn is
5101  * allocated from listener's squeue and freed to the same. Time wait
5102  * collector will free up the freelist is the connection ends up sitting
5103  * there for too long.
5104  */
5105 void *
5106 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5107 {
5108 	tcp_t			*tcp = NULL;
5109 	conn_t			*connp = NULL;
5110 	squeue_t		*sqp = (squeue_t *)arg;
5111 	tcp_squeue_priv_t 	*tcp_time_wait;
5112 	netstack_t		*ns;
5113 
5114 	tcp_time_wait =
5115 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5116 
5117 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5118 	tcp = tcp_time_wait->tcp_free_list;
5119 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5120 	if (tcp != NULL) {
5121 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5122 		tcp_time_wait->tcp_free_list_cnt--;
5123 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5124 		tcp->tcp_time_wait_next = NULL;
5125 		connp = tcp->tcp_connp;
5126 		connp->conn_flags |= IPCL_REUSED;
5127 
5128 		ASSERT(tcp->tcp_tcps == NULL);
5129 		ASSERT(connp->conn_netstack == NULL);
5130 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5131 		ns = tcps->tcps_netstack;
5132 		netstack_hold(ns);
5133 		connp->conn_netstack = ns;
5134 		tcp->tcp_tcps = tcps;
5135 		TCPS_REFHOLD(tcps);
5136 		ipcl_globalhash_insert(connp);
5137 		return ((void *)connp);
5138 	}
5139 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5140 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5141 	    tcps->tcps_netstack)) == NULL)
5142 		return (NULL);
5143 	tcp = connp->conn_tcp;
5144 	/*
5145 	 * Pre-allocate the tcp_rsrv_mp.  This mblk will not be freed
5146 	 * until this conn_t/tcp_t is freed at ipcl_conn_destroy().
5147 	 */
5148 	if ((tcp->tcp_rsrv_mp = allocb(0, BPRI_HI)) == NULL) {
5149 		ipcl_conn_destroy(connp);
5150 		return (NULL);
5151 	}
5152 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5153 	tcp->tcp_tcps = tcps;
5154 	TCPS_REFHOLD(tcps);
5155 
5156 	return ((void *)connp);
5157 }
5158 
5159 /*
5160  * Update the cached label for the given tcp_t.  This should be called once per
5161  * connection, and before any packets are sent or tcp_process_options is
5162  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5163  */
5164 static boolean_t
5165 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5166 {
5167 	conn_t *connp = tcp->tcp_connp;
5168 
5169 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5170 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5171 		int added;
5172 
5173 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5174 		    connp->conn_mac_exempt,
5175 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5176 			return (B_FALSE);
5177 
5178 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5179 		if (added == -1)
5180 			return (B_FALSE);
5181 		tcp->tcp_hdr_len += added;
5182 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5183 		tcp->tcp_ip_hdr_len += added;
5184 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5185 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5186 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5187 			    tcp->tcp_hdr_len);
5188 			if (added == -1)
5189 				return (B_FALSE);
5190 			tcp->tcp_hdr_len += added;
5191 			tcp->tcp_tcph = (tcph_t *)
5192 			    ((uchar_t *)tcp->tcp_tcph + added);
5193 			tcp->tcp_ip_hdr_len += added;
5194 		}
5195 	} else {
5196 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5197 
5198 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5199 		    connp->conn_mac_exempt,
5200 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5201 			return (B_FALSE);
5202 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5203 		    &tcp->tcp_label_len, optbuf) != 0)
5204 			return (B_FALSE);
5205 		if (tcp_build_hdrs(tcp) != 0)
5206 			return (B_FALSE);
5207 	}
5208 
5209 	connp->conn_ulp_labeled = 1;
5210 
5211 	return (B_TRUE);
5212 }
5213 
5214 /* BEGIN CSTYLED */
5215 /*
5216  *
5217  * The sockfs ACCEPT path:
5218  * =======================
5219  *
5220  * The eager is now established in its own perimeter as soon as SYN is
5221  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5222  * completes the accept processing on the acceptor STREAM. The sending
5223  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5224  * listener but a TLI/XTI listener completes the accept processing
5225  * on the listener perimeter.
5226  *
5227  * Common control flow for 3 way handshake:
5228  * ----------------------------------------
5229  *
5230  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5231  *					-> tcp_conn_request()
5232  *
5233  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5234  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5235  *
5236  * Sockfs ACCEPT Path:
5237  * -------------------
5238  *
5239  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5240  * as STREAM entry point)
5241  *
5242  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5243  *
5244  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5245  * association (we are not behind eager's squeue but sockfs is protecting us
5246  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5247  * is changed to point at tcp_wput().
5248  *
5249  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5250  * listener (done on listener's perimeter).
5251  *
5252  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5253  * accept.
5254  *
5255  * TLI/XTI client ACCEPT path:
5256  * ---------------------------
5257  *
5258  * soaccept() sends T_CONN_RES on the listener STREAM.
5259  *
5260  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5261  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5262  *
5263  * Locks:
5264  * ======
5265  *
5266  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5267  * and listeners->tcp_eager_next_q.
5268  *
5269  * Referencing:
5270  * ============
5271  *
5272  * 1) We start out in tcp_conn_request by eager placing a ref on
5273  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5274  *
5275  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5276  * doing so we place a ref on the eager. This ref is finally dropped at the
5277  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5278  * reference is dropped by the squeue framework.
5279  *
5280  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5281  *
5282  * The reference must be released by the same entity that added the reference
5283  * In the above scheme, the eager is the entity that adds and releases the
5284  * references. Note that tcp_accept_finish executes in the squeue of the eager
5285  * (albeit after it is attached to the acceptor stream). Though 1. executes
5286  * in the listener's squeue, the eager is nascent at this point and the
5287  * reference can be considered to have been added on behalf of the eager.
5288  *
5289  * Eager getting a Reset or listener closing:
5290  * ==========================================
5291  *
5292  * Once the listener and eager are linked, the listener never does the unlink.
5293  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5294  * a message on all eager perimeter. The eager then does the unlink, clears
5295  * any pointers to the listener's queue and drops the reference to the
5296  * listener. The listener waits in tcp_close outside the squeue until its
5297  * refcount has dropped to 1. This ensures that the listener has waited for
5298  * all eagers to clear their association with the listener.
5299  *
5300  * Similarly, if eager decides to go away, it can unlink itself and close.
5301  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5302  * the reference to eager is still valid because of the extra ref we put
5303  * in tcp_send_conn_ind.
5304  *
5305  * Listener can always locate the eager under the protection
5306  * of the listener->tcp_eager_lock, and then do a refhold
5307  * on the eager during the accept processing.
5308  *
5309  * The acceptor stream accesses the eager in the accept processing
5310  * based on the ref placed on eager before sending T_conn_ind.
5311  * The only entity that can negate this refhold is a listener close
5312  * which is mutually exclusive with an active acceptor stream.
5313  *
5314  * Eager's reference on the listener
5315  * ===================================
5316  *
5317  * If the accept happens (even on a closed eager) the eager drops its
5318  * reference on the listener at the start of tcp_accept_finish. If the
5319  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5320  * the reference is dropped in tcp_closei_local. If the listener closes,
5321  * the reference is dropped in tcp_eager_kill. In all cases the reference
5322  * is dropped while executing in the eager's context (squeue).
5323  */
5324 /* END CSTYLED */
5325 
5326 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5327 
5328 /*
5329  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5330  * tcp_rput_data will not see any SYN packets.
5331  */
5332 /* ARGSUSED */
5333 void
5334 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5335 {
5336 	tcph_t		*tcph;
5337 	uint32_t	seg_seq;
5338 	tcp_t		*eager;
5339 	uint_t		ipvers;
5340 	ipha_t		*ipha;
5341 	ip6_t		*ip6h;
5342 	int		err;
5343 	conn_t		*econnp = NULL;
5344 	squeue_t	*new_sqp;
5345 	mblk_t		*mp1;
5346 	uint_t 		ip_hdr_len;
5347 	conn_t		*connp = (conn_t *)arg;
5348 	tcp_t		*tcp = connp->conn_tcp;
5349 	cred_t		*credp;
5350 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5351 	ip_stack_t	*ipst;
5352 
5353 	if (tcp->tcp_state != TCPS_LISTEN)
5354 		goto error2;
5355 
5356 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5357 
5358 	mutex_enter(&tcp->tcp_eager_lock);
5359 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5360 		mutex_exit(&tcp->tcp_eager_lock);
5361 		TCP_STAT(tcps, tcp_listendrop);
5362 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5363 		if (tcp->tcp_debug) {
5364 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5365 			    "tcp_conn_request: listen backlog (max=%d) "
5366 			    "overflow (%d pending) on %s",
5367 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5368 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5369 		}
5370 		goto error2;
5371 	}
5372 
5373 	if (tcp->tcp_conn_req_cnt_q0 >=
5374 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5375 		/*
5376 		 * Q0 is full. Drop a pending half-open req from the queue
5377 		 * to make room for the new SYN req. Also mark the time we
5378 		 * drop a SYN.
5379 		 *
5380 		 * A more aggressive defense against SYN attack will
5381 		 * be to set the "tcp_syn_defense" flag now.
5382 		 */
5383 		TCP_STAT(tcps, tcp_listendropq0);
5384 		tcp->tcp_last_rcv_lbolt = lbolt64;
5385 		if (!tcp_drop_q0(tcp)) {
5386 			mutex_exit(&tcp->tcp_eager_lock);
5387 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5388 			if (tcp->tcp_debug) {
5389 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5390 				    "tcp_conn_request: listen half-open queue "
5391 				    "(max=%d) full (%d pending) on %s",
5392 				    tcps->tcps_conn_req_max_q0,
5393 				    tcp->tcp_conn_req_cnt_q0,
5394 				    tcp_display(tcp, NULL,
5395 				    DISP_PORT_ONLY));
5396 			}
5397 			goto error2;
5398 		}
5399 	}
5400 	mutex_exit(&tcp->tcp_eager_lock);
5401 
5402 	/*
5403 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5404 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5405 	 * link local address.  If IPSec is enabled, db_struioflag has
5406 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5407 	 * otherwise an error case if neither of them is set.
5408 	 */
5409 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5410 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5411 		DB_CKSUMSTART(mp) = 0;
5412 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5413 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5414 		if (econnp == NULL)
5415 			goto error2;
5416 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5417 		econnp->conn_sqp = new_sqp;
5418 		econnp->conn_initial_sqp = new_sqp;
5419 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5420 		/*
5421 		 * mp is updated in tcp_get_ipsec_conn().
5422 		 */
5423 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5424 		if (econnp == NULL) {
5425 			/*
5426 			 * mp freed by tcp_get_ipsec_conn.
5427 			 */
5428 			return;
5429 		}
5430 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5431 	} else {
5432 		goto error2;
5433 	}
5434 
5435 	ASSERT(DB_TYPE(mp) == M_DATA);
5436 
5437 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5438 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5439 	ASSERT(OK_32PTR(mp->b_rptr));
5440 	if (ipvers == IPV4_VERSION) {
5441 		ipha = (ipha_t *)mp->b_rptr;
5442 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5443 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5444 	} else {
5445 		ip6h = (ip6_t *)mp->b_rptr;
5446 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5447 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5448 	}
5449 
5450 	if (tcp->tcp_family == AF_INET) {
5451 		ASSERT(ipvers == IPV4_VERSION);
5452 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5453 	} else {
5454 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5455 	}
5456 
5457 	if (err)
5458 		goto error3;
5459 
5460 	eager = econnp->conn_tcp;
5461 
5462 	/*
5463 	 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that at close
5464 	 * time, we will always have that to send up.  Otherwise, we need to do
5465 	 * special handling in case the allocation fails at that time.
5466 	 */
5467 	ASSERT(eager->tcp_ordrel_mp == NULL);
5468 	if (!IPCL_IS_NONSTR(econnp) &&
5469 	    (eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5470 		goto error3;
5471 
5472 	/* Inherit various TCP parameters from the listener */
5473 	eager->tcp_naglim = tcp->tcp_naglim;
5474 	eager->tcp_first_timer_threshold =
5475 	    tcp->tcp_first_timer_threshold;
5476 	eager->tcp_second_timer_threshold =
5477 	    tcp->tcp_second_timer_threshold;
5478 
5479 	eager->tcp_first_ctimer_threshold =
5480 	    tcp->tcp_first_ctimer_threshold;
5481 	eager->tcp_second_ctimer_threshold =
5482 	    tcp->tcp_second_ctimer_threshold;
5483 
5484 	/*
5485 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5486 	 * If it does not, the eager's receive window will be set to the
5487 	 * listener's receive window later in this function.
5488 	 */
5489 	eager->tcp_rwnd = 0;
5490 
5491 	/*
5492 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5493 	 * calling tcp_process_options() where tcp_mss_set() is called
5494 	 * to set the initial cwnd.
5495 	 */
5496 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5497 
5498 	/*
5499 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5500 	 * zone id before the accept is completed in tcp_wput_accept().
5501 	 */
5502 	econnp->conn_zoneid = connp->conn_zoneid;
5503 	econnp->conn_allzones = connp->conn_allzones;
5504 
5505 	/* Copy nexthop information from listener to eager */
5506 	if (connp->conn_nexthop_set) {
5507 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5508 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5509 	}
5510 
5511 	/*
5512 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5513 	 * eager is accepted
5514 	 */
5515 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5516 	crhold(credp);
5517 
5518 	/*
5519 	 * If the caller has the process-wide flag set, then default to MAC
5520 	 * exempt mode.  This allows read-down to unlabeled hosts.
5521 	 */
5522 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5523 		econnp->conn_mac_exempt = B_TRUE;
5524 
5525 	if (is_system_labeled()) {
5526 		cred_t *cr;
5527 
5528 		if (connp->conn_mlp_type != mlptSingle) {
5529 			cr = econnp->conn_peercred = DB_CRED(mp);
5530 			if (cr != NULL)
5531 				crhold(cr);
5532 			else
5533 				cr = econnp->conn_cred;
5534 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5535 			    econnp, cred_t *, cr)
5536 		} else {
5537 			cr = econnp->conn_cred;
5538 			DTRACE_PROBE2(syn_accept, conn_t *,
5539 			    econnp, cred_t *, cr)
5540 		}
5541 
5542 		if (!tcp_update_label(eager, cr)) {
5543 			DTRACE_PROBE3(
5544 			    tx__ip__log__error__connrequest__tcp,
5545 			    char *, "eager connp(1) label on SYN mp(2) failed",
5546 			    conn_t *, econnp, mblk_t *, mp);
5547 			goto error3;
5548 		}
5549 	}
5550 
5551 	eager->tcp_hard_binding = B_TRUE;
5552 
5553 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5554 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5555 
5556 	CL_INET_CONNECT(connp, eager, B_FALSE, err);
5557 	if (err != 0) {
5558 		tcp_bind_hash_remove(eager);
5559 		goto error3;
5560 	}
5561 
5562 	/*
5563 	 * No need to check for multicast destination since ip will only pass
5564 	 * up multicasts to those that have expressed interest
5565 	 * TODO: what about rejecting broadcasts?
5566 	 * Also check that source is not a multicast or broadcast address.
5567 	 */
5568 	eager->tcp_state = TCPS_SYN_RCVD;
5569 
5570 
5571 	/*
5572 	 * There should be no ire in the mp as we are being called after
5573 	 * receiving the SYN.
5574 	 */
5575 	ASSERT(tcp_ire_mp(&mp) == NULL);
5576 
5577 	/*
5578 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5579 	 */
5580 
5581 	if (tcp_adapt_ire(eager, NULL) == 0) {
5582 		/* Undo the bind_hash_insert */
5583 		tcp_bind_hash_remove(eager);
5584 		goto error3;
5585 	}
5586 
5587 	/* Process all TCP options. */
5588 	tcp_process_options(eager, tcph);
5589 
5590 	/* Is the other end ECN capable? */
5591 	if (tcps->tcps_ecn_permitted >= 1 &&
5592 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5593 		eager->tcp_ecn_ok = B_TRUE;
5594 	}
5595 
5596 	/*
5597 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5598 	 * window size changed via SO_RCVBUF option.  First round up the
5599 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5600 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5601 	 * setting.
5602 	 *
5603 	 * Note if there is a rpipe metric associated with the remote host,
5604 	 * we should not inherit receive window size from listener.
5605 	 */
5606 	eager->tcp_rwnd = MSS_ROUNDUP(
5607 	    (eager->tcp_rwnd == 0 ? tcp->tcp_recv_hiwater:
5608 	    eager->tcp_rwnd), eager->tcp_mss);
5609 	if (eager->tcp_snd_ws_ok)
5610 		tcp_set_ws_value(eager);
5611 	/*
5612 	 * Note that this is the only place tcp_rwnd_set() is called for
5613 	 * accepting a connection.  We need to call it here instead of
5614 	 * after the 3-way handshake because we need to tell the other
5615 	 * side our rwnd in the SYN-ACK segment.
5616 	 */
5617 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5618 
5619 	/*
5620 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5621 	 * via soaccept()->soinheritoptions() which essentially applies
5622 	 * all the listener options to the new STREAM. The options that we
5623 	 * need to take care of are:
5624 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5625 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5626 	 * SO_SNDBUF, SO_RCVBUF.
5627 	 *
5628 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5629 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5630 	 *		tcp_maxpsz_set() gets called later from
5631 	 *		tcp_accept_finish(), the option takes effect.
5632 	 *
5633 	 */
5634 	/* Set the TCP options */
5635 	eager->tcp_recv_hiwater = tcp->tcp_recv_hiwater;
5636 	eager->tcp_recv_lowater = tcp->tcp_recv_lowater;
5637 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5638 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5639 	eager->tcp_oobinline = tcp->tcp_oobinline;
5640 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5641 	eager->tcp_broadcast = tcp->tcp_broadcast;
5642 	eager->tcp_useloopback = tcp->tcp_useloopback;
5643 	eager->tcp_dontroute = tcp->tcp_dontroute;
5644 	eager->tcp_debug = tcp->tcp_debug;
5645 	eager->tcp_linger = tcp->tcp_linger;
5646 	eager->tcp_lingertime = tcp->tcp_lingertime;
5647 	if (tcp->tcp_ka_enabled)
5648 		eager->tcp_ka_enabled = 1;
5649 
5650 	/* Set the IP options */
5651 	econnp->conn_broadcast = connp->conn_broadcast;
5652 	econnp->conn_loopback = connp->conn_loopback;
5653 	econnp->conn_dontroute = connp->conn_dontroute;
5654 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5655 
5656 	/* Put a ref on the listener for the eager. */
5657 	CONN_INC_REF(connp);
5658 	mutex_enter(&tcp->tcp_eager_lock);
5659 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5660 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5661 	tcp->tcp_eager_next_q0 = eager;
5662 	eager->tcp_eager_prev_q0 = tcp;
5663 
5664 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5665 	eager->tcp_listener = tcp;
5666 	eager->tcp_saved_listener = tcp;
5667 
5668 	/*
5669 	 * Tag this detached tcp vector for later retrieval
5670 	 * by our listener client in tcp_accept().
5671 	 */
5672 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5673 	tcp->tcp_conn_req_cnt_q0++;
5674 	if (++tcp->tcp_conn_req_seqnum == -1) {
5675 		/*
5676 		 * -1 is "special" and defined in TPI as something
5677 		 * that should never be used in T_CONN_IND
5678 		 */
5679 		++tcp->tcp_conn_req_seqnum;
5680 	}
5681 	mutex_exit(&tcp->tcp_eager_lock);
5682 
5683 	if (tcp->tcp_syn_defense) {
5684 		/* Don't drop the SYN that comes from a good IP source */
5685 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5686 		if (addr_cache != NULL && eager->tcp_remote ==
5687 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5688 			eager->tcp_dontdrop = B_TRUE;
5689 		}
5690 	}
5691 
5692 	/*
5693 	 * We need to insert the eager in its own perimeter but as soon
5694 	 * as we do that, we expose the eager to the classifier and
5695 	 * should not touch any field outside the eager's perimeter.
5696 	 * So do all the work necessary before inserting the eager
5697 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5698 	 * will succeed but undo everything if it fails.
5699 	 */
5700 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5701 	eager->tcp_irs = seg_seq;
5702 	eager->tcp_rack = seg_seq;
5703 	eager->tcp_rnxt = seg_seq + 1;
5704 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5705 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5706 	eager->tcp_state = TCPS_SYN_RCVD;
5707 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5708 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5709 	if (mp1 == NULL) {
5710 		/*
5711 		 * Increment the ref count as we are going to
5712 		 * enqueueing an mp in squeue
5713 		 */
5714 		CONN_INC_REF(econnp);
5715 		goto error;
5716 	}
5717 	DB_CPID(mp1) = tcp->tcp_cpid;
5718 	mblk_setcred(mp1, tcp->tcp_cred);
5719 	eager->tcp_cpid = tcp->tcp_cpid;
5720 	eager->tcp_open_time = lbolt64;
5721 
5722 	/*
5723 	 * We need to start the rto timer. In normal case, we start
5724 	 * the timer after sending the packet on the wire (or at
5725 	 * least believing that packet was sent by waiting for
5726 	 * CALL_IP_WPUT() to return). Since this is the first packet
5727 	 * being sent on the wire for the eager, our initial tcp_rto
5728 	 * is at least tcp_rexmit_interval_min which is a fairly
5729 	 * large value to allow the algorithm to adjust slowly to large
5730 	 * fluctuations of RTT during first few transmissions.
5731 	 *
5732 	 * Starting the timer first and then sending the packet in this
5733 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5734 	 * is of the order of several 100ms and starting the timer
5735 	 * first and then sending the packet will result in difference
5736 	 * of few micro seconds.
5737 	 *
5738 	 * Without this optimization, we are forced to hold the fanout
5739 	 * lock across the ipcl_bind_insert() and sending the packet
5740 	 * so that we don't race against an incoming packet (maybe RST)
5741 	 * for this eager.
5742 	 *
5743 	 * It is necessary to acquire an extra reference on the eager
5744 	 * at this point and hold it until after tcp_send_data() to
5745 	 * ensure against an eager close race.
5746 	 */
5747 
5748 	CONN_INC_REF(eager->tcp_connp);
5749 
5750 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5751 
5752 	/*
5753 	 * Insert the eager in its own perimeter now. We are ready to deal
5754 	 * with any packets on eager.
5755 	 */
5756 	if (eager->tcp_ipversion == IPV4_VERSION) {
5757 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5758 			goto error;
5759 		}
5760 	} else {
5761 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5762 			goto error;
5763 		}
5764 	}
5765 
5766 	/* mark conn as fully-bound */
5767 	econnp->conn_fully_bound = B_TRUE;
5768 
5769 	/* Send the SYN-ACK */
5770 	tcp_send_data(eager, eager->tcp_wq, mp1);
5771 	CONN_DEC_REF(eager->tcp_connp);
5772 	freemsg(mp);
5773 
5774 	return;
5775 error:
5776 	freemsg(mp1);
5777 	eager->tcp_closemp_used = B_TRUE;
5778 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5779 	mp1 = &eager->tcp_closemp;
5780 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5781 	    econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5782 
5783 	/*
5784 	 * If a connection already exists, send the mp to that connections so
5785 	 * that it can be appropriately dealt with.
5786 	 */
5787 	ipst = tcps->tcps_netstack->netstack_ip;
5788 
5789 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
5790 		if (!IPCL_IS_CONNECTED(econnp)) {
5791 			/*
5792 			 * Something bad happened. ipcl_conn_insert()
5793 			 * failed because a connection already existed
5794 			 * in connected hash but we can't find it
5795 			 * anymore (someone blew it away). Just
5796 			 * free this message and hopefully remote
5797 			 * will retransmit at which time the SYN can be
5798 			 * treated as a new connection or dealth with
5799 			 * a TH_RST if a connection already exists.
5800 			 */
5801 			CONN_DEC_REF(econnp);
5802 			freemsg(mp);
5803 		} else {
5804 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp,
5805 			    tcp_input, econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5806 		}
5807 	} else {
5808 		/* Nobody wants this packet */
5809 		freemsg(mp);
5810 	}
5811 	return;
5812 error3:
5813 	CONN_DEC_REF(econnp);
5814 error2:
5815 	freemsg(mp);
5816 }
5817 
5818 /*
5819  * In an ideal case of vertical partition in NUMA architecture, its
5820  * beneficial to have the listener and all the incoming connections
5821  * tied to the same squeue. The other constraint is that incoming
5822  * connections should be tied to the squeue attached to interrupted
5823  * CPU for obvious locality reason so this leaves the listener to
5824  * be tied to the same squeue. Our only problem is that when listener
5825  * is binding, the CPU that will get interrupted by the NIC whose
5826  * IP address the listener is binding to is not even known. So
5827  * the code below allows us to change that binding at the time the
5828  * CPU is interrupted by virtue of incoming connection's squeue.
5829  *
5830  * This is usefull only in case of a listener bound to a specific IP
5831  * address. For other kind of listeners, they get bound the
5832  * very first time and there is no attempt to rebind them.
5833  */
5834 void
5835 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5836 {
5837 	conn_t		*connp = (conn_t *)arg;
5838 	squeue_t	*sqp = (squeue_t *)arg2;
5839 	squeue_t	*new_sqp;
5840 	uint32_t	conn_flags;
5841 
5842 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5843 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5844 	} else {
5845 		goto done;
5846 	}
5847 
5848 	if (connp->conn_fanout == NULL)
5849 		goto done;
5850 
5851 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5852 		mutex_enter(&connp->conn_fanout->connf_lock);
5853 		mutex_enter(&connp->conn_lock);
5854 		/*
5855 		 * No one from read or write side can access us now
5856 		 * except for already queued packets on this squeue.
5857 		 * But since we haven't changed the squeue yet, they
5858 		 * can't execute. If they are processed after we have
5859 		 * changed the squeue, they are sent back to the
5860 		 * correct squeue down below.
5861 		 * But a listner close can race with processing of
5862 		 * incoming SYN. If incoming SYN processing changes
5863 		 * the squeue then the listener close which is waiting
5864 		 * to enter the squeue would operate on the wrong
5865 		 * squeue. Hence we don't change the squeue here unless
5866 		 * the refcount is exactly the minimum refcount. The
5867 		 * minimum refcount of 4 is counted as - 1 each for
5868 		 * TCP and IP, 1 for being in the classifier hash, and
5869 		 * 1 for the mblk being processed.
5870 		 */
5871 
5872 		if (connp->conn_ref != 4 ||
5873 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5874 			mutex_exit(&connp->conn_lock);
5875 			mutex_exit(&connp->conn_fanout->connf_lock);
5876 			goto done;
5877 		}
5878 		if (connp->conn_sqp != new_sqp) {
5879 			while (connp->conn_sqp != new_sqp)
5880 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5881 		}
5882 
5883 		do {
5884 			conn_flags = connp->conn_flags;
5885 			conn_flags |= IPCL_FULLY_BOUND;
5886 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5887 			    conn_flags);
5888 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5889 
5890 		mutex_exit(&connp->conn_fanout->connf_lock);
5891 		mutex_exit(&connp->conn_lock);
5892 	}
5893 
5894 done:
5895 	if (connp->conn_sqp != sqp) {
5896 		CONN_INC_REF(connp);
5897 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5898 		    SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5899 	} else {
5900 		tcp_conn_request(connp, mp, sqp);
5901 	}
5902 }
5903 
5904 /*
5905  * Successful connect request processing begins when our client passes
5906  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5907  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5908  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_tpi_connect() -> IP
5909  *   upstream <- tcp_rput()		<- IP
5910  * After various error checks are completed, tcp_tpi_connect() lays
5911  * the target address and port into the composite header template,
5912  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5913  * request followed by an IRE request, and passes the three mblk message
5914  * down to IP looking like this:
5915  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5916  * Processing continues in tcp_rput() when we receive the following message:
5917  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5918  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5919  * to fire off the connection request, and then passes the T_OK_ACK mblk
5920  * upstream that we filled in below.  There are, of course, numerous
5921  * error conditions along the way which truncate the processing described
5922  * above.
5923  */
5924 static void
5925 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5926 {
5927 	sin_t		*sin;
5928 	queue_t		*q = tcp->tcp_wq;
5929 	struct T_conn_req	*tcr;
5930 	struct sockaddr	*sa;
5931 	socklen_t	len;
5932 	int		error;
5933 
5934 	tcr = (struct T_conn_req *)mp->b_rptr;
5935 
5936 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5937 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5938 		tcp_err_ack(tcp, mp, TPROTO, 0);
5939 		return;
5940 	}
5941 
5942 	/*
5943 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5944 	 * will always have that to send up.  Otherwise, we need to do
5945 	 * special handling in case the allocation fails at that time.
5946 	 * If the end point is TPI, the tcp_t can be reused and the
5947 	 * tcp_ordrel_mp may be allocated already.
5948 	 */
5949 	if (tcp->tcp_ordrel_mp == NULL) {
5950 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5951 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5952 			return;
5953 		}
5954 	}
5955 
5956 	/*
5957 	 * Determine packet type based on type of address passed in
5958 	 * the request should contain an IPv4 or IPv6 address.
5959 	 * Make sure that address family matches the type of
5960 	 * family of the the address passed down
5961 	 */
5962 	switch (tcr->DEST_length) {
5963 	default:
5964 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5965 		return;
5966 
5967 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5968 		/*
5969 		 * XXX: The check for valid DEST_length was not there
5970 		 * in earlier releases and some buggy
5971 		 * TLI apps (e.g Sybase) got away with not feeding
5972 		 * in sin_zero part of address.
5973 		 * We allow that bug to keep those buggy apps humming.
5974 		 * Test suites require the check on DEST_length.
5975 		 * We construct a new mblk with valid DEST_length
5976 		 * free the original so the rest of the code does
5977 		 * not have to keep track of this special shorter
5978 		 * length address case.
5979 		 */
5980 		mblk_t *nmp;
5981 		struct T_conn_req *ntcr;
5982 		sin_t *nsin;
5983 
5984 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5985 		    tcr->OPT_length, BPRI_HI);
5986 		if (nmp == NULL) {
5987 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5988 			return;
5989 		}
5990 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5991 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5992 		ntcr->PRIM_type = T_CONN_REQ;
5993 		ntcr->DEST_length = sizeof (sin_t);
5994 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5995 
5996 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5997 		*nsin = sin_null;
5998 		/* Get pointer to shorter address to copy from original mp */
5999 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6000 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6001 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6002 			freemsg(nmp);
6003 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6004 			return;
6005 		}
6006 		nsin->sin_family = sin->sin_family;
6007 		nsin->sin_port = sin->sin_port;
6008 		nsin->sin_addr = sin->sin_addr;
6009 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6010 		nmp->b_wptr = (uchar_t *)&nsin[1];
6011 		if (tcr->OPT_length != 0) {
6012 			ntcr->OPT_length = tcr->OPT_length;
6013 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6014 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6015 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6016 			    tcr->OPT_length);
6017 			nmp->b_wptr += tcr->OPT_length;
6018 		}
6019 		freemsg(mp);	/* original mp freed */
6020 		mp = nmp;	/* re-initialize original variables */
6021 		tcr = ntcr;
6022 	}
6023 	/* FALLTHRU */
6024 
6025 	case sizeof (sin_t):
6026 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6027 		    sizeof (sin_t));
6028 		len = sizeof (sin_t);
6029 		break;
6030 
6031 	case sizeof (sin6_t):
6032 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6033 		    sizeof (sin6_t));
6034 		len = sizeof (sin6_t);
6035 		break;
6036 	}
6037 
6038 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
6039 	if (error != 0) {
6040 		tcp_err_ack(tcp, mp, TSYSERR, error);
6041 		return;
6042 	}
6043 
6044 	/*
6045 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6046 	 * should key on their sequence number and cut them loose.
6047 	 */
6048 
6049 	/*
6050 	 * If options passed in, feed it for verification and handling
6051 	 */
6052 	if (tcr->OPT_length != 0) {
6053 		mblk_t	*ok_mp;
6054 		mblk_t	*discon_mp;
6055 		mblk_t  *conn_opts_mp;
6056 		int t_error, sys_error, do_disconnect;
6057 
6058 		conn_opts_mp = NULL;
6059 
6060 		if (tcp_conprim_opt_process(tcp, mp,
6061 		    &do_disconnect, &t_error, &sys_error) < 0) {
6062 			if (do_disconnect) {
6063 				ASSERT(t_error == 0 && sys_error == 0);
6064 				discon_mp = mi_tpi_discon_ind(NULL,
6065 				    ECONNREFUSED, 0);
6066 				if (!discon_mp) {
6067 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6068 					    TSYSERR, ENOMEM);
6069 					return;
6070 				}
6071 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6072 				if (!ok_mp) {
6073 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6074 					    TSYSERR, ENOMEM);
6075 					return;
6076 				}
6077 				qreply(q, ok_mp);
6078 				qreply(q, discon_mp); /* no flush! */
6079 			} else {
6080 				ASSERT(t_error != 0);
6081 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6082 				    sys_error);
6083 			}
6084 			return;
6085 		}
6086 		/*
6087 		 * Success in setting options, the mp option buffer represented
6088 		 * by OPT_length/offset has been potentially modified and
6089 		 * contains results of option processing. We copy it in
6090 		 * another mp to save it for potentially influencing returning
6091 		 * it in T_CONN_CONN.
6092 		 */
6093 		if (tcr->OPT_length != 0) { /* there are resulting options */
6094 			conn_opts_mp = copyb(mp);
6095 			if (!conn_opts_mp) {
6096 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6097 				    TSYSERR, ENOMEM);
6098 				return;
6099 			}
6100 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6101 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6102 			/*
6103 			 * Note:
6104 			 * These resulting option negotiation can include any
6105 			 * end-to-end negotiation options but there no such
6106 			 * thing (yet?) in our TCP/IP.
6107 			 */
6108 		}
6109 	}
6110 
6111 	/* call the non-TPI version */
6112 	error = tcp_do_connect(tcp->tcp_connp, sa, len, DB_CRED(mp),
6113 	    DB_CPID(mp));
6114 	if (error < 0) {
6115 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
6116 	} else if (error > 0) {
6117 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
6118 	} else {
6119 		mp = mi_tpi_ok_ack_alloc(mp);
6120 	}
6121 
6122 	/*
6123 	 * Note: Code below is the "failure" case
6124 	 */
6125 	/* return error ack and blow away saved option results if any */
6126 connect_failed:
6127 	if (mp != NULL)
6128 		putnext(tcp->tcp_rq, mp);
6129 	else {
6130 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6131 		    TSYSERR, ENOMEM);
6132 	}
6133 }
6134 
6135 /*
6136  * Handle connect to IPv4 destinations, including connections for AF_INET6
6137  * sockets connecting to IPv4 mapped IPv6 destinations.
6138  */
6139 static int
6140 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
6141     uint_t srcid, cred_t *cr, pid_t pid)
6142 {
6143 	tcph_t	*tcph;
6144 	mblk_t	*mp;
6145 	ipaddr_t dstaddr = *dstaddrp;
6146 	int32_t	oldstate;
6147 	uint16_t lport;
6148 	int	error = 0;
6149 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6150 
6151 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6152 
6153 	/* Check for attempt to connect to INADDR_ANY */
6154 	if (dstaddr == INADDR_ANY)  {
6155 		/*
6156 		 * SunOS 4.x and 4.3 BSD allow an application
6157 		 * to connect a TCP socket to INADDR_ANY.
6158 		 * When they do this, the kernel picks the
6159 		 * address of one interface and uses it
6160 		 * instead.  The kernel usually ends up
6161 		 * picking the address of the loopback
6162 		 * interface.  This is an undocumented feature.
6163 		 * However, we provide the same thing here
6164 		 * in order to have source and binary
6165 		 * compatibility with SunOS 4.x.
6166 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6167 		 * generate the T_CONN_CON.
6168 		 */
6169 		dstaddr = htonl(INADDR_LOOPBACK);
6170 		*dstaddrp = dstaddr;
6171 	}
6172 
6173 	/* Handle __sin6_src_id if socket not bound to an IP address */
6174 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6175 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6176 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6177 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6178 		    tcp->tcp_ipha->ipha_src);
6179 	}
6180 
6181 	/*
6182 	 * Don't let an endpoint connect to itself.  Note that
6183 	 * the test here does not catch the case where the
6184 	 * source IP addr was left unspecified by the user. In
6185 	 * this case, the source addr is set in tcp_adapt_ire()
6186 	 * using the reply to the T_BIND message that we send
6187 	 * down to IP here and the check is repeated in tcp_rput_other.
6188 	 */
6189 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6190 	    dstport == tcp->tcp_lport) {
6191 		error = -TBADADDR;
6192 		goto failed;
6193 	}
6194 
6195 	tcp->tcp_ipha->ipha_dst = dstaddr;
6196 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6197 
6198 	/*
6199 	 * Massage a source route if any putting the first hop
6200 	 * in iph_dst. Compute a starting value for the checksum which
6201 	 * takes into account that the original iph_dst should be
6202 	 * included in the checksum but that ip will include the
6203 	 * first hop in the source route in the tcp checksum.
6204 	 */
6205 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6206 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6207 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6208 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6209 	if ((int)tcp->tcp_sum < 0)
6210 		tcp->tcp_sum--;
6211 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6212 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6213 	    (tcp->tcp_sum >> 16));
6214 	tcph = tcp->tcp_tcph;
6215 	*(uint16_t *)tcph->th_fport = dstport;
6216 	tcp->tcp_fport = dstport;
6217 
6218 	oldstate = tcp->tcp_state;
6219 	/*
6220 	 * At this point the remote destination address and remote port fields
6221 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6222 	 * have to see which state tcp was in so we can take apropriate action.
6223 	 */
6224 	if (oldstate == TCPS_IDLE) {
6225 		/*
6226 		 * We support a quick connect capability here, allowing
6227 		 * clients to transition directly from IDLE to SYN_SENT
6228 		 * tcp_bindi will pick an unused port, insert the connection
6229 		 * in the bind hash and transition to BOUND state.
6230 		 */
6231 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6232 		    tcp, B_TRUE);
6233 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6234 		    B_FALSE, B_FALSE);
6235 		if (lport == 0) {
6236 			error = -TNOADDR;
6237 			goto failed;
6238 		}
6239 	}
6240 	tcp->tcp_state = TCPS_SYN_SENT;
6241 
6242 	mp = allocb(sizeof (ire_t), BPRI_HI);
6243 	if (mp == NULL) {
6244 		tcp->tcp_state = oldstate;
6245 		error = ENOMEM;
6246 		goto failed;
6247 	}
6248 	mp->b_wptr += sizeof (ire_t);
6249 	mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6250 	tcp->tcp_hard_binding = 1;
6251 	if (cr == NULL) {
6252 		cr = tcp->tcp_cred;
6253 		pid = tcp->tcp_cpid;
6254 	}
6255 	mblk_setcred(mp, cr);
6256 	DB_CPID(mp) = pid;
6257 
6258 	/*
6259 	 * We need to make sure that the conn_recv is set to a non-null
6260 	 * value before we insert the conn_t into the classifier table.
6261 	 * This is to avoid a race with an incoming packet which does
6262 	 * an ipcl_classify().
6263 	 */
6264 	tcp->tcp_connp->conn_recv = tcp_input;
6265 
6266 	if (tcp->tcp_family == AF_INET) {
6267 		error = ip_proto_bind_connected_v4(tcp->tcp_connp, &mp,
6268 		    IPPROTO_TCP, &tcp->tcp_ipha->ipha_src, tcp->tcp_lport,
6269 		    tcp->tcp_remote, tcp->tcp_fport, B_TRUE, B_TRUE);
6270 	} else {
6271 		in6_addr_t v6src;
6272 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6273 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6274 		} else {
6275 			v6src = tcp->tcp_ip6h->ip6_src;
6276 		}
6277 		error = ip_proto_bind_connected_v6(tcp->tcp_connp, &mp,
6278 		    IPPROTO_TCP, &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6279 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE);
6280 	}
6281 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6282 	tcp->tcp_active_open = 1;
6283 
6284 	return (tcp_post_ip_bind(tcp, mp, error));
6285 failed:
6286 	/* return error ack and blow away saved option results if any */
6287 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6288 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6289 	return (error);
6290 }
6291 
6292 /*
6293  * Handle connect to IPv6 destinations.
6294  */
6295 static int
6296 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
6297     uint32_t flowinfo, uint_t srcid, uint32_t scope_id, cred_t *cr, pid_t pid)
6298 {
6299 	tcph_t	*tcph;
6300 	mblk_t	*mp;
6301 	ip6_rthdr_t *rth;
6302 	int32_t  oldstate;
6303 	uint16_t lport;
6304 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6305 	int	error = 0;
6306 	conn_t	*connp = tcp->tcp_connp;
6307 
6308 	ASSERT(tcp->tcp_family == AF_INET6);
6309 
6310 	/*
6311 	 * If we're here, it means that the destination address is a native
6312 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6313 	 * reason why it might not be IPv6 is if the socket was bound to an
6314 	 * IPv4-mapped IPv6 address.
6315 	 */
6316 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6317 		return (-TBADADDR);
6318 	}
6319 
6320 	/*
6321 	 * Interpret a zero destination to mean loopback.
6322 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6323 	 * generate the T_CONN_CON.
6324 	 */
6325 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6326 		*dstaddrp = ipv6_loopback;
6327 	}
6328 
6329 	/* Handle __sin6_src_id if socket not bound to an IP address */
6330 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6331 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6332 		    connp->conn_zoneid, tcps->tcps_netstack);
6333 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6334 	}
6335 
6336 	/*
6337 	 * Take care of the scope_id now and add ip6i_t
6338 	 * if ip6i_t is not already allocated through TCP
6339 	 * sticky options. At this point tcp_ip6h does not
6340 	 * have dst info, thus use dstaddrp.
6341 	 */
6342 	if (scope_id != 0 &&
6343 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6344 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6345 		ip6i_t  *ip6i;
6346 
6347 		ipp->ipp_ifindex = scope_id;
6348 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6349 
6350 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6351 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6352 			/* Already allocated */
6353 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6354 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6355 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6356 		} else {
6357 			int reterr;
6358 
6359 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6360 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6361 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6362 			reterr = tcp_build_hdrs(tcp);
6363 			if (reterr != 0)
6364 				goto failed;
6365 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6366 		}
6367 	}
6368 
6369 	/*
6370 	 * Don't let an endpoint connect to itself.  Note that
6371 	 * the test here does not catch the case where the
6372 	 * source IP addr was left unspecified by the user. In
6373 	 * this case, the source addr is set in tcp_adapt_ire()
6374 	 * using the reply to the T_BIND message that we send
6375 	 * down to IP here and the check is repeated in tcp_rput_other.
6376 	 */
6377 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6378 	    (dstport == tcp->tcp_lport)) {
6379 		error = -TBADADDR;
6380 		goto failed;
6381 	}
6382 
6383 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6384 	tcp->tcp_remote_v6 = *dstaddrp;
6385 	tcp->tcp_ip6h->ip6_vcf =
6386 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6387 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6388 
6389 	/*
6390 	 * Massage a routing header (if present) putting the first hop
6391 	 * in ip6_dst. Compute a starting value for the checksum which
6392 	 * takes into account that the original ip6_dst should be
6393 	 * included in the checksum but that ip will include the
6394 	 * first hop in the source route in the tcp checksum.
6395 	 */
6396 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6397 	if (rth != NULL) {
6398 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6399 		    tcps->tcps_netstack);
6400 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6401 		    (tcp->tcp_sum >> 16));
6402 	} else {
6403 		tcp->tcp_sum = 0;
6404 	}
6405 
6406 	tcph = tcp->tcp_tcph;
6407 	*(uint16_t *)tcph->th_fport = dstport;
6408 	tcp->tcp_fport = dstport;
6409 
6410 	oldstate = tcp->tcp_state;
6411 	/*
6412 	 * At this point the remote destination address and remote port fields
6413 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6414 	 * have to see which state tcp was in so we can take apropriate action.
6415 	 */
6416 	if (oldstate == TCPS_IDLE) {
6417 		/*
6418 		 * We support a quick connect capability here, allowing
6419 		 * clients to transition directly from IDLE to SYN_SENT
6420 		 * tcp_bindi will pick an unused port, insert the connection
6421 		 * in the bind hash and transition to BOUND state.
6422 		 */
6423 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6424 		    tcp, B_TRUE);
6425 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6426 		    B_FALSE, B_FALSE);
6427 		if (lport == 0) {
6428 			error = -TNOADDR;
6429 			goto failed;
6430 		}
6431 	}
6432 	tcp->tcp_state = TCPS_SYN_SENT;
6433 
6434 	mp = allocb(sizeof (ire_t), BPRI_HI);
6435 	if (mp != NULL) {
6436 		in6_addr_t v6src;
6437 
6438 		mp->b_wptr += sizeof (ire_t);
6439 		mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6440 		if (cr == NULL) {
6441 			cr = tcp->tcp_cred;
6442 			pid = tcp->tcp_cpid;
6443 		}
6444 		mblk_setcred(mp, cr);
6445 		DB_CPID(mp) = pid;
6446 		tcp->tcp_hard_binding = 1;
6447 
6448 		/*
6449 		 * We need to make sure that the conn_recv is set to a non-null
6450 		 * value before we insert the conn_t into the classifier table.
6451 		 * This is to avoid a race with an incoming packet which does
6452 		 * an ipcl_classify().
6453 		 */
6454 		tcp->tcp_connp->conn_recv = tcp_input;
6455 
6456 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6457 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6458 		} else {
6459 			v6src = tcp->tcp_ip6h->ip6_src;
6460 		}
6461 		error = ip_proto_bind_connected_v6(connp, &mp, IPPROTO_TCP,
6462 		    &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6463 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE);
6464 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6465 		tcp->tcp_active_open = 1;
6466 
6467 		return (tcp_post_ip_bind(tcp, mp, error));
6468 	}
6469 	/* Error case */
6470 	tcp->tcp_state = oldstate;
6471 	error = ENOMEM;
6472 
6473 failed:
6474 	/* return error ack and blow away saved option results if any */
6475 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6476 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6477 	return (error);
6478 }
6479 
6480 /*
6481  * We need a stream q for detached closing tcp connections
6482  * to use.  Our client hereby indicates that this q is the
6483  * one to use.
6484  */
6485 static void
6486 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6487 {
6488 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6489 	queue_t	*q = tcp->tcp_wq;
6490 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6491 
6492 #ifdef NS_DEBUG
6493 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6494 	    tcps->tcps_netstack->netstack_stackid);
6495 #endif
6496 	mp->b_datap->db_type = M_IOCACK;
6497 	iocp->ioc_count = 0;
6498 	mutex_enter(&tcps->tcps_g_q_lock);
6499 	if (tcps->tcps_g_q != NULL) {
6500 		mutex_exit(&tcps->tcps_g_q_lock);
6501 		iocp->ioc_error = EALREADY;
6502 	} else {
6503 		int error = 0;
6504 		conn_t *connp = tcp->tcp_connp;
6505 		ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
6506 
6507 		tcps->tcps_g_q = tcp->tcp_rq;
6508 		mutex_exit(&tcps->tcps_g_q_lock);
6509 		iocp->ioc_error = 0;
6510 		iocp->ioc_rval = 0;
6511 		/*
6512 		 * We are passing tcp_sticky_ipp as NULL
6513 		 * as it is not useful for tcp_default queue
6514 		 *
6515 		 * Set conn_recv just in case.
6516 		 */
6517 		tcp->tcp_connp->conn_recv = tcp_conn_request;
6518 
6519 		ASSERT(connp->conn_af_isv6);
6520 		connp->conn_ulp = IPPROTO_TCP;
6521 
6522 		if (ipst->ips_ipcl_proto_fanout_v6[IPPROTO_TCP].connf_head !=
6523 		    NULL || connp->conn_mac_exempt) {
6524 			error = -TBADADDR;
6525 		} else {
6526 			connp->conn_srcv6 = ipv6_all_zeros;
6527 			ipcl_proto_insert_v6(connp, IPPROTO_TCP);
6528 		}
6529 
6530 		(void) tcp_post_ip_bind(tcp, NULL, error);
6531 	}
6532 	qreply(q, mp);
6533 }
6534 
6535 static int
6536 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
6537 {
6538 	tcp_t	*ltcp = NULL;
6539 	conn_t	*connp;
6540 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6541 
6542 	/*
6543 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6544 	 * when the stream is in BOUND state. Do not send a reset,
6545 	 * since the destination IP address is not valid, and it can
6546 	 * be the initialized value of all zeros (broadcast address).
6547 	 *
6548 	 * XXX There won't be any pending bind request to IP.
6549 	 */
6550 	if (tcp->tcp_state <= TCPS_BOUND) {
6551 		if (tcp->tcp_debug) {
6552 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6553 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6554 		}
6555 		return (TOUTSTATE);
6556 	}
6557 
6558 
6559 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6560 
6561 		/*
6562 		 * According to TPI, for non-listeners, ignore seqnum
6563 		 * and disconnect.
6564 		 * Following interpretation of -1 seqnum is historical
6565 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6566 		 * a valid seqnum should not be -1).
6567 		 *
6568 		 *	-1 means disconnect everything
6569 		 *	regardless even on a listener.
6570 		 */
6571 
6572 		int old_state = tcp->tcp_state;
6573 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6574 
6575 		/*
6576 		 * The connection can't be on the tcp_time_wait_head list
6577 		 * since it is not detached.
6578 		 */
6579 		ASSERT(tcp->tcp_time_wait_next == NULL);
6580 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6581 		ASSERT(tcp->tcp_time_wait_expire == 0);
6582 		ltcp = NULL;
6583 		/*
6584 		 * If it used to be a listener, check to make sure no one else
6585 		 * has taken the port before switching back to LISTEN state.
6586 		 */
6587 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6588 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6589 			    tcp->tcp_ipha->ipha_src,
6590 			    tcp->tcp_connp->conn_zoneid, ipst);
6591 			if (connp != NULL)
6592 				ltcp = connp->conn_tcp;
6593 		} else {
6594 			/* Allow tcp_bound_if listeners? */
6595 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6596 			    &tcp->tcp_ip6h->ip6_src, 0,
6597 			    tcp->tcp_connp->conn_zoneid, ipst);
6598 			if (connp != NULL)
6599 				ltcp = connp->conn_tcp;
6600 		}
6601 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6602 			tcp->tcp_state = TCPS_LISTEN;
6603 		} else if (old_state > TCPS_BOUND) {
6604 			tcp->tcp_conn_req_max = 0;
6605 			tcp->tcp_state = TCPS_BOUND;
6606 		}
6607 		if (ltcp != NULL)
6608 			CONN_DEC_REF(ltcp->tcp_connp);
6609 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6610 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6611 		} else if (old_state == TCPS_ESTABLISHED ||
6612 		    old_state == TCPS_CLOSE_WAIT) {
6613 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6614 		}
6615 
6616 		if (tcp->tcp_fused)
6617 			tcp_unfuse(tcp);
6618 
6619 		mutex_enter(&tcp->tcp_eager_lock);
6620 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6621 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6622 			tcp_eager_cleanup(tcp, 0);
6623 		}
6624 		mutex_exit(&tcp->tcp_eager_lock);
6625 
6626 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6627 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6628 
6629 		tcp_reinit(tcp);
6630 
6631 		return (0);
6632 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6633 		return (TBADSEQ);
6634 	}
6635 	return (0);
6636 }
6637 
6638 /*
6639  * Our client hereby directs us to reject the connection request
6640  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6641  * of sending the appropriate RST, not an ICMP error.
6642  */
6643 static void
6644 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6645 {
6646 	t_scalar_t seqnum;
6647 	int	error;
6648 
6649 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6650 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6651 		tcp_err_ack(tcp, mp, TPROTO, 0);
6652 		return;
6653 	}
6654 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6655 	error = tcp_disconnect_common(tcp, seqnum);
6656 	if (error != 0)
6657 		tcp_err_ack(tcp, mp, error, 0);
6658 	else {
6659 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6660 			/* Send M_FLUSH according to TPI */
6661 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6662 		}
6663 		mp = mi_tpi_ok_ack_alloc(mp);
6664 		if (mp)
6665 			putnext(tcp->tcp_rq, mp);
6666 	}
6667 }
6668 
6669 /*
6670  * Diagnostic routine used to return a string associated with the tcp state.
6671  * Note that if the caller does not supply a buffer, it will use an internal
6672  * static string.  This means that if multiple threads call this function at
6673  * the same time, output can be corrupted...  Note also that this function
6674  * does not check the size of the supplied buffer.  The caller has to make
6675  * sure that it is big enough.
6676  */
6677 static char *
6678 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6679 {
6680 	char		buf1[30];
6681 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6682 	char		*buf;
6683 	char		*cp;
6684 	in6_addr_t	local, remote;
6685 	char		local_addrbuf[INET6_ADDRSTRLEN];
6686 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6687 
6688 	if (sup_buf != NULL)
6689 		buf = sup_buf;
6690 	else
6691 		buf = priv_buf;
6692 
6693 	if (tcp == NULL)
6694 		return ("NULL_TCP");
6695 	switch (tcp->tcp_state) {
6696 	case TCPS_CLOSED:
6697 		cp = "TCP_CLOSED";
6698 		break;
6699 	case TCPS_IDLE:
6700 		cp = "TCP_IDLE";
6701 		break;
6702 	case TCPS_BOUND:
6703 		cp = "TCP_BOUND";
6704 		break;
6705 	case TCPS_LISTEN:
6706 		cp = "TCP_LISTEN";
6707 		break;
6708 	case TCPS_SYN_SENT:
6709 		cp = "TCP_SYN_SENT";
6710 		break;
6711 	case TCPS_SYN_RCVD:
6712 		cp = "TCP_SYN_RCVD";
6713 		break;
6714 	case TCPS_ESTABLISHED:
6715 		cp = "TCP_ESTABLISHED";
6716 		break;
6717 	case TCPS_CLOSE_WAIT:
6718 		cp = "TCP_CLOSE_WAIT";
6719 		break;
6720 	case TCPS_FIN_WAIT_1:
6721 		cp = "TCP_FIN_WAIT_1";
6722 		break;
6723 	case TCPS_CLOSING:
6724 		cp = "TCP_CLOSING";
6725 		break;
6726 	case TCPS_LAST_ACK:
6727 		cp = "TCP_LAST_ACK";
6728 		break;
6729 	case TCPS_FIN_WAIT_2:
6730 		cp = "TCP_FIN_WAIT_2";
6731 		break;
6732 	case TCPS_TIME_WAIT:
6733 		cp = "TCP_TIME_WAIT";
6734 		break;
6735 	default:
6736 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6737 		cp = buf1;
6738 		break;
6739 	}
6740 	switch (format) {
6741 	case DISP_ADDR_AND_PORT:
6742 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6743 			/*
6744 			 * Note that we use the remote address in the tcp_b
6745 			 * structure.  This means that it will print out
6746 			 * the real destination address, not the next hop's
6747 			 * address if source routing is used.
6748 			 */
6749 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6750 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6751 
6752 		} else {
6753 			local = tcp->tcp_ip_src_v6;
6754 			remote = tcp->tcp_remote_v6;
6755 		}
6756 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6757 		    sizeof (local_addrbuf));
6758 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6759 		    sizeof (remote_addrbuf));
6760 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6761 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6762 		    ntohs(tcp->tcp_fport), cp);
6763 		break;
6764 	case DISP_PORT_ONLY:
6765 	default:
6766 		(void) mi_sprintf(buf, "[%u, %u] %s",
6767 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6768 		break;
6769 	}
6770 
6771 	return (buf);
6772 }
6773 
6774 /*
6775  * Called via squeue to get on to eager's perimeter. It sends a
6776  * TH_RST if eager is in the fanout table. The listener wants the
6777  * eager to disappear either by means of tcp_eager_blowoff() or
6778  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
6779  * called (via squeue) if the eager cannot be inserted in the
6780  * fanout table in tcp_conn_request().
6781  */
6782 /* ARGSUSED */
6783 void
6784 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6785 {
6786 	conn_t	*econnp = (conn_t *)arg;
6787 	tcp_t	*eager = econnp->conn_tcp;
6788 	tcp_t	*listener = eager->tcp_listener;
6789 	tcp_stack_t	*tcps = eager->tcp_tcps;
6790 
6791 	/*
6792 	 * We could be called because listener is closing. Since
6793 	 * the eager is using listener's queue's, its not safe.
6794 	 * Better use the default queue just to send the TH_RST
6795 	 * out.
6796 	 */
6797 	ASSERT(tcps->tcps_g_q != NULL);
6798 	eager->tcp_rq = tcps->tcps_g_q;
6799 	eager->tcp_wq = WR(tcps->tcps_g_q);
6800 
6801 	/*
6802 	 * An eager's conn_fanout will be NULL if it's a duplicate
6803 	 * for an existing 4-tuples in the conn fanout table.
6804 	 * We don't want to send an RST out in such case.
6805 	 */
6806 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
6807 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6808 		    eager, eager->tcp_snxt, 0, TH_RST);
6809 	}
6810 
6811 	/* We are here because listener wants this eager gone */
6812 	if (listener != NULL) {
6813 		mutex_enter(&listener->tcp_eager_lock);
6814 		tcp_eager_unlink(eager);
6815 		if (eager->tcp_tconnind_started) {
6816 			/*
6817 			 * The eager has sent a conn_ind up to the
6818 			 * listener but listener decides to close
6819 			 * instead. We need to drop the extra ref
6820 			 * placed on eager in tcp_rput_data() before
6821 			 * sending the conn_ind to listener.
6822 			 */
6823 			CONN_DEC_REF(econnp);
6824 		}
6825 		mutex_exit(&listener->tcp_eager_lock);
6826 		CONN_DEC_REF(listener->tcp_connp);
6827 	}
6828 
6829 	if (eager->tcp_state > TCPS_BOUND)
6830 		tcp_close_detached(eager);
6831 }
6832 
6833 /*
6834  * Reset any eager connection hanging off this listener marked
6835  * with 'seqnum' and then reclaim it's resources.
6836  */
6837 static boolean_t
6838 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6839 {
6840 	tcp_t	*eager;
6841 	mblk_t 	*mp;
6842 	tcp_stack_t	*tcps = listener->tcp_tcps;
6843 
6844 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
6845 	eager = listener;
6846 	mutex_enter(&listener->tcp_eager_lock);
6847 	do {
6848 		eager = eager->tcp_eager_next_q;
6849 		if (eager == NULL) {
6850 			mutex_exit(&listener->tcp_eager_lock);
6851 			return (B_FALSE);
6852 		}
6853 	} while (eager->tcp_conn_req_seqnum != seqnum);
6854 
6855 	if (eager->tcp_closemp_used) {
6856 		mutex_exit(&listener->tcp_eager_lock);
6857 		return (B_TRUE);
6858 	}
6859 	eager->tcp_closemp_used = B_TRUE;
6860 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6861 	CONN_INC_REF(eager->tcp_connp);
6862 	mutex_exit(&listener->tcp_eager_lock);
6863 	mp = &eager->tcp_closemp;
6864 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6865 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
6866 	return (B_TRUE);
6867 }
6868 
6869 /*
6870  * Reset any eager connection hanging off this listener
6871  * and then reclaim it's resources.
6872  */
6873 static void
6874 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6875 {
6876 	tcp_t	*eager;
6877 	mblk_t	*mp;
6878 	tcp_stack_t	*tcps = listener->tcp_tcps;
6879 
6880 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6881 
6882 	if (!q0_only) {
6883 		/* First cleanup q */
6884 		TCP_STAT(tcps, tcp_eager_blowoff_q);
6885 		eager = listener->tcp_eager_next_q;
6886 		while (eager != NULL) {
6887 			if (!eager->tcp_closemp_used) {
6888 				eager->tcp_closemp_used = B_TRUE;
6889 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6890 				CONN_INC_REF(eager->tcp_connp);
6891 				mp = &eager->tcp_closemp;
6892 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6893 				    tcp_eager_kill, eager->tcp_connp,
6894 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
6895 			}
6896 			eager = eager->tcp_eager_next_q;
6897 		}
6898 	}
6899 	/* Then cleanup q0 */
6900 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6901 	eager = listener->tcp_eager_next_q0;
6902 	while (eager != listener) {
6903 		if (!eager->tcp_closemp_used) {
6904 			eager->tcp_closemp_used = B_TRUE;
6905 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6906 			CONN_INC_REF(eager->tcp_connp);
6907 			mp = &eager->tcp_closemp;
6908 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6909 			    tcp_eager_kill, eager->tcp_connp, SQ_FILL,
6910 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6911 		}
6912 		eager = eager->tcp_eager_next_q0;
6913 	}
6914 }
6915 
6916 /*
6917  * If we are an eager connection hanging off a listener that hasn't
6918  * formally accepted the connection yet, get off his list and blow off
6919  * any data that we have accumulated.
6920  */
6921 static void
6922 tcp_eager_unlink(tcp_t *tcp)
6923 {
6924 	tcp_t	*listener = tcp->tcp_listener;
6925 
6926 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6927 	ASSERT(listener != NULL);
6928 	if (tcp->tcp_eager_next_q0 != NULL) {
6929 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6930 
6931 		/* Remove the eager tcp from q0 */
6932 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6933 		    tcp->tcp_eager_prev_q0;
6934 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6935 		    tcp->tcp_eager_next_q0;
6936 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6937 		listener->tcp_conn_req_cnt_q0--;
6938 
6939 		tcp->tcp_eager_next_q0 = NULL;
6940 		tcp->tcp_eager_prev_q0 = NULL;
6941 
6942 		/*
6943 		 * Take the eager out, if it is in the list of droppable
6944 		 * eagers.
6945 		 */
6946 		MAKE_UNDROPPABLE(tcp);
6947 
6948 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6949 			/* we have timed out before */
6950 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6951 			listener->tcp_syn_rcvd_timeout--;
6952 		}
6953 	} else {
6954 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6955 		tcp_t	*prev = NULL;
6956 
6957 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6958 			if (tcpp[0] == tcp) {
6959 				if (listener->tcp_eager_last_q == tcp) {
6960 					/*
6961 					 * If we are unlinking the last
6962 					 * element on the list, adjust
6963 					 * tail pointer. Set tail pointer
6964 					 * to nil when list is empty.
6965 					 */
6966 					ASSERT(tcp->tcp_eager_next_q == NULL);
6967 					if (listener->tcp_eager_last_q ==
6968 					    listener->tcp_eager_next_q) {
6969 						listener->tcp_eager_last_q =
6970 						    NULL;
6971 					} else {
6972 						/*
6973 						 * We won't get here if there
6974 						 * is only one eager in the
6975 						 * list.
6976 						 */
6977 						ASSERT(prev != NULL);
6978 						listener->tcp_eager_last_q =
6979 						    prev;
6980 					}
6981 				}
6982 				tcpp[0] = tcp->tcp_eager_next_q;
6983 				tcp->tcp_eager_next_q = NULL;
6984 				tcp->tcp_eager_last_q = NULL;
6985 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6986 				listener->tcp_conn_req_cnt_q--;
6987 				break;
6988 			}
6989 			prev = tcpp[0];
6990 		}
6991 	}
6992 	tcp->tcp_listener = NULL;
6993 }
6994 
6995 /* Shorthand to generate and send TPI error acks to our client */
6996 static void
6997 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6998 {
6999 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7000 		putnext(tcp->tcp_rq, mp);
7001 }
7002 
7003 /* Shorthand to generate and send TPI error acks to our client */
7004 static void
7005 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7006     int t_error, int sys_error)
7007 {
7008 	struct T_error_ack	*teackp;
7009 
7010 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7011 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7012 		teackp = (struct T_error_ack *)mp->b_rptr;
7013 		teackp->ERROR_prim = primitive;
7014 		teackp->TLI_error = t_error;
7015 		teackp->UNIX_error = sys_error;
7016 		putnext(tcp->tcp_rq, mp);
7017 	}
7018 }
7019 
7020 /*
7021  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7022  * but instead the code relies on:
7023  * - the fact that the address of the array and its size never changes
7024  * - the atomic assignment of the elements of the array
7025  */
7026 /* ARGSUSED */
7027 static int
7028 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7029 {
7030 	int i;
7031 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7032 
7033 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7034 		if (tcps->tcps_g_epriv_ports[i] != 0)
7035 			(void) mi_mpprintf(mp, "%d ",
7036 			    tcps->tcps_g_epriv_ports[i]);
7037 	}
7038 	return (0);
7039 }
7040 
7041 /*
7042  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7043  * threads from changing it at the same time.
7044  */
7045 /* ARGSUSED */
7046 static int
7047 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7048     cred_t *cr)
7049 {
7050 	long	new_value;
7051 	int	i;
7052 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7053 
7054 	/*
7055 	 * Fail the request if the new value does not lie within the
7056 	 * port number limits.
7057 	 */
7058 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7059 	    new_value <= 0 || new_value >= 65536) {
7060 		return (EINVAL);
7061 	}
7062 
7063 	mutex_enter(&tcps->tcps_epriv_port_lock);
7064 	/* Check if the value is already in the list */
7065 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7066 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7067 			mutex_exit(&tcps->tcps_epriv_port_lock);
7068 			return (EEXIST);
7069 		}
7070 	}
7071 	/* Find an empty slot */
7072 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7073 		if (tcps->tcps_g_epriv_ports[i] == 0)
7074 			break;
7075 	}
7076 	if (i == tcps->tcps_g_num_epriv_ports) {
7077 		mutex_exit(&tcps->tcps_epriv_port_lock);
7078 		return (EOVERFLOW);
7079 	}
7080 	/* Set the new value */
7081 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7082 	mutex_exit(&tcps->tcps_epriv_port_lock);
7083 	return (0);
7084 }
7085 
7086 /*
7087  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7088  * threads from changing it at the same time.
7089  */
7090 /* ARGSUSED */
7091 static int
7092 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7093     cred_t *cr)
7094 {
7095 	long	new_value;
7096 	int	i;
7097 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7098 
7099 	/*
7100 	 * Fail the request if the new value does not lie within the
7101 	 * port number limits.
7102 	 */
7103 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7104 	    new_value >= 65536) {
7105 		return (EINVAL);
7106 	}
7107 
7108 	mutex_enter(&tcps->tcps_epriv_port_lock);
7109 	/* Check that the value is already in the list */
7110 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7111 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7112 			break;
7113 	}
7114 	if (i == tcps->tcps_g_num_epriv_ports) {
7115 		mutex_exit(&tcps->tcps_epriv_port_lock);
7116 		return (ESRCH);
7117 	}
7118 	/* Clear the value */
7119 	tcps->tcps_g_epriv_ports[i] = 0;
7120 	mutex_exit(&tcps->tcps_epriv_port_lock);
7121 	return (0);
7122 }
7123 
7124 /* Return the TPI/TLI equivalent of our current tcp_state */
7125 static int
7126 tcp_tpistate(tcp_t *tcp)
7127 {
7128 	switch (tcp->tcp_state) {
7129 	case TCPS_IDLE:
7130 		return (TS_UNBND);
7131 	case TCPS_LISTEN:
7132 		/*
7133 		 * Return whether there are outstanding T_CONN_IND waiting
7134 		 * for the matching T_CONN_RES. Therefore don't count q0.
7135 		 */
7136 		if (tcp->tcp_conn_req_cnt_q > 0)
7137 			return (TS_WRES_CIND);
7138 		else
7139 			return (TS_IDLE);
7140 	case TCPS_BOUND:
7141 		return (TS_IDLE);
7142 	case TCPS_SYN_SENT:
7143 		return (TS_WCON_CREQ);
7144 	case TCPS_SYN_RCVD:
7145 		/*
7146 		 * Note: assumption: this has to the active open SYN_RCVD.
7147 		 * The passive instance is detached in SYN_RCVD stage of
7148 		 * incoming connection processing so we cannot get request
7149 		 * for T_info_ack on it.
7150 		 */
7151 		return (TS_WACK_CRES);
7152 	case TCPS_ESTABLISHED:
7153 		return (TS_DATA_XFER);
7154 	case TCPS_CLOSE_WAIT:
7155 		return (TS_WREQ_ORDREL);
7156 	case TCPS_FIN_WAIT_1:
7157 		return (TS_WIND_ORDREL);
7158 	case TCPS_FIN_WAIT_2:
7159 		return (TS_WIND_ORDREL);
7160 
7161 	case TCPS_CLOSING:
7162 	case TCPS_LAST_ACK:
7163 	case TCPS_TIME_WAIT:
7164 	case TCPS_CLOSED:
7165 		/*
7166 		 * Following TS_WACK_DREQ7 is a rendition of "not
7167 		 * yet TS_IDLE" TPI state. There is no best match to any
7168 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7169 		 * choose a value chosen that will map to TLI/XTI level
7170 		 * state of TSTATECHNG (state is process of changing) which
7171 		 * captures what this dummy state represents.
7172 		 */
7173 		return (TS_WACK_DREQ7);
7174 	default:
7175 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7176 		    tcp->tcp_state, tcp_display(tcp, NULL,
7177 		    DISP_PORT_ONLY));
7178 		return (TS_UNBND);
7179 	}
7180 }
7181 
7182 static void
7183 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7184 {
7185 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7186 
7187 	if (tcp->tcp_family == AF_INET6)
7188 		*tia = tcp_g_t_info_ack_v6;
7189 	else
7190 		*tia = tcp_g_t_info_ack;
7191 	tia->CURRENT_state = tcp_tpistate(tcp);
7192 	tia->OPT_size = tcp_max_optsize;
7193 	if (tcp->tcp_mss == 0) {
7194 		/* Not yet set - tcp_open does not set mss */
7195 		if (tcp->tcp_ipversion == IPV4_VERSION)
7196 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7197 		else
7198 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7199 	} else {
7200 		tia->TIDU_size = tcp->tcp_mss;
7201 	}
7202 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7203 }
7204 
7205 static void
7206 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
7207     t_uscalar_t cap_bits1)
7208 {
7209 	tcap->CAP_bits1 = 0;
7210 
7211 	if (cap_bits1 & TC1_INFO) {
7212 		tcp_copy_info(&tcap->INFO_ack, tcp);
7213 		tcap->CAP_bits1 |= TC1_INFO;
7214 	}
7215 
7216 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7217 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7218 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7219 	}
7220 
7221 }
7222 
7223 /*
7224  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7225  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7226  * tcp_g_t_info_ack.  The current state of the stream is copied from
7227  * tcp_state.
7228  */
7229 static void
7230 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7231 {
7232 	t_uscalar_t		cap_bits1;
7233 	struct T_capability_ack	*tcap;
7234 
7235 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7236 		freemsg(mp);
7237 		return;
7238 	}
7239 
7240 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7241 
7242 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7243 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7244 	if (mp == NULL)
7245 		return;
7246 
7247 	tcap = (struct T_capability_ack *)mp->b_rptr;
7248 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
7249 
7250 	putnext(tcp->tcp_rq, mp);
7251 }
7252 
7253 /*
7254  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7255  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7256  * The current state of the stream is copied from tcp_state.
7257  */
7258 static void
7259 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7260 {
7261 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7262 	    T_INFO_ACK);
7263 	if (!mp) {
7264 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7265 		return;
7266 	}
7267 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7268 	putnext(tcp->tcp_rq, mp);
7269 }
7270 
7271 /* Respond to the TPI addr request */
7272 static void
7273 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7274 {
7275 	sin_t	*sin;
7276 	mblk_t	*ackmp;
7277 	struct T_addr_ack *taa;
7278 
7279 	/* Make it large enough for worst case */
7280 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7281 	    2 * sizeof (sin6_t), 1);
7282 	if (ackmp == NULL) {
7283 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7284 		return;
7285 	}
7286 
7287 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7288 		tcp_addr_req_ipv6(tcp, ackmp);
7289 		return;
7290 	}
7291 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7292 
7293 	bzero(taa, sizeof (struct T_addr_ack));
7294 	ackmp->b_wptr = (uchar_t *)&taa[1];
7295 
7296 	taa->PRIM_type = T_ADDR_ACK;
7297 	ackmp->b_datap->db_type = M_PCPROTO;
7298 
7299 	/*
7300 	 * Note: Following code assumes 32 bit alignment of basic
7301 	 * data structures like sin_t and struct T_addr_ack.
7302 	 */
7303 	if (tcp->tcp_state >= TCPS_BOUND) {
7304 		/*
7305 		 * Fill in local address
7306 		 */
7307 		taa->LOCADDR_length = sizeof (sin_t);
7308 		taa->LOCADDR_offset = sizeof (*taa);
7309 
7310 		sin = (sin_t *)&taa[1];
7311 
7312 		/* Fill zeroes and then intialize non-zero fields */
7313 		*sin = sin_null;
7314 
7315 		sin->sin_family = AF_INET;
7316 
7317 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7318 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7319 
7320 		ackmp->b_wptr = (uchar_t *)&sin[1];
7321 
7322 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7323 			/*
7324 			 * Fill in Remote address
7325 			 */
7326 			taa->REMADDR_length = sizeof (sin_t);
7327 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7328 			    taa->LOCADDR_length);
7329 
7330 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7331 			*sin = sin_null;
7332 			sin->sin_family = AF_INET;
7333 			sin->sin_addr.s_addr = tcp->tcp_remote;
7334 			sin->sin_port = tcp->tcp_fport;
7335 
7336 			ackmp->b_wptr = (uchar_t *)&sin[1];
7337 		}
7338 	}
7339 	putnext(tcp->tcp_rq, ackmp);
7340 }
7341 
7342 /* Assumes that tcp_addr_req gets enough space and alignment */
7343 static void
7344 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7345 {
7346 	sin6_t	*sin6;
7347 	struct T_addr_ack *taa;
7348 
7349 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7350 	ASSERT(OK_32PTR(ackmp->b_rptr));
7351 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7352 	    2 * sizeof (sin6_t));
7353 
7354 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7355 
7356 	bzero(taa, sizeof (struct T_addr_ack));
7357 	ackmp->b_wptr = (uchar_t *)&taa[1];
7358 
7359 	taa->PRIM_type = T_ADDR_ACK;
7360 	ackmp->b_datap->db_type = M_PCPROTO;
7361 
7362 	/*
7363 	 * Note: Following code assumes 32 bit alignment of basic
7364 	 * data structures like sin6_t and struct T_addr_ack.
7365 	 */
7366 	if (tcp->tcp_state >= TCPS_BOUND) {
7367 		/*
7368 		 * Fill in local address
7369 		 */
7370 		taa->LOCADDR_length = sizeof (sin6_t);
7371 		taa->LOCADDR_offset = sizeof (*taa);
7372 
7373 		sin6 = (sin6_t *)&taa[1];
7374 		*sin6 = sin6_null;
7375 
7376 		sin6->sin6_family = AF_INET6;
7377 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7378 		sin6->sin6_port = tcp->tcp_lport;
7379 
7380 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7381 
7382 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7383 			/*
7384 			 * Fill in Remote address
7385 			 */
7386 			taa->REMADDR_length = sizeof (sin6_t);
7387 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7388 			    taa->LOCADDR_length);
7389 
7390 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7391 			*sin6 = sin6_null;
7392 			sin6->sin6_family = AF_INET6;
7393 			sin6->sin6_flowinfo =
7394 			    tcp->tcp_ip6h->ip6_vcf &
7395 			    ~IPV6_VERS_AND_FLOW_MASK;
7396 			sin6->sin6_addr = tcp->tcp_remote_v6;
7397 			sin6->sin6_port = tcp->tcp_fport;
7398 
7399 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7400 		}
7401 	}
7402 	putnext(tcp->tcp_rq, ackmp);
7403 }
7404 
7405 /*
7406  * Handle reinitialization of a tcp structure.
7407  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7408  */
7409 static void
7410 tcp_reinit(tcp_t *tcp)
7411 {
7412 	mblk_t	*mp;
7413 	int 	err;
7414 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7415 
7416 	TCP_STAT(tcps, tcp_reinit_calls);
7417 
7418 	/* tcp_reinit should never be called for detached tcp_t's */
7419 	ASSERT(tcp->tcp_listener == NULL);
7420 	ASSERT((tcp->tcp_family == AF_INET &&
7421 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7422 	    (tcp->tcp_family == AF_INET6 &&
7423 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7424 	    tcp->tcp_ipversion == IPV6_VERSION)));
7425 
7426 	/* Cancel outstanding timers */
7427 	tcp_timers_stop(tcp);
7428 
7429 	/*
7430 	 * Reset everything in the state vector, after updating global
7431 	 * MIB data from instance counters.
7432 	 */
7433 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7434 	tcp->tcp_ibsegs = 0;
7435 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7436 	tcp->tcp_obsegs = 0;
7437 
7438 	tcp_close_mpp(&tcp->tcp_xmit_head);
7439 	if (tcp->tcp_snd_zcopy_aware)
7440 		tcp_zcopy_notify(tcp);
7441 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7442 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7443 	mutex_enter(&tcp->tcp_non_sq_lock);
7444 	if (tcp->tcp_flow_stopped &&
7445 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7446 		tcp_clrqfull(tcp);
7447 	}
7448 	mutex_exit(&tcp->tcp_non_sq_lock);
7449 	tcp_close_mpp(&tcp->tcp_reass_head);
7450 	tcp->tcp_reass_tail = NULL;
7451 	if (tcp->tcp_rcv_list != NULL) {
7452 		/* Free b_next chain */
7453 		tcp_close_mpp(&tcp->tcp_rcv_list);
7454 		tcp->tcp_rcv_last_head = NULL;
7455 		tcp->tcp_rcv_last_tail = NULL;
7456 		tcp->tcp_rcv_cnt = 0;
7457 	}
7458 	tcp->tcp_rcv_last_tail = NULL;
7459 
7460 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7461 		freemsg(mp);
7462 		tcp->tcp_urp_mp = NULL;
7463 	}
7464 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7465 		freemsg(mp);
7466 		tcp->tcp_urp_mark_mp = NULL;
7467 	}
7468 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7469 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7470 		freeb(tcp->tcp_fused_sigurg_mp);
7471 		tcp->tcp_fused_sigurg_mp = NULL;
7472 	}
7473 	if (tcp->tcp_ordrel_mp != NULL) {
7474 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7475 		freeb(tcp->tcp_ordrel_mp);
7476 		tcp->tcp_ordrel_mp = NULL;
7477 	}
7478 
7479 	/*
7480 	 * Following is a union with two members which are
7481 	 * identical types and size so the following cleanup
7482 	 * is enough.
7483 	 */
7484 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7485 
7486 	CL_INET_DISCONNECT(tcp->tcp_connp, tcp);
7487 
7488 	/*
7489 	 * The connection can't be on the tcp_time_wait_head list
7490 	 * since it is not detached.
7491 	 */
7492 	ASSERT(tcp->tcp_time_wait_next == NULL);
7493 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7494 	ASSERT(tcp->tcp_time_wait_expire == 0);
7495 
7496 	if (tcp->tcp_kssl_pending) {
7497 		tcp->tcp_kssl_pending = B_FALSE;
7498 
7499 		/* Don't reset if the initialized by bind. */
7500 		if (tcp->tcp_kssl_ent != NULL) {
7501 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7502 			    KSSL_NO_PROXY);
7503 		}
7504 	}
7505 	if (tcp->tcp_kssl_ctx != NULL) {
7506 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7507 		tcp->tcp_kssl_ctx = NULL;
7508 	}
7509 
7510 	/*
7511 	 * Reset/preserve other values
7512 	 */
7513 	tcp_reinit_values(tcp);
7514 	ipcl_hash_remove(tcp->tcp_connp);
7515 	conn_delete_ire(tcp->tcp_connp, NULL);
7516 	tcp_ipsec_cleanup(tcp);
7517 
7518 	if (tcp->tcp_conn_req_max != 0) {
7519 		/*
7520 		 * This is the case when a TLI program uses the same
7521 		 * transport end point to accept a connection.  This
7522 		 * makes the TCP both a listener and acceptor.  When
7523 		 * this connection is closed, we need to set the state
7524 		 * back to TCPS_LISTEN.  Make sure that the eager list
7525 		 * is reinitialized.
7526 		 *
7527 		 * Note that this stream is still bound to the four
7528 		 * tuples of the previous connection in IP.  If a new
7529 		 * SYN with different foreign address comes in, IP will
7530 		 * not find it and will send it to the global queue.  In
7531 		 * the global queue, TCP will do a tcp_lookup_listener()
7532 		 * to find this stream.  This works because this stream
7533 		 * is only removed from connected hash.
7534 		 *
7535 		 */
7536 		tcp->tcp_state = TCPS_LISTEN;
7537 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7538 		tcp->tcp_eager_next_drop_q0 = tcp;
7539 		tcp->tcp_eager_prev_drop_q0 = tcp;
7540 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7541 		if (tcp->tcp_family == AF_INET6) {
7542 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7543 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7544 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7545 		} else {
7546 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7547 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7548 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7549 		}
7550 	} else {
7551 		tcp->tcp_state = TCPS_BOUND;
7552 	}
7553 
7554 	/*
7555 	 * Initialize to default values
7556 	 * Can't fail since enough header template space already allocated
7557 	 * at open().
7558 	 */
7559 	err = tcp_init_values(tcp);
7560 	ASSERT(err == 0);
7561 	/* Restore state in tcp_tcph */
7562 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7563 	if (tcp->tcp_ipversion == IPV4_VERSION)
7564 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7565 	else
7566 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7567 	/*
7568 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7569 	 * since the lookup funcs can only lookup on tcp_t
7570 	 */
7571 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7572 
7573 	ASSERT(tcp->tcp_ptpbhn != NULL);
7574 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
7575 		tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7576 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
7577 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
7578 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7579 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7580 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7581 }
7582 
7583 /*
7584  * Force values to zero that need be zero.
7585  * Do not touch values asociated with the BOUND or LISTEN state
7586  * since the connection will end up in that state after the reinit.
7587  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7588  * structure!
7589  */
7590 static void
7591 tcp_reinit_values(tcp)
7592 	tcp_t *tcp;
7593 {
7594 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7595 
7596 #ifndef	lint
7597 #define	DONTCARE(x)
7598 #define	PRESERVE(x)
7599 #else
7600 #define	DONTCARE(x)	((x) = (x))
7601 #define	PRESERVE(x)	((x) = (x))
7602 #endif	/* lint */
7603 
7604 	PRESERVE(tcp->tcp_bind_hash_port);
7605 	PRESERVE(tcp->tcp_bind_hash);
7606 	PRESERVE(tcp->tcp_ptpbhn);
7607 	PRESERVE(tcp->tcp_acceptor_hash);
7608 	PRESERVE(tcp->tcp_ptpahn);
7609 
7610 	/* Should be ASSERT NULL on these with new code! */
7611 	ASSERT(tcp->tcp_time_wait_next == NULL);
7612 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7613 	ASSERT(tcp->tcp_time_wait_expire == 0);
7614 	PRESERVE(tcp->tcp_state);
7615 	PRESERVE(tcp->tcp_rq);
7616 	PRESERVE(tcp->tcp_wq);
7617 
7618 	ASSERT(tcp->tcp_xmit_head == NULL);
7619 	ASSERT(tcp->tcp_xmit_last == NULL);
7620 	ASSERT(tcp->tcp_unsent == 0);
7621 	ASSERT(tcp->tcp_xmit_tail == NULL);
7622 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7623 
7624 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7625 	tcp->tcp_suna = 0;			/* Displayed in mib */
7626 	tcp->tcp_swnd = 0;
7627 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7628 
7629 	ASSERT(tcp->tcp_ibsegs == 0);
7630 	ASSERT(tcp->tcp_obsegs == 0);
7631 
7632 	if (tcp->tcp_iphc != NULL) {
7633 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7634 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7635 	}
7636 
7637 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7638 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7639 	DONTCARE(tcp->tcp_ipha);
7640 	DONTCARE(tcp->tcp_ip6h);
7641 	DONTCARE(tcp->tcp_ip_hdr_len);
7642 	DONTCARE(tcp->tcp_tcph);
7643 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7644 	tcp->tcp_valid_bits = 0;
7645 
7646 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7647 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7648 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7649 	tcp->tcp_last_rcv_lbolt = 0;
7650 
7651 	tcp->tcp_init_cwnd = 0;
7652 
7653 	tcp->tcp_urp_last_valid = 0;
7654 	tcp->tcp_hard_binding = 0;
7655 	tcp->tcp_hard_bound = 0;
7656 	PRESERVE(tcp->tcp_cred);
7657 	PRESERVE(tcp->tcp_cpid);
7658 	PRESERVE(tcp->tcp_open_time);
7659 	PRESERVE(tcp->tcp_exclbind);
7660 
7661 	tcp->tcp_fin_acked = 0;
7662 	tcp->tcp_fin_rcvd = 0;
7663 	tcp->tcp_fin_sent = 0;
7664 	tcp->tcp_ordrel_done = 0;
7665 
7666 	tcp->tcp_debug = 0;
7667 	tcp->tcp_dontroute = 0;
7668 	tcp->tcp_broadcast = 0;
7669 
7670 	tcp->tcp_useloopback = 0;
7671 	tcp->tcp_reuseaddr = 0;
7672 	tcp->tcp_oobinline = 0;
7673 	tcp->tcp_dgram_errind = 0;
7674 
7675 	tcp->tcp_detached = 0;
7676 	tcp->tcp_bind_pending = 0;
7677 	tcp->tcp_unbind_pending = 0;
7678 
7679 	tcp->tcp_snd_ws_ok = B_FALSE;
7680 	tcp->tcp_snd_ts_ok = B_FALSE;
7681 	tcp->tcp_linger = 0;
7682 	tcp->tcp_ka_enabled = 0;
7683 	tcp->tcp_zero_win_probe = 0;
7684 
7685 	tcp->tcp_loopback = 0;
7686 	tcp->tcp_refuse = 0;
7687 	tcp->tcp_localnet = 0;
7688 	tcp->tcp_syn_defense = 0;
7689 	tcp->tcp_set_timer = 0;
7690 
7691 	tcp->tcp_active_open = 0;
7692 	tcp->tcp_rexmit = B_FALSE;
7693 	tcp->tcp_xmit_zc_clean = B_FALSE;
7694 
7695 	tcp->tcp_snd_sack_ok = B_FALSE;
7696 	PRESERVE(tcp->tcp_recvdstaddr);
7697 	tcp->tcp_hwcksum = B_FALSE;
7698 
7699 	tcp->tcp_ire_ill_check_done = B_FALSE;
7700 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7701 
7702 	tcp->tcp_mdt = B_FALSE;
7703 	tcp->tcp_mdt_hdr_head = 0;
7704 	tcp->tcp_mdt_hdr_tail = 0;
7705 
7706 	tcp->tcp_conn_def_q0 = 0;
7707 	tcp->tcp_ip_forward_progress = B_FALSE;
7708 	tcp->tcp_anon_priv_bind = 0;
7709 	tcp->tcp_ecn_ok = B_FALSE;
7710 
7711 	tcp->tcp_cwr = B_FALSE;
7712 	tcp->tcp_ecn_echo_on = B_FALSE;
7713 
7714 	if (tcp->tcp_sack_info != NULL) {
7715 		if (tcp->tcp_notsack_list != NULL) {
7716 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7717 		}
7718 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7719 		tcp->tcp_sack_info = NULL;
7720 	}
7721 
7722 	tcp->tcp_rcv_ws = 0;
7723 	tcp->tcp_snd_ws = 0;
7724 	tcp->tcp_ts_recent = 0;
7725 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7726 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7727 	tcp->tcp_if_mtu = 0;
7728 
7729 	ASSERT(tcp->tcp_reass_head == NULL);
7730 	ASSERT(tcp->tcp_reass_tail == NULL);
7731 
7732 	tcp->tcp_cwnd_cnt = 0;
7733 
7734 	ASSERT(tcp->tcp_rcv_list == NULL);
7735 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7736 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7737 	ASSERT(tcp->tcp_rcv_cnt == 0);
7738 
7739 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7740 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7741 	tcp->tcp_csuna = 0;
7742 
7743 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7744 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7745 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7746 	tcp->tcp_rtt_update = 0;
7747 
7748 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7749 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7750 
7751 	tcp->tcp_rack = 0;			/* Displayed in mib */
7752 	tcp->tcp_rack_cnt = 0;
7753 	tcp->tcp_rack_cur_max = 0;
7754 	tcp->tcp_rack_abs_max = 0;
7755 
7756 	tcp->tcp_max_swnd = 0;
7757 
7758 	ASSERT(tcp->tcp_listener == NULL);
7759 
7760 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7761 
7762 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7763 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7764 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7765 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7766 
7767 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7768 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7769 	PRESERVE(tcp->tcp_conn_req_max);
7770 	PRESERVE(tcp->tcp_conn_req_seqnum);
7771 
7772 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7773 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7774 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7775 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7776 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7777 
7778 	tcp->tcp_lingertime = 0;
7779 
7780 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7781 	ASSERT(tcp->tcp_urp_mp == NULL);
7782 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7783 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7784 
7785 	ASSERT(tcp->tcp_eager_next_q == NULL);
7786 	ASSERT(tcp->tcp_eager_last_q == NULL);
7787 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7788 	    tcp->tcp_eager_prev_q0 == NULL) ||
7789 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7790 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7791 
7792 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
7793 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
7794 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
7795 
7796 	tcp->tcp_client_errno = 0;
7797 
7798 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7799 
7800 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7801 
7802 	PRESERVE(tcp->tcp_bound_source_v6);
7803 	tcp->tcp_last_sent_len = 0;
7804 	tcp->tcp_dupack_cnt = 0;
7805 
7806 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7807 	PRESERVE(tcp->tcp_lport);
7808 
7809 	PRESERVE(tcp->tcp_acceptor_lockp);
7810 
7811 	ASSERT(tcp->tcp_ordrel_mp == NULL);
7812 	PRESERVE(tcp->tcp_acceptor_id);
7813 	DONTCARE(tcp->tcp_ipsec_overhead);
7814 
7815 	PRESERVE(tcp->tcp_family);
7816 	if (tcp->tcp_family == AF_INET6) {
7817 		tcp->tcp_ipversion = IPV6_VERSION;
7818 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7819 	} else {
7820 		tcp->tcp_ipversion = IPV4_VERSION;
7821 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7822 	}
7823 
7824 	tcp->tcp_bound_if = 0;
7825 	tcp->tcp_ipv6_recvancillary = 0;
7826 	tcp->tcp_recvifindex = 0;
7827 	tcp->tcp_recvhops = 0;
7828 	tcp->tcp_closed = 0;
7829 	tcp->tcp_cleandeathtag = 0;
7830 	if (tcp->tcp_hopopts != NULL) {
7831 		mi_free(tcp->tcp_hopopts);
7832 		tcp->tcp_hopopts = NULL;
7833 		tcp->tcp_hopoptslen = 0;
7834 	}
7835 	ASSERT(tcp->tcp_hopoptslen == 0);
7836 	if (tcp->tcp_dstopts != NULL) {
7837 		mi_free(tcp->tcp_dstopts);
7838 		tcp->tcp_dstopts = NULL;
7839 		tcp->tcp_dstoptslen = 0;
7840 	}
7841 	ASSERT(tcp->tcp_dstoptslen == 0);
7842 	if (tcp->tcp_rtdstopts != NULL) {
7843 		mi_free(tcp->tcp_rtdstopts);
7844 		tcp->tcp_rtdstopts = NULL;
7845 		tcp->tcp_rtdstoptslen = 0;
7846 	}
7847 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7848 	if (tcp->tcp_rthdr != NULL) {
7849 		mi_free(tcp->tcp_rthdr);
7850 		tcp->tcp_rthdr = NULL;
7851 		tcp->tcp_rthdrlen = 0;
7852 	}
7853 	ASSERT(tcp->tcp_rthdrlen == 0);
7854 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7855 
7856 	/* Reset fusion-related fields */
7857 	tcp->tcp_fused = B_FALSE;
7858 	tcp->tcp_unfusable = B_FALSE;
7859 	tcp->tcp_fused_sigurg = B_FALSE;
7860 	tcp->tcp_direct_sockfs = B_FALSE;
7861 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7862 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7863 	tcp->tcp_loopback_peer = NULL;
7864 	tcp->tcp_fuse_rcv_hiwater = 0;
7865 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7866 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7867 
7868 	tcp->tcp_lso = B_FALSE;
7869 
7870 	tcp->tcp_in_ack_unsent = 0;
7871 	tcp->tcp_cork = B_FALSE;
7872 	tcp->tcp_tconnind_started = B_FALSE;
7873 
7874 	PRESERVE(tcp->tcp_squeue_bytes);
7875 
7876 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7877 	ASSERT(!tcp->tcp_kssl_pending);
7878 	PRESERVE(tcp->tcp_kssl_ent);
7879 
7880 	/* Sodirect */
7881 	tcp->tcp_sodirect = NULL;
7882 
7883 	tcp->tcp_closemp_used = B_FALSE;
7884 
7885 	PRESERVE(tcp->tcp_rsrv_mp);
7886 	PRESERVE(tcp->tcp_rsrv_mp_lock);
7887 
7888 #ifdef DEBUG
7889 	DONTCARE(tcp->tcmp_stk[0]);
7890 #endif
7891 
7892 	PRESERVE(tcp->tcp_connid);
7893 
7894 
7895 #undef	DONTCARE
7896 #undef	PRESERVE
7897 }
7898 
7899 /*
7900  * Allocate necessary resources and initialize state vector.
7901  * Guaranteed not to fail so that when an error is returned,
7902  * the caller doesn't need to do any additional cleanup.
7903  */
7904 int
7905 tcp_init(tcp_t *tcp, queue_t *q)
7906 {
7907 	int	err;
7908 
7909 	tcp->tcp_rq = q;
7910 	tcp->tcp_wq = WR(q);
7911 	tcp->tcp_state = TCPS_IDLE;
7912 	if ((err = tcp_init_values(tcp)) != 0)
7913 		tcp_timers_stop(tcp);
7914 	return (err);
7915 }
7916 
7917 static int
7918 tcp_init_values(tcp_t *tcp)
7919 {
7920 	int	err;
7921 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7922 
7923 	ASSERT((tcp->tcp_family == AF_INET &&
7924 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7925 	    (tcp->tcp_family == AF_INET6 &&
7926 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7927 	    tcp->tcp_ipversion == IPV6_VERSION)));
7928 
7929 	/*
7930 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7931 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7932 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7933 	 * during first few transmissions of a connection as seen in slow
7934 	 * links.
7935 	 */
7936 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
7937 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
7938 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7939 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7940 	    tcps->tcps_conn_grace_period;
7941 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
7942 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
7943 	tcp->tcp_timer_backoff = 0;
7944 	tcp->tcp_ms_we_have_waited = 0;
7945 	tcp->tcp_last_recv_time = lbolt;
7946 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
7947 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7948 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7949 
7950 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
7951 
7952 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
7953 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
7954 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
7955 	/*
7956 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7957 	 * passive open.
7958 	 */
7959 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
7960 
7961 	tcp->tcp_naglim = tcps->tcps_naglim_def;
7962 
7963 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7964 
7965 	tcp->tcp_mdt_hdr_head = 0;
7966 	tcp->tcp_mdt_hdr_tail = 0;
7967 
7968 	/* Reset fusion-related fields */
7969 	tcp->tcp_fused = B_FALSE;
7970 	tcp->tcp_unfusable = B_FALSE;
7971 	tcp->tcp_fused_sigurg = B_FALSE;
7972 	tcp->tcp_direct_sockfs = B_FALSE;
7973 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7974 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7975 	tcp->tcp_loopback_peer = NULL;
7976 	tcp->tcp_fuse_rcv_hiwater = 0;
7977 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7978 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7979 
7980 	/* Sodirect */
7981 	tcp->tcp_sodirect = NULL;
7982 
7983 	/* Initialize the header template */
7984 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7985 		err = tcp_header_init_ipv4(tcp);
7986 	} else {
7987 		err = tcp_header_init_ipv6(tcp);
7988 	}
7989 	if (err)
7990 		return (err);
7991 
7992 	/*
7993 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7994 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7995 	 */
7996 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7997 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
7998 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
7999 
8000 	tcp->tcp_cork = B_FALSE;
8001 	/*
8002 	 * Init the tcp_debug option.  This value determines whether TCP
8003 	 * calls strlog() to print out debug messages.  Doing this
8004 	 * initialization here means that this value is not inherited thru
8005 	 * tcp_reinit().
8006 	 */
8007 	tcp->tcp_debug = tcps->tcps_dbg;
8008 
8009 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8010 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8011 
8012 	return (0);
8013 }
8014 
8015 /*
8016  * Initialize the IPv4 header. Loses any record of any IP options.
8017  */
8018 static int
8019 tcp_header_init_ipv4(tcp_t *tcp)
8020 {
8021 	tcph_t		*tcph;
8022 	uint32_t	sum;
8023 	conn_t		*connp;
8024 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8025 
8026 	/*
8027 	 * This is a simple initialization. If there's
8028 	 * already a template, it should never be too small,
8029 	 * so reuse it.  Otherwise, allocate space for the new one.
8030 	 */
8031 	if (tcp->tcp_iphc == NULL) {
8032 		ASSERT(tcp->tcp_iphc_len == 0);
8033 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8034 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8035 		if (tcp->tcp_iphc == NULL) {
8036 			tcp->tcp_iphc_len = 0;
8037 			return (ENOMEM);
8038 		}
8039 	}
8040 
8041 	/* options are gone; may need a new label */
8042 	connp = tcp->tcp_connp;
8043 	connp->conn_mlp_type = mlptSingle;
8044 	connp->conn_ulp_labeled = !is_system_labeled();
8045 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8046 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8047 	tcp->tcp_ip6h = NULL;
8048 	tcp->tcp_ipversion = IPV4_VERSION;
8049 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8050 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8051 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8052 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8053 	tcp->tcp_ipha->ipha_version_and_hdr_length
8054 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8055 	tcp->tcp_ipha->ipha_ident = 0;
8056 
8057 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8058 	tcp->tcp_tos = 0;
8059 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8060 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8061 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8062 
8063 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8064 	tcp->tcp_tcph = tcph;
8065 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8066 	/*
8067 	 * IP wants our header length in the checksum field to
8068 	 * allow it to perform a single pseudo-header+checksum
8069 	 * calculation on behalf of TCP.
8070 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8071 	 */
8072 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8073 	sum = (sum >> 16) + (sum & 0xFFFF);
8074 	U16_TO_ABE16(sum, tcph->th_sum);
8075 	return (0);
8076 }
8077 
8078 /*
8079  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8080  */
8081 static int
8082 tcp_header_init_ipv6(tcp_t *tcp)
8083 {
8084 	tcph_t	*tcph;
8085 	uint32_t	sum;
8086 	conn_t	*connp;
8087 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8088 
8089 	/*
8090 	 * This is a simple initialization. If there's
8091 	 * already a template, it should never be too small,
8092 	 * so reuse it. Otherwise, allocate space for the new one.
8093 	 * Ensure that there is enough space to "downgrade" the tcp_t
8094 	 * to an IPv4 tcp_t. This requires having space for a full load
8095 	 * of IPv4 options, as well as a full load of TCP options
8096 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8097 	 * than a v6 header and a TCP header with a full load of TCP options
8098 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8099 	 * We want to avoid reallocation in the "downgraded" case when
8100 	 * processing outbound IPv4 options.
8101 	 */
8102 	if (tcp->tcp_iphc == NULL) {
8103 		ASSERT(tcp->tcp_iphc_len == 0);
8104 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8105 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8106 		if (tcp->tcp_iphc == NULL) {
8107 			tcp->tcp_iphc_len = 0;
8108 			return (ENOMEM);
8109 		}
8110 	}
8111 
8112 	/* options are gone; may need a new label */
8113 	connp = tcp->tcp_connp;
8114 	connp->conn_mlp_type = mlptSingle;
8115 	connp->conn_ulp_labeled = !is_system_labeled();
8116 
8117 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8118 	tcp->tcp_ipversion = IPV6_VERSION;
8119 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8120 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8121 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8122 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8123 	tcp->tcp_ipha = NULL;
8124 
8125 	/* Initialize the header template */
8126 
8127 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8128 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8129 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8130 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8131 
8132 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8133 	tcp->tcp_tcph = tcph;
8134 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8135 	/*
8136 	 * IP wants our header length in the checksum field to
8137 	 * allow it to perform a single psuedo-header+checksum
8138 	 * calculation on behalf of TCP.
8139 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8140 	 */
8141 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8142 	sum = (sum >> 16) + (sum & 0xFFFF);
8143 	U16_TO_ABE16(sum, tcph->th_sum);
8144 	return (0);
8145 }
8146 
8147 /* At minimum we need 8 bytes in the TCP header for the lookup */
8148 #define	ICMP_MIN_TCP_HDR	8
8149 
8150 /*
8151  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8152  * passed up by IP. The message is always received on the correct tcp_t.
8153  * Assumes that IP has pulled up everything up to and including the ICMP header.
8154  */
8155 void
8156 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8157 {
8158 	icmph_t *icmph;
8159 	ipha_t	*ipha;
8160 	int	iph_hdr_length;
8161 	tcph_t	*tcph;
8162 	boolean_t ipsec_mctl = B_FALSE;
8163 	boolean_t secure;
8164 	mblk_t *first_mp = mp;
8165 	int32_t new_mss;
8166 	uint32_t ratio;
8167 	size_t mp_size = MBLKL(mp);
8168 	uint32_t seg_seq;
8169 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8170 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8171 
8172 	/* Assume IP provides aligned packets - otherwise toss */
8173 	if (!OK_32PTR(mp->b_rptr)) {
8174 		freemsg(mp);
8175 		return;
8176 	}
8177 
8178 	/*
8179 	 * Since ICMP errors are normal data marked with M_CTL when sent
8180 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8181 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8182 	 */
8183 	if ((mp_size == sizeof (ipsec_info_t)) &&
8184 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8185 		ASSERT(mp->b_cont != NULL);
8186 		mp = mp->b_cont;
8187 		/* IP should have done this */
8188 		ASSERT(OK_32PTR(mp->b_rptr));
8189 		mp_size = MBLKL(mp);
8190 		ipsec_mctl = B_TRUE;
8191 	}
8192 
8193 	/*
8194 	 * Verify that we have a complete outer IP header. If not, drop it.
8195 	 */
8196 	if (mp_size < sizeof (ipha_t)) {
8197 noticmpv4:
8198 		freemsg(first_mp);
8199 		return;
8200 	}
8201 
8202 	ipha = (ipha_t *)mp->b_rptr;
8203 	/*
8204 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8205 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8206 	 */
8207 	switch (IPH_HDR_VERSION(ipha)) {
8208 	case IPV6_VERSION:
8209 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8210 		return;
8211 	case IPV4_VERSION:
8212 		break;
8213 	default:
8214 		goto noticmpv4;
8215 	}
8216 
8217 	/* Skip past the outer IP and ICMP headers */
8218 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8219 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8220 	/*
8221 	 * If we don't have the correct outer IP header length or if the ULP
8222 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8223 	 * send it upstream.
8224 	 */
8225 	if (iph_hdr_length < sizeof (ipha_t) ||
8226 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8227 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8228 		goto noticmpv4;
8229 	}
8230 	ipha = (ipha_t *)&icmph[1];
8231 
8232 	/* Skip past the inner IP and find the ULP header */
8233 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8234 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8235 	/*
8236 	 * If we don't have the correct inner IP header length or if the ULP
8237 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8238 	 * bytes of TCP header, drop it.
8239 	 */
8240 	if (iph_hdr_length < sizeof (ipha_t) ||
8241 	    ipha->ipha_protocol != IPPROTO_TCP ||
8242 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8243 		goto noticmpv4;
8244 	}
8245 
8246 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8247 		if (ipsec_mctl) {
8248 			secure = ipsec_in_is_secure(first_mp);
8249 		} else {
8250 			secure = B_FALSE;
8251 		}
8252 		if (secure) {
8253 			/*
8254 			 * If we are willing to accept this in clear
8255 			 * we don't have to verify policy.
8256 			 */
8257 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8258 				if (!tcp_check_policy(tcp, first_mp,
8259 				    ipha, NULL, secure, ipsec_mctl)) {
8260 					/*
8261 					 * tcp_check_policy called
8262 					 * ip_drop_packet() on failure.
8263 					 */
8264 					return;
8265 				}
8266 			}
8267 		}
8268 	} else if (ipsec_mctl) {
8269 		/*
8270 		 * This is a hard_bound connection. IP has already
8271 		 * verified policy. We don't have to do it again.
8272 		 */
8273 		freeb(first_mp);
8274 		first_mp = mp;
8275 		ipsec_mctl = B_FALSE;
8276 	}
8277 
8278 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8279 	/*
8280 	 * TCP SHOULD check that the TCP sequence number contained in
8281 	 * payload of the ICMP error message is within the range
8282 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8283 	 */
8284 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8285 		/*
8286 		 * The ICMP message is bogus, just drop it.  But if this is
8287 		 * an ICMP too big message, IP has already changed
8288 		 * the ire_max_frag to the bogus value.  We need to change
8289 		 * it back.
8290 		 */
8291 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8292 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8293 			conn_t *connp = tcp->tcp_connp;
8294 			ire_t *ire;
8295 			int flag;
8296 
8297 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8298 				flag = tcp->tcp_ipha->
8299 				    ipha_fragment_offset_and_flags;
8300 			} else {
8301 				flag = 0;
8302 			}
8303 			mutex_enter(&connp->conn_lock);
8304 			if ((ire = connp->conn_ire_cache) != NULL) {
8305 				mutex_enter(&ire->ire_lock);
8306 				mutex_exit(&connp->conn_lock);
8307 				ire->ire_max_frag = tcp->tcp_if_mtu;
8308 				ire->ire_frag_flag |= flag;
8309 				mutex_exit(&ire->ire_lock);
8310 			} else {
8311 				mutex_exit(&connp->conn_lock);
8312 			}
8313 		}
8314 		goto noticmpv4;
8315 	}
8316 
8317 	switch (icmph->icmph_type) {
8318 	case ICMP_DEST_UNREACHABLE:
8319 		switch (icmph->icmph_code) {
8320 		case ICMP_FRAGMENTATION_NEEDED:
8321 			/*
8322 			 * Reduce the MSS based on the new MTU.  This will
8323 			 * eliminate any fragmentation locally.
8324 			 * N.B.  There may well be some funny side-effects on
8325 			 * the local send policy and the remote receive policy.
8326 			 * Pending further research, we provide
8327 			 * tcp_ignore_path_mtu just in case this proves
8328 			 * disastrous somewhere.
8329 			 *
8330 			 * After updating the MSS, retransmit part of the
8331 			 * dropped segment using the new mss by calling
8332 			 * tcp_wput_data().  Need to adjust all those
8333 			 * params to make sure tcp_wput_data() work properly.
8334 			 */
8335 			if (tcps->tcps_ignore_path_mtu ||
8336 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8337 				break;
8338 
8339 			/*
8340 			 * Decrease the MSS by time stamp options
8341 			 * IP options and IPSEC options. tcp_hdr_len
8342 			 * includes time stamp option and IP option
8343 			 * length.  Note that new_mss may be negative
8344 			 * if tcp_ipsec_overhead is large and the
8345 			 * icmph_du_mtu is the minimum value, which is 68.
8346 			 */
8347 			new_mss = ntohs(icmph->icmph_du_mtu) -
8348 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8349 
8350 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8351 			    new_mss);
8352 
8353 			/*
8354 			 * Only update the MSS if the new one is
8355 			 * smaller than the previous one.  This is
8356 			 * to avoid problems when getting multiple
8357 			 * ICMP errors for the same MTU.
8358 			 */
8359 			if (new_mss >= tcp->tcp_mss)
8360 				break;
8361 
8362 			/*
8363 			 * Note that we are using the template header's DF
8364 			 * bit in the fast path sending.  So we need to compare
8365 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8366 			 * And stop doing IPv4 PMTUd if new_mss is less than
8367 			 * MAX(tcps_mss_min, ip_pmtu_min).
8368 			 */
8369 			if (new_mss < tcps->tcps_mss_min ||
8370 			    new_mss < ipst->ips_ip_pmtu_min) {
8371 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8372 				    0;
8373 			}
8374 
8375 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8376 			ASSERT(ratio >= 1);
8377 			tcp_mss_set(tcp, new_mss, B_TRUE);
8378 
8379 			/*
8380 			 * Make sure we have something to
8381 			 * send.
8382 			 */
8383 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8384 			    (tcp->tcp_xmit_head != NULL)) {
8385 				/*
8386 				 * Shrink tcp_cwnd in
8387 				 * proportion to the old MSS/new MSS.
8388 				 */
8389 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8390 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8391 				    (tcp->tcp_unsent == 0)) {
8392 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8393 				} else {
8394 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8395 				}
8396 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8397 				tcp->tcp_rexmit = B_TRUE;
8398 				tcp->tcp_dupack_cnt = 0;
8399 				tcp->tcp_snd_burst = TCP_CWND_SS;
8400 				tcp_ss_rexmit(tcp);
8401 			}
8402 			break;
8403 		case ICMP_PORT_UNREACHABLE:
8404 		case ICMP_PROTOCOL_UNREACHABLE:
8405 			switch (tcp->tcp_state) {
8406 			case TCPS_SYN_SENT:
8407 			case TCPS_SYN_RCVD:
8408 				/*
8409 				 * ICMP can snipe away incipient
8410 				 * TCP connections as long as
8411 				 * seq number is same as initial
8412 				 * send seq number.
8413 				 */
8414 				if (seg_seq == tcp->tcp_iss) {
8415 					(void) tcp_clean_death(tcp,
8416 					    ECONNREFUSED, 6);
8417 				}
8418 				break;
8419 			}
8420 			break;
8421 		case ICMP_HOST_UNREACHABLE:
8422 		case ICMP_NET_UNREACHABLE:
8423 			/* Record the error in case we finally time out. */
8424 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8425 				tcp->tcp_client_errno = EHOSTUNREACH;
8426 			else
8427 				tcp->tcp_client_errno = ENETUNREACH;
8428 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8429 				if (tcp->tcp_listener != NULL &&
8430 				    tcp->tcp_listener->tcp_syn_defense) {
8431 					/*
8432 					 * Ditch the half-open connection if we
8433 					 * suspect a SYN attack is under way.
8434 					 */
8435 					tcp_ip_ire_mark_advice(tcp);
8436 					(void) tcp_clean_death(tcp,
8437 					    tcp->tcp_client_errno, 7);
8438 				}
8439 			}
8440 			break;
8441 		default:
8442 			break;
8443 		}
8444 		break;
8445 	case ICMP_SOURCE_QUENCH: {
8446 		/*
8447 		 * use a global boolean to control
8448 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8449 		 * The default is false.
8450 		 */
8451 		if (tcp_icmp_source_quench) {
8452 			/*
8453 			 * Reduce the sending rate as if we got a
8454 			 * retransmit timeout
8455 			 */
8456 			uint32_t npkt;
8457 
8458 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8459 			    tcp->tcp_mss;
8460 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8461 			tcp->tcp_cwnd = tcp->tcp_mss;
8462 			tcp->tcp_cwnd_cnt = 0;
8463 		}
8464 		break;
8465 	}
8466 	}
8467 	freemsg(first_mp);
8468 }
8469 
8470 /*
8471  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8472  * error messages passed up by IP.
8473  * Assumes that IP has pulled up all the extension headers as well
8474  * as the ICMPv6 header.
8475  */
8476 static void
8477 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8478 {
8479 	icmp6_t *icmp6;
8480 	ip6_t	*ip6h;
8481 	uint16_t	iph_hdr_length;
8482 	tcpha_t	*tcpha;
8483 	uint8_t	*nexthdrp;
8484 	uint32_t new_mss;
8485 	uint32_t ratio;
8486 	boolean_t secure;
8487 	mblk_t *first_mp = mp;
8488 	size_t mp_size;
8489 	uint32_t seg_seq;
8490 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8491 
8492 	/*
8493 	 * The caller has determined if this is an IPSEC_IN packet and
8494 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8495 	 */
8496 	if (ipsec_mctl)
8497 		mp = mp->b_cont;
8498 
8499 	mp_size = MBLKL(mp);
8500 
8501 	/*
8502 	 * Verify that we have a complete IP header. If not, send it upstream.
8503 	 */
8504 	if (mp_size < sizeof (ip6_t)) {
8505 noticmpv6:
8506 		freemsg(first_mp);
8507 		return;
8508 	}
8509 
8510 	/*
8511 	 * Verify this is an ICMPV6 packet, else send it upstream.
8512 	 */
8513 	ip6h = (ip6_t *)mp->b_rptr;
8514 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8515 		iph_hdr_length = IPV6_HDR_LEN;
8516 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8517 	    &nexthdrp) ||
8518 	    *nexthdrp != IPPROTO_ICMPV6) {
8519 		goto noticmpv6;
8520 	}
8521 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8522 	ip6h = (ip6_t *)&icmp6[1];
8523 	/*
8524 	 * Verify if we have a complete ICMP and inner IP header.
8525 	 */
8526 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8527 		goto noticmpv6;
8528 
8529 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8530 		goto noticmpv6;
8531 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8532 	/*
8533 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8534 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8535 	 * packet.
8536 	 */
8537 	if ((*nexthdrp != IPPROTO_TCP) ||
8538 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8539 		goto noticmpv6;
8540 	}
8541 
8542 	/*
8543 	 * ICMP errors come on the right queue or come on
8544 	 * listener/global queue for detached connections and
8545 	 * get switched to the right queue. If it comes on the
8546 	 * right queue, policy check has already been done by IP
8547 	 * and thus free the first_mp without verifying the policy.
8548 	 * If it has come for a non-hard bound connection, we need
8549 	 * to verify policy as IP may not have done it.
8550 	 */
8551 	if (!tcp->tcp_hard_bound) {
8552 		if (ipsec_mctl) {
8553 			secure = ipsec_in_is_secure(first_mp);
8554 		} else {
8555 			secure = B_FALSE;
8556 		}
8557 		if (secure) {
8558 			/*
8559 			 * If we are willing to accept this in clear
8560 			 * we don't have to verify policy.
8561 			 */
8562 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8563 				if (!tcp_check_policy(tcp, first_mp,
8564 				    NULL, ip6h, secure, ipsec_mctl)) {
8565 					/*
8566 					 * tcp_check_policy called
8567 					 * ip_drop_packet() on failure.
8568 					 */
8569 					return;
8570 				}
8571 			}
8572 		}
8573 	} else if (ipsec_mctl) {
8574 		/*
8575 		 * This is a hard_bound connection. IP has already
8576 		 * verified policy. We don't have to do it again.
8577 		 */
8578 		freeb(first_mp);
8579 		first_mp = mp;
8580 		ipsec_mctl = B_FALSE;
8581 	}
8582 
8583 	seg_seq = ntohl(tcpha->tha_seq);
8584 	/*
8585 	 * TCP SHOULD check that the TCP sequence number contained in
8586 	 * payload of the ICMP error message is within the range
8587 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8588 	 */
8589 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8590 		/*
8591 		 * If the ICMP message is bogus, should we kill the
8592 		 * connection, or should we just drop the bogus ICMP
8593 		 * message? It would probably make more sense to just
8594 		 * drop the message so that if this one managed to get
8595 		 * in, the real connection should not suffer.
8596 		 */
8597 		goto noticmpv6;
8598 	}
8599 
8600 	switch (icmp6->icmp6_type) {
8601 	case ICMP6_PACKET_TOO_BIG:
8602 		/*
8603 		 * Reduce the MSS based on the new MTU.  This will
8604 		 * eliminate any fragmentation locally.
8605 		 * N.B.  There may well be some funny side-effects on
8606 		 * the local send policy and the remote receive policy.
8607 		 * Pending further research, we provide
8608 		 * tcp_ignore_path_mtu just in case this proves
8609 		 * disastrous somewhere.
8610 		 *
8611 		 * After updating the MSS, retransmit part of the
8612 		 * dropped segment using the new mss by calling
8613 		 * tcp_wput_data().  Need to adjust all those
8614 		 * params to make sure tcp_wput_data() work properly.
8615 		 */
8616 		if (tcps->tcps_ignore_path_mtu)
8617 			break;
8618 
8619 		/*
8620 		 * Decrease the MSS by time stamp options
8621 		 * IP options and IPSEC options. tcp_hdr_len
8622 		 * includes time stamp option and IP option
8623 		 * length.
8624 		 */
8625 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8626 		    tcp->tcp_ipsec_overhead;
8627 
8628 		/*
8629 		 * Only update the MSS if the new one is
8630 		 * smaller than the previous one.  This is
8631 		 * to avoid problems when getting multiple
8632 		 * ICMP errors for the same MTU.
8633 		 */
8634 		if (new_mss >= tcp->tcp_mss)
8635 			break;
8636 
8637 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8638 		ASSERT(ratio >= 1);
8639 		tcp_mss_set(tcp, new_mss, B_TRUE);
8640 
8641 		/*
8642 		 * Make sure we have something to
8643 		 * send.
8644 		 */
8645 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8646 		    (tcp->tcp_xmit_head != NULL)) {
8647 			/*
8648 			 * Shrink tcp_cwnd in
8649 			 * proportion to the old MSS/new MSS.
8650 			 */
8651 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8652 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8653 			    (tcp->tcp_unsent == 0)) {
8654 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8655 			} else {
8656 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8657 			}
8658 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8659 			tcp->tcp_rexmit = B_TRUE;
8660 			tcp->tcp_dupack_cnt = 0;
8661 			tcp->tcp_snd_burst = TCP_CWND_SS;
8662 			tcp_ss_rexmit(tcp);
8663 		}
8664 		break;
8665 
8666 	case ICMP6_DST_UNREACH:
8667 		switch (icmp6->icmp6_code) {
8668 		case ICMP6_DST_UNREACH_NOPORT:
8669 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8670 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8671 			    (seg_seq == tcp->tcp_iss)) {
8672 				(void) tcp_clean_death(tcp,
8673 				    ECONNREFUSED, 8);
8674 			}
8675 			break;
8676 
8677 		case ICMP6_DST_UNREACH_ADMIN:
8678 		case ICMP6_DST_UNREACH_NOROUTE:
8679 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8680 		case ICMP6_DST_UNREACH_ADDR:
8681 			/* Record the error in case we finally time out. */
8682 			tcp->tcp_client_errno = EHOSTUNREACH;
8683 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8684 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8685 			    (seg_seq == tcp->tcp_iss)) {
8686 				if (tcp->tcp_listener != NULL &&
8687 				    tcp->tcp_listener->tcp_syn_defense) {
8688 					/*
8689 					 * Ditch the half-open connection if we
8690 					 * suspect a SYN attack is under way.
8691 					 */
8692 					tcp_ip_ire_mark_advice(tcp);
8693 					(void) tcp_clean_death(tcp,
8694 					    tcp->tcp_client_errno, 9);
8695 				}
8696 			}
8697 
8698 
8699 			break;
8700 		default:
8701 			break;
8702 		}
8703 		break;
8704 
8705 	case ICMP6_PARAM_PROB:
8706 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8707 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8708 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8709 		    (uchar_t *)nexthdrp) {
8710 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8711 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8712 				(void) tcp_clean_death(tcp,
8713 				    ECONNREFUSED, 10);
8714 			}
8715 			break;
8716 		}
8717 		break;
8718 
8719 	case ICMP6_TIME_EXCEEDED:
8720 	default:
8721 		break;
8722 	}
8723 	freemsg(first_mp);
8724 }
8725 
8726 /*
8727  * Notify IP that we are having trouble with this connection.  IP should
8728  * blow the IRE away and start over.
8729  */
8730 static void
8731 tcp_ip_notify(tcp_t *tcp)
8732 {
8733 	struct iocblk	*iocp;
8734 	ipid_t	*ipid;
8735 	mblk_t	*mp;
8736 
8737 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8738 	if (tcp->tcp_ipversion == IPV6_VERSION)
8739 		return;
8740 
8741 	mp = mkiocb(IP_IOCTL);
8742 	if (mp == NULL)
8743 		return;
8744 
8745 	iocp = (struct iocblk *)mp->b_rptr;
8746 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8747 
8748 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8749 	if (!mp->b_cont) {
8750 		freeb(mp);
8751 		return;
8752 	}
8753 
8754 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8755 	mp->b_cont->b_wptr += iocp->ioc_count;
8756 	bzero(ipid, sizeof (*ipid));
8757 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8758 	ipid->ipid_ire_type = IRE_CACHE;
8759 	ipid->ipid_addr_offset = sizeof (ipid_t);
8760 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8761 	/*
8762 	 * Note: in the case of source routing we want to blow away the
8763 	 * route to the first source route hop.
8764 	 */
8765 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8766 	    sizeof (tcp->tcp_ipha->ipha_dst));
8767 
8768 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8769 }
8770 
8771 /* Unlink and return any mblk that looks like it contains an ire */
8772 static mblk_t *
8773 tcp_ire_mp(mblk_t **mpp)
8774 {
8775 	mblk_t 	*mp = *mpp;
8776 	mblk_t	*prev_mp = NULL;
8777 
8778 	for (;;) {
8779 		switch (DB_TYPE(mp)) {
8780 		case IRE_DB_TYPE:
8781 		case IRE_DB_REQ_TYPE:
8782 			if (mp == *mpp) {
8783 				*mpp = mp->b_cont;
8784 			} else {
8785 				prev_mp->b_cont = mp->b_cont;
8786 			}
8787 			mp->b_cont = NULL;
8788 			return (mp);
8789 		default:
8790 			break;
8791 		}
8792 		prev_mp = mp;
8793 		mp = mp->b_cont;
8794 		if (mp == NULL)
8795 			break;
8796 	}
8797 	return (mp);
8798 }
8799 
8800 /*
8801  * Timer callback routine for keepalive probe.  We do a fake resend of
8802  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8803  * check to see if we have heard anything from the other end for the last
8804  * RTO period.  If we have, set the timer to expire for another
8805  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8806  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8807  * the timeout if we have not heard from the other side.  If for more than
8808  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8809  * kill the connection unless the keepalive abort threshold is 0.  In
8810  * that case, we will probe "forever."
8811  */
8812 static void
8813 tcp_keepalive_killer(void *arg)
8814 {
8815 	mblk_t	*mp;
8816 	conn_t	*connp = (conn_t *)arg;
8817 	tcp_t  	*tcp = connp->conn_tcp;
8818 	int32_t	firetime;
8819 	int32_t	idletime;
8820 	int32_t	ka_intrvl;
8821 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8822 
8823 	tcp->tcp_ka_tid = 0;
8824 
8825 	if (tcp->tcp_fused)
8826 		return;
8827 
8828 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
8829 	ka_intrvl = tcp->tcp_ka_interval;
8830 
8831 	/*
8832 	 * Keepalive probe should only be sent if the application has not
8833 	 * done a close on the connection.
8834 	 */
8835 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8836 		return;
8837 	}
8838 	/* Timer fired too early, restart it. */
8839 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8840 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8841 		    MSEC_TO_TICK(ka_intrvl));
8842 		return;
8843 	}
8844 
8845 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8846 	/*
8847 	 * If we have not heard from the other side for a long
8848 	 * time, kill the connection unless the keepalive abort
8849 	 * threshold is 0.  In that case, we will probe "forever."
8850 	 */
8851 	if (tcp->tcp_ka_abort_thres != 0 &&
8852 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8853 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
8854 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8855 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8856 		return;
8857 	}
8858 
8859 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8860 	    idletime >= ka_intrvl) {
8861 		/* Fake resend of last ACKed byte. */
8862 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8863 
8864 		if (mp1 != NULL) {
8865 			*mp1->b_wptr++ = '\0';
8866 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8867 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8868 			freeb(mp1);
8869 			/*
8870 			 * if allocation failed, fall through to start the
8871 			 * timer back.
8872 			 */
8873 			if (mp != NULL) {
8874 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8875 				BUMP_MIB(&tcps->tcps_mib,
8876 				    tcpTimKeepaliveProbe);
8877 				if (tcp->tcp_ka_last_intrvl != 0) {
8878 					int max;
8879 					/*
8880 					 * We should probe again at least
8881 					 * in ka_intrvl, but not more than
8882 					 * tcp_rexmit_interval_max.
8883 					 */
8884 					max = tcps->tcps_rexmit_interval_max;
8885 					firetime = MIN(ka_intrvl - 1,
8886 					    tcp->tcp_ka_last_intrvl << 1);
8887 					if (firetime > max)
8888 						firetime = max;
8889 				} else {
8890 					firetime = tcp->tcp_rto;
8891 				}
8892 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8893 				    tcp_keepalive_killer,
8894 				    MSEC_TO_TICK(firetime));
8895 				tcp->tcp_ka_last_intrvl = firetime;
8896 				return;
8897 			}
8898 		}
8899 	} else {
8900 		tcp->tcp_ka_last_intrvl = 0;
8901 	}
8902 
8903 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8904 	if ((firetime = ka_intrvl - idletime) < 0) {
8905 		firetime = ka_intrvl;
8906 	}
8907 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8908 	    MSEC_TO_TICK(firetime));
8909 }
8910 
8911 int
8912 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8913 {
8914 	queue_t	*q = tcp->tcp_rq;
8915 	int32_t	mss = tcp->tcp_mss;
8916 	int	maxpsz;
8917 	conn_t	*connp = tcp->tcp_connp;
8918 
8919 	if (TCP_IS_DETACHED(tcp))
8920 		return (mss);
8921 	if (tcp->tcp_fused) {
8922 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8923 		mss = INFPSZ;
8924 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
8925 		/*
8926 		 * Set the sd_qn_maxpsz according to the socket send buffer
8927 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8928 		 * instruct the stream head to copyin user data into contiguous
8929 		 * kernel-allocated buffers without breaking it up into smaller
8930 		 * chunks.  We round up the buffer size to the nearest SMSS.
8931 		 */
8932 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8933 		if (tcp->tcp_kssl_ctx == NULL)
8934 			mss = INFPSZ;
8935 		else
8936 			mss = SSL3_MAX_RECORD_LEN;
8937 	} else {
8938 		/*
8939 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8940 		 * (and a multiple of the mss).  This instructs the stream
8941 		 * head to break down larger than SMSS writes into SMSS-
8942 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8943 		 */
8944 		/* XXX tune this with ndd tcp_maxpsz_multiplier */
8945 		maxpsz = tcp->tcp_maxpsz * mss;
8946 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8947 			maxpsz = tcp->tcp_xmit_hiwater/2;
8948 			/* Round up to nearest mss */
8949 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8950 		}
8951 	}
8952 
8953 	(void) proto_set_maxpsz(q, connp, maxpsz);
8954 	if (!(IPCL_IS_NONSTR(connp))) {
8955 		/* XXX do it in set_maxpsz()? */
8956 		tcp->tcp_wq->q_maxpsz = maxpsz;
8957 	}
8958 
8959 	if (set_maxblk)
8960 		(void) proto_set_tx_maxblk(q, connp, mss);
8961 	return (mss);
8962 }
8963 
8964 /*
8965  * Extract option values from a tcp header.  We put any found values into the
8966  * tcpopt struct and return a bitmask saying which options were found.
8967  */
8968 static int
8969 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8970 {
8971 	uchar_t		*endp;
8972 	int		len;
8973 	uint32_t	mss;
8974 	uchar_t		*up = (uchar_t *)tcph;
8975 	int		found = 0;
8976 	int32_t		sack_len;
8977 	tcp_seq		sack_begin, sack_end;
8978 	tcp_t		*tcp;
8979 
8980 	endp = up + TCP_HDR_LENGTH(tcph);
8981 	up += TCP_MIN_HEADER_LENGTH;
8982 	while (up < endp) {
8983 		len = endp - up;
8984 		switch (*up) {
8985 		case TCPOPT_EOL:
8986 			break;
8987 
8988 		case TCPOPT_NOP:
8989 			up++;
8990 			continue;
8991 
8992 		case TCPOPT_MAXSEG:
8993 			if (len < TCPOPT_MAXSEG_LEN ||
8994 			    up[1] != TCPOPT_MAXSEG_LEN)
8995 				break;
8996 
8997 			mss = BE16_TO_U16(up+2);
8998 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
8999 			tcpopt->tcp_opt_mss = mss;
9000 			found |= TCP_OPT_MSS_PRESENT;
9001 
9002 			up += TCPOPT_MAXSEG_LEN;
9003 			continue;
9004 
9005 		case TCPOPT_WSCALE:
9006 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9007 				break;
9008 
9009 			if (up[2] > TCP_MAX_WINSHIFT)
9010 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9011 			else
9012 				tcpopt->tcp_opt_wscale = up[2];
9013 			found |= TCP_OPT_WSCALE_PRESENT;
9014 
9015 			up += TCPOPT_WS_LEN;
9016 			continue;
9017 
9018 		case TCPOPT_SACK_PERMITTED:
9019 			if (len < TCPOPT_SACK_OK_LEN ||
9020 			    up[1] != TCPOPT_SACK_OK_LEN)
9021 				break;
9022 			found |= TCP_OPT_SACK_OK_PRESENT;
9023 			up += TCPOPT_SACK_OK_LEN;
9024 			continue;
9025 
9026 		case TCPOPT_SACK:
9027 			if (len <= 2 || up[1] <= 2 || len < up[1])
9028 				break;
9029 
9030 			/* If TCP is not interested in SACK blks... */
9031 			if ((tcp = tcpopt->tcp) == NULL) {
9032 				up += up[1];
9033 				continue;
9034 			}
9035 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9036 			up += TCPOPT_HEADER_LEN;
9037 
9038 			/*
9039 			 * If the list is empty, allocate one and assume
9040 			 * nothing is sack'ed.
9041 			 */
9042 			ASSERT(tcp->tcp_sack_info != NULL);
9043 			if (tcp->tcp_notsack_list == NULL) {
9044 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9045 				    tcp->tcp_suna, tcp->tcp_snxt,
9046 				    &(tcp->tcp_num_notsack_blk),
9047 				    &(tcp->tcp_cnt_notsack_list));
9048 
9049 				/*
9050 				 * Make sure tcp_notsack_list is not NULL.
9051 				 * This happens when kmem_alloc(KM_NOSLEEP)
9052 				 * returns NULL.
9053 				 */
9054 				if (tcp->tcp_notsack_list == NULL) {
9055 					up += sack_len;
9056 					continue;
9057 				}
9058 				tcp->tcp_fack = tcp->tcp_suna;
9059 			}
9060 
9061 			while (sack_len > 0) {
9062 				if (up + 8 > endp) {
9063 					up = endp;
9064 					break;
9065 				}
9066 				sack_begin = BE32_TO_U32(up);
9067 				up += 4;
9068 				sack_end = BE32_TO_U32(up);
9069 				up += 4;
9070 				sack_len -= 8;
9071 				/*
9072 				 * Bounds checking.  Make sure the SACK
9073 				 * info is within tcp_suna and tcp_snxt.
9074 				 * If this SACK blk is out of bound, ignore
9075 				 * it but continue to parse the following
9076 				 * blks.
9077 				 */
9078 				if (SEQ_LEQ(sack_end, sack_begin) ||
9079 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9080 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9081 					continue;
9082 				}
9083 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9084 				    sack_begin, sack_end,
9085 				    &(tcp->tcp_num_notsack_blk),
9086 				    &(tcp->tcp_cnt_notsack_list));
9087 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9088 					tcp->tcp_fack = sack_end;
9089 				}
9090 			}
9091 			found |= TCP_OPT_SACK_PRESENT;
9092 			continue;
9093 
9094 		case TCPOPT_TSTAMP:
9095 			if (len < TCPOPT_TSTAMP_LEN ||
9096 			    up[1] != TCPOPT_TSTAMP_LEN)
9097 				break;
9098 
9099 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9100 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9101 
9102 			found |= TCP_OPT_TSTAMP_PRESENT;
9103 
9104 			up += TCPOPT_TSTAMP_LEN;
9105 			continue;
9106 
9107 		default:
9108 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9109 				break;
9110 			up += up[1];
9111 			continue;
9112 		}
9113 		break;
9114 	}
9115 	return (found);
9116 }
9117 
9118 /*
9119  * Set the mss associated with a particular tcp based on its current value,
9120  * and a new one passed in. Observe minimums and maximums, and reset
9121  * other state variables that we want to view as multiples of mss.
9122  *
9123  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9124  * highwater marks etc. need to be initialized or adjusted.
9125  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9126  *    packet arrives.
9127  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9128  *    ICMP6_PACKET_TOO_BIG arrives.
9129  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9130  *    to increase the MSS to use the extra bytes available.
9131  *
9132  * Callers except tcp_paws_check() ensure that they only reduce mss.
9133  */
9134 static void
9135 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9136 {
9137 	uint32_t	mss_max;
9138 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9139 
9140 	if (tcp->tcp_ipversion == IPV4_VERSION)
9141 		mss_max = tcps->tcps_mss_max_ipv4;
9142 	else
9143 		mss_max = tcps->tcps_mss_max_ipv6;
9144 
9145 	if (mss < tcps->tcps_mss_min)
9146 		mss = tcps->tcps_mss_min;
9147 	if (mss > mss_max)
9148 		mss = mss_max;
9149 	/*
9150 	 * Unless naglim has been set by our client to
9151 	 * a non-mss value, force naglim to track mss.
9152 	 * This can help to aggregate small writes.
9153 	 */
9154 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9155 		tcp->tcp_naglim = mss;
9156 	/*
9157 	 * TCP should be able to buffer at least 4 MSS data for obvious
9158 	 * performance reason.
9159 	 */
9160 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9161 		tcp->tcp_xmit_hiwater = mss << 2;
9162 
9163 	if (do_ss) {
9164 		/*
9165 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9166 		 * changing due to a reduction in MTU, presumably as a
9167 		 * result of a new path component, reset cwnd to its
9168 		 * "initial" value, as a multiple of the new mss.
9169 		 */
9170 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9171 	} else {
9172 		/*
9173 		 * Called by tcp_paws_check(), the mss increased
9174 		 * marginally to allow use of space previously taken
9175 		 * by the timestamp option. It would be inappropriate
9176 		 * to apply slow start or tcp_init_cwnd values to
9177 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9178 		 */
9179 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9180 		tcp->tcp_cwnd_cnt = 0;
9181 	}
9182 	tcp->tcp_mss = mss;
9183 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9184 }
9185 
9186 /* For /dev/tcp aka AF_INET open */
9187 static int
9188 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9189 {
9190 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9191 }
9192 
9193 /* For /dev/tcp6 aka AF_INET6 open */
9194 static int
9195 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9196 {
9197 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9198 }
9199 
9200 static conn_t *
9201 tcp_create_common(queue_t *q, cred_t *credp, boolean_t isv6,
9202     boolean_t issocket, int *errorp)
9203 {
9204 	tcp_t		*tcp = NULL;
9205 	conn_t		*connp;
9206 	int		err;
9207 	zoneid_t	zoneid;
9208 	tcp_stack_t	*tcps;
9209 	squeue_t	*sqp;
9210 
9211 	ASSERT(errorp != NULL);
9212 	/*
9213 	 * Find the proper zoneid and netstack.
9214 	 */
9215 	/*
9216 	 * Special case for install: miniroot needs to be able to
9217 	 * access files via NFS as though it were always in the
9218 	 * global zone.
9219 	 */
9220 	if (credp == kcred && nfs_global_client_only != 0) {
9221 		zoneid = GLOBAL_ZONEID;
9222 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9223 		    netstack_tcp;
9224 		ASSERT(tcps != NULL);
9225 	} else {
9226 		netstack_t *ns;
9227 
9228 		ns = netstack_find_by_cred(credp);
9229 		ASSERT(ns != NULL);
9230 		tcps = ns->netstack_tcp;
9231 		ASSERT(tcps != NULL);
9232 
9233 		/*
9234 		 * For exclusive stacks we set the zoneid to zero
9235 		 * to make TCP operate as if in the global zone.
9236 		 */
9237 		if (tcps->tcps_netstack->netstack_stackid !=
9238 		    GLOBAL_NETSTACKID)
9239 			zoneid = GLOBAL_ZONEID;
9240 		else
9241 			zoneid = crgetzoneid(credp);
9242 	}
9243 	/*
9244 	 * For stackid zero this is done from strplumb.c, but
9245 	 * non-zero stackids are handled here.
9246 	 */
9247 	if (tcps->tcps_g_q == NULL &&
9248 	    tcps->tcps_netstack->netstack_stackid !=
9249 	    GLOBAL_NETSTACKID) {
9250 		tcp_g_q_setup(tcps);
9251 	}
9252 
9253 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
9254 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
9255 	/*
9256 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9257 	 * so we drop it by one.
9258 	 */
9259 	netstack_rele(tcps->tcps_netstack);
9260 	if (connp == NULL) {
9261 		*errorp = ENOSR;
9262 		return (NULL);
9263 	}
9264 	connp->conn_sqp = sqp;
9265 	connp->conn_initial_sqp = connp->conn_sqp;
9266 	tcp = connp->conn_tcp;
9267 
9268 	if (isv6) {
9269 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9270 		connp->conn_send = ip_output_v6;
9271 		connp->conn_af_isv6 = B_TRUE;
9272 		connp->conn_pkt_isv6 = B_TRUE;
9273 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9274 		tcp->tcp_ipversion = IPV6_VERSION;
9275 		tcp->tcp_family = AF_INET6;
9276 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9277 	} else {
9278 		connp->conn_flags |= IPCL_TCP4;
9279 		connp->conn_send = ip_output;
9280 		connp->conn_af_isv6 = B_FALSE;
9281 		connp->conn_pkt_isv6 = B_FALSE;
9282 		tcp->tcp_ipversion = IPV4_VERSION;
9283 		tcp->tcp_family = AF_INET;
9284 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9285 	}
9286 
9287 	/*
9288 	 * TCP keeps a copy of cred for cache locality reasons but
9289 	 * we put a reference only once. If connp->conn_cred
9290 	 * becomes invalid, tcp_cred should also be set to NULL.
9291 	 */
9292 	tcp->tcp_cred = connp->conn_cred = credp;
9293 	crhold(connp->conn_cred);
9294 	tcp->tcp_cpid = curproc->p_pid;
9295 	tcp->tcp_open_time = lbolt64;
9296 	connp->conn_zoneid = zoneid;
9297 	connp->conn_mlp_type = mlptSingle;
9298 	connp->conn_ulp_labeled = !is_system_labeled();
9299 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9300 	ASSERT(tcp->tcp_tcps == tcps);
9301 
9302 	/*
9303 	 * If the caller has the process-wide flag set, then default to MAC
9304 	 * exempt mode.  This allows read-down to unlabeled hosts.
9305 	 */
9306 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9307 		connp->conn_mac_exempt = B_TRUE;
9308 
9309 	connp->conn_dev = NULL;
9310 	if (issocket) {
9311 		connp->conn_flags |= IPCL_SOCKET;
9312 		tcp->tcp_issocket = 1;
9313 	}
9314 
9315 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
9316 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9317 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
9318 
9319 	/* Non-zero default values */
9320 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9321 
9322 	if (q == NULL) {
9323 		/*
9324 		 * Create a helper stream for non-STREAMS socket.
9325 		 */
9326 		err = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
9327 		if (err != 0) {
9328 			ip1dbg(("tcp_create: create of IP helper stream "
9329 			    "failed\n"));
9330 			CONN_DEC_REF(connp);
9331 			*errorp = err;
9332 			return (NULL);
9333 		}
9334 		q = connp->conn_rq;
9335 	} else {
9336 		RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9337 	}
9338 
9339 	SOCK_CONNID_INIT(tcp->tcp_connid);
9340 	err = tcp_init(tcp, q);
9341 	if (err != 0) {
9342 		CONN_DEC_REF(connp);
9343 		*errorp = err;
9344 		return (NULL);
9345 	}
9346 
9347 	return (connp);
9348 }
9349 
9350 static int
9351 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9352     boolean_t isv6)
9353 {
9354 	tcp_t		*tcp = NULL;
9355 	conn_t		*connp = NULL;
9356 	int		err;
9357 	vmem_t		*minor_arena = NULL;
9358 	dev_t		conn_dev;
9359 	boolean_t	issocket;
9360 
9361 	if (q->q_ptr != NULL)
9362 		return (0);
9363 
9364 	if (sflag == MODOPEN)
9365 		return (EINVAL);
9366 
9367 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9368 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9369 		minor_arena = ip_minor_arena_la;
9370 	} else {
9371 		/*
9372 		 * Either minor numbers in the large arena were exhausted
9373 		 * or a non socket application is doing the open.
9374 		 * Try to allocate from the small arena.
9375 		 */
9376 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9377 			return (EBUSY);
9378 		}
9379 		minor_arena = ip_minor_arena_sa;
9380 	}
9381 
9382 	ASSERT(minor_arena != NULL);
9383 
9384 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
9385 
9386 	if (flag & SO_FALLBACK) {
9387 		/*
9388 		 * Non streams socket needs a stream to fallback to
9389 		 */
9390 		RD(q)->q_ptr = (void *)conn_dev;
9391 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
9392 		WR(q)->q_ptr = (void *)minor_arena;
9393 		qprocson(q);
9394 		return (0);
9395 	} else if (flag & SO_ACCEPTOR) {
9396 		q->q_qinfo = &tcp_acceptor_rinit;
9397 		/*
9398 		 * the conn_dev and minor_arena will be subsequently used by
9399 		 * tcp_wput_accept() and tcpclose_accept() to figure out the
9400 		 * minor device number for this connection from the q_ptr.
9401 		 */
9402 		RD(q)->q_ptr = (void *)conn_dev;
9403 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9404 		WR(q)->q_ptr = (void *)minor_arena;
9405 		qprocson(q);
9406 		return (0);
9407 	}
9408 
9409 	issocket = flag & SO_SOCKSTR;
9410 	connp = tcp_create_common(q, credp, isv6, issocket, &err);
9411 
9412 	if (connp == NULL) {
9413 		inet_minor_free(minor_arena, conn_dev);
9414 		q->q_ptr = WR(q)->q_ptr = NULL;
9415 		return (err);
9416 	}
9417 
9418 	q->q_ptr = WR(q)->q_ptr = connp;
9419 
9420 	connp->conn_dev = conn_dev;
9421 	connp->conn_minor_arena = minor_arena;
9422 
9423 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9424 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9425 
9426 	if (issocket) {
9427 		WR(q)->q_qinfo = &tcp_sock_winit;
9428 	} else {
9429 		tcp = connp->conn_tcp;
9430 #ifdef  _ILP32
9431 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9432 #else
9433 		tcp->tcp_acceptor_id = conn_dev;
9434 #endif  /* _ILP32 */
9435 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9436 	}
9437 
9438 	/*
9439 	 * Put the ref for TCP. Ref for IP was already put
9440 	 * by ipcl_conn_create. Also Make the conn_t globally
9441 	 * visible to walkers
9442 	 */
9443 	mutex_enter(&connp->conn_lock);
9444 	CONN_INC_REF_LOCKED(connp);
9445 	ASSERT(connp->conn_ref == 2);
9446 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9447 	mutex_exit(&connp->conn_lock);
9448 
9449 	qprocson(q);
9450 	return (0);
9451 }
9452 
9453 /*
9454  * Some TCP options can be "set" by requesting them in the option
9455  * buffer. This is needed for XTI feature test though we do not
9456  * allow it in general. We interpret that this mechanism is more
9457  * applicable to OSI protocols and need not be allowed in general.
9458  * This routine filters out options for which it is not allowed (most)
9459  * and lets through those (few) for which it is. [ The XTI interface
9460  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9461  * ever implemented will have to be allowed here ].
9462  */
9463 static boolean_t
9464 tcp_allow_connopt_set(int level, int name)
9465 {
9466 
9467 	switch (level) {
9468 	case IPPROTO_TCP:
9469 		switch (name) {
9470 		case TCP_NODELAY:
9471 			return (B_TRUE);
9472 		default:
9473 			return (B_FALSE);
9474 		}
9475 		/*NOTREACHED*/
9476 	default:
9477 		return (B_FALSE);
9478 	}
9479 	/*NOTREACHED*/
9480 }
9481 
9482 /*
9483  * this routine gets default values of certain options whose default
9484  * values are maintained by protocol specific code
9485  */
9486 /* ARGSUSED */
9487 int
9488 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9489 {
9490 	int32_t	*i1 = (int32_t *)ptr;
9491 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9492 
9493 	switch (level) {
9494 	case IPPROTO_TCP:
9495 		switch (name) {
9496 		case TCP_NOTIFY_THRESHOLD:
9497 			*i1 = tcps->tcps_ip_notify_interval;
9498 			break;
9499 		case TCP_ABORT_THRESHOLD:
9500 			*i1 = tcps->tcps_ip_abort_interval;
9501 			break;
9502 		case TCP_CONN_NOTIFY_THRESHOLD:
9503 			*i1 = tcps->tcps_ip_notify_cinterval;
9504 			break;
9505 		case TCP_CONN_ABORT_THRESHOLD:
9506 			*i1 = tcps->tcps_ip_abort_cinterval;
9507 			break;
9508 		default:
9509 			return (-1);
9510 		}
9511 		break;
9512 	case IPPROTO_IP:
9513 		switch (name) {
9514 		case IP_TTL:
9515 			*i1 = tcps->tcps_ipv4_ttl;
9516 			break;
9517 		default:
9518 			return (-1);
9519 		}
9520 		break;
9521 	case IPPROTO_IPV6:
9522 		switch (name) {
9523 		case IPV6_UNICAST_HOPS:
9524 			*i1 = tcps->tcps_ipv6_hoplimit;
9525 			break;
9526 		default:
9527 			return (-1);
9528 		}
9529 		break;
9530 	default:
9531 		return (-1);
9532 	}
9533 	return (sizeof (int));
9534 }
9535 
9536 static int
9537 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
9538 {
9539 	int		*i1 = (int *)ptr;
9540 	tcp_t		*tcp = connp->conn_tcp;
9541 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9542 
9543 	switch (level) {
9544 	case SOL_SOCKET:
9545 		switch (name) {
9546 		case SO_LINGER:	{
9547 			struct linger *lgr = (struct linger *)ptr;
9548 
9549 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9550 			lgr->l_linger = tcp->tcp_lingertime;
9551 			}
9552 			return (sizeof (struct linger));
9553 		case SO_DEBUG:
9554 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9555 			break;
9556 		case SO_KEEPALIVE:
9557 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9558 			break;
9559 		case SO_DONTROUTE:
9560 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9561 			break;
9562 		case SO_USELOOPBACK:
9563 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9564 			break;
9565 		case SO_BROADCAST:
9566 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9567 			break;
9568 		case SO_REUSEADDR:
9569 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9570 			break;
9571 		case SO_OOBINLINE:
9572 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9573 			break;
9574 		case SO_DGRAM_ERRIND:
9575 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9576 			break;
9577 		case SO_TYPE:
9578 			*i1 = SOCK_STREAM;
9579 			break;
9580 		case SO_SNDBUF:
9581 			*i1 = tcp->tcp_xmit_hiwater;
9582 			break;
9583 		case SO_RCVBUF:
9584 			*i1 = tcp->tcp_recv_hiwater;
9585 			break;
9586 		case SO_SND_COPYAVOID:
9587 			*i1 = tcp->tcp_snd_zcopy_on ?
9588 			    SO_SND_COPYAVOID : 0;
9589 			break;
9590 		case SO_ALLZONES:
9591 			*i1 = connp->conn_allzones ? 1 : 0;
9592 			break;
9593 		case SO_ANON_MLP:
9594 			*i1 = connp->conn_anon_mlp;
9595 			break;
9596 		case SO_MAC_EXEMPT:
9597 			*i1 = connp->conn_mac_exempt;
9598 			break;
9599 		case SO_EXCLBIND:
9600 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9601 			break;
9602 		case SO_PROTOTYPE:
9603 			*i1 = IPPROTO_TCP;
9604 			break;
9605 		case SO_DOMAIN:
9606 			*i1 = tcp->tcp_family;
9607 			break;
9608 		case SO_ACCEPTCONN:
9609 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
9610 		default:
9611 			return (-1);
9612 		}
9613 		break;
9614 	case IPPROTO_TCP:
9615 		switch (name) {
9616 		case TCP_NODELAY:
9617 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9618 			break;
9619 		case TCP_MAXSEG:
9620 			*i1 = tcp->tcp_mss;
9621 			break;
9622 		case TCP_NOTIFY_THRESHOLD:
9623 			*i1 = (int)tcp->tcp_first_timer_threshold;
9624 			break;
9625 		case TCP_ABORT_THRESHOLD:
9626 			*i1 = tcp->tcp_second_timer_threshold;
9627 			break;
9628 		case TCP_CONN_NOTIFY_THRESHOLD:
9629 			*i1 = tcp->tcp_first_ctimer_threshold;
9630 			break;
9631 		case TCP_CONN_ABORT_THRESHOLD:
9632 			*i1 = tcp->tcp_second_ctimer_threshold;
9633 			break;
9634 		case TCP_RECVDSTADDR:
9635 			*i1 = tcp->tcp_recvdstaddr;
9636 			break;
9637 		case TCP_ANONPRIVBIND:
9638 			*i1 = tcp->tcp_anon_priv_bind;
9639 			break;
9640 		case TCP_EXCLBIND:
9641 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9642 			break;
9643 		case TCP_INIT_CWND:
9644 			*i1 = tcp->tcp_init_cwnd;
9645 			break;
9646 		case TCP_KEEPALIVE_THRESHOLD:
9647 			*i1 = tcp->tcp_ka_interval;
9648 			break;
9649 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9650 			*i1 = tcp->tcp_ka_abort_thres;
9651 			break;
9652 		case TCP_CORK:
9653 			*i1 = tcp->tcp_cork;
9654 			break;
9655 		default:
9656 			return (-1);
9657 		}
9658 		break;
9659 	case IPPROTO_IP:
9660 		if (tcp->tcp_family != AF_INET)
9661 			return (-1);
9662 		switch (name) {
9663 		case IP_OPTIONS:
9664 		case T_IP_OPTIONS: {
9665 			/*
9666 			 * This is compatible with BSD in that in only return
9667 			 * the reverse source route with the final destination
9668 			 * as the last entry. The first 4 bytes of the option
9669 			 * will contain the final destination.
9670 			 */
9671 			int	opt_len;
9672 
9673 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9674 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9675 			ASSERT(opt_len >= 0);
9676 			/* Caller ensures enough space */
9677 			if (opt_len > 0) {
9678 				/*
9679 				 * TODO: Do we have to handle getsockopt on an
9680 				 * initiator as well?
9681 				 */
9682 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9683 			}
9684 			return (0);
9685 			}
9686 		case IP_TOS:
9687 		case T_IP_TOS:
9688 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9689 			break;
9690 		case IP_TTL:
9691 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9692 			break;
9693 		case IP_NEXTHOP:
9694 			/* Handled at IP level */
9695 			return (-EINVAL);
9696 		default:
9697 			return (-1);
9698 		}
9699 		break;
9700 	case IPPROTO_IPV6:
9701 		/*
9702 		 * IPPROTO_IPV6 options are only supported for sockets
9703 		 * that are using IPv6 on the wire.
9704 		 */
9705 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9706 			return (-1);
9707 		}
9708 		switch (name) {
9709 		case IPV6_UNICAST_HOPS:
9710 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9711 			break;	/* goto sizeof (int) option return */
9712 		case IPV6_BOUND_IF:
9713 			/* Zero if not set */
9714 			*i1 = tcp->tcp_bound_if;
9715 			break;	/* goto sizeof (int) option return */
9716 		case IPV6_RECVPKTINFO:
9717 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9718 				*i1 = 1;
9719 			else
9720 				*i1 = 0;
9721 			break;	/* goto sizeof (int) option return */
9722 		case IPV6_RECVTCLASS:
9723 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9724 				*i1 = 1;
9725 			else
9726 				*i1 = 0;
9727 			break;	/* goto sizeof (int) option return */
9728 		case IPV6_RECVHOPLIMIT:
9729 			if (tcp->tcp_ipv6_recvancillary &
9730 			    TCP_IPV6_RECVHOPLIMIT)
9731 				*i1 = 1;
9732 			else
9733 				*i1 = 0;
9734 			break;	/* goto sizeof (int) option return */
9735 		case IPV6_RECVHOPOPTS:
9736 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9737 				*i1 = 1;
9738 			else
9739 				*i1 = 0;
9740 			break;	/* goto sizeof (int) option return */
9741 		case IPV6_RECVDSTOPTS:
9742 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9743 				*i1 = 1;
9744 			else
9745 				*i1 = 0;
9746 			break;	/* goto sizeof (int) option return */
9747 		case _OLD_IPV6_RECVDSTOPTS:
9748 			if (tcp->tcp_ipv6_recvancillary &
9749 			    TCP_OLD_IPV6_RECVDSTOPTS)
9750 				*i1 = 1;
9751 			else
9752 				*i1 = 0;
9753 			break;	/* goto sizeof (int) option return */
9754 		case IPV6_RECVRTHDR:
9755 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9756 				*i1 = 1;
9757 			else
9758 				*i1 = 0;
9759 			break;	/* goto sizeof (int) option return */
9760 		case IPV6_RECVRTHDRDSTOPTS:
9761 			if (tcp->tcp_ipv6_recvancillary &
9762 			    TCP_IPV6_RECVRTDSTOPTS)
9763 				*i1 = 1;
9764 			else
9765 				*i1 = 0;
9766 			break;	/* goto sizeof (int) option return */
9767 		case IPV6_PKTINFO: {
9768 			/* XXX assumes that caller has room for max size! */
9769 			struct in6_pktinfo *pkti;
9770 
9771 			pkti = (struct in6_pktinfo *)ptr;
9772 			if (ipp->ipp_fields & IPPF_IFINDEX)
9773 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9774 			else
9775 				pkti->ipi6_ifindex = 0;
9776 			if (ipp->ipp_fields & IPPF_ADDR)
9777 				pkti->ipi6_addr = ipp->ipp_addr;
9778 			else
9779 				pkti->ipi6_addr = ipv6_all_zeros;
9780 			return (sizeof (struct in6_pktinfo));
9781 		}
9782 		case IPV6_TCLASS:
9783 			if (ipp->ipp_fields & IPPF_TCLASS)
9784 				*i1 = ipp->ipp_tclass;
9785 			else
9786 				*i1 = IPV6_FLOW_TCLASS(
9787 				    IPV6_DEFAULT_VERS_AND_FLOW);
9788 			break;	/* goto sizeof (int) option return */
9789 		case IPV6_NEXTHOP: {
9790 			sin6_t *sin6 = (sin6_t *)ptr;
9791 
9792 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9793 				return (0);
9794 			*sin6 = sin6_null;
9795 			sin6->sin6_family = AF_INET6;
9796 			sin6->sin6_addr = ipp->ipp_nexthop;
9797 			return (sizeof (sin6_t));
9798 		}
9799 		case IPV6_HOPOPTS:
9800 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9801 				return (0);
9802 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9803 				return (0);
9804 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9805 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9806 			if (tcp->tcp_label_len > 0) {
9807 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9808 				ptr[1] = (ipp->ipp_hopoptslen -
9809 				    tcp->tcp_label_len + 7) / 8 - 1;
9810 			}
9811 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9812 		case IPV6_RTHDRDSTOPTS:
9813 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9814 				return (0);
9815 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9816 			return (ipp->ipp_rtdstoptslen);
9817 		case IPV6_RTHDR:
9818 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9819 				return (0);
9820 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9821 			return (ipp->ipp_rthdrlen);
9822 		case IPV6_DSTOPTS:
9823 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9824 				return (0);
9825 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9826 			return (ipp->ipp_dstoptslen);
9827 		case IPV6_SRC_PREFERENCES:
9828 			return (ip6_get_src_preferences(connp,
9829 			    (uint32_t *)ptr));
9830 		case IPV6_PATHMTU: {
9831 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9832 
9833 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9834 				return (-1);
9835 
9836 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9837 			    connp->conn_fport, mtuinfo,
9838 			    connp->conn_netstack));
9839 		}
9840 		default:
9841 			return (-1);
9842 		}
9843 		break;
9844 	default:
9845 		return (-1);
9846 	}
9847 	return (sizeof (int));
9848 }
9849 
9850 /*
9851  * TCP routine to get the values of options.
9852  */
9853 int
9854 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
9855 {
9856 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
9857 }
9858 
9859 /* returns UNIX error, the optlen is a value-result arg */
9860 int
9861 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
9862     void *optvalp, socklen_t *optlen, cred_t *cr)
9863 {
9864 	conn_t		*connp = (conn_t *)proto_handle;
9865 	squeue_t	*sqp = connp->conn_sqp;
9866 	int		error;
9867 	t_uscalar_t	max_optbuf_len;
9868 	void		*optvalp_buf;
9869 	int		len;
9870 
9871 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
9872 	    tcp_opt_obj.odb_opt_des_arr,
9873 	    tcp_opt_obj.odb_opt_arr_cnt,
9874 	    tcp_opt_obj.odb_topmost_tpiprovider,
9875 	    B_FALSE, B_TRUE, cr);
9876 	if (error != 0) {
9877 		if (error < 0) {
9878 			error = proto_tlitosyserr(-error);
9879 		}
9880 		return (error);
9881 	}
9882 
9883 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
9884 
9885 	error = squeue_synch_enter(sqp, connp, 0);
9886 	if (error == ENOMEM) {
9887 		return (ENOMEM);
9888 	}
9889 
9890 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
9891 	squeue_synch_exit(sqp, connp);
9892 
9893 	if (len < 0) {
9894 		/*
9895 		 * Pass on to IP
9896 		 */
9897 		kmem_free(optvalp_buf, max_optbuf_len);
9898 		return (ip_get_options(connp, level, option_name,
9899 		    optvalp, optlen, cr));
9900 	} else {
9901 		/*
9902 		 * update optlen and copy option value
9903 		 */
9904 		t_uscalar_t size = MIN(len, *optlen);
9905 		bcopy(optvalp_buf, optvalp, size);
9906 		bcopy(&size, optlen, sizeof (size));
9907 
9908 		kmem_free(optvalp_buf, max_optbuf_len);
9909 		return (0);
9910 	}
9911 }
9912 
9913 /*
9914  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9915  * Parameters are assumed to be verified by the caller.
9916  */
9917 /* ARGSUSED */
9918 int
9919 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
9920     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9921     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9922 {
9923 	tcp_t	*tcp = connp->conn_tcp;
9924 	int	*i1 = (int *)invalp;
9925 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9926 	boolean_t checkonly;
9927 	int	reterr;
9928 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9929 
9930 	switch (optset_context) {
9931 	case SETFN_OPTCOM_CHECKONLY:
9932 		checkonly = B_TRUE;
9933 		/*
9934 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9935 		 * inlen != 0 implies value supplied and
9936 		 * 	we have to "pretend" to set it.
9937 		 * inlen == 0 implies that there is no
9938 		 * 	value part in T_CHECK request and just validation
9939 		 * done elsewhere should be enough, we just return here.
9940 		 */
9941 		if (inlen == 0) {
9942 			*outlenp = 0;
9943 			return (0);
9944 		}
9945 		break;
9946 	case SETFN_OPTCOM_NEGOTIATE:
9947 		checkonly = B_FALSE;
9948 		break;
9949 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9950 	case SETFN_CONN_NEGOTIATE:
9951 		checkonly = B_FALSE;
9952 		/*
9953 		 * Negotiating local and "association-related" options
9954 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9955 		 * primitives is allowed by XTI, but we choose
9956 		 * to not implement this style negotiation for Internet
9957 		 * protocols (We interpret it is a must for OSI world but
9958 		 * optional for Internet protocols) for all options.
9959 		 * [ Will do only for the few options that enable test
9960 		 * suites that our XTI implementation of this feature
9961 		 * works for transports that do allow it ]
9962 		 */
9963 		if (!tcp_allow_connopt_set(level, name)) {
9964 			*outlenp = 0;
9965 			return (EINVAL);
9966 		}
9967 		break;
9968 	default:
9969 		/*
9970 		 * We should never get here
9971 		 */
9972 		*outlenp = 0;
9973 		return (EINVAL);
9974 	}
9975 
9976 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9977 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9978 
9979 	/*
9980 	 * For TCP, we should have no ancillary data sent down
9981 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9982 	 * has to be zero.
9983 	 */
9984 	ASSERT(thisdg_attrs == NULL);
9985 
9986 	/*
9987 	 * For fixed length options, no sanity check
9988 	 * of passed in length is done. It is assumed *_optcom_req()
9989 	 * routines do the right thing.
9990 	 */
9991 	switch (level) {
9992 	case SOL_SOCKET:
9993 		switch (name) {
9994 		case SO_LINGER: {
9995 			struct linger *lgr = (struct linger *)invalp;
9996 
9997 			if (!checkonly) {
9998 				if (lgr->l_onoff) {
9999 					tcp->tcp_linger = 1;
10000 					tcp->tcp_lingertime = lgr->l_linger;
10001 				} else {
10002 					tcp->tcp_linger = 0;
10003 					tcp->tcp_lingertime = 0;
10004 				}
10005 				/* struct copy */
10006 				*(struct linger *)outvalp = *lgr;
10007 			} else {
10008 				if (!lgr->l_onoff) {
10009 					((struct linger *)
10010 					    outvalp)->l_onoff = 0;
10011 					((struct linger *)
10012 					    outvalp)->l_linger = 0;
10013 				} else {
10014 					/* struct copy */
10015 					*(struct linger *)outvalp = *lgr;
10016 				}
10017 			}
10018 			*outlenp = sizeof (struct linger);
10019 			return (0);
10020 		}
10021 		case SO_DEBUG:
10022 			if (!checkonly)
10023 				tcp->tcp_debug = onoff;
10024 			break;
10025 		case SO_KEEPALIVE:
10026 			if (checkonly) {
10027 				/* check only case */
10028 				break;
10029 			}
10030 
10031 			if (!onoff) {
10032 				if (tcp->tcp_ka_enabled) {
10033 					if (tcp->tcp_ka_tid != 0) {
10034 						(void) TCP_TIMER_CANCEL(tcp,
10035 						    tcp->tcp_ka_tid);
10036 						tcp->tcp_ka_tid = 0;
10037 					}
10038 					tcp->tcp_ka_enabled = 0;
10039 				}
10040 				break;
10041 			}
10042 			if (!tcp->tcp_ka_enabled) {
10043 				/* Crank up the keepalive timer */
10044 				tcp->tcp_ka_last_intrvl = 0;
10045 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10046 				    tcp_keepalive_killer,
10047 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10048 				tcp->tcp_ka_enabled = 1;
10049 			}
10050 			break;
10051 		case SO_DONTROUTE:
10052 			/*
10053 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10054 			 * only of interest to IP.  We track them here only so
10055 			 * that we can report their current value.
10056 			 */
10057 			if (!checkonly) {
10058 				tcp->tcp_dontroute = onoff;
10059 				tcp->tcp_connp->conn_dontroute = onoff;
10060 			}
10061 			break;
10062 		case SO_USELOOPBACK:
10063 			if (!checkonly) {
10064 				tcp->tcp_useloopback = onoff;
10065 				tcp->tcp_connp->conn_loopback = onoff;
10066 			}
10067 			break;
10068 		case SO_BROADCAST:
10069 			if (!checkonly) {
10070 				tcp->tcp_broadcast = onoff;
10071 				tcp->tcp_connp->conn_broadcast = onoff;
10072 			}
10073 			break;
10074 		case SO_REUSEADDR:
10075 			if (!checkonly) {
10076 				tcp->tcp_reuseaddr = onoff;
10077 				tcp->tcp_connp->conn_reuseaddr = onoff;
10078 			}
10079 			break;
10080 		case SO_OOBINLINE:
10081 			if (!checkonly) {
10082 				tcp->tcp_oobinline = onoff;
10083 				if (IPCL_IS_NONSTR(tcp->tcp_connp))
10084 					proto_set_rx_oob_opt(connp, onoff);
10085 			}
10086 			break;
10087 		case SO_DGRAM_ERRIND:
10088 			if (!checkonly)
10089 				tcp->tcp_dgram_errind = onoff;
10090 			break;
10091 		case SO_SNDBUF: {
10092 			if (*i1 > tcps->tcps_max_buf) {
10093 				*outlenp = 0;
10094 				return (ENOBUFS);
10095 			}
10096 			if (checkonly)
10097 				break;
10098 
10099 			tcp->tcp_xmit_hiwater = *i1;
10100 			if (tcps->tcps_snd_lowat_fraction != 0)
10101 				tcp->tcp_xmit_lowater =
10102 				    tcp->tcp_xmit_hiwater /
10103 				    tcps->tcps_snd_lowat_fraction;
10104 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10105 			/*
10106 			 * If we are flow-controlled, recheck the condition.
10107 			 * There are apps that increase SO_SNDBUF size when
10108 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10109 			 * control condition to be lifted right away.
10110 			 */
10111 			mutex_enter(&tcp->tcp_non_sq_lock);
10112 			if (tcp->tcp_flow_stopped &&
10113 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10114 				tcp_clrqfull(tcp);
10115 			}
10116 			mutex_exit(&tcp->tcp_non_sq_lock);
10117 			break;
10118 		}
10119 		case SO_RCVBUF:
10120 			if (*i1 > tcps->tcps_max_buf) {
10121 				*outlenp = 0;
10122 				return (ENOBUFS);
10123 			}
10124 			/* Silently ignore zero */
10125 			if (!checkonly && *i1 != 0) {
10126 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10127 				(void) tcp_rwnd_set(tcp, *i1);
10128 			}
10129 			/*
10130 			 * XXX should we return the rwnd here
10131 			 * and tcp_opt_get ?
10132 			 */
10133 			break;
10134 		case SO_SND_COPYAVOID:
10135 			if (!checkonly) {
10136 				/* we only allow enable at most once for now */
10137 				if (tcp->tcp_loopback ||
10138 				    (tcp->tcp_kssl_ctx != NULL) ||
10139 				    (!tcp->tcp_snd_zcopy_aware &&
10140 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10141 					*outlenp = 0;
10142 					return (EOPNOTSUPP);
10143 				}
10144 				tcp->tcp_snd_zcopy_aware = 1;
10145 			}
10146 			break;
10147 		case SO_ALLZONES:
10148 			/* Pass option along to IP level for handling */
10149 			return (-EINVAL);
10150 		case SO_ANON_MLP:
10151 			/* Pass option along to IP level for handling */
10152 			return (-EINVAL);
10153 		case SO_MAC_EXEMPT:
10154 			/* Pass option along to IP level for handling */
10155 			return (-EINVAL);
10156 		case SO_EXCLBIND:
10157 			if (!checkonly)
10158 				tcp->tcp_exclbind = onoff;
10159 			break;
10160 		default:
10161 			*outlenp = 0;
10162 			return (EINVAL);
10163 		}
10164 		break;
10165 	case IPPROTO_TCP:
10166 		switch (name) {
10167 		case TCP_NODELAY:
10168 			if (!checkonly)
10169 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10170 			break;
10171 		case TCP_NOTIFY_THRESHOLD:
10172 			if (!checkonly)
10173 				tcp->tcp_first_timer_threshold = *i1;
10174 			break;
10175 		case TCP_ABORT_THRESHOLD:
10176 			if (!checkonly)
10177 				tcp->tcp_second_timer_threshold = *i1;
10178 			break;
10179 		case TCP_CONN_NOTIFY_THRESHOLD:
10180 			if (!checkonly)
10181 				tcp->tcp_first_ctimer_threshold = *i1;
10182 			break;
10183 		case TCP_CONN_ABORT_THRESHOLD:
10184 			if (!checkonly)
10185 				tcp->tcp_second_ctimer_threshold = *i1;
10186 			break;
10187 		case TCP_RECVDSTADDR:
10188 			if (tcp->tcp_state > TCPS_LISTEN)
10189 				return (EOPNOTSUPP);
10190 			if (!checkonly)
10191 				tcp->tcp_recvdstaddr = onoff;
10192 			break;
10193 		case TCP_ANONPRIVBIND:
10194 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10195 			    IPPROTO_TCP)) != 0) {
10196 				*outlenp = 0;
10197 				return (reterr);
10198 			}
10199 			if (!checkonly) {
10200 				tcp->tcp_anon_priv_bind = onoff;
10201 			}
10202 			break;
10203 		case TCP_EXCLBIND:
10204 			if (!checkonly)
10205 				tcp->tcp_exclbind = onoff;
10206 			break;	/* goto sizeof (int) option return */
10207 		case TCP_INIT_CWND: {
10208 			uint32_t init_cwnd = *((uint32_t *)invalp);
10209 
10210 			if (checkonly)
10211 				break;
10212 
10213 			/*
10214 			 * Only allow socket with network configuration
10215 			 * privilege to set the initial cwnd to be larger
10216 			 * than allowed by RFC 3390.
10217 			 */
10218 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10219 				tcp->tcp_init_cwnd = init_cwnd;
10220 				break;
10221 			}
10222 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10223 				*outlenp = 0;
10224 				return (reterr);
10225 			}
10226 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10227 				*outlenp = 0;
10228 				return (EINVAL);
10229 			}
10230 			tcp->tcp_init_cwnd = init_cwnd;
10231 			break;
10232 		}
10233 		case TCP_KEEPALIVE_THRESHOLD:
10234 			if (checkonly)
10235 				break;
10236 
10237 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10238 			    *i1 > tcps->tcps_keepalive_interval_high) {
10239 				*outlenp = 0;
10240 				return (EINVAL);
10241 			}
10242 			if (*i1 != tcp->tcp_ka_interval) {
10243 				tcp->tcp_ka_interval = *i1;
10244 				/*
10245 				 * Check if we need to restart the
10246 				 * keepalive timer.
10247 				 */
10248 				if (tcp->tcp_ka_tid != 0) {
10249 					ASSERT(tcp->tcp_ka_enabled);
10250 					(void) TCP_TIMER_CANCEL(tcp,
10251 					    tcp->tcp_ka_tid);
10252 					tcp->tcp_ka_last_intrvl = 0;
10253 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10254 					    tcp_keepalive_killer,
10255 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10256 				}
10257 			}
10258 			break;
10259 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10260 			if (!checkonly) {
10261 				if (*i1 <
10262 				    tcps->tcps_keepalive_abort_interval_low ||
10263 				    *i1 >
10264 				    tcps->tcps_keepalive_abort_interval_high) {
10265 					*outlenp = 0;
10266 					return (EINVAL);
10267 				}
10268 				tcp->tcp_ka_abort_thres = *i1;
10269 			}
10270 			break;
10271 		case TCP_CORK:
10272 			if (!checkonly) {
10273 				/*
10274 				 * if tcp->tcp_cork was set and is now
10275 				 * being unset, we have to make sure that
10276 				 * the remaining data gets sent out. Also
10277 				 * unset tcp->tcp_cork so that tcp_wput_data()
10278 				 * can send data even if it is less than mss
10279 				 */
10280 				if (tcp->tcp_cork && onoff == 0 &&
10281 				    tcp->tcp_unsent > 0) {
10282 					tcp->tcp_cork = B_FALSE;
10283 					tcp_wput_data(tcp, NULL, B_FALSE);
10284 				}
10285 				tcp->tcp_cork = onoff;
10286 			}
10287 			break;
10288 		default:
10289 			*outlenp = 0;
10290 			return (EINVAL);
10291 		}
10292 		break;
10293 	case IPPROTO_IP:
10294 		if (tcp->tcp_family != AF_INET) {
10295 			*outlenp = 0;
10296 			return (ENOPROTOOPT);
10297 		}
10298 		switch (name) {
10299 		case IP_OPTIONS:
10300 		case T_IP_OPTIONS:
10301 			reterr = tcp_opt_set_header(tcp, checkonly,
10302 			    invalp, inlen);
10303 			if (reterr) {
10304 				*outlenp = 0;
10305 				return (reterr);
10306 			}
10307 			/* OK return - copy input buffer into output buffer */
10308 			if (invalp != outvalp) {
10309 				/* don't trust bcopy for identical src/dst */
10310 				bcopy(invalp, outvalp, inlen);
10311 			}
10312 			*outlenp = inlen;
10313 			return (0);
10314 		case IP_TOS:
10315 		case T_IP_TOS:
10316 			if (!checkonly) {
10317 				tcp->tcp_ipha->ipha_type_of_service =
10318 				    (uchar_t)*i1;
10319 				tcp->tcp_tos = (uchar_t)*i1;
10320 			}
10321 			break;
10322 		case IP_TTL:
10323 			if (!checkonly) {
10324 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10325 				tcp->tcp_ttl = (uchar_t)*i1;
10326 			}
10327 			break;
10328 		case IP_BOUND_IF:
10329 		case IP_NEXTHOP:
10330 			/* Handled at the IP level */
10331 			return (-EINVAL);
10332 		case IP_SEC_OPT:
10333 			/*
10334 			 * We should not allow policy setting after
10335 			 * we start listening for connections.
10336 			 */
10337 			if (tcp->tcp_state == TCPS_LISTEN) {
10338 				return (EINVAL);
10339 			} else {
10340 				/* Handled at the IP level */
10341 				return (-EINVAL);
10342 			}
10343 		default:
10344 			*outlenp = 0;
10345 			return (EINVAL);
10346 		}
10347 		break;
10348 	case IPPROTO_IPV6: {
10349 		ip6_pkt_t		*ipp;
10350 
10351 		/*
10352 		 * IPPROTO_IPV6 options are only supported for sockets
10353 		 * that are using IPv6 on the wire.
10354 		 */
10355 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10356 			*outlenp = 0;
10357 			return (ENOPROTOOPT);
10358 		}
10359 		/*
10360 		 * Only sticky options; no ancillary data
10361 		 */
10362 		ipp = &tcp->tcp_sticky_ipp;
10363 
10364 		switch (name) {
10365 		case IPV6_UNICAST_HOPS:
10366 			/* -1 means use default */
10367 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10368 				*outlenp = 0;
10369 				return (EINVAL);
10370 			}
10371 			if (!checkonly) {
10372 				if (*i1 == -1) {
10373 					tcp->tcp_ip6h->ip6_hops =
10374 					    ipp->ipp_unicast_hops =
10375 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10376 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10377 					/* Pass modified value to IP. */
10378 					*i1 = tcp->tcp_ip6h->ip6_hops;
10379 				} else {
10380 					tcp->tcp_ip6h->ip6_hops =
10381 					    ipp->ipp_unicast_hops =
10382 					    (uint8_t)*i1;
10383 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10384 				}
10385 				reterr = tcp_build_hdrs(tcp);
10386 				if (reterr != 0)
10387 					return (reterr);
10388 			}
10389 			break;
10390 		case IPV6_BOUND_IF:
10391 			if (!checkonly) {
10392 				tcp->tcp_bound_if = *i1;
10393 				PASS_OPT_TO_IP(connp);
10394 			}
10395 			break;
10396 		/*
10397 		 * Set boolean switches for ancillary data delivery
10398 		 */
10399 		case IPV6_RECVPKTINFO:
10400 			if (!checkonly) {
10401 				if (onoff)
10402 					tcp->tcp_ipv6_recvancillary |=
10403 					    TCP_IPV6_RECVPKTINFO;
10404 				else
10405 					tcp->tcp_ipv6_recvancillary &=
10406 					    ~TCP_IPV6_RECVPKTINFO;
10407 				/* Force it to be sent up with the next msg */
10408 				tcp->tcp_recvifindex = 0;
10409 				PASS_OPT_TO_IP(connp);
10410 			}
10411 			break;
10412 		case IPV6_RECVTCLASS:
10413 			if (!checkonly) {
10414 				if (onoff)
10415 					tcp->tcp_ipv6_recvancillary |=
10416 					    TCP_IPV6_RECVTCLASS;
10417 				else
10418 					tcp->tcp_ipv6_recvancillary &=
10419 					    ~TCP_IPV6_RECVTCLASS;
10420 				PASS_OPT_TO_IP(connp);
10421 			}
10422 			break;
10423 		case IPV6_RECVHOPLIMIT:
10424 			if (!checkonly) {
10425 				if (onoff)
10426 					tcp->tcp_ipv6_recvancillary |=
10427 					    TCP_IPV6_RECVHOPLIMIT;
10428 				else
10429 					tcp->tcp_ipv6_recvancillary &=
10430 					    ~TCP_IPV6_RECVHOPLIMIT;
10431 				/* Force it to be sent up with the next msg */
10432 				tcp->tcp_recvhops = 0xffffffffU;
10433 				PASS_OPT_TO_IP(connp);
10434 			}
10435 			break;
10436 		case IPV6_RECVHOPOPTS:
10437 			if (!checkonly) {
10438 				if (onoff)
10439 					tcp->tcp_ipv6_recvancillary |=
10440 					    TCP_IPV6_RECVHOPOPTS;
10441 				else
10442 					tcp->tcp_ipv6_recvancillary &=
10443 					    ~TCP_IPV6_RECVHOPOPTS;
10444 				PASS_OPT_TO_IP(connp);
10445 			}
10446 			break;
10447 		case IPV6_RECVDSTOPTS:
10448 			if (!checkonly) {
10449 				if (onoff)
10450 					tcp->tcp_ipv6_recvancillary |=
10451 					    TCP_IPV6_RECVDSTOPTS;
10452 				else
10453 					tcp->tcp_ipv6_recvancillary &=
10454 					    ~TCP_IPV6_RECVDSTOPTS;
10455 				PASS_OPT_TO_IP(connp);
10456 			}
10457 			break;
10458 		case _OLD_IPV6_RECVDSTOPTS:
10459 			if (!checkonly) {
10460 				if (onoff)
10461 					tcp->tcp_ipv6_recvancillary |=
10462 					    TCP_OLD_IPV6_RECVDSTOPTS;
10463 				else
10464 					tcp->tcp_ipv6_recvancillary &=
10465 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10466 			}
10467 			break;
10468 		case IPV6_RECVRTHDR:
10469 			if (!checkonly) {
10470 				if (onoff)
10471 					tcp->tcp_ipv6_recvancillary |=
10472 					    TCP_IPV6_RECVRTHDR;
10473 				else
10474 					tcp->tcp_ipv6_recvancillary &=
10475 					    ~TCP_IPV6_RECVRTHDR;
10476 				PASS_OPT_TO_IP(connp);
10477 			}
10478 			break;
10479 		case IPV6_RECVRTHDRDSTOPTS:
10480 			if (!checkonly) {
10481 				if (onoff)
10482 					tcp->tcp_ipv6_recvancillary |=
10483 					    TCP_IPV6_RECVRTDSTOPTS;
10484 				else
10485 					tcp->tcp_ipv6_recvancillary &=
10486 					    ~TCP_IPV6_RECVRTDSTOPTS;
10487 				PASS_OPT_TO_IP(connp);
10488 			}
10489 			break;
10490 		case IPV6_PKTINFO:
10491 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10492 				return (EINVAL);
10493 			if (checkonly)
10494 				break;
10495 
10496 			if (inlen == 0) {
10497 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10498 			} else {
10499 				struct in6_pktinfo *pkti;
10500 
10501 				pkti = (struct in6_pktinfo *)invalp;
10502 				/*
10503 				 * RFC 3542 states that ipi6_addr must be
10504 				 * the unspecified address when setting the
10505 				 * IPV6_PKTINFO sticky socket option on a
10506 				 * TCP socket.
10507 				 */
10508 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10509 					return (EINVAL);
10510 				/*
10511 				 * IP will validate the source address and
10512 				 * interface index.
10513 				 */
10514 				if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
10515 					reterr = ip_set_options(tcp->tcp_connp,
10516 					    level, name, invalp, inlen, cr);
10517 				} else {
10518 					reterr = ip6_set_pktinfo(cr,
10519 					    tcp->tcp_connp, pkti, mblk);
10520 				}
10521 				if (reterr != 0)
10522 					return (reterr);
10523 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10524 				ipp->ipp_addr = pkti->ipi6_addr;
10525 				if (ipp->ipp_ifindex != 0)
10526 					ipp->ipp_fields |= IPPF_IFINDEX;
10527 				else
10528 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10529 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10530 					ipp->ipp_fields |= IPPF_ADDR;
10531 				else
10532 					ipp->ipp_fields &= ~IPPF_ADDR;
10533 			}
10534 			reterr = tcp_build_hdrs(tcp);
10535 			if (reterr != 0)
10536 				return (reterr);
10537 			break;
10538 		case IPV6_TCLASS:
10539 			if (inlen != 0 && inlen != sizeof (int))
10540 				return (EINVAL);
10541 			if (checkonly)
10542 				break;
10543 
10544 			if (inlen == 0) {
10545 				ipp->ipp_fields &= ~IPPF_TCLASS;
10546 			} else {
10547 				if (*i1 > 255 || *i1 < -1)
10548 					return (EINVAL);
10549 				if (*i1 == -1) {
10550 					ipp->ipp_tclass = 0;
10551 					*i1 = 0;
10552 				} else {
10553 					ipp->ipp_tclass = *i1;
10554 				}
10555 				ipp->ipp_fields |= IPPF_TCLASS;
10556 			}
10557 			reterr = tcp_build_hdrs(tcp);
10558 			if (reterr != 0)
10559 				return (reterr);
10560 			break;
10561 		case IPV6_NEXTHOP:
10562 			/*
10563 			 * IP will verify that the nexthop is reachable
10564 			 * and fail for sticky options.
10565 			 */
10566 			if (inlen != 0 && inlen != sizeof (sin6_t))
10567 				return (EINVAL);
10568 			if (checkonly)
10569 				break;
10570 
10571 			if (inlen == 0) {
10572 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10573 			} else {
10574 				sin6_t *sin6 = (sin6_t *)invalp;
10575 
10576 				if (sin6->sin6_family != AF_INET6)
10577 					return (EAFNOSUPPORT);
10578 				if (IN6_IS_ADDR_V4MAPPED(
10579 				    &sin6->sin6_addr))
10580 					return (EADDRNOTAVAIL);
10581 				ipp->ipp_nexthop = sin6->sin6_addr;
10582 				if (!IN6_IS_ADDR_UNSPECIFIED(
10583 				    &ipp->ipp_nexthop))
10584 					ipp->ipp_fields |= IPPF_NEXTHOP;
10585 				else
10586 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10587 			}
10588 			reterr = tcp_build_hdrs(tcp);
10589 			if (reterr != 0)
10590 				return (reterr);
10591 			PASS_OPT_TO_IP(connp);
10592 			break;
10593 		case IPV6_HOPOPTS: {
10594 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10595 
10596 			/*
10597 			 * Sanity checks - minimum size, size a multiple of
10598 			 * eight bytes, and matching size passed in.
10599 			 */
10600 			if (inlen != 0 &&
10601 			    inlen != (8 * (hopts->ip6h_len + 1)))
10602 				return (EINVAL);
10603 
10604 			if (checkonly)
10605 				break;
10606 
10607 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10608 			    (uchar_t **)&ipp->ipp_hopopts,
10609 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10610 			if (reterr != 0)
10611 				return (reterr);
10612 			if (ipp->ipp_hopoptslen == 0)
10613 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10614 			else
10615 				ipp->ipp_fields |= IPPF_HOPOPTS;
10616 			reterr = tcp_build_hdrs(tcp);
10617 			if (reterr != 0)
10618 				return (reterr);
10619 			break;
10620 		}
10621 		case IPV6_RTHDRDSTOPTS: {
10622 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10623 
10624 			/*
10625 			 * Sanity checks - minimum size, size a multiple of
10626 			 * eight bytes, and matching size passed in.
10627 			 */
10628 			if (inlen != 0 &&
10629 			    inlen != (8 * (dopts->ip6d_len + 1)))
10630 				return (EINVAL);
10631 
10632 			if (checkonly)
10633 				break;
10634 
10635 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10636 			    (uchar_t **)&ipp->ipp_rtdstopts,
10637 			    &ipp->ipp_rtdstoptslen, 0);
10638 			if (reterr != 0)
10639 				return (reterr);
10640 			if (ipp->ipp_rtdstoptslen == 0)
10641 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10642 			else
10643 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10644 			reterr = tcp_build_hdrs(tcp);
10645 			if (reterr != 0)
10646 				return (reterr);
10647 			break;
10648 		}
10649 		case IPV6_DSTOPTS: {
10650 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10651 
10652 			/*
10653 			 * Sanity checks - minimum size, size a multiple of
10654 			 * eight bytes, and matching size passed in.
10655 			 */
10656 			if (inlen != 0 &&
10657 			    inlen != (8 * (dopts->ip6d_len + 1)))
10658 				return (EINVAL);
10659 
10660 			if (checkonly)
10661 				break;
10662 
10663 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10664 			    (uchar_t **)&ipp->ipp_dstopts,
10665 			    &ipp->ipp_dstoptslen, 0);
10666 			if (reterr != 0)
10667 				return (reterr);
10668 			if (ipp->ipp_dstoptslen == 0)
10669 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10670 			else
10671 				ipp->ipp_fields |= IPPF_DSTOPTS;
10672 			reterr = tcp_build_hdrs(tcp);
10673 			if (reterr != 0)
10674 				return (reterr);
10675 			break;
10676 		}
10677 		case IPV6_RTHDR: {
10678 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10679 
10680 			/*
10681 			 * Sanity checks - minimum size, size a multiple of
10682 			 * eight bytes, and matching size passed in.
10683 			 */
10684 			if (inlen != 0 &&
10685 			    inlen != (8 * (rt->ip6r_len + 1)))
10686 				return (EINVAL);
10687 
10688 			if (checkonly)
10689 				break;
10690 
10691 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10692 			    (uchar_t **)&ipp->ipp_rthdr,
10693 			    &ipp->ipp_rthdrlen, 0);
10694 			if (reterr != 0)
10695 				return (reterr);
10696 			if (ipp->ipp_rthdrlen == 0)
10697 				ipp->ipp_fields &= ~IPPF_RTHDR;
10698 			else
10699 				ipp->ipp_fields |= IPPF_RTHDR;
10700 			reterr = tcp_build_hdrs(tcp);
10701 			if (reterr != 0)
10702 				return (reterr);
10703 			break;
10704 		}
10705 		case IPV6_V6ONLY:
10706 			if (!checkonly) {
10707 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10708 			}
10709 			break;
10710 		case IPV6_USE_MIN_MTU:
10711 			if (inlen != sizeof (int))
10712 				return (EINVAL);
10713 
10714 			if (*i1 < -1 || *i1 > 1)
10715 				return (EINVAL);
10716 
10717 			if (checkonly)
10718 				break;
10719 
10720 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10721 			ipp->ipp_use_min_mtu = *i1;
10722 			break;
10723 		case IPV6_BOUND_PIF:
10724 			/* Handled at the IP level */
10725 			return (-EINVAL);
10726 		case IPV6_SEC_OPT:
10727 			/*
10728 			 * We should not allow policy setting after
10729 			 * we start listening for connections.
10730 			 */
10731 			if (tcp->tcp_state == TCPS_LISTEN) {
10732 				return (EINVAL);
10733 			} else {
10734 				/* Handled at the IP level */
10735 				return (-EINVAL);
10736 			}
10737 		case IPV6_SRC_PREFERENCES:
10738 			if (inlen != sizeof (uint32_t))
10739 				return (EINVAL);
10740 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10741 			    *(uint32_t *)invalp);
10742 			if (reterr != 0) {
10743 				*outlenp = 0;
10744 				return (reterr);
10745 			}
10746 			break;
10747 		default:
10748 			*outlenp = 0;
10749 			return (EINVAL);
10750 		}
10751 		break;
10752 	}		/* end IPPROTO_IPV6 */
10753 	default:
10754 		*outlenp = 0;
10755 		return (EINVAL);
10756 	}
10757 	/*
10758 	 * Common case of OK return with outval same as inval
10759 	 */
10760 	if (invalp != outvalp) {
10761 		/* don't trust bcopy for identical src/dst */
10762 		(void) bcopy(invalp, outvalp, inlen);
10763 	}
10764 	*outlenp = inlen;
10765 	return (0);
10766 }
10767 
10768 /* ARGSUSED */
10769 int
10770 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10771     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10772     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10773 {
10774 	conn_t	*connp =  Q_TO_CONN(q);
10775 
10776 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
10777 	    outlenp, outvalp, thisdg_attrs, cr, mblk));
10778 }
10779 
10780 int
10781 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
10782     const void *optvalp, socklen_t optlen, cred_t *cr)
10783 {
10784 	conn_t		*connp = (conn_t *)proto_handle;
10785 	squeue_t	*sqp = connp->conn_sqp;
10786 	int		error;
10787 
10788 	/*
10789 	 * Entering the squeue synchronously can result in a context switch,
10790 	 * which can cause a rather sever performance degradation. So we try to
10791 	 * handle whatever options we can without entering the squeue.
10792 	 */
10793 	if (level == IPPROTO_TCP) {
10794 		switch (option_name) {
10795 		case TCP_NODELAY:
10796 			if (optlen != sizeof (int32_t))
10797 				return (EINVAL);
10798 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
10799 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
10800 			    connp->conn_tcp->tcp_mss;
10801 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
10802 			return (0);
10803 		default:
10804 			break;
10805 		}
10806 	}
10807 
10808 	error = squeue_synch_enter(sqp, connp, 0);
10809 	if (error == ENOMEM) {
10810 		return (ENOMEM);
10811 	}
10812 
10813 	error = proto_opt_check(level, option_name, optlen, NULL,
10814 	    tcp_opt_obj.odb_opt_des_arr,
10815 	    tcp_opt_obj.odb_opt_arr_cnt,
10816 	    tcp_opt_obj.odb_topmost_tpiprovider,
10817 	    B_TRUE, B_FALSE, cr);
10818 
10819 	if (error != 0) {
10820 		if (error < 0) {
10821 			error = proto_tlitosyserr(-error);
10822 		}
10823 		squeue_synch_exit(sqp, connp);
10824 		return (error);
10825 	}
10826 
10827 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
10828 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
10829 	    NULL, cr, NULL);
10830 	squeue_synch_exit(sqp, connp);
10831 
10832 	if (error < 0) {
10833 		/*
10834 		 * Pass on to ip
10835 		 */
10836 		error = ip_set_options(connp, level, option_name, optvalp,
10837 		    optlen, cr);
10838 	}
10839 	return (error);
10840 }
10841 
10842 /*
10843  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10844  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10845  * headers, and the maximum size tcp header (to avoid reallocation
10846  * on the fly for additional tcp options).
10847  * Returns failure if can't allocate memory.
10848  */
10849 static int
10850 tcp_build_hdrs(tcp_t *tcp)
10851 {
10852 	char	*hdrs;
10853 	uint_t	hdrs_len;
10854 	ip6i_t	*ip6i;
10855 	char	buf[TCP_MAX_HDR_LENGTH];
10856 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10857 	in6_addr_t src, dst;
10858 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10859 	conn_t *connp = tcp->tcp_connp;
10860 
10861 	/*
10862 	 * save the existing tcp header and source/dest IP addresses
10863 	 */
10864 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10865 	src = tcp->tcp_ip6h->ip6_src;
10866 	dst = tcp->tcp_ip6h->ip6_dst;
10867 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10868 	ASSERT(hdrs_len != 0);
10869 	if (hdrs_len > tcp->tcp_iphc_len) {
10870 		/* Need to reallocate */
10871 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10872 		if (hdrs == NULL)
10873 			return (ENOMEM);
10874 		if (tcp->tcp_iphc != NULL) {
10875 			if (tcp->tcp_hdr_grown) {
10876 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10877 			} else {
10878 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10879 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10880 			}
10881 			tcp->tcp_iphc_len = 0;
10882 		}
10883 		ASSERT(tcp->tcp_iphc_len == 0);
10884 		tcp->tcp_iphc = hdrs;
10885 		tcp->tcp_iphc_len = hdrs_len;
10886 		tcp->tcp_hdr_grown = B_TRUE;
10887 	}
10888 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10889 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10890 
10891 	/* Set header fields not in ipp */
10892 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10893 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10894 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10895 	} else {
10896 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10897 	}
10898 	/*
10899 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10900 	 *
10901 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10902 	 */
10903 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10904 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10905 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10906 
10907 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10908 
10909 	tcp->tcp_ip6h->ip6_src = src;
10910 	tcp->tcp_ip6h->ip6_dst = dst;
10911 
10912 	/*
10913 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10914 	 * the default value for TCP.
10915 	 */
10916 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10917 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
10918 
10919 	/*
10920 	 * If we're setting extension headers after a connection
10921 	 * has been established, and if we have a routing header
10922 	 * among the extension headers, call ip_massage_options_v6 to
10923 	 * manipulate the routing header/ip6_dst set the checksum
10924 	 * difference in the tcp header template.
10925 	 * (This happens in tcp_connect_ipv6 if the routing header
10926 	 * is set prior to the connect.)
10927 	 * Set the tcp_sum to zero first in case we've cleared a
10928 	 * routing header or don't have one at all.
10929 	 */
10930 	tcp->tcp_sum = 0;
10931 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10932 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10933 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10934 		    (uint8_t *)tcp->tcp_tcph);
10935 		if (rth != NULL) {
10936 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10937 			    rth, tcps->tcps_netstack);
10938 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10939 			    (tcp->tcp_sum >> 16));
10940 		}
10941 	}
10942 
10943 	/* Try to get everything in a single mblk */
10944 	(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
10945 	    hdrs_len + tcps->tcps_wroff_xtra);
10946 	return (0);
10947 }
10948 
10949 /*
10950  * Transfer any source route option from ipha to buf/dst in reversed form.
10951  */
10952 static int
10953 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10954 {
10955 	ipoptp_t	opts;
10956 	uchar_t		*opt;
10957 	uint8_t		optval;
10958 	uint8_t		optlen;
10959 	uint32_t	len = 0;
10960 
10961 	for (optval = ipoptp_first(&opts, ipha);
10962 	    optval != IPOPT_EOL;
10963 	    optval = ipoptp_next(&opts)) {
10964 		opt = opts.ipoptp_cur;
10965 		optlen = opts.ipoptp_len;
10966 		switch (optval) {
10967 			int	off1, off2;
10968 		case IPOPT_SSRR:
10969 		case IPOPT_LSRR:
10970 
10971 			/* Reverse source route */
10972 			/*
10973 			 * First entry should be the next to last one in the
10974 			 * current source route (the last entry is our
10975 			 * address.)
10976 			 * The last entry should be the final destination.
10977 			 */
10978 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10979 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10980 			off1 = IPOPT_MINOFF_SR - 1;
10981 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10982 			if (off2 < 0) {
10983 				/* No entries in source route */
10984 				break;
10985 			}
10986 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10987 			/*
10988 			 * Note: use src since ipha has not had its src
10989 			 * and dst reversed (it is in the state it was
10990 			 * received.
10991 			 */
10992 			bcopy(&ipha->ipha_src, buf + off2,
10993 			    IP_ADDR_LEN);
10994 			off2 -= IP_ADDR_LEN;
10995 
10996 			while (off2 > 0) {
10997 				bcopy(opt + off2, buf + off1,
10998 				    IP_ADDR_LEN);
10999 				off1 += IP_ADDR_LEN;
11000 				off2 -= IP_ADDR_LEN;
11001 			}
11002 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11003 			buf += optlen;
11004 			len += optlen;
11005 			break;
11006 		}
11007 	}
11008 done:
11009 	/* Pad the resulting options */
11010 	while (len & 0x3) {
11011 		*buf++ = IPOPT_EOL;
11012 		len++;
11013 	}
11014 	return (len);
11015 }
11016 
11017 
11018 /*
11019  * Extract and revert a source route from ipha (if any)
11020  * and then update the relevant fields in both tcp_t and the standard header.
11021  */
11022 static void
11023 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11024 {
11025 	char	buf[TCP_MAX_HDR_LENGTH];
11026 	uint_t	tcph_len;
11027 	int	len;
11028 
11029 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11030 	len = IPH_HDR_LENGTH(ipha);
11031 	if (len == IP_SIMPLE_HDR_LENGTH)
11032 		/* Nothing to do */
11033 		return;
11034 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11035 	    (len & 0x3))
11036 		return;
11037 
11038 	tcph_len = tcp->tcp_tcp_hdr_len;
11039 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11040 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11041 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11042 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11043 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11044 	len += IP_SIMPLE_HDR_LENGTH;
11045 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11046 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11047 	if ((int)tcp->tcp_sum < 0)
11048 		tcp->tcp_sum--;
11049 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11050 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11051 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11052 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11053 	tcp->tcp_ip_hdr_len = len;
11054 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11055 	    (IP_VERSION << 4) | (len >> 2);
11056 	len += tcph_len;
11057 	tcp->tcp_hdr_len = len;
11058 }
11059 
11060 /*
11061  * Copy the standard header into its new location,
11062  * lay in the new options and then update the relevant
11063  * fields in both tcp_t and the standard header.
11064  */
11065 static int
11066 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11067 {
11068 	uint_t	tcph_len;
11069 	uint8_t	*ip_optp;
11070 	tcph_t	*new_tcph;
11071 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11072 	conn_t	*connp = tcp->tcp_connp;
11073 
11074 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11075 		return (EINVAL);
11076 
11077 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11078 		return (EINVAL);
11079 
11080 	if (checkonly) {
11081 		/*
11082 		 * do not really set, just pretend to - T_CHECK
11083 		 */
11084 		return (0);
11085 	}
11086 
11087 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11088 	if (tcp->tcp_label_len > 0) {
11089 		int padlen;
11090 		uint8_t opt;
11091 
11092 		/* convert list termination to no-ops */
11093 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11094 		ip_optp += ip_optp[IPOPT_OLEN];
11095 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11096 		while (--padlen >= 0)
11097 			*ip_optp++ = opt;
11098 	}
11099 	tcph_len = tcp->tcp_tcp_hdr_len;
11100 	new_tcph = (tcph_t *)(ip_optp + len);
11101 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11102 	tcp->tcp_tcph = new_tcph;
11103 	bcopy(ptr, ip_optp, len);
11104 
11105 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11106 
11107 	tcp->tcp_ip_hdr_len = len;
11108 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11109 	    (IP_VERSION << 4) | (len >> 2);
11110 	tcp->tcp_hdr_len = len + tcph_len;
11111 	if (!TCP_IS_DETACHED(tcp)) {
11112 		/* Always allocate room for all options. */
11113 		(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
11114 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11115 	}
11116 	return (0);
11117 }
11118 
11119 /* Get callback routine passed to nd_load by tcp_param_register */
11120 /* ARGSUSED */
11121 static int
11122 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11123 {
11124 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11125 
11126 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11127 	return (0);
11128 }
11129 
11130 /*
11131  * Walk through the param array specified registering each element with the
11132  * named dispatch handler.
11133  */
11134 static boolean_t
11135 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11136 {
11137 	for (; cnt-- > 0; tcppa++) {
11138 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11139 			if (!nd_load(ndp, tcppa->tcp_param_name,
11140 			    tcp_param_get, tcp_param_set,
11141 			    (caddr_t)tcppa)) {
11142 				nd_free(ndp);
11143 				return (B_FALSE);
11144 			}
11145 		}
11146 	}
11147 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11148 	    KM_SLEEP);
11149 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11150 	    sizeof (tcpparam_t));
11151 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11152 	    tcp_param_get, tcp_param_set_aligned,
11153 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11154 		nd_free(ndp);
11155 		return (B_FALSE);
11156 	}
11157 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11158 	    KM_SLEEP);
11159 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11160 	    sizeof (tcpparam_t));
11161 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11162 	    tcp_param_get, tcp_param_set_aligned,
11163 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11164 		nd_free(ndp);
11165 		return (B_FALSE);
11166 	}
11167 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11168 	    KM_SLEEP);
11169 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11170 	    sizeof (tcpparam_t));
11171 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11172 	    tcp_param_get, tcp_param_set_aligned,
11173 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11174 		nd_free(ndp);
11175 		return (B_FALSE);
11176 	}
11177 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11178 	    KM_SLEEP);
11179 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11180 	    sizeof (tcpparam_t));
11181 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11182 	    tcp_param_get, tcp_param_set_aligned,
11183 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11184 		nd_free(ndp);
11185 		return (B_FALSE);
11186 	}
11187 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11188 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11189 		nd_free(ndp);
11190 		return (B_FALSE);
11191 	}
11192 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11193 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11194 		nd_free(ndp);
11195 		return (B_FALSE);
11196 	}
11197 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11198 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11199 		nd_free(ndp);
11200 		return (B_FALSE);
11201 	}
11202 	if (!nd_load(ndp, "tcp_status", tcp_status_report, NULL,
11203 	    NULL)) {
11204 		nd_free(ndp);
11205 		return (B_FALSE);
11206 	}
11207 	if (!nd_load(ndp, "tcp_bind_hash", tcp_bind_hash_report,
11208 	    NULL, NULL)) {
11209 		nd_free(ndp);
11210 		return (B_FALSE);
11211 	}
11212 	if (!nd_load(ndp, "tcp_listen_hash",
11213 	    tcp_listen_hash_report, NULL, NULL)) {
11214 		nd_free(ndp);
11215 		return (B_FALSE);
11216 	}
11217 	if (!nd_load(ndp, "tcp_conn_hash", tcp_conn_hash_report,
11218 	    NULL, NULL)) {
11219 		nd_free(ndp);
11220 		return (B_FALSE);
11221 	}
11222 	if (!nd_load(ndp, "tcp_acceptor_hash",
11223 	    tcp_acceptor_hash_report, NULL, NULL)) {
11224 		nd_free(ndp);
11225 		return (B_FALSE);
11226 	}
11227 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11228 	    tcp_1948_phrase_set, NULL)) {
11229 		nd_free(ndp);
11230 		return (B_FALSE);
11231 	}
11232 	/*
11233 	 * Dummy ndd variables - only to convey obsolescence information
11234 	 * through printing of their name (no get or set routines)
11235 	 * XXX Remove in future releases ?
11236 	 */
11237 	if (!nd_load(ndp,
11238 	    "tcp_close_wait_interval(obsoleted - "
11239 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11240 		nd_free(ndp);
11241 		return (B_FALSE);
11242 	}
11243 	return (B_TRUE);
11244 }
11245 
11246 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11247 /* ARGSUSED */
11248 static int
11249 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11250     cred_t *cr)
11251 {
11252 	long new_value;
11253 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11254 
11255 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11256 	    new_value < tcppa->tcp_param_min ||
11257 	    new_value > tcppa->tcp_param_max) {
11258 		return (EINVAL);
11259 	}
11260 	/*
11261 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11262 	 * round it up.  For future 64 bit requirement, we actually make it
11263 	 * a multiple of 8.
11264 	 */
11265 	if (new_value & 0x7) {
11266 		new_value = (new_value & ~0x7) + 0x8;
11267 	}
11268 	tcppa->tcp_param_val = new_value;
11269 	return (0);
11270 }
11271 
11272 /* Set callback routine passed to nd_load by tcp_param_register */
11273 /* ARGSUSED */
11274 static int
11275 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11276 {
11277 	long	new_value;
11278 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11279 
11280 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11281 	    new_value < tcppa->tcp_param_min ||
11282 	    new_value > tcppa->tcp_param_max) {
11283 		return (EINVAL);
11284 	}
11285 	tcppa->tcp_param_val = new_value;
11286 	return (0);
11287 }
11288 
11289 /*
11290  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11291  * is filled, return as much as we can.  The message passed in may be
11292  * multi-part, chained using b_cont.  "start" is the starting sequence
11293  * number for this piece.
11294  */
11295 static mblk_t *
11296 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11297 {
11298 	uint32_t	end;
11299 	mblk_t		*mp1;
11300 	mblk_t		*mp2;
11301 	mblk_t		*next_mp;
11302 	uint32_t	u1;
11303 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11304 
11305 	/* Walk through all the new pieces. */
11306 	do {
11307 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11308 		    (uintptr_t)INT_MAX);
11309 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11310 		next_mp = mp->b_cont;
11311 		if (start == end) {
11312 			/* Empty.  Blast it. */
11313 			freeb(mp);
11314 			continue;
11315 		}
11316 		mp->b_cont = NULL;
11317 		TCP_REASS_SET_SEQ(mp, start);
11318 		TCP_REASS_SET_END(mp, end);
11319 		mp1 = tcp->tcp_reass_tail;
11320 		if (!mp1) {
11321 			tcp->tcp_reass_tail = mp;
11322 			tcp->tcp_reass_head = mp;
11323 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11324 			UPDATE_MIB(&tcps->tcps_mib,
11325 			    tcpInDataUnorderBytes, end - start);
11326 			continue;
11327 		}
11328 		/* New stuff completely beyond tail? */
11329 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11330 			/* Link it on end. */
11331 			mp1->b_cont = mp;
11332 			tcp->tcp_reass_tail = mp;
11333 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11334 			UPDATE_MIB(&tcps->tcps_mib,
11335 			    tcpInDataUnorderBytes, end - start);
11336 			continue;
11337 		}
11338 		mp1 = tcp->tcp_reass_head;
11339 		u1 = TCP_REASS_SEQ(mp1);
11340 		/* New stuff at the front? */
11341 		if (SEQ_LT(start, u1)) {
11342 			/* Yes... Check for overlap. */
11343 			mp->b_cont = mp1;
11344 			tcp->tcp_reass_head = mp;
11345 			tcp_reass_elim_overlap(tcp, mp);
11346 			continue;
11347 		}
11348 		/*
11349 		 * The new piece fits somewhere between the head and tail.
11350 		 * We find our slot, where mp1 precedes us and mp2 trails.
11351 		 */
11352 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11353 			u1 = TCP_REASS_SEQ(mp2);
11354 			if (SEQ_LEQ(start, u1))
11355 				break;
11356 		}
11357 		/* Link ourselves in */
11358 		mp->b_cont = mp2;
11359 		mp1->b_cont = mp;
11360 
11361 		/* Trim overlap with following mblk(s) first */
11362 		tcp_reass_elim_overlap(tcp, mp);
11363 
11364 		/* Trim overlap with preceding mblk */
11365 		tcp_reass_elim_overlap(tcp, mp1);
11366 
11367 	} while (start = end, mp = next_mp);
11368 	mp1 = tcp->tcp_reass_head;
11369 	/* Anything ready to go? */
11370 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11371 		return (NULL);
11372 	/* Eat what we can off the queue */
11373 	for (;;) {
11374 		mp = mp1->b_cont;
11375 		end = TCP_REASS_END(mp1);
11376 		TCP_REASS_SET_SEQ(mp1, 0);
11377 		TCP_REASS_SET_END(mp1, 0);
11378 		if (!mp) {
11379 			tcp->tcp_reass_tail = NULL;
11380 			break;
11381 		}
11382 		if (end != TCP_REASS_SEQ(mp)) {
11383 			mp1->b_cont = NULL;
11384 			break;
11385 		}
11386 		mp1 = mp;
11387 	}
11388 	mp1 = tcp->tcp_reass_head;
11389 	tcp->tcp_reass_head = mp;
11390 	return (mp1);
11391 }
11392 
11393 /* Eliminate any overlap that mp may have over later mblks */
11394 static void
11395 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11396 {
11397 	uint32_t	end;
11398 	mblk_t		*mp1;
11399 	uint32_t	u1;
11400 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11401 
11402 	end = TCP_REASS_END(mp);
11403 	while ((mp1 = mp->b_cont) != NULL) {
11404 		u1 = TCP_REASS_SEQ(mp1);
11405 		if (!SEQ_GT(end, u1))
11406 			break;
11407 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11408 			mp->b_wptr -= end - u1;
11409 			TCP_REASS_SET_END(mp, u1);
11410 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11411 			UPDATE_MIB(&tcps->tcps_mib,
11412 			    tcpInDataPartDupBytes, end - u1);
11413 			break;
11414 		}
11415 		mp->b_cont = mp1->b_cont;
11416 		TCP_REASS_SET_SEQ(mp1, 0);
11417 		TCP_REASS_SET_END(mp1, 0);
11418 		freeb(mp1);
11419 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11420 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11421 	}
11422 	if (!mp1)
11423 		tcp->tcp_reass_tail = mp;
11424 }
11425 
11426 static uint_t
11427 tcp_rwnd_reopen(tcp_t *tcp)
11428 {
11429 	uint_t ret = 0;
11430 	uint_t thwin;
11431 
11432 	/* Learn the latest rwnd information that we sent to the other side. */
11433 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11434 	    << tcp->tcp_rcv_ws;
11435 	/* This is peer's calculated send window (our receive window). */
11436 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11437 	/*
11438 	 * Increase the receive window to max.  But we need to do receiver
11439 	 * SWS avoidance.  This means that we need to check the increase of
11440 	 * of receive window is at least 1 MSS.
11441 	 */
11442 	if (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss) {
11443 		/*
11444 		 * If the window that the other side knows is less than max
11445 		 * deferred acks segments, send an update immediately.
11446 		 */
11447 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11448 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
11449 			ret = TH_ACK_NEEDED;
11450 		}
11451 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
11452 	}
11453 	return (ret);
11454 }
11455 
11456 /*
11457  * Send up all messages queued on tcp_rcv_list.
11458  */
11459 static uint_t
11460 tcp_rcv_drain(tcp_t *tcp)
11461 {
11462 	mblk_t *mp;
11463 	uint_t ret = 0;
11464 #ifdef DEBUG
11465 	uint_t cnt = 0;
11466 #endif
11467 	queue_t	*q = tcp->tcp_rq;
11468 
11469 	/* Can't drain on an eager connection */
11470 	if (tcp->tcp_listener != NULL)
11471 		return (ret);
11472 
11473 	/* Can't be a non-STREAMS connection or sodirect enabled */
11474 	ASSERT((!IPCL_IS_NONSTR(tcp->tcp_connp)) && SOD_NOT_ENABLED(tcp));
11475 
11476 	/* No need for the push timer now. */
11477 	if (tcp->tcp_push_tid != 0) {
11478 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11479 		tcp->tcp_push_tid = 0;
11480 	}
11481 
11482 	/*
11483 	 * Handle two cases here: we are currently fused or we were
11484 	 * previously fused and have some urgent data to be delivered
11485 	 * upstream.  The latter happens because we either ran out of
11486 	 * memory or were detached and therefore sending the SIGURG was
11487 	 * deferred until this point.  In either case we pass control
11488 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11489 	 * some work.
11490 	 */
11491 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11492 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
11493 		    tcp->tcp_fused_sigurg_mp != NULL);
11494 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11495 		    &tcp->tcp_fused_sigurg_mp))
11496 			return (ret);
11497 	}
11498 
11499 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11500 		tcp->tcp_rcv_list = mp->b_next;
11501 		mp->b_next = NULL;
11502 #ifdef DEBUG
11503 		cnt += msgdsize(mp);
11504 #endif
11505 		/* Does this need SSL processing first? */
11506 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11507 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11508 			    mblk_t *, mp);
11509 			tcp_kssl_input(tcp, mp);
11510 			continue;
11511 		}
11512 		putnext(q, mp);
11513 	}
11514 #ifdef DEBUG
11515 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11516 #endif
11517 	tcp->tcp_rcv_last_head = NULL;
11518 	tcp->tcp_rcv_last_tail = NULL;
11519 	tcp->tcp_rcv_cnt = 0;
11520 
11521 	if (canputnext(q))
11522 		return (tcp_rwnd_reopen(tcp));
11523 
11524 	return (ret);
11525 }
11526 
11527 /*
11528  * Queue data on tcp_rcv_list which is a b_next chain.
11529  * tcp_rcv_last_head/tail is the last element of this chain.
11530  * Each element of the chain is a b_cont chain.
11531  *
11532  * M_DATA messages are added to the current element.
11533  * Other messages are added as new (b_next) elements.
11534  */
11535 void
11536 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11537 {
11538 	ASSERT(seg_len == msgdsize(mp));
11539 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11540 
11541 	if (tcp->tcp_rcv_list == NULL) {
11542 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11543 		tcp->tcp_rcv_list = mp;
11544 		tcp->tcp_rcv_last_head = mp;
11545 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11546 		tcp->tcp_rcv_last_tail->b_cont = mp;
11547 	} else {
11548 		tcp->tcp_rcv_last_head->b_next = mp;
11549 		tcp->tcp_rcv_last_head = mp;
11550 	}
11551 
11552 	while (mp->b_cont)
11553 		mp = mp->b_cont;
11554 
11555 	tcp->tcp_rcv_last_tail = mp;
11556 	tcp->tcp_rcv_cnt += seg_len;
11557 	tcp->tcp_rwnd -= seg_len;
11558 }
11559 
11560 /*
11561  * The tcp_rcv_sod_XXX() functions enqueue data directly to the socket
11562  * above, in addition when uioa is enabled schedule an asynchronous uio
11563  * prior to enqueuing. They implement the combinhed semantics of the
11564  * tcp_rcv_XXX() functions, tcp_rcv_list push logic, and STREAMS putnext()
11565  * canputnext(), i.e. flow-control with backenable.
11566  *
11567  * tcp_sod_wakeup() is called where tcp_rcv_drain() would be called in the
11568  * non sodirect connection but as there are no tcp_tcv_list mblk_t's we deal
11569  * with the rcv_wnd and push timer and call the sodirect wakeup function.
11570  *
11571  * Must be called with sodp->sod_lockp held and will return with the lock
11572  * released.
11573  */
11574 static uint_t
11575 tcp_rcv_sod_wakeup(tcp_t *tcp, sodirect_t *sodp)
11576 {
11577 	queue_t		*q = tcp->tcp_rq;
11578 	uint_t		thwin;
11579 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11580 	uint_t		ret = 0;
11581 
11582 	/* Can't be an eager connection */
11583 	ASSERT(tcp->tcp_listener == NULL);
11584 
11585 	/* Caller must have lock held */
11586 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11587 
11588 	/* Sodirect mode so must not be a tcp_rcv_list */
11589 	ASSERT(tcp->tcp_rcv_list == NULL);
11590 
11591 	if (SOD_QFULL(sodp)) {
11592 		/* Q is full, mark Q for need backenable */
11593 		SOD_QSETBE(sodp);
11594 	}
11595 	/* Last advertised rwnd, i.e. rwnd last sent in a packet */
11596 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11597 	    << tcp->tcp_rcv_ws;
11598 	/* This is peer's calculated send window (our available rwnd). */
11599 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11600 	/*
11601 	 * Increase the receive window to max.  But we need to do receiver
11602 	 * SWS avoidance.  This means that we need to check the increase of
11603 	 * of receive window is at least 1 MSS.
11604 	 */
11605 	if (!SOD_QFULL(sodp) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11606 		/*
11607 		 * If the window that the other side knows is less than max
11608 		 * deferred acks segments, send an update immediately.
11609 		 */
11610 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11611 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11612 			ret = TH_ACK_NEEDED;
11613 		}
11614 		tcp->tcp_rwnd = q->q_hiwat;
11615 	}
11616 
11617 	if (!SOD_QEMPTY(sodp)) {
11618 		/* Wakeup to socket */
11619 		sodp->sod_state &= SOD_WAKE_CLR;
11620 		sodp->sod_state |= SOD_WAKE_DONE;
11621 		(sodp->sod_wakeup)(sodp);
11622 		/* wakeup() does the mutex_ext() */
11623 	} else {
11624 		/* Q is empty, no need to wake */
11625 		sodp->sod_state &= SOD_WAKE_CLR;
11626 		sodp->sod_state |= SOD_WAKE_NOT;
11627 		mutex_exit(sodp->sod_lockp);
11628 	}
11629 
11630 	/* No need for the push timer now. */
11631 	if (tcp->tcp_push_tid != 0) {
11632 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11633 		tcp->tcp_push_tid = 0;
11634 	}
11635 
11636 	return (ret);
11637 }
11638 
11639 /*
11640  * Called where tcp_rcv_enqueue()/putnext(RD(q)) would be. For M_DATA
11641  * mblk_t's if uioa enabled then start a uioa asynchronous copy directly
11642  * to the user-land buffer and flag the mblk_t as such.
11643  *
11644  * Also, handle tcp_rwnd.
11645  */
11646 uint_t
11647 tcp_rcv_sod_enqueue(tcp_t *tcp, sodirect_t *sodp, mblk_t *mp, uint_t seg_len)
11648 {
11649 	uioa_t		*uioap = &sodp->sod_uioa;
11650 	boolean_t	qfull;
11651 	uint_t		thwin;
11652 
11653 	/* Can't be an eager connection */
11654 	ASSERT(tcp->tcp_listener == NULL);
11655 
11656 	/* Caller must have lock held */
11657 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11658 
11659 	/* Sodirect mode so must not be a tcp_rcv_list */
11660 	ASSERT(tcp->tcp_rcv_list == NULL);
11661 
11662 	/* Passed in segment length must be equal to mblk_t chain data size */
11663 	ASSERT(seg_len == msgdsize(mp));
11664 
11665 	if (DB_TYPE(mp) != M_DATA) {
11666 		/* Only process M_DATA mblk_t's */
11667 		goto enq;
11668 	}
11669 	if (uioap->uioa_state & UIOA_ENABLED) {
11670 		/* Uioa is enabled */
11671 		mblk_t		*mp1 = mp;
11672 		mblk_t		*lmp = NULL;
11673 
11674 		if (seg_len > uioap->uio_resid) {
11675 			/*
11676 			 * There isn't enough uio space for the mblk_t chain
11677 			 * so disable uioa such that this and any additional
11678 			 * mblk_t data is handled by the socket and schedule
11679 			 * the socket for wakeup to finish this uioa.
11680 			 */
11681 			uioap->uioa_state &= UIOA_CLR;
11682 			uioap->uioa_state |= UIOA_FINI;
11683 			if (sodp->sod_state & SOD_WAKE_NOT) {
11684 				sodp->sod_state &= SOD_WAKE_CLR;
11685 				sodp->sod_state |= SOD_WAKE_NEED;
11686 			}
11687 			goto enq;
11688 		}
11689 		do {
11690 			uint32_t	len = MBLKL(mp1);
11691 
11692 			if (!uioamove(mp1->b_rptr, len, UIO_READ, uioap)) {
11693 				/* Scheduled, mark dblk_t as such */
11694 				DB_FLAGS(mp1) |= DBLK_UIOA;
11695 			} else {
11696 				/* Error, turn off async processing */
11697 				uioap->uioa_state &= UIOA_CLR;
11698 				uioap->uioa_state |= UIOA_FINI;
11699 				break;
11700 			}
11701 			lmp = mp1;
11702 		} while ((mp1 = mp1->b_cont) != NULL);
11703 
11704 		if (mp1 != NULL || uioap->uio_resid == 0) {
11705 			/*
11706 			 * Not all mblk_t(s) uioamoved (error) or all uio
11707 			 * space has been consumed so schedule the socket
11708 			 * for wakeup to finish this uio.
11709 			 */
11710 			sodp->sod_state &= SOD_WAKE_CLR;
11711 			sodp->sod_state |= SOD_WAKE_NEED;
11712 
11713 			/* Break the mblk chain if neccessary. */
11714 			if (mp1 != NULL && lmp != NULL) {
11715 				mp->b_next = mp1;
11716 				lmp->b_cont = NULL;
11717 			}
11718 		}
11719 	} else if (uioap->uioa_state & UIOA_FINI) {
11720 		/*
11721 		 * Post UIO_ENABLED waiting for socket to finish processing
11722 		 * so just enqueue and update tcp_rwnd.
11723 		 */
11724 		if (SOD_QFULL(sodp))
11725 			tcp->tcp_rwnd -= seg_len;
11726 	} else if (sodp->sod_want > 0) {
11727 		/*
11728 		 * Uioa isn't enabled but sodirect has a pending read().
11729 		 */
11730 		if (SOD_QCNT(sodp) + seg_len >= sodp->sod_want) {
11731 			if (sodp->sod_state & SOD_WAKE_NOT) {
11732 				/* Schedule socket for wakeup */
11733 				sodp->sod_state &= SOD_WAKE_CLR;
11734 				sodp->sod_state |= SOD_WAKE_NEED;
11735 			}
11736 			tcp->tcp_rwnd -= seg_len;
11737 		}
11738 	} else if (SOD_QCNT(sodp) + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
11739 		/*
11740 		 * No pending sodirect read() so used the default
11741 		 * TCP push logic to guess that a push is needed.
11742 		 */
11743 		if (sodp->sod_state & SOD_WAKE_NOT) {
11744 			/* Schedule socket for wakeup */
11745 			sodp->sod_state &= SOD_WAKE_CLR;
11746 			sodp->sod_state |= SOD_WAKE_NEED;
11747 		}
11748 		tcp->tcp_rwnd -= seg_len;
11749 	} else {
11750 		/* Just update tcp_rwnd */
11751 		tcp->tcp_rwnd -= seg_len;
11752 	}
11753 enq:
11754 	qfull = SOD_QFULL(sodp);
11755 
11756 	(sodp->sod_enqueue)(sodp, mp);
11757 
11758 	if (! qfull && SOD_QFULL(sodp)) {
11759 		/* Wasn't QFULL, now QFULL, need back-enable */
11760 		SOD_QSETBE(sodp);
11761 	}
11762 
11763 	/*
11764 	 * Check to see if remote avail swnd < mss due to delayed ACK,
11765 	 * first get advertised rwnd.
11766 	 */
11767 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win));
11768 	/* Minus delayed ACK count */
11769 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11770 	if (thwin < tcp->tcp_mss) {
11771 		/* Remote avail swnd < mss, need ACK now */
11772 		return (TH_ACK_NEEDED);
11773 	}
11774 
11775 	return (0);
11776 }
11777 
11778 /*
11779  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11780  *
11781  * This is the default entry function into TCP on the read side. TCP is
11782  * always entered via squeue i.e. using squeue's for mutual exclusion.
11783  * When classifier does a lookup to find the tcp, it also puts a reference
11784  * on the conn structure associated so the tcp is guaranteed to exist
11785  * when we come here. We still need to check the state because it might
11786  * as well has been closed. The squeue processing function i.e. squeue_enter,
11787  * is responsible for doing the CONN_DEC_REF.
11788  *
11789  * Apart from the default entry point, IP also sends packets directly to
11790  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11791  * connections.
11792  */
11793 boolean_t tcp_outbound_squeue_switch = B_FALSE;
11794 void
11795 tcp_input(void *arg, mblk_t *mp, void *arg2)
11796 {
11797 	conn_t	*connp = (conn_t *)arg;
11798 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11799 
11800 	/* arg2 is the sqp */
11801 	ASSERT(arg2 != NULL);
11802 	ASSERT(mp != NULL);
11803 
11804 	/*
11805 	 * Don't accept any input on a closed tcp as this TCP logically does
11806 	 * not exist on the system. Don't proceed further with this TCP.
11807 	 * For eg. this packet could trigger another close of this tcp
11808 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11809 	 * tcp_clean_death / tcp_closei_local must be called at most once
11810 	 * on a TCP. In this case we need to refeed the packet into the
11811 	 * classifier and figure out where the packet should go. Need to
11812 	 * preserve the recv_ill somehow. Until we figure that out, for
11813 	 * now just drop the packet if we can't classify the packet.
11814 	 */
11815 	if (tcp->tcp_state == TCPS_CLOSED ||
11816 	    tcp->tcp_state == TCPS_BOUND) {
11817 		conn_t	*new_connp;
11818 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11819 
11820 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11821 		if (new_connp != NULL) {
11822 			tcp_reinput(new_connp, mp, arg2);
11823 			return;
11824 		}
11825 		/* We failed to classify. For now just drop the packet */
11826 		freemsg(mp);
11827 		return;
11828 	}
11829 
11830 	if (DB_TYPE(mp) != M_DATA) {
11831 		tcp_rput_common(tcp, mp);
11832 		return;
11833 	}
11834 
11835 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
11836 		squeue_t	*final_sqp;
11837 
11838 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
11839 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
11840 		DB_CKSUMSTART(mp) = 0;
11841 		if (tcp->tcp_state == TCPS_SYN_SENT &&
11842 		    connp->conn_final_sqp == NULL &&
11843 		    tcp_outbound_squeue_switch) {
11844 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
11845 			connp->conn_final_sqp = final_sqp;
11846 			if (connp->conn_final_sqp != connp->conn_sqp) {
11847 				CONN_INC_REF(connp);
11848 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
11849 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
11850 				    tcp_rput_data, connp, ip_squeue_flag,
11851 				    SQTAG_CONNECT_FINISH);
11852 				return;
11853 			}
11854 		}
11855 	}
11856 	tcp_rput_data(connp, mp, arg2);
11857 }
11858 
11859 /*
11860  * The read side put procedure.
11861  * The packets passed up by ip are assume to be aligned according to
11862  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11863  */
11864 static void
11865 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11866 {
11867 	/*
11868 	 * tcp_rput_data() does not expect M_CTL except for the case
11869 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11870 	 * type. Need to make sure that any other M_CTLs don't make
11871 	 * it to tcp_rput_data since it is not expecting any and doesn't
11872 	 * check for it.
11873 	 */
11874 	if (DB_TYPE(mp) == M_CTL) {
11875 		switch (*(uint32_t *)(mp->b_rptr)) {
11876 		case TCP_IOC_ABORT_CONN:
11877 			/*
11878 			 * Handle connection abort request.
11879 			 */
11880 			tcp_ioctl_abort_handler(tcp, mp);
11881 			return;
11882 		case IPSEC_IN:
11883 			/*
11884 			 * Only secure icmp arrive in TCP and they
11885 			 * don't go through data path.
11886 			 */
11887 			tcp_icmp_error(tcp, mp);
11888 			return;
11889 		case IN_PKTINFO:
11890 			/*
11891 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11892 			 * sockets that are receiving IPv4 traffic. tcp
11893 			 */
11894 			ASSERT(tcp->tcp_family == AF_INET6);
11895 			ASSERT(tcp->tcp_ipv6_recvancillary &
11896 			    TCP_IPV6_RECVPKTINFO);
11897 			tcp_rput_data(tcp->tcp_connp, mp,
11898 			    tcp->tcp_connp->conn_sqp);
11899 			return;
11900 		case MDT_IOC_INFO_UPDATE:
11901 			/*
11902 			 * Handle Multidata information update; the
11903 			 * following routine will free the message.
11904 			 */
11905 			if (tcp->tcp_connp->conn_mdt_ok) {
11906 				tcp_mdt_update(tcp,
11907 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11908 				    B_FALSE);
11909 			}
11910 			freemsg(mp);
11911 			return;
11912 		case LSO_IOC_INFO_UPDATE:
11913 			/*
11914 			 * Handle LSO information update; the following
11915 			 * routine will free the message.
11916 			 */
11917 			if (tcp->tcp_connp->conn_lso_ok) {
11918 				tcp_lso_update(tcp,
11919 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11920 			}
11921 			freemsg(mp);
11922 			return;
11923 		default:
11924 			/*
11925 			 * tcp_icmp_err() will process the M_CTL packets.
11926 			 * Non-ICMP packets, if any, will be discarded in
11927 			 * tcp_icmp_err(). We will process the ICMP packet
11928 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11929 			 * incoming ICMP packet may result in changing
11930 			 * the tcp_mss, which we would need if we have
11931 			 * packets to retransmit.
11932 			 */
11933 			tcp_icmp_error(tcp, mp);
11934 			return;
11935 		}
11936 	}
11937 
11938 	/* No point processing the message if tcp is already closed */
11939 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11940 		freemsg(mp);
11941 		return;
11942 	}
11943 
11944 	tcp_rput_other(tcp, mp);
11945 }
11946 
11947 
11948 /* The minimum of smoothed mean deviation in RTO calculation. */
11949 #define	TCP_SD_MIN	400
11950 
11951 /*
11952  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11953  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11954  * are the same as those in Appendix A.2 of that paper.
11955  *
11956  * m = new measurement
11957  * sa = smoothed RTT average (8 * average estimates).
11958  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11959  */
11960 static void
11961 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11962 {
11963 	long m = TICK_TO_MSEC(rtt);
11964 	clock_t sa = tcp->tcp_rtt_sa;
11965 	clock_t sv = tcp->tcp_rtt_sd;
11966 	clock_t rto;
11967 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11968 
11969 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11970 	tcp->tcp_rtt_update++;
11971 
11972 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11973 	if (sa != 0) {
11974 		/*
11975 		 * Update average estimator:
11976 		 *	new rtt = 7/8 old rtt + 1/8 Error
11977 		 */
11978 
11979 		/* m is now Error in estimate. */
11980 		m -= sa >> 3;
11981 		if ((sa += m) <= 0) {
11982 			/*
11983 			 * Don't allow the smoothed average to be negative.
11984 			 * We use 0 to denote reinitialization of the
11985 			 * variables.
11986 			 */
11987 			sa = 1;
11988 		}
11989 
11990 		/*
11991 		 * Update deviation estimator:
11992 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11993 		 */
11994 		if (m < 0)
11995 			m = -m;
11996 		m -= sv >> 2;
11997 		sv += m;
11998 	} else {
11999 		/*
12000 		 * This follows BSD's implementation.  So the reinitialized
12001 		 * RTO is 3 * m.  We cannot go less than 2 because if the
12002 		 * link is bandwidth dominated, doubling the window size
12003 		 * during slow start means doubling the RTT.  We want to be
12004 		 * more conservative when we reinitialize our estimates.  3
12005 		 * is just a convenient number.
12006 		 */
12007 		sa = m << 3;
12008 		sv = m << 1;
12009 	}
12010 	if (sv < TCP_SD_MIN) {
12011 		/*
12012 		 * We do not know that if sa captures the delay ACK
12013 		 * effect as in a long train of segments, a receiver
12014 		 * does not delay its ACKs.  So set the minimum of sv
12015 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
12016 		 * of BSD DATO.  That means the minimum of mean
12017 		 * deviation is 100 ms.
12018 		 *
12019 		 */
12020 		sv = TCP_SD_MIN;
12021 	}
12022 	tcp->tcp_rtt_sa = sa;
12023 	tcp->tcp_rtt_sd = sv;
12024 	/*
12025 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
12026 	 *
12027 	 * Add tcp_rexmit_interval extra in case of extreme environment
12028 	 * where the algorithm fails to work.  The default value of
12029 	 * tcp_rexmit_interval_extra should be 0.
12030 	 *
12031 	 * As we use a finer grained clock than BSD and update
12032 	 * RTO for every ACKs, add in another .25 of RTT to the
12033 	 * deviation of RTO to accomodate burstiness of 1/4 of
12034 	 * window size.
12035 	 */
12036 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
12037 
12038 	if (rto > tcps->tcps_rexmit_interval_max) {
12039 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
12040 	} else if (rto < tcps->tcps_rexmit_interval_min) {
12041 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
12042 	} else {
12043 		tcp->tcp_rto = rto;
12044 	}
12045 
12046 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12047 	tcp->tcp_timer_backoff = 0;
12048 }
12049 
12050 /*
12051  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12052  * send queue which starts at the given seq. no.
12053  *
12054  * Parameters:
12055  *	tcp_t *tcp: the tcp instance pointer.
12056  *	uint32_t seq: the starting seq. no of the requested segment.
12057  *	int32_t *off: after the execution, *off will be the offset to
12058  *		the returned mblk which points to the requested seq no.
12059  *		It is the caller's responsibility to send in a non-null off.
12060  *
12061  * Return:
12062  *	A mblk_t pointer pointing to the requested segment in send queue.
12063  */
12064 static mblk_t *
12065 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12066 {
12067 	int32_t	cnt;
12068 	mblk_t	*mp;
12069 
12070 	/* Defensive coding.  Make sure we don't send incorrect data. */
12071 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12072 		return (NULL);
12073 
12074 	cnt = seq - tcp->tcp_suna;
12075 	mp = tcp->tcp_xmit_head;
12076 	while (cnt > 0 && mp != NULL) {
12077 		cnt -= mp->b_wptr - mp->b_rptr;
12078 		if (cnt < 0) {
12079 			cnt += mp->b_wptr - mp->b_rptr;
12080 			break;
12081 		}
12082 		mp = mp->b_cont;
12083 	}
12084 	ASSERT(mp != NULL);
12085 	*off = cnt;
12086 	return (mp);
12087 }
12088 
12089 /*
12090  * This function handles all retransmissions if SACK is enabled for this
12091  * connection.  First it calculates how many segments can be retransmitted
12092  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12093  * segments.  A segment is eligible if sack_cnt for that segment is greater
12094  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12095  * all eligible segments, it checks to see if TCP can send some new segments
12096  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12097  *
12098  * Parameters:
12099  *	tcp_t *tcp: the tcp structure of the connection.
12100  *	uint_t *flags: in return, appropriate value will be set for
12101  *	tcp_rput_data().
12102  */
12103 static void
12104 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12105 {
12106 	notsack_blk_t	*notsack_blk;
12107 	int32_t		usable_swnd;
12108 	int32_t		mss;
12109 	uint32_t	seg_len;
12110 	mblk_t		*xmit_mp;
12111 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12112 
12113 	ASSERT(tcp->tcp_sack_info != NULL);
12114 	ASSERT(tcp->tcp_notsack_list != NULL);
12115 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12116 
12117 	/* Defensive coding in case there is a bug... */
12118 	if (tcp->tcp_notsack_list == NULL) {
12119 		return;
12120 	}
12121 	notsack_blk = tcp->tcp_notsack_list;
12122 	mss = tcp->tcp_mss;
12123 
12124 	/*
12125 	 * Limit the num of outstanding data in the network to be
12126 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12127 	 */
12128 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12129 
12130 	/* At least retransmit 1 MSS of data. */
12131 	if (usable_swnd <= 0) {
12132 		usable_swnd = mss;
12133 	}
12134 
12135 	/* Make sure no new RTT samples will be taken. */
12136 	tcp->tcp_csuna = tcp->tcp_snxt;
12137 
12138 	notsack_blk = tcp->tcp_notsack_list;
12139 	while (usable_swnd > 0) {
12140 		mblk_t		*snxt_mp, *tmp_mp;
12141 		tcp_seq		begin = tcp->tcp_sack_snxt;
12142 		tcp_seq		end;
12143 		int32_t		off;
12144 
12145 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12146 			if (SEQ_GT(notsack_blk->end, begin) &&
12147 			    (notsack_blk->sack_cnt >=
12148 			    tcps->tcps_dupack_fast_retransmit)) {
12149 				end = notsack_blk->end;
12150 				if (SEQ_LT(begin, notsack_blk->begin)) {
12151 					begin = notsack_blk->begin;
12152 				}
12153 				break;
12154 			}
12155 		}
12156 		/*
12157 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12158 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12159 		 * set to tcp_cwnd_ssthresh.
12160 		 */
12161 		if (notsack_blk == NULL) {
12162 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12163 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12164 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12165 				ASSERT(tcp->tcp_cwnd > 0);
12166 				return;
12167 			} else {
12168 				usable_swnd = usable_swnd / mss;
12169 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12170 				    MAX(usable_swnd * mss, mss);
12171 				*flags |= TH_XMIT_NEEDED;
12172 				return;
12173 			}
12174 		}
12175 
12176 		/*
12177 		 * Note that we may send more than usable_swnd allows here
12178 		 * because of round off, but no more than 1 MSS of data.
12179 		 */
12180 		seg_len = end - begin;
12181 		if (seg_len > mss)
12182 			seg_len = mss;
12183 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12184 		ASSERT(snxt_mp != NULL);
12185 		/* This should not happen.  Defensive coding again... */
12186 		if (snxt_mp == NULL) {
12187 			return;
12188 		}
12189 
12190 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12191 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12192 		if (xmit_mp == NULL)
12193 			return;
12194 
12195 		usable_swnd -= seg_len;
12196 		tcp->tcp_pipe += seg_len;
12197 		tcp->tcp_sack_snxt = begin + seg_len;
12198 
12199 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12200 
12201 		/*
12202 		 * Update the send timestamp to avoid false retransmission.
12203 		 */
12204 		snxt_mp->b_prev = (mblk_t *)lbolt;
12205 
12206 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12207 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12208 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12209 		/*
12210 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12211 		 * This happens when new data sent during fast recovery is
12212 		 * also lost.  If TCP retransmits those new data, it needs
12213 		 * to extend SACK recover phase to avoid starting another
12214 		 * fast retransmit/recovery unnecessarily.
12215 		 */
12216 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12217 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12218 		}
12219 	}
12220 }
12221 
12222 /*
12223  * This function handles policy checking at TCP level for non-hard_bound/
12224  * detached connections.
12225  */
12226 static boolean_t
12227 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12228     boolean_t secure, boolean_t mctl_present)
12229 {
12230 	ipsec_latch_t *ipl = NULL;
12231 	ipsec_action_t *act = NULL;
12232 	mblk_t *data_mp;
12233 	ipsec_in_t *ii;
12234 	const char *reason;
12235 	kstat_named_t *counter;
12236 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12237 	ipsec_stack_t	*ipss;
12238 	ip_stack_t	*ipst;
12239 
12240 	ASSERT(mctl_present || !secure);
12241 
12242 	ASSERT((ipha == NULL && ip6h != NULL) ||
12243 	    (ip6h == NULL && ipha != NULL));
12244 
12245 	/*
12246 	 * We don't necessarily have an ipsec_in_act action to verify
12247 	 * policy because of assymetrical policy where we have only
12248 	 * outbound policy and no inbound policy (possible with global
12249 	 * policy).
12250 	 */
12251 	if (!secure) {
12252 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12253 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12254 			return (B_TRUE);
12255 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12256 		    "tcp_check_policy", ipha, ip6h, secure,
12257 		    tcps->tcps_netstack);
12258 		ipss = tcps->tcps_netstack->netstack_ipsec;
12259 
12260 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12261 		    DROPPER(ipss, ipds_tcp_clear),
12262 		    &tcps->tcps_dropper);
12263 		return (B_FALSE);
12264 	}
12265 
12266 	/*
12267 	 * We have a secure packet.
12268 	 */
12269 	if (act == NULL) {
12270 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12271 		    "tcp_check_policy", ipha, ip6h, secure,
12272 		    tcps->tcps_netstack);
12273 		ipss = tcps->tcps_netstack->netstack_ipsec;
12274 
12275 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12276 		    DROPPER(ipss, ipds_tcp_secure),
12277 		    &tcps->tcps_dropper);
12278 		return (B_FALSE);
12279 	}
12280 
12281 	/*
12282 	 * XXX This whole routine is currently incorrect.  ipl should
12283 	 * be set to the latch pointer, but is currently not set, so
12284 	 * we initialize it to NULL to avoid picking up random garbage.
12285 	 */
12286 	if (ipl == NULL)
12287 		return (B_TRUE);
12288 
12289 	data_mp = first_mp->b_cont;
12290 
12291 	ii = (ipsec_in_t *)first_mp->b_rptr;
12292 
12293 	ipst = tcps->tcps_netstack->netstack_ip;
12294 
12295 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12296 	    &counter, tcp->tcp_connp)) {
12297 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12298 		return (B_TRUE);
12299 	}
12300 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12301 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12302 	    reason);
12303 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12304 
12305 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12306 	    &tcps->tcps_dropper);
12307 	return (B_FALSE);
12308 }
12309 
12310 /*
12311  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12312  * retransmission after a timeout.
12313  *
12314  * To limit the number of duplicate segments, we limit the number of segment
12315  * to be sent in one time to tcp_snd_burst, the burst variable.
12316  */
12317 static void
12318 tcp_ss_rexmit(tcp_t *tcp)
12319 {
12320 	uint32_t	snxt;
12321 	uint32_t	smax;
12322 	int32_t		win;
12323 	int32_t		mss;
12324 	int32_t		off;
12325 	int32_t		burst = tcp->tcp_snd_burst;
12326 	mblk_t		*snxt_mp;
12327 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12328 
12329 	/*
12330 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12331 	 * all unack'ed segments.
12332 	 */
12333 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12334 		smax = tcp->tcp_rexmit_max;
12335 		snxt = tcp->tcp_rexmit_nxt;
12336 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12337 			snxt = tcp->tcp_suna;
12338 		}
12339 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12340 		win -= snxt - tcp->tcp_suna;
12341 		mss = tcp->tcp_mss;
12342 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12343 
12344 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12345 		    (burst > 0) && (snxt_mp != NULL)) {
12346 			mblk_t	*xmit_mp;
12347 			mblk_t	*old_snxt_mp = snxt_mp;
12348 			uint32_t cnt = mss;
12349 
12350 			if (win < cnt) {
12351 				cnt = win;
12352 			}
12353 			if (SEQ_GT(snxt + cnt, smax)) {
12354 				cnt = smax - snxt;
12355 			}
12356 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12357 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12358 			if (xmit_mp == NULL)
12359 				return;
12360 
12361 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12362 
12363 			snxt += cnt;
12364 			win -= cnt;
12365 			/*
12366 			 * Update the send timestamp to avoid false
12367 			 * retransmission.
12368 			 */
12369 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12370 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12371 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12372 
12373 			tcp->tcp_rexmit_nxt = snxt;
12374 			burst--;
12375 		}
12376 		/*
12377 		 * If we have transmitted all we have at the time
12378 		 * we started the retranmission, we can leave
12379 		 * the rest of the job to tcp_wput_data().  But we
12380 		 * need to check the send window first.  If the
12381 		 * win is not 0, go on with tcp_wput_data().
12382 		 */
12383 		if (SEQ_LT(snxt, smax) || win == 0) {
12384 			return;
12385 		}
12386 	}
12387 	/* Only call tcp_wput_data() if there is data to be sent. */
12388 	if (tcp->tcp_unsent) {
12389 		tcp_wput_data(tcp, NULL, B_FALSE);
12390 	}
12391 }
12392 
12393 /*
12394  * Process all TCP option in SYN segment.  Note that this function should
12395  * be called after tcp_adapt_ire() is called so that the necessary info
12396  * from IRE is already set in the tcp structure.
12397  *
12398  * This function sets up the correct tcp_mss value according to the
12399  * MSS option value and our header size.  It also sets up the window scale
12400  * and timestamp values, and initialize SACK info blocks.  But it does not
12401  * change receive window size after setting the tcp_mss value.  The caller
12402  * should do the appropriate change.
12403  */
12404 void
12405 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12406 {
12407 	int options;
12408 	tcp_opt_t tcpopt;
12409 	uint32_t mss_max;
12410 	char *tmp_tcph;
12411 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12412 
12413 	tcpopt.tcp = NULL;
12414 	options = tcp_parse_options(tcph, &tcpopt);
12415 
12416 	/*
12417 	 * Process MSS option.  Note that MSS option value does not account
12418 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12419 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12420 	 * IPv6.
12421 	 */
12422 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12423 		if (tcp->tcp_ipversion == IPV4_VERSION)
12424 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12425 		else
12426 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12427 	} else {
12428 		if (tcp->tcp_ipversion == IPV4_VERSION)
12429 			mss_max = tcps->tcps_mss_max_ipv4;
12430 		else
12431 			mss_max = tcps->tcps_mss_max_ipv6;
12432 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12433 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12434 		else if (tcpopt.tcp_opt_mss > mss_max)
12435 			tcpopt.tcp_opt_mss = mss_max;
12436 	}
12437 
12438 	/* Process Window Scale option. */
12439 	if (options & TCP_OPT_WSCALE_PRESENT) {
12440 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12441 		tcp->tcp_snd_ws_ok = B_TRUE;
12442 	} else {
12443 		tcp->tcp_snd_ws = B_FALSE;
12444 		tcp->tcp_snd_ws_ok = B_FALSE;
12445 		tcp->tcp_rcv_ws = B_FALSE;
12446 	}
12447 
12448 	/* Process Timestamp option. */
12449 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12450 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12451 		tmp_tcph = (char *)tcp->tcp_tcph;
12452 
12453 		tcp->tcp_snd_ts_ok = B_TRUE;
12454 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12455 		tcp->tcp_last_rcv_lbolt = lbolt64;
12456 		ASSERT(OK_32PTR(tmp_tcph));
12457 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12458 
12459 		/* Fill in our template header with basic timestamp option. */
12460 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12461 		tmp_tcph[0] = TCPOPT_NOP;
12462 		tmp_tcph[1] = TCPOPT_NOP;
12463 		tmp_tcph[2] = TCPOPT_TSTAMP;
12464 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12465 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12466 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12467 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12468 	} else {
12469 		tcp->tcp_snd_ts_ok = B_FALSE;
12470 	}
12471 
12472 	/*
12473 	 * Process SACK options.  If SACK is enabled for this connection,
12474 	 * then allocate the SACK info structure.  Note the following ways
12475 	 * when tcp_snd_sack_ok is set to true.
12476 	 *
12477 	 * For active connection: in tcp_adapt_ire() called in
12478 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12479 	 * is checked.
12480 	 *
12481 	 * For passive connection: in tcp_adapt_ire() called in
12482 	 * tcp_accept_comm().
12483 	 *
12484 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12485 	 * That check makes sure that if we did not send a SACK OK option,
12486 	 * we will not enable SACK for this connection even though the other
12487 	 * side sends us SACK OK option.  For active connection, the SACK
12488 	 * info structure has already been allocated.  So we need to free
12489 	 * it if SACK is disabled.
12490 	 */
12491 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12492 	    (tcp->tcp_snd_sack_ok ||
12493 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12494 		/* This should be true only in the passive case. */
12495 		if (tcp->tcp_sack_info == NULL) {
12496 			ASSERT(TCP_IS_DETACHED(tcp));
12497 			tcp->tcp_sack_info =
12498 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12499 		}
12500 		if (tcp->tcp_sack_info == NULL) {
12501 			tcp->tcp_snd_sack_ok = B_FALSE;
12502 		} else {
12503 			tcp->tcp_snd_sack_ok = B_TRUE;
12504 			if (tcp->tcp_snd_ts_ok) {
12505 				tcp->tcp_max_sack_blk = 3;
12506 			} else {
12507 				tcp->tcp_max_sack_blk = 4;
12508 			}
12509 		}
12510 	} else {
12511 		/*
12512 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12513 		 * no SACK info will be used for this
12514 		 * connection.  This assumes that SACK usage
12515 		 * permission is negotiated.  This may need
12516 		 * to be changed once this is clarified.
12517 		 */
12518 		if (tcp->tcp_sack_info != NULL) {
12519 			ASSERT(tcp->tcp_notsack_list == NULL);
12520 			kmem_cache_free(tcp_sack_info_cache,
12521 			    tcp->tcp_sack_info);
12522 			tcp->tcp_sack_info = NULL;
12523 		}
12524 		tcp->tcp_snd_sack_ok = B_FALSE;
12525 	}
12526 
12527 	/*
12528 	 * Now we know the exact TCP/IP header length, subtract
12529 	 * that from tcp_mss to get our side's MSS.
12530 	 */
12531 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12532 	/*
12533 	 * Here we assume that the other side's header size will be equal to
12534 	 * our header size.  We calculate the real MSS accordingly.  Need to
12535 	 * take into additional stuffs IPsec puts in.
12536 	 *
12537 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12538 	 */
12539 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12540 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12541 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12542 
12543 	/*
12544 	 * Set MSS to the smaller one of both ends of the connection.
12545 	 * We should not have called tcp_mss_set() before, but our
12546 	 * side of the MSS should have been set to a proper value
12547 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12548 	 * STREAM head parameters properly.
12549 	 *
12550 	 * If we have a larger-than-16-bit window but the other side
12551 	 * didn't want to do window scale, tcp_rwnd_set() will take
12552 	 * care of that.
12553 	 */
12554 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12555 }
12556 
12557 /*
12558  * Sends the T_CONN_IND to the listener. The caller calls this
12559  * functions via squeue to get inside the listener's perimeter
12560  * once the 3 way hand shake is done a T_CONN_IND needs to be
12561  * sent. As an optimization, the caller can call this directly
12562  * if listener's perimeter is same as eager's.
12563  */
12564 /* ARGSUSED */
12565 void
12566 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12567 {
12568 	conn_t			*lconnp = (conn_t *)arg;
12569 	tcp_t			*listener = lconnp->conn_tcp;
12570 	tcp_t			*tcp;
12571 	struct T_conn_ind	*conn_ind;
12572 	ipaddr_t 		*addr_cache;
12573 	boolean_t		need_send_conn_ind = B_FALSE;
12574 	tcp_stack_t		*tcps = listener->tcp_tcps;
12575 
12576 	/* retrieve the eager */
12577 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12578 	ASSERT(conn_ind->OPT_offset != 0 &&
12579 	    conn_ind->OPT_length == sizeof (intptr_t));
12580 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12581 	    conn_ind->OPT_length);
12582 
12583 	/*
12584 	 * TLI/XTI applications will get confused by
12585 	 * sending eager as an option since it violates
12586 	 * the option semantics. So remove the eager as
12587 	 * option since TLI/XTI app doesn't need it anyway.
12588 	 */
12589 	if (!TCP_IS_SOCKET(listener)) {
12590 		conn_ind->OPT_length = 0;
12591 		conn_ind->OPT_offset = 0;
12592 	}
12593 	if (listener->tcp_state == TCPS_CLOSED ||
12594 	    TCP_IS_DETACHED(listener)) {
12595 		/*
12596 		 * If listener has closed, it would have caused a
12597 		 * a cleanup/blowoff to happen for the eager. We
12598 		 * just need to return.
12599 		 */
12600 		freemsg(mp);
12601 		return;
12602 	}
12603 
12604 
12605 	/*
12606 	 * if the conn_req_q is full defer passing up the
12607 	 * T_CONN_IND until space is availabe after t_accept()
12608 	 * processing
12609 	 */
12610 	mutex_enter(&listener->tcp_eager_lock);
12611 
12612 	/*
12613 	 * Take the eager out, if it is in the list of droppable eagers
12614 	 * as we are here because the 3W handshake is over.
12615 	 */
12616 	MAKE_UNDROPPABLE(tcp);
12617 
12618 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12619 		tcp_t *tail;
12620 
12621 		/*
12622 		 * The eager already has an extra ref put in tcp_rput_data
12623 		 * so that it stays till accept comes back even though it
12624 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12625 		 */
12626 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12627 		listener->tcp_conn_req_cnt_q0--;
12628 		listener->tcp_conn_req_cnt_q++;
12629 
12630 		/* Move from SYN_RCVD to ESTABLISHED list  */
12631 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12632 		    tcp->tcp_eager_prev_q0;
12633 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12634 		    tcp->tcp_eager_next_q0;
12635 		tcp->tcp_eager_prev_q0 = NULL;
12636 		tcp->tcp_eager_next_q0 = NULL;
12637 
12638 		/*
12639 		 * Insert at end of the queue because sockfs
12640 		 * sends down T_CONN_RES in chronological
12641 		 * order. Leaving the older conn indications
12642 		 * at front of the queue helps reducing search
12643 		 * time.
12644 		 */
12645 		tail = listener->tcp_eager_last_q;
12646 		if (tail != NULL)
12647 			tail->tcp_eager_next_q = tcp;
12648 		else
12649 			listener->tcp_eager_next_q = tcp;
12650 		listener->tcp_eager_last_q = tcp;
12651 		tcp->tcp_eager_next_q = NULL;
12652 		/*
12653 		 * Delay sending up the T_conn_ind until we are
12654 		 * done with the eager. Once we have have sent up
12655 		 * the T_conn_ind, the accept can potentially complete
12656 		 * any time and release the refhold we have on the eager.
12657 		 */
12658 		need_send_conn_ind = B_TRUE;
12659 	} else {
12660 		/*
12661 		 * Defer connection on q0 and set deferred
12662 		 * connection bit true
12663 		 */
12664 		tcp->tcp_conn_def_q0 = B_TRUE;
12665 
12666 		/* take tcp out of q0 ... */
12667 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12668 		    tcp->tcp_eager_next_q0;
12669 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12670 		    tcp->tcp_eager_prev_q0;
12671 
12672 		/* ... and place it at the end of q0 */
12673 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12674 		tcp->tcp_eager_next_q0 = listener;
12675 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12676 		listener->tcp_eager_prev_q0 = tcp;
12677 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12678 	}
12679 
12680 	/* we have timed out before */
12681 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12682 		tcp->tcp_syn_rcvd_timeout = 0;
12683 		listener->tcp_syn_rcvd_timeout--;
12684 		if (listener->tcp_syn_defense &&
12685 		    listener->tcp_syn_rcvd_timeout <=
12686 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12687 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12688 		    listener->tcp_last_rcv_lbolt)) {
12689 			/*
12690 			 * Turn off the defense mode if we
12691 			 * believe the SYN attack is over.
12692 			 */
12693 			listener->tcp_syn_defense = B_FALSE;
12694 			if (listener->tcp_ip_addr_cache) {
12695 				kmem_free((void *)listener->tcp_ip_addr_cache,
12696 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12697 				listener->tcp_ip_addr_cache = NULL;
12698 			}
12699 		}
12700 	}
12701 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12702 	if (addr_cache != NULL) {
12703 		/*
12704 		 * We have finished a 3-way handshake with this
12705 		 * remote host. This proves the IP addr is good.
12706 		 * Cache it!
12707 		 */
12708 		addr_cache[IP_ADDR_CACHE_HASH(
12709 		    tcp->tcp_remote)] = tcp->tcp_remote;
12710 	}
12711 	mutex_exit(&listener->tcp_eager_lock);
12712 	if (need_send_conn_ind) {
12713 		if (IPCL_IS_NONSTR(lconnp)) {
12714 			ASSERT(tcp->tcp_listener == listener);
12715 			ASSERT(tcp->tcp_saved_listener == listener);
12716 			if ((*lconnp->conn_upcalls->su_newconn)
12717 			    (lconnp->conn_upper_handle,
12718 			    (sock_lower_handle_t)tcp->tcp_connp,
12719 			    &sock_tcp_downcalls, DB_CRED(mp), DB_CPID(mp),
12720 			    &tcp->tcp_connp->conn_upcalls) != NULL) {
12721 				/*
12722 				 * Keep the message around
12723 				 * in case of fallback
12724 				 */
12725 				tcp->tcp_conn.tcp_eager_conn_ind = mp;
12726 			} else {
12727 				freemsg(mp);
12728 			}
12729 		} else {
12730 			putnext(listener->tcp_rq, mp);
12731 		}
12732 	}
12733 }
12734 
12735 mblk_t *
12736 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12737     uint_t *ifindexp, ip6_pkt_t *ippp)
12738 {
12739 	ip_pktinfo_t	*pinfo;
12740 	ip6_t		*ip6h;
12741 	uchar_t		*rptr;
12742 	mblk_t		*first_mp = mp;
12743 	boolean_t	mctl_present = B_FALSE;
12744 	uint_t 		ifindex = 0;
12745 	ip6_pkt_t	ipp;
12746 	uint_t		ipvers;
12747 	uint_t		ip_hdr_len;
12748 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12749 
12750 	rptr = mp->b_rptr;
12751 	ASSERT(OK_32PTR(rptr));
12752 	ASSERT(tcp != NULL);
12753 	ipp.ipp_fields = 0;
12754 
12755 	switch DB_TYPE(mp) {
12756 	case M_CTL:
12757 		mp = mp->b_cont;
12758 		if (mp == NULL) {
12759 			freemsg(first_mp);
12760 			return (NULL);
12761 		}
12762 		if (DB_TYPE(mp) != M_DATA) {
12763 			freemsg(first_mp);
12764 			return (NULL);
12765 		}
12766 		mctl_present = B_TRUE;
12767 		break;
12768 	case M_DATA:
12769 		break;
12770 	default:
12771 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12772 		freemsg(mp);
12773 		return (NULL);
12774 	}
12775 	ipvers = IPH_HDR_VERSION(rptr);
12776 	if (ipvers == IPV4_VERSION) {
12777 		if (tcp == NULL) {
12778 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12779 			goto done;
12780 		}
12781 
12782 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12783 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12784 
12785 		/*
12786 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12787 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12788 		 */
12789 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12790 		    mctl_present) {
12791 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12792 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12793 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12794 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12795 				ipp.ipp_fields |= IPPF_IFINDEX;
12796 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12797 				ifindex = pinfo->ip_pkt_ifindex;
12798 			}
12799 			freeb(first_mp);
12800 			mctl_present = B_FALSE;
12801 		}
12802 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12803 	} else {
12804 		ip6h = (ip6_t *)rptr;
12805 
12806 		ASSERT(ipvers == IPV6_VERSION);
12807 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12808 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12809 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12810 
12811 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12812 			uint8_t	nexthdrp;
12813 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12814 
12815 			/* Look for ifindex information */
12816 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12817 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12818 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12819 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12820 					freemsg(first_mp);
12821 					return (NULL);
12822 				}
12823 
12824 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12825 					ASSERT(ip6i->ip6i_ifindex != 0);
12826 					ipp.ipp_fields |= IPPF_IFINDEX;
12827 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12828 					ifindex = ip6i->ip6i_ifindex;
12829 				}
12830 				rptr = (uchar_t *)&ip6i[1];
12831 				mp->b_rptr = rptr;
12832 				if (rptr == mp->b_wptr) {
12833 					mblk_t *mp1;
12834 					mp1 = mp->b_cont;
12835 					freeb(mp);
12836 					mp = mp1;
12837 					rptr = mp->b_rptr;
12838 				}
12839 				if (MBLKL(mp) < IPV6_HDR_LEN +
12840 				    sizeof (tcph_t)) {
12841 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12842 					freemsg(first_mp);
12843 					return (NULL);
12844 				}
12845 				ip6h = (ip6_t *)rptr;
12846 			}
12847 
12848 			/*
12849 			 * Find any potentially interesting extension headers
12850 			 * as well as the length of the IPv6 + extension
12851 			 * headers.
12852 			 */
12853 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12854 			/* Verify if this is a TCP packet */
12855 			if (nexthdrp != IPPROTO_TCP) {
12856 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12857 				freemsg(first_mp);
12858 				return (NULL);
12859 			}
12860 		} else {
12861 			ip_hdr_len = IPV6_HDR_LEN;
12862 		}
12863 	}
12864 
12865 done:
12866 	if (ipversp != NULL)
12867 		*ipversp = ipvers;
12868 	if (ip_hdr_lenp != NULL)
12869 		*ip_hdr_lenp = ip_hdr_len;
12870 	if (ippp != NULL)
12871 		*ippp = ipp;
12872 	if (ifindexp != NULL)
12873 		*ifindexp = ifindex;
12874 	if (mctl_present) {
12875 		freeb(first_mp);
12876 	}
12877 	return (mp);
12878 }
12879 
12880 /*
12881  * Handle M_DATA messages from IP. Its called directly from IP via
12882  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12883  * in this path.
12884  *
12885  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12886  * v4 and v6), we are called through tcp_input() and a M_CTL can
12887  * be present for options but tcp_find_pktinfo() deals with it. We
12888  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12889  *
12890  * The first argument is always the connp/tcp to which the mp belongs.
12891  * There are no exceptions to this rule. The caller has already put
12892  * a reference on this connp/tcp and once tcp_rput_data() returns,
12893  * the squeue will do the refrele.
12894  *
12895  * The TH_SYN for the listener directly go to tcp_conn_request via
12896  * squeue.
12897  *
12898  * sqp: NULL = recursive, sqp != NULL means called from squeue
12899  */
12900 void
12901 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12902 {
12903 	int32_t		bytes_acked;
12904 	int32_t		gap;
12905 	mblk_t		*mp1;
12906 	uint_t		flags;
12907 	uint32_t	new_swnd = 0;
12908 	uchar_t		*iphdr;
12909 	uchar_t		*rptr;
12910 	int32_t		rgap;
12911 	uint32_t	seg_ack;
12912 	int		seg_len;
12913 	uint_t		ip_hdr_len;
12914 	uint32_t	seg_seq;
12915 	tcph_t		*tcph;
12916 	int		urp;
12917 	tcp_opt_t	tcpopt;
12918 	uint_t		ipvers;
12919 	ip6_pkt_t	ipp;
12920 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12921 	uint32_t	cwnd;
12922 	uint32_t	add;
12923 	int		npkt;
12924 	int		mss;
12925 	conn_t		*connp = (conn_t *)arg;
12926 	squeue_t	*sqp = (squeue_t *)arg2;
12927 	tcp_t		*tcp = connp->conn_tcp;
12928 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12929 
12930 	/*
12931 	 * RST from fused tcp loopback peer should trigger an unfuse.
12932 	 */
12933 	if (tcp->tcp_fused) {
12934 		TCP_STAT(tcps, tcp_fusion_aborted);
12935 		tcp_unfuse(tcp);
12936 	}
12937 
12938 	iphdr = mp->b_rptr;
12939 	rptr = mp->b_rptr;
12940 	ASSERT(OK_32PTR(rptr));
12941 
12942 	/*
12943 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12944 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12945 	 * necessary information.
12946 	 */
12947 	if (IPCL_IS_TCP4(connp)) {
12948 		ipvers = IPV4_VERSION;
12949 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12950 	} else {
12951 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12952 		    NULL, &ipp);
12953 		if (mp == NULL) {
12954 			TCP_STAT(tcps, tcp_rput_v6_error);
12955 			return;
12956 		}
12957 		iphdr = mp->b_rptr;
12958 		rptr = mp->b_rptr;
12959 	}
12960 	ASSERT(DB_TYPE(mp) == M_DATA);
12961 	ASSERT(mp->b_next == NULL);
12962 
12963 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12964 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12965 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12966 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12967 	seg_len = (int)(mp->b_wptr - rptr) -
12968 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12969 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12970 		do {
12971 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12972 			    (uintptr_t)INT_MAX);
12973 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12974 		} while ((mp1 = mp1->b_cont) != NULL &&
12975 		    mp1->b_datap->db_type == M_DATA);
12976 	}
12977 
12978 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12979 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12980 		    seg_len, tcph);
12981 		return;
12982 	}
12983 
12984 	if (sqp != NULL) {
12985 		/*
12986 		 * This is the correct place to update tcp_last_recv_time. Note
12987 		 * that it is also updated for tcp structure that belongs to
12988 		 * global and listener queues which do not really need updating.
12989 		 * But that should not cause any harm.  And it is updated for
12990 		 * all kinds of incoming segments, not only for data segments.
12991 		 */
12992 		tcp->tcp_last_recv_time = lbolt;
12993 	}
12994 
12995 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12996 
12997 	BUMP_LOCAL(tcp->tcp_ibsegs);
12998 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
12999 
13000 	if ((flags & TH_URG) && sqp != NULL) {
13001 		/*
13002 		 * TCP can't handle urgent pointers that arrive before
13003 		 * the connection has been accept()ed since it can't
13004 		 * buffer OOB data.  Discard segment if this happens.
13005 		 *
13006 		 * We can't just rely on a non-null tcp_listener to indicate
13007 		 * that the accept() has completed since unlinking of the
13008 		 * eager and completion of the accept are not atomic.
13009 		 * tcp_detached, when it is not set (B_FALSE) indicates
13010 		 * that the accept() has completed.
13011 		 *
13012 		 * Nor can it reassemble urgent pointers, so discard
13013 		 * if it's not the next segment expected.
13014 		 *
13015 		 * Otherwise, collapse chain into one mblk (discard if
13016 		 * that fails).  This makes sure the headers, retransmitted
13017 		 * data, and new data all are in the same mblk.
13018 		 */
13019 		ASSERT(mp != NULL);
13020 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
13021 			freemsg(mp);
13022 			return;
13023 		}
13024 		/* Update pointers into message */
13025 		iphdr = rptr = mp->b_rptr;
13026 		tcph = (tcph_t *)&rptr[ip_hdr_len];
13027 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
13028 			/*
13029 			 * Since we can't handle any data with this urgent
13030 			 * pointer that is out of sequence, we expunge
13031 			 * the data.  This allows us to still register
13032 			 * the urgent mark and generate the M_PCSIG,
13033 			 * which we can do.
13034 			 */
13035 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13036 			seg_len = 0;
13037 		}
13038 	}
13039 
13040 	switch (tcp->tcp_state) {
13041 	case TCPS_SYN_SENT:
13042 		if (flags & TH_ACK) {
13043 			/*
13044 			 * Note that our stack cannot send data before a
13045 			 * connection is established, therefore the
13046 			 * following check is valid.  Otherwise, it has
13047 			 * to be changed.
13048 			 */
13049 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13050 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13051 				freemsg(mp);
13052 				if (flags & TH_RST)
13053 					return;
13054 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13055 				    tcp, seg_ack, 0, TH_RST);
13056 				return;
13057 			}
13058 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13059 		}
13060 		if (flags & TH_RST) {
13061 			freemsg(mp);
13062 			if (flags & TH_ACK)
13063 				(void) tcp_clean_death(tcp,
13064 				    ECONNREFUSED, 13);
13065 			return;
13066 		}
13067 		if (!(flags & TH_SYN)) {
13068 			freemsg(mp);
13069 			return;
13070 		}
13071 
13072 		/* Process all TCP options. */
13073 		tcp_process_options(tcp, tcph);
13074 		/*
13075 		 * The following changes our rwnd to be a multiple of the
13076 		 * MIN(peer MSS, our MSS) for performance reason.
13077 		 */
13078 		(void) tcp_rwnd_set(tcp,
13079 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
13080 
13081 		/* Is the other end ECN capable? */
13082 		if (tcp->tcp_ecn_ok) {
13083 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13084 				tcp->tcp_ecn_ok = B_FALSE;
13085 			}
13086 		}
13087 		/*
13088 		 * Clear ECN flags because it may interfere with later
13089 		 * processing.
13090 		 */
13091 		flags &= ~(TH_ECE|TH_CWR);
13092 
13093 		tcp->tcp_irs = seg_seq;
13094 		tcp->tcp_rack = seg_seq;
13095 		tcp->tcp_rnxt = seg_seq + 1;
13096 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13097 		if (!TCP_IS_DETACHED(tcp)) {
13098 			/* Allocate room for SACK options if needed. */
13099 			if (tcp->tcp_snd_sack_ok) {
13100 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13101 				    tcp->tcp_hdr_len +
13102 				    TCPOPT_MAX_SACK_LEN +
13103 				    (tcp->tcp_loopback ? 0 :
13104 				    tcps->tcps_wroff_xtra));
13105 			} else {
13106 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13107 				    tcp->tcp_hdr_len +
13108 				    (tcp->tcp_loopback ? 0 :
13109 				    tcps->tcps_wroff_xtra));
13110 			}
13111 		}
13112 		if (flags & TH_ACK) {
13113 			/*
13114 			 * If we can't get the confirmation upstream, pretend
13115 			 * we didn't even see this one.
13116 			 *
13117 			 * XXX: how can we pretend we didn't see it if we
13118 			 * have updated rnxt et. al.
13119 			 *
13120 			 * For loopback we defer sending up the T_CONN_CON
13121 			 * until after some checks below.
13122 			 */
13123 			mp1 = NULL;
13124 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13125 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13126 				freemsg(mp);
13127 				return;
13128 			}
13129 			/* SYN was acked - making progress */
13130 			if (tcp->tcp_ipversion == IPV6_VERSION)
13131 				tcp->tcp_ip_forward_progress = B_TRUE;
13132 
13133 			/* One for the SYN */
13134 			tcp->tcp_suna = tcp->tcp_iss + 1;
13135 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13136 			tcp->tcp_state = TCPS_ESTABLISHED;
13137 
13138 			/*
13139 			 * If SYN was retransmitted, need to reset all
13140 			 * retransmission info.  This is because this
13141 			 * segment will be treated as a dup ACK.
13142 			 */
13143 			if (tcp->tcp_rexmit) {
13144 				tcp->tcp_rexmit = B_FALSE;
13145 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13146 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13147 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13148 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13149 				tcp->tcp_ms_we_have_waited = 0;
13150 
13151 				/*
13152 				 * Set tcp_cwnd back to 1 MSS, per
13153 				 * recommendation from
13154 				 * draft-floyd-incr-init-win-01.txt,
13155 				 * Increasing TCP's Initial Window.
13156 				 */
13157 				tcp->tcp_cwnd = tcp->tcp_mss;
13158 			}
13159 
13160 			tcp->tcp_swl1 = seg_seq;
13161 			tcp->tcp_swl2 = seg_ack;
13162 
13163 			new_swnd = BE16_TO_U16(tcph->th_win);
13164 			tcp->tcp_swnd = new_swnd;
13165 			if (new_swnd > tcp->tcp_max_swnd)
13166 				tcp->tcp_max_swnd = new_swnd;
13167 
13168 			/*
13169 			 * Always send the three-way handshake ack immediately
13170 			 * in order to make the connection complete as soon as
13171 			 * possible on the accepting host.
13172 			 */
13173 			flags |= TH_ACK_NEEDED;
13174 
13175 			/*
13176 			 * Special case for loopback.  At this point we have
13177 			 * received SYN-ACK from the remote endpoint.  In
13178 			 * order to ensure that both endpoints reach the
13179 			 * fused state prior to any data exchange, the final
13180 			 * ACK needs to be sent before we indicate T_CONN_CON
13181 			 * to the module upstream.
13182 			 */
13183 			if (tcp->tcp_loopback) {
13184 				mblk_t *ack_mp;
13185 
13186 				ASSERT(!tcp->tcp_unfusable);
13187 				ASSERT(mp1 != NULL);
13188 				/*
13189 				 * For loopback, we always get a pure SYN-ACK
13190 				 * and only need to send back the final ACK
13191 				 * with no data (this is because the other
13192 				 * tcp is ours and we don't do T/TCP).  This
13193 				 * final ACK triggers the passive side to
13194 				 * perform fusion in ESTABLISHED state.
13195 				 */
13196 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13197 					if (tcp->tcp_ack_tid != 0) {
13198 						(void) TCP_TIMER_CANCEL(tcp,
13199 						    tcp->tcp_ack_tid);
13200 						tcp->tcp_ack_tid = 0;
13201 					}
13202 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13203 					BUMP_LOCAL(tcp->tcp_obsegs);
13204 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13205 
13206 					if (!IPCL_IS_NONSTR(connp)) {
13207 						/* Send up T_CONN_CON */
13208 						putnext(tcp->tcp_rq, mp1);
13209 					} else {
13210 						(*connp->conn_upcalls->
13211 						    su_connected)
13212 						    (connp->conn_upper_handle,
13213 						    tcp->tcp_connid,
13214 						    DB_CRED(mp1),
13215 						    DB_CPID(mp1));
13216 						freemsg(mp1);
13217 					}
13218 
13219 					freemsg(mp);
13220 					return;
13221 				}
13222 				/*
13223 				 * Forget fusion; we need to handle more
13224 				 * complex cases below.  Send the deferred
13225 				 * T_CONN_CON message upstream and proceed
13226 				 * as usual.  Mark this tcp as not capable
13227 				 * of fusion.
13228 				 */
13229 				TCP_STAT(tcps, tcp_fusion_unfusable);
13230 				tcp->tcp_unfusable = B_TRUE;
13231 				if (!IPCL_IS_NONSTR(connp)) {
13232 					putnext(tcp->tcp_rq, mp1);
13233 				} else {
13234 					(*connp->conn_upcalls->su_connected)
13235 					    (connp->conn_upper_handle,
13236 					    tcp->tcp_connid, DB_CRED(mp1),
13237 					    DB_CPID(mp1));
13238 					freemsg(mp1);
13239 				}
13240 			}
13241 
13242 			/*
13243 			 * Check to see if there is data to be sent.  If
13244 			 * yes, set the transmit flag.  Then check to see
13245 			 * if received data processing needs to be done.
13246 			 * If not, go straight to xmit_check.  This short
13247 			 * cut is OK as we don't support T/TCP.
13248 			 */
13249 			if (tcp->tcp_unsent)
13250 				flags |= TH_XMIT_NEEDED;
13251 
13252 			if (seg_len == 0 && !(flags & TH_URG)) {
13253 				freemsg(mp);
13254 				goto xmit_check;
13255 			}
13256 
13257 			flags &= ~TH_SYN;
13258 			seg_seq++;
13259 			break;
13260 		}
13261 		tcp->tcp_state = TCPS_SYN_RCVD;
13262 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13263 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13264 		if (mp1) {
13265 			DB_CPID(mp1) = tcp->tcp_cpid;
13266 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13267 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13268 		}
13269 		freemsg(mp);
13270 		return;
13271 	case TCPS_SYN_RCVD:
13272 		if (flags & TH_ACK) {
13273 			/*
13274 			 * In this state, a SYN|ACK packet is either bogus
13275 			 * because the other side must be ACKing our SYN which
13276 			 * indicates it has seen the ACK for their SYN and
13277 			 * shouldn't retransmit it or we're crossing SYNs
13278 			 * on active open.
13279 			 */
13280 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13281 				freemsg(mp);
13282 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13283 				    tcp, seg_ack, 0, TH_RST);
13284 				return;
13285 			}
13286 			/*
13287 			 * NOTE: RFC 793 pg. 72 says this should be
13288 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13289 			 * but that would mean we have an ack that ignored
13290 			 * our SYN.
13291 			 */
13292 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13293 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13294 				freemsg(mp);
13295 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13296 				    tcp, seg_ack, 0, TH_RST);
13297 				return;
13298 			}
13299 		}
13300 		break;
13301 	case TCPS_LISTEN:
13302 		/*
13303 		 * Only a TLI listener can come through this path when a
13304 		 * acceptor is going back to be a listener and a packet
13305 		 * for the acceptor hits the classifier. For a socket
13306 		 * listener, this can never happen because a listener
13307 		 * can never accept connection on itself and hence a
13308 		 * socket acceptor can not go back to being a listener.
13309 		 */
13310 		ASSERT(!TCP_IS_SOCKET(tcp));
13311 		/*FALLTHRU*/
13312 	case TCPS_CLOSED:
13313 	case TCPS_BOUND: {
13314 		conn_t	*new_connp;
13315 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13316 
13317 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13318 		if (new_connp != NULL) {
13319 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13320 			return;
13321 		}
13322 		/* We failed to classify. For now just drop the packet */
13323 		freemsg(mp);
13324 		return;
13325 	}
13326 	case TCPS_IDLE:
13327 		/*
13328 		 * Handle the case where the tcp_clean_death() has happened
13329 		 * on a connection (application hasn't closed yet) but a packet
13330 		 * was already queued on squeue before tcp_clean_death()
13331 		 * was processed. Calling tcp_clean_death() twice on same
13332 		 * connection can result in weird behaviour.
13333 		 */
13334 		freemsg(mp);
13335 		return;
13336 	default:
13337 		break;
13338 	}
13339 
13340 	/*
13341 	 * Already on the correct queue/perimeter.
13342 	 * If this is a detached connection and not an eager
13343 	 * connection hanging off a listener then new data
13344 	 * (past the FIN) will cause a reset.
13345 	 * We do a special check here where it
13346 	 * is out of the main line, rather than check
13347 	 * if we are detached every time we see new
13348 	 * data down below.
13349 	 */
13350 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13351 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13352 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13353 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13354 
13355 		freemsg(mp);
13356 		/*
13357 		 * This could be an SSL closure alert. We're detached so just
13358 		 * acknowledge it this last time.
13359 		 */
13360 		if (tcp->tcp_kssl_ctx != NULL) {
13361 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13362 			tcp->tcp_kssl_ctx = NULL;
13363 
13364 			tcp->tcp_rnxt += seg_len;
13365 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13366 			flags |= TH_ACK_NEEDED;
13367 			goto ack_check;
13368 		}
13369 
13370 		tcp_xmit_ctl("new data when detached", tcp,
13371 		    tcp->tcp_snxt, 0, TH_RST);
13372 		(void) tcp_clean_death(tcp, EPROTO, 12);
13373 		return;
13374 	}
13375 
13376 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13377 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13378 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13379 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13380 
13381 	if (tcp->tcp_snd_ts_ok) {
13382 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13383 			/*
13384 			 * This segment is not acceptable.
13385 			 * Drop it and send back an ACK.
13386 			 */
13387 			freemsg(mp);
13388 			flags |= TH_ACK_NEEDED;
13389 			goto ack_check;
13390 		}
13391 	} else if (tcp->tcp_snd_sack_ok) {
13392 		ASSERT(tcp->tcp_sack_info != NULL);
13393 		tcpopt.tcp = tcp;
13394 		/*
13395 		 * SACK info in already updated in tcp_parse_options.  Ignore
13396 		 * all other TCP options...
13397 		 */
13398 		(void) tcp_parse_options(tcph, &tcpopt);
13399 	}
13400 try_again:;
13401 	mss = tcp->tcp_mss;
13402 	gap = seg_seq - tcp->tcp_rnxt;
13403 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13404 	/*
13405 	 * gap is the amount of sequence space between what we expect to see
13406 	 * and what we got for seg_seq.  A positive value for gap means
13407 	 * something got lost.  A negative value means we got some old stuff.
13408 	 */
13409 	if (gap < 0) {
13410 		/* Old stuff present.  Is the SYN in there? */
13411 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13412 		    (seg_len != 0)) {
13413 			flags &= ~TH_SYN;
13414 			seg_seq++;
13415 			urp--;
13416 			/* Recompute the gaps after noting the SYN. */
13417 			goto try_again;
13418 		}
13419 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13420 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13421 		    (seg_len > -gap ? -gap : seg_len));
13422 		/* Remove the old stuff from seg_len. */
13423 		seg_len += gap;
13424 		/*
13425 		 * Anything left?
13426 		 * Make sure to check for unack'd FIN when rest of data
13427 		 * has been previously ack'd.
13428 		 */
13429 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13430 			/*
13431 			 * Resets are only valid if they lie within our offered
13432 			 * window.  If the RST bit is set, we just ignore this
13433 			 * segment.
13434 			 */
13435 			if (flags & TH_RST) {
13436 				freemsg(mp);
13437 				return;
13438 			}
13439 
13440 			/*
13441 			 * The arriving of dup data packets indicate that we
13442 			 * may have postponed an ack for too long, or the other
13443 			 * side's RTT estimate is out of shape. Start acking
13444 			 * more often.
13445 			 */
13446 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13447 			    tcp->tcp_rack_cnt >= 1 &&
13448 			    tcp->tcp_rack_abs_max > 2) {
13449 				tcp->tcp_rack_abs_max--;
13450 			}
13451 			tcp->tcp_rack_cur_max = 1;
13452 
13453 			/*
13454 			 * This segment is "unacceptable".  None of its
13455 			 * sequence space lies within our advertized window.
13456 			 *
13457 			 * Adjust seg_len to the original value for tracing.
13458 			 */
13459 			seg_len -= gap;
13460 			if (tcp->tcp_debug) {
13461 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13462 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13463 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13464 				    "seg_len %d, rnxt %u, snxt %u, %s",
13465 				    gap, rgap, flags, seg_seq, seg_ack,
13466 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13467 				    tcp_display(tcp, NULL,
13468 				    DISP_ADDR_AND_PORT));
13469 			}
13470 
13471 			/*
13472 			 * Arrange to send an ACK in response to the
13473 			 * unacceptable segment per RFC 793 page 69. There
13474 			 * is only one small difference between ours and the
13475 			 * acceptability test in the RFC - we accept ACK-only
13476 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13477 			 * will be generated.
13478 			 *
13479 			 * Note that we have to ACK an ACK-only packet at least
13480 			 * for stacks that send 0-length keep-alives with
13481 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13482 			 * section 4.2.3.6. As long as we don't ever generate
13483 			 * an unacceptable packet in response to an incoming
13484 			 * packet that is unacceptable, it should not cause
13485 			 * "ACK wars".
13486 			 */
13487 			flags |=  TH_ACK_NEEDED;
13488 
13489 			/*
13490 			 * Continue processing this segment in order to use the
13491 			 * ACK information it contains, but skip all other
13492 			 * sequence-number processing.	Processing the ACK
13493 			 * information is necessary in order to
13494 			 * re-synchronize connections that may have lost
13495 			 * synchronization.
13496 			 *
13497 			 * We clear seg_len and flag fields related to
13498 			 * sequence number processing as they are not
13499 			 * to be trusted for an unacceptable segment.
13500 			 */
13501 			seg_len = 0;
13502 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13503 			goto process_ack;
13504 		}
13505 
13506 		/* Fix seg_seq, and chew the gap off the front. */
13507 		seg_seq = tcp->tcp_rnxt;
13508 		urp += gap;
13509 		do {
13510 			mblk_t	*mp2;
13511 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13512 			    (uintptr_t)UINT_MAX);
13513 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13514 			if (gap > 0) {
13515 				mp->b_rptr = mp->b_wptr - gap;
13516 				break;
13517 			}
13518 			mp2 = mp;
13519 			mp = mp->b_cont;
13520 			freeb(mp2);
13521 		} while (gap < 0);
13522 		/*
13523 		 * If the urgent data has already been acknowledged, we
13524 		 * should ignore TH_URG below
13525 		 */
13526 		if (urp < 0)
13527 			flags &= ~TH_URG;
13528 	}
13529 	/*
13530 	 * rgap is the amount of stuff received out of window.  A negative
13531 	 * value is the amount out of window.
13532 	 */
13533 	if (rgap < 0) {
13534 		mblk_t	*mp2;
13535 
13536 		if (tcp->tcp_rwnd == 0) {
13537 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13538 		} else {
13539 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13540 			UPDATE_MIB(&tcps->tcps_mib,
13541 			    tcpInDataPastWinBytes, -rgap);
13542 		}
13543 
13544 		/*
13545 		 * seg_len does not include the FIN, so if more than
13546 		 * just the FIN is out of window, we act like we don't
13547 		 * see it.  (If just the FIN is out of window, rgap
13548 		 * will be zero and we will go ahead and acknowledge
13549 		 * the FIN.)
13550 		 */
13551 		flags &= ~TH_FIN;
13552 
13553 		/* Fix seg_len and make sure there is something left. */
13554 		seg_len += rgap;
13555 		if (seg_len <= 0) {
13556 			/*
13557 			 * Resets are only valid if they lie within our offered
13558 			 * window.  If the RST bit is set, we just ignore this
13559 			 * segment.
13560 			 */
13561 			if (flags & TH_RST) {
13562 				freemsg(mp);
13563 				return;
13564 			}
13565 
13566 			/* Per RFC 793, we need to send back an ACK. */
13567 			flags |= TH_ACK_NEEDED;
13568 
13569 			/*
13570 			 * Send SIGURG as soon as possible i.e. even
13571 			 * if the TH_URG was delivered in a window probe
13572 			 * packet (which will be unacceptable).
13573 			 *
13574 			 * We generate a signal if none has been generated
13575 			 * for this connection or if this is a new urgent
13576 			 * byte. Also send a zero-length "unmarked" message
13577 			 * to inform SIOCATMARK that this is not the mark.
13578 			 *
13579 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13580 			 * is sent up. This plus the check for old data
13581 			 * (gap >= 0) handles the wraparound of the sequence
13582 			 * number space without having to always track the
13583 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13584 			 * this max in its rcv_up variable).
13585 			 *
13586 			 * This prevents duplicate SIGURGS due to a "late"
13587 			 * zero-window probe when the T_EXDATA_IND has already
13588 			 * been sent up.
13589 			 */
13590 			if ((flags & TH_URG) &&
13591 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13592 			    tcp->tcp_urp_last))) {
13593 				if (IPCL_IS_NONSTR(connp)) {
13594 					if (!TCP_IS_DETACHED(tcp)) {
13595 						(*connp->conn_upcalls->
13596 						    su_signal_oob)
13597 						    (connp->conn_upper_handle,
13598 						    urp);
13599 					}
13600 				} else {
13601 					mp1 = allocb(0, BPRI_MED);
13602 					if (mp1 == NULL) {
13603 						freemsg(mp);
13604 						return;
13605 					}
13606 					if (!TCP_IS_DETACHED(tcp) &&
13607 					    !putnextctl1(tcp->tcp_rq,
13608 					    M_PCSIG, SIGURG)) {
13609 						/* Try again on the rexmit. */
13610 						freemsg(mp1);
13611 						freemsg(mp);
13612 						return;
13613 					}
13614 					/*
13615 					 * If the next byte would be the mark
13616 					 * then mark with MARKNEXT else mark
13617 					 * with NOTMARKNEXT.
13618 					 */
13619 					if (gap == 0 && urp == 0)
13620 						mp1->b_flag |= MSGMARKNEXT;
13621 					else
13622 						mp1->b_flag |= MSGNOTMARKNEXT;
13623 					freemsg(tcp->tcp_urp_mark_mp);
13624 					tcp->tcp_urp_mark_mp = mp1;
13625 					flags |= TH_SEND_URP_MARK;
13626 				}
13627 				tcp->tcp_urp_last_valid = B_TRUE;
13628 				tcp->tcp_urp_last = urp + seg_seq;
13629 			}
13630 			/*
13631 			 * If this is a zero window probe, continue to
13632 			 * process the ACK part.  But we need to set seg_len
13633 			 * to 0 to avoid data processing.  Otherwise just
13634 			 * drop the segment and send back an ACK.
13635 			 */
13636 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13637 				flags &= ~(TH_SYN | TH_URG);
13638 				seg_len = 0;
13639 				goto process_ack;
13640 			} else {
13641 				freemsg(mp);
13642 				goto ack_check;
13643 			}
13644 		}
13645 		/* Pitch out of window stuff off the end. */
13646 		rgap = seg_len;
13647 		mp2 = mp;
13648 		do {
13649 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13650 			    (uintptr_t)INT_MAX);
13651 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13652 			if (rgap < 0) {
13653 				mp2->b_wptr += rgap;
13654 				if ((mp1 = mp2->b_cont) != NULL) {
13655 					mp2->b_cont = NULL;
13656 					freemsg(mp1);
13657 				}
13658 				break;
13659 			}
13660 		} while ((mp2 = mp2->b_cont) != NULL);
13661 	}
13662 ok:;
13663 	/*
13664 	 * TCP should check ECN info for segments inside the window only.
13665 	 * Therefore the check should be done here.
13666 	 */
13667 	if (tcp->tcp_ecn_ok) {
13668 		if (flags & TH_CWR) {
13669 			tcp->tcp_ecn_echo_on = B_FALSE;
13670 		}
13671 		/*
13672 		 * Note that both ECN_CE and CWR can be set in the
13673 		 * same segment.  In this case, we once again turn
13674 		 * on ECN_ECHO.
13675 		 */
13676 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13677 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13678 
13679 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13680 				tcp->tcp_ecn_echo_on = B_TRUE;
13681 			}
13682 		} else {
13683 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13684 
13685 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13686 			    htonl(IPH_ECN_CE << 20)) {
13687 				tcp->tcp_ecn_echo_on = B_TRUE;
13688 			}
13689 		}
13690 	}
13691 
13692 	/*
13693 	 * Check whether we can update tcp_ts_recent.  This test is
13694 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13695 	 * Extensions for High Performance: An Update", Internet Draft.
13696 	 */
13697 	if (tcp->tcp_snd_ts_ok &&
13698 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13699 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13700 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13701 		tcp->tcp_last_rcv_lbolt = lbolt64;
13702 	}
13703 
13704 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13705 		/*
13706 		 * FIN in an out of order segment.  We record this in
13707 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13708 		 * Clear the FIN so that any check on FIN flag will fail.
13709 		 * Remember that FIN also counts in the sequence number
13710 		 * space.  So we need to ack out of order FIN only segments.
13711 		 */
13712 		if (flags & TH_FIN) {
13713 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13714 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13715 			flags &= ~TH_FIN;
13716 			flags |= TH_ACK_NEEDED;
13717 		}
13718 		if (seg_len > 0) {
13719 			/* Fill in the SACK blk list. */
13720 			if (tcp->tcp_snd_sack_ok) {
13721 				ASSERT(tcp->tcp_sack_info != NULL);
13722 				tcp_sack_insert(tcp->tcp_sack_list,
13723 				    seg_seq, seg_seq + seg_len,
13724 				    &(tcp->tcp_num_sack_blk));
13725 			}
13726 
13727 			/*
13728 			 * Attempt reassembly and see if we have something
13729 			 * ready to go.
13730 			 */
13731 			mp = tcp_reass(tcp, mp, seg_seq);
13732 			/* Always ack out of order packets */
13733 			flags |= TH_ACK_NEEDED | TH_PUSH;
13734 			if (mp) {
13735 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13736 				    (uintptr_t)INT_MAX);
13737 				seg_len = mp->b_cont ? msgdsize(mp) :
13738 				    (int)(mp->b_wptr - mp->b_rptr);
13739 				seg_seq = tcp->tcp_rnxt;
13740 				/*
13741 				 * A gap is filled and the seq num and len
13742 				 * of the gap match that of a previously
13743 				 * received FIN, put the FIN flag back in.
13744 				 */
13745 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13746 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13747 					flags |= TH_FIN;
13748 					tcp->tcp_valid_bits &=
13749 					    ~TCP_OFO_FIN_VALID;
13750 				}
13751 			} else {
13752 				/*
13753 				 * Keep going even with NULL mp.
13754 				 * There may be a useful ACK or something else
13755 				 * we don't want to miss.
13756 				 *
13757 				 * But TCP should not perform fast retransmit
13758 				 * because of the ack number.  TCP uses
13759 				 * seg_len == 0 to determine if it is a pure
13760 				 * ACK.  And this is not a pure ACK.
13761 				 */
13762 				seg_len = 0;
13763 				ofo_seg = B_TRUE;
13764 			}
13765 		}
13766 	} else if (seg_len > 0) {
13767 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13768 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13769 		/*
13770 		 * If an out of order FIN was received before, and the seq
13771 		 * num and len of the new segment match that of the FIN,
13772 		 * put the FIN flag back in.
13773 		 */
13774 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13775 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13776 			flags |= TH_FIN;
13777 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13778 		}
13779 	}
13780 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13781 	if (flags & TH_RST) {
13782 		freemsg(mp);
13783 		switch (tcp->tcp_state) {
13784 		case TCPS_SYN_RCVD:
13785 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13786 			break;
13787 		case TCPS_ESTABLISHED:
13788 		case TCPS_FIN_WAIT_1:
13789 		case TCPS_FIN_WAIT_2:
13790 		case TCPS_CLOSE_WAIT:
13791 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13792 			break;
13793 		case TCPS_CLOSING:
13794 		case TCPS_LAST_ACK:
13795 			(void) tcp_clean_death(tcp, 0, 16);
13796 			break;
13797 		default:
13798 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13799 			(void) tcp_clean_death(tcp, ENXIO, 17);
13800 			break;
13801 		}
13802 		return;
13803 	}
13804 	if (flags & TH_SYN) {
13805 		/*
13806 		 * See RFC 793, Page 71
13807 		 *
13808 		 * The seq number must be in the window as it should
13809 		 * be "fixed" above.  If it is outside window, it should
13810 		 * be already rejected.  Note that we allow seg_seq to be
13811 		 * rnxt + rwnd because we want to accept 0 window probe.
13812 		 */
13813 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13814 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13815 		freemsg(mp);
13816 		/*
13817 		 * If the ACK flag is not set, just use our snxt as the
13818 		 * seq number of the RST segment.
13819 		 */
13820 		if (!(flags & TH_ACK)) {
13821 			seg_ack = tcp->tcp_snxt;
13822 		}
13823 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13824 		    TH_RST|TH_ACK);
13825 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13826 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13827 		return;
13828 	}
13829 	/*
13830 	 * urp could be -1 when the urp field in the packet is 0
13831 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13832 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13833 	 */
13834 	if (flags & TH_URG && urp >= 0) {
13835 		if (!tcp->tcp_urp_last_valid ||
13836 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13837 			if (IPCL_IS_NONSTR(connp)) {
13838 				if (!TCP_IS_DETACHED(tcp)) {
13839 					(*connp->conn_upcalls->su_signal_oob)
13840 					    (connp->conn_upper_handle, urp);
13841 				}
13842 			} else {
13843 				/*
13844 				 * If we haven't generated the signal yet for
13845 				 * this urgent pointer value, do it now.  Also,
13846 				 * send up a zero-length M_DATA indicating
13847 				 * whether or not this is the mark. The latter
13848 				 * is not needed when a T_EXDATA_IND is sent up.
13849 				 * However, if there are allocation failures
13850 				 * this code relies on the sender retransmitting
13851 				 * and the socket code for determining the mark
13852 				 * should not block waiting for the peer to
13853 				 * transmit. Thus, for simplicity we always
13854 				 * send up the mark indication.
13855 				 */
13856 				mp1 = allocb(0, BPRI_MED);
13857 				if (mp1 == NULL) {
13858 					freemsg(mp);
13859 					return;
13860 				}
13861 				if (!TCP_IS_DETACHED(tcp) &&
13862 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13863 				    SIGURG)) {
13864 					/* Try again on the rexmit. */
13865 					freemsg(mp1);
13866 					freemsg(mp);
13867 					return;
13868 				}
13869 				/*
13870 				 * Mark with NOTMARKNEXT for now.
13871 				 * The code below will change this to MARKNEXT
13872 				 * if we are at the mark.
13873 				 *
13874 				 * If there are allocation failures (e.g. in
13875 				 * dupmsg below) the next time tcp_rput_data
13876 				 * sees the urgent segment it will send up the
13877 				 * MSGMARKNEXT message.
13878 				 */
13879 				mp1->b_flag |= MSGNOTMARKNEXT;
13880 				freemsg(tcp->tcp_urp_mark_mp);
13881 				tcp->tcp_urp_mark_mp = mp1;
13882 				flags |= TH_SEND_URP_MARK;
13883 #ifdef DEBUG
13884 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13885 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13886 				    "last %x, %s",
13887 				    seg_seq, urp, tcp->tcp_urp_last,
13888 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13889 #endif /* DEBUG */
13890 			}
13891 			tcp->tcp_urp_last_valid = B_TRUE;
13892 			tcp->tcp_urp_last = urp + seg_seq;
13893 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13894 			/*
13895 			 * An allocation failure prevented the previous
13896 			 * tcp_rput_data from sending up the allocated
13897 			 * MSG*MARKNEXT message - send it up this time
13898 			 * around.
13899 			 */
13900 			flags |= TH_SEND_URP_MARK;
13901 		}
13902 
13903 		/*
13904 		 * If the urgent byte is in this segment, make sure that it is
13905 		 * all by itself.  This makes it much easier to deal with the
13906 		 * possibility of an allocation failure on the T_exdata_ind.
13907 		 * Note that seg_len is the number of bytes in the segment, and
13908 		 * urp is the offset into the segment of the urgent byte.
13909 		 * urp < seg_len means that the urgent byte is in this segment.
13910 		 */
13911 		if (urp < seg_len) {
13912 			if (seg_len != 1) {
13913 				uint32_t  tmp_rnxt;
13914 				/*
13915 				 * Break it up and feed it back in.
13916 				 * Re-attach the IP header.
13917 				 */
13918 				mp->b_rptr = iphdr;
13919 				if (urp > 0) {
13920 					/*
13921 					 * There is stuff before the urgent
13922 					 * byte.
13923 					 */
13924 					mp1 = dupmsg(mp);
13925 					if (!mp1) {
13926 						/*
13927 						 * Trim from urgent byte on.
13928 						 * The rest will come back.
13929 						 */
13930 						(void) adjmsg(mp,
13931 						    urp - seg_len);
13932 						tcp_rput_data(connp,
13933 						    mp, NULL);
13934 						return;
13935 					}
13936 					(void) adjmsg(mp1, urp - seg_len);
13937 					/* Feed this piece back in. */
13938 					tmp_rnxt = tcp->tcp_rnxt;
13939 					tcp_rput_data(connp, mp1, NULL);
13940 					/*
13941 					 * If the data passed back in was not
13942 					 * processed (ie: bad ACK) sending
13943 					 * the remainder back in will cause a
13944 					 * loop. In this case, drop the
13945 					 * packet and let the sender try
13946 					 * sending a good packet.
13947 					 */
13948 					if (tmp_rnxt == tcp->tcp_rnxt) {
13949 						freemsg(mp);
13950 						return;
13951 					}
13952 				}
13953 				if (urp != seg_len - 1) {
13954 					uint32_t  tmp_rnxt;
13955 					/*
13956 					 * There is stuff after the urgent
13957 					 * byte.
13958 					 */
13959 					mp1 = dupmsg(mp);
13960 					if (!mp1) {
13961 						/*
13962 						 * Trim everything beyond the
13963 						 * urgent byte.  The rest will
13964 						 * come back.
13965 						 */
13966 						(void) adjmsg(mp,
13967 						    urp + 1 - seg_len);
13968 						tcp_rput_data(connp,
13969 						    mp, NULL);
13970 						return;
13971 					}
13972 					(void) adjmsg(mp1, urp + 1 - seg_len);
13973 					tmp_rnxt = tcp->tcp_rnxt;
13974 					tcp_rput_data(connp, mp1, NULL);
13975 					/*
13976 					 * If the data passed back in was not
13977 					 * processed (ie: bad ACK) sending
13978 					 * the remainder back in will cause a
13979 					 * loop. In this case, drop the
13980 					 * packet and let the sender try
13981 					 * sending a good packet.
13982 					 */
13983 					if (tmp_rnxt == tcp->tcp_rnxt) {
13984 						freemsg(mp);
13985 						return;
13986 					}
13987 				}
13988 				tcp_rput_data(connp, mp, NULL);
13989 				return;
13990 			}
13991 			/*
13992 			 * This segment contains only the urgent byte.  We
13993 			 * have to allocate the T_exdata_ind, if we can.
13994 			 */
13995 			if (IPCL_IS_NONSTR(connp)) {
13996 				int error;
13997 
13998 				(*connp->conn_upcalls->su_recv)
13999 				    (connp->conn_upper_handle, mp, seg_len,
14000 				    MSG_OOB, &error, NULL);
14001 				mp = NULL;
14002 				goto update_ack;
14003 			} else if (!tcp->tcp_urp_mp) {
14004 				struct T_exdata_ind *tei;
14005 				mp1 = allocb(sizeof (struct T_exdata_ind),
14006 				    BPRI_MED);
14007 				if (!mp1) {
14008 					/*
14009 					 * Sigh... It'll be back.
14010 					 * Generate any MSG*MARK message now.
14011 					 */
14012 					freemsg(mp);
14013 					seg_len = 0;
14014 					if (flags & TH_SEND_URP_MARK) {
14015 
14016 
14017 						ASSERT(tcp->tcp_urp_mark_mp);
14018 						tcp->tcp_urp_mark_mp->b_flag &=
14019 						    ~MSGNOTMARKNEXT;
14020 						tcp->tcp_urp_mark_mp->b_flag |=
14021 						    MSGMARKNEXT;
14022 					}
14023 					goto ack_check;
14024 				}
14025 				mp1->b_datap->db_type = M_PROTO;
14026 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14027 				tei->PRIM_type = T_EXDATA_IND;
14028 				tei->MORE_flag = 0;
14029 				mp1->b_wptr = (uchar_t *)&tei[1];
14030 				tcp->tcp_urp_mp = mp1;
14031 #ifdef DEBUG
14032 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14033 				    "tcp_rput: allocated exdata_ind %s",
14034 				    tcp_display(tcp, NULL,
14035 				    DISP_PORT_ONLY));
14036 #endif /* DEBUG */
14037 				/*
14038 				 * There is no need to send a separate MSG*MARK
14039 				 * message since the T_EXDATA_IND will be sent
14040 				 * now.
14041 				 */
14042 				flags &= ~TH_SEND_URP_MARK;
14043 				freemsg(tcp->tcp_urp_mark_mp);
14044 				tcp->tcp_urp_mark_mp = NULL;
14045 			}
14046 			/*
14047 			 * Now we are all set.  On the next putnext upstream,
14048 			 * tcp_urp_mp will be non-NULL and will get prepended
14049 			 * to what has to be this piece containing the urgent
14050 			 * byte.  If for any reason we abort this segment below,
14051 			 * if it comes back, we will have this ready, or it
14052 			 * will get blown off in close.
14053 			 */
14054 		} else if (urp == seg_len) {
14055 			/*
14056 			 * The urgent byte is the next byte after this sequence
14057 			 * number. If there is data it is marked with
14058 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14059 			 * since it is not needed. Otherwise, if the code
14060 			 * above just allocated a zero-length tcp_urp_mark_mp
14061 			 * message, that message is tagged with MSGMARKNEXT.
14062 			 * Sending up these MSGMARKNEXT messages makes
14063 			 * SIOCATMARK work correctly even though
14064 			 * the T_EXDATA_IND will not be sent up until the
14065 			 * urgent byte arrives.
14066 			 */
14067 			if (seg_len != 0) {
14068 				flags |= TH_MARKNEXT_NEEDED;
14069 				freemsg(tcp->tcp_urp_mark_mp);
14070 				tcp->tcp_urp_mark_mp = NULL;
14071 				flags &= ~TH_SEND_URP_MARK;
14072 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14073 				flags |= TH_SEND_URP_MARK;
14074 				tcp->tcp_urp_mark_mp->b_flag &=
14075 				    ~MSGNOTMARKNEXT;
14076 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14077 			}
14078 #ifdef DEBUG
14079 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14080 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14081 			    seg_len, flags,
14082 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14083 #endif /* DEBUG */
14084 		}
14085 #ifdef DEBUG
14086 		else {
14087 			/* Data left until we hit mark */
14088 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14089 			    "tcp_rput: URP %d bytes left, %s",
14090 			    urp - seg_len, tcp_display(tcp, NULL,
14091 			    DISP_PORT_ONLY));
14092 		}
14093 #endif /* DEBUG */
14094 	}
14095 
14096 process_ack:
14097 	if (!(flags & TH_ACK)) {
14098 		freemsg(mp);
14099 		goto xmit_check;
14100 	}
14101 	}
14102 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14103 
14104 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14105 		tcp->tcp_ip_forward_progress = B_TRUE;
14106 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14107 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
14108 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
14109 			/* 3-way handshake complete - pass up the T_CONN_IND */
14110 			tcp_t	*listener = tcp->tcp_listener;
14111 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14112 
14113 			tcp->tcp_tconnind_started = B_TRUE;
14114 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14115 			/*
14116 			 * We are here means eager is fine but it can
14117 			 * get a TH_RST at any point between now and till
14118 			 * accept completes and disappear. We need to
14119 			 * ensure that reference to eager is valid after
14120 			 * we get out of eager's perimeter. So we do
14121 			 * an extra refhold.
14122 			 */
14123 			CONN_INC_REF(connp);
14124 
14125 			/*
14126 			 * The listener also exists because of the refhold
14127 			 * done in tcp_conn_request. Its possible that it
14128 			 * might have closed. We will check that once we
14129 			 * get inside listeners context.
14130 			 */
14131 			CONN_INC_REF(listener->tcp_connp);
14132 			if (listener->tcp_connp->conn_sqp ==
14133 			    connp->conn_sqp) {
14134 				/*
14135 				 * We optimize by not calling an SQUEUE_ENTER
14136 				 * on the listener since we know that the
14137 				 * listener and eager squeues are the same.
14138 				 * We are able to make this check safely only
14139 				 * because neither the eager nor the listener
14140 				 * can change its squeue. Only an active connect
14141 				 * can change its squeue
14142 				 */
14143 				tcp_send_conn_ind(listener->tcp_connp, mp,
14144 				    listener->tcp_connp->conn_sqp);
14145 				CONN_DEC_REF(listener->tcp_connp);
14146 			} else if (!tcp->tcp_loopback) {
14147 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14148 				    mp, tcp_send_conn_ind,
14149 				    listener->tcp_connp, SQ_FILL,
14150 				    SQTAG_TCP_CONN_IND);
14151 			} else {
14152 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14153 				    mp, tcp_send_conn_ind,
14154 				    listener->tcp_connp, SQ_PROCESS,
14155 				    SQTAG_TCP_CONN_IND);
14156 			}
14157 		}
14158 
14159 		if (tcp->tcp_active_open) {
14160 			/*
14161 			 * We are seeing the final ack in the three way
14162 			 * hand shake of a active open'ed connection
14163 			 * so we must send up a T_CONN_CON
14164 			 */
14165 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14166 				freemsg(mp);
14167 				return;
14168 			}
14169 			/*
14170 			 * Don't fuse the loopback endpoints for
14171 			 * simultaneous active opens.
14172 			 */
14173 			if (tcp->tcp_loopback) {
14174 				TCP_STAT(tcps, tcp_fusion_unfusable);
14175 				tcp->tcp_unfusable = B_TRUE;
14176 			}
14177 		}
14178 
14179 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14180 		bytes_acked--;
14181 		/* SYN was acked - making progress */
14182 		if (tcp->tcp_ipversion == IPV6_VERSION)
14183 			tcp->tcp_ip_forward_progress = B_TRUE;
14184 
14185 		/*
14186 		 * If SYN was retransmitted, need to reset all
14187 		 * retransmission info as this segment will be
14188 		 * treated as a dup ACK.
14189 		 */
14190 		if (tcp->tcp_rexmit) {
14191 			tcp->tcp_rexmit = B_FALSE;
14192 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14193 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14194 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14195 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14196 			tcp->tcp_ms_we_have_waited = 0;
14197 			tcp->tcp_cwnd = mss;
14198 		}
14199 
14200 		/*
14201 		 * We set the send window to zero here.
14202 		 * This is needed if there is data to be
14203 		 * processed already on the queue.
14204 		 * Later (at swnd_update label), the
14205 		 * "new_swnd > tcp_swnd" condition is satisfied
14206 		 * the XMIT_NEEDED flag is set in the current
14207 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14208 		 * called if there is already data on queue in
14209 		 * this state.
14210 		 */
14211 		tcp->tcp_swnd = 0;
14212 
14213 		if (new_swnd > tcp->tcp_max_swnd)
14214 			tcp->tcp_max_swnd = new_swnd;
14215 		tcp->tcp_swl1 = seg_seq;
14216 		tcp->tcp_swl2 = seg_ack;
14217 		tcp->tcp_state = TCPS_ESTABLISHED;
14218 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14219 
14220 		/* Fuse when both sides are in ESTABLISHED state */
14221 		if (tcp->tcp_loopback && do_tcp_fusion)
14222 			tcp_fuse(tcp, iphdr, tcph);
14223 
14224 	}
14225 	/* This code follows 4.4BSD-Lite2 mostly. */
14226 	if (bytes_acked < 0)
14227 		goto est;
14228 
14229 	/*
14230 	 * If TCP is ECN capable and the congestion experience bit is
14231 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14232 	 * done once per window (or more loosely, per RTT).
14233 	 */
14234 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14235 		tcp->tcp_cwr = B_FALSE;
14236 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14237 		if (!tcp->tcp_cwr) {
14238 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14239 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14240 			tcp->tcp_cwnd = npkt * mss;
14241 			/*
14242 			 * If the cwnd is 0, use the timer to clock out
14243 			 * new segments.  This is required by the ECN spec.
14244 			 */
14245 			if (npkt == 0) {
14246 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14247 				/*
14248 				 * This makes sure that when the ACK comes
14249 				 * back, we will increase tcp_cwnd by 1 MSS.
14250 				 */
14251 				tcp->tcp_cwnd_cnt = 0;
14252 			}
14253 			tcp->tcp_cwr = B_TRUE;
14254 			/*
14255 			 * This marks the end of the current window of in
14256 			 * flight data.  That is why we don't use
14257 			 * tcp_suna + tcp_swnd.  Only data in flight can
14258 			 * provide ECN info.
14259 			 */
14260 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14261 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14262 		}
14263 	}
14264 
14265 	mp1 = tcp->tcp_xmit_head;
14266 	if (bytes_acked == 0) {
14267 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14268 			int dupack_cnt;
14269 
14270 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14271 			/*
14272 			 * Fast retransmit.  When we have seen exactly three
14273 			 * identical ACKs while we have unacked data
14274 			 * outstanding we take it as a hint that our peer
14275 			 * dropped something.
14276 			 *
14277 			 * If TCP is retransmitting, don't do fast retransmit.
14278 			 */
14279 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14280 			    ! tcp->tcp_rexmit) {
14281 				/* Do Limited Transmit */
14282 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14283 				    tcps->tcps_dupack_fast_retransmit) {
14284 					/*
14285 					 * RFC 3042
14286 					 *
14287 					 * What we need to do is temporarily
14288 					 * increase tcp_cwnd so that new
14289 					 * data can be sent if it is allowed
14290 					 * by the receive window (tcp_rwnd).
14291 					 * tcp_wput_data() will take care of
14292 					 * the rest.
14293 					 *
14294 					 * If the connection is SACK capable,
14295 					 * only do limited xmit when there
14296 					 * is SACK info.
14297 					 *
14298 					 * Note how tcp_cwnd is incremented.
14299 					 * The first dup ACK will increase
14300 					 * it by 1 MSS.  The second dup ACK
14301 					 * will increase it by 2 MSS.  This
14302 					 * means that only 1 new segment will
14303 					 * be sent for each dup ACK.
14304 					 */
14305 					if (tcp->tcp_unsent > 0 &&
14306 					    (!tcp->tcp_snd_sack_ok ||
14307 					    (tcp->tcp_snd_sack_ok &&
14308 					    tcp->tcp_notsack_list != NULL))) {
14309 						tcp->tcp_cwnd += mss <<
14310 						    (tcp->tcp_dupack_cnt - 1);
14311 						flags |= TH_LIMIT_XMIT;
14312 					}
14313 				} else if (dupack_cnt ==
14314 				    tcps->tcps_dupack_fast_retransmit) {
14315 
14316 				/*
14317 				 * If we have reduced tcp_ssthresh
14318 				 * because of ECN, do not reduce it again
14319 				 * unless it is already one window of data
14320 				 * away.  After one window of data, tcp_cwr
14321 				 * should then be cleared.  Note that
14322 				 * for non ECN capable connection, tcp_cwr
14323 				 * should always be false.
14324 				 *
14325 				 * Adjust cwnd since the duplicate
14326 				 * ack indicates that a packet was
14327 				 * dropped (due to congestion.)
14328 				 */
14329 				if (!tcp->tcp_cwr) {
14330 					npkt = ((tcp->tcp_snxt -
14331 					    tcp->tcp_suna) >> 1) / mss;
14332 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14333 					    mss;
14334 					tcp->tcp_cwnd = (npkt +
14335 					    tcp->tcp_dupack_cnt) * mss;
14336 				}
14337 				if (tcp->tcp_ecn_ok) {
14338 					tcp->tcp_cwr = B_TRUE;
14339 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14340 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14341 				}
14342 
14343 				/*
14344 				 * We do Hoe's algorithm.  Refer to her
14345 				 * paper "Improving the Start-up Behavior
14346 				 * of a Congestion Control Scheme for TCP,"
14347 				 * appeared in SIGCOMM'96.
14348 				 *
14349 				 * Save highest seq no we have sent so far.
14350 				 * Be careful about the invisible FIN byte.
14351 				 */
14352 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14353 				    (tcp->tcp_unsent == 0)) {
14354 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14355 				} else {
14356 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14357 				}
14358 
14359 				/*
14360 				 * Do not allow bursty traffic during.
14361 				 * fast recovery.  Refer to Fall and Floyd's
14362 				 * paper "Simulation-based Comparisons of
14363 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14364 				 * This is a best current practise.
14365 				 */
14366 				tcp->tcp_snd_burst = TCP_CWND_SS;
14367 
14368 				/*
14369 				 * For SACK:
14370 				 * Calculate tcp_pipe, which is the
14371 				 * estimated number of bytes in
14372 				 * network.
14373 				 *
14374 				 * tcp_fack is the highest sack'ed seq num
14375 				 * TCP has received.
14376 				 *
14377 				 * tcp_pipe is explained in the above quoted
14378 				 * Fall and Floyd's paper.  tcp_fack is
14379 				 * explained in Mathis and Mahdavi's
14380 				 * "Forward Acknowledgment: Refining TCP
14381 				 * Congestion Control" in SIGCOMM '96.
14382 				 */
14383 				if (tcp->tcp_snd_sack_ok) {
14384 					ASSERT(tcp->tcp_sack_info != NULL);
14385 					if (tcp->tcp_notsack_list != NULL) {
14386 						tcp->tcp_pipe = tcp->tcp_snxt -
14387 						    tcp->tcp_fack;
14388 						tcp->tcp_sack_snxt = seg_ack;
14389 						flags |= TH_NEED_SACK_REXMIT;
14390 					} else {
14391 						/*
14392 						 * Always initialize tcp_pipe
14393 						 * even though we don't have
14394 						 * any SACK info.  If later
14395 						 * we get SACK info and
14396 						 * tcp_pipe is not initialized,
14397 						 * funny things will happen.
14398 						 */
14399 						tcp->tcp_pipe =
14400 						    tcp->tcp_cwnd_ssthresh;
14401 					}
14402 				} else {
14403 					flags |= TH_REXMIT_NEEDED;
14404 				} /* tcp_snd_sack_ok */
14405 
14406 				} else {
14407 					/*
14408 					 * Here we perform congestion
14409 					 * avoidance, but NOT slow start.
14410 					 * This is known as the Fast
14411 					 * Recovery Algorithm.
14412 					 */
14413 					if (tcp->tcp_snd_sack_ok &&
14414 					    tcp->tcp_notsack_list != NULL) {
14415 						flags |= TH_NEED_SACK_REXMIT;
14416 						tcp->tcp_pipe -= mss;
14417 						if (tcp->tcp_pipe < 0)
14418 							tcp->tcp_pipe = 0;
14419 					} else {
14420 					/*
14421 					 * We know that one more packet has
14422 					 * left the pipe thus we can update
14423 					 * cwnd.
14424 					 */
14425 					cwnd = tcp->tcp_cwnd + mss;
14426 					if (cwnd > tcp->tcp_cwnd_max)
14427 						cwnd = tcp->tcp_cwnd_max;
14428 					tcp->tcp_cwnd = cwnd;
14429 					if (tcp->tcp_unsent > 0)
14430 						flags |= TH_XMIT_NEEDED;
14431 					}
14432 				}
14433 			}
14434 		} else if (tcp->tcp_zero_win_probe) {
14435 			/*
14436 			 * If the window has opened, need to arrange
14437 			 * to send additional data.
14438 			 */
14439 			if (new_swnd != 0) {
14440 				/* tcp_suna != tcp_snxt */
14441 				/* Packet contains a window update */
14442 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14443 				tcp->tcp_zero_win_probe = 0;
14444 				tcp->tcp_timer_backoff = 0;
14445 				tcp->tcp_ms_we_have_waited = 0;
14446 
14447 				/*
14448 				 * Transmit starting with tcp_suna since
14449 				 * the one byte probe is not ack'ed.
14450 				 * If TCP has sent more than one identical
14451 				 * probe, tcp_rexmit will be set.  That means
14452 				 * tcp_ss_rexmit() will send out the one
14453 				 * byte along with new data.  Otherwise,
14454 				 * fake the retransmission.
14455 				 */
14456 				flags |= TH_XMIT_NEEDED;
14457 				if (!tcp->tcp_rexmit) {
14458 					tcp->tcp_rexmit = B_TRUE;
14459 					tcp->tcp_dupack_cnt = 0;
14460 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14461 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14462 				}
14463 			}
14464 		}
14465 		goto swnd_update;
14466 	}
14467 
14468 	/*
14469 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14470 	 * If the ACK value acks something that we have not yet sent, it might
14471 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14472 	 * other side.
14473 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14474 	 * state is handled above, so we can always just drop the segment and
14475 	 * send an ACK here.
14476 	 *
14477 	 * Should we send ACKs in response to ACK only segments?
14478 	 */
14479 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14480 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14481 		/* drop the received segment */
14482 		freemsg(mp);
14483 
14484 		/*
14485 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14486 		 * greater than 0, check if the number of such
14487 		 * bogus ACks is greater than that count.  If yes,
14488 		 * don't send back any ACK.  This prevents TCP from
14489 		 * getting into an ACK storm if somehow an attacker
14490 		 * successfully spoofs an acceptable segment to our
14491 		 * peer.
14492 		 */
14493 		if (tcp_drop_ack_unsent_cnt > 0 &&
14494 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14495 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14496 			return;
14497 		}
14498 		mp = tcp_ack_mp(tcp);
14499 		if (mp != NULL) {
14500 			BUMP_LOCAL(tcp->tcp_obsegs);
14501 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14502 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14503 		}
14504 		return;
14505 	}
14506 
14507 	/*
14508 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14509 	 * blocks that are covered by this ACK.
14510 	 */
14511 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14512 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14513 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14514 	}
14515 
14516 	/*
14517 	 * If we got an ACK after fast retransmit, check to see
14518 	 * if it is a partial ACK.  If it is not and the congestion
14519 	 * window was inflated to account for the other side's
14520 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14521 	 */
14522 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14523 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14524 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14525 			tcp->tcp_dupack_cnt = 0;
14526 			/*
14527 			 * Restore the orig tcp_cwnd_ssthresh after
14528 			 * fast retransmit phase.
14529 			 */
14530 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14531 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14532 			}
14533 			tcp->tcp_rexmit_max = seg_ack;
14534 			tcp->tcp_cwnd_cnt = 0;
14535 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14536 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14537 
14538 			/*
14539 			 * Remove all notsack info to avoid confusion with
14540 			 * the next fast retrasnmit/recovery phase.
14541 			 */
14542 			if (tcp->tcp_snd_sack_ok &&
14543 			    tcp->tcp_notsack_list != NULL) {
14544 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14545 			}
14546 		} else {
14547 			if (tcp->tcp_snd_sack_ok &&
14548 			    tcp->tcp_notsack_list != NULL) {
14549 				flags |= TH_NEED_SACK_REXMIT;
14550 				tcp->tcp_pipe -= mss;
14551 				if (tcp->tcp_pipe < 0)
14552 					tcp->tcp_pipe = 0;
14553 			} else {
14554 				/*
14555 				 * Hoe's algorithm:
14556 				 *
14557 				 * Retransmit the unack'ed segment and
14558 				 * restart fast recovery.  Note that we
14559 				 * need to scale back tcp_cwnd to the
14560 				 * original value when we started fast
14561 				 * recovery.  This is to prevent overly
14562 				 * aggressive behaviour in sending new
14563 				 * segments.
14564 				 */
14565 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14566 				    tcps->tcps_dupack_fast_retransmit * mss;
14567 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14568 				flags |= TH_REXMIT_NEEDED;
14569 			}
14570 		}
14571 	} else {
14572 		tcp->tcp_dupack_cnt = 0;
14573 		if (tcp->tcp_rexmit) {
14574 			/*
14575 			 * TCP is retranmitting.  If the ACK ack's all
14576 			 * outstanding data, update tcp_rexmit_max and
14577 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14578 			 * to the correct value.
14579 			 *
14580 			 * Note that SEQ_LEQ() is used.  This is to avoid
14581 			 * unnecessary fast retransmit caused by dup ACKs
14582 			 * received when TCP does slow start retransmission
14583 			 * after a time out.  During this phase, TCP may
14584 			 * send out segments which are already received.
14585 			 * This causes dup ACKs to be sent back.
14586 			 */
14587 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14588 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14589 					tcp->tcp_rexmit_nxt = seg_ack;
14590 				}
14591 				if (seg_ack != tcp->tcp_rexmit_max) {
14592 					flags |= TH_XMIT_NEEDED;
14593 				}
14594 			} else {
14595 				tcp->tcp_rexmit = B_FALSE;
14596 				tcp->tcp_xmit_zc_clean = B_FALSE;
14597 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14598 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14599 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14600 			}
14601 			tcp->tcp_ms_we_have_waited = 0;
14602 		}
14603 	}
14604 
14605 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14606 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14607 	tcp->tcp_suna = seg_ack;
14608 	if (tcp->tcp_zero_win_probe != 0) {
14609 		tcp->tcp_zero_win_probe = 0;
14610 		tcp->tcp_timer_backoff = 0;
14611 	}
14612 
14613 	/*
14614 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14615 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14616 	 * will not reach here.
14617 	 */
14618 	if (mp1 == NULL) {
14619 		goto fin_acked;
14620 	}
14621 
14622 	/*
14623 	 * Update the congestion window.
14624 	 *
14625 	 * If TCP is not ECN capable or TCP is ECN capable but the
14626 	 * congestion experience bit is not set, increase the tcp_cwnd as
14627 	 * usual.
14628 	 */
14629 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14630 		cwnd = tcp->tcp_cwnd;
14631 		add = mss;
14632 
14633 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14634 			/*
14635 			 * This is to prevent an increase of less than 1 MSS of
14636 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14637 			 * may send out tinygrams in order to preserve mblk
14638 			 * boundaries.
14639 			 *
14640 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14641 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14642 			 * increased by 1 MSS for every RTTs.
14643 			 */
14644 			if (tcp->tcp_cwnd_cnt <= 0) {
14645 				tcp->tcp_cwnd_cnt = cwnd + add;
14646 			} else {
14647 				tcp->tcp_cwnd_cnt -= add;
14648 				add = 0;
14649 			}
14650 		}
14651 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14652 	}
14653 
14654 	/* See if the latest urgent data has been acknowledged */
14655 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14656 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14657 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14658 
14659 	/* Can we update the RTT estimates? */
14660 	if (tcp->tcp_snd_ts_ok) {
14661 		/* Ignore zero timestamp echo-reply. */
14662 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14663 			tcp_set_rto(tcp, (int32_t)lbolt -
14664 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14665 		}
14666 
14667 		/* If needed, restart the timer. */
14668 		if (tcp->tcp_set_timer == 1) {
14669 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14670 			tcp->tcp_set_timer = 0;
14671 		}
14672 		/*
14673 		 * Update tcp_csuna in case the other side stops sending
14674 		 * us timestamps.
14675 		 */
14676 		tcp->tcp_csuna = tcp->tcp_snxt;
14677 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14678 		/*
14679 		 * An ACK sequence we haven't seen before, so get the RTT
14680 		 * and update the RTO. But first check if the timestamp is
14681 		 * valid to use.
14682 		 */
14683 		if ((mp1->b_next != NULL) &&
14684 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14685 			tcp_set_rto(tcp, (int32_t)lbolt -
14686 			    (int32_t)(intptr_t)mp1->b_prev);
14687 		else
14688 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14689 
14690 		/* Remeber the last sequence to be ACKed */
14691 		tcp->tcp_csuna = seg_ack;
14692 		if (tcp->tcp_set_timer == 1) {
14693 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14694 			tcp->tcp_set_timer = 0;
14695 		}
14696 	} else {
14697 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14698 	}
14699 
14700 	/* Eat acknowledged bytes off the xmit queue. */
14701 	for (;;) {
14702 		mblk_t	*mp2;
14703 		uchar_t	*wptr;
14704 
14705 		wptr = mp1->b_wptr;
14706 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14707 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14708 		if (bytes_acked < 0) {
14709 			mp1->b_rptr = wptr + bytes_acked;
14710 			/*
14711 			 * Set a new timestamp if all the bytes timed by the
14712 			 * old timestamp have been ack'ed.
14713 			 */
14714 			if (SEQ_GT(seg_ack,
14715 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14716 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14717 				mp1->b_next = NULL;
14718 			}
14719 			break;
14720 		}
14721 		mp1->b_next = NULL;
14722 		mp1->b_prev = NULL;
14723 		mp2 = mp1;
14724 		mp1 = mp1->b_cont;
14725 
14726 		/*
14727 		 * This notification is required for some zero-copy
14728 		 * clients to maintain a copy semantic. After the data
14729 		 * is ack'ed, client is safe to modify or reuse the buffer.
14730 		 */
14731 		if (tcp->tcp_snd_zcopy_aware &&
14732 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14733 			tcp_zcopy_notify(tcp);
14734 		freeb(mp2);
14735 		if (bytes_acked == 0) {
14736 			if (mp1 == NULL) {
14737 				/* Everything is ack'ed, clear the tail. */
14738 				tcp->tcp_xmit_tail = NULL;
14739 				/*
14740 				 * Cancel the timer unless we are still
14741 				 * waiting for an ACK for the FIN packet.
14742 				 */
14743 				if (tcp->tcp_timer_tid != 0 &&
14744 				    tcp->tcp_snxt == tcp->tcp_suna) {
14745 					(void) TCP_TIMER_CANCEL(tcp,
14746 					    tcp->tcp_timer_tid);
14747 					tcp->tcp_timer_tid = 0;
14748 				}
14749 				goto pre_swnd_update;
14750 			}
14751 			if (mp2 != tcp->tcp_xmit_tail)
14752 				break;
14753 			tcp->tcp_xmit_tail = mp1;
14754 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14755 			    (uintptr_t)INT_MAX);
14756 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14757 			    mp1->b_rptr);
14758 			break;
14759 		}
14760 		if (mp1 == NULL) {
14761 			/*
14762 			 * More was acked but there is nothing more
14763 			 * outstanding.  This means that the FIN was
14764 			 * just acked or that we're talking to a clown.
14765 			 */
14766 fin_acked:
14767 			ASSERT(tcp->tcp_fin_sent);
14768 			tcp->tcp_xmit_tail = NULL;
14769 			if (tcp->tcp_fin_sent) {
14770 				/* FIN was acked - making progress */
14771 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14772 				    !tcp->tcp_fin_acked)
14773 					tcp->tcp_ip_forward_progress = B_TRUE;
14774 				tcp->tcp_fin_acked = B_TRUE;
14775 				if (tcp->tcp_linger_tid != 0 &&
14776 				    TCP_TIMER_CANCEL(tcp,
14777 				    tcp->tcp_linger_tid) >= 0) {
14778 					tcp_stop_lingering(tcp);
14779 					freemsg(mp);
14780 					mp = NULL;
14781 				}
14782 			} else {
14783 				/*
14784 				 * We should never get here because
14785 				 * we have already checked that the
14786 				 * number of bytes ack'ed should be
14787 				 * smaller than or equal to what we
14788 				 * have sent so far (it is the
14789 				 * acceptability check of the ACK).
14790 				 * We can only get here if the send
14791 				 * queue is corrupted.
14792 				 *
14793 				 * Terminate the connection and
14794 				 * panic the system.  It is better
14795 				 * for us to panic instead of
14796 				 * continuing to avoid other disaster.
14797 				 */
14798 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14799 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14800 				panic("Memory corruption "
14801 				    "detected for connection %s.",
14802 				    tcp_display(tcp, NULL,
14803 				    DISP_ADDR_AND_PORT));
14804 				/*NOTREACHED*/
14805 			}
14806 			goto pre_swnd_update;
14807 		}
14808 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14809 	}
14810 	if (tcp->tcp_unsent) {
14811 		flags |= TH_XMIT_NEEDED;
14812 	}
14813 pre_swnd_update:
14814 	tcp->tcp_xmit_head = mp1;
14815 swnd_update:
14816 	/*
14817 	 * The following check is different from most other implementations.
14818 	 * For bi-directional transfer, when segments are dropped, the
14819 	 * "normal" check will not accept a window update in those
14820 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14821 	 * segments which are outside receiver's window.  As TCP accepts
14822 	 * the ack in those retransmitted segments, if the window update in
14823 	 * the same segment is not accepted, TCP will incorrectly calculates
14824 	 * that it can send more segments.  This can create a deadlock
14825 	 * with the receiver if its window becomes zero.
14826 	 */
14827 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14828 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14829 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14830 		/*
14831 		 * The criteria for update is:
14832 		 *
14833 		 * 1. the segment acknowledges some data.  Or
14834 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14835 		 * 3. the segment is not old and the advertised window is
14836 		 * larger than the previous advertised window.
14837 		 */
14838 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14839 			flags |= TH_XMIT_NEEDED;
14840 		tcp->tcp_swnd = new_swnd;
14841 		if (new_swnd > tcp->tcp_max_swnd)
14842 			tcp->tcp_max_swnd = new_swnd;
14843 		tcp->tcp_swl1 = seg_seq;
14844 		tcp->tcp_swl2 = seg_ack;
14845 	}
14846 est:
14847 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14848 
14849 		switch (tcp->tcp_state) {
14850 		case TCPS_FIN_WAIT_1:
14851 			if (tcp->tcp_fin_acked) {
14852 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14853 				/*
14854 				 * We implement the non-standard BSD/SunOS
14855 				 * FIN_WAIT_2 flushing algorithm.
14856 				 * If there is no user attached to this
14857 				 * TCP endpoint, then this TCP struct
14858 				 * could hang around forever in FIN_WAIT_2
14859 				 * state if the peer forgets to send us
14860 				 * a FIN.  To prevent this, we wait only
14861 				 * 2*MSL (a convenient time value) for
14862 				 * the FIN to arrive.  If it doesn't show up,
14863 				 * we flush the TCP endpoint.  This algorithm,
14864 				 * though a violation of RFC-793, has worked
14865 				 * for over 10 years in BSD systems.
14866 				 * Note: SunOS 4.x waits 675 seconds before
14867 				 * flushing the FIN_WAIT_2 connection.
14868 				 */
14869 				TCP_TIMER_RESTART(tcp,
14870 				    tcps->tcps_fin_wait_2_flush_interval);
14871 			}
14872 			break;
14873 		case TCPS_FIN_WAIT_2:
14874 			break;	/* Shutdown hook? */
14875 		case TCPS_LAST_ACK:
14876 			freemsg(mp);
14877 			if (tcp->tcp_fin_acked) {
14878 				(void) tcp_clean_death(tcp, 0, 19);
14879 				return;
14880 			}
14881 			goto xmit_check;
14882 		case TCPS_CLOSING:
14883 			if (tcp->tcp_fin_acked) {
14884 				tcp->tcp_state = TCPS_TIME_WAIT;
14885 				/*
14886 				 * Unconditionally clear the exclusive binding
14887 				 * bit so this TIME-WAIT connection won't
14888 				 * interfere with new ones.
14889 				 */
14890 				tcp->tcp_exclbind = 0;
14891 				if (!TCP_IS_DETACHED(tcp)) {
14892 					TCP_TIMER_RESTART(tcp,
14893 					    tcps->tcps_time_wait_interval);
14894 				} else {
14895 					tcp_time_wait_append(tcp);
14896 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14897 				}
14898 			}
14899 			/*FALLTHRU*/
14900 		case TCPS_CLOSE_WAIT:
14901 			freemsg(mp);
14902 			goto xmit_check;
14903 		default:
14904 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14905 			break;
14906 		}
14907 	}
14908 	if (flags & TH_FIN) {
14909 		/* Make sure we ack the fin */
14910 		flags |= TH_ACK_NEEDED;
14911 		if (!tcp->tcp_fin_rcvd) {
14912 			tcp->tcp_fin_rcvd = B_TRUE;
14913 			tcp->tcp_rnxt++;
14914 			tcph = tcp->tcp_tcph;
14915 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14916 
14917 			/*
14918 			 * Generate the ordrel_ind at the end unless we
14919 			 * are an eager guy.
14920 			 * In the eager case tcp_rsrv will do this when run
14921 			 * after tcp_accept is done.
14922 			 */
14923 			if (tcp->tcp_listener == NULL &&
14924 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14925 				flags |= TH_ORDREL_NEEDED;
14926 			switch (tcp->tcp_state) {
14927 			case TCPS_SYN_RCVD:
14928 			case TCPS_ESTABLISHED:
14929 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14930 				/* Keepalive? */
14931 				break;
14932 			case TCPS_FIN_WAIT_1:
14933 				if (!tcp->tcp_fin_acked) {
14934 					tcp->tcp_state = TCPS_CLOSING;
14935 					break;
14936 				}
14937 				/* FALLTHRU */
14938 			case TCPS_FIN_WAIT_2:
14939 				tcp->tcp_state = TCPS_TIME_WAIT;
14940 				/*
14941 				 * Unconditionally clear the exclusive binding
14942 				 * bit so this TIME-WAIT connection won't
14943 				 * interfere with new ones.
14944 				 */
14945 				tcp->tcp_exclbind = 0;
14946 				if (!TCP_IS_DETACHED(tcp)) {
14947 					TCP_TIMER_RESTART(tcp,
14948 					    tcps->tcps_time_wait_interval);
14949 				} else {
14950 					tcp_time_wait_append(tcp);
14951 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14952 				}
14953 				if (seg_len) {
14954 					/*
14955 					 * implies data piggybacked on FIN.
14956 					 * break to handle data.
14957 					 */
14958 					break;
14959 				}
14960 				freemsg(mp);
14961 				goto ack_check;
14962 			}
14963 		}
14964 	}
14965 	if (mp == NULL)
14966 		goto xmit_check;
14967 	if (seg_len == 0) {
14968 		freemsg(mp);
14969 		goto xmit_check;
14970 	}
14971 	if (mp->b_rptr == mp->b_wptr) {
14972 		/*
14973 		 * The header has been consumed, so we remove the
14974 		 * zero-length mblk here.
14975 		 */
14976 		mp1 = mp;
14977 		mp = mp->b_cont;
14978 		freeb(mp1);
14979 	}
14980 update_ack:
14981 	tcph = tcp->tcp_tcph;
14982 	tcp->tcp_rack_cnt++;
14983 	{
14984 		uint32_t cur_max;
14985 
14986 		cur_max = tcp->tcp_rack_cur_max;
14987 		if (tcp->tcp_rack_cnt >= cur_max) {
14988 			/*
14989 			 * We have more unacked data than we should - send
14990 			 * an ACK now.
14991 			 */
14992 			flags |= TH_ACK_NEEDED;
14993 			cur_max++;
14994 			if (cur_max > tcp->tcp_rack_abs_max)
14995 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14996 			else
14997 				tcp->tcp_rack_cur_max = cur_max;
14998 		} else if (TCP_IS_DETACHED(tcp)) {
14999 			/* We don't have an ACK timer for detached TCP. */
15000 			flags |= TH_ACK_NEEDED;
15001 		} else if (seg_len < mss) {
15002 			/*
15003 			 * If we get a segment that is less than an mss, and we
15004 			 * already have unacknowledged data, and the amount
15005 			 * unacknowledged is not a multiple of mss, then we
15006 			 * better generate an ACK now.  Otherwise, this may be
15007 			 * the tail piece of a transaction, and we would rather
15008 			 * wait for the response.
15009 			 */
15010 			uint32_t udif;
15011 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
15012 			    (uintptr_t)INT_MAX);
15013 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
15014 			if (udif && (udif % mss))
15015 				flags |= TH_ACK_NEEDED;
15016 			else
15017 				flags |= TH_ACK_TIMER_NEEDED;
15018 		} else {
15019 			/* Start delayed ack timer */
15020 			flags |= TH_ACK_TIMER_NEEDED;
15021 		}
15022 	}
15023 	tcp->tcp_rnxt += seg_len;
15024 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15025 
15026 	if (mp == NULL)
15027 		goto xmit_check;
15028 
15029 	/* Update SACK list */
15030 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15031 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15032 		    &(tcp->tcp_num_sack_blk));
15033 	}
15034 
15035 	if (tcp->tcp_urp_mp) {
15036 		tcp->tcp_urp_mp->b_cont = mp;
15037 		mp = tcp->tcp_urp_mp;
15038 		tcp->tcp_urp_mp = NULL;
15039 		/* Ready for a new signal. */
15040 		tcp->tcp_urp_last_valid = B_FALSE;
15041 #ifdef DEBUG
15042 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15043 		    "tcp_rput: sending exdata_ind %s",
15044 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15045 #endif /* DEBUG */
15046 	}
15047 
15048 	/*
15049 	 * Check for ancillary data changes compared to last segment.
15050 	 */
15051 	if (tcp->tcp_ipv6_recvancillary != 0) {
15052 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15053 		ASSERT(mp != NULL);
15054 	}
15055 
15056 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15057 		/*
15058 		 * Side queue inbound data until the accept happens.
15059 		 * tcp_accept/tcp_rput drains this when the accept happens.
15060 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15061 		 * T_EXDATA_IND) it is queued on b_next.
15062 		 * XXX Make urgent data use this. Requires:
15063 		 *	Removing tcp_listener check for TH_URG
15064 		 *	Making M_PCPROTO and MARK messages skip the eager case
15065 		 */
15066 
15067 		if (tcp->tcp_kssl_pending) {
15068 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
15069 			    mblk_t *, mp);
15070 			tcp_kssl_input(tcp, mp);
15071 		} else {
15072 			tcp_rcv_enqueue(tcp, mp, seg_len);
15073 		}
15074 	} else {
15075 		sodirect_t	*sodp = tcp->tcp_sodirect;
15076 
15077 		/*
15078 		 * If an sodirect connection and an enabled sodirect_t then
15079 		 * sodp will be set to point to the tcp_t/sonode_t shared
15080 		 * sodirect_t and the sodirect_t's lock will be held.
15081 		 */
15082 		if (sodp != NULL) {
15083 			mutex_enter(sodp->sod_lockp);
15084 			if (!(sodp->sod_state & SOD_ENABLED) ||
15085 			    (tcp->tcp_kssl_ctx != NULL &&
15086 			    DB_TYPE(mp) == M_DATA)) {
15087 				sodp = NULL;
15088 			}
15089 			mutex_exit(sodp->sod_lockp);
15090 		}
15091 		if (mp->b_datap->db_type != M_DATA ||
15092 		    (flags & TH_MARKNEXT_NEEDED)) {
15093 			if (IPCL_IS_NONSTR(connp)) {
15094 				int error;
15095 
15096 				if ((*connp->conn_upcalls->su_recv)
15097 				    (connp->conn_upper_handle, mp,
15098 				    seg_len, 0, &error, NULL) <= 0) {
15099 					if (error == ENOSPC) {
15100 						tcp->tcp_rwnd -= seg_len;
15101 					} else if (error == EOPNOTSUPP) {
15102 						tcp_rcv_enqueue(tcp, mp,
15103 						    seg_len);
15104 					}
15105 				}
15106 			} else if (sodp != NULL) {
15107 				mutex_enter(sodp->sod_lockp);
15108 				SOD_UIOAFINI(sodp);
15109 				if (!SOD_QEMPTY(sodp) &&
15110 				    (sodp->sod_state & SOD_WAKE_NOT)) {
15111 					flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15112 					/* sod_wakeup() did the mutex_exit() */
15113 				} else {
15114 					mutex_exit(sodp->sod_lockp);
15115 				}
15116 			} else if (tcp->tcp_rcv_list != NULL) {
15117 				flags |= tcp_rcv_drain(tcp);
15118 			}
15119 			ASSERT(tcp->tcp_rcv_list == NULL ||
15120 			    tcp->tcp_fused_sigurg);
15121 
15122 			if (flags & TH_MARKNEXT_NEEDED) {
15123 #ifdef DEBUG
15124 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15125 				    "tcp_rput: sending MSGMARKNEXT %s",
15126 				    tcp_display(tcp, NULL,
15127 				    DISP_PORT_ONLY));
15128 #endif /* DEBUG */
15129 				mp->b_flag |= MSGMARKNEXT;
15130 				flags &= ~TH_MARKNEXT_NEEDED;
15131 			}
15132 
15133 			/* Does this need SSL processing first? */
15134 			if ((tcp->tcp_kssl_ctx != NULL) &&
15135 			    (DB_TYPE(mp) == M_DATA)) {
15136 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15137 				    mblk_t *, mp);
15138 				tcp_kssl_input(tcp, mp);
15139 			} else if (!IPCL_IS_NONSTR(connp)) {
15140 				/* Already handled non-STREAMS case. */
15141 				putnext(tcp->tcp_rq, mp);
15142 				if (!canputnext(tcp->tcp_rq))
15143 					tcp->tcp_rwnd -= seg_len;
15144 			}
15145 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15146 		    (DB_TYPE(mp) == M_DATA)) {
15147 			/* Does this need SSL processing first? */
15148 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
15149 			tcp_kssl_input(tcp, mp);
15150 		} else if (IPCL_IS_NONSTR(connp)) {
15151 			/* Non-STREAMS socket */
15152 			boolean_t push = flags & (TH_PUSH|TH_FIN);
15153 			int	error;
15154 
15155 			if ((*connp->conn_upcalls->su_recv)(
15156 			    connp->conn_upper_handle,
15157 			    mp, seg_len, 0, &error, &push) <= 0) {
15158 				if (error == ENOSPC) {
15159 					tcp->tcp_rwnd -= seg_len;
15160 				} else if (error == EOPNOTSUPP) {
15161 					tcp_rcv_enqueue(tcp, mp, seg_len);
15162 				}
15163 			} else if (push) {
15164 				/*
15165 				 * PUSH bit set and sockfs is not
15166 				 * flow controlled
15167 				 */
15168 				flags |= tcp_rwnd_reopen(tcp);
15169 			}
15170 		} else if (sodp != NULL) {
15171 			/*
15172 			 * Sodirect so all mblk_t's are queued on the
15173 			 * socket directly, check for wakeup of blocked
15174 			 * reader (if any), and last if flow-controled.
15175 			 */
15176 			mutex_enter(sodp->sod_lockp);
15177 			flags |= tcp_rcv_sod_enqueue(tcp, sodp, mp, seg_len);
15178 			if ((sodp->sod_state & SOD_WAKE_NEED) ||
15179 			    (flags & (TH_PUSH|TH_FIN))) {
15180 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15181 				/* sod_wakeup() did the mutex_exit() */
15182 			} else {
15183 				if (SOD_QFULL(sodp)) {
15184 					/* Q is full, need backenable */
15185 					SOD_QSETBE(sodp);
15186 				}
15187 				mutex_exit(sodp->sod_lockp);
15188 			}
15189 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15190 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_recv_hiwater >> 3) {
15191 			if (tcp->tcp_rcv_list != NULL) {
15192 				/*
15193 				 * Enqueue the new segment first and then
15194 				 * call tcp_rcv_drain() to send all data
15195 				 * up.  The other way to do this is to
15196 				 * send all queued data up and then call
15197 				 * putnext() to send the new segment up.
15198 				 * This way can remove the else part later
15199 				 * on.
15200 				 *
15201 				 * We don't do this to avoid one more call to
15202 				 * canputnext() as tcp_rcv_drain() needs to
15203 				 * call canputnext().
15204 				 */
15205 				tcp_rcv_enqueue(tcp, mp, seg_len);
15206 				flags |= tcp_rcv_drain(tcp);
15207 			} else {
15208 				putnext(tcp->tcp_rq, mp);
15209 				if (!canputnext(tcp->tcp_rq))
15210 					tcp->tcp_rwnd -= seg_len;
15211 			}
15212 		} else {
15213 			/*
15214 			 * Enqueue all packets when processing an mblk
15215 			 * from the co queue and also enqueue normal packets.
15216 			 * For packets which belong to SSL stream do SSL
15217 			 * processing first.
15218 			 */
15219 			tcp_rcv_enqueue(tcp, mp, seg_len);
15220 		}
15221 		/*
15222 		 * Make sure the timer is running if we have data waiting
15223 		 * for a push bit. This provides resiliency against
15224 		 * implementations that do not correctly generate push bits.
15225 		 *
15226 		 * Note, for sodirect if Q isn't empty and there's not a
15227 		 * pending wakeup then we need a timer. Also note that sodp
15228 		 * is assumed to be still valid after exit()ing the sod_lockp
15229 		 * above and while the SOD state can change it can only change
15230 		 * such that the Q is empty now even though data was added
15231 		 * above.
15232 		 */
15233 		if (!IPCL_IS_NONSTR(connp) &&
15234 		    ((sodp != NULL && !SOD_QEMPTY(sodp) &&
15235 		    (sodp->sod_state & SOD_WAKE_NOT)) ||
15236 		    (sodp == NULL && tcp->tcp_rcv_list != NULL)) &&
15237 		    tcp->tcp_push_tid == 0) {
15238 			/*
15239 			 * The connection may be closed at this point, so don't
15240 			 * do anything for a detached tcp.
15241 			 */
15242 			if (!TCP_IS_DETACHED(tcp))
15243 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15244 				    tcp_push_timer,
15245 				    MSEC_TO_TICK(
15246 				    tcps->tcps_push_timer_interval));
15247 		}
15248 	}
15249 
15250 xmit_check:
15251 	/* Is there anything left to do? */
15252 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15253 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15254 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15255 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15256 		goto done;
15257 
15258 	/* Any transmit work to do and a non-zero window? */
15259 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15260 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15261 		if (flags & TH_REXMIT_NEEDED) {
15262 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15263 
15264 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15265 			if (snd_size > mss)
15266 				snd_size = mss;
15267 			if (snd_size > tcp->tcp_swnd)
15268 				snd_size = tcp->tcp_swnd;
15269 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15270 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15271 			    B_TRUE);
15272 
15273 			if (mp1 != NULL) {
15274 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15275 				tcp->tcp_csuna = tcp->tcp_snxt;
15276 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15277 				UPDATE_MIB(&tcps->tcps_mib,
15278 				    tcpRetransBytes, snd_size);
15279 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15280 			}
15281 		}
15282 		if (flags & TH_NEED_SACK_REXMIT) {
15283 			tcp_sack_rxmit(tcp, &flags);
15284 		}
15285 		/*
15286 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15287 		 * out new segment.  Note that tcp_rexmit should not be
15288 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15289 		 */
15290 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15291 			if (!tcp->tcp_rexmit) {
15292 				tcp_wput_data(tcp, NULL, B_FALSE);
15293 			} else {
15294 				tcp_ss_rexmit(tcp);
15295 			}
15296 		}
15297 		/*
15298 		 * Adjust tcp_cwnd back to normal value after sending
15299 		 * new data segments.
15300 		 */
15301 		if (flags & TH_LIMIT_XMIT) {
15302 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15303 			/*
15304 			 * This will restart the timer.  Restarting the
15305 			 * timer is used to avoid a timeout before the
15306 			 * limited transmitted segment's ACK gets back.
15307 			 */
15308 			if (tcp->tcp_xmit_head != NULL)
15309 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15310 		}
15311 
15312 		/* Anything more to do? */
15313 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15314 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15315 			goto done;
15316 	}
15317 ack_check:
15318 	if (flags & TH_SEND_URP_MARK) {
15319 		ASSERT(tcp->tcp_urp_mark_mp);
15320 		ASSERT(!IPCL_IS_NONSTR(connp));
15321 		/*
15322 		 * Send up any queued data and then send the mark message
15323 		 */
15324 		sodirect_t *sodp;
15325 
15326 		SOD_PTR_ENTER(tcp, sodp);
15327 
15328 		mp1 = tcp->tcp_urp_mark_mp;
15329 		tcp->tcp_urp_mark_mp = NULL;
15330 		if (sodp != NULL) {
15331 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15332 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15333 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15334 			}
15335 			ASSERT(tcp->tcp_rcv_list == NULL);
15336 
15337 			flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15338 			/* sod_wakeup() does the mutex_exit() */
15339 		} else if (tcp->tcp_rcv_list != NULL) {
15340 			flags |= tcp_rcv_drain(tcp);
15341 
15342 			ASSERT(tcp->tcp_rcv_list == NULL ||
15343 			    tcp->tcp_fused_sigurg);
15344 
15345 		}
15346 		putnext(tcp->tcp_rq, mp1);
15347 #ifdef DEBUG
15348 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15349 		    "tcp_rput: sending zero-length %s %s",
15350 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15351 		    "MSGNOTMARKNEXT"),
15352 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15353 #endif /* DEBUG */
15354 		flags &= ~TH_SEND_URP_MARK;
15355 	}
15356 	if (flags & TH_ACK_NEEDED) {
15357 		/*
15358 		 * Time to send an ack for some reason.
15359 		 */
15360 		mp1 = tcp_ack_mp(tcp);
15361 
15362 		if (mp1 != NULL) {
15363 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15364 			BUMP_LOCAL(tcp->tcp_obsegs);
15365 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15366 		}
15367 		if (tcp->tcp_ack_tid != 0) {
15368 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15369 			tcp->tcp_ack_tid = 0;
15370 		}
15371 	}
15372 	if (flags & TH_ACK_TIMER_NEEDED) {
15373 		/*
15374 		 * Arrange for deferred ACK or push wait timeout.
15375 		 * Start timer if it is not already running.
15376 		 */
15377 		if (tcp->tcp_ack_tid == 0) {
15378 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15379 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15380 			    (clock_t)tcps->tcps_local_dack_interval :
15381 			    (clock_t)tcps->tcps_deferred_ack_interval));
15382 		}
15383 	}
15384 	if (flags & TH_ORDREL_NEEDED) {
15385 		/*
15386 		 * Send up the ordrel_ind unless we are an eager guy.
15387 		 * In the eager case tcp_rsrv will do this when run
15388 		 * after tcp_accept is done.
15389 		 */
15390 		sodirect_t *sodp;
15391 
15392 		ASSERT(tcp->tcp_listener == NULL);
15393 
15394 		if (IPCL_IS_NONSTR(connp)) {
15395 			ASSERT(tcp->tcp_ordrel_mp == NULL);
15396 			tcp->tcp_ordrel_done = B_TRUE;
15397 			(*connp->conn_upcalls->su_opctl)
15398 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
15399 			goto done;
15400 		}
15401 
15402 		SOD_PTR_ENTER(tcp, sodp);
15403 		if (sodp != NULL) {
15404 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15405 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15406 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15407 			}
15408 			/* No more sodirect */
15409 			tcp->tcp_sodirect = NULL;
15410 			if (!SOD_QEMPTY(sodp)) {
15411 				/* Mblk(s) to process, notify */
15412 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15413 				/* sod_wakeup() does the mutex_exit() */
15414 			} else {
15415 				/* Nothing to process */
15416 				mutex_exit(sodp->sod_lockp);
15417 			}
15418 		} else if (tcp->tcp_rcv_list != NULL) {
15419 			/*
15420 			 * Push any mblk(s) enqueued from co processing.
15421 			 */
15422 			flags |= tcp_rcv_drain(tcp);
15423 
15424 			ASSERT(tcp->tcp_rcv_list == NULL ||
15425 			    tcp->tcp_fused_sigurg);
15426 		}
15427 
15428 		mp1 = tcp->tcp_ordrel_mp;
15429 		tcp->tcp_ordrel_mp = NULL;
15430 		tcp->tcp_ordrel_done = B_TRUE;
15431 		putnext(tcp->tcp_rq, mp1);
15432 	}
15433 done:
15434 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15435 }
15436 
15437 /*
15438  * This function does PAWS protection check. Returns B_TRUE if the
15439  * segment passes the PAWS test, else returns B_FALSE.
15440  */
15441 boolean_t
15442 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15443 {
15444 	uint8_t	flags;
15445 	int	options;
15446 	uint8_t *up;
15447 
15448 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15449 	/*
15450 	 * If timestamp option is aligned nicely, get values inline,
15451 	 * otherwise call general routine to parse.  Only do that
15452 	 * if timestamp is the only option.
15453 	 */
15454 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15455 	    TCPOPT_REAL_TS_LEN &&
15456 	    OK_32PTR((up = ((uint8_t *)tcph) +
15457 	    TCP_MIN_HEADER_LENGTH)) &&
15458 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15459 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15460 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15461 
15462 		options = TCP_OPT_TSTAMP_PRESENT;
15463 	} else {
15464 		if (tcp->tcp_snd_sack_ok) {
15465 			tcpoptp->tcp = tcp;
15466 		} else {
15467 			tcpoptp->tcp = NULL;
15468 		}
15469 		options = tcp_parse_options(tcph, tcpoptp);
15470 	}
15471 
15472 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15473 		/*
15474 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15475 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15476 		 */
15477 		if ((flags & TH_RST) == 0 &&
15478 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15479 		    tcp->tcp_ts_recent)) {
15480 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15481 			    PAWS_TIMEOUT)) {
15482 				/* This segment is not acceptable. */
15483 				return (B_FALSE);
15484 			} else {
15485 				/*
15486 				 * Connection has been idle for
15487 				 * too long.  Reset the timestamp
15488 				 * and assume the segment is valid.
15489 				 */
15490 				tcp->tcp_ts_recent =
15491 				    tcpoptp->tcp_opt_ts_val;
15492 			}
15493 		}
15494 	} else {
15495 		/*
15496 		 * If we don't get a timestamp on every packet, we
15497 		 * figure we can't really trust 'em, so we stop sending
15498 		 * and parsing them.
15499 		 */
15500 		tcp->tcp_snd_ts_ok = B_FALSE;
15501 
15502 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15503 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15504 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15505 		/*
15506 		 * Adjust the tcp_mss accordingly. We also need to
15507 		 * adjust tcp_cwnd here in accordance with the new mss.
15508 		 * But we avoid doing a slow start here so as to not
15509 		 * to lose on the transfer rate built up so far.
15510 		 */
15511 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15512 		if (tcp->tcp_snd_sack_ok) {
15513 			ASSERT(tcp->tcp_sack_info != NULL);
15514 			tcp->tcp_max_sack_blk = 4;
15515 		}
15516 	}
15517 	return (B_TRUE);
15518 }
15519 
15520 /*
15521  * Attach ancillary data to a received TCP segments for the
15522  * ancillary pieces requested by the application that are
15523  * different than they were in the previous data segment.
15524  *
15525  * Save the "current" values once memory allocation is ok so that
15526  * when memory allocation fails we can just wait for the next data segment.
15527  */
15528 static mblk_t *
15529 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15530 {
15531 	struct T_optdata_ind *todi;
15532 	int optlen;
15533 	uchar_t *optptr;
15534 	struct T_opthdr *toh;
15535 	uint_t addflag;	/* Which pieces to add */
15536 	mblk_t *mp1;
15537 
15538 	optlen = 0;
15539 	addflag = 0;
15540 	/* If app asked for pktinfo and the index has changed ... */
15541 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15542 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15543 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15544 		optlen += sizeof (struct T_opthdr) +
15545 		    sizeof (struct in6_pktinfo);
15546 		addflag |= TCP_IPV6_RECVPKTINFO;
15547 	}
15548 	/* If app asked for hoplimit and it has changed ... */
15549 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15550 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15551 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15552 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15553 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15554 	}
15555 	/* If app asked for tclass and it has changed ... */
15556 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15557 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15558 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15559 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15560 		addflag |= TCP_IPV6_RECVTCLASS;
15561 	}
15562 	/*
15563 	 * If app asked for hopbyhop headers and it has changed ...
15564 	 * For security labels, note that (1) security labels can't change on
15565 	 * a connected socket at all, (2) we're connected to at most one peer,
15566 	 * (3) if anything changes, then it must be some other extra option.
15567 	 */
15568 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15569 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15570 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15571 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15572 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15573 		    tcp->tcp_label_len;
15574 		addflag |= TCP_IPV6_RECVHOPOPTS;
15575 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15576 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15577 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15578 			return (mp);
15579 	}
15580 	/* If app asked for dst headers before routing headers ... */
15581 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15582 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15583 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15584 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15585 		optlen += sizeof (struct T_opthdr) +
15586 		    ipp->ipp_rtdstoptslen;
15587 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15588 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15589 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15590 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15591 			return (mp);
15592 	}
15593 	/* If app asked for routing headers and it has changed ... */
15594 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15595 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15596 	    (ipp->ipp_fields & IPPF_RTHDR),
15597 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15598 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15599 		addflag |= TCP_IPV6_RECVRTHDR;
15600 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15601 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15602 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15603 			return (mp);
15604 	}
15605 	/* If app asked for dest headers and it has changed ... */
15606 	if ((tcp->tcp_ipv6_recvancillary &
15607 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15608 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15609 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15610 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15611 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15612 		addflag |= TCP_IPV6_RECVDSTOPTS;
15613 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15614 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15615 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15616 			return (mp);
15617 	}
15618 
15619 	if (optlen == 0) {
15620 		/* Nothing to add */
15621 		return (mp);
15622 	}
15623 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15624 	if (mp1 == NULL) {
15625 		/*
15626 		 * Defer sending ancillary data until the next TCP segment
15627 		 * arrives.
15628 		 */
15629 		return (mp);
15630 	}
15631 	mp1->b_cont = mp;
15632 	mp = mp1;
15633 	mp->b_wptr += sizeof (*todi) + optlen;
15634 	mp->b_datap->db_type = M_PROTO;
15635 	todi = (struct T_optdata_ind *)mp->b_rptr;
15636 	todi->PRIM_type = T_OPTDATA_IND;
15637 	todi->DATA_flag = 1;	/* MORE data */
15638 	todi->OPT_length = optlen;
15639 	todi->OPT_offset = sizeof (*todi);
15640 	optptr = (uchar_t *)&todi[1];
15641 	/*
15642 	 * If app asked for pktinfo and the index has changed ...
15643 	 * Note that the local address never changes for the connection.
15644 	 */
15645 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15646 		struct in6_pktinfo *pkti;
15647 
15648 		toh = (struct T_opthdr *)optptr;
15649 		toh->level = IPPROTO_IPV6;
15650 		toh->name = IPV6_PKTINFO;
15651 		toh->len = sizeof (*toh) + sizeof (*pkti);
15652 		toh->status = 0;
15653 		optptr += sizeof (*toh);
15654 		pkti = (struct in6_pktinfo *)optptr;
15655 		if (tcp->tcp_ipversion == IPV6_VERSION)
15656 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15657 		else
15658 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15659 			    &pkti->ipi6_addr);
15660 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15661 		optptr += sizeof (*pkti);
15662 		ASSERT(OK_32PTR(optptr));
15663 		/* Save as "last" value */
15664 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15665 	}
15666 	/* If app asked for hoplimit and it has changed ... */
15667 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15668 		toh = (struct T_opthdr *)optptr;
15669 		toh->level = IPPROTO_IPV6;
15670 		toh->name = IPV6_HOPLIMIT;
15671 		toh->len = sizeof (*toh) + sizeof (uint_t);
15672 		toh->status = 0;
15673 		optptr += sizeof (*toh);
15674 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15675 		optptr += sizeof (uint_t);
15676 		ASSERT(OK_32PTR(optptr));
15677 		/* Save as "last" value */
15678 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15679 	}
15680 	/* If app asked for tclass and it has changed ... */
15681 	if (addflag & TCP_IPV6_RECVTCLASS) {
15682 		toh = (struct T_opthdr *)optptr;
15683 		toh->level = IPPROTO_IPV6;
15684 		toh->name = IPV6_TCLASS;
15685 		toh->len = sizeof (*toh) + sizeof (uint_t);
15686 		toh->status = 0;
15687 		optptr += sizeof (*toh);
15688 		*(uint_t *)optptr = ipp->ipp_tclass;
15689 		optptr += sizeof (uint_t);
15690 		ASSERT(OK_32PTR(optptr));
15691 		/* Save as "last" value */
15692 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15693 	}
15694 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15695 		toh = (struct T_opthdr *)optptr;
15696 		toh->level = IPPROTO_IPV6;
15697 		toh->name = IPV6_HOPOPTS;
15698 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15699 		    tcp->tcp_label_len;
15700 		toh->status = 0;
15701 		optptr += sizeof (*toh);
15702 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15703 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15704 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15705 		ASSERT(OK_32PTR(optptr));
15706 		/* Save as last value */
15707 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15708 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15709 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15710 	}
15711 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15712 		toh = (struct T_opthdr *)optptr;
15713 		toh->level = IPPROTO_IPV6;
15714 		toh->name = IPV6_RTHDRDSTOPTS;
15715 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15716 		toh->status = 0;
15717 		optptr += sizeof (*toh);
15718 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15719 		optptr += ipp->ipp_rtdstoptslen;
15720 		ASSERT(OK_32PTR(optptr));
15721 		/* Save as last value */
15722 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15723 		    &tcp->tcp_rtdstoptslen,
15724 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15725 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15726 	}
15727 	if (addflag & TCP_IPV6_RECVRTHDR) {
15728 		toh = (struct T_opthdr *)optptr;
15729 		toh->level = IPPROTO_IPV6;
15730 		toh->name = IPV6_RTHDR;
15731 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15732 		toh->status = 0;
15733 		optptr += sizeof (*toh);
15734 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15735 		optptr += ipp->ipp_rthdrlen;
15736 		ASSERT(OK_32PTR(optptr));
15737 		/* Save as last value */
15738 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15739 		    (ipp->ipp_fields & IPPF_RTHDR),
15740 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15741 	}
15742 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15743 		toh = (struct T_opthdr *)optptr;
15744 		toh->level = IPPROTO_IPV6;
15745 		toh->name = IPV6_DSTOPTS;
15746 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15747 		toh->status = 0;
15748 		optptr += sizeof (*toh);
15749 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15750 		optptr += ipp->ipp_dstoptslen;
15751 		ASSERT(OK_32PTR(optptr));
15752 		/* Save as last value */
15753 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15754 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15755 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15756 	}
15757 	ASSERT(optptr == mp->b_wptr);
15758 	return (mp);
15759 }
15760 
15761 /*
15762  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15763  * or a "bad" IRE detected by tcp_adapt_ire.
15764  * We can't tell if the failure was due to the laddr or the faddr
15765  * thus we clear out all addresses and ports.
15766  */
15767 static void
15768 tcp_tpi_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15769 {
15770 	queue_t	*q = tcp->tcp_rq;
15771 	tcph_t	*tcph;
15772 	struct T_error_ack *tea;
15773 	conn_t	*connp = tcp->tcp_connp;
15774 
15775 
15776 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15777 
15778 	if (mp->b_cont) {
15779 		freemsg(mp->b_cont);
15780 		mp->b_cont = NULL;
15781 	}
15782 	tea = (struct T_error_ack *)mp->b_rptr;
15783 	switch (tea->PRIM_type) {
15784 	case T_BIND_ACK:
15785 		/*
15786 		 * Need to unbind with classifier since we were just told that
15787 		 * our bind succeeded.
15788 		 */
15789 		tcp->tcp_hard_bound = B_FALSE;
15790 		tcp->tcp_hard_binding = B_FALSE;
15791 
15792 		ipcl_hash_remove(connp);
15793 		/* Reuse the mblk if possible */
15794 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15795 		    sizeof (*tea));
15796 		mp->b_rptr = mp->b_datap->db_base;
15797 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15798 		tea = (struct T_error_ack *)mp->b_rptr;
15799 		tea->PRIM_type = T_ERROR_ACK;
15800 		tea->TLI_error = TSYSERR;
15801 		tea->UNIX_error = error;
15802 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15803 			tea->ERROR_prim = T_CONN_REQ;
15804 		} else {
15805 			tea->ERROR_prim = O_T_BIND_REQ;
15806 		}
15807 		break;
15808 
15809 	case T_ERROR_ACK:
15810 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15811 			tea->ERROR_prim = T_CONN_REQ;
15812 		break;
15813 	default:
15814 		panic("tcp_tpi_bind_failed: unexpected TPI type");
15815 		/*NOTREACHED*/
15816 	}
15817 
15818 	tcp->tcp_state = TCPS_IDLE;
15819 	if (tcp->tcp_ipversion == IPV4_VERSION)
15820 		tcp->tcp_ipha->ipha_src = 0;
15821 	else
15822 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15823 	/*
15824 	 * Copy of the src addr. in tcp_t is needed since
15825 	 * the lookup funcs. can only look at tcp_t
15826 	 */
15827 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15828 
15829 	tcph = tcp->tcp_tcph;
15830 	tcph->th_lport[0] = 0;
15831 	tcph->th_lport[1] = 0;
15832 	tcp_bind_hash_remove(tcp);
15833 	bzero(&connp->u_port, sizeof (connp->u_port));
15834 	/* blow away saved option results if any */
15835 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15836 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15837 
15838 	conn_delete_ire(tcp->tcp_connp, NULL);
15839 	putnext(q, mp);
15840 }
15841 
15842 /*
15843  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15844  * messages.
15845  */
15846 void
15847 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15848 {
15849 	uchar_t	*rptr = mp->b_rptr;
15850 	queue_t	*q = tcp->tcp_rq;
15851 	struct T_error_ack *tea;
15852 
15853 	switch (mp->b_datap->db_type) {
15854 	case M_PROTO:
15855 	case M_PCPROTO:
15856 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15857 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15858 			break;
15859 		tea = (struct T_error_ack *)rptr;
15860 		switch (tea->PRIM_type) {
15861 		case T_BIND_ACK:
15862 			/*
15863 			 * AF_INET socket should not be here.
15864 			 */
15865 			ASSERT(tcp->tcp_family != AF_INET &&
15866 			    tcp->tcp_family != AF_INET6);
15867 			(void) tcp_post_ip_bind(tcp, mp->b_cont, 0);
15868 			return;
15869 		case T_ERROR_ACK:
15870 			if (tcp->tcp_debug) {
15871 				(void) strlog(TCP_MOD_ID, 0, 1,
15872 				    SL_TRACE|SL_ERROR,
15873 				    "tcp_rput_other: case T_ERROR_ACK, "
15874 				    "ERROR_prim == %d",
15875 				    tea->ERROR_prim);
15876 			}
15877 			switch (tea->ERROR_prim) {
15878 			case O_T_BIND_REQ:
15879 			case T_BIND_REQ:
15880 				ASSERT(tcp->tcp_family != AF_INET);
15881 				tcp_tpi_bind_failed(tcp, mp,
15882 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15883 				    ENETUNREACH : EADDRNOTAVAIL));
15884 				return;
15885 			case T_SVR4_OPTMGMT_REQ:
15886 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15887 					/* T_OPTMGMT_REQ generated by TCP */
15888 					printf("T_SVR4_OPTMGMT_REQ failed "
15889 					    "%d/%d - dropped (cnt %d)\n",
15890 					    tea->TLI_error, tea->UNIX_error,
15891 					    tcp->tcp_drop_opt_ack_cnt);
15892 					freemsg(mp);
15893 					tcp->tcp_drop_opt_ack_cnt--;
15894 					return;
15895 				}
15896 				break;
15897 			}
15898 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15899 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15900 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15901 				    "- dropped (cnt %d)\n",
15902 				    tea->TLI_error, tea->UNIX_error,
15903 				    tcp->tcp_drop_opt_ack_cnt);
15904 				freemsg(mp);
15905 				tcp->tcp_drop_opt_ack_cnt--;
15906 				return;
15907 			}
15908 			break;
15909 		case T_OPTMGMT_ACK:
15910 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15911 				/* T_OPTMGMT_REQ generated by TCP */
15912 				freemsg(mp);
15913 				tcp->tcp_drop_opt_ack_cnt--;
15914 				return;
15915 			}
15916 			break;
15917 		default:
15918 			ASSERT(tea->ERROR_prim != T_UNBIND_REQ);
15919 			break;
15920 		}
15921 		break;
15922 	case M_FLUSH:
15923 		if (*rptr & FLUSHR)
15924 			flushq(q, FLUSHDATA);
15925 		break;
15926 	default:
15927 		/* M_CTL will be directly sent to tcp_icmp_error() */
15928 		ASSERT(DB_TYPE(mp) != M_CTL);
15929 		break;
15930 	}
15931 	/*
15932 	 * Make sure we set this bit before sending the ACK for
15933 	 * bind. Otherwise accept could possibly run and free
15934 	 * this tcp struct.
15935 	 */
15936 	ASSERT(q != NULL);
15937 	putnext(q, mp);
15938 }
15939 
15940 /* ARGSUSED */
15941 static void
15942 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15943 {
15944 	conn_t	*connp = (conn_t *)arg;
15945 	tcp_t	*tcp = connp->conn_tcp;
15946 	queue_t	*q = tcp->tcp_rq;
15947 	uint_t	thwin;
15948 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15949 	sodirect_t	*sodp;
15950 	boolean_t	fc;
15951 
15952 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15953 	tcp->tcp_rsrv_mp = mp;
15954 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15955 
15956 	TCP_STAT(tcps, tcp_rsrv_calls);
15957 
15958 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15959 		return;
15960 	}
15961 
15962 	if (tcp->tcp_fused) {
15963 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15964 
15965 		ASSERT(tcp->tcp_fused);
15966 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15967 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15968 		ASSERT(!TCP_IS_DETACHED(tcp));
15969 		ASSERT(tcp->tcp_connp->conn_sqp ==
15970 		    peer_tcp->tcp_connp->conn_sqp);
15971 
15972 		/*
15973 		 * Normally we would not get backenabled in synchronous
15974 		 * streams mode, but in case this happens, we need to plug
15975 		 * synchronous streams during our drain to prevent a race
15976 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
15977 		 */
15978 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
15979 		if (tcp->tcp_rcv_list != NULL)
15980 			(void) tcp_rcv_drain(tcp);
15981 
15982 		if (peer_tcp > tcp) {
15983 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15984 			mutex_enter(&tcp->tcp_non_sq_lock);
15985 		} else {
15986 			mutex_enter(&tcp->tcp_non_sq_lock);
15987 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15988 		}
15989 
15990 		if (peer_tcp->tcp_flow_stopped &&
15991 		    (TCP_UNSENT_BYTES(peer_tcp) <=
15992 		    peer_tcp->tcp_xmit_lowater)) {
15993 			tcp_clrqfull(peer_tcp);
15994 		}
15995 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
15996 		mutex_exit(&tcp->tcp_non_sq_lock);
15997 
15998 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
15999 		TCP_STAT(tcps, tcp_fusion_backenabled);
16000 		return;
16001 	}
16002 
16003 	SOD_PTR_ENTER(tcp, sodp);
16004 	if (sodp != NULL) {
16005 		/* An sodirect connection */
16006 		if (SOD_QFULL(sodp)) {
16007 			/* Flow-controlled, need another back-enable */
16008 			fc = B_TRUE;
16009 			SOD_QSETBE(sodp);
16010 		} else {
16011 			/* Not flow-controlled */
16012 			fc = B_FALSE;
16013 		}
16014 		mutex_exit(sodp->sod_lockp);
16015 	} else if (canputnext(q)) {
16016 		/* STREAMS, not flow-controlled */
16017 		fc = B_FALSE;
16018 	} else {
16019 		/* STREAMS, flow-controlled */
16020 		fc = B_TRUE;
16021 	}
16022 	if (!fc) {
16023 		/* Not flow-controlled, open rwnd */
16024 		tcp->tcp_rwnd = q->q_hiwat;
16025 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
16026 		    << tcp->tcp_rcv_ws;
16027 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
16028 		/*
16029 		 * Send back a window update immediately if TCP is above
16030 		 * ESTABLISHED state and the increase of the rcv window
16031 		 * that the other side knows is at least 1 MSS after flow
16032 		 * control is lifted.
16033 		 */
16034 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
16035 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
16036 			tcp_xmit_ctl(NULL, tcp,
16037 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
16038 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
16039 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
16040 		}
16041 	}
16042 }
16043 
16044 /*
16045  * The read side service routine is called mostly when we get back-enabled as a
16046  * result of flow control relief.  Since we don't actually queue anything in
16047  * TCP, we have no data to send out of here.  What we do is clear the receive
16048  * window, and send out a window update.
16049  */
16050 static void
16051 tcp_rsrv(queue_t *q)
16052 {
16053 	conn_t		*connp = Q_TO_CONN(q);
16054 	tcp_t		*tcp = connp->conn_tcp;
16055 	mblk_t		*mp;
16056 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16057 
16058 	/* No code does a putq on the read side */
16059 	ASSERT(q->q_first == NULL);
16060 
16061 	/* Nothing to do for the default queue */
16062 	if (q == tcps->tcps_g_q) {
16063 		return;
16064 	}
16065 
16066 	/*
16067 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
16068 	 * been run.  So just return.
16069 	 */
16070 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
16071 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
16072 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
16073 		return;
16074 	}
16075 	tcp->tcp_rsrv_mp = NULL;
16076 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
16077 
16078 	CONN_INC_REF(connp);
16079 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16080 	    SQ_PROCESS, SQTAG_TCP_RSRV);
16081 }
16082 
16083 /*
16084  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16085  * We do not allow the receive window to shrink.  After setting rwnd,
16086  * set the flow control hiwat of the stream.
16087  *
16088  * This function is called in 2 cases:
16089  *
16090  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16091  *    connection (passive open) and in tcp_rput_data() for active connect.
16092  *    This is called after tcp_mss_set() when the desired MSS value is known.
16093  *    This makes sure that our window size is a mutiple of the other side's
16094  *    MSS.
16095  * 2) Handling SO_RCVBUF option.
16096  *
16097  * It is ASSUMED that the requested size is a multiple of the current MSS.
16098  *
16099  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16100  * user requests so.
16101  */
16102 static int
16103 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16104 {
16105 	uint32_t	mss = tcp->tcp_mss;
16106 	uint32_t	old_max_rwnd;
16107 	uint32_t	max_transmittable_rwnd;
16108 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16109 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16110 
16111 	if (tcp->tcp_fused) {
16112 		size_t sth_hiwat;
16113 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16114 
16115 		ASSERT(peer_tcp != NULL);
16116 		/*
16117 		 * Record the stream head's high water mark for
16118 		 * this endpoint; this is used for flow-control
16119 		 * purposes in tcp_fuse_output().
16120 		 */
16121 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16122 		if (!tcp_detached) {
16123 			(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
16124 			    sth_hiwat);
16125 			if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
16126 				conn_t *connp = tcp->tcp_connp;
16127 				struct sock_proto_props sopp;
16128 
16129 				sopp.sopp_flags = SOCKOPT_RCVTHRESH;
16130 				sopp.sopp_rcvthresh = sth_hiwat >> 3;
16131 
16132 				(*connp->conn_upcalls->su_set_proto_props)
16133 				    (connp->conn_upper_handle, &sopp);
16134 			}
16135 		}
16136 
16137 		/*
16138 		 * In the fusion case, the maxpsz stream head value of
16139 		 * our peer is set according to its send buffer size
16140 		 * and our receive buffer size; since the latter may
16141 		 * have changed we need to update the peer's maxpsz.
16142 		 */
16143 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16144 		return (rwnd);
16145 	}
16146 
16147 	if (tcp_detached) {
16148 		old_max_rwnd = tcp->tcp_rwnd;
16149 	} else {
16150 		old_max_rwnd = tcp->tcp_recv_hiwater;
16151 	}
16152 
16153 	/*
16154 	 * Insist on a receive window that is at least
16155 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16156 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16157 	 * and delayed acknowledgement.
16158 	 */
16159 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16160 
16161 	/*
16162 	 * If window size info has already been exchanged, TCP should not
16163 	 * shrink the window.  Shrinking window is doable if done carefully.
16164 	 * We may add that support later.  But so far there is not a real
16165 	 * need to do that.
16166 	 */
16167 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16168 		/* MSS may have changed, do a round up again. */
16169 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16170 	}
16171 
16172 	/*
16173 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16174 	 * can be applied even before the window scale option is decided.
16175 	 */
16176 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16177 	if (rwnd > max_transmittable_rwnd) {
16178 		rwnd = max_transmittable_rwnd -
16179 		    (max_transmittable_rwnd % mss);
16180 		if (rwnd < mss)
16181 			rwnd = max_transmittable_rwnd;
16182 		/*
16183 		 * If we're over the limit we may have to back down tcp_rwnd.
16184 		 * The increment below won't work for us. So we set all three
16185 		 * here and the increment below will have no effect.
16186 		 */
16187 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16188 	}
16189 	if (tcp->tcp_localnet) {
16190 		tcp->tcp_rack_abs_max =
16191 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16192 	} else {
16193 		/*
16194 		 * For a remote host on a different subnet (through a router),
16195 		 * we ack every other packet to be conforming to RFC1122.
16196 		 * tcp_deferred_acks_max is default to 2.
16197 		 */
16198 		tcp->tcp_rack_abs_max =
16199 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16200 	}
16201 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16202 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16203 	else
16204 		tcp->tcp_rack_cur_max = 0;
16205 	/*
16206 	 * Increment the current rwnd by the amount the maximum grew (we
16207 	 * can not overwrite it since we might be in the middle of a
16208 	 * connection.)
16209 	 */
16210 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16211 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16212 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16213 		tcp->tcp_cwnd_max = rwnd;
16214 
16215 	if (tcp_detached)
16216 		return (rwnd);
16217 	/*
16218 	 * We set the maximum receive window into rq->q_hiwat if it is
16219 	 * a STREAMS socket.
16220 	 * This is not actually used for flow control.
16221 	 */
16222 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
16223 		tcp->tcp_rq->q_hiwat = rwnd;
16224 	tcp->tcp_recv_hiwater = rwnd;
16225 	/*
16226 	 * Set the STREAM head high water mark. This doesn't have to be
16227 	 * here, since we are simply using default values, but we would
16228 	 * prefer to choose these values algorithmically, with a likely
16229 	 * relationship to rwnd.
16230 	 */
16231 	(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
16232 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16233 	return (rwnd);
16234 }
16235 
16236 /*
16237  * Return SNMP stuff in buffer in mpdata.
16238  */
16239 mblk_t *
16240 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16241 {
16242 	mblk_t			*mpdata;
16243 	mblk_t			*mp_conn_ctl = NULL;
16244 	mblk_t			*mp_conn_tail;
16245 	mblk_t			*mp_attr_ctl = NULL;
16246 	mblk_t			*mp_attr_tail;
16247 	mblk_t			*mp6_conn_ctl = NULL;
16248 	mblk_t			*mp6_conn_tail;
16249 	mblk_t			*mp6_attr_ctl = NULL;
16250 	mblk_t			*mp6_attr_tail;
16251 	struct opthdr		*optp;
16252 	mib2_tcpConnEntry_t	tce;
16253 	mib2_tcp6ConnEntry_t	tce6;
16254 	mib2_transportMLPEntry_t mlp;
16255 	connf_t			*connfp;
16256 	int			i;
16257 	boolean_t 		ispriv;
16258 	zoneid_t 		zoneid;
16259 	int			v4_conn_idx;
16260 	int			v6_conn_idx;
16261 	conn_t			*connp = Q_TO_CONN(q);
16262 	tcp_stack_t		*tcps;
16263 	ip_stack_t		*ipst;
16264 	mblk_t			*mp2ctl;
16265 
16266 	/*
16267 	 * make a copy of the original message
16268 	 */
16269 	mp2ctl = copymsg(mpctl);
16270 
16271 	if (mpctl == NULL ||
16272 	    (mpdata = mpctl->b_cont) == NULL ||
16273 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16274 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16275 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16276 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16277 		freemsg(mp_conn_ctl);
16278 		freemsg(mp_attr_ctl);
16279 		freemsg(mp6_conn_ctl);
16280 		freemsg(mp6_attr_ctl);
16281 		freemsg(mpctl);
16282 		freemsg(mp2ctl);
16283 		return (NULL);
16284 	}
16285 
16286 	ipst = connp->conn_netstack->netstack_ip;
16287 	tcps = connp->conn_netstack->netstack_tcp;
16288 
16289 	/* build table of connections -- need count in fixed part */
16290 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16291 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16292 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16293 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16294 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16295 
16296 	ispriv =
16297 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16298 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16299 
16300 	v4_conn_idx = v6_conn_idx = 0;
16301 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16302 
16303 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16304 		ipst = tcps->tcps_netstack->netstack_ip;
16305 
16306 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16307 
16308 		connp = NULL;
16309 
16310 		while ((connp =
16311 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16312 			tcp_t *tcp;
16313 			boolean_t needattr;
16314 
16315 			if (connp->conn_zoneid != zoneid)
16316 				continue;	/* not in this zone */
16317 
16318 			tcp = connp->conn_tcp;
16319 			UPDATE_MIB(&tcps->tcps_mib,
16320 			    tcpHCInSegs, tcp->tcp_ibsegs);
16321 			tcp->tcp_ibsegs = 0;
16322 			UPDATE_MIB(&tcps->tcps_mib,
16323 			    tcpHCOutSegs, tcp->tcp_obsegs);
16324 			tcp->tcp_obsegs = 0;
16325 
16326 			tce6.tcp6ConnState = tce.tcpConnState =
16327 			    tcp_snmp_state(tcp);
16328 			if (tce.tcpConnState == MIB2_TCP_established ||
16329 			    tce.tcpConnState == MIB2_TCP_closeWait)
16330 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16331 
16332 			needattr = B_FALSE;
16333 			bzero(&mlp, sizeof (mlp));
16334 			if (connp->conn_mlp_type != mlptSingle) {
16335 				if (connp->conn_mlp_type == mlptShared ||
16336 				    connp->conn_mlp_type == mlptBoth)
16337 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16338 				if (connp->conn_mlp_type == mlptPrivate ||
16339 				    connp->conn_mlp_type == mlptBoth)
16340 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16341 				needattr = B_TRUE;
16342 			}
16343 			if (connp->conn_peercred != NULL) {
16344 				ts_label_t *tsl;
16345 
16346 				tsl = crgetlabel(connp->conn_peercred);
16347 				mlp.tme_doi = label2doi(tsl);
16348 				mlp.tme_label = *label2bslabel(tsl);
16349 				needattr = B_TRUE;
16350 			}
16351 
16352 			/* Create a message to report on IPv6 entries */
16353 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16354 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16355 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16356 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16357 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16358 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16359 			/* Don't want just anybody seeing these... */
16360 			if (ispriv) {
16361 				tce6.tcp6ConnEntryInfo.ce_snxt =
16362 				    tcp->tcp_snxt;
16363 				tce6.tcp6ConnEntryInfo.ce_suna =
16364 				    tcp->tcp_suna;
16365 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16366 				    tcp->tcp_rnxt;
16367 				tce6.tcp6ConnEntryInfo.ce_rack =
16368 				    tcp->tcp_rack;
16369 			} else {
16370 				/*
16371 				 * Netstat, unfortunately, uses this to
16372 				 * get send/receive queue sizes.  How to fix?
16373 				 * Why not compute the difference only?
16374 				 */
16375 				tce6.tcp6ConnEntryInfo.ce_snxt =
16376 				    tcp->tcp_snxt - tcp->tcp_suna;
16377 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16378 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16379 				    tcp->tcp_rnxt - tcp->tcp_rack;
16380 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16381 			}
16382 
16383 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16384 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16385 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16386 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16387 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16388 
16389 			tce6.tcp6ConnCreationProcess =
16390 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16391 			    tcp->tcp_cpid;
16392 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16393 
16394 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16395 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16396 
16397 			mlp.tme_connidx = v6_conn_idx++;
16398 			if (needattr)
16399 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16400 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16401 			}
16402 			/*
16403 			 * Create an IPv4 table entry for IPv4 entries and also
16404 			 * for IPv6 entries which are bound to in6addr_any
16405 			 * but don't have IPV6_V6ONLY set.
16406 			 * (i.e. anything an IPv4 peer could connect to)
16407 			 */
16408 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16409 			    (tcp->tcp_state <= TCPS_LISTEN &&
16410 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16411 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16412 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16413 					tce.tcpConnRemAddress = INADDR_ANY;
16414 					tce.tcpConnLocalAddress = INADDR_ANY;
16415 				} else {
16416 					tce.tcpConnRemAddress =
16417 					    tcp->tcp_remote;
16418 					tce.tcpConnLocalAddress =
16419 					    tcp->tcp_ip_src;
16420 				}
16421 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16422 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16423 				/* Don't want just anybody seeing these... */
16424 				if (ispriv) {
16425 					tce.tcpConnEntryInfo.ce_snxt =
16426 					    tcp->tcp_snxt;
16427 					tce.tcpConnEntryInfo.ce_suna =
16428 					    tcp->tcp_suna;
16429 					tce.tcpConnEntryInfo.ce_rnxt =
16430 					    tcp->tcp_rnxt;
16431 					tce.tcpConnEntryInfo.ce_rack =
16432 					    tcp->tcp_rack;
16433 				} else {
16434 					/*
16435 					 * Netstat, unfortunately, uses this to
16436 					 * get send/receive queue sizes.  How
16437 					 * to fix?
16438 					 * Why not compute the difference only?
16439 					 */
16440 					tce.tcpConnEntryInfo.ce_snxt =
16441 					    tcp->tcp_snxt - tcp->tcp_suna;
16442 					tce.tcpConnEntryInfo.ce_suna = 0;
16443 					tce.tcpConnEntryInfo.ce_rnxt =
16444 					    tcp->tcp_rnxt - tcp->tcp_rack;
16445 					tce.tcpConnEntryInfo.ce_rack = 0;
16446 				}
16447 
16448 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16449 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16450 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16451 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16452 				tce.tcpConnEntryInfo.ce_state =
16453 				    tcp->tcp_state;
16454 
16455 				tce.tcpConnCreationProcess =
16456 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16457 				    tcp->tcp_cpid;
16458 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16459 
16460 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16461 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16462 
16463 				mlp.tme_connidx = v4_conn_idx++;
16464 				if (needattr)
16465 					(void) snmp_append_data2(
16466 					    mp_attr_ctl->b_cont,
16467 					    &mp_attr_tail, (char *)&mlp,
16468 					    sizeof (mlp));
16469 			}
16470 		}
16471 	}
16472 
16473 	/* fixed length structure for IPv4 and IPv6 counters */
16474 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16475 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16476 	    sizeof (mib2_tcp6ConnEntry_t));
16477 	/* synchronize 32- and 64-bit counters */
16478 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16479 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16480 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16481 	optp->level = MIB2_TCP;
16482 	optp->name = 0;
16483 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16484 	    sizeof (tcps->tcps_mib));
16485 	optp->len = msgdsize(mpdata);
16486 	qreply(q, mpctl);
16487 
16488 	/* table of connections... */
16489 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16490 	    sizeof (struct T_optmgmt_ack)];
16491 	optp->level = MIB2_TCP;
16492 	optp->name = MIB2_TCP_CONN;
16493 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16494 	qreply(q, mp_conn_ctl);
16495 
16496 	/* table of MLP attributes... */
16497 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16498 	    sizeof (struct T_optmgmt_ack)];
16499 	optp->level = MIB2_TCP;
16500 	optp->name = EXPER_XPORT_MLP;
16501 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16502 	if (optp->len == 0)
16503 		freemsg(mp_attr_ctl);
16504 	else
16505 		qreply(q, mp_attr_ctl);
16506 
16507 	/* table of IPv6 connections... */
16508 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16509 	    sizeof (struct T_optmgmt_ack)];
16510 	optp->level = MIB2_TCP6;
16511 	optp->name = MIB2_TCP6_CONN;
16512 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16513 	qreply(q, mp6_conn_ctl);
16514 
16515 	/* table of IPv6 MLP attributes... */
16516 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16517 	    sizeof (struct T_optmgmt_ack)];
16518 	optp->level = MIB2_TCP6;
16519 	optp->name = EXPER_XPORT_MLP;
16520 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16521 	if (optp->len == 0)
16522 		freemsg(mp6_attr_ctl);
16523 	else
16524 		qreply(q, mp6_attr_ctl);
16525 	return (mp2ctl);
16526 }
16527 
16528 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16529 /* ARGSUSED */
16530 int
16531 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16532 {
16533 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16534 
16535 	switch (level) {
16536 	case MIB2_TCP:
16537 		switch (name) {
16538 		case 13:
16539 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16540 				return (0);
16541 			/* TODO: delete entry defined by tce */
16542 			return (1);
16543 		default:
16544 			return (0);
16545 		}
16546 	default:
16547 		return (1);
16548 	}
16549 }
16550 
16551 /* Translate TCP state to MIB2 TCP state. */
16552 static int
16553 tcp_snmp_state(tcp_t *tcp)
16554 {
16555 	if (tcp == NULL)
16556 		return (0);
16557 
16558 	switch (tcp->tcp_state) {
16559 	case TCPS_CLOSED:
16560 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16561 	case TCPS_BOUND:
16562 		return (MIB2_TCP_closed);
16563 	case TCPS_LISTEN:
16564 		return (MIB2_TCP_listen);
16565 	case TCPS_SYN_SENT:
16566 		return (MIB2_TCP_synSent);
16567 	case TCPS_SYN_RCVD:
16568 		return (MIB2_TCP_synReceived);
16569 	case TCPS_ESTABLISHED:
16570 		return (MIB2_TCP_established);
16571 	case TCPS_CLOSE_WAIT:
16572 		return (MIB2_TCP_closeWait);
16573 	case TCPS_FIN_WAIT_1:
16574 		return (MIB2_TCP_finWait1);
16575 	case TCPS_CLOSING:
16576 		return (MIB2_TCP_closing);
16577 	case TCPS_LAST_ACK:
16578 		return (MIB2_TCP_lastAck);
16579 	case TCPS_FIN_WAIT_2:
16580 		return (MIB2_TCP_finWait2);
16581 	case TCPS_TIME_WAIT:
16582 		return (MIB2_TCP_timeWait);
16583 	default:
16584 		return (0);
16585 	}
16586 }
16587 
16588 static char tcp_report_header[] =
16589 	"TCP     " MI_COL_HDRPAD_STR
16590 	"zone dest	    snxt     suna     "
16591 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16592 	"recent   [lport,fport] state";
16593 
16594 /*
16595  * TCP status report triggered via the Named Dispatch mechanism.
16596  */
16597 /* ARGSUSED */
16598 static void
16599 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16600     cred_t *cr)
16601 {
16602 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16603 	boolean_t ispriv = secpolicy_ip_config(cr, B_TRUE) == 0;
16604 	char cflag;
16605 	in6_addr_t	v6dst;
16606 	char buf[80];
16607 	uint_t print_len, buf_len;
16608 
16609 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16610 	if (buf_len <= 0)
16611 		return;
16612 
16613 	if (hashval >= 0)
16614 		(void) sprintf(hash, "%03d ", hashval);
16615 	else
16616 		hash[0] = '\0';
16617 
16618 	/*
16619 	 * Note that we use the remote address in the tcp_b  structure.
16620 	 * This means that it will print out the real destination address,
16621 	 * not the next hop's address if source routing is used.  This
16622 	 * avoid the confusion on the output because user may not
16623 	 * know that source routing is used for a connection.
16624 	 */
16625 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16626 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16627 	} else {
16628 		v6dst = tcp->tcp_remote_v6;
16629 	}
16630 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16631 	/*
16632 	 * the ispriv checks are so that normal users cannot determine
16633 	 * sequence number information using NDD.
16634 	 */
16635 
16636 	if (TCP_IS_DETACHED(tcp))
16637 		cflag = '*';
16638 	else
16639 		cflag = ' ';
16640 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16641 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16642 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16643 	    hash,
16644 	    (void *)tcp,
16645 	    tcp->tcp_connp->conn_zoneid,
16646 	    addrbuf,
16647 	    (ispriv) ? tcp->tcp_snxt : 0,
16648 	    (ispriv) ? tcp->tcp_suna : 0,
16649 	    tcp->tcp_swnd,
16650 	    (ispriv) ? tcp->tcp_rnxt : 0,
16651 	    (ispriv) ? tcp->tcp_rack : 0,
16652 	    tcp->tcp_rwnd,
16653 	    tcp->tcp_rto,
16654 	    tcp->tcp_mss,
16655 	    tcp->tcp_snd_ws_ok,
16656 	    tcp->tcp_snd_ws,
16657 	    tcp->tcp_rcv_ws,
16658 	    tcp->tcp_snd_ts_ok,
16659 	    tcp->tcp_ts_recent,
16660 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16661 	if (print_len < buf_len) {
16662 		((mblk_t *)mp)->b_wptr += print_len;
16663 	} else {
16664 		((mblk_t *)mp)->b_wptr += buf_len;
16665 	}
16666 }
16667 
16668 /*
16669  * TCP status report (for listeners only) triggered via the Named Dispatch
16670  * mechanism.
16671  */
16672 /* ARGSUSED */
16673 static void
16674 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16675 {
16676 	char addrbuf[INET6_ADDRSTRLEN];
16677 	in6_addr_t	v6dst;
16678 	uint_t print_len, buf_len;
16679 
16680 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16681 	if (buf_len <= 0)
16682 		return;
16683 
16684 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16685 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16686 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16687 	} else {
16688 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16689 		    addrbuf, sizeof (addrbuf));
16690 	}
16691 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16692 	    "%03d "
16693 	    MI_COL_PTRFMT_STR
16694 	    "%d %s %05u %08u %d/%d/%d%c\n",
16695 	    hashval, (void *)tcp,
16696 	    tcp->tcp_connp->conn_zoneid,
16697 	    addrbuf,
16698 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16699 	    tcp->tcp_conn_req_seqnum,
16700 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16701 	    tcp->tcp_conn_req_max,
16702 	    tcp->tcp_syn_defense ? '*' : ' ');
16703 	if (print_len < buf_len) {
16704 		((mblk_t *)mp)->b_wptr += print_len;
16705 	} else {
16706 		((mblk_t *)mp)->b_wptr += buf_len;
16707 	}
16708 }
16709 
16710 /* TCP status report triggered via the Named Dispatch mechanism. */
16711 /* ARGSUSED */
16712 static int
16713 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16714 {
16715 	tcp_t	*tcp;
16716 	int	i;
16717 	conn_t	*connp;
16718 	connf_t	*connfp;
16719 	zoneid_t zoneid;
16720 	tcp_stack_t *tcps;
16721 	ip_stack_t *ipst;
16722 
16723 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16724 	tcps = Q_TO_TCP(q)->tcp_tcps;
16725 
16726 	/*
16727 	 * Because of the ndd constraint, at most we can have 64K buffer
16728 	 * to put in all TCP info.  So to be more efficient, just
16729 	 * allocate a 64K buffer here, assuming we need that large buffer.
16730 	 * This may be a problem as any user can read tcp_status.  Therefore
16731 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16732 	 * This should be OK as normal users should not do this too often.
16733 	 */
16734 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16735 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16736 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16737 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16738 			return (0);
16739 		}
16740 	}
16741 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16742 		/* The following may work even if we cannot get a large buf. */
16743 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16744 		return (0);
16745 	}
16746 
16747 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16748 
16749 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16750 
16751 		ipst = tcps->tcps_netstack->netstack_ip;
16752 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16753 
16754 		connp = NULL;
16755 
16756 		while ((connp =
16757 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16758 			tcp = connp->conn_tcp;
16759 			if (zoneid != GLOBAL_ZONEID &&
16760 			    zoneid != connp->conn_zoneid)
16761 				continue;
16762 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16763 			    cr);
16764 		}
16765 
16766 	}
16767 
16768 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16769 	return (0);
16770 }
16771 
16772 /* TCP status report triggered via the Named Dispatch mechanism. */
16773 /* ARGSUSED */
16774 static int
16775 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16776 {
16777 	tf_t	*tbf;
16778 	tcp_t	*tcp, *ltcp;
16779 	int	i;
16780 	zoneid_t zoneid;
16781 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
16782 
16783 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16784 
16785 	/* Refer to comments in tcp_status_report(). */
16786 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16787 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16788 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16789 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16790 			return (0);
16791 		}
16792 	}
16793 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16794 		/* The following may work even if we cannot get a large buf. */
16795 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16796 		return (0);
16797 	}
16798 
16799 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16800 
16801 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
16802 		tbf = &tcps->tcps_bind_fanout[i];
16803 		mutex_enter(&tbf->tf_lock);
16804 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
16805 		    ltcp = ltcp->tcp_bind_hash) {
16806 			for (tcp = ltcp; tcp != NULL;
16807 			    tcp = tcp->tcp_bind_hash_port) {
16808 				if (zoneid != GLOBAL_ZONEID &&
16809 				    zoneid != tcp->tcp_connp->conn_zoneid)
16810 					continue;
16811 				CONN_INC_REF(tcp->tcp_connp);
16812 				tcp_report_item(mp->b_cont, tcp, i,
16813 				    Q_TO_TCP(q), cr);
16814 				CONN_DEC_REF(tcp->tcp_connp);
16815 			}
16816 		}
16817 		mutex_exit(&tbf->tf_lock);
16818 	}
16819 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16820 	return (0);
16821 }
16822 
16823 /* TCP status report triggered via the Named Dispatch mechanism. */
16824 /* ARGSUSED */
16825 static int
16826 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16827 {
16828 	connf_t	*connfp;
16829 	conn_t	*connp;
16830 	tcp_t	*tcp;
16831 	int	i;
16832 	zoneid_t zoneid;
16833 	tcp_stack_t *tcps;
16834 	ip_stack_t	*ipst;
16835 
16836 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16837 	tcps = Q_TO_TCP(q)->tcp_tcps;
16838 
16839 	/* Refer to comments in tcp_status_report(). */
16840 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16841 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16842 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16843 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16844 			return (0);
16845 		}
16846 	}
16847 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16848 		/* The following may work even if we cannot get a large buf. */
16849 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16850 		return (0);
16851 	}
16852 
16853 	(void) mi_mpprintf(mp,
16854 	    "    TCP    " MI_COL_HDRPAD_STR
16855 	    "zone IP addr	 port  seqnum   backlog (q0/q/max)");
16856 
16857 	ipst = tcps->tcps_netstack->netstack_ip;
16858 
16859 	for (i = 0; i < ipst->ips_ipcl_bind_fanout_size; i++) {
16860 		connfp = &ipst->ips_ipcl_bind_fanout[i];
16861 		connp = NULL;
16862 		while ((connp =
16863 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16864 			tcp = connp->conn_tcp;
16865 			if (zoneid != GLOBAL_ZONEID &&
16866 			    zoneid != connp->conn_zoneid)
16867 				continue;
16868 			tcp_report_listener(mp->b_cont, tcp, i);
16869 		}
16870 	}
16871 
16872 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16873 	return (0);
16874 }
16875 
16876 /* TCP status report triggered via the Named Dispatch mechanism. */
16877 /* ARGSUSED */
16878 static int
16879 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16880 {
16881 	connf_t	*connfp;
16882 	conn_t	*connp;
16883 	tcp_t	*tcp;
16884 	int	i;
16885 	zoneid_t zoneid;
16886 	tcp_stack_t *tcps;
16887 	ip_stack_t *ipst;
16888 
16889 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16890 	tcps = Q_TO_TCP(q)->tcp_tcps;
16891 	ipst = tcps->tcps_netstack->netstack_ip;
16892 
16893 	/* Refer to comments in tcp_status_report(). */
16894 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16895 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16896 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16897 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16898 			return (0);
16899 		}
16900 	}
16901 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16902 		/* The following may work even if we cannot get a large buf. */
16903 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16904 		return (0);
16905 	}
16906 
16907 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16908 	    ipst->ips_ipcl_conn_fanout_size);
16909 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16910 
16911 	for (i = 0; i < ipst->ips_ipcl_conn_fanout_size; i++) {
16912 		connfp =  &ipst->ips_ipcl_conn_fanout[i];
16913 		connp = NULL;
16914 		while ((connp =
16915 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16916 			tcp = connp->conn_tcp;
16917 			if (zoneid != GLOBAL_ZONEID &&
16918 			    zoneid != connp->conn_zoneid)
16919 				continue;
16920 			tcp_report_item(mp->b_cont, tcp, i,
16921 			    Q_TO_TCP(q), cr);
16922 		}
16923 	}
16924 
16925 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16926 	return (0);
16927 }
16928 
16929 /* TCP status report triggered via the Named Dispatch mechanism. */
16930 /* ARGSUSED */
16931 static int
16932 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16933 {
16934 	tf_t	*tf;
16935 	tcp_t	*tcp;
16936 	int	i;
16937 	zoneid_t zoneid;
16938 	tcp_stack_t	*tcps;
16939 
16940 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16941 	tcps = Q_TO_TCP(q)->tcp_tcps;
16942 
16943 	/* Refer to comments in tcp_status_report(). */
16944 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16945 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16946 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16947 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16948 			return (0);
16949 		}
16950 	}
16951 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16952 		/* The following may work even if we cannot get a large buf. */
16953 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16954 		return (0);
16955 	}
16956 
16957 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16958 
16959 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
16960 		tf = &tcps->tcps_acceptor_fanout[i];
16961 		mutex_enter(&tf->tf_lock);
16962 		for (tcp = tf->tf_tcp; tcp != NULL;
16963 		    tcp = tcp->tcp_acceptor_hash) {
16964 			if (zoneid != GLOBAL_ZONEID &&
16965 			    zoneid != tcp->tcp_connp->conn_zoneid)
16966 				continue;
16967 			tcp_report_item(mp->b_cont, tcp, i,
16968 			    Q_TO_TCP(q), cr);
16969 		}
16970 		mutex_exit(&tf->tf_lock);
16971 	}
16972 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16973 	return (0);
16974 }
16975 
16976 /*
16977  * tcp_timer is the timer service routine.  It handles the retransmission,
16978  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16979  * from the state of the tcp instance what kind of action needs to be done
16980  * at the time it is called.
16981  */
16982 static void
16983 tcp_timer(void *arg)
16984 {
16985 	mblk_t		*mp;
16986 	clock_t		first_threshold;
16987 	clock_t		second_threshold;
16988 	clock_t		ms;
16989 	uint32_t	mss;
16990 	conn_t		*connp = (conn_t *)arg;
16991 	tcp_t		*tcp = connp->conn_tcp;
16992 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16993 
16994 	tcp->tcp_timer_tid = 0;
16995 
16996 	if (tcp->tcp_fused)
16997 		return;
16998 
16999 	first_threshold =  tcp->tcp_first_timer_threshold;
17000 	second_threshold = tcp->tcp_second_timer_threshold;
17001 	switch (tcp->tcp_state) {
17002 	case TCPS_IDLE:
17003 	case TCPS_BOUND:
17004 	case TCPS_LISTEN:
17005 		return;
17006 	case TCPS_SYN_RCVD: {
17007 		tcp_t	*listener = tcp->tcp_listener;
17008 
17009 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
17010 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
17011 			/* it's our first timeout */
17012 			tcp->tcp_syn_rcvd_timeout = 1;
17013 			mutex_enter(&listener->tcp_eager_lock);
17014 			listener->tcp_syn_rcvd_timeout++;
17015 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
17016 				/*
17017 				 * Make this eager available for drop if we
17018 				 * need to drop one to accomodate a new
17019 				 * incoming SYN request.
17020 				 */
17021 				MAKE_DROPPABLE(listener, tcp);
17022 			}
17023 			if (!listener->tcp_syn_defense &&
17024 			    (listener->tcp_syn_rcvd_timeout >
17025 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
17026 			    (tcps->tcps_conn_req_max_q0 > 200)) {
17027 				/* We may be under attack. Put on a defense. */
17028 				listener->tcp_syn_defense = B_TRUE;
17029 				cmn_err(CE_WARN, "High TCP connect timeout "
17030 				    "rate! System (port %d) may be under a "
17031 				    "SYN flood attack!",
17032 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
17033 
17034 				listener->tcp_ip_addr_cache = kmem_zalloc(
17035 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
17036 				    KM_NOSLEEP);
17037 			}
17038 			mutex_exit(&listener->tcp_eager_lock);
17039 		} else if (listener != NULL) {
17040 			mutex_enter(&listener->tcp_eager_lock);
17041 			tcp->tcp_syn_rcvd_timeout++;
17042 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
17043 			    !tcp->tcp_closemp_used) {
17044 				/*
17045 				 * This is our second timeout. Put the tcp in
17046 				 * the list of droppable eagers to allow it to
17047 				 * be dropped, if needed. We don't check
17048 				 * whether tcp_dontdrop is set or not to
17049 				 * protect ourselve from a SYN attack where a
17050 				 * remote host can spoof itself as one of the
17051 				 * good IP source and continue to hold
17052 				 * resources too long.
17053 				 */
17054 				MAKE_DROPPABLE(listener, tcp);
17055 			}
17056 			mutex_exit(&listener->tcp_eager_lock);
17057 		}
17058 	}
17059 		/* FALLTHRU */
17060 	case TCPS_SYN_SENT:
17061 		first_threshold =  tcp->tcp_first_ctimer_threshold;
17062 		second_threshold = tcp->tcp_second_ctimer_threshold;
17063 		break;
17064 	case TCPS_ESTABLISHED:
17065 	case TCPS_FIN_WAIT_1:
17066 	case TCPS_CLOSING:
17067 	case TCPS_CLOSE_WAIT:
17068 	case TCPS_LAST_ACK:
17069 		/* If we have data to rexmit */
17070 		if (tcp->tcp_suna != tcp->tcp_snxt) {
17071 			clock_t	time_to_wait;
17072 
17073 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
17074 			if (!tcp->tcp_xmit_head)
17075 				break;
17076 			time_to_wait = lbolt -
17077 			    (clock_t)tcp->tcp_xmit_head->b_prev;
17078 			time_to_wait = tcp->tcp_rto -
17079 			    TICK_TO_MSEC(time_to_wait);
17080 			/*
17081 			 * If the timer fires too early, 1 clock tick earlier,
17082 			 * restart the timer.
17083 			 */
17084 			if (time_to_wait > msec_per_tick) {
17085 				TCP_STAT(tcps, tcp_timer_fire_early);
17086 				TCP_TIMER_RESTART(tcp, time_to_wait);
17087 				return;
17088 			}
17089 			/*
17090 			 * When we probe zero windows, we force the swnd open.
17091 			 * If our peer acks with a closed window swnd will be
17092 			 * set to zero by tcp_rput(). As long as we are
17093 			 * receiving acks tcp_rput will
17094 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
17095 			 * first and second interval actions.  NOTE: the timer
17096 			 * interval is allowed to continue its exponential
17097 			 * backoff.
17098 			 */
17099 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
17100 				if (tcp->tcp_debug) {
17101 					(void) strlog(TCP_MOD_ID, 0, 1,
17102 					    SL_TRACE, "tcp_timer: zero win");
17103 				}
17104 			} else {
17105 				/*
17106 				 * After retransmission, we need to do
17107 				 * slow start.  Set the ssthresh to one
17108 				 * half of current effective window and
17109 				 * cwnd to one MSS.  Also reset
17110 				 * tcp_cwnd_cnt.
17111 				 *
17112 				 * Note that if tcp_ssthresh is reduced because
17113 				 * of ECN, do not reduce it again unless it is
17114 				 * already one window of data away (tcp_cwr
17115 				 * should then be cleared) or this is a
17116 				 * timeout for a retransmitted segment.
17117 				 */
17118 				uint32_t npkt;
17119 
17120 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
17121 					npkt = ((tcp->tcp_timer_backoff ?
17122 					    tcp->tcp_cwnd_ssthresh :
17123 					    tcp->tcp_snxt -
17124 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
17125 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
17126 					    tcp->tcp_mss;
17127 				}
17128 				tcp->tcp_cwnd = tcp->tcp_mss;
17129 				tcp->tcp_cwnd_cnt = 0;
17130 				if (tcp->tcp_ecn_ok) {
17131 					tcp->tcp_cwr = B_TRUE;
17132 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17133 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17134 				}
17135 			}
17136 			break;
17137 		}
17138 		/*
17139 		 * We have something to send yet we cannot send.  The
17140 		 * reason can be:
17141 		 *
17142 		 * 1. Zero send window: we need to do zero window probe.
17143 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17144 		 * segments.
17145 		 * 3. SWS avoidance: receiver may have shrunk window,
17146 		 * reset our knowledge.
17147 		 *
17148 		 * Note that condition 2 can happen with either 1 or
17149 		 * 3.  But 1 and 3 are exclusive.
17150 		 */
17151 		if (tcp->tcp_unsent != 0) {
17152 			if (tcp->tcp_cwnd == 0) {
17153 				/*
17154 				 * Set tcp_cwnd to 1 MSS so that a
17155 				 * new segment can be sent out.  We
17156 				 * are "clocking out" new data when
17157 				 * the network is really congested.
17158 				 */
17159 				ASSERT(tcp->tcp_ecn_ok);
17160 				tcp->tcp_cwnd = tcp->tcp_mss;
17161 			}
17162 			if (tcp->tcp_swnd == 0) {
17163 				/* Extend window for zero window probe */
17164 				tcp->tcp_swnd++;
17165 				tcp->tcp_zero_win_probe = B_TRUE;
17166 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
17167 			} else {
17168 				/*
17169 				 * Handle timeout from sender SWS avoidance.
17170 				 * Reset our knowledge of the max send window
17171 				 * since the receiver might have reduced its
17172 				 * receive buffer.  Avoid setting tcp_max_swnd
17173 				 * to one since that will essentially disable
17174 				 * the SWS checks.
17175 				 *
17176 				 * Note that since we don't have a SWS
17177 				 * state variable, if the timeout is set
17178 				 * for ECN but not for SWS, this
17179 				 * code will also be executed.  This is
17180 				 * fine as tcp_max_swnd is updated
17181 				 * constantly and it will not affect
17182 				 * anything.
17183 				 */
17184 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17185 			}
17186 			tcp_wput_data(tcp, NULL, B_FALSE);
17187 			return;
17188 		}
17189 		/* Is there a FIN that needs to be to re retransmitted? */
17190 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17191 		    !tcp->tcp_fin_acked)
17192 			break;
17193 		/* Nothing to do, return without restarting timer. */
17194 		TCP_STAT(tcps, tcp_timer_fire_miss);
17195 		return;
17196 	case TCPS_FIN_WAIT_2:
17197 		/*
17198 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17199 		 * We waited some time for for peer's FIN, but it hasn't
17200 		 * arrived.  We flush the connection now to avoid
17201 		 * case where the peer has rebooted.
17202 		 */
17203 		if (TCP_IS_DETACHED(tcp)) {
17204 			(void) tcp_clean_death(tcp, 0, 23);
17205 		} else {
17206 			TCP_TIMER_RESTART(tcp,
17207 			    tcps->tcps_fin_wait_2_flush_interval);
17208 		}
17209 		return;
17210 	case TCPS_TIME_WAIT:
17211 		(void) tcp_clean_death(tcp, 0, 24);
17212 		return;
17213 	default:
17214 		if (tcp->tcp_debug) {
17215 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
17216 			    "tcp_timer: strange state (%d) %s",
17217 			    tcp->tcp_state, tcp_display(tcp, NULL,
17218 			    DISP_PORT_ONLY));
17219 		}
17220 		return;
17221 	}
17222 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17223 		/*
17224 		 * For zero window probe, we need to send indefinitely,
17225 		 * unless we have not heard from the other side for some
17226 		 * time...
17227 		 */
17228 		if ((tcp->tcp_zero_win_probe == 0) ||
17229 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17230 		    second_threshold)) {
17231 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
17232 			/*
17233 			 * If TCP is in SYN_RCVD state, send back a
17234 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17235 			 * should be zero in TCPS_SYN_RCVD state.
17236 			 */
17237 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17238 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17239 				    "in SYN_RCVD",
17240 				    tcp, tcp->tcp_snxt,
17241 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17242 			}
17243 			(void) tcp_clean_death(tcp,
17244 			    tcp->tcp_client_errno ?
17245 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17246 			return;
17247 		} else {
17248 			/*
17249 			 * Set tcp_ms_we_have_waited to second_threshold
17250 			 * so that in next timeout, we will do the above
17251 			 * check (lbolt - tcp_last_recv_time).  This is
17252 			 * also to avoid overflow.
17253 			 *
17254 			 * We don't need to decrement tcp_timer_backoff
17255 			 * to avoid overflow because it will be decremented
17256 			 * later if new timeout value is greater than
17257 			 * tcp_rexmit_interval_max.  In the case when
17258 			 * tcp_rexmit_interval_max is greater than
17259 			 * second_threshold, it means that we will wait
17260 			 * longer than second_threshold to send the next
17261 			 * window probe.
17262 			 */
17263 			tcp->tcp_ms_we_have_waited = second_threshold;
17264 		}
17265 	} else if (ms > first_threshold) {
17266 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17267 		    tcp->tcp_xmit_head != NULL) {
17268 			tcp->tcp_xmit_head =
17269 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17270 		}
17271 		/*
17272 		 * We have been retransmitting for too long...  The RTT
17273 		 * we calculated is probably incorrect.  Reinitialize it.
17274 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17275 		 * tcp_rtt_update so that we won't accidentally cache a
17276 		 * bad value.  But only do this if this is not a zero
17277 		 * window probe.
17278 		 */
17279 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17280 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17281 			    (tcp->tcp_rtt_sa >> 5);
17282 			tcp->tcp_rtt_sa = 0;
17283 			tcp_ip_notify(tcp);
17284 			tcp->tcp_rtt_update = 0;
17285 		}
17286 	}
17287 	tcp->tcp_timer_backoff++;
17288 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17289 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17290 	    tcps->tcps_rexmit_interval_min) {
17291 		/*
17292 		 * This means the original RTO is tcp_rexmit_interval_min.
17293 		 * So we will use tcp_rexmit_interval_min as the RTO value
17294 		 * and do the backoff.
17295 		 */
17296 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
17297 	} else {
17298 		ms <<= tcp->tcp_timer_backoff;
17299 	}
17300 	if (ms > tcps->tcps_rexmit_interval_max) {
17301 		ms = tcps->tcps_rexmit_interval_max;
17302 		/*
17303 		 * ms is at max, decrement tcp_timer_backoff to avoid
17304 		 * overflow.
17305 		 */
17306 		tcp->tcp_timer_backoff--;
17307 	}
17308 	tcp->tcp_ms_we_have_waited += ms;
17309 	if (tcp->tcp_zero_win_probe == 0) {
17310 		tcp->tcp_rto = ms;
17311 	}
17312 	TCP_TIMER_RESTART(tcp, ms);
17313 	/*
17314 	 * This is after a timeout and tcp_rto is backed off.  Set
17315 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17316 	 * restart the timer with a correct value.
17317 	 */
17318 	tcp->tcp_set_timer = 1;
17319 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17320 	if (mss > tcp->tcp_mss)
17321 		mss = tcp->tcp_mss;
17322 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17323 		mss = tcp->tcp_swnd;
17324 
17325 	if ((mp = tcp->tcp_xmit_head) != NULL)
17326 		mp->b_prev = (mblk_t *)lbolt;
17327 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17328 	    B_TRUE);
17329 
17330 	/*
17331 	 * When slow start after retransmission begins, start with
17332 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17333 	 * start phase.  tcp_snd_burst controls how many segments
17334 	 * can be sent because of an ack.
17335 	 */
17336 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17337 	tcp->tcp_snd_burst = TCP_CWND_SS;
17338 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17339 	    (tcp->tcp_unsent == 0)) {
17340 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17341 	} else {
17342 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17343 	}
17344 	tcp->tcp_rexmit = B_TRUE;
17345 	tcp->tcp_dupack_cnt = 0;
17346 
17347 	/*
17348 	 * Remove all rexmit SACK blk to start from fresh.
17349 	 */
17350 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17351 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17352 		tcp->tcp_num_notsack_blk = 0;
17353 		tcp->tcp_cnt_notsack_list = 0;
17354 	}
17355 	if (mp == NULL) {
17356 		return;
17357 	}
17358 	/* Attach credentials to retransmitted initial SYNs. */
17359 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17360 		mblk_setcred(mp, tcp->tcp_cred);
17361 		DB_CPID(mp) = tcp->tcp_cpid;
17362 	}
17363 
17364 	tcp->tcp_csuna = tcp->tcp_snxt;
17365 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17366 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17367 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17368 
17369 }
17370 
17371 static int
17372 tcp_do_unbind(conn_t *connp)
17373 {
17374 	tcp_t *tcp = connp->conn_tcp;
17375 	int error = 0;
17376 
17377 	switch (tcp->tcp_state) {
17378 	case TCPS_BOUND:
17379 	case TCPS_LISTEN:
17380 		break;
17381 	default:
17382 		return (-TOUTSTATE);
17383 	}
17384 
17385 	/*
17386 	 * Need to clean up all the eagers since after the unbind, segments
17387 	 * will no longer be delivered to this listener stream.
17388 	 */
17389 	mutex_enter(&tcp->tcp_eager_lock);
17390 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17391 		tcp_eager_cleanup(tcp, 0);
17392 	}
17393 	mutex_exit(&tcp->tcp_eager_lock);
17394 
17395 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17396 		tcp->tcp_ipha->ipha_src = 0;
17397 	} else {
17398 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17399 	}
17400 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17401 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17402 	tcp_bind_hash_remove(tcp);
17403 	tcp->tcp_state = TCPS_IDLE;
17404 	tcp->tcp_mdt = B_FALSE;
17405 
17406 	connp = tcp->tcp_connp;
17407 	connp->conn_mdt_ok = B_FALSE;
17408 	ipcl_hash_remove(connp);
17409 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17410 
17411 	return (error);
17412 }
17413 
17414 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17415 static void
17416 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
17417 {
17418 	int error = tcp_do_unbind(tcp->tcp_connp);
17419 
17420 	if (error > 0) {
17421 		tcp_err_ack(tcp, mp, TSYSERR, error);
17422 	} else if (error < 0) {
17423 		tcp_err_ack(tcp, mp, -error, 0);
17424 	} else {
17425 		/* Send M_FLUSH according to TPI */
17426 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17427 
17428 		mp = mi_tpi_ok_ack_alloc(mp);
17429 		putnext(tcp->tcp_rq, mp);
17430 	}
17431 }
17432 
17433 /*
17434  * Don't let port fall into the privileged range.
17435  * Since the extra privileged ports can be arbitrary we also
17436  * ensure that we exclude those from consideration.
17437  * tcp_g_epriv_ports is not sorted thus we loop over it until
17438  * there are no changes.
17439  *
17440  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17441  * but instead the code relies on:
17442  * - the fact that the address of the array and its size never changes
17443  * - the atomic assignment of the elements of the array
17444  *
17445  * Returns 0 if there are no more ports available.
17446  *
17447  * TS note: skip multilevel ports.
17448  */
17449 static in_port_t
17450 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17451 {
17452 	int i;
17453 	boolean_t restart = B_FALSE;
17454 	tcp_stack_t *tcps = tcp->tcp_tcps;
17455 
17456 	if (random && tcp_random_anon_port != 0) {
17457 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17458 		    sizeof (in_port_t));
17459 		/*
17460 		 * Unless changed by a sys admin, the smallest anon port
17461 		 * is 32768 and the largest anon port is 65535.  It is
17462 		 * very likely (50%) for the random port to be smaller
17463 		 * than the smallest anon port.  When that happens,
17464 		 * add port % (anon port range) to the smallest anon
17465 		 * port to get the random port.  It should fall into the
17466 		 * valid anon port range.
17467 		 */
17468 		if (port < tcps->tcps_smallest_anon_port) {
17469 			port = tcps->tcps_smallest_anon_port +
17470 			    port % (tcps->tcps_largest_anon_port -
17471 			    tcps->tcps_smallest_anon_port);
17472 		}
17473 	}
17474 
17475 retry:
17476 	if (port < tcps->tcps_smallest_anon_port)
17477 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17478 
17479 	if (port > tcps->tcps_largest_anon_port) {
17480 		if (restart)
17481 			return (0);
17482 		restart = B_TRUE;
17483 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17484 	}
17485 
17486 	if (port < tcps->tcps_smallest_nonpriv_port)
17487 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17488 
17489 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17490 		if (port == tcps->tcps_g_epriv_ports[i]) {
17491 			port++;
17492 			/*
17493 			 * Make sure whether the port is in the
17494 			 * valid range.
17495 			 */
17496 			goto retry;
17497 		}
17498 	}
17499 	if (is_system_labeled() &&
17500 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17501 	    IPPROTO_TCP, B_TRUE)) != 0) {
17502 		port = i;
17503 		goto retry;
17504 	}
17505 	return (port);
17506 }
17507 
17508 /*
17509  * Return the next anonymous port in the privileged port range for
17510  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17511  * downwards.  This is the same behavior as documented in the userland
17512  * library call rresvport(3N).
17513  *
17514  * TS note: skip multilevel ports.
17515  */
17516 static in_port_t
17517 tcp_get_next_priv_port(const tcp_t *tcp)
17518 {
17519 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17520 	in_port_t nextport;
17521 	boolean_t restart = B_FALSE;
17522 	tcp_stack_t *tcps = tcp->tcp_tcps;
17523 retry:
17524 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17525 	    next_priv_port >= IPPORT_RESERVED) {
17526 		next_priv_port = IPPORT_RESERVED - 1;
17527 		if (restart)
17528 			return (0);
17529 		restart = B_TRUE;
17530 	}
17531 	if (is_system_labeled() &&
17532 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17533 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17534 		next_priv_port = nextport;
17535 		goto retry;
17536 	}
17537 	return (next_priv_port--);
17538 }
17539 
17540 /* The write side r/w procedure. */
17541 
17542 #if CCS_STATS
17543 struct {
17544 	struct {
17545 		int64_t count, bytes;
17546 	} tot, hit;
17547 } wrw_stats;
17548 #endif
17549 
17550 /*
17551  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17552  * messages.
17553  */
17554 /* ARGSUSED */
17555 static void
17556 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17557 {
17558 	conn_t	*connp = (conn_t *)arg;
17559 	tcp_t	*tcp = connp->conn_tcp;
17560 	queue_t	*q = tcp->tcp_wq;
17561 
17562 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17563 	/*
17564 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17565 	 * Once the close starts, streamhead and sockfs will not let any data
17566 	 * packets come down (close ensures that there are no threads using the
17567 	 * queue and no new threads will come down) but since qprocsoff()
17568 	 * hasn't happened yet, a M_FLUSH or some non data message might
17569 	 * get reflected back (in response to our own FLUSHRW) and get
17570 	 * processed after tcp_close() is done. The conn would still be valid
17571 	 * because a ref would have added but we need to check the state
17572 	 * before actually processing the packet.
17573 	 */
17574 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17575 		freemsg(mp);
17576 		return;
17577 	}
17578 
17579 	switch (DB_TYPE(mp)) {
17580 	case M_IOCDATA:
17581 		tcp_wput_iocdata(tcp, mp);
17582 		break;
17583 	case M_FLUSH:
17584 		tcp_wput_flush(tcp, mp);
17585 		break;
17586 	default:
17587 		CALL_IP_WPUT(connp, q, mp);
17588 		break;
17589 	}
17590 }
17591 
17592 /*
17593  * The TCP fast path write put procedure.
17594  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17595  */
17596 /* ARGSUSED */
17597 void
17598 tcp_output(void *arg, mblk_t *mp, void *arg2)
17599 {
17600 	int		len;
17601 	int		hdrlen;
17602 	int		plen;
17603 	mblk_t		*mp1;
17604 	uchar_t		*rptr;
17605 	uint32_t	snxt;
17606 	tcph_t		*tcph;
17607 	struct datab	*db;
17608 	uint32_t	suna;
17609 	uint32_t	mss;
17610 	ipaddr_t	*dst;
17611 	ipaddr_t	*src;
17612 	uint32_t	sum;
17613 	int		usable;
17614 	conn_t		*connp = (conn_t *)arg;
17615 	tcp_t		*tcp = connp->conn_tcp;
17616 	uint32_t	msize;
17617 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17618 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17619 
17620 	/*
17621 	 * Try and ASSERT the minimum possible references on the
17622 	 * conn early enough. Since we are executing on write side,
17623 	 * the connection is obviously not detached and that means
17624 	 * there is a ref each for TCP and IP. Since we are behind
17625 	 * the squeue, the minimum references needed are 3. If the
17626 	 * conn is in classifier hash list, there should be an
17627 	 * extra ref for that (we check both the possibilities).
17628 	 */
17629 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17630 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17631 
17632 	ASSERT(DB_TYPE(mp) == M_DATA);
17633 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17634 
17635 	mutex_enter(&tcp->tcp_non_sq_lock);
17636 	tcp->tcp_squeue_bytes -= msize;
17637 	mutex_exit(&tcp->tcp_non_sq_lock);
17638 
17639 	/* Check to see if this connection wants to be re-fused. */
17640 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
17641 		if (tcp->tcp_ipversion == IPV4_VERSION) {
17642 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
17643 			    &tcp->tcp_saved_tcph);
17644 		} else {
17645 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
17646 			    &tcp->tcp_saved_tcph);
17647 		}
17648 	}
17649 	/* Bypass tcp protocol for fused tcp loopback */
17650 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17651 		return;
17652 
17653 	mss = tcp->tcp_mss;
17654 	if (tcp->tcp_xmit_zc_clean)
17655 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17656 
17657 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17658 	len = (int)(mp->b_wptr - mp->b_rptr);
17659 
17660 	/*
17661 	 * Criteria for fast path:
17662 	 *
17663 	 *   1. no unsent data
17664 	 *   2. single mblk in request
17665 	 *   3. connection established
17666 	 *   4. data in mblk
17667 	 *   5. len <= mss
17668 	 *   6. no tcp_valid bits
17669 	 */
17670 	if ((tcp->tcp_unsent != 0) ||
17671 	    (tcp->tcp_cork) ||
17672 	    (mp->b_cont != NULL) ||
17673 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17674 	    (len == 0) ||
17675 	    (len > mss) ||
17676 	    (tcp->tcp_valid_bits != 0)) {
17677 		tcp_wput_data(tcp, mp, B_FALSE);
17678 		return;
17679 	}
17680 
17681 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17682 	ASSERT(tcp->tcp_fin_sent == 0);
17683 
17684 	/* queue new packet onto retransmission queue */
17685 	if (tcp->tcp_xmit_head == NULL) {
17686 		tcp->tcp_xmit_head = mp;
17687 	} else {
17688 		tcp->tcp_xmit_last->b_cont = mp;
17689 	}
17690 	tcp->tcp_xmit_last = mp;
17691 	tcp->tcp_xmit_tail = mp;
17692 
17693 	/* find out how much we can send */
17694 	/* BEGIN CSTYLED */
17695 	/*
17696 	 *    un-acked	   usable
17697 	 *  |--------------|-----------------|
17698 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
17699 	 */
17700 	/* END CSTYLED */
17701 
17702 	/* start sending from tcp_snxt */
17703 	snxt = tcp->tcp_snxt;
17704 
17705 	/*
17706 	 * Check to see if this connection has been idled for some
17707 	 * time and no ACK is expected.  If it is, we need to slow
17708 	 * start again to get back the connection's "self-clock" as
17709 	 * described in VJ's paper.
17710 	 *
17711 	 * Refer to the comment in tcp_mss_set() for the calculation
17712 	 * of tcp_cwnd after idle.
17713 	 */
17714 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17715 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17716 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
17717 	}
17718 
17719 	usable = tcp->tcp_swnd;		/* tcp window size */
17720 	if (usable > tcp->tcp_cwnd)
17721 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17722 	usable -= snxt;		/* subtract stuff already sent */
17723 	suna = tcp->tcp_suna;
17724 	usable += suna;
17725 	/* usable can be < 0 if the congestion window is smaller */
17726 	if (len > usable) {
17727 		/* Can't send complete M_DATA in one shot */
17728 		goto slow;
17729 	}
17730 
17731 	mutex_enter(&tcp->tcp_non_sq_lock);
17732 	if (tcp->tcp_flow_stopped &&
17733 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17734 		tcp_clrqfull(tcp);
17735 	}
17736 	mutex_exit(&tcp->tcp_non_sq_lock);
17737 
17738 	/*
17739 	 * determine if anything to send (Nagle).
17740 	 *
17741 	 *   1. len < tcp_mss (i.e. small)
17742 	 *   2. unacknowledged data present
17743 	 *   3. len < nagle limit
17744 	 *   4. last packet sent < nagle limit (previous packet sent)
17745 	 */
17746 	if ((len < mss) && (snxt != suna) &&
17747 	    (len < (int)tcp->tcp_naglim) &&
17748 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17749 		/*
17750 		 * This was the first unsent packet and normally
17751 		 * mss < xmit_hiwater so there is no need to worry
17752 		 * about flow control. The next packet will go
17753 		 * through the flow control check in tcp_wput_data().
17754 		 */
17755 		/* leftover work from above */
17756 		tcp->tcp_unsent = len;
17757 		tcp->tcp_xmit_tail_unsent = len;
17758 
17759 		return;
17760 	}
17761 
17762 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17763 
17764 	if (snxt == suna) {
17765 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17766 	}
17767 
17768 	/* we have always sent something */
17769 	tcp->tcp_rack_cnt = 0;
17770 
17771 	tcp->tcp_snxt = snxt + len;
17772 	tcp->tcp_rack = tcp->tcp_rnxt;
17773 
17774 	if ((mp1 = dupb(mp)) == 0)
17775 		goto no_memory;
17776 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17777 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17778 
17779 	/* adjust tcp header information */
17780 	tcph = tcp->tcp_tcph;
17781 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17782 
17783 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17784 	sum = (sum >> 16) + (sum & 0xFFFF);
17785 	U16_TO_ABE16(sum, tcph->th_sum);
17786 
17787 	U32_TO_ABE32(snxt, tcph->th_seq);
17788 
17789 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17790 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17791 	BUMP_LOCAL(tcp->tcp_obsegs);
17792 
17793 	/* Update the latest receive window size in TCP header. */
17794 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17795 	    tcph->th_win);
17796 
17797 	tcp->tcp_last_sent_len = (ushort_t)len;
17798 
17799 	plen = len + tcp->tcp_hdr_len;
17800 
17801 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17802 		tcp->tcp_ipha->ipha_length = htons(plen);
17803 	} else {
17804 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17805 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17806 	}
17807 
17808 	/* see if we need to allocate a mblk for the headers */
17809 	hdrlen = tcp->tcp_hdr_len;
17810 	rptr = mp1->b_rptr - hdrlen;
17811 	db = mp1->b_datap;
17812 	if ((db->db_ref != 2) || rptr < db->db_base ||
17813 	    (!OK_32PTR(rptr))) {
17814 		/* NOTE: we assume allocb returns an OK_32PTR */
17815 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17816 		    tcps->tcps_wroff_xtra, BPRI_MED);
17817 		if (!mp) {
17818 			freemsg(mp1);
17819 			goto no_memory;
17820 		}
17821 		mp->b_cont = mp1;
17822 		mp1 = mp;
17823 		/* Leave room for Link Level header */
17824 		/* hdrlen = tcp->tcp_hdr_len; */
17825 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17826 		mp1->b_wptr = &rptr[hdrlen];
17827 	}
17828 	mp1->b_rptr = rptr;
17829 
17830 	/* Fill in the timestamp option. */
17831 	if (tcp->tcp_snd_ts_ok) {
17832 		U32_TO_BE32((uint32_t)lbolt,
17833 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17834 		U32_TO_BE32(tcp->tcp_ts_recent,
17835 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17836 	} else {
17837 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17838 	}
17839 
17840 	/* copy header into outgoing packet */
17841 	dst = (ipaddr_t *)rptr;
17842 	src = (ipaddr_t *)tcp->tcp_iphc;
17843 	dst[0] = src[0];
17844 	dst[1] = src[1];
17845 	dst[2] = src[2];
17846 	dst[3] = src[3];
17847 	dst[4] = src[4];
17848 	dst[5] = src[5];
17849 	dst[6] = src[6];
17850 	dst[7] = src[7];
17851 	dst[8] = src[8];
17852 	dst[9] = src[9];
17853 	if (hdrlen -= 40) {
17854 		hdrlen >>= 2;
17855 		dst += 10;
17856 		src += 10;
17857 		do {
17858 			*dst++ = *src++;
17859 		} while (--hdrlen);
17860 	}
17861 
17862 	/*
17863 	 * Set the ECN info in the TCP header.  Note that this
17864 	 * is not the template header.
17865 	 */
17866 	if (tcp->tcp_ecn_ok) {
17867 		SET_ECT(tcp, rptr);
17868 
17869 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17870 		if (tcp->tcp_ecn_echo_on)
17871 			tcph->th_flags[0] |= TH_ECE;
17872 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17873 			tcph->th_flags[0] |= TH_CWR;
17874 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17875 		}
17876 	}
17877 
17878 	if (tcp->tcp_ip_forward_progress) {
17879 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17880 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17881 		tcp->tcp_ip_forward_progress = B_FALSE;
17882 	}
17883 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17884 	return;
17885 
17886 	/*
17887 	 * If we ran out of memory, we pretend to have sent the packet
17888 	 * and that it was lost on the wire.
17889 	 */
17890 no_memory:
17891 	return;
17892 
17893 slow:
17894 	/* leftover work from above */
17895 	tcp->tcp_unsent = len;
17896 	tcp->tcp_xmit_tail_unsent = len;
17897 	tcp_wput_data(tcp, NULL, B_FALSE);
17898 }
17899 
17900 /* ARGSUSED */
17901 void
17902 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17903 {
17904 	conn_t			*connp = (conn_t *)arg;
17905 	tcp_t			*tcp = connp->conn_tcp;
17906 	queue_t			*q = tcp->tcp_rq;
17907 	struct tcp_options	*tcpopt;
17908 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17909 
17910 	/* socket options */
17911 	uint_t 			sopp_flags;
17912 	ssize_t			sopp_rxhiwat;
17913 	ssize_t			sopp_maxblk;
17914 	ushort_t		sopp_wroff;
17915 	ushort_t		sopp_tail;
17916 	ushort_t		sopp_copyopt;
17917 
17918 	tcpopt = (struct tcp_options *)mp->b_rptr;
17919 
17920 	/*
17921 	 * Drop the eager's ref on the listener, that was placed when
17922 	 * this eager began life in tcp_conn_request.
17923 	 */
17924 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17925 	if (IPCL_IS_NONSTR(connp)) {
17926 		/* Safe to free conn_ind message */
17927 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17928 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17929 
17930 		/* The listener tells us which upper handle to use */
17931 		ASSERT(tcpopt->to_flags & TCPOPT_UPPERHANDLE);
17932 		connp->conn_upper_handle = tcpopt->to_handle;
17933 	}
17934 
17935 	tcp->tcp_detached = B_FALSE;
17936 
17937 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17938 		/*
17939 		 * Someone blewoff the eager before we could finish
17940 		 * the accept.
17941 		 *
17942 		 * The only reason eager exists it because we put in
17943 		 * a ref on it when conn ind went up. We need to send
17944 		 * a disconnect indication up while the last reference
17945 		 * on the eager will be dropped by the squeue when we
17946 		 * return.
17947 		 */
17948 		ASSERT(tcp->tcp_listener == NULL);
17949 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17950 			if (IPCL_IS_NONSTR(connp)) {
17951 				ASSERT(tcp->tcp_issocket);
17952 				(*connp->conn_upcalls->su_disconnected)(
17953 				    connp->conn_upper_handle, tcp->tcp_connid,
17954 				    ECONNREFUSED);
17955 				freemsg(mp);
17956 			} else {
17957 				struct	T_discon_ind	*tdi;
17958 
17959 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17960 				/*
17961 				 * Let us reuse the incoming mblk to avoid
17962 				 * memory allocation failure problems. We know
17963 				 * that the size of the incoming mblk i.e.
17964 				 * stroptions is greater than sizeof
17965 				 * T_discon_ind. So the reallocb below can't
17966 				 * fail.
17967 				 */
17968 				freemsg(mp->b_cont);
17969 				mp->b_cont = NULL;
17970 				ASSERT(DB_REF(mp) == 1);
17971 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17972 				    B_FALSE);
17973 				ASSERT(mp != NULL);
17974 				DB_TYPE(mp) = M_PROTO;
17975 				((union T_primitives *)mp->b_rptr)->type =
17976 				    T_DISCON_IND;
17977 				tdi = (struct T_discon_ind *)mp->b_rptr;
17978 				if (tcp->tcp_issocket) {
17979 					tdi->DISCON_reason = ECONNREFUSED;
17980 					tdi->SEQ_number = 0;
17981 				} else {
17982 					tdi->DISCON_reason = ENOPROTOOPT;
17983 					tdi->SEQ_number =
17984 					    tcp->tcp_conn_req_seqnum;
17985 				}
17986 				mp->b_wptr = mp->b_rptr +
17987 				    sizeof (struct T_discon_ind);
17988 				putnext(q, mp);
17989 				return;
17990 			}
17991 		}
17992 		if (tcp->tcp_hard_binding) {
17993 			tcp->tcp_hard_binding = B_FALSE;
17994 			tcp->tcp_hard_bound = B_TRUE;
17995 		}
17996 		return;
17997 	}
17998 
17999 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
18000 		int boundif = tcpopt->to_boundif;
18001 		uint_t len = sizeof (int);
18002 
18003 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
18004 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
18005 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred, NULL);
18006 	}
18007 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
18008 		uint_t on = 1;
18009 		uint_t len = sizeof (uint_t);
18010 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
18011 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
18012 		    (uchar_t *)&on, NULL, tcp->tcp_cred, NULL);
18013 	}
18014 
18015 	/*
18016 	 * For a loopback connection with tcp_direct_sockfs on, note that
18017 	 * we don't have to protect tcp_rcv_list yet because synchronous
18018 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
18019 	 * possibly race with us.
18020 	 */
18021 
18022 	/*
18023 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
18024 	 * properly.  This is the first time we know of the acceptor'
18025 	 * queue.  So we do it here.
18026 	 *
18027 	 * XXX
18028 	 */
18029 	if (tcp->tcp_rcv_list == NULL) {
18030 		/*
18031 		 * Recv queue is empty, tcp_rwnd should not have changed.
18032 		 * That means it should be equal to the listener's tcp_rwnd.
18033 		 */
18034 		if (!IPCL_IS_NONSTR(connp))
18035 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
18036 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
18037 	} else {
18038 #ifdef DEBUG
18039 		mblk_t *tmp;
18040 		mblk_t	*mp1;
18041 		uint_t	cnt = 0;
18042 
18043 		mp1 = tcp->tcp_rcv_list;
18044 		while ((tmp = mp1) != NULL) {
18045 			mp1 = tmp->b_next;
18046 			cnt += msgdsize(tmp);
18047 		}
18048 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
18049 #endif
18050 		/* There is some data, add them back to get the max. */
18051 		if (!IPCL_IS_NONSTR(connp))
18052 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
18053 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
18054 	}
18055 	/*
18056 	 * This is the first time we run on the correct
18057 	 * queue after tcp_accept. So fix all the q parameters
18058 	 * here.
18059 	 */
18060 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
18061 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
18062 
18063 	/*
18064 	 * Record the stream head's high water mark for this endpoint;
18065 	 * this is used for flow-control purposes.
18066 	 */
18067 	sopp_rxhiwat = tcp->tcp_fused ?
18068 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
18069 	    MAX(tcp->tcp_recv_hiwater, tcps->tcps_sth_rcv_hiwat);
18070 
18071 	/*
18072 	 * Determine what write offset value to use depending on SACK and
18073 	 * whether the endpoint is fused or not.
18074 	 */
18075 	if (tcp->tcp_fused) {
18076 		ASSERT(tcp->tcp_loopback);
18077 		ASSERT(tcp->tcp_loopback_peer != NULL);
18078 		/*
18079 		 * For fused tcp loopback, set the stream head's write
18080 		 * offset value to zero since we won't be needing any room
18081 		 * for TCP/IP headers.  This would also improve performance
18082 		 * since it would reduce the amount of work done by kmem.
18083 		 * Non-fused tcp loopback case is handled separately below.
18084 		 */
18085 		sopp_wroff = 0;
18086 		/*
18087 		 * Update the peer's transmit parameters according to
18088 		 * our recently calculated high water mark value.
18089 		 */
18090 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
18091 	} else if (tcp->tcp_snd_sack_ok) {
18092 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
18093 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
18094 	} else {
18095 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
18096 		    tcps->tcps_wroff_xtra);
18097 	}
18098 
18099 	/*
18100 	 * If this is endpoint is handling SSL, then reserve extra
18101 	 * offset and space at the end.
18102 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
18103 	 * overriding the previous setting. The extra cost of signing and
18104 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
18105 	 * instead of a single contiguous one by the stream head
18106 	 * largely outweighs the statistical reduction of ACKs, when
18107 	 * applicable. The peer will also save on decryption and verification
18108 	 * costs.
18109 	 */
18110 	if (tcp->tcp_kssl_ctx != NULL) {
18111 		sopp_wroff += SSL3_WROFFSET;
18112 
18113 		sopp_flags |= SOCKOPT_TAIL;
18114 		sopp_tail = SSL3_MAX_TAIL_LEN;
18115 
18116 		sopp_flags |= SOCKOPT_ZCOPY;
18117 		sopp_copyopt = ZCVMUNSAFE;
18118 
18119 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
18120 	}
18121 
18122 	/* Send the options up */
18123 	if (IPCL_IS_NONSTR(connp)) {
18124 		struct sock_proto_props sopp;
18125 
18126 		sopp.sopp_flags = sopp_flags;
18127 		sopp.sopp_wroff = sopp_wroff;
18128 		sopp.sopp_maxblk = sopp_maxblk;
18129 		sopp.sopp_rxhiwat = sopp_rxhiwat;
18130 		if (sopp_flags & SOCKOPT_TAIL) {
18131 			ASSERT(tcp->tcp_kssl_ctx != NULL);
18132 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
18133 			sopp.sopp_tail = sopp_tail;
18134 			sopp.sopp_zcopyflag = sopp_copyopt;
18135 		}
18136 		(*connp->conn_upcalls->su_set_proto_props)
18137 		    (connp->conn_upper_handle, &sopp);
18138 	} else {
18139 		struct stroptions *stropt;
18140 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18141 		if (stropt_mp == NULL) {
18142 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
18143 			return;
18144 		}
18145 		DB_TYPE(stropt_mp) = M_SETOPTS;
18146 		stropt = (struct stroptions *)stropt_mp->b_rptr;
18147 		stropt_mp->b_wptr += sizeof (struct stroptions);
18148 		stropt = (struct stroptions *)stropt_mp->b_rptr;
18149 		stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
18150 		stropt->so_hiwat = sopp_rxhiwat;
18151 		stropt->so_wroff = sopp_wroff;
18152 		stropt->so_maxblk = sopp_maxblk;
18153 
18154 		if (sopp_flags & SOCKOPT_TAIL) {
18155 			ASSERT(tcp->tcp_kssl_ctx != NULL);
18156 
18157 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
18158 			stropt->so_tail = sopp_tail;
18159 			stropt->so_copyopt = sopp_copyopt;
18160 		}
18161 
18162 		/* Send the options up */
18163 		putnext(q, stropt_mp);
18164 	}
18165 
18166 	freemsg(mp);
18167 	/*
18168 	 * Pass up any data and/or a fin that has been received.
18169 	 *
18170 	 * Adjust receive window in case it had decreased
18171 	 * (because there is data <=> tcp_rcv_list != NULL)
18172 	 * while the connection was detached. Note that
18173 	 * in case the eager was flow-controlled, w/o this
18174 	 * code, the rwnd may never open up again!
18175 	 */
18176 	if (tcp->tcp_rcv_list != NULL) {
18177 		if (IPCL_IS_NONSTR(connp)) {
18178 			mblk_t *mp;
18179 			int space_left;
18180 			int error;
18181 			boolean_t push = B_TRUE;
18182 
18183 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
18184 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
18185 			    &push) >= 0) {
18186 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
18187 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18188 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
18189 					tcp_xmit_ctl(NULL,
18190 					    tcp, (tcp->tcp_swnd == 0) ?
18191 					    tcp->tcp_suna : tcp->tcp_snxt,
18192 					    tcp->tcp_rnxt, TH_ACK);
18193 				}
18194 			}
18195 			while ((mp = tcp->tcp_rcv_list) != NULL) {
18196 				push = B_TRUE;
18197 				tcp->tcp_rcv_list = mp->b_next;
18198 				mp->b_next = NULL;
18199 				space_left = (*connp->conn_upcalls->su_recv)
18200 				    (connp->conn_upper_handle, mp, msgdsize(mp),
18201 				    0, &error, &push);
18202 				if (space_left < 0) {
18203 					/*
18204 					 * At this point the eager is not
18205 					 * visible to anyone, so fallback
18206 					 * can not happen.
18207 					 */
18208 					ASSERT(error != EOPNOTSUPP);
18209 				}
18210 			}
18211 			tcp->tcp_rcv_last_head = NULL;
18212 			tcp->tcp_rcv_last_tail = NULL;
18213 			tcp->tcp_rcv_cnt = 0;
18214 		} else {
18215 			/* We drain directly in case of fused tcp loopback */
18216 			sodirect_t *sodp;
18217 
18218 			if (!tcp->tcp_fused && canputnext(q)) {
18219 				tcp->tcp_rwnd = q->q_hiwat;
18220 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18221 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
18222 					tcp_xmit_ctl(NULL,
18223 					    tcp, (tcp->tcp_swnd == 0) ?
18224 					    tcp->tcp_suna : tcp->tcp_snxt,
18225 					    tcp->tcp_rnxt, TH_ACK);
18226 				}
18227 			}
18228 
18229 			SOD_PTR_ENTER(tcp, sodp);
18230 			if (sodp != NULL) {
18231 				/* Sodirect, move from rcv_list */
18232 				ASSERT(!tcp->tcp_fused);
18233 				while ((mp = tcp->tcp_rcv_list) != NULL) {
18234 					tcp->tcp_rcv_list = mp->b_next;
18235 					mp->b_next = NULL;
18236 					(void) tcp_rcv_sod_enqueue(tcp, sodp,
18237 					    mp, msgdsize(mp));
18238 				}
18239 				tcp->tcp_rcv_last_head = NULL;
18240 				tcp->tcp_rcv_last_tail = NULL;
18241 				tcp->tcp_rcv_cnt = 0;
18242 				(void) tcp_rcv_sod_wakeup(tcp, sodp);
18243 				/* sod_wakeup() did the mutex_exit() */
18244 			} else {
18245 				/* Not sodirect, drain */
18246 				(void) tcp_rcv_drain(tcp);
18247 			}
18248 		}
18249 
18250 		/*
18251 		 * For fused tcp loopback, back-enable peer endpoint
18252 		 * if it's currently flow-controlled.
18253 		 */
18254 		if (tcp->tcp_fused) {
18255 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18256 
18257 			ASSERT(peer_tcp != NULL);
18258 			ASSERT(peer_tcp->tcp_fused);
18259 			/*
18260 			 * In order to change the peer's tcp_flow_stopped,
18261 			 * we need to take locks for both end points. The
18262 			 * highest address is taken first.
18263 			 */
18264 			if (peer_tcp > tcp) {
18265 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18266 				mutex_enter(&tcp->tcp_non_sq_lock);
18267 			} else {
18268 				mutex_enter(&tcp->tcp_non_sq_lock);
18269 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18270 			}
18271 			if (peer_tcp->tcp_flow_stopped) {
18272 				tcp_clrqfull(peer_tcp);
18273 				TCP_STAT(tcps, tcp_fusion_backenabled);
18274 			}
18275 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18276 			mutex_exit(&tcp->tcp_non_sq_lock);
18277 		}
18278 	}
18279 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18280 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18281 		tcp->tcp_ordrel_done = B_TRUE;
18282 		if (IPCL_IS_NONSTR(connp)) {
18283 			ASSERT(tcp->tcp_ordrel_mp == NULL);
18284 			(*connp->conn_upcalls->su_opctl)(
18285 			    connp->conn_upper_handle,
18286 			    SOCK_OPCTL_SHUT_RECV, 0);
18287 		} else {
18288 			mp = tcp->tcp_ordrel_mp;
18289 			tcp->tcp_ordrel_mp = NULL;
18290 			putnext(q, mp);
18291 		}
18292 	}
18293 	if (tcp->tcp_hard_binding) {
18294 		tcp->tcp_hard_binding = B_FALSE;
18295 		tcp->tcp_hard_bound = B_TRUE;
18296 	}
18297 
18298 	/* We can enable synchronous streams for STREAMS tcp endpoint now */
18299 	if (tcp->tcp_fused && !IPCL_IS_NONSTR(connp) &&
18300 	    tcp->tcp_loopback_peer != NULL &&
18301 	    !IPCL_IS_NONSTR(tcp->tcp_loopback_peer->tcp_connp)) {
18302 		tcp_fuse_syncstr_enable_pair(tcp);
18303 	}
18304 
18305 	if (tcp->tcp_ka_enabled) {
18306 		tcp->tcp_ka_last_intrvl = 0;
18307 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18308 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18309 	}
18310 
18311 	/*
18312 	 * At this point, eager is fully established and will
18313 	 * have the following references -
18314 	 *
18315 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18316 	 * 1 reference for the squeue which will be dropped by the squeue as
18317 	 *	soon as this function returns.
18318 	 * There will be 1 additonal reference for being in classifier
18319 	 *	hash list provided something bad hasn't happened.
18320 	 */
18321 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18322 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18323 }
18324 
18325 /*
18326  * The function called through squeue to get behind listener's perimeter to
18327  * send a deffered conn_ind.
18328  */
18329 /* ARGSUSED */
18330 void
18331 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18332 {
18333 	conn_t	*connp = (conn_t *)arg;
18334 	tcp_t *listener = connp->conn_tcp;
18335 	struct T_conn_ind *conn_ind;
18336 	tcp_t *tcp;
18337 
18338 	if (listener->tcp_state == TCPS_CLOSED ||
18339 	    TCP_IS_DETACHED(listener)) {
18340 		/*
18341 		 * If listener has closed, it would have caused a
18342 		 * a cleanup/blowoff to happen for the eager.
18343 		 */
18344 
18345 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18346 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18347 		    conn_ind->OPT_length);
18348 		/*
18349 		 * We need to drop the ref on eager that was put
18350 		 * tcp_rput_data() before trying to send the conn_ind
18351 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18352 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18353 		 * listener is closed so we drop the ref.
18354 		 */
18355 		CONN_DEC_REF(tcp->tcp_connp);
18356 		freemsg(mp);
18357 		return;
18358 	}
18359 	if (IPCL_IS_NONSTR(connp)) {
18360 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18361 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18362 		    conn_ind->OPT_length);
18363 
18364 		if ((*connp->conn_upcalls->su_newconn)
18365 		    (connp->conn_upper_handle,
18366 		    (sock_lower_handle_t)tcp->tcp_connp,
18367 		    &sock_tcp_downcalls, DB_CRED(mp), DB_CPID(mp),
18368 		    &tcp->tcp_connp->conn_upcalls) != NULL) {
18369 			/* Keep the message around in case of fallback */
18370 			tcp->tcp_conn.tcp_eager_conn_ind = mp;
18371 		} else {
18372 			freemsg(mp);
18373 		}
18374 	} else {
18375 		putnext(listener->tcp_rq, mp);
18376 	}
18377 }
18378 
18379 /* ARGSUSED */
18380 static int
18381 tcp_accept_common(conn_t *lconnp, conn_t *econnp,
18382     sock_upper_handle_t sock_handle, cred_t *cr)
18383 {
18384 	tcp_t *listener, *eager;
18385 	mblk_t *opt_mp;
18386 	struct tcp_options *tcpopt;
18387 
18388 	listener = lconnp->conn_tcp;
18389 	ASSERT(listener->tcp_state == TCPS_LISTEN);
18390 	eager = econnp->conn_tcp;
18391 	ASSERT(eager->tcp_listener != NULL);
18392 
18393 	ASSERT(eager->tcp_rq != NULL);
18394 
18395 	/* If tcp_fused and sodirect enabled disable it */
18396 	if (eager->tcp_fused && eager->tcp_sodirect != NULL) {
18397 		/* Fused, disable sodirect */
18398 		mutex_enter(eager->tcp_sodirect->sod_lockp);
18399 		SOD_DISABLE(eager->tcp_sodirect);
18400 		mutex_exit(eager->tcp_sodirect->sod_lockp);
18401 		eager->tcp_sodirect = NULL;
18402 	}
18403 
18404 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
18405 	if (opt_mp == NULL) {
18406 		return (-TPROTO);
18407 	}
18408 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
18409 	eager->tcp_issocket = B_TRUE;
18410 
18411 	econnp->conn_upcalls = lconnp->conn_upcalls;
18412 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18413 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18414 	ASSERT(econnp->conn_netstack ==
18415 	    listener->tcp_connp->conn_netstack);
18416 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18417 
18418 	/* Put the ref for IP */
18419 	CONN_INC_REF(econnp);
18420 
18421 	/*
18422 	 * We should have minimum of 3 references on the conn
18423 	 * at this point. One each for TCP and IP and one for
18424 	 * the T_conn_ind that was sent up when the 3-way handshake
18425 	 * completed. In the normal case we would also have another
18426 	 * reference (making a total of 4) for the conn being in the
18427 	 * classifier hash list. However the eager could have received
18428 	 * an RST subsequently and tcp_closei_local could have removed
18429 	 * the eager from the classifier hash list, hence we can't
18430 	 * assert that reference.
18431 	 */
18432 	ASSERT(econnp->conn_ref >= 3);
18433 
18434 	opt_mp->b_datap->db_type = M_SETOPTS;
18435 	opt_mp->b_wptr += sizeof (struct tcp_options);
18436 
18437 	/*
18438 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18439 	 * from listener to acceptor. In case of non-STREAMS sockets,
18440 	 * we also need to pass the upper handle along.
18441 	 */
18442 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
18443 	tcpopt->to_flags = 0;
18444 
18445 	if (IPCL_IS_NONSTR(econnp)) {
18446 		ASSERT(sock_handle != NULL);
18447 		tcpopt->to_flags |= TCPOPT_UPPERHANDLE;
18448 		tcpopt->to_handle = sock_handle;
18449 	}
18450 	if (listener->tcp_bound_if != 0) {
18451 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
18452 		tcpopt->to_boundif = listener->tcp_bound_if;
18453 	}
18454 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18455 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
18456 	}
18457 
18458 	mutex_enter(&listener->tcp_eager_lock);
18459 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18460 
18461 		tcp_t *tail;
18462 		tcp_t *tcp;
18463 		mblk_t *mp1;
18464 
18465 		tcp = listener->tcp_eager_prev_q0;
18466 		/*
18467 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
18468 		 * deferred T_conn_ind queue. We need to get to the head
18469 		 * of the queue in order to send up T_conn_ind the same
18470 		 * order as how the 3WHS is completed.
18471 		 */
18472 		while (tcp != listener) {
18473 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18474 			    !tcp->tcp_kssl_pending)
18475 				break;
18476 			else
18477 				tcp = tcp->tcp_eager_prev_q0;
18478 		}
18479 		/* None of the pending eagers can be sent up now */
18480 		if (tcp == listener)
18481 			goto no_more_eagers;
18482 
18483 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18484 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18485 		/* Move from q0 to q */
18486 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18487 		listener->tcp_conn_req_cnt_q0--;
18488 		listener->tcp_conn_req_cnt_q++;
18489 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18490 		    tcp->tcp_eager_prev_q0;
18491 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18492 		    tcp->tcp_eager_next_q0;
18493 		tcp->tcp_eager_prev_q0 = NULL;
18494 		tcp->tcp_eager_next_q0 = NULL;
18495 		tcp->tcp_conn_def_q0 = B_FALSE;
18496 
18497 		/* Make sure the tcp isn't in the list of droppables */
18498 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18499 		    tcp->tcp_eager_prev_drop_q0 == NULL);
18500 
18501 		/*
18502 		 * Insert at end of the queue because sockfs sends
18503 		 * down T_CONN_RES in chronological order. Leaving
18504 		 * the older conn indications at front of the queue
18505 		 * helps reducing search time.
18506 		 */
18507 		tail = listener->tcp_eager_last_q;
18508 		if (tail != NULL) {
18509 			tail->tcp_eager_next_q = tcp;
18510 		} else {
18511 			listener->tcp_eager_next_q = tcp;
18512 		}
18513 		listener->tcp_eager_last_q = tcp;
18514 		tcp->tcp_eager_next_q = NULL;
18515 
18516 		/* Need to get inside the listener perimeter */
18517 		CONN_INC_REF(listener->tcp_connp);
18518 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
18519 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
18520 		    SQTAG_TCP_SEND_PENDING);
18521 	}
18522 no_more_eagers:
18523 	tcp_eager_unlink(eager);
18524 	mutex_exit(&listener->tcp_eager_lock);
18525 
18526 	/*
18527 	 * At this point, the eager is detached from the listener
18528 	 * but we still have an extra refs on eager (apart from the
18529 	 * usual tcp references). The ref was placed in tcp_rput_data
18530 	 * before sending the conn_ind in tcp_send_conn_ind.
18531 	 * The ref will be dropped in tcp_accept_finish().
18532 	 */
18533 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
18534 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
18535 	return (0);
18536 }
18537 
18538 int
18539 tcp_accept(sock_lower_handle_t lproto_handle,
18540     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
18541     cred_t *cr)
18542 {
18543 	conn_t *lconnp, *econnp;
18544 	tcp_t *listener, *eager;
18545 	tcp_stack_t	*tcps;
18546 
18547 	lconnp = (conn_t *)lproto_handle;
18548 	listener = lconnp->conn_tcp;
18549 	ASSERT(listener->tcp_state == TCPS_LISTEN);
18550 	econnp = (conn_t *)eproto_handle;
18551 	eager = econnp->conn_tcp;
18552 	ASSERT(eager->tcp_listener != NULL);
18553 	tcps = eager->tcp_tcps;
18554 
18555 	ASSERT(IPCL_IS_NONSTR(econnp));
18556 	/*
18557 	 * Create helper stream if it is a non-TPI TCP connection.
18558 	 */
18559 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
18560 		ip1dbg(("tcp_accept: create of IP helper stream"
18561 		    " failed\n"));
18562 		return (EPROTO);
18563 	}
18564 	eager->tcp_rq = econnp->conn_rq;
18565 	eager->tcp_wq = econnp->conn_wq;
18566 
18567 	ASSERT(eager->tcp_rq != NULL);
18568 
18569 	eager->tcp_sodirect = SOD_SOTOSODP(sock_handle);
18570 	return (tcp_accept_common(lconnp, econnp, sock_handle, cr));
18571 }
18572 
18573 
18574 /*
18575  * This is the STREAMS entry point for T_CONN_RES coming down on
18576  * Acceptor STREAM when  sockfs listener does accept processing.
18577  * Read the block comment on top of tcp_conn_request().
18578  */
18579 void
18580 tcp_tpi_accept(queue_t *q, mblk_t *mp)
18581 {
18582 	queue_t *rq = RD(q);
18583 	struct T_conn_res *conn_res;
18584 	tcp_t *eager;
18585 	tcp_t *listener;
18586 	struct T_ok_ack *ok;
18587 	t_scalar_t PRIM_type;
18588 	conn_t *econnp;
18589 
18590 	ASSERT(DB_TYPE(mp) == M_PROTO);
18591 
18592 	conn_res = (struct T_conn_res *)mp->b_rptr;
18593 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18594 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18595 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18596 		if (mp != NULL)
18597 			putnext(rq, mp);
18598 		return;
18599 	}
18600 	switch (conn_res->PRIM_type) {
18601 	case O_T_CONN_RES:
18602 	case T_CONN_RES:
18603 		/*
18604 		 * We pass up an err ack if allocb fails. This will
18605 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18606 		 * tcp_eager_blowoff to be called. sockfs will then call
18607 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18608 		 * we need to do the allocb up here because we have to
18609 		 * make sure rq->q_qinfo->qi_qclose still points to the
18610 		 * correct function (tcpclose_accept) in case allocb
18611 		 * fails.
18612 		 */
18613 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18614 		    &eager, conn_res->OPT_length);
18615 		PRIM_type = conn_res->PRIM_type;
18616 		mp->b_datap->db_type = M_PCPROTO;
18617 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18618 		ok = (struct T_ok_ack *)mp->b_rptr;
18619 		ok->PRIM_type = T_OK_ACK;
18620 		ok->CORRECT_prim = PRIM_type;
18621 		econnp = eager->tcp_connp;
18622 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
18623 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
18624 		eager->tcp_rq = rq;
18625 		eager->tcp_wq = q;
18626 		rq->q_ptr = econnp;
18627 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
18628 		q->q_ptr = econnp;
18629 		q->q_qinfo = &tcp_winit;
18630 		listener = eager->tcp_listener;
18631 
18632 		/*
18633 		 * TCP is _D_SODIRECT and sockfs is directly above so
18634 		 * save shared sodirect_t pointer (if any).
18635 		 */
18636 		eager->tcp_sodirect = SOD_QTOSODP(eager->tcp_rq);
18637 		if (tcp_accept_common(listener->tcp_connp,
18638 		    econnp, NULL, CRED()) < 0) {
18639 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18640 			if (mp != NULL)
18641 				putnext(rq, mp);
18642 			return;
18643 		}
18644 
18645 		/*
18646 		 * Send the new local address also up to sockfs. There
18647 		 * should already be enough space in the mp that came
18648 		 * down from soaccept().
18649 		 */
18650 		if (eager->tcp_family == AF_INET) {
18651 			sin_t *sin;
18652 
18653 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18654 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18655 			sin = (sin_t *)mp->b_wptr;
18656 			mp->b_wptr += sizeof (sin_t);
18657 			sin->sin_family = AF_INET;
18658 			sin->sin_port = eager->tcp_lport;
18659 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18660 		} else {
18661 			sin6_t *sin6;
18662 
18663 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18664 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18665 			sin6 = (sin6_t *)mp->b_wptr;
18666 			mp->b_wptr += sizeof (sin6_t);
18667 			sin6->sin6_family = AF_INET6;
18668 			sin6->sin6_port = eager->tcp_lport;
18669 			if (eager->tcp_ipversion == IPV4_VERSION) {
18670 				sin6->sin6_flowinfo = 0;
18671 				IN6_IPADDR_TO_V4MAPPED(
18672 				    eager->tcp_ipha->ipha_src,
18673 				    &sin6->sin6_addr);
18674 			} else {
18675 				ASSERT(eager->tcp_ip6h != NULL);
18676 				sin6->sin6_flowinfo =
18677 				    eager->tcp_ip6h->ip6_vcf &
18678 				    ~IPV6_VERS_AND_FLOW_MASK;
18679 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18680 			}
18681 			sin6->sin6_scope_id = 0;
18682 			sin6->__sin6_src_id = 0;
18683 		}
18684 
18685 		putnext(rq, mp);
18686 		return;
18687 	default:
18688 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18689 		if (mp != NULL)
18690 			putnext(rq, mp);
18691 		return;
18692 	}
18693 }
18694 
18695 static int
18696 tcp_getmyname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18697 {
18698 	sin_t *sin = (sin_t *)sa;
18699 	sin6_t *sin6 = (sin6_t *)sa;
18700 
18701 	switch (tcp->tcp_family) {
18702 	case AF_INET:
18703 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18704 
18705 		if (*salenp < sizeof (sin_t))
18706 			return (EINVAL);
18707 
18708 		*sin = sin_null;
18709 		sin->sin_family = AF_INET;
18710 		sin->sin_port = tcp->tcp_lport;
18711 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
18712 		break;
18713 
18714 	case AF_INET6:
18715 		if (*salenp < sizeof (sin6_t))
18716 			return (EINVAL);
18717 
18718 		*sin6 = sin6_null;
18719 		sin6->sin6_family = AF_INET6;
18720 		sin6->sin6_port = tcp->tcp_lport;
18721 		if (tcp->tcp_ipversion == IPV4_VERSION) {
18722 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
18723 			    &sin6->sin6_addr);
18724 		} else {
18725 			sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
18726 		}
18727 		break;
18728 	}
18729 
18730 	return (0);
18731 }
18732 
18733 static int
18734 i_tcp_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18735 {
18736 	sin_t *sin = (sin_t *)sa;
18737 	sin6_t *sin6 = (sin6_t *)sa;
18738 
18739 	if (tcp->tcp_state < TCPS_SYN_RCVD)
18740 		return (ENOTCONN);
18741 
18742 	switch (tcp->tcp_family) {
18743 	case AF_INET:
18744 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18745 
18746 		if (*salenp < sizeof (sin_t))
18747 			return (EINVAL);
18748 
18749 		*sin = sin_null;
18750 		sin->sin_family = AF_INET;
18751 		sin->sin_port = tcp->tcp_fport;
18752 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
18753 		    sin->sin_addr.s_addr);
18754 		*salenp = sizeof (sin_t);
18755 		break;
18756 
18757 	case AF_INET6:
18758 		if (*salenp < sizeof (sin6_t))
18759 			return (EINVAL);
18760 
18761 		*sin6 = sin6_null;
18762 		sin6->sin6_family = AF_INET6;
18763 		sin6->sin6_port = tcp->tcp_fport;
18764 		sin6->sin6_addr = tcp->tcp_remote_v6;
18765 		if (tcp->tcp_ipversion == IPV6_VERSION) {
18766 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
18767 			    ~IPV6_VERS_AND_FLOW_MASK;
18768 		}
18769 		*salenp = sizeof (sin6_t);
18770 		break;
18771 	}
18772 
18773 	return (0);
18774 }
18775 
18776 /*
18777  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
18778  */
18779 static void
18780 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
18781 {
18782 	void	*data;
18783 	mblk_t	*datamp = mp->b_cont;
18784 	tcp_t	*tcp = Q_TO_TCP(q);
18785 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
18786 
18787 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
18788 		cmdp->cb_error = EPROTO;
18789 		qreply(q, mp);
18790 		return;
18791 	}
18792 
18793 	data = datamp->b_rptr;
18794 
18795 	switch (cmdp->cb_cmd) {
18796 	case TI_GETPEERNAME:
18797 		cmdp->cb_error = i_tcp_getpeername(tcp, data, &cmdp->cb_len);
18798 		break;
18799 	case TI_GETMYNAME:
18800 		cmdp->cb_error = tcp_getmyname(tcp, data, &cmdp->cb_len);
18801 		break;
18802 	default:
18803 		cmdp->cb_error = EINVAL;
18804 		break;
18805 	}
18806 
18807 	qreply(q, mp);
18808 }
18809 
18810 void
18811 tcp_wput(queue_t *q, mblk_t *mp)
18812 {
18813 	conn_t	*connp = Q_TO_CONN(q);
18814 	tcp_t	*tcp;
18815 	void (*output_proc)();
18816 	t_scalar_t type;
18817 	uchar_t *rptr;
18818 	struct iocblk	*iocp;
18819 	size_t size;
18820 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18821 
18822 	ASSERT(connp->conn_ref >= 2);
18823 
18824 	switch (DB_TYPE(mp)) {
18825 	case M_DATA:
18826 		tcp = connp->conn_tcp;
18827 		ASSERT(tcp != NULL);
18828 
18829 		size = msgdsize(mp);
18830 
18831 		mutex_enter(&tcp->tcp_non_sq_lock);
18832 		tcp->tcp_squeue_bytes += size;
18833 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18834 			tcp_setqfull(tcp);
18835 		}
18836 		mutex_exit(&tcp->tcp_non_sq_lock);
18837 
18838 		if (DB_CRED(mp) == NULL && is_system_labeled())
18839 			msg_setcredpid(mp, CONN_CRED(connp), curproc->p_pid);
18840 
18841 		CONN_INC_REF(connp);
18842 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18843 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18844 		return;
18845 
18846 	case M_CMD:
18847 		tcp_wput_cmdblk(q, mp);
18848 		return;
18849 
18850 	case M_PROTO:
18851 	case M_PCPROTO:
18852 		/*
18853 		 * if it is a snmp message, don't get behind the squeue
18854 		 */
18855 		tcp = connp->conn_tcp;
18856 		rptr = mp->b_rptr;
18857 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18858 			type = ((union T_primitives *)rptr)->type;
18859 		} else {
18860 			if (tcp->tcp_debug) {
18861 				(void) strlog(TCP_MOD_ID, 0, 1,
18862 				    SL_ERROR|SL_TRACE,
18863 				    "tcp_wput_proto, dropping one...");
18864 			}
18865 			freemsg(mp);
18866 			return;
18867 		}
18868 		if (type == T_SVR4_OPTMGMT_REQ) {
18869 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
18870 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18871 			    cr)) {
18872 				/*
18873 				 * This was a SNMP request
18874 				 */
18875 				return;
18876 			} else {
18877 				output_proc = tcp_wput_proto;
18878 			}
18879 		} else {
18880 			output_proc = tcp_wput_proto;
18881 		}
18882 		break;
18883 	case M_IOCTL:
18884 		/*
18885 		 * Most ioctls can be processed right away without going via
18886 		 * squeues - process them right here. Those that do require
18887 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18888 		 * are processed by tcp_wput_ioctl().
18889 		 */
18890 		iocp = (struct iocblk *)mp->b_rptr;
18891 		tcp = connp->conn_tcp;
18892 
18893 		switch (iocp->ioc_cmd) {
18894 		case TCP_IOC_ABORT_CONN:
18895 			tcp_ioctl_abort_conn(q, mp);
18896 			return;
18897 		case TI_GETPEERNAME:
18898 		case TI_GETMYNAME:
18899 			mi_copyin(q, mp, NULL,
18900 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18901 			return;
18902 		case ND_SET:
18903 			/* nd_getset does the necessary checks */
18904 		case ND_GET:
18905 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18906 				CALL_IP_WPUT(connp, q, mp);
18907 				return;
18908 			}
18909 			qreply(q, mp);
18910 			return;
18911 		case TCP_IOC_DEFAULT_Q:
18912 			/*
18913 			 * Wants to be the default wq. Check the credentials
18914 			 * first, the rest is executed via squeue.
18915 			 */
18916 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18917 				iocp->ioc_error = EPERM;
18918 				iocp->ioc_count = 0;
18919 				mp->b_datap->db_type = M_IOCACK;
18920 				qreply(q, mp);
18921 				return;
18922 			}
18923 			output_proc = tcp_wput_ioctl;
18924 			break;
18925 		default:
18926 			output_proc = tcp_wput_ioctl;
18927 			break;
18928 		}
18929 		break;
18930 	default:
18931 		output_proc = tcp_wput_nondata;
18932 		break;
18933 	}
18934 
18935 	CONN_INC_REF(connp);
18936 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18937 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18938 }
18939 
18940 /*
18941  * Initial STREAMS write side put() procedure for sockets. It tries to
18942  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18943  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18944  * are handled by tcp_wput() as usual.
18945  *
18946  * All further messages will also be handled by tcp_wput() because we cannot
18947  * be sure that the above short cut is safe later.
18948  */
18949 static void
18950 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18951 {
18952 	conn_t			*connp = Q_TO_CONN(wq);
18953 	tcp_t			*tcp = connp->conn_tcp;
18954 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18955 
18956 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18957 	wq->q_qinfo = &tcp_winit;
18958 
18959 	ASSERT(IPCL_IS_TCP(connp));
18960 	ASSERT(TCP_IS_SOCKET(tcp));
18961 
18962 	if (DB_TYPE(mp) == M_PCPROTO &&
18963 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18964 	    car->PRIM_type == T_CAPABILITY_REQ) {
18965 		tcp_capability_req(tcp, mp);
18966 		return;
18967 	}
18968 
18969 	tcp_wput(wq, mp);
18970 }
18971 
18972 /* ARGSUSED */
18973 static void
18974 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18975 {
18976 #ifdef DEBUG
18977 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18978 #endif
18979 	freemsg(mp);
18980 }
18981 
18982 static boolean_t
18983 tcp_zcopy_check(tcp_t *tcp)
18984 {
18985 	conn_t	*connp = tcp->tcp_connp;
18986 	ire_t	*ire;
18987 	boolean_t	zc_enabled = B_FALSE;
18988 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18989 
18990 	if (do_tcpzcopy == 2)
18991 		zc_enabled = B_TRUE;
18992 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18993 	    IPCL_IS_CONNECTED(connp) &&
18994 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18995 	    connp->conn_dontroute == 0 &&
18996 	    !connp->conn_nexthop_set &&
18997 	    connp->conn_outgoing_ill == NULL &&
18998 	    connp->conn_nofailover_ill == NULL &&
18999 	    do_tcpzcopy == 1) {
19000 		/*
19001 		 * the checks above  closely resemble the fast path checks
19002 		 * in tcp_send_data().
19003 		 */
19004 		mutex_enter(&connp->conn_lock);
19005 		ire = connp->conn_ire_cache;
19006 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19007 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19008 			IRE_REFHOLD(ire);
19009 			if (ire->ire_stq != NULL) {
19010 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
19011 
19012 				zc_enabled = ill && (ill->ill_capabilities &
19013 				    ILL_CAPAB_ZEROCOPY) &&
19014 				    (ill->ill_zerocopy_capab->
19015 				    ill_zerocopy_flags != 0);
19016 			}
19017 			IRE_REFRELE(ire);
19018 		}
19019 		mutex_exit(&connp->conn_lock);
19020 	}
19021 	tcp->tcp_snd_zcopy_on = zc_enabled;
19022 	if (!TCP_IS_DETACHED(tcp)) {
19023 		if (zc_enabled) {
19024 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
19025 			    ZCVMSAFE);
19026 			TCP_STAT(tcps, tcp_zcopy_on);
19027 		} else {
19028 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
19029 			    ZCVMUNSAFE);
19030 			TCP_STAT(tcps, tcp_zcopy_off);
19031 		}
19032 	}
19033 	return (zc_enabled);
19034 }
19035 
19036 static mblk_t *
19037 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
19038 {
19039 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19040 
19041 	if (do_tcpzcopy == 2)
19042 		return (bp);
19043 	else if (tcp->tcp_snd_zcopy_on) {
19044 		tcp->tcp_snd_zcopy_on = B_FALSE;
19045 		if (!TCP_IS_DETACHED(tcp)) {
19046 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
19047 			    ZCVMUNSAFE);
19048 			TCP_STAT(tcps, tcp_zcopy_disable);
19049 		}
19050 	}
19051 	return (tcp_zcopy_backoff(tcp, bp, 0));
19052 }
19053 
19054 /*
19055  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
19056  * the original desballoca'ed segmapped mblk.
19057  */
19058 static mblk_t *
19059 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
19060 {
19061 	mblk_t *head, *tail, *nbp;
19062 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19063 
19064 	if (IS_VMLOANED_MBLK(bp)) {
19065 		TCP_STAT(tcps, tcp_zcopy_backoff);
19066 		if ((head = copyb(bp)) == NULL) {
19067 			/* fail to backoff; leave it for the next backoff */
19068 			tcp->tcp_xmit_zc_clean = B_FALSE;
19069 			return (bp);
19070 		}
19071 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19072 			if (fix_xmitlist)
19073 				tcp_zcopy_notify(tcp);
19074 			else
19075 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19076 		}
19077 		nbp = bp->b_cont;
19078 		if (fix_xmitlist) {
19079 			head->b_prev = bp->b_prev;
19080 			head->b_next = bp->b_next;
19081 			if (tcp->tcp_xmit_tail == bp)
19082 				tcp->tcp_xmit_tail = head;
19083 		}
19084 		bp->b_next = NULL;
19085 		bp->b_prev = NULL;
19086 		freeb(bp);
19087 	} else {
19088 		head = bp;
19089 		nbp = bp->b_cont;
19090 	}
19091 	tail = head;
19092 	while (nbp) {
19093 		if (IS_VMLOANED_MBLK(nbp)) {
19094 			TCP_STAT(tcps, tcp_zcopy_backoff);
19095 			if ((tail->b_cont = copyb(nbp)) == NULL) {
19096 				tcp->tcp_xmit_zc_clean = B_FALSE;
19097 				tail->b_cont = nbp;
19098 				return (head);
19099 			}
19100 			tail = tail->b_cont;
19101 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19102 				if (fix_xmitlist)
19103 					tcp_zcopy_notify(tcp);
19104 				else
19105 					tail->b_datap->db_struioflag |=
19106 					    STRUIO_ZCNOTIFY;
19107 			}
19108 			bp = nbp;
19109 			nbp = nbp->b_cont;
19110 			if (fix_xmitlist) {
19111 				tail->b_prev = bp->b_prev;
19112 				tail->b_next = bp->b_next;
19113 				if (tcp->tcp_xmit_tail == bp)
19114 					tcp->tcp_xmit_tail = tail;
19115 			}
19116 			bp->b_next = NULL;
19117 			bp->b_prev = NULL;
19118 			freeb(bp);
19119 		} else {
19120 			tail->b_cont = nbp;
19121 			tail = nbp;
19122 			nbp = nbp->b_cont;
19123 		}
19124 	}
19125 	if (fix_xmitlist) {
19126 		tcp->tcp_xmit_last = tail;
19127 		tcp->tcp_xmit_zc_clean = B_TRUE;
19128 	}
19129 	return (head);
19130 }
19131 
19132 static void
19133 tcp_zcopy_notify(tcp_t *tcp)
19134 {
19135 	struct stdata	*stp;
19136 	conn_t *connp;
19137 
19138 	if (tcp->tcp_detached)
19139 		return;
19140 	connp = tcp->tcp_connp;
19141 	if (IPCL_IS_NONSTR(connp)) {
19142 		(*connp->conn_upcalls->su_zcopy_notify)
19143 		    (connp->conn_upper_handle);
19144 		return;
19145 	}
19146 	stp = STREAM(tcp->tcp_rq);
19147 	mutex_enter(&stp->sd_lock);
19148 	stp->sd_flag |= STZCNOTIFY;
19149 	cv_broadcast(&stp->sd_zcopy_wait);
19150 	mutex_exit(&stp->sd_lock);
19151 }
19152 
19153 static boolean_t
19154 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
19155 {
19156 	ire_t	*ire;
19157 	conn_t	*connp = tcp->tcp_connp;
19158 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19159 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19160 
19161 	mutex_enter(&connp->conn_lock);
19162 	ire = connp->conn_ire_cache;
19163 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19164 
19165 	if ((ire != NULL) &&
19166 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
19167 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
19168 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19169 		IRE_REFHOLD(ire);
19170 		mutex_exit(&connp->conn_lock);
19171 	} else {
19172 		boolean_t cached = B_FALSE;
19173 		ts_label_t *tsl;
19174 
19175 		/* force a recheck later on */
19176 		tcp->tcp_ire_ill_check_done = B_FALSE;
19177 
19178 		TCP_DBGSTAT(tcps, tcp_ire_null1);
19179 		connp->conn_ire_cache = NULL;
19180 		mutex_exit(&connp->conn_lock);
19181 
19182 		if (ire != NULL)
19183 			IRE_REFRELE_NOTR(ire);
19184 
19185 		tsl = crgetlabel(CONN_CRED(connp));
19186 		ire = (dst ?
19187 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
19188 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19189 		    connp->conn_zoneid, tsl, ipst));
19190 
19191 		if (ire == NULL) {
19192 			TCP_STAT(tcps, tcp_ire_null);
19193 			return (B_FALSE);
19194 		}
19195 
19196 		IRE_REFHOLD_NOTR(ire);
19197 
19198 		mutex_enter(&connp->conn_lock);
19199 		if (CONN_CACHE_IRE(connp)) {
19200 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19201 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19202 				TCP_CHECK_IREINFO(tcp, ire);
19203 				connp->conn_ire_cache = ire;
19204 				cached = B_TRUE;
19205 			}
19206 			rw_exit(&ire->ire_bucket->irb_lock);
19207 		}
19208 		mutex_exit(&connp->conn_lock);
19209 
19210 		/*
19211 		 * We can continue to use the ire but since it was
19212 		 * not cached, we should drop the extra reference.
19213 		 */
19214 		if (!cached)
19215 			IRE_REFRELE_NOTR(ire);
19216 
19217 		/*
19218 		 * Rampart note: no need to select a new label here, since
19219 		 * labels are not allowed to change during the life of a TCP
19220 		 * connection.
19221 		 */
19222 	}
19223 
19224 	*irep = ire;
19225 
19226 	return (B_TRUE);
19227 }
19228 
19229 /*
19230  * Called from tcp_send() or tcp_send_data() to find workable IRE.
19231  *
19232  * 0 = success;
19233  * 1 = failed to find ire and ill.
19234  */
19235 static boolean_t
19236 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
19237 {
19238 	ipha_t		*ipha;
19239 	ipaddr_t	dst;
19240 	ire_t		*ire;
19241 	ill_t		*ill;
19242 	conn_t		*connp = tcp->tcp_connp;
19243 	mblk_t		*ire_fp_mp;
19244 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19245 
19246 	if (mp != NULL)
19247 		ipha = (ipha_t *)mp->b_rptr;
19248 	else
19249 		ipha = tcp->tcp_ipha;
19250 	dst = ipha->ipha_dst;
19251 
19252 	if (!tcp_send_find_ire(tcp, &dst, &ire))
19253 		return (B_FALSE);
19254 
19255 	if ((ire->ire_flags & RTF_MULTIRT) ||
19256 	    (ire->ire_stq == NULL) ||
19257 	    (ire->ire_nce == NULL) ||
19258 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
19259 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
19260 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
19261 		TCP_STAT(tcps, tcp_ip_ire_send);
19262 		IRE_REFRELE(ire);
19263 		return (B_FALSE);
19264 	}
19265 
19266 	ill = ire_to_ill(ire);
19267 	if (connp->conn_outgoing_ill != NULL) {
19268 		ill_t *conn_outgoing_ill = NULL;
19269 		/*
19270 		 * Choose a good ill in the group to send the packets on.
19271 		 */
19272 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
19273 		ill = ire_to_ill(ire);
19274 	}
19275 	ASSERT(ill != NULL);
19276 
19277 	if (!tcp->tcp_ire_ill_check_done) {
19278 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19279 		tcp->tcp_ire_ill_check_done = B_TRUE;
19280 	}
19281 
19282 	*irep = ire;
19283 	*illp = ill;
19284 
19285 	return (B_TRUE);
19286 }
19287 
19288 static void
19289 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
19290 {
19291 	ipha_t		*ipha;
19292 	ipaddr_t	src;
19293 	ipaddr_t	dst;
19294 	uint32_t	cksum;
19295 	ire_t		*ire;
19296 	uint16_t	*up;
19297 	ill_t		*ill;
19298 	conn_t		*connp = tcp->tcp_connp;
19299 	uint32_t	hcksum_txflags = 0;
19300 	mblk_t		*ire_fp_mp;
19301 	uint_t		ire_fp_mp_len;
19302 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19303 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19304 
19305 	ASSERT(DB_TYPE(mp) == M_DATA);
19306 
19307 	if (is_system_labeled() && DB_CRED(mp) == NULL)
19308 		mblk_setcred(mp, CONN_CRED(tcp->tcp_connp));
19309 
19310 	ipha = (ipha_t *)mp->b_rptr;
19311 	src = ipha->ipha_src;
19312 	dst = ipha->ipha_dst;
19313 
19314 	ASSERT(q != NULL);
19315 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
19316 
19317 	/*
19318 	 * Drop off fast path for IPv6 and also if options are present or
19319 	 * we need to resolve a TS label.
19320 	 */
19321 	if (tcp->tcp_ipversion != IPV4_VERSION ||
19322 	    !IPCL_IS_CONNECTED(connp) ||
19323 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
19324 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
19325 	    !connp->conn_ulp_labeled ||
19326 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
19327 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
19328 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
19329 		if (tcp->tcp_snd_zcopy_aware)
19330 			mp = tcp_zcopy_disable(tcp, mp);
19331 		TCP_STAT(tcps, tcp_ip_send);
19332 		CALL_IP_WPUT(connp, q, mp);
19333 		return;
19334 	}
19335 
19336 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
19337 		if (tcp->tcp_snd_zcopy_aware)
19338 			mp = tcp_zcopy_backoff(tcp, mp, 0);
19339 		CALL_IP_WPUT(connp, q, mp);
19340 		return;
19341 	}
19342 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
19343 	ire_fp_mp_len = MBLKL(ire_fp_mp);
19344 
19345 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19346 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19347 #ifndef _BIG_ENDIAN
19348 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19349 #endif
19350 
19351 	/*
19352 	 * Check to see if we need to re-enable LSO/MDT for this connection
19353 	 * because it was previously disabled due to changes in the ill;
19354 	 * note that by doing it here, this re-enabling only applies when
19355 	 * the packet is not dispatched through CALL_IP_WPUT().
19356 	 *
19357 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
19358 	 * case, since that's how we ended up here.  For IPv6, we do the
19359 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
19360 	 */
19361 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
19362 		/*
19363 		 * Restore LSO for this connection, so that next time around
19364 		 * it is eligible to go through tcp_lsosend() path again.
19365 		 */
19366 		TCP_STAT(tcps, tcp_lso_enabled);
19367 		tcp->tcp_lso = B_TRUE;
19368 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
19369 		    "interface %s\n", (void *)connp, ill->ill_name));
19370 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
19371 		/*
19372 		 * Restore MDT for this connection, so that next time around
19373 		 * it is eligible to go through tcp_multisend() path again.
19374 		 */
19375 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
19376 		tcp->tcp_mdt = B_TRUE;
19377 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
19378 		    "interface %s\n", (void *)connp, ill->ill_name));
19379 	}
19380 
19381 	if (tcp->tcp_snd_zcopy_aware) {
19382 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
19383 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
19384 			mp = tcp_zcopy_disable(tcp, mp);
19385 		/*
19386 		 * we shouldn't need to reset ipha as the mp containing
19387 		 * ipha should never be a zero-copy mp.
19388 		 */
19389 	}
19390 
19391 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
19392 		ASSERT(ill->ill_hcksum_capab != NULL);
19393 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
19394 	}
19395 
19396 	/* pseudo-header checksum (do it in parts for IP header checksum) */
19397 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19398 
19399 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
19400 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
19401 
19402 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
19403 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
19404 
19405 	/* Software checksum? */
19406 	if (DB_CKSUMFLAGS(mp) == 0) {
19407 		TCP_STAT(tcps, tcp_out_sw_cksum);
19408 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
19409 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
19410 	}
19411 
19412 	/* Calculate IP header checksum if hardware isn't capable */
19413 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
19414 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
19415 		    ((uint16_t *)ipha)[4]);
19416 	}
19417 
19418 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
19419 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
19420 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
19421 
19422 	UPDATE_OB_PKT_COUNT(ire);
19423 	ire->ire_last_used_time = lbolt;
19424 
19425 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
19426 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
19427 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
19428 	    ntohs(ipha->ipha_length));
19429 
19430 	DTRACE_PROBE4(ip4__physical__out__start,
19431 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
19432 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
19433 	    ipst->ips_ipv4firewall_physical_out,
19434 	    NULL, ill, ipha, mp, mp, 0, ipst);
19435 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19436 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
19437 
19438 	if (mp != NULL) {
19439 		if (ipst->ips_ipobs_enabled) {
19440 			zoneid_t szone;
19441 
19442 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
19443 			    ipst, ALL_ZONES);
19444 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
19445 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
19446 		}
19447 
19448 		ILL_SEND_TX(ill, ire, connp, mp, 0);
19449 	}
19450 
19451 	IRE_REFRELE(ire);
19452 }
19453 
19454 /*
19455  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19456  * if the receiver shrinks the window, i.e. moves the right window to the
19457  * left, the we should not send new data, but should retransmit normally the
19458  * old unacked data between suna and suna + swnd. We might has sent data
19459  * that is now outside the new window, pretend that we didn't send  it.
19460  */
19461 static void
19462 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19463 {
19464 	uint32_t	snxt = tcp->tcp_snxt;
19465 	mblk_t		*xmit_tail;
19466 	int32_t		offset;
19467 
19468 	ASSERT(shrunk_count > 0);
19469 
19470 	/* Pretend we didn't send the data outside the window */
19471 	snxt -= shrunk_count;
19472 
19473 	/* Get the mblk and the offset in it per the shrunk window */
19474 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19475 
19476 	ASSERT(xmit_tail != NULL);
19477 
19478 	/* Reset all the values per the now shrunk window */
19479 	tcp->tcp_snxt = snxt;
19480 	tcp->tcp_xmit_tail = xmit_tail;
19481 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19482 	    offset;
19483 	tcp->tcp_unsent += shrunk_count;
19484 
19485 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19486 		/*
19487 		 * Make sure the timer is running so that we will probe a zero
19488 		 * window.
19489 		 */
19490 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19491 }
19492 
19493 
19494 /*
19495  * The TCP normal data output path.
19496  * NOTE: the logic of the fast path is duplicated from this function.
19497  */
19498 static void
19499 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19500 {
19501 	int		len;
19502 	mblk_t		*local_time;
19503 	mblk_t		*mp1;
19504 	uint32_t	snxt;
19505 	int		tail_unsent;
19506 	int		tcpstate;
19507 	int		usable = 0;
19508 	mblk_t		*xmit_tail;
19509 	queue_t		*q = tcp->tcp_wq;
19510 	int32_t		mss;
19511 	int32_t		num_sack_blk = 0;
19512 	int32_t		tcp_hdr_len;
19513 	int32_t		tcp_tcp_hdr_len;
19514 	int		mdt_thres;
19515 	int		rc;
19516 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19517 	ip_stack_t	*ipst;
19518 
19519 	tcpstate = tcp->tcp_state;
19520 	if (mp == NULL) {
19521 		/*
19522 		 * tcp_wput_data() with NULL mp should only be called when
19523 		 * there is unsent data.
19524 		 */
19525 		ASSERT(tcp->tcp_unsent > 0);
19526 		/* Really tacky... but we need this for detached closes. */
19527 		len = tcp->tcp_unsent;
19528 		goto data_null;
19529 	}
19530 
19531 #if CCS_STATS
19532 	wrw_stats.tot.count++;
19533 	wrw_stats.tot.bytes += msgdsize(mp);
19534 #endif
19535 	ASSERT(mp->b_datap->db_type == M_DATA);
19536 	/*
19537 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19538 	 * or before a connection attempt has begun.
19539 	 */
19540 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19541 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19542 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19543 #ifdef DEBUG
19544 			cmn_err(CE_WARN,
19545 			    "tcp_wput_data: data after ordrel, %s",
19546 			    tcp_display(tcp, NULL,
19547 			    DISP_ADDR_AND_PORT));
19548 #else
19549 			if (tcp->tcp_debug) {
19550 				(void) strlog(TCP_MOD_ID, 0, 1,
19551 				    SL_TRACE|SL_ERROR,
19552 				    "tcp_wput_data: data after ordrel, %s\n",
19553 				    tcp_display(tcp, NULL,
19554 				    DISP_ADDR_AND_PORT));
19555 			}
19556 #endif /* DEBUG */
19557 		}
19558 		if (tcp->tcp_snd_zcopy_aware &&
19559 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19560 			tcp_zcopy_notify(tcp);
19561 		freemsg(mp);
19562 		mutex_enter(&tcp->tcp_non_sq_lock);
19563 		if (tcp->tcp_flow_stopped &&
19564 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19565 			tcp_clrqfull(tcp);
19566 		}
19567 		mutex_exit(&tcp->tcp_non_sq_lock);
19568 		return;
19569 	}
19570 
19571 	/* Strip empties */
19572 	for (;;) {
19573 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19574 		    (uintptr_t)INT_MAX);
19575 		len = (int)(mp->b_wptr - mp->b_rptr);
19576 		if (len > 0)
19577 			break;
19578 		mp1 = mp;
19579 		mp = mp->b_cont;
19580 		freeb(mp1);
19581 		if (!mp) {
19582 			return;
19583 		}
19584 	}
19585 
19586 	/* If we are the first on the list ... */
19587 	if (tcp->tcp_xmit_head == NULL) {
19588 		tcp->tcp_xmit_head = mp;
19589 		tcp->tcp_xmit_tail = mp;
19590 		tcp->tcp_xmit_tail_unsent = len;
19591 	} else {
19592 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19593 		struct datab *dp;
19594 
19595 		mp1 = tcp->tcp_xmit_last;
19596 		if (len < tcp_tx_pull_len &&
19597 		    (dp = mp1->b_datap)->db_ref == 1 &&
19598 		    dp->db_lim - mp1->b_wptr >= len) {
19599 			ASSERT(len > 0);
19600 			ASSERT(!mp1->b_cont);
19601 			if (len == 1) {
19602 				*mp1->b_wptr++ = *mp->b_rptr;
19603 			} else {
19604 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19605 				mp1->b_wptr += len;
19606 			}
19607 			if (mp1 == tcp->tcp_xmit_tail)
19608 				tcp->tcp_xmit_tail_unsent += len;
19609 			mp1->b_cont = mp->b_cont;
19610 			if (tcp->tcp_snd_zcopy_aware &&
19611 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19612 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19613 			freeb(mp);
19614 			mp = mp1;
19615 		} else {
19616 			tcp->tcp_xmit_last->b_cont = mp;
19617 		}
19618 		len += tcp->tcp_unsent;
19619 	}
19620 
19621 	/* Tack on however many more positive length mblks we have */
19622 	if ((mp1 = mp->b_cont) != NULL) {
19623 		do {
19624 			int tlen;
19625 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19626 			    (uintptr_t)INT_MAX);
19627 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19628 			if (tlen <= 0) {
19629 				mp->b_cont = mp1->b_cont;
19630 				freeb(mp1);
19631 			} else {
19632 				len += tlen;
19633 				mp = mp1;
19634 			}
19635 		} while ((mp1 = mp->b_cont) != NULL);
19636 	}
19637 	tcp->tcp_xmit_last = mp;
19638 	tcp->tcp_unsent = len;
19639 
19640 	if (urgent)
19641 		usable = 1;
19642 
19643 data_null:
19644 	snxt = tcp->tcp_snxt;
19645 	xmit_tail = tcp->tcp_xmit_tail;
19646 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19647 
19648 	/*
19649 	 * Note that tcp_mss has been adjusted to take into account the
19650 	 * timestamp option if applicable.  Because SACK options do not
19651 	 * appear in every TCP segments and they are of variable lengths,
19652 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19653 	 * the actual segment length when we need to send a segment which
19654 	 * includes SACK options.
19655 	 */
19656 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19657 		int32_t	opt_len;
19658 
19659 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19660 		    tcp->tcp_num_sack_blk);
19661 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19662 		    2 + TCPOPT_HEADER_LEN;
19663 		mss = tcp->tcp_mss - opt_len;
19664 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19665 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19666 	} else {
19667 		mss = tcp->tcp_mss;
19668 		tcp_hdr_len = tcp->tcp_hdr_len;
19669 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19670 	}
19671 
19672 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19673 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19674 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19675 	}
19676 	if (tcpstate == TCPS_SYN_RCVD) {
19677 		/*
19678 		 * The three-way connection establishment handshake is not
19679 		 * complete yet. We want to queue the data for transmission
19680 		 * after entering ESTABLISHED state (RFC793). A jump to
19681 		 * "done" label effectively leaves data on the queue.
19682 		 */
19683 		goto done;
19684 	} else {
19685 		int usable_r;
19686 
19687 		/*
19688 		 * In the special case when cwnd is zero, which can only
19689 		 * happen if the connection is ECN capable, return now.
19690 		 * New segments is sent using tcp_timer().  The timer
19691 		 * is set in tcp_rput_data().
19692 		 */
19693 		if (tcp->tcp_cwnd == 0) {
19694 			/*
19695 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19696 			 * finished.
19697 			 */
19698 			ASSERT(tcp->tcp_ecn_ok ||
19699 			    tcp->tcp_state < TCPS_ESTABLISHED);
19700 			return;
19701 		}
19702 
19703 		/* NOTE: trouble if xmitting while SYN not acked? */
19704 		usable_r = snxt - tcp->tcp_suna;
19705 		usable_r = tcp->tcp_swnd - usable_r;
19706 
19707 		/*
19708 		 * Check if the receiver has shrunk the window.  If
19709 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19710 		 * cannot be set as there is unsent data, so FIN cannot
19711 		 * be sent out.  Otherwise, we need to take into account
19712 		 * of FIN as it consumes an "invisible" sequence number.
19713 		 */
19714 		ASSERT(tcp->tcp_fin_sent == 0);
19715 		if (usable_r < 0) {
19716 			/*
19717 			 * The receiver has shrunk the window and we have sent
19718 			 * -usable_r date beyond the window, re-adjust.
19719 			 *
19720 			 * If TCP window scaling is enabled, there can be
19721 			 * round down error as the advertised receive window
19722 			 * is actually right shifted n bits.  This means that
19723 			 * the lower n bits info is wiped out.  It will look
19724 			 * like the window is shrunk.  Do a check here to
19725 			 * see if the shrunk amount is actually within the
19726 			 * error in window calculation.  If it is, just
19727 			 * return.  Note that this check is inside the
19728 			 * shrunk window check.  This makes sure that even
19729 			 * though tcp_process_shrunk_swnd() is not called,
19730 			 * we will stop further processing.
19731 			 */
19732 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19733 				tcp_process_shrunk_swnd(tcp, -usable_r);
19734 			}
19735 			return;
19736 		}
19737 
19738 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19739 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19740 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19741 
19742 		/* usable = MIN(usable, unsent) */
19743 		if (usable_r > len)
19744 			usable_r = len;
19745 
19746 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19747 		if (usable_r > 0) {
19748 			usable = usable_r;
19749 		} else {
19750 			/* Bypass all other unnecessary processing. */
19751 			goto done;
19752 		}
19753 	}
19754 
19755 	local_time = (mblk_t *)lbolt;
19756 
19757 	/*
19758 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19759 	 * BSD.  This is more in line with the true intent of Nagle.
19760 	 *
19761 	 * The conditions are:
19762 	 * 1. The amount of unsent data (or amount of data which can be
19763 	 *    sent, whichever is smaller) is less than Nagle limit.
19764 	 * 2. The last sent size is also less than Nagle limit.
19765 	 * 3. There is unack'ed data.
19766 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19767 	 *    Nagle algorithm.  This reduces the probability that urgent
19768 	 *    bytes get "merged" together.
19769 	 * 5. The app has not closed the connection.  This eliminates the
19770 	 *    wait time of the receiving side waiting for the last piece of
19771 	 *    (small) data.
19772 	 *
19773 	 * If all are satisified, exit without sending anything.  Note
19774 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19775 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19776 	 * 4095).
19777 	 */
19778 	if (usable < (int)tcp->tcp_naglim &&
19779 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19780 	    snxt != tcp->tcp_suna &&
19781 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19782 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19783 		goto done;
19784 	}
19785 
19786 	if (tcp->tcp_cork) {
19787 		/*
19788 		 * if the tcp->tcp_cork option is set, then we have to force
19789 		 * TCP not to send partial segment (smaller than MSS bytes).
19790 		 * We are calculating the usable now based on full mss and
19791 		 * will save the rest of remaining data for later.
19792 		 */
19793 		if (usable < mss)
19794 			goto done;
19795 		usable = (usable / mss) * mss;
19796 	}
19797 
19798 	/* Update the latest receive window size in TCP header. */
19799 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19800 	    tcp->tcp_tcph->th_win);
19801 
19802 	/*
19803 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19804 	 *
19805 	 * 1. Simple TCP/IP{v4,v6} (no options).
19806 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19807 	 * 3. If the TCP connection is in ESTABLISHED state.
19808 	 * 4. The TCP is not detached.
19809 	 *
19810 	 * If any of the above conditions have changed during the
19811 	 * connection, stop using LSO/MDT and restore the stream head
19812 	 * parameters accordingly.
19813 	 */
19814 	ipst = tcps->tcps_netstack->netstack_ip;
19815 
19816 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19817 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19818 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19819 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19820 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19821 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19822 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19823 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19824 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19825 		if (tcp->tcp_lso) {
19826 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19827 			tcp->tcp_lso = B_FALSE;
19828 		} else {
19829 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19830 			tcp->tcp_mdt = B_FALSE;
19831 		}
19832 
19833 		/* Anything other than detached is considered pathological */
19834 		if (!TCP_IS_DETACHED(tcp)) {
19835 			if (tcp->tcp_lso)
19836 				TCP_STAT(tcps, tcp_lso_disabled);
19837 			else
19838 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19839 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19840 		}
19841 	}
19842 
19843 	/* Use MDT if sendable amount is greater than the threshold */
19844 	if (tcp->tcp_mdt &&
19845 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19846 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19847 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19848 	    (tcp->tcp_valid_bits == 0 ||
19849 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19850 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19851 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19852 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19853 		    local_time, mdt_thres);
19854 	} else {
19855 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19856 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19857 		    local_time, INT_MAX);
19858 	}
19859 
19860 	/* Pretend that all we were trying to send really got sent */
19861 	if (rc < 0 && tail_unsent < 0) {
19862 		do {
19863 			xmit_tail = xmit_tail->b_cont;
19864 			xmit_tail->b_prev = local_time;
19865 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19866 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19867 			tail_unsent += (int)(xmit_tail->b_wptr -
19868 			    xmit_tail->b_rptr);
19869 		} while (tail_unsent < 0);
19870 	}
19871 done:;
19872 	tcp->tcp_xmit_tail = xmit_tail;
19873 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19874 	len = tcp->tcp_snxt - snxt;
19875 	if (len) {
19876 		/*
19877 		 * If new data was sent, need to update the notsack
19878 		 * list, which is, afterall, data blocks that have
19879 		 * not been sack'ed by the receiver.  New data is
19880 		 * not sack'ed.
19881 		 */
19882 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19883 			/* len is a negative value. */
19884 			tcp->tcp_pipe -= len;
19885 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19886 			    tcp->tcp_snxt, snxt,
19887 			    &(tcp->tcp_num_notsack_blk),
19888 			    &(tcp->tcp_cnt_notsack_list));
19889 		}
19890 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19891 		tcp->tcp_rack = tcp->tcp_rnxt;
19892 		tcp->tcp_rack_cnt = 0;
19893 		if ((snxt + len) == tcp->tcp_suna) {
19894 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19895 		}
19896 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19897 		/*
19898 		 * Didn't send anything. Make sure the timer is running
19899 		 * so that we will probe a zero window.
19900 		 */
19901 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19902 	}
19903 	/* Note that len is the amount we just sent but with a negative sign */
19904 	tcp->tcp_unsent += len;
19905 	mutex_enter(&tcp->tcp_non_sq_lock);
19906 	if (tcp->tcp_flow_stopped) {
19907 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19908 			tcp_clrqfull(tcp);
19909 		}
19910 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19911 		tcp_setqfull(tcp);
19912 	}
19913 	mutex_exit(&tcp->tcp_non_sq_lock);
19914 }
19915 
19916 /*
19917  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19918  * outgoing TCP header with the template header, as well as other
19919  * options such as time-stamp, ECN and/or SACK.
19920  */
19921 static void
19922 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19923 {
19924 	tcph_t *tcp_tmpl, *tcp_h;
19925 	uint32_t *dst, *src;
19926 	int hdrlen;
19927 
19928 	ASSERT(OK_32PTR(rptr));
19929 
19930 	/* Template header */
19931 	tcp_tmpl = tcp->tcp_tcph;
19932 
19933 	/* Header of outgoing packet */
19934 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19935 
19936 	/* dst and src are opaque 32-bit fields, used for copying */
19937 	dst = (uint32_t *)rptr;
19938 	src = (uint32_t *)tcp->tcp_iphc;
19939 	hdrlen = tcp->tcp_hdr_len;
19940 
19941 	/* Fill time-stamp option if needed */
19942 	if (tcp->tcp_snd_ts_ok) {
19943 		U32_TO_BE32((uint32_t)now,
19944 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19945 		U32_TO_BE32(tcp->tcp_ts_recent,
19946 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19947 	} else {
19948 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19949 	}
19950 
19951 	/*
19952 	 * Copy the template header; is this really more efficient than
19953 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19954 	 * but perhaps not for other scenarios.
19955 	 */
19956 	dst[0] = src[0];
19957 	dst[1] = src[1];
19958 	dst[2] = src[2];
19959 	dst[3] = src[3];
19960 	dst[4] = src[4];
19961 	dst[5] = src[5];
19962 	dst[6] = src[6];
19963 	dst[7] = src[7];
19964 	dst[8] = src[8];
19965 	dst[9] = src[9];
19966 	if (hdrlen -= 40) {
19967 		hdrlen >>= 2;
19968 		dst += 10;
19969 		src += 10;
19970 		do {
19971 			*dst++ = *src++;
19972 		} while (--hdrlen);
19973 	}
19974 
19975 	/*
19976 	 * Set the ECN info in the TCP header if it is not a zero
19977 	 * window probe.  Zero window probe is only sent in
19978 	 * tcp_wput_data() and tcp_timer().
19979 	 */
19980 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19981 		SET_ECT(tcp, rptr);
19982 
19983 		if (tcp->tcp_ecn_echo_on)
19984 			tcp_h->th_flags[0] |= TH_ECE;
19985 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19986 			tcp_h->th_flags[0] |= TH_CWR;
19987 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19988 		}
19989 	}
19990 
19991 	/* Fill in SACK options */
19992 	if (num_sack_blk > 0) {
19993 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19994 		sack_blk_t *tmp;
19995 		int32_t	i;
19996 
19997 		wptr[0] = TCPOPT_NOP;
19998 		wptr[1] = TCPOPT_NOP;
19999 		wptr[2] = TCPOPT_SACK;
20000 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
20001 		    sizeof (sack_blk_t);
20002 		wptr += TCPOPT_REAL_SACK_LEN;
20003 
20004 		tmp = tcp->tcp_sack_list;
20005 		for (i = 0; i < num_sack_blk; i++) {
20006 			U32_TO_BE32(tmp[i].begin, wptr);
20007 			wptr += sizeof (tcp_seq);
20008 			U32_TO_BE32(tmp[i].end, wptr);
20009 			wptr += sizeof (tcp_seq);
20010 		}
20011 		tcp_h->th_offset_and_rsrvd[0] +=
20012 		    ((num_sack_blk * 2 + 1) << 4);
20013 	}
20014 }
20015 
20016 /*
20017  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
20018  * the destination address and SAP attribute, and if necessary, the
20019  * hardware checksum offload attribute to a Multidata message.
20020  */
20021 static int
20022 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
20023     const uint32_t start, const uint32_t stuff, const uint32_t end,
20024     const uint32_t flags, tcp_stack_t *tcps)
20025 {
20026 	/* Add global destination address & SAP attribute */
20027 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
20028 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
20029 		    "destination address+SAP\n"));
20030 
20031 		if (dlmp != NULL)
20032 			TCP_STAT(tcps, tcp_mdt_allocfail);
20033 		return (-1);
20034 	}
20035 
20036 	/* Add global hwcksum attribute */
20037 	if (hwcksum &&
20038 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
20039 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
20040 		    "checksum attribute\n"));
20041 
20042 		TCP_STAT(tcps, tcp_mdt_allocfail);
20043 		return (-1);
20044 	}
20045 
20046 	return (0);
20047 }
20048 
20049 /*
20050  * Smaller and private version of pdescinfo_t used specifically for TCP,
20051  * which allows for only two payload spans per packet.
20052  */
20053 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
20054 
20055 /*
20056  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
20057  * scheme, and returns one the following:
20058  *
20059  * -1 = failed allocation.
20060  *  0 = success; burst count reached, or usable send window is too small,
20061  *      and that we'd rather wait until later before sending again.
20062  */
20063 static int
20064 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20065     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20066     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20067     const int mdt_thres)
20068 {
20069 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
20070 	multidata_t	*mmd;
20071 	uint_t		obsegs, obbytes, hdr_frag_sz;
20072 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
20073 	int		num_burst_seg, max_pld;
20074 	pdesc_t		*pkt;
20075 	tcp_pdescinfo_t	tcp_pkt_info;
20076 	pdescinfo_t	*pkt_info;
20077 	int		pbuf_idx, pbuf_idx_nxt;
20078 	int		seg_len, len, spill, af;
20079 	boolean_t	add_buffer, zcopy, clusterwide;
20080 	boolean_t	rconfirm = B_FALSE;
20081 	boolean_t	done = B_FALSE;
20082 	uint32_t	cksum;
20083 	uint32_t	hwcksum_flags;
20084 	ire_t		*ire = NULL;
20085 	ill_t		*ill;
20086 	ipha_t		*ipha;
20087 	ip6_t		*ip6h;
20088 	ipaddr_t	src, dst;
20089 	ill_zerocopy_capab_t *zc_cap = NULL;
20090 	uint16_t	*up;
20091 	int		err;
20092 	conn_t		*connp;
20093 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20094 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
20095 	int		usable_mmd, tail_unsent_mmd;
20096 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
20097 	mblk_t		*xmit_tail_mmd;
20098 	netstackid_t	stack_id;
20099 
20100 #ifdef	_BIG_ENDIAN
20101 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
20102 #else
20103 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
20104 #endif
20105 
20106 #define	PREP_NEW_MULTIDATA() {			\
20107 	mmd = NULL;				\
20108 	md_mp = md_hbuf = NULL;			\
20109 	cur_hdr_off = 0;			\
20110 	max_pld = tcp->tcp_mdt_max_pld;		\
20111 	pbuf_idx = pbuf_idx_nxt = -1;		\
20112 	add_buffer = B_TRUE;			\
20113 	zcopy = B_FALSE;			\
20114 }
20115 
20116 #define	PREP_NEW_PBUF() {			\
20117 	md_pbuf = md_pbuf_nxt = NULL;		\
20118 	pbuf_idx = pbuf_idx_nxt = -1;		\
20119 	cur_pld_off = 0;			\
20120 	first_snxt = *snxt;			\
20121 	ASSERT(*tail_unsent > 0);		\
20122 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
20123 }
20124 
20125 	ASSERT(mdt_thres >= mss);
20126 	ASSERT(*usable > 0 && *usable > mdt_thres);
20127 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20128 	ASSERT(!TCP_IS_DETACHED(tcp));
20129 	ASSERT(tcp->tcp_valid_bits == 0 ||
20130 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
20131 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
20132 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
20133 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20134 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
20135 
20136 	connp = tcp->tcp_connp;
20137 	ASSERT(connp != NULL);
20138 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
20139 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
20140 
20141 	stack_id = connp->conn_netstack->netstack_stackid;
20142 
20143 	usable_mmd = tail_unsent_mmd = 0;
20144 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
20145 	xmit_tail_mmd = NULL;
20146 	/*
20147 	 * Note that tcp will only declare at most 2 payload spans per
20148 	 * packet, which is much lower than the maximum allowable number
20149 	 * of packet spans per Multidata.  For this reason, we use the
20150 	 * privately declared and smaller descriptor info structure, in
20151 	 * order to save some stack space.
20152 	 */
20153 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
20154 
20155 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
20156 	if (af == AF_INET) {
20157 		dst = tcp->tcp_ipha->ipha_dst;
20158 		src = tcp->tcp_ipha->ipha_src;
20159 		ASSERT(!CLASSD(dst));
20160 	}
20161 	ASSERT(af == AF_INET ||
20162 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
20163 
20164 	obsegs = obbytes = 0;
20165 	num_burst_seg = tcp->tcp_snd_burst;
20166 	md_mp_head = NULL;
20167 	PREP_NEW_MULTIDATA();
20168 
20169 	/*
20170 	 * Before we go on further, make sure there is an IRE that we can
20171 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
20172 	 * in proceeding any further, and we should just hand everything
20173 	 * off to the legacy path.
20174 	 */
20175 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
20176 		goto legacy_send_no_md;
20177 
20178 	ASSERT(ire != NULL);
20179 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
20180 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
20181 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
20182 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
20183 	/*
20184 	 * If we do support loopback for MDT (which requires modifications
20185 	 * to the receiving paths), the following assertions should go away,
20186 	 * and we would be sending the Multidata to loopback conn later on.
20187 	 */
20188 	ASSERT(!IRE_IS_LOCAL(ire));
20189 	ASSERT(ire->ire_stq != NULL);
20190 
20191 	ill = ire_to_ill(ire);
20192 	ASSERT(ill != NULL);
20193 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
20194 
20195 	if (!tcp->tcp_ire_ill_check_done) {
20196 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
20197 		tcp->tcp_ire_ill_check_done = B_TRUE;
20198 	}
20199 
20200 	/*
20201 	 * If the underlying interface conditions have changed, or if the
20202 	 * new interface does not support MDT, go back to legacy path.
20203 	 */
20204 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
20205 		/* don't go through this path anymore for this connection */
20206 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
20207 		tcp->tcp_mdt = B_FALSE;
20208 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
20209 		    "interface %s\n", (void *)connp, ill->ill_name));
20210 		/* IRE will be released prior to returning */
20211 		goto legacy_send_no_md;
20212 	}
20213 
20214 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
20215 		zc_cap = ill->ill_zerocopy_capab;
20216 
20217 	/*
20218 	 * Check if we can take tcp fast-path. Note that "incomplete"
20219 	 * ire's (where the link-layer for next hop is not resolved
20220 	 * or where the fast-path header in nce_fp_mp is not available
20221 	 * yet) are sent down the legacy (slow) path.
20222 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
20223 	 */
20224 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
20225 		/* IRE will be released prior to returning */
20226 		goto legacy_send_no_md;
20227 	}
20228 
20229 	/* go to legacy path if interface doesn't support zerocopy */
20230 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
20231 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
20232 		/* IRE will be released prior to returning */
20233 		goto legacy_send_no_md;
20234 	}
20235 
20236 	/* does the interface support hardware checksum offload? */
20237 	hwcksum_flags = 0;
20238 	if (ILL_HCKSUM_CAPABLE(ill) &&
20239 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
20240 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
20241 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
20242 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20243 		    HCKSUM_IPHDRCKSUM)
20244 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
20245 
20246 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20247 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
20248 			hwcksum_flags |= HCK_FULLCKSUM;
20249 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20250 		    HCKSUM_INET_PARTIAL)
20251 			hwcksum_flags |= HCK_PARTIALCKSUM;
20252 	}
20253 
20254 	/*
20255 	 * Each header fragment consists of the leading extra space,
20256 	 * followed by the TCP/IP header, and the trailing extra space.
20257 	 * We make sure that each header fragment begins on a 32-bit
20258 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
20259 	 * aligned in tcp_mdt_update).
20260 	 */
20261 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
20262 	    tcp->tcp_mdt_hdr_tail), 4);
20263 
20264 	/* are we starting from the beginning of data block? */
20265 	if (*tail_unsent == 0) {
20266 		*xmit_tail = (*xmit_tail)->b_cont;
20267 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
20268 		*tail_unsent = (int)MBLKL(*xmit_tail);
20269 	}
20270 
20271 	/*
20272 	 * Here we create one or more Multidata messages, each made up of
20273 	 * one header buffer and up to N payload buffers.  This entire
20274 	 * operation is done within two loops:
20275 	 *
20276 	 * The outer loop mostly deals with creating the Multidata message,
20277 	 * as well as the header buffer that gets added to it.  It also
20278 	 * links the Multidata messages together such that all of them can
20279 	 * be sent down to the lower layer in a single putnext call; this
20280 	 * linking behavior depends on the tcp_mdt_chain tunable.
20281 	 *
20282 	 * The inner loop takes an existing Multidata message, and adds
20283 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
20284 	 * packetizes those buffers by filling up the corresponding header
20285 	 * buffer fragments with the proper IP and TCP headers, and by
20286 	 * describing the layout of each packet in the packet descriptors
20287 	 * that get added to the Multidata.
20288 	 */
20289 	do {
20290 		/*
20291 		 * If usable send window is too small, or data blocks in
20292 		 * transmit list are smaller than our threshold (i.e. app
20293 		 * performs large writes followed by small ones), we hand
20294 		 * off the control over to the legacy path.  Note that we'll
20295 		 * get back the control once it encounters a large block.
20296 		 */
20297 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
20298 		    (*xmit_tail)->b_cont != NULL &&
20299 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
20300 			/* send down what we've got so far */
20301 			if (md_mp_head != NULL) {
20302 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
20303 				    obsegs, obbytes, &rconfirm);
20304 			}
20305 			/*
20306 			 * Pass control over to tcp_send(), but tell it to
20307 			 * return to us once a large-size transmission is
20308 			 * possible.
20309 			 */
20310 			TCP_STAT(tcps, tcp_mdt_legacy_small);
20311 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
20312 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
20313 			    tail_unsent, xmit_tail, local_time,
20314 			    mdt_thres)) <= 0) {
20315 				/* burst count reached, or alloc failed */
20316 				IRE_REFRELE(ire);
20317 				return (err);
20318 			}
20319 
20320 			/* tcp_send() may have sent everything, so check */
20321 			if (*usable <= 0) {
20322 				IRE_REFRELE(ire);
20323 				return (0);
20324 			}
20325 
20326 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
20327 			/*
20328 			 * We may have delivered the Multidata, so make sure
20329 			 * to re-initialize before the next round.
20330 			 */
20331 			md_mp_head = NULL;
20332 			obsegs = obbytes = 0;
20333 			num_burst_seg = tcp->tcp_snd_burst;
20334 			PREP_NEW_MULTIDATA();
20335 
20336 			/* are we starting from the beginning of data block? */
20337 			if (*tail_unsent == 0) {
20338 				*xmit_tail = (*xmit_tail)->b_cont;
20339 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20340 				    (uintptr_t)INT_MAX);
20341 				*tail_unsent = (int)MBLKL(*xmit_tail);
20342 			}
20343 		}
20344 		/*
20345 		 * Record current values for parameters we may need to pass
20346 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
20347 		 * each iteration of the outer loop (each multidata message
20348 		 * creation). If we have a failure in the inner loop, we send
20349 		 * any complete multidata messages we have before reverting
20350 		 * to using the traditional non-md path.
20351 		 */
20352 		snxt_mmd = *snxt;
20353 		usable_mmd = *usable;
20354 		xmit_tail_mmd = *xmit_tail;
20355 		tail_unsent_mmd = *tail_unsent;
20356 		obsegs_mmd = obsegs;
20357 		obbytes_mmd = obbytes;
20358 
20359 		/*
20360 		 * max_pld limits the number of mblks in tcp's transmit
20361 		 * queue that can be added to a Multidata message.  Once
20362 		 * this counter reaches zero, no more additional mblks
20363 		 * can be added to it.  What happens afterwards depends
20364 		 * on whether or not we are set to chain the Multidata
20365 		 * messages.  If we are to link them together, reset
20366 		 * max_pld to its original value (tcp_mdt_max_pld) and
20367 		 * prepare to create a new Multidata message which will
20368 		 * get linked to md_mp_head.  Else, leave it alone and
20369 		 * let the inner loop break on its own.
20370 		 */
20371 		if (tcp_mdt_chain && max_pld == 0)
20372 			PREP_NEW_MULTIDATA();
20373 
20374 		/* adding a payload buffer; re-initialize values */
20375 		if (add_buffer)
20376 			PREP_NEW_PBUF();
20377 
20378 		/*
20379 		 * If we don't have a Multidata, either because we just
20380 		 * (re)entered this outer loop, or after we branched off
20381 		 * to tcp_send above, setup the Multidata and header
20382 		 * buffer to be used.
20383 		 */
20384 		if (md_mp == NULL) {
20385 			int md_hbuflen;
20386 			uint32_t start, stuff;
20387 
20388 			/*
20389 			 * Calculate Multidata header buffer size large enough
20390 			 * to hold all of the headers that can possibly be
20391 			 * sent at this moment.  We'd rather over-estimate
20392 			 * the size than running out of space; this is okay
20393 			 * since this buffer is small anyway.
20394 			 */
20395 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
20396 
20397 			/*
20398 			 * Start and stuff offset for partial hardware
20399 			 * checksum offload; these are currently for IPv4.
20400 			 * For full checksum offload, they are set to zero.
20401 			 */
20402 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
20403 				if (af == AF_INET) {
20404 					start = IP_SIMPLE_HDR_LENGTH;
20405 					stuff = IP_SIMPLE_HDR_LENGTH +
20406 					    TCP_CHECKSUM_OFFSET;
20407 				} else {
20408 					start = IPV6_HDR_LEN;
20409 					stuff = IPV6_HDR_LEN +
20410 					    TCP_CHECKSUM_OFFSET;
20411 				}
20412 			} else {
20413 				start = stuff = 0;
20414 			}
20415 
20416 			/*
20417 			 * Create the header buffer, Multidata, as well as
20418 			 * any necessary attributes (destination address,
20419 			 * SAP and hardware checksum offload) that should
20420 			 * be associated with the Multidata message.
20421 			 */
20422 			ASSERT(cur_hdr_off == 0);
20423 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
20424 			    ((md_hbuf->b_wptr += md_hbuflen),
20425 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
20426 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
20427 			    /* fastpath mblk */
20428 			    ire->ire_nce->nce_res_mp,
20429 			    /* hardware checksum enabled */
20430 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
20431 			    /* hardware checksum offsets */
20432 			    start, stuff, 0,
20433 			    /* hardware checksum flag */
20434 			    hwcksum_flags, tcps) != 0)) {
20435 legacy_send:
20436 				/*
20437 				 * We arrive here from a failure within the
20438 				 * inner (packetizer) loop or we fail one of
20439 				 * the conditionals above. We restore the
20440 				 * previously checkpointed values for:
20441 				 *    xmit_tail
20442 				 *    usable
20443 				 *    tail_unsent
20444 				 *    snxt
20445 				 *    obbytes
20446 				 *    obsegs
20447 				 * We should then be able to dispatch any
20448 				 * complete multidata before reverting to the
20449 				 * traditional path with consistent parameters
20450 				 * (the inner loop updates these as it
20451 				 * iterates).
20452 				 */
20453 				*xmit_tail = xmit_tail_mmd;
20454 				*usable = usable_mmd;
20455 				*tail_unsent = tail_unsent_mmd;
20456 				*snxt = snxt_mmd;
20457 				obbytes = obbytes_mmd;
20458 				obsegs = obsegs_mmd;
20459 				if (md_mp != NULL) {
20460 					/* Unlink message from the chain */
20461 					if (md_mp_head != NULL) {
20462 						err = (intptr_t)rmvb(md_mp_head,
20463 						    md_mp);
20464 						/*
20465 						 * We can't assert that rmvb
20466 						 * did not return -1, since we
20467 						 * may get here before linkb
20468 						 * happens.  We do, however,
20469 						 * check if we just removed the
20470 						 * only element in the list.
20471 						 */
20472 						if (err == 0)
20473 							md_mp_head = NULL;
20474 					}
20475 					/* md_hbuf gets freed automatically */
20476 					TCP_STAT(tcps, tcp_mdt_discarded);
20477 					freeb(md_mp);
20478 				} else {
20479 					/* Either allocb or mmd_alloc failed */
20480 					TCP_STAT(tcps, tcp_mdt_allocfail);
20481 					if (md_hbuf != NULL)
20482 						freeb(md_hbuf);
20483 				}
20484 
20485 				/* send down what we've got so far */
20486 				if (md_mp_head != NULL) {
20487 					tcp_multisend_data(tcp, ire, ill,
20488 					    md_mp_head, obsegs, obbytes,
20489 					    &rconfirm);
20490 				}
20491 legacy_send_no_md:
20492 				if (ire != NULL)
20493 					IRE_REFRELE(ire);
20494 				/*
20495 				 * Too bad; let the legacy path handle this.
20496 				 * We specify INT_MAX for the threshold, since
20497 				 * we gave up with the Multidata processings
20498 				 * and let the old path have it all.
20499 				 */
20500 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20501 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20502 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20503 				    snxt, tail_unsent, xmit_tail, local_time,
20504 				    INT_MAX));
20505 			}
20506 
20507 			/* link to any existing ones, if applicable */
20508 			TCP_STAT(tcps, tcp_mdt_allocd);
20509 			if (md_mp_head == NULL) {
20510 				md_mp_head = md_mp;
20511 			} else if (tcp_mdt_chain) {
20512 				TCP_STAT(tcps, tcp_mdt_linked);
20513 				linkb(md_mp_head, md_mp);
20514 			}
20515 		}
20516 
20517 		ASSERT(md_mp_head != NULL);
20518 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20519 		ASSERT(md_mp != NULL && mmd != NULL);
20520 		ASSERT(md_hbuf != NULL);
20521 
20522 		/*
20523 		 * Packetize the transmittable portion of the data block;
20524 		 * each data block is essentially added to the Multidata
20525 		 * as a payload buffer.  We also deal with adding more
20526 		 * than one payload buffers, which happens when the remaining
20527 		 * packetized portion of the current payload buffer is less
20528 		 * than MSS, while the next data block in transmit queue
20529 		 * has enough data to make up for one.  This "spillover"
20530 		 * case essentially creates a split-packet, where portions
20531 		 * of the packet's payload fragments may span across two
20532 		 * virtually discontiguous address blocks.
20533 		 */
20534 		seg_len = mss;
20535 		do {
20536 			len = seg_len;
20537 
20538 			/* one must remain NULL for DTRACE_IP_FASTPATH */
20539 			ipha = NULL;
20540 			ip6h = NULL;
20541 
20542 			ASSERT(len > 0);
20543 			ASSERT(max_pld >= 0);
20544 			ASSERT(!add_buffer || cur_pld_off == 0);
20545 
20546 			/*
20547 			 * First time around for this payload buffer; note
20548 			 * in the case of a spillover, the following has
20549 			 * been done prior to adding the split-packet
20550 			 * descriptor to Multidata, and we don't want to
20551 			 * repeat the process.
20552 			 */
20553 			if (add_buffer) {
20554 				ASSERT(mmd != NULL);
20555 				ASSERT(md_pbuf == NULL);
20556 				ASSERT(md_pbuf_nxt == NULL);
20557 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20558 
20559 				/*
20560 				 * Have we reached the limit?  We'd get to
20561 				 * this case when we're not chaining the
20562 				 * Multidata messages together, and since
20563 				 * we're done, terminate this loop.
20564 				 */
20565 				if (max_pld == 0)
20566 					break; /* done */
20567 
20568 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20569 					TCP_STAT(tcps, tcp_mdt_allocfail);
20570 					goto legacy_send; /* out_of_mem */
20571 				}
20572 
20573 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20574 				    zc_cap != NULL) {
20575 					if (!ip_md_zcopy_attr(mmd, NULL,
20576 					    zc_cap->ill_zerocopy_flags)) {
20577 						freeb(md_pbuf);
20578 						TCP_STAT(tcps,
20579 						    tcp_mdt_allocfail);
20580 						/* out_of_mem */
20581 						goto legacy_send;
20582 					}
20583 					zcopy = B_TRUE;
20584 				}
20585 
20586 				md_pbuf->b_rptr += base_pld_off;
20587 
20588 				/*
20589 				 * Add a payload buffer to the Multidata; this
20590 				 * operation must not fail, or otherwise our
20591 				 * logic in this routine is broken.  There
20592 				 * is no memory allocation done by the
20593 				 * routine, so any returned failure simply
20594 				 * tells us that we've done something wrong.
20595 				 *
20596 				 * A failure tells us that either we're adding
20597 				 * the same payload buffer more than once, or
20598 				 * we're trying to add more buffers than
20599 				 * allowed (max_pld calculation is wrong).
20600 				 * None of the above cases should happen, and
20601 				 * we panic because either there's horrible
20602 				 * heap corruption, and/or programming mistake.
20603 				 */
20604 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20605 				if (pbuf_idx < 0) {
20606 					cmn_err(CE_PANIC, "tcp_multisend: "
20607 					    "payload buffer logic error "
20608 					    "detected for tcp %p mmd %p "
20609 					    "pbuf %p (%d)\n",
20610 					    (void *)tcp, (void *)mmd,
20611 					    (void *)md_pbuf, pbuf_idx);
20612 				}
20613 
20614 				ASSERT(max_pld > 0);
20615 				--max_pld;
20616 				add_buffer = B_FALSE;
20617 			}
20618 
20619 			ASSERT(md_mp_head != NULL);
20620 			ASSERT(md_pbuf != NULL);
20621 			ASSERT(md_pbuf_nxt == NULL);
20622 			ASSERT(pbuf_idx != -1);
20623 			ASSERT(pbuf_idx_nxt == -1);
20624 			ASSERT(*usable > 0);
20625 
20626 			/*
20627 			 * We spillover to the next payload buffer only
20628 			 * if all of the following is true:
20629 			 *
20630 			 *   1. There is not enough data on the current
20631 			 *	payload buffer to make up `len',
20632 			 *   2. We are allowed to send `len',
20633 			 *   3. The next payload buffer length is large
20634 			 *	enough to accomodate `spill'.
20635 			 */
20636 			if ((spill = len - *tail_unsent) > 0 &&
20637 			    *usable >= len &&
20638 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20639 			    max_pld > 0) {
20640 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20641 				if (md_pbuf_nxt == NULL) {
20642 					TCP_STAT(tcps, tcp_mdt_allocfail);
20643 					goto legacy_send; /* out_of_mem */
20644 				}
20645 
20646 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20647 				    zc_cap != NULL) {
20648 					if (!ip_md_zcopy_attr(mmd, NULL,
20649 					    zc_cap->ill_zerocopy_flags)) {
20650 						freeb(md_pbuf_nxt);
20651 						TCP_STAT(tcps,
20652 						    tcp_mdt_allocfail);
20653 						/* out_of_mem */
20654 						goto legacy_send;
20655 					}
20656 					zcopy = B_TRUE;
20657 				}
20658 
20659 				/*
20660 				 * See comments above on the first call to
20661 				 * mmd_addpldbuf for explanation on the panic.
20662 				 */
20663 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20664 				if (pbuf_idx_nxt < 0) {
20665 					panic("tcp_multisend: "
20666 					    "next payload buffer logic error "
20667 					    "detected for tcp %p mmd %p "
20668 					    "pbuf %p (%d)\n",
20669 					    (void *)tcp, (void *)mmd,
20670 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20671 				}
20672 
20673 				ASSERT(max_pld > 0);
20674 				--max_pld;
20675 			} else if (spill > 0) {
20676 				/*
20677 				 * If there's a spillover, but the following
20678 				 * xmit_tail couldn't give us enough octets
20679 				 * to reach "len", then stop the current
20680 				 * Multidata creation and let the legacy
20681 				 * tcp_send() path take over.  We don't want
20682 				 * to send the tiny segment as part of this
20683 				 * Multidata for performance reasons; instead,
20684 				 * we let the legacy path deal with grouping
20685 				 * it with the subsequent small mblks.
20686 				 */
20687 				if (*usable >= len &&
20688 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20689 					max_pld = 0;
20690 					break;	/* done */
20691 				}
20692 
20693 				/*
20694 				 * We can't spillover, and we are near
20695 				 * the end of the current payload buffer,
20696 				 * so send what's left.
20697 				 */
20698 				ASSERT(*tail_unsent > 0);
20699 				len = *tail_unsent;
20700 			}
20701 
20702 			/* tail_unsent is negated if there is a spillover */
20703 			*tail_unsent -= len;
20704 			*usable -= len;
20705 			ASSERT(*usable >= 0);
20706 
20707 			if (*usable < mss)
20708 				seg_len = *usable;
20709 			/*
20710 			 * Sender SWS avoidance; see comments in tcp_send();
20711 			 * everything else is the same, except that we only
20712 			 * do this here if there is no more data to be sent
20713 			 * following the current xmit_tail.  We don't check
20714 			 * for 1-byte urgent data because we shouldn't get
20715 			 * here if TCP_URG_VALID is set.
20716 			 */
20717 			if (*usable > 0 && *usable < mss &&
20718 			    ((md_pbuf_nxt == NULL &&
20719 			    (*xmit_tail)->b_cont == NULL) ||
20720 			    (md_pbuf_nxt != NULL &&
20721 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20722 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20723 			    (tcp->tcp_unsent -
20724 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20725 			    !tcp->tcp_zero_win_probe) {
20726 				if ((*snxt + len) == tcp->tcp_snxt &&
20727 				    (*snxt + len) == tcp->tcp_suna) {
20728 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20729 				}
20730 				done = B_TRUE;
20731 			}
20732 
20733 			/*
20734 			 * Prime pump for IP's checksumming on our behalf;
20735 			 * include the adjustment for a source route if any.
20736 			 * Do this only for software/partial hardware checksum
20737 			 * offload, as this field gets zeroed out later for
20738 			 * the full hardware checksum offload case.
20739 			 */
20740 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20741 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20742 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20743 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20744 			}
20745 
20746 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20747 			*snxt += len;
20748 
20749 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20750 			/*
20751 			 * We set the PUSH bit only if TCP has no more buffered
20752 			 * data to be transmitted (or if sender SWS avoidance
20753 			 * takes place), as opposed to setting it for every
20754 			 * last packet in the burst.
20755 			 */
20756 			if (done ||
20757 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20758 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20759 
20760 			/*
20761 			 * Set FIN bit if this is our last segment; snxt
20762 			 * already includes its length, and it will not
20763 			 * be adjusted after this point.
20764 			 */
20765 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20766 			    *snxt == tcp->tcp_fss) {
20767 				if (!tcp->tcp_fin_acked) {
20768 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20769 					BUMP_MIB(&tcps->tcps_mib,
20770 					    tcpOutControl);
20771 				}
20772 				if (!tcp->tcp_fin_sent) {
20773 					tcp->tcp_fin_sent = B_TRUE;
20774 					/*
20775 					 * tcp state must be ESTABLISHED
20776 					 * in order for us to get here in
20777 					 * the first place.
20778 					 */
20779 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20780 
20781 					/*
20782 					 * Upon returning from this routine,
20783 					 * tcp_wput_data() will set tcp_snxt
20784 					 * to be equal to snxt + tcp_fin_sent.
20785 					 * This is essentially the same as
20786 					 * setting it to tcp_fss + 1.
20787 					 */
20788 				}
20789 			}
20790 
20791 			tcp->tcp_last_sent_len = (ushort_t)len;
20792 
20793 			len += tcp_hdr_len;
20794 			if (tcp->tcp_ipversion == IPV4_VERSION)
20795 				tcp->tcp_ipha->ipha_length = htons(len);
20796 			else
20797 				tcp->tcp_ip6h->ip6_plen = htons(len -
20798 				    ((char *)&tcp->tcp_ip6h[1] -
20799 				    tcp->tcp_iphc));
20800 
20801 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20802 
20803 			/* setup header fragment */
20804 			PDESC_HDR_ADD(pkt_info,
20805 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20806 			    tcp->tcp_mdt_hdr_head,		/* head room */
20807 			    tcp_hdr_len,			/* len */
20808 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20809 
20810 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20811 			    hdr_frag_sz);
20812 			ASSERT(MBLKIN(md_hbuf,
20813 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20814 			    PDESC_HDRSIZE(pkt_info)));
20815 
20816 			/* setup first payload fragment */
20817 			PDESC_PLD_INIT(pkt_info);
20818 			PDESC_PLD_SPAN_ADD(pkt_info,
20819 			    pbuf_idx,				/* index */
20820 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20821 			    tcp->tcp_last_sent_len);		/* len */
20822 
20823 			/* create a split-packet in case of a spillover */
20824 			if (md_pbuf_nxt != NULL) {
20825 				ASSERT(spill > 0);
20826 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20827 				ASSERT(!add_buffer);
20828 
20829 				md_pbuf = md_pbuf_nxt;
20830 				md_pbuf_nxt = NULL;
20831 				pbuf_idx = pbuf_idx_nxt;
20832 				pbuf_idx_nxt = -1;
20833 				cur_pld_off = spill;
20834 
20835 				/* trim out first payload fragment */
20836 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20837 
20838 				/* setup second payload fragment */
20839 				PDESC_PLD_SPAN_ADD(pkt_info,
20840 				    pbuf_idx,			/* index */
20841 				    md_pbuf->b_rptr,		/* start */
20842 				    spill);			/* len */
20843 
20844 				if ((*xmit_tail)->b_next == NULL) {
20845 					/*
20846 					 * Store the lbolt used for RTT
20847 					 * estimation. We can only record one
20848 					 * timestamp per mblk so we do it when
20849 					 * we reach the end of the payload
20850 					 * buffer.  Also we only take a new
20851 					 * timestamp sample when the previous
20852 					 * timed data from the same mblk has
20853 					 * been ack'ed.
20854 					 */
20855 					(*xmit_tail)->b_prev = local_time;
20856 					(*xmit_tail)->b_next =
20857 					    (mblk_t *)(uintptr_t)first_snxt;
20858 				}
20859 
20860 				first_snxt = *snxt - spill;
20861 
20862 				/*
20863 				 * Advance xmit_tail; usable could be 0 by
20864 				 * the time we got here, but we made sure
20865 				 * above that we would only spillover to
20866 				 * the next data block if usable includes
20867 				 * the spilled-over amount prior to the
20868 				 * subtraction.  Therefore, we are sure
20869 				 * that xmit_tail->b_cont can't be NULL.
20870 				 */
20871 				ASSERT((*xmit_tail)->b_cont != NULL);
20872 				*xmit_tail = (*xmit_tail)->b_cont;
20873 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20874 				    (uintptr_t)INT_MAX);
20875 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20876 			} else {
20877 				cur_pld_off += tcp->tcp_last_sent_len;
20878 			}
20879 
20880 			/*
20881 			 * Fill in the header using the template header, and
20882 			 * add options such as time-stamp, ECN and/or SACK,
20883 			 * as needed.
20884 			 */
20885 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20886 			    (clock_t)local_time, num_sack_blk);
20887 
20888 			/* take care of some IP header businesses */
20889 			if (af == AF_INET) {
20890 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20891 
20892 				ASSERT(OK_32PTR((uchar_t *)ipha));
20893 				ASSERT(PDESC_HDRL(pkt_info) >=
20894 				    IP_SIMPLE_HDR_LENGTH);
20895 				ASSERT(ipha->ipha_version_and_hdr_length ==
20896 				    IP_SIMPLE_HDR_VERSION);
20897 
20898 				/*
20899 				 * Assign ident value for current packet; see
20900 				 * related comments in ip_wput_ire() about the
20901 				 * contract private interface with clustering
20902 				 * group.
20903 				 */
20904 				clusterwide = B_FALSE;
20905 				if (cl_inet_ipident != NULL) {
20906 					ASSERT(cl_inet_isclusterwide != NULL);
20907 					if ((*cl_inet_isclusterwide)(stack_id,
20908 					    IPPROTO_IP, AF_INET,
20909 					    (uint8_t *)(uintptr_t)src, NULL)) {
20910 						ipha->ipha_ident =
20911 						    (*cl_inet_ipident)(stack_id,
20912 						    IPPROTO_IP, AF_INET,
20913 						    (uint8_t *)(uintptr_t)src,
20914 						    (uint8_t *)(uintptr_t)dst,
20915 						    NULL);
20916 						clusterwide = B_TRUE;
20917 					}
20918 				}
20919 
20920 				if (!clusterwide) {
20921 					ipha->ipha_ident = (uint16_t)
20922 					    atomic_add_32_nv(
20923 						&ire->ire_ident, 1);
20924 				}
20925 #ifndef _BIG_ENDIAN
20926 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20927 				    (ipha->ipha_ident >> 8);
20928 #endif
20929 			} else {
20930 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20931 
20932 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20933 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20934 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20935 				ASSERT(PDESC_HDRL(pkt_info) >=
20936 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20937 				    TCP_CHECKSUM_SIZE));
20938 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20939 
20940 				if (tcp->tcp_ip_forward_progress) {
20941 					rconfirm = B_TRUE;
20942 					tcp->tcp_ip_forward_progress = B_FALSE;
20943 				}
20944 			}
20945 
20946 			/* at least one payload span, and at most two */
20947 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20948 
20949 			/* add the packet descriptor to Multidata */
20950 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20951 			    KM_NOSLEEP)) == NULL) {
20952 				/*
20953 				 * Any failure other than ENOMEM indicates
20954 				 * that we have passed in invalid pkt_info
20955 				 * or parameters to mmd_addpdesc, which must
20956 				 * not happen.
20957 				 *
20958 				 * EINVAL is a result of failure on boundary
20959 				 * checks against the pkt_info contents.  It
20960 				 * should not happen, and we panic because
20961 				 * either there's horrible heap corruption,
20962 				 * and/or programming mistake.
20963 				 */
20964 				if (err != ENOMEM) {
20965 					cmn_err(CE_PANIC, "tcp_multisend: "
20966 					    "pdesc logic error detected for "
20967 					    "tcp %p mmd %p pinfo %p (%d)\n",
20968 					    (void *)tcp, (void *)mmd,
20969 					    (void *)pkt_info, err);
20970 				}
20971 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20972 				goto legacy_send; /* out_of_mem */
20973 			}
20974 			ASSERT(pkt != NULL);
20975 
20976 			/* calculate IP header and TCP checksums */
20977 			if (af == AF_INET) {
20978 				/* calculate pseudo-header checksum */
20979 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20980 				    (src >> 16) + (src & 0xFFFF);
20981 
20982 				/* offset for TCP header checksum */
20983 				up = IPH_TCPH_CHECKSUMP(ipha,
20984 				    IP_SIMPLE_HDR_LENGTH);
20985 			} else {
20986 				up = (uint16_t *)&ip6h->ip6_src;
20987 
20988 				/* calculate pseudo-header checksum */
20989 				cksum = up[0] + up[1] + up[2] + up[3] +
20990 				    up[4] + up[5] + up[6] + up[7] +
20991 				    up[8] + up[9] + up[10] + up[11] +
20992 				    up[12] + up[13] + up[14] + up[15];
20993 
20994 				/* Fold the initial sum */
20995 				cksum = (cksum & 0xffff) + (cksum >> 16);
20996 
20997 				up = (uint16_t *)(((uchar_t *)ip6h) +
20998 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20999 			}
21000 
21001 			if (hwcksum_flags & HCK_FULLCKSUM) {
21002 				/* clear checksum field for hardware */
21003 				*up = 0;
21004 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
21005 				uint32_t sum;
21006 
21007 				/* pseudo-header checksumming */
21008 				sum = *up + cksum + IP_TCP_CSUM_COMP;
21009 				sum = (sum & 0xFFFF) + (sum >> 16);
21010 				*up = (sum & 0xFFFF) + (sum >> 16);
21011 			} else {
21012 				/* software checksumming */
21013 				TCP_STAT(tcps, tcp_out_sw_cksum);
21014 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
21015 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
21016 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
21017 				    cksum + IP_TCP_CSUM_COMP);
21018 				if (*up == 0)
21019 					*up = 0xFFFF;
21020 			}
21021 
21022 			/* IPv4 header checksum */
21023 			if (af == AF_INET) {
21024 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
21025 					ipha->ipha_hdr_checksum = 0;
21026 				} else {
21027 					IP_HDR_CKSUM(ipha, cksum,
21028 					    ((uint32_t *)ipha)[0],
21029 					    ((uint16_t *)ipha)[4]);
21030 				}
21031 			}
21032 
21033 			if (af == AF_INET &&
21034 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
21035 			    af == AF_INET6 &&
21036 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
21037 				mblk_t	*mp, *mp1;
21038 				uchar_t	*hdr_rptr, *hdr_wptr;
21039 				uchar_t	*pld_rptr, *pld_wptr;
21040 
21041 				/*
21042 				 * We reconstruct a pseudo packet for the hooks
21043 				 * framework using mmd_transform_link().
21044 				 * If it is a split packet we pullup the
21045 				 * payload. FW_HOOKS expects a pkt comprising
21046 				 * of two mblks: a header and the payload.
21047 				 */
21048 				if ((mp = mmd_transform_link(pkt)) == NULL) {
21049 					TCP_STAT(tcps, tcp_mdt_allocfail);
21050 					goto legacy_send;
21051 				}
21052 
21053 				if (pkt_info->pld_cnt > 1) {
21054 					/* split payload, more than one pld */
21055 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
21056 					    NULL) {
21057 						freemsg(mp);
21058 						TCP_STAT(tcps,
21059 						    tcp_mdt_allocfail);
21060 						goto legacy_send;
21061 					}
21062 					freemsg(mp->b_cont);
21063 					mp->b_cont = mp1;
21064 				} else {
21065 					mp1 = mp->b_cont;
21066 				}
21067 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
21068 
21069 				/*
21070 				 * Remember the message offsets. This is so we
21071 				 * can detect changes when we return from the
21072 				 * FW_HOOKS callbacks.
21073 				 */
21074 				hdr_rptr = mp->b_rptr;
21075 				hdr_wptr = mp->b_wptr;
21076 				pld_rptr = mp->b_cont->b_rptr;
21077 				pld_wptr = mp->b_cont->b_wptr;
21078 
21079 				if (af == AF_INET) {
21080 					DTRACE_PROBE4(
21081 					    ip4__physical__out__start,
21082 					    ill_t *, NULL,
21083 					    ill_t *, ill,
21084 					    ipha_t *, ipha,
21085 					    mblk_t *, mp);
21086 					FW_HOOKS(
21087 					    ipst->ips_ip4_physical_out_event,
21088 					    ipst->ips_ipv4firewall_physical_out,
21089 					    NULL, ill, ipha, mp, mp, 0, ipst);
21090 					DTRACE_PROBE1(
21091 					    ip4__physical__out__end,
21092 					    mblk_t *, mp);
21093 				} else {
21094 					DTRACE_PROBE4(
21095 					    ip6__physical__out_start,
21096 					    ill_t *, NULL,
21097 					    ill_t *, ill,
21098 					    ip6_t *, ip6h,
21099 					    mblk_t *, mp);
21100 					FW_HOOKS6(
21101 					    ipst->ips_ip6_physical_out_event,
21102 					    ipst->ips_ipv6firewall_physical_out,
21103 					    NULL, ill, ip6h, mp, mp, 0, ipst);
21104 					DTRACE_PROBE1(
21105 					    ip6__physical__out__end,
21106 					    mblk_t *, mp);
21107 				}
21108 
21109 				if (mp == NULL ||
21110 				    (mp1 = mp->b_cont) == NULL ||
21111 				    mp->b_rptr != hdr_rptr ||
21112 				    mp->b_wptr != hdr_wptr ||
21113 				    mp1->b_rptr != pld_rptr ||
21114 				    mp1->b_wptr != pld_wptr ||
21115 				    mp1->b_cont != NULL) {
21116 					/*
21117 					 * We abandon multidata processing and
21118 					 * return to the normal path, either
21119 					 * when a packet is blocked, or when
21120 					 * the boundaries of header buffer or
21121 					 * payload buffer have been changed by
21122 					 * FW_HOOKS[6].
21123 					 */
21124 					if (mp != NULL)
21125 						freemsg(mp);
21126 					goto legacy_send;
21127 				}
21128 				/* Finished with the pseudo packet */
21129 				freemsg(mp);
21130 			}
21131 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
21132 			    ill, ipha, ip6h);
21133 			/* advance header offset */
21134 			cur_hdr_off += hdr_frag_sz;
21135 
21136 			obbytes += tcp->tcp_last_sent_len;
21137 			++obsegs;
21138 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
21139 		    *tail_unsent > 0);
21140 
21141 		if ((*xmit_tail)->b_next == NULL) {
21142 			/*
21143 			 * Store the lbolt used for RTT estimation. We can only
21144 			 * record one timestamp per mblk so we do it when we
21145 			 * reach the end of the payload buffer. Also we only
21146 			 * take a new timestamp sample when the previous timed
21147 			 * data from the same mblk has been ack'ed.
21148 			 */
21149 			(*xmit_tail)->b_prev = local_time;
21150 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
21151 		}
21152 
21153 		ASSERT(*tail_unsent >= 0);
21154 		if (*tail_unsent > 0) {
21155 			/*
21156 			 * We got here because we broke out of the above
21157 			 * loop due to of one of the following cases:
21158 			 *
21159 			 *   1. len < adjusted MSS (i.e. small),
21160 			 *   2. Sender SWS avoidance,
21161 			 *   3. max_pld is zero.
21162 			 *
21163 			 * We are done for this Multidata, so trim our
21164 			 * last payload buffer (if any) accordingly.
21165 			 */
21166 			if (md_pbuf != NULL)
21167 				md_pbuf->b_wptr -= *tail_unsent;
21168 		} else if (*usable > 0) {
21169 			*xmit_tail = (*xmit_tail)->b_cont;
21170 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
21171 			    (uintptr_t)INT_MAX);
21172 			*tail_unsent = (int)MBLKL(*xmit_tail);
21173 			add_buffer = B_TRUE;
21174 		}
21175 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
21176 	    (tcp_mdt_chain || max_pld > 0));
21177 
21178 	if (md_mp_head != NULL) {
21179 		/* send everything down */
21180 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
21181 		    &rconfirm);
21182 	}
21183 
21184 #undef PREP_NEW_MULTIDATA
21185 #undef PREP_NEW_PBUF
21186 #undef IPVER
21187 
21188 	IRE_REFRELE(ire);
21189 	return (0);
21190 }
21191 
21192 /*
21193  * A wrapper function for sending one or more Multidata messages down to
21194  * the module below ip; this routine does not release the reference of the
21195  * IRE (caller does that).  This routine is analogous to tcp_send_data().
21196  */
21197 static void
21198 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
21199     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
21200 {
21201 	uint64_t delta;
21202 	nce_t *nce;
21203 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21204 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21205 
21206 	ASSERT(ire != NULL && ill != NULL);
21207 	ASSERT(ire->ire_stq != NULL);
21208 	ASSERT(md_mp_head != NULL);
21209 	ASSERT(rconfirm != NULL);
21210 
21211 	/* adjust MIBs and IRE timestamp */
21212 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
21213 	tcp->tcp_obsegs += obsegs;
21214 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
21215 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
21216 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
21217 
21218 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21219 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
21220 	} else {
21221 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
21222 	}
21223 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
21224 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
21225 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
21226 
21227 	ire->ire_ob_pkt_count += obsegs;
21228 	if (ire->ire_ipif != NULL)
21229 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
21230 	ire->ire_last_used_time = lbolt;
21231 
21232 	if (ipst->ips_ipobs_enabled) {
21233 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
21234 		pdesc_t *dl_pkt;
21235 		pdescinfo_t pinfo;
21236 		mblk_t *nmp;
21237 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
21238 
21239 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
21240 		    (dl_pkt != NULL);
21241 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
21242 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
21243 				continue;
21244 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
21245 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
21246 			freemsg(nmp);
21247 		}
21248 	}
21249 
21250 	/* send it down */
21251 	putnext(ire->ire_stq, md_mp_head);
21252 
21253 	/* we're done for TCP/IPv4 */
21254 	if (tcp->tcp_ipversion == IPV4_VERSION)
21255 		return;
21256 
21257 	nce = ire->ire_nce;
21258 
21259 	ASSERT(nce != NULL);
21260 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
21261 	ASSERT(nce->nce_state != ND_INCOMPLETE);
21262 
21263 	/* reachability confirmation? */
21264 	if (*rconfirm) {
21265 		nce->nce_last = TICK_TO_MSEC(lbolt64);
21266 		if (nce->nce_state != ND_REACHABLE) {
21267 			mutex_enter(&nce->nce_lock);
21268 			nce->nce_state = ND_REACHABLE;
21269 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
21270 			mutex_exit(&nce->nce_lock);
21271 			(void) untimeout(nce->nce_timeout_id);
21272 			if (ip_debug > 2) {
21273 				/* ip1dbg */
21274 				pr_addr_dbg("tcp_multisend_data: state "
21275 				    "for %s changed to REACHABLE\n",
21276 				    AF_INET6, &ire->ire_addr_v6);
21277 			}
21278 		}
21279 		/* reset transport reachability confirmation */
21280 		*rconfirm = B_FALSE;
21281 	}
21282 
21283 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
21284 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
21285 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
21286 
21287 	if (delta > (uint64_t)ill->ill_reachable_time) {
21288 		mutex_enter(&nce->nce_lock);
21289 		switch (nce->nce_state) {
21290 		case ND_REACHABLE:
21291 		case ND_STALE:
21292 			/*
21293 			 * ND_REACHABLE is identical to ND_STALE in this
21294 			 * specific case. If reachable time has expired for
21295 			 * this neighbor (delta is greater than reachable
21296 			 * time), conceptually, the neighbor cache is no
21297 			 * longer in REACHABLE state, but already in STALE
21298 			 * state.  So the correct transition here is to
21299 			 * ND_DELAY.
21300 			 */
21301 			nce->nce_state = ND_DELAY;
21302 			mutex_exit(&nce->nce_lock);
21303 			NDP_RESTART_TIMER(nce,
21304 			    ipst->ips_delay_first_probe_time);
21305 			if (ip_debug > 3) {
21306 				/* ip2dbg */
21307 				pr_addr_dbg("tcp_multisend_data: state "
21308 				    "for %s changed to DELAY\n",
21309 				    AF_INET6, &ire->ire_addr_v6);
21310 			}
21311 			break;
21312 		case ND_DELAY:
21313 		case ND_PROBE:
21314 			mutex_exit(&nce->nce_lock);
21315 			/* Timers have already started */
21316 			break;
21317 		case ND_UNREACHABLE:
21318 			/*
21319 			 * ndp timer has detected that this nce is
21320 			 * unreachable and initiated deleting this nce
21321 			 * and all its associated IREs. This is a race
21322 			 * where we found the ire before it was deleted
21323 			 * and have just sent out a packet using this
21324 			 * unreachable nce.
21325 			 */
21326 			mutex_exit(&nce->nce_lock);
21327 			break;
21328 		default:
21329 			ASSERT(0);
21330 		}
21331 	}
21332 }
21333 
21334 /*
21335  * Derived from tcp_send_data().
21336  */
21337 static void
21338 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
21339     int num_lso_seg)
21340 {
21341 	ipha_t		*ipha;
21342 	mblk_t		*ire_fp_mp;
21343 	uint_t		ire_fp_mp_len;
21344 	uint32_t	hcksum_txflags = 0;
21345 	ipaddr_t	src;
21346 	ipaddr_t	dst;
21347 	uint32_t	cksum;
21348 	uint16_t	*up;
21349 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21350 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21351 
21352 	ASSERT(DB_TYPE(mp) == M_DATA);
21353 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
21354 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
21355 	ASSERT(tcp->tcp_connp != NULL);
21356 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
21357 
21358 	ipha = (ipha_t *)mp->b_rptr;
21359 	src = ipha->ipha_src;
21360 	dst = ipha->ipha_dst;
21361 
21362 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
21363 
21364 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21365 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
21366 	    num_lso_seg);
21367 #ifndef _BIG_ENDIAN
21368 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21369 #endif
21370 	if (tcp->tcp_snd_zcopy_aware) {
21371 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
21372 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
21373 			mp = tcp_zcopy_disable(tcp, mp);
21374 	}
21375 
21376 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
21377 		ASSERT(ill->ill_hcksum_capab != NULL);
21378 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
21379 	}
21380 
21381 	/*
21382 	 * Since the TCP checksum should be recalculated by h/w, we can just
21383 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
21384 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
21385 	 * The partial pseudo-header excludes TCP length, that was calculated
21386 	 * in tcp_send(), so to zero *up before further processing.
21387 	 */
21388 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21389 
21390 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
21391 	*up = 0;
21392 
21393 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
21394 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
21395 
21396 	/*
21397 	 * Append LSO flags and mss to the mp.
21398 	 */
21399 	lso_info_set(mp, mss, HW_LSO);
21400 
21401 	ipha->ipha_fragment_offset_and_flags |=
21402 	    (uint32_t)htons(ire->ire_frag_flag);
21403 
21404 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
21405 	ire_fp_mp_len = MBLKL(ire_fp_mp);
21406 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
21407 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
21408 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
21409 
21410 	UPDATE_OB_PKT_COUNT(ire);
21411 	ire->ire_last_used_time = lbolt;
21412 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
21413 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
21414 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
21415 	    ntohs(ipha->ipha_length));
21416 
21417 	DTRACE_PROBE4(ip4__physical__out__start,
21418 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
21419 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
21420 	    ipst->ips_ipv4firewall_physical_out, NULL,
21421 	    ill, ipha, mp, mp, 0, ipst);
21422 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21423 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
21424 
21425 	if (mp != NULL) {
21426 		if (ipst->ips_ipobs_enabled) {
21427 			zoneid_t szone;
21428 
21429 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
21430 			    ipst, ALL_ZONES);
21431 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
21432 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
21433 		}
21434 
21435 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0);
21436 	}
21437 }
21438 
21439 /*
21440  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
21441  * scheme, and returns one of the following:
21442  *
21443  * -1 = failed allocation.
21444  *  0 = success; burst count reached, or usable send window is too small,
21445  *      and that we'd rather wait until later before sending again.
21446  *  1 = success; we are called from tcp_multisend(), and both usable send
21447  *      window and tail_unsent are greater than the MDT threshold, and thus
21448  *      Multidata Transmit should be used instead.
21449  */
21450 static int
21451 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
21452     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
21453     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
21454     const int mdt_thres)
21455 {
21456 	int num_burst_seg = tcp->tcp_snd_burst;
21457 	ire_t		*ire = NULL;
21458 	ill_t		*ill = NULL;
21459 	mblk_t		*ire_fp_mp = NULL;
21460 	uint_t		ire_fp_mp_len = 0;
21461 	int		num_lso_seg = 1;
21462 	uint_t		lso_usable;
21463 	boolean_t	do_lso_send = B_FALSE;
21464 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21465 
21466 	/*
21467 	 * Check LSO capability before any further work. And the similar check
21468 	 * need to be done in for(;;) loop.
21469 	 * LSO will be deployed when therer is more than one mss of available
21470 	 * data and a burst transmission is allowed.
21471 	 */
21472 	if (tcp->tcp_lso &&
21473 	    (tcp->tcp_valid_bits == 0 ||
21474 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21475 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21476 		/*
21477 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21478 		 */
21479 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
21480 			/*
21481 			 * Enable LSO with this transmission.
21482 			 * Since IRE has been hold in
21483 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
21484 			 * should be called before return.
21485 			 */
21486 			do_lso_send = B_TRUE;
21487 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21488 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21489 			/* Round up to multiple of 4 */
21490 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21491 		} else {
21492 			do_lso_send = B_FALSE;
21493 			ill = NULL;
21494 		}
21495 	}
21496 
21497 	for (;;) {
21498 		struct datab	*db;
21499 		tcph_t		*tcph;
21500 		uint32_t	sum;
21501 		mblk_t		*mp, *mp1;
21502 		uchar_t		*rptr;
21503 		int		len;
21504 
21505 		/*
21506 		 * If we're called by tcp_multisend(), and the amount of
21507 		 * sendable data as well as the size of current xmit_tail
21508 		 * is beyond the MDT threshold, return to the caller and
21509 		 * let the large data transmit be done using MDT.
21510 		 */
21511 		if (*usable > 0 && *usable > mdt_thres &&
21512 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21513 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21514 			ASSERT(tcp->tcp_mdt);
21515 			return (1);	/* success; do large send */
21516 		}
21517 
21518 		if (num_burst_seg == 0)
21519 			break;		/* success; burst count reached */
21520 
21521 		/*
21522 		 * Calculate the maximum payload length we can send in *one*
21523 		 * time.
21524 		 */
21525 		if (do_lso_send) {
21526 			/*
21527 			 * Check whether need to do LSO any more.
21528 			 */
21529 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21530 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21531 				lso_usable = MIN(lso_usable,
21532 				    num_burst_seg * mss);
21533 
21534 				num_lso_seg = lso_usable / mss;
21535 				if (lso_usable % mss) {
21536 					num_lso_seg++;
21537 					tcp->tcp_last_sent_len = (ushort_t)
21538 					    (lso_usable % mss);
21539 				} else {
21540 					tcp->tcp_last_sent_len = (ushort_t)mss;
21541 				}
21542 			} else {
21543 				do_lso_send = B_FALSE;
21544 				num_lso_seg = 1;
21545 				lso_usable = mss;
21546 			}
21547 		}
21548 
21549 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21550 
21551 		/*
21552 		 * Adjust num_burst_seg here.
21553 		 */
21554 		num_burst_seg -= num_lso_seg;
21555 
21556 		len = mss;
21557 		if (len > *usable) {
21558 			ASSERT(do_lso_send == B_FALSE);
21559 
21560 			len = *usable;
21561 			if (len <= 0) {
21562 				/* Terminate the loop */
21563 				break;	/* success; too small */
21564 			}
21565 			/*
21566 			 * Sender silly-window avoidance.
21567 			 * Ignore this if we are going to send a
21568 			 * zero window probe out.
21569 			 *
21570 			 * TODO: force data into microscopic window?
21571 			 *	==> (!pushed || (unsent > usable))
21572 			 */
21573 			if (len < (tcp->tcp_max_swnd >> 1) &&
21574 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21575 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21576 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21577 				/*
21578 				 * If the retransmit timer is not running
21579 				 * we start it so that we will retransmit
21580 				 * in the case when the the receiver has
21581 				 * decremented the window.
21582 				 */
21583 				if (*snxt == tcp->tcp_snxt &&
21584 				    *snxt == tcp->tcp_suna) {
21585 					/*
21586 					 * We are not supposed to send
21587 					 * anything.  So let's wait a little
21588 					 * bit longer before breaking SWS
21589 					 * avoidance.
21590 					 *
21591 					 * What should the value be?
21592 					 * Suggestion: MAX(init rexmit time,
21593 					 * tcp->tcp_rto)
21594 					 */
21595 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21596 				}
21597 				break;	/* success; too small */
21598 			}
21599 		}
21600 
21601 		tcph = tcp->tcp_tcph;
21602 
21603 		/*
21604 		 * The reason to adjust len here is that we need to set flags
21605 		 * and calculate checksum.
21606 		 */
21607 		if (do_lso_send)
21608 			len = lso_usable;
21609 
21610 		*usable -= len; /* Approximate - can be adjusted later */
21611 		if (*usable > 0)
21612 			tcph->th_flags[0] = TH_ACK;
21613 		else
21614 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21615 
21616 		/*
21617 		 * Prime pump for IP's checksumming on our behalf
21618 		 * Include the adjustment for a source route if any.
21619 		 */
21620 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21621 		sum = (sum >> 16) + (sum & 0xFFFF);
21622 		U16_TO_ABE16(sum, tcph->th_sum);
21623 
21624 		U32_TO_ABE32(*snxt, tcph->th_seq);
21625 
21626 		/*
21627 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21628 		 * set.  For the case when TCP_FSS_VALID is the only valid
21629 		 * bit (normal active close), branch off only when we think
21630 		 * that the FIN flag needs to be set.  Note for this case,
21631 		 * that (snxt + len) may not reflect the actual seg_len,
21632 		 * as len may be further reduced in tcp_xmit_mp().  If len
21633 		 * gets modified, we will end up here again.
21634 		 */
21635 		if (tcp->tcp_valid_bits != 0 &&
21636 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21637 		    ((*snxt + len) == tcp->tcp_fss))) {
21638 			uchar_t		*prev_rptr;
21639 			uint32_t	prev_snxt = tcp->tcp_snxt;
21640 
21641 			if (*tail_unsent == 0) {
21642 				ASSERT((*xmit_tail)->b_cont != NULL);
21643 				*xmit_tail = (*xmit_tail)->b_cont;
21644 				prev_rptr = (*xmit_tail)->b_rptr;
21645 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21646 				    (*xmit_tail)->b_rptr);
21647 			} else {
21648 				prev_rptr = (*xmit_tail)->b_rptr;
21649 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21650 				    *tail_unsent;
21651 			}
21652 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21653 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21654 			/* Restore tcp_snxt so we get amount sent right. */
21655 			tcp->tcp_snxt = prev_snxt;
21656 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21657 				/*
21658 				 * If the previous timestamp is still in use,
21659 				 * don't stomp on it.
21660 				 */
21661 				if ((*xmit_tail)->b_next == NULL) {
21662 					(*xmit_tail)->b_prev = local_time;
21663 					(*xmit_tail)->b_next =
21664 					    (mblk_t *)(uintptr_t)(*snxt);
21665 				}
21666 			} else
21667 				(*xmit_tail)->b_rptr = prev_rptr;
21668 
21669 			if (mp == NULL) {
21670 				if (ire != NULL)
21671 					IRE_REFRELE(ire);
21672 				return (-1);
21673 			}
21674 			mp1 = mp->b_cont;
21675 
21676 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21677 				tcp->tcp_last_sent_len = (ushort_t)len;
21678 			while (mp1->b_cont) {
21679 				*xmit_tail = (*xmit_tail)->b_cont;
21680 				(*xmit_tail)->b_prev = local_time;
21681 				(*xmit_tail)->b_next =
21682 				    (mblk_t *)(uintptr_t)(*snxt);
21683 				mp1 = mp1->b_cont;
21684 			}
21685 			*snxt += len;
21686 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21687 			BUMP_LOCAL(tcp->tcp_obsegs);
21688 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21689 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21690 			tcp_send_data(tcp, q, mp);
21691 			continue;
21692 		}
21693 
21694 		*snxt += len;	/* Adjust later if we don't send all of len */
21695 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21696 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21697 
21698 		if (*tail_unsent) {
21699 			/* Are the bytes above us in flight? */
21700 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21701 			if (rptr != (*xmit_tail)->b_rptr) {
21702 				*tail_unsent -= len;
21703 				if (len <= mss) /* LSO is unusable */
21704 					tcp->tcp_last_sent_len = (ushort_t)len;
21705 				len += tcp_hdr_len;
21706 				if (tcp->tcp_ipversion == IPV4_VERSION)
21707 					tcp->tcp_ipha->ipha_length = htons(len);
21708 				else
21709 					tcp->tcp_ip6h->ip6_plen =
21710 					    htons(len -
21711 					    ((char *)&tcp->tcp_ip6h[1] -
21712 					    tcp->tcp_iphc));
21713 				mp = dupb(*xmit_tail);
21714 				if (mp == NULL) {
21715 					if (ire != NULL)
21716 						IRE_REFRELE(ire);
21717 					return (-1);	/* out_of_mem */
21718 				}
21719 				mp->b_rptr = rptr;
21720 				/*
21721 				 * If the old timestamp is no longer in use,
21722 				 * sample a new timestamp now.
21723 				 */
21724 				if ((*xmit_tail)->b_next == NULL) {
21725 					(*xmit_tail)->b_prev = local_time;
21726 					(*xmit_tail)->b_next =
21727 					    (mblk_t *)(uintptr_t)(*snxt-len);
21728 				}
21729 				goto must_alloc;
21730 			}
21731 		} else {
21732 			*xmit_tail = (*xmit_tail)->b_cont;
21733 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21734 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21735 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21736 			    (*xmit_tail)->b_rptr);
21737 		}
21738 
21739 		(*xmit_tail)->b_prev = local_time;
21740 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21741 
21742 		*tail_unsent -= len;
21743 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21744 			tcp->tcp_last_sent_len = (ushort_t)len;
21745 
21746 		len += tcp_hdr_len;
21747 		if (tcp->tcp_ipversion == IPV4_VERSION)
21748 			tcp->tcp_ipha->ipha_length = htons(len);
21749 		else
21750 			tcp->tcp_ip6h->ip6_plen = htons(len -
21751 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21752 
21753 		mp = dupb(*xmit_tail);
21754 		if (mp == NULL) {
21755 			if (ire != NULL)
21756 				IRE_REFRELE(ire);
21757 			return (-1);	/* out_of_mem */
21758 		}
21759 
21760 		len = tcp_hdr_len;
21761 		/*
21762 		 * There are four reasons to allocate a new hdr mblk:
21763 		 *  1) The bytes above us are in use by another packet
21764 		 *  2) We don't have good alignment
21765 		 *  3) The mblk is being shared
21766 		 *  4) We don't have enough room for a header
21767 		 */
21768 		rptr = mp->b_rptr - len;
21769 		if (!OK_32PTR(rptr) ||
21770 		    ((db = mp->b_datap), db->db_ref != 2) ||
21771 		    rptr < db->db_base + ire_fp_mp_len) {
21772 			/* NOTE: we assume allocb returns an OK_32PTR */
21773 
21774 		must_alloc:;
21775 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21776 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21777 			if (mp1 == NULL) {
21778 				freemsg(mp);
21779 				if (ire != NULL)
21780 					IRE_REFRELE(ire);
21781 				return (-1);	/* out_of_mem */
21782 			}
21783 			mp1->b_cont = mp;
21784 			mp = mp1;
21785 			/* Leave room for Link Level header */
21786 			len = tcp_hdr_len;
21787 			rptr =
21788 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21789 			mp->b_wptr = &rptr[len];
21790 		}
21791 
21792 		/*
21793 		 * Fill in the header using the template header, and add
21794 		 * options such as time-stamp, ECN and/or SACK, as needed.
21795 		 */
21796 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21797 
21798 		mp->b_rptr = rptr;
21799 
21800 		if (*tail_unsent) {
21801 			int spill = *tail_unsent;
21802 
21803 			mp1 = mp->b_cont;
21804 			if (mp1 == NULL)
21805 				mp1 = mp;
21806 
21807 			/*
21808 			 * If we're a little short, tack on more mblks until
21809 			 * there is no more spillover.
21810 			 */
21811 			while (spill < 0) {
21812 				mblk_t *nmp;
21813 				int nmpsz;
21814 
21815 				nmp = (*xmit_tail)->b_cont;
21816 				nmpsz = MBLKL(nmp);
21817 
21818 				/*
21819 				 * Excess data in mblk; can we split it?
21820 				 * If MDT is enabled for the connection,
21821 				 * keep on splitting as this is a transient
21822 				 * send path.
21823 				 */
21824 				if (!do_lso_send && !tcp->tcp_mdt &&
21825 				    (spill + nmpsz > 0)) {
21826 					/*
21827 					 * Don't split if stream head was
21828 					 * told to break up larger writes
21829 					 * into smaller ones.
21830 					 */
21831 					if (tcp->tcp_maxpsz > 0)
21832 						break;
21833 
21834 					/*
21835 					 * Next mblk is less than SMSS/2
21836 					 * rounded up to nearest 64-byte;
21837 					 * let it get sent as part of the
21838 					 * next segment.
21839 					 */
21840 					if (tcp->tcp_localnet &&
21841 					    !tcp->tcp_cork &&
21842 					    (nmpsz < roundup((mss >> 1), 64)))
21843 						break;
21844 				}
21845 
21846 				*xmit_tail = nmp;
21847 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21848 				/* Stash for rtt use later */
21849 				(*xmit_tail)->b_prev = local_time;
21850 				(*xmit_tail)->b_next =
21851 				    (mblk_t *)(uintptr_t)(*snxt - len);
21852 				mp1->b_cont = dupb(*xmit_tail);
21853 				mp1 = mp1->b_cont;
21854 
21855 				spill += nmpsz;
21856 				if (mp1 == NULL) {
21857 					*tail_unsent = spill;
21858 					freemsg(mp);
21859 					if (ire != NULL)
21860 						IRE_REFRELE(ire);
21861 					return (-1);	/* out_of_mem */
21862 				}
21863 			}
21864 
21865 			/* Trim back any surplus on the last mblk */
21866 			if (spill >= 0) {
21867 				mp1->b_wptr -= spill;
21868 				*tail_unsent = spill;
21869 			} else {
21870 				/*
21871 				 * We did not send everything we could in
21872 				 * order to remain within the b_cont limit.
21873 				 */
21874 				*usable -= spill;
21875 				*snxt += spill;
21876 				tcp->tcp_last_sent_len += spill;
21877 				UPDATE_MIB(&tcps->tcps_mib,
21878 				    tcpOutDataBytes, spill);
21879 				/*
21880 				 * Adjust the checksum
21881 				 */
21882 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21883 				sum += spill;
21884 				sum = (sum >> 16) + (sum & 0xFFFF);
21885 				U16_TO_ABE16(sum, tcph->th_sum);
21886 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21887 					sum = ntohs(
21888 					    ((ipha_t *)rptr)->ipha_length) +
21889 					    spill;
21890 					((ipha_t *)rptr)->ipha_length =
21891 					    htons(sum);
21892 				} else {
21893 					sum = ntohs(
21894 					    ((ip6_t *)rptr)->ip6_plen) +
21895 					    spill;
21896 					((ip6_t *)rptr)->ip6_plen =
21897 					    htons(sum);
21898 				}
21899 				*tail_unsent = 0;
21900 			}
21901 		}
21902 		if (tcp->tcp_ip_forward_progress) {
21903 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21904 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21905 			tcp->tcp_ip_forward_progress = B_FALSE;
21906 		}
21907 
21908 		if (do_lso_send) {
21909 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21910 			    num_lso_seg);
21911 			tcp->tcp_obsegs += num_lso_seg;
21912 
21913 			TCP_STAT(tcps, tcp_lso_times);
21914 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21915 		} else {
21916 			tcp_send_data(tcp, q, mp);
21917 			BUMP_LOCAL(tcp->tcp_obsegs);
21918 		}
21919 	}
21920 
21921 	if (ire != NULL)
21922 		IRE_REFRELE(ire);
21923 	return (0);
21924 }
21925 
21926 /* Unlink and return any mblk that looks like it contains a MDT info */
21927 static mblk_t *
21928 tcp_mdt_info_mp(mblk_t *mp)
21929 {
21930 	mblk_t	*prev_mp;
21931 
21932 	for (;;) {
21933 		prev_mp = mp;
21934 		/* no more to process? */
21935 		if ((mp = mp->b_cont) == NULL)
21936 			break;
21937 
21938 		switch (DB_TYPE(mp)) {
21939 		case M_CTL:
21940 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21941 				continue;
21942 			ASSERT(prev_mp != NULL);
21943 			prev_mp->b_cont = mp->b_cont;
21944 			mp->b_cont = NULL;
21945 			return (mp);
21946 		default:
21947 			break;
21948 		}
21949 	}
21950 	return (mp);
21951 }
21952 
21953 /* MDT info update routine, called when IP notifies us about MDT */
21954 static void
21955 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21956 {
21957 	boolean_t prev_state;
21958 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21959 
21960 	/*
21961 	 * IP is telling us to abort MDT on this connection?  We know
21962 	 * this because the capability is only turned off when IP
21963 	 * encounters some pathological cases, e.g. link-layer change
21964 	 * where the new driver doesn't support MDT, or in situation
21965 	 * where MDT usage on the link-layer has been switched off.
21966 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21967 	 * if the link-layer doesn't support MDT, and if it does, it
21968 	 * will indicate that the feature is to be turned on.
21969 	 */
21970 	prev_state = tcp->tcp_mdt;
21971 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21972 	if (!tcp->tcp_mdt && !first) {
21973 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21974 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21975 		    (void *)tcp->tcp_connp));
21976 	}
21977 
21978 	/*
21979 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21980 	 * so disable MDT otherwise.  The checks are done here
21981 	 * and in tcp_wput_data().
21982 	 */
21983 	if (tcp->tcp_mdt &&
21984 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21985 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21986 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21987 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21988 		tcp->tcp_mdt = B_FALSE;
21989 
21990 	if (tcp->tcp_mdt) {
21991 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21992 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21993 			    "version (%d), expected version is %d",
21994 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21995 			tcp->tcp_mdt = B_FALSE;
21996 			return;
21997 		}
21998 
21999 		/*
22000 		 * We need the driver to be able to handle at least three
22001 		 * spans per packet in order for tcp MDT to be utilized.
22002 		 * The first is for the header portion, while the rest are
22003 		 * needed to handle a packet that straddles across two
22004 		 * virtually non-contiguous buffers; a typical tcp packet
22005 		 * therefore consists of only two spans.  Note that we take
22006 		 * a zero as "don't care".
22007 		 */
22008 		if (mdt_capab->ill_mdt_span_limit > 0 &&
22009 		    mdt_capab->ill_mdt_span_limit < 3) {
22010 			tcp->tcp_mdt = B_FALSE;
22011 			return;
22012 		}
22013 
22014 		/* a zero means driver wants default value */
22015 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
22016 		    tcps->tcps_mdt_max_pbufs);
22017 		if (tcp->tcp_mdt_max_pld == 0)
22018 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
22019 
22020 		/* ensure 32-bit alignment */
22021 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
22022 		    mdt_capab->ill_mdt_hdr_head), 4);
22023 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
22024 		    mdt_capab->ill_mdt_hdr_tail), 4);
22025 
22026 		if (!first && !prev_state) {
22027 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
22028 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
22029 			    (void *)tcp->tcp_connp));
22030 		}
22031 	}
22032 }
22033 
22034 /* Unlink and return any mblk that looks like it contains a LSO info */
22035 static mblk_t *
22036 tcp_lso_info_mp(mblk_t *mp)
22037 {
22038 	mblk_t	*prev_mp;
22039 
22040 	for (;;) {
22041 		prev_mp = mp;
22042 		/* no more to process? */
22043 		if ((mp = mp->b_cont) == NULL)
22044 			break;
22045 
22046 		switch (DB_TYPE(mp)) {
22047 		case M_CTL:
22048 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
22049 				continue;
22050 			ASSERT(prev_mp != NULL);
22051 			prev_mp->b_cont = mp->b_cont;
22052 			mp->b_cont = NULL;
22053 			return (mp);
22054 		default:
22055 			break;
22056 		}
22057 	}
22058 
22059 	return (mp);
22060 }
22061 
22062 /* LSO info update routine, called when IP notifies us about LSO */
22063 static void
22064 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
22065 {
22066 	tcp_stack_t *tcps = tcp->tcp_tcps;
22067 
22068 	/*
22069 	 * IP is telling us to abort LSO on this connection?  We know
22070 	 * this because the capability is only turned off when IP
22071 	 * encounters some pathological cases, e.g. link-layer change
22072 	 * where the new NIC/driver doesn't support LSO, or in situation
22073 	 * where LSO usage on the link-layer has been switched off.
22074 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
22075 	 * if the link-layer doesn't support LSO, and if it does, it
22076 	 * will indicate that the feature is to be turned on.
22077 	 */
22078 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
22079 	TCP_STAT(tcps, tcp_lso_enabled);
22080 
22081 	/*
22082 	 * We currently only support LSO on simple TCP/IPv4,
22083 	 * so disable LSO otherwise.  The checks are done here
22084 	 * and in tcp_wput_data().
22085 	 */
22086 	if (tcp->tcp_lso &&
22087 	    (tcp->tcp_ipversion == IPV4_VERSION &&
22088 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
22089 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
22090 		tcp->tcp_lso = B_FALSE;
22091 		TCP_STAT(tcps, tcp_lso_disabled);
22092 	} else {
22093 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
22094 		    lso_capab->ill_lso_max);
22095 	}
22096 }
22097 
22098 static void
22099 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
22100 {
22101 	conn_t *connp = tcp->tcp_connp;
22102 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22103 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22104 
22105 	ASSERT(ire != NULL);
22106 
22107 	/*
22108 	 * We may be in the fastpath here, and although we essentially do
22109 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
22110 	 * we try to keep things as brief as possible.  After all, these
22111 	 * are only best-effort checks, and we do more thorough ones prior
22112 	 * to calling tcp_send()/tcp_multisend().
22113 	 */
22114 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
22115 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
22116 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
22117 	    !(ire->ire_flags & RTF_MULTIRT) &&
22118 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
22119 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
22120 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
22121 			/* Cache the result */
22122 			connp->conn_lso_ok = B_TRUE;
22123 
22124 			ASSERT(ill->ill_lso_capab != NULL);
22125 			if (!ill->ill_lso_capab->ill_lso_on) {
22126 				ill->ill_lso_capab->ill_lso_on = 1;
22127 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22128 				    "LSO for interface %s\n", (void *)connp,
22129 				    ill->ill_name));
22130 			}
22131 			tcp_lso_update(tcp, ill->ill_lso_capab);
22132 		} else if (ipst->ips_ip_multidata_outbound &&
22133 		    ILL_MDT_CAPABLE(ill)) {
22134 			/* Cache the result */
22135 			connp->conn_mdt_ok = B_TRUE;
22136 
22137 			ASSERT(ill->ill_mdt_capab != NULL);
22138 			if (!ill->ill_mdt_capab->ill_mdt_on) {
22139 				ill->ill_mdt_capab->ill_mdt_on = 1;
22140 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22141 				    "MDT for interface %s\n", (void *)connp,
22142 				    ill->ill_name));
22143 			}
22144 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
22145 		}
22146 	}
22147 
22148 	/*
22149 	 * The goal is to reduce the number of generated tcp segments by
22150 	 * setting the maxpsz multiplier to 0; this will have an affect on
22151 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
22152 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
22153 	 * of outbound segments and incoming ACKs, thus allowing for better
22154 	 * network and system performance.  In contrast the legacy behavior
22155 	 * may result in sending less than SMSS size, because the last mblk
22156 	 * for some packets may have more data than needed to make up SMSS,
22157 	 * and the legacy code refused to "split" it.
22158 	 *
22159 	 * We apply the new behavior on following situations:
22160 	 *
22161 	 *   1) Loopback connections,
22162 	 *   2) Connections in which the remote peer is not on local subnet,
22163 	 *   3) Local subnet connections over the bge interface (see below).
22164 	 *
22165 	 * Ideally, we would like this behavior to apply for interfaces other
22166 	 * than bge.  However, doing so would negatively impact drivers which
22167 	 * perform dynamic mapping and unmapping of DMA resources, which are
22168 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
22169 	 * packet will be generated by tcp).  The bge driver does not suffer
22170 	 * from this, as it copies the mblks into pre-mapped buffers, and
22171 	 * therefore does not require more I/O resources than before.
22172 	 *
22173 	 * Otherwise, this behavior is present on all network interfaces when
22174 	 * the destination endpoint is non-local, since reducing the number
22175 	 * of packets in general is good for the network.
22176 	 *
22177 	 * TODO We need to remove this hard-coded conditional for bge once
22178 	 *	a better "self-tuning" mechanism, or a way to comprehend
22179 	 *	the driver transmit strategy is devised.  Until the solution
22180 	 *	is found and well understood, we live with this hack.
22181 	 */
22182 	if (!tcp_static_maxpsz &&
22183 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
22184 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
22185 		/* override the default value */
22186 		tcp->tcp_maxpsz = 0;
22187 
22188 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
22189 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
22190 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
22191 	}
22192 
22193 	/* set the stream head parameters accordingly */
22194 	(void) tcp_maxpsz_set(tcp, B_TRUE);
22195 }
22196 
22197 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
22198 static void
22199 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
22200 {
22201 	uchar_t	fval = *mp->b_rptr;
22202 	mblk_t	*tail;
22203 	queue_t	*q = tcp->tcp_wq;
22204 
22205 	/* TODO: How should flush interact with urgent data? */
22206 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
22207 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
22208 		/*
22209 		 * Flush only data that has not yet been put on the wire.  If
22210 		 * we flush data that we have already transmitted, life, as we
22211 		 * know it, may come to an end.
22212 		 */
22213 		tail = tcp->tcp_xmit_tail;
22214 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
22215 		tcp->tcp_xmit_tail_unsent = 0;
22216 		tcp->tcp_unsent = 0;
22217 		if (tail->b_wptr != tail->b_rptr)
22218 			tail = tail->b_cont;
22219 		if (tail) {
22220 			mblk_t **excess = &tcp->tcp_xmit_head;
22221 			for (;;) {
22222 				mblk_t *mp1 = *excess;
22223 				if (mp1 == tail)
22224 					break;
22225 				tcp->tcp_xmit_tail = mp1;
22226 				tcp->tcp_xmit_last = mp1;
22227 				excess = &mp1->b_cont;
22228 			}
22229 			*excess = NULL;
22230 			tcp_close_mpp(&tail);
22231 			if (tcp->tcp_snd_zcopy_aware)
22232 				tcp_zcopy_notify(tcp);
22233 		}
22234 		/*
22235 		 * We have no unsent data, so unsent must be less than
22236 		 * tcp_xmit_lowater, so re-enable flow.
22237 		 */
22238 		mutex_enter(&tcp->tcp_non_sq_lock);
22239 		if (tcp->tcp_flow_stopped) {
22240 			tcp_clrqfull(tcp);
22241 		}
22242 		mutex_exit(&tcp->tcp_non_sq_lock);
22243 	}
22244 	/*
22245 	 * TODO: you can't just flush these, you have to increase rwnd for one
22246 	 * thing.  For another, how should urgent data interact?
22247 	 */
22248 	if (fval & FLUSHR) {
22249 		*mp->b_rptr = fval & ~FLUSHW;
22250 		/* XXX */
22251 		qreply(q, mp);
22252 		return;
22253 	}
22254 	freemsg(mp);
22255 }
22256 
22257 /*
22258  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
22259  * messages.
22260  */
22261 static void
22262 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
22263 {
22264 	mblk_t	*mp1;
22265 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
22266 	STRUCT_HANDLE(strbuf, sb);
22267 	queue_t *q = tcp->tcp_wq;
22268 	int	error;
22269 	uint_t	addrlen;
22270 
22271 	/* Make sure it is one of ours. */
22272 	switch (iocp->ioc_cmd) {
22273 	case TI_GETMYNAME:
22274 	case TI_GETPEERNAME:
22275 		break;
22276 	default:
22277 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
22278 		return;
22279 	}
22280 	switch (mi_copy_state(q, mp, &mp1)) {
22281 	case -1:
22282 		return;
22283 	case MI_COPY_CASE(MI_COPY_IN, 1):
22284 		break;
22285 	case MI_COPY_CASE(MI_COPY_OUT, 1):
22286 		/* Copy out the strbuf. */
22287 		mi_copyout(q, mp);
22288 		return;
22289 	case MI_COPY_CASE(MI_COPY_OUT, 2):
22290 		/* All done. */
22291 		mi_copy_done(q, mp, 0);
22292 		return;
22293 	default:
22294 		mi_copy_done(q, mp, EPROTO);
22295 		return;
22296 	}
22297 	/* Check alignment of the strbuf */
22298 	if (!OK_32PTR(mp1->b_rptr)) {
22299 		mi_copy_done(q, mp, EINVAL);
22300 		return;
22301 	}
22302 
22303 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
22304 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
22305 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
22306 		mi_copy_done(q, mp, EINVAL);
22307 		return;
22308 	}
22309 
22310 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
22311 	if (mp1 == NULL)
22312 		return;
22313 
22314 	switch (iocp->ioc_cmd) {
22315 	case TI_GETMYNAME:
22316 		error = tcp_getmyname(tcp, (void *)mp1->b_rptr, &addrlen);
22317 		break;
22318 	case TI_GETPEERNAME:
22319 		error = i_tcp_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
22320 		break;
22321 	}
22322 
22323 	if (error != 0) {
22324 		mi_copy_done(q, mp, error);
22325 	} else {
22326 		mp1->b_wptr += addrlen;
22327 		STRUCT_FSET(sb, len, addrlen);
22328 
22329 		/* Copy out the address */
22330 		mi_copyout(q, mp);
22331 	}
22332 }
22333 
22334 static void
22335 tcp_disable_direct_sockfs(tcp_t *tcp)
22336 {
22337 #ifdef	_ILP32
22338 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
22339 #else
22340 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
22341 #endif
22342 	/*
22343 	 * Insert this socket into the acceptor hash.
22344 	 * We might need it for T_CONN_RES message
22345 	 */
22346 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
22347 
22348 	if (tcp->tcp_fused) {
22349 		/*
22350 		 * This is a fused loopback tcp; disable
22351 		 * read-side synchronous streams interface
22352 		 * and drain any queued data.  It is okay
22353 		 * to do this for non-synchronous streams
22354 		 * fused tcp as well.
22355 		 */
22356 		tcp_fuse_disable_pair(tcp, B_FALSE);
22357 	}
22358 	tcp->tcp_issocket = B_FALSE;
22359 	tcp->tcp_sodirect = NULL;
22360 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
22361 }
22362 
22363 /*
22364  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
22365  * messages.
22366  */
22367 /* ARGSUSED */
22368 static void
22369 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
22370 {
22371 	conn_t 	*connp = (conn_t *)arg;
22372 	tcp_t	*tcp = connp->conn_tcp;
22373 	queue_t	*q = tcp->tcp_wq;
22374 	struct iocblk	*iocp;
22375 
22376 	ASSERT(DB_TYPE(mp) == M_IOCTL);
22377 	/*
22378 	 * Try and ASSERT the minimum possible references on the
22379 	 * conn early enough. Since we are executing on write side,
22380 	 * the connection is obviously not detached and that means
22381 	 * there is a ref each for TCP and IP. Since we are behind
22382 	 * the squeue, the minimum references needed are 3. If the
22383 	 * conn is in classifier hash list, there should be an
22384 	 * extra ref for that (we check both the possibilities).
22385 	 */
22386 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22387 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22388 
22389 	iocp = (struct iocblk *)mp->b_rptr;
22390 	switch (iocp->ioc_cmd) {
22391 	case TCP_IOC_DEFAULT_Q:
22392 		/* Wants to be the default wq. */
22393 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
22394 			iocp->ioc_error = EPERM;
22395 			iocp->ioc_count = 0;
22396 			mp->b_datap->db_type = M_IOCACK;
22397 			qreply(q, mp);
22398 			return;
22399 		}
22400 		tcp_def_q_set(tcp, mp);
22401 		return;
22402 	case _SIOCSOCKFALLBACK:
22403 		/*
22404 		 * Either sockmod is about to be popped and the socket
22405 		 * would now be treated as a plain stream, or a module
22406 		 * is about to be pushed so we could no longer use read-
22407 		 * side synchronous streams for fused loopback tcp.
22408 		 * Drain any queued data and disable direct sockfs
22409 		 * interface from now on.
22410 		 */
22411 		if (!tcp->tcp_issocket) {
22412 			DB_TYPE(mp) = M_IOCNAK;
22413 			iocp->ioc_error = EINVAL;
22414 		} else {
22415 			tcp_disable_direct_sockfs(tcp);
22416 			DB_TYPE(mp) = M_IOCACK;
22417 			iocp->ioc_error = 0;
22418 		}
22419 		iocp->ioc_count = 0;
22420 		iocp->ioc_rval = 0;
22421 		qreply(q, mp);
22422 		return;
22423 	}
22424 	CALL_IP_WPUT(connp, q, mp);
22425 }
22426 
22427 /*
22428  * This routine is called by tcp_wput() to handle all TPI requests.
22429  */
22430 /* ARGSUSED */
22431 static void
22432 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22433 {
22434 	conn_t 	*connp = (conn_t *)arg;
22435 	tcp_t	*tcp = connp->conn_tcp;
22436 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22437 	uchar_t *rptr;
22438 	t_scalar_t type;
22439 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
22440 
22441 	/*
22442 	 * Try and ASSERT the minimum possible references on the
22443 	 * conn early enough. Since we are executing on write side,
22444 	 * the connection is obviously not detached and that means
22445 	 * there is a ref each for TCP and IP. Since we are behind
22446 	 * the squeue, the minimum references needed are 3. If the
22447 	 * conn is in classifier hash list, there should be an
22448 	 * extra ref for that (we check both the possibilities).
22449 	 */
22450 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22451 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22452 
22453 	rptr = mp->b_rptr;
22454 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22455 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22456 		type = ((union T_primitives *)rptr)->type;
22457 		if (type == T_EXDATA_REQ) {
22458 			tcp_output_urgent(connp, mp->b_cont, arg2);
22459 			freeb(mp);
22460 		} else if (type != T_DATA_REQ) {
22461 			goto non_urgent_data;
22462 		} else {
22463 			/* TODO: options, flags, ... from user */
22464 			/* Set length to zero for reclamation below */
22465 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22466 			freeb(mp);
22467 		}
22468 		return;
22469 	} else {
22470 		if (tcp->tcp_debug) {
22471 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22472 			    "tcp_wput_proto, dropping one...");
22473 		}
22474 		freemsg(mp);
22475 		return;
22476 	}
22477 
22478 non_urgent_data:
22479 
22480 	switch ((int)tprim->type) {
22481 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22482 		/*
22483 		 * save the kssl_ent_t from the next block, and convert this
22484 		 * back to a normal bind_req.
22485 		 */
22486 		if (mp->b_cont != NULL) {
22487 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22488 
22489 			if (tcp->tcp_kssl_ent != NULL) {
22490 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22491 				    KSSL_NO_PROXY);
22492 				tcp->tcp_kssl_ent = NULL;
22493 			}
22494 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22495 			    sizeof (kssl_ent_t));
22496 			kssl_hold_ent(tcp->tcp_kssl_ent);
22497 			freemsg(mp->b_cont);
22498 			mp->b_cont = NULL;
22499 		}
22500 		tprim->type = T_BIND_REQ;
22501 
22502 	/* FALLTHROUGH */
22503 	case O_T_BIND_REQ:	/* bind request */
22504 	case T_BIND_REQ:	/* new semantics bind request */
22505 		tcp_tpi_bind(tcp, mp);
22506 		break;
22507 	case T_UNBIND_REQ:	/* unbind request */
22508 		tcp_tpi_unbind(tcp, mp);
22509 		break;
22510 	case O_T_CONN_RES:	/* old connection response XXX */
22511 	case T_CONN_RES:	/* connection response */
22512 		tcp_tli_accept(tcp, mp);
22513 		break;
22514 	case T_CONN_REQ:	/* connection request */
22515 		tcp_tpi_connect(tcp, mp);
22516 		break;
22517 	case T_DISCON_REQ:	/* disconnect request */
22518 		tcp_disconnect(tcp, mp);
22519 		break;
22520 	case T_CAPABILITY_REQ:
22521 		tcp_capability_req(tcp, mp);	/* capability request */
22522 		break;
22523 	case T_INFO_REQ:	/* information request */
22524 		tcp_info_req(tcp, mp);
22525 		break;
22526 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22527 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr,
22528 		    &tcp_opt_obj, B_TRUE);
22529 		break;
22530 	case T_OPTMGMT_REQ:
22531 		/*
22532 		 * Note:  no support for snmpcom_req() through new
22533 		 * T_OPTMGMT_REQ. See comments in ip.c
22534 		 */
22535 		/* Only IP is allowed to return meaningful value */
22536 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22537 		    B_TRUE);
22538 		break;
22539 
22540 	case T_UNITDATA_REQ:	/* unitdata request */
22541 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22542 		break;
22543 	case T_ORDREL_REQ:	/* orderly release req */
22544 		freemsg(mp);
22545 
22546 		if (tcp->tcp_fused)
22547 			tcp_unfuse(tcp);
22548 
22549 		if (tcp_xmit_end(tcp) != 0) {
22550 			/*
22551 			 * We were crossing FINs and got a reset from
22552 			 * the other side. Just ignore it.
22553 			 */
22554 			if (tcp->tcp_debug) {
22555 				(void) strlog(TCP_MOD_ID, 0, 1,
22556 				    SL_ERROR|SL_TRACE,
22557 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22558 				    "state %s",
22559 				    tcp_display(tcp, NULL,
22560 				    DISP_ADDR_AND_PORT));
22561 			}
22562 		}
22563 		break;
22564 	case T_ADDR_REQ:
22565 		tcp_addr_req(tcp, mp);
22566 		break;
22567 	default:
22568 		if (tcp->tcp_debug) {
22569 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22570 			    "tcp_wput_proto, bogus TPI msg, type %d",
22571 			    tprim->type);
22572 		}
22573 		/*
22574 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22575 		 * to recover.
22576 		 */
22577 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22578 		break;
22579 	}
22580 }
22581 
22582 /*
22583  * The TCP write service routine should never be called...
22584  */
22585 /* ARGSUSED */
22586 static void
22587 tcp_wsrv(queue_t *q)
22588 {
22589 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22590 
22591 	TCP_STAT(tcps, tcp_wsrv_called);
22592 }
22593 
22594 /* Non overlapping byte exchanger */
22595 static void
22596 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22597 {
22598 	uchar_t	uch;
22599 
22600 	while (len-- > 0) {
22601 		uch = a[len];
22602 		a[len] = b[len];
22603 		b[len] = uch;
22604 	}
22605 }
22606 
22607 /*
22608  * Send out a control packet on the tcp connection specified.  This routine
22609  * is typically called where we need a simple ACK or RST generated.
22610  */
22611 static void
22612 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22613 {
22614 	uchar_t		*rptr;
22615 	tcph_t		*tcph;
22616 	ipha_t		*ipha = NULL;
22617 	ip6_t		*ip6h = NULL;
22618 	uint32_t	sum;
22619 	int		tcp_hdr_len;
22620 	int		tcp_ip_hdr_len;
22621 	mblk_t		*mp;
22622 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22623 
22624 	/*
22625 	 * Save sum for use in source route later.
22626 	 */
22627 	ASSERT(tcp != NULL);
22628 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22629 	tcp_hdr_len = tcp->tcp_hdr_len;
22630 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22631 
22632 	/* If a text string is passed in with the request, pass it to strlog. */
22633 	if (str != NULL && tcp->tcp_debug) {
22634 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22635 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22636 		    str, seq, ack, ctl);
22637 	}
22638 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22639 	    BPRI_MED);
22640 	if (mp == NULL) {
22641 		return;
22642 	}
22643 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22644 	mp->b_rptr = rptr;
22645 	mp->b_wptr = &rptr[tcp_hdr_len];
22646 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22647 
22648 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22649 		ipha = (ipha_t *)rptr;
22650 		ipha->ipha_length = htons(tcp_hdr_len);
22651 	} else {
22652 		ip6h = (ip6_t *)rptr;
22653 		ASSERT(tcp != NULL);
22654 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22655 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22656 	}
22657 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22658 	tcph->th_flags[0] = (uint8_t)ctl;
22659 	if (ctl & TH_RST) {
22660 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22661 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22662 		/*
22663 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22664 		 */
22665 		if (tcp->tcp_snd_ts_ok &&
22666 		    tcp->tcp_state > TCPS_SYN_SENT) {
22667 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22668 			*(mp->b_wptr) = TCPOPT_EOL;
22669 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22670 				ipha->ipha_length = htons(tcp_hdr_len -
22671 				    TCPOPT_REAL_TS_LEN);
22672 			} else {
22673 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22674 				    TCPOPT_REAL_TS_LEN);
22675 			}
22676 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22677 			sum -= TCPOPT_REAL_TS_LEN;
22678 		}
22679 	}
22680 	if (ctl & TH_ACK) {
22681 		if (tcp->tcp_snd_ts_ok) {
22682 			U32_TO_BE32(lbolt,
22683 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22684 			U32_TO_BE32(tcp->tcp_ts_recent,
22685 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22686 		}
22687 
22688 		/* Update the latest receive window size in TCP header. */
22689 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22690 		    tcph->th_win);
22691 		tcp->tcp_rack = ack;
22692 		tcp->tcp_rack_cnt = 0;
22693 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22694 	}
22695 	BUMP_LOCAL(tcp->tcp_obsegs);
22696 	U32_TO_BE32(seq, tcph->th_seq);
22697 	U32_TO_BE32(ack, tcph->th_ack);
22698 	/*
22699 	 * Include the adjustment for a source route if any.
22700 	 */
22701 	sum = (sum >> 16) + (sum & 0xFFFF);
22702 	U16_TO_BE16(sum, tcph->th_sum);
22703 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22704 }
22705 
22706 /*
22707  * If this routine returns B_TRUE, TCP can generate a RST in response
22708  * to a segment.  If it returns B_FALSE, TCP should not respond.
22709  */
22710 static boolean_t
22711 tcp_send_rst_chk(tcp_stack_t *tcps)
22712 {
22713 	clock_t	now;
22714 
22715 	/*
22716 	 * TCP needs to protect itself from generating too many RSTs.
22717 	 * This can be a DoS attack by sending us random segments
22718 	 * soliciting RSTs.
22719 	 *
22720 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22721 	 * in each 1 second interval.  In this way, TCP still generate
22722 	 * RSTs in normal cases but when under attack, the impact is
22723 	 * limited.
22724 	 */
22725 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22726 		now = lbolt;
22727 		/* lbolt can wrap around. */
22728 		if ((tcps->tcps_last_rst_intrvl > now) ||
22729 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22730 		    1*SECONDS)) {
22731 			tcps->tcps_last_rst_intrvl = now;
22732 			tcps->tcps_rst_cnt = 1;
22733 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22734 			return (B_FALSE);
22735 		}
22736 	}
22737 	return (B_TRUE);
22738 }
22739 
22740 /*
22741  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22742  */
22743 static void
22744 tcp_ip_ire_mark_advice(tcp_t *tcp)
22745 {
22746 	mblk_t *mp;
22747 	ipic_t *ipic;
22748 
22749 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22750 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22751 		    &ipic);
22752 	} else {
22753 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22754 		    &ipic);
22755 	}
22756 	if (mp == NULL)
22757 		return;
22758 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22759 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22760 }
22761 
22762 /*
22763  * Return an IP advice ioctl mblk and set ipic to be the pointer
22764  * to the advice structure.
22765  */
22766 static mblk_t *
22767 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22768 {
22769 	struct iocblk *ioc;
22770 	mblk_t *mp, *mp1;
22771 
22772 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22773 	if (mp == NULL)
22774 		return (NULL);
22775 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22776 	*ipic = (ipic_t *)mp->b_rptr;
22777 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22778 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22779 
22780 	bcopy(addr, *ipic + 1, addr_len);
22781 
22782 	(*ipic)->ipic_addr_length = addr_len;
22783 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22784 
22785 	mp1 = mkiocb(IP_IOCTL);
22786 	if (mp1 == NULL) {
22787 		freemsg(mp);
22788 		return (NULL);
22789 	}
22790 	mp1->b_cont = mp;
22791 	ioc = (struct iocblk *)mp1->b_rptr;
22792 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22793 
22794 	return (mp1);
22795 }
22796 
22797 /*
22798  * Generate a reset based on an inbound packet, connp is set by caller
22799  * when RST is in response to an unexpected inbound packet for which
22800  * there is active tcp state in the system.
22801  *
22802  * IPSEC NOTE : Try to send the reply with the same protection as it came
22803  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22804  * the packet will go out at the same level of protection as it came in by
22805  * converting the IPSEC_IN to IPSEC_OUT.
22806  */
22807 static void
22808 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22809     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22810     tcp_stack_t *tcps, conn_t *connp)
22811 {
22812 	ipha_t		*ipha = NULL;
22813 	ip6_t		*ip6h = NULL;
22814 	ushort_t	len;
22815 	tcph_t		*tcph;
22816 	int		i;
22817 	mblk_t		*ipsec_mp;
22818 	boolean_t	mctl_present;
22819 	ipic_t		*ipic;
22820 	ipaddr_t	v4addr;
22821 	in6_addr_t	v6addr;
22822 	int		addr_len;
22823 	void		*addr;
22824 	queue_t		*q = tcps->tcps_g_q;
22825 	tcp_t		*tcp;
22826 	cred_t		*cr;
22827 	mblk_t		*nmp;
22828 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22829 
22830 	if (tcps->tcps_g_q == NULL) {
22831 		/*
22832 		 * For non-zero stackids the default queue isn't created
22833 		 * until the first open, thus there can be a need to send
22834 		 * a reset before then. But we can't do that, hence we just
22835 		 * drop the packet. Later during boot, when the default queue
22836 		 * has been setup, a retransmitted packet from the peer
22837 		 * will result in a reset.
22838 		 */
22839 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22840 		    GLOBAL_NETSTACKID);
22841 		freemsg(mp);
22842 		return;
22843 	}
22844 
22845 	if (connp != NULL)
22846 		tcp = connp->conn_tcp;
22847 	else
22848 		tcp = Q_TO_TCP(q);
22849 
22850 	if (!tcp_send_rst_chk(tcps)) {
22851 		tcps->tcps_rst_unsent++;
22852 		freemsg(mp);
22853 		return;
22854 	}
22855 
22856 	if (mp->b_datap->db_type == M_CTL) {
22857 		ipsec_mp = mp;
22858 		mp = mp->b_cont;
22859 		mctl_present = B_TRUE;
22860 	} else {
22861 		ipsec_mp = mp;
22862 		mctl_present = B_FALSE;
22863 	}
22864 
22865 	if (str && q && tcps->tcps_dbg) {
22866 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22867 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22868 		    "flags 0x%x",
22869 		    str, seq, ack, ctl);
22870 	}
22871 	if (mp->b_datap->db_ref != 1) {
22872 		mblk_t *mp1 = copyb(mp);
22873 		freemsg(mp);
22874 		mp = mp1;
22875 		if (!mp) {
22876 			if (mctl_present)
22877 				freeb(ipsec_mp);
22878 			return;
22879 		} else {
22880 			if (mctl_present) {
22881 				ipsec_mp->b_cont = mp;
22882 			} else {
22883 				ipsec_mp = mp;
22884 			}
22885 		}
22886 	} else if (mp->b_cont) {
22887 		freemsg(mp->b_cont);
22888 		mp->b_cont = NULL;
22889 	}
22890 	/*
22891 	 * We skip reversing source route here.
22892 	 * (for now we replace all IP options with EOL)
22893 	 */
22894 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22895 		ipha = (ipha_t *)mp->b_rptr;
22896 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22897 			mp->b_rptr[i] = IPOPT_EOL;
22898 		/*
22899 		 * Make sure that src address isn't flagrantly invalid.
22900 		 * Not all broadcast address checking for the src address
22901 		 * is possible, since we don't know the netmask of the src
22902 		 * addr.  No check for destination address is done, since
22903 		 * IP will not pass up a packet with a broadcast dest
22904 		 * address to TCP.  Similar checks are done below for IPv6.
22905 		 */
22906 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22907 		    CLASSD(ipha->ipha_src)) {
22908 			freemsg(ipsec_mp);
22909 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22910 			return;
22911 		}
22912 	} else {
22913 		ip6h = (ip6_t *)mp->b_rptr;
22914 
22915 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22916 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22917 			freemsg(ipsec_mp);
22918 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22919 			return;
22920 		}
22921 
22922 		/* Remove any extension headers assuming partial overlay */
22923 		if (ip_hdr_len > IPV6_HDR_LEN) {
22924 			uint8_t *to;
22925 
22926 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22927 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22928 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22929 			ip_hdr_len = IPV6_HDR_LEN;
22930 			ip6h = (ip6_t *)mp->b_rptr;
22931 			ip6h->ip6_nxt = IPPROTO_TCP;
22932 		}
22933 	}
22934 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22935 	if (tcph->th_flags[0] & TH_RST) {
22936 		freemsg(ipsec_mp);
22937 		return;
22938 	}
22939 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22940 	len = ip_hdr_len + sizeof (tcph_t);
22941 	mp->b_wptr = &mp->b_rptr[len];
22942 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22943 		ipha->ipha_length = htons(len);
22944 		/* Swap addresses */
22945 		v4addr = ipha->ipha_src;
22946 		ipha->ipha_src = ipha->ipha_dst;
22947 		ipha->ipha_dst = v4addr;
22948 		ipha->ipha_ident = 0;
22949 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22950 		addr_len = IP_ADDR_LEN;
22951 		addr = &v4addr;
22952 	} else {
22953 		/* No ip6i_t in this case */
22954 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22955 		/* Swap addresses */
22956 		v6addr = ip6h->ip6_src;
22957 		ip6h->ip6_src = ip6h->ip6_dst;
22958 		ip6h->ip6_dst = v6addr;
22959 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22960 		addr_len = IPV6_ADDR_LEN;
22961 		addr = &v6addr;
22962 	}
22963 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22964 	U32_TO_BE32(ack, tcph->th_ack);
22965 	U32_TO_BE32(seq, tcph->th_seq);
22966 	U16_TO_BE16(0, tcph->th_win);
22967 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22968 	tcph->th_flags[0] = (uint8_t)ctl;
22969 	if (ctl & TH_RST) {
22970 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22971 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22972 	}
22973 
22974 	/* IP trusts us to set up labels when required. */
22975 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
22976 	    crgetlabel(cr) != NULL) {
22977 		int err;
22978 
22979 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22980 			err = tsol_check_label(cr, &mp,
22981 			    tcp->tcp_connp->conn_mac_exempt,
22982 			    tcps->tcps_netstack->netstack_ip);
22983 		else
22984 			err = tsol_check_label_v6(cr, &mp,
22985 			    tcp->tcp_connp->conn_mac_exempt,
22986 			    tcps->tcps_netstack->netstack_ip);
22987 		if (mctl_present)
22988 			ipsec_mp->b_cont = mp;
22989 		else
22990 			ipsec_mp = mp;
22991 		if (err != 0) {
22992 			freemsg(ipsec_mp);
22993 			return;
22994 		}
22995 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22996 			ipha = (ipha_t *)mp->b_rptr;
22997 		} else {
22998 			ip6h = (ip6_t *)mp->b_rptr;
22999 		}
23000 	}
23001 
23002 	if (mctl_present) {
23003 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23004 
23005 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23006 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
23007 			return;
23008 		}
23009 	}
23010 	if (zoneid == ALL_ZONES)
23011 		zoneid = GLOBAL_ZONEID;
23012 
23013 	/* Add the zoneid so ip_output routes it properly */
23014 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
23015 		freemsg(ipsec_mp);
23016 		return;
23017 	}
23018 	ipsec_mp = nmp;
23019 
23020 	/*
23021 	 * NOTE:  one might consider tracing a TCP packet here, but
23022 	 * this function has no active TCP state and no tcp structure
23023 	 * that has a trace buffer.  If we traced here, we would have
23024 	 * to keep a local trace buffer in tcp_record_trace().
23025 	 *
23026 	 * TSol note: The mblk that contains the incoming packet was
23027 	 * reused by tcp_xmit_listener_reset, so it already contains
23028 	 * the right credentials and we don't need to call mblk_setcred.
23029 	 * Also the conn's cred is not right since it is associated
23030 	 * with tcps_g_q.
23031 	 */
23032 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
23033 
23034 	/*
23035 	 * Tell IP to mark the IRE used for this destination temporary.
23036 	 * This way, we can limit our exposure to DoS attack because IP
23037 	 * creates an IRE for each destination.  If there are too many,
23038 	 * the time to do any routing lookup will be extremely long.  And
23039 	 * the lookup can be in interrupt context.
23040 	 *
23041 	 * Note that in normal circumstances, this marking should not
23042 	 * affect anything.  It would be nice if only 1 message is
23043 	 * needed to inform IP that the IRE created for this RST should
23044 	 * not be added to the cache table.  But there is currently
23045 	 * not such communication mechanism between TCP and IP.  So
23046 	 * the best we can do now is to send the advice ioctl to IP
23047 	 * to mark the IRE temporary.
23048 	 */
23049 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
23050 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
23051 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23052 	}
23053 }
23054 
23055 /*
23056  * Initiate closedown sequence on an active connection.  (May be called as
23057  * writer.)  Return value zero for OK return, non-zero for error return.
23058  */
23059 static int
23060 tcp_xmit_end(tcp_t *tcp)
23061 {
23062 	ipic_t	*ipic;
23063 	mblk_t	*mp;
23064 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23065 
23066 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
23067 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
23068 		/*
23069 		 * Invalid state, only states TCPS_SYN_RCVD,
23070 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
23071 		 */
23072 		return (-1);
23073 	}
23074 
23075 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
23076 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
23077 	/*
23078 	 * If there is nothing more unsent, send the FIN now.
23079 	 * Otherwise, it will go out with the last segment.
23080 	 */
23081 	if (tcp->tcp_unsent == 0) {
23082 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
23083 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
23084 
23085 		if (mp) {
23086 			tcp_send_data(tcp, tcp->tcp_wq, mp);
23087 		} else {
23088 			/*
23089 			 * Couldn't allocate msg.  Pretend we got it out.
23090 			 * Wait for rexmit timeout.
23091 			 */
23092 			tcp->tcp_snxt = tcp->tcp_fss + 1;
23093 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23094 		}
23095 
23096 		/*
23097 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
23098 		 * changed.
23099 		 */
23100 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
23101 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23102 		}
23103 	} else {
23104 		/*
23105 		 * If tcp->tcp_cork is set, then the data will not get sent,
23106 		 * so we have to check that and unset it first.
23107 		 */
23108 		if (tcp->tcp_cork)
23109 			tcp->tcp_cork = B_FALSE;
23110 		tcp_wput_data(tcp, NULL, B_FALSE);
23111 	}
23112 
23113 	/*
23114 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
23115 	 * is 0, don't update the cache.
23116 	 */
23117 	if (tcps->tcps_rtt_updates == 0 ||
23118 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
23119 		return (0);
23120 
23121 	/*
23122 	 * NOTE: should not update if source routes i.e. if tcp_remote if
23123 	 * different from the destination.
23124 	 */
23125 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23126 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
23127 			return (0);
23128 		}
23129 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
23130 		    &ipic);
23131 	} else {
23132 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
23133 		    &tcp->tcp_ip6h->ip6_dst))) {
23134 			return (0);
23135 		}
23136 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
23137 		    &ipic);
23138 	}
23139 
23140 	/* Record route attributes in the IRE for use by future connections. */
23141 	if (mp == NULL)
23142 		return (0);
23143 
23144 	/*
23145 	 * We do not have a good algorithm to update ssthresh at this time.
23146 	 * So don't do any update.
23147 	 */
23148 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
23149 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
23150 
23151 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23152 
23153 	return (0);
23154 }
23155 
23156 /*
23157  * Generate a "no listener here" RST in response to an "unknown" segment.
23158  * connp is set by caller when RST is in response to an unexpected
23159  * inbound packet for which there is active tcp state in the system.
23160  * Note that we are reusing the incoming mp to construct the outgoing RST.
23161  */
23162 void
23163 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
23164     tcp_stack_t *tcps, conn_t *connp)
23165 {
23166 	uchar_t		*rptr;
23167 	uint32_t	seg_len;
23168 	tcph_t		*tcph;
23169 	uint32_t	seg_seq;
23170 	uint32_t	seg_ack;
23171 	uint_t		flags;
23172 	mblk_t		*ipsec_mp;
23173 	ipha_t 		*ipha;
23174 	ip6_t 		*ip6h;
23175 	boolean_t	mctl_present = B_FALSE;
23176 	boolean_t	check = B_TRUE;
23177 	boolean_t	policy_present;
23178 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
23179 
23180 	TCP_STAT(tcps, tcp_no_listener);
23181 
23182 	ipsec_mp = mp;
23183 
23184 	if (mp->b_datap->db_type == M_CTL) {
23185 		ipsec_in_t *ii;
23186 
23187 		mctl_present = B_TRUE;
23188 		mp = mp->b_cont;
23189 
23190 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23191 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23192 		if (ii->ipsec_in_dont_check) {
23193 			check = B_FALSE;
23194 			if (!ii->ipsec_in_secure) {
23195 				freeb(ipsec_mp);
23196 				mctl_present = B_FALSE;
23197 				ipsec_mp = mp;
23198 			}
23199 		}
23200 	}
23201 
23202 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23203 		policy_present = ipss->ipsec_inbound_v4_policy_present;
23204 		ipha = (ipha_t *)mp->b_rptr;
23205 		ip6h = NULL;
23206 	} else {
23207 		policy_present = ipss->ipsec_inbound_v6_policy_present;
23208 		ipha = NULL;
23209 		ip6h = (ip6_t *)mp->b_rptr;
23210 	}
23211 
23212 	if (check && policy_present) {
23213 		/*
23214 		 * The conn_t parameter is NULL because we already know
23215 		 * nobody's home.
23216 		 */
23217 		ipsec_mp = ipsec_check_global_policy(
23218 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
23219 		    tcps->tcps_netstack);
23220 		if (ipsec_mp == NULL)
23221 			return;
23222 	}
23223 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
23224 		DTRACE_PROBE2(
23225 		    tx__ip__log__error__nolistener__tcp,
23226 		    char *, "Could not reply with RST to mp(1)",
23227 		    mblk_t *, mp);
23228 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
23229 		freemsg(ipsec_mp);
23230 		return;
23231 	}
23232 
23233 	rptr = mp->b_rptr;
23234 
23235 	tcph = (tcph_t *)&rptr[ip_hdr_len];
23236 	seg_seq = BE32_TO_U32(tcph->th_seq);
23237 	seg_ack = BE32_TO_U32(tcph->th_ack);
23238 	flags = tcph->th_flags[0];
23239 
23240 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
23241 	if (flags & TH_RST) {
23242 		freemsg(ipsec_mp);
23243 	} else if (flags & TH_ACK) {
23244 		tcp_xmit_early_reset("no tcp, reset",
23245 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
23246 		    connp);
23247 	} else {
23248 		if (flags & TH_SYN) {
23249 			seg_len++;
23250 		} else {
23251 			/*
23252 			 * Here we violate the RFC.  Note that a normal
23253 			 * TCP will never send a segment without the ACK
23254 			 * flag, except for RST or SYN segment.  This
23255 			 * segment is neither.  Just drop it on the
23256 			 * floor.
23257 			 */
23258 			freemsg(ipsec_mp);
23259 			tcps->tcps_rst_unsent++;
23260 			return;
23261 		}
23262 
23263 		tcp_xmit_early_reset("no tcp, reset/ack",
23264 		    ipsec_mp, 0, seg_seq + seg_len,
23265 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
23266 	}
23267 }
23268 
23269 /*
23270  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
23271  * ip and tcp header ready to pass down to IP.  If the mp passed in is
23272  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
23273  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
23274  * otherwise it will dup partial mblks.)
23275  * Otherwise, an appropriate ACK packet will be generated.  This
23276  * routine is not usually called to send new data for the first time.  It
23277  * is mostly called out of the timer for retransmits, and to generate ACKs.
23278  *
23279  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
23280  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
23281  * of the original mblk chain will be returned in *offset and *end_mp.
23282  */
23283 mblk_t *
23284 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
23285     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
23286     boolean_t rexmit)
23287 {
23288 	int	data_length;
23289 	int32_t	off = 0;
23290 	uint_t	flags;
23291 	mblk_t	*mp1;
23292 	mblk_t	*mp2;
23293 	uchar_t	*rptr;
23294 	tcph_t	*tcph;
23295 	int32_t	num_sack_blk = 0;
23296 	int32_t	sack_opt_len = 0;
23297 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23298 
23299 	/* Allocate for our maximum TCP header + link-level */
23300 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
23301 	    tcps->tcps_wroff_xtra, BPRI_MED);
23302 	if (!mp1)
23303 		return (NULL);
23304 	data_length = 0;
23305 
23306 	/*
23307 	 * Note that tcp_mss has been adjusted to take into account the
23308 	 * timestamp option if applicable.  Because SACK options do not
23309 	 * appear in every TCP segments and they are of variable lengths,
23310 	 * they cannot be included in tcp_mss.  Thus we need to calculate
23311 	 * the actual segment length when we need to send a segment which
23312 	 * includes SACK options.
23313 	 */
23314 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23315 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23316 		    tcp->tcp_num_sack_blk);
23317 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23318 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23319 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
23320 			max_to_send -= sack_opt_len;
23321 	}
23322 
23323 	if (offset != NULL) {
23324 		off = *offset;
23325 		/* We use offset as an indicator that end_mp is not NULL. */
23326 		*end_mp = NULL;
23327 	}
23328 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
23329 		/* This could be faster with cooperation from downstream */
23330 		if (mp2 != mp1 && !sendall &&
23331 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
23332 		    max_to_send)
23333 			/*
23334 			 * Don't send the next mblk since the whole mblk
23335 			 * does not fit.
23336 			 */
23337 			break;
23338 		mp2->b_cont = dupb(mp);
23339 		mp2 = mp2->b_cont;
23340 		if (!mp2) {
23341 			freemsg(mp1);
23342 			return (NULL);
23343 		}
23344 		mp2->b_rptr += off;
23345 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
23346 		    (uintptr_t)INT_MAX);
23347 
23348 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
23349 		if (data_length > max_to_send) {
23350 			mp2->b_wptr -= data_length - max_to_send;
23351 			data_length = max_to_send;
23352 			off = mp2->b_wptr - mp->b_rptr;
23353 			break;
23354 		} else {
23355 			off = 0;
23356 		}
23357 	}
23358 	if (offset != NULL) {
23359 		*offset = off;
23360 		*end_mp = mp;
23361 	}
23362 	if (seg_len != NULL) {
23363 		*seg_len = data_length;
23364 	}
23365 
23366 	/* Update the latest receive window size in TCP header. */
23367 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23368 	    tcp->tcp_tcph->th_win);
23369 
23370 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23371 	mp1->b_rptr = rptr;
23372 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
23373 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23374 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23375 	U32_TO_ABE32(seq, tcph->th_seq);
23376 
23377 	/*
23378 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
23379 	 * that this function was called from tcp_wput_data. Thus, when called
23380 	 * to retransmit data the setting of the PUSH bit may appear some
23381 	 * what random in that it might get set when it should not. This
23382 	 * should not pose any performance issues.
23383 	 */
23384 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
23385 	    tcp->tcp_unsent == data_length)) {
23386 		flags = TH_ACK | TH_PUSH;
23387 	} else {
23388 		flags = TH_ACK;
23389 	}
23390 
23391 	if (tcp->tcp_ecn_ok) {
23392 		if (tcp->tcp_ecn_echo_on)
23393 			flags |= TH_ECE;
23394 
23395 		/*
23396 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
23397 		 * There is no TCP flow control for non-data segments, and
23398 		 * only data segment is transmitted reliably.
23399 		 */
23400 		if (data_length > 0 && !rexmit) {
23401 			SET_ECT(tcp, rptr);
23402 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23403 				flags |= TH_CWR;
23404 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23405 			}
23406 		}
23407 	}
23408 
23409 	if (tcp->tcp_valid_bits) {
23410 		uint32_t u1;
23411 
23412 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23413 		    seq == tcp->tcp_iss) {
23414 			uchar_t	*wptr;
23415 
23416 			/*
23417 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23418 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23419 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23420 			 * our SYN is not ack'ed but the app closes this
23421 			 * TCP connection.
23422 			 */
23423 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23424 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23425 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23426 
23427 			/*
23428 			 * Tack on the MSS option.  It is always needed
23429 			 * for both active and passive open.
23430 			 *
23431 			 * MSS option value should be interface MTU - MIN
23432 			 * TCP/IP header according to RFC 793 as it means
23433 			 * the maximum segment size TCP can receive.  But
23434 			 * to get around some broken middle boxes/end hosts
23435 			 * out there, we allow the option value to be the
23436 			 * same as the MSS option size on the peer side.
23437 			 * In this way, the other side will not send
23438 			 * anything larger than they can receive.
23439 			 *
23440 			 * Note that for SYN_SENT state, the ndd param
23441 			 * tcp_use_smss_as_mss_opt has no effect as we
23442 			 * don't know the peer's MSS option value. So
23443 			 * the only case we need to take care of is in
23444 			 * SYN_RCVD state, which is done later.
23445 			 */
23446 			wptr = mp1->b_wptr;
23447 			wptr[0] = TCPOPT_MAXSEG;
23448 			wptr[1] = TCPOPT_MAXSEG_LEN;
23449 			wptr += 2;
23450 			u1 = tcp->tcp_if_mtu -
23451 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23452 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23453 			    TCP_MIN_HEADER_LENGTH;
23454 			U16_TO_BE16(u1, wptr);
23455 			mp1->b_wptr = wptr + 2;
23456 			/* Update the offset to cover the additional word */
23457 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23458 
23459 			/*
23460 			 * Note that the following way of filling in
23461 			 * TCP options are not optimal.  Some NOPs can
23462 			 * be saved.  But there is no need at this time
23463 			 * to optimize it.  When it is needed, we will
23464 			 * do it.
23465 			 */
23466 			switch (tcp->tcp_state) {
23467 			case TCPS_SYN_SENT:
23468 				flags = TH_SYN;
23469 
23470 				if (tcp->tcp_snd_ts_ok) {
23471 					uint32_t llbolt = (uint32_t)lbolt;
23472 
23473 					wptr = mp1->b_wptr;
23474 					wptr[0] = TCPOPT_NOP;
23475 					wptr[1] = TCPOPT_NOP;
23476 					wptr[2] = TCPOPT_TSTAMP;
23477 					wptr[3] = TCPOPT_TSTAMP_LEN;
23478 					wptr += 4;
23479 					U32_TO_BE32(llbolt, wptr);
23480 					wptr += 4;
23481 					ASSERT(tcp->tcp_ts_recent == 0);
23482 					U32_TO_BE32(0L, wptr);
23483 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23484 					tcph->th_offset_and_rsrvd[0] +=
23485 					    (3 << 4);
23486 				}
23487 
23488 				/*
23489 				 * Set up all the bits to tell other side
23490 				 * we are ECN capable.
23491 				 */
23492 				if (tcp->tcp_ecn_ok) {
23493 					flags |= (TH_ECE | TH_CWR);
23494 				}
23495 				break;
23496 			case TCPS_SYN_RCVD:
23497 				flags |= TH_SYN;
23498 
23499 				/*
23500 				 * Reset the MSS option value to be SMSS
23501 				 * We should probably add back the bytes
23502 				 * for timestamp option and IPsec.  We
23503 				 * don't do that as this is a workaround
23504 				 * for broken middle boxes/end hosts, it
23505 				 * is better for us to be more cautious.
23506 				 * They may not take these things into
23507 				 * account in their SMSS calculation.  Thus
23508 				 * the peer's calculated SMSS may be smaller
23509 				 * than what it can be.  This should be OK.
23510 				 */
23511 				if (tcps->tcps_use_smss_as_mss_opt) {
23512 					u1 = tcp->tcp_mss;
23513 					U16_TO_BE16(u1, wptr);
23514 				}
23515 
23516 				/*
23517 				 * If the other side is ECN capable, reply
23518 				 * that we are also ECN capable.
23519 				 */
23520 				if (tcp->tcp_ecn_ok)
23521 					flags |= TH_ECE;
23522 				break;
23523 			default:
23524 				/*
23525 				 * The above ASSERT() makes sure that this
23526 				 * must be FIN-WAIT-1 state.  Our SYN has
23527 				 * not been ack'ed so retransmit it.
23528 				 */
23529 				flags |= TH_SYN;
23530 				break;
23531 			}
23532 
23533 			if (tcp->tcp_snd_ws_ok) {
23534 				wptr = mp1->b_wptr;
23535 				wptr[0] =  TCPOPT_NOP;
23536 				wptr[1] =  TCPOPT_WSCALE;
23537 				wptr[2] =  TCPOPT_WS_LEN;
23538 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23539 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23540 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23541 			}
23542 
23543 			if (tcp->tcp_snd_sack_ok) {
23544 				wptr = mp1->b_wptr;
23545 				wptr[0] = TCPOPT_NOP;
23546 				wptr[1] = TCPOPT_NOP;
23547 				wptr[2] = TCPOPT_SACK_PERMITTED;
23548 				wptr[3] = TCPOPT_SACK_OK_LEN;
23549 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23550 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23551 			}
23552 
23553 			/* allocb() of adequate mblk assures space */
23554 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23555 			    (uintptr_t)INT_MAX);
23556 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23557 			/*
23558 			 * Get IP set to checksum on our behalf
23559 			 * Include the adjustment for a source route if any.
23560 			 */
23561 			u1 += tcp->tcp_sum;
23562 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23563 			U16_TO_BE16(u1, tcph->th_sum);
23564 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23565 		}
23566 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23567 		    (seq + data_length) == tcp->tcp_fss) {
23568 			if (!tcp->tcp_fin_acked) {
23569 				flags |= TH_FIN;
23570 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23571 			}
23572 			if (!tcp->tcp_fin_sent) {
23573 				tcp->tcp_fin_sent = B_TRUE;
23574 				switch (tcp->tcp_state) {
23575 				case TCPS_SYN_RCVD:
23576 				case TCPS_ESTABLISHED:
23577 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23578 					break;
23579 				case TCPS_CLOSE_WAIT:
23580 					tcp->tcp_state = TCPS_LAST_ACK;
23581 					break;
23582 				}
23583 				if (tcp->tcp_suna == tcp->tcp_snxt)
23584 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23585 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23586 			}
23587 		}
23588 		/*
23589 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23590 		 * is smaller than seq, u1 will become a very huge value.
23591 		 * So the comparison will fail.  Also note that tcp_urp
23592 		 * should be positive, see RFC 793 page 17.
23593 		 */
23594 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23595 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23596 		    u1 < (uint32_t)(64 * 1024)) {
23597 			flags |= TH_URG;
23598 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23599 			U32_TO_ABE16(u1, tcph->th_urp);
23600 		}
23601 	}
23602 	tcph->th_flags[0] = (uchar_t)flags;
23603 	tcp->tcp_rack = tcp->tcp_rnxt;
23604 	tcp->tcp_rack_cnt = 0;
23605 
23606 	if (tcp->tcp_snd_ts_ok) {
23607 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23608 			uint32_t llbolt = (uint32_t)lbolt;
23609 
23610 			U32_TO_BE32(llbolt,
23611 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23612 			U32_TO_BE32(tcp->tcp_ts_recent,
23613 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23614 		}
23615 	}
23616 
23617 	if (num_sack_blk > 0) {
23618 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23619 		sack_blk_t *tmp;
23620 		int32_t	i;
23621 
23622 		wptr[0] = TCPOPT_NOP;
23623 		wptr[1] = TCPOPT_NOP;
23624 		wptr[2] = TCPOPT_SACK;
23625 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23626 		    sizeof (sack_blk_t);
23627 		wptr += TCPOPT_REAL_SACK_LEN;
23628 
23629 		tmp = tcp->tcp_sack_list;
23630 		for (i = 0; i < num_sack_blk; i++) {
23631 			U32_TO_BE32(tmp[i].begin, wptr);
23632 			wptr += sizeof (tcp_seq);
23633 			U32_TO_BE32(tmp[i].end, wptr);
23634 			wptr += sizeof (tcp_seq);
23635 		}
23636 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23637 	}
23638 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23639 	data_length += (int)(mp1->b_wptr - rptr);
23640 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23641 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23642 	} else {
23643 		ip6_t *ip6 = (ip6_t *)(rptr +
23644 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23645 		    sizeof (ip6i_t) : 0));
23646 
23647 		ip6->ip6_plen = htons(data_length -
23648 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23649 	}
23650 
23651 	/*
23652 	 * Prime pump for IP
23653 	 * Include the adjustment for a source route if any.
23654 	 */
23655 	data_length -= tcp->tcp_ip_hdr_len;
23656 	data_length += tcp->tcp_sum;
23657 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23658 	U16_TO_ABE16(data_length, tcph->th_sum);
23659 	if (tcp->tcp_ip_forward_progress) {
23660 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23661 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23662 		tcp->tcp_ip_forward_progress = B_FALSE;
23663 	}
23664 	return (mp1);
23665 }
23666 
23667 /* This function handles the push timeout. */
23668 void
23669 tcp_push_timer(void *arg)
23670 {
23671 	conn_t	*connp = (conn_t *)arg;
23672 	tcp_t *tcp = connp->conn_tcp;
23673 	uint_t		flags;
23674 	sodirect_t	*sodp;
23675 
23676 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
23677 
23678 	ASSERT(tcp->tcp_listener == NULL);
23679 
23680 	ASSERT(!IPCL_IS_NONSTR(connp));
23681 
23682 	/*
23683 	 * We need to plug synchronous streams during our drain to prevent
23684 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23685 	 */
23686 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23687 	tcp->tcp_push_tid = 0;
23688 
23689 	SOD_PTR_ENTER(tcp, sodp);
23690 	if (sodp != NULL) {
23691 		flags = tcp_rcv_sod_wakeup(tcp, sodp);
23692 		/* sod_wakeup() does the mutex_exit() */
23693 	} else if (tcp->tcp_rcv_list != NULL) {
23694 		flags = tcp_rcv_drain(tcp);
23695 	}
23696 	if (flags == TH_ACK_NEEDED)
23697 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23698 
23699 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23700 }
23701 
23702 /*
23703  * This function handles delayed ACK timeout.
23704  */
23705 static void
23706 tcp_ack_timer(void *arg)
23707 {
23708 	conn_t	*connp = (conn_t *)arg;
23709 	tcp_t *tcp = connp->conn_tcp;
23710 	mblk_t *mp;
23711 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23712 
23713 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23714 
23715 	tcp->tcp_ack_tid = 0;
23716 
23717 	if (tcp->tcp_fused)
23718 		return;
23719 
23720 	/*
23721 	 * Do not send ACK if there is no outstanding unack'ed data.
23722 	 */
23723 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23724 		return;
23725 	}
23726 
23727 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23728 		/*
23729 		 * Make sure we don't allow deferred ACKs to result in
23730 		 * timer-based ACKing.  If we have held off an ACK
23731 		 * when there was more than an mss here, and the timer
23732 		 * goes off, we have to worry about the possibility
23733 		 * that the sender isn't doing slow-start, or is out
23734 		 * of step with us for some other reason.  We fall
23735 		 * permanently back in the direction of
23736 		 * ACK-every-other-packet as suggested in RFC 1122.
23737 		 */
23738 		if (tcp->tcp_rack_abs_max > 2)
23739 			tcp->tcp_rack_abs_max--;
23740 		tcp->tcp_rack_cur_max = 2;
23741 	}
23742 	mp = tcp_ack_mp(tcp);
23743 
23744 	if (mp != NULL) {
23745 		BUMP_LOCAL(tcp->tcp_obsegs);
23746 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23747 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23748 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23749 	}
23750 }
23751 
23752 
23753 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23754 static mblk_t *
23755 tcp_ack_mp(tcp_t *tcp)
23756 {
23757 	uint32_t	seq_no;
23758 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23759 
23760 	/*
23761 	 * There are a few cases to be considered while setting the sequence no.
23762 	 * Essentially, we can come here while processing an unacceptable pkt
23763 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23764 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23765 	 * If we are here for a zero window probe, stick with suna. In all
23766 	 * other cases, we check if suna + swnd encompasses snxt and set
23767 	 * the sequence number to snxt, if so. If snxt falls outside the
23768 	 * window (the receiver probably shrunk its window), we will go with
23769 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23770 	 * receiver.
23771 	 */
23772 	if (tcp->tcp_zero_win_probe) {
23773 		seq_no = tcp->tcp_suna;
23774 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23775 		ASSERT(tcp->tcp_swnd == 0);
23776 		seq_no = tcp->tcp_snxt;
23777 	} else {
23778 		seq_no = SEQ_GT(tcp->tcp_snxt,
23779 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23780 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23781 	}
23782 
23783 	if (tcp->tcp_valid_bits) {
23784 		/*
23785 		 * For the complex case where we have to send some
23786 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23787 		 */
23788 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23789 		    NULL, B_FALSE));
23790 	} else {
23791 		/* Generate a simple ACK */
23792 		int	data_length;
23793 		uchar_t	*rptr;
23794 		tcph_t	*tcph;
23795 		mblk_t	*mp1;
23796 		int32_t	tcp_hdr_len;
23797 		int32_t	tcp_tcp_hdr_len;
23798 		int32_t	num_sack_blk = 0;
23799 		int32_t sack_opt_len;
23800 
23801 		/*
23802 		 * Allocate space for TCP + IP headers
23803 		 * and link-level header
23804 		 */
23805 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23806 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23807 			    tcp->tcp_num_sack_blk);
23808 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23809 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23810 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23811 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23812 		} else {
23813 			tcp_hdr_len = tcp->tcp_hdr_len;
23814 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23815 		}
23816 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23817 		if (!mp1)
23818 			return (NULL);
23819 
23820 		/* Update the latest receive window size in TCP header. */
23821 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23822 		    tcp->tcp_tcph->th_win);
23823 		/* copy in prototype TCP + IP header */
23824 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23825 		mp1->b_rptr = rptr;
23826 		mp1->b_wptr = rptr + tcp_hdr_len;
23827 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23828 
23829 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23830 
23831 		/* Set the TCP sequence number. */
23832 		U32_TO_ABE32(seq_no, tcph->th_seq);
23833 
23834 		/* Set up the TCP flag field. */
23835 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23836 		if (tcp->tcp_ecn_echo_on)
23837 			tcph->th_flags[0] |= TH_ECE;
23838 
23839 		tcp->tcp_rack = tcp->tcp_rnxt;
23840 		tcp->tcp_rack_cnt = 0;
23841 
23842 		/* fill in timestamp option if in use */
23843 		if (tcp->tcp_snd_ts_ok) {
23844 			uint32_t llbolt = (uint32_t)lbolt;
23845 
23846 			U32_TO_BE32(llbolt,
23847 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23848 			U32_TO_BE32(tcp->tcp_ts_recent,
23849 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23850 		}
23851 
23852 		/* Fill in SACK options */
23853 		if (num_sack_blk > 0) {
23854 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23855 			sack_blk_t *tmp;
23856 			int32_t	i;
23857 
23858 			wptr[0] = TCPOPT_NOP;
23859 			wptr[1] = TCPOPT_NOP;
23860 			wptr[2] = TCPOPT_SACK;
23861 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23862 			    sizeof (sack_blk_t);
23863 			wptr += TCPOPT_REAL_SACK_LEN;
23864 
23865 			tmp = tcp->tcp_sack_list;
23866 			for (i = 0; i < num_sack_blk; i++) {
23867 				U32_TO_BE32(tmp[i].begin, wptr);
23868 				wptr += sizeof (tcp_seq);
23869 				U32_TO_BE32(tmp[i].end, wptr);
23870 				wptr += sizeof (tcp_seq);
23871 			}
23872 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23873 			    << 4);
23874 		}
23875 
23876 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23877 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23878 		} else {
23879 			/* Check for ip6i_t header in sticky hdrs */
23880 			ip6_t *ip6 = (ip6_t *)(rptr +
23881 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23882 			    sizeof (ip6i_t) : 0));
23883 
23884 			ip6->ip6_plen = htons(tcp_hdr_len -
23885 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23886 		}
23887 
23888 		/*
23889 		 * Prime pump for checksum calculation in IP.  Include the
23890 		 * adjustment for a source route if any.
23891 		 */
23892 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23893 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23894 		U16_TO_ABE16(data_length, tcph->th_sum);
23895 
23896 		if (tcp->tcp_ip_forward_progress) {
23897 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23898 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23899 			tcp->tcp_ip_forward_progress = B_FALSE;
23900 		}
23901 		return (mp1);
23902 	}
23903 }
23904 
23905 /*
23906  * Hash list insertion routine for tcp_t structures. Each hash bucket
23907  * contains a list of tcp_t entries, and each entry is bound to a unique
23908  * port. If there are multiple tcp_t's that are bound to the same port, then
23909  * one of them will be linked into the hash bucket list, and the rest will
23910  * hang off of that one entry. For each port, entries bound to a specific IP
23911  * address will be inserted before those those bound to INADDR_ANY.
23912  */
23913 static void
23914 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23915 {
23916 	tcp_t	**tcpp;
23917 	tcp_t	*tcpnext;
23918 	tcp_t	*tcphash;
23919 
23920 	if (tcp->tcp_ptpbhn != NULL) {
23921 		ASSERT(!caller_holds_lock);
23922 		tcp_bind_hash_remove(tcp);
23923 	}
23924 	tcpp = &tbf->tf_tcp;
23925 	if (!caller_holds_lock) {
23926 		mutex_enter(&tbf->tf_lock);
23927 	} else {
23928 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23929 	}
23930 	tcphash = tcpp[0];
23931 	tcpnext = NULL;
23932 	if (tcphash != NULL) {
23933 		/* Look for an entry using the same port */
23934 		while ((tcphash = tcpp[0]) != NULL &&
23935 		    tcp->tcp_lport != tcphash->tcp_lport)
23936 			tcpp = &(tcphash->tcp_bind_hash);
23937 
23938 		/* The port was not found, just add to the end */
23939 		if (tcphash == NULL)
23940 			goto insert;
23941 
23942 		/*
23943 		 * OK, there already exists an entry bound to the
23944 		 * same port.
23945 		 *
23946 		 * If the new tcp bound to the INADDR_ANY address
23947 		 * and the first one in the list is not bound to
23948 		 * INADDR_ANY we skip all entries until we find the
23949 		 * first one bound to INADDR_ANY.
23950 		 * This makes sure that applications binding to a
23951 		 * specific address get preference over those binding to
23952 		 * INADDR_ANY.
23953 		 */
23954 		tcpnext = tcphash;
23955 		tcphash = NULL;
23956 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23957 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23958 			while ((tcpnext = tcpp[0]) != NULL &&
23959 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23960 				tcpp = &(tcpnext->tcp_bind_hash_port);
23961 
23962 			if (tcpnext) {
23963 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23964 				tcphash = tcpnext->tcp_bind_hash;
23965 				if (tcphash != NULL) {
23966 					tcphash->tcp_ptpbhn =
23967 					    &(tcp->tcp_bind_hash);
23968 					tcpnext->tcp_bind_hash = NULL;
23969 				}
23970 			}
23971 		} else {
23972 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23973 			tcphash = tcpnext->tcp_bind_hash;
23974 			if (tcphash != NULL) {
23975 				tcphash->tcp_ptpbhn =
23976 				    &(tcp->tcp_bind_hash);
23977 				tcpnext->tcp_bind_hash = NULL;
23978 			}
23979 		}
23980 	}
23981 insert:
23982 	tcp->tcp_bind_hash_port = tcpnext;
23983 	tcp->tcp_bind_hash = tcphash;
23984 	tcp->tcp_ptpbhn = tcpp;
23985 	tcpp[0] = tcp;
23986 	if (!caller_holds_lock)
23987 		mutex_exit(&tbf->tf_lock);
23988 }
23989 
23990 /*
23991  * Hash list removal routine for tcp_t structures.
23992  */
23993 static void
23994 tcp_bind_hash_remove(tcp_t *tcp)
23995 {
23996 	tcp_t	*tcpnext;
23997 	kmutex_t *lockp;
23998 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23999 
24000 	if (tcp->tcp_ptpbhn == NULL)
24001 		return;
24002 
24003 	/*
24004 	 * Extract the lock pointer in case there are concurrent
24005 	 * hash_remove's for this instance.
24006 	 */
24007 	ASSERT(tcp->tcp_lport != 0);
24008 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
24009 
24010 	ASSERT(lockp != NULL);
24011 	mutex_enter(lockp);
24012 	if (tcp->tcp_ptpbhn) {
24013 		tcpnext = tcp->tcp_bind_hash_port;
24014 		if (tcpnext != NULL) {
24015 			tcp->tcp_bind_hash_port = NULL;
24016 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
24017 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
24018 			if (tcpnext->tcp_bind_hash != NULL) {
24019 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
24020 				    &(tcpnext->tcp_bind_hash);
24021 				tcp->tcp_bind_hash = NULL;
24022 			}
24023 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
24024 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
24025 			tcp->tcp_bind_hash = NULL;
24026 		}
24027 		*tcp->tcp_ptpbhn = tcpnext;
24028 		tcp->tcp_ptpbhn = NULL;
24029 	}
24030 	mutex_exit(lockp);
24031 }
24032 
24033 
24034 /*
24035  * Hash list lookup routine for tcp_t structures.
24036  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
24037  */
24038 static tcp_t *
24039 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
24040 {
24041 	tf_t	*tf;
24042 	tcp_t	*tcp;
24043 
24044 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24045 	mutex_enter(&tf->tf_lock);
24046 	for (tcp = tf->tf_tcp; tcp != NULL;
24047 	    tcp = tcp->tcp_acceptor_hash) {
24048 		if (tcp->tcp_acceptor_id == id) {
24049 			CONN_INC_REF(tcp->tcp_connp);
24050 			mutex_exit(&tf->tf_lock);
24051 			return (tcp);
24052 		}
24053 	}
24054 	mutex_exit(&tf->tf_lock);
24055 	return (NULL);
24056 }
24057 
24058 
24059 /*
24060  * Hash list insertion routine for tcp_t structures.
24061  */
24062 void
24063 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
24064 {
24065 	tf_t	*tf;
24066 	tcp_t	**tcpp;
24067 	tcp_t	*tcpnext;
24068 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24069 
24070 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24071 
24072 	if (tcp->tcp_ptpahn != NULL)
24073 		tcp_acceptor_hash_remove(tcp);
24074 	tcpp = &tf->tf_tcp;
24075 	mutex_enter(&tf->tf_lock);
24076 	tcpnext = tcpp[0];
24077 	if (tcpnext)
24078 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
24079 	tcp->tcp_acceptor_hash = tcpnext;
24080 	tcp->tcp_ptpahn = tcpp;
24081 	tcpp[0] = tcp;
24082 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
24083 	mutex_exit(&tf->tf_lock);
24084 }
24085 
24086 /*
24087  * Hash list removal routine for tcp_t structures.
24088  */
24089 static void
24090 tcp_acceptor_hash_remove(tcp_t *tcp)
24091 {
24092 	tcp_t	*tcpnext;
24093 	kmutex_t *lockp;
24094 
24095 	/*
24096 	 * Extract the lock pointer in case there are concurrent
24097 	 * hash_remove's for this instance.
24098 	 */
24099 	lockp = tcp->tcp_acceptor_lockp;
24100 
24101 	if (tcp->tcp_ptpahn == NULL)
24102 		return;
24103 
24104 	ASSERT(lockp != NULL);
24105 	mutex_enter(lockp);
24106 	if (tcp->tcp_ptpahn) {
24107 		tcpnext = tcp->tcp_acceptor_hash;
24108 		if (tcpnext) {
24109 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
24110 			tcp->tcp_acceptor_hash = NULL;
24111 		}
24112 		*tcp->tcp_ptpahn = tcpnext;
24113 		tcp->tcp_ptpahn = NULL;
24114 	}
24115 	mutex_exit(lockp);
24116 	tcp->tcp_acceptor_lockp = NULL;
24117 }
24118 
24119 /* Data for fast netmask macro used by tcp_hsp_lookup */
24120 
24121 static ipaddr_t netmasks[] = {
24122 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24123 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24124 };
24125 
24126 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24127 
24128 /*
24129  * XXX This routine should go away and instead we should use the metrics
24130  * associated with the routes to determine the default sndspace and rcvspace.
24131  */
24132 static tcp_hsp_t *
24133 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24134 {
24135 	tcp_hsp_t *hsp = NULL;
24136 
24137 	/* Quick check without acquiring the lock. */
24138 	if (tcps->tcps_hsp_hash == NULL)
24139 		return (NULL);
24140 
24141 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24142 
24143 	/* This routine finds the best-matching HSP for address addr. */
24144 
24145 	if (tcps->tcps_hsp_hash) {
24146 		int i;
24147 		ipaddr_t srchaddr;
24148 		tcp_hsp_t *hsp_net;
24149 
24150 		/* We do three passes: host, network, and subnet. */
24151 
24152 		srchaddr = addr;
24153 
24154 		for (i = 1; i <= 3; i++) {
24155 			/* Look for exact match on srchaddr */
24156 
24157 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24158 			while (hsp) {
24159 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24160 				    hsp->tcp_hsp_addr == srchaddr)
24161 					break;
24162 				hsp = hsp->tcp_hsp_next;
24163 			}
24164 			ASSERT(hsp == NULL ||
24165 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24166 
24167 			/*
24168 			 * If this is the first pass:
24169 			 *   If we found a match, great, return it.
24170 			 *   If not, search for the network on the second pass.
24171 			 */
24172 
24173 			if (i == 1)
24174 				if (hsp)
24175 					break;
24176 				else
24177 				{
24178 					srchaddr = addr & netmask(addr);
24179 					continue;
24180 				}
24181 
24182 			/*
24183 			 * If this is the second pass:
24184 			 *   If we found a match, but there's a subnet mask,
24185 			 *    save the match but try again using the subnet
24186 			 *    mask on the third pass.
24187 			 *   Otherwise, return whatever we found.
24188 			 */
24189 
24190 			if (i == 2) {
24191 				if (hsp && hsp->tcp_hsp_subnet) {
24192 					hsp_net = hsp;
24193 					srchaddr = addr & hsp->tcp_hsp_subnet;
24194 					continue;
24195 				} else {
24196 					break;
24197 				}
24198 			}
24199 
24200 			/*
24201 			 * This must be the third pass.  If we didn't find
24202 			 * anything, return the saved network HSP instead.
24203 			 */
24204 
24205 			if (!hsp)
24206 				hsp = hsp_net;
24207 		}
24208 	}
24209 
24210 	rw_exit(&tcps->tcps_hsp_lock);
24211 	return (hsp);
24212 }
24213 
24214 /*
24215  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24216  * match lookup.
24217  */
24218 static tcp_hsp_t *
24219 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
24220 {
24221 	tcp_hsp_t *hsp = NULL;
24222 
24223 	/* Quick check without acquiring the lock. */
24224 	if (tcps->tcps_hsp_hash == NULL)
24225 		return (NULL);
24226 
24227 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24228 
24229 	/* This routine finds the best-matching HSP for address addr. */
24230 
24231 	if (tcps->tcps_hsp_hash) {
24232 		int i;
24233 		in6_addr_t v6srchaddr;
24234 		tcp_hsp_t *hsp_net;
24235 
24236 		/* We do three passes: host, network, and subnet. */
24237 
24238 		v6srchaddr = *v6addr;
24239 
24240 		for (i = 1; i <= 3; i++) {
24241 			/* Look for exact match on srchaddr */
24242 
24243 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
24244 			    V4_PART_OF_V6(v6srchaddr))];
24245 			while (hsp) {
24246 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24247 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24248 				    &v6srchaddr))
24249 					break;
24250 				hsp = hsp->tcp_hsp_next;
24251 			}
24252 
24253 			/*
24254 			 * If this is the first pass:
24255 			 *   If we found a match, great, return it.
24256 			 *   If not, search for the network on the second pass.
24257 			 */
24258 
24259 			if (i == 1)
24260 				if (hsp)
24261 					break;
24262 				else {
24263 					/* Assume a 64 bit mask */
24264 					v6srchaddr.s6_addr32[0] =
24265 					    v6addr->s6_addr32[0];
24266 					v6srchaddr.s6_addr32[1] =
24267 					    v6addr->s6_addr32[1];
24268 					v6srchaddr.s6_addr32[2] = 0;
24269 					v6srchaddr.s6_addr32[3] = 0;
24270 					continue;
24271 				}
24272 
24273 			/*
24274 			 * If this is the second pass:
24275 			 *   If we found a match, but there's a subnet mask,
24276 			 *    save the match but try again using the subnet
24277 			 *    mask on the third pass.
24278 			 *   Otherwise, return whatever we found.
24279 			 */
24280 
24281 			if (i == 2) {
24282 				ASSERT(hsp == NULL ||
24283 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24284 				if (hsp &&
24285 				    !IN6_IS_ADDR_UNSPECIFIED(
24286 				    &hsp->tcp_hsp_subnet_v6)) {
24287 					hsp_net = hsp;
24288 					V6_MASK_COPY(*v6addr,
24289 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24290 					continue;
24291 				} else {
24292 					break;
24293 				}
24294 			}
24295 
24296 			/*
24297 			 * This must be the third pass.  If we didn't find
24298 			 * anything, return the saved network HSP instead.
24299 			 */
24300 
24301 			if (!hsp)
24302 				hsp = hsp_net;
24303 		}
24304 	}
24305 
24306 	rw_exit(&tcps->tcps_hsp_lock);
24307 	return (hsp);
24308 }
24309 
24310 /*
24311  * Type three generator adapted from the random() function in 4.4 BSD:
24312  */
24313 
24314 /*
24315  * Copyright (c) 1983, 1993
24316  *	The Regents of the University of California.  All rights reserved.
24317  *
24318  * Redistribution and use in source and binary forms, with or without
24319  * modification, are permitted provided that the following conditions
24320  * are met:
24321  * 1. Redistributions of source code must retain the above copyright
24322  *    notice, this list of conditions and the following disclaimer.
24323  * 2. Redistributions in binary form must reproduce the above copyright
24324  *    notice, this list of conditions and the following disclaimer in the
24325  *    documentation and/or other materials provided with the distribution.
24326  * 3. All advertising materials mentioning features or use of this software
24327  *    must display the following acknowledgement:
24328  *	This product includes software developed by the University of
24329  *	California, Berkeley and its contributors.
24330  * 4. Neither the name of the University nor the names of its contributors
24331  *    may be used to endorse or promote products derived from this software
24332  *    without specific prior written permission.
24333  *
24334  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24335  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24336  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24337  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24338  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24339  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24340  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24341  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24342  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24343  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24344  * SUCH DAMAGE.
24345  */
24346 
24347 /* Type 3 -- x**31 + x**3 + 1 */
24348 #define	DEG_3		31
24349 #define	SEP_3		3
24350 
24351 
24352 /* Protected by tcp_random_lock */
24353 static int tcp_randtbl[DEG_3 + 1];
24354 
24355 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24356 static int *tcp_random_rptr = &tcp_randtbl[1];
24357 
24358 static int *tcp_random_state = &tcp_randtbl[1];
24359 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24360 
24361 kmutex_t tcp_random_lock;
24362 
24363 void
24364 tcp_random_init(void)
24365 {
24366 	int i;
24367 	hrtime_t hrt;
24368 	time_t wallclock;
24369 	uint64_t result;
24370 
24371 	/*
24372 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24373 	 * a longlong, which may contain resolution down to nanoseconds.
24374 	 * The current time will either be a 32-bit or a 64-bit quantity.
24375 	 * XOR the two together in a 64-bit result variable.
24376 	 * Convert the result to a 32-bit value by multiplying the high-order
24377 	 * 32-bits by the low-order 32-bits.
24378 	 */
24379 
24380 	hrt = gethrtime();
24381 	(void) drv_getparm(TIME, &wallclock);
24382 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24383 	mutex_enter(&tcp_random_lock);
24384 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24385 	    (result & 0xffffffff);
24386 
24387 	for (i = 1; i < DEG_3; i++)
24388 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24389 		    + 12345;
24390 	tcp_random_fptr = &tcp_random_state[SEP_3];
24391 	tcp_random_rptr = &tcp_random_state[0];
24392 	mutex_exit(&tcp_random_lock);
24393 	for (i = 0; i < 10 * DEG_3; i++)
24394 		(void) tcp_random();
24395 }
24396 
24397 /*
24398  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24399  * This range is selected to be approximately centered on TCP_ISS / 2,
24400  * and easy to compute. We get this value by generating a 32-bit random
24401  * number, selecting out the high-order 17 bits, and then adding one so
24402  * that we never return zero.
24403  */
24404 int
24405 tcp_random(void)
24406 {
24407 	int i;
24408 
24409 	mutex_enter(&tcp_random_lock);
24410 	*tcp_random_fptr += *tcp_random_rptr;
24411 
24412 	/*
24413 	 * The high-order bits are more random than the low-order bits,
24414 	 * so we select out the high-order 17 bits and add one so that
24415 	 * we never return zero.
24416 	 */
24417 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24418 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24419 		tcp_random_fptr = tcp_random_state;
24420 		++tcp_random_rptr;
24421 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24422 		tcp_random_rptr = tcp_random_state;
24423 
24424 	mutex_exit(&tcp_random_lock);
24425 	return (i);
24426 }
24427 
24428 static int
24429 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24430     int *t_errorp, int *sys_errorp)
24431 {
24432 	int error;
24433 	int is_absreq_failure;
24434 	t_scalar_t *opt_lenp;
24435 	t_scalar_t opt_offset;
24436 	int prim_type;
24437 	struct T_conn_req *tcreqp;
24438 	struct T_conn_res *tcresp;
24439 	cred_t *cr;
24440 
24441 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
24442 
24443 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24444 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24445 	    prim_type == T_CONN_RES);
24446 
24447 	switch (prim_type) {
24448 	case T_CONN_REQ:
24449 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24450 		opt_offset = tcreqp->OPT_offset;
24451 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24452 		break;
24453 	case O_T_CONN_RES:
24454 	case T_CONN_RES:
24455 		tcresp = (struct T_conn_res *)mp->b_rptr;
24456 		opt_offset = tcresp->OPT_offset;
24457 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24458 		break;
24459 	}
24460 
24461 	*t_errorp = 0;
24462 	*sys_errorp = 0;
24463 	*do_disconnectp = 0;
24464 
24465 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24466 	    opt_offset, cr, &tcp_opt_obj,
24467 	    NULL, &is_absreq_failure);
24468 
24469 	switch (error) {
24470 	case  0:		/* no error */
24471 		ASSERT(is_absreq_failure == 0);
24472 		return (0);
24473 	case ENOPROTOOPT:
24474 		*t_errorp = TBADOPT;
24475 		break;
24476 	case EACCES:
24477 		*t_errorp = TACCES;
24478 		break;
24479 	default:
24480 		*t_errorp = TSYSERR; *sys_errorp = error;
24481 		break;
24482 	}
24483 	if (is_absreq_failure != 0) {
24484 		/*
24485 		 * The connection request should get the local ack
24486 		 * T_OK_ACK and then a T_DISCON_IND.
24487 		 */
24488 		*do_disconnectp = 1;
24489 	}
24490 	return (-1);
24491 }
24492 
24493 /*
24494  * Split this function out so that if the secret changes, I'm okay.
24495  *
24496  * Initialize the tcp_iss_cookie and tcp_iss_key.
24497  */
24498 
24499 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24500 
24501 static void
24502 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
24503 {
24504 	struct {
24505 		int32_t current_time;
24506 		uint32_t randnum;
24507 		uint16_t pad;
24508 		uint8_t ether[6];
24509 		uint8_t passwd[PASSWD_SIZE];
24510 	} tcp_iss_cookie;
24511 	time_t t;
24512 
24513 	/*
24514 	 * Start with the current absolute time.
24515 	 */
24516 	(void) drv_getparm(TIME, &t);
24517 	tcp_iss_cookie.current_time = t;
24518 
24519 	/*
24520 	 * XXX - Need a more random number per RFC 1750, not this crap.
24521 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24522 	 */
24523 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24524 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24525 
24526 	/*
24527 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24528 	 * as a good template.
24529 	 */
24530 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24531 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24532 
24533 	/*
24534 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24535 	 */
24536 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24537 
24538 	/*
24539 	 * See 4010593 if this section becomes a problem again,
24540 	 * but the local ethernet address is useful here.
24541 	 */
24542 	(void) localetheraddr(NULL,
24543 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24544 
24545 	/*
24546 	 * Hash 'em all together.  The MD5Final is called per-connection.
24547 	 */
24548 	mutex_enter(&tcps->tcps_iss_key_lock);
24549 	MD5Init(&tcps->tcps_iss_key);
24550 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
24551 	    sizeof (tcp_iss_cookie));
24552 	mutex_exit(&tcps->tcps_iss_key_lock);
24553 }
24554 
24555 /*
24556  * Set the RFC 1948 pass phrase
24557  */
24558 /* ARGSUSED */
24559 static int
24560 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24561     cred_t *cr)
24562 {
24563 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24564 
24565 	/*
24566 	 * Basically, value contains a new pass phrase.  Pass it along!
24567 	 */
24568 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
24569 	return (0);
24570 }
24571 
24572 /* ARGSUSED */
24573 static int
24574 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24575 {
24576 	bzero(buf, sizeof (tcp_sack_info_t));
24577 	return (0);
24578 }
24579 
24580 /* ARGSUSED */
24581 static int
24582 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24583 {
24584 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24585 	return (0);
24586 }
24587 
24588 /*
24589  * Make sure we wait until the default queue is setup, yet allow
24590  * tcp_g_q_create() to open a TCP stream.
24591  * We need to allow tcp_g_q_create() do do an open
24592  * of tcp, hence we compare curhread.
24593  * All others have to wait until the tcps_g_q has been
24594  * setup.
24595  */
24596 void
24597 tcp_g_q_setup(tcp_stack_t *tcps)
24598 {
24599 	mutex_enter(&tcps->tcps_g_q_lock);
24600 	if (tcps->tcps_g_q != NULL) {
24601 		mutex_exit(&tcps->tcps_g_q_lock);
24602 		return;
24603 	}
24604 	if (tcps->tcps_g_q_creator == NULL) {
24605 		/* This thread will set it up */
24606 		tcps->tcps_g_q_creator = curthread;
24607 		mutex_exit(&tcps->tcps_g_q_lock);
24608 		tcp_g_q_create(tcps);
24609 		mutex_enter(&tcps->tcps_g_q_lock);
24610 		ASSERT(tcps->tcps_g_q_creator == curthread);
24611 		tcps->tcps_g_q_creator = NULL;
24612 		cv_signal(&tcps->tcps_g_q_cv);
24613 		ASSERT(tcps->tcps_g_q != NULL);
24614 		mutex_exit(&tcps->tcps_g_q_lock);
24615 		return;
24616 	}
24617 	/* Everybody but the creator has to wait */
24618 	if (tcps->tcps_g_q_creator != curthread) {
24619 		while (tcps->tcps_g_q == NULL)
24620 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24621 	}
24622 	mutex_exit(&tcps->tcps_g_q_lock);
24623 }
24624 
24625 #define	IP	"ip"
24626 
24627 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24628 
24629 /*
24630  * Create a default tcp queue here instead of in strplumb
24631  */
24632 void
24633 tcp_g_q_create(tcp_stack_t *tcps)
24634 {
24635 	int error;
24636 	ldi_handle_t	lh = NULL;
24637 	ldi_ident_t	li = NULL;
24638 	int		rval;
24639 	cred_t		*cr;
24640 	major_t IP_MAJ;
24641 
24642 #ifdef NS_DEBUG
24643 	(void) printf("tcp_g_q_create()\n");
24644 #endif
24645 
24646 	IP_MAJ = ddi_name_to_major(IP);
24647 
24648 	ASSERT(tcps->tcps_g_q_creator == curthread);
24649 
24650 	error = ldi_ident_from_major(IP_MAJ, &li);
24651 	if (error) {
24652 #ifdef DEBUG
24653 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24654 		    error);
24655 #endif
24656 		return;
24657 	}
24658 
24659 	cr = zone_get_kcred(netstackid_to_zoneid(
24660 	    tcps->tcps_netstack->netstack_stackid));
24661 	ASSERT(cr != NULL);
24662 	/*
24663 	 * We set the tcp default queue to IPv6 because IPv4 falls
24664 	 * back to IPv6 when it can't find a client, but
24665 	 * IPv6 does not fall back to IPv4.
24666 	 */
24667 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24668 	if (error) {
24669 #ifdef DEBUG
24670 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24671 		    error);
24672 #endif
24673 		goto out;
24674 	}
24675 
24676 	/*
24677 	 * This ioctl causes the tcp framework to cache a pointer to
24678 	 * this stream, so we don't want to close the stream after
24679 	 * this operation.
24680 	 * Use the kernel credentials that are for the zone we're in.
24681 	 */
24682 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24683 	    (intptr_t)0, FKIOCTL, cr, &rval);
24684 	if (error) {
24685 #ifdef DEBUG
24686 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24687 		    "error %d\n", error);
24688 #endif
24689 		goto out;
24690 	}
24691 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24692 	lh = NULL;
24693 out:
24694 	/* Close layered handles */
24695 	if (li)
24696 		ldi_ident_release(li);
24697 	/* Keep cred around until _inactive needs it */
24698 	tcps->tcps_g_q_cr = cr;
24699 }
24700 
24701 /*
24702  * We keep tcp_g_q set until all other tcp_t's in the zone
24703  * has gone away, and then when tcp_g_q_inactive() is called
24704  * we clear it.
24705  */
24706 void
24707 tcp_g_q_destroy(tcp_stack_t *tcps)
24708 {
24709 #ifdef NS_DEBUG
24710 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24711 	    tcps->tcps_netstack->netstack_stackid);
24712 #endif
24713 
24714 	if (tcps->tcps_g_q == NULL) {
24715 		return;	/* Nothing to cleanup */
24716 	}
24717 	/*
24718 	 * Drop reference corresponding to the default queue.
24719 	 * This reference was added from tcp_open when the default queue
24720 	 * was created, hence we compensate for this extra drop in
24721 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24722 	 * the default queue was the last one to be open, in which
24723 	 * case, then tcp_g_q_inactive will be
24724 	 * called as a result of the refrele.
24725 	 */
24726 	TCPS_REFRELE(tcps);
24727 }
24728 
24729 /*
24730  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24731  * Run by tcp_q_q_inactive using a taskq.
24732  */
24733 static void
24734 tcp_g_q_close(void *arg)
24735 {
24736 	tcp_stack_t *tcps = arg;
24737 	int error;
24738 	ldi_handle_t	lh = NULL;
24739 	ldi_ident_t	li = NULL;
24740 	cred_t		*cr;
24741 	major_t IP_MAJ;
24742 
24743 	IP_MAJ = ddi_name_to_major(IP);
24744 
24745 #ifdef NS_DEBUG
24746 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24747 	    tcps->tcps_netstack->netstack_stackid,
24748 	    tcps->tcps_netstack->netstack_refcnt);
24749 #endif
24750 	lh = tcps->tcps_g_q_lh;
24751 	if (lh == NULL)
24752 		return;	/* Nothing to cleanup */
24753 
24754 	ASSERT(tcps->tcps_refcnt == 1);
24755 	ASSERT(tcps->tcps_g_q != NULL);
24756 
24757 	error = ldi_ident_from_major(IP_MAJ, &li);
24758 	if (error) {
24759 #ifdef DEBUG
24760 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
24761 		    error);
24762 #endif
24763 		return;
24764 	}
24765 
24766 	cr = tcps->tcps_g_q_cr;
24767 	tcps->tcps_g_q_cr = NULL;
24768 	ASSERT(cr != NULL);
24769 
24770 	/*
24771 	 * Make sure we can break the recursion when tcp_close decrements
24772 	 * the reference count causing g_q_inactive to be called again.
24773 	 */
24774 	tcps->tcps_g_q_lh = NULL;
24775 
24776 	/* close the default queue */
24777 	(void) ldi_close(lh, FREAD|FWRITE, cr);
24778 	/*
24779 	 * At this point in time tcps and the rest of netstack_t might
24780 	 * have been deleted.
24781 	 */
24782 	tcps = NULL;
24783 
24784 	/* Close layered handles */
24785 	ldi_ident_release(li);
24786 	crfree(cr);
24787 }
24788 
24789 /*
24790  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24791  *
24792  * Have to ensure that the ldi routines are not used by an
24793  * interrupt thread by using a taskq.
24794  */
24795 void
24796 tcp_g_q_inactive(tcp_stack_t *tcps)
24797 {
24798 	if (tcps->tcps_g_q_lh == NULL)
24799 		return;	/* Nothing to cleanup */
24800 
24801 	ASSERT(tcps->tcps_refcnt == 0);
24802 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
24803 
24804 	if (servicing_interrupt()) {
24805 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
24806 		    (void *) tcps, TQ_SLEEP);
24807 	} else {
24808 		tcp_g_q_close(tcps);
24809 	}
24810 }
24811 
24812 /*
24813  * Called by IP when IP is loaded into the kernel
24814  */
24815 void
24816 tcp_ddi_g_init(void)
24817 {
24818 	tcp_timercache = kmem_cache_create("tcp_timercache",
24819 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24820 	    NULL, NULL, NULL, NULL, NULL, 0);
24821 
24822 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24823 	    sizeof (tcp_sack_info_t), 0,
24824 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24825 
24826 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24827 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24828 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24829 
24830 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24831 
24832 	/* Initialize the random number generator */
24833 	tcp_random_init();
24834 
24835 	/* A single callback independently of how many netstacks we have */
24836 	ip_squeue_init(tcp_squeue_add);
24837 
24838 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
24839 
24840 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
24841 	    TASKQ_PREPOPULATE);
24842 
24843 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
24844 
24845 	/*
24846 	 * We want to be informed each time a stack is created or
24847 	 * destroyed in the kernel, so we can maintain the
24848 	 * set of tcp_stack_t's.
24849 	 */
24850 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
24851 	    tcp_stack_fini);
24852 }
24853 
24854 
24855 #define	INET_NAME	"ip"
24856 
24857 /*
24858  * Initialize the TCP stack instance.
24859  */
24860 static void *
24861 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
24862 {
24863 	tcp_stack_t	*tcps;
24864 	tcpparam_t	*pa;
24865 	int		i;
24866 	int		error = 0;
24867 	major_t		major;
24868 
24869 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
24870 	tcps->tcps_netstack = ns;
24871 
24872 	/* Initialize locks */
24873 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
24874 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24875 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
24876 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24877 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24878 
24879 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
24880 	tcps->tcps_g_epriv_ports[0] = 2049;
24881 	tcps->tcps_g_epriv_ports[1] = 4045;
24882 	tcps->tcps_min_anonpriv_port = 512;
24883 
24884 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
24885 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
24886 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
24887 	    TCP_FANOUT_SIZE, KM_SLEEP);
24888 
24889 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24890 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
24891 		    MUTEX_DEFAULT, NULL);
24892 	}
24893 
24894 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24895 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
24896 		    MUTEX_DEFAULT, NULL);
24897 	}
24898 
24899 	/* TCP's IPsec code calls the packet dropper. */
24900 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
24901 
24902 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
24903 	tcps->tcps_params = pa;
24904 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24905 
24906 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
24907 	    A_CNT(lcl_tcp_param_arr), tcps);
24908 
24909 	/*
24910 	 * Note: To really walk the device tree you need the devinfo
24911 	 * pointer to your device which is only available after probe/attach.
24912 	 * The following is safe only because it uses ddi_root_node()
24913 	 */
24914 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24915 	    tcp_opt_obj.odb_opt_arr_cnt);
24916 
24917 	/*
24918 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24919 	 * by the boot scripts.
24920 	 *
24921 	 * Use NULL name, as the name is caught by the new lockstats.
24922 	 *
24923 	 * Initialize with some random, non-guessable string, like the global
24924 	 * T_INFO_ACK.
24925 	 */
24926 
24927 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24928 	    sizeof (tcp_g_t_info_ack), tcps);
24929 
24930 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
24931 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
24932 
24933 	major = mod_name_to_major(INET_NAME);
24934 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
24935 	ASSERT(error == 0);
24936 	return (tcps);
24937 }
24938 
24939 /*
24940  * Called when the IP module is about to be unloaded.
24941  */
24942 void
24943 tcp_ddi_g_destroy(void)
24944 {
24945 	tcp_g_kstat_fini(tcp_g_kstat);
24946 	tcp_g_kstat = NULL;
24947 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
24948 
24949 	mutex_destroy(&tcp_random_lock);
24950 
24951 	kmem_cache_destroy(tcp_timercache);
24952 	kmem_cache_destroy(tcp_sack_info_cache);
24953 	kmem_cache_destroy(tcp_iphc_cache);
24954 
24955 	netstack_unregister(NS_TCP);
24956 	taskq_destroy(tcp_taskq);
24957 }
24958 
24959 /*
24960  * Shut down the TCP stack instance.
24961  */
24962 /* ARGSUSED */
24963 static void
24964 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24965 {
24966 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24967 
24968 	tcp_g_q_destroy(tcps);
24969 }
24970 
24971 /*
24972  * Free the TCP stack instance.
24973  */
24974 static void
24975 tcp_stack_fini(netstackid_t stackid, void *arg)
24976 {
24977 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24978 	int i;
24979 
24980 	nd_free(&tcps->tcps_g_nd);
24981 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24982 	tcps->tcps_params = NULL;
24983 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24984 	tcps->tcps_wroff_xtra_param = NULL;
24985 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24986 	tcps->tcps_mdt_head_param = NULL;
24987 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24988 	tcps->tcps_mdt_tail_param = NULL;
24989 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24990 	tcps->tcps_mdt_max_pbufs_param = NULL;
24991 
24992 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24993 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24994 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24995 	}
24996 
24997 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24998 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
24999 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
25000 	}
25001 
25002 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
25003 	tcps->tcps_bind_fanout = NULL;
25004 
25005 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
25006 	tcps->tcps_acceptor_fanout = NULL;
25007 
25008 	mutex_destroy(&tcps->tcps_iss_key_lock);
25009 	rw_destroy(&tcps->tcps_hsp_lock);
25010 	mutex_destroy(&tcps->tcps_g_q_lock);
25011 	cv_destroy(&tcps->tcps_g_q_cv);
25012 	mutex_destroy(&tcps->tcps_epriv_port_lock);
25013 
25014 	ip_drop_unregister(&tcps->tcps_dropper);
25015 
25016 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
25017 	tcps->tcps_kstat = NULL;
25018 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
25019 
25020 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
25021 	tcps->tcps_mibkp = NULL;
25022 
25023 	ldi_ident_release(tcps->tcps_ldi_ident);
25024 	kmem_free(tcps, sizeof (*tcps));
25025 }
25026 
25027 /*
25028  * Generate ISS, taking into account NDD changes may happen halfway through.
25029  * (If the iss is not zero, set it.)
25030  */
25031 
25032 static void
25033 tcp_iss_init(tcp_t *tcp)
25034 {
25035 	MD5_CTX context;
25036 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
25037 	uint32_t answer[4];
25038 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25039 
25040 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
25041 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
25042 	switch (tcps->tcps_strong_iss) {
25043 	case 2:
25044 		mutex_enter(&tcps->tcps_iss_key_lock);
25045 		context = tcps->tcps_iss_key;
25046 		mutex_exit(&tcps->tcps_iss_key_lock);
25047 		arg.ports = tcp->tcp_ports;
25048 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25049 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
25050 			    &arg.src);
25051 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
25052 			    &arg.dst);
25053 		} else {
25054 			arg.src = tcp->tcp_ip6h->ip6_src;
25055 			arg.dst = tcp->tcp_ip6h->ip6_dst;
25056 		}
25057 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
25058 		MD5Final((uchar_t *)answer, &context);
25059 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
25060 		/*
25061 		 * Now that we've hashed into a unique per-connection sequence
25062 		 * space, add a random increment per strong_iss == 1.  So I
25063 		 * guess we'll have to...
25064 		 */
25065 		/* FALLTHRU */
25066 	case 1:
25067 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
25068 		break;
25069 	default:
25070 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25071 		break;
25072 	}
25073 	tcp->tcp_valid_bits = TCP_ISS_VALID;
25074 	tcp->tcp_fss = tcp->tcp_iss - 1;
25075 	tcp->tcp_suna = tcp->tcp_iss;
25076 	tcp->tcp_snxt = tcp->tcp_iss + 1;
25077 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
25078 	tcp->tcp_csuna = tcp->tcp_snxt;
25079 }
25080 
25081 /*
25082  * Exported routine for extracting active tcp connection status.
25083  *
25084  * This is used by the Solaris Cluster Networking software to
25085  * gather a list of connections that need to be forwarded to
25086  * specific nodes in the cluster when configuration changes occur.
25087  *
25088  * The callback is invoked for each tcp_t structure from all netstacks,
25089  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
25090  * from the netstack with the specified stack_id. Returning
25091  * non-zero from the callback routine terminates the search.
25092  */
25093 int
25094 cl_tcp_walk_list(netstackid_t stack_id,
25095     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
25096 {
25097 	netstack_handle_t nh;
25098 	netstack_t *ns;
25099 	int ret = 0;
25100 
25101 	if (stack_id >= 0) {
25102 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
25103 			return (EINVAL);
25104 
25105 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25106 		    ns->netstack_tcp);
25107 		netstack_rele(ns);
25108 		return (ret);
25109 	}
25110 
25111 	netstack_next_init(&nh);
25112 	while ((ns = netstack_next(&nh)) != NULL) {
25113 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25114 		    ns->netstack_tcp);
25115 		netstack_rele(ns);
25116 	}
25117 	netstack_next_fini(&nh);
25118 	return (ret);
25119 }
25120 
25121 static int
25122 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25123     tcp_stack_t *tcps)
25124 {
25125 	tcp_t *tcp;
25126 	cl_tcp_info_t	cl_tcpi;
25127 	connf_t	*connfp;
25128 	conn_t	*connp;
25129 	int	i;
25130 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25131 
25132 	ASSERT(callback != NULL);
25133 
25134 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25135 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25136 		connp = NULL;
25137 
25138 		while ((connp =
25139 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25140 
25141 			tcp = connp->conn_tcp;
25142 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
25143 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
25144 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
25145 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
25146 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
25147 			/*
25148 			 * The macros tcp_laddr and tcp_faddr give the IPv4
25149 			 * addresses. They are copied implicitly below as
25150 			 * mapped addresses.
25151 			 */
25152 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
25153 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25154 				cl_tcpi.cl_tcpi_faddr =
25155 				    tcp->tcp_ipha->ipha_dst;
25156 			} else {
25157 				cl_tcpi.cl_tcpi_faddr_v6 =
25158 				    tcp->tcp_ip6h->ip6_dst;
25159 			}
25160 
25161 			/*
25162 			 * If the callback returns non-zero
25163 			 * we terminate the traversal.
25164 			 */
25165 			if ((*callback)(&cl_tcpi, arg) != 0) {
25166 				CONN_DEC_REF(tcp->tcp_connp);
25167 				return (1);
25168 			}
25169 		}
25170 	}
25171 
25172 	return (0);
25173 }
25174 
25175 /*
25176  * Macros used for accessing the different types of sockaddr
25177  * structures inside a tcp_ioc_abort_conn_t.
25178  */
25179 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
25180 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
25181 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
25182 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
25183 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
25184 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
25185 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
25186 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
25187 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
25188 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
25189 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
25190 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
25191 
25192 /*
25193  * Return the correct error code to mimic the behavior
25194  * of a connection reset.
25195  */
25196 #define	TCP_AC_GET_ERRCODE(state, err) {	\
25197 		switch ((state)) {		\
25198 		case TCPS_SYN_SENT:		\
25199 		case TCPS_SYN_RCVD:		\
25200 			(err) = ECONNREFUSED;	\
25201 			break;			\
25202 		case TCPS_ESTABLISHED:		\
25203 		case TCPS_FIN_WAIT_1:		\
25204 		case TCPS_FIN_WAIT_2:		\
25205 		case TCPS_CLOSE_WAIT:		\
25206 			(err) = ECONNRESET;	\
25207 			break;			\
25208 		case TCPS_CLOSING:		\
25209 		case TCPS_LAST_ACK:		\
25210 		case TCPS_TIME_WAIT:		\
25211 			(err) = 0;		\
25212 			break;			\
25213 		default:			\
25214 			(err) = ENXIO;		\
25215 		}				\
25216 	}
25217 
25218 /*
25219  * Check if a tcp structure matches the info in acp.
25220  */
25221 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
25222 	(((acp)->ac_local.ss_family == AF_INET) ?		\
25223 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
25224 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
25225 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
25226 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
25227 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
25228 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
25229 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
25230 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
25231 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25232 	(acp)->ac_end >= (tcp)->tcp_state) :		\
25233 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
25234 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
25235 	&(tcp)->tcp_ip_src_v6)) &&				\
25236 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
25237 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
25238 	&(tcp)->tcp_remote_v6)) &&				\
25239 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
25240 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
25241 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
25242 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
25243 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25244 	(acp)->ac_end >= (tcp)->tcp_state))
25245 
25246 #define	TCP_AC_MATCH(acp, tcp)					\
25247 	(((acp)->ac_zoneid == ALL_ZONES ||			\
25248 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
25249 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
25250 
25251 /*
25252  * Build a message containing a tcp_ioc_abort_conn_t structure
25253  * which is filled in with information from acp and tp.
25254  */
25255 static mblk_t *
25256 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
25257 {
25258 	mblk_t *mp;
25259 	tcp_ioc_abort_conn_t *tacp;
25260 
25261 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
25262 	if (mp == NULL)
25263 		return (NULL);
25264 
25265 	mp->b_datap->db_type = M_CTL;
25266 
25267 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
25268 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
25269 	    sizeof (uint32_t));
25270 
25271 	tacp->ac_start = acp->ac_start;
25272 	tacp->ac_end = acp->ac_end;
25273 	tacp->ac_zoneid = acp->ac_zoneid;
25274 
25275 	if (acp->ac_local.ss_family == AF_INET) {
25276 		tacp->ac_local.ss_family = AF_INET;
25277 		tacp->ac_remote.ss_family = AF_INET;
25278 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
25279 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
25280 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
25281 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
25282 	} else {
25283 		tacp->ac_local.ss_family = AF_INET6;
25284 		tacp->ac_remote.ss_family = AF_INET6;
25285 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
25286 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
25287 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
25288 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
25289 	}
25290 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
25291 	return (mp);
25292 }
25293 
25294 /*
25295  * Print a tcp_ioc_abort_conn_t structure.
25296  */
25297 static void
25298 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
25299 {
25300 	char lbuf[128];
25301 	char rbuf[128];
25302 	sa_family_t af;
25303 	in_port_t lport, rport;
25304 	ushort_t logflags;
25305 
25306 	af = acp->ac_local.ss_family;
25307 
25308 	if (af == AF_INET) {
25309 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
25310 		    lbuf, 128);
25311 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
25312 		    rbuf, 128);
25313 		lport = ntohs(TCP_AC_V4LPORT(acp));
25314 		rport = ntohs(TCP_AC_V4RPORT(acp));
25315 	} else {
25316 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
25317 		    lbuf, 128);
25318 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
25319 		    rbuf, 128);
25320 		lport = ntohs(TCP_AC_V6LPORT(acp));
25321 		rport = ntohs(TCP_AC_V6RPORT(acp));
25322 	}
25323 
25324 	logflags = SL_TRACE | SL_NOTE;
25325 	/*
25326 	 * Don't print this message to the console if the operation was done
25327 	 * to a non-global zone.
25328 	 */
25329 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25330 		logflags |= SL_CONSOLE;
25331 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
25332 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
25333 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
25334 	    acp->ac_start, acp->ac_end);
25335 }
25336 
25337 /*
25338  * Called inside tcp_rput when a message built using
25339  * tcp_ioctl_abort_build_msg is put into a queue.
25340  * Note that when we get here there is no wildcard in acp any more.
25341  */
25342 static void
25343 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
25344 {
25345 	tcp_ioc_abort_conn_t *acp;
25346 
25347 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
25348 	if (tcp->tcp_state <= acp->ac_end) {
25349 		/*
25350 		 * If we get here, we are already on the correct
25351 		 * squeue. This ioctl follows the following path
25352 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
25353 		 * ->tcp_ioctl_abort->squeue_enter (if on a
25354 		 * different squeue)
25355 		 */
25356 		int errcode;
25357 
25358 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
25359 		(void) tcp_clean_death(tcp, errcode, 26);
25360 	}
25361 	freemsg(mp);
25362 }
25363 
25364 /*
25365  * Abort all matching connections on a hash chain.
25366  */
25367 static int
25368 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
25369     boolean_t exact, tcp_stack_t *tcps)
25370 {
25371 	int nmatch, err = 0;
25372 	tcp_t *tcp;
25373 	MBLKP mp, last, listhead = NULL;
25374 	conn_t	*tconnp;
25375 	connf_t	*connfp;
25376 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25377 
25378 	connfp = &ipst->ips_ipcl_conn_fanout[index];
25379 
25380 startover:
25381 	nmatch = 0;
25382 
25383 	mutex_enter(&connfp->connf_lock);
25384 	for (tconnp = connfp->connf_head; tconnp != NULL;
25385 	    tconnp = tconnp->conn_next) {
25386 		tcp = tconnp->conn_tcp;
25387 		if (TCP_AC_MATCH(acp, tcp)) {
25388 			CONN_INC_REF(tcp->tcp_connp);
25389 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
25390 			if (mp == NULL) {
25391 				err = ENOMEM;
25392 				CONN_DEC_REF(tcp->tcp_connp);
25393 				break;
25394 			}
25395 			mp->b_prev = (mblk_t *)tcp;
25396 
25397 			if (listhead == NULL) {
25398 				listhead = mp;
25399 				last = mp;
25400 			} else {
25401 				last->b_next = mp;
25402 				last = mp;
25403 			}
25404 			nmatch++;
25405 			if (exact)
25406 				break;
25407 		}
25408 
25409 		/* Avoid holding lock for too long. */
25410 		if (nmatch >= 500)
25411 			break;
25412 	}
25413 	mutex_exit(&connfp->connf_lock);
25414 
25415 	/* Pass mp into the correct tcp */
25416 	while ((mp = listhead) != NULL) {
25417 		listhead = listhead->b_next;
25418 		tcp = (tcp_t *)mp->b_prev;
25419 		mp->b_next = mp->b_prev = NULL;
25420 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
25421 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
25422 	}
25423 
25424 	*count += nmatch;
25425 	if (nmatch >= 500 && err == 0)
25426 		goto startover;
25427 	return (err);
25428 }
25429 
25430 /*
25431  * Abort all connections that matches the attributes specified in acp.
25432  */
25433 static int
25434 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
25435 {
25436 	sa_family_t af;
25437 	uint32_t  ports;
25438 	uint16_t *pports;
25439 	int err = 0, count = 0;
25440 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25441 	int index = -1;
25442 	ushort_t logflags;
25443 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25444 
25445 	af = acp->ac_local.ss_family;
25446 
25447 	if (af == AF_INET) {
25448 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25449 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25450 			pports = (uint16_t *)&ports;
25451 			pports[1] = TCP_AC_V4LPORT(acp);
25452 			pports[0] = TCP_AC_V4RPORT(acp);
25453 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25454 		}
25455 	} else {
25456 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25457 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25458 			pports = (uint16_t *)&ports;
25459 			pports[1] = TCP_AC_V6LPORT(acp);
25460 			pports[0] = TCP_AC_V6RPORT(acp);
25461 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25462 		}
25463 	}
25464 
25465 	/*
25466 	 * For cases where remote addr, local port, and remote port are non-
25467 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25468 	 */
25469 	if (index != -1) {
25470 		err = tcp_ioctl_abort_bucket(acp, index,
25471 		    &count, exact, tcps);
25472 	} else {
25473 		/*
25474 		 * loop through all entries for wildcard case
25475 		 */
25476 		for (index = 0;
25477 		    index < ipst->ips_ipcl_conn_fanout_size;
25478 		    index++) {
25479 			err = tcp_ioctl_abort_bucket(acp, index,
25480 			    &count, exact, tcps);
25481 			if (err != 0)
25482 				break;
25483 		}
25484 	}
25485 
25486 	logflags = SL_TRACE | SL_NOTE;
25487 	/*
25488 	 * Don't print this message to the console if the operation was done
25489 	 * to a non-global zone.
25490 	 */
25491 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25492 		logflags |= SL_CONSOLE;
25493 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25494 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25495 	if (err == 0 && count == 0)
25496 		err = ENOENT;
25497 	return (err);
25498 }
25499 
25500 /*
25501  * Process the TCP_IOC_ABORT_CONN ioctl request.
25502  */
25503 static void
25504 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25505 {
25506 	int	err;
25507 	IOCP    iocp;
25508 	MBLKP   mp1;
25509 	sa_family_t laf, raf;
25510 	tcp_ioc_abort_conn_t *acp;
25511 	zone_t		*zptr;
25512 	conn_t		*connp = Q_TO_CONN(q);
25513 	zoneid_t	zoneid = connp->conn_zoneid;
25514 	tcp_t		*tcp = connp->conn_tcp;
25515 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25516 
25517 	iocp = (IOCP)mp->b_rptr;
25518 
25519 	if ((mp1 = mp->b_cont) == NULL ||
25520 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25521 		err = EINVAL;
25522 		goto out;
25523 	}
25524 
25525 	/* check permissions */
25526 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
25527 		err = EPERM;
25528 		goto out;
25529 	}
25530 
25531 	if (mp1->b_cont != NULL) {
25532 		freemsg(mp1->b_cont);
25533 		mp1->b_cont = NULL;
25534 	}
25535 
25536 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25537 	laf = acp->ac_local.ss_family;
25538 	raf = acp->ac_remote.ss_family;
25539 
25540 	/* check that a zone with the supplied zoneid exists */
25541 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25542 		zptr = zone_find_by_id(zoneid);
25543 		if (zptr != NULL) {
25544 			zone_rele(zptr);
25545 		} else {
25546 			err = EINVAL;
25547 			goto out;
25548 		}
25549 	}
25550 
25551 	/*
25552 	 * For exclusive stacks we set the zoneid to zero
25553 	 * to make TCP operate as if in the global zone.
25554 	 */
25555 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
25556 		acp->ac_zoneid = GLOBAL_ZONEID;
25557 
25558 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25559 	    acp->ac_start > acp->ac_end || laf != raf ||
25560 	    (laf != AF_INET && laf != AF_INET6)) {
25561 		err = EINVAL;
25562 		goto out;
25563 	}
25564 
25565 	tcp_ioctl_abort_dump(acp);
25566 	err = tcp_ioctl_abort(acp, tcps);
25567 
25568 out:
25569 	if (mp1 != NULL) {
25570 		freemsg(mp1);
25571 		mp->b_cont = NULL;
25572 	}
25573 
25574 	if (err != 0)
25575 		miocnak(q, mp, 0, err);
25576 	else
25577 		miocack(q, mp, 0, 0);
25578 }
25579 
25580 /*
25581  * tcp_time_wait_processing() handles processing of incoming packets when
25582  * the tcp is in the TIME_WAIT state.
25583  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25584  * on the time wait list.
25585  */
25586 void
25587 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25588     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25589 {
25590 	int32_t		bytes_acked;
25591 	int32_t		gap;
25592 	int32_t		rgap;
25593 	tcp_opt_t	tcpopt;
25594 	uint_t		flags;
25595 	uint32_t	new_swnd = 0;
25596 	conn_t		*connp;
25597 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25598 
25599 	BUMP_LOCAL(tcp->tcp_ibsegs);
25600 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
25601 
25602 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25603 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25604 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25605 	if (tcp->tcp_snd_ts_ok) {
25606 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25607 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25608 			    tcp->tcp_rnxt, TH_ACK);
25609 			goto done;
25610 		}
25611 	}
25612 	gap = seg_seq - tcp->tcp_rnxt;
25613 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25614 	if (gap < 0) {
25615 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25616 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25617 		    (seg_len > -gap ? -gap : seg_len));
25618 		seg_len += gap;
25619 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25620 			if (flags & TH_RST) {
25621 				goto done;
25622 			}
25623 			if ((flags & TH_FIN) && seg_len == -1) {
25624 				/*
25625 				 * When TCP receives a duplicate FIN in
25626 				 * TIME_WAIT state, restart the 2 MSL timer.
25627 				 * See page 73 in RFC 793. Make sure this TCP
25628 				 * is already on the TIME_WAIT list. If not,
25629 				 * just restart the timer.
25630 				 */
25631 				if (TCP_IS_DETACHED(tcp)) {
25632 					if (tcp_time_wait_remove(tcp, NULL) ==
25633 					    B_TRUE) {
25634 						tcp_time_wait_append(tcp);
25635 						TCP_DBGSTAT(tcps,
25636 						    tcp_rput_time_wait);
25637 					}
25638 				} else {
25639 					ASSERT(tcp != NULL);
25640 					TCP_TIMER_RESTART(tcp,
25641 					    tcps->tcps_time_wait_interval);
25642 				}
25643 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25644 				    tcp->tcp_rnxt, TH_ACK);
25645 				goto done;
25646 			}
25647 			flags |=  TH_ACK_NEEDED;
25648 			seg_len = 0;
25649 			goto process_ack;
25650 		}
25651 
25652 		/* Fix seg_seq, and chew the gap off the front. */
25653 		seg_seq = tcp->tcp_rnxt;
25654 	}
25655 
25656 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25657 		/*
25658 		 * Make sure that when we accept the connection, pick
25659 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25660 		 * old connection.
25661 		 *
25662 		 * The next ISS generated is equal to tcp_iss_incr_extra
25663 		 * + ISS_INCR/2 + other components depending on the
25664 		 * value of tcp_strong_iss.  We pre-calculate the new
25665 		 * ISS here and compare with tcp_snxt to determine if
25666 		 * we need to make adjustment to tcp_iss_incr_extra.
25667 		 *
25668 		 * The above calculation is ugly and is a
25669 		 * waste of CPU cycles...
25670 		 */
25671 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25672 		int32_t adj;
25673 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25674 
25675 		switch (tcps->tcps_strong_iss) {
25676 		case 2: {
25677 			/* Add time and MD5 components. */
25678 			uint32_t answer[4];
25679 			struct {
25680 				uint32_t ports;
25681 				in6_addr_t src;
25682 				in6_addr_t dst;
25683 			} arg;
25684 			MD5_CTX context;
25685 
25686 			mutex_enter(&tcps->tcps_iss_key_lock);
25687 			context = tcps->tcps_iss_key;
25688 			mutex_exit(&tcps->tcps_iss_key_lock);
25689 			arg.ports = tcp->tcp_ports;
25690 			/* We use MAPPED addresses in tcp_iss_init */
25691 			arg.src = tcp->tcp_ip_src_v6;
25692 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25693 				IN6_IPADDR_TO_V4MAPPED(
25694 				    tcp->tcp_ipha->ipha_dst,
25695 				    &arg.dst);
25696 			} else {
25697 				arg.dst =
25698 				    tcp->tcp_ip6h->ip6_dst;
25699 			}
25700 			MD5Update(&context, (uchar_t *)&arg,
25701 			    sizeof (arg));
25702 			MD5Final((uchar_t *)answer, &context);
25703 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25704 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25705 			break;
25706 		}
25707 		case 1:
25708 			/* Add time component and min random (i.e. 1). */
25709 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25710 			break;
25711 		default:
25712 			/* Add only time component. */
25713 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25714 			break;
25715 		}
25716 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25717 			/*
25718 			 * New ISS not guaranteed to be ISS_INCR/2
25719 			 * ahead of the current tcp_snxt, so add the
25720 			 * difference to tcp_iss_incr_extra.
25721 			 */
25722 			tcps->tcps_iss_incr_extra += adj;
25723 		}
25724 		/*
25725 		 * If tcp_clean_death() can not perform the task now,
25726 		 * drop the SYN packet and let the other side re-xmit.
25727 		 * Otherwise pass the SYN packet back in, since the
25728 		 * old tcp state has been cleaned up or freed.
25729 		 */
25730 		if (tcp_clean_death(tcp, 0, 27) == -1)
25731 			goto done;
25732 		/*
25733 		 * We will come back to tcp_rput_data
25734 		 * on the global queue. Packets destined
25735 		 * for the global queue will be checked
25736 		 * with global policy. But the policy for
25737 		 * this packet has already been checked as
25738 		 * this was destined for the detached
25739 		 * connection. We need to bypass policy
25740 		 * check this time by attaching a dummy
25741 		 * ipsec_in with ipsec_in_dont_check set.
25742 		 */
25743 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25744 		if (connp != NULL) {
25745 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25746 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25747 			return;
25748 		}
25749 		goto done;
25750 	}
25751 
25752 	/*
25753 	 * rgap is the amount of stuff received out of window.  A negative
25754 	 * value is the amount out of window.
25755 	 */
25756 	if (rgap < 0) {
25757 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25758 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
25759 		/* Fix seg_len and make sure there is something left. */
25760 		seg_len += rgap;
25761 		if (seg_len <= 0) {
25762 			if (flags & TH_RST) {
25763 				goto done;
25764 			}
25765 			flags |=  TH_ACK_NEEDED;
25766 			seg_len = 0;
25767 			goto process_ack;
25768 		}
25769 	}
25770 	/*
25771 	 * Check whether we can update tcp_ts_recent.  This test is
25772 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
25773 	 * Extensions for High Performance: An Update", Internet Draft.
25774 	 */
25775 	if (tcp->tcp_snd_ts_ok &&
25776 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
25777 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
25778 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
25779 		tcp->tcp_last_rcv_lbolt = lbolt64;
25780 	}
25781 
25782 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
25783 		/* Always ack out of order packets */
25784 		flags |= TH_ACK_NEEDED;
25785 		seg_len = 0;
25786 	} else if (seg_len > 0) {
25787 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
25788 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
25789 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
25790 	}
25791 	if (flags & TH_RST) {
25792 		(void) tcp_clean_death(tcp, 0, 28);
25793 		goto done;
25794 	}
25795 	if (flags & TH_SYN) {
25796 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
25797 		    TH_RST|TH_ACK);
25798 		/*
25799 		 * Do not delete the TCP structure if it is in
25800 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
25801 		 */
25802 		goto done;
25803 	}
25804 process_ack:
25805 	if (flags & TH_ACK) {
25806 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
25807 		if (bytes_acked <= 0) {
25808 			if (bytes_acked == 0 && seg_len == 0 &&
25809 			    new_swnd == tcp->tcp_swnd)
25810 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
25811 		} else {
25812 			/* Acks something not sent */
25813 			flags |= TH_ACK_NEEDED;
25814 		}
25815 	}
25816 	if (flags & TH_ACK_NEEDED) {
25817 		/*
25818 		 * Time to send an ack for some reason.
25819 		 */
25820 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25821 		    tcp->tcp_rnxt, TH_ACK);
25822 	}
25823 done:
25824 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25825 		DB_CKSUMSTART(mp) = 0;
25826 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
25827 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
25828 	}
25829 	freemsg(mp);
25830 }
25831 
25832 /*
25833  * TCP Timers Implementation.
25834  */
25835 timeout_id_t
25836 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25837 {
25838 	mblk_t *mp;
25839 	tcp_timer_t *tcpt;
25840 	tcp_t *tcp = connp->conn_tcp;
25841 
25842 	ASSERT(connp->conn_sqp != NULL);
25843 
25844 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
25845 
25846 	if (tcp->tcp_timercache == NULL) {
25847 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25848 	} else {
25849 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
25850 		mp = tcp->tcp_timercache;
25851 		tcp->tcp_timercache = mp->b_next;
25852 		mp->b_next = NULL;
25853 		ASSERT(mp->b_wptr == NULL);
25854 	}
25855 
25856 	CONN_INC_REF(connp);
25857 	tcpt = (tcp_timer_t *)mp->b_rptr;
25858 	tcpt->connp = connp;
25859 	tcpt->tcpt_proc = f;
25860 	/*
25861 	 * TCP timers are normal timeouts. Plus, they do not require more than
25862 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
25863 	 * rounding up the expiration to the next resolution boundary, we can
25864 	 * batch timers in the callout subsystem to make TCP timers more
25865 	 * efficient. The roundup also protects short timers from expiring too
25866 	 * early before they have a chance to be cancelled.
25867 	 */
25868 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
25869 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
25870 
25871 	return ((timeout_id_t)mp);
25872 }
25873 
25874 static void
25875 tcp_timer_callback(void *arg)
25876 {
25877 	mblk_t *mp = (mblk_t *)arg;
25878 	tcp_timer_t *tcpt;
25879 	conn_t	*connp;
25880 
25881 	tcpt = (tcp_timer_t *)mp->b_rptr;
25882 	connp = tcpt->connp;
25883 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
25884 	    SQ_FILL, SQTAG_TCP_TIMER);
25885 }
25886 
25887 static void
25888 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
25889 {
25890 	tcp_timer_t *tcpt;
25891 	conn_t *connp = (conn_t *)arg;
25892 	tcp_t *tcp = connp->conn_tcp;
25893 
25894 	tcpt = (tcp_timer_t *)mp->b_rptr;
25895 	ASSERT(connp == tcpt->connp);
25896 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
25897 
25898 	/*
25899 	 * If the TCP has reached the closed state, don't proceed any
25900 	 * further. This TCP logically does not exist on the system.
25901 	 * tcpt_proc could for example access queues, that have already
25902 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
25903 	 */
25904 	if (tcp->tcp_state != TCPS_CLOSED) {
25905 		(*tcpt->tcpt_proc)(connp);
25906 	} else {
25907 		tcp->tcp_timer_tid = 0;
25908 	}
25909 	tcp_timer_free(connp->conn_tcp, mp);
25910 }
25911 
25912 /*
25913  * There is potential race with untimeout and the handler firing at the same
25914  * time. The mblock may be freed by the handler while we are trying to use
25915  * it. But since both should execute on the same squeue, this race should not
25916  * occur.
25917  */
25918 clock_t
25919 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
25920 {
25921 	mblk_t	*mp = (mblk_t *)id;
25922 	tcp_timer_t *tcpt;
25923 	clock_t delta;
25924 
25925 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
25926 
25927 	if (mp == NULL)
25928 		return (-1);
25929 
25930 	tcpt = (tcp_timer_t *)mp->b_rptr;
25931 	ASSERT(tcpt->connp == connp);
25932 
25933 	delta = untimeout_default(tcpt->tcpt_tid, 0);
25934 
25935 	if (delta >= 0) {
25936 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
25937 		tcp_timer_free(connp->conn_tcp, mp);
25938 		CONN_DEC_REF(connp);
25939 	}
25940 
25941 	return (delta);
25942 }
25943 
25944 /*
25945  * Allocate space for the timer event. The allocation looks like mblk, but it is
25946  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25947  *
25948  * Dealing with failures: If we can't allocate from the timer cache we try
25949  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25950  * points to b_rptr.
25951  * If we can't allocate anything using allocb_tryhard(), we perform a last
25952  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25953  * save the actual allocation size in b_datap.
25954  */
25955 mblk_t *
25956 tcp_timermp_alloc(int kmflags)
25957 {
25958 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25959 	    kmflags & ~KM_PANIC);
25960 
25961 	if (mp != NULL) {
25962 		mp->b_next = mp->b_prev = NULL;
25963 		mp->b_rptr = (uchar_t *)(&mp[1]);
25964 		mp->b_wptr = NULL;
25965 		mp->b_datap = NULL;
25966 		mp->b_queue = NULL;
25967 		mp->b_cont = NULL;
25968 	} else if (kmflags & KM_PANIC) {
25969 		/*
25970 		 * Failed to allocate memory for the timer. Try allocating from
25971 		 * dblock caches.
25972 		 */
25973 		/* ipclassifier calls this from a constructor - hence no tcps */
25974 		TCP_G_STAT(tcp_timermp_allocfail);
25975 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25976 		if (mp == NULL) {
25977 			size_t size = 0;
25978 			/*
25979 			 * Memory is really low. Try tryhard allocation.
25980 			 *
25981 			 * ipclassifier calls this from a constructor -
25982 			 * hence no tcps
25983 			 */
25984 			TCP_G_STAT(tcp_timermp_allocdblfail);
25985 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25986 			    sizeof (tcp_timer_t), &size, kmflags);
25987 			mp->b_rptr = (uchar_t *)(&mp[1]);
25988 			mp->b_next = mp->b_prev = NULL;
25989 			mp->b_wptr = (uchar_t *)-1;
25990 			mp->b_datap = (dblk_t *)size;
25991 			mp->b_queue = NULL;
25992 			mp->b_cont = NULL;
25993 		}
25994 		ASSERT(mp->b_wptr != NULL);
25995 	}
25996 	/* ipclassifier calls this from a constructor - hence no tcps */
25997 	TCP_G_DBGSTAT(tcp_timermp_alloced);
25998 
25999 	return (mp);
26000 }
26001 
26002 /*
26003  * Free per-tcp timer cache.
26004  * It can only contain entries from tcp_timercache.
26005  */
26006 void
26007 tcp_timermp_free(tcp_t *tcp)
26008 {
26009 	mblk_t *mp;
26010 
26011 	while ((mp = tcp->tcp_timercache) != NULL) {
26012 		ASSERT(mp->b_wptr == NULL);
26013 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
26014 		kmem_cache_free(tcp_timercache, mp);
26015 	}
26016 }
26017 
26018 /*
26019  * Free timer event. Put it on the per-tcp timer cache if there is not too many
26020  * events there already (currently at most two events are cached).
26021  * If the event is not allocated from the timer cache, free it right away.
26022  */
26023 static void
26024 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
26025 {
26026 	mblk_t *mp1 = tcp->tcp_timercache;
26027 
26028 	if (mp->b_wptr != NULL) {
26029 		/*
26030 		 * This allocation is not from a timer cache, free it right
26031 		 * away.
26032 		 */
26033 		if (mp->b_wptr != (uchar_t *)-1)
26034 			freeb(mp);
26035 		else
26036 			kmem_free(mp, (size_t)mp->b_datap);
26037 	} else if (mp1 == NULL || mp1->b_next == NULL) {
26038 		/* Cache this timer block for future allocations */
26039 		mp->b_rptr = (uchar_t *)(&mp[1]);
26040 		mp->b_next = mp1;
26041 		tcp->tcp_timercache = mp;
26042 	} else {
26043 		kmem_cache_free(tcp_timercache, mp);
26044 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
26045 	}
26046 }
26047 
26048 /*
26049  * End of TCP Timers implementation.
26050  */
26051 
26052 /*
26053  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
26054  * on the specified backing STREAMS q. Note, the caller may make the
26055  * decision to call based on the tcp_t.tcp_flow_stopped value which
26056  * when check outside the q's lock is only an advisory check ...
26057  */
26058 void
26059 tcp_setqfull(tcp_t *tcp)
26060 {
26061 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26062 	conn_t	*connp = tcp->tcp_connp;
26063 
26064 	if (tcp->tcp_closed)
26065 		return;
26066 
26067 	if (IPCL_IS_NONSTR(connp)) {
26068 		(*connp->conn_upcalls->su_txq_full)
26069 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
26070 		tcp->tcp_flow_stopped = B_TRUE;
26071 	} else {
26072 		queue_t *q = tcp->tcp_wq;
26073 
26074 		if (!(q->q_flag & QFULL)) {
26075 			mutex_enter(QLOCK(q));
26076 			if (!(q->q_flag & QFULL)) {
26077 				/* still need to set QFULL */
26078 				q->q_flag |= QFULL;
26079 				tcp->tcp_flow_stopped = B_TRUE;
26080 				mutex_exit(QLOCK(q));
26081 				TCP_STAT(tcps, tcp_flwctl_on);
26082 			} else {
26083 				mutex_exit(QLOCK(q));
26084 			}
26085 		}
26086 	}
26087 }
26088 
26089 void
26090 tcp_clrqfull(tcp_t *tcp)
26091 {
26092 	conn_t  *connp = tcp->tcp_connp;
26093 
26094 	if (tcp->tcp_closed)
26095 		return;
26096 
26097 	if (IPCL_IS_NONSTR(connp)) {
26098 		(*connp->conn_upcalls->su_txq_full)
26099 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
26100 		tcp->tcp_flow_stopped = B_FALSE;
26101 	} else {
26102 		queue_t *q = tcp->tcp_wq;
26103 
26104 		if (q->q_flag & QFULL) {
26105 			mutex_enter(QLOCK(q));
26106 			if (q->q_flag & QFULL) {
26107 				q->q_flag &= ~QFULL;
26108 				tcp->tcp_flow_stopped = B_FALSE;
26109 				mutex_exit(QLOCK(q));
26110 				if (q->q_flag & QWANTW)
26111 					qbackenable(q, 0);
26112 			} else {
26113 				mutex_exit(QLOCK(q));
26114 			}
26115 		}
26116 	}
26117 }
26118 
26119 /*
26120  * kstats related to squeues i.e. not per IP instance
26121  */
26122 static void *
26123 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26124 {
26125 	kstat_t *ksp;
26126 
26127 	tcp_g_stat_t template = {
26128 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26129 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
26130 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
26131 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
26132 	};
26133 
26134 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
26135 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26136 	    KSTAT_FLAG_VIRTUAL);
26137 
26138 	if (ksp == NULL)
26139 		return (NULL);
26140 
26141 	bcopy(&template, tcp_g_statp, sizeof (template));
26142 	ksp->ks_data = (void *)tcp_g_statp;
26143 
26144 	kstat_install(ksp);
26145 	return (ksp);
26146 }
26147 
26148 static void
26149 tcp_g_kstat_fini(kstat_t *ksp)
26150 {
26151 	if (ksp != NULL) {
26152 		kstat_delete(ksp);
26153 	}
26154 }
26155 
26156 
26157 static void *
26158 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
26159 {
26160 	kstat_t *ksp;
26161 
26162 	tcp_stat_t template = {
26163 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
26164 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
26165 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
26166 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
26167 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
26168 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
26169 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
26170 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
26171 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
26172 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
26173 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
26174 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
26175 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
26176 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
26177 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
26178 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
26179 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
26180 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
26181 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
26182 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
26183 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
26184 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
26185 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
26186 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
26187 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
26188 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
26189 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
26190 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
26191 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
26192 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
26193 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
26194 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
26195 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
26196 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
26197 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
26198 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
26199 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
26200 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
26201 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
26202 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
26203 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
26204 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
26205 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
26206 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
26207 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
26208 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
26209 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
26210 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
26211 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
26212 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
26213 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
26214 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
26215 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
26216 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
26217 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
26218 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
26219 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
26220 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
26221 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
26222 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
26223 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
26224 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
26225 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
26226 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
26227 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
26228 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
26229 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
26230 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
26231 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
26232 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
26233 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
26234 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
26235 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
26236 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
26237 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
26238 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
26239 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
26240 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
26241 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
26242 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
26243 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
26244 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
26245 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
26246 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
26247 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
26248 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
26249 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
26250 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
26251 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
26252 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
26253 	};
26254 
26255 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
26256 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26257 	    KSTAT_FLAG_VIRTUAL, stackid);
26258 
26259 	if (ksp == NULL)
26260 		return (NULL);
26261 
26262 	bcopy(&template, tcps_statisticsp, sizeof (template));
26263 	ksp->ks_data = (void *)tcps_statisticsp;
26264 	ksp->ks_private = (void *)(uintptr_t)stackid;
26265 
26266 	kstat_install(ksp);
26267 	return (ksp);
26268 }
26269 
26270 static void
26271 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
26272 {
26273 	if (ksp != NULL) {
26274 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26275 		kstat_delete_netstack(ksp, stackid);
26276 	}
26277 }
26278 
26279 /*
26280  * TCP Kstats implementation
26281  */
26282 static void *
26283 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
26284 {
26285 	kstat_t	*ksp;
26286 
26287 	tcp_named_kstat_t template = {
26288 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
26289 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
26290 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
26291 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
26292 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
26293 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
26294 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
26295 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
26296 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
26297 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
26298 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
26299 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
26300 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
26301 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
26302 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
26303 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
26304 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
26305 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
26306 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
26307 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
26308 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
26309 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
26310 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
26311 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
26312 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
26313 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
26314 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
26315 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
26316 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
26317 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
26318 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
26319 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
26320 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
26321 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
26322 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
26323 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
26324 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
26325 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
26326 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
26327 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
26328 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
26329 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
26330 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
26331 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
26332 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
26333 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
26334 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
26335 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
26336 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
26337 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
26338 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
26339 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
26340 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
26341 	};
26342 
26343 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
26344 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
26345 
26346 	if (ksp == NULL)
26347 		return (NULL);
26348 
26349 	template.rtoAlgorithm.value.ui32 = 4;
26350 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
26351 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
26352 	template.maxConn.value.i32 = -1;
26353 
26354 	bcopy(&template, ksp->ks_data, sizeof (template));
26355 	ksp->ks_update = tcp_kstat_update;
26356 	ksp->ks_private = (void *)(uintptr_t)stackid;
26357 
26358 	kstat_install(ksp);
26359 	return (ksp);
26360 }
26361 
26362 static void
26363 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
26364 {
26365 	if (ksp != NULL) {
26366 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26367 		kstat_delete_netstack(ksp, stackid);
26368 	}
26369 }
26370 
26371 static int
26372 tcp_kstat_update(kstat_t *kp, int rw)
26373 {
26374 	tcp_named_kstat_t *tcpkp;
26375 	tcp_t		*tcp;
26376 	connf_t		*connfp;
26377 	conn_t		*connp;
26378 	int 		i;
26379 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
26380 	netstack_t	*ns;
26381 	tcp_stack_t	*tcps;
26382 	ip_stack_t	*ipst;
26383 
26384 	if ((kp == NULL) || (kp->ks_data == NULL))
26385 		return (EIO);
26386 
26387 	if (rw == KSTAT_WRITE)
26388 		return (EACCES);
26389 
26390 	ns = netstack_find_by_stackid(stackid);
26391 	if (ns == NULL)
26392 		return (-1);
26393 	tcps = ns->netstack_tcp;
26394 	if (tcps == NULL) {
26395 		netstack_rele(ns);
26396 		return (-1);
26397 	}
26398 
26399 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
26400 
26401 	tcpkp->currEstab.value.ui32 = 0;
26402 
26403 	ipst = ns->netstack_ip;
26404 
26405 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
26406 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
26407 		connp = NULL;
26408 		while ((connp =
26409 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
26410 			tcp = connp->conn_tcp;
26411 			switch (tcp_snmp_state(tcp)) {
26412 			case MIB2_TCP_established:
26413 			case MIB2_TCP_closeWait:
26414 				tcpkp->currEstab.value.ui32++;
26415 				break;
26416 			}
26417 		}
26418 	}
26419 
26420 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
26421 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
26422 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
26423 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
26424 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
26425 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
26426 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
26427 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
26428 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
26429 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
26430 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
26431 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
26432 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
26433 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
26434 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
26435 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
26436 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
26437 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
26438 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
26439 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
26440 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
26441 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
26442 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
26443 	tcpkp->inDataInorderSegs.value.ui32 =
26444 	    tcps->tcps_mib.tcpInDataInorderSegs;
26445 	tcpkp->inDataInorderBytes.value.ui32 =
26446 	    tcps->tcps_mib.tcpInDataInorderBytes;
26447 	tcpkp->inDataUnorderSegs.value.ui32 =
26448 	    tcps->tcps_mib.tcpInDataUnorderSegs;
26449 	tcpkp->inDataUnorderBytes.value.ui32 =
26450 	    tcps->tcps_mib.tcpInDataUnorderBytes;
26451 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
26452 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
26453 	tcpkp->inDataPartDupSegs.value.ui32 =
26454 	    tcps->tcps_mib.tcpInDataPartDupSegs;
26455 	tcpkp->inDataPartDupBytes.value.ui32 =
26456 	    tcps->tcps_mib.tcpInDataPartDupBytes;
26457 	tcpkp->inDataPastWinSegs.value.ui32 =
26458 	    tcps->tcps_mib.tcpInDataPastWinSegs;
26459 	tcpkp->inDataPastWinBytes.value.ui32 =
26460 	    tcps->tcps_mib.tcpInDataPastWinBytes;
26461 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
26462 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
26463 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
26464 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
26465 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
26466 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
26467 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
26468 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
26469 	tcpkp->timKeepaliveProbe.value.ui32 =
26470 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
26471 	tcpkp->timKeepaliveDrop.value.ui32 =
26472 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
26473 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
26474 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
26475 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
26476 	tcpkp->outSackRetransSegs.value.ui32 =
26477 	    tcps->tcps_mib.tcpOutSackRetransSegs;
26478 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
26479 
26480 	netstack_rele(ns);
26481 	return (0);
26482 }
26483 
26484 void
26485 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
26486 {
26487 	uint16_t	hdr_len;
26488 	ipha_t		*ipha;
26489 	uint8_t		*nexthdrp;
26490 	tcph_t		*tcph;
26491 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26492 
26493 	/* Already has an eager */
26494 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26495 		TCP_STAT(tcps, tcp_reinput_syn);
26496 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26497 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
26498 		return;
26499 	}
26500 
26501 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
26502 	case IPV4_VERSION:
26503 		ipha = (ipha_t *)mp->b_rptr;
26504 		hdr_len = IPH_HDR_LENGTH(ipha);
26505 		break;
26506 	case IPV6_VERSION:
26507 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
26508 		    &hdr_len, &nexthdrp)) {
26509 			CONN_DEC_REF(connp);
26510 			freemsg(mp);
26511 			return;
26512 		}
26513 		break;
26514 	}
26515 
26516 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
26517 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
26518 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
26519 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
26520 	}
26521 
26522 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26523 	    SQ_FILL, SQTAG_TCP_REINPUT);
26524 }
26525 
26526 static int
26527 tcp_squeue_switch(int val)
26528 {
26529 	int rval = SQ_FILL;
26530 
26531 	switch (val) {
26532 	case 1:
26533 		rval = SQ_NODRAIN;
26534 		break;
26535 	case 2:
26536 		rval = SQ_PROCESS;
26537 		break;
26538 	default:
26539 		break;
26540 	}
26541 	return (rval);
26542 }
26543 
26544 /*
26545  * This is called once for each squeue - globally for all stack
26546  * instances.
26547  */
26548 static void
26549 tcp_squeue_add(squeue_t *sqp)
26550 {
26551 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
26552 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
26553 
26554 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
26555 	tcp_time_wait->tcp_time_wait_tid =
26556 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
26557 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
26558 	    CALLOUT_FLAG_ROUNDUP);
26559 	if (tcp_free_list_max_cnt == 0) {
26560 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
26561 		    max_ncpus : boot_max_ncpus);
26562 
26563 		/*
26564 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
26565 		 */
26566 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
26567 		    (tcp_ncpus * sizeof (tcp_t) * 100);
26568 	}
26569 	tcp_time_wait->tcp_free_list_cnt = 0;
26570 }
26571 
26572 static int
26573 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error)
26574 {
26575 	mblk_t	*ire_mp = NULL;
26576 	mblk_t	*syn_mp;
26577 	mblk_t	*mdti;
26578 	mblk_t	*lsoi;
26579 	int	retval;
26580 	tcph_t	*tcph;
26581 	uint32_t	mss;
26582 	queue_t	*q = tcp->tcp_rq;
26583 	conn_t	*connp = tcp->tcp_connp;
26584 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26585 
26586 	if (error == 0) {
26587 		/*
26588 		 * Adapt Multidata information, if any.  The
26589 		 * following tcp_mdt_update routine will free
26590 		 * the message.
26591 		 */
26592 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
26593 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
26594 			    b_rptr)->mdt_capab, B_TRUE);
26595 			freemsg(mdti);
26596 		}
26597 
26598 		/*
26599 		 * Check to update LSO information with tcp, and
26600 		 * tcp_lso_update routine will free the message.
26601 		 */
26602 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
26603 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
26604 			    b_rptr)->lso_capab);
26605 			freemsg(lsoi);
26606 		}
26607 
26608 		/* Get the IRE, if we had requested for it */
26609 		if (mp != NULL)
26610 			ire_mp = tcp_ire_mp(&mp);
26611 
26612 		if (tcp->tcp_hard_binding) {
26613 			tcp->tcp_hard_binding = B_FALSE;
26614 			tcp->tcp_hard_bound = B_TRUE;
26615 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
26616 			if (retval != 0) {
26617 				error = EADDRINUSE;
26618 				goto bind_failed;
26619 			}
26620 		} else {
26621 			if (ire_mp != NULL)
26622 				freeb(ire_mp);
26623 			goto after_syn_sent;
26624 		}
26625 
26626 		retval = tcp_adapt_ire(tcp, ire_mp);
26627 		if (ire_mp != NULL)
26628 			freeb(ire_mp);
26629 		if (retval == 0) {
26630 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
26631 			    ENETUNREACH : EADDRNOTAVAIL);
26632 			goto ipcl_rm;
26633 		}
26634 		/*
26635 		 * Don't let an endpoint connect to itself.
26636 		 * Also checked in tcp_connect() but that
26637 		 * check can't handle the case when the
26638 		 * local IP address is INADDR_ANY.
26639 		 */
26640 		if (tcp->tcp_ipversion == IPV4_VERSION) {
26641 			if ((tcp->tcp_ipha->ipha_dst ==
26642 			    tcp->tcp_ipha->ipha_src) &&
26643 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26644 			    tcp->tcp_tcph->th_fport))) {
26645 				error = EADDRNOTAVAIL;
26646 				goto ipcl_rm;
26647 			}
26648 		} else {
26649 			if (IN6_ARE_ADDR_EQUAL(
26650 			    &tcp->tcp_ip6h->ip6_dst,
26651 			    &tcp->tcp_ip6h->ip6_src) &&
26652 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26653 			    tcp->tcp_tcph->th_fport))) {
26654 				error = EADDRNOTAVAIL;
26655 				goto ipcl_rm;
26656 			}
26657 		}
26658 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
26659 		/*
26660 		 * This should not be possible!  Just for
26661 		 * defensive coding...
26662 		 */
26663 		if (tcp->tcp_state != TCPS_SYN_SENT)
26664 			goto after_syn_sent;
26665 
26666 		if (is_system_labeled() &&
26667 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
26668 			error = EHOSTUNREACH;
26669 			goto ipcl_rm;
26670 		}
26671 
26672 		/*
26673 		 * tcp_adapt_ire() does not adjust
26674 		 * for TCP/IP header length.
26675 		 */
26676 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
26677 
26678 		/*
26679 		 * Just make sure our rwnd is at
26680 		 * least tcp_recv_hiwat_mss * MSS
26681 		 * large, and round up to the nearest
26682 		 * MSS.
26683 		 *
26684 		 * We do the round up here because
26685 		 * we need to get the interface
26686 		 * MTU first before we can do the
26687 		 * round up.
26688 		 */
26689 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
26690 		    tcps->tcps_recv_hiwat_minmss * mss);
26691 		if (!IPCL_IS_NONSTR(connp))
26692 			q->q_hiwat = tcp->tcp_rwnd;
26693 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
26694 		tcp_set_ws_value(tcp);
26695 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
26696 		    tcp->tcp_tcph->th_win);
26697 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
26698 			tcp->tcp_snd_ws_ok = B_TRUE;
26699 
26700 		/*
26701 		 * Set tcp_snd_ts_ok to true
26702 		 * so that tcp_xmit_mp will
26703 		 * include the timestamp
26704 		 * option in the SYN segment.
26705 		 */
26706 		if (tcps->tcps_tstamp_always ||
26707 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
26708 			tcp->tcp_snd_ts_ok = B_TRUE;
26709 		}
26710 
26711 		/*
26712 		 * tcp_snd_sack_ok can be set in
26713 		 * tcp_adapt_ire() if the sack metric
26714 		 * is set.  So check it here also.
26715 		 */
26716 		if (tcps->tcps_sack_permitted == 2 ||
26717 		    tcp->tcp_snd_sack_ok) {
26718 			if (tcp->tcp_sack_info == NULL) {
26719 				tcp->tcp_sack_info =
26720 				    kmem_cache_alloc(tcp_sack_info_cache,
26721 				    KM_SLEEP);
26722 			}
26723 			tcp->tcp_snd_sack_ok = B_TRUE;
26724 		}
26725 
26726 		/*
26727 		 * Should we use ECN?  Note that the current
26728 		 * default value (SunOS 5.9) of tcp_ecn_permitted
26729 		 * is 1.  The reason for doing this is that there
26730 		 * are equipments out there that will drop ECN
26731 		 * enabled IP packets.  Setting it to 1 avoids
26732 		 * compatibility problems.
26733 		 */
26734 		if (tcps->tcps_ecn_permitted == 2)
26735 			tcp->tcp_ecn_ok = B_TRUE;
26736 
26737 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
26738 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
26739 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
26740 		if (syn_mp) {
26741 			cred_t *cr;
26742 			pid_t pid;
26743 
26744 			/*
26745 			 * Obtain the credential from the
26746 			 * thread calling connect().
26747 			 * If none can be found, default to
26748 			 * the creator  of the socket.
26749 			 */
26750 			if (mp == NULL ||
26751 			    (cr = DB_CRED(mp)) == NULL) {
26752 				cr = tcp->tcp_cred;
26753 				pid = tcp->tcp_cpid;
26754 			} else {
26755 				pid = DB_CPID(mp);
26756 			}
26757 
26758 			mblk_setcred(syn_mp, cr);
26759 			DB_CPID(syn_mp) = pid;
26760 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
26761 		}
26762 	after_syn_sent:
26763 		/*
26764 		 * A trailer mblk indicates a waiting client upstream.
26765 		 * We complete here the processing begun in
26766 		 * either tcp_bind() or tcp_connect() by passing
26767 		 * upstream the reply message they supplied.
26768 		 */
26769 		if (mp != NULL) {
26770 			ASSERT(mp->b_cont == NULL);
26771 			freeb(mp);
26772 		}
26773 		return (error);
26774 	} else {
26775 		/* error */
26776 		if (tcp->tcp_debug) {
26777 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
26778 			    "tcp_post_ip_bind: error == %d", error);
26779 		}
26780 		if (mp != NULL) {
26781 			freeb(mp);
26782 		}
26783 	}
26784 
26785 ipcl_rm:
26786 	/*
26787 	 * Need to unbind with classifier since we were just
26788 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
26789 	 */
26790 	tcp->tcp_hard_bound = B_FALSE;
26791 	tcp->tcp_hard_binding = B_FALSE;
26792 
26793 	ipcl_hash_remove(connp);
26794 
26795 bind_failed:
26796 	tcp->tcp_state = TCPS_IDLE;
26797 	if (tcp->tcp_ipversion == IPV4_VERSION)
26798 		tcp->tcp_ipha->ipha_src = 0;
26799 	else
26800 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
26801 	/*
26802 	 * Copy of the src addr. in tcp_t is needed since
26803 	 * the lookup funcs. can only look at tcp_t
26804 	 */
26805 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
26806 
26807 	tcph = tcp->tcp_tcph;
26808 	tcph->th_lport[0] = 0;
26809 	tcph->th_lport[1] = 0;
26810 	tcp_bind_hash_remove(tcp);
26811 	bzero(&connp->u_port, sizeof (connp->u_port));
26812 	/* blow away saved option results if any */
26813 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26814 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26815 
26816 	conn_delete_ire(tcp->tcp_connp, NULL);
26817 
26818 	return (error);
26819 }
26820 
26821 static int
26822 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
26823     boolean_t bind_to_req_port_only, cred_t *cr)
26824 {
26825 	in_port_t	mlp_port;
26826 	mlp_type_t 	addrtype, mlptype;
26827 	boolean_t	user_specified;
26828 	in_port_t	allocated_port;
26829 	in_port_t	requested_port = *requested_port_ptr;
26830 	conn_t		*connp;
26831 	zone_t		*zone;
26832 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26833 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
26834 
26835 	/*
26836 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
26837 	 */
26838 	if (cr == NULL)
26839 		cr = tcp->tcp_cred;
26840 	/*
26841 	 * Get a valid port (within the anonymous range and should not
26842 	 * be a privileged one) to use if the user has not given a port.
26843 	 * If multiple threads are here, they may all start with
26844 	 * with the same initial port. But, it should be fine as long as
26845 	 * tcp_bindi will ensure that no two threads will be assigned
26846 	 * the same port.
26847 	 *
26848 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
26849 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
26850 	 * unless TCP_ANONPRIVBIND option is set.
26851 	 */
26852 	mlptype = mlptSingle;
26853 	mlp_port = requested_port;
26854 	if (requested_port == 0) {
26855 		requested_port = tcp->tcp_anon_priv_bind ?
26856 		    tcp_get_next_priv_port(tcp) :
26857 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
26858 		    tcp, B_TRUE);
26859 		if (requested_port == 0) {
26860 			return (-TNOADDR);
26861 		}
26862 		user_specified = B_FALSE;
26863 
26864 		/*
26865 		 * If the user went through one of the RPC interfaces to create
26866 		 * this socket and RPC is MLP in this zone, then give him an
26867 		 * anonymous MLP.
26868 		 */
26869 		connp = tcp->tcp_connp;
26870 		if (connp->conn_anon_mlp && is_system_labeled()) {
26871 			zone = crgetzone(cr);
26872 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26873 			    IPV6_VERSION, &v6addr,
26874 			    tcps->tcps_netstack->netstack_ip);
26875 			if (addrtype == mlptSingle) {
26876 				return (-TNOADDR);
26877 			}
26878 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26879 			    PMAPPORT, addrtype);
26880 			mlp_port = PMAPPORT;
26881 		}
26882 	} else {
26883 		int i;
26884 		boolean_t priv = B_FALSE;
26885 
26886 		/*
26887 		 * If the requested_port is in the well-known privileged range,
26888 		 * verify that the stream was opened by a privileged user.
26889 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
26890 		 * but instead the code relies on:
26891 		 * - the fact that the address of the array and its size never
26892 		 *   changes
26893 		 * - the atomic assignment of the elements of the array
26894 		 */
26895 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
26896 			priv = B_TRUE;
26897 		} else {
26898 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
26899 				if (requested_port ==
26900 				    tcps->tcps_g_epriv_ports[i]) {
26901 					priv = B_TRUE;
26902 					break;
26903 				}
26904 			}
26905 		}
26906 		if (priv) {
26907 			if (secpolicy_net_privaddr(cr, requested_port,
26908 			    IPPROTO_TCP) != 0) {
26909 				if (tcp->tcp_debug) {
26910 					(void) strlog(TCP_MOD_ID, 0, 1,
26911 					    SL_ERROR|SL_TRACE,
26912 					    "tcp_bind: no priv for port %d",
26913 					    requested_port);
26914 				}
26915 				return (-TACCES);
26916 			}
26917 		}
26918 		user_specified = B_TRUE;
26919 
26920 		connp = tcp->tcp_connp;
26921 		if (is_system_labeled()) {
26922 			zone = crgetzone(cr);
26923 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26924 			    IPV6_VERSION, &v6addr,
26925 			    tcps->tcps_netstack->netstack_ip);
26926 			if (addrtype == mlptSingle) {
26927 				return (-TNOADDR);
26928 			}
26929 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26930 			    requested_port, addrtype);
26931 		}
26932 	}
26933 
26934 	if (mlptype != mlptSingle) {
26935 		if (secpolicy_net_bindmlp(cr) != 0) {
26936 			if (tcp->tcp_debug) {
26937 				(void) strlog(TCP_MOD_ID, 0, 1,
26938 				    SL_ERROR|SL_TRACE,
26939 				    "tcp_bind: no priv for multilevel port %d",
26940 				    requested_port);
26941 			}
26942 			return (-TACCES);
26943 		}
26944 
26945 		/*
26946 		 * If we're specifically binding a shared IP address and the
26947 		 * port is MLP on shared addresses, then check to see if this
26948 		 * zone actually owns the MLP.  Reject if not.
26949 		 */
26950 		if (mlptype == mlptShared && addrtype == mlptShared) {
26951 			/*
26952 			 * No need to handle exclusive-stack zones since
26953 			 * ALL_ZONES only applies to the shared stack.
26954 			 */
26955 			zoneid_t mlpzone;
26956 
26957 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26958 			    htons(mlp_port));
26959 			if (connp->conn_zoneid != mlpzone) {
26960 				if (tcp->tcp_debug) {
26961 					(void) strlog(TCP_MOD_ID, 0, 1,
26962 					    SL_ERROR|SL_TRACE,
26963 					    "tcp_bind: attempt to bind port "
26964 					    "%d on shared addr in zone %d "
26965 					    "(should be %d)",
26966 					    mlp_port, connp->conn_zoneid,
26967 					    mlpzone);
26968 				}
26969 				return (-TACCES);
26970 			}
26971 		}
26972 
26973 		if (!user_specified) {
26974 			int err;
26975 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26976 			    requested_port, B_TRUE);
26977 			if (err != 0) {
26978 				if (tcp->tcp_debug) {
26979 					(void) strlog(TCP_MOD_ID, 0, 1,
26980 					    SL_ERROR|SL_TRACE,
26981 					    "tcp_bind: cannot establish anon "
26982 					    "MLP for port %d",
26983 					    requested_port);
26984 				}
26985 				return (err);
26986 			}
26987 			connp->conn_anon_port = B_TRUE;
26988 		}
26989 		connp->conn_mlp_type = mlptype;
26990 	}
26991 
26992 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26993 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26994 
26995 	if (allocated_port == 0) {
26996 		connp->conn_mlp_type = mlptSingle;
26997 		if (connp->conn_anon_port) {
26998 			connp->conn_anon_port = B_FALSE;
26999 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
27000 			    requested_port, B_FALSE);
27001 		}
27002 		if (bind_to_req_port_only) {
27003 			if (tcp->tcp_debug) {
27004 				(void) strlog(TCP_MOD_ID, 0, 1,
27005 				    SL_ERROR|SL_TRACE,
27006 				    "tcp_bind: requested addr busy");
27007 			}
27008 			return (-TADDRBUSY);
27009 		} else {
27010 			/* If we are out of ports, fail the bind. */
27011 			if (tcp->tcp_debug) {
27012 				(void) strlog(TCP_MOD_ID, 0, 1,
27013 				    SL_ERROR|SL_TRACE,
27014 				    "tcp_bind: out of ports?");
27015 			}
27016 			return (-TNOADDR);
27017 		}
27018 	}
27019 
27020 	/* Pass the allocated port back */
27021 	*requested_port_ptr = allocated_port;
27022 	return (0);
27023 }
27024 
27025 static int
27026 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
27027     boolean_t bind_to_req_port_only)
27028 {
27029 	tcp_t	*tcp = connp->conn_tcp;
27030 
27031 	sin_t	*sin;
27032 	sin6_t  *sin6;
27033 	sin6_t		sin6addr;
27034 	in_port_t requested_port;
27035 	ipaddr_t	v4addr;
27036 	in6_addr_t	v6addr;
27037 	uint_t	origipversion;
27038 	int	error = 0;
27039 
27040 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
27041 
27042 	if (tcp->tcp_state == TCPS_BOUND) {
27043 		return (0);
27044 	} else if (tcp->tcp_state > TCPS_BOUND) {
27045 		if (tcp->tcp_debug) {
27046 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27047 			    "tcp_bind: bad state, %d", tcp->tcp_state);
27048 		}
27049 		return (-TOUTSTATE);
27050 	}
27051 	origipversion = tcp->tcp_ipversion;
27052 
27053 	if (sa != NULL && !OK_32PTR((char *)sa)) {
27054 		if (tcp->tcp_debug) {
27055 			(void) strlog(TCP_MOD_ID, 0, 1,
27056 			    SL_ERROR|SL_TRACE,
27057 			    "tcp_bind: bad address parameter, "
27058 			    "address %p, len %d",
27059 			    (void *)sa, len);
27060 		}
27061 		return (-TPROTO);
27062 	}
27063 
27064 	switch (len) {
27065 	case 0:		/* request for a generic port */
27066 		if (tcp->tcp_family == AF_INET) {
27067 			sin = (sin_t *)&sin6addr;
27068 			*sin = sin_null;
27069 			sin->sin_family = AF_INET;
27070 			tcp->tcp_ipversion = IPV4_VERSION;
27071 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
27072 		} else {
27073 			ASSERT(tcp->tcp_family == AF_INET6);
27074 			sin6 = (sin6_t *)&sin6addr;
27075 			*sin6 = sin6_null;
27076 			sin6->sin6_family = AF_INET6;
27077 			tcp->tcp_ipversion = IPV6_VERSION;
27078 			V6_SET_ZERO(v6addr);
27079 		}
27080 		requested_port = 0;
27081 		break;
27082 
27083 	case sizeof (sin_t):	/* Complete IPv4 address */
27084 		sin = (sin_t *)sa;
27085 		/*
27086 		 * With sockets sockfs will accept bogus sin_family in
27087 		 * bind() and replace it with the family used in the socket
27088 		 * call.
27089 		 */
27090 		if (sin->sin_family != AF_INET ||
27091 		    tcp->tcp_family != AF_INET) {
27092 			return (EAFNOSUPPORT);
27093 		}
27094 		requested_port = ntohs(sin->sin_port);
27095 		tcp->tcp_ipversion = IPV4_VERSION;
27096 		v4addr = sin->sin_addr.s_addr;
27097 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
27098 		break;
27099 
27100 	case sizeof (sin6_t): /* Complete IPv6 address */
27101 		sin6 = (sin6_t *)sa;
27102 		if (sin6->sin6_family != AF_INET6 ||
27103 		    tcp->tcp_family != AF_INET6) {
27104 			return (EAFNOSUPPORT);
27105 		}
27106 		requested_port = ntohs(sin6->sin6_port);
27107 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
27108 		    IPV4_VERSION : IPV6_VERSION;
27109 		v6addr = sin6->sin6_addr;
27110 		break;
27111 
27112 	default:
27113 		if (tcp->tcp_debug) {
27114 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27115 			    "tcp_bind: bad address length, %d", len);
27116 		}
27117 		return (EAFNOSUPPORT);
27118 		/* return (-TBADADDR); */
27119 	}
27120 
27121 	tcp->tcp_bound_source_v6 = v6addr;
27122 
27123 	/* Check for change in ipversion */
27124 	if (origipversion != tcp->tcp_ipversion) {
27125 		ASSERT(tcp->tcp_family == AF_INET6);
27126 		error = tcp->tcp_ipversion == IPV6_VERSION ?
27127 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
27128 		if (error) {
27129 			return (ENOMEM);
27130 		}
27131 	}
27132 
27133 	/*
27134 	 * Initialize family specific fields. Copy of the src addr.
27135 	 * in tcp_t is needed for the lookup funcs.
27136 	 */
27137 	if (tcp->tcp_ipversion == IPV6_VERSION) {
27138 		tcp->tcp_ip6h->ip6_src = v6addr;
27139 	} else {
27140 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
27141 	}
27142 	tcp->tcp_ip_src_v6 = v6addr;
27143 
27144 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
27145 
27146 	error = tcp_bind_select_lport(tcp, &requested_port,
27147 	    bind_to_req_port_only, cr);
27148 
27149 	return (error);
27150 }
27151 
27152 /*
27153  * Return unix error is tli error is TSYSERR, otherwise return a negative
27154  * tli error.
27155  */
27156 int
27157 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
27158     boolean_t bind_to_req_port_only)
27159 {
27160 	int error;
27161 	tcp_t *tcp = connp->conn_tcp;
27162 
27163 	if (tcp->tcp_state >= TCPS_BOUND) {
27164 		if (tcp->tcp_debug) {
27165 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27166 			    "tcp_bind: bad state, %d", tcp->tcp_state);
27167 		}
27168 		return (-TOUTSTATE);
27169 	}
27170 
27171 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
27172 	if (error != 0)
27173 		return (error);
27174 
27175 	ASSERT(tcp->tcp_state == TCPS_BOUND);
27176 
27177 	tcp->tcp_conn_req_max = 0;
27178 
27179 	/*
27180 	 * We need to make sure that the conn_recv is set to a non-null
27181 	 * value before we insert the conn into the classifier table.
27182 	 * This is to avoid a race with an incoming packet which does an
27183 	 * ipcl_classify().
27184 	 */
27185 	connp->conn_recv = tcp_conn_request;
27186 
27187 	if (tcp->tcp_family == AF_INET6) {
27188 		ASSERT(tcp->tcp_connp->conn_af_isv6);
27189 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27190 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
27191 	} else {
27192 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
27193 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
27194 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
27195 	}
27196 	return (tcp_post_ip_bind(tcp, NULL, error));
27197 }
27198 
27199 int
27200 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
27201     socklen_t len, cred_t *cr)
27202 {
27203 	int 		error;
27204 	conn_t		*connp = (conn_t *)proto_handle;
27205 	squeue_t	*sqp = connp->conn_sqp;
27206 
27207 	ASSERT(sqp != NULL);
27208 
27209 	error = squeue_synch_enter(sqp, connp, 0);
27210 	if (error != 0) {
27211 		/* failed to enter */
27212 		return (ENOSR);
27213 	}
27214 
27215 	/* binding to a NULL address really means unbind */
27216 	if (sa == NULL) {
27217 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
27218 			error = tcp_do_unbind(connp);
27219 		else
27220 			error = EINVAL;
27221 	} else {
27222 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
27223 	}
27224 
27225 	squeue_synch_exit(sqp, connp);
27226 
27227 	if (error < 0) {
27228 		if (error == -TOUTSTATE)
27229 			error = EINVAL;
27230 		else
27231 			error = proto_tlitosyserr(-error);
27232 	}
27233 
27234 	return (error);
27235 }
27236 
27237 /*
27238  * If the return value from this function is positive, it's a UNIX error.
27239  * Otherwise, if it's negative, then the absolute value is a TLI error.
27240  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
27241  */
27242 int
27243 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
27244     cred_t *cr, pid_t pid)
27245 {
27246 	tcp_t		*tcp = connp->conn_tcp;
27247 	sin_t		*sin = (sin_t *)sa;
27248 	sin6_t		*sin6 = (sin6_t *)sa;
27249 	ipaddr_t	*dstaddrp;
27250 	in_port_t	dstport;
27251 	uint_t		srcid;
27252 	int		error = 0;
27253 
27254 	switch (len) {
27255 	default:
27256 		/*
27257 		 * Should never happen
27258 		 */
27259 		return (EINVAL);
27260 
27261 	case sizeof (sin_t):
27262 		sin = (sin_t *)sa;
27263 		if (sin->sin_port == 0) {
27264 			return (-TBADADDR);
27265 		}
27266 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
27267 			return (EAFNOSUPPORT);
27268 		}
27269 		break;
27270 
27271 	case sizeof (sin6_t):
27272 		sin6 = (sin6_t *)sa;
27273 		if (sin6->sin6_port == 0) {
27274 			return (-TBADADDR);
27275 		}
27276 		break;
27277 	}
27278 	/*
27279 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
27280 	 * make sure that the template IP header in the tcp structure is an
27281 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
27282 	 * need to this before we call tcp_bindi() so that the port lookup
27283 	 * code will look for ports in the correct port space (IPv4 and
27284 	 * IPv6 have separate port spaces).
27285 	 */
27286 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
27287 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
27288 		int err = 0;
27289 
27290 		err = tcp_header_init_ipv4(tcp);
27291 			if (err != 0) {
27292 				error = ENOMEM;
27293 				goto connect_failed;
27294 			}
27295 		if (tcp->tcp_lport != 0)
27296 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
27297 	}
27298 
27299 	switch (tcp->tcp_state) {
27300 	case TCPS_LISTEN:
27301 		/*
27302 		 * Listening sockets are not allowed to issue connect().
27303 		 */
27304 		if (IPCL_IS_NONSTR(connp))
27305 			return (EOPNOTSUPP);
27306 		/* FALLTHRU */
27307 	case TCPS_IDLE:
27308 		/*
27309 		 * We support quick connect, refer to comments in
27310 		 * tcp_connect_*()
27311 		 */
27312 		/* FALLTHRU */
27313 	case TCPS_BOUND:
27314 		/*
27315 		 * We must bump the generation before the operation start.
27316 		 * This is done to ensure that any upcall made later on sends
27317 		 * up the right generation to the socket.
27318 		 */
27319 		SOCK_CONNID_BUMP(tcp->tcp_connid);
27320 
27321 		if (tcp->tcp_family == AF_INET6) {
27322 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
27323 				return (tcp_connect_ipv6(tcp,
27324 				    &sin6->sin6_addr,
27325 				    sin6->sin6_port, sin6->sin6_flowinfo,
27326 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
27327 				    cr, pid));
27328 			}
27329 			/*
27330 			 * Destination adress is mapped IPv6 address.
27331 			 * Source bound address should be unspecified or
27332 			 * IPv6 mapped address as well.
27333 			 */
27334 			if (!IN6_IS_ADDR_UNSPECIFIED(
27335 			    &tcp->tcp_bound_source_v6) &&
27336 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
27337 				return (EADDRNOTAVAIL);
27338 			}
27339 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
27340 			dstport = sin6->sin6_port;
27341 			srcid = sin6->__sin6_src_id;
27342 		} else {
27343 			dstaddrp = &sin->sin_addr.s_addr;
27344 			dstport = sin->sin_port;
27345 			srcid = 0;
27346 		}
27347 
27348 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
27349 		    pid);
27350 		break;
27351 	default:
27352 		return (-TOUTSTATE);
27353 	}
27354 	/*
27355 	 * Note: Code below is the "failure" case
27356 	 */
27357 connect_failed:
27358 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
27359 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
27360 	return (error);
27361 }
27362 
27363 int
27364 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
27365     socklen_t len, sock_connid_t *id, cred_t *cr)
27366 {
27367 	conn_t		*connp = (conn_t *)proto_handle;
27368 	tcp_t		*tcp = connp->conn_tcp;
27369 	squeue_t	*sqp = connp->conn_sqp;
27370 	int		error;
27371 
27372 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
27373 	if (error != 0) {
27374 		return (error);
27375 	}
27376 
27377 	error = squeue_synch_enter(sqp, connp, 0);
27378 	if (error != 0) {
27379 		/* failed to enter */
27380 		return (ENOSR);
27381 	}
27382 
27383 	/*
27384 	 * TCP supports quick connect, so no need to do an implicit bind
27385 	 */
27386 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
27387 	if (error == 0) {
27388 		*id = connp->conn_tcp->tcp_connid;
27389 	} else if (error < 0) {
27390 		if (error == -TOUTSTATE) {
27391 			switch (connp->conn_tcp->tcp_state) {
27392 			case TCPS_SYN_SENT:
27393 				error = EALREADY;
27394 				break;
27395 			case TCPS_ESTABLISHED:
27396 				error = EISCONN;
27397 				break;
27398 			case TCPS_LISTEN:
27399 				error = EOPNOTSUPP;
27400 				break;
27401 			default:
27402 				error = EINVAL;
27403 				break;
27404 			}
27405 		} else {
27406 			error = proto_tlitosyserr(-error);
27407 		}
27408 	}
27409 done:
27410 	squeue_synch_exit(sqp, connp);
27411 
27412 	return ((error == 0) ? EINPROGRESS : error);
27413 }
27414 
27415 /* ARGSUSED */
27416 sock_lower_handle_t
27417 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
27418     uint_t *smodep, int *errorp, int flags, cred_t *credp)
27419 {
27420 	conn_t		*connp;
27421 	boolean_t	isv6 = family == AF_INET6;
27422 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
27423 	    (proto != 0 && proto != IPPROTO_TCP)) {
27424 		*errorp = EPROTONOSUPPORT;
27425 		return (NULL);
27426 	}
27427 
27428 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
27429 	if (connp == NULL) {
27430 		return (NULL);
27431 	}
27432 
27433 	/*
27434 	 * Put the ref for TCP. Ref for IP was already put
27435 	 * by ipcl_conn_create. Also Make the conn_t globally
27436 	 * visible to walkers
27437 	 */
27438 	mutex_enter(&connp->conn_lock);
27439 	CONN_INC_REF_LOCKED(connp);
27440 	ASSERT(connp->conn_ref == 2);
27441 	connp->conn_state_flags &= ~CONN_INCIPIENT;
27442 
27443 	connp->conn_flags |= IPCL_NONSTR;
27444 	mutex_exit(&connp->conn_lock);
27445 
27446 	ASSERT(errorp != NULL);
27447 	*errorp = 0;
27448 	*sock_downcalls = &sock_tcp_downcalls;
27449 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
27450 	    SM_SENDFILESUPP;
27451 
27452 	return ((sock_lower_handle_t)connp);
27453 }
27454 
27455 /* ARGSUSED */
27456 void
27457 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
27458     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
27459 {
27460 	conn_t *connp = (conn_t *)proto_handle;
27461 	struct sock_proto_props sopp;
27462 
27463 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
27464 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
27465 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
27466 
27467 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
27468 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
27469 	sopp.sopp_maxpsz = INFPSZ;
27470 	sopp.sopp_maxblk = INFPSZ;
27471 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
27472 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
27473 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
27474 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
27475 	    tcp_rinfo.mi_minpsz;
27476 
27477 	connp->conn_upcalls = sock_upcalls;
27478 	connp->conn_upper_handle = sock_handle;
27479 
27480 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
27481 }
27482 
27483 /* ARGSUSED */
27484 int
27485 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
27486 {
27487 	conn_t *connp = (conn_t *)proto_handle;
27488 
27489 	tcp_close_common(connp, flags);
27490 
27491 	ip_close_helper_stream(connp);
27492 
27493 	/*
27494 	 * Drop IP's reference on the conn. This is the last reference
27495 	 * on the connp if the state was less than established. If the
27496 	 * connection has gone into timewait state, then we will have
27497 	 * one ref for the TCP and one more ref (total of two) for the
27498 	 * classifier connected hash list (a timewait connections stays
27499 	 * in connected hash till closed).
27500 	 *
27501 	 * We can't assert the references because there might be other
27502 	 * transient reference places because of some walkers or queued
27503 	 * packets in squeue for the timewait state.
27504 	 */
27505 	CONN_DEC_REF(connp);
27506 	return (0);
27507 }
27508 
27509 /* ARGSUSED */
27510 int
27511 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
27512     cred_t *cr)
27513 {
27514 	tcp_t		*tcp;
27515 	uint32_t	msize;
27516 	conn_t *connp = (conn_t *)proto_handle;
27517 	int32_t		tcpstate;
27518 
27519 	ASSERT(connp->conn_ref >= 2);
27520 
27521 	if (msg->msg_controllen != 0) {
27522 		return (EOPNOTSUPP);
27523 
27524 	}
27525 	switch (DB_TYPE(mp)) {
27526 	case M_DATA:
27527 		tcp = connp->conn_tcp;
27528 		ASSERT(tcp != NULL);
27529 
27530 		tcpstate = tcp->tcp_state;
27531 		if (tcpstate < TCPS_ESTABLISHED) {
27532 			freemsg(mp);
27533 			return (ENOTCONN);
27534 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
27535 			freemsg(mp);
27536 			return (EPIPE);
27537 		}
27538 
27539 		if (is_system_labeled())
27540 			msg_setcredpid(mp, cr, curproc->p_pid);
27541 
27542 		/* XXX pass the size down and to the squeue */
27543 		msize = msgdsize(mp);
27544 
27545 		mutex_enter(&tcp->tcp_non_sq_lock);
27546 		tcp->tcp_squeue_bytes += msize;
27547 		/*
27548 		 * Squeue Flow Control
27549 		 */
27550 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
27551 			tcp_setqfull(tcp);
27552 		}
27553 		mutex_exit(&tcp->tcp_non_sq_lock);
27554 
27555 		/*
27556 		 * The application may pass in an address in the msghdr, but
27557 		 * we ignore the address on connection-oriented sockets.
27558 		 * Just like BSD this code does not generate an error for
27559 		 * TCP (a CONNREQUIRED socket) when sending to an address
27560 		 * passed in with sendto/sendmsg. Instead the data is
27561 		 * delivered on the connection as if no address had been
27562 		 * supplied.
27563 		 */
27564 		CONN_INC_REF(connp);
27565 
27566 		if (msg != NULL && msg->msg_flags & MSG_OOB) {
27567 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
27568 			    tcp_output_urgent, connp, tcp_squeue_flag,
27569 			    SQTAG_TCP_OUTPUT);
27570 		} else {
27571 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
27572 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
27573 		}
27574 
27575 		return (0);
27576 
27577 	default:
27578 		ASSERT(0);
27579 	}
27580 
27581 	freemsg(mp);
27582 	return (0);
27583 }
27584 
27585 /* ARGSUSED */
27586 void
27587 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
27588 {
27589 	int len;
27590 	uint32_t msize;
27591 	conn_t *connp = (conn_t *)arg;
27592 	tcp_t *tcp = connp->conn_tcp;
27593 
27594 	msize = msgdsize(mp);
27595 
27596 	len = msize - 1;
27597 	if (len < 0) {
27598 		freemsg(mp);
27599 		return;
27600 	}
27601 
27602 	/*
27603 	 * Try to force urgent data out on the wire.
27604 	 * Even if we have unsent data this will
27605 	 * at least send the urgent flag.
27606 	 * XXX does not handle more flag correctly.
27607 	 */
27608 	len += tcp->tcp_unsent;
27609 	len += tcp->tcp_snxt;
27610 	tcp->tcp_urg = len;
27611 	tcp->tcp_valid_bits |= TCP_URG_VALID;
27612 
27613 	/* Bypass tcp protocol for fused tcp loopback */
27614 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
27615 		return;
27616 	tcp_wput_data(tcp, mp, B_TRUE);
27617 }
27618 
27619 /* ARGSUSED */
27620 int
27621 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27622     socklen_t *addrlen, cred_t *cr)
27623 {
27624 	sin_t   *sin;
27625 	sin6_t  *sin6;
27626 	conn_t	*connp = (conn_t *)proto_handle;
27627 	tcp_t	*tcp = connp->conn_tcp;
27628 
27629 	ASSERT(tcp != NULL);
27630 	if (tcp->tcp_state < TCPS_SYN_RCVD)
27631 		return (ENOTCONN);
27632 
27633 	addr->sa_family = tcp->tcp_family;
27634 	switch (tcp->tcp_family) {
27635 	case AF_INET:
27636 		if (*addrlen < sizeof (sin_t))
27637 			return (EINVAL);
27638 
27639 		sin = (sin_t *)addr;
27640 		*sin = sin_null;
27641 		sin->sin_family = AF_INET;
27642 		if (tcp->tcp_ipversion == IPV4_VERSION) {
27643 			IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
27644 			    sin->sin_addr.s_addr);
27645 		}
27646 		sin->sin_port = tcp->tcp_fport;
27647 		*addrlen = sizeof (struct sockaddr_in);
27648 		break;
27649 	case AF_INET6:
27650 		sin6 = (sin6_t *)addr;
27651 		*sin6 = sin6_null;
27652 		sin6->sin6_family = AF_INET6;
27653 
27654 		if (*addrlen < sizeof (struct sockaddr_in6))
27655 			return (EINVAL);
27656 
27657 		if (tcp->tcp_ipversion == IPV6_VERSION) {
27658 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
27659 			    ~IPV6_VERS_AND_FLOW_MASK;
27660 		}
27661 
27662 		sin6->sin6_addr = tcp->tcp_remote_v6;
27663 		sin6->sin6_port = tcp->tcp_fport;
27664 		*addrlen = sizeof (struct sockaddr_in6);
27665 		break;
27666 	}
27667 	return (0);
27668 }
27669 
27670 /* ARGSUSED */
27671 int
27672 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27673     socklen_t *addrlenp, cred_t *cr)
27674 {
27675 	sin_t   *sin;
27676 	sin6_t  *sin6;
27677 	conn_t	*connp = (conn_t *)proto_handle;
27678 	tcp_t	*tcp = connp->conn_tcp;
27679 
27680 	switch (tcp->tcp_family) {
27681 	case AF_INET:
27682 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
27683 		if (*addrlenp < sizeof (sin_t))
27684 			return (EINVAL);
27685 		sin = (sin_t *)addr;
27686 		*sin = sin_null;
27687 		sin->sin_family = AF_INET;
27688 		*addrlenp = sizeof (sin_t);
27689 		if (tcp->tcp_state >= TCPS_BOUND) {
27690 			sin->sin_addr.s_addr =  tcp->tcp_ipha->ipha_src;
27691 			sin->sin_port = tcp->tcp_lport;
27692 		}
27693 		break;
27694 
27695 	case AF_INET6:
27696 		if (*addrlenp < sizeof (sin6_t))
27697 			return (EINVAL);
27698 		sin6 = (sin6_t *)addr;
27699 		*sin6 = sin6_null;
27700 		sin6->sin6_family = AF_INET6;
27701 		*addrlenp = sizeof (sin6_t);
27702 		if (tcp->tcp_state >= TCPS_BOUND) {
27703 			sin6->sin6_port = tcp->tcp_lport;
27704 			if (tcp->tcp_ipversion == IPV4_VERSION) {
27705 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
27706 				    &sin6->sin6_addr);
27707 			} else {
27708 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
27709 			}
27710 		}
27711 		break;
27712 	}
27713 	return (0);
27714 }
27715 
27716 /*
27717  * tcp_fallback
27718  *
27719  * A direct socket is falling back to using STREAMS. Hanging
27720  * off of the queue is a temporary tcp_t, which was created using
27721  * tcp_open(). The tcp_open() was called as part of the regular
27722  * sockfs create path, i.e., the SO_SOCKSTR flag is passed down,
27723  * and therefore the temporary tcp_t is marked to be a socket
27724  * (i.e., IPCL_SOCKET, tcp_issocket). So the optimizations
27725  * introduced by FireEngine will be used.
27726  *
27727  * The tcp_t associated with the socket falling back will
27728  * still be marked as a socket, although the direct socket flag
27729  * (IPCL_NONSTR) is removed. A fall back to true TPI semantics
27730  * will not take place until a _SIOCSOCKFALLBACK ioctl is issued.
27731  *
27732  * If the above mentioned behavior, i.e., the tmp tcp_t is created
27733  * as a STREAMS/TPI endpoint, then we will need to do more work here.
27734  * Such as inserting the direct socket into the acceptor hash.
27735  */
27736 void
27737 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
27738     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
27739 {
27740 	tcp_t			*tcp, *eager;
27741 	conn_t 			*connp = (conn_t *)proto_handle;
27742 	int			error;
27743 	struct T_capability_ack tca;
27744 	struct sockaddr_in6	laddr, faddr;
27745 	socklen_t 		laddrlen, faddrlen;
27746 	short			opts;
27747 	struct stroptions	*stropt;
27748 	mblk_t			*stropt_mp;
27749 	mblk_t			*mp;
27750 	mblk_t			*conn_ind_head = NULL;
27751 	mblk_t			*conn_ind_tail = NULL;
27752 	mblk_t			*ordrel_mp;
27753 	mblk_t			*fused_sigurp_mp;
27754 
27755 	tcp = connp->conn_tcp;
27756 	/*
27757 	 * No support for acceptor fallback
27758 	 */
27759 	ASSERT(q->q_qinfo != &tcp_acceptor_rinit);
27760 
27761 	stropt_mp = allocb_wait(sizeof (*stropt), BPRI_HI, STR_NOSIG, NULL);
27762 
27763 	/* Pre-allocate the T_ordrel_ind mblk. */
27764 	ASSERT(tcp->tcp_ordrel_mp == NULL);
27765 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
27766 	    STR_NOSIG, NULL);
27767 	ordrel_mp->b_datap->db_type = M_PROTO;
27768 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
27769 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
27770 
27771 	/* Pre-allocate the M_PCSIG anyway */
27772 	fused_sigurp_mp = allocb_wait(1, BPRI_HI, STR_NOSIG, NULL);
27773 
27774 	/*
27775 	 * Enter the squeue so that no new packets can come in
27776 	 */
27777 	error = squeue_synch_enter(connp->conn_sqp, connp, 0);
27778 	if (error != 0) {
27779 		/* failed to enter, free all the pre-allocated messages. */
27780 		freeb(stropt_mp);
27781 		freeb(ordrel_mp);
27782 		freeb(fused_sigurp_mp);
27783 		return;
27784 	}
27785 
27786 	/* Disable I/OAT during fallback */
27787 	tcp->tcp_sodirect = NULL;
27788 
27789 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
27790 	connp->conn_minor_arena = WR(q)->q_ptr;
27791 
27792 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
27793 
27794 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
27795 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
27796 
27797 	WR(q)->q_qinfo = &tcp_sock_winit;
27798 
27799 	if (!direct_sockfs)
27800 		tcp_disable_direct_sockfs(tcp);
27801 
27802 	/*
27803 	 * free the helper stream
27804 	 */
27805 	ip_close_helper_stream(connp);
27806 
27807 	/*
27808 	 * Notify the STREAM head about options
27809 	 */
27810 	DB_TYPE(stropt_mp) = M_SETOPTS;
27811 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27812 	stropt_mp->b_wptr += sizeof (struct stroptions);
27813 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27814 	stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
27815 
27816 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
27817 	    tcp->tcp_tcps->tcps_wroff_xtra);
27818 	if (tcp->tcp_snd_sack_ok)
27819 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
27820 	stropt->so_hiwat = tcp->tcp_fused ?
27821 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
27822 	    MAX(tcp->tcp_recv_hiwater, tcp->tcp_tcps->tcps_sth_rcv_hiwat);
27823 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
27824 
27825 	putnext(RD(q), stropt_mp);
27826 
27827 	/*
27828 	 * Collect the information needed to sync with the sonode
27829 	 */
27830 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
27831 
27832 	laddrlen = faddrlen = sizeof (sin6_t);
27833 	(void) tcp_getsockname(proto_handle, (struct sockaddr *)&laddr,
27834 	    &laddrlen, CRED());
27835 	error = tcp_getpeername(proto_handle, (struct sockaddr *)&faddr,
27836 	    &faddrlen, CRED());
27837 	if (error != 0)
27838 		faddrlen = 0;
27839 
27840 	opts = 0;
27841 	if (tcp->tcp_oobinline)
27842 		opts |= SO_OOBINLINE;
27843 	if (tcp->tcp_dontroute)
27844 		opts |= SO_DONTROUTE;
27845 
27846 	/*
27847 	 * Notify the socket that the protocol is now quiescent,
27848 	 * and it's therefore safe move data from the socket
27849 	 * to the stream head.
27850 	 */
27851 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
27852 	    (struct sockaddr *)&laddr, laddrlen,
27853 	    (struct sockaddr *)&faddr, faddrlen, opts);
27854 
27855 	while ((mp = tcp->tcp_rcv_list) != NULL) {
27856 		tcp->tcp_rcv_list = mp->b_next;
27857 		mp->b_next = NULL;
27858 		putnext(q, mp);
27859 	}
27860 	tcp->tcp_rcv_last_head = NULL;
27861 	tcp->tcp_rcv_last_tail = NULL;
27862 	tcp->tcp_rcv_cnt = 0;
27863 
27864 	/*
27865 	 * No longer a direct socket
27866 	 */
27867 	connp->conn_flags &= ~IPCL_NONSTR;
27868 
27869 	tcp->tcp_ordrel_mp = ordrel_mp;
27870 
27871 	if (tcp->tcp_fused) {
27872 		ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
27873 		tcp->tcp_fused_sigurg_mp = fused_sigurp_mp;
27874 	} else {
27875 		freeb(fused_sigurp_mp);
27876 	}
27877 
27878 	/*
27879 	 * Send T_CONN_IND messages for all ESTABLISHED connections.
27880 	 */
27881 	mutex_enter(&tcp->tcp_eager_lock);
27882 	for (eager = tcp->tcp_eager_next_q; eager != NULL;
27883 	    eager = eager->tcp_eager_next_q) {
27884 		mp = eager->tcp_conn.tcp_eager_conn_ind;
27885 
27886 		eager->tcp_conn.tcp_eager_conn_ind = NULL;
27887 		ASSERT(mp != NULL);
27888 		/*
27889 		 * TLI/XTI applications will get confused by
27890 		 * sending eager as an option since it violates
27891 		 * the option semantics. So remove the eager as
27892 		 * option since TLI/XTI app doesn't need it anyway.
27893 		 */
27894 		if (!TCP_IS_SOCKET(tcp)) {
27895 			struct T_conn_ind *conn_ind;
27896 
27897 			conn_ind = (struct T_conn_ind *)mp->b_rptr;
27898 			conn_ind->OPT_length = 0;
27899 			conn_ind->OPT_offset = 0;
27900 		}
27901 		if (conn_ind_head == NULL) {
27902 			conn_ind_head = mp;
27903 		} else {
27904 			conn_ind_tail->b_next = mp;
27905 		}
27906 		conn_ind_tail = mp;
27907 	}
27908 	mutex_exit(&tcp->tcp_eager_lock);
27909 
27910 	mp = conn_ind_head;
27911 	while (mp != NULL) {
27912 		mblk_t *nmp = mp->b_next;
27913 		mp->b_next = NULL;
27914 
27915 		putnext(tcp->tcp_rq, mp);
27916 		mp = nmp;
27917 	}
27918 
27919 	/*
27920 	 * There should be atleast two ref's (IP + TCP)
27921 	 */
27922 	ASSERT(connp->conn_ref >= 2);
27923 	squeue_synch_exit(connp->conn_sqp, connp);
27924 }
27925 
27926 /* ARGSUSED */
27927 static void
27928 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
27929 {
27930 	conn_t 	*connp = (conn_t *)arg;
27931 	tcp_t	*tcp = connp->conn_tcp;
27932 
27933 	freemsg(mp);
27934 
27935 	if (tcp->tcp_fused)
27936 		tcp_unfuse(tcp);
27937 
27938 	if (tcp_xmit_end(tcp) != 0) {
27939 		/*
27940 		 * We were crossing FINs and got a reset from
27941 		 * the other side. Just ignore it.
27942 		 */
27943 		if (tcp->tcp_debug) {
27944 			(void) strlog(TCP_MOD_ID, 0, 1,
27945 			    SL_ERROR|SL_TRACE,
27946 			    "tcp_shutdown_output() out of state %s",
27947 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
27948 		}
27949 	}
27950 }
27951 
27952 /* ARGSUSED */
27953 int
27954 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
27955 {
27956 	conn_t  *connp = (conn_t *)proto_handle;
27957 	tcp_t   *tcp = connp->conn_tcp;
27958 
27959 	/*
27960 	 * X/Open requires that we check the connected state.
27961 	 */
27962 	if (tcp->tcp_state < TCPS_SYN_SENT)
27963 		return (ENOTCONN);
27964 
27965 	/* shutdown the send side */
27966 	if (how != SHUT_RD) {
27967 		mblk_t *bp;
27968 
27969 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
27970 		CONN_INC_REF(connp);
27971 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
27972 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
27973 
27974 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27975 		    SOCK_OPCTL_SHUT_SEND, 0);
27976 	}
27977 
27978 	/* shutdown the recv side */
27979 	if (how != SHUT_WR)
27980 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27981 		    SOCK_OPCTL_SHUT_RECV, 0);
27982 
27983 	return (0);
27984 }
27985 
27986 /*
27987  * SOP_LISTEN() calls into tcp_listen().
27988  */
27989 /* ARGSUSED */
27990 int
27991 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27992 {
27993 	conn_t	*connp = (conn_t *)proto_handle;
27994 	int 	error;
27995 	squeue_t *sqp = connp->conn_sqp;
27996 
27997 	error = squeue_synch_enter(sqp, connp, 0);
27998 	if (error != 0) {
27999 		/* failed to enter */
28000 		return (ENOBUFS);
28001 	}
28002 
28003 	error = tcp_do_listen(connp, backlog, cr);
28004 	if (error == 0) {
28005 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
28006 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
28007 	} else if (error < 0) {
28008 		if (error == -TOUTSTATE)
28009 			error = EINVAL;
28010 		else
28011 			error = proto_tlitosyserr(-error);
28012 	}
28013 	squeue_synch_exit(sqp, connp);
28014 	return (error);
28015 }
28016 
28017 static int
28018 tcp_do_listen(conn_t *connp, int backlog, cred_t *cr)
28019 {
28020 	tcp_t		*tcp = connp->conn_tcp;
28021 	sin_t		*sin;
28022 	sin6_t  	*sin6;
28023 	int		error = 0;
28024 	tcp_stack_t	*tcps = tcp->tcp_tcps;
28025 
28026 	if (tcp->tcp_state >= TCPS_BOUND) {
28027 		if ((tcp->tcp_state == TCPS_BOUND ||
28028 		    tcp->tcp_state == TCPS_LISTEN) &&
28029 		    backlog > 0) {
28030 			/*
28031 			 * Handle listen() increasing backlog.
28032 			 * This is more "liberal" then what the TPI spec
28033 			 * requires but is needed to avoid a t_unbind
28034 			 * when handling listen() since the port number
28035 			 * might be "stolen" between the unbind and bind.
28036 			 */
28037 			goto do_listen;
28038 		}
28039 		if (tcp->tcp_debug) {
28040 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
28041 			    "tcp_bind: bad state, %d", tcp->tcp_state);
28042 		}
28043 		return (-TOUTSTATE);
28044 	} else {
28045 		int32_t len;
28046 		sin6_t	addr;
28047 
28048 		/* Do an implicit bind: Request for a generic port. */
28049 		if (tcp->tcp_family == AF_INET) {
28050 			len = sizeof (sin_t);
28051 			sin = (sin_t *)&addr;
28052 			*sin = sin_null;
28053 			sin->sin_family = AF_INET;
28054 			tcp->tcp_ipversion = IPV4_VERSION;
28055 		} else {
28056 			ASSERT(tcp->tcp_family == AF_INET6);
28057 			len = sizeof (sin6_t);
28058 			sin6 = (sin6_t *)&addr;
28059 			*sin6 = sin6_null;
28060 			sin6->sin6_family = AF_INET6;
28061 			tcp->tcp_ipversion = IPV6_VERSION;
28062 		}
28063 
28064 		error = tcp_bind_check(connp, (struct sockaddr *)&addr, len,
28065 		    cr, B_FALSE);
28066 		if (error)
28067 			return (error);
28068 		/* Fall through and do the fanout insertion */
28069 	}
28070 
28071 do_listen:
28072 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
28073 	tcp->tcp_conn_req_max = backlog;
28074 	if (tcp->tcp_conn_req_max) {
28075 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
28076 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
28077 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
28078 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
28079 		/*
28080 		 * If this is a listener, do not reset the eager list
28081 		 * and other stuffs.  Note that we don't check if the
28082 		 * existing eager list meets the new tcp_conn_req_max
28083 		 * requirement.
28084 		 */
28085 		if (tcp->tcp_state != TCPS_LISTEN) {
28086 			tcp->tcp_state = TCPS_LISTEN;
28087 			/* Initialize the chain. Don't need the eager_lock */
28088 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
28089 			tcp->tcp_eager_next_drop_q0 = tcp;
28090 			tcp->tcp_eager_prev_drop_q0 = tcp;
28091 			tcp->tcp_second_ctimer_threshold =
28092 			    tcps->tcps_ip_abort_linterval;
28093 		}
28094 	}
28095 
28096 	/*
28097 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
28098 	 * processing continues in tcp_rput_other().
28099 	 *
28100 	 * We need to make sure that the conn_recv is set to a non-null
28101 	 * value before we insert the conn into the classifier table.
28102 	 * This is to avoid a race with an incoming packet which does an
28103 	 * ipcl_classify().
28104 	 */
28105 	connp->conn_recv = tcp_conn_request;
28106 	if (tcp->tcp_family == AF_INET) {
28107 		error = ip_proto_bind_laddr_v4(connp, NULL,
28108 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
28109 	} else {
28110 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
28111 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
28112 	}
28113 	return (tcp_post_ip_bind(tcp, NULL, error));
28114 }
28115 
28116 void
28117 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
28118 {
28119 	conn_t  *connp = (conn_t *)proto_handle;
28120 	tcp_t	*tcp = connp->conn_tcp;
28121 	tcp_stack_t	*tcps = tcp->tcp_tcps;
28122 	uint_t thwin;
28123 
28124 	(void) squeue_synch_enter(connp->conn_sqp, connp, 0);
28125 
28126 	/* Flow control condition has been removed. */
28127 	tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
28128 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
28129 	    << tcp->tcp_rcv_ws;
28130 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
28131 	/*
28132 	 * Send back a window update immediately if TCP is above
28133 	 * ESTABLISHED state and the increase of the rcv window
28134 	 * that the other side knows is at least 1 MSS after flow
28135 	 * control is lifted.
28136 	 */
28137 	if (tcp->tcp_state >= TCPS_ESTABLISHED &&
28138 	    (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss)) {
28139 		tcp_xmit_ctl(NULL, tcp,
28140 		    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
28141 		    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
28142 		BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
28143 	}
28144 
28145 	squeue_synch_exit(connp->conn_sqp, connp);
28146 }
28147 
28148 /* ARGSUSED */
28149 int
28150 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
28151     int mode, int32_t *rvalp, cred_t *cr)
28152 {
28153 	conn_t  	*connp = (conn_t *)proto_handle;
28154 	int		error;
28155 
28156 	switch (cmd) {
28157 		case ND_SET:
28158 		case ND_GET:
28159 		case TCP_IOC_DEFAULT_Q:
28160 		case _SIOCSOCKFALLBACK:
28161 		case TCP_IOC_ABORT_CONN:
28162 		case TI_GETPEERNAME:
28163 		case TI_GETMYNAME:
28164 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
28165 			    cmd));
28166 			error = EINVAL;
28167 			break;
28168 		default:
28169 			/*
28170 			 * Pass on to IP using helper stream
28171 			 */
28172 			error = ldi_ioctl(
28173 			    connp->conn_helper_info->ip_helper_stream_handle,
28174 			    cmd, arg, mode, cr, rvalp);
28175 			break;
28176 	}
28177 	return (error);
28178 }
28179 
28180 sock_downcalls_t sock_tcp_downcalls = {
28181 	tcp_activate,
28182 	tcp_accept,
28183 	tcp_bind,
28184 	tcp_listen,
28185 	tcp_connect,
28186 	tcp_getpeername,
28187 	tcp_getsockname,
28188 	tcp_getsockopt,
28189 	tcp_setsockopt,
28190 	tcp_sendmsg,
28191 	NULL,
28192 	NULL,
28193 	NULL,
28194 	tcp_shutdown,
28195 	tcp_clr_flowctrl,
28196 	tcp_ioctl,
28197 	tcp_close,
28198 };
28199