xref: /titanic_50/usr/src/uts/common/inet/tcp/tcp.c (revision 3270659f55e0928d6edec3d26217cc29398a8149)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/strsun.h>
31 #include <sys/strsubr.h>
32 #include <sys/stropts.h>
33 #include <sys/strlog.h>
34 #define	_SUN_TPI_VERSION 2
35 #include <sys/tihdr.h>
36 #include <sys/timod.h>
37 #include <sys/ddi.h>
38 #include <sys/sunddi.h>
39 #include <sys/suntpi.h>
40 #include <sys/xti_inet.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/sdt.h>
44 #include <sys/vtrace.h>
45 #include <sys/kmem.h>
46 #include <sys/ethernet.h>
47 #include <sys/cpuvar.h>
48 #include <sys/dlpi.h>
49 #include <sys/multidata.h>
50 #include <sys/multidata_impl.h>
51 #include <sys/pattr.h>
52 #include <sys/policy.h>
53 #include <sys/priv.h>
54 #include <sys/zone.h>
55 #include <sys/sunldi.h>
56 
57 #include <sys/errno.h>
58 #include <sys/signal.h>
59 #include <sys/socket.h>
60 #include <sys/socketvar.h>
61 #include <sys/sockio.h>
62 #include <sys/isa_defs.h>
63 #include <sys/md5.h>
64 #include <sys/random.h>
65 #include <sys/sodirect.h>
66 #include <sys/uio.h>
67 #include <sys/systm.h>
68 #include <netinet/in.h>
69 #include <netinet/tcp.h>
70 #include <netinet/ip6.h>
71 #include <netinet/icmp6.h>
72 #include <net/if.h>
73 #include <net/route.h>
74 #include <inet/ipsec_impl.h>
75 
76 #include <inet/common.h>
77 #include <inet/ip.h>
78 #include <inet/ip_impl.h>
79 #include <inet/ip6.h>
80 #include <inet/ip_ndp.h>
81 #include <inet/proto_set.h>
82 #include <inet/mib2.h>
83 #include <inet/nd.h>
84 #include <inet/optcom.h>
85 #include <inet/snmpcom.h>
86 #include <inet/kstatcom.h>
87 #include <inet/tcp.h>
88 #include <inet/tcp_impl.h>
89 #include <inet/udp_impl.h>
90 #include <net/pfkeyv2.h>
91 #include <inet/ipsec_info.h>
92 #include <inet/ipdrop.h>
93 
94 #include <inet/ipclassifier.h>
95 #include <inet/ip_ire.h>
96 #include <inet/ip_ftable.h>
97 #include <inet/ip_if.h>
98 #include <inet/ipp_common.h>
99 #include <inet/ip_netinfo.h>
100 #include <sys/squeue_impl.h>
101 #include <sys/squeue.h>
102 #include <inet/kssl/ksslapi.h>
103 #include <sys/tsol/label.h>
104 #include <sys/tsol/tnet.h>
105 #include <rpc/pmap_prot.h>
106 #include <sys/callo.h>
107 
108 /*
109  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
110  *
111  * (Read the detailed design doc in PSARC case directory)
112  *
113  * The entire tcp state is contained in tcp_t and conn_t structure
114  * which are allocated in tandem using ipcl_conn_create() and passing
115  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
116  * the references on the tcp_t. The tcp_t structure is never compressed
117  * and packets always land on the correct TCP perimeter from the time
118  * eager is created till the time tcp_t dies (as such the old mentat
119  * TCP global queue is not used for detached state and no IPSEC checking
120  * is required). The global queue is still allocated to send out resets
121  * for connection which have no listeners and IP directly calls
122  * tcp_xmit_listeners_reset() which does any policy check.
123  *
124  * Protection and Synchronisation mechanism:
125  *
126  * The tcp data structure does not use any kind of lock for protecting
127  * its state but instead uses 'squeues' for mutual exclusion from various
128  * read and write side threads. To access a tcp member, the thread should
129  * always be behind squeue (via squeue_enter with flags as SQ_FILL, SQ_PROCESS,
130  * or SQ_NODRAIN). Since the squeues allow a direct function call, caller
131  * can pass any tcp function having prototype of edesc_t as argument
132  * (different from traditional STREAMs model where packets come in only
133  * designated entry points). The list of functions that can be directly
134  * called via squeue are listed before the usual function prototype.
135  *
136  * Referencing:
137  *
138  * TCP is MT-Hot and we use a reference based scheme to make sure that the
139  * tcp structure doesn't disappear when its needed. When the application
140  * creates an outgoing connection or accepts an incoming connection, we
141  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
142  * The IP reference is just a symbolic reference since ip_tcpclose()
143  * looks at tcp structure after tcp_close_output() returns which could
144  * have dropped the last TCP reference. So as long as the connection is
145  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
146  * conn_t. The classifier puts its own reference when the connection is
147  * inserted in listen or connected hash. Anytime a thread needs to enter
148  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
149  * on write side or by doing a classify on read side and then puts a
150  * reference on the conn before doing squeue_enter/tryenter/fill. For
151  * read side, the classifier itself puts the reference under fanout lock
152  * to make sure that tcp can't disappear before it gets processed. The
153  * squeue will drop this reference automatically so the called function
154  * doesn't have to do a DEC_REF.
155  *
156  * Opening a new connection:
157  *
158  * The outgoing connection open is pretty simple. tcp_open() does the
159  * work in creating the conn/tcp structure and initializing it. The
160  * squeue assignment is done based on the CPU the application
161  * is running on. So for outbound connections, processing is always done
162  * on application CPU which might be different from the incoming CPU
163  * being interrupted by the NIC. An optimal way would be to figure out
164  * the NIC <-> CPU binding at listen time, and assign the outgoing
165  * connection to the squeue attached to the CPU that will be interrupted
166  * for incoming packets (we know the NIC based on the bind IP address).
167  * This might seem like a problem if more data is going out but the
168  * fact is that in most cases the transmit is ACK driven transmit where
169  * the outgoing data normally sits on TCP's xmit queue waiting to be
170  * transmitted.
171  *
172  * Accepting a connection:
173  *
174  * This is a more interesting case because of various races involved in
175  * establishing a eager in its own perimeter. Read the meta comment on
176  * top of tcp_conn_request(). But briefly, the squeue is picked by
177  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
178  *
179  * Closing a connection:
180  *
181  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
182  * via squeue to do the close and mark the tcp as detached if the connection
183  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
184  * reference but tcp_close() drop IP's reference always. So if tcp was
185  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
186  * and 1 because it is in classifier's connected hash. This is the condition
187  * we use to determine that its OK to clean up the tcp outside of squeue
188  * when time wait expires (check the ref under fanout and conn_lock and
189  * if it is 2, remove it from fanout hash and kill it).
190  *
191  * Although close just drops the necessary references and marks the
192  * tcp_detached state, tcp_close needs to know the tcp_detached has been
193  * set (under squeue) before letting the STREAM go away (because a
194  * inbound packet might attempt to go up the STREAM while the close
195  * has happened and tcp_detached is not set). So a special lock and
196  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
197  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
198  * tcp_detached.
199  *
200  * Special provisions and fast paths:
201  *
202  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
203  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
204  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
205  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
206  * check to send packets directly to tcp_rput_data via squeue. Everyone
207  * else comes through tcp_input() on the read side.
208  *
209  * We also make special provisions for sockfs by marking tcp_issocket
210  * whenever we have only sockfs on top of TCP. This allows us to skip
211  * putting the tcp in acceptor hash since a sockfs listener can never
212  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
213  * since eager has already been allocated and the accept now happens
214  * on acceptor STREAM. There is a big blob of comment on top of
215  * tcp_conn_request explaining the new accept. When socket is POP'd,
216  * sockfs sends us an ioctl to mark the fact and we go back to old
217  * behaviour. Once tcp_issocket is unset, its never set for the
218  * life of that connection.
219  *
220  * In support of on-board asynchronous DMA hardware (e.g. Intel I/OAT)
221  * two consoldiation private KAPIs are used to enqueue M_DATA mblk_t's
222  * directly to the socket (sodirect) and start an asynchronous copyout
223  * to a user-land receive-side buffer (uioa) when a blocking socket read
224  * (e.g. read, recv, ...) is pending.
225  *
226  * This is accomplished when tcp_issocket is set and tcp_sodirect is not
227  * NULL so points to an sodirect_t and if marked enabled then we enqueue
228  * all mblk_t's directly to the socket.
229  *
230  * Further, if the sodirect_t sod_uioa and if marked enabled (due to a
231  * blocking socket read, e.g. user-land read, recv, ...) then an asynchronous
232  * copyout will be started directly to the user-land uio buffer. Also, as we
233  * have a pending read, TCP's push logic can take into account the number of
234  * bytes to be received and only awake the blocked read()er when the uioa_t
235  * byte count has been satisfied.
236  *
237  * IPsec notes :
238  *
239  * Since a packet is always executed on the correct TCP perimeter
240  * all IPsec processing is defered to IP including checking new
241  * connections and setting IPSEC policies for new connection. The
242  * only exception is tcp_xmit_listeners_reset() which is called
243  * directly from IP and needs to policy check to see if TH_RST
244  * can be sent out.
245  *
246  * PFHooks notes :
247  *
248  * For mdt case, one meta buffer contains multiple packets. Mblks for every
249  * packet are assembled and passed to the hooks. When packets are blocked,
250  * or boundary of any packet is changed, the mdt processing is stopped, and
251  * packets of the meta buffer are send to the IP path one by one.
252  */
253 
254 /*
255  * Values for squeue switch:
256  * 1: SQ_NODRAIN
257  * 2: SQ_PROCESS
258  * 3: SQ_FILL
259  */
260 int tcp_squeue_wput = 2;	/* /etc/systems */
261 int tcp_squeue_flag;
262 
263 /*
264  * Macros for sodirect:
265  *
266  * SOD_PTR_ENTER(tcp, sodp) - for the tcp_t pointer "tcp" set the
267  * sodirect_t pointer "sodp" to the socket/tcp shared sodirect_t
268  * if it exists and is enabled, else to NULL. Note, in the current
269  * sodirect implementation the sod_lockp must not be held across any
270  * STREAMS call (e.g. putnext) else a "recursive mutex_enter" PANIC
271  * will result as sod_lockp is the streamhead stdata.sd_lock.
272  *
273  * SOD_NOT_ENABLED(tcp) - return true if not a sodirect tcp_t or the
274  * sodirect_t isn't enabled, usefull for ASSERT()ing that a recieve
275  * side tcp code path dealing with a tcp_rcv_list or putnext() isn't
276  * being used when sodirect code paths should be.
277  */
278 
279 #define	SOD_PTR_ENTER(tcp, sodp)					\
280 	(sodp) = (tcp)->tcp_sodirect;					\
281 									\
282 	if ((sodp) != NULL) {						\
283 		mutex_enter((sodp)->sod_lockp);				\
284 		if (!((sodp)->sod_state & SOD_ENABLED)) {		\
285 			mutex_exit((sodp)->sod_lockp);			\
286 			(sodp) = NULL;					\
287 		}							\
288 	}
289 
290 #define	SOD_NOT_ENABLED(tcp)						\
291 	((tcp)->tcp_sodirect == NULL ||					\
292 	    !((tcp)->tcp_sodirect->sod_state & SOD_ENABLED))
293 
294 /*
295  * This controls how tiny a write must be before we try to copy it
296  * into the the mblk on the tail of the transmit queue.  Not much
297  * speedup is observed for values larger than sixteen.  Zero will
298  * disable the optimisation.
299  */
300 int tcp_tx_pull_len = 16;
301 
302 /*
303  * TCP Statistics.
304  *
305  * How TCP statistics work.
306  *
307  * There are two types of statistics invoked by two macros.
308  *
309  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
310  * supposed to be used in non MT-hot paths of the code.
311  *
312  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
313  * supposed to be used for DEBUG purposes and may be used on a hot path.
314  *
315  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
316  * (use "kstat tcp" to get them).
317  *
318  * There is also additional debugging facility that marks tcp_clean_death()
319  * instances and saves them in tcp_t structure. It is triggered by
320  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
321  * tcp_clean_death() calls that counts the number of times each tag was hit. It
322  * is triggered by TCP_CLD_COUNTERS define.
323  *
324  * How to add new counters.
325  *
326  * 1) Add a field in the tcp_stat structure describing your counter.
327  * 2) Add a line in the template in tcp_kstat2_init() with the name
328  *    of the counter.
329  *
330  *    IMPORTANT!! - make sure that both are in sync !!
331  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
332  *
333  * Please avoid using private counters which are not kstat-exported.
334  *
335  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
336  * in tcp_t structure.
337  *
338  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
339  */
340 
341 #ifndef TCP_DEBUG_COUNTER
342 #ifdef DEBUG
343 #define	TCP_DEBUG_COUNTER 1
344 #else
345 #define	TCP_DEBUG_COUNTER 0
346 #endif
347 #endif
348 
349 #define	TCP_CLD_COUNTERS 0
350 
351 #define	TCP_TAG_CLEAN_DEATH 1
352 #define	TCP_MAX_CLEAN_DEATH_TAG 32
353 
354 #ifdef lint
355 static int _lint_dummy_;
356 #endif
357 
358 #if TCP_CLD_COUNTERS
359 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
360 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
361 #elif defined(lint)
362 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
363 #else
364 #define	TCP_CLD_STAT(x)
365 #endif
366 
367 #if TCP_DEBUG_COUNTER
368 #define	TCP_DBGSTAT(tcps, x)	\
369 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
370 #define	TCP_G_DBGSTAT(x)	\
371 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
372 #elif defined(lint)
373 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
374 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
375 #else
376 #define	TCP_DBGSTAT(tcps, x)
377 #define	TCP_G_DBGSTAT(x)
378 #endif
379 
380 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
381 
382 tcp_g_stat_t	tcp_g_statistics;
383 kstat_t		*tcp_g_kstat;
384 
385 /*
386  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
387  * tcp write side.
388  */
389 #define	CALL_IP_WPUT(connp, q, mp) {					\
390 	ASSERT(((q)->q_flag & QREADR) == 0);				\
391 	TCP_DBGSTAT(connp->conn_netstack->netstack_tcp, tcp_ip_output);	\
392 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
393 }
394 
395 /* Macros for timestamp comparisons */
396 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
397 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
398 
399 /*
400  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
401  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
402  * by adding three components: a time component which grows by 1 every 4096
403  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
404  * a per-connection component which grows by 125000 for every new connection;
405  * and an "extra" component that grows by a random amount centered
406  * approximately on 64000.  This causes the the ISS generator to cycle every
407  * 4.89 hours if no TCP connections are made, and faster if connections are
408  * made.
409  *
410  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
411  * components: a time component which grows by 250000 every second; and
412  * a per-connection component which grows by 125000 for every new connections.
413  *
414  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
415  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
416  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
417  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
418  * password.
419  */
420 #define	ISS_INCR	250000
421 #define	ISS_NSEC_SHT	12
422 
423 static sin_t	sin_null;	/* Zero address for quick clears */
424 static sin6_t	sin6_null;	/* Zero address for quick clears */
425 
426 /*
427  * This implementation follows the 4.3BSD interpretation of the urgent
428  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
429  * incompatible changes in protocols like telnet and rlogin.
430  */
431 #define	TCP_OLD_URP_INTERPRETATION	1
432 
433 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
434 	(TCP_IS_DETACHED(tcp) && \
435 	    (!(tcp)->tcp_hard_binding))
436 
437 /*
438  * TCP reassembly macros.  We hide starting and ending sequence numbers in
439  * b_next and b_prev of messages on the reassembly queue.  The messages are
440  * chained using b_cont.  These macros are used in tcp_reass() so we don't
441  * have to see the ugly casts and assignments.
442  */
443 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
444 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
445 					(mblk_t *)(uintptr_t)(u))
446 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
447 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
448 					(mblk_t *)(uintptr_t)(u))
449 
450 /*
451  * Implementation of TCP Timers.
452  * =============================
453  *
454  * INTERFACE:
455  *
456  * There are two basic functions dealing with tcp timers:
457  *
458  *	timeout_id_t	tcp_timeout(connp, func, time)
459  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
460  *	TCP_TIMER_RESTART(tcp, intvl)
461  *
462  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
463  * after 'time' ticks passed. The function called by timeout() must adhere to
464  * the same restrictions as a driver soft interrupt handler - it must not sleep
465  * or call other functions that might sleep. The value returned is the opaque
466  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
467  * cancel the request. The call to tcp_timeout() may fail in which case it
468  * returns zero. This is different from the timeout(9F) function which never
469  * fails.
470  *
471  * The call-back function 'func' always receives 'connp' as its single
472  * argument. It is always executed in the squeue corresponding to the tcp
473  * structure. The tcp structure is guaranteed to be present at the time the
474  * call-back is called.
475  *
476  * NOTE: The call-back function 'func' is never called if tcp is in
477  * 	the TCPS_CLOSED state.
478  *
479  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
480  * request. locks acquired by the call-back routine should not be held across
481  * the call to tcp_timeout_cancel() or a deadlock may result.
482  *
483  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
484  * Otherwise, it returns an integer value greater than or equal to 0. In
485  * particular, if the call-back function is already placed on the squeue, it can
486  * not be canceled.
487  *
488  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
489  * 	within squeue context corresponding to the tcp instance. Since the
490  *	call-back is also called via the same squeue, there are no race
491  *	conditions described in untimeout(9F) manual page since all calls are
492  *	strictly serialized.
493  *
494  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
495  *	stored in tcp_timer_tid and starts a new one using
496  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
497  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
498  *	field.
499  *
500  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
501  *	call-back may still be called, so it is possible tcp_timer() will be
502  *	called several times. This should not be a problem since tcp_timer()
503  *	should always check the tcp instance state.
504  *
505  *
506  * IMPLEMENTATION:
507  *
508  * TCP timers are implemented using three-stage process. The call to
509  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
510  * when the timer expires. The tcp_timer_callback() arranges the call of the
511  * tcp_timer_handler() function via squeue corresponding to the tcp
512  * instance. The tcp_timer_handler() calls actual requested timeout call-back
513  * and passes tcp instance as an argument to it. Information is passed between
514  * stages using the tcp_timer_t structure which contains the connp pointer, the
515  * tcp call-back to call and the timeout id returned by the timeout(9F).
516  *
517  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
518  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
519  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
520  * returns the pointer to this mblk.
521  *
522  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
523  * looks like a normal mblk without actual dblk attached to it.
524  *
525  * To optimize performance each tcp instance holds a small cache of timer
526  * mblocks. In the current implementation it caches up to two timer mblocks per
527  * tcp instance. The cache is preserved over tcp frees and is only freed when
528  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
529  * timer processing happens on a corresponding squeue, the cache manipulation
530  * does not require any locks. Experiments show that majority of timer mblocks
531  * allocations are satisfied from the tcp cache and do not involve kmem calls.
532  *
533  * The tcp_timeout() places a refhold on the connp instance which guarantees
534  * that it will be present at the time the call-back function fires. The
535  * tcp_timer_handler() drops the reference after calling the call-back, so the
536  * call-back function does not need to manipulate the references explicitly.
537  */
538 
539 typedef struct tcp_timer_s {
540 	conn_t	*connp;
541 	void 	(*tcpt_proc)(void *);
542 	callout_id_t   tcpt_tid;
543 } tcp_timer_t;
544 
545 static kmem_cache_t *tcp_timercache;
546 kmem_cache_t	*tcp_sack_info_cache;
547 kmem_cache_t	*tcp_iphc_cache;
548 
549 /*
550  * For scalability, we must not run a timer for every TCP connection
551  * in TIME_WAIT state.  To see why, consider (for time wait interval of
552  * 4 minutes):
553  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
554  *
555  * This list is ordered by time, so you need only delete from the head
556  * until you get to entries which aren't old enough to delete yet.
557  * The list consists of only the detached TIME_WAIT connections.
558  *
559  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
560  * becomes detached TIME_WAIT (either by changing the state and already
561  * being detached or the other way around). This means that the TIME_WAIT
562  * state can be extended (up to doubled) if the connection doesn't become
563  * detached for a long time.
564  *
565  * The list manipulations (including tcp_time_wait_next/prev)
566  * are protected by the tcp_time_wait_lock. The content of the
567  * detached TIME_WAIT connections is protected by the normal perimeters.
568  *
569  * This list is per squeue and squeues are shared across the tcp_stack_t's.
570  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
571  * and conn_netstack.
572  * The tcp_t's that are added to tcp_free_list are disassociated and
573  * have NULL tcp_tcps and conn_netstack pointers.
574  */
575 typedef struct tcp_squeue_priv_s {
576 	kmutex_t	tcp_time_wait_lock;
577 	callout_id_t	tcp_time_wait_tid;
578 	tcp_t		*tcp_time_wait_head;
579 	tcp_t		*tcp_time_wait_tail;
580 	tcp_t		*tcp_free_list;
581 	uint_t		tcp_free_list_cnt;
582 } tcp_squeue_priv_t;
583 
584 /*
585  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
586  * Running it every 5 seconds seems to give the best results.
587  */
588 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
589 
590 /*
591  * To prevent memory hog, limit the number of entries in tcp_free_list
592  * to 1% of available memory / number of cpus
593  */
594 uint_t tcp_free_list_max_cnt = 0;
595 
596 #define	TCP_XMIT_LOWATER	4096
597 #define	TCP_XMIT_HIWATER	49152
598 #define	TCP_RECV_LOWATER	2048
599 #define	TCP_RECV_HIWATER	49152
600 
601 /*
602  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
603  */
604 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
605 
606 #define	TIDUSZ	4096	/* transport interface data unit size */
607 
608 /*
609  * Bind hash list size and has function.  It has to be a power of 2 for
610  * hashing.
611  */
612 #define	TCP_BIND_FANOUT_SIZE	512
613 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
614 /*
615  * Size of listen and acceptor hash list.  It has to be a power of 2 for
616  * hashing.
617  */
618 #define	TCP_FANOUT_SIZE		256
619 
620 #ifdef	_ILP32
621 #define	TCP_ACCEPTOR_HASH(accid)					\
622 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
623 #else
624 #define	TCP_ACCEPTOR_HASH(accid)					\
625 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
626 #endif	/* _ILP32 */
627 
628 #define	IP_ADDR_CACHE_SIZE	2048
629 #define	IP_ADDR_CACHE_HASH(faddr)					\
630 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
631 
632 /*
633  * TCP options struct returned from tcp_parse_options.
634  */
635 typedef struct tcp_opt_s {
636 	uint32_t	tcp_opt_mss;
637 	uint32_t	tcp_opt_wscale;
638 	uint32_t	tcp_opt_ts_val;
639 	uint32_t	tcp_opt_ts_ecr;
640 	tcp_t		*tcp;
641 } tcp_opt_t;
642 
643 /*
644  * TCP option struct passing information b/w lisenter and eager.
645  */
646 struct tcp_options {
647 	uint_t			to_flags;
648 	ssize_t			to_boundif;	/* IPV6_BOUND_IF */
649 };
650 
651 #define	TCPOPT_BOUNDIF		0x00000001	/* set IPV6_BOUND_IF */
652 #define	TCPOPT_RECVPKTINFO	0x00000002	/* set IPV6_RECVPKTINFO */
653 
654 /*
655  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
656  */
657 
658 #ifdef _BIG_ENDIAN
659 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
660 	(TCPOPT_TSTAMP << 8) | 10)
661 #else
662 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
663 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
664 #endif
665 
666 /*
667  * Flags returned from tcp_parse_options.
668  */
669 #define	TCP_OPT_MSS_PRESENT	1
670 #define	TCP_OPT_WSCALE_PRESENT	2
671 #define	TCP_OPT_TSTAMP_PRESENT	4
672 #define	TCP_OPT_SACK_OK_PRESENT	8
673 #define	TCP_OPT_SACK_PRESENT	16
674 
675 /* TCP option length */
676 #define	TCPOPT_NOP_LEN		1
677 #define	TCPOPT_MAXSEG_LEN	4
678 #define	TCPOPT_WS_LEN		3
679 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
680 #define	TCPOPT_TSTAMP_LEN	10
681 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
682 #define	TCPOPT_SACK_OK_LEN	2
683 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
684 #define	TCPOPT_REAL_SACK_LEN	4
685 #define	TCPOPT_MAX_SACK_LEN	36
686 #define	TCPOPT_HEADER_LEN	2
687 
688 /* TCP cwnd burst factor. */
689 #define	TCP_CWND_INFINITE	65535
690 #define	TCP_CWND_SS		3
691 #define	TCP_CWND_NORMAL		5
692 
693 /* Maximum TCP initial cwin (start/restart). */
694 #define	TCP_MAX_INIT_CWND	8
695 
696 /*
697  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
698  * either tcp_slow_start_initial or tcp_slow_start_after idle
699  * depending on the caller.  If the upper layer has not used the
700  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
701  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
702  * If the upper layer has changed set the tcp_init_cwnd, just use
703  * it to calculate the tcp_cwnd.
704  */
705 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
706 {									\
707 	if ((tcp)->tcp_init_cwnd == 0) {				\
708 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
709 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
710 	} else {							\
711 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
712 	}								\
713 	tcp->tcp_cwnd_cnt = 0;						\
714 }
715 
716 /* TCP Timer control structure */
717 typedef struct tcpt_s {
718 	pfv_t	tcpt_pfv;	/* The routine we are to call */
719 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
720 } tcpt_t;
721 
722 /*
723  * Functions called directly via squeue having a prototype of edesc_t.
724  */
725 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
726 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
727 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
728 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
729 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
730 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
731 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
732 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
733 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
734 void		tcp_output_urgent(void *arg, mblk_t *mp, void *arg2);
735 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
736 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
737 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
738 
739 
740 /* Prototype for TCP functions */
741 static void	tcp_random_init(void);
742 int		tcp_random(void);
743 static void	tcp_tli_accept(tcp_t *tcp, mblk_t *mp);
744 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
745 		    tcp_t *eager);
746 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
747 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
748     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
749     boolean_t user_specified);
750 static void	tcp_closei_local(tcp_t *tcp);
751 static void	tcp_close_detached(tcp_t *tcp);
752 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
753 			mblk_t *idmp, mblk_t **defermp);
754 static void	tcp_tpi_connect(tcp_t *tcp, mblk_t *mp);
755 static int	tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
756 		    in_port_t dstport, uint_t srcid, cred_t *cr, pid_t pid);
757 static int 	tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
758 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
759 		    uint32_t scope_id, cred_t *cr, pid_t pid);
760 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
761 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
762 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
763 static char	*tcp_display(tcp_t *tcp, char *, char);
764 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
765 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
766 static void	tcp_eager_unlink(tcp_t *tcp);
767 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
768 		    int unixerr);
769 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
770 		    int tlierr, int unixerr);
771 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
772 		    cred_t *cr);
773 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
774 		    char *value, caddr_t cp, cred_t *cr);
775 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
776 		    char *value, caddr_t cp, cred_t *cr);
777 static int	tcp_tpistate(tcp_t *tcp);
778 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
779     int caller_holds_lock);
780 static void	tcp_bind_hash_remove(tcp_t *tcp);
781 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
782 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
783 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
784 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
785 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
786 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
787 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
788 void		tcp_g_q_setup(tcp_stack_t *);
789 void		tcp_g_q_create(tcp_stack_t *);
790 void		tcp_g_q_destroy(tcp_stack_t *);
791 static int	tcp_header_init_ipv4(tcp_t *tcp);
792 static int	tcp_header_init_ipv6(tcp_t *tcp);
793 int		tcp_init(tcp_t *tcp, queue_t *q);
794 static int	tcp_init_values(tcp_t *tcp);
795 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
796 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
797 static void	tcp_ip_notify(tcp_t *tcp);
798 static mblk_t	*tcp_ire_mp(mblk_t **mpp);
799 static void	tcp_iss_init(tcp_t *tcp);
800 static void	tcp_keepalive_killer(void *arg);
801 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
802 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
803 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
804 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
805 static boolean_t tcp_allow_connopt_set(int level, int name);
806 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
807 int		tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
808 int		tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level,
809 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
810 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
811 		    mblk_t *mblk);
812 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
813 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
814 		    uchar_t *ptr, uint_t len);
815 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
816 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
817     tcp_stack_t *);
818 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
819 		    caddr_t cp, cred_t *cr);
820 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
821 		    caddr_t cp, cred_t *cr);
822 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
823 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
824 		    caddr_t cp, cred_t *cr);
825 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
826 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
827 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
828 static void	tcp_reinit(tcp_t *tcp);
829 static void	tcp_reinit_values(tcp_t *tcp);
830 
831 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
832 static uint_t	tcp_rcv_drain(tcp_t *tcp);
833 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
834 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
835 static void	tcp_ss_rexmit(tcp_t *tcp);
836 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
837 static void	tcp_process_options(tcp_t *, tcph_t *);
838 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
839 static void	tcp_rsrv(queue_t *q);
840 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
841 static int	tcp_snmp_state(tcp_t *tcp);
842 static void	tcp_timer(void *arg);
843 static void	tcp_timer_callback(void *);
844 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
845     boolean_t random);
846 static in_port_t tcp_get_next_priv_port(const tcp_t *);
847 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
848 static void	tcp_wput_fallback(queue_t *q, mblk_t *mp);
849 void		tcp_tpi_accept(queue_t *q, mblk_t *mp);
850 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
851 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
852 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
853 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
854 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
855 		    const int num_sack_blk, int *usable, uint_t *snxt,
856 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
857 		    const int mdt_thres);
858 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
859 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
860 		    const int num_sack_blk, int *usable, uint_t *snxt,
861 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
862 		    const int mdt_thres);
863 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
864 		    int num_sack_blk);
865 static void	tcp_wsrv(queue_t *q);
866 static int	tcp_xmit_end(tcp_t *tcp);
867 static void	tcp_ack_timer(void *arg);
868 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
869 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
870 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
871 		    zoneid_t zoneid, tcp_stack_t *, conn_t *connp);
872 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
873 		    uint32_t ack, int ctl);
874 static int	setmaxps(queue_t *q, int maxpsz);
875 static void	tcp_set_rto(tcp_t *, time_t);
876 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
877 		    boolean_t, boolean_t);
878 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
879 		    boolean_t ipsec_mctl);
880 static int	tcp_build_hdrs(tcp_t *);
881 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
882 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
883 		    tcph_t *tcph);
884 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
885 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
886 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
887 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
888 		    const boolean_t, const uint32_t, const uint32_t,
889 		    const uint32_t, const uint32_t, tcp_stack_t *);
890 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
891 		    const uint_t, const uint_t, boolean_t *);
892 static mblk_t	*tcp_lso_info_mp(mblk_t *);
893 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
894 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
895 extern mblk_t	*tcp_timermp_alloc(int);
896 extern void	tcp_timermp_free(tcp_t *);
897 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
898 static void	tcp_stop_lingering(tcp_t *tcp);
899 static void	tcp_close_linger_timeout(void *arg);
900 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
901 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
902 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
903 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
904 static void	tcp_g_kstat_fini(kstat_t *);
905 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
906 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
907 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
908 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
909 static int	tcp_kstat_update(kstat_t *kp, int rw);
910 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
911 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
912 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
913 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
914 			tcph_t *tcph, mblk_t *idmp);
915 static int	tcp_squeue_switch(int);
916 
917 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
918 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
919 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
920 static int	tcp_tpi_close(queue_t *, int);
921 static int	tcpclose_accept(queue_t *);
922 
923 static void	tcp_squeue_add(squeue_t *);
924 static boolean_t tcp_zcopy_check(tcp_t *);
925 static void	tcp_zcopy_notify(tcp_t *);
926 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
927 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
928 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
929 
930 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
931 
932 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
933 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
934 
935 static int tcp_accept(sock_lower_handle_t, sock_lower_handle_t,
936 	    sock_upper_handle_t, cred_t *);
937 static int tcp_listen(sock_lower_handle_t, int, cred_t *);
938 static int tcp_post_ip_bind(tcp_t *, mblk_t *, int, cred_t *, pid_t);
939 static int tcp_do_listen(conn_t *, int, cred_t *);
940 static int tcp_do_connect(conn_t *, const struct sockaddr *, socklen_t,
941     cred_t *, pid_t);
942 static int tcp_do_bind(conn_t *, struct sockaddr *, socklen_t, cred_t *,
943     boolean_t);
944 static int tcp_do_unbind(conn_t *);
945 static int tcp_bind_check(conn_t *, struct sockaddr *, socklen_t, cred_t *,
946     boolean_t);
947 
948 static void tcp_ulp_newconn(conn_t *, conn_t *, mblk_t *);
949 
950 /*
951  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
952  *
953  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
954  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
955  * (defined in tcp.h) needs to be filled in and passed into the kernel
956  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
957  * structure contains the four-tuple of a TCP connection and a range of TCP
958  * states (specified by ac_start and ac_end). The use of wildcard addresses
959  * and ports is allowed. Connections with a matching four tuple and a state
960  * within the specified range will be aborted. The valid states for the
961  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
962  * inclusive.
963  *
964  * An application which has its connection aborted by this ioctl will receive
965  * an error that is dependent on the connection state at the time of the abort.
966  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
967  * though a RST packet has been received.  If the connection state is equal to
968  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
969  * and all resources associated with the connection will be freed.
970  */
971 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
972 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
973 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
974 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
975 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
976 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
977     boolean_t, tcp_stack_t *);
978 
979 static struct module_info tcp_rinfo =  {
980 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
981 };
982 
983 static struct module_info tcp_winfo =  {
984 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
985 };
986 
987 /*
988  * Entry points for TCP as a device. The normal case which supports
989  * the TCP functionality.
990  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
991  */
992 struct qinit tcp_rinitv4 = {
993 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, NULL, &tcp_rinfo
994 };
995 
996 struct qinit tcp_rinitv6 = {
997 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_tpi_close, NULL, &tcp_rinfo
998 };
999 
1000 struct qinit tcp_winit = {
1001 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1002 };
1003 
1004 /* Initial entry point for TCP in socket mode. */
1005 struct qinit tcp_sock_winit = {
1006 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1007 };
1008 
1009 /* TCP entry point during fallback */
1010 struct qinit tcp_fallback_sock_winit = {
1011 	(pfi_t)tcp_wput_fallback, NULL, NULL, NULL, NULL, &tcp_winfo
1012 };
1013 
1014 /*
1015  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1016  * an accept. Avoid allocating data structures since eager has already
1017  * been created.
1018  */
1019 struct qinit tcp_acceptor_rinit = {
1020 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1021 };
1022 
1023 struct qinit tcp_acceptor_winit = {
1024 	(pfi_t)tcp_tpi_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1025 };
1026 
1027 /*
1028  * Entry points for TCP loopback (read side only)
1029  * The open routine is only used for reopens, thus no need to
1030  * have a separate one for tcp_openv6.
1031  */
1032 struct qinit tcp_loopback_rinit = {
1033 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, (pfi_t)0,
1034 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1035 };
1036 
1037 /* For AF_INET aka /dev/tcp */
1038 struct streamtab tcpinfov4 = {
1039 	&tcp_rinitv4, &tcp_winit
1040 };
1041 
1042 /* For AF_INET6 aka /dev/tcp6 */
1043 struct streamtab tcpinfov6 = {
1044 	&tcp_rinitv6, &tcp_winit
1045 };
1046 
1047 sock_downcalls_t sock_tcp_downcalls;
1048 
1049 /*
1050  * Have to ensure that tcp_g_q_close is not done by an
1051  * interrupt thread.
1052  */
1053 static taskq_t *tcp_taskq;
1054 
1055 /* Setable only in /etc/system. Move to ndd? */
1056 boolean_t tcp_icmp_source_quench = B_FALSE;
1057 
1058 /*
1059  * Following assumes TPI alignment requirements stay along 32 bit
1060  * boundaries
1061  */
1062 #define	ROUNDUP32(x) \
1063 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1064 
1065 /* Template for response to info request. */
1066 static struct T_info_ack tcp_g_t_info_ack = {
1067 	T_INFO_ACK,		/* PRIM_type */
1068 	0,			/* TSDU_size */
1069 	T_INFINITE,		/* ETSDU_size */
1070 	T_INVALID,		/* CDATA_size */
1071 	T_INVALID,		/* DDATA_size */
1072 	sizeof (sin_t),		/* ADDR_size */
1073 	0,			/* OPT_size - not initialized here */
1074 	TIDUSZ,			/* TIDU_size */
1075 	T_COTS_ORD,		/* SERV_type */
1076 	TCPS_IDLE,		/* CURRENT_state */
1077 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1078 };
1079 
1080 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1081 	T_INFO_ACK,		/* PRIM_type */
1082 	0,			/* TSDU_size */
1083 	T_INFINITE,		/* ETSDU_size */
1084 	T_INVALID,		/* CDATA_size */
1085 	T_INVALID,		/* DDATA_size */
1086 	sizeof (sin6_t),	/* ADDR_size */
1087 	0,			/* OPT_size - not initialized here */
1088 	TIDUSZ,		/* TIDU_size */
1089 	T_COTS_ORD,		/* SERV_type */
1090 	TCPS_IDLE,		/* CURRENT_state */
1091 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1092 };
1093 
1094 #define	MS	1L
1095 #define	SECONDS	(1000 * MS)
1096 #define	MINUTES	(60 * SECONDS)
1097 #define	HOURS	(60 * MINUTES)
1098 #define	DAYS	(24 * HOURS)
1099 
1100 #define	PARAM_MAX (~(uint32_t)0)
1101 
1102 /* Max size IP datagram is 64k - 1 */
1103 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1104 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1105 /* Max of the above */
1106 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1107 
1108 /* Largest TCP port number */
1109 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1110 
1111 /*
1112  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1113  * layer header.  It has to be a multiple of 4.
1114  */
1115 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1116 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1117 
1118 /*
1119  * All of these are alterable, within the min/max values given, at run time.
1120  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1121  * per the TCP spec.
1122  */
1123 /* BEGIN CSTYLED */
1124 static tcpparam_t	lcl_tcp_param_arr[] = {
1125  /*min		max		value		name */
1126  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1127  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1128  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1129  { 1,		1024,		1,		"tcp_conn_req_min" },
1130  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1131  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1132  { 0,		10,		0,		"tcp_debug" },
1133  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1134  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1135  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1136  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1137  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1138  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1139  { 1,		255,		64,		"tcp_ipv4_ttl"},
1140  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1141  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1142  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1143  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1144  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1145  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1146  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1147  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1148  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1149  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1150  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1151  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1152  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1153  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1154  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1155  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1156  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1157  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1158  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1159  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1160  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1161  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1162  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1163 /*
1164  * Question:  What default value should I set for tcp_strong_iss?
1165  */
1166  { 0,		2,		1,		"tcp_strong_iss"},
1167  { 0,		65536,		20,		"tcp_rtt_updates"},
1168  { 0,		1,		1,		"tcp_wscale_always"},
1169  { 0,		1,		0,		"tcp_tstamp_always"},
1170  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1171  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1172  { 0,		16,		2,		"tcp_deferred_acks_max"},
1173  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1174  { 1,		4,		4,		"tcp_slow_start_initial"},
1175  { 0,		2,		2,		"tcp_sack_permitted"},
1176  { 0,		1,		1,		"tcp_compression_enabled"},
1177  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1178  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1179  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1180  { 0,		1,		0,		"tcp_rev_src_routes"},
1181  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1182  { 0,		16,		8,		"tcp_local_dacks_max"},
1183  { 0,		2,		1,		"tcp_ecn_permitted"},
1184  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1185  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1186  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1187  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1188  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1189 };
1190 /* END CSTYLED */
1191 
1192 /*
1193  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1194  * each header fragment in the header buffer.  Each parameter value has
1195  * to be a multiple of 4 (32-bit aligned).
1196  */
1197 static tcpparam_t lcl_tcp_mdt_head_param =
1198 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1199 static tcpparam_t lcl_tcp_mdt_tail_param =
1200 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1201 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1202 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1203 
1204 /*
1205  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1206  * the maximum number of payload buffers associated per Multidata.
1207  */
1208 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1209 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1210 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1211 
1212 /* Round up the value to the nearest mss. */
1213 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1214 
1215 /*
1216  * Set ECN capable transport (ECT) code point in IP header.
1217  *
1218  * Note that there are 2 ECT code points '01' and '10', which are called
1219  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1220  * point ECT(0) for TCP as described in RFC 2481.
1221  */
1222 #define	SET_ECT(tcp, iph) \
1223 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1224 		/* We need to clear the code point first. */ \
1225 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1226 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1227 	} else { \
1228 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1229 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1230 	}
1231 
1232 /*
1233  * The format argument to pass to tcp_display().
1234  * DISP_PORT_ONLY means that the returned string has only port info.
1235  * DISP_ADDR_AND_PORT means that the returned string also contains the
1236  * remote and local IP address.
1237  */
1238 #define	DISP_PORT_ONLY		1
1239 #define	DISP_ADDR_AND_PORT	2
1240 
1241 #define	IS_VMLOANED_MBLK(mp) \
1242 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1243 
1244 
1245 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1246 boolean_t tcp_mdt_chain = B_TRUE;
1247 
1248 /*
1249  * MDT threshold in the form of effective send MSS multiplier; we take
1250  * the MDT path if the amount of unsent data exceeds the threshold value
1251  * (default threshold is 1*SMSS).
1252  */
1253 uint_t tcp_mdt_smss_threshold = 1;
1254 
1255 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1256 
1257 /*
1258  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1259  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1260  * determined dynamically during tcp_adapt_ire(), which is the default.
1261  */
1262 boolean_t tcp_static_maxpsz = B_FALSE;
1263 
1264 /* Setable in /etc/system */
1265 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1266 uint32_t tcp_random_anon_port = 1;
1267 
1268 /*
1269  * To reach to an eager in Q0 which can be dropped due to an incoming
1270  * new SYN request when Q0 is full, a new doubly linked list is
1271  * introduced. This list allows to select an eager from Q0 in O(1) time.
1272  * This is needed to avoid spending too much time walking through the
1273  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1274  * this new list has to be a member of Q0.
1275  * This list is headed by listener's tcp_t. When the list is empty,
1276  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1277  * of listener's tcp_t point to listener's tcp_t itself.
1278  *
1279  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1280  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1281  * These macros do not affect the eager's membership to Q0.
1282  */
1283 
1284 
1285 #define	MAKE_DROPPABLE(listener, eager)					\
1286 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1287 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1288 		    = (eager);						\
1289 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1290 		(eager)->tcp_eager_next_drop_q0 =			\
1291 		    (listener)->tcp_eager_next_drop_q0;			\
1292 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1293 	}
1294 
1295 #define	MAKE_UNDROPPABLE(eager)						\
1296 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1297 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1298 		    = (eager)->tcp_eager_prev_drop_q0;			\
1299 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1300 		    = (eager)->tcp_eager_next_drop_q0;			\
1301 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1302 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1303 	}
1304 
1305 /*
1306  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1307  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1308  * data, TCP will not respond with an ACK.  RFC 793 requires that
1309  * TCP responds with an ACK for such a bogus ACK.  By not following
1310  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1311  * an attacker successfully spoofs an acceptable segment to our
1312  * peer; or when our peer is "confused."
1313  */
1314 uint32_t tcp_drop_ack_unsent_cnt = 10;
1315 
1316 /*
1317  * Hook functions to enable cluster networking
1318  * On non-clustered systems these vectors must always be NULL.
1319  */
1320 
1321 void (*cl_inet_listen)(netstackid_t stack_id, uint8_t protocol,
1322 			    sa_family_t addr_family, uint8_t *laddrp,
1323 			    in_port_t lport, void *args) = NULL;
1324 void (*cl_inet_unlisten)(netstackid_t stack_id, uint8_t protocol,
1325 			    sa_family_t addr_family, uint8_t *laddrp,
1326 			    in_port_t lport, void *args) = NULL;
1327 
1328 int (*cl_inet_connect2)(netstackid_t stack_id, uint8_t protocol,
1329 			    boolean_t is_outgoing,
1330 			    sa_family_t addr_family,
1331 			    uint8_t *laddrp, in_port_t lport,
1332 			    uint8_t *faddrp, in_port_t fport,
1333 			    void *args) = NULL;
1334 
1335 void (*cl_inet_disconnect)(netstackid_t stack_id, uint8_t protocol,
1336 			    sa_family_t addr_family, uint8_t *laddrp,
1337 			    in_port_t lport, uint8_t *faddrp,
1338 			    in_port_t fport, void *args) = NULL;
1339 
1340 /*
1341  * The following are defined in ip.c
1342  */
1343 extern int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
1344 			    sa_family_t addr_family, uint8_t *laddrp,
1345 			    void *args);
1346 extern uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
1347 			    sa_family_t addr_family, uint8_t *laddrp,
1348 			    uint8_t *faddrp, void *args);
1349 
1350 
1351 /*
1352  * int CL_INET_CONNECT(conn_t *cp, tcp_t *tcp, boolean_t is_outgoing, int err)
1353  */
1354 #define	CL_INET_CONNECT(connp, tcp, is_outgoing, err) {		\
1355 	(err) = 0;						\
1356 	if (cl_inet_connect2 != NULL) {				\
1357 		/*						\
1358 		 * Running in cluster mode - register active connection	\
1359 		 * information						\
1360 		 */							\
1361 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1362 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1363 				(err) = (*cl_inet_connect2)(		\
1364 				    (connp)->conn_netstack->netstack_stackid,\
1365 				    IPPROTO_TCP, is_outgoing, AF_INET,	\
1366 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1367 				    (in_port_t)(tcp)->tcp_lport,	\
1368 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1369 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1370 			}						\
1371 		} else {						\
1372 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1373 			    &(tcp)->tcp_ip6h->ip6_src)) {		\
1374 				(err) = (*cl_inet_connect2)(		\
1375 				    (connp)->conn_netstack->netstack_stackid,\
1376 				    IPPROTO_TCP, is_outgoing, AF_INET6,	\
1377 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1378 				    (in_port_t)(tcp)->tcp_lport,	\
1379 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1380 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1381 			}						\
1382 		}							\
1383 	}								\
1384 }
1385 
1386 #define	CL_INET_DISCONNECT(connp, tcp)	{				\
1387 	if (cl_inet_disconnect != NULL) {				\
1388 		/*							\
1389 		 * Running in cluster mode - deregister active		\
1390 		 * connection information				\
1391 		 */							\
1392 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1393 			if ((tcp)->tcp_ip_src != 0) {			\
1394 				(*cl_inet_disconnect)(			\
1395 				    (connp)->conn_netstack->netstack_stackid,\
1396 				    IPPROTO_TCP, AF_INET,		\
1397 				    (uint8_t *)(&((tcp)->tcp_ip_src)),	\
1398 				    (in_port_t)(tcp)->tcp_lport,	\
1399 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1400 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1401 			}						\
1402 		} else {						\
1403 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1404 			    &(tcp)->tcp_ip_src_v6)) {			\
1405 				(*cl_inet_disconnect)(			\
1406 				    (connp)->conn_netstack->netstack_stackid,\
1407 				    IPPROTO_TCP, AF_INET6,		\
1408 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1409 				    (in_port_t)(tcp)->tcp_lport,	\
1410 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1411 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1412 			}						\
1413 		}							\
1414 	}								\
1415 }
1416 
1417 /*
1418  * Cluster networking hook for traversing current connection list.
1419  * This routine is used to extract the current list of live connections
1420  * which must continue to to be dispatched to this node.
1421  */
1422 int cl_tcp_walk_list(netstackid_t stack_id,
1423     int (*callback)(cl_tcp_info_t *, void *), void *arg);
1424 
1425 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1426     void *arg, tcp_stack_t *tcps);
1427 
1428 #define	DTRACE_IP_FASTPATH(mp, iph, ill, ipha, ip6h) 			\
1429 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,	\
1430 	    iph, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha,		\
1431 	    ip6_t *, ip6h, int, 0);
1432 
1433 /*
1434  * Figure out the value of window scale opton.  Note that the rwnd is
1435  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1436  * We cannot find the scale value and then do a round up of tcp_rwnd
1437  * because the scale value may not be correct after that.
1438  *
1439  * Set the compiler flag to make this function inline.
1440  */
1441 static void
1442 tcp_set_ws_value(tcp_t *tcp)
1443 {
1444 	int i;
1445 	uint32_t rwnd = tcp->tcp_rwnd;
1446 
1447 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1448 	    i++, rwnd >>= 1)
1449 		;
1450 	tcp->tcp_rcv_ws = i;
1451 }
1452 
1453 /*
1454  * Remove a connection from the list of detached TIME_WAIT connections.
1455  * It returns B_FALSE if it can't remove the connection from the list
1456  * as the connection has already been removed from the list due to an
1457  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1458  */
1459 static boolean_t
1460 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1461 {
1462 	boolean_t	locked = B_FALSE;
1463 
1464 	if (tcp_time_wait == NULL) {
1465 		tcp_time_wait = *((tcp_squeue_priv_t **)
1466 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1467 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1468 		locked = B_TRUE;
1469 	} else {
1470 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1471 	}
1472 
1473 	if (tcp->tcp_time_wait_expire == 0) {
1474 		ASSERT(tcp->tcp_time_wait_next == NULL);
1475 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1476 		if (locked)
1477 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1478 		return (B_FALSE);
1479 	}
1480 	ASSERT(TCP_IS_DETACHED(tcp));
1481 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1482 
1483 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1484 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1485 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1486 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1487 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1488 			    NULL;
1489 		} else {
1490 			tcp_time_wait->tcp_time_wait_tail = NULL;
1491 		}
1492 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1493 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1494 		ASSERT(tcp->tcp_time_wait_next == NULL);
1495 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1496 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1497 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1498 	} else {
1499 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1500 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1501 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1502 		    tcp->tcp_time_wait_next;
1503 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1504 		    tcp->tcp_time_wait_prev;
1505 	}
1506 	tcp->tcp_time_wait_next = NULL;
1507 	tcp->tcp_time_wait_prev = NULL;
1508 	tcp->tcp_time_wait_expire = 0;
1509 
1510 	if (locked)
1511 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1512 	return (B_TRUE);
1513 }
1514 
1515 /*
1516  * Add a connection to the list of detached TIME_WAIT connections
1517  * and set its time to expire.
1518  */
1519 static void
1520 tcp_time_wait_append(tcp_t *tcp)
1521 {
1522 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1523 	tcp_squeue_priv_t *tcp_time_wait =
1524 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1525 	    SQPRIVATE_TCP));
1526 
1527 	tcp_timers_stop(tcp);
1528 
1529 	/* Freed above */
1530 	ASSERT(tcp->tcp_timer_tid == 0);
1531 	ASSERT(tcp->tcp_ack_tid == 0);
1532 
1533 	/* must have happened at the time of detaching the tcp */
1534 	ASSERT(tcp->tcp_ptpahn == NULL);
1535 	ASSERT(tcp->tcp_flow_stopped == 0);
1536 	ASSERT(tcp->tcp_time_wait_next == NULL);
1537 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1538 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1539 	ASSERT(tcp->tcp_listener == NULL);
1540 
1541 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1542 	/*
1543 	 * The value computed below in tcp->tcp_time_wait_expire may
1544 	 * appear negative or wrap around. That is ok since our
1545 	 * interest is only in the difference between the current lbolt
1546 	 * value and tcp->tcp_time_wait_expire. But the value should not
1547 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1548 	 * The corresponding comparison in tcp_time_wait_collector() uses
1549 	 * modular arithmetic.
1550 	 */
1551 	tcp->tcp_time_wait_expire +=
1552 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1553 	if (tcp->tcp_time_wait_expire == 0)
1554 		tcp->tcp_time_wait_expire = 1;
1555 
1556 	ASSERT(TCP_IS_DETACHED(tcp));
1557 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1558 	ASSERT(tcp->tcp_time_wait_next == NULL);
1559 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1560 	TCP_DBGSTAT(tcps, tcp_time_wait);
1561 
1562 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1563 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1564 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1565 		tcp_time_wait->tcp_time_wait_head = tcp;
1566 	} else {
1567 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1568 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1569 		    TCPS_TIME_WAIT);
1570 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1571 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1572 	}
1573 	tcp_time_wait->tcp_time_wait_tail = tcp;
1574 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1575 }
1576 
1577 /* ARGSUSED */
1578 void
1579 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1580 {
1581 	conn_t	*connp = (conn_t *)arg;
1582 	tcp_t	*tcp = connp->conn_tcp;
1583 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1584 
1585 	ASSERT(tcp != NULL);
1586 	if (tcp->tcp_state == TCPS_CLOSED) {
1587 		return;
1588 	}
1589 
1590 	ASSERT((tcp->tcp_family == AF_INET &&
1591 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1592 	    (tcp->tcp_family == AF_INET6 &&
1593 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1594 	    tcp->tcp_ipversion == IPV6_VERSION)));
1595 	ASSERT(!tcp->tcp_listener);
1596 
1597 	TCP_STAT(tcps, tcp_time_wait_reap);
1598 	ASSERT(TCP_IS_DETACHED(tcp));
1599 
1600 	/*
1601 	 * Because they have no upstream client to rebind or tcp_close()
1602 	 * them later, we axe the connection here and now.
1603 	 */
1604 	tcp_close_detached(tcp);
1605 }
1606 
1607 /*
1608  * Remove cached/latched IPsec references.
1609  */
1610 void
1611 tcp_ipsec_cleanup(tcp_t *tcp)
1612 {
1613 	conn_t		*connp = tcp->tcp_connp;
1614 
1615 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1616 
1617 	if (connp->conn_latch != NULL) {
1618 		IPLATCH_REFRELE(connp->conn_latch,
1619 		    connp->conn_netstack);
1620 		connp->conn_latch = NULL;
1621 	}
1622 	if (connp->conn_policy != NULL) {
1623 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1624 		connp->conn_policy = NULL;
1625 	}
1626 }
1627 
1628 /*
1629  * Cleaup before placing on free list.
1630  * Disassociate from the netstack/tcp_stack_t since the freelist
1631  * is per squeue and not per netstack.
1632  */
1633 void
1634 tcp_cleanup(tcp_t *tcp)
1635 {
1636 	mblk_t		*mp;
1637 	char		*tcp_iphc;
1638 	int		tcp_iphc_len;
1639 	int		tcp_hdr_grown;
1640 	tcp_sack_info_t	*tcp_sack_info;
1641 	conn_t		*connp = tcp->tcp_connp;
1642 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1643 	netstack_t	*ns = tcps->tcps_netstack;
1644 	mblk_t		*tcp_rsrv_mp;
1645 
1646 	tcp_bind_hash_remove(tcp);
1647 
1648 	/* Cleanup that which needs the netstack first */
1649 	tcp_ipsec_cleanup(tcp);
1650 
1651 	tcp_free(tcp);
1652 
1653 	/* Release any SSL context */
1654 	if (tcp->tcp_kssl_ent != NULL) {
1655 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1656 		tcp->tcp_kssl_ent = NULL;
1657 	}
1658 
1659 	if (tcp->tcp_kssl_ctx != NULL) {
1660 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1661 		tcp->tcp_kssl_ctx = NULL;
1662 	}
1663 	tcp->tcp_kssl_pending = B_FALSE;
1664 
1665 	conn_delete_ire(connp, NULL);
1666 
1667 	/*
1668 	 * Since we will bzero the entire structure, we need to
1669 	 * remove it and reinsert it in global hash list. We
1670 	 * know the walkers can't get to this conn because we
1671 	 * had set CONDEMNED flag earlier and checked reference
1672 	 * under conn_lock so walker won't pick it and when we
1673 	 * go the ipcl_globalhash_remove() below, no walker
1674 	 * can get to it.
1675 	 */
1676 	ipcl_globalhash_remove(connp);
1677 
1678 	/*
1679 	 * Now it is safe to decrement the reference counts.
1680 	 * This might be the last reference on the netstack and TCPS
1681 	 * in which case it will cause the tcp_g_q_close and
1682 	 * the freeing of the IP Instance.
1683 	 */
1684 	connp->conn_netstack = NULL;
1685 	netstack_rele(ns);
1686 	ASSERT(tcps != NULL);
1687 	tcp->tcp_tcps = NULL;
1688 	TCPS_REFRELE(tcps);
1689 
1690 	/* Save some state */
1691 	mp = tcp->tcp_timercache;
1692 
1693 	tcp_sack_info = tcp->tcp_sack_info;
1694 	tcp_iphc = tcp->tcp_iphc;
1695 	tcp_iphc_len = tcp->tcp_iphc_len;
1696 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1697 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1698 
1699 	if (connp->conn_cred != NULL) {
1700 		crfree(connp->conn_cred);
1701 		connp->conn_cred = NULL;
1702 	}
1703 	if (connp->conn_peercred != NULL) {
1704 		crfree(connp->conn_peercred);
1705 		connp->conn_peercred = NULL;
1706 	}
1707 	ipcl_conn_cleanup(connp);
1708 	connp->conn_flags = IPCL_TCPCONN;
1709 	bzero(tcp, sizeof (tcp_t));
1710 
1711 	/* restore the state */
1712 	tcp->tcp_timercache = mp;
1713 
1714 	tcp->tcp_sack_info = tcp_sack_info;
1715 	tcp->tcp_iphc = tcp_iphc;
1716 	tcp->tcp_iphc_len = tcp_iphc_len;
1717 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1718 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1719 
1720 	tcp->tcp_connp = connp;
1721 
1722 	ASSERT(connp->conn_tcp == tcp);
1723 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1724 	connp->conn_state_flags = CONN_INCIPIENT;
1725 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1726 	ASSERT(connp->conn_ref == 1);
1727 }
1728 
1729 /*
1730  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1731  * is done forwards from the head.
1732  * This walks all stack instances since
1733  * tcp_time_wait remains global across all stacks.
1734  */
1735 /* ARGSUSED */
1736 void
1737 tcp_time_wait_collector(void *arg)
1738 {
1739 	tcp_t *tcp;
1740 	clock_t now;
1741 	mblk_t *mp;
1742 	conn_t *connp;
1743 	kmutex_t *lock;
1744 	boolean_t removed;
1745 
1746 	squeue_t *sqp = (squeue_t *)arg;
1747 	tcp_squeue_priv_t *tcp_time_wait =
1748 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1749 
1750 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1751 	tcp_time_wait->tcp_time_wait_tid = 0;
1752 
1753 	if (tcp_time_wait->tcp_free_list != NULL &&
1754 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1755 		TCP_G_STAT(tcp_freelist_cleanup);
1756 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1757 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1758 			tcp->tcp_time_wait_next = NULL;
1759 			tcp_time_wait->tcp_free_list_cnt--;
1760 			ASSERT(tcp->tcp_tcps == NULL);
1761 			CONN_DEC_REF(tcp->tcp_connp);
1762 		}
1763 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1764 	}
1765 
1766 	/*
1767 	 * In order to reap time waits reliably, we should use a
1768 	 * source of time that is not adjustable by the user -- hence
1769 	 * the call to ddi_get_lbolt().
1770 	 */
1771 	now = ddi_get_lbolt();
1772 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1773 		/*
1774 		 * Compare times using modular arithmetic, since
1775 		 * lbolt can wrapover.
1776 		 */
1777 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1778 			break;
1779 		}
1780 
1781 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1782 		ASSERT(removed);
1783 
1784 		connp = tcp->tcp_connp;
1785 		ASSERT(connp->conn_fanout != NULL);
1786 		lock = &connp->conn_fanout->connf_lock;
1787 		/*
1788 		 * This is essentially a TW reclaim fast path optimization for
1789 		 * performance where the timewait collector checks under the
1790 		 * fanout lock (so that no one else can get access to the
1791 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1792 		 * the classifier hash list. If ref count is indeed 2, we can
1793 		 * just remove the conn under the fanout lock and avoid
1794 		 * cleaning up the conn under the squeue, provided that
1795 		 * clustering callbacks are not enabled. If clustering is
1796 		 * enabled, we need to make the clustering callback before
1797 		 * setting the CONDEMNED flag and after dropping all locks and
1798 		 * so we forego this optimization and fall back to the slow
1799 		 * path. Also please see the comments in tcp_closei_local
1800 		 * regarding the refcnt logic.
1801 		 *
1802 		 * Since we are holding the tcp_time_wait_lock, its better
1803 		 * not to block on the fanout_lock because other connections
1804 		 * can't add themselves to time_wait list. So we do a
1805 		 * tryenter instead of mutex_enter.
1806 		 */
1807 		if (mutex_tryenter(lock)) {
1808 			mutex_enter(&connp->conn_lock);
1809 			if ((connp->conn_ref == 2) &&
1810 			    (cl_inet_disconnect == NULL)) {
1811 				ipcl_hash_remove_locked(connp,
1812 				    connp->conn_fanout);
1813 				/*
1814 				 * Set the CONDEMNED flag now itself so that
1815 				 * the refcnt cannot increase due to any
1816 				 * walker. But we have still not cleaned up
1817 				 * conn_ire_cache. This is still ok since
1818 				 * we are going to clean it up in tcp_cleanup
1819 				 * immediately and any interface unplumb
1820 				 * thread will wait till the ire is blown away
1821 				 */
1822 				connp->conn_state_flags |= CONN_CONDEMNED;
1823 				mutex_exit(lock);
1824 				mutex_exit(&connp->conn_lock);
1825 				if (tcp_time_wait->tcp_free_list_cnt <
1826 				    tcp_free_list_max_cnt) {
1827 					/* Add to head of tcp_free_list */
1828 					mutex_exit(
1829 					    &tcp_time_wait->tcp_time_wait_lock);
1830 					tcp_cleanup(tcp);
1831 					ASSERT(connp->conn_latch == NULL);
1832 					ASSERT(connp->conn_policy == NULL);
1833 					ASSERT(tcp->tcp_tcps == NULL);
1834 					ASSERT(connp->conn_netstack == NULL);
1835 
1836 					mutex_enter(
1837 					    &tcp_time_wait->tcp_time_wait_lock);
1838 					tcp->tcp_time_wait_next =
1839 					    tcp_time_wait->tcp_free_list;
1840 					tcp_time_wait->tcp_free_list = tcp;
1841 					tcp_time_wait->tcp_free_list_cnt++;
1842 					continue;
1843 				} else {
1844 					/* Do not add to tcp_free_list */
1845 					mutex_exit(
1846 					    &tcp_time_wait->tcp_time_wait_lock);
1847 					tcp_bind_hash_remove(tcp);
1848 					conn_delete_ire(tcp->tcp_connp, NULL);
1849 					tcp_ipsec_cleanup(tcp);
1850 					CONN_DEC_REF(tcp->tcp_connp);
1851 				}
1852 			} else {
1853 				CONN_INC_REF_LOCKED(connp);
1854 				mutex_exit(lock);
1855 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1856 				mutex_exit(&connp->conn_lock);
1857 				/*
1858 				 * We can reuse the closemp here since conn has
1859 				 * detached (otherwise we wouldn't even be in
1860 				 * time_wait list). tcp_closemp_used can safely
1861 				 * be changed without taking a lock as no other
1862 				 * thread can concurrently access it at this
1863 				 * point in the connection lifecycle.
1864 				 */
1865 
1866 				if (tcp->tcp_closemp.b_prev == NULL)
1867 					tcp->tcp_closemp_used = B_TRUE;
1868 				else
1869 					cmn_err(CE_PANIC,
1870 					    "tcp_timewait_collector: "
1871 					    "concurrent use of tcp_closemp: "
1872 					    "connp %p tcp %p\n", (void *)connp,
1873 					    (void *)tcp);
1874 
1875 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1876 				mp = &tcp->tcp_closemp;
1877 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1878 				    tcp_timewait_output, connp,
1879 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1880 			}
1881 		} else {
1882 			mutex_enter(&connp->conn_lock);
1883 			CONN_INC_REF_LOCKED(connp);
1884 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1885 			mutex_exit(&connp->conn_lock);
1886 			/*
1887 			 * We can reuse the closemp here since conn has
1888 			 * detached (otherwise we wouldn't even be in
1889 			 * time_wait list). tcp_closemp_used can safely
1890 			 * be changed without taking a lock as no other
1891 			 * thread can concurrently access it at this
1892 			 * point in the connection lifecycle.
1893 			 */
1894 
1895 			if (tcp->tcp_closemp.b_prev == NULL)
1896 				tcp->tcp_closemp_used = B_TRUE;
1897 			else
1898 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1899 				    "concurrent use of tcp_closemp: "
1900 				    "connp %p tcp %p\n", (void *)connp,
1901 				    (void *)tcp);
1902 
1903 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1904 			mp = &tcp->tcp_closemp;
1905 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1906 			    tcp_timewait_output, connp,
1907 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1908 		}
1909 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1910 	}
1911 
1912 	if (tcp_time_wait->tcp_free_list != NULL)
1913 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1914 
1915 	tcp_time_wait->tcp_time_wait_tid =
1916 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1917 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1918 	    CALLOUT_FLAG_ROUNDUP);
1919 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1920 }
1921 
1922 /*
1923  * Reply to a clients T_CONN_RES TPI message. This function
1924  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1925  * on the acceptor STREAM and processed in tcp_wput_accept().
1926  * Read the block comment on top of tcp_conn_request().
1927  */
1928 static void
1929 tcp_tli_accept(tcp_t *listener, mblk_t *mp)
1930 {
1931 	tcp_t	*acceptor;
1932 	tcp_t	*eager;
1933 	tcp_t   *tcp;
1934 	struct T_conn_res	*tcr;
1935 	t_uscalar_t	acceptor_id;
1936 	t_scalar_t	seqnum;
1937 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1938 	struct tcp_options *tcpopt;
1939 	mblk_t	*ok_mp;
1940 	mblk_t	*mp1;
1941 	tcp_stack_t	*tcps = listener->tcp_tcps;
1942 
1943 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1944 		tcp_err_ack(listener, mp, TPROTO, 0);
1945 		return;
1946 	}
1947 	tcr = (struct T_conn_res *)mp->b_rptr;
1948 
1949 	/*
1950 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1951 	 * read side queue of the streams device underneath us i.e. the
1952 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1953 	 * look it up in the queue_hash.  Under LP64 it sends down the
1954 	 * minor_t of the accepting endpoint.
1955 	 *
1956 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1957 	 * fanout hash lock is held.
1958 	 * This prevents any thread from entering the acceptor queue from
1959 	 * below (since it has not been hard bound yet i.e. any inbound
1960 	 * packets will arrive on the listener or default tcp queue and
1961 	 * go through tcp_lookup).
1962 	 * The CONN_INC_REF will prevent the acceptor from closing.
1963 	 *
1964 	 * XXX It is still possible for a tli application to send down data
1965 	 * on the accepting stream while another thread calls t_accept.
1966 	 * This should not be a problem for well-behaved applications since
1967 	 * the T_OK_ACK is sent after the queue swapping is completed.
1968 	 *
1969 	 * If the accepting fd is the same as the listening fd, avoid
1970 	 * queue hash lookup since that will return an eager listener in a
1971 	 * already established state.
1972 	 */
1973 	acceptor_id = tcr->ACCEPTOR_id;
1974 	mutex_enter(&listener->tcp_eager_lock);
1975 	if (listener->tcp_acceptor_id == acceptor_id) {
1976 		eager = listener->tcp_eager_next_q;
1977 		/* only count how many T_CONN_INDs so don't count q0 */
1978 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1979 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1980 			mutex_exit(&listener->tcp_eager_lock);
1981 			tcp_err_ack(listener, mp, TBADF, 0);
1982 			return;
1983 		}
1984 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1985 			/* Throw away all the eagers on q0. */
1986 			tcp_eager_cleanup(listener, 1);
1987 		}
1988 		if (listener->tcp_syn_defense) {
1989 			listener->tcp_syn_defense = B_FALSE;
1990 			if (listener->tcp_ip_addr_cache != NULL) {
1991 				kmem_free(listener->tcp_ip_addr_cache,
1992 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1993 				listener->tcp_ip_addr_cache = NULL;
1994 			}
1995 		}
1996 		/*
1997 		 * Transfer tcp_conn_req_max to the eager so that when
1998 		 * a disconnect occurs we can revert the endpoint to the
1999 		 * listen state.
2000 		 */
2001 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
2002 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
2003 		/*
2004 		 * Get a reference on the acceptor just like the
2005 		 * tcp_acceptor_hash_lookup below.
2006 		 */
2007 		acceptor = listener;
2008 		CONN_INC_REF(acceptor->tcp_connp);
2009 	} else {
2010 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
2011 		if (acceptor == NULL) {
2012 			if (listener->tcp_debug) {
2013 				(void) strlog(TCP_MOD_ID, 0, 1,
2014 				    SL_ERROR|SL_TRACE,
2015 				    "tcp_accept: did not find acceptor 0x%x\n",
2016 				    acceptor_id);
2017 			}
2018 			mutex_exit(&listener->tcp_eager_lock);
2019 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2020 			return;
2021 		}
2022 		/*
2023 		 * Verify acceptor state. The acceptable states for an acceptor
2024 		 * include TCPS_IDLE and TCPS_BOUND.
2025 		 */
2026 		switch (acceptor->tcp_state) {
2027 		case TCPS_IDLE:
2028 			/* FALLTHRU */
2029 		case TCPS_BOUND:
2030 			break;
2031 		default:
2032 			CONN_DEC_REF(acceptor->tcp_connp);
2033 			mutex_exit(&listener->tcp_eager_lock);
2034 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2035 			return;
2036 		}
2037 	}
2038 
2039 	/* The listener must be in TCPS_LISTEN */
2040 	if (listener->tcp_state != TCPS_LISTEN) {
2041 		CONN_DEC_REF(acceptor->tcp_connp);
2042 		mutex_exit(&listener->tcp_eager_lock);
2043 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2044 		return;
2045 	}
2046 
2047 	/*
2048 	 * Rendezvous with an eager connection request packet hanging off
2049 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2050 	 * tcp structure when the connection packet arrived in
2051 	 * tcp_conn_request().
2052 	 */
2053 	seqnum = tcr->SEQ_number;
2054 	eager = listener;
2055 	do {
2056 		eager = eager->tcp_eager_next_q;
2057 		if (eager == NULL) {
2058 			CONN_DEC_REF(acceptor->tcp_connp);
2059 			mutex_exit(&listener->tcp_eager_lock);
2060 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2061 			return;
2062 		}
2063 	} while (eager->tcp_conn_req_seqnum != seqnum);
2064 	mutex_exit(&listener->tcp_eager_lock);
2065 
2066 	/*
2067 	 * At this point, both acceptor and listener have 2 ref
2068 	 * that they begin with. Acceptor has one additional ref
2069 	 * we placed in lookup while listener has 3 additional
2070 	 * ref for being behind the squeue (tcp_accept() is
2071 	 * done on listener's squeue); being in classifier hash;
2072 	 * and eager's ref on listener.
2073 	 */
2074 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2075 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2076 
2077 	/*
2078 	 * The eager at this point is set in its own squeue and
2079 	 * could easily have been killed (tcp_accept_finish will
2080 	 * deal with that) because of a TH_RST so we can only
2081 	 * ASSERT for a single ref.
2082 	 */
2083 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2084 
2085 	/* Pre allocate the stroptions mblk also */
2086 	opt_mp = allocb(MAX(sizeof (struct tcp_options),
2087 	    sizeof (struct T_conn_res)), BPRI_HI);
2088 	if (opt_mp == NULL) {
2089 		CONN_DEC_REF(acceptor->tcp_connp);
2090 		CONN_DEC_REF(eager->tcp_connp);
2091 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2092 		return;
2093 	}
2094 	DB_TYPE(opt_mp) = M_SETOPTS;
2095 	opt_mp->b_wptr += sizeof (struct tcp_options);
2096 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
2097 	tcpopt->to_flags = 0;
2098 
2099 	/*
2100 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2101 	 * from listener to acceptor.
2102 	 */
2103 	if (listener->tcp_bound_if != 0) {
2104 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
2105 		tcpopt->to_boundif = listener->tcp_bound_if;
2106 	}
2107 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2108 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
2109 	}
2110 
2111 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2112 	if ((mp1 = copymsg(mp)) == NULL) {
2113 		CONN_DEC_REF(acceptor->tcp_connp);
2114 		CONN_DEC_REF(eager->tcp_connp);
2115 		freemsg(opt_mp);
2116 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2117 		return;
2118 	}
2119 
2120 	tcr = (struct T_conn_res *)mp1->b_rptr;
2121 
2122 	/*
2123 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2124 	 * which allocates a larger mblk and appends the new
2125 	 * local address to the ok_ack.  The address is copied by
2126 	 * soaccept() for getsockname().
2127 	 */
2128 	{
2129 		int extra;
2130 
2131 		extra = (eager->tcp_family == AF_INET) ?
2132 		    sizeof (sin_t) : sizeof (sin6_t);
2133 
2134 		/*
2135 		 * Try to re-use mp, if possible.  Otherwise, allocate
2136 		 * an mblk and return it as ok_mp.  In any case, mp
2137 		 * is no longer usable upon return.
2138 		 */
2139 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2140 			CONN_DEC_REF(acceptor->tcp_connp);
2141 			CONN_DEC_REF(eager->tcp_connp);
2142 			freemsg(opt_mp);
2143 			/* Original mp has been freed by now, so use mp1 */
2144 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2145 			return;
2146 		}
2147 
2148 		mp = NULL;	/* We should never use mp after this point */
2149 
2150 		switch (extra) {
2151 		case sizeof (sin_t): {
2152 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2153 
2154 				ok_mp->b_wptr += extra;
2155 				sin->sin_family = AF_INET;
2156 				sin->sin_port = eager->tcp_lport;
2157 				sin->sin_addr.s_addr =
2158 				    eager->tcp_ipha->ipha_src;
2159 				break;
2160 			}
2161 		case sizeof (sin6_t): {
2162 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2163 
2164 				ok_mp->b_wptr += extra;
2165 				sin6->sin6_family = AF_INET6;
2166 				sin6->sin6_port = eager->tcp_lport;
2167 				if (eager->tcp_ipversion == IPV4_VERSION) {
2168 					sin6->sin6_flowinfo = 0;
2169 					IN6_IPADDR_TO_V4MAPPED(
2170 					    eager->tcp_ipha->ipha_src,
2171 					    &sin6->sin6_addr);
2172 				} else {
2173 					ASSERT(eager->tcp_ip6h != NULL);
2174 					sin6->sin6_flowinfo =
2175 					    eager->tcp_ip6h->ip6_vcf &
2176 					    ~IPV6_VERS_AND_FLOW_MASK;
2177 					sin6->sin6_addr =
2178 					    eager->tcp_ip6h->ip6_src;
2179 				}
2180 				sin6->sin6_scope_id = 0;
2181 				sin6->__sin6_src_id = 0;
2182 				break;
2183 			}
2184 		default:
2185 			break;
2186 		}
2187 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2188 	}
2189 
2190 	/*
2191 	 * If there are no options we know that the T_CONN_RES will
2192 	 * succeed. However, we can't send the T_OK_ACK upstream until
2193 	 * the tcp_accept_swap is done since it would be dangerous to
2194 	 * let the application start using the new fd prior to the swap.
2195 	 */
2196 	tcp_accept_swap(listener, acceptor, eager);
2197 
2198 	/*
2199 	 * tcp_accept_swap unlinks eager from listener but does not drop
2200 	 * the eager's reference on the listener.
2201 	 */
2202 	ASSERT(eager->tcp_listener == NULL);
2203 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2204 
2205 	/*
2206 	 * The eager is now associated with its own queue. Insert in
2207 	 * the hash so that the connection can be reused for a future
2208 	 * T_CONN_RES.
2209 	 */
2210 	tcp_acceptor_hash_insert(acceptor_id, eager);
2211 
2212 	/*
2213 	 * We now do the processing of options with T_CONN_RES.
2214 	 * We delay till now since we wanted to have queue to pass to
2215 	 * option processing routines that points back to the right
2216 	 * instance structure which does not happen until after
2217 	 * tcp_accept_swap().
2218 	 *
2219 	 * Note:
2220 	 * The sanity of the logic here assumes that whatever options
2221 	 * are appropriate to inherit from listner=>eager are done
2222 	 * before this point, and whatever were to be overridden (or not)
2223 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2224 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2225 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2226 	 * This may not be true at this point in time but can be fixed
2227 	 * independently. This option processing code starts with
2228 	 * the instantiated acceptor instance and the final queue at
2229 	 * this point.
2230 	 */
2231 
2232 	if (tcr->OPT_length != 0) {
2233 		/* Options to process */
2234 		int t_error = 0;
2235 		int sys_error = 0;
2236 		int do_disconnect = 0;
2237 
2238 		if (tcp_conprim_opt_process(eager, mp1,
2239 		    &do_disconnect, &t_error, &sys_error) < 0) {
2240 			eager->tcp_accept_error = 1;
2241 			if (do_disconnect) {
2242 				/*
2243 				 * An option failed which does not allow
2244 				 * connection to be accepted.
2245 				 *
2246 				 * We allow T_CONN_RES to succeed and
2247 				 * put a T_DISCON_IND on the eager queue.
2248 				 */
2249 				ASSERT(t_error == 0 && sys_error == 0);
2250 				eager->tcp_send_discon_ind = 1;
2251 			} else {
2252 				ASSERT(t_error != 0);
2253 				freemsg(ok_mp);
2254 				/*
2255 				 * Original mp was either freed or set
2256 				 * to ok_mp above, so use mp1 instead.
2257 				 */
2258 				tcp_err_ack(listener, mp1, t_error, sys_error);
2259 				goto finish;
2260 			}
2261 		}
2262 		/*
2263 		 * Most likely success in setting options (except if
2264 		 * eager->tcp_send_discon_ind set).
2265 		 * mp1 option buffer represented by OPT_length/offset
2266 		 * potentially modified and contains results of setting
2267 		 * options at this point
2268 		 */
2269 	}
2270 
2271 	/* We no longer need mp1, since all options processing has passed */
2272 	freemsg(mp1);
2273 
2274 	putnext(listener->tcp_rq, ok_mp);
2275 
2276 	mutex_enter(&listener->tcp_eager_lock);
2277 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2278 		tcp_t	*tail;
2279 		mblk_t	*conn_ind;
2280 
2281 		/*
2282 		 * This path should not be executed if listener and
2283 		 * acceptor streams are the same.
2284 		 */
2285 		ASSERT(listener != acceptor);
2286 
2287 		tcp = listener->tcp_eager_prev_q0;
2288 		/*
2289 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2290 		 * deferred T_conn_ind queue. We need to get to the head of
2291 		 * the queue in order to send up T_conn_ind the same order as
2292 		 * how the 3WHS is completed.
2293 		 */
2294 		while (tcp != listener) {
2295 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2296 				break;
2297 			else
2298 				tcp = tcp->tcp_eager_prev_q0;
2299 		}
2300 		ASSERT(tcp != listener);
2301 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2302 		ASSERT(conn_ind != NULL);
2303 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2304 
2305 		/* Move from q0 to q */
2306 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2307 		listener->tcp_conn_req_cnt_q0--;
2308 		listener->tcp_conn_req_cnt_q++;
2309 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2310 		    tcp->tcp_eager_prev_q0;
2311 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2312 		    tcp->tcp_eager_next_q0;
2313 		tcp->tcp_eager_prev_q0 = NULL;
2314 		tcp->tcp_eager_next_q0 = NULL;
2315 		tcp->tcp_conn_def_q0 = B_FALSE;
2316 
2317 		/* Make sure the tcp isn't in the list of droppables */
2318 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2319 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2320 
2321 		/*
2322 		 * Insert at end of the queue because sockfs sends
2323 		 * down T_CONN_RES in chronological order. Leaving
2324 		 * the older conn indications at front of the queue
2325 		 * helps reducing search time.
2326 		 */
2327 		tail = listener->tcp_eager_last_q;
2328 		if (tail != NULL)
2329 			tail->tcp_eager_next_q = tcp;
2330 		else
2331 			listener->tcp_eager_next_q = tcp;
2332 		listener->tcp_eager_last_q = tcp;
2333 		tcp->tcp_eager_next_q = NULL;
2334 		mutex_exit(&listener->tcp_eager_lock);
2335 		putnext(tcp->tcp_rq, conn_ind);
2336 	} else {
2337 		mutex_exit(&listener->tcp_eager_lock);
2338 	}
2339 
2340 	/*
2341 	 * Done with the acceptor - free it
2342 	 *
2343 	 * Note: from this point on, no access to listener should be made
2344 	 * as listener can be equal to acceptor.
2345 	 */
2346 finish:
2347 	ASSERT(acceptor->tcp_detached);
2348 	ASSERT(tcps->tcps_g_q != NULL);
2349 	ASSERT(!IPCL_IS_NONSTR(acceptor->tcp_connp));
2350 	acceptor->tcp_rq = tcps->tcps_g_q;
2351 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2352 	(void) tcp_clean_death(acceptor, 0, 2);
2353 	CONN_DEC_REF(acceptor->tcp_connp);
2354 
2355 	/*
2356 	 * In case we already received a FIN we have to make tcp_rput send
2357 	 * the ordrel_ind. This will also send up a window update if the window
2358 	 * has opened up.
2359 	 *
2360 	 * In the normal case of a successful connection acceptance
2361 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2362 	 * indication that this was just accepted. This tells tcp_rput to
2363 	 * pass up any data queued in tcp_rcv_list.
2364 	 *
2365 	 * In the fringe case where options sent with T_CONN_RES failed and
2366 	 * we required, we would be indicating a T_DISCON_IND to blow
2367 	 * away this connection.
2368 	 */
2369 
2370 	/*
2371 	 * XXX: we currently have a problem if XTI application closes the
2372 	 * acceptor stream in between. This problem exists in on10-gate also
2373 	 * and is well know but nothing can be done short of major rewrite
2374 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2375 	 * eager same squeue as listener (we can distinguish non socket
2376 	 * listeners at the time of handling a SYN in tcp_conn_request)
2377 	 * and do most of the work that tcp_accept_finish does here itself
2378 	 * and then get behind the acceptor squeue to access the acceptor
2379 	 * queue.
2380 	 */
2381 	/*
2382 	 * We already have a ref on tcp so no need to do one before squeue_enter
2383 	 */
2384 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, opt_mp, tcp_accept_finish,
2385 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_ACCEPT_FINISH);
2386 }
2387 
2388 /*
2389  * Swap information between the eager and acceptor for a TLI/XTI client.
2390  * The sockfs accept is done on the acceptor stream and control goes
2391  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2392  * called. In either case, both the eager and listener are in their own
2393  * perimeter (squeue) and the code has to deal with potential race.
2394  *
2395  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2396  */
2397 static void
2398 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2399 {
2400 	conn_t	*econnp, *aconnp;
2401 
2402 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2403 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2404 	ASSERT(!eager->tcp_hard_bound);
2405 	ASSERT(!TCP_IS_SOCKET(acceptor));
2406 	ASSERT(!TCP_IS_SOCKET(eager));
2407 	ASSERT(!TCP_IS_SOCKET(listener));
2408 
2409 	acceptor->tcp_detached = B_TRUE;
2410 	/*
2411 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2412 	 * the acceptor id.
2413 	 */
2414 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2415 
2416 	/* remove eager from listen list... */
2417 	mutex_enter(&listener->tcp_eager_lock);
2418 	tcp_eager_unlink(eager);
2419 	ASSERT(eager->tcp_eager_next_q == NULL &&
2420 	    eager->tcp_eager_last_q == NULL);
2421 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2422 	    eager->tcp_eager_prev_q0 == NULL);
2423 	mutex_exit(&listener->tcp_eager_lock);
2424 	eager->tcp_rq = acceptor->tcp_rq;
2425 	eager->tcp_wq = acceptor->tcp_wq;
2426 
2427 	econnp = eager->tcp_connp;
2428 	aconnp = acceptor->tcp_connp;
2429 
2430 	eager->tcp_rq->q_ptr = econnp;
2431 	eager->tcp_wq->q_ptr = econnp;
2432 
2433 	/*
2434 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2435 	 * which might be a different squeue from our peer TCP instance.
2436 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2437 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2438 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2439 	 * above reach global visibility prior to the clearing of tcp_detached.
2440 	 */
2441 	membar_producer();
2442 	eager->tcp_detached = B_FALSE;
2443 
2444 	ASSERT(eager->tcp_ack_tid == 0);
2445 
2446 	econnp->conn_dev = aconnp->conn_dev;
2447 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2448 	ASSERT(econnp->conn_minor_arena != NULL);
2449 	if (eager->tcp_cred != NULL)
2450 		crfree(eager->tcp_cred);
2451 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2452 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2453 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2454 
2455 	aconnp->conn_cred = NULL;
2456 
2457 	econnp->conn_zoneid = aconnp->conn_zoneid;
2458 	econnp->conn_allzones = aconnp->conn_allzones;
2459 
2460 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2461 	aconnp->conn_mac_exempt = B_FALSE;
2462 
2463 	ASSERT(aconnp->conn_peercred == NULL);
2464 
2465 	/* Do the IPC initialization */
2466 	CONN_INC_REF(econnp);
2467 
2468 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2469 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2470 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2471 
2472 	/* Done with old IPC. Drop its ref on its connp */
2473 	CONN_DEC_REF(aconnp);
2474 }
2475 
2476 
2477 /*
2478  * Adapt to the information, such as rtt and rtt_sd, provided from the
2479  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2480  *
2481  * Checks for multicast and broadcast destination address.
2482  * Returns zero on failure; non-zero if ok.
2483  *
2484  * Note that the MSS calculation here is based on the info given in
2485  * the IRE.  We do not do any calculation based on TCP options.  They
2486  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2487  * knows which options to use.
2488  *
2489  * Note on how TCP gets its parameters for a connection.
2490  *
2491  * When a tcp_t structure is allocated, it gets all the default parameters.
2492  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2493  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2494  * default.
2495  *
2496  * An incoming SYN with a multicast or broadcast destination address, is dropped
2497  * in 1 of 2 places.
2498  *
2499  * 1. If the packet was received over the wire it is dropped in
2500  * ip_rput_process_broadcast()
2501  *
2502  * 2. If the packet was received through internal IP loopback, i.e. the packet
2503  * was generated and received on the same machine, it is dropped in
2504  * ip_wput_local()
2505  *
2506  * An incoming SYN with a multicast or broadcast source address is always
2507  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2508  * reject an attempt to connect to a broadcast or multicast (destination)
2509  * address.
2510  */
2511 static int
2512 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2513 {
2514 	ire_t		*ire;
2515 	ire_t		*sire = NULL;
2516 	iulp_t		*ire_uinfo = NULL;
2517 	uint32_t	mss_max;
2518 	uint32_t	mss;
2519 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2520 	conn_t		*connp = tcp->tcp_connp;
2521 	boolean_t	ire_cacheable = B_FALSE;
2522 	zoneid_t	zoneid = connp->conn_zoneid;
2523 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2524 	    MATCH_IRE_SECATTR;
2525 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2526 	ill_t		*ill = NULL;
2527 	boolean_t	incoming = (ire_mp == NULL);
2528 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2529 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2530 
2531 	ASSERT(connp->conn_ire_cache == NULL);
2532 
2533 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2534 
2535 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2536 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2537 			return (0);
2538 		}
2539 		/*
2540 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2541 		 * for the destination with the nexthop as gateway.
2542 		 * ire_ctable_lookup() is used because this particular
2543 		 * ire, if it exists, will be marked private.
2544 		 * If that is not available, use the interface ire
2545 		 * for the nexthop.
2546 		 *
2547 		 * TSol: tcp_update_label will detect label mismatches based
2548 		 * only on the destination's label, but that would not
2549 		 * detect label mismatches based on the security attributes
2550 		 * of routes or next hop gateway. Hence we need to pass the
2551 		 * label to ire_ftable_lookup below in order to locate the
2552 		 * right prefix (and/or) ire cache. Similarly we also need
2553 		 * pass the label to the ire_cache_lookup below to locate
2554 		 * the right ire that also matches on the label.
2555 		 */
2556 		if (tcp->tcp_connp->conn_nexthop_set) {
2557 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2558 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2559 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2560 			    ipst);
2561 			if (ire == NULL) {
2562 				ire = ire_ftable_lookup(
2563 				    tcp->tcp_connp->conn_nexthop_v4,
2564 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2565 				    tsl, match_flags, ipst);
2566 				if (ire == NULL)
2567 					return (0);
2568 			} else {
2569 				ire_uinfo = &ire->ire_uinfo;
2570 			}
2571 		} else {
2572 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2573 			    zoneid, tsl, ipst);
2574 			if (ire != NULL) {
2575 				ire_cacheable = B_TRUE;
2576 				ire_uinfo = (ire_mp != NULL) ?
2577 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2578 				    &ire->ire_uinfo;
2579 
2580 			} else {
2581 				if (ire_mp == NULL) {
2582 					ire = ire_ftable_lookup(
2583 					    tcp->tcp_connp->conn_rem,
2584 					    0, 0, 0, NULL, &sire, zoneid, 0,
2585 					    tsl, (MATCH_IRE_RECURSIVE |
2586 					    MATCH_IRE_DEFAULT), ipst);
2587 					if (ire == NULL)
2588 						return (0);
2589 					ire_uinfo = (sire != NULL) ?
2590 					    &sire->ire_uinfo :
2591 					    &ire->ire_uinfo;
2592 				} else {
2593 					ire = (ire_t *)ire_mp->b_rptr;
2594 					ire_uinfo =
2595 					    &((ire_t *)
2596 					    ire_mp->b_rptr)->ire_uinfo;
2597 				}
2598 			}
2599 		}
2600 		ASSERT(ire != NULL);
2601 
2602 		if ((ire->ire_src_addr == INADDR_ANY) ||
2603 		    (ire->ire_type & IRE_BROADCAST)) {
2604 			/*
2605 			 * ire->ire_mp is non null when ire_mp passed in is used
2606 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2607 			 */
2608 			if (ire->ire_mp == NULL)
2609 				ire_refrele(ire);
2610 			if (sire != NULL)
2611 				ire_refrele(sire);
2612 			return (0);
2613 		}
2614 
2615 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2616 			ipaddr_t src_addr;
2617 
2618 			/*
2619 			 * ip_bind_connected() has stored the correct source
2620 			 * address in conn_src.
2621 			 */
2622 			src_addr = tcp->tcp_connp->conn_src;
2623 			tcp->tcp_ipha->ipha_src = src_addr;
2624 			/*
2625 			 * Copy of the src addr. in tcp_t is needed
2626 			 * for the lookup funcs.
2627 			 */
2628 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2629 		}
2630 		/*
2631 		 * Set the fragment bit so that IP will tell us if the MTU
2632 		 * should change. IP tells us the latest setting of
2633 		 * ip_path_mtu_discovery through ire_frag_flag.
2634 		 */
2635 		if (ipst->ips_ip_path_mtu_discovery) {
2636 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2637 			    htons(IPH_DF);
2638 		}
2639 		/*
2640 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2641 		 * for IP_NEXTHOP. No cache ire has been found for the
2642 		 * destination and we are working with the nexthop's
2643 		 * interface ire. Since we need to forward all packets
2644 		 * to the nexthop first, we "blindly" set tcp_localnet
2645 		 * to false, eventhough the destination may also be
2646 		 * onlink.
2647 		 */
2648 		if (ire_uinfo == NULL)
2649 			tcp->tcp_localnet = 0;
2650 		else
2651 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2652 	} else {
2653 		/*
2654 		 * For incoming connection ire_mp = NULL
2655 		 * For outgoing connection ire_mp != NULL
2656 		 * Technically we should check conn_incoming_ill
2657 		 * when ire_mp is NULL and conn_outgoing_ill when
2658 		 * ire_mp is non-NULL. But this is performance
2659 		 * critical path and for IPV*_BOUND_IF, outgoing
2660 		 * and incoming ill are always set to the same value.
2661 		 */
2662 		ill_t	*dst_ill = NULL;
2663 		ipif_t  *dst_ipif = NULL;
2664 
2665 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2666 
2667 		if (connp->conn_outgoing_ill != NULL) {
2668 			/* Outgoing or incoming path */
2669 			int   err;
2670 
2671 			dst_ill = conn_get_held_ill(connp,
2672 			    &connp->conn_outgoing_ill, &err);
2673 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2674 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2675 				return (0);
2676 			}
2677 			match_flags |= MATCH_IRE_ILL;
2678 			dst_ipif = dst_ill->ill_ipif;
2679 		}
2680 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2681 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2682 
2683 		if (ire != NULL) {
2684 			ire_cacheable = B_TRUE;
2685 			ire_uinfo = (ire_mp != NULL) ?
2686 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2687 			    &ire->ire_uinfo;
2688 		} else {
2689 			if (ire_mp == NULL) {
2690 				ire = ire_ftable_lookup_v6(
2691 				    &tcp->tcp_connp->conn_remv6,
2692 				    0, 0, 0, dst_ipif, &sire, zoneid,
2693 				    0, tsl, match_flags, ipst);
2694 				if (ire == NULL) {
2695 					if (dst_ill != NULL)
2696 						ill_refrele(dst_ill);
2697 					return (0);
2698 				}
2699 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2700 				    &ire->ire_uinfo;
2701 			} else {
2702 				ire = (ire_t *)ire_mp->b_rptr;
2703 				ire_uinfo =
2704 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2705 			}
2706 		}
2707 		if (dst_ill != NULL)
2708 			ill_refrele(dst_ill);
2709 
2710 		ASSERT(ire != NULL);
2711 		ASSERT(ire_uinfo != NULL);
2712 
2713 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2714 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2715 			/*
2716 			 * ire->ire_mp is non null when ire_mp passed in is used
2717 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2718 			 */
2719 			if (ire->ire_mp == NULL)
2720 				ire_refrele(ire);
2721 			if (sire != NULL)
2722 				ire_refrele(sire);
2723 			return (0);
2724 		}
2725 
2726 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2727 			in6_addr_t	src_addr;
2728 
2729 			/*
2730 			 * ip_bind_connected_v6() has stored the correct source
2731 			 * address per IPv6 addr. selection policy in
2732 			 * conn_src_v6.
2733 			 */
2734 			src_addr = tcp->tcp_connp->conn_srcv6;
2735 
2736 			tcp->tcp_ip6h->ip6_src = src_addr;
2737 			/*
2738 			 * Copy of the src addr. in tcp_t is needed
2739 			 * for the lookup funcs.
2740 			 */
2741 			tcp->tcp_ip_src_v6 = src_addr;
2742 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2743 			    &connp->conn_srcv6));
2744 		}
2745 		tcp->tcp_localnet =
2746 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2747 	}
2748 
2749 	/*
2750 	 * This allows applications to fail quickly when connections are made
2751 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2752 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2753 	 */
2754 	if ((ire->ire_flags & RTF_REJECT) &&
2755 	    (ire->ire_flags & RTF_PRIVATE))
2756 		goto error;
2757 
2758 	/*
2759 	 * Make use of the cached rtt and rtt_sd values to calculate the
2760 	 * initial RTO.  Note that they are already initialized in
2761 	 * tcp_init_values().
2762 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2763 	 * IP_NEXTHOP, but instead are using the interface ire for the
2764 	 * nexthop, then we do not use the ire_uinfo from that ire to
2765 	 * do any initializations.
2766 	 */
2767 	if (ire_uinfo != NULL) {
2768 		if (ire_uinfo->iulp_rtt != 0) {
2769 			clock_t	rto;
2770 
2771 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2772 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2773 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2774 			    tcps->tcps_rexmit_interval_extra +
2775 			    (tcp->tcp_rtt_sa >> 5);
2776 
2777 			if (rto > tcps->tcps_rexmit_interval_max) {
2778 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2779 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2780 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2781 			} else {
2782 				tcp->tcp_rto = rto;
2783 			}
2784 		}
2785 		if (ire_uinfo->iulp_ssthresh != 0)
2786 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2787 		else
2788 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2789 		if (ire_uinfo->iulp_spipe > 0) {
2790 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2791 			    tcps->tcps_max_buf);
2792 			if (tcps->tcps_snd_lowat_fraction != 0)
2793 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2794 				    tcps->tcps_snd_lowat_fraction;
2795 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2796 		}
2797 		/*
2798 		 * Note that up till now, acceptor always inherits receive
2799 		 * window from the listener.  But if there is a metrics
2800 		 * associated with a host, we should use that instead of
2801 		 * inheriting it from listener. Thus we need to pass this
2802 		 * info back to the caller.
2803 		 */
2804 		if (ire_uinfo->iulp_rpipe > 0) {
2805 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2806 			    tcps->tcps_max_buf);
2807 		}
2808 
2809 		if (ire_uinfo->iulp_rtomax > 0) {
2810 			tcp->tcp_second_timer_threshold =
2811 			    ire_uinfo->iulp_rtomax;
2812 		}
2813 
2814 		/*
2815 		 * Use the metric option settings, iulp_tstamp_ok and
2816 		 * iulp_wscale_ok, only for active open. What this means
2817 		 * is that if the other side uses timestamp or window
2818 		 * scale option, TCP will also use those options. That
2819 		 * is for passive open.  If the application sets a
2820 		 * large window, window scale is enabled regardless of
2821 		 * the value in iulp_wscale_ok.  This is the behavior
2822 		 * since 2.6.  So we keep it.
2823 		 * The only case left in passive open processing is the
2824 		 * check for SACK.
2825 		 * For ECN, it should probably be like SACK.  But the
2826 		 * current value is binary, so we treat it like the other
2827 		 * cases.  The metric only controls active open.For passive
2828 		 * open, the ndd param, tcp_ecn_permitted, controls the
2829 		 * behavior.
2830 		 */
2831 		if (!tcp_detached) {
2832 			/*
2833 			 * The if check means that the following can only
2834 			 * be turned on by the metrics only IRE, but not off.
2835 			 */
2836 			if (ire_uinfo->iulp_tstamp_ok)
2837 				tcp->tcp_snd_ts_ok = B_TRUE;
2838 			if (ire_uinfo->iulp_wscale_ok)
2839 				tcp->tcp_snd_ws_ok = B_TRUE;
2840 			if (ire_uinfo->iulp_sack == 2)
2841 				tcp->tcp_snd_sack_ok = B_TRUE;
2842 			if (ire_uinfo->iulp_ecn_ok)
2843 				tcp->tcp_ecn_ok = B_TRUE;
2844 		} else {
2845 			/*
2846 			 * Passive open.
2847 			 *
2848 			 * As above, the if check means that SACK can only be
2849 			 * turned on by the metric only IRE.
2850 			 */
2851 			if (ire_uinfo->iulp_sack > 0) {
2852 				tcp->tcp_snd_sack_ok = B_TRUE;
2853 			}
2854 		}
2855 	}
2856 
2857 
2858 	/*
2859 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2860 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2861 	 * length of all those options exceeds 28 bytes.  But because
2862 	 * of the tcp_mss_min check below, we may not have a problem if
2863 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2864 	 * the negative problem still exists.  And the check defeats PMTUd.
2865 	 * In fact, if PMTUd finds that the MSS should be smaller than
2866 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2867 	 * value.
2868 	 *
2869 	 * We do not deal with that now.  All those problems related to
2870 	 * PMTUd will be fixed later.
2871 	 */
2872 	ASSERT(ire->ire_max_frag != 0);
2873 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2874 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2875 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2876 			mss = MIN(mss, IPV6_MIN_MTU);
2877 		}
2878 	}
2879 
2880 	/* Sanity check for MSS value. */
2881 	if (tcp->tcp_ipversion == IPV4_VERSION)
2882 		mss_max = tcps->tcps_mss_max_ipv4;
2883 	else
2884 		mss_max = tcps->tcps_mss_max_ipv6;
2885 
2886 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2887 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2888 		/*
2889 		 * After receiving an ICMPv6 "packet too big" message with a
2890 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2891 		 * will insert a 8-byte fragment header in every packet; we
2892 		 * reduce the MSS by that amount here.
2893 		 */
2894 		mss -= sizeof (ip6_frag_t);
2895 	}
2896 
2897 	if (tcp->tcp_ipsec_overhead == 0)
2898 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2899 
2900 	mss -= tcp->tcp_ipsec_overhead;
2901 
2902 	if (mss < tcps->tcps_mss_min)
2903 		mss = tcps->tcps_mss_min;
2904 	if (mss > mss_max)
2905 		mss = mss_max;
2906 
2907 	/* Note that this is the maximum MSS, excluding all options. */
2908 	tcp->tcp_mss = mss;
2909 
2910 	/*
2911 	 * Initialize the ISS here now that we have the full connection ID.
2912 	 * The RFC 1948 method of initial sequence number generation requires
2913 	 * knowledge of the full connection ID before setting the ISS.
2914 	 */
2915 
2916 	tcp_iss_init(tcp);
2917 
2918 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2919 		tcp->tcp_loopback = B_TRUE;
2920 
2921 	if (sire != NULL)
2922 		IRE_REFRELE(sire);
2923 
2924 	/*
2925 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2926 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2927 	 */
2928 	if (tcp->tcp_loopback ||
2929 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2930 		/*
2931 		 * For incoming, see if this tcp may be MDT-capable.  For
2932 		 * outgoing, this process has been taken care of through
2933 		 * tcp_rput_other.
2934 		 */
2935 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2936 		tcp->tcp_ire_ill_check_done = B_TRUE;
2937 	}
2938 
2939 	mutex_enter(&connp->conn_lock);
2940 	/*
2941 	 * Make sure that conn is not marked incipient
2942 	 * for incoming connections. A blind
2943 	 * removal of incipient flag is cheaper than
2944 	 * check and removal.
2945 	 */
2946 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2947 
2948 	/*
2949 	 * Must not cache forwarding table routes
2950 	 * or recache an IRE after the conn_t has
2951 	 * had conn_ire_cache cleared and is flagged
2952 	 * unusable, (see the CONN_CACHE_IRE() macro).
2953 	 */
2954 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
2955 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2956 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2957 			connp->conn_ire_cache = ire;
2958 			IRE_UNTRACE_REF(ire);
2959 			rw_exit(&ire->ire_bucket->irb_lock);
2960 			mutex_exit(&connp->conn_lock);
2961 			return (1);
2962 		}
2963 		rw_exit(&ire->ire_bucket->irb_lock);
2964 	}
2965 	mutex_exit(&connp->conn_lock);
2966 
2967 	if (ire->ire_mp == NULL)
2968 		ire_refrele(ire);
2969 	return (1);
2970 
2971 error:
2972 	if (ire->ire_mp == NULL)
2973 		ire_refrele(ire);
2974 	if (sire != NULL)
2975 		ire_refrele(sire);
2976 	return (0);
2977 }
2978 
2979 static void
2980 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
2981 {
2982 	int	error;
2983 	conn_t	*connp = tcp->tcp_connp;
2984 	struct sockaddr	*sa;
2985 	mblk_t  *mp1;
2986 	struct T_bind_req *tbr;
2987 	int	backlog;
2988 	socklen_t	len;
2989 	sin_t	*sin;
2990 	sin6_t	*sin6;
2991 	cred_t		*cr;
2992 
2993 	/*
2994 	 * All Solaris components should pass a db_credp
2995 	 * for this TPI message, hence we ASSERT.
2996 	 * But in case there is some other M_PROTO that looks
2997 	 * like a TPI message sent by some other kernel
2998 	 * component, we check and return an error.
2999 	 */
3000 	cr = msg_getcred(mp, NULL);
3001 	ASSERT(cr != NULL);
3002 	if (cr == NULL) {
3003 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3004 		return;
3005 	}
3006 
3007 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3008 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3009 		if (tcp->tcp_debug) {
3010 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3011 			    "tcp_tpi_bind: bad req, len %u",
3012 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3013 		}
3014 		tcp_err_ack(tcp, mp, TPROTO, 0);
3015 		return;
3016 	}
3017 	/* Make sure the largest address fits */
3018 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3019 	if (mp1 == NULL) {
3020 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3021 		return;
3022 	}
3023 	mp = mp1;
3024 	tbr = (struct T_bind_req *)mp->b_rptr;
3025 
3026 	backlog = tbr->CONIND_number;
3027 	len = tbr->ADDR_length;
3028 
3029 	switch (len) {
3030 	case 0:		/* request for a generic port */
3031 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3032 		if (tcp->tcp_family == AF_INET) {
3033 			tbr->ADDR_length = sizeof (sin_t);
3034 			sin = (sin_t *)&tbr[1];
3035 			*sin = sin_null;
3036 			sin->sin_family = AF_INET;
3037 			sa = (struct sockaddr *)sin;
3038 			len = sizeof (sin_t);
3039 			mp->b_wptr = (uchar_t *)&sin[1];
3040 		} else {
3041 			ASSERT(tcp->tcp_family == AF_INET6);
3042 			tbr->ADDR_length = sizeof (sin6_t);
3043 			sin6 = (sin6_t *)&tbr[1];
3044 			*sin6 = sin6_null;
3045 			sin6->sin6_family = AF_INET6;
3046 			sa = (struct sockaddr *)sin6;
3047 			len = sizeof (sin6_t);
3048 			mp->b_wptr = (uchar_t *)&sin6[1];
3049 		}
3050 		break;
3051 
3052 	case sizeof (sin_t):    /* Complete IPv4 address */
3053 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
3054 		    sizeof (sin_t));
3055 		break;
3056 
3057 	case sizeof (sin6_t): /* Complete IPv6 address */
3058 		sa = (struct sockaddr *)mi_offset_param(mp,
3059 		    tbr->ADDR_offset, sizeof (sin6_t));
3060 		break;
3061 
3062 	default:
3063 		if (tcp->tcp_debug) {
3064 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3065 			    "tcp_tpi_bind: bad address length, %d",
3066 			    tbr->ADDR_length);
3067 		}
3068 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3069 		return;
3070 	}
3071 
3072 	error = tcp_bind_check(connp, sa, len, cr,
3073 	    tbr->PRIM_type != O_T_BIND_REQ);
3074 	if (error == 0) {
3075 		if (tcp->tcp_family == AF_INET) {
3076 			sin = (sin_t *)sa;
3077 			sin->sin_port = tcp->tcp_lport;
3078 		} else {
3079 			sin6 = (sin6_t *)sa;
3080 			sin6->sin6_port = tcp->tcp_lport;
3081 		}
3082 
3083 		if (backlog > 0) {
3084 			error = tcp_do_listen(connp, backlog, cr);
3085 		}
3086 	}
3087 done:
3088 	if (error > 0) {
3089 		tcp_err_ack(tcp, mp, TSYSERR, error);
3090 	} else if (error < 0) {
3091 		tcp_err_ack(tcp, mp, -error, 0);
3092 	} else {
3093 		mp->b_datap->db_type = M_PCPROTO;
3094 		tbr->PRIM_type = T_BIND_ACK;
3095 		putnext(tcp->tcp_rq, mp);
3096 	}
3097 }
3098 
3099 /*
3100  * If the "bind_to_req_port_only" parameter is set, if the requested port
3101  * number is available, return it, If not return 0
3102  *
3103  * If "bind_to_req_port_only" parameter is not set and
3104  * If the requested port number is available, return it.  If not, return
3105  * the first anonymous port we happen across.  If no anonymous ports are
3106  * available, return 0. addr is the requested local address, if any.
3107  *
3108  * In either case, when succeeding update the tcp_t to record the port number
3109  * and insert it in the bind hash table.
3110  *
3111  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3112  * without setting SO_REUSEADDR. This is needed so that they
3113  * can be viewed as two independent transport protocols.
3114  */
3115 static in_port_t
3116 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3117     int reuseaddr, boolean_t quick_connect,
3118     boolean_t bind_to_req_port_only, boolean_t user_specified)
3119 {
3120 	/* number of times we have run around the loop */
3121 	int count = 0;
3122 	/* maximum number of times to run around the loop */
3123 	int loopmax;
3124 	conn_t *connp = tcp->tcp_connp;
3125 	zoneid_t zoneid = connp->conn_zoneid;
3126 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3127 
3128 	/*
3129 	 * Lookup for free addresses is done in a loop and "loopmax"
3130 	 * influences how long we spin in the loop
3131 	 */
3132 	if (bind_to_req_port_only) {
3133 		/*
3134 		 * If the requested port is busy, don't bother to look
3135 		 * for a new one. Setting loop maximum count to 1 has
3136 		 * that effect.
3137 		 */
3138 		loopmax = 1;
3139 	} else {
3140 		/*
3141 		 * If the requested port is busy, look for a free one
3142 		 * in the anonymous port range.
3143 		 * Set loopmax appropriately so that one does not look
3144 		 * forever in the case all of the anonymous ports are in use.
3145 		 */
3146 		if (tcp->tcp_anon_priv_bind) {
3147 			/*
3148 			 * loopmax =
3149 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3150 			 */
3151 			loopmax = IPPORT_RESERVED -
3152 			    tcps->tcps_min_anonpriv_port;
3153 		} else {
3154 			loopmax = (tcps->tcps_largest_anon_port -
3155 			    tcps->tcps_smallest_anon_port + 1);
3156 		}
3157 	}
3158 	do {
3159 		uint16_t	lport;
3160 		tf_t		*tbf;
3161 		tcp_t		*ltcp;
3162 		conn_t		*lconnp;
3163 
3164 		lport = htons(port);
3165 
3166 		/*
3167 		 * Ensure that the tcp_t is not currently in the bind hash.
3168 		 * Hold the lock on the hash bucket to ensure that
3169 		 * the duplicate check plus the insertion is an atomic
3170 		 * operation.
3171 		 *
3172 		 * This function does an inline lookup on the bind hash list
3173 		 * Make sure that we access only members of tcp_t
3174 		 * and that we don't look at tcp_tcp, since we are not
3175 		 * doing a CONN_INC_REF.
3176 		 */
3177 		tcp_bind_hash_remove(tcp);
3178 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3179 		mutex_enter(&tbf->tf_lock);
3180 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3181 		    ltcp = ltcp->tcp_bind_hash) {
3182 			if (lport == ltcp->tcp_lport)
3183 				break;
3184 		}
3185 
3186 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
3187 			boolean_t not_socket;
3188 			boolean_t exclbind;
3189 
3190 			lconnp = ltcp->tcp_connp;
3191 
3192 			/*
3193 			 * On a labeled system, we must treat bindings to ports
3194 			 * on shared IP addresses by sockets with MAC exemption
3195 			 * privilege as being in all zones, as there's
3196 			 * otherwise no way to identify the right receiver.
3197 			 */
3198 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3199 			    IPCL_ZONE_MATCH(connp,
3200 			    ltcp->tcp_connp->conn_zoneid)) &&
3201 			    !lconnp->conn_mac_exempt &&
3202 			    !connp->conn_mac_exempt)
3203 				continue;
3204 
3205 			/*
3206 			 * If TCP_EXCLBIND is set for either the bound or
3207 			 * binding endpoint, the semantics of bind
3208 			 * is changed according to the following.
3209 			 *
3210 			 * spec = specified address (v4 or v6)
3211 			 * unspec = unspecified address (v4 or v6)
3212 			 * A = specified addresses are different for endpoints
3213 			 *
3214 			 * bound	bind to		allowed
3215 			 * -------------------------------------
3216 			 * unspec	unspec		no
3217 			 * unspec	spec		no
3218 			 * spec		unspec		no
3219 			 * spec		spec		yes if A
3220 			 *
3221 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3222 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3223 			 *
3224 			 * Note:
3225 			 *
3226 			 * 1. Because of TLI semantics, an endpoint can go
3227 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3228 			 * TCPS_BOUND, depending on whether it is originally
3229 			 * a listener or not.  That is why we need to check
3230 			 * for states greater than or equal to TCPS_BOUND
3231 			 * here.
3232 			 *
3233 			 * 2. Ideally, we should only check for state equals
3234 			 * to TCPS_LISTEN. And the following check should be
3235 			 * added.
3236 			 *
3237 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3238 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3239 			 *		...
3240 			 * }
3241 			 *
3242 			 * The semantics will be changed to this.  If the
3243 			 * endpoint on the list is in state not equal to
3244 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3245 			 * set, let the bind succeed.
3246 			 *
3247 			 * Because of (1), we cannot do that for TLI
3248 			 * endpoints.  But we can do that for socket endpoints.
3249 			 * If in future, we can change this going back
3250 			 * semantics, we can use the above check for TLI also.
3251 			 */
3252 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3253 			    TCP_IS_SOCKET(tcp));
3254 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3255 
3256 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3257 			    (exclbind && (not_socket ||
3258 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3259 				if (V6_OR_V4_INADDR_ANY(
3260 				    ltcp->tcp_bound_source_v6) ||
3261 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3262 				    IN6_ARE_ADDR_EQUAL(laddr,
3263 				    &ltcp->tcp_bound_source_v6)) {
3264 					break;
3265 				}
3266 				continue;
3267 			}
3268 
3269 			/*
3270 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3271 			 * have disjoint port number spaces, if *_EXCLBIND
3272 			 * is not set and only if the application binds to a
3273 			 * specific port. We use the same autoassigned port
3274 			 * number space for IPv4 and IPv6 sockets.
3275 			 */
3276 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3277 			    bind_to_req_port_only)
3278 				continue;
3279 
3280 			/*
3281 			 * Ideally, we should make sure that the source
3282 			 * address, remote address, and remote port in the
3283 			 * four tuple for this tcp-connection is unique.
3284 			 * However, trying to find out the local source
3285 			 * address would require too much code duplication
3286 			 * with IP, since IP needs needs to have that code
3287 			 * to support userland TCP implementations.
3288 			 */
3289 			if (quick_connect &&
3290 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3291 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3292 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3293 			    &ltcp->tcp_remote_v6)))
3294 				continue;
3295 
3296 			if (!reuseaddr) {
3297 				/*
3298 				 * No socket option SO_REUSEADDR.
3299 				 * If existing port is bound to
3300 				 * a non-wildcard IP address
3301 				 * and the requesting stream is
3302 				 * bound to a distinct
3303 				 * different IP addresses
3304 				 * (non-wildcard, also), keep
3305 				 * going.
3306 				 */
3307 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3308 				    !V6_OR_V4_INADDR_ANY(
3309 				    ltcp->tcp_bound_source_v6) &&
3310 				    !IN6_ARE_ADDR_EQUAL(laddr,
3311 				    &ltcp->tcp_bound_source_v6))
3312 					continue;
3313 				if (ltcp->tcp_state >= TCPS_BOUND) {
3314 					/*
3315 					 * This port is being used and
3316 					 * its state is >= TCPS_BOUND,
3317 					 * so we can't bind to it.
3318 					 */
3319 					break;
3320 				}
3321 			} else {
3322 				/*
3323 				 * socket option SO_REUSEADDR is set on the
3324 				 * binding tcp_t.
3325 				 *
3326 				 * If two streams are bound to
3327 				 * same IP address or both addr
3328 				 * and bound source are wildcards
3329 				 * (INADDR_ANY), we want to stop
3330 				 * searching.
3331 				 * We have found a match of IP source
3332 				 * address and source port, which is
3333 				 * refused regardless of the
3334 				 * SO_REUSEADDR setting, so we break.
3335 				 */
3336 				if (IN6_ARE_ADDR_EQUAL(laddr,
3337 				    &ltcp->tcp_bound_source_v6) &&
3338 				    (ltcp->tcp_state == TCPS_LISTEN ||
3339 				    ltcp->tcp_state == TCPS_BOUND))
3340 					break;
3341 			}
3342 		}
3343 		if (ltcp != NULL) {
3344 			/* The port number is busy */
3345 			mutex_exit(&tbf->tf_lock);
3346 		} else {
3347 			/*
3348 			 * This port is ours. Insert in fanout and mark as
3349 			 * bound to prevent others from getting the port
3350 			 * number.
3351 			 */
3352 			tcp->tcp_state = TCPS_BOUND;
3353 			tcp->tcp_lport = htons(port);
3354 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3355 
3356 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3357 			    tcp->tcp_lport)] == tbf);
3358 			tcp_bind_hash_insert(tbf, tcp, 1);
3359 
3360 			mutex_exit(&tbf->tf_lock);
3361 
3362 			/*
3363 			 * We don't want tcp_next_port_to_try to "inherit"
3364 			 * a port number supplied by the user in a bind.
3365 			 */
3366 			if (user_specified)
3367 				return (port);
3368 
3369 			/*
3370 			 * This is the only place where tcp_next_port_to_try
3371 			 * is updated. After the update, it may or may not
3372 			 * be in the valid range.
3373 			 */
3374 			if (!tcp->tcp_anon_priv_bind)
3375 				tcps->tcps_next_port_to_try = port + 1;
3376 			return (port);
3377 		}
3378 
3379 		if (tcp->tcp_anon_priv_bind) {
3380 			port = tcp_get_next_priv_port(tcp);
3381 		} else {
3382 			if (count == 0 && user_specified) {
3383 				/*
3384 				 * We may have to return an anonymous port. So
3385 				 * get one to start with.
3386 				 */
3387 				port =
3388 				    tcp_update_next_port(
3389 				    tcps->tcps_next_port_to_try,
3390 				    tcp, B_TRUE);
3391 				user_specified = B_FALSE;
3392 			} else {
3393 				port = tcp_update_next_port(port + 1, tcp,
3394 				    B_FALSE);
3395 			}
3396 		}
3397 		if (port == 0)
3398 			break;
3399 
3400 		/*
3401 		 * Don't let this loop run forever in the case where
3402 		 * all of the anonymous ports are in use.
3403 		 */
3404 	} while (++count < loopmax);
3405 	return (0);
3406 }
3407 
3408 /*
3409  * tcp_clean_death / tcp_close_detached must not be called more than once
3410  * on a tcp. Thus every function that potentially calls tcp_clean_death
3411  * must check for the tcp state before calling tcp_clean_death.
3412  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3413  * tcp_timer_handler, all check for the tcp state.
3414  */
3415 /* ARGSUSED */
3416 void
3417 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3418 {
3419 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3420 
3421 	freemsg(mp);
3422 	if (tcp->tcp_state > TCPS_BOUND)
3423 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3424 		    ETIMEDOUT, 5);
3425 }
3426 
3427 /*
3428  * We are dying for some reason.  Try to do it gracefully.  (May be called
3429  * as writer.)
3430  *
3431  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3432  * done by a service procedure).
3433  * TBD - Should the return value distinguish between the tcp_t being
3434  * freed and it being reinitialized?
3435  */
3436 static int
3437 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3438 {
3439 	mblk_t	*mp;
3440 	queue_t	*q;
3441 	conn_t	*connp = tcp->tcp_connp;
3442 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3443 	sodirect_t	*sodp;
3444 
3445 	TCP_CLD_STAT(tag);
3446 
3447 #if TCP_TAG_CLEAN_DEATH
3448 	tcp->tcp_cleandeathtag = tag;
3449 #endif
3450 
3451 	if (tcp->tcp_fused)
3452 		tcp_unfuse(tcp);
3453 
3454 	if (tcp->tcp_linger_tid != 0 &&
3455 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3456 		tcp_stop_lingering(tcp);
3457 	}
3458 
3459 	ASSERT(tcp != NULL);
3460 	ASSERT((tcp->tcp_family == AF_INET &&
3461 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3462 	    (tcp->tcp_family == AF_INET6 &&
3463 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3464 	    tcp->tcp_ipversion == IPV6_VERSION)));
3465 
3466 	if (TCP_IS_DETACHED(tcp)) {
3467 		if (tcp->tcp_hard_binding) {
3468 			/*
3469 			 * Its an eager that we are dealing with. We close the
3470 			 * eager but in case a conn_ind has already gone to the
3471 			 * listener, let tcp_accept_finish() send a discon_ind
3472 			 * to the listener and drop the last reference. If the
3473 			 * listener doesn't even know about the eager i.e. the
3474 			 * conn_ind hasn't gone up, blow away the eager and drop
3475 			 * the last reference as well. If the conn_ind has gone
3476 			 * up, state should be BOUND. tcp_accept_finish
3477 			 * will figure out that the connection has received a
3478 			 * RST and will send a DISCON_IND to the application.
3479 			 */
3480 			tcp_closei_local(tcp);
3481 			if (!tcp->tcp_tconnind_started) {
3482 				CONN_DEC_REF(connp);
3483 			} else {
3484 				tcp->tcp_state = TCPS_BOUND;
3485 			}
3486 		} else {
3487 			tcp_close_detached(tcp);
3488 		}
3489 		return (0);
3490 	}
3491 
3492 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3493 
3494 	/* If sodirect, not anymore */
3495 	SOD_PTR_ENTER(tcp, sodp);
3496 	if (sodp != NULL) {
3497 		tcp->tcp_sodirect = NULL;
3498 		mutex_exit(sodp->sod_lockp);
3499 	}
3500 
3501 	q = tcp->tcp_rq;
3502 
3503 	/* Trash all inbound data */
3504 	if (!IPCL_IS_NONSTR(connp)) {
3505 		ASSERT(q != NULL);
3506 		flushq(q, FLUSHALL);
3507 	}
3508 
3509 	/*
3510 	 * If we are at least part way open and there is error
3511 	 * (err==0 implies no error)
3512 	 * notify our client by a T_DISCON_IND.
3513 	 */
3514 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3515 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3516 		    !TCP_IS_SOCKET(tcp)) {
3517 			/*
3518 			 * Send M_FLUSH according to TPI. Because sockets will
3519 			 * (and must) ignore FLUSHR we do that only for TPI
3520 			 * endpoints and sockets in STREAMS mode.
3521 			 */
3522 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3523 		}
3524 		if (tcp->tcp_debug) {
3525 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3526 			    "tcp_clean_death: discon err %d", err);
3527 		}
3528 		if (IPCL_IS_NONSTR(connp)) {
3529 			/* Direct socket, use upcall */
3530 			(*connp->conn_upcalls->su_disconnected)(
3531 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3532 		} else {
3533 			mp = mi_tpi_discon_ind(NULL, err, 0);
3534 			if (mp != NULL) {
3535 				putnext(q, mp);
3536 			} else {
3537 				if (tcp->tcp_debug) {
3538 					(void) strlog(TCP_MOD_ID, 0, 1,
3539 					    SL_ERROR|SL_TRACE,
3540 					    "tcp_clean_death, sending M_ERROR");
3541 				}
3542 				(void) putnextctl1(q, M_ERROR, EPROTO);
3543 			}
3544 		}
3545 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3546 			/* SYN_SENT or SYN_RCVD */
3547 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3548 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3549 			/* ESTABLISHED or CLOSE_WAIT */
3550 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3551 		}
3552 	}
3553 
3554 	tcp_reinit(tcp);
3555 	if (IPCL_IS_NONSTR(connp))
3556 		(void) tcp_do_unbind(connp);
3557 
3558 	return (-1);
3559 }
3560 
3561 /*
3562  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3563  * to expire, stop the wait and finish the close.
3564  */
3565 static void
3566 tcp_stop_lingering(tcp_t *tcp)
3567 {
3568 	clock_t	delta = 0;
3569 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3570 
3571 	tcp->tcp_linger_tid = 0;
3572 	if (tcp->tcp_state > TCPS_LISTEN) {
3573 		tcp_acceptor_hash_remove(tcp);
3574 		mutex_enter(&tcp->tcp_non_sq_lock);
3575 		if (tcp->tcp_flow_stopped) {
3576 			tcp_clrqfull(tcp);
3577 		}
3578 		mutex_exit(&tcp->tcp_non_sq_lock);
3579 
3580 		if (tcp->tcp_timer_tid != 0) {
3581 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3582 			tcp->tcp_timer_tid = 0;
3583 		}
3584 		/*
3585 		 * Need to cancel those timers which will not be used when
3586 		 * TCP is detached.  This has to be done before the tcp_wq
3587 		 * is set to the global queue.
3588 		 */
3589 		tcp_timers_stop(tcp);
3590 
3591 		tcp->tcp_detached = B_TRUE;
3592 		ASSERT(tcps->tcps_g_q != NULL);
3593 		tcp->tcp_rq = tcps->tcps_g_q;
3594 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3595 
3596 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3597 			tcp_time_wait_append(tcp);
3598 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3599 			goto finish;
3600 		}
3601 
3602 		/*
3603 		 * If delta is zero the timer event wasn't executed and was
3604 		 * successfully canceled. In this case we need to restart it
3605 		 * with the minimal delta possible.
3606 		 */
3607 		if (delta >= 0) {
3608 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3609 			    delta ? delta : 1);
3610 		}
3611 	} else {
3612 		tcp_closei_local(tcp);
3613 		CONN_DEC_REF(tcp->tcp_connp);
3614 	}
3615 finish:
3616 	/* Signal closing thread that it can complete close */
3617 	mutex_enter(&tcp->tcp_closelock);
3618 	tcp->tcp_detached = B_TRUE;
3619 	ASSERT(tcps->tcps_g_q != NULL);
3620 
3621 	tcp->tcp_rq = tcps->tcps_g_q;
3622 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3623 
3624 	tcp->tcp_closed = 1;
3625 	cv_signal(&tcp->tcp_closecv);
3626 	mutex_exit(&tcp->tcp_closelock);
3627 }
3628 
3629 /*
3630  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3631  * expires.
3632  */
3633 static void
3634 tcp_close_linger_timeout(void *arg)
3635 {
3636 	conn_t	*connp = (conn_t *)arg;
3637 	tcp_t 	*tcp = connp->conn_tcp;
3638 
3639 	tcp->tcp_client_errno = ETIMEDOUT;
3640 	tcp_stop_lingering(tcp);
3641 }
3642 
3643 static void
3644 tcp_close_common(conn_t *connp, int flags)
3645 {
3646 	tcp_t		*tcp = connp->conn_tcp;
3647 	mblk_t 		*mp = &tcp->tcp_closemp;
3648 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3649 	mblk_t		*bp;
3650 
3651 	ASSERT(connp->conn_ref >= 2);
3652 
3653 	/*
3654 	 * Mark the conn as closing. ill_pending_mp_add will not
3655 	 * add any mp to the pending mp list, after this conn has
3656 	 * started closing. Same for sq_pending_mp_add
3657 	 */
3658 	mutex_enter(&connp->conn_lock);
3659 	connp->conn_state_flags |= CONN_CLOSING;
3660 	if (connp->conn_oper_pending_ill != NULL)
3661 		conn_ioctl_cleanup_reqd = B_TRUE;
3662 	CONN_INC_REF_LOCKED(connp);
3663 	mutex_exit(&connp->conn_lock);
3664 	tcp->tcp_closeflags = (uint8_t)flags;
3665 	ASSERT(connp->conn_ref >= 3);
3666 
3667 	/*
3668 	 * tcp_closemp_used is used below without any protection of a lock
3669 	 * as we don't expect any one else to use it concurrently at this
3670 	 * point otherwise it would be a major defect.
3671 	 */
3672 
3673 	if (mp->b_prev == NULL)
3674 		tcp->tcp_closemp_used = B_TRUE;
3675 	else
3676 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3677 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3678 
3679 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3680 
3681 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3682 	    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3683 
3684 	mutex_enter(&tcp->tcp_closelock);
3685 	while (!tcp->tcp_closed) {
3686 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3687 			/*
3688 			 * The cv_wait_sig() was interrupted. We now do the
3689 			 * following:
3690 			 *
3691 			 * 1) If the endpoint was lingering, we allow this
3692 			 * to be interrupted by cancelling the linger timeout
3693 			 * and closing normally.
3694 			 *
3695 			 * 2) Revert to calling cv_wait()
3696 			 *
3697 			 * We revert to using cv_wait() to avoid an
3698 			 * infinite loop which can occur if the calling
3699 			 * thread is higher priority than the squeue worker
3700 			 * thread and is bound to the same cpu.
3701 			 */
3702 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
3703 				mutex_exit(&tcp->tcp_closelock);
3704 				/* Entering squeue, bump ref count. */
3705 				CONN_INC_REF(connp);
3706 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3707 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3708 				    tcp_linger_interrupted, connp,
3709 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3710 				mutex_enter(&tcp->tcp_closelock);
3711 			}
3712 			break;
3713 		}
3714 	}
3715 	while (!tcp->tcp_closed)
3716 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3717 	mutex_exit(&tcp->tcp_closelock);
3718 
3719 	/*
3720 	 * In the case of listener streams that have eagers in the q or q0
3721 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3722 	 * tcp_wq of the eagers point to our queues. By waiting for the
3723 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3724 	 * up their queue pointers and also dropped their references to us.
3725 	 */
3726 	if (tcp->tcp_wait_for_eagers) {
3727 		mutex_enter(&connp->conn_lock);
3728 		while (connp->conn_ref != 1) {
3729 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3730 		}
3731 		mutex_exit(&connp->conn_lock);
3732 	}
3733 	/*
3734 	 * ioctl cleanup. The mp is queued in the
3735 	 * ill_pending_mp or in the sq_pending_mp.
3736 	 */
3737 	if (conn_ioctl_cleanup_reqd)
3738 		conn_ioctl_cleanup(connp);
3739 
3740 	tcp->tcp_cpid = -1;
3741 }
3742 
3743 static int
3744 tcp_tpi_close(queue_t *q, int flags)
3745 {
3746 	conn_t		*connp;
3747 
3748 	ASSERT(WR(q)->q_next == NULL);
3749 
3750 	if (flags & SO_FALLBACK) {
3751 		/*
3752 		 * stream is being closed while in fallback
3753 		 * simply free the resources that were allocated
3754 		 */
3755 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3756 		qprocsoff(q);
3757 		goto done;
3758 	}
3759 
3760 	connp = Q_TO_CONN(q);
3761 	/*
3762 	 * We are being closed as /dev/tcp or /dev/tcp6.
3763 	 */
3764 	tcp_close_common(connp, flags);
3765 
3766 	qprocsoff(q);
3767 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3768 
3769 	/*
3770 	 * Drop IP's reference on the conn. This is the last reference
3771 	 * on the connp if the state was less than established. If the
3772 	 * connection has gone into timewait state, then we will have
3773 	 * one ref for the TCP and one more ref (total of two) for the
3774 	 * classifier connected hash list (a timewait connections stays
3775 	 * in connected hash till closed).
3776 	 *
3777 	 * We can't assert the references because there might be other
3778 	 * transient reference places because of some walkers or queued
3779 	 * packets in squeue for the timewait state.
3780 	 */
3781 	CONN_DEC_REF(connp);
3782 done:
3783 	q->q_ptr = WR(q)->q_ptr = NULL;
3784 	return (0);
3785 }
3786 
3787 static int
3788 tcpclose_accept(queue_t *q)
3789 {
3790 	vmem_t	*minor_arena;
3791 	dev_t	conn_dev;
3792 
3793 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3794 
3795 	/*
3796 	 * We had opened an acceptor STREAM for sockfs which is
3797 	 * now being closed due to some error.
3798 	 */
3799 	qprocsoff(q);
3800 
3801 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3802 	conn_dev = (dev_t)RD(q)->q_ptr;
3803 	ASSERT(minor_arena != NULL);
3804 	ASSERT(conn_dev != 0);
3805 	inet_minor_free(minor_arena, conn_dev);
3806 	q->q_ptr = WR(q)->q_ptr = NULL;
3807 	return (0);
3808 }
3809 
3810 /*
3811  * Called by tcp_close() routine via squeue when lingering is
3812  * interrupted by a signal.
3813  */
3814 
3815 /* ARGSUSED */
3816 static void
3817 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
3818 {
3819 	conn_t	*connp = (conn_t *)arg;
3820 	tcp_t	*tcp = connp->conn_tcp;
3821 
3822 	freeb(mp);
3823 	if (tcp->tcp_linger_tid != 0 &&
3824 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3825 		tcp_stop_lingering(tcp);
3826 		tcp->tcp_client_errno = EINTR;
3827 	}
3828 }
3829 
3830 /*
3831  * Called by streams close routine via squeues when our client blows off her
3832  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3833  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3834  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3835  * acked.
3836  *
3837  * NOTE: tcp_close potentially returns error when lingering.
3838  * However, the stream head currently does not pass these errors
3839  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3840  * errors to the application (from tsleep()) and not errors
3841  * like ECONNRESET caused by receiving a reset packet.
3842  */
3843 
3844 /* ARGSUSED */
3845 static void
3846 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3847 {
3848 	char	*msg;
3849 	conn_t	*connp = (conn_t *)arg;
3850 	tcp_t	*tcp = connp->conn_tcp;
3851 	clock_t	delta = 0;
3852 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3853 
3854 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3855 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3856 
3857 	mutex_enter(&tcp->tcp_eager_lock);
3858 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3859 		/* Cleanup for listener */
3860 		tcp_eager_cleanup(tcp, 0);
3861 		tcp->tcp_wait_for_eagers = 1;
3862 	}
3863 	mutex_exit(&tcp->tcp_eager_lock);
3864 
3865 	connp->conn_mdt_ok = B_FALSE;
3866 	tcp->tcp_mdt = B_FALSE;
3867 
3868 	connp->conn_lso_ok = B_FALSE;
3869 	tcp->tcp_lso = B_FALSE;
3870 
3871 	msg = NULL;
3872 	switch (tcp->tcp_state) {
3873 	case TCPS_CLOSED:
3874 	case TCPS_IDLE:
3875 	case TCPS_BOUND:
3876 	case TCPS_LISTEN:
3877 		break;
3878 	case TCPS_SYN_SENT:
3879 		msg = "tcp_close, during connect";
3880 		break;
3881 	case TCPS_SYN_RCVD:
3882 		/*
3883 		 * Close during the connect 3-way handshake
3884 		 * but here there may or may not be pending data
3885 		 * already on queue. Process almost same as in
3886 		 * the ESTABLISHED state.
3887 		 */
3888 		/* FALLTHRU */
3889 	default:
3890 		if (tcp->tcp_sodirect != NULL) {
3891 			/* Ok, no more sodirect */
3892 			tcp->tcp_sodirect = NULL;
3893 		}
3894 
3895 		if (tcp->tcp_fused)
3896 			tcp_unfuse(tcp);
3897 
3898 		/*
3899 		 * If SO_LINGER has set a zero linger time, abort the
3900 		 * connection with a reset.
3901 		 */
3902 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3903 			msg = "tcp_close, zero lingertime";
3904 			break;
3905 		}
3906 
3907 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3908 		/*
3909 		 * Abort connection if there is unread data queued.
3910 		 */
3911 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3912 			msg = "tcp_close, unread data";
3913 			break;
3914 		}
3915 		/*
3916 		 * tcp_hard_bound is now cleared thus all packets go through
3917 		 * tcp_lookup. This fact is used by tcp_detach below.
3918 		 *
3919 		 * We have done a qwait() above which could have possibly
3920 		 * drained more messages in turn causing transition to a
3921 		 * different state. Check whether we have to do the rest
3922 		 * of the processing or not.
3923 		 */
3924 		if (tcp->tcp_state <= TCPS_LISTEN)
3925 			break;
3926 
3927 		/*
3928 		 * Transmit the FIN before detaching the tcp_t.
3929 		 * After tcp_detach returns this queue/perimeter
3930 		 * no longer owns the tcp_t thus others can modify it.
3931 		 */
3932 		(void) tcp_xmit_end(tcp);
3933 
3934 		/*
3935 		 * If lingering on close then wait until the fin is acked,
3936 		 * the SO_LINGER time passes, or a reset is sent/received.
3937 		 */
3938 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
3939 		    !(tcp->tcp_fin_acked) &&
3940 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3941 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3942 				tcp->tcp_client_errno = EWOULDBLOCK;
3943 			} else if (tcp->tcp_client_errno == 0) {
3944 
3945 				ASSERT(tcp->tcp_linger_tid == 0);
3946 
3947 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3948 				    tcp_close_linger_timeout,
3949 				    tcp->tcp_lingertime * hz);
3950 
3951 				/* tcp_close_linger_timeout will finish close */
3952 				if (tcp->tcp_linger_tid == 0)
3953 					tcp->tcp_client_errno = ENOSR;
3954 				else
3955 					return;
3956 			}
3957 
3958 			/*
3959 			 * Check if we need to detach or just close
3960 			 * the instance.
3961 			 */
3962 			if (tcp->tcp_state <= TCPS_LISTEN)
3963 				break;
3964 		}
3965 
3966 		/*
3967 		 * Make sure that no other thread will access the tcp_rq of
3968 		 * this instance (through lookups etc.) as tcp_rq will go
3969 		 * away shortly.
3970 		 */
3971 		tcp_acceptor_hash_remove(tcp);
3972 
3973 		mutex_enter(&tcp->tcp_non_sq_lock);
3974 		if (tcp->tcp_flow_stopped) {
3975 			tcp_clrqfull(tcp);
3976 		}
3977 		mutex_exit(&tcp->tcp_non_sq_lock);
3978 
3979 		if (tcp->tcp_timer_tid != 0) {
3980 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3981 			tcp->tcp_timer_tid = 0;
3982 		}
3983 		/*
3984 		 * Need to cancel those timers which will not be used when
3985 		 * TCP is detached.  This has to be done before the tcp_wq
3986 		 * is set to the global queue.
3987 		 */
3988 		tcp_timers_stop(tcp);
3989 
3990 		tcp->tcp_detached = B_TRUE;
3991 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3992 			tcp_time_wait_append(tcp);
3993 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3994 			ASSERT(connp->conn_ref >= 3);
3995 			goto finish;
3996 		}
3997 
3998 		/*
3999 		 * If delta is zero the timer event wasn't executed and was
4000 		 * successfully canceled. In this case we need to restart it
4001 		 * with the minimal delta possible.
4002 		 */
4003 		if (delta >= 0)
4004 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4005 			    delta ? delta : 1);
4006 
4007 		ASSERT(connp->conn_ref >= 3);
4008 		goto finish;
4009 	}
4010 
4011 	/* Detach did not complete. Still need to remove q from stream. */
4012 	if (msg) {
4013 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4014 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4015 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4016 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4017 		    tcp->tcp_state == TCPS_SYN_RCVD)
4018 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4019 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4020 	}
4021 
4022 	tcp_closei_local(tcp);
4023 	CONN_DEC_REF(connp);
4024 	ASSERT(connp->conn_ref >= 2);
4025 
4026 finish:
4027 	/*
4028 	 * Although packets are always processed on the correct
4029 	 * tcp's perimeter and access is serialized via squeue's,
4030 	 * IP still needs a queue when sending packets in time_wait
4031 	 * state so use WR(tcps_g_q) till ip_output() can be
4032 	 * changed to deal with just connp. For read side, we
4033 	 * could have set tcp_rq to NULL but there are some cases
4034 	 * in tcp_rput_data() from early days of this code which
4035 	 * do a putnext without checking if tcp is closed. Those
4036 	 * need to be identified before both tcp_rq and tcp_wq
4037 	 * can be set to NULL and tcps_g_q can disappear forever.
4038 	 */
4039 	mutex_enter(&tcp->tcp_closelock);
4040 	/*
4041 	 * Don't change the queues in the case of a listener that has
4042 	 * eagers in its q or q0. It could surprise the eagers.
4043 	 * Instead wait for the eagers outside the squeue.
4044 	 */
4045 	if (!tcp->tcp_wait_for_eagers) {
4046 		tcp->tcp_detached = B_TRUE;
4047 		/*
4048 		 * When default queue is closing we set tcps_g_q to NULL
4049 		 * after the close is done.
4050 		 */
4051 		ASSERT(tcps->tcps_g_q != NULL);
4052 		tcp->tcp_rq = tcps->tcps_g_q;
4053 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4054 	}
4055 
4056 	/* Signal tcp_close() to finish closing. */
4057 	tcp->tcp_closed = 1;
4058 	cv_signal(&tcp->tcp_closecv);
4059 	mutex_exit(&tcp->tcp_closelock);
4060 }
4061 
4062 
4063 /*
4064  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4065  * Some stream heads get upset if they see these later on as anything but NULL.
4066  */
4067 static void
4068 tcp_close_mpp(mblk_t **mpp)
4069 {
4070 	mblk_t	*mp;
4071 
4072 	if ((mp = *mpp) != NULL) {
4073 		do {
4074 			mp->b_next = NULL;
4075 			mp->b_prev = NULL;
4076 		} while ((mp = mp->b_cont) != NULL);
4077 
4078 		mp = *mpp;
4079 		*mpp = NULL;
4080 		freemsg(mp);
4081 	}
4082 }
4083 
4084 /* Do detached close. */
4085 static void
4086 tcp_close_detached(tcp_t *tcp)
4087 {
4088 	if (tcp->tcp_fused)
4089 		tcp_unfuse(tcp);
4090 
4091 	/*
4092 	 * Clustering code serializes TCP disconnect callbacks and
4093 	 * cluster tcp list walks by blocking a TCP disconnect callback
4094 	 * if a cluster tcp list walk is in progress. This ensures
4095 	 * accurate accounting of TCPs in the cluster code even though
4096 	 * the TCP list walk itself is not atomic.
4097 	 */
4098 	tcp_closei_local(tcp);
4099 	CONN_DEC_REF(tcp->tcp_connp);
4100 }
4101 
4102 /*
4103  * Stop all TCP timers, and free the timer mblks if requested.
4104  */
4105 void
4106 tcp_timers_stop(tcp_t *tcp)
4107 {
4108 	if (tcp->tcp_timer_tid != 0) {
4109 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4110 		tcp->tcp_timer_tid = 0;
4111 	}
4112 	if (tcp->tcp_ka_tid != 0) {
4113 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4114 		tcp->tcp_ka_tid = 0;
4115 	}
4116 	if (tcp->tcp_ack_tid != 0) {
4117 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4118 		tcp->tcp_ack_tid = 0;
4119 	}
4120 	if (tcp->tcp_push_tid != 0) {
4121 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4122 		tcp->tcp_push_tid = 0;
4123 	}
4124 }
4125 
4126 /*
4127  * The tcp_t is going away. Remove it from all lists and set it
4128  * to TCPS_CLOSED. The freeing up of memory is deferred until
4129  * tcp_inactive. This is needed since a thread in tcp_rput might have
4130  * done a CONN_INC_REF on this structure before it was removed from the
4131  * hashes.
4132  */
4133 static void
4134 tcp_closei_local(tcp_t *tcp)
4135 {
4136 	ire_t 	*ire;
4137 	conn_t	*connp = tcp->tcp_connp;
4138 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4139 
4140 	if (!TCP_IS_SOCKET(tcp))
4141 		tcp_acceptor_hash_remove(tcp);
4142 
4143 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4144 	tcp->tcp_ibsegs = 0;
4145 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4146 	tcp->tcp_obsegs = 0;
4147 
4148 	/*
4149 	 * If we are an eager connection hanging off a listener that
4150 	 * hasn't formally accepted the connection yet, get off his
4151 	 * list and blow off any data that we have accumulated.
4152 	 */
4153 	if (tcp->tcp_listener != NULL) {
4154 		tcp_t	*listener = tcp->tcp_listener;
4155 		mutex_enter(&listener->tcp_eager_lock);
4156 		/*
4157 		 * tcp_tconnind_started == B_TRUE means that the
4158 		 * conn_ind has already gone to listener. At
4159 		 * this point, eager will be closed but we
4160 		 * leave it in listeners eager list so that
4161 		 * if listener decides to close without doing
4162 		 * accept, we can clean this up. In tcp_wput_accept
4163 		 * we take care of the case of accept on closed
4164 		 * eager.
4165 		 */
4166 		if (!tcp->tcp_tconnind_started) {
4167 			tcp_eager_unlink(tcp);
4168 			mutex_exit(&listener->tcp_eager_lock);
4169 			/*
4170 			 * We don't want to have any pointers to the
4171 			 * listener queue, after we have released our
4172 			 * reference on the listener
4173 			 */
4174 			ASSERT(tcps->tcps_g_q != NULL);
4175 			tcp->tcp_rq = tcps->tcps_g_q;
4176 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4177 			CONN_DEC_REF(listener->tcp_connp);
4178 		} else {
4179 			mutex_exit(&listener->tcp_eager_lock);
4180 		}
4181 	}
4182 
4183 	/* Stop all the timers */
4184 	tcp_timers_stop(tcp);
4185 
4186 	if (tcp->tcp_state == TCPS_LISTEN) {
4187 		if (tcp->tcp_ip_addr_cache) {
4188 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4189 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4190 			tcp->tcp_ip_addr_cache = NULL;
4191 		}
4192 	}
4193 	mutex_enter(&tcp->tcp_non_sq_lock);
4194 	if (tcp->tcp_flow_stopped)
4195 		tcp_clrqfull(tcp);
4196 	mutex_exit(&tcp->tcp_non_sq_lock);
4197 
4198 	tcp_bind_hash_remove(tcp);
4199 	/*
4200 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4201 	 * is trying to remove this tcp from the time wait list, we will
4202 	 * block in tcp_time_wait_remove while trying to acquire the
4203 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4204 	 * requires the ipcl_hash_remove to be ordered after the
4205 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4206 	 */
4207 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4208 		(void) tcp_time_wait_remove(tcp, NULL);
4209 	CL_INET_DISCONNECT(connp, tcp);
4210 	ipcl_hash_remove(connp);
4211 
4212 	/*
4213 	 * Delete the cached ire in conn_ire_cache and also mark
4214 	 * the conn as CONDEMNED
4215 	 */
4216 	mutex_enter(&connp->conn_lock);
4217 	connp->conn_state_flags |= CONN_CONDEMNED;
4218 	ire = connp->conn_ire_cache;
4219 	connp->conn_ire_cache = NULL;
4220 	mutex_exit(&connp->conn_lock);
4221 	if (ire != NULL)
4222 		IRE_REFRELE_NOTR(ire);
4223 
4224 	/* Need to cleanup any pending ioctls */
4225 	ASSERT(tcp->tcp_time_wait_next == NULL);
4226 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4227 	ASSERT(tcp->tcp_time_wait_expire == 0);
4228 	tcp->tcp_state = TCPS_CLOSED;
4229 
4230 	/* Release any SSL context */
4231 	if (tcp->tcp_kssl_ent != NULL) {
4232 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4233 		tcp->tcp_kssl_ent = NULL;
4234 	}
4235 	if (tcp->tcp_kssl_ctx != NULL) {
4236 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4237 		tcp->tcp_kssl_ctx = NULL;
4238 	}
4239 	tcp->tcp_kssl_pending = B_FALSE;
4240 
4241 	tcp_ipsec_cleanup(tcp);
4242 }
4243 
4244 /*
4245  * tcp is dying (called from ipcl_conn_destroy and error cases).
4246  * Free the tcp_t in either case.
4247  */
4248 void
4249 tcp_free(tcp_t *tcp)
4250 {
4251 	mblk_t	*mp;
4252 	ip6_pkt_t	*ipp;
4253 
4254 	ASSERT(tcp != NULL);
4255 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4256 
4257 	tcp->tcp_rq = NULL;
4258 	tcp->tcp_wq = NULL;
4259 
4260 	tcp_close_mpp(&tcp->tcp_xmit_head);
4261 	tcp_close_mpp(&tcp->tcp_reass_head);
4262 	if (tcp->tcp_rcv_list != NULL) {
4263 		/* Free b_next chain */
4264 		tcp_close_mpp(&tcp->tcp_rcv_list);
4265 	}
4266 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4267 		freemsg(mp);
4268 	}
4269 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4270 		freemsg(mp);
4271 	}
4272 
4273 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4274 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4275 		freeb(tcp->tcp_fused_sigurg_mp);
4276 		tcp->tcp_fused_sigurg_mp = NULL;
4277 	}
4278 
4279 	if (tcp->tcp_ordrel_mp != NULL) {
4280 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4281 		freeb(tcp->tcp_ordrel_mp);
4282 		tcp->tcp_ordrel_mp = NULL;
4283 	}
4284 
4285 	if (tcp->tcp_sack_info != NULL) {
4286 		if (tcp->tcp_notsack_list != NULL) {
4287 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4288 		}
4289 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4290 	}
4291 
4292 	if (tcp->tcp_hopopts != NULL) {
4293 		mi_free(tcp->tcp_hopopts);
4294 		tcp->tcp_hopopts = NULL;
4295 		tcp->tcp_hopoptslen = 0;
4296 	}
4297 	ASSERT(tcp->tcp_hopoptslen == 0);
4298 	if (tcp->tcp_dstopts != NULL) {
4299 		mi_free(tcp->tcp_dstopts);
4300 		tcp->tcp_dstopts = NULL;
4301 		tcp->tcp_dstoptslen = 0;
4302 	}
4303 	ASSERT(tcp->tcp_dstoptslen == 0);
4304 	if (tcp->tcp_rtdstopts != NULL) {
4305 		mi_free(tcp->tcp_rtdstopts);
4306 		tcp->tcp_rtdstopts = NULL;
4307 		tcp->tcp_rtdstoptslen = 0;
4308 	}
4309 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4310 	if (tcp->tcp_rthdr != NULL) {
4311 		mi_free(tcp->tcp_rthdr);
4312 		tcp->tcp_rthdr = NULL;
4313 		tcp->tcp_rthdrlen = 0;
4314 	}
4315 	ASSERT(tcp->tcp_rthdrlen == 0);
4316 
4317 	ipp = &tcp->tcp_sticky_ipp;
4318 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4319 	    IPPF_RTHDR))
4320 		ip6_pkt_free(ipp);
4321 
4322 	/*
4323 	 * Free memory associated with the tcp/ip header template.
4324 	 */
4325 
4326 	if (tcp->tcp_iphc != NULL)
4327 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4328 
4329 	/*
4330 	 * Following is really a blowing away a union.
4331 	 * It happens to have exactly two members of identical size
4332 	 * the following code is enough.
4333 	 */
4334 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4335 }
4336 
4337 
4338 /*
4339  * Put a connection confirmation message upstream built from the
4340  * address information within 'iph' and 'tcph'.  Report our success or failure.
4341  */
4342 static boolean_t
4343 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4344     mblk_t **defermp)
4345 {
4346 	sin_t	sin;
4347 	sin6_t	sin6;
4348 	mblk_t	*mp;
4349 	char	*optp = NULL;
4350 	int	optlen = 0;
4351 
4352 	if (defermp != NULL)
4353 		*defermp = NULL;
4354 
4355 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4356 		/*
4357 		 * Return in T_CONN_CON results of option negotiation through
4358 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4359 		 * negotiation, then what is received from remote end needs
4360 		 * to be taken into account but there is no such thing (yet?)
4361 		 * in our TCP/IP.
4362 		 * Note: We do not use mi_offset_param() here as
4363 		 * tcp_opts_conn_req contents do not directly come from
4364 		 * an application and are either generated in kernel or
4365 		 * from user input that was already verified.
4366 		 */
4367 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4368 		optp = (char *)(mp->b_rptr +
4369 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4370 		optlen = (int)
4371 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4372 	}
4373 
4374 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4375 		ipha_t *ipha = (ipha_t *)iphdr;
4376 
4377 		/* packet is IPv4 */
4378 		if (tcp->tcp_family == AF_INET) {
4379 			sin = sin_null;
4380 			sin.sin_addr.s_addr = ipha->ipha_src;
4381 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4382 			sin.sin_family = AF_INET;
4383 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4384 			    (int)sizeof (sin_t), optp, optlen);
4385 		} else {
4386 			sin6 = sin6_null;
4387 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4388 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4389 			sin6.sin6_family = AF_INET6;
4390 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4391 			    (int)sizeof (sin6_t), optp, optlen);
4392 
4393 		}
4394 	} else {
4395 		ip6_t	*ip6h = (ip6_t *)iphdr;
4396 
4397 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4398 		ASSERT(tcp->tcp_family == AF_INET6);
4399 		sin6 = sin6_null;
4400 		sin6.sin6_addr = ip6h->ip6_src;
4401 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4402 		sin6.sin6_family = AF_INET6;
4403 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4404 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4405 		    (int)sizeof (sin6_t), optp, optlen);
4406 	}
4407 
4408 	if (!mp)
4409 		return (B_FALSE);
4410 
4411 	mblk_copycred(mp, idmp);
4412 
4413 	if (defermp == NULL) {
4414 		conn_t *connp = tcp->tcp_connp;
4415 		if (IPCL_IS_NONSTR(connp)) {
4416 			cred_t *cr;
4417 			pid_t cpid;
4418 
4419 			cr = msg_getcred(mp, &cpid);
4420 			(*connp->conn_upcalls->su_connected)
4421 			    (connp->conn_upper_handle, tcp->tcp_connid, cr,
4422 			    cpid);
4423 			freemsg(mp);
4424 		} else {
4425 			putnext(tcp->tcp_rq, mp);
4426 		}
4427 	} else {
4428 		*defermp = mp;
4429 	}
4430 
4431 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4432 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4433 	return (B_TRUE);
4434 }
4435 
4436 /*
4437  * Defense for the SYN attack -
4438  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4439  *    one from the list of droppable eagers. This list is a subset of q0.
4440  *    see comments before the definition of MAKE_DROPPABLE().
4441  * 2. Don't drop a SYN request before its first timeout. This gives every
4442  *    request at least til the first timeout to complete its 3-way handshake.
4443  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4444  *    requests currently on the queue that has timed out. This will be used
4445  *    as an indicator of whether an attack is under way, so that appropriate
4446  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4447  *    either when eager goes into ESTABLISHED, or gets freed up.)
4448  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4449  *    # of timeout drops back to <= q0len/32 => SYN alert off
4450  */
4451 static boolean_t
4452 tcp_drop_q0(tcp_t *tcp)
4453 {
4454 	tcp_t	*eager;
4455 	mblk_t	*mp;
4456 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4457 
4458 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4459 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4460 
4461 	/* Pick oldest eager from the list of droppable eagers */
4462 	eager = tcp->tcp_eager_prev_drop_q0;
4463 
4464 	/* If list is empty. return B_FALSE */
4465 	if (eager == tcp) {
4466 		return (B_FALSE);
4467 	}
4468 
4469 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4470 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4471 		return (B_FALSE);
4472 
4473 	/*
4474 	 * Take this eager out from the list of droppable eagers since we are
4475 	 * going to drop it.
4476 	 */
4477 	MAKE_UNDROPPABLE(eager);
4478 
4479 	if (tcp->tcp_debug) {
4480 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4481 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4482 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4483 		    tcp->tcp_conn_req_cnt_q0,
4484 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4485 	}
4486 
4487 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4488 
4489 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4490 	CONN_INC_REF(eager->tcp_connp);
4491 
4492 	/* Mark the IRE created for this SYN request temporary */
4493 	tcp_ip_ire_mark_advice(eager);
4494 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4495 	    tcp_clean_death_wrapper, eager->tcp_connp,
4496 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4497 
4498 	return (B_TRUE);
4499 }
4500 
4501 int
4502 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4503     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4504 {
4505 	tcp_t 		*ltcp = lconnp->conn_tcp;
4506 	tcp_t		*tcp = connp->conn_tcp;
4507 	mblk_t		*tpi_mp;
4508 	ipha_t		*ipha;
4509 	ip6_t		*ip6h;
4510 	sin6_t 		sin6;
4511 	in6_addr_t 	v6dst;
4512 	int		err;
4513 	int		ifindex = 0;
4514 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4515 
4516 	if (ipvers == IPV4_VERSION) {
4517 		ipha = (ipha_t *)mp->b_rptr;
4518 
4519 		connp->conn_send = ip_output;
4520 		connp->conn_recv = tcp_input;
4521 
4522 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4523 		    &connp->conn_bound_source_v6);
4524 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4525 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4526 
4527 		sin6 = sin6_null;
4528 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4529 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4530 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4531 		sin6.sin6_family = AF_INET6;
4532 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4533 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4534 		if (tcp->tcp_recvdstaddr) {
4535 			sin6_t	sin6d;
4536 
4537 			sin6d = sin6_null;
4538 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4539 			    &sin6d.sin6_addr);
4540 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4541 			sin6d.sin6_family = AF_INET;
4542 			tpi_mp = mi_tpi_extconn_ind(NULL,
4543 			    (char *)&sin6d, sizeof (sin6_t),
4544 			    (char *)&tcp,
4545 			    (t_scalar_t)sizeof (intptr_t),
4546 			    (char *)&sin6d, sizeof (sin6_t),
4547 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4548 		} else {
4549 			tpi_mp = mi_tpi_conn_ind(NULL,
4550 			    (char *)&sin6, sizeof (sin6_t),
4551 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4552 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4553 		}
4554 	} else {
4555 		ip6h = (ip6_t *)mp->b_rptr;
4556 
4557 		connp->conn_send = ip_output_v6;
4558 		connp->conn_recv = tcp_input;
4559 
4560 		connp->conn_bound_source_v6 = ip6h->ip6_dst;
4561 		connp->conn_srcv6 = ip6h->ip6_dst;
4562 		connp->conn_remv6 = ip6h->ip6_src;
4563 
4564 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4565 		ifindex = (int)DB_CKSUMSTUFF(mp);
4566 		DB_CKSUMSTUFF(mp) = 0;
4567 
4568 		sin6 = sin6_null;
4569 		sin6.sin6_addr = ip6h->ip6_src;
4570 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4571 		sin6.sin6_family = AF_INET6;
4572 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4573 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4574 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4575 
4576 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4577 			/* Pass up the scope_id of remote addr */
4578 			sin6.sin6_scope_id = ifindex;
4579 		} else {
4580 			sin6.sin6_scope_id = 0;
4581 		}
4582 		if (tcp->tcp_recvdstaddr) {
4583 			sin6_t	sin6d;
4584 
4585 			sin6d = sin6_null;
4586 			sin6.sin6_addr = ip6h->ip6_dst;
4587 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4588 			sin6d.sin6_family = AF_INET;
4589 			tpi_mp = mi_tpi_extconn_ind(NULL,
4590 			    (char *)&sin6d, sizeof (sin6_t),
4591 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4592 			    (char *)&sin6d, sizeof (sin6_t),
4593 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4594 		} else {
4595 			tpi_mp = mi_tpi_conn_ind(NULL,
4596 			    (char *)&sin6, sizeof (sin6_t),
4597 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4598 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4599 		}
4600 	}
4601 
4602 	if (tpi_mp == NULL)
4603 		return (ENOMEM);
4604 
4605 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4606 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4607 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4608 	connp->conn_fully_bound = B_FALSE;
4609 
4610 	/* Inherit information from the "parent" */
4611 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4612 	tcp->tcp_family = ltcp->tcp_family;
4613 
4614 	tcp->tcp_wq = ltcp->tcp_wq;
4615 	tcp->tcp_rq = ltcp->tcp_rq;
4616 
4617 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4618 	tcp->tcp_detached = B_TRUE;
4619 	SOCK_CONNID_INIT(tcp->tcp_connid);
4620 	if ((err = tcp_init_values(tcp)) != 0) {
4621 		freemsg(tpi_mp);
4622 		return (err);
4623 	}
4624 
4625 	if (ipvers == IPV4_VERSION) {
4626 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4627 			freemsg(tpi_mp);
4628 			return (err);
4629 		}
4630 		ASSERT(tcp->tcp_ipha != NULL);
4631 	} else {
4632 		/* ifindex must be already set */
4633 		ASSERT(ifindex != 0);
4634 
4635 		if (ltcp->tcp_bound_if != 0)
4636 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4637 		else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src))
4638 			tcp->tcp_bound_if = ifindex;
4639 
4640 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4641 		tcp->tcp_recvifindex = 0;
4642 		tcp->tcp_recvhops = 0xffffffffU;
4643 		ASSERT(tcp->tcp_ip6h != NULL);
4644 	}
4645 
4646 	tcp->tcp_lport = ltcp->tcp_lport;
4647 
4648 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4649 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4650 			/*
4651 			 * Listener had options of some sort; eager inherits.
4652 			 * Free up the eager template and allocate one
4653 			 * of the right size.
4654 			 */
4655 			if (tcp->tcp_hdr_grown) {
4656 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4657 			} else {
4658 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4659 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4660 			}
4661 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4662 			    KM_NOSLEEP);
4663 			if (tcp->tcp_iphc == NULL) {
4664 				tcp->tcp_iphc_len = 0;
4665 				freemsg(tpi_mp);
4666 				return (ENOMEM);
4667 			}
4668 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4669 			tcp->tcp_hdr_grown = B_TRUE;
4670 		}
4671 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4672 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4673 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4674 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4675 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4676 
4677 		/*
4678 		 * Copy the IP+TCP header template from listener to eager
4679 		 */
4680 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4681 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4682 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4683 			    IPPROTO_RAW) {
4684 				tcp->tcp_ip6h =
4685 				    (ip6_t *)(tcp->tcp_iphc +
4686 				    sizeof (ip6i_t));
4687 			} else {
4688 				tcp->tcp_ip6h =
4689 				    (ip6_t *)(tcp->tcp_iphc);
4690 			}
4691 			tcp->tcp_ipha = NULL;
4692 		} else {
4693 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4694 			tcp->tcp_ip6h = NULL;
4695 		}
4696 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4697 		    tcp->tcp_ip_hdr_len);
4698 	} else {
4699 		/*
4700 		 * only valid case when ipversion of listener and
4701 		 * eager differ is when listener is IPv6 and
4702 		 * eager is IPv4.
4703 		 * Eager header template has been initialized to the
4704 		 * maximum v4 header sizes, which includes space for
4705 		 * TCP and IP options.
4706 		 */
4707 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4708 		    (tcp->tcp_ipversion == IPV4_VERSION));
4709 		ASSERT(tcp->tcp_iphc_len >=
4710 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4711 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4712 		/* copy IP header fields individually */
4713 		tcp->tcp_ipha->ipha_ttl =
4714 		    ltcp->tcp_ip6h->ip6_hops;
4715 		bcopy(ltcp->tcp_tcph->th_lport,
4716 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4717 	}
4718 
4719 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4720 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4721 	    sizeof (in_port_t));
4722 
4723 	if (ltcp->tcp_lport == 0) {
4724 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4725 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4726 		    sizeof (in_port_t));
4727 	}
4728 
4729 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4730 		ASSERT(ipha != NULL);
4731 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4732 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4733 
4734 		/* Source routing option copyover (reverse it) */
4735 		if (tcps->tcps_rev_src_routes)
4736 			tcp_opt_reverse(tcp, ipha);
4737 	} else {
4738 		ASSERT(ip6h != NULL);
4739 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4740 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4741 	}
4742 
4743 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4744 	ASSERT(!tcp->tcp_tconnind_started);
4745 	/*
4746 	 * If the SYN contains a credential, it's a loopback packet; attach
4747 	 * the credential to the TPI message.
4748 	 */
4749 	mblk_copycred(tpi_mp, idmp);
4750 
4751 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4752 
4753 	/* Inherit the listener's SSL protection state */
4754 
4755 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4756 		kssl_hold_ent(tcp->tcp_kssl_ent);
4757 		tcp->tcp_kssl_pending = B_TRUE;
4758 	}
4759 
4760 	/* Inherit the listener's non-STREAMS flag */
4761 	if (IPCL_IS_NONSTR(lconnp)) {
4762 		connp->conn_flags |= IPCL_NONSTR;
4763 	}
4764 
4765 	return (0);
4766 }
4767 
4768 
4769 int
4770 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4771     tcph_t *tcph, mblk_t *idmp)
4772 {
4773 	tcp_t 		*ltcp = lconnp->conn_tcp;
4774 	tcp_t		*tcp = connp->conn_tcp;
4775 	sin_t		sin;
4776 	mblk_t		*tpi_mp = NULL;
4777 	int		err;
4778 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4779 
4780 	sin = sin_null;
4781 	sin.sin_addr.s_addr = ipha->ipha_src;
4782 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4783 	sin.sin_family = AF_INET;
4784 	if (ltcp->tcp_recvdstaddr) {
4785 		sin_t	sind;
4786 
4787 		sind = sin_null;
4788 		sind.sin_addr.s_addr = ipha->ipha_dst;
4789 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4790 		sind.sin_family = AF_INET;
4791 		tpi_mp = mi_tpi_extconn_ind(NULL,
4792 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4793 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4794 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4795 	} else {
4796 		tpi_mp = mi_tpi_conn_ind(NULL,
4797 		    (char *)&sin, sizeof (sin_t),
4798 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4799 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4800 	}
4801 
4802 	if (tpi_mp == NULL) {
4803 		return (ENOMEM);
4804 	}
4805 
4806 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4807 	connp->conn_send = ip_output;
4808 	connp->conn_recv = tcp_input;
4809 	connp->conn_fully_bound = B_FALSE;
4810 
4811 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_bound_source_v6);
4812 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4813 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4814 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4815 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4816 
4817 	/* Inherit information from the "parent" */
4818 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4819 	tcp->tcp_family = ltcp->tcp_family;
4820 	tcp->tcp_wq = ltcp->tcp_wq;
4821 	tcp->tcp_rq = ltcp->tcp_rq;
4822 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4823 	tcp->tcp_detached = B_TRUE;
4824 	SOCK_CONNID_INIT(tcp->tcp_connid);
4825 	if ((err = tcp_init_values(tcp)) != 0) {
4826 		freemsg(tpi_mp);
4827 		return (err);
4828 	}
4829 
4830 	/*
4831 	 * Let's make sure that eager tcp template has enough space to
4832 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4833 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4834 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4835 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4836 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4837 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4838 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4839 	 */
4840 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4841 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4842 
4843 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4844 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4845 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4846 	tcp->tcp_ttl = ltcp->tcp_ttl;
4847 	tcp->tcp_tos = ltcp->tcp_tos;
4848 
4849 	/* Copy the IP+TCP header template from listener to eager */
4850 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4851 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4852 	tcp->tcp_ip6h = NULL;
4853 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4854 	    tcp->tcp_ip_hdr_len);
4855 
4856 	/* Initialize the IP addresses and Ports */
4857 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4858 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4859 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4860 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4861 
4862 	/* Source routing option copyover (reverse it) */
4863 	if (tcps->tcps_rev_src_routes)
4864 		tcp_opt_reverse(tcp, ipha);
4865 
4866 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4867 	ASSERT(!tcp->tcp_tconnind_started);
4868 
4869 	/*
4870 	 * If the SYN contains a credential, it's a loopback packet; attach
4871 	 * the credential to the TPI message.
4872 	 */
4873 	mblk_copycred(tpi_mp, idmp);
4874 
4875 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4876 
4877 	/* Inherit the listener's SSL protection state */
4878 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4879 		kssl_hold_ent(tcp->tcp_kssl_ent);
4880 		tcp->tcp_kssl_pending = B_TRUE;
4881 	}
4882 
4883 	/* Inherit the listener's non-STREAMS flag */
4884 	if (IPCL_IS_NONSTR(lconnp)) {
4885 		connp->conn_flags |= IPCL_NONSTR;
4886 	}
4887 
4888 	return (0);
4889 }
4890 
4891 /*
4892  * sets up conn for ipsec.
4893  * if the first mblk is M_CTL it is consumed and mpp is updated.
4894  * in case of error mpp is freed.
4895  */
4896 conn_t *
4897 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4898 {
4899 	conn_t 		*connp = tcp->tcp_connp;
4900 	conn_t 		*econnp;
4901 	squeue_t 	*new_sqp;
4902 	mblk_t 		*first_mp = *mpp;
4903 	mblk_t		*mp = *mpp;
4904 	boolean_t	mctl_present = B_FALSE;
4905 	uint_t		ipvers;
4906 
4907 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
4908 	if (econnp == NULL) {
4909 		freemsg(first_mp);
4910 		return (NULL);
4911 	}
4912 	if (DB_TYPE(mp) == M_CTL) {
4913 		if (mp->b_cont == NULL ||
4914 		    mp->b_cont->b_datap->db_type != M_DATA) {
4915 			freemsg(first_mp);
4916 			return (NULL);
4917 		}
4918 		mp = mp->b_cont;
4919 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4920 			freemsg(first_mp);
4921 			return (NULL);
4922 		}
4923 
4924 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4925 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4926 		mctl_present = B_TRUE;
4927 	} else {
4928 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4929 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4930 	}
4931 
4932 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4933 	DB_CKSUMSTART(mp) = 0;
4934 
4935 	ASSERT(OK_32PTR(mp->b_rptr));
4936 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
4937 	if (ipvers == IPV4_VERSION) {
4938 		uint16_t  	*up;
4939 		uint32_t	ports;
4940 		ipha_t		*ipha;
4941 
4942 		ipha = (ipha_t *)mp->b_rptr;
4943 		up = (uint16_t *)((uchar_t *)ipha +
4944 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
4945 		ports = *(uint32_t *)up;
4946 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
4947 		    ipha->ipha_dst, ipha->ipha_src, ports);
4948 	} else {
4949 		uint16_t  	*up;
4950 		uint32_t	ports;
4951 		uint16_t	ip_hdr_len;
4952 		uint8_t		*nexthdrp;
4953 		ip6_t 		*ip6h;
4954 		tcph_t		*tcph;
4955 
4956 		ip6h = (ip6_t *)mp->b_rptr;
4957 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
4958 			ip_hdr_len = IPV6_HDR_LEN;
4959 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
4960 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
4961 			CONN_DEC_REF(econnp);
4962 			freemsg(first_mp);
4963 			return (NULL);
4964 		}
4965 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
4966 		up = (uint16_t *)tcph->th_lport;
4967 		ports = *(uint32_t *)up;
4968 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
4969 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
4970 	}
4971 
4972 	/*
4973 	 * The caller already ensured that there is a sqp present.
4974 	 */
4975 	econnp->conn_sqp = new_sqp;
4976 	econnp->conn_initial_sqp = new_sqp;
4977 
4978 	if (connp->conn_policy != NULL) {
4979 		ipsec_in_t *ii;
4980 		ii = (ipsec_in_t *)(first_mp->b_rptr);
4981 		ASSERT(ii->ipsec_in_policy == NULL);
4982 		IPPH_REFHOLD(connp->conn_policy);
4983 		ii->ipsec_in_policy = connp->conn_policy;
4984 
4985 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
4986 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
4987 			CONN_DEC_REF(econnp);
4988 			freemsg(first_mp);
4989 			return (NULL);
4990 		}
4991 	}
4992 
4993 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
4994 		CONN_DEC_REF(econnp);
4995 		freemsg(first_mp);
4996 		return (NULL);
4997 	}
4998 
4999 	/*
5000 	 * If we know we have some policy, pass the "IPSEC"
5001 	 * options size TCP uses this adjust the MSS.
5002 	 */
5003 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5004 	if (mctl_present) {
5005 		freeb(first_mp);
5006 		*mpp = mp;
5007 	}
5008 
5009 	return (econnp);
5010 }
5011 
5012 /*
5013  * tcp_get_conn/tcp_free_conn
5014  *
5015  * tcp_get_conn is used to get a clean tcp connection structure.
5016  * It tries to reuse the connections put on the freelist by the
5017  * time_wait_collector failing which it goes to kmem_cache. This
5018  * way has two benefits compared to just allocating from and
5019  * freeing to kmem_cache.
5020  * 1) The time_wait_collector can free (which includes the cleanup)
5021  * outside the squeue. So when the interrupt comes, we have a clean
5022  * connection sitting in the freelist. Obviously, this buys us
5023  * performance.
5024  *
5025  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5026  * has multiple disadvantages - tying up the squeue during alloc, and the
5027  * fact that IPSec policy initialization has to happen here which
5028  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5029  * But allocating the conn/tcp in IP land is also not the best since
5030  * we can't check the 'q' and 'q0' which are protected by squeue and
5031  * blindly allocate memory which might have to be freed here if we are
5032  * not allowed to accept the connection. By using the freelist and
5033  * putting the conn/tcp back in freelist, we don't pay a penalty for
5034  * allocating memory without checking 'q/q0' and freeing it if we can't
5035  * accept the connection.
5036  *
5037  * Care should be taken to put the conn back in the same squeue's freelist
5038  * from which it was allocated. Best results are obtained if conn is
5039  * allocated from listener's squeue and freed to the same. Time wait
5040  * collector will free up the freelist is the connection ends up sitting
5041  * there for too long.
5042  */
5043 void *
5044 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5045 {
5046 	tcp_t			*tcp = NULL;
5047 	conn_t			*connp = NULL;
5048 	squeue_t		*sqp = (squeue_t *)arg;
5049 	tcp_squeue_priv_t 	*tcp_time_wait;
5050 	netstack_t		*ns;
5051 
5052 	tcp_time_wait =
5053 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5054 
5055 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5056 	tcp = tcp_time_wait->tcp_free_list;
5057 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5058 	if (tcp != NULL) {
5059 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5060 		tcp_time_wait->tcp_free_list_cnt--;
5061 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5062 		tcp->tcp_time_wait_next = NULL;
5063 		connp = tcp->tcp_connp;
5064 		connp->conn_flags |= IPCL_REUSED;
5065 
5066 		ASSERT(tcp->tcp_tcps == NULL);
5067 		ASSERT(connp->conn_netstack == NULL);
5068 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5069 		ns = tcps->tcps_netstack;
5070 		netstack_hold(ns);
5071 		connp->conn_netstack = ns;
5072 		tcp->tcp_tcps = tcps;
5073 		TCPS_REFHOLD(tcps);
5074 		ipcl_globalhash_insert(connp);
5075 		return ((void *)connp);
5076 	}
5077 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5078 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5079 	    tcps->tcps_netstack)) == NULL)
5080 		return (NULL);
5081 	tcp = connp->conn_tcp;
5082 	/*
5083 	 * Pre-allocate the tcp_rsrv_mp.  This mblk will not be freed
5084 	 * until this conn_t/tcp_t is freed at ipcl_conn_destroy().
5085 	 */
5086 	if ((tcp->tcp_rsrv_mp = allocb(0, BPRI_HI)) == NULL) {
5087 		ipcl_conn_destroy(connp);
5088 		return (NULL);
5089 	}
5090 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5091 	tcp->tcp_tcps = tcps;
5092 	TCPS_REFHOLD(tcps);
5093 
5094 	return ((void *)connp);
5095 }
5096 
5097 /*
5098  * Update the cached label for the given tcp_t.  This should be called once per
5099  * connection, and before any packets are sent or tcp_process_options is
5100  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5101  */
5102 static boolean_t
5103 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5104 {
5105 	conn_t *connp = tcp->tcp_connp;
5106 
5107 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5108 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5109 		int added;
5110 
5111 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5112 		    connp->conn_mac_exempt,
5113 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5114 			return (B_FALSE);
5115 
5116 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5117 		if (added == -1)
5118 			return (B_FALSE);
5119 		tcp->tcp_hdr_len += added;
5120 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5121 		tcp->tcp_ip_hdr_len += added;
5122 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5123 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5124 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5125 			    tcp->tcp_hdr_len);
5126 			if (added == -1)
5127 				return (B_FALSE);
5128 			tcp->tcp_hdr_len += added;
5129 			tcp->tcp_tcph = (tcph_t *)
5130 			    ((uchar_t *)tcp->tcp_tcph + added);
5131 			tcp->tcp_ip_hdr_len += added;
5132 		}
5133 	} else {
5134 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5135 
5136 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5137 		    connp->conn_mac_exempt,
5138 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5139 			return (B_FALSE);
5140 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5141 		    &tcp->tcp_label_len, optbuf) != 0)
5142 			return (B_FALSE);
5143 		if (tcp_build_hdrs(tcp) != 0)
5144 			return (B_FALSE);
5145 	}
5146 
5147 	connp->conn_ulp_labeled = 1;
5148 
5149 	return (B_TRUE);
5150 }
5151 
5152 /* BEGIN CSTYLED */
5153 /*
5154  *
5155  * The sockfs ACCEPT path:
5156  * =======================
5157  *
5158  * The eager is now established in its own perimeter as soon as SYN is
5159  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5160  * completes the accept processing on the acceptor STREAM. The sending
5161  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5162  * listener but a TLI/XTI listener completes the accept processing
5163  * on the listener perimeter.
5164  *
5165  * Common control flow for 3 way handshake:
5166  * ----------------------------------------
5167  *
5168  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5169  *					-> tcp_conn_request()
5170  *
5171  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5172  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5173  *
5174  * Sockfs ACCEPT Path:
5175  * -------------------
5176  *
5177  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5178  * as STREAM entry point)
5179  *
5180  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5181  *
5182  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5183  * association (we are not behind eager's squeue but sockfs is protecting us
5184  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5185  * is changed to point at tcp_wput().
5186  *
5187  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5188  * listener (done on listener's perimeter).
5189  *
5190  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5191  * accept.
5192  *
5193  * TLI/XTI client ACCEPT path:
5194  * ---------------------------
5195  *
5196  * soaccept() sends T_CONN_RES on the listener STREAM.
5197  *
5198  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5199  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5200  *
5201  * Locks:
5202  * ======
5203  *
5204  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5205  * and listeners->tcp_eager_next_q.
5206  *
5207  * Referencing:
5208  * ============
5209  *
5210  * 1) We start out in tcp_conn_request by eager placing a ref on
5211  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5212  *
5213  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5214  * doing so we place a ref on the eager. This ref is finally dropped at the
5215  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5216  * reference is dropped by the squeue framework.
5217  *
5218  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5219  *
5220  * The reference must be released by the same entity that added the reference
5221  * In the above scheme, the eager is the entity that adds and releases the
5222  * references. Note that tcp_accept_finish executes in the squeue of the eager
5223  * (albeit after it is attached to the acceptor stream). Though 1. executes
5224  * in the listener's squeue, the eager is nascent at this point and the
5225  * reference can be considered to have been added on behalf of the eager.
5226  *
5227  * Eager getting a Reset or listener closing:
5228  * ==========================================
5229  *
5230  * Once the listener and eager are linked, the listener never does the unlink.
5231  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5232  * a message on all eager perimeter. The eager then does the unlink, clears
5233  * any pointers to the listener's queue and drops the reference to the
5234  * listener. The listener waits in tcp_close outside the squeue until its
5235  * refcount has dropped to 1. This ensures that the listener has waited for
5236  * all eagers to clear their association with the listener.
5237  *
5238  * Similarly, if eager decides to go away, it can unlink itself and close.
5239  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5240  * the reference to eager is still valid because of the extra ref we put
5241  * in tcp_send_conn_ind.
5242  *
5243  * Listener can always locate the eager under the protection
5244  * of the listener->tcp_eager_lock, and then do a refhold
5245  * on the eager during the accept processing.
5246  *
5247  * The acceptor stream accesses the eager in the accept processing
5248  * based on the ref placed on eager before sending T_conn_ind.
5249  * The only entity that can negate this refhold is a listener close
5250  * which is mutually exclusive with an active acceptor stream.
5251  *
5252  * Eager's reference on the listener
5253  * ===================================
5254  *
5255  * If the accept happens (even on a closed eager) the eager drops its
5256  * reference on the listener at the start of tcp_accept_finish. If the
5257  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5258  * the reference is dropped in tcp_closei_local. If the listener closes,
5259  * the reference is dropped in tcp_eager_kill. In all cases the reference
5260  * is dropped while executing in the eager's context (squeue).
5261  */
5262 /* END CSTYLED */
5263 
5264 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5265 
5266 /*
5267  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5268  * tcp_rput_data will not see any SYN packets.
5269  */
5270 /* ARGSUSED */
5271 void
5272 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5273 {
5274 	tcph_t		*tcph;
5275 	uint32_t	seg_seq;
5276 	tcp_t		*eager;
5277 	uint_t		ipvers;
5278 	ipha_t		*ipha;
5279 	ip6_t		*ip6h;
5280 	int		err;
5281 	conn_t		*econnp = NULL;
5282 	squeue_t	*new_sqp;
5283 	mblk_t		*mp1;
5284 	uint_t 		ip_hdr_len;
5285 	conn_t		*connp = (conn_t *)arg;
5286 	tcp_t		*tcp = connp->conn_tcp;
5287 	cred_t		*credp;
5288 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5289 	ip_stack_t	*ipst;
5290 
5291 	if (tcp->tcp_state != TCPS_LISTEN)
5292 		goto error2;
5293 
5294 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5295 
5296 	mutex_enter(&tcp->tcp_eager_lock);
5297 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5298 		mutex_exit(&tcp->tcp_eager_lock);
5299 		TCP_STAT(tcps, tcp_listendrop);
5300 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5301 		if (tcp->tcp_debug) {
5302 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5303 			    "tcp_conn_request: listen backlog (max=%d) "
5304 			    "overflow (%d pending) on %s",
5305 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5306 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5307 		}
5308 		goto error2;
5309 	}
5310 
5311 	if (tcp->tcp_conn_req_cnt_q0 >=
5312 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5313 		/*
5314 		 * Q0 is full. Drop a pending half-open req from the queue
5315 		 * to make room for the new SYN req. Also mark the time we
5316 		 * drop a SYN.
5317 		 *
5318 		 * A more aggressive defense against SYN attack will
5319 		 * be to set the "tcp_syn_defense" flag now.
5320 		 */
5321 		TCP_STAT(tcps, tcp_listendropq0);
5322 		tcp->tcp_last_rcv_lbolt = lbolt64;
5323 		if (!tcp_drop_q0(tcp)) {
5324 			mutex_exit(&tcp->tcp_eager_lock);
5325 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5326 			if (tcp->tcp_debug) {
5327 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5328 				    "tcp_conn_request: listen half-open queue "
5329 				    "(max=%d) full (%d pending) on %s",
5330 				    tcps->tcps_conn_req_max_q0,
5331 				    tcp->tcp_conn_req_cnt_q0,
5332 				    tcp_display(tcp, NULL,
5333 				    DISP_PORT_ONLY));
5334 			}
5335 			goto error2;
5336 		}
5337 	}
5338 	mutex_exit(&tcp->tcp_eager_lock);
5339 
5340 	/*
5341 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5342 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5343 	 * link local address.  If IPSec is enabled, db_struioflag has
5344 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5345 	 * otherwise an error case if neither of them is set.
5346 	 */
5347 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5348 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5349 		DB_CKSUMSTART(mp) = 0;
5350 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5351 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5352 		if (econnp == NULL)
5353 			goto error2;
5354 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5355 		econnp->conn_sqp = new_sqp;
5356 		econnp->conn_initial_sqp = new_sqp;
5357 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5358 		/*
5359 		 * mp is updated in tcp_get_ipsec_conn().
5360 		 */
5361 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5362 		if (econnp == NULL) {
5363 			/*
5364 			 * mp freed by tcp_get_ipsec_conn.
5365 			 */
5366 			return;
5367 		}
5368 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5369 	} else {
5370 		goto error2;
5371 	}
5372 
5373 	ASSERT(DB_TYPE(mp) == M_DATA);
5374 
5375 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5376 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5377 	ASSERT(OK_32PTR(mp->b_rptr));
5378 	if (ipvers == IPV4_VERSION) {
5379 		ipha = (ipha_t *)mp->b_rptr;
5380 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5381 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5382 	} else {
5383 		ip6h = (ip6_t *)mp->b_rptr;
5384 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5385 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5386 	}
5387 
5388 	if (tcp->tcp_family == AF_INET) {
5389 		ASSERT(ipvers == IPV4_VERSION);
5390 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5391 	} else {
5392 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5393 	}
5394 
5395 	if (err)
5396 		goto error3;
5397 
5398 	eager = econnp->conn_tcp;
5399 
5400 	/*
5401 	 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that at close
5402 	 * time, we will always have that to send up.  Otherwise, we need to do
5403 	 * special handling in case the allocation fails at that time.
5404 	 */
5405 	ASSERT(eager->tcp_ordrel_mp == NULL);
5406 	if (!IPCL_IS_NONSTR(econnp) &&
5407 	    (eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5408 		goto error3;
5409 
5410 	/* Inherit various TCP parameters from the listener */
5411 	eager->tcp_naglim = tcp->tcp_naglim;
5412 	eager->tcp_first_timer_threshold =
5413 	    tcp->tcp_first_timer_threshold;
5414 	eager->tcp_second_timer_threshold =
5415 	    tcp->tcp_second_timer_threshold;
5416 
5417 	eager->tcp_first_ctimer_threshold =
5418 	    tcp->tcp_first_ctimer_threshold;
5419 	eager->tcp_second_ctimer_threshold =
5420 	    tcp->tcp_second_ctimer_threshold;
5421 
5422 	/*
5423 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5424 	 * If it does not, the eager's receive window will be set to the
5425 	 * listener's receive window later in this function.
5426 	 */
5427 	eager->tcp_rwnd = 0;
5428 
5429 	/*
5430 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5431 	 * calling tcp_process_options() where tcp_mss_set() is called
5432 	 * to set the initial cwnd.
5433 	 */
5434 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5435 
5436 	/*
5437 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5438 	 * zone id before the accept is completed in tcp_wput_accept().
5439 	 */
5440 	econnp->conn_zoneid = connp->conn_zoneid;
5441 	econnp->conn_allzones = connp->conn_allzones;
5442 
5443 	/* Copy nexthop information from listener to eager */
5444 	if (connp->conn_nexthop_set) {
5445 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5446 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5447 	}
5448 
5449 	/*
5450 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5451 	 * eager is accepted
5452 	 */
5453 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5454 	crhold(credp);
5455 
5456 	/*
5457 	 * If the caller has the process-wide flag set, then default to MAC
5458 	 * exempt mode.  This allows read-down to unlabeled hosts.
5459 	 */
5460 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5461 		econnp->conn_mac_exempt = B_TRUE;
5462 
5463 	if (is_system_labeled()) {
5464 		cred_t *cr;
5465 
5466 		if (connp->conn_mlp_type != mlptSingle) {
5467 			cr = econnp->conn_peercred = msg_getcred(mp, NULL);
5468 			if (cr != NULL)
5469 				crhold(cr);
5470 			else
5471 				cr = econnp->conn_cred;
5472 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5473 			    econnp, cred_t *, cr)
5474 		} else {
5475 			cr = econnp->conn_cred;
5476 			DTRACE_PROBE2(syn_accept, conn_t *,
5477 			    econnp, cred_t *, cr)
5478 		}
5479 
5480 		if (!tcp_update_label(eager, cr)) {
5481 			DTRACE_PROBE3(
5482 			    tx__ip__log__error__connrequest__tcp,
5483 			    char *, "eager connp(1) label on SYN mp(2) failed",
5484 			    conn_t *, econnp, mblk_t *, mp);
5485 			goto error3;
5486 		}
5487 	}
5488 
5489 	eager->tcp_hard_binding = B_TRUE;
5490 
5491 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5492 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5493 
5494 	CL_INET_CONNECT(connp, eager, B_FALSE, err);
5495 	if (err != 0) {
5496 		tcp_bind_hash_remove(eager);
5497 		goto error3;
5498 	}
5499 
5500 	/*
5501 	 * No need to check for multicast destination since ip will only pass
5502 	 * up multicasts to those that have expressed interest
5503 	 * TODO: what about rejecting broadcasts?
5504 	 * Also check that source is not a multicast or broadcast address.
5505 	 */
5506 	eager->tcp_state = TCPS_SYN_RCVD;
5507 
5508 
5509 	/*
5510 	 * There should be no ire in the mp as we are being called after
5511 	 * receiving the SYN.
5512 	 */
5513 	ASSERT(tcp_ire_mp(&mp) == NULL);
5514 
5515 	/*
5516 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5517 	 */
5518 
5519 	if (tcp_adapt_ire(eager, NULL) == 0) {
5520 		/* Undo the bind_hash_insert */
5521 		tcp_bind_hash_remove(eager);
5522 		goto error3;
5523 	}
5524 
5525 	/* Process all TCP options. */
5526 	tcp_process_options(eager, tcph);
5527 
5528 	/* Is the other end ECN capable? */
5529 	if (tcps->tcps_ecn_permitted >= 1 &&
5530 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5531 		eager->tcp_ecn_ok = B_TRUE;
5532 	}
5533 
5534 	/*
5535 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5536 	 * window size changed via SO_RCVBUF option.  First round up the
5537 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5538 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5539 	 * setting.
5540 	 *
5541 	 * Note if there is a rpipe metric associated with the remote host,
5542 	 * we should not inherit receive window size from listener.
5543 	 */
5544 	eager->tcp_rwnd = MSS_ROUNDUP(
5545 	    (eager->tcp_rwnd == 0 ? tcp->tcp_recv_hiwater:
5546 	    eager->tcp_rwnd), eager->tcp_mss);
5547 	if (eager->tcp_snd_ws_ok)
5548 		tcp_set_ws_value(eager);
5549 	/*
5550 	 * Note that this is the only place tcp_rwnd_set() is called for
5551 	 * accepting a connection.  We need to call it here instead of
5552 	 * after the 3-way handshake because we need to tell the other
5553 	 * side our rwnd in the SYN-ACK segment.
5554 	 */
5555 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5556 
5557 	/*
5558 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5559 	 * via soaccept()->soinheritoptions() which essentially applies
5560 	 * all the listener options to the new STREAM. The options that we
5561 	 * need to take care of are:
5562 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5563 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5564 	 * SO_SNDBUF, SO_RCVBUF.
5565 	 *
5566 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5567 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5568 	 *		tcp_maxpsz_set() gets called later from
5569 	 *		tcp_accept_finish(), the option takes effect.
5570 	 *
5571 	 */
5572 	/* Set the TCP options */
5573 	eager->tcp_recv_hiwater = tcp->tcp_recv_hiwater;
5574 	eager->tcp_recv_lowater = tcp->tcp_recv_lowater;
5575 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5576 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5577 	eager->tcp_oobinline = tcp->tcp_oobinline;
5578 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5579 	eager->tcp_broadcast = tcp->tcp_broadcast;
5580 	eager->tcp_useloopback = tcp->tcp_useloopback;
5581 	eager->tcp_dontroute = tcp->tcp_dontroute;
5582 	eager->tcp_debug = tcp->tcp_debug;
5583 	eager->tcp_linger = tcp->tcp_linger;
5584 	eager->tcp_lingertime = tcp->tcp_lingertime;
5585 	if (tcp->tcp_ka_enabled)
5586 		eager->tcp_ka_enabled = 1;
5587 
5588 	/* Set the IP options */
5589 	econnp->conn_broadcast = connp->conn_broadcast;
5590 	econnp->conn_loopback = connp->conn_loopback;
5591 	econnp->conn_dontroute = connp->conn_dontroute;
5592 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5593 
5594 	/* Put a ref on the listener for the eager. */
5595 	CONN_INC_REF(connp);
5596 	mutex_enter(&tcp->tcp_eager_lock);
5597 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5598 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5599 	tcp->tcp_eager_next_q0 = eager;
5600 	eager->tcp_eager_prev_q0 = tcp;
5601 
5602 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5603 	eager->tcp_listener = tcp;
5604 	eager->tcp_saved_listener = tcp;
5605 
5606 	/*
5607 	 * Tag this detached tcp vector for later retrieval
5608 	 * by our listener client in tcp_accept().
5609 	 */
5610 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5611 	tcp->tcp_conn_req_cnt_q0++;
5612 	if (++tcp->tcp_conn_req_seqnum == -1) {
5613 		/*
5614 		 * -1 is "special" and defined in TPI as something
5615 		 * that should never be used in T_CONN_IND
5616 		 */
5617 		++tcp->tcp_conn_req_seqnum;
5618 	}
5619 	mutex_exit(&tcp->tcp_eager_lock);
5620 
5621 	if (tcp->tcp_syn_defense) {
5622 		/* Don't drop the SYN that comes from a good IP source */
5623 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5624 		if (addr_cache != NULL && eager->tcp_remote ==
5625 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5626 			eager->tcp_dontdrop = B_TRUE;
5627 		}
5628 	}
5629 
5630 	/*
5631 	 * We need to insert the eager in its own perimeter but as soon
5632 	 * as we do that, we expose the eager to the classifier and
5633 	 * should not touch any field outside the eager's perimeter.
5634 	 * So do all the work necessary before inserting the eager
5635 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5636 	 * will succeed but undo everything if it fails.
5637 	 */
5638 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5639 	eager->tcp_irs = seg_seq;
5640 	eager->tcp_rack = seg_seq;
5641 	eager->tcp_rnxt = seg_seq + 1;
5642 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5643 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5644 	eager->tcp_state = TCPS_SYN_RCVD;
5645 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5646 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5647 	if (mp1 == NULL) {
5648 		/*
5649 		 * Increment the ref count as we are going to
5650 		 * enqueueing an mp in squeue
5651 		 */
5652 		CONN_INC_REF(econnp);
5653 		goto error;
5654 	}
5655 
5656 	/*
5657 	 * Note that in theory this should use the current pid
5658 	 * so that getpeerucred on the client returns the actual listener
5659 	 * that does accept. But accept() hasn't been called yet. We could use
5660 	 * the pid of the process that did bind/listen on the server.
5661 	 * However, with common usage like inetd() the bind/listen can be done
5662 	 * by a different process than the accept().
5663 	 * Hence we do the simple thing of using the open pid here.
5664 	 * Note that db_credp is set later in tcp_send_data().
5665 	 */
5666 	mblk_setcred(mp1, credp, tcp->tcp_cpid);
5667 	eager->tcp_cpid = tcp->tcp_cpid;
5668 	eager->tcp_open_time = lbolt64;
5669 
5670 	/*
5671 	 * We need to start the rto timer. In normal case, we start
5672 	 * the timer after sending the packet on the wire (or at
5673 	 * least believing that packet was sent by waiting for
5674 	 * CALL_IP_WPUT() to return). Since this is the first packet
5675 	 * being sent on the wire for the eager, our initial tcp_rto
5676 	 * is at least tcp_rexmit_interval_min which is a fairly
5677 	 * large value to allow the algorithm to adjust slowly to large
5678 	 * fluctuations of RTT during first few transmissions.
5679 	 *
5680 	 * Starting the timer first and then sending the packet in this
5681 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5682 	 * is of the order of several 100ms and starting the timer
5683 	 * first and then sending the packet will result in difference
5684 	 * of few micro seconds.
5685 	 *
5686 	 * Without this optimization, we are forced to hold the fanout
5687 	 * lock across the ipcl_bind_insert() and sending the packet
5688 	 * so that we don't race against an incoming packet (maybe RST)
5689 	 * for this eager.
5690 	 *
5691 	 * It is necessary to acquire an extra reference on the eager
5692 	 * at this point and hold it until after tcp_send_data() to
5693 	 * ensure against an eager close race.
5694 	 */
5695 
5696 	CONN_INC_REF(eager->tcp_connp);
5697 
5698 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5699 
5700 	/*
5701 	 * Insert the eager in its own perimeter now. We are ready to deal
5702 	 * with any packets on eager.
5703 	 */
5704 	if (eager->tcp_ipversion == IPV4_VERSION) {
5705 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5706 			goto error;
5707 		}
5708 	} else {
5709 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5710 			goto error;
5711 		}
5712 	}
5713 
5714 	/* mark conn as fully-bound */
5715 	econnp->conn_fully_bound = B_TRUE;
5716 
5717 	/* Send the SYN-ACK */
5718 	tcp_send_data(eager, eager->tcp_wq, mp1);
5719 	CONN_DEC_REF(eager->tcp_connp);
5720 	freemsg(mp);
5721 
5722 	return;
5723 error:
5724 	freemsg(mp1);
5725 	eager->tcp_closemp_used = B_TRUE;
5726 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5727 	mp1 = &eager->tcp_closemp;
5728 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5729 	    econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5730 
5731 	/*
5732 	 * If a connection already exists, send the mp to that connections so
5733 	 * that it can be appropriately dealt with.
5734 	 */
5735 	ipst = tcps->tcps_netstack->netstack_ip;
5736 
5737 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
5738 		if (!IPCL_IS_CONNECTED(econnp)) {
5739 			/*
5740 			 * Something bad happened. ipcl_conn_insert()
5741 			 * failed because a connection already existed
5742 			 * in connected hash but we can't find it
5743 			 * anymore (someone blew it away). Just
5744 			 * free this message and hopefully remote
5745 			 * will retransmit at which time the SYN can be
5746 			 * treated as a new connection or dealth with
5747 			 * a TH_RST if a connection already exists.
5748 			 */
5749 			CONN_DEC_REF(econnp);
5750 			freemsg(mp);
5751 		} else {
5752 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp,
5753 			    tcp_input, econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5754 		}
5755 	} else {
5756 		/* Nobody wants this packet */
5757 		freemsg(mp);
5758 	}
5759 	return;
5760 error3:
5761 	CONN_DEC_REF(econnp);
5762 error2:
5763 	freemsg(mp);
5764 }
5765 
5766 /*
5767  * In an ideal case of vertical partition in NUMA architecture, its
5768  * beneficial to have the listener and all the incoming connections
5769  * tied to the same squeue. The other constraint is that incoming
5770  * connections should be tied to the squeue attached to interrupted
5771  * CPU for obvious locality reason so this leaves the listener to
5772  * be tied to the same squeue. Our only problem is that when listener
5773  * is binding, the CPU that will get interrupted by the NIC whose
5774  * IP address the listener is binding to is not even known. So
5775  * the code below allows us to change that binding at the time the
5776  * CPU is interrupted by virtue of incoming connection's squeue.
5777  *
5778  * This is usefull only in case of a listener bound to a specific IP
5779  * address. For other kind of listeners, they get bound the
5780  * very first time and there is no attempt to rebind them.
5781  */
5782 void
5783 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5784 {
5785 	conn_t		*connp = (conn_t *)arg;
5786 	squeue_t	*sqp = (squeue_t *)arg2;
5787 	squeue_t	*new_sqp;
5788 	uint32_t	conn_flags;
5789 
5790 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5791 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5792 	} else {
5793 		goto done;
5794 	}
5795 
5796 	if (connp->conn_fanout == NULL)
5797 		goto done;
5798 
5799 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5800 		mutex_enter(&connp->conn_fanout->connf_lock);
5801 		mutex_enter(&connp->conn_lock);
5802 		/*
5803 		 * No one from read or write side can access us now
5804 		 * except for already queued packets on this squeue.
5805 		 * But since we haven't changed the squeue yet, they
5806 		 * can't execute. If they are processed after we have
5807 		 * changed the squeue, they are sent back to the
5808 		 * correct squeue down below.
5809 		 * But a listner close can race with processing of
5810 		 * incoming SYN. If incoming SYN processing changes
5811 		 * the squeue then the listener close which is waiting
5812 		 * to enter the squeue would operate on the wrong
5813 		 * squeue. Hence we don't change the squeue here unless
5814 		 * the refcount is exactly the minimum refcount. The
5815 		 * minimum refcount of 4 is counted as - 1 each for
5816 		 * TCP and IP, 1 for being in the classifier hash, and
5817 		 * 1 for the mblk being processed.
5818 		 */
5819 
5820 		if (connp->conn_ref != 4 ||
5821 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5822 			mutex_exit(&connp->conn_lock);
5823 			mutex_exit(&connp->conn_fanout->connf_lock);
5824 			goto done;
5825 		}
5826 		if (connp->conn_sqp != new_sqp) {
5827 			while (connp->conn_sqp != new_sqp)
5828 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5829 		}
5830 
5831 		do {
5832 			conn_flags = connp->conn_flags;
5833 			conn_flags |= IPCL_FULLY_BOUND;
5834 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5835 			    conn_flags);
5836 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5837 
5838 		mutex_exit(&connp->conn_fanout->connf_lock);
5839 		mutex_exit(&connp->conn_lock);
5840 	}
5841 
5842 done:
5843 	if (connp->conn_sqp != sqp) {
5844 		CONN_INC_REF(connp);
5845 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5846 		    SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5847 	} else {
5848 		tcp_conn_request(connp, mp, sqp);
5849 	}
5850 }
5851 
5852 /*
5853  * Successful connect request processing begins when our client passes
5854  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5855  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5856  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_tpi_connect() -> IP
5857  *   upstream <- tcp_rput()		<- IP
5858  * After various error checks are completed, tcp_tpi_connect() lays
5859  * the target address and port into the composite header template,
5860  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5861  * request followed by an IRE request, and passes the three mblk message
5862  * down to IP looking like this:
5863  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5864  * Processing continues in tcp_rput() when we receive the following message:
5865  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5866  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5867  * to fire off the connection request, and then passes the T_OK_ACK mblk
5868  * upstream that we filled in below.  There are, of course, numerous
5869  * error conditions along the way which truncate the processing described
5870  * above.
5871  */
5872 static void
5873 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5874 {
5875 	sin_t		*sin;
5876 	queue_t		*q = tcp->tcp_wq;
5877 	struct T_conn_req	*tcr;
5878 	struct sockaddr	*sa;
5879 	socklen_t	len;
5880 	int		error;
5881 	cred_t		*cr;
5882 	pid_t		cpid;
5883 
5884 	/*
5885 	 * All Solaris components should pass a db_credp
5886 	 * for this TPI message, hence we ASSERT.
5887 	 * But in case there is some other M_PROTO that looks
5888 	 * like a TPI message sent by some other kernel
5889 	 * component, we check and return an error.
5890 	 */
5891 	cr = msg_getcred(mp, &cpid);
5892 	ASSERT(cr != NULL);
5893 	if (cr == NULL) {
5894 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5895 		return;
5896 	}
5897 
5898 	tcr = (struct T_conn_req *)mp->b_rptr;
5899 
5900 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5901 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5902 		tcp_err_ack(tcp, mp, TPROTO, 0);
5903 		return;
5904 	}
5905 
5906 	/*
5907 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5908 	 * will always have that to send up.  Otherwise, we need to do
5909 	 * special handling in case the allocation fails at that time.
5910 	 * If the end point is TPI, the tcp_t can be reused and the
5911 	 * tcp_ordrel_mp may be allocated already.
5912 	 */
5913 	if (tcp->tcp_ordrel_mp == NULL) {
5914 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5915 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5916 			return;
5917 		}
5918 	}
5919 
5920 	/*
5921 	 * Determine packet type based on type of address passed in
5922 	 * the request should contain an IPv4 or IPv6 address.
5923 	 * Make sure that address family matches the type of
5924 	 * family of the the address passed down
5925 	 */
5926 	switch (tcr->DEST_length) {
5927 	default:
5928 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5929 		return;
5930 
5931 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5932 		/*
5933 		 * XXX: The check for valid DEST_length was not there
5934 		 * in earlier releases and some buggy
5935 		 * TLI apps (e.g Sybase) got away with not feeding
5936 		 * in sin_zero part of address.
5937 		 * We allow that bug to keep those buggy apps humming.
5938 		 * Test suites require the check on DEST_length.
5939 		 * We construct a new mblk with valid DEST_length
5940 		 * free the original so the rest of the code does
5941 		 * not have to keep track of this special shorter
5942 		 * length address case.
5943 		 */
5944 		mblk_t *nmp;
5945 		struct T_conn_req *ntcr;
5946 		sin_t *nsin;
5947 
5948 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5949 		    tcr->OPT_length, BPRI_HI);
5950 		if (nmp == NULL) {
5951 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5952 			return;
5953 		}
5954 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5955 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5956 		ntcr->PRIM_type = T_CONN_REQ;
5957 		ntcr->DEST_length = sizeof (sin_t);
5958 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5959 
5960 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5961 		*nsin = sin_null;
5962 		/* Get pointer to shorter address to copy from original mp */
5963 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5964 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5965 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5966 			freemsg(nmp);
5967 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5968 			return;
5969 		}
5970 		nsin->sin_family = sin->sin_family;
5971 		nsin->sin_port = sin->sin_port;
5972 		nsin->sin_addr = sin->sin_addr;
5973 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5974 		nmp->b_wptr = (uchar_t *)&nsin[1];
5975 		if (tcr->OPT_length != 0) {
5976 			ntcr->OPT_length = tcr->OPT_length;
5977 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5978 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5979 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5980 			    tcr->OPT_length);
5981 			nmp->b_wptr += tcr->OPT_length;
5982 		}
5983 		freemsg(mp);	/* original mp freed */
5984 		mp = nmp;	/* re-initialize original variables */
5985 		tcr = ntcr;
5986 	}
5987 	/* FALLTHRU */
5988 
5989 	case sizeof (sin_t):
5990 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5991 		    sizeof (sin_t));
5992 		len = sizeof (sin_t);
5993 		break;
5994 
5995 	case sizeof (sin6_t):
5996 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5997 		    sizeof (sin6_t));
5998 		len = sizeof (sin6_t);
5999 		break;
6000 	}
6001 
6002 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
6003 	if (error != 0) {
6004 		tcp_err_ack(tcp, mp, TSYSERR, error);
6005 		return;
6006 	}
6007 
6008 	/*
6009 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6010 	 * should key on their sequence number and cut them loose.
6011 	 */
6012 
6013 	/*
6014 	 * If options passed in, feed it for verification and handling
6015 	 */
6016 	if (tcr->OPT_length != 0) {
6017 		mblk_t	*ok_mp;
6018 		mblk_t	*discon_mp;
6019 		mblk_t  *conn_opts_mp;
6020 		int t_error, sys_error, do_disconnect;
6021 
6022 		conn_opts_mp = NULL;
6023 
6024 		if (tcp_conprim_opt_process(tcp, mp,
6025 		    &do_disconnect, &t_error, &sys_error) < 0) {
6026 			if (do_disconnect) {
6027 				ASSERT(t_error == 0 && sys_error == 0);
6028 				discon_mp = mi_tpi_discon_ind(NULL,
6029 				    ECONNREFUSED, 0);
6030 				if (!discon_mp) {
6031 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6032 					    TSYSERR, ENOMEM);
6033 					return;
6034 				}
6035 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6036 				if (!ok_mp) {
6037 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6038 					    TSYSERR, ENOMEM);
6039 					return;
6040 				}
6041 				qreply(q, ok_mp);
6042 				qreply(q, discon_mp); /* no flush! */
6043 			} else {
6044 				ASSERT(t_error != 0);
6045 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6046 				    sys_error);
6047 			}
6048 			return;
6049 		}
6050 		/*
6051 		 * Success in setting options, the mp option buffer represented
6052 		 * by OPT_length/offset has been potentially modified and
6053 		 * contains results of option processing. We copy it in
6054 		 * another mp to save it for potentially influencing returning
6055 		 * it in T_CONN_CONN.
6056 		 */
6057 		if (tcr->OPT_length != 0) { /* there are resulting options */
6058 			conn_opts_mp = copyb(mp);
6059 			if (!conn_opts_mp) {
6060 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6061 				    TSYSERR, ENOMEM);
6062 				return;
6063 			}
6064 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6065 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6066 			/*
6067 			 * Note:
6068 			 * These resulting option negotiation can include any
6069 			 * end-to-end negotiation options but there no such
6070 			 * thing (yet?) in our TCP/IP.
6071 			 */
6072 		}
6073 	}
6074 
6075 	/* call the non-TPI version */
6076 	error = tcp_do_connect(tcp->tcp_connp, sa, len, cr, cpid);
6077 	if (error < 0) {
6078 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
6079 	} else if (error > 0) {
6080 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
6081 	} else {
6082 		mp = mi_tpi_ok_ack_alloc(mp);
6083 	}
6084 
6085 	/*
6086 	 * Note: Code below is the "failure" case
6087 	 */
6088 	/* return error ack and blow away saved option results if any */
6089 connect_failed:
6090 	if (mp != NULL)
6091 		putnext(tcp->tcp_rq, mp);
6092 	else {
6093 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6094 		    TSYSERR, ENOMEM);
6095 	}
6096 }
6097 
6098 /*
6099  * Handle connect to IPv4 destinations, including connections for AF_INET6
6100  * sockets connecting to IPv4 mapped IPv6 destinations.
6101  */
6102 static int
6103 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
6104     uint_t srcid, cred_t *cr, pid_t pid)
6105 {
6106 	tcph_t	*tcph;
6107 	mblk_t	*mp;
6108 	ipaddr_t dstaddr = *dstaddrp;
6109 	int32_t	oldstate;
6110 	uint16_t lport;
6111 	int	error = 0;
6112 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6113 
6114 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6115 
6116 	/* Check for attempt to connect to INADDR_ANY */
6117 	if (dstaddr == INADDR_ANY)  {
6118 		/*
6119 		 * SunOS 4.x and 4.3 BSD allow an application
6120 		 * to connect a TCP socket to INADDR_ANY.
6121 		 * When they do this, the kernel picks the
6122 		 * address of one interface and uses it
6123 		 * instead.  The kernel usually ends up
6124 		 * picking the address of the loopback
6125 		 * interface.  This is an undocumented feature.
6126 		 * However, we provide the same thing here
6127 		 * in order to have source and binary
6128 		 * compatibility with SunOS 4.x.
6129 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6130 		 * generate the T_CONN_CON.
6131 		 */
6132 		dstaddr = htonl(INADDR_LOOPBACK);
6133 		*dstaddrp = dstaddr;
6134 	}
6135 
6136 	/* Handle __sin6_src_id if socket not bound to an IP address */
6137 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6138 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6139 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6140 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6141 		    tcp->tcp_ipha->ipha_src);
6142 	}
6143 
6144 	/*
6145 	 * Don't let an endpoint connect to itself.  Note that
6146 	 * the test here does not catch the case where the
6147 	 * source IP addr was left unspecified by the user. In
6148 	 * this case, the source addr is set in tcp_adapt_ire()
6149 	 * using the reply to the T_BIND message that we send
6150 	 * down to IP here and the check is repeated in tcp_rput_other.
6151 	 */
6152 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6153 	    dstport == tcp->tcp_lport) {
6154 		error = -TBADADDR;
6155 		goto failed;
6156 	}
6157 
6158 	tcp->tcp_ipha->ipha_dst = dstaddr;
6159 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6160 
6161 	/*
6162 	 * Massage a source route if any putting the first hop
6163 	 * in iph_dst. Compute a starting value for the checksum which
6164 	 * takes into account that the original iph_dst should be
6165 	 * included in the checksum but that ip will include the
6166 	 * first hop in the source route in the tcp checksum.
6167 	 */
6168 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6169 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6170 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6171 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6172 	if ((int)tcp->tcp_sum < 0)
6173 		tcp->tcp_sum--;
6174 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6175 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6176 	    (tcp->tcp_sum >> 16));
6177 	tcph = tcp->tcp_tcph;
6178 	*(uint16_t *)tcph->th_fport = dstport;
6179 	tcp->tcp_fport = dstport;
6180 
6181 	oldstate = tcp->tcp_state;
6182 	/*
6183 	 * At this point the remote destination address and remote port fields
6184 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6185 	 * have to see which state tcp was in so we can take apropriate action.
6186 	 */
6187 	if (oldstate == TCPS_IDLE) {
6188 		/*
6189 		 * We support a quick connect capability here, allowing
6190 		 * clients to transition directly from IDLE to SYN_SENT
6191 		 * tcp_bindi will pick an unused port, insert the connection
6192 		 * in the bind hash and transition to BOUND state.
6193 		 */
6194 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6195 		    tcp, B_TRUE);
6196 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6197 		    B_FALSE, B_FALSE);
6198 		if (lport == 0) {
6199 			error = -TNOADDR;
6200 			goto failed;
6201 		}
6202 	}
6203 	tcp->tcp_state = TCPS_SYN_SENT;
6204 
6205 	mp = allocb(sizeof (ire_t), BPRI_HI);
6206 	if (mp == NULL) {
6207 		tcp->tcp_state = oldstate;
6208 		error = ENOMEM;
6209 		goto failed;
6210 	}
6211 
6212 	mp->b_wptr += sizeof (ire_t);
6213 	mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6214 	tcp->tcp_hard_binding = 1;
6215 
6216 	/*
6217 	 * We need to make sure that the conn_recv is set to a non-null
6218 	 * value before we insert the conn_t into the classifier table.
6219 	 * This is to avoid a race with an incoming packet which does
6220 	 * an ipcl_classify().
6221 	 */
6222 	tcp->tcp_connp->conn_recv = tcp_input;
6223 
6224 	if (tcp->tcp_family == AF_INET) {
6225 		error = ip_proto_bind_connected_v4(tcp->tcp_connp, &mp,
6226 		    IPPROTO_TCP, &tcp->tcp_ipha->ipha_src, tcp->tcp_lport,
6227 		    tcp->tcp_remote, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6228 	} else {
6229 		in6_addr_t v6src;
6230 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6231 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6232 		} else {
6233 			v6src = tcp->tcp_ip6h->ip6_src;
6234 		}
6235 		error = ip_proto_bind_connected_v6(tcp->tcp_connp, &mp,
6236 		    IPPROTO_TCP, &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6237 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6238 	}
6239 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6240 	tcp->tcp_active_open = 1;
6241 
6242 
6243 	return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6244 failed:
6245 	/* return error ack and blow away saved option results if any */
6246 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6247 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6248 	return (error);
6249 }
6250 
6251 /*
6252  * Handle connect to IPv6 destinations.
6253  */
6254 static int
6255 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
6256     uint32_t flowinfo, uint_t srcid, uint32_t scope_id, cred_t *cr, pid_t pid)
6257 {
6258 	tcph_t	*tcph;
6259 	mblk_t	*mp;
6260 	ip6_rthdr_t *rth;
6261 	int32_t  oldstate;
6262 	uint16_t lport;
6263 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6264 	int	error = 0;
6265 	conn_t	*connp = tcp->tcp_connp;
6266 
6267 	ASSERT(tcp->tcp_family == AF_INET6);
6268 
6269 	/*
6270 	 * If we're here, it means that the destination address is a native
6271 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6272 	 * reason why it might not be IPv6 is if the socket was bound to an
6273 	 * IPv4-mapped IPv6 address.
6274 	 */
6275 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6276 		return (-TBADADDR);
6277 	}
6278 
6279 	/*
6280 	 * Interpret a zero destination to mean loopback.
6281 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6282 	 * generate the T_CONN_CON.
6283 	 */
6284 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6285 		*dstaddrp = ipv6_loopback;
6286 	}
6287 
6288 	/* Handle __sin6_src_id if socket not bound to an IP address */
6289 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6290 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6291 		    connp->conn_zoneid, tcps->tcps_netstack);
6292 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6293 	}
6294 
6295 	/*
6296 	 * Take care of the scope_id now and add ip6i_t
6297 	 * if ip6i_t is not already allocated through TCP
6298 	 * sticky options. At this point tcp_ip6h does not
6299 	 * have dst info, thus use dstaddrp.
6300 	 */
6301 	if (scope_id != 0 &&
6302 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6303 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6304 		ip6i_t  *ip6i;
6305 
6306 		ipp->ipp_ifindex = scope_id;
6307 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6308 
6309 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6310 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6311 			/* Already allocated */
6312 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6313 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6314 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6315 		} else {
6316 			int reterr;
6317 
6318 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6319 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6320 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6321 			reterr = tcp_build_hdrs(tcp);
6322 			if (reterr != 0)
6323 				goto failed;
6324 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6325 		}
6326 	}
6327 
6328 	/*
6329 	 * Don't let an endpoint connect to itself.  Note that
6330 	 * the test here does not catch the case where the
6331 	 * source IP addr was left unspecified by the user. In
6332 	 * this case, the source addr is set in tcp_adapt_ire()
6333 	 * using the reply to the T_BIND message that we send
6334 	 * down to IP here and the check is repeated in tcp_rput_other.
6335 	 */
6336 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6337 	    (dstport == tcp->tcp_lport)) {
6338 		error = -TBADADDR;
6339 		goto failed;
6340 	}
6341 
6342 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6343 	tcp->tcp_remote_v6 = *dstaddrp;
6344 	tcp->tcp_ip6h->ip6_vcf =
6345 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6346 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6347 
6348 	/*
6349 	 * Massage a routing header (if present) putting the first hop
6350 	 * in ip6_dst. Compute a starting value for the checksum which
6351 	 * takes into account that the original ip6_dst should be
6352 	 * included in the checksum but that ip will include the
6353 	 * first hop in the source route in the tcp checksum.
6354 	 */
6355 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6356 	if (rth != NULL) {
6357 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6358 		    tcps->tcps_netstack);
6359 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6360 		    (tcp->tcp_sum >> 16));
6361 	} else {
6362 		tcp->tcp_sum = 0;
6363 	}
6364 
6365 	tcph = tcp->tcp_tcph;
6366 	*(uint16_t *)tcph->th_fport = dstport;
6367 	tcp->tcp_fport = dstport;
6368 
6369 	oldstate = tcp->tcp_state;
6370 	/*
6371 	 * At this point the remote destination address and remote port fields
6372 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6373 	 * have to see which state tcp was in so we can take apropriate action.
6374 	 */
6375 	if (oldstate == TCPS_IDLE) {
6376 		/*
6377 		 * We support a quick connect capability here, allowing
6378 		 * clients to transition directly from IDLE to SYN_SENT
6379 		 * tcp_bindi will pick an unused port, insert the connection
6380 		 * in the bind hash and transition to BOUND state.
6381 		 */
6382 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6383 		    tcp, B_TRUE);
6384 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6385 		    B_FALSE, B_FALSE);
6386 		if (lport == 0) {
6387 			error = -TNOADDR;
6388 			goto failed;
6389 		}
6390 	}
6391 	tcp->tcp_state = TCPS_SYN_SENT;
6392 
6393 	mp = allocb(sizeof (ire_t), BPRI_HI);
6394 	if (mp != NULL) {
6395 		in6_addr_t v6src;
6396 
6397 		mp->b_wptr += sizeof (ire_t);
6398 		mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6399 
6400 		tcp->tcp_hard_binding = 1;
6401 
6402 		/*
6403 		 * We need to make sure that the conn_recv is set to a non-null
6404 		 * value before we insert the conn_t into the classifier table.
6405 		 * This is to avoid a race with an incoming packet which does
6406 		 * an ipcl_classify().
6407 		 */
6408 		tcp->tcp_connp->conn_recv = tcp_input;
6409 
6410 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6411 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6412 		} else {
6413 			v6src = tcp->tcp_ip6h->ip6_src;
6414 		}
6415 		error = ip_proto_bind_connected_v6(connp, &mp, IPPROTO_TCP,
6416 		    &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6417 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6418 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6419 		tcp->tcp_active_open = 1;
6420 
6421 		return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6422 	}
6423 	/* Error case */
6424 	tcp->tcp_state = oldstate;
6425 	error = ENOMEM;
6426 
6427 failed:
6428 	/* return error ack and blow away saved option results if any */
6429 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6430 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6431 	return (error);
6432 }
6433 
6434 /*
6435  * We need a stream q for detached closing tcp connections
6436  * to use.  Our client hereby indicates that this q is the
6437  * one to use.
6438  */
6439 static void
6440 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6441 {
6442 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6443 	queue_t	*q = tcp->tcp_wq;
6444 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6445 
6446 #ifdef NS_DEBUG
6447 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6448 	    tcps->tcps_netstack->netstack_stackid);
6449 #endif
6450 	mp->b_datap->db_type = M_IOCACK;
6451 	iocp->ioc_count = 0;
6452 	mutex_enter(&tcps->tcps_g_q_lock);
6453 	if (tcps->tcps_g_q != NULL) {
6454 		mutex_exit(&tcps->tcps_g_q_lock);
6455 		iocp->ioc_error = EALREADY;
6456 	} else {
6457 		int error = 0;
6458 		conn_t *connp = tcp->tcp_connp;
6459 		ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
6460 
6461 		tcps->tcps_g_q = tcp->tcp_rq;
6462 		mutex_exit(&tcps->tcps_g_q_lock);
6463 		iocp->ioc_error = 0;
6464 		iocp->ioc_rval = 0;
6465 		/*
6466 		 * We are passing tcp_sticky_ipp as NULL
6467 		 * as it is not useful for tcp_default queue
6468 		 *
6469 		 * Set conn_recv just in case.
6470 		 */
6471 		tcp->tcp_connp->conn_recv = tcp_conn_request;
6472 
6473 		ASSERT(connp->conn_af_isv6);
6474 		connp->conn_ulp = IPPROTO_TCP;
6475 
6476 		if (ipst->ips_ipcl_proto_fanout_v6[IPPROTO_TCP].connf_head !=
6477 		    NULL || connp->conn_mac_exempt) {
6478 			error = -TBADADDR;
6479 		} else {
6480 			connp->conn_srcv6 = ipv6_all_zeros;
6481 			ipcl_proto_insert_v6(connp, IPPROTO_TCP);
6482 		}
6483 
6484 		(void) tcp_post_ip_bind(tcp, NULL, error, NULL, 0);
6485 	}
6486 	qreply(q, mp);
6487 }
6488 
6489 static int
6490 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
6491 {
6492 	tcp_t	*ltcp = NULL;
6493 	conn_t	*connp;
6494 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6495 
6496 	/*
6497 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6498 	 * when the stream is in BOUND state. Do not send a reset,
6499 	 * since the destination IP address is not valid, and it can
6500 	 * be the initialized value of all zeros (broadcast address).
6501 	 *
6502 	 * XXX There won't be any pending bind request to IP.
6503 	 */
6504 	if (tcp->tcp_state <= TCPS_BOUND) {
6505 		if (tcp->tcp_debug) {
6506 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6507 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6508 		}
6509 		return (TOUTSTATE);
6510 	}
6511 
6512 
6513 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6514 
6515 		/*
6516 		 * According to TPI, for non-listeners, ignore seqnum
6517 		 * and disconnect.
6518 		 * Following interpretation of -1 seqnum is historical
6519 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6520 		 * a valid seqnum should not be -1).
6521 		 *
6522 		 *	-1 means disconnect everything
6523 		 *	regardless even on a listener.
6524 		 */
6525 
6526 		int old_state = tcp->tcp_state;
6527 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6528 
6529 		/*
6530 		 * The connection can't be on the tcp_time_wait_head list
6531 		 * since it is not detached.
6532 		 */
6533 		ASSERT(tcp->tcp_time_wait_next == NULL);
6534 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6535 		ASSERT(tcp->tcp_time_wait_expire == 0);
6536 		ltcp = NULL;
6537 		/*
6538 		 * If it used to be a listener, check to make sure no one else
6539 		 * has taken the port before switching back to LISTEN state.
6540 		 */
6541 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6542 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6543 			    tcp->tcp_ipha->ipha_src,
6544 			    tcp->tcp_connp->conn_zoneid, ipst);
6545 			if (connp != NULL)
6546 				ltcp = connp->conn_tcp;
6547 		} else {
6548 			/* Allow tcp_bound_if listeners? */
6549 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6550 			    &tcp->tcp_ip6h->ip6_src, 0,
6551 			    tcp->tcp_connp->conn_zoneid, ipst);
6552 			if (connp != NULL)
6553 				ltcp = connp->conn_tcp;
6554 		}
6555 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6556 			tcp->tcp_state = TCPS_LISTEN;
6557 		} else if (old_state > TCPS_BOUND) {
6558 			tcp->tcp_conn_req_max = 0;
6559 			tcp->tcp_state = TCPS_BOUND;
6560 		}
6561 		if (ltcp != NULL)
6562 			CONN_DEC_REF(ltcp->tcp_connp);
6563 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6564 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6565 		} else if (old_state == TCPS_ESTABLISHED ||
6566 		    old_state == TCPS_CLOSE_WAIT) {
6567 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6568 		}
6569 
6570 		if (tcp->tcp_fused)
6571 			tcp_unfuse(tcp);
6572 
6573 		mutex_enter(&tcp->tcp_eager_lock);
6574 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6575 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6576 			tcp_eager_cleanup(tcp, 0);
6577 		}
6578 		mutex_exit(&tcp->tcp_eager_lock);
6579 
6580 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6581 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6582 
6583 		tcp_reinit(tcp);
6584 
6585 		return (0);
6586 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6587 		return (TBADSEQ);
6588 	}
6589 	return (0);
6590 }
6591 
6592 /*
6593  * Our client hereby directs us to reject the connection request
6594  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6595  * of sending the appropriate RST, not an ICMP error.
6596  */
6597 static void
6598 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6599 {
6600 	t_scalar_t seqnum;
6601 	int	error;
6602 
6603 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6604 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6605 		tcp_err_ack(tcp, mp, TPROTO, 0);
6606 		return;
6607 	}
6608 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6609 	error = tcp_disconnect_common(tcp, seqnum);
6610 	if (error != 0)
6611 		tcp_err_ack(tcp, mp, error, 0);
6612 	else {
6613 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6614 			/* Send M_FLUSH according to TPI */
6615 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6616 		}
6617 		mp = mi_tpi_ok_ack_alloc(mp);
6618 		if (mp)
6619 			putnext(tcp->tcp_rq, mp);
6620 	}
6621 }
6622 
6623 /*
6624  * Diagnostic routine used to return a string associated with the tcp state.
6625  * Note that if the caller does not supply a buffer, it will use an internal
6626  * static string.  This means that if multiple threads call this function at
6627  * the same time, output can be corrupted...  Note also that this function
6628  * does not check the size of the supplied buffer.  The caller has to make
6629  * sure that it is big enough.
6630  */
6631 static char *
6632 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6633 {
6634 	char		buf1[30];
6635 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6636 	char		*buf;
6637 	char		*cp;
6638 	in6_addr_t	local, remote;
6639 	char		local_addrbuf[INET6_ADDRSTRLEN];
6640 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6641 
6642 	if (sup_buf != NULL)
6643 		buf = sup_buf;
6644 	else
6645 		buf = priv_buf;
6646 
6647 	if (tcp == NULL)
6648 		return ("NULL_TCP");
6649 	switch (tcp->tcp_state) {
6650 	case TCPS_CLOSED:
6651 		cp = "TCP_CLOSED";
6652 		break;
6653 	case TCPS_IDLE:
6654 		cp = "TCP_IDLE";
6655 		break;
6656 	case TCPS_BOUND:
6657 		cp = "TCP_BOUND";
6658 		break;
6659 	case TCPS_LISTEN:
6660 		cp = "TCP_LISTEN";
6661 		break;
6662 	case TCPS_SYN_SENT:
6663 		cp = "TCP_SYN_SENT";
6664 		break;
6665 	case TCPS_SYN_RCVD:
6666 		cp = "TCP_SYN_RCVD";
6667 		break;
6668 	case TCPS_ESTABLISHED:
6669 		cp = "TCP_ESTABLISHED";
6670 		break;
6671 	case TCPS_CLOSE_WAIT:
6672 		cp = "TCP_CLOSE_WAIT";
6673 		break;
6674 	case TCPS_FIN_WAIT_1:
6675 		cp = "TCP_FIN_WAIT_1";
6676 		break;
6677 	case TCPS_CLOSING:
6678 		cp = "TCP_CLOSING";
6679 		break;
6680 	case TCPS_LAST_ACK:
6681 		cp = "TCP_LAST_ACK";
6682 		break;
6683 	case TCPS_FIN_WAIT_2:
6684 		cp = "TCP_FIN_WAIT_2";
6685 		break;
6686 	case TCPS_TIME_WAIT:
6687 		cp = "TCP_TIME_WAIT";
6688 		break;
6689 	default:
6690 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6691 		cp = buf1;
6692 		break;
6693 	}
6694 	switch (format) {
6695 	case DISP_ADDR_AND_PORT:
6696 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6697 			/*
6698 			 * Note that we use the remote address in the tcp_b
6699 			 * structure.  This means that it will print out
6700 			 * the real destination address, not the next hop's
6701 			 * address if source routing is used.
6702 			 */
6703 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6704 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6705 
6706 		} else {
6707 			local = tcp->tcp_ip_src_v6;
6708 			remote = tcp->tcp_remote_v6;
6709 		}
6710 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6711 		    sizeof (local_addrbuf));
6712 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6713 		    sizeof (remote_addrbuf));
6714 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6715 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6716 		    ntohs(tcp->tcp_fport), cp);
6717 		break;
6718 	case DISP_PORT_ONLY:
6719 	default:
6720 		(void) mi_sprintf(buf, "[%u, %u] %s",
6721 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6722 		break;
6723 	}
6724 
6725 	return (buf);
6726 }
6727 
6728 /*
6729  * Called via squeue to get on to eager's perimeter. It sends a
6730  * TH_RST if eager is in the fanout table. The listener wants the
6731  * eager to disappear either by means of tcp_eager_blowoff() or
6732  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
6733  * called (via squeue) if the eager cannot be inserted in the
6734  * fanout table in tcp_conn_request().
6735  */
6736 /* ARGSUSED */
6737 void
6738 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6739 {
6740 	conn_t	*econnp = (conn_t *)arg;
6741 	tcp_t	*eager = econnp->conn_tcp;
6742 	tcp_t	*listener = eager->tcp_listener;
6743 	tcp_stack_t	*tcps = eager->tcp_tcps;
6744 
6745 	/*
6746 	 * We could be called because listener is closing. Since
6747 	 * the eager is using listener's queue's, its not safe.
6748 	 * Better use the default queue just to send the TH_RST
6749 	 * out.
6750 	 */
6751 	ASSERT(tcps->tcps_g_q != NULL);
6752 	eager->tcp_rq = tcps->tcps_g_q;
6753 	eager->tcp_wq = WR(tcps->tcps_g_q);
6754 
6755 	/*
6756 	 * An eager's conn_fanout will be NULL if it's a duplicate
6757 	 * for an existing 4-tuples in the conn fanout table.
6758 	 * We don't want to send an RST out in such case.
6759 	 */
6760 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
6761 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6762 		    eager, eager->tcp_snxt, 0, TH_RST);
6763 	}
6764 
6765 	/* We are here because listener wants this eager gone */
6766 	if (listener != NULL) {
6767 		mutex_enter(&listener->tcp_eager_lock);
6768 		tcp_eager_unlink(eager);
6769 		if (eager->tcp_tconnind_started) {
6770 			/*
6771 			 * The eager has sent a conn_ind up to the
6772 			 * listener but listener decides to close
6773 			 * instead. We need to drop the extra ref
6774 			 * placed on eager in tcp_rput_data() before
6775 			 * sending the conn_ind to listener.
6776 			 */
6777 			CONN_DEC_REF(econnp);
6778 		}
6779 		mutex_exit(&listener->tcp_eager_lock);
6780 		CONN_DEC_REF(listener->tcp_connp);
6781 	}
6782 
6783 	if (eager->tcp_state > TCPS_BOUND)
6784 		tcp_close_detached(eager);
6785 }
6786 
6787 /*
6788  * Reset any eager connection hanging off this listener marked
6789  * with 'seqnum' and then reclaim it's resources.
6790  */
6791 static boolean_t
6792 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6793 {
6794 	tcp_t	*eager;
6795 	mblk_t 	*mp;
6796 	tcp_stack_t	*tcps = listener->tcp_tcps;
6797 
6798 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
6799 	eager = listener;
6800 	mutex_enter(&listener->tcp_eager_lock);
6801 	do {
6802 		eager = eager->tcp_eager_next_q;
6803 		if (eager == NULL) {
6804 			mutex_exit(&listener->tcp_eager_lock);
6805 			return (B_FALSE);
6806 		}
6807 	} while (eager->tcp_conn_req_seqnum != seqnum);
6808 
6809 	if (eager->tcp_closemp_used) {
6810 		mutex_exit(&listener->tcp_eager_lock);
6811 		return (B_TRUE);
6812 	}
6813 	eager->tcp_closemp_used = B_TRUE;
6814 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6815 	CONN_INC_REF(eager->tcp_connp);
6816 	mutex_exit(&listener->tcp_eager_lock);
6817 	mp = &eager->tcp_closemp;
6818 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6819 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
6820 	return (B_TRUE);
6821 }
6822 
6823 /*
6824  * Reset any eager connection hanging off this listener
6825  * and then reclaim it's resources.
6826  */
6827 static void
6828 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6829 {
6830 	tcp_t	*eager;
6831 	mblk_t	*mp;
6832 	tcp_stack_t	*tcps = listener->tcp_tcps;
6833 
6834 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6835 
6836 	if (!q0_only) {
6837 		/* First cleanup q */
6838 		TCP_STAT(tcps, tcp_eager_blowoff_q);
6839 		eager = listener->tcp_eager_next_q;
6840 		while (eager != NULL) {
6841 			if (!eager->tcp_closemp_used) {
6842 				eager->tcp_closemp_used = B_TRUE;
6843 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6844 				CONN_INC_REF(eager->tcp_connp);
6845 				mp = &eager->tcp_closemp;
6846 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6847 				    tcp_eager_kill, eager->tcp_connp,
6848 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
6849 			}
6850 			eager = eager->tcp_eager_next_q;
6851 		}
6852 	}
6853 	/* Then cleanup q0 */
6854 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6855 	eager = listener->tcp_eager_next_q0;
6856 	while (eager != listener) {
6857 		if (!eager->tcp_closemp_used) {
6858 			eager->tcp_closemp_used = B_TRUE;
6859 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6860 			CONN_INC_REF(eager->tcp_connp);
6861 			mp = &eager->tcp_closemp;
6862 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6863 			    tcp_eager_kill, eager->tcp_connp, SQ_FILL,
6864 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6865 		}
6866 		eager = eager->tcp_eager_next_q0;
6867 	}
6868 }
6869 
6870 /*
6871  * If we are an eager connection hanging off a listener that hasn't
6872  * formally accepted the connection yet, get off his list and blow off
6873  * any data that we have accumulated.
6874  */
6875 static void
6876 tcp_eager_unlink(tcp_t *tcp)
6877 {
6878 	tcp_t	*listener = tcp->tcp_listener;
6879 
6880 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6881 	ASSERT(listener != NULL);
6882 	if (tcp->tcp_eager_next_q0 != NULL) {
6883 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6884 
6885 		/* Remove the eager tcp from q0 */
6886 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6887 		    tcp->tcp_eager_prev_q0;
6888 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6889 		    tcp->tcp_eager_next_q0;
6890 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6891 		listener->tcp_conn_req_cnt_q0--;
6892 
6893 		tcp->tcp_eager_next_q0 = NULL;
6894 		tcp->tcp_eager_prev_q0 = NULL;
6895 
6896 		/*
6897 		 * Take the eager out, if it is in the list of droppable
6898 		 * eagers.
6899 		 */
6900 		MAKE_UNDROPPABLE(tcp);
6901 
6902 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6903 			/* we have timed out before */
6904 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6905 			listener->tcp_syn_rcvd_timeout--;
6906 		}
6907 	} else {
6908 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6909 		tcp_t	*prev = NULL;
6910 
6911 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6912 			if (tcpp[0] == tcp) {
6913 				if (listener->tcp_eager_last_q == tcp) {
6914 					/*
6915 					 * If we are unlinking the last
6916 					 * element on the list, adjust
6917 					 * tail pointer. Set tail pointer
6918 					 * to nil when list is empty.
6919 					 */
6920 					ASSERT(tcp->tcp_eager_next_q == NULL);
6921 					if (listener->tcp_eager_last_q ==
6922 					    listener->tcp_eager_next_q) {
6923 						listener->tcp_eager_last_q =
6924 						    NULL;
6925 					} else {
6926 						/*
6927 						 * We won't get here if there
6928 						 * is only one eager in the
6929 						 * list.
6930 						 */
6931 						ASSERT(prev != NULL);
6932 						listener->tcp_eager_last_q =
6933 						    prev;
6934 					}
6935 				}
6936 				tcpp[0] = tcp->tcp_eager_next_q;
6937 				tcp->tcp_eager_next_q = NULL;
6938 				tcp->tcp_eager_last_q = NULL;
6939 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6940 				listener->tcp_conn_req_cnt_q--;
6941 				break;
6942 			}
6943 			prev = tcpp[0];
6944 		}
6945 	}
6946 	tcp->tcp_listener = NULL;
6947 }
6948 
6949 /* Shorthand to generate and send TPI error acks to our client */
6950 static void
6951 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6952 {
6953 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6954 		putnext(tcp->tcp_rq, mp);
6955 }
6956 
6957 /* Shorthand to generate and send TPI error acks to our client */
6958 static void
6959 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6960     int t_error, int sys_error)
6961 {
6962 	struct T_error_ack	*teackp;
6963 
6964 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
6965 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
6966 		teackp = (struct T_error_ack *)mp->b_rptr;
6967 		teackp->ERROR_prim = primitive;
6968 		teackp->TLI_error = t_error;
6969 		teackp->UNIX_error = sys_error;
6970 		putnext(tcp->tcp_rq, mp);
6971 	}
6972 }
6973 
6974 /*
6975  * Note: No locks are held when inspecting tcp_g_*epriv_ports
6976  * but instead the code relies on:
6977  * - the fact that the address of the array and its size never changes
6978  * - the atomic assignment of the elements of the array
6979  */
6980 /* ARGSUSED */
6981 static int
6982 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
6983 {
6984 	int i;
6985 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6986 
6987 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6988 		if (tcps->tcps_g_epriv_ports[i] != 0)
6989 			(void) mi_mpprintf(mp, "%d ",
6990 			    tcps->tcps_g_epriv_ports[i]);
6991 	}
6992 	return (0);
6993 }
6994 
6995 /*
6996  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6997  * threads from changing it at the same time.
6998  */
6999 /* ARGSUSED */
7000 static int
7001 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7002     cred_t *cr)
7003 {
7004 	long	new_value;
7005 	int	i;
7006 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7007 
7008 	/*
7009 	 * Fail the request if the new value does not lie within the
7010 	 * port number limits.
7011 	 */
7012 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7013 	    new_value <= 0 || new_value >= 65536) {
7014 		return (EINVAL);
7015 	}
7016 
7017 	mutex_enter(&tcps->tcps_epriv_port_lock);
7018 	/* Check if the value is already in the list */
7019 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7020 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7021 			mutex_exit(&tcps->tcps_epriv_port_lock);
7022 			return (EEXIST);
7023 		}
7024 	}
7025 	/* Find an empty slot */
7026 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7027 		if (tcps->tcps_g_epriv_ports[i] == 0)
7028 			break;
7029 	}
7030 	if (i == tcps->tcps_g_num_epriv_ports) {
7031 		mutex_exit(&tcps->tcps_epriv_port_lock);
7032 		return (EOVERFLOW);
7033 	}
7034 	/* Set the new value */
7035 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7036 	mutex_exit(&tcps->tcps_epriv_port_lock);
7037 	return (0);
7038 }
7039 
7040 /*
7041  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7042  * threads from changing it at the same time.
7043  */
7044 /* ARGSUSED */
7045 static int
7046 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7047     cred_t *cr)
7048 {
7049 	long	new_value;
7050 	int	i;
7051 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7052 
7053 	/*
7054 	 * Fail the request if the new value does not lie within the
7055 	 * port number limits.
7056 	 */
7057 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7058 	    new_value >= 65536) {
7059 		return (EINVAL);
7060 	}
7061 
7062 	mutex_enter(&tcps->tcps_epriv_port_lock);
7063 	/* Check that the value is already in the list */
7064 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7065 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7066 			break;
7067 	}
7068 	if (i == tcps->tcps_g_num_epriv_ports) {
7069 		mutex_exit(&tcps->tcps_epriv_port_lock);
7070 		return (ESRCH);
7071 	}
7072 	/* Clear the value */
7073 	tcps->tcps_g_epriv_ports[i] = 0;
7074 	mutex_exit(&tcps->tcps_epriv_port_lock);
7075 	return (0);
7076 }
7077 
7078 /* Return the TPI/TLI equivalent of our current tcp_state */
7079 static int
7080 tcp_tpistate(tcp_t *tcp)
7081 {
7082 	switch (tcp->tcp_state) {
7083 	case TCPS_IDLE:
7084 		return (TS_UNBND);
7085 	case TCPS_LISTEN:
7086 		/*
7087 		 * Return whether there are outstanding T_CONN_IND waiting
7088 		 * for the matching T_CONN_RES. Therefore don't count q0.
7089 		 */
7090 		if (tcp->tcp_conn_req_cnt_q > 0)
7091 			return (TS_WRES_CIND);
7092 		else
7093 			return (TS_IDLE);
7094 	case TCPS_BOUND:
7095 		return (TS_IDLE);
7096 	case TCPS_SYN_SENT:
7097 		return (TS_WCON_CREQ);
7098 	case TCPS_SYN_RCVD:
7099 		/*
7100 		 * Note: assumption: this has to the active open SYN_RCVD.
7101 		 * The passive instance is detached in SYN_RCVD stage of
7102 		 * incoming connection processing so we cannot get request
7103 		 * for T_info_ack on it.
7104 		 */
7105 		return (TS_WACK_CRES);
7106 	case TCPS_ESTABLISHED:
7107 		return (TS_DATA_XFER);
7108 	case TCPS_CLOSE_WAIT:
7109 		return (TS_WREQ_ORDREL);
7110 	case TCPS_FIN_WAIT_1:
7111 		return (TS_WIND_ORDREL);
7112 	case TCPS_FIN_WAIT_2:
7113 		return (TS_WIND_ORDREL);
7114 
7115 	case TCPS_CLOSING:
7116 	case TCPS_LAST_ACK:
7117 	case TCPS_TIME_WAIT:
7118 	case TCPS_CLOSED:
7119 		/*
7120 		 * Following TS_WACK_DREQ7 is a rendition of "not
7121 		 * yet TS_IDLE" TPI state. There is no best match to any
7122 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7123 		 * choose a value chosen that will map to TLI/XTI level
7124 		 * state of TSTATECHNG (state is process of changing) which
7125 		 * captures what this dummy state represents.
7126 		 */
7127 		return (TS_WACK_DREQ7);
7128 	default:
7129 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7130 		    tcp->tcp_state, tcp_display(tcp, NULL,
7131 		    DISP_PORT_ONLY));
7132 		return (TS_UNBND);
7133 	}
7134 }
7135 
7136 static void
7137 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7138 {
7139 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7140 
7141 	if (tcp->tcp_family == AF_INET6)
7142 		*tia = tcp_g_t_info_ack_v6;
7143 	else
7144 		*tia = tcp_g_t_info_ack;
7145 	tia->CURRENT_state = tcp_tpistate(tcp);
7146 	tia->OPT_size = tcp_max_optsize;
7147 	if (tcp->tcp_mss == 0) {
7148 		/* Not yet set - tcp_open does not set mss */
7149 		if (tcp->tcp_ipversion == IPV4_VERSION)
7150 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7151 		else
7152 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7153 	} else {
7154 		tia->TIDU_size = tcp->tcp_mss;
7155 	}
7156 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7157 }
7158 
7159 static void
7160 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
7161     t_uscalar_t cap_bits1)
7162 {
7163 	tcap->CAP_bits1 = 0;
7164 
7165 	if (cap_bits1 & TC1_INFO) {
7166 		tcp_copy_info(&tcap->INFO_ack, tcp);
7167 		tcap->CAP_bits1 |= TC1_INFO;
7168 	}
7169 
7170 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7171 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7172 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7173 	}
7174 
7175 }
7176 
7177 /*
7178  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7179  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7180  * tcp_g_t_info_ack.  The current state of the stream is copied from
7181  * tcp_state.
7182  */
7183 static void
7184 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7185 {
7186 	t_uscalar_t		cap_bits1;
7187 	struct T_capability_ack	*tcap;
7188 
7189 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7190 		freemsg(mp);
7191 		return;
7192 	}
7193 
7194 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7195 
7196 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7197 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7198 	if (mp == NULL)
7199 		return;
7200 
7201 	tcap = (struct T_capability_ack *)mp->b_rptr;
7202 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
7203 
7204 	putnext(tcp->tcp_rq, mp);
7205 }
7206 
7207 /*
7208  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7209  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7210  * The current state of the stream is copied from tcp_state.
7211  */
7212 static void
7213 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7214 {
7215 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7216 	    T_INFO_ACK);
7217 	if (!mp) {
7218 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7219 		return;
7220 	}
7221 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7222 	putnext(tcp->tcp_rq, mp);
7223 }
7224 
7225 /* Respond to the TPI addr request */
7226 static void
7227 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7228 {
7229 	sin_t	*sin;
7230 	mblk_t	*ackmp;
7231 	struct T_addr_ack *taa;
7232 
7233 	/* Make it large enough for worst case */
7234 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7235 	    2 * sizeof (sin6_t), 1);
7236 	if (ackmp == NULL) {
7237 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7238 		return;
7239 	}
7240 
7241 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7242 		tcp_addr_req_ipv6(tcp, ackmp);
7243 		return;
7244 	}
7245 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7246 
7247 	bzero(taa, sizeof (struct T_addr_ack));
7248 	ackmp->b_wptr = (uchar_t *)&taa[1];
7249 
7250 	taa->PRIM_type = T_ADDR_ACK;
7251 	ackmp->b_datap->db_type = M_PCPROTO;
7252 
7253 	/*
7254 	 * Note: Following code assumes 32 bit alignment of basic
7255 	 * data structures like sin_t and struct T_addr_ack.
7256 	 */
7257 	if (tcp->tcp_state >= TCPS_BOUND) {
7258 		/*
7259 		 * Fill in local address
7260 		 */
7261 		taa->LOCADDR_length = sizeof (sin_t);
7262 		taa->LOCADDR_offset = sizeof (*taa);
7263 
7264 		sin = (sin_t *)&taa[1];
7265 
7266 		/* Fill zeroes and then intialize non-zero fields */
7267 		*sin = sin_null;
7268 
7269 		sin->sin_family = AF_INET;
7270 
7271 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7272 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7273 
7274 		ackmp->b_wptr = (uchar_t *)&sin[1];
7275 
7276 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7277 			/*
7278 			 * Fill in Remote address
7279 			 */
7280 			taa->REMADDR_length = sizeof (sin_t);
7281 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7282 			    taa->LOCADDR_length);
7283 
7284 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7285 			*sin = sin_null;
7286 			sin->sin_family = AF_INET;
7287 			sin->sin_addr.s_addr = tcp->tcp_remote;
7288 			sin->sin_port = tcp->tcp_fport;
7289 
7290 			ackmp->b_wptr = (uchar_t *)&sin[1];
7291 		}
7292 	}
7293 	putnext(tcp->tcp_rq, ackmp);
7294 }
7295 
7296 /* Assumes that tcp_addr_req gets enough space and alignment */
7297 static void
7298 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7299 {
7300 	sin6_t	*sin6;
7301 	struct T_addr_ack *taa;
7302 
7303 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7304 	ASSERT(OK_32PTR(ackmp->b_rptr));
7305 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7306 	    2 * sizeof (sin6_t));
7307 
7308 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7309 
7310 	bzero(taa, sizeof (struct T_addr_ack));
7311 	ackmp->b_wptr = (uchar_t *)&taa[1];
7312 
7313 	taa->PRIM_type = T_ADDR_ACK;
7314 	ackmp->b_datap->db_type = M_PCPROTO;
7315 
7316 	/*
7317 	 * Note: Following code assumes 32 bit alignment of basic
7318 	 * data structures like sin6_t and struct T_addr_ack.
7319 	 */
7320 	if (tcp->tcp_state >= TCPS_BOUND) {
7321 		/*
7322 		 * Fill in local address
7323 		 */
7324 		taa->LOCADDR_length = sizeof (sin6_t);
7325 		taa->LOCADDR_offset = sizeof (*taa);
7326 
7327 		sin6 = (sin6_t *)&taa[1];
7328 		*sin6 = sin6_null;
7329 
7330 		sin6->sin6_family = AF_INET6;
7331 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7332 		sin6->sin6_port = tcp->tcp_lport;
7333 
7334 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7335 
7336 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7337 			/*
7338 			 * Fill in Remote address
7339 			 */
7340 			taa->REMADDR_length = sizeof (sin6_t);
7341 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7342 			    taa->LOCADDR_length);
7343 
7344 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7345 			*sin6 = sin6_null;
7346 			sin6->sin6_family = AF_INET6;
7347 			sin6->sin6_flowinfo =
7348 			    tcp->tcp_ip6h->ip6_vcf &
7349 			    ~IPV6_VERS_AND_FLOW_MASK;
7350 			sin6->sin6_addr = tcp->tcp_remote_v6;
7351 			sin6->sin6_port = tcp->tcp_fport;
7352 
7353 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7354 		}
7355 	}
7356 	putnext(tcp->tcp_rq, ackmp);
7357 }
7358 
7359 /*
7360  * Handle reinitialization of a tcp structure.
7361  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7362  */
7363 static void
7364 tcp_reinit(tcp_t *tcp)
7365 {
7366 	mblk_t	*mp;
7367 	int 	err;
7368 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7369 
7370 	TCP_STAT(tcps, tcp_reinit_calls);
7371 
7372 	/* tcp_reinit should never be called for detached tcp_t's */
7373 	ASSERT(tcp->tcp_listener == NULL);
7374 	ASSERT((tcp->tcp_family == AF_INET &&
7375 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7376 	    (tcp->tcp_family == AF_INET6 &&
7377 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7378 	    tcp->tcp_ipversion == IPV6_VERSION)));
7379 
7380 	/* Cancel outstanding timers */
7381 	tcp_timers_stop(tcp);
7382 
7383 	/*
7384 	 * Reset everything in the state vector, after updating global
7385 	 * MIB data from instance counters.
7386 	 */
7387 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7388 	tcp->tcp_ibsegs = 0;
7389 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7390 	tcp->tcp_obsegs = 0;
7391 
7392 	tcp_close_mpp(&tcp->tcp_xmit_head);
7393 	if (tcp->tcp_snd_zcopy_aware)
7394 		tcp_zcopy_notify(tcp);
7395 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7396 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7397 	mutex_enter(&tcp->tcp_non_sq_lock);
7398 	if (tcp->tcp_flow_stopped &&
7399 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7400 		tcp_clrqfull(tcp);
7401 	}
7402 	mutex_exit(&tcp->tcp_non_sq_lock);
7403 	tcp_close_mpp(&tcp->tcp_reass_head);
7404 	tcp->tcp_reass_tail = NULL;
7405 	if (tcp->tcp_rcv_list != NULL) {
7406 		/* Free b_next chain */
7407 		tcp_close_mpp(&tcp->tcp_rcv_list);
7408 		tcp->tcp_rcv_last_head = NULL;
7409 		tcp->tcp_rcv_last_tail = NULL;
7410 		tcp->tcp_rcv_cnt = 0;
7411 	}
7412 	tcp->tcp_rcv_last_tail = NULL;
7413 
7414 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7415 		freemsg(mp);
7416 		tcp->tcp_urp_mp = NULL;
7417 	}
7418 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7419 		freemsg(mp);
7420 		tcp->tcp_urp_mark_mp = NULL;
7421 	}
7422 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7423 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7424 		freeb(tcp->tcp_fused_sigurg_mp);
7425 		tcp->tcp_fused_sigurg_mp = NULL;
7426 	}
7427 	if (tcp->tcp_ordrel_mp != NULL) {
7428 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7429 		freeb(tcp->tcp_ordrel_mp);
7430 		tcp->tcp_ordrel_mp = NULL;
7431 	}
7432 
7433 	/*
7434 	 * Following is a union with two members which are
7435 	 * identical types and size so the following cleanup
7436 	 * is enough.
7437 	 */
7438 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7439 
7440 	CL_INET_DISCONNECT(tcp->tcp_connp, tcp);
7441 
7442 	/*
7443 	 * The connection can't be on the tcp_time_wait_head list
7444 	 * since it is not detached.
7445 	 */
7446 	ASSERT(tcp->tcp_time_wait_next == NULL);
7447 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7448 	ASSERT(tcp->tcp_time_wait_expire == 0);
7449 
7450 	if (tcp->tcp_kssl_pending) {
7451 		tcp->tcp_kssl_pending = B_FALSE;
7452 
7453 		/* Don't reset if the initialized by bind. */
7454 		if (tcp->tcp_kssl_ent != NULL) {
7455 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7456 			    KSSL_NO_PROXY);
7457 		}
7458 	}
7459 	if (tcp->tcp_kssl_ctx != NULL) {
7460 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7461 		tcp->tcp_kssl_ctx = NULL;
7462 	}
7463 
7464 	/*
7465 	 * Reset/preserve other values
7466 	 */
7467 	tcp_reinit_values(tcp);
7468 	ipcl_hash_remove(tcp->tcp_connp);
7469 	conn_delete_ire(tcp->tcp_connp, NULL);
7470 	tcp_ipsec_cleanup(tcp);
7471 
7472 	if (tcp->tcp_conn_req_max != 0) {
7473 		/*
7474 		 * This is the case when a TLI program uses the same
7475 		 * transport end point to accept a connection.  This
7476 		 * makes the TCP both a listener and acceptor.  When
7477 		 * this connection is closed, we need to set the state
7478 		 * back to TCPS_LISTEN.  Make sure that the eager list
7479 		 * is reinitialized.
7480 		 *
7481 		 * Note that this stream is still bound to the four
7482 		 * tuples of the previous connection in IP.  If a new
7483 		 * SYN with different foreign address comes in, IP will
7484 		 * not find it and will send it to the global queue.  In
7485 		 * the global queue, TCP will do a tcp_lookup_listener()
7486 		 * to find this stream.  This works because this stream
7487 		 * is only removed from connected hash.
7488 		 *
7489 		 */
7490 		tcp->tcp_state = TCPS_LISTEN;
7491 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7492 		tcp->tcp_eager_next_drop_q0 = tcp;
7493 		tcp->tcp_eager_prev_drop_q0 = tcp;
7494 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7495 		if (tcp->tcp_family == AF_INET6) {
7496 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7497 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7498 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7499 		} else {
7500 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7501 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7502 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7503 		}
7504 	} else {
7505 		tcp->tcp_state = TCPS_BOUND;
7506 	}
7507 
7508 	/*
7509 	 * Initialize to default values
7510 	 * Can't fail since enough header template space already allocated
7511 	 * at open().
7512 	 */
7513 	err = tcp_init_values(tcp);
7514 	ASSERT(err == 0);
7515 	/* Restore state in tcp_tcph */
7516 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7517 	if (tcp->tcp_ipversion == IPV4_VERSION)
7518 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7519 	else
7520 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7521 	/*
7522 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7523 	 * since the lookup funcs can only lookup on tcp_t
7524 	 */
7525 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7526 
7527 	ASSERT(tcp->tcp_ptpbhn != NULL);
7528 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
7529 		tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7530 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
7531 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
7532 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7533 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7534 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7535 }
7536 
7537 /*
7538  * Force values to zero that need be zero.
7539  * Do not touch values asociated with the BOUND or LISTEN state
7540  * since the connection will end up in that state after the reinit.
7541  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7542  * structure!
7543  */
7544 static void
7545 tcp_reinit_values(tcp)
7546 	tcp_t *tcp;
7547 {
7548 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7549 
7550 #ifndef	lint
7551 #define	DONTCARE(x)
7552 #define	PRESERVE(x)
7553 #else
7554 #define	DONTCARE(x)	((x) = (x))
7555 #define	PRESERVE(x)	((x) = (x))
7556 #endif	/* lint */
7557 
7558 	PRESERVE(tcp->tcp_bind_hash_port);
7559 	PRESERVE(tcp->tcp_bind_hash);
7560 	PRESERVE(tcp->tcp_ptpbhn);
7561 	PRESERVE(tcp->tcp_acceptor_hash);
7562 	PRESERVE(tcp->tcp_ptpahn);
7563 
7564 	/* Should be ASSERT NULL on these with new code! */
7565 	ASSERT(tcp->tcp_time_wait_next == NULL);
7566 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7567 	ASSERT(tcp->tcp_time_wait_expire == 0);
7568 	PRESERVE(tcp->tcp_state);
7569 	PRESERVE(tcp->tcp_rq);
7570 	PRESERVE(tcp->tcp_wq);
7571 
7572 	ASSERT(tcp->tcp_xmit_head == NULL);
7573 	ASSERT(tcp->tcp_xmit_last == NULL);
7574 	ASSERT(tcp->tcp_unsent == 0);
7575 	ASSERT(tcp->tcp_xmit_tail == NULL);
7576 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7577 
7578 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7579 	tcp->tcp_suna = 0;			/* Displayed in mib */
7580 	tcp->tcp_swnd = 0;
7581 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7582 
7583 	ASSERT(tcp->tcp_ibsegs == 0);
7584 	ASSERT(tcp->tcp_obsegs == 0);
7585 
7586 	if (tcp->tcp_iphc != NULL) {
7587 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7588 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7589 	}
7590 
7591 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7592 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7593 	DONTCARE(tcp->tcp_ipha);
7594 	DONTCARE(tcp->tcp_ip6h);
7595 	DONTCARE(tcp->tcp_ip_hdr_len);
7596 	DONTCARE(tcp->tcp_tcph);
7597 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7598 	tcp->tcp_valid_bits = 0;
7599 
7600 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7601 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7602 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7603 	tcp->tcp_last_rcv_lbolt = 0;
7604 
7605 	tcp->tcp_init_cwnd = 0;
7606 
7607 	tcp->tcp_urp_last_valid = 0;
7608 	tcp->tcp_hard_binding = 0;
7609 	tcp->tcp_hard_bound = 0;
7610 	PRESERVE(tcp->tcp_cred);
7611 	PRESERVE(tcp->tcp_cpid);
7612 	PRESERVE(tcp->tcp_open_time);
7613 	PRESERVE(tcp->tcp_exclbind);
7614 
7615 	tcp->tcp_fin_acked = 0;
7616 	tcp->tcp_fin_rcvd = 0;
7617 	tcp->tcp_fin_sent = 0;
7618 	tcp->tcp_ordrel_done = 0;
7619 
7620 	tcp->tcp_debug = 0;
7621 	tcp->tcp_dontroute = 0;
7622 	tcp->tcp_broadcast = 0;
7623 
7624 	tcp->tcp_useloopback = 0;
7625 	tcp->tcp_reuseaddr = 0;
7626 	tcp->tcp_oobinline = 0;
7627 	tcp->tcp_dgram_errind = 0;
7628 
7629 	tcp->tcp_detached = 0;
7630 	tcp->tcp_bind_pending = 0;
7631 	tcp->tcp_unbind_pending = 0;
7632 
7633 	tcp->tcp_snd_ws_ok = B_FALSE;
7634 	tcp->tcp_snd_ts_ok = B_FALSE;
7635 	tcp->tcp_linger = 0;
7636 	tcp->tcp_ka_enabled = 0;
7637 	tcp->tcp_zero_win_probe = 0;
7638 
7639 	tcp->tcp_loopback = 0;
7640 	tcp->tcp_refuse = 0;
7641 	tcp->tcp_localnet = 0;
7642 	tcp->tcp_syn_defense = 0;
7643 	tcp->tcp_set_timer = 0;
7644 
7645 	tcp->tcp_active_open = 0;
7646 	tcp->tcp_rexmit = B_FALSE;
7647 	tcp->tcp_xmit_zc_clean = B_FALSE;
7648 
7649 	tcp->tcp_snd_sack_ok = B_FALSE;
7650 	PRESERVE(tcp->tcp_recvdstaddr);
7651 	tcp->tcp_hwcksum = B_FALSE;
7652 
7653 	tcp->tcp_ire_ill_check_done = B_FALSE;
7654 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7655 
7656 	tcp->tcp_mdt = B_FALSE;
7657 	tcp->tcp_mdt_hdr_head = 0;
7658 	tcp->tcp_mdt_hdr_tail = 0;
7659 
7660 	tcp->tcp_conn_def_q0 = 0;
7661 	tcp->tcp_ip_forward_progress = B_FALSE;
7662 	tcp->tcp_anon_priv_bind = 0;
7663 	tcp->tcp_ecn_ok = B_FALSE;
7664 
7665 	tcp->tcp_cwr = B_FALSE;
7666 	tcp->tcp_ecn_echo_on = B_FALSE;
7667 
7668 	if (tcp->tcp_sack_info != NULL) {
7669 		if (tcp->tcp_notsack_list != NULL) {
7670 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7671 		}
7672 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7673 		tcp->tcp_sack_info = NULL;
7674 	}
7675 
7676 	tcp->tcp_rcv_ws = 0;
7677 	tcp->tcp_snd_ws = 0;
7678 	tcp->tcp_ts_recent = 0;
7679 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7680 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7681 	tcp->tcp_if_mtu = 0;
7682 
7683 	ASSERT(tcp->tcp_reass_head == NULL);
7684 	ASSERT(tcp->tcp_reass_tail == NULL);
7685 
7686 	tcp->tcp_cwnd_cnt = 0;
7687 
7688 	ASSERT(tcp->tcp_rcv_list == NULL);
7689 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7690 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7691 	ASSERT(tcp->tcp_rcv_cnt == 0);
7692 
7693 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7694 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7695 	tcp->tcp_csuna = 0;
7696 
7697 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7698 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7699 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7700 	tcp->tcp_rtt_update = 0;
7701 
7702 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7703 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7704 
7705 	tcp->tcp_rack = 0;			/* Displayed in mib */
7706 	tcp->tcp_rack_cnt = 0;
7707 	tcp->tcp_rack_cur_max = 0;
7708 	tcp->tcp_rack_abs_max = 0;
7709 
7710 	tcp->tcp_max_swnd = 0;
7711 
7712 	ASSERT(tcp->tcp_listener == NULL);
7713 
7714 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7715 
7716 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7717 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7718 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7719 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7720 
7721 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7722 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7723 	PRESERVE(tcp->tcp_conn_req_max);
7724 	PRESERVE(tcp->tcp_conn_req_seqnum);
7725 
7726 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7727 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7728 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7729 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7730 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7731 
7732 	tcp->tcp_lingertime = 0;
7733 
7734 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7735 	ASSERT(tcp->tcp_urp_mp == NULL);
7736 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7737 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7738 
7739 	ASSERT(tcp->tcp_eager_next_q == NULL);
7740 	ASSERT(tcp->tcp_eager_last_q == NULL);
7741 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7742 	    tcp->tcp_eager_prev_q0 == NULL) ||
7743 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7744 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7745 
7746 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
7747 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
7748 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
7749 
7750 	tcp->tcp_client_errno = 0;
7751 
7752 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7753 
7754 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7755 
7756 	PRESERVE(tcp->tcp_bound_source_v6);
7757 	tcp->tcp_last_sent_len = 0;
7758 	tcp->tcp_dupack_cnt = 0;
7759 
7760 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7761 	PRESERVE(tcp->tcp_lport);
7762 
7763 	PRESERVE(tcp->tcp_acceptor_lockp);
7764 
7765 	ASSERT(tcp->tcp_ordrel_mp == NULL);
7766 	PRESERVE(tcp->tcp_acceptor_id);
7767 	DONTCARE(tcp->tcp_ipsec_overhead);
7768 
7769 	PRESERVE(tcp->tcp_family);
7770 	if (tcp->tcp_family == AF_INET6) {
7771 		tcp->tcp_ipversion = IPV6_VERSION;
7772 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7773 	} else {
7774 		tcp->tcp_ipversion = IPV4_VERSION;
7775 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7776 	}
7777 
7778 	tcp->tcp_bound_if = 0;
7779 	tcp->tcp_ipv6_recvancillary = 0;
7780 	tcp->tcp_recvifindex = 0;
7781 	tcp->tcp_recvhops = 0;
7782 	tcp->tcp_closed = 0;
7783 	tcp->tcp_cleandeathtag = 0;
7784 	if (tcp->tcp_hopopts != NULL) {
7785 		mi_free(tcp->tcp_hopopts);
7786 		tcp->tcp_hopopts = NULL;
7787 		tcp->tcp_hopoptslen = 0;
7788 	}
7789 	ASSERT(tcp->tcp_hopoptslen == 0);
7790 	if (tcp->tcp_dstopts != NULL) {
7791 		mi_free(tcp->tcp_dstopts);
7792 		tcp->tcp_dstopts = NULL;
7793 		tcp->tcp_dstoptslen = 0;
7794 	}
7795 	ASSERT(tcp->tcp_dstoptslen == 0);
7796 	if (tcp->tcp_rtdstopts != NULL) {
7797 		mi_free(tcp->tcp_rtdstopts);
7798 		tcp->tcp_rtdstopts = NULL;
7799 		tcp->tcp_rtdstoptslen = 0;
7800 	}
7801 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7802 	if (tcp->tcp_rthdr != NULL) {
7803 		mi_free(tcp->tcp_rthdr);
7804 		tcp->tcp_rthdr = NULL;
7805 		tcp->tcp_rthdrlen = 0;
7806 	}
7807 	ASSERT(tcp->tcp_rthdrlen == 0);
7808 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7809 
7810 	/* Reset fusion-related fields */
7811 	tcp->tcp_fused = B_FALSE;
7812 	tcp->tcp_unfusable = B_FALSE;
7813 	tcp->tcp_fused_sigurg = B_FALSE;
7814 	tcp->tcp_direct_sockfs = B_FALSE;
7815 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7816 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7817 	tcp->tcp_loopback_peer = NULL;
7818 	tcp->tcp_fuse_rcv_hiwater = 0;
7819 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7820 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7821 
7822 	tcp->tcp_lso = B_FALSE;
7823 
7824 	tcp->tcp_in_ack_unsent = 0;
7825 	tcp->tcp_cork = B_FALSE;
7826 	tcp->tcp_tconnind_started = B_FALSE;
7827 
7828 	PRESERVE(tcp->tcp_squeue_bytes);
7829 
7830 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7831 	ASSERT(!tcp->tcp_kssl_pending);
7832 	PRESERVE(tcp->tcp_kssl_ent);
7833 
7834 	/* Sodirect */
7835 	tcp->tcp_sodirect = NULL;
7836 
7837 	tcp->tcp_closemp_used = B_FALSE;
7838 
7839 	PRESERVE(tcp->tcp_rsrv_mp);
7840 	PRESERVE(tcp->tcp_rsrv_mp_lock);
7841 
7842 #ifdef DEBUG
7843 	DONTCARE(tcp->tcmp_stk[0]);
7844 #endif
7845 
7846 	PRESERVE(tcp->tcp_connid);
7847 
7848 
7849 #undef	DONTCARE
7850 #undef	PRESERVE
7851 }
7852 
7853 /*
7854  * Allocate necessary resources and initialize state vector.
7855  * Guaranteed not to fail so that when an error is returned,
7856  * the caller doesn't need to do any additional cleanup.
7857  */
7858 int
7859 tcp_init(tcp_t *tcp, queue_t *q)
7860 {
7861 	int	err;
7862 
7863 	tcp->tcp_rq = q;
7864 	tcp->tcp_wq = WR(q);
7865 	tcp->tcp_state = TCPS_IDLE;
7866 	if ((err = tcp_init_values(tcp)) != 0)
7867 		tcp_timers_stop(tcp);
7868 	return (err);
7869 }
7870 
7871 static int
7872 tcp_init_values(tcp_t *tcp)
7873 {
7874 	int	err;
7875 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7876 
7877 	ASSERT((tcp->tcp_family == AF_INET &&
7878 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7879 	    (tcp->tcp_family == AF_INET6 &&
7880 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7881 	    tcp->tcp_ipversion == IPV6_VERSION)));
7882 
7883 	/*
7884 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7885 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7886 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7887 	 * during first few transmissions of a connection as seen in slow
7888 	 * links.
7889 	 */
7890 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
7891 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
7892 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7893 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7894 	    tcps->tcps_conn_grace_period;
7895 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
7896 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
7897 	tcp->tcp_timer_backoff = 0;
7898 	tcp->tcp_ms_we_have_waited = 0;
7899 	tcp->tcp_last_recv_time = lbolt;
7900 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
7901 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7902 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7903 
7904 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
7905 
7906 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
7907 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
7908 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
7909 	/*
7910 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7911 	 * passive open.
7912 	 */
7913 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
7914 
7915 	tcp->tcp_naglim = tcps->tcps_naglim_def;
7916 
7917 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7918 
7919 	tcp->tcp_mdt_hdr_head = 0;
7920 	tcp->tcp_mdt_hdr_tail = 0;
7921 
7922 	/* Reset fusion-related fields */
7923 	tcp->tcp_fused = B_FALSE;
7924 	tcp->tcp_unfusable = B_FALSE;
7925 	tcp->tcp_fused_sigurg = B_FALSE;
7926 	tcp->tcp_direct_sockfs = B_FALSE;
7927 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7928 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7929 	tcp->tcp_loopback_peer = NULL;
7930 	tcp->tcp_fuse_rcv_hiwater = 0;
7931 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7932 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7933 
7934 	/* Sodirect */
7935 	tcp->tcp_sodirect = NULL;
7936 
7937 	/* Initialize the header template */
7938 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7939 		err = tcp_header_init_ipv4(tcp);
7940 	} else {
7941 		err = tcp_header_init_ipv6(tcp);
7942 	}
7943 	if (err)
7944 		return (err);
7945 
7946 	/*
7947 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7948 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7949 	 */
7950 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7951 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
7952 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
7953 
7954 	tcp->tcp_cork = B_FALSE;
7955 	/*
7956 	 * Init the tcp_debug option.  This value determines whether TCP
7957 	 * calls strlog() to print out debug messages.  Doing this
7958 	 * initialization here means that this value is not inherited thru
7959 	 * tcp_reinit().
7960 	 */
7961 	tcp->tcp_debug = tcps->tcps_dbg;
7962 
7963 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
7964 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
7965 
7966 	return (0);
7967 }
7968 
7969 /*
7970  * Initialize the IPv4 header. Loses any record of any IP options.
7971  */
7972 static int
7973 tcp_header_init_ipv4(tcp_t *tcp)
7974 {
7975 	tcph_t		*tcph;
7976 	uint32_t	sum;
7977 	conn_t		*connp;
7978 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7979 
7980 	/*
7981 	 * This is a simple initialization. If there's
7982 	 * already a template, it should never be too small,
7983 	 * so reuse it.  Otherwise, allocate space for the new one.
7984 	 */
7985 	if (tcp->tcp_iphc == NULL) {
7986 		ASSERT(tcp->tcp_iphc_len == 0);
7987 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
7988 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
7989 		if (tcp->tcp_iphc == NULL) {
7990 			tcp->tcp_iphc_len = 0;
7991 			return (ENOMEM);
7992 		}
7993 	}
7994 
7995 	/* options are gone; may need a new label */
7996 	connp = tcp->tcp_connp;
7997 	connp->conn_mlp_type = mlptSingle;
7998 	connp->conn_ulp_labeled = !is_system_labeled();
7999 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8000 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8001 	tcp->tcp_ip6h = NULL;
8002 	tcp->tcp_ipversion = IPV4_VERSION;
8003 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8004 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8005 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8006 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8007 	tcp->tcp_ipha->ipha_version_and_hdr_length
8008 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8009 	tcp->tcp_ipha->ipha_ident = 0;
8010 
8011 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8012 	tcp->tcp_tos = 0;
8013 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8014 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8015 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8016 
8017 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8018 	tcp->tcp_tcph = tcph;
8019 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8020 	/*
8021 	 * IP wants our header length in the checksum field to
8022 	 * allow it to perform a single pseudo-header+checksum
8023 	 * calculation on behalf of TCP.
8024 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8025 	 */
8026 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8027 	sum = (sum >> 16) + (sum & 0xFFFF);
8028 	U16_TO_ABE16(sum, tcph->th_sum);
8029 	return (0);
8030 }
8031 
8032 /*
8033  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8034  */
8035 static int
8036 tcp_header_init_ipv6(tcp_t *tcp)
8037 {
8038 	tcph_t	*tcph;
8039 	uint32_t	sum;
8040 	conn_t	*connp;
8041 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8042 
8043 	/*
8044 	 * This is a simple initialization. If there's
8045 	 * already a template, it should never be too small,
8046 	 * so reuse it. Otherwise, allocate space for the new one.
8047 	 * Ensure that there is enough space to "downgrade" the tcp_t
8048 	 * to an IPv4 tcp_t. This requires having space for a full load
8049 	 * of IPv4 options, as well as a full load of TCP options
8050 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8051 	 * than a v6 header and a TCP header with a full load of TCP options
8052 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8053 	 * We want to avoid reallocation in the "downgraded" case when
8054 	 * processing outbound IPv4 options.
8055 	 */
8056 	if (tcp->tcp_iphc == NULL) {
8057 		ASSERT(tcp->tcp_iphc_len == 0);
8058 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8059 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8060 		if (tcp->tcp_iphc == NULL) {
8061 			tcp->tcp_iphc_len = 0;
8062 			return (ENOMEM);
8063 		}
8064 	}
8065 
8066 	/* options are gone; may need a new label */
8067 	connp = tcp->tcp_connp;
8068 	connp->conn_mlp_type = mlptSingle;
8069 	connp->conn_ulp_labeled = !is_system_labeled();
8070 
8071 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8072 	tcp->tcp_ipversion = IPV6_VERSION;
8073 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8074 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8075 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8076 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8077 	tcp->tcp_ipha = NULL;
8078 
8079 	/* Initialize the header template */
8080 
8081 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8082 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8083 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8084 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8085 
8086 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8087 	tcp->tcp_tcph = tcph;
8088 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8089 	/*
8090 	 * IP wants our header length in the checksum field to
8091 	 * allow it to perform a single psuedo-header+checksum
8092 	 * calculation on behalf of TCP.
8093 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8094 	 */
8095 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8096 	sum = (sum >> 16) + (sum & 0xFFFF);
8097 	U16_TO_ABE16(sum, tcph->th_sum);
8098 	return (0);
8099 }
8100 
8101 /* At minimum we need 8 bytes in the TCP header for the lookup */
8102 #define	ICMP_MIN_TCP_HDR	8
8103 
8104 /*
8105  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8106  * passed up by IP. The message is always received on the correct tcp_t.
8107  * Assumes that IP has pulled up everything up to and including the ICMP header.
8108  */
8109 void
8110 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8111 {
8112 	icmph_t *icmph;
8113 	ipha_t	*ipha;
8114 	int	iph_hdr_length;
8115 	tcph_t	*tcph;
8116 	boolean_t ipsec_mctl = B_FALSE;
8117 	boolean_t secure;
8118 	mblk_t *first_mp = mp;
8119 	int32_t new_mss;
8120 	uint32_t ratio;
8121 	size_t mp_size = MBLKL(mp);
8122 	uint32_t seg_seq;
8123 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8124 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8125 
8126 	/* Assume IP provides aligned packets - otherwise toss */
8127 	if (!OK_32PTR(mp->b_rptr)) {
8128 		freemsg(mp);
8129 		return;
8130 	}
8131 
8132 	/*
8133 	 * Since ICMP errors are normal data marked with M_CTL when sent
8134 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8135 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8136 	 */
8137 	if ((mp_size == sizeof (ipsec_info_t)) &&
8138 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8139 		ASSERT(mp->b_cont != NULL);
8140 		mp = mp->b_cont;
8141 		/* IP should have done this */
8142 		ASSERT(OK_32PTR(mp->b_rptr));
8143 		mp_size = MBLKL(mp);
8144 		ipsec_mctl = B_TRUE;
8145 	}
8146 
8147 	/*
8148 	 * Verify that we have a complete outer IP header. If not, drop it.
8149 	 */
8150 	if (mp_size < sizeof (ipha_t)) {
8151 noticmpv4:
8152 		freemsg(first_mp);
8153 		return;
8154 	}
8155 
8156 	ipha = (ipha_t *)mp->b_rptr;
8157 	/*
8158 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8159 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8160 	 */
8161 	switch (IPH_HDR_VERSION(ipha)) {
8162 	case IPV6_VERSION:
8163 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8164 		return;
8165 	case IPV4_VERSION:
8166 		break;
8167 	default:
8168 		goto noticmpv4;
8169 	}
8170 
8171 	/* Skip past the outer IP and ICMP headers */
8172 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8173 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8174 	/*
8175 	 * If we don't have the correct outer IP header length or if the ULP
8176 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8177 	 * send it upstream.
8178 	 */
8179 	if (iph_hdr_length < sizeof (ipha_t) ||
8180 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8181 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8182 		goto noticmpv4;
8183 	}
8184 	ipha = (ipha_t *)&icmph[1];
8185 
8186 	/* Skip past the inner IP and find the ULP header */
8187 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8188 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8189 	/*
8190 	 * If we don't have the correct inner IP header length or if the ULP
8191 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8192 	 * bytes of TCP header, drop it.
8193 	 */
8194 	if (iph_hdr_length < sizeof (ipha_t) ||
8195 	    ipha->ipha_protocol != IPPROTO_TCP ||
8196 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8197 		goto noticmpv4;
8198 	}
8199 
8200 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8201 		if (ipsec_mctl) {
8202 			secure = ipsec_in_is_secure(first_mp);
8203 		} else {
8204 			secure = B_FALSE;
8205 		}
8206 		if (secure) {
8207 			/*
8208 			 * If we are willing to accept this in clear
8209 			 * we don't have to verify policy.
8210 			 */
8211 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8212 				if (!tcp_check_policy(tcp, first_mp,
8213 				    ipha, NULL, secure, ipsec_mctl)) {
8214 					/*
8215 					 * tcp_check_policy called
8216 					 * ip_drop_packet() on failure.
8217 					 */
8218 					return;
8219 				}
8220 			}
8221 		}
8222 	} else if (ipsec_mctl) {
8223 		/*
8224 		 * This is a hard_bound connection. IP has already
8225 		 * verified policy. We don't have to do it again.
8226 		 */
8227 		freeb(first_mp);
8228 		first_mp = mp;
8229 		ipsec_mctl = B_FALSE;
8230 	}
8231 
8232 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8233 	/*
8234 	 * TCP SHOULD check that the TCP sequence number contained in
8235 	 * payload of the ICMP error message is within the range
8236 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8237 	 */
8238 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8239 		/*
8240 		 * The ICMP message is bogus, just drop it.  But if this is
8241 		 * an ICMP too big message, IP has already changed
8242 		 * the ire_max_frag to the bogus value.  We need to change
8243 		 * it back.
8244 		 */
8245 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8246 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8247 			conn_t *connp = tcp->tcp_connp;
8248 			ire_t *ire;
8249 			int flag;
8250 
8251 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8252 				flag = tcp->tcp_ipha->
8253 				    ipha_fragment_offset_and_flags;
8254 			} else {
8255 				flag = 0;
8256 			}
8257 			mutex_enter(&connp->conn_lock);
8258 			if ((ire = connp->conn_ire_cache) != NULL) {
8259 				mutex_enter(&ire->ire_lock);
8260 				mutex_exit(&connp->conn_lock);
8261 				ire->ire_max_frag = tcp->tcp_if_mtu;
8262 				ire->ire_frag_flag |= flag;
8263 				mutex_exit(&ire->ire_lock);
8264 			} else {
8265 				mutex_exit(&connp->conn_lock);
8266 			}
8267 		}
8268 		goto noticmpv4;
8269 	}
8270 
8271 	switch (icmph->icmph_type) {
8272 	case ICMP_DEST_UNREACHABLE:
8273 		switch (icmph->icmph_code) {
8274 		case ICMP_FRAGMENTATION_NEEDED:
8275 			/*
8276 			 * Reduce the MSS based on the new MTU.  This will
8277 			 * eliminate any fragmentation locally.
8278 			 * N.B.  There may well be some funny side-effects on
8279 			 * the local send policy and the remote receive policy.
8280 			 * Pending further research, we provide
8281 			 * tcp_ignore_path_mtu just in case this proves
8282 			 * disastrous somewhere.
8283 			 *
8284 			 * After updating the MSS, retransmit part of the
8285 			 * dropped segment using the new mss by calling
8286 			 * tcp_wput_data().  Need to adjust all those
8287 			 * params to make sure tcp_wput_data() work properly.
8288 			 */
8289 			if (tcps->tcps_ignore_path_mtu ||
8290 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8291 				break;
8292 
8293 			/*
8294 			 * Decrease the MSS by time stamp options
8295 			 * IP options and IPSEC options. tcp_hdr_len
8296 			 * includes time stamp option and IP option
8297 			 * length.  Note that new_mss may be negative
8298 			 * if tcp_ipsec_overhead is large and the
8299 			 * icmph_du_mtu is the minimum value, which is 68.
8300 			 */
8301 			new_mss = ntohs(icmph->icmph_du_mtu) -
8302 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8303 
8304 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8305 			    new_mss);
8306 
8307 			/*
8308 			 * Only update the MSS if the new one is
8309 			 * smaller than the previous one.  This is
8310 			 * to avoid problems when getting multiple
8311 			 * ICMP errors for the same MTU.
8312 			 */
8313 			if (new_mss >= tcp->tcp_mss)
8314 				break;
8315 
8316 			/*
8317 			 * Note that we are using the template header's DF
8318 			 * bit in the fast path sending.  So we need to compare
8319 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8320 			 * And stop doing IPv4 PMTUd if new_mss is less than
8321 			 * MAX(tcps_mss_min, ip_pmtu_min).
8322 			 */
8323 			if (new_mss < tcps->tcps_mss_min ||
8324 			    new_mss < ipst->ips_ip_pmtu_min) {
8325 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8326 				    0;
8327 			}
8328 
8329 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8330 			ASSERT(ratio >= 1);
8331 			tcp_mss_set(tcp, new_mss, B_TRUE);
8332 
8333 			/*
8334 			 * Make sure we have something to
8335 			 * send.
8336 			 */
8337 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8338 			    (tcp->tcp_xmit_head != NULL)) {
8339 				/*
8340 				 * Shrink tcp_cwnd in
8341 				 * proportion to the old MSS/new MSS.
8342 				 */
8343 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8344 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8345 				    (tcp->tcp_unsent == 0)) {
8346 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8347 				} else {
8348 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8349 				}
8350 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8351 				tcp->tcp_rexmit = B_TRUE;
8352 				tcp->tcp_dupack_cnt = 0;
8353 				tcp->tcp_snd_burst = TCP_CWND_SS;
8354 				tcp_ss_rexmit(tcp);
8355 			}
8356 			break;
8357 		case ICMP_PORT_UNREACHABLE:
8358 		case ICMP_PROTOCOL_UNREACHABLE:
8359 			switch (tcp->tcp_state) {
8360 			case TCPS_SYN_SENT:
8361 			case TCPS_SYN_RCVD:
8362 				/*
8363 				 * ICMP can snipe away incipient
8364 				 * TCP connections as long as
8365 				 * seq number is same as initial
8366 				 * send seq number.
8367 				 */
8368 				if (seg_seq == tcp->tcp_iss) {
8369 					(void) tcp_clean_death(tcp,
8370 					    ECONNREFUSED, 6);
8371 				}
8372 				break;
8373 			}
8374 			break;
8375 		case ICMP_HOST_UNREACHABLE:
8376 		case ICMP_NET_UNREACHABLE:
8377 			/* Record the error in case we finally time out. */
8378 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8379 				tcp->tcp_client_errno = EHOSTUNREACH;
8380 			else
8381 				tcp->tcp_client_errno = ENETUNREACH;
8382 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8383 				if (tcp->tcp_listener != NULL &&
8384 				    tcp->tcp_listener->tcp_syn_defense) {
8385 					/*
8386 					 * Ditch the half-open connection if we
8387 					 * suspect a SYN attack is under way.
8388 					 */
8389 					tcp_ip_ire_mark_advice(tcp);
8390 					(void) tcp_clean_death(tcp,
8391 					    tcp->tcp_client_errno, 7);
8392 				}
8393 			}
8394 			break;
8395 		default:
8396 			break;
8397 		}
8398 		break;
8399 	case ICMP_SOURCE_QUENCH: {
8400 		/*
8401 		 * use a global boolean to control
8402 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8403 		 * The default is false.
8404 		 */
8405 		if (tcp_icmp_source_quench) {
8406 			/*
8407 			 * Reduce the sending rate as if we got a
8408 			 * retransmit timeout
8409 			 */
8410 			uint32_t npkt;
8411 
8412 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8413 			    tcp->tcp_mss;
8414 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8415 			tcp->tcp_cwnd = tcp->tcp_mss;
8416 			tcp->tcp_cwnd_cnt = 0;
8417 		}
8418 		break;
8419 	}
8420 	}
8421 	freemsg(first_mp);
8422 }
8423 
8424 /*
8425  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8426  * error messages passed up by IP.
8427  * Assumes that IP has pulled up all the extension headers as well
8428  * as the ICMPv6 header.
8429  */
8430 static void
8431 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8432 {
8433 	icmp6_t *icmp6;
8434 	ip6_t	*ip6h;
8435 	uint16_t	iph_hdr_length;
8436 	tcpha_t	*tcpha;
8437 	uint8_t	*nexthdrp;
8438 	uint32_t new_mss;
8439 	uint32_t ratio;
8440 	boolean_t secure;
8441 	mblk_t *first_mp = mp;
8442 	size_t mp_size;
8443 	uint32_t seg_seq;
8444 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8445 
8446 	/*
8447 	 * The caller has determined if this is an IPSEC_IN packet and
8448 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8449 	 */
8450 	if (ipsec_mctl)
8451 		mp = mp->b_cont;
8452 
8453 	mp_size = MBLKL(mp);
8454 
8455 	/*
8456 	 * Verify that we have a complete IP header. If not, send it upstream.
8457 	 */
8458 	if (mp_size < sizeof (ip6_t)) {
8459 noticmpv6:
8460 		freemsg(first_mp);
8461 		return;
8462 	}
8463 
8464 	/*
8465 	 * Verify this is an ICMPV6 packet, else send it upstream.
8466 	 */
8467 	ip6h = (ip6_t *)mp->b_rptr;
8468 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8469 		iph_hdr_length = IPV6_HDR_LEN;
8470 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8471 	    &nexthdrp) ||
8472 	    *nexthdrp != IPPROTO_ICMPV6) {
8473 		goto noticmpv6;
8474 	}
8475 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8476 	ip6h = (ip6_t *)&icmp6[1];
8477 	/*
8478 	 * Verify if we have a complete ICMP and inner IP header.
8479 	 */
8480 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8481 		goto noticmpv6;
8482 
8483 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8484 		goto noticmpv6;
8485 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8486 	/*
8487 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8488 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8489 	 * packet.
8490 	 */
8491 	if ((*nexthdrp != IPPROTO_TCP) ||
8492 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8493 		goto noticmpv6;
8494 	}
8495 
8496 	/*
8497 	 * ICMP errors come on the right queue or come on
8498 	 * listener/global queue for detached connections and
8499 	 * get switched to the right queue. If it comes on the
8500 	 * right queue, policy check has already been done by IP
8501 	 * and thus free the first_mp without verifying the policy.
8502 	 * If it has come for a non-hard bound connection, we need
8503 	 * to verify policy as IP may not have done it.
8504 	 */
8505 	if (!tcp->tcp_hard_bound) {
8506 		if (ipsec_mctl) {
8507 			secure = ipsec_in_is_secure(first_mp);
8508 		} else {
8509 			secure = B_FALSE;
8510 		}
8511 		if (secure) {
8512 			/*
8513 			 * If we are willing to accept this in clear
8514 			 * we don't have to verify policy.
8515 			 */
8516 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8517 				if (!tcp_check_policy(tcp, first_mp,
8518 				    NULL, ip6h, secure, ipsec_mctl)) {
8519 					/*
8520 					 * tcp_check_policy called
8521 					 * ip_drop_packet() on failure.
8522 					 */
8523 					return;
8524 				}
8525 			}
8526 		}
8527 	} else if (ipsec_mctl) {
8528 		/*
8529 		 * This is a hard_bound connection. IP has already
8530 		 * verified policy. We don't have to do it again.
8531 		 */
8532 		freeb(first_mp);
8533 		first_mp = mp;
8534 		ipsec_mctl = B_FALSE;
8535 	}
8536 
8537 	seg_seq = ntohl(tcpha->tha_seq);
8538 	/*
8539 	 * TCP SHOULD check that the TCP sequence number contained in
8540 	 * payload of the ICMP error message is within the range
8541 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8542 	 */
8543 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8544 		/*
8545 		 * If the ICMP message is bogus, should we kill the
8546 		 * connection, or should we just drop the bogus ICMP
8547 		 * message? It would probably make more sense to just
8548 		 * drop the message so that if this one managed to get
8549 		 * in, the real connection should not suffer.
8550 		 */
8551 		goto noticmpv6;
8552 	}
8553 
8554 	switch (icmp6->icmp6_type) {
8555 	case ICMP6_PACKET_TOO_BIG:
8556 		/*
8557 		 * Reduce the MSS based on the new MTU.  This will
8558 		 * eliminate any fragmentation locally.
8559 		 * N.B.  There may well be some funny side-effects on
8560 		 * the local send policy and the remote receive policy.
8561 		 * Pending further research, we provide
8562 		 * tcp_ignore_path_mtu just in case this proves
8563 		 * disastrous somewhere.
8564 		 *
8565 		 * After updating the MSS, retransmit part of the
8566 		 * dropped segment using the new mss by calling
8567 		 * tcp_wput_data().  Need to adjust all those
8568 		 * params to make sure tcp_wput_data() work properly.
8569 		 */
8570 		if (tcps->tcps_ignore_path_mtu)
8571 			break;
8572 
8573 		/*
8574 		 * Decrease the MSS by time stamp options
8575 		 * IP options and IPSEC options. tcp_hdr_len
8576 		 * includes time stamp option and IP option
8577 		 * length.
8578 		 */
8579 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8580 		    tcp->tcp_ipsec_overhead;
8581 
8582 		/*
8583 		 * Only update the MSS if the new one is
8584 		 * smaller than the previous one.  This is
8585 		 * to avoid problems when getting multiple
8586 		 * ICMP errors for the same MTU.
8587 		 */
8588 		if (new_mss >= tcp->tcp_mss)
8589 			break;
8590 
8591 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8592 		ASSERT(ratio >= 1);
8593 		tcp_mss_set(tcp, new_mss, B_TRUE);
8594 
8595 		/*
8596 		 * Make sure we have something to
8597 		 * send.
8598 		 */
8599 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8600 		    (tcp->tcp_xmit_head != NULL)) {
8601 			/*
8602 			 * Shrink tcp_cwnd in
8603 			 * proportion to the old MSS/new MSS.
8604 			 */
8605 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8606 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8607 			    (tcp->tcp_unsent == 0)) {
8608 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8609 			} else {
8610 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8611 			}
8612 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8613 			tcp->tcp_rexmit = B_TRUE;
8614 			tcp->tcp_dupack_cnt = 0;
8615 			tcp->tcp_snd_burst = TCP_CWND_SS;
8616 			tcp_ss_rexmit(tcp);
8617 		}
8618 		break;
8619 
8620 	case ICMP6_DST_UNREACH:
8621 		switch (icmp6->icmp6_code) {
8622 		case ICMP6_DST_UNREACH_NOPORT:
8623 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8624 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8625 			    (seg_seq == tcp->tcp_iss)) {
8626 				(void) tcp_clean_death(tcp,
8627 				    ECONNREFUSED, 8);
8628 			}
8629 			break;
8630 
8631 		case ICMP6_DST_UNREACH_ADMIN:
8632 		case ICMP6_DST_UNREACH_NOROUTE:
8633 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8634 		case ICMP6_DST_UNREACH_ADDR:
8635 			/* Record the error in case we finally time out. */
8636 			tcp->tcp_client_errno = EHOSTUNREACH;
8637 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8638 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8639 			    (seg_seq == tcp->tcp_iss)) {
8640 				if (tcp->tcp_listener != NULL &&
8641 				    tcp->tcp_listener->tcp_syn_defense) {
8642 					/*
8643 					 * Ditch the half-open connection if we
8644 					 * suspect a SYN attack is under way.
8645 					 */
8646 					tcp_ip_ire_mark_advice(tcp);
8647 					(void) tcp_clean_death(tcp,
8648 					    tcp->tcp_client_errno, 9);
8649 				}
8650 			}
8651 
8652 
8653 			break;
8654 		default:
8655 			break;
8656 		}
8657 		break;
8658 
8659 	case ICMP6_PARAM_PROB:
8660 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8661 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8662 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8663 		    (uchar_t *)nexthdrp) {
8664 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8665 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8666 				(void) tcp_clean_death(tcp,
8667 				    ECONNREFUSED, 10);
8668 			}
8669 			break;
8670 		}
8671 		break;
8672 
8673 	case ICMP6_TIME_EXCEEDED:
8674 	default:
8675 		break;
8676 	}
8677 	freemsg(first_mp);
8678 }
8679 
8680 /*
8681  * Notify IP that we are having trouble with this connection.  IP should
8682  * blow the IRE away and start over.
8683  */
8684 static void
8685 tcp_ip_notify(tcp_t *tcp)
8686 {
8687 	struct iocblk	*iocp;
8688 	ipid_t	*ipid;
8689 	mblk_t	*mp;
8690 
8691 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8692 	if (tcp->tcp_ipversion == IPV6_VERSION)
8693 		return;
8694 
8695 	mp = mkiocb(IP_IOCTL);
8696 	if (mp == NULL)
8697 		return;
8698 
8699 	iocp = (struct iocblk *)mp->b_rptr;
8700 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8701 
8702 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8703 	if (!mp->b_cont) {
8704 		freeb(mp);
8705 		return;
8706 	}
8707 
8708 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8709 	mp->b_cont->b_wptr += iocp->ioc_count;
8710 	bzero(ipid, sizeof (*ipid));
8711 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8712 	ipid->ipid_ire_type = IRE_CACHE;
8713 	ipid->ipid_addr_offset = sizeof (ipid_t);
8714 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8715 	/*
8716 	 * Note: in the case of source routing we want to blow away the
8717 	 * route to the first source route hop.
8718 	 */
8719 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8720 	    sizeof (tcp->tcp_ipha->ipha_dst));
8721 
8722 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8723 }
8724 
8725 /* Unlink and return any mblk that looks like it contains an ire */
8726 static mblk_t *
8727 tcp_ire_mp(mblk_t **mpp)
8728 {
8729 	mblk_t 	*mp = *mpp;
8730 	mblk_t	*prev_mp = NULL;
8731 
8732 	for (;;) {
8733 		switch (DB_TYPE(mp)) {
8734 		case IRE_DB_TYPE:
8735 		case IRE_DB_REQ_TYPE:
8736 			if (mp == *mpp) {
8737 				*mpp = mp->b_cont;
8738 			} else {
8739 				prev_mp->b_cont = mp->b_cont;
8740 			}
8741 			mp->b_cont = NULL;
8742 			return (mp);
8743 		default:
8744 			break;
8745 		}
8746 		prev_mp = mp;
8747 		mp = mp->b_cont;
8748 		if (mp == NULL)
8749 			break;
8750 	}
8751 	return (mp);
8752 }
8753 
8754 /*
8755  * Timer callback routine for keepalive probe.  We do a fake resend of
8756  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8757  * check to see if we have heard anything from the other end for the last
8758  * RTO period.  If we have, set the timer to expire for another
8759  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8760  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8761  * the timeout if we have not heard from the other side.  If for more than
8762  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8763  * kill the connection unless the keepalive abort threshold is 0.  In
8764  * that case, we will probe "forever."
8765  */
8766 static void
8767 tcp_keepalive_killer(void *arg)
8768 {
8769 	mblk_t	*mp;
8770 	conn_t	*connp = (conn_t *)arg;
8771 	tcp_t  	*tcp = connp->conn_tcp;
8772 	int32_t	firetime;
8773 	int32_t	idletime;
8774 	int32_t	ka_intrvl;
8775 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8776 
8777 	tcp->tcp_ka_tid = 0;
8778 
8779 	if (tcp->tcp_fused)
8780 		return;
8781 
8782 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
8783 	ka_intrvl = tcp->tcp_ka_interval;
8784 
8785 	/*
8786 	 * Keepalive probe should only be sent if the application has not
8787 	 * done a close on the connection.
8788 	 */
8789 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8790 		return;
8791 	}
8792 	/* Timer fired too early, restart it. */
8793 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8794 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8795 		    MSEC_TO_TICK(ka_intrvl));
8796 		return;
8797 	}
8798 
8799 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8800 	/*
8801 	 * If we have not heard from the other side for a long
8802 	 * time, kill the connection unless the keepalive abort
8803 	 * threshold is 0.  In that case, we will probe "forever."
8804 	 */
8805 	if (tcp->tcp_ka_abort_thres != 0 &&
8806 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8807 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
8808 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8809 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8810 		return;
8811 	}
8812 
8813 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8814 	    idletime >= ka_intrvl) {
8815 		/* Fake resend of last ACKed byte. */
8816 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8817 
8818 		if (mp1 != NULL) {
8819 			*mp1->b_wptr++ = '\0';
8820 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8821 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8822 			freeb(mp1);
8823 			/*
8824 			 * if allocation failed, fall through to start the
8825 			 * timer back.
8826 			 */
8827 			if (mp != NULL) {
8828 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8829 				BUMP_MIB(&tcps->tcps_mib,
8830 				    tcpTimKeepaliveProbe);
8831 				if (tcp->tcp_ka_last_intrvl != 0) {
8832 					int max;
8833 					/*
8834 					 * We should probe again at least
8835 					 * in ka_intrvl, but not more than
8836 					 * tcp_rexmit_interval_max.
8837 					 */
8838 					max = tcps->tcps_rexmit_interval_max;
8839 					firetime = MIN(ka_intrvl - 1,
8840 					    tcp->tcp_ka_last_intrvl << 1);
8841 					if (firetime > max)
8842 						firetime = max;
8843 				} else {
8844 					firetime = tcp->tcp_rto;
8845 				}
8846 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8847 				    tcp_keepalive_killer,
8848 				    MSEC_TO_TICK(firetime));
8849 				tcp->tcp_ka_last_intrvl = firetime;
8850 				return;
8851 			}
8852 		}
8853 	} else {
8854 		tcp->tcp_ka_last_intrvl = 0;
8855 	}
8856 
8857 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8858 	if ((firetime = ka_intrvl - idletime) < 0) {
8859 		firetime = ka_intrvl;
8860 	}
8861 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8862 	    MSEC_TO_TICK(firetime));
8863 }
8864 
8865 int
8866 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8867 {
8868 	queue_t	*q = tcp->tcp_rq;
8869 	int32_t	mss = tcp->tcp_mss;
8870 	int	maxpsz;
8871 	conn_t	*connp = tcp->tcp_connp;
8872 
8873 	if (TCP_IS_DETACHED(tcp))
8874 		return (mss);
8875 	if (tcp->tcp_fused) {
8876 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8877 		mss = INFPSZ;
8878 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
8879 		/*
8880 		 * Set the sd_qn_maxpsz according to the socket send buffer
8881 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8882 		 * instruct the stream head to copyin user data into contiguous
8883 		 * kernel-allocated buffers without breaking it up into smaller
8884 		 * chunks.  We round up the buffer size to the nearest SMSS.
8885 		 */
8886 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8887 		if (tcp->tcp_kssl_ctx == NULL)
8888 			mss = INFPSZ;
8889 		else
8890 			mss = SSL3_MAX_RECORD_LEN;
8891 	} else {
8892 		/*
8893 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8894 		 * (and a multiple of the mss).  This instructs the stream
8895 		 * head to break down larger than SMSS writes into SMSS-
8896 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8897 		 */
8898 		/* XXX tune this with ndd tcp_maxpsz_multiplier */
8899 		maxpsz = tcp->tcp_maxpsz * mss;
8900 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8901 			maxpsz = tcp->tcp_xmit_hiwater/2;
8902 			/* Round up to nearest mss */
8903 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8904 		}
8905 	}
8906 
8907 	(void) proto_set_maxpsz(q, connp, maxpsz);
8908 	if (!(IPCL_IS_NONSTR(connp))) {
8909 		/* XXX do it in set_maxpsz()? */
8910 		tcp->tcp_wq->q_maxpsz = maxpsz;
8911 	}
8912 
8913 	if (set_maxblk)
8914 		(void) proto_set_tx_maxblk(q, connp, mss);
8915 	return (mss);
8916 }
8917 
8918 /*
8919  * Extract option values from a tcp header.  We put any found values into the
8920  * tcpopt struct and return a bitmask saying which options were found.
8921  */
8922 static int
8923 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8924 {
8925 	uchar_t		*endp;
8926 	int		len;
8927 	uint32_t	mss;
8928 	uchar_t		*up = (uchar_t *)tcph;
8929 	int		found = 0;
8930 	int32_t		sack_len;
8931 	tcp_seq		sack_begin, sack_end;
8932 	tcp_t		*tcp;
8933 
8934 	endp = up + TCP_HDR_LENGTH(tcph);
8935 	up += TCP_MIN_HEADER_LENGTH;
8936 	while (up < endp) {
8937 		len = endp - up;
8938 		switch (*up) {
8939 		case TCPOPT_EOL:
8940 			break;
8941 
8942 		case TCPOPT_NOP:
8943 			up++;
8944 			continue;
8945 
8946 		case TCPOPT_MAXSEG:
8947 			if (len < TCPOPT_MAXSEG_LEN ||
8948 			    up[1] != TCPOPT_MAXSEG_LEN)
8949 				break;
8950 
8951 			mss = BE16_TO_U16(up+2);
8952 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
8953 			tcpopt->tcp_opt_mss = mss;
8954 			found |= TCP_OPT_MSS_PRESENT;
8955 
8956 			up += TCPOPT_MAXSEG_LEN;
8957 			continue;
8958 
8959 		case TCPOPT_WSCALE:
8960 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
8961 				break;
8962 
8963 			if (up[2] > TCP_MAX_WINSHIFT)
8964 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
8965 			else
8966 				tcpopt->tcp_opt_wscale = up[2];
8967 			found |= TCP_OPT_WSCALE_PRESENT;
8968 
8969 			up += TCPOPT_WS_LEN;
8970 			continue;
8971 
8972 		case TCPOPT_SACK_PERMITTED:
8973 			if (len < TCPOPT_SACK_OK_LEN ||
8974 			    up[1] != TCPOPT_SACK_OK_LEN)
8975 				break;
8976 			found |= TCP_OPT_SACK_OK_PRESENT;
8977 			up += TCPOPT_SACK_OK_LEN;
8978 			continue;
8979 
8980 		case TCPOPT_SACK:
8981 			if (len <= 2 || up[1] <= 2 || len < up[1])
8982 				break;
8983 
8984 			/* If TCP is not interested in SACK blks... */
8985 			if ((tcp = tcpopt->tcp) == NULL) {
8986 				up += up[1];
8987 				continue;
8988 			}
8989 			sack_len = up[1] - TCPOPT_HEADER_LEN;
8990 			up += TCPOPT_HEADER_LEN;
8991 
8992 			/*
8993 			 * If the list is empty, allocate one and assume
8994 			 * nothing is sack'ed.
8995 			 */
8996 			ASSERT(tcp->tcp_sack_info != NULL);
8997 			if (tcp->tcp_notsack_list == NULL) {
8998 				tcp_notsack_update(&(tcp->tcp_notsack_list),
8999 				    tcp->tcp_suna, tcp->tcp_snxt,
9000 				    &(tcp->tcp_num_notsack_blk),
9001 				    &(tcp->tcp_cnt_notsack_list));
9002 
9003 				/*
9004 				 * Make sure tcp_notsack_list is not NULL.
9005 				 * This happens when kmem_alloc(KM_NOSLEEP)
9006 				 * returns NULL.
9007 				 */
9008 				if (tcp->tcp_notsack_list == NULL) {
9009 					up += sack_len;
9010 					continue;
9011 				}
9012 				tcp->tcp_fack = tcp->tcp_suna;
9013 			}
9014 
9015 			while (sack_len > 0) {
9016 				if (up + 8 > endp) {
9017 					up = endp;
9018 					break;
9019 				}
9020 				sack_begin = BE32_TO_U32(up);
9021 				up += 4;
9022 				sack_end = BE32_TO_U32(up);
9023 				up += 4;
9024 				sack_len -= 8;
9025 				/*
9026 				 * Bounds checking.  Make sure the SACK
9027 				 * info is within tcp_suna and tcp_snxt.
9028 				 * If this SACK blk is out of bound, ignore
9029 				 * it but continue to parse the following
9030 				 * blks.
9031 				 */
9032 				if (SEQ_LEQ(sack_end, sack_begin) ||
9033 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9034 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9035 					continue;
9036 				}
9037 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9038 				    sack_begin, sack_end,
9039 				    &(tcp->tcp_num_notsack_blk),
9040 				    &(tcp->tcp_cnt_notsack_list));
9041 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9042 					tcp->tcp_fack = sack_end;
9043 				}
9044 			}
9045 			found |= TCP_OPT_SACK_PRESENT;
9046 			continue;
9047 
9048 		case TCPOPT_TSTAMP:
9049 			if (len < TCPOPT_TSTAMP_LEN ||
9050 			    up[1] != TCPOPT_TSTAMP_LEN)
9051 				break;
9052 
9053 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9054 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9055 
9056 			found |= TCP_OPT_TSTAMP_PRESENT;
9057 
9058 			up += TCPOPT_TSTAMP_LEN;
9059 			continue;
9060 
9061 		default:
9062 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9063 				break;
9064 			up += up[1];
9065 			continue;
9066 		}
9067 		break;
9068 	}
9069 	return (found);
9070 }
9071 
9072 /*
9073  * Set the mss associated with a particular tcp based on its current value,
9074  * and a new one passed in. Observe minimums and maximums, and reset
9075  * other state variables that we want to view as multiples of mss.
9076  *
9077  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9078  * highwater marks etc. need to be initialized or adjusted.
9079  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9080  *    packet arrives.
9081  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9082  *    ICMP6_PACKET_TOO_BIG arrives.
9083  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9084  *    to increase the MSS to use the extra bytes available.
9085  *
9086  * Callers except tcp_paws_check() ensure that they only reduce mss.
9087  */
9088 static void
9089 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9090 {
9091 	uint32_t	mss_max;
9092 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9093 
9094 	if (tcp->tcp_ipversion == IPV4_VERSION)
9095 		mss_max = tcps->tcps_mss_max_ipv4;
9096 	else
9097 		mss_max = tcps->tcps_mss_max_ipv6;
9098 
9099 	if (mss < tcps->tcps_mss_min)
9100 		mss = tcps->tcps_mss_min;
9101 	if (mss > mss_max)
9102 		mss = mss_max;
9103 	/*
9104 	 * Unless naglim has been set by our client to
9105 	 * a non-mss value, force naglim to track mss.
9106 	 * This can help to aggregate small writes.
9107 	 */
9108 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9109 		tcp->tcp_naglim = mss;
9110 	/*
9111 	 * TCP should be able to buffer at least 4 MSS data for obvious
9112 	 * performance reason.
9113 	 */
9114 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9115 		tcp->tcp_xmit_hiwater = mss << 2;
9116 
9117 	if (do_ss) {
9118 		/*
9119 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9120 		 * changing due to a reduction in MTU, presumably as a
9121 		 * result of a new path component, reset cwnd to its
9122 		 * "initial" value, as a multiple of the new mss.
9123 		 */
9124 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9125 	} else {
9126 		/*
9127 		 * Called by tcp_paws_check(), the mss increased
9128 		 * marginally to allow use of space previously taken
9129 		 * by the timestamp option. It would be inappropriate
9130 		 * to apply slow start or tcp_init_cwnd values to
9131 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9132 		 */
9133 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9134 		tcp->tcp_cwnd_cnt = 0;
9135 	}
9136 	tcp->tcp_mss = mss;
9137 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9138 }
9139 
9140 /* For /dev/tcp aka AF_INET open */
9141 static int
9142 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9143 {
9144 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9145 }
9146 
9147 /* For /dev/tcp6 aka AF_INET6 open */
9148 static int
9149 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9150 {
9151 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9152 }
9153 
9154 static conn_t *
9155 tcp_create_common(queue_t *q, cred_t *credp, boolean_t isv6,
9156     boolean_t issocket, int *errorp)
9157 {
9158 	tcp_t		*tcp = NULL;
9159 	conn_t		*connp;
9160 	int		err;
9161 	zoneid_t	zoneid;
9162 	tcp_stack_t	*tcps;
9163 	squeue_t	*sqp;
9164 
9165 	ASSERT(errorp != NULL);
9166 	/*
9167 	 * Find the proper zoneid and netstack.
9168 	 */
9169 	/*
9170 	 * Special case for install: miniroot needs to be able to
9171 	 * access files via NFS as though it were always in the
9172 	 * global zone.
9173 	 */
9174 	if (credp == kcred && nfs_global_client_only != 0) {
9175 		zoneid = GLOBAL_ZONEID;
9176 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9177 		    netstack_tcp;
9178 		ASSERT(tcps != NULL);
9179 	} else {
9180 		netstack_t *ns;
9181 
9182 		ns = netstack_find_by_cred(credp);
9183 		ASSERT(ns != NULL);
9184 		tcps = ns->netstack_tcp;
9185 		ASSERT(tcps != NULL);
9186 
9187 		/*
9188 		 * For exclusive stacks we set the zoneid to zero
9189 		 * to make TCP operate as if in the global zone.
9190 		 */
9191 		if (tcps->tcps_netstack->netstack_stackid !=
9192 		    GLOBAL_NETSTACKID)
9193 			zoneid = GLOBAL_ZONEID;
9194 		else
9195 			zoneid = crgetzoneid(credp);
9196 	}
9197 	/*
9198 	 * For stackid zero this is done from strplumb.c, but
9199 	 * non-zero stackids are handled here.
9200 	 */
9201 	if (tcps->tcps_g_q == NULL &&
9202 	    tcps->tcps_netstack->netstack_stackid !=
9203 	    GLOBAL_NETSTACKID) {
9204 		tcp_g_q_setup(tcps);
9205 	}
9206 
9207 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
9208 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
9209 	/*
9210 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9211 	 * so we drop it by one.
9212 	 */
9213 	netstack_rele(tcps->tcps_netstack);
9214 	if (connp == NULL) {
9215 		*errorp = ENOSR;
9216 		return (NULL);
9217 	}
9218 	connp->conn_sqp = sqp;
9219 	connp->conn_initial_sqp = connp->conn_sqp;
9220 	tcp = connp->conn_tcp;
9221 
9222 	if (isv6) {
9223 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9224 		connp->conn_send = ip_output_v6;
9225 		connp->conn_af_isv6 = B_TRUE;
9226 		connp->conn_pkt_isv6 = B_TRUE;
9227 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9228 		tcp->tcp_ipversion = IPV6_VERSION;
9229 		tcp->tcp_family = AF_INET6;
9230 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9231 	} else {
9232 		connp->conn_flags |= IPCL_TCP4;
9233 		connp->conn_send = ip_output;
9234 		connp->conn_af_isv6 = B_FALSE;
9235 		connp->conn_pkt_isv6 = B_FALSE;
9236 		tcp->tcp_ipversion = IPV4_VERSION;
9237 		tcp->tcp_family = AF_INET;
9238 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9239 	}
9240 
9241 	/*
9242 	 * TCP keeps a copy of cred for cache locality reasons but
9243 	 * we put a reference only once. If connp->conn_cred
9244 	 * becomes invalid, tcp_cred should also be set to NULL.
9245 	 */
9246 	tcp->tcp_cred = connp->conn_cred = credp;
9247 	crhold(connp->conn_cred);
9248 	tcp->tcp_cpid = curproc->p_pid;
9249 	tcp->tcp_open_time = lbolt64;
9250 	connp->conn_zoneid = zoneid;
9251 	connp->conn_mlp_type = mlptSingle;
9252 	connp->conn_ulp_labeled = !is_system_labeled();
9253 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9254 	ASSERT(tcp->tcp_tcps == tcps);
9255 
9256 	/*
9257 	 * If the caller has the process-wide flag set, then default to MAC
9258 	 * exempt mode.  This allows read-down to unlabeled hosts.
9259 	 */
9260 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9261 		connp->conn_mac_exempt = B_TRUE;
9262 
9263 	connp->conn_dev = NULL;
9264 	if (issocket) {
9265 		connp->conn_flags |= IPCL_SOCKET;
9266 		tcp->tcp_issocket = 1;
9267 	}
9268 
9269 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
9270 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9271 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
9272 
9273 	/* Non-zero default values */
9274 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9275 
9276 	if (q == NULL) {
9277 		/*
9278 		 * Create a helper stream for non-STREAMS socket.
9279 		 */
9280 		err = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
9281 		if (err != 0) {
9282 			ip1dbg(("tcp_create_common: create of IP helper stream "
9283 			    "failed\n"));
9284 			CONN_DEC_REF(connp);
9285 			*errorp = err;
9286 			return (NULL);
9287 		}
9288 		q = connp->conn_rq;
9289 	} else {
9290 		RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9291 	}
9292 
9293 	SOCK_CONNID_INIT(tcp->tcp_connid);
9294 	err = tcp_init(tcp, q);
9295 	if (err != 0) {
9296 		CONN_DEC_REF(connp);
9297 		*errorp = err;
9298 		return (NULL);
9299 	}
9300 
9301 	return (connp);
9302 }
9303 
9304 static int
9305 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9306     boolean_t isv6)
9307 {
9308 	tcp_t		*tcp = NULL;
9309 	conn_t		*connp = NULL;
9310 	int		err;
9311 	vmem_t		*minor_arena = NULL;
9312 	dev_t		conn_dev;
9313 	boolean_t	issocket;
9314 
9315 	if (q->q_ptr != NULL)
9316 		return (0);
9317 
9318 	if (sflag == MODOPEN)
9319 		return (EINVAL);
9320 
9321 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9322 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9323 		minor_arena = ip_minor_arena_la;
9324 	} else {
9325 		/*
9326 		 * Either minor numbers in the large arena were exhausted
9327 		 * or a non socket application is doing the open.
9328 		 * Try to allocate from the small arena.
9329 		 */
9330 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9331 			return (EBUSY);
9332 		}
9333 		minor_arena = ip_minor_arena_sa;
9334 	}
9335 
9336 	ASSERT(minor_arena != NULL);
9337 
9338 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
9339 
9340 	if (flag & SO_FALLBACK) {
9341 		/*
9342 		 * Non streams socket needs a stream to fallback to
9343 		 */
9344 		RD(q)->q_ptr = (void *)conn_dev;
9345 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
9346 		WR(q)->q_ptr = (void *)minor_arena;
9347 		qprocson(q);
9348 		return (0);
9349 	} else if (flag & SO_ACCEPTOR) {
9350 		q->q_qinfo = &tcp_acceptor_rinit;
9351 		/*
9352 		 * the conn_dev and minor_arena will be subsequently used by
9353 		 * tcp_wput_accept() and tcpclose_accept() to figure out the
9354 		 * minor device number for this connection from the q_ptr.
9355 		 */
9356 		RD(q)->q_ptr = (void *)conn_dev;
9357 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9358 		WR(q)->q_ptr = (void *)minor_arena;
9359 		qprocson(q);
9360 		return (0);
9361 	}
9362 
9363 	issocket = flag & SO_SOCKSTR;
9364 	connp = tcp_create_common(q, credp, isv6, issocket, &err);
9365 
9366 	if (connp == NULL) {
9367 		inet_minor_free(minor_arena, conn_dev);
9368 		q->q_ptr = WR(q)->q_ptr = NULL;
9369 		return (err);
9370 	}
9371 
9372 	q->q_ptr = WR(q)->q_ptr = connp;
9373 
9374 	connp->conn_dev = conn_dev;
9375 	connp->conn_minor_arena = minor_arena;
9376 
9377 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9378 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9379 
9380 	if (issocket) {
9381 		WR(q)->q_qinfo = &tcp_sock_winit;
9382 	} else {
9383 		tcp = connp->conn_tcp;
9384 #ifdef  _ILP32
9385 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9386 #else
9387 		tcp->tcp_acceptor_id = conn_dev;
9388 #endif  /* _ILP32 */
9389 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9390 	}
9391 
9392 	/*
9393 	 * Put the ref for TCP. Ref for IP was already put
9394 	 * by ipcl_conn_create. Also Make the conn_t globally
9395 	 * visible to walkers
9396 	 */
9397 	mutex_enter(&connp->conn_lock);
9398 	CONN_INC_REF_LOCKED(connp);
9399 	ASSERT(connp->conn_ref == 2);
9400 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9401 	mutex_exit(&connp->conn_lock);
9402 
9403 	qprocson(q);
9404 	return (0);
9405 }
9406 
9407 /*
9408  * Some TCP options can be "set" by requesting them in the option
9409  * buffer. This is needed for XTI feature test though we do not
9410  * allow it in general. We interpret that this mechanism is more
9411  * applicable to OSI protocols and need not be allowed in general.
9412  * This routine filters out options for which it is not allowed (most)
9413  * and lets through those (few) for which it is. [ The XTI interface
9414  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9415  * ever implemented will have to be allowed here ].
9416  */
9417 static boolean_t
9418 tcp_allow_connopt_set(int level, int name)
9419 {
9420 
9421 	switch (level) {
9422 	case IPPROTO_TCP:
9423 		switch (name) {
9424 		case TCP_NODELAY:
9425 			return (B_TRUE);
9426 		default:
9427 			return (B_FALSE);
9428 		}
9429 		/*NOTREACHED*/
9430 	default:
9431 		return (B_FALSE);
9432 	}
9433 	/*NOTREACHED*/
9434 }
9435 
9436 /*
9437  * this routine gets default values of certain options whose default
9438  * values are maintained by protocol specific code
9439  */
9440 /* ARGSUSED */
9441 int
9442 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9443 {
9444 	int32_t	*i1 = (int32_t *)ptr;
9445 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9446 
9447 	switch (level) {
9448 	case IPPROTO_TCP:
9449 		switch (name) {
9450 		case TCP_NOTIFY_THRESHOLD:
9451 			*i1 = tcps->tcps_ip_notify_interval;
9452 			break;
9453 		case TCP_ABORT_THRESHOLD:
9454 			*i1 = tcps->tcps_ip_abort_interval;
9455 			break;
9456 		case TCP_CONN_NOTIFY_THRESHOLD:
9457 			*i1 = tcps->tcps_ip_notify_cinterval;
9458 			break;
9459 		case TCP_CONN_ABORT_THRESHOLD:
9460 			*i1 = tcps->tcps_ip_abort_cinterval;
9461 			break;
9462 		default:
9463 			return (-1);
9464 		}
9465 		break;
9466 	case IPPROTO_IP:
9467 		switch (name) {
9468 		case IP_TTL:
9469 			*i1 = tcps->tcps_ipv4_ttl;
9470 			break;
9471 		default:
9472 			return (-1);
9473 		}
9474 		break;
9475 	case IPPROTO_IPV6:
9476 		switch (name) {
9477 		case IPV6_UNICAST_HOPS:
9478 			*i1 = tcps->tcps_ipv6_hoplimit;
9479 			break;
9480 		default:
9481 			return (-1);
9482 		}
9483 		break;
9484 	default:
9485 		return (-1);
9486 	}
9487 	return (sizeof (int));
9488 }
9489 
9490 static int
9491 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
9492 {
9493 	int		*i1 = (int *)ptr;
9494 	tcp_t		*tcp = connp->conn_tcp;
9495 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9496 
9497 	switch (level) {
9498 	case SOL_SOCKET:
9499 		switch (name) {
9500 		case SO_LINGER:	{
9501 			struct linger *lgr = (struct linger *)ptr;
9502 
9503 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9504 			lgr->l_linger = tcp->tcp_lingertime;
9505 			}
9506 			return (sizeof (struct linger));
9507 		case SO_DEBUG:
9508 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9509 			break;
9510 		case SO_KEEPALIVE:
9511 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9512 			break;
9513 		case SO_DONTROUTE:
9514 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9515 			break;
9516 		case SO_USELOOPBACK:
9517 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9518 			break;
9519 		case SO_BROADCAST:
9520 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9521 			break;
9522 		case SO_REUSEADDR:
9523 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9524 			break;
9525 		case SO_OOBINLINE:
9526 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9527 			break;
9528 		case SO_DGRAM_ERRIND:
9529 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9530 			break;
9531 		case SO_TYPE:
9532 			*i1 = SOCK_STREAM;
9533 			break;
9534 		case SO_SNDBUF:
9535 			*i1 = tcp->tcp_xmit_hiwater;
9536 			break;
9537 		case SO_RCVBUF:
9538 			*i1 = tcp->tcp_recv_hiwater;
9539 			break;
9540 		case SO_SND_COPYAVOID:
9541 			*i1 = tcp->tcp_snd_zcopy_on ?
9542 			    SO_SND_COPYAVOID : 0;
9543 			break;
9544 		case SO_ALLZONES:
9545 			*i1 = connp->conn_allzones ? 1 : 0;
9546 			break;
9547 		case SO_ANON_MLP:
9548 			*i1 = connp->conn_anon_mlp;
9549 			break;
9550 		case SO_MAC_EXEMPT:
9551 			*i1 = connp->conn_mac_exempt;
9552 			break;
9553 		case SO_EXCLBIND:
9554 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9555 			break;
9556 		case SO_PROTOTYPE:
9557 			*i1 = IPPROTO_TCP;
9558 			break;
9559 		case SO_DOMAIN:
9560 			*i1 = tcp->tcp_family;
9561 			break;
9562 		case SO_ACCEPTCONN:
9563 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
9564 		default:
9565 			return (-1);
9566 		}
9567 		break;
9568 	case IPPROTO_TCP:
9569 		switch (name) {
9570 		case TCP_NODELAY:
9571 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9572 			break;
9573 		case TCP_MAXSEG:
9574 			*i1 = tcp->tcp_mss;
9575 			break;
9576 		case TCP_NOTIFY_THRESHOLD:
9577 			*i1 = (int)tcp->tcp_first_timer_threshold;
9578 			break;
9579 		case TCP_ABORT_THRESHOLD:
9580 			*i1 = tcp->tcp_second_timer_threshold;
9581 			break;
9582 		case TCP_CONN_NOTIFY_THRESHOLD:
9583 			*i1 = tcp->tcp_first_ctimer_threshold;
9584 			break;
9585 		case TCP_CONN_ABORT_THRESHOLD:
9586 			*i1 = tcp->tcp_second_ctimer_threshold;
9587 			break;
9588 		case TCP_RECVDSTADDR:
9589 			*i1 = tcp->tcp_recvdstaddr;
9590 			break;
9591 		case TCP_ANONPRIVBIND:
9592 			*i1 = tcp->tcp_anon_priv_bind;
9593 			break;
9594 		case TCP_EXCLBIND:
9595 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9596 			break;
9597 		case TCP_INIT_CWND:
9598 			*i1 = tcp->tcp_init_cwnd;
9599 			break;
9600 		case TCP_KEEPALIVE_THRESHOLD:
9601 			*i1 = tcp->tcp_ka_interval;
9602 			break;
9603 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9604 			*i1 = tcp->tcp_ka_abort_thres;
9605 			break;
9606 		case TCP_CORK:
9607 			*i1 = tcp->tcp_cork;
9608 			break;
9609 		default:
9610 			return (-1);
9611 		}
9612 		break;
9613 	case IPPROTO_IP:
9614 		if (tcp->tcp_family != AF_INET)
9615 			return (-1);
9616 		switch (name) {
9617 		case IP_OPTIONS:
9618 		case T_IP_OPTIONS: {
9619 			/*
9620 			 * This is compatible with BSD in that in only return
9621 			 * the reverse source route with the final destination
9622 			 * as the last entry. The first 4 bytes of the option
9623 			 * will contain the final destination.
9624 			 */
9625 			int	opt_len;
9626 
9627 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9628 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9629 			ASSERT(opt_len >= 0);
9630 			/* Caller ensures enough space */
9631 			if (opt_len > 0) {
9632 				/*
9633 				 * TODO: Do we have to handle getsockopt on an
9634 				 * initiator as well?
9635 				 */
9636 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9637 			}
9638 			return (0);
9639 			}
9640 		case IP_TOS:
9641 		case T_IP_TOS:
9642 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9643 			break;
9644 		case IP_TTL:
9645 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9646 			break;
9647 		case IP_NEXTHOP:
9648 			/* Handled at IP level */
9649 			return (-EINVAL);
9650 		default:
9651 			return (-1);
9652 		}
9653 		break;
9654 	case IPPROTO_IPV6:
9655 		/*
9656 		 * IPPROTO_IPV6 options are only supported for sockets
9657 		 * that are using IPv6 on the wire.
9658 		 */
9659 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9660 			return (-1);
9661 		}
9662 		switch (name) {
9663 		case IPV6_UNICAST_HOPS:
9664 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9665 			break;	/* goto sizeof (int) option return */
9666 		case IPV6_BOUND_IF:
9667 			/* Zero if not set */
9668 			*i1 = tcp->tcp_bound_if;
9669 			break;	/* goto sizeof (int) option return */
9670 		case IPV6_RECVPKTINFO:
9671 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9672 				*i1 = 1;
9673 			else
9674 				*i1 = 0;
9675 			break;	/* goto sizeof (int) option return */
9676 		case IPV6_RECVTCLASS:
9677 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9678 				*i1 = 1;
9679 			else
9680 				*i1 = 0;
9681 			break;	/* goto sizeof (int) option return */
9682 		case IPV6_RECVHOPLIMIT:
9683 			if (tcp->tcp_ipv6_recvancillary &
9684 			    TCP_IPV6_RECVHOPLIMIT)
9685 				*i1 = 1;
9686 			else
9687 				*i1 = 0;
9688 			break;	/* goto sizeof (int) option return */
9689 		case IPV6_RECVHOPOPTS:
9690 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9691 				*i1 = 1;
9692 			else
9693 				*i1 = 0;
9694 			break;	/* goto sizeof (int) option return */
9695 		case IPV6_RECVDSTOPTS:
9696 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9697 				*i1 = 1;
9698 			else
9699 				*i1 = 0;
9700 			break;	/* goto sizeof (int) option return */
9701 		case _OLD_IPV6_RECVDSTOPTS:
9702 			if (tcp->tcp_ipv6_recvancillary &
9703 			    TCP_OLD_IPV6_RECVDSTOPTS)
9704 				*i1 = 1;
9705 			else
9706 				*i1 = 0;
9707 			break;	/* goto sizeof (int) option return */
9708 		case IPV6_RECVRTHDR:
9709 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9710 				*i1 = 1;
9711 			else
9712 				*i1 = 0;
9713 			break;	/* goto sizeof (int) option return */
9714 		case IPV6_RECVRTHDRDSTOPTS:
9715 			if (tcp->tcp_ipv6_recvancillary &
9716 			    TCP_IPV6_RECVRTDSTOPTS)
9717 				*i1 = 1;
9718 			else
9719 				*i1 = 0;
9720 			break;	/* goto sizeof (int) option return */
9721 		case IPV6_PKTINFO: {
9722 			/* XXX assumes that caller has room for max size! */
9723 			struct in6_pktinfo *pkti;
9724 
9725 			pkti = (struct in6_pktinfo *)ptr;
9726 			if (ipp->ipp_fields & IPPF_IFINDEX)
9727 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9728 			else
9729 				pkti->ipi6_ifindex = 0;
9730 			if (ipp->ipp_fields & IPPF_ADDR)
9731 				pkti->ipi6_addr = ipp->ipp_addr;
9732 			else
9733 				pkti->ipi6_addr = ipv6_all_zeros;
9734 			return (sizeof (struct in6_pktinfo));
9735 		}
9736 		case IPV6_TCLASS:
9737 			if (ipp->ipp_fields & IPPF_TCLASS)
9738 				*i1 = ipp->ipp_tclass;
9739 			else
9740 				*i1 = IPV6_FLOW_TCLASS(
9741 				    IPV6_DEFAULT_VERS_AND_FLOW);
9742 			break;	/* goto sizeof (int) option return */
9743 		case IPV6_NEXTHOP: {
9744 			sin6_t *sin6 = (sin6_t *)ptr;
9745 
9746 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9747 				return (0);
9748 			*sin6 = sin6_null;
9749 			sin6->sin6_family = AF_INET6;
9750 			sin6->sin6_addr = ipp->ipp_nexthop;
9751 			return (sizeof (sin6_t));
9752 		}
9753 		case IPV6_HOPOPTS:
9754 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9755 				return (0);
9756 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9757 				return (0);
9758 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9759 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9760 			if (tcp->tcp_label_len > 0) {
9761 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9762 				ptr[1] = (ipp->ipp_hopoptslen -
9763 				    tcp->tcp_label_len + 7) / 8 - 1;
9764 			}
9765 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9766 		case IPV6_RTHDRDSTOPTS:
9767 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9768 				return (0);
9769 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9770 			return (ipp->ipp_rtdstoptslen);
9771 		case IPV6_RTHDR:
9772 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9773 				return (0);
9774 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9775 			return (ipp->ipp_rthdrlen);
9776 		case IPV6_DSTOPTS:
9777 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9778 				return (0);
9779 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9780 			return (ipp->ipp_dstoptslen);
9781 		case IPV6_SRC_PREFERENCES:
9782 			return (ip6_get_src_preferences(connp,
9783 			    (uint32_t *)ptr));
9784 		case IPV6_PATHMTU: {
9785 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9786 
9787 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9788 				return (-1);
9789 
9790 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9791 			    connp->conn_fport, mtuinfo,
9792 			    connp->conn_netstack));
9793 		}
9794 		default:
9795 			return (-1);
9796 		}
9797 		break;
9798 	default:
9799 		return (-1);
9800 	}
9801 	return (sizeof (int));
9802 }
9803 
9804 /*
9805  * TCP routine to get the values of options.
9806  */
9807 int
9808 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
9809 {
9810 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
9811 }
9812 
9813 /* returns UNIX error, the optlen is a value-result arg */
9814 int
9815 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
9816     void *optvalp, socklen_t *optlen, cred_t *cr)
9817 {
9818 	conn_t		*connp = (conn_t *)proto_handle;
9819 	squeue_t	*sqp = connp->conn_sqp;
9820 	int		error;
9821 	t_uscalar_t	max_optbuf_len;
9822 	void		*optvalp_buf;
9823 	int		len;
9824 
9825 	ASSERT(connp->conn_upper_handle != NULL);
9826 
9827 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
9828 	    tcp_opt_obj.odb_opt_des_arr,
9829 	    tcp_opt_obj.odb_opt_arr_cnt,
9830 	    tcp_opt_obj.odb_topmost_tpiprovider,
9831 	    B_FALSE, B_TRUE, cr);
9832 	if (error != 0) {
9833 		if (error < 0) {
9834 			error = proto_tlitosyserr(-error);
9835 		}
9836 		return (error);
9837 	}
9838 
9839 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
9840 
9841 	error = squeue_synch_enter(sqp, connp, 0);
9842 	if (error == ENOMEM) {
9843 		return (ENOMEM);
9844 	}
9845 
9846 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
9847 	squeue_synch_exit(sqp, connp);
9848 
9849 	if (len < 0) {
9850 		/*
9851 		 * Pass on to IP
9852 		 */
9853 		kmem_free(optvalp_buf, max_optbuf_len);
9854 		return (ip_get_options(connp, level, option_name,
9855 		    optvalp, optlen, cr));
9856 	} else {
9857 		/*
9858 		 * update optlen and copy option value
9859 		 */
9860 		t_uscalar_t size = MIN(len, *optlen);
9861 		bcopy(optvalp_buf, optvalp, size);
9862 		bcopy(&size, optlen, sizeof (size));
9863 
9864 		kmem_free(optvalp_buf, max_optbuf_len);
9865 		return (0);
9866 	}
9867 }
9868 
9869 /*
9870  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9871  * Parameters are assumed to be verified by the caller.
9872  */
9873 /* ARGSUSED */
9874 int
9875 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
9876     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9877     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9878 {
9879 	tcp_t	*tcp = connp->conn_tcp;
9880 	int	*i1 = (int *)invalp;
9881 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9882 	boolean_t checkonly;
9883 	int	reterr;
9884 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9885 
9886 	switch (optset_context) {
9887 	case SETFN_OPTCOM_CHECKONLY:
9888 		checkonly = B_TRUE;
9889 		/*
9890 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9891 		 * inlen != 0 implies value supplied and
9892 		 * 	we have to "pretend" to set it.
9893 		 * inlen == 0 implies that there is no
9894 		 * 	value part in T_CHECK request and just validation
9895 		 * done elsewhere should be enough, we just return here.
9896 		 */
9897 		if (inlen == 0) {
9898 			*outlenp = 0;
9899 			return (0);
9900 		}
9901 		break;
9902 	case SETFN_OPTCOM_NEGOTIATE:
9903 		checkonly = B_FALSE;
9904 		break;
9905 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9906 	case SETFN_CONN_NEGOTIATE:
9907 		checkonly = B_FALSE;
9908 		/*
9909 		 * Negotiating local and "association-related" options
9910 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9911 		 * primitives is allowed by XTI, but we choose
9912 		 * to not implement this style negotiation for Internet
9913 		 * protocols (We interpret it is a must for OSI world but
9914 		 * optional for Internet protocols) for all options.
9915 		 * [ Will do only for the few options that enable test
9916 		 * suites that our XTI implementation of this feature
9917 		 * works for transports that do allow it ]
9918 		 */
9919 		if (!tcp_allow_connopt_set(level, name)) {
9920 			*outlenp = 0;
9921 			return (EINVAL);
9922 		}
9923 		break;
9924 	default:
9925 		/*
9926 		 * We should never get here
9927 		 */
9928 		*outlenp = 0;
9929 		return (EINVAL);
9930 	}
9931 
9932 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9933 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9934 
9935 	/*
9936 	 * For TCP, we should have no ancillary data sent down
9937 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9938 	 * has to be zero.
9939 	 */
9940 	ASSERT(thisdg_attrs == NULL);
9941 
9942 	/*
9943 	 * For fixed length options, no sanity check
9944 	 * of passed in length is done. It is assumed *_optcom_req()
9945 	 * routines do the right thing.
9946 	 */
9947 	switch (level) {
9948 	case SOL_SOCKET:
9949 		switch (name) {
9950 		case SO_LINGER: {
9951 			struct linger *lgr = (struct linger *)invalp;
9952 
9953 			if (!checkonly) {
9954 				if (lgr->l_onoff) {
9955 					tcp->tcp_linger = 1;
9956 					tcp->tcp_lingertime = lgr->l_linger;
9957 				} else {
9958 					tcp->tcp_linger = 0;
9959 					tcp->tcp_lingertime = 0;
9960 				}
9961 				/* struct copy */
9962 				*(struct linger *)outvalp = *lgr;
9963 			} else {
9964 				if (!lgr->l_onoff) {
9965 					((struct linger *)
9966 					    outvalp)->l_onoff = 0;
9967 					((struct linger *)
9968 					    outvalp)->l_linger = 0;
9969 				} else {
9970 					/* struct copy */
9971 					*(struct linger *)outvalp = *lgr;
9972 				}
9973 			}
9974 			*outlenp = sizeof (struct linger);
9975 			return (0);
9976 		}
9977 		case SO_DEBUG:
9978 			if (!checkonly)
9979 				tcp->tcp_debug = onoff;
9980 			break;
9981 		case SO_KEEPALIVE:
9982 			if (checkonly) {
9983 				/* check only case */
9984 				break;
9985 			}
9986 
9987 			if (!onoff) {
9988 				if (tcp->tcp_ka_enabled) {
9989 					if (tcp->tcp_ka_tid != 0) {
9990 						(void) TCP_TIMER_CANCEL(tcp,
9991 						    tcp->tcp_ka_tid);
9992 						tcp->tcp_ka_tid = 0;
9993 					}
9994 					tcp->tcp_ka_enabled = 0;
9995 				}
9996 				break;
9997 			}
9998 			if (!tcp->tcp_ka_enabled) {
9999 				/* Crank up the keepalive timer */
10000 				tcp->tcp_ka_last_intrvl = 0;
10001 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10002 				    tcp_keepalive_killer,
10003 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10004 				tcp->tcp_ka_enabled = 1;
10005 			}
10006 			break;
10007 		case SO_DONTROUTE:
10008 			/*
10009 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10010 			 * only of interest to IP.  We track them here only so
10011 			 * that we can report their current value.
10012 			 */
10013 			if (!checkonly) {
10014 				tcp->tcp_dontroute = onoff;
10015 				tcp->tcp_connp->conn_dontroute = onoff;
10016 			}
10017 			break;
10018 		case SO_USELOOPBACK:
10019 			if (!checkonly) {
10020 				tcp->tcp_useloopback = onoff;
10021 				tcp->tcp_connp->conn_loopback = onoff;
10022 			}
10023 			break;
10024 		case SO_BROADCAST:
10025 			if (!checkonly) {
10026 				tcp->tcp_broadcast = onoff;
10027 				tcp->tcp_connp->conn_broadcast = onoff;
10028 			}
10029 			break;
10030 		case SO_REUSEADDR:
10031 			if (!checkonly) {
10032 				tcp->tcp_reuseaddr = onoff;
10033 				tcp->tcp_connp->conn_reuseaddr = onoff;
10034 			}
10035 			break;
10036 		case SO_OOBINLINE:
10037 			if (!checkonly) {
10038 				tcp->tcp_oobinline = onoff;
10039 				if (IPCL_IS_NONSTR(tcp->tcp_connp))
10040 					proto_set_rx_oob_opt(connp, onoff);
10041 			}
10042 			break;
10043 		case SO_DGRAM_ERRIND:
10044 			if (!checkonly)
10045 				tcp->tcp_dgram_errind = onoff;
10046 			break;
10047 		case SO_SNDBUF: {
10048 			if (*i1 > tcps->tcps_max_buf) {
10049 				*outlenp = 0;
10050 				return (ENOBUFS);
10051 			}
10052 			if (checkonly)
10053 				break;
10054 
10055 			tcp->tcp_xmit_hiwater = *i1;
10056 			if (tcps->tcps_snd_lowat_fraction != 0)
10057 				tcp->tcp_xmit_lowater =
10058 				    tcp->tcp_xmit_hiwater /
10059 				    tcps->tcps_snd_lowat_fraction;
10060 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10061 			/*
10062 			 * If we are flow-controlled, recheck the condition.
10063 			 * There are apps that increase SO_SNDBUF size when
10064 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10065 			 * control condition to be lifted right away.
10066 			 */
10067 			mutex_enter(&tcp->tcp_non_sq_lock);
10068 			if (tcp->tcp_flow_stopped &&
10069 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10070 				tcp_clrqfull(tcp);
10071 			}
10072 			mutex_exit(&tcp->tcp_non_sq_lock);
10073 			break;
10074 		}
10075 		case SO_RCVBUF:
10076 			if (*i1 > tcps->tcps_max_buf) {
10077 				*outlenp = 0;
10078 				return (ENOBUFS);
10079 			}
10080 			/* Silently ignore zero */
10081 			if (!checkonly && *i1 != 0) {
10082 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10083 				(void) tcp_rwnd_set(tcp, *i1);
10084 			}
10085 			/*
10086 			 * XXX should we return the rwnd here
10087 			 * and tcp_opt_get ?
10088 			 */
10089 			break;
10090 		case SO_SND_COPYAVOID:
10091 			if (!checkonly) {
10092 				/* we only allow enable at most once for now */
10093 				if (tcp->tcp_loopback ||
10094 				    (tcp->tcp_kssl_ctx != NULL) ||
10095 				    (!tcp->tcp_snd_zcopy_aware &&
10096 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10097 					*outlenp = 0;
10098 					return (EOPNOTSUPP);
10099 				}
10100 				tcp->tcp_snd_zcopy_aware = 1;
10101 			}
10102 			break;
10103 		case SO_RCVTIMEO:
10104 		case SO_SNDTIMEO:
10105 			/*
10106 			 * Pass these two options in order for third part
10107 			 * protocol usage. Here just return directly.
10108 			 */
10109 			return (0);
10110 		case SO_ALLZONES:
10111 			/* Pass option along to IP level for handling */
10112 			return (-EINVAL);
10113 		case SO_ANON_MLP:
10114 			/* Pass option along to IP level for handling */
10115 			return (-EINVAL);
10116 		case SO_MAC_EXEMPT:
10117 			/* Pass option along to IP level for handling */
10118 			return (-EINVAL);
10119 		case SO_EXCLBIND:
10120 			if (!checkonly)
10121 				tcp->tcp_exclbind = onoff;
10122 			break;
10123 		default:
10124 			*outlenp = 0;
10125 			return (EINVAL);
10126 		}
10127 		break;
10128 	case IPPROTO_TCP:
10129 		switch (name) {
10130 		case TCP_NODELAY:
10131 			if (!checkonly)
10132 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10133 			break;
10134 		case TCP_NOTIFY_THRESHOLD:
10135 			if (!checkonly)
10136 				tcp->tcp_first_timer_threshold = *i1;
10137 			break;
10138 		case TCP_ABORT_THRESHOLD:
10139 			if (!checkonly)
10140 				tcp->tcp_second_timer_threshold = *i1;
10141 			break;
10142 		case TCP_CONN_NOTIFY_THRESHOLD:
10143 			if (!checkonly)
10144 				tcp->tcp_first_ctimer_threshold = *i1;
10145 			break;
10146 		case TCP_CONN_ABORT_THRESHOLD:
10147 			if (!checkonly)
10148 				tcp->tcp_second_ctimer_threshold = *i1;
10149 			break;
10150 		case TCP_RECVDSTADDR:
10151 			if (tcp->tcp_state > TCPS_LISTEN)
10152 				return (EOPNOTSUPP);
10153 			if (!checkonly)
10154 				tcp->tcp_recvdstaddr = onoff;
10155 			break;
10156 		case TCP_ANONPRIVBIND:
10157 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10158 			    IPPROTO_TCP)) != 0) {
10159 				*outlenp = 0;
10160 				return (reterr);
10161 			}
10162 			if (!checkonly) {
10163 				tcp->tcp_anon_priv_bind = onoff;
10164 			}
10165 			break;
10166 		case TCP_EXCLBIND:
10167 			if (!checkonly)
10168 				tcp->tcp_exclbind = onoff;
10169 			break;	/* goto sizeof (int) option return */
10170 		case TCP_INIT_CWND: {
10171 			uint32_t init_cwnd = *((uint32_t *)invalp);
10172 
10173 			if (checkonly)
10174 				break;
10175 
10176 			/*
10177 			 * Only allow socket with network configuration
10178 			 * privilege to set the initial cwnd to be larger
10179 			 * than allowed by RFC 3390.
10180 			 */
10181 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10182 				tcp->tcp_init_cwnd = init_cwnd;
10183 				break;
10184 			}
10185 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10186 				*outlenp = 0;
10187 				return (reterr);
10188 			}
10189 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10190 				*outlenp = 0;
10191 				return (EINVAL);
10192 			}
10193 			tcp->tcp_init_cwnd = init_cwnd;
10194 			break;
10195 		}
10196 		case TCP_KEEPALIVE_THRESHOLD:
10197 			if (checkonly)
10198 				break;
10199 
10200 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10201 			    *i1 > tcps->tcps_keepalive_interval_high) {
10202 				*outlenp = 0;
10203 				return (EINVAL);
10204 			}
10205 			if (*i1 != tcp->tcp_ka_interval) {
10206 				tcp->tcp_ka_interval = *i1;
10207 				/*
10208 				 * Check if we need to restart the
10209 				 * keepalive timer.
10210 				 */
10211 				if (tcp->tcp_ka_tid != 0) {
10212 					ASSERT(tcp->tcp_ka_enabled);
10213 					(void) TCP_TIMER_CANCEL(tcp,
10214 					    tcp->tcp_ka_tid);
10215 					tcp->tcp_ka_last_intrvl = 0;
10216 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10217 					    tcp_keepalive_killer,
10218 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10219 				}
10220 			}
10221 			break;
10222 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10223 			if (!checkonly) {
10224 				if (*i1 <
10225 				    tcps->tcps_keepalive_abort_interval_low ||
10226 				    *i1 >
10227 				    tcps->tcps_keepalive_abort_interval_high) {
10228 					*outlenp = 0;
10229 					return (EINVAL);
10230 				}
10231 				tcp->tcp_ka_abort_thres = *i1;
10232 			}
10233 			break;
10234 		case TCP_CORK:
10235 			if (!checkonly) {
10236 				/*
10237 				 * if tcp->tcp_cork was set and is now
10238 				 * being unset, we have to make sure that
10239 				 * the remaining data gets sent out. Also
10240 				 * unset tcp->tcp_cork so that tcp_wput_data()
10241 				 * can send data even if it is less than mss
10242 				 */
10243 				if (tcp->tcp_cork && onoff == 0 &&
10244 				    tcp->tcp_unsent > 0) {
10245 					tcp->tcp_cork = B_FALSE;
10246 					tcp_wput_data(tcp, NULL, B_FALSE);
10247 				}
10248 				tcp->tcp_cork = onoff;
10249 			}
10250 			break;
10251 		default:
10252 			*outlenp = 0;
10253 			return (EINVAL);
10254 		}
10255 		break;
10256 	case IPPROTO_IP:
10257 		if (tcp->tcp_family != AF_INET) {
10258 			*outlenp = 0;
10259 			return (ENOPROTOOPT);
10260 		}
10261 		switch (name) {
10262 		case IP_OPTIONS:
10263 		case T_IP_OPTIONS:
10264 			reterr = tcp_opt_set_header(tcp, checkonly,
10265 			    invalp, inlen);
10266 			if (reterr) {
10267 				*outlenp = 0;
10268 				return (reterr);
10269 			}
10270 			/* OK return - copy input buffer into output buffer */
10271 			if (invalp != outvalp) {
10272 				/* don't trust bcopy for identical src/dst */
10273 				bcopy(invalp, outvalp, inlen);
10274 			}
10275 			*outlenp = inlen;
10276 			return (0);
10277 		case IP_TOS:
10278 		case T_IP_TOS:
10279 			if (!checkonly) {
10280 				tcp->tcp_ipha->ipha_type_of_service =
10281 				    (uchar_t)*i1;
10282 				tcp->tcp_tos = (uchar_t)*i1;
10283 			}
10284 			break;
10285 		case IP_TTL:
10286 			if (!checkonly) {
10287 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10288 				tcp->tcp_ttl = (uchar_t)*i1;
10289 			}
10290 			break;
10291 		case IP_BOUND_IF:
10292 		case IP_NEXTHOP:
10293 			/* Handled at the IP level */
10294 			return (-EINVAL);
10295 		case IP_SEC_OPT:
10296 			/*
10297 			 * We should not allow policy setting after
10298 			 * we start listening for connections.
10299 			 */
10300 			if (tcp->tcp_state == TCPS_LISTEN) {
10301 				return (EINVAL);
10302 			} else {
10303 				/* Handled at the IP level */
10304 				return (-EINVAL);
10305 			}
10306 		default:
10307 			*outlenp = 0;
10308 			return (EINVAL);
10309 		}
10310 		break;
10311 	case IPPROTO_IPV6: {
10312 		ip6_pkt_t		*ipp;
10313 
10314 		/*
10315 		 * IPPROTO_IPV6 options are only supported for sockets
10316 		 * that are using IPv6 on the wire.
10317 		 */
10318 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10319 			*outlenp = 0;
10320 			return (ENOPROTOOPT);
10321 		}
10322 		/*
10323 		 * Only sticky options; no ancillary data
10324 		 */
10325 		ipp = &tcp->tcp_sticky_ipp;
10326 
10327 		switch (name) {
10328 		case IPV6_UNICAST_HOPS:
10329 			/* -1 means use default */
10330 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10331 				*outlenp = 0;
10332 				return (EINVAL);
10333 			}
10334 			if (!checkonly) {
10335 				if (*i1 == -1) {
10336 					tcp->tcp_ip6h->ip6_hops =
10337 					    ipp->ipp_unicast_hops =
10338 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10339 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10340 					/* Pass modified value to IP. */
10341 					*i1 = tcp->tcp_ip6h->ip6_hops;
10342 				} else {
10343 					tcp->tcp_ip6h->ip6_hops =
10344 					    ipp->ipp_unicast_hops =
10345 					    (uint8_t)*i1;
10346 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10347 				}
10348 				reterr = tcp_build_hdrs(tcp);
10349 				if (reterr != 0)
10350 					return (reterr);
10351 			}
10352 			break;
10353 		case IPV6_BOUND_IF:
10354 			if (!checkonly) {
10355 				tcp->tcp_bound_if = *i1;
10356 				PASS_OPT_TO_IP(connp);
10357 			}
10358 			break;
10359 		/*
10360 		 * Set boolean switches for ancillary data delivery
10361 		 */
10362 		case IPV6_RECVPKTINFO:
10363 			if (!checkonly) {
10364 				if (onoff)
10365 					tcp->tcp_ipv6_recvancillary |=
10366 					    TCP_IPV6_RECVPKTINFO;
10367 				else
10368 					tcp->tcp_ipv6_recvancillary &=
10369 					    ~TCP_IPV6_RECVPKTINFO;
10370 				/* Force it to be sent up with the next msg */
10371 				tcp->tcp_recvifindex = 0;
10372 				PASS_OPT_TO_IP(connp);
10373 			}
10374 			break;
10375 		case IPV6_RECVTCLASS:
10376 			if (!checkonly) {
10377 				if (onoff)
10378 					tcp->tcp_ipv6_recvancillary |=
10379 					    TCP_IPV6_RECVTCLASS;
10380 				else
10381 					tcp->tcp_ipv6_recvancillary &=
10382 					    ~TCP_IPV6_RECVTCLASS;
10383 				PASS_OPT_TO_IP(connp);
10384 			}
10385 			break;
10386 		case IPV6_RECVHOPLIMIT:
10387 			if (!checkonly) {
10388 				if (onoff)
10389 					tcp->tcp_ipv6_recvancillary |=
10390 					    TCP_IPV6_RECVHOPLIMIT;
10391 				else
10392 					tcp->tcp_ipv6_recvancillary &=
10393 					    ~TCP_IPV6_RECVHOPLIMIT;
10394 				/* Force it to be sent up with the next msg */
10395 				tcp->tcp_recvhops = 0xffffffffU;
10396 				PASS_OPT_TO_IP(connp);
10397 			}
10398 			break;
10399 		case IPV6_RECVHOPOPTS:
10400 			if (!checkonly) {
10401 				if (onoff)
10402 					tcp->tcp_ipv6_recvancillary |=
10403 					    TCP_IPV6_RECVHOPOPTS;
10404 				else
10405 					tcp->tcp_ipv6_recvancillary &=
10406 					    ~TCP_IPV6_RECVHOPOPTS;
10407 				PASS_OPT_TO_IP(connp);
10408 			}
10409 			break;
10410 		case IPV6_RECVDSTOPTS:
10411 			if (!checkonly) {
10412 				if (onoff)
10413 					tcp->tcp_ipv6_recvancillary |=
10414 					    TCP_IPV6_RECVDSTOPTS;
10415 				else
10416 					tcp->tcp_ipv6_recvancillary &=
10417 					    ~TCP_IPV6_RECVDSTOPTS;
10418 				PASS_OPT_TO_IP(connp);
10419 			}
10420 			break;
10421 		case _OLD_IPV6_RECVDSTOPTS:
10422 			if (!checkonly) {
10423 				if (onoff)
10424 					tcp->tcp_ipv6_recvancillary |=
10425 					    TCP_OLD_IPV6_RECVDSTOPTS;
10426 				else
10427 					tcp->tcp_ipv6_recvancillary &=
10428 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10429 			}
10430 			break;
10431 		case IPV6_RECVRTHDR:
10432 			if (!checkonly) {
10433 				if (onoff)
10434 					tcp->tcp_ipv6_recvancillary |=
10435 					    TCP_IPV6_RECVRTHDR;
10436 				else
10437 					tcp->tcp_ipv6_recvancillary &=
10438 					    ~TCP_IPV6_RECVRTHDR;
10439 				PASS_OPT_TO_IP(connp);
10440 			}
10441 			break;
10442 		case IPV6_RECVRTHDRDSTOPTS:
10443 			if (!checkonly) {
10444 				if (onoff)
10445 					tcp->tcp_ipv6_recvancillary |=
10446 					    TCP_IPV6_RECVRTDSTOPTS;
10447 				else
10448 					tcp->tcp_ipv6_recvancillary &=
10449 					    ~TCP_IPV6_RECVRTDSTOPTS;
10450 				PASS_OPT_TO_IP(connp);
10451 			}
10452 			break;
10453 		case IPV6_PKTINFO:
10454 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10455 				return (EINVAL);
10456 			if (checkonly)
10457 				break;
10458 
10459 			if (inlen == 0) {
10460 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10461 			} else {
10462 				struct in6_pktinfo *pkti;
10463 
10464 				pkti = (struct in6_pktinfo *)invalp;
10465 				/*
10466 				 * RFC 3542 states that ipi6_addr must be
10467 				 * the unspecified address when setting the
10468 				 * IPV6_PKTINFO sticky socket option on a
10469 				 * TCP socket.
10470 				 */
10471 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10472 					return (EINVAL);
10473 				/*
10474 				 * IP will validate the source address and
10475 				 * interface index.
10476 				 */
10477 				if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
10478 					reterr = ip_set_options(tcp->tcp_connp,
10479 					    level, name, invalp, inlen, cr);
10480 				} else {
10481 					reterr = ip6_set_pktinfo(cr,
10482 					    tcp->tcp_connp, pkti);
10483 				}
10484 				if (reterr != 0)
10485 					return (reterr);
10486 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10487 				ipp->ipp_addr = pkti->ipi6_addr;
10488 				if (ipp->ipp_ifindex != 0)
10489 					ipp->ipp_fields |= IPPF_IFINDEX;
10490 				else
10491 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10492 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10493 					ipp->ipp_fields |= IPPF_ADDR;
10494 				else
10495 					ipp->ipp_fields &= ~IPPF_ADDR;
10496 			}
10497 			reterr = tcp_build_hdrs(tcp);
10498 			if (reterr != 0)
10499 				return (reterr);
10500 			break;
10501 		case IPV6_TCLASS:
10502 			if (inlen != 0 && inlen != sizeof (int))
10503 				return (EINVAL);
10504 			if (checkonly)
10505 				break;
10506 
10507 			if (inlen == 0) {
10508 				ipp->ipp_fields &= ~IPPF_TCLASS;
10509 			} else {
10510 				if (*i1 > 255 || *i1 < -1)
10511 					return (EINVAL);
10512 				if (*i1 == -1) {
10513 					ipp->ipp_tclass = 0;
10514 					*i1 = 0;
10515 				} else {
10516 					ipp->ipp_tclass = *i1;
10517 				}
10518 				ipp->ipp_fields |= IPPF_TCLASS;
10519 			}
10520 			reterr = tcp_build_hdrs(tcp);
10521 			if (reterr != 0)
10522 				return (reterr);
10523 			break;
10524 		case IPV6_NEXTHOP:
10525 			/*
10526 			 * IP will verify that the nexthop is reachable
10527 			 * and fail for sticky options.
10528 			 */
10529 			if (inlen != 0 && inlen != sizeof (sin6_t))
10530 				return (EINVAL);
10531 			if (checkonly)
10532 				break;
10533 
10534 			if (inlen == 0) {
10535 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10536 			} else {
10537 				sin6_t *sin6 = (sin6_t *)invalp;
10538 
10539 				if (sin6->sin6_family != AF_INET6)
10540 					return (EAFNOSUPPORT);
10541 				if (IN6_IS_ADDR_V4MAPPED(
10542 				    &sin6->sin6_addr))
10543 					return (EADDRNOTAVAIL);
10544 				ipp->ipp_nexthop = sin6->sin6_addr;
10545 				if (!IN6_IS_ADDR_UNSPECIFIED(
10546 				    &ipp->ipp_nexthop))
10547 					ipp->ipp_fields |= IPPF_NEXTHOP;
10548 				else
10549 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10550 			}
10551 			reterr = tcp_build_hdrs(tcp);
10552 			if (reterr != 0)
10553 				return (reterr);
10554 			PASS_OPT_TO_IP(connp);
10555 			break;
10556 		case IPV6_HOPOPTS: {
10557 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10558 
10559 			/*
10560 			 * Sanity checks - minimum size, size a multiple of
10561 			 * eight bytes, and matching size passed in.
10562 			 */
10563 			if (inlen != 0 &&
10564 			    inlen != (8 * (hopts->ip6h_len + 1)))
10565 				return (EINVAL);
10566 
10567 			if (checkonly)
10568 				break;
10569 
10570 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10571 			    (uchar_t **)&ipp->ipp_hopopts,
10572 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10573 			if (reterr != 0)
10574 				return (reterr);
10575 			if (ipp->ipp_hopoptslen == 0)
10576 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10577 			else
10578 				ipp->ipp_fields |= IPPF_HOPOPTS;
10579 			reterr = tcp_build_hdrs(tcp);
10580 			if (reterr != 0)
10581 				return (reterr);
10582 			break;
10583 		}
10584 		case IPV6_RTHDRDSTOPTS: {
10585 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10586 
10587 			/*
10588 			 * Sanity checks - minimum size, size a multiple of
10589 			 * eight bytes, and matching size passed in.
10590 			 */
10591 			if (inlen != 0 &&
10592 			    inlen != (8 * (dopts->ip6d_len + 1)))
10593 				return (EINVAL);
10594 
10595 			if (checkonly)
10596 				break;
10597 
10598 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10599 			    (uchar_t **)&ipp->ipp_rtdstopts,
10600 			    &ipp->ipp_rtdstoptslen, 0);
10601 			if (reterr != 0)
10602 				return (reterr);
10603 			if (ipp->ipp_rtdstoptslen == 0)
10604 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10605 			else
10606 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10607 			reterr = tcp_build_hdrs(tcp);
10608 			if (reterr != 0)
10609 				return (reterr);
10610 			break;
10611 		}
10612 		case IPV6_DSTOPTS: {
10613 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10614 
10615 			/*
10616 			 * Sanity checks - minimum size, size a multiple of
10617 			 * eight bytes, and matching size passed in.
10618 			 */
10619 			if (inlen != 0 &&
10620 			    inlen != (8 * (dopts->ip6d_len + 1)))
10621 				return (EINVAL);
10622 
10623 			if (checkonly)
10624 				break;
10625 
10626 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10627 			    (uchar_t **)&ipp->ipp_dstopts,
10628 			    &ipp->ipp_dstoptslen, 0);
10629 			if (reterr != 0)
10630 				return (reterr);
10631 			if (ipp->ipp_dstoptslen == 0)
10632 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10633 			else
10634 				ipp->ipp_fields |= IPPF_DSTOPTS;
10635 			reterr = tcp_build_hdrs(tcp);
10636 			if (reterr != 0)
10637 				return (reterr);
10638 			break;
10639 		}
10640 		case IPV6_RTHDR: {
10641 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10642 
10643 			/*
10644 			 * Sanity checks - minimum size, size a multiple of
10645 			 * eight bytes, and matching size passed in.
10646 			 */
10647 			if (inlen != 0 &&
10648 			    inlen != (8 * (rt->ip6r_len + 1)))
10649 				return (EINVAL);
10650 
10651 			if (checkonly)
10652 				break;
10653 
10654 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10655 			    (uchar_t **)&ipp->ipp_rthdr,
10656 			    &ipp->ipp_rthdrlen, 0);
10657 			if (reterr != 0)
10658 				return (reterr);
10659 			if (ipp->ipp_rthdrlen == 0)
10660 				ipp->ipp_fields &= ~IPPF_RTHDR;
10661 			else
10662 				ipp->ipp_fields |= IPPF_RTHDR;
10663 			reterr = tcp_build_hdrs(tcp);
10664 			if (reterr != 0)
10665 				return (reterr);
10666 			break;
10667 		}
10668 		case IPV6_V6ONLY:
10669 			if (!checkonly) {
10670 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10671 			}
10672 			break;
10673 		case IPV6_USE_MIN_MTU:
10674 			if (inlen != sizeof (int))
10675 				return (EINVAL);
10676 
10677 			if (*i1 < -1 || *i1 > 1)
10678 				return (EINVAL);
10679 
10680 			if (checkonly)
10681 				break;
10682 
10683 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10684 			ipp->ipp_use_min_mtu = *i1;
10685 			break;
10686 		case IPV6_SEC_OPT:
10687 			/*
10688 			 * We should not allow policy setting after
10689 			 * we start listening for connections.
10690 			 */
10691 			if (tcp->tcp_state == TCPS_LISTEN) {
10692 				return (EINVAL);
10693 			} else {
10694 				/* Handled at the IP level */
10695 				return (-EINVAL);
10696 			}
10697 		case IPV6_SRC_PREFERENCES:
10698 			if (inlen != sizeof (uint32_t))
10699 				return (EINVAL);
10700 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10701 			    *(uint32_t *)invalp);
10702 			if (reterr != 0) {
10703 				*outlenp = 0;
10704 				return (reterr);
10705 			}
10706 			break;
10707 		default:
10708 			*outlenp = 0;
10709 			return (EINVAL);
10710 		}
10711 		break;
10712 	}		/* end IPPROTO_IPV6 */
10713 	default:
10714 		*outlenp = 0;
10715 		return (EINVAL);
10716 	}
10717 	/*
10718 	 * Common case of OK return with outval same as inval
10719 	 */
10720 	if (invalp != outvalp) {
10721 		/* don't trust bcopy for identical src/dst */
10722 		(void) bcopy(invalp, outvalp, inlen);
10723 	}
10724 	*outlenp = inlen;
10725 	return (0);
10726 }
10727 
10728 /* ARGSUSED */
10729 int
10730 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10731     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10732     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10733 {
10734 	conn_t	*connp =  Q_TO_CONN(q);
10735 
10736 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
10737 	    outlenp, outvalp, thisdg_attrs, cr, mblk));
10738 }
10739 
10740 int
10741 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
10742     const void *optvalp, socklen_t optlen, cred_t *cr)
10743 {
10744 	conn_t		*connp = (conn_t *)proto_handle;
10745 	squeue_t	*sqp = connp->conn_sqp;
10746 	int		error;
10747 
10748 	ASSERT(connp->conn_upper_handle != NULL);
10749 	/*
10750 	 * Entering the squeue synchronously can result in a context switch,
10751 	 * which can cause a rather sever performance degradation. So we try to
10752 	 * handle whatever options we can without entering the squeue.
10753 	 */
10754 	if (level == IPPROTO_TCP) {
10755 		switch (option_name) {
10756 		case TCP_NODELAY:
10757 			if (optlen != sizeof (int32_t))
10758 				return (EINVAL);
10759 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
10760 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
10761 			    connp->conn_tcp->tcp_mss;
10762 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
10763 			return (0);
10764 		default:
10765 			break;
10766 		}
10767 	}
10768 
10769 	error = squeue_synch_enter(sqp, connp, 0);
10770 	if (error == ENOMEM) {
10771 		return (ENOMEM);
10772 	}
10773 
10774 	error = proto_opt_check(level, option_name, optlen, NULL,
10775 	    tcp_opt_obj.odb_opt_des_arr,
10776 	    tcp_opt_obj.odb_opt_arr_cnt,
10777 	    tcp_opt_obj.odb_topmost_tpiprovider,
10778 	    B_TRUE, B_FALSE, cr);
10779 
10780 	if (error != 0) {
10781 		if (error < 0) {
10782 			error = proto_tlitosyserr(-error);
10783 		}
10784 		squeue_synch_exit(sqp, connp);
10785 		return (error);
10786 	}
10787 
10788 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
10789 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
10790 	    NULL, cr, NULL);
10791 	squeue_synch_exit(sqp, connp);
10792 
10793 	if (error < 0) {
10794 		/*
10795 		 * Pass on to ip
10796 		 */
10797 		error = ip_set_options(connp, level, option_name, optvalp,
10798 		    optlen, cr);
10799 	}
10800 	return (error);
10801 }
10802 
10803 /*
10804  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10805  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10806  * headers, and the maximum size tcp header (to avoid reallocation
10807  * on the fly for additional tcp options).
10808  * Returns failure if can't allocate memory.
10809  */
10810 static int
10811 tcp_build_hdrs(tcp_t *tcp)
10812 {
10813 	char	*hdrs;
10814 	uint_t	hdrs_len;
10815 	ip6i_t	*ip6i;
10816 	char	buf[TCP_MAX_HDR_LENGTH];
10817 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10818 	in6_addr_t src, dst;
10819 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10820 	conn_t *connp = tcp->tcp_connp;
10821 
10822 	/*
10823 	 * save the existing tcp header and source/dest IP addresses
10824 	 */
10825 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10826 	src = tcp->tcp_ip6h->ip6_src;
10827 	dst = tcp->tcp_ip6h->ip6_dst;
10828 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10829 	ASSERT(hdrs_len != 0);
10830 	if (hdrs_len > tcp->tcp_iphc_len) {
10831 		/* Need to reallocate */
10832 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10833 		if (hdrs == NULL)
10834 			return (ENOMEM);
10835 		if (tcp->tcp_iphc != NULL) {
10836 			if (tcp->tcp_hdr_grown) {
10837 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10838 			} else {
10839 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10840 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10841 			}
10842 			tcp->tcp_iphc_len = 0;
10843 		}
10844 		ASSERT(tcp->tcp_iphc_len == 0);
10845 		tcp->tcp_iphc = hdrs;
10846 		tcp->tcp_iphc_len = hdrs_len;
10847 		tcp->tcp_hdr_grown = B_TRUE;
10848 	}
10849 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10850 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10851 
10852 	/* Set header fields not in ipp */
10853 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10854 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10855 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10856 	} else {
10857 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10858 	}
10859 	/*
10860 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10861 	 *
10862 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10863 	 */
10864 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10865 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10866 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10867 
10868 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10869 
10870 	tcp->tcp_ip6h->ip6_src = src;
10871 	tcp->tcp_ip6h->ip6_dst = dst;
10872 
10873 	/*
10874 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10875 	 * the default value for TCP.
10876 	 */
10877 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10878 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
10879 
10880 	/*
10881 	 * If we're setting extension headers after a connection
10882 	 * has been established, and if we have a routing header
10883 	 * among the extension headers, call ip_massage_options_v6 to
10884 	 * manipulate the routing header/ip6_dst set the checksum
10885 	 * difference in the tcp header template.
10886 	 * (This happens in tcp_connect_ipv6 if the routing header
10887 	 * is set prior to the connect.)
10888 	 * Set the tcp_sum to zero first in case we've cleared a
10889 	 * routing header or don't have one at all.
10890 	 */
10891 	tcp->tcp_sum = 0;
10892 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10893 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10894 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10895 		    (uint8_t *)tcp->tcp_tcph);
10896 		if (rth != NULL) {
10897 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10898 			    rth, tcps->tcps_netstack);
10899 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10900 			    (tcp->tcp_sum >> 16));
10901 		}
10902 	}
10903 
10904 	/* Try to get everything in a single mblk */
10905 	(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
10906 	    hdrs_len + tcps->tcps_wroff_xtra);
10907 	return (0);
10908 }
10909 
10910 /*
10911  * Transfer any source route option from ipha to buf/dst in reversed form.
10912  */
10913 static int
10914 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10915 {
10916 	ipoptp_t	opts;
10917 	uchar_t		*opt;
10918 	uint8_t		optval;
10919 	uint8_t		optlen;
10920 	uint32_t	len = 0;
10921 
10922 	for (optval = ipoptp_first(&opts, ipha);
10923 	    optval != IPOPT_EOL;
10924 	    optval = ipoptp_next(&opts)) {
10925 		opt = opts.ipoptp_cur;
10926 		optlen = opts.ipoptp_len;
10927 		switch (optval) {
10928 			int	off1, off2;
10929 		case IPOPT_SSRR:
10930 		case IPOPT_LSRR:
10931 
10932 			/* Reverse source route */
10933 			/*
10934 			 * First entry should be the next to last one in the
10935 			 * current source route (the last entry is our
10936 			 * address.)
10937 			 * The last entry should be the final destination.
10938 			 */
10939 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10940 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10941 			off1 = IPOPT_MINOFF_SR - 1;
10942 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10943 			if (off2 < 0) {
10944 				/* No entries in source route */
10945 				break;
10946 			}
10947 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10948 			/*
10949 			 * Note: use src since ipha has not had its src
10950 			 * and dst reversed (it is in the state it was
10951 			 * received.
10952 			 */
10953 			bcopy(&ipha->ipha_src, buf + off2,
10954 			    IP_ADDR_LEN);
10955 			off2 -= IP_ADDR_LEN;
10956 
10957 			while (off2 > 0) {
10958 				bcopy(opt + off2, buf + off1,
10959 				    IP_ADDR_LEN);
10960 				off1 += IP_ADDR_LEN;
10961 				off2 -= IP_ADDR_LEN;
10962 			}
10963 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
10964 			buf += optlen;
10965 			len += optlen;
10966 			break;
10967 		}
10968 	}
10969 done:
10970 	/* Pad the resulting options */
10971 	while (len & 0x3) {
10972 		*buf++ = IPOPT_EOL;
10973 		len++;
10974 	}
10975 	return (len);
10976 }
10977 
10978 
10979 /*
10980  * Extract and revert a source route from ipha (if any)
10981  * and then update the relevant fields in both tcp_t and the standard header.
10982  */
10983 static void
10984 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
10985 {
10986 	char	buf[TCP_MAX_HDR_LENGTH];
10987 	uint_t	tcph_len;
10988 	int	len;
10989 
10990 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
10991 	len = IPH_HDR_LENGTH(ipha);
10992 	if (len == IP_SIMPLE_HDR_LENGTH)
10993 		/* Nothing to do */
10994 		return;
10995 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
10996 	    (len & 0x3))
10997 		return;
10998 
10999 	tcph_len = tcp->tcp_tcp_hdr_len;
11000 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11001 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11002 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11003 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11004 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11005 	len += IP_SIMPLE_HDR_LENGTH;
11006 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11007 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11008 	if ((int)tcp->tcp_sum < 0)
11009 		tcp->tcp_sum--;
11010 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11011 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11012 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11013 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11014 	tcp->tcp_ip_hdr_len = len;
11015 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11016 	    (IP_VERSION << 4) | (len >> 2);
11017 	len += tcph_len;
11018 	tcp->tcp_hdr_len = len;
11019 }
11020 
11021 /*
11022  * Copy the standard header into its new location,
11023  * lay in the new options and then update the relevant
11024  * fields in both tcp_t and the standard header.
11025  */
11026 static int
11027 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11028 {
11029 	uint_t	tcph_len;
11030 	uint8_t	*ip_optp;
11031 	tcph_t	*new_tcph;
11032 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11033 	conn_t	*connp = tcp->tcp_connp;
11034 
11035 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11036 		return (EINVAL);
11037 
11038 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11039 		return (EINVAL);
11040 
11041 	if (checkonly) {
11042 		/*
11043 		 * do not really set, just pretend to - T_CHECK
11044 		 */
11045 		return (0);
11046 	}
11047 
11048 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11049 	if (tcp->tcp_label_len > 0) {
11050 		int padlen;
11051 		uint8_t opt;
11052 
11053 		/* convert list termination to no-ops */
11054 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11055 		ip_optp += ip_optp[IPOPT_OLEN];
11056 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11057 		while (--padlen >= 0)
11058 			*ip_optp++ = opt;
11059 	}
11060 	tcph_len = tcp->tcp_tcp_hdr_len;
11061 	new_tcph = (tcph_t *)(ip_optp + len);
11062 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11063 	tcp->tcp_tcph = new_tcph;
11064 	bcopy(ptr, ip_optp, len);
11065 
11066 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11067 
11068 	tcp->tcp_ip_hdr_len = len;
11069 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11070 	    (IP_VERSION << 4) | (len >> 2);
11071 	tcp->tcp_hdr_len = len + tcph_len;
11072 	if (!TCP_IS_DETACHED(tcp)) {
11073 		/* Always allocate room for all options. */
11074 		(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
11075 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11076 	}
11077 	return (0);
11078 }
11079 
11080 /* Get callback routine passed to nd_load by tcp_param_register */
11081 /* ARGSUSED */
11082 static int
11083 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11084 {
11085 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11086 
11087 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11088 	return (0);
11089 }
11090 
11091 /*
11092  * Walk through the param array specified registering each element with the
11093  * named dispatch handler.
11094  */
11095 static boolean_t
11096 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11097 {
11098 	for (; cnt-- > 0; tcppa++) {
11099 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11100 			if (!nd_load(ndp, tcppa->tcp_param_name,
11101 			    tcp_param_get, tcp_param_set,
11102 			    (caddr_t)tcppa)) {
11103 				nd_free(ndp);
11104 				return (B_FALSE);
11105 			}
11106 		}
11107 	}
11108 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11109 	    KM_SLEEP);
11110 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11111 	    sizeof (tcpparam_t));
11112 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11113 	    tcp_param_get, tcp_param_set_aligned,
11114 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11115 		nd_free(ndp);
11116 		return (B_FALSE);
11117 	}
11118 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11119 	    KM_SLEEP);
11120 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11121 	    sizeof (tcpparam_t));
11122 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11123 	    tcp_param_get, tcp_param_set_aligned,
11124 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11125 		nd_free(ndp);
11126 		return (B_FALSE);
11127 	}
11128 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11129 	    KM_SLEEP);
11130 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11131 	    sizeof (tcpparam_t));
11132 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11133 	    tcp_param_get, tcp_param_set_aligned,
11134 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11135 		nd_free(ndp);
11136 		return (B_FALSE);
11137 	}
11138 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11139 	    KM_SLEEP);
11140 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11141 	    sizeof (tcpparam_t));
11142 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11143 	    tcp_param_get, tcp_param_set_aligned,
11144 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11145 		nd_free(ndp);
11146 		return (B_FALSE);
11147 	}
11148 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11149 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11150 		nd_free(ndp);
11151 		return (B_FALSE);
11152 	}
11153 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11154 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11155 		nd_free(ndp);
11156 		return (B_FALSE);
11157 	}
11158 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11159 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11160 		nd_free(ndp);
11161 		return (B_FALSE);
11162 	}
11163 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11164 	    tcp_1948_phrase_set, NULL)) {
11165 		nd_free(ndp);
11166 		return (B_FALSE);
11167 	}
11168 	/*
11169 	 * Dummy ndd variables - only to convey obsolescence information
11170 	 * through printing of their name (no get or set routines)
11171 	 * XXX Remove in future releases ?
11172 	 */
11173 	if (!nd_load(ndp,
11174 	    "tcp_close_wait_interval(obsoleted - "
11175 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11176 		nd_free(ndp);
11177 		return (B_FALSE);
11178 	}
11179 	return (B_TRUE);
11180 }
11181 
11182 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11183 /* ARGSUSED */
11184 static int
11185 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11186     cred_t *cr)
11187 {
11188 	long new_value;
11189 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11190 
11191 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11192 	    new_value < tcppa->tcp_param_min ||
11193 	    new_value > tcppa->tcp_param_max) {
11194 		return (EINVAL);
11195 	}
11196 	/*
11197 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11198 	 * round it up.  For future 64 bit requirement, we actually make it
11199 	 * a multiple of 8.
11200 	 */
11201 	if (new_value & 0x7) {
11202 		new_value = (new_value & ~0x7) + 0x8;
11203 	}
11204 	tcppa->tcp_param_val = new_value;
11205 	return (0);
11206 }
11207 
11208 /* Set callback routine passed to nd_load by tcp_param_register */
11209 /* ARGSUSED */
11210 static int
11211 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11212 {
11213 	long	new_value;
11214 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11215 
11216 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11217 	    new_value < tcppa->tcp_param_min ||
11218 	    new_value > tcppa->tcp_param_max) {
11219 		return (EINVAL);
11220 	}
11221 	tcppa->tcp_param_val = new_value;
11222 	return (0);
11223 }
11224 
11225 /*
11226  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11227  * is filled, return as much as we can.  The message passed in may be
11228  * multi-part, chained using b_cont.  "start" is the starting sequence
11229  * number for this piece.
11230  */
11231 static mblk_t *
11232 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11233 {
11234 	uint32_t	end;
11235 	mblk_t		*mp1;
11236 	mblk_t		*mp2;
11237 	mblk_t		*next_mp;
11238 	uint32_t	u1;
11239 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11240 
11241 	/* Walk through all the new pieces. */
11242 	do {
11243 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11244 		    (uintptr_t)INT_MAX);
11245 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11246 		next_mp = mp->b_cont;
11247 		if (start == end) {
11248 			/* Empty.  Blast it. */
11249 			freeb(mp);
11250 			continue;
11251 		}
11252 		mp->b_cont = NULL;
11253 		TCP_REASS_SET_SEQ(mp, start);
11254 		TCP_REASS_SET_END(mp, end);
11255 		mp1 = tcp->tcp_reass_tail;
11256 		if (!mp1) {
11257 			tcp->tcp_reass_tail = mp;
11258 			tcp->tcp_reass_head = mp;
11259 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11260 			UPDATE_MIB(&tcps->tcps_mib,
11261 			    tcpInDataUnorderBytes, end - start);
11262 			continue;
11263 		}
11264 		/* New stuff completely beyond tail? */
11265 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11266 			/* Link it on end. */
11267 			mp1->b_cont = mp;
11268 			tcp->tcp_reass_tail = mp;
11269 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11270 			UPDATE_MIB(&tcps->tcps_mib,
11271 			    tcpInDataUnorderBytes, end - start);
11272 			continue;
11273 		}
11274 		mp1 = tcp->tcp_reass_head;
11275 		u1 = TCP_REASS_SEQ(mp1);
11276 		/* New stuff at the front? */
11277 		if (SEQ_LT(start, u1)) {
11278 			/* Yes... Check for overlap. */
11279 			mp->b_cont = mp1;
11280 			tcp->tcp_reass_head = mp;
11281 			tcp_reass_elim_overlap(tcp, mp);
11282 			continue;
11283 		}
11284 		/*
11285 		 * The new piece fits somewhere between the head and tail.
11286 		 * We find our slot, where mp1 precedes us and mp2 trails.
11287 		 */
11288 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11289 			u1 = TCP_REASS_SEQ(mp2);
11290 			if (SEQ_LEQ(start, u1))
11291 				break;
11292 		}
11293 		/* Link ourselves in */
11294 		mp->b_cont = mp2;
11295 		mp1->b_cont = mp;
11296 
11297 		/* Trim overlap with following mblk(s) first */
11298 		tcp_reass_elim_overlap(tcp, mp);
11299 
11300 		/* Trim overlap with preceding mblk */
11301 		tcp_reass_elim_overlap(tcp, mp1);
11302 
11303 	} while (start = end, mp = next_mp);
11304 	mp1 = tcp->tcp_reass_head;
11305 	/* Anything ready to go? */
11306 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11307 		return (NULL);
11308 	/* Eat what we can off the queue */
11309 	for (;;) {
11310 		mp = mp1->b_cont;
11311 		end = TCP_REASS_END(mp1);
11312 		TCP_REASS_SET_SEQ(mp1, 0);
11313 		TCP_REASS_SET_END(mp1, 0);
11314 		if (!mp) {
11315 			tcp->tcp_reass_tail = NULL;
11316 			break;
11317 		}
11318 		if (end != TCP_REASS_SEQ(mp)) {
11319 			mp1->b_cont = NULL;
11320 			break;
11321 		}
11322 		mp1 = mp;
11323 	}
11324 	mp1 = tcp->tcp_reass_head;
11325 	tcp->tcp_reass_head = mp;
11326 	return (mp1);
11327 }
11328 
11329 /* Eliminate any overlap that mp may have over later mblks */
11330 static void
11331 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11332 {
11333 	uint32_t	end;
11334 	mblk_t		*mp1;
11335 	uint32_t	u1;
11336 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11337 
11338 	end = TCP_REASS_END(mp);
11339 	while ((mp1 = mp->b_cont) != NULL) {
11340 		u1 = TCP_REASS_SEQ(mp1);
11341 		if (!SEQ_GT(end, u1))
11342 			break;
11343 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11344 			mp->b_wptr -= end - u1;
11345 			TCP_REASS_SET_END(mp, u1);
11346 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11347 			UPDATE_MIB(&tcps->tcps_mib,
11348 			    tcpInDataPartDupBytes, end - u1);
11349 			break;
11350 		}
11351 		mp->b_cont = mp1->b_cont;
11352 		TCP_REASS_SET_SEQ(mp1, 0);
11353 		TCP_REASS_SET_END(mp1, 0);
11354 		freeb(mp1);
11355 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11356 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11357 	}
11358 	if (!mp1)
11359 		tcp->tcp_reass_tail = mp;
11360 }
11361 
11362 static uint_t
11363 tcp_rwnd_reopen(tcp_t *tcp)
11364 {
11365 	uint_t ret = 0;
11366 	uint_t thwin;
11367 
11368 	/* Learn the latest rwnd information that we sent to the other side. */
11369 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11370 	    << tcp->tcp_rcv_ws;
11371 	/* This is peer's calculated send window (our receive window). */
11372 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11373 	/*
11374 	 * Increase the receive window to max.  But we need to do receiver
11375 	 * SWS avoidance.  This means that we need to check the increase of
11376 	 * of receive window is at least 1 MSS.
11377 	 */
11378 	if (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss) {
11379 		/*
11380 		 * If the window that the other side knows is less than max
11381 		 * deferred acks segments, send an update immediately.
11382 		 */
11383 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11384 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
11385 			ret = TH_ACK_NEEDED;
11386 		}
11387 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
11388 	}
11389 	return (ret);
11390 }
11391 
11392 /*
11393  * Send up all messages queued on tcp_rcv_list.
11394  */
11395 static uint_t
11396 tcp_rcv_drain(tcp_t *tcp)
11397 {
11398 	mblk_t *mp;
11399 	uint_t ret = 0;
11400 #ifdef DEBUG
11401 	uint_t cnt = 0;
11402 #endif
11403 	queue_t	*q = tcp->tcp_rq;
11404 
11405 	/* Can't drain on an eager connection */
11406 	if (tcp->tcp_listener != NULL)
11407 		return (ret);
11408 
11409 	/* Can't be a non-STREAMS connection or sodirect enabled */
11410 	ASSERT((!IPCL_IS_NONSTR(tcp->tcp_connp)) && SOD_NOT_ENABLED(tcp));
11411 
11412 	/* No need for the push timer now. */
11413 	if (tcp->tcp_push_tid != 0) {
11414 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11415 		tcp->tcp_push_tid = 0;
11416 	}
11417 
11418 	/*
11419 	 * Handle two cases here: we are currently fused or we were
11420 	 * previously fused and have some urgent data to be delivered
11421 	 * upstream.  The latter happens because we either ran out of
11422 	 * memory or were detached and therefore sending the SIGURG was
11423 	 * deferred until this point.  In either case we pass control
11424 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11425 	 * some work.
11426 	 */
11427 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11428 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
11429 		    tcp->tcp_fused_sigurg_mp != NULL);
11430 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11431 		    &tcp->tcp_fused_sigurg_mp))
11432 			return (ret);
11433 	}
11434 
11435 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11436 		tcp->tcp_rcv_list = mp->b_next;
11437 		mp->b_next = NULL;
11438 #ifdef DEBUG
11439 		cnt += msgdsize(mp);
11440 #endif
11441 		/* Does this need SSL processing first? */
11442 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11443 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11444 			    mblk_t *, mp);
11445 			tcp_kssl_input(tcp, mp);
11446 			continue;
11447 		}
11448 		putnext(q, mp);
11449 	}
11450 #ifdef DEBUG
11451 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11452 #endif
11453 	tcp->tcp_rcv_last_head = NULL;
11454 	tcp->tcp_rcv_last_tail = NULL;
11455 	tcp->tcp_rcv_cnt = 0;
11456 
11457 	if (canputnext(q))
11458 		return (tcp_rwnd_reopen(tcp));
11459 
11460 	return (ret);
11461 }
11462 
11463 /*
11464  * Queue data on tcp_rcv_list which is a b_next chain.
11465  * tcp_rcv_last_head/tail is the last element of this chain.
11466  * Each element of the chain is a b_cont chain.
11467  *
11468  * M_DATA messages are added to the current element.
11469  * Other messages are added as new (b_next) elements.
11470  */
11471 void
11472 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11473 {
11474 	ASSERT(seg_len == msgdsize(mp));
11475 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11476 
11477 	if (tcp->tcp_rcv_list == NULL) {
11478 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11479 		tcp->tcp_rcv_list = mp;
11480 		tcp->tcp_rcv_last_head = mp;
11481 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11482 		tcp->tcp_rcv_last_tail->b_cont = mp;
11483 	} else {
11484 		tcp->tcp_rcv_last_head->b_next = mp;
11485 		tcp->tcp_rcv_last_head = mp;
11486 	}
11487 
11488 	while (mp->b_cont)
11489 		mp = mp->b_cont;
11490 
11491 	tcp->tcp_rcv_last_tail = mp;
11492 	tcp->tcp_rcv_cnt += seg_len;
11493 	tcp->tcp_rwnd -= seg_len;
11494 }
11495 
11496 /*
11497  * The tcp_rcv_sod_XXX() functions enqueue data directly to the socket
11498  * above, in addition when uioa is enabled schedule an asynchronous uio
11499  * prior to enqueuing. They implement the combinhed semantics of the
11500  * tcp_rcv_XXX() functions, tcp_rcv_list push logic, and STREAMS putnext()
11501  * canputnext(), i.e. flow-control with backenable.
11502  *
11503  * tcp_sod_wakeup() is called where tcp_rcv_drain() would be called in the
11504  * non sodirect connection but as there are no tcp_tcv_list mblk_t's we deal
11505  * with the rcv_wnd and push timer and call the sodirect wakeup function.
11506  *
11507  * Must be called with sodp->sod_lockp held and will return with the lock
11508  * released.
11509  */
11510 static uint_t
11511 tcp_rcv_sod_wakeup(tcp_t *tcp, sodirect_t *sodp)
11512 {
11513 	queue_t		*q = tcp->tcp_rq;
11514 	uint_t		thwin;
11515 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11516 	uint_t		ret = 0;
11517 
11518 	/* Can't be an eager connection */
11519 	ASSERT(tcp->tcp_listener == NULL);
11520 
11521 	/* Caller must have lock held */
11522 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11523 
11524 	/* Sodirect mode so must not be a tcp_rcv_list */
11525 	ASSERT(tcp->tcp_rcv_list == NULL);
11526 
11527 	if (SOD_QFULL(sodp)) {
11528 		/* Q is full, mark Q for need backenable */
11529 		SOD_QSETBE(sodp);
11530 	}
11531 	/* Last advertised rwnd, i.e. rwnd last sent in a packet */
11532 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11533 	    << tcp->tcp_rcv_ws;
11534 	/* This is peer's calculated send window (our available rwnd). */
11535 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11536 	/*
11537 	 * Increase the receive window to max.  But we need to do receiver
11538 	 * SWS avoidance.  This means that we need to check the increase of
11539 	 * of receive window is at least 1 MSS.
11540 	 */
11541 	if (!SOD_QFULL(sodp) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11542 		/*
11543 		 * If the window that the other side knows is less than max
11544 		 * deferred acks segments, send an update immediately.
11545 		 */
11546 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11547 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11548 			ret = TH_ACK_NEEDED;
11549 		}
11550 		tcp->tcp_rwnd = q->q_hiwat;
11551 	}
11552 
11553 	if (!SOD_QEMPTY(sodp)) {
11554 		/* Wakeup to socket */
11555 		sodp->sod_state &= SOD_WAKE_CLR;
11556 		sodp->sod_state |= SOD_WAKE_DONE;
11557 		(sodp->sod_wakeup)(sodp);
11558 		/* wakeup() does the mutex_ext() */
11559 	} else {
11560 		/* Q is empty, no need to wake */
11561 		sodp->sod_state &= SOD_WAKE_CLR;
11562 		sodp->sod_state |= SOD_WAKE_NOT;
11563 		mutex_exit(sodp->sod_lockp);
11564 	}
11565 
11566 	/* No need for the push timer now. */
11567 	if (tcp->tcp_push_tid != 0) {
11568 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11569 		tcp->tcp_push_tid = 0;
11570 	}
11571 
11572 	return (ret);
11573 }
11574 
11575 /*
11576  * Called where tcp_rcv_enqueue()/putnext(RD(q)) would be. For M_DATA
11577  * mblk_t's if uioa enabled then start a uioa asynchronous copy directly
11578  * to the user-land buffer and flag the mblk_t as such.
11579  *
11580  * Also, handle tcp_rwnd.
11581  */
11582 uint_t
11583 tcp_rcv_sod_enqueue(tcp_t *tcp, sodirect_t *sodp, mblk_t *mp, uint_t seg_len)
11584 {
11585 	uioa_t		*uioap = &sodp->sod_uioa;
11586 	boolean_t	qfull;
11587 	uint_t		thwin;
11588 
11589 	/* Can't be an eager connection */
11590 	ASSERT(tcp->tcp_listener == NULL);
11591 
11592 	/* Caller must have lock held */
11593 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11594 
11595 	/* Sodirect mode so must not be a tcp_rcv_list */
11596 	ASSERT(tcp->tcp_rcv_list == NULL);
11597 
11598 	/* Passed in segment length must be equal to mblk_t chain data size */
11599 	ASSERT(seg_len == msgdsize(mp));
11600 
11601 	if (DB_TYPE(mp) != M_DATA) {
11602 		/* Only process M_DATA mblk_t's */
11603 		goto enq;
11604 	}
11605 	if (uioap->uioa_state & UIOA_ENABLED) {
11606 		/* Uioa is enabled */
11607 		mblk_t		*mp1 = mp;
11608 		mblk_t		*lmp = NULL;
11609 
11610 		if (seg_len > uioap->uio_resid) {
11611 			/*
11612 			 * There isn't enough uio space for the mblk_t chain
11613 			 * so disable uioa such that this and any additional
11614 			 * mblk_t data is handled by the socket and schedule
11615 			 * the socket for wakeup to finish this uioa.
11616 			 */
11617 			uioap->uioa_state &= UIOA_CLR;
11618 			uioap->uioa_state |= UIOA_FINI;
11619 			if (sodp->sod_state & SOD_WAKE_NOT) {
11620 				sodp->sod_state &= SOD_WAKE_CLR;
11621 				sodp->sod_state |= SOD_WAKE_NEED;
11622 			}
11623 			goto enq;
11624 		}
11625 		do {
11626 			uint32_t	len = MBLKL(mp1);
11627 
11628 			if (!uioamove(mp1->b_rptr, len, UIO_READ, uioap)) {
11629 				/* Scheduled, mark dblk_t as such */
11630 				DB_FLAGS(mp1) |= DBLK_UIOA;
11631 			} else {
11632 				/* Error, turn off async processing */
11633 				uioap->uioa_state &= UIOA_CLR;
11634 				uioap->uioa_state |= UIOA_FINI;
11635 				break;
11636 			}
11637 			lmp = mp1;
11638 		} while ((mp1 = mp1->b_cont) != NULL);
11639 
11640 		if (mp1 != NULL || uioap->uio_resid == 0) {
11641 			/*
11642 			 * Not all mblk_t(s) uioamoved (error) or all uio
11643 			 * space has been consumed so schedule the socket
11644 			 * for wakeup to finish this uio.
11645 			 */
11646 			sodp->sod_state &= SOD_WAKE_CLR;
11647 			sodp->sod_state |= SOD_WAKE_NEED;
11648 
11649 			/* Break the mblk chain if neccessary. */
11650 			if (mp1 != NULL && lmp != NULL) {
11651 				mp->b_next = mp1;
11652 				lmp->b_cont = NULL;
11653 			}
11654 		}
11655 	} else if (uioap->uioa_state & UIOA_FINI) {
11656 		/*
11657 		 * Post UIO_ENABLED waiting for socket to finish processing
11658 		 * so just enqueue and update tcp_rwnd.
11659 		 */
11660 		if (SOD_QFULL(sodp))
11661 			tcp->tcp_rwnd -= seg_len;
11662 	} else if (sodp->sod_want > 0) {
11663 		/*
11664 		 * Uioa isn't enabled but sodirect has a pending read().
11665 		 */
11666 		if (SOD_QCNT(sodp) + seg_len >= sodp->sod_want) {
11667 			if (sodp->sod_state & SOD_WAKE_NOT) {
11668 				/* Schedule socket for wakeup */
11669 				sodp->sod_state &= SOD_WAKE_CLR;
11670 				sodp->sod_state |= SOD_WAKE_NEED;
11671 			}
11672 			tcp->tcp_rwnd -= seg_len;
11673 		}
11674 	} else if (SOD_QCNT(sodp) + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
11675 		/*
11676 		 * No pending sodirect read() so used the default
11677 		 * TCP push logic to guess that a push is needed.
11678 		 */
11679 		if (sodp->sod_state & SOD_WAKE_NOT) {
11680 			/* Schedule socket for wakeup */
11681 			sodp->sod_state &= SOD_WAKE_CLR;
11682 			sodp->sod_state |= SOD_WAKE_NEED;
11683 		}
11684 		tcp->tcp_rwnd -= seg_len;
11685 	} else {
11686 		/* Just update tcp_rwnd */
11687 		tcp->tcp_rwnd -= seg_len;
11688 	}
11689 enq:
11690 	qfull = SOD_QFULL(sodp);
11691 
11692 	(sodp->sod_enqueue)(sodp, mp);
11693 
11694 	if (! qfull && SOD_QFULL(sodp)) {
11695 		/* Wasn't QFULL, now QFULL, need back-enable */
11696 		SOD_QSETBE(sodp);
11697 	}
11698 
11699 	/*
11700 	 * Check to see if remote avail swnd < mss due to delayed ACK,
11701 	 * first get advertised rwnd.
11702 	 */
11703 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win));
11704 	/* Minus delayed ACK count */
11705 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11706 	if (thwin < tcp->tcp_mss) {
11707 		/* Remote avail swnd < mss, need ACK now */
11708 		return (TH_ACK_NEEDED);
11709 	}
11710 
11711 	return (0);
11712 }
11713 
11714 /*
11715  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11716  *
11717  * This is the default entry function into TCP on the read side. TCP is
11718  * always entered via squeue i.e. using squeue's for mutual exclusion.
11719  * When classifier does a lookup to find the tcp, it also puts a reference
11720  * on the conn structure associated so the tcp is guaranteed to exist
11721  * when we come here. We still need to check the state because it might
11722  * as well has been closed. The squeue processing function i.e. squeue_enter,
11723  * is responsible for doing the CONN_DEC_REF.
11724  *
11725  * Apart from the default entry point, IP also sends packets directly to
11726  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11727  * connections.
11728  */
11729 boolean_t tcp_outbound_squeue_switch = B_FALSE;
11730 void
11731 tcp_input(void *arg, mblk_t *mp, void *arg2)
11732 {
11733 	conn_t	*connp = (conn_t *)arg;
11734 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11735 
11736 	/* arg2 is the sqp */
11737 	ASSERT(arg2 != NULL);
11738 	ASSERT(mp != NULL);
11739 
11740 	/*
11741 	 * Don't accept any input on a closed tcp as this TCP logically does
11742 	 * not exist on the system. Don't proceed further with this TCP.
11743 	 * For eg. this packet could trigger another close of this tcp
11744 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11745 	 * tcp_clean_death / tcp_closei_local must be called at most once
11746 	 * on a TCP. In this case we need to refeed the packet into the
11747 	 * classifier and figure out where the packet should go. Need to
11748 	 * preserve the recv_ill somehow. Until we figure that out, for
11749 	 * now just drop the packet if we can't classify the packet.
11750 	 */
11751 	if (tcp->tcp_state == TCPS_CLOSED ||
11752 	    tcp->tcp_state == TCPS_BOUND) {
11753 		conn_t	*new_connp;
11754 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11755 
11756 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11757 		if (new_connp != NULL) {
11758 			tcp_reinput(new_connp, mp, arg2);
11759 			return;
11760 		}
11761 		/* We failed to classify. For now just drop the packet */
11762 		freemsg(mp);
11763 		return;
11764 	}
11765 
11766 	if (DB_TYPE(mp) != M_DATA) {
11767 		tcp_rput_common(tcp, mp);
11768 		return;
11769 	}
11770 
11771 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
11772 		squeue_t	*final_sqp;
11773 
11774 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
11775 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
11776 		DB_CKSUMSTART(mp) = 0;
11777 		if (tcp->tcp_state == TCPS_SYN_SENT &&
11778 		    connp->conn_final_sqp == NULL &&
11779 		    tcp_outbound_squeue_switch) {
11780 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
11781 			connp->conn_final_sqp = final_sqp;
11782 			if (connp->conn_final_sqp != connp->conn_sqp) {
11783 				CONN_INC_REF(connp);
11784 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
11785 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
11786 				    tcp_rput_data, connp, ip_squeue_flag,
11787 				    SQTAG_CONNECT_FINISH);
11788 				return;
11789 			}
11790 		}
11791 	}
11792 	tcp_rput_data(connp, mp, arg2);
11793 }
11794 
11795 /*
11796  * The read side put procedure.
11797  * The packets passed up by ip are assume to be aligned according to
11798  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11799  */
11800 static void
11801 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11802 {
11803 	/*
11804 	 * tcp_rput_data() does not expect M_CTL except for the case
11805 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11806 	 * type. Need to make sure that any other M_CTLs don't make
11807 	 * it to tcp_rput_data since it is not expecting any and doesn't
11808 	 * check for it.
11809 	 */
11810 	if (DB_TYPE(mp) == M_CTL) {
11811 		switch (*(uint32_t *)(mp->b_rptr)) {
11812 		case TCP_IOC_ABORT_CONN:
11813 			/*
11814 			 * Handle connection abort request.
11815 			 */
11816 			tcp_ioctl_abort_handler(tcp, mp);
11817 			return;
11818 		case IPSEC_IN:
11819 			/*
11820 			 * Only secure icmp arrive in TCP and they
11821 			 * don't go through data path.
11822 			 */
11823 			tcp_icmp_error(tcp, mp);
11824 			return;
11825 		case IN_PKTINFO:
11826 			/*
11827 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11828 			 * sockets that are receiving IPv4 traffic. tcp
11829 			 */
11830 			ASSERT(tcp->tcp_family == AF_INET6);
11831 			ASSERT(tcp->tcp_ipv6_recvancillary &
11832 			    TCP_IPV6_RECVPKTINFO);
11833 			tcp_rput_data(tcp->tcp_connp, mp,
11834 			    tcp->tcp_connp->conn_sqp);
11835 			return;
11836 		case MDT_IOC_INFO_UPDATE:
11837 			/*
11838 			 * Handle Multidata information update; the
11839 			 * following routine will free the message.
11840 			 */
11841 			if (tcp->tcp_connp->conn_mdt_ok) {
11842 				tcp_mdt_update(tcp,
11843 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11844 				    B_FALSE);
11845 			}
11846 			freemsg(mp);
11847 			return;
11848 		case LSO_IOC_INFO_UPDATE:
11849 			/*
11850 			 * Handle LSO information update; the following
11851 			 * routine will free the message.
11852 			 */
11853 			if (tcp->tcp_connp->conn_lso_ok) {
11854 				tcp_lso_update(tcp,
11855 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11856 			}
11857 			freemsg(mp);
11858 			return;
11859 		default:
11860 			/*
11861 			 * tcp_icmp_err() will process the M_CTL packets.
11862 			 * Non-ICMP packets, if any, will be discarded in
11863 			 * tcp_icmp_err(). We will process the ICMP packet
11864 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11865 			 * incoming ICMP packet may result in changing
11866 			 * the tcp_mss, which we would need if we have
11867 			 * packets to retransmit.
11868 			 */
11869 			tcp_icmp_error(tcp, mp);
11870 			return;
11871 		}
11872 	}
11873 
11874 	/* No point processing the message if tcp is already closed */
11875 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11876 		freemsg(mp);
11877 		return;
11878 	}
11879 
11880 	tcp_rput_other(tcp, mp);
11881 }
11882 
11883 
11884 /* The minimum of smoothed mean deviation in RTO calculation. */
11885 #define	TCP_SD_MIN	400
11886 
11887 /*
11888  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11889  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11890  * are the same as those in Appendix A.2 of that paper.
11891  *
11892  * m = new measurement
11893  * sa = smoothed RTT average (8 * average estimates).
11894  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11895  */
11896 static void
11897 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11898 {
11899 	long m = TICK_TO_MSEC(rtt);
11900 	clock_t sa = tcp->tcp_rtt_sa;
11901 	clock_t sv = tcp->tcp_rtt_sd;
11902 	clock_t rto;
11903 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11904 
11905 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11906 	tcp->tcp_rtt_update++;
11907 
11908 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11909 	if (sa != 0) {
11910 		/*
11911 		 * Update average estimator:
11912 		 *	new rtt = 7/8 old rtt + 1/8 Error
11913 		 */
11914 
11915 		/* m is now Error in estimate. */
11916 		m -= sa >> 3;
11917 		if ((sa += m) <= 0) {
11918 			/*
11919 			 * Don't allow the smoothed average to be negative.
11920 			 * We use 0 to denote reinitialization of the
11921 			 * variables.
11922 			 */
11923 			sa = 1;
11924 		}
11925 
11926 		/*
11927 		 * Update deviation estimator:
11928 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11929 		 */
11930 		if (m < 0)
11931 			m = -m;
11932 		m -= sv >> 2;
11933 		sv += m;
11934 	} else {
11935 		/*
11936 		 * This follows BSD's implementation.  So the reinitialized
11937 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11938 		 * link is bandwidth dominated, doubling the window size
11939 		 * during slow start means doubling the RTT.  We want to be
11940 		 * more conservative when we reinitialize our estimates.  3
11941 		 * is just a convenient number.
11942 		 */
11943 		sa = m << 3;
11944 		sv = m << 1;
11945 	}
11946 	if (sv < TCP_SD_MIN) {
11947 		/*
11948 		 * We do not know that if sa captures the delay ACK
11949 		 * effect as in a long train of segments, a receiver
11950 		 * does not delay its ACKs.  So set the minimum of sv
11951 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11952 		 * of BSD DATO.  That means the minimum of mean
11953 		 * deviation is 100 ms.
11954 		 *
11955 		 */
11956 		sv = TCP_SD_MIN;
11957 	}
11958 	tcp->tcp_rtt_sa = sa;
11959 	tcp->tcp_rtt_sd = sv;
11960 	/*
11961 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11962 	 *
11963 	 * Add tcp_rexmit_interval extra in case of extreme environment
11964 	 * where the algorithm fails to work.  The default value of
11965 	 * tcp_rexmit_interval_extra should be 0.
11966 	 *
11967 	 * As we use a finer grained clock than BSD and update
11968 	 * RTO for every ACKs, add in another .25 of RTT to the
11969 	 * deviation of RTO to accomodate burstiness of 1/4 of
11970 	 * window size.
11971 	 */
11972 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
11973 
11974 	if (rto > tcps->tcps_rexmit_interval_max) {
11975 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
11976 	} else if (rto < tcps->tcps_rexmit_interval_min) {
11977 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
11978 	} else {
11979 		tcp->tcp_rto = rto;
11980 	}
11981 
11982 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11983 	tcp->tcp_timer_backoff = 0;
11984 }
11985 
11986 /*
11987  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11988  * send queue which starts at the given seq. no.
11989  *
11990  * Parameters:
11991  *	tcp_t *tcp: the tcp instance pointer.
11992  *	uint32_t seq: the starting seq. no of the requested segment.
11993  *	int32_t *off: after the execution, *off will be the offset to
11994  *		the returned mblk which points to the requested seq no.
11995  *		It is the caller's responsibility to send in a non-null off.
11996  *
11997  * Return:
11998  *	A mblk_t pointer pointing to the requested segment in send queue.
11999  */
12000 static mblk_t *
12001 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12002 {
12003 	int32_t	cnt;
12004 	mblk_t	*mp;
12005 
12006 	/* Defensive coding.  Make sure we don't send incorrect data. */
12007 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12008 		return (NULL);
12009 
12010 	cnt = seq - tcp->tcp_suna;
12011 	mp = tcp->tcp_xmit_head;
12012 	while (cnt > 0 && mp != NULL) {
12013 		cnt -= mp->b_wptr - mp->b_rptr;
12014 		if (cnt < 0) {
12015 			cnt += mp->b_wptr - mp->b_rptr;
12016 			break;
12017 		}
12018 		mp = mp->b_cont;
12019 	}
12020 	ASSERT(mp != NULL);
12021 	*off = cnt;
12022 	return (mp);
12023 }
12024 
12025 /*
12026  * This function handles all retransmissions if SACK is enabled for this
12027  * connection.  First it calculates how many segments can be retransmitted
12028  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12029  * segments.  A segment is eligible if sack_cnt for that segment is greater
12030  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12031  * all eligible segments, it checks to see if TCP can send some new segments
12032  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12033  *
12034  * Parameters:
12035  *	tcp_t *tcp: the tcp structure of the connection.
12036  *	uint_t *flags: in return, appropriate value will be set for
12037  *	tcp_rput_data().
12038  */
12039 static void
12040 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12041 {
12042 	notsack_blk_t	*notsack_blk;
12043 	int32_t		usable_swnd;
12044 	int32_t		mss;
12045 	uint32_t	seg_len;
12046 	mblk_t		*xmit_mp;
12047 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12048 
12049 	ASSERT(tcp->tcp_sack_info != NULL);
12050 	ASSERT(tcp->tcp_notsack_list != NULL);
12051 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12052 
12053 	/* Defensive coding in case there is a bug... */
12054 	if (tcp->tcp_notsack_list == NULL) {
12055 		return;
12056 	}
12057 	notsack_blk = tcp->tcp_notsack_list;
12058 	mss = tcp->tcp_mss;
12059 
12060 	/*
12061 	 * Limit the num of outstanding data in the network to be
12062 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12063 	 */
12064 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12065 
12066 	/* At least retransmit 1 MSS of data. */
12067 	if (usable_swnd <= 0) {
12068 		usable_swnd = mss;
12069 	}
12070 
12071 	/* Make sure no new RTT samples will be taken. */
12072 	tcp->tcp_csuna = tcp->tcp_snxt;
12073 
12074 	notsack_blk = tcp->tcp_notsack_list;
12075 	while (usable_swnd > 0) {
12076 		mblk_t		*snxt_mp, *tmp_mp;
12077 		tcp_seq		begin = tcp->tcp_sack_snxt;
12078 		tcp_seq		end;
12079 		int32_t		off;
12080 
12081 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12082 			if (SEQ_GT(notsack_blk->end, begin) &&
12083 			    (notsack_blk->sack_cnt >=
12084 			    tcps->tcps_dupack_fast_retransmit)) {
12085 				end = notsack_blk->end;
12086 				if (SEQ_LT(begin, notsack_blk->begin)) {
12087 					begin = notsack_blk->begin;
12088 				}
12089 				break;
12090 			}
12091 		}
12092 		/*
12093 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12094 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12095 		 * set to tcp_cwnd_ssthresh.
12096 		 */
12097 		if (notsack_blk == NULL) {
12098 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12099 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12100 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12101 				ASSERT(tcp->tcp_cwnd > 0);
12102 				return;
12103 			} else {
12104 				usable_swnd = usable_swnd / mss;
12105 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12106 				    MAX(usable_swnd * mss, mss);
12107 				*flags |= TH_XMIT_NEEDED;
12108 				return;
12109 			}
12110 		}
12111 
12112 		/*
12113 		 * Note that we may send more than usable_swnd allows here
12114 		 * because of round off, but no more than 1 MSS of data.
12115 		 */
12116 		seg_len = end - begin;
12117 		if (seg_len > mss)
12118 			seg_len = mss;
12119 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12120 		ASSERT(snxt_mp != NULL);
12121 		/* This should not happen.  Defensive coding again... */
12122 		if (snxt_mp == NULL) {
12123 			return;
12124 		}
12125 
12126 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12127 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12128 		if (xmit_mp == NULL)
12129 			return;
12130 
12131 		usable_swnd -= seg_len;
12132 		tcp->tcp_pipe += seg_len;
12133 		tcp->tcp_sack_snxt = begin + seg_len;
12134 
12135 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12136 
12137 		/*
12138 		 * Update the send timestamp to avoid false retransmission.
12139 		 */
12140 		snxt_mp->b_prev = (mblk_t *)lbolt;
12141 
12142 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12143 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12144 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12145 		/*
12146 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12147 		 * This happens when new data sent during fast recovery is
12148 		 * also lost.  If TCP retransmits those new data, it needs
12149 		 * to extend SACK recover phase to avoid starting another
12150 		 * fast retransmit/recovery unnecessarily.
12151 		 */
12152 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12153 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12154 		}
12155 	}
12156 }
12157 
12158 /*
12159  * This function handles policy checking at TCP level for non-hard_bound/
12160  * detached connections.
12161  */
12162 static boolean_t
12163 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12164     boolean_t secure, boolean_t mctl_present)
12165 {
12166 	ipsec_latch_t *ipl = NULL;
12167 	ipsec_action_t *act = NULL;
12168 	mblk_t *data_mp;
12169 	ipsec_in_t *ii;
12170 	const char *reason;
12171 	kstat_named_t *counter;
12172 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12173 	ipsec_stack_t	*ipss;
12174 	ip_stack_t	*ipst;
12175 
12176 	ASSERT(mctl_present || !secure);
12177 
12178 	ASSERT((ipha == NULL && ip6h != NULL) ||
12179 	    (ip6h == NULL && ipha != NULL));
12180 
12181 	/*
12182 	 * We don't necessarily have an ipsec_in_act action to verify
12183 	 * policy because of assymetrical policy where we have only
12184 	 * outbound policy and no inbound policy (possible with global
12185 	 * policy).
12186 	 */
12187 	if (!secure) {
12188 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12189 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12190 			return (B_TRUE);
12191 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12192 		    "tcp_check_policy", ipha, ip6h, secure,
12193 		    tcps->tcps_netstack);
12194 		ipss = tcps->tcps_netstack->netstack_ipsec;
12195 
12196 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12197 		    DROPPER(ipss, ipds_tcp_clear),
12198 		    &tcps->tcps_dropper);
12199 		return (B_FALSE);
12200 	}
12201 
12202 	/*
12203 	 * We have a secure packet.
12204 	 */
12205 	if (act == NULL) {
12206 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12207 		    "tcp_check_policy", ipha, ip6h, secure,
12208 		    tcps->tcps_netstack);
12209 		ipss = tcps->tcps_netstack->netstack_ipsec;
12210 
12211 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12212 		    DROPPER(ipss, ipds_tcp_secure),
12213 		    &tcps->tcps_dropper);
12214 		return (B_FALSE);
12215 	}
12216 
12217 	/*
12218 	 * XXX This whole routine is currently incorrect.  ipl should
12219 	 * be set to the latch pointer, but is currently not set, so
12220 	 * we initialize it to NULL to avoid picking up random garbage.
12221 	 */
12222 	if (ipl == NULL)
12223 		return (B_TRUE);
12224 
12225 	data_mp = first_mp->b_cont;
12226 
12227 	ii = (ipsec_in_t *)first_mp->b_rptr;
12228 
12229 	ipst = tcps->tcps_netstack->netstack_ip;
12230 
12231 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12232 	    &counter, tcp->tcp_connp)) {
12233 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12234 		return (B_TRUE);
12235 	}
12236 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12237 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12238 	    reason);
12239 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12240 
12241 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12242 	    &tcps->tcps_dropper);
12243 	return (B_FALSE);
12244 }
12245 
12246 /*
12247  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12248  * retransmission after a timeout.
12249  *
12250  * To limit the number of duplicate segments, we limit the number of segment
12251  * to be sent in one time to tcp_snd_burst, the burst variable.
12252  */
12253 static void
12254 tcp_ss_rexmit(tcp_t *tcp)
12255 {
12256 	uint32_t	snxt;
12257 	uint32_t	smax;
12258 	int32_t		win;
12259 	int32_t		mss;
12260 	int32_t		off;
12261 	int32_t		burst = tcp->tcp_snd_burst;
12262 	mblk_t		*snxt_mp;
12263 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12264 
12265 	/*
12266 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12267 	 * all unack'ed segments.
12268 	 */
12269 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12270 		smax = tcp->tcp_rexmit_max;
12271 		snxt = tcp->tcp_rexmit_nxt;
12272 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12273 			snxt = tcp->tcp_suna;
12274 		}
12275 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12276 		win -= snxt - tcp->tcp_suna;
12277 		mss = tcp->tcp_mss;
12278 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12279 
12280 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12281 		    (burst > 0) && (snxt_mp != NULL)) {
12282 			mblk_t	*xmit_mp;
12283 			mblk_t	*old_snxt_mp = snxt_mp;
12284 			uint32_t cnt = mss;
12285 
12286 			if (win < cnt) {
12287 				cnt = win;
12288 			}
12289 			if (SEQ_GT(snxt + cnt, smax)) {
12290 				cnt = smax - snxt;
12291 			}
12292 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12293 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12294 			if (xmit_mp == NULL)
12295 				return;
12296 
12297 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12298 
12299 			snxt += cnt;
12300 			win -= cnt;
12301 			/*
12302 			 * Update the send timestamp to avoid false
12303 			 * retransmission.
12304 			 */
12305 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12306 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12307 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12308 
12309 			tcp->tcp_rexmit_nxt = snxt;
12310 			burst--;
12311 		}
12312 		/*
12313 		 * If we have transmitted all we have at the time
12314 		 * we started the retranmission, we can leave
12315 		 * the rest of the job to tcp_wput_data().  But we
12316 		 * need to check the send window first.  If the
12317 		 * win is not 0, go on with tcp_wput_data().
12318 		 */
12319 		if (SEQ_LT(snxt, smax) || win == 0) {
12320 			return;
12321 		}
12322 	}
12323 	/* Only call tcp_wput_data() if there is data to be sent. */
12324 	if (tcp->tcp_unsent) {
12325 		tcp_wput_data(tcp, NULL, B_FALSE);
12326 	}
12327 }
12328 
12329 /*
12330  * Process all TCP option in SYN segment.  Note that this function should
12331  * be called after tcp_adapt_ire() is called so that the necessary info
12332  * from IRE is already set in the tcp structure.
12333  *
12334  * This function sets up the correct tcp_mss value according to the
12335  * MSS option value and our header size.  It also sets up the window scale
12336  * and timestamp values, and initialize SACK info blocks.  But it does not
12337  * change receive window size after setting the tcp_mss value.  The caller
12338  * should do the appropriate change.
12339  */
12340 void
12341 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12342 {
12343 	int options;
12344 	tcp_opt_t tcpopt;
12345 	uint32_t mss_max;
12346 	char *tmp_tcph;
12347 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12348 
12349 	tcpopt.tcp = NULL;
12350 	options = tcp_parse_options(tcph, &tcpopt);
12351 
12352 	/*
12353 	 * Process MSS option.  Note that MSS option value does not account
12354 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12355 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12356 	 * IPv6.
12357 	 */
12358 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12359 		if (tcp->tcp_ipversion == IPV4_VERSION)
12360 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12361 		else
12362 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12363 	} else {
12364 		if (tcp->tcp_ipversion == IPV4_VERSION)
12365 			mss_max = tcps->tcps_mss_max_ipv4;
12366 		else
12367 			mss_max = tcps->tcps_mss_max_ipv6;
12368 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12369 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12370 		else if (tcpopt.tcp_opt_mss > mss_max)
12371 			tcpopt.tcp_opt_mss = mss_max;
12372 	}
12373 
12374 	/* Process Window Scale option. */
12375 	if (options & TCP_OPT_WSCALE_PRESENT) {
12376 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12377 		tcp->tcp_snd_ws_ok = B_TRUE;
12378 	} else {
12379 		tcp->tcp_snd_ws = B_FALSE;
12380 		tcp->tcp_snd_ws_ok = B_FALSE;
12381 		tcp->tcp_rcv_ws = B_FALSE;
12382 	}
12383 
12384 	/* Process Timestamp option. */
12385 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12386 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12387 		tmp_tcph = (char *)tcp->tcp_tcph;
12388 
12389 		tcp->tcp_snd_ts_ok = B_TRUE;
12390 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12391 		tcp->tcp_last_rcv_lbolt = lbolt64;
12392 		ASSERT(OK_32PTR(tmp_tcph));
12393 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12394 
12395 		/* Fill in our template header with basic timestamp option. */
12396 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12397 		tmp_tcph[0] = TCPOPT_NOP;
12398 		tmp_tcph[1] = TCPOPT_NOP;
12399 		tmp_tcph[2] = TCPOPT_TSTAMP;
12400 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12401 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12402 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12403 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12404 	} else {
12405 		tcp->tcp_snd_ts_ok = B_FALSE;
12406 	}
12407 
12408 	/*
12409 	 * Process SACK options.  If SACK is enabled for this connection,
12410 	 * then allocate the SACK info structure.  Note the following ways
12411 	 * when tcp_snd_sack_ok is set to true.
12412 	 *
12413 	 * For active connection: in tcp_adapt_ire() called in
12414 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12415 	 * is checked.
12416 	 *
12417 	 * For passive connection: in tcp_adapt_ire() called in
12418 	 * tcp_accept_comm().
12419 	 *
12420 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12421 	 * That check makes sure that if we did not send a SACK OK option,
12422 	 * we will not enable SACK for this connection even though the other
12423 	 * side sends us SACK OK option.  For active connection, the SACK
12424 	 * info structure has already been allocated.  So we need to free
12425 	 * it if SACK is disabled.
12426 	 */
12427 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12428 	    (tcp->tcp_snd_sack_ok ||
12429 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12430 		/* This should be true only in the passive case. */
12431 		if (tcp->tcp_sack_info == NULL) {
12432 			ASSERT(TCP_IS_DETACHED(tcp));
12433 			tcp->tcp_sack_info =
12434 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12435 		}
12436 		if (tcp->tcp_sack_info == NULL) {
12437 			tcp->tcp_snd_sack_ok = B_FALSE;
12438 		} else {
12439 			tcp->tcp_snd_sack_ok = B_TRUE;
12440 			if (tcp->tcp_snd_ts_ok) {
12441 				tcp->tcp_max_sack_blk = 3;
12442 			} else {
12443 				tcp->tcp_max_sack_blk = 4;
12444 			}
12445 		}
12446 	} else {
12447 		/*
12448 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12449 		 * no SACK info will be used for this
12450 		 * connection.  This assumes that SACK usage
12451 		 * permission is negotiated.  This may need
12452 		 * to be changed once this is clarified.
12453 		 */
12454 		if (tcp->tcp_sack_info != NULL) {
12455 			ASSERT(tcp->tcp_notsack_list == NULL);
12456 			kmem_cache_free(tcp_sack_info_cache,
12457 			    tcp->tcp_sack_info);
12458 			tcp->tcp_sack_info = NULL;
12459 		}
12460 		tcp->tcp_snd_sack_ok = B_FALSE;
12461 	}
12462 
12463 	/*
12464 	 * Now we know the exact TCP/IP header length, subtract
12465 	 * that from tcp_mss to get our side's MSS.
12466 	 */
12467 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12468 	/*
12469 	 * Here we assume that the other side's header size will be equal to
12470 	 * our header size.  We calculate the real MSS accordingly.  Need to
12471 	 * take into additional stuffs IPsec puts in.
12472 	 *
12473 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12474 	 */
12475 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12476 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12477 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12478 
12479 	/*
12480 	 * Set MSS to the smaller one of both ends of the connection.
12481 	 * We should not have called tcp_mss_set() before, but our
12482 	 * side of the MSS should have been set to a proper value
12483 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12484 	 * STREAM head parameters properly.
12485 	 *
12486 	 * If we have a larger-than-16-bit window but the other side
12487 	 * didn't want to do window scale, tcp_rwnd_set() will take
12488 	 * care of that.
12489 	 */
12490 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12491 }
12492 
12493 /*
12494  * Sends the T_CONN_IND to the listener. The caller calls this
12495  * functions via squeue to get inside the listener's perimeter
12496  * once the 3 way hand shake is done a T_CONN_IND needs to be
12497  * sent. As an optimization, the caller can call this directly
12498  * if listener's perimeter is same as eager's.
12499  */
12500 /* ARGSUSED */
12501 void
12502 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12503 {
12504 	conn_t			*lconnp = (conn_t *)arg;
12505 	tcp_t			*listener = lconnp->conn_tcp;
12506 	tcp_t			*tcp;
12507 	struct T_conn_ind	*conn_ind;
12508 	ipaddr_t 		*addr_cache;
12509 	boolean_t		need_send_conn_ind = B_FALSE;
12510 	tcp_stack_t		*tcps = listener->tcp_tcps;
12511 
12512 	/* retrieve the eager */
12513 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12514 	ASSERT(conn_ind->OPT_offset != 0 &&
12515 	    conn_ind->OPT_length == sizeof (intptr_t));
12516 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12517 	    conn_ind->OPT_length);
12518 
12519 	/*
12520 	 * TLI/XTI applications will get confused by
12521 	 * sending eager as an option since it violates
12522 	 * the option semantics. So remove the eager as
12523 	 * option since TLI/XTI app doesn't need it anyway.
12524 	 */
12525 	if (!TCP_IS_SOCKET(listener)) {
12526 		conn_ind->OPT_length = 0;
12527 		conn_ind->OPT_offset = 0;
12528 	}
12529 	if (listener->tcp_state == TCPS_CLOSED ||
12530 	    TCP_IS_DETACHED(listener)) {
12531 		/*
12532 		 * If listener has closed, it would have caused a
12533 		 * a cleanup/blowoff to happen for the eager. We
12534 		 * just need to return.
12535 		 */
12536 		freemsg(mp);
12537 		return;
12538 	}
12539 
12540 
12541 	/*
12542 	 * if the conn_req_q is full defer passing up the
12543 	 * T_CONN_IND until space is availabe after t_accept()
12544 	 * processing
12545 	 */
12546 	mutex_enter(&listener->tcp_eager_lock);
12547 
12548 	/*
12549 	 * Take the eager out, if it is in the list of droppable eagers
12550 	 * as we are here because the 3W handshake is over.
12551 	 */
12552 	MAKE_UNDROPPABLE(tcp);
12553 
12554 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12555 		tcp_t *tail;
12556 
12557 		/*
12558 		 * The eager already has an extra ref put in tcp_rput_data
12559 		 * so that it stays till accept comes back even though it
12560 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12561 		 */
12562 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12563 		listener->tcp_conn_req_cnt_q0--;
12564 		listener->tcp_conn_req_cnt_q++;
12565 
12566 		/* Move from SYN_RCVD to ESTABLISHED list  */
12567 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12568 		    tcp->tcp_eager_prev_q0;
12569 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12570 		    tcp->tcp_eager_next_q0;
12571 		tcp->tcp_eager_prev_q0 = NULL;
12572 		tcp->tcp_eager_next_q0 = NULL;
12573 
12574 		/*
12575 		 * Insert at end of the queue because sockfs
12576 		 * sends down T_CONN_RES in chronological
12577 		 * order. Leaving the older conn indications
12578 		 * at front of the queue helps reducing search
12579 		 * time.
12580 		 */
12581 		tail = listener->tcp_eager_last_q;
12582 		if (tail != NULL)
12583 			tail->tcp_eager_next_q = tcp;
12584 		else
12585 			listener->tcp_eager_next_q = tcp;
12586 		listener->tcp_eager_last_q = tcp;
12587 		tcp->tcp_eager_next_q = NULL;
12588 		/*
12589 		 * Delay sending up the T_conn_ind until we are
12590 		 * done with the eager. Once we have have sent up
12591 		 * the T_conn_ind, the accept can potentially complete
12592 		 * any time and release the refhold we have on the eager.
12593 		 */
12594 		need_send_conn_ind = B_TRUE;
12595 	} else {
12596 		/*
12597 		 * Defer connection on q0 and set deferred
12598 		 * connection bit true
12599 		 */
12600 		tcp->tcp_conn_def_q0 = B_TRUE;
12601 
12602 		/* take tcp out of q0 ... */
12603 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12604 		    tcp->tcp_eager_next_q0;
12605 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12606 		    tcp->tcp_eager_prev_q0;
12607 
12608 		/* ... and place it at the end of q0 */
12609 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12610 		tcp->tcp_eager_next_q0 = listener;
12611 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12612 		listener->tcp_eager_prev_q0 = tcp;
12613 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12614 	}
12615 
12616 	/* we have timed out before */
12617 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12618 		tcp->tcp_syn_rcvd_timeout = 0;
12619 		listener->tcp_syn_rcvd_timeout--;
12620 		if (listener->tcp_syn_defense &&
12621 		    listener->tcp_syn_rcvd_timeout <=
12622 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12623 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12624 		    listener->tcp_last_rcv_lbolt)) {
12625 			/*
12626 			 * Turn off the defense mode if we
12627 			 * believe the SYN attack is over.
12628 			 */
12629 			listener->tcp_syn_defense = B_FALSE;
12630 			if (listener->tcp_ip_addr_cache) {
12631 				kmem_free((void *)listener->tcp_ip_addr_cache,
12632 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12633 				listener->tcp_ip_addr_cache = NULL;
12634 			}
12635 		}
12636 	}
12637 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12638 	if (addr_cache != NULL) {
12639 		/*
12640 		 * We have finished a 3-way handshake with this
12641 		 * remote host. This proves the IP addr is good.
12642 		 * Cache it!
12643 		 */
12644 		addr_cache[IP_ADDR_CACHE_HASH(
12645 		    tcp->tcp_remote)] = tcp->tcp_remote;
12646 	}
12647 	mutex_exit(&listener->tcp_eager_lock);
12648 	if (need_send_conn_ind)
12649 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
12650 }
12651 
12652 /*
12653  * Send the newconn notification to ulp. The eager is blown off if the
12654  * notification fails.
12655  */
12656 static void
12657 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
12658 {
12659 	if (IPCL_IS_NONSTR(lconnp)) {
12660 		cred_t	*cr;
12661 		pid_t	cpid;
12662 
12663 		cr = msg_getcred(mp, &cpid);
12664 
12665 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
12666 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
12667 		    lconnp->conn_tcp);
12668 
12669 		/* Keep the message around in case of a fallback to TPI */
12670 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
12671 
12672 		/*
12673 		 * Notify the ULP about the newconn. It is guaranteed that no
12674 		 * tcp_accept() call will be made for the eager if the
12675 		 * notification fails, so it's safe to blow it off in that
12676 		 * case.
12677 		 *
12678 		 * The upper handle will be assigned when tcp_accept() is
12679 		 * called.
12680 		 */
12681 		if ((*lconnp->conn_upcalls->su_newconn)
12682 		    (lconnp->conn_upper_handle,
12683 		    (sock_lower_handle_t)econnp,
12684 		    &sock_tcp_downcalls, cr, cpid,
12685 		    &econnp->conn_upcalls) == NULL) {
12686 			/* Failed to allocate a socket */
12687 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
12688 			    tcpEstabResets);
12689 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
12690 			    econnp->conn_tcp->tcp_conn_req_seqnum);
12691 		}
12692 	} else {
12693 		putnext(lconnp->conn_tcp->tcp_rq, mp);
12694 	}
12695 }
12696 
12697 mblk_t *
12698 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12699     uint_t *ifindexp, ip6_pkt_t *ippp)
12700 {
12701 	ip_pktinfo_t	*pinfo;
12702 	ip6_t		*ip6h;
12703 	uchar_t		*rptr;
12704 	mblk_t		*first_mp = mp;
12705 	boolean_t	mctl_present = B_FALSE;
12706 	uint_t 		ifindex = 0;
12707 	ip6_pkt_t	ipp;
12708 	uint_t		ipvers;
12709 	uint_t		ip_hdr_len;
12710 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12711 
12712 	rptr = mp->b_rptr;
12713 	ASSERT(OK_32PTR(rptr));
12714 	ASSERT(tcp != NULL);
12715 	ipp.ipp_fields = 0;
12716 
12717 	switch DB_TYPE(mp) {
12718 	case M_CTL:
12719 		mp = mp->b_cont;
12720 		if (mp == NULL) {
12721 			freemsg(first_mp);
12722 			return (NULL);
12723 		}
12724 		if (DB_TYPE(mp) != M_DATA) {
12725 			freemsg(first_mp);
12726 			return (NULL);
12727 		}
12728 		mctl_present = B_TRUE;
12729 		break;
12730 	case M_DATA:
12731 		break;
12732 	default:
12733 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12734 		freemsg(mp);
12735 		return (NULL);
12736 	}
12737 	ipvers = IPH_HDR_VERSION(rptr);
12738 	if (ipvers == IPV4_VERSION) {
12739 		if (tcp == NULL) {
12740 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12741 			goto done;
12742 		}
12743 
12744 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12745 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12746 
12747 		/*
12748 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12749 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12750 		 */
12751 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12752 		    mctl_present) {
12753 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12754 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12755 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12756 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12757 				ipp.ipp_fields |= IPPF_IFINDEX;
12758 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12759 				ifindex = pinfo->ip_pkt_ifindex;
12760 			}
12761 			freeb(first_mp);
12762 			mctl_present = B_FALSE;
12763 		}
12764 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12765 	} else {
12766 		ip6h = (ip6_t *)rptr;
12767 
12768 		ASSERT(ipvers == IPV6_VERSION);
12769 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12770 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12771 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12772 
12773 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12774 			uint8_t	nexthdrp;
12775 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12776 
12777 			/* Look for ifindex information */
12778 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12779 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12780 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12781 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12782 					freemsg(first_mp);
12783 					return (NULL);
12784 				}
12785 
12786 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12787 					ASSERT(ip6i->ip6i_ifindex != 0);
12788 					ipp.ipp_fields |= IPPF_IFINDEX;
12789 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12790 					ifindex = ip6i->ip6i_ifindex;
12791 				}
12792 				rptr = (uchar_t *)&ip6i[1];
12793 				mp->b_rptr = rptr;
12794 				if (rptr == mp->b_wptr) {
12795 					mblk_t *mp1;
12796 					mp1 = mp->b_cont;
12797 					freeb(mp);
12798 					mp = mp1;
12799 					rptr = mp->b_rptr;
12800 				}
12801 				if (MBLKL(mp) < IPV6_HDR_LEN +
12802 				    sizeof (tcph_t)) {
12803 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12804 					freemsg(first_mp);
12805 					return (NULL);
12806 				}
12807 				ip6h = (ip6_t *)rptr;
12808 			}
12809 
12810 			/*
12811 			 * Find any potentially interesting extension headers
12812 			 * as well as the length of the IPv6 + extension
12813 			 * headers.
12814 			 */
12815 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12816 			/* Verify if this is a TCP packet */
12817 			if (nexthdrp != IPPROTO_TCP) {
12818 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12819 				freemsg(first_mp);
12820 				return (NULL);
12821 			}
12822 		} else {
12823 			ip_hdr_len = IPV6_HDR_LEN;
12824 		}
12825 	}
12826 
12827 done:
12828 	if (ipversp != NULL)
12829 		*ipversp = ipvers;
12830 	if (ip_hdr_lenp != NULL)
12831 		*ip_hdr_lenp = ip_hdr_len;
12832 	if (ippp != NULL)
12833 		*ippp = ipp;
12834 	if (ifindexp != NULL)
12835 		*ifindexp = ifindex;
12836 	if (mctl_present) {
12837 		freeb(first_mp);
12838 	}
12839 	return (mp);
12840 }
12841 
12842 /*
12843  * Handle M_DATA messages from IP. Its called directly from IP via
12844  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12845  * in this path.
12846  *
12847  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12848  * v4 and v6), we are called through tcp_input() and a M_CTL can
12849  * be present for options but tcp_find_pktinfo() deals with it. We
12850  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12851  *
12852  * The first argument is always the connp/tcp to which the mp belongs.
12853  * There are no exceptions to this rule. The caller has already put
12854  * a reference on this connp/tcp and once tcp_rput_data() returns,
12855  * the squeue will do the refrele.
12856  *
12857  * The TH_SYN for the listener directly go to tcp_conn_request via
12858  * squeue.
12859  *
12860  * sqp: NULL = recursive, sqp != NULL means called from squeue
12861  */
12862 void
12863 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12864 {
12865 	int32_t		bytes_acked;
12866 	int32_t		gap;
12867 	mblk_t		*mp1;
12868 	uint_t		flags;
12869 	uint32_t	new_swnd = 0;
12870 	uchar_t		*iphdr;
12871 	uchar_t		*rptr;
12872 	int32_t		rgap;
12873 	uint32_t	seg_ack;
12874 	int		seg_len;
12875 	uint_t		ip_hdr_len;
12876 	uint32_t	seg_seq;
12877 	tcph_t		*tcph;
12878 	int		urp;
12879 	tcp_opt_t	tcpopt;
12880 	uint_t		ipvers;
12881 	ip6_pkt_t	ipp;
12882 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12883 	uint32_t	cwnd;
12884 	uint32_t	add;
12885 	int		npkt;
12886 	int		mss;
12887 	conn_t		*connp = (conn_t *)arg;
12888 	squeue_t	*sqp = (squeue_t *)arg2;
12889 	tcp_t		*tcp = connp->conn_tcp;
12890 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12891 
12892 	/*
12893 	 * RST from fused tcp loopback peer should trigger an unfuse.
12894 	 */
12895 	if (tcp->tcp_fused) {
12896 		TCP_STAT(tcps, tcp_fusion_aborted);
12897 		tcp_unfuse(tcp);
12898 	}
12899 
12900 	iphdr = mp->b_rptr;
12901 	rptr = mp->b_rptr;
12902 	ASSERT(OK_32PTR(rptr));
12903 
12904 	/*
12905 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12906 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12907 	 * necessary information.
12908 	 */
12909 	if (IPCL_IS_TCP4(connp)) {
12910 		ipvers = IPV4_VERSION;
12911 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12912 	} else {
12913 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12914 		    NULL, &ipp);
12915 		if (mp == NULL) {
12916 			TCP_STAT(tcps, tcp_rput_v6_error);
12917 			return;
12918 		}
12919 		iphdr = mp->b_rptr;
12920 		rptr = mp->b_rptr;
12921 	}
12922 	ASSERT(DB_TYPE(mp) == M_DATA);
12923 	ASSERT(mp->b_next == NULL);
12924 
12925 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12926 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12927 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12928 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12929 	seg_len = (int)(mp->b_wptr - rptr) -
12930 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12931 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12932 		do {
12933 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12934 			    (uintptr_t)INT_MAX);
12935 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12936 		} while ((mp1 = mp1->b_cont) != NULL &&
12937 		    mp1->b_datap->db_type == M_DATA);
12938 	}
12939 
12940 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12941 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12942 		    seg_len, tcph);
12943 		return;
12944 	}
12945 
12946 	if (sqp != NULL) {
12947 		/*
12948 		 * This is the correct place to update tcp_last_recv_time. Note
12949 		 * that it is also updated for tcp structure that belongs to
12950 		 * global and listener queues which do not really need updating.
12951 		 * But that should not cause any harm.  And it is updated for
12952 		 * all kinds of incoming segments, not only for data segments.
12953 		 */
12954 		tcp->tcp_last_recv_time = lbolt;
12955 	}
12956 
12957 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12958 
12959 	BUMP_LOCAL(tcp->tcp_ibsegs);
12960 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
12961 
12962 	if ((flags & TH_URG) && sqp != NULL) {
12963 		/*
12964 		 * TCP can't handle urgent pointers that arrive before
12965 		 * the connection has been accept()ed since it can't
12966 		 * buffer OOB data.  Discard segment if this happens.
12967 		 *
12968 		 * We can't just rely on a non-null tcp_listener to indicate
12969 		 * that the accept() has completed since unlinking of the
12970 		 * eager and completion of the accept are not atomic.
12971 		 * tcp_detached, when it is not set (B_FALSE) indicates
12972 		 * that the accept() has completed.
12973 		 *
12974 		 * Nor can it reassemble urgent pointers, so discard
12975 		 * if it's not the next segment expected.
12976 		 *
12977 		 * Otherwise, collapse chain into one mblk (discard if
12978 		 * that fails).  This makes sure the headers, retransmitted
12979 		 * data, and new data all are in the same mblk.
12980 		 */
12981 		ASSERT(mp != NULL);
12982 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
12983 			freemsg(mp);
12984 			return;
12985 		}
12986 		/* Update pointers into message */
12987 		iphdr = rptr = mp->b_rptr;
12988 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12989 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12990 			/*
12991 			 * Since we can't handle any data with this urgent
12992 			 * pointer that is out of sequence, we expunge
12993 			 * the data.  This allows us to still register
12994 			 * the urgent mark and generate the M_PCSIG,
12995 			 * which we can do.
12996 			 */
12997 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12998 			seg_len = 0;
12999 		}
13000 	}
13001 
13002 	switch (tcp->tcp_state) {
13003 	case TCPS_SYN_SENT:
13004 		if (flags & TH_ACK) {
13005 			/*
13006 			 * Note that our stack cannot send data before a
13007 			 * connection is established, therefore the
13008 			 * following check is valid.  Otherwise, it has
13009 			 * to be changed.
13010 			 */
13011 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13012 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13013 				freemsg(mp);
13014 				if (flags & TH_RST)
13015 					return;
13016 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13017 				    tcp, seg_ack, 0, TH_RST);
13018 				return;
13019 			}
13020 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13021 		}
13022 		if (flags & TH_RST) {
13023 			freemsg(mp);
13024 			if (flags & TH_ACK)
13025 				(void) tcp_clean_death(tcp,
13026 				    ECONNREFUSED, 13);
13027 			return;
13028 		}
13029 		if (!(flags & TH_SYN)) {
13030 			freemsg(mp);
13031 			return;
13032 		}
13033 
13034 		/* Process all TCP options. */
13035 		tcp_process_options(tcp, tcph);
13036 		/*
13037 		 * The following changes our rwnd to be a multiple of the
13038 		 * MIN(peer MSS, our MSS) for performance reason.
13039 		 */
13040 		(void) tcp_rwnd_set(tcp,
13041 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
13042 
13043 		/* Is the other end ECN capable? */
13044 		if (tcp->tcp_ecn_ok) {
13045 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13046 				tcp->tcp_ecn_ok = B_FALSE;
13047 			}
13048 		}
13049 		/*
13050 		 * Clear ECN flags because it may interfere with later
13051 		 * processing.
13052 		 */
13053 		flags &= ~(TH_ECE|TH_CWR);
13054 
13055 		tcp->tcp_irs = seg_seq;
13056 		tcp->tcp_rack = seg_seq;
13057 		tcp->tcp_rnxt = seg_seq + 1;
13058 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13059 		if (!TCP_IS_DETACHED(tcp)) {
13060 			/* Allocate room for SACK options if needed. */
13061 			if (tcp->tcp_snd_sack_ok) {
13062 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13063 				    tcp->tcp_hdr_len +
13064 				    TCPOPT_MAX_SACK_LEN +
13065 				    (tcp->tcp_loopback ? 0 :
13066 				    tcps->tcps_wroff_xtra));
13067 			} else {
13068 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13069 				    tcp->tcp_hdr_len +
13070 				    (tcp->tcp_loopback ? 0 :
13071 				    tcps->tcps_wroff_xtra));
13072 			}
13073 		}
13074 		if (flags & TH_ACK) {
13075 			/*
13076 			 * If we can't get the confirmation upstream, pretend
13077 			 * we didn't even see this one.
13078 			 *
13079 			 * XXX: how can we pretend we didn't see it if we
13080 			 * have updated rnxt et. al.
13081 			 *
13082 			 * For loopback we defer sending up the T_CONN_CON
13083 			 * until after some checks below.
13084 			 */
13085 			mp1 = NULL;
13086 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13087 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13088 				freemsg(mp);
13089 				return;
13090 			}
13091 			/* SYN was acked - making progress */
13092 			if (tcp->tcp_ipversion == IPV6_VERSION)
13093 				tcp->tcp_ip_forward_progress = B_TRUE;
13094 
13095 			/* One for the SYN */
13096 			tcp->tcp_suna = tcp->tcp_iss + 1;
13097 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13098 			tcp->tcp_state = TCPS_ESTABLISHED;
13099 
13100 			/*
13101 			 * If SYN was retransmitted, need to reset all
13102 			 * retransmission info.  This is because this
13103 			 * segment will be treated as a dup ACK.
13104 			 */
13105 			if (tcp->tcp_rexmit) {
13106 				tcp->tcp_rexmit = B_FALSE;
13107 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13108 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13109 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13110 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13111 				tcp->tcp_ms_we_have_waited = 0;
13112 
13113 				/*
13114 				 * Set tcp_cwnd back to 1 MSS, per
13115 				 * recommendation from
13116 				 * draft-floyd-incr-init-win-01.txt,
13117 				 * Increasing TCP's Initial Window.
13118 				 */
13119 				tcp->tcp_cwnd = tcp->tcp_mss;
13120 			}
13121 
13122 			tcp->tcp_swl1 = seg_seq;
13123 			tcp->tcp_swl2 = seg_ack;
13124 
13125 			new_swnd = BE16_TO_U16(tcph->th_win);
13126 			tcp->tcp_swnd = new_swnd;
13127 			if (new_swnd > tcp->tcp_max_swnd)
13128 				tcp->tcp_max_swnd = new_swnd;
13129 
13130 			/*
13131 			 * Always send the three-way handshake ack immediately
13132 			 * in order to make the connection complete as soon as
13133 			 * possible on the accepting host.
13134 			 */
13135 			flags |= TH_ACK_NEEDED;
13136 
13137 			/*
13138 			 * Special case for loopback.  At this point we have
13139 			 * received SYN-ACK from the remote endpoint.  In
13140 			 * order to ensure that both endpoints reach the
13141 			 * fused state prior to any data exchange, the final
13142 			 * ACK needs to be sent before we indicate T_CONN_CON
13143 			 * to the module upstream.
13144 			 */
13145 			if (tcp->tcp_loopback) {
13146 				mblk_t *ack_mp;
13147 
13148 				ASSERT(!tcp->tcp_unfusable);
13149 				ASSERT(mp1 != NULL);
13150 				/*
13151 				 * For loopback, we always get a pure SYN-ACK
13152 				 * and only need to send back the final ACK
13153 				 * with no data (this is because the other
13154 				 * tcp is ours and we don't do T/TCP).  This
13155 				 * final ACK triggers the passive side to
13156 				 * perform fusion in ESTABLISHED state.
13157 				 */
13158 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13159 					if (tcp->tcp_ack_tid != 0) {
13160 						(void) TCP_TIMER_CANCEL(tcp,
13161 						    tcp->tcp_ack_tid);
13162 						tcp->tcp_ack_tid = 0;
13163 					}
13164 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13165 					BUMP_LOCAL(tcp->tcp_obsegs);
13166 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13167 
13168 					if (!IPCL_IS_NONSTR(connp)) {
13169 						/* Send up T_CONN_CON */
13170 						putnext(tcp->tcp_rq, mp1);
13171 					} else {
13172 						cred_t	*cr;
13173 						pid_t	cpid;
13174 
13175 						cr = msg_getcred(mp1, &cpid);
13176 						(*connp->conn_upcalls->
13177 						    su_connected)
13178 						    (connp->conn_upper_handle,
13179 						    tcp->tcp_connid, cr, cpid);
13180 						freemsg(mp1);
13181 					}
13182 
13183 					freemsg(mp);
13184 					return;
13185 				}
13186 				/*
13187 				 * Forget fusion; we need to handle more
13188 				 * complex cases below.  Send the deferred
13189 				 * T_CONN_CON message upstream and proceed
13190 				 * as usual.  Mark this tcp as not capable
13191 				 * of fusion.
13192 				 */
13193 				TCP_STAT(tcps, tcp_fusion_unfusable);
13194 				tcp->tcp_unfusable = B_TRUE;
13195 				if (!IPCL_IS_NONSTR(connp)) {
13196 					putnext(tcp->tcp_rq, mp1);
13197 				} else {
13198 					cred_t	*cr;
13199 					pid_t	cpid;
13200 
13201 					cr = msg_getcred(mp1, &cpid);
13202 					(*connp->conn_upcalls->su_connected)
13203 					    (connp->conn_upper_handle,
13204 					    tcp->tcp_connid, cr, cpid);
13205 					freemsg(mp1);
13206 				}
13207 			}
13208 
13209 			/*
13210 			 * Check to see if there is data to be sent.  If
13211 			 * yes, set the transmit flag.  Then check to see
13212 			 * if received data processing needs to be done.
13213 			 * If not, go straight to xmit_check.  This short
13214 			 * cut is OK as we don't support T/TCP.
13215 			 */
13216 			if (tcp->tcp_unsent)
13217 				flags |= TH_XMIT_NEEDED;
13218 
13219 			if (seg_len == 0 && !(flags & TH_URG)) {
13220 				freemsg(mp);
13221 				goto xmit_check;
13222 			}
13223 
13224 			flags &= ~TH_SYN;
13225 			seg_seq++;
13226 			break;
13227 		}
13228 		tcp->tcp_state = TCPS_SYN_RCVD;
13229 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13230 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13231 		if (mp1) {
13232 			/*
13233 			 * See comment in tcp_conn_request() for why we use
13234 			 * the open() time pid here.
13235 			 */
13236 			DB_CPID(mp1) = tcp->tcp_cpid;
13237 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13238 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13239 		}
13240 		freemsg(mp);
13241 		return;
13242 	case TCPS_SYN_RCVD:
13243 		if (flags & TH_ACK) {
13244 			/*
13245 			 * In this state, a SYN|ACK packet is either bogus
13246 			 * because the other side must be ACKing our SYN which
13247 			 * indicates it has seen the ACK for their SYN and
13248 			 * shouldn't retransmit it or we're crossing SYNs
13249 			 * on active open.
13250 			 */
13251 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13252 				freemsg(mp);
13253 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13254 				    tcp, seg_ack, 0, TH_RST);
13255 				return;
13256 			}
13257 			/*
13258 			 * NOTE: RFC 793 pg. 72 says this should be
13259 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13260 			 * but that would mean we have an ack that ignored
13261 			 * our SYN.
13262 			 */
13263 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13264 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13265 				freemsg(mp);
13266 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13267 				    tcp, seg_ack, 0, TH_RST);
13268 				return;
13269 			}
13270 		}
13271 		break;
13272 	case TCPS_LISTEN:
13273 		/*
13274 		 * Only a TLI listener can come through this path when a
13275 		 * acceptor is going back to be a listener and a packet
13276 		 * for the acceptor hits the classifier. For a socket
13277 		 * listener, this can never happen because a listener
13278 		 * can never accept connection on itself and hence a
13279 		 * socket acceptor can not go back to being a listener.
13280 		 */
13281 		ASSERT(!TCP_IS_SOCKET(tcp));
13282 		/*FALLTHRU*/
13283 	case TCPS_CLOSED:
13284 	case TCPS_BOUND: {
13285 		conn_t	*new_connp;
13286 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13287 
13288 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13289 		if (new_connp != NULL) {
13290 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13291 			return;
13292 		}
13293 		/* We failed to classify. For now just drop the packet */
13294 		freemsg(mp);
13295 		return;
13296 	}
13297 	case TCPS_IDLE:
13298 		/*
13299 		 * Handle the case where the tcp_clean_death() has happened
13300 		 * on a connection (application hasn't closed yet) but a packet
13301 		 * was already queued on squeue before tcp_clean_death()
13302 		 * was processed. Calling tcp_clean_death() twice on same
13303 		 * connection can result in weird behaviour.
13304 		 */
13305 		freemsg(mp);
13306 		return;
13307 	default:
13308 		break;
13309 	}
13310 
13311 	/*
13312 	 * Already on the correct queue/perimeter.
13313 	 * If this is a detached connection and not an eager
13314 	 * connection hanging off a listener then new data
13315 	 * (past the FIN) will cause a reset.
13316 	 * We do a special check here where it
13317 	 * is out of the main line, rather than check
13318 	 * if we are detached every time we see new
13319 	 * data down below.
13320 	 */
13321 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13322 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13323 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13324 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13325 
13326 		freemsg(mp);
13327 		/*
13328 		 * This could be an SSL closure alert. We're detached so just
13329 		 * acknowledge it this last time.
13330 		 */
13331 		if (tcp->tcp_kssl_ctx != NULL) {
13332 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13333 			tcp->tcp_kssl_ctx = NULL;
13334 
13335 			tcp->tcp_rnxt += seg_len;
13336 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13337 			flags |= TH_ACK_NEEDED;
13338 			goto ack_check;
13339 		}
13340 
13341 		tcp_xmit_ctl("new data when detached", tcp,
13342 		    tcp->tcp_snxt, 0, TH_RST);
13343 		(void) tcp_clean_death(tcp, EPROTO, 12);
13344 		return;
13345 	}
13346 
13347 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13348 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13349 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13350 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13351 
13352 	if (tcp->tcp_snd_ts_ok) {
13353 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13354 			/*
13355 			 * This segment is not acceptable.
13356 			 * Drop it and send back an ACK.
13357 			 */
13358 			freemsg(mp);
13359 			flags |= TH_ACK_NEEDED;
13360 			goto ack_check;
13361 		}
13362 	} else if (tcp->tcp_snd_sack_ok) {
13363 		ASSERT(tcp->tcp_sack_info != NULL);
13364 		tcpopt.tcp = tcp;
13365 		/*
13366 		 * SACK info in already updated in tcp_parse_options.  Ignore
13367 		 * all other TCP options...
13368 		 */
13369 		(void) tcp_parse_options(tcph, &tcpopt);
13370 	}
13371 try_again:;
13372 	mss = tcp->tcp_mss;
13373 	gap = seg_seq - tcp->tcp_rnxt;
13374 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13375 	/*
13376 	 * gap is the amount of sequence space between what we expect to see
13377 	 * and what we got for seg_seq.  A positive value for gap means
13378 	 * something got lost.  A negative value means we got some old stuff.
13379 	 */
13380 	if (gap < 0) {
13381 		/* Old stuff present.  Is the SYN in there? */
13382 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13383 		    (seg_len != 0)) {
13384 			flags &= ~TH_SYN;
13385 			seg_seq++;
13386 			urp--;
13387 			/* Recompute the gaps after noting the SYN. */
13388 			goto try_again;
13389 		}
13390 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13391 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13392 		    (seg_len > -gap ? -gap : seg_len));
13393 		/* Remove the old stuff from seg_len. */
13394 		seg_len += gap;
13395 		/*
13396 		 * Anything left?
13397 		 * Make sure to check for unack'd FIN when rest of data
13398 		 * has been previously ack'd.
13399 		 */
13400 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13401 			/*
13402 			 * Resets are only valid if they lie within our offered
13403 			 * window.  If the RST bit is set, we just ignore this
13404 			 * segment.
13405 			 */
13406 			if (flags & TH_RST) {
13407 				freemsg(mp);
13408 				return;
13409 			}
13410 
13411 			/*
13412 			 * The arriving of dup data packets indicate that we
13413 			 * may have postponed an ack for too long, or the other
13414 			 * side's RTT estimate is out of shape. Start acking
13415 			 * more often.
13416 			 */
13417 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13418 			    tcp->tcp_rack_cnt >= 1 &&
13419 			    tcp->tcp_rack_abs_max > 2) {
13420 				tcp->tcp_rack_abs_max--;
13421 			}
13422 			tcp->tcp_rack_cur_max = 1;
13423 
13424 			/*
13425 			 * This segment is "unacceptable".  None of its
13426 			 * sequence space lies within our advertized window.
13427 			 *
13428 			 * Adjust seg_len to the original value for tracing.
13429 			 */
13430 			seg_len -= gap;
13431 			if (tcp->tcp_debug) {
13432 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13433 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13434 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13435 				    "seg_len %d, rnxt %u, snxt %u, %s",
13436 				    gap, rgap, flags, seg_seq, seg_ack,
13437 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13438 				    tcp_display(tcp, NULL,
13439 				    DISP_ADDR_AND_PORT));
13440 			}
13441 
13442 			/*
13443 			 * Arrange to send an ACK in response to the
13444 			 * unacceptable segment per RFC 793 page 69. There
13445 			 * is only one small difference between ours and the
13446 			 * acceptability test in the RFC - we accept ACK-only
13447 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13448 			 * will be generated.
13449 			 *
13450 			 * Note that we have to ACK an ACK-only packet at least
13451 			 * for stacks that send 0-length keep-alives with
13452 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13453 			 * section 4.2.3.6. As long as we don't ever generate
13454 			 * an unacceptable packet in response to an incoming
13455 			 * packet that is unacceptable, it should not cause
13456 			 * "ACK wars".
13457 			 */
13458 			flags |=  TH_ACK_NEEDED;
13459 
13460 			/*
13461 			 * Continue processing this segment in order to use the
13462 			 * ACK information it contains, but skip all other
13463 			 * sequence-number processing.	Processing the ACK
13464 			 * information is necessary in order to
13465 			 * re-synchronize connections that may have lost
13466 			 * synchronization.
13467 			 *
13468 			 * We clear seg_len and flag fields related to
13469 			 * sequence number processing as they are not
13470 			 * to be trusted for an unacceptable segment.
13471 			 */
13472 			seg_len = 0;
13473 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13474 			goto process_ack;
13475 		}
13476 
13477 		/* Fix seg_seq, and chew the gap off the front. */
13478 		seg_seq = tcp->tcp_rnxt;
13479 		urp += gap;
13480 		do {
13481 			mblk_t	*mp2;
13482 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13483 			    (uintptr_t)UINT_MAX);
13484 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13485 			if (gap > 0) {
13486 				mp->b_rptr = mp->b_wptr - gap;
13487 				break;
13488 			}
13489 			mp2 = mp;
13490 			mp = mp->b_cont;
13491 			freeb(mp2);
13492 		} while (gap < 0);
13493 		/*
13494 		 * If the urgent data has already been acknowledged, we
13495 		 * should ignore TH_URG below
13496 		 */
13497 		if (urp < 0)
13498 			flags &= ~TH_URG;
13499 	}
13500 	/*
13501 	 * rgap is the amount of stuff received out of window.  A negative
13502 	 * value is the amount out of window.
13503 	 */
13504 	if (rgap < 0) {
13505 		mblk_t	*mp2;
13506 
13507 		if (tcp->tcp_rwnd == 0) {
13508 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13509 		} else {
13510 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13511 			UPDATE_MIB(&tcps->tcps_mib,
13512 			    tcpInDataPastWinBytes, -rgap);
13513 		}
13514 
13515 		/*
13516 		 * seg_len does not include the FIN, so if more than
13517 		 * just the FIN is out of window, we act like we don't
13518 		 * see it.  (If just the FIN is out of window, rgap
13519 		 * will be zero and we will go ahead and acknowledge
13520 		 * the FIN.)
13521 		 */
13522 		flags &= ~TH_FIN;
13523 
13524 		/* Fix seg_len and make sure there is something left. */
13525 		seg_len += rgap;
13526 		if (seg_len <= 0) {
13527 			/*
13528 			 * Resets are only valid if they lie within our offered
13529 			 * window.  If the RST bit is set, we just ignore this
13530 			 * segment.
13531 			 */
13532 			if (flags & TH_RST) {
13533 				freemsg(mp);
13534 				return;
13535 			}
13536 
13537 			/* Per RFC 793, we need to send back an ACK. */
13538 			flags |= TH_ACK_NEEDED;
13539 
13540 			/*
13541 			 * Send SIGURG as soon as possible i.e. even
13542 			 * if the TH_URG was delivered in a window probe
13543 			 * packet (which will be unacceptable).
13544 			 *
13545 			 * We generate a signal if none has been generated
13546 			 * for this connection or if this is a new urgent
13547 			 * byte. Also send a zero-length "unmarked" message
13548 			 * to inform SIOCATMARK that this is not the mark.
13549 			 *
13550 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13551 			 * is sent up. This plus the check for old data
13552 			 * (gap >= 0) handles the wraparound of the sequence
13553 			 * number space without having to always track the
13554 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13555 			 * this max in its rcv_up variable).
13556 			 *
13557 			 * This prevents duplicate SIGURGS due to a "late"
13558 			 * zero-window probe when the T_EXDATA_IND has already
13559 			 * been sent up.
13560 			 */
13561 			if ((flags & TH_URG) &&
13562 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13563 			    tcp->tcp_urp_last))) {
13564 				if (IPCL_IS_NONSTR(connp)) {
13565 					if (!TCP_IS_DETACHED(tcp)) {
13566 						(*connp->conn_upcalls->
13567 						    su_signal_oob)
13568 						    (connp->conn_upper_handle,
13569 						    urp);
13570 					}
13571 				} else {
13572 					mp1 = allocb(0, BPRI_MED);
13573 					if (mp1 == NULL) {
13574 						freemsg(mp);
13575 						return;
13576 					}
13577 					if (!TCP_IS_DETACHED(tcp) &&
13578 					    !putnextctl1(tcp->tcp_rq,
13579 					    M_PCSIG, SIGURG)) {
13580 						/* Try again on the rexmit. */
13581 						freemsg(mp1);
13582 						freemsg(mp);
13583 						return;
13584 					}
13585 					/*
13586 					 * If the next byte would be the mark
13587 					 * then mark with MARKNEXT else mark
13588 					 * with NOTMARKNEXT.
13589 					 */
13590 					if (gap == 0 && urp == 0)
13591 						mp1->b_flag |= MSGMARKNEXT;
13592 					else
13593 						mp1->b_flag |= MSGNOTMARKNEXT;
13594 					freemsg(tcp->tcp_urp_mark_mp);
13595 					tcp->tcp_urp_mark_mp = mp1;
13596 					flags |= TH_SEND_URP_MARK;
13597 				}
13598 				tcp->tcp_urp_last_valid = B_TRUE;
13599 				tcp->tcp_urp_last = urp + seg_seq;
13600 			}
13601 			/*
13602 			 * If this is a zero window probe, continue to
13603 			 * process the ACK part.  But we need to set seg_len
13604 			 * to 0 to avoid data processing.  Otherwise just
13605 			 * drop the segment and send back an ACK.
13606 			 */
13607 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13608 				flags &= ~(TH_SYN | TH_URG);
13609 				seg_len = 0;
13610 				goto process_ack;
13611 			} else {
13612 				freemsg(mp);
13613 				goto ack_check;
13614 			}
13615 		}
13616 		/* Pitch out of window stuff off the end. */
13617 		rgap = seg_len;
13618 		mp2 = mp;
13619 		do {
13620 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13621 			    (uintptr_t)INT_MAX);
13622 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13623 			if (rgap < 0) {
13624 				mp2->b_wptr += rgap;
13625 				if ((mp1 = mp2->b_cont) != NULL) {
13626 					mp2->b_cont = NULL;
13627 					freemsg(mp1);
13628 				}
13629 				break;
13630 			}
13631 		} while ((mp2 = mp2->b_cont) != NULL);
13632 	}
13633 ok:;
13634 	/*
13635 	 * TCP should check ECN info for segments inside the window only.
13636 	 * Therefore the check should be done here.
13637 	 */
13638 	if (tcp->tcp_ecn_ok) {
13639 		if (flags & TH_CWR) {
13640 			tcp->tcp_ecn_echo_on = B_FALSE;
13641 		}
13642 		/*
13643 		 * Note that both ECN_CE and CWR can be set in the
13644 		 * same segment.  In this case, we once again turn
13645 		 * on ECN_ECHO.
13646 		 */
13647 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13648 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13649 
13650 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13651 				tcp->tcp_ecn_echo_on = B_TRUE;
13652 			}
13653 		} else {
13654 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13655 
13656 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13657 			    htonl(IPH_ECN_CE << 20)) {
13658 				tcp->tcp_ecn_echo_on = B_TRUE;
13659 			}
13660 		}
13661 	}
13662 
13663 	/*
13664 	 * Check whether we can update tcp_ts_recent.  This test is
13665 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13666 	 * Extensions for High Performance: An Update", Internet Draft.
13667 	 */
13668 	if (tcp->tcp_snd_ts_ok &&
13669 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13670 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13671 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13672 		tcp->tcp_last_rcv_lbolt = lbolt64;
13673 	}
13674 
13675 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13676 		/*
13677 		 * FIN in an out of order segment.  We record this in
13678 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13679 		 * Clear the FIN so that any check on FIN flag will fail.
13680 		 * Remember that FIN also counts in the sequence number
13681 		 * space.  So we need to ack out of order FIN only segments.
13682 		 */
13683 		if (flags & TH_FIN) {
13684 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13685 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13686 			flags &= ~TH_FIN;
13687 			flags |= TH_ACK_NEEDED;
13688 		}
13689 		if (seg_len > 0) {
13690 			/* Fill in the SACK blk list. */
13691 			if (tcp->tcp_snd_sack_ok) {
13692 				ASSERT(tcp->tcp_sack_info != NULL);
13693 				tcp_sack_insert(tcp->tcp_sack_list,
13694 				    seg_seq, seg_seq + seg_len,
13695 				    &(tcp->tcp_num_sack_blk));
13696 			}
13697 
13698 			/*
13699 			 * Attempt reassembly and see if we have something
13700 			 * ready to go.
13701 			 */
13702 			mp = tcp_reass(tcp, mp, seg_seq);
13703 			/* Always ack out of order packets */
13704 			flags |= TH_ACK_NEEDED | TH_PUSH;
13705 			if (mp) {
13706 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13707 				    (uintptr_t)INT_MAX);
13708 				seg_len = mp->b_cont ? msgdsize(mp) :
13709 				    (int)(mp->b_wptr - mp->b_rptr);
13710 				seg_seq = tcp->tcp_rnxt;
13711 				/*
13712 				 * A gap is filled and the seq num and len
13713 				 * of the gap match that of a previously
13714 				 * received FIN, put the FIN flag back in.
13715 				 */
13716 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13717 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13718 					flags |= TH_FIN;
13719 					tcp->tcp_valid_bits &=
13720 					    ~TCP_OFO_FIN_VALID;
13721 				}
13722 			} else {
13723 				/*
13724 				 * Keep going even with NULL mp.
13725 				 * There may be a useful ACK or something else
13726 				 * we don't want to miss.
13727 				 *
13728 				 * But TCP should not perform fast retransmit
13729 				 * because of the ack number.  TCP uses
13730 				 * seg_len == 0 to determine if it is a pure
13731 				 * ACK.  And this is not a pure ACK.
13732 				 */
13733 				seg_len = 0;
13734 				ofo_seg = B_TRUE;
13735 			}
13736 		}
13737 	} else if (seg_len > 0) {
13738 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13739 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13740 		/*
13741 		 * If an out of order FIN was received before, and the seq
13742 		 * num and len of the new segment match that of the FIN,
13743 		 * 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 &= ~TCP_OFO_FIN_VALID;
13749 		}
13750 	}
13751 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13752 	if (flags & TH_RST) {
13753 		freemsg(mp);
13754 		switch (tcp->tcp_state) {
13755 		case TCPS_SYN_RCVD:
13756 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13757 			break;
13758 		case TCPS_ESTABLISHED:
13759 		case TCPS_FIN_WAIT_1:
13760 		case TCPS_FIN_WAIT_2:
13761 		case TCPS_CLOSE_WAIT:
13762 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13763 			break;
13764 		case TCPS_CLOSING:
13765 		case TCPS_LAST_ACK:
13766 			(void) tcp_clean_death(tcp, 0, 16);
13767 			break;
13768 		default:
13769 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13770 			(void) tcp_clean_death(tcp, ENXIO, 17);
13771 			break;
13772 		}
13773 		return;
13774 	}
13775 	if (flags & TH_SYN) {
13776 		/*
13777 		 * See RFC 793, Page 71
13778 		 *
13779 		 * The seq number must be in the window as it should
13780 		 * be "fixed" above.  If it is outside window, it should
13781 		 * be already rejected.  Note that we allow seg_seq to be
13782 		 * rnxt + rwnd because we want to accept 0 window probe.
13783 		 */
13784 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13785 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13786 		freemsg(mp);
13787 		/*
13788 		 * If the ACK flag is not set, just use our snxt as the
13789 		 * seq number of the RST segment.
13790 		 */
13791 		if (!(flags & TH_ACK)) {
13792 			seg_ack = tcp->tcp_snxt;
13793 		}
13794 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13795 		    TH_RST|TH_ACK);
13796 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13797 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13798 		return;
13799 	}
13800 	/*
13801 	 * urp could be -1 when the urp field in the packet is 0
13802 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13803 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13804 	 */
13805 	if (flags & TH_URG && urp >= 0) {
13806 		if (!tcp->tcp_urp_last_valid ||
13807 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13808 			if (IPCL_IS_NONSTR(connp)) {
13809 				if (!TCP_IS_DETACHED(tcp)) {
13810 					(*connp->conn_upcalls->su_signal_oob)
13811 					    (connp->conn_upper_handle, urp);
13812 				}
13813 			} else {
13814 				/*
13815 				 * If we haven't generated the signal yet for
13816 				 * this urgent pointer value, do it now.  Also,
13817 				 * send up a zero-length M_DATA indicating
13818 				 * whether or not this is the mark. The latter
13819 				 * is not needed when a T_EXDATA_IND is sent up.
13820 				 * However, if there are allocation failures
13821 				 * this code relies on the sender retransmitting
13822 				 * and the socket code for determining the mark
13823 				 * should not block waiting for the peer to
13824 				 * transmit. Thus, for simplicity we always
13825 				 * send up the mark indication.
13826 				 */
13827 				mp1 = allocb(0, BPRI_MED);
13828 				if (mp1 == NULL) {
13829 					freemsg(mp);
13830 					return;
13831 				}
13832 				if (!TCP_IS_DETACHED(tcp) &&
13833 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13834 				    SIGURG)) {
13835 					/* Try again on the rexmit. */
13836 					freemsg(mp1);
13837 					freemsg(mp);
13838 					return;
13839 				}
13840 				/*
13841 				 * Mark with NOTMARKNEXT for now.
13842 				 * The code below will change this to MARKNEXT
13843 				 * if we are at the mark.
13844 				 *
13845 				 * If there are allocation failures (e.g. in
13846 				 * dupmsg below) the next time tcp_rput_data
13847 				 * sees the urgent segment it will send up the
13848 				 * MSGMARKNEXT message.
13849 				 */
13850 				mp1->b_flag |= MSGNOTMARKNEXT;
13851 				freemsg(tcp->tcp_urp_mark_mp);
13852 				tcp->tcp_urp_mark_mp = mp1;
13853 				flags |= TH_SEND_URP_MARK;
13854 #ifdef DEBUG
13855 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13856 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13857 				    "last %x, %s",
13858 				    seg_seq, urp, tcp->tcp_urp_last,
13859 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13860 #endif /* DEBUG */
13861 			}
13862 			tcp->tcp_urp_last_valid = B_TRUE;
13863 			tcp->tcp_urp_last = urp + seg_seq;
13864 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13865 			/*
13866 			 * An allocation failure prevented the previous
13867 			 * tcp_rput_data from sending up the allocated
13868 			 * MSG*MARKNEXT message - send it up this time
13869 			 * around.
13870 			 */
13871 			flags |= TH_SEND_URP_MARK;
13872 		}
13873 
13874 		/*
13875 		 * If the urgent byte is in this segment, make sure that it is
13876 		 * all by itself.  This makes it much easier to deal with the
13877 		 * possibility of an allocation failure on the T_exdata_ind.
13878 		 * Note that seg_len is the number of bytes in the segment, and
13879 		 * urp is the offset into the segment of the urgent byte.
13880 		 * urp < seg_len means that the urgent byte is in this segment.
13881 		 */
13882 		if (urp < seg_len) {
13883 			if (seg_len != 1) {
13884 				uint32_t  tmp_rnxt;
13885 				/*
13886 				 * Break it up and feed it back in.
13887 				 * Re-attach the IP header.
13888 				 */
13889 				mp->b_rptr = iphdr;
13890 				if (urp > 0) {
13891 					/*
13892 					 * There is stuff before the urgent
13893 					 * byte.
13894 					 */
13895 					mp1 = dupmsg(mp);
13896 					if (!mp1) {
13897 						/*
13898 						 * Trim from urgent byte on.
13899 						 * The rest will come back.
13900 						 */
13901 						(void) adjmsg(mp,
13902 						    urp - seg_len);
13903 						tcp_rput_data(connp,
13904 						    mp, NULL);
13905 						return;
13906 					}
13907 					(void) adjmsg(mp1, urp - seg_len);
13908 					/* Feed this piece back in. */
13909 					tmp_rnxt = tcp->tcp_rnxt;
13910 					tcp_rput_data(connp, mp1, NULL);
13911 					/*
13912 					 * If the data passed back in was not
13913 					 * processed (ie: bad ACK) sending
13914 					 * the remainder back in will cause a
13915 					 * loop. In this case, drop the
13916 					 * packet and let the sender try
13917 					 * sending a good packet.
13918 					 */
13919 					if (tmp_rnxt == tcp->tcp_rnxt) {
13920 						freemsg(mp);
13921 						return;
13922 					}
13923 				}
13924 				if (urp != seg_len - 1) {
13925 					uint32_t  tmp_rnxt;
13926 					/*
13927 					 * There is stuff after the urgent
13928 					 * byte.
13929 					 */
13930 					mp1 = dupmsg(mp);
13931 					if (!mp1) {
13932 						/*
13933 						 * Trim everything beyond the
13934 						 * urgent byte.  The rest will
13935 						 * come back.
13936 						 */
13937 						(void) adjmsg(mp,
13938 						    urp + 1 - seg_len);
13939 						tcp_rput_data(connp,
13940 						    mp, NULL);
13941 						return;
13942 					}
13943 					(void) adjmsg(mp1, urp + 1 - seg_len);
13944 					tmp_rnxt = tcp->tcp_rnxt;
13945 					tcp_rput_data(connp, mp1, NULL);
13946 					/*
13947 					 * If the data passed back in was not
13948 					 * processed (ie: bad ACK) sending
13949 					 * the remainder back in will cause a
13950 					 * loop. In this case, drop the
13951 					 * packet and let the sender try
13952 					 * sending a good packet.
13953 					 */
13954 					if (tmp_rnxt == tcp->tcp_rnxt) {
13955 						freemsg(mp);
13956 						return;
13957 					}
13958 				}
13959 				tcp_rput_data(connp, mp, NULL);
13960 				return;
13961 			}
13962 			/*
13963 			 * This segment contains only the urgent byte.  We
13964 			 * have to allocate the T_exdata_ind, if we can.
13965 			 */
13966 			if (IPCL_IS_NONSTR(connp)) {
13967 				int error;
13968 
13969 				(*connp->conn_upcalls->su_recv)
13970 				    (connp->conn_upper_handle, mp, seg_len,
13971 				    MSG_OOB, &error, NULL);
13972 				/*
13973 				 * We should never be in middle of a
13974 				 * fallback, the squeue guarantees that.
13975 				 */
13976 				ASSERT(error != EOPNOTSUPP);
13977 				mp = NULL;
13978 				goto update_ack;
13979 			} else if (!tcp->tcp_urp_mp) {
13980 				struct T_exdata_ind *tei;
13981 				mp1 = allocb(sizeof (struct T_exdata_ind),
13982 				    BPRI_MED);
13983 				if (!mp1) {
13984 					/*
13985 					 * Sigh... It'll be back.
13986 					 * Generate any MSG*MARK message now.
13987 					 */
13988 					freemsg(mp);
13989 					seg_len = 0;
13990 					if (flags & TH_SEND_URP_MARK) {
13991 
13992 
13993 						ASSERT(tcp->tcp_urp_mark_mp);
13994 						tcp->tcp_urp_mark_mp->b_flag &=
13995 						    ~MSGNOTMARKNEXT;
13996 						tcp->tcp_urp_mark_mp->b_flag |=
13997 						    MSGMARKNEXT;
13998 					}
13999 					goto ack_check;
14000 				}
14001 				mp1->b_datap->db_type = M_PROTO;
14002 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14003 				tei->PRIM_type = T_EXDATA_IND;
14004 				tei->MORE_flag = 0;
14005 				mp1->b_wptr = (uchar_t *)&tei[1];
14006 				tcp->tcp_urp_mp = mp1;
14007 #ifdef DEBUG
14008 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14009 				    "tcp_rput: allocated exdata_ind %s",
14010 				    tcp_display(tcp, NULL,
14011 				    DISP_PORT_ONLY));
14012 #endif /* DEBUG */
14013 				/*
14014 				 * There is no need to send a separate MSG*MARK
14015 				 * message since the T_EXDATA_IND will be sent
14016 				 * now.
14017 				 */
14018 				flags &= ~TH_SEND_URP_MARK;
14019 				freemsg(tcp->tcp_urp_mark_mp);
14020 				tcp->tcp_urp_mark_mp = NULL;
14021 			}
14022 			/*
14023 			 * Now we are all set.  On the next putnext upstream,
14024 			 * tcp_urp_mp will be non-NULL and will get prepended
14025 			 * to what has to be this piece containing the urgent
14026 			 * byte.  If for any reason we abort this segment below,
14027 			 * if it comes back, we will have this ready, or it
14028 			 * will get blown off in close.
14029 			 */
14030 		} else if (urp == seg_len) {
14031 			/*
14032 			 * The urgent byte is the next byte after this sequence
14033 			 * number. If there is data it is marked with
14034 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14035 			 * since it is not needed. Otherwise, if the code
14036 			 * above just allocated a zero-length tcp_urp_mark_mp
14037 			 * message, that message is tagged with MSGMARKNEXT.
14038 			 * Sending up these MSGMARKNEXT messages makes
14039 			 * SIOCATMARK work correctly even though
14040 			 * the T_EXDATA_IND will not be sent up until the
14041 			 * urgent byte arrives.
14042 			 */
14043 			if (seg_len != 0) {
14044 				flags |= TH_MARKNEXT_NEEDED;
14045 				freemsg(tcp->tcp_urp_mark_mp);
14046 				tcp->tcp_urp_mark_mp = NULL;
14047 				flags &= ~TH_SEND_URP_MARK;
14048 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14049 				flags |= TH_SEND_URP_MARK;
14050 				tcp->tcp_urp_mark_mp->b_flag &=
14051 				    ~MSGNOTMARKNEXT;
14052 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14053 			}
14054 #ifdef DEBUG
14055 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14056 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14057 			    seg_len, flags,
14058 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14059 #endif /* DEBUG */
14060 		}
14061 #ifdef DEBUG
14062 		else {
14063 			/* Data left until we hit mark */
14064 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14065 			    "tcp_rput: URP %d bytes left, %s",
14066 			    urp - seg_len, tcp_display(tcp, NULL,
14067 			    DISP_PORT_ONLY));
14068 		}
14069 #endif /* DEBUG */
14070 	}
14071 
14072 process_ack:
14073 	if (!(flags & TH_ACK)) {
14074 		freemsg(mp);
14075 		goto xmit_check;
14076 	}
14077 	}
14078 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14079 
14080 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14081 		tcp->tcp_ip_forward_progress = B_TRUE;
14082 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14083 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
14084 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
14085 			/* 3-way handshake complete - pass up the T_CONN_IND */
14086 			tcp_t	*listener = tcp->tcp_listener;
14087 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14088 
14089 			tcp->tcp_tconnind_started = B_TRUE;
14090 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14091 			/*
14092 			 * We are here means eager is fine but it can
14093 			 * get a TH_RST at any point between now and till
14094 			 * accept completes and disappear. We need to
14095 			 * ensure that reference to eager is valid after
14096 			 * we get out of eager's perimeter. So we do
14097 			 * an extra refhold.
14098 			 */
14099 			CONN_INC_REF(connp);
14100 
14101 			/*
14102 			 * The listener also exists because of the refhold
14103 			 * done in tcp_conn_request. Its possible that it
14104 			 * might have closed. We will check that once we
14105 			 * get inside listeners context.
14106 			 */
14107 			CONN_INC_REF(listener->tcp_connp);
14108 			if (listener->tcp_connp->conn_sqp ==
14109 			    connp->conn_sqp) {
14110 				/*
14111 				 * We optimize by not calling an SQUEUE_ENTER
14112 				 * on the listener since we know that the
14113 				 * listener and eager squeues are the same.
14114 				 * We are able to make this check safely only
14115 				 * because neither the eager nor the listener
14116 				 * can change its squeue. Only an active connect
14117 				 * can change its squeue
14118 				 */
14119 				tcp_send_conn_ind(listener->tcp_connp, mp,
14120 				    listener->tcp_connp->conn_sqp);
14121 				CONN_DEC_REF(listener->tcp_connp);
14122 			} else if (!tcp->tcp_loopback) {
14123 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14124 				    mp, tcp_send_conn_ind,
14125 				    listener->tcp_connp, SQ_FILL,
14126 				    SQTAG_TCP_CONN_IND);
14127 			} else {
14128 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14129 				    mp, tcp_send_conn_ind,
14130 				    listener->tcp_connp, SQ_PROCESS,
14131 				    SQTAG_TCP_CONN_IND);
14132 			}
14133 		}
14134 
14135 		if (tcp->tcp_active_open) {
14136 			/*
14137 			 * We are seeing the final ack in the three way
14138 			 * hand shake of a active open'ed connection
14139 			 * so we must send up a T_CONN_CON
14140 			 */
14141 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14142 				freemsg(mp);
14143 				return;
14144 			}
14145 			/*
14146 			 * Don't fuse the loopback endpoints for
14147 			 * simultaneous active opens.
14148 			 */
14149 			if (tcp->tcp_loopback) {
14150 				TCP_STAT(tcps, tcp_fusion_unfusable);
14151 				tcp->tcp_unfusable = B_TRUE;
14152 			}
14153 		}
14154 
14155 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14156 		bytes_acked--;
14157 		/* SYN was acked - making progress */
14158 		if (tcp->tcp_ipversion == IPV6_VERSION)
14159 			tcp->tcp_ip_forward_progress = B_TRUE;
14160 
14161 		/*
14162 		 * If SYN was retransmitted, need to reset all
14163 		 * retransmission info as this segment will be
14164 		 * treated as a dup ACK.
14165 		 */
14166 		if (tcp->tcp_rexmit) {
14167 			tcp->tcp_rexmit = B_FALSE;
14168 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14169 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14170 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14171 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14172 			tcp->tcp_ms_we_have_waited = 0;
14173 			tcp->tcp_cwnd = mss;
14174 		}
14175 
14176 		/*
14177 		 * We set the send window to zero here.
14178 		 * This is needed if there is data to be
14179 		 * processed already on the queue.
14180 		 * Later (at swnd_update label), the
14181 		 * "new_swnd > tcp_swnd" condition is satisfied
14182 		 * the XMIT_NEEDED flag is set in the current
14183 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14184 		 * called if there is already data on queue in
14185 		 * this state.
14186 		 */
14187 		tcp->tcp_swnd = 0;
14188 
14189 		if (new_swnd > tcp->tcp_max_swnd)
14190 			tcp->tcp_max_swnd = new_swnd;
14191 		tcp->tcp_swl1 = seg_seq;
14192 		tcp->tcp_swl2 = seg_ack;
14193 		tcp->tcp_state = TCPS_ESTABLISHED;
14194 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14195 
14196 		/* Fuse when both sides are in ESTABLISHED state */
14197 		if (tcp->tcp_loopback && do_tcp_fusion)
14198 			tcp_fuse(tcp, iphdr, tcph);
14199 
14200 	}
14201 	/* This code follows 4.4BSD-Lite2 mostly. */
14202 	if (bytes_acked < 0)
14203 		goto est;
14204 
14205 	/*
14206 	 * If TCP is ECN capable and the congestion experience bit is
14207 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14208 	 * done once per window (or more loosely, per RTT).
14209 	 */
14210 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14211 		tcp->tcp_cwr = B_FALSE;
14212 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14213 		if (!tcp->tcp_cwr) {
14214 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14215 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14216 			tcp->tcp_cwnd = npkt * mss;
14217 			/*
14218 			 * If the cwnd is 0, use the timer to clock out
14219 			 * new segments.  This is required by the ECN spec.
14220 			 */
14221 			if (npkt == 0) {
14222 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14223 				/*
14224 				 * This makes sure that when the ACK comes
14225 				 * back, we will increase tcp_cwnd by 1 MSS.
14226 				 */
14227 				tcp->tcp_cwnd_cnt = 0;
14228 			}
14229 			tcp->tcp_cwr = B_TRUE;
14230 			/*
14231 			 * This marks the end of the current window of in
14232 			 * flight data.  That is why we don't use
14233 			 * tcp_suna + tcp_swnd.  Only data in flight can
14234 			 * provide ECN info.
14235 			 */
14236 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14237 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14238 		}
14239 	}
14240 
14241 	mp1 = tcp->tcp_xmit_head;
14242 	if (bytes_acked == 0) {
14243 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14244 			int dupack_cnt;
14245 
14246 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14247 			/*
14248 			 * Fast retransmit.  When we have seen exactly three
14249 			 * identical ACKs while we have unacked data
14250 			 * outstanding we take it as a hint that our peer
14251 			 * dropped something.
14252 			 *
14253 			 * If TCP is retransmitting, don't do fast retransmit.
14254 			 */
14255 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14256 			    ! tcp->tcp_rexmit) {
14257 				/* Do Limited Transmit */
14258 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14259 				    tcps->tcps_dupack_fast_retransmit) {
14260 					/*
14261 					 * RFC 3042
14262 					 *
14263 					 * What we need to do is temporarily
14264 					 * increase tcp_cwnd so that new
14265 					 * data can be sent if it is allowed
14266 					 * by the receive window (tcp_rwnd).
14267 					 * tcp_wput_data() will take care of
14268 					 * the rest.
14269 					 *
14270 					 * If the connection is SACK capable,
14271 					 * only do limited xmit when there
14272 					 * is SACK info.
14273 					 *
14274 					 * Note how tcp_cwnd is incremented.
14275 					 * The first dup ACK will increase
14276 					 * it by 1 MSS.  The second dup ACK
14277 					 * will increase it by 2 MSS.  This
14278 					 * means that only 1 new segment will
14279 					 * be sent for each dup ACK.
14280 					 */
14281 					if (tcp->tcp_unsent > 0 &&
14282 					    (!tcp->tcp_snd_sack_ok ||
14283 					    (tcp->tcp_snd_sack_ok &&
14284 					    tcp->tcp_notsack_list != NULL))) {
14285 						tcp->tcp_cwnd += mss <<
14286 						    (tcp->tcp_dupack_cnt - 1);
14287 						flags |= TH_LIMIT_XMIT;
14288 					}
14289 				} else if (dupack_cnt ==
14290 				    tcps->tcps_dupack_fast_retransmit) {
14291 
14292 				/*
14293 				 * If we have reduced tcp_ssthresh
14294 				 * because of ECN, do not reduce it again
14295 				 * unless it is already one window of data
14296 				 * away.  After one window of data, tcp_cwr
14297 				 * should then be cleared.  Note that
14298 				 * for non ECN capable connection, tcp_cwr
14299 				 * should always be false.
14300 				 *
14301 				 * Adjust cwnd since the duplicate
14302 				 * ack indicates that a packet was
14303 				 * dropped (due to congestion.)
14304 				 */
14305 				if (!tcp->tcp_cwr) {
14306 					npkt = ((tcp->tcp_snxt -
14307 					    tcp->tcp_suna) >> 1) / mss;
14308 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14309 					    mss;
14310 					tcp->tcp_cwnd = (npkt +
14311 					    tcp->tcp_dupack_cnt) * mss;
14312 				}
14313 				if (tcp->tcp_ecn_ok) {
14314 					tcp->tcp_cwr = B_TRUE;
14315 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14316 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14317 				}
14318 
14319 				/*
14320 				 * We do Hoe's algorithm.  Refer to her
14321 				 * paper "Improving the Start-up Behavior
14322 				 * of a Congestion Control Scheme for TCP,"
14323 				 * appeared in SIGCOMM'96.
14324 				 *
14325 				 * Save highest seq no we have sent so far.
14326 				 * Be careful about the invisible FIN byte.
14327 				 */
14328 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14329 				    (tcp->tcp_unsent == 0)) {
14330 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14331 				} else {
14332 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14333 				}
14334 
14335 				/*
14336 				 * Do not allow bursty traffic during.
14337 				 * fast recovery.  Refer to Fall and Floyd's
14338 				 * paper "Simulation-based Comparisons of
14339 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14340 				 * This is a best current practise.
14341 				 */
14342 				tcp->tcp_snd_burst = TCP_CWND_SS;
14343 
14344 				/*
14345 				 * For SACK:
14346 				 * Calculate tcp_pipe, which is the
14347 				 * estimated number of bytes in
14348 				 * network.
14349 				 *
14350 				 * tcp_fack is the highest sack'ed seq num
14351 				 * TCP has received.
14352 				 *
14353 				 * tcp_pipe is explained in the above quoted
14354 				 * Fall and Floyd's paper.  tcp_fack is
14355 				 * explained in Mathis and Mahdavi's
14356 				 * "Forward Acknowledgment: Refining TCP
14357 				 * Congestion Control" in SIGCOMM '96.
14358 				 */
14359 				if (tcp->tcp_snd_sack_ok) {
14360 					ASSERT(tcp->tcp_sack_info != NULL);
14361 					if (tcp->tcp_notsack_list != NULL) {
14362 						tcp->tcp_pipe = tcp->tcp_snxt -
14363 						    tcp->tcp_fack;
14364 						tcp->tcp_sack_snxt = seg_ack;
14365 						flags |= TH_NEED_SACK_REXMIT;
14366 					} else {
14367 						/*
14368 						 * Always initialize tcp_pipe
14369 						 * even though we don't have
14370 						 * any SACK info.  If later
14371 						 * we get SACK info and
14372 						 * tcp_pipe is not initialized,
14373 						 * funny things will happen.
14374 						 */
14375 						tcp->tcp_pipe =
14376 						    tcp->tcp_cwnd_ssthresh;
14377 					}
14378 				} else {
14379 					flags |= TH_REXMIT_NEEDED;
14380 				} /* tcp_snd_sack_ok */
14381 
14382 				} else {
14383 					/*
14384 					 * Here we perform congestion
14385 					 * avoidance, but NOT slow start.
14386 					 * This is known as the Fast
14387 					 * Recovery Algorithm.
14388 					 */
14389 					if (tcp->tcp_snd_sack_ok &&
14390 					    tcp->tcp_notsack_list != NULL) {
14391 						flags |= TH_NEED_SACK_REXMIT;
14392 						tcp->tcp_pipe -= mss;
14393 						if (tcp->tcp_pipe < 0)
14394 							tcp->tcp_pipe = 0;
14395 					} else {
14396 					/*
14397 					 * We know that one more packet has
14398 					 * left the pipe thus we can update
14399 					 * cwnd.
14400 					 */
14401 					cwnd = tcp->tcp_cwnd + mss;
14402 					if (cwnd > tcp->tcp_cwnd_max)
14403 						cwnd = tcp->tcp_cwnd_max;
14404 					tcp->tcp_cwnd = cwnd;
14405 					if (tcp->tcp_unsent > 0)
14406 						flags |= TH_XMIT_NEEDED;
14407 					}
14408 				}
14409 			}
14410 		} else if (tcp->tcp_zero_win_probe) {
14411 			/*
14412 			 * If the window has opened, need to arrange
14413 			 * to send additional data.
14414 			 */
14415 			if (new_swnd != 0) {
14416 				/* tcp_suna != tcp_snxt */
14417 				/* Packet contains a window update */
14418 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14419 				tcp->tcp_zero_win_probe = 0;
14420 				tcp->tcp_timer_backoff = 0;
14421 				tcp->tcp_ms_we_have_waited = 0;
14422 
14423 				/*
14424 				 * Transmit starting with tcp_suna since
14425 				 * the one byte probe is not ack'ed.
14426 				 * If TCP has sent more than one identical
14427 				 * probe, tcp_rexmit will be set.  That means
14428 				 * tcp_ss_rexmit() will send out the one
14429 				 * byte along with new data.  Otherwise,
14430 				 * fake the retransmission.
14431 				 */
14432 				flags |= TH_XMIT_NEEDED;
14433 				if (!tcp->tcp_rexmit) {
14434 					tcp->tcp_rexmit = B_TRUE;
14435 					tcp->tcp_dupack_cnt = 0;
14436 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14437 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14438 				}
14439 			}
14440 		}
14441 		goto swnd_update;
14442 	}
14443 
14444 	/*
14445 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14446 	 * If the ACK value acks something that we have not yet sent, it might
14447 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14448 	 * other side.
14449 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14450 	 * state is handled above, so we can always just drop the segment and
14451 	 * send an ACK here.
14452 	 *
14453 	 * Should we send ACKs in response to ACK only segments?
14454 	 */
14455 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14456 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14457 		/* drop the received segment */
14458 		freemsg(mp);
14459 
14460 		/*
14461 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14462 		 * greater than 0, check if the number of such
14463 		 * bogus ACks is greater than that count.  If yes,
14464 		 * don't send back any ACK.  This prevents TCP from
14465 		 * getting into an ACK storm if somehow an attacker
14466 		 * successfully spoofs an acceptable segment to our
14467 		 * peer.
14468 		 */
14469 		if (tcp_drop_ack_unsent_cnt > 0 &&
14470 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14471 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14472 			return;
14473 		}
14474 		mp = tcp_ack_mp(tcp);
14475 		if (mp != NULL) {
14476 			BUMP_LOCAL(tcp->tcp_obsegs);
14477 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14478 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14479 		}
14480 		return;
14481 	}
14482 
14483 	/*
14484 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14485 	 * blocks that are covered by this ACK.
14486 	 */
14487 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14488 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14489 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14490 	}
14491 
14492 	/*
14493 	 * If we got an ACK after fast retransmit, check to see
14494 	 * if it is a partial ACK.  If it is not and the congestion
14495 	 * window was inflated to account for the other side's
14496 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14497 	 */
14498 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14499 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14500 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14501 			tcp->tcp_dupack_cnt = 0;
14502 			/*
14503 			 * Restore the orig tcp_cwnd_ssthresh after
14504 			 * fast retransmit phase.
14505 			 */
14506 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14507 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14508 			}
14509 			tcp->tcp_rexmit_max = seg_ack;
14510 			tcp->tcp_cwnd_cnt = 0;
14511 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14512 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14513 
14514 			/*
14515 			 * Remove all notsack info to avoid confusion with
14516 			 * the next fast retrasnmit/recovery phase.
14517 			 */
14518 			if (tcp->tcp_snd_sack_ok &&
14519 			    tcp->tcp_notsack_list != NULL) {
14520 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14521 			}
14522 		} else {
14523 			if (tcp->tcp_snd_sack_ok &&
14524 			    tcp->tcp_notsack_list != NULL) {
14525 				flags |= TH_NEED_SACK_REXMIT;
14526 				tcp->tcp_pipe -= mss;
14527 				if (tcp->tcp_pipe < 0)
14528 					tcp->tcp_pipe = 0;
14529 			} else {
14530 				/*
14531 				 * Hoe's algorithm:
14532 				 *
14533 				 * Retransmit the unack'ed segment and
14534 				 * restart fast recovery.  Note that we
14535 				 * need to scale back tcp_cwnd to the
14536 				 * original value when we started fast
14537 				 * recovery.  This is to prevent overly
14538 				 * aggressive behaviour in sending new
14539 				 * segments.
14540 				 */
14541 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14542 				    tcps->tcps_dupack_fast_retransmit * mss;
14543 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14544 				flags |= TH_REXMIT_NEEDED;
14545 			}
14546 		}
14547 	} else {
14548 		tcp->tcp_dupack_cnt = 0;
14549 		if (tcp->tcp_rexmit) {
14550 			/*
14551 			 * TCP is retranmitting.  If the ACK ack's all
14552 			 * outstanding data, update tcp_rexmit_max and
14553 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14554 			 * to the correct value.
14555 			 *
14556 			 * Note that SEQ_LEQ() is used.  This is to avoid
14557 			 * unnecessary fast retransmit caused by dup ACKs
14558 			 * received when TCP does slow start retransmission
14559 			 * after a time out.  During this phase, TCP may
14560 			 * send out segments which are already received.
14561 			 * This causes dup ACKs to be sent back.
14562 			 */
14563 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14564 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14565 					tcp->tcp_rexmit_nxt = seg_ack;
14566 				}
14567 				if (seg_ack != tcp->tcp_rexmit_max) {
14568 					flags |= TH_XMIT_NEEDED;
14569 				}
14570 			} else {
14571 				tcp->tcp_rexmit = B_FALSE;
14572 				tcp->tcp_xmit_zc_clean = B_FALSE;
14573 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14574 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14575 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14576 			}
14577 			tcp->tcp_ms_we_have_waited = 0;
14578 		}
14579 	}
14580 
14581 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14582 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14583 	tcp->tcp_suna = seg_ack;
14584 	if (tcp->tcp_zero_win_probe != 0) {
14585 		tcp->tcp_zero_win_probe = 0;
14586 		tcp->tcp_timer_backoff = 0;
14587 	}
14588 
14589 	/*
14590 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14591 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14592 	 * will not reach here.
14593 	 */
14594 	if (mp1 == NULL) {
14595 		goto fin_acked;
14596 	}
14597 
14598 	/*
14599 	 * Update the congestion window.
14600 	 *
14601 	 * If TCP is not ECN capable or TCP is ECN capable but the
14602 	 * congestion experience bit is not set, increase the tcp_cwnd as
14603 	 * usual.
14604 	 */
14605 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14606 		cwnd = tcp->tcp_cwnd;
14607 		add = mss;
14608 
14609 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14610 			/*
14611 			 * This is to prevent an increase of less than 1 MSS of
14612 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14613 			 * may send out tinygrams in order to preserve mblk
14614 			 * boundaries.
14615 			 *
14616 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14617 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14618 			 * increased by 1 MSS for every RTTs.
14619 			 */
14620 			if (tcp->tcp_cwnd_cnt <= 0) {
14621 				tcp->tcp_cwnd_cnt = cwnd + add;
14622 			} else {
14623 				tcp->tcp_cwnd_cnt -= add;
14624 				add = 0;
14625 			}
14626 		}
14627 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14628 	}
14629 
14630 	/* See if the latest urgent data has been acknowledged */
14631 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14632 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14633 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14634 
14635 	/* Can we update the RTT estimates? */
14636 	if (tcp->tcp_snd_ts_ok) {
14637 		/* Ignore zero timestamp echo-reply. */
14638 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14639 			tcp_set_rto(tcp, (int32_t)lbolt -
14640 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14641 		}
14642 
14643 		/* If needed, restart the timer. */
14644 		if (tcp->tcp_set_timer == 1) {
14645 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14646 			tcp->tcp_set_timer = 0;
14647 		}
14648 		/*
14649 		 * Update tcp_csuna in case the other side stops sending
14650 		 * us timestamps.
14651 		 */
14652 		tcp->tcp_csuna = tcp->tcp_snxt;
14653 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14654 		/*
14655 		 * An ACK sequence we haven't seen before, so get the RTT
14656 		 * and update the RTO. But first check if the timestamp is
14657 		 * valid to use.
14658 		 */
14659 		if ((mp1->b_next != NULL) &&
14660 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14661 			tcp_set_rto(tcp, (int32_t)lbolt -
14662 			    (int32_t)(intptr_t)mp1->b_prev);
14663 		else
14664 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14665 
14666 		/* Remeber the last sequence to be ACKed */
14667 		tcp->tcp_csuna = seg_ack;
14668 		if (tcp->tcp_set_timer == 1) {
14669 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14670 			tcp->tcp_set_timer = 0;
14671 		}
14672 	} else {
14673 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14674 	}
14675 
14676 	/* Eat acknowledged bytes off the xmit queue. */
14677 	for (;;) {
14678 		mblk_t	*mp2;
14679 		uchar_t	*wptr;
14680 
14681 		wptr = mp1->b_wptr;
14682 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14683 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14684 		if (bytes_acked < 0) {
14685 			mp1->b_rptr = wptr + bytes_acked;
14686 			/*
14687 			 * Set a new timestamp if all the bytes timed by the
14688 			 * old timestamp have been ack'ed.
14689 			 */
14690 			if (SEQ_GT(seg_ack,
14691 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14692 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14693 				mp1->b_next = NULL;
14694 			}
14695 			break;
14696 		}
14697 		mp1->b_next = NULL;
14698 		mp1->b_prev = NULL;
14699 		mp2 = mp1;
14700 		mp1 = mp1->b_cont;
14701 
14702 		/*
14703 		 * This notification is required for some zero-copy
14704 		 * clients to maintain a copy semantic. After the data
14705 		 * is ack'ed, client is safe to modify or reuse the buffer.
14706 		 */
14707 		if (tcp->tcp_snd_zcopy_aware &&
14708 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14709 			tcp_zcopy_notify(tcp);
14710 		freeb(mp2);
14711 		if (bytes_acked == 0) {
14712 			if (mp1 == NULL) {
14713 				/* Everything is ack'ed, clear the tail. */
14714 				tcp->tcp_xmit_tail = NULL;
14715 				/*
14716 				 * Cancel the timer unless we are still
14717 				 * waiting for an ACK for the FIN packet.
14718 				 */
14719 				if (tcp->tcp_timer_tid != 0 &&
14720 				    tcp->tcp_snxt == tcp->tcp_suna) {
14721 					(void) TCP_TIMER_CANCEL(tcp,
14722 					    tcp->tcp_timer_tid);
14723 					tcp->tcp_timer_tid = 0;
14724 				}
14725 				goto pre_swnd_update;
14726 			}
14727 			if (mp2 != tcp->tcp_xmit_tail)
14728 				break;
14729 			tcp->tcp_xmit_tail = mp1;
14730 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14731 			    (uintptr_t)INT_MAX);
14732 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14733 			    mp1->b_rptr);
14734 			break;
14735 		}
14736 		if (mp1 == NULL) {
14737 			/*
14738 			 * More was acked but there is nothing more
14739 			 * outstanding.  This means that the FIN was
14740 			 * just acked or that we're talking to a clown.
14741 			 */
14742 fin_acked:
14743 			ASSERT(tcp->tcp_fin_sent);
14744 			tcp->tcp_xmit_tail = NULL;
14745 			if (tcp->tcp_fin_sent) {
14746 				/* FIN was acked - making progress */
14747 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14748 				    !tcp->tcp_fin_acked)
14749 					tcp->tcp_ip_forward_progress = B_TRUE;
14750 				tcp->tcp_fin_acked = B_TRUE;
14751 				if (tcp->tcp_linger_tid != 0 &&
14752 				    TCP_TIMER_CANCEL(tcp,
14753 				    tcp->tcp_linger_tid) >= 0) {
14754 					tcp_stop_lingering(tcp);
14755 					freemsg(mp);
14756 					mp = NULL;
14757 				}
14758 			} else {
14759 				/*
14760 				 * We should never get here because
14761 				 * we have already checked that the
14762 				 * number of bytes ack'ed should be
14763 				 * smaller than or equal to what we
14764 				 * have sent so far (it is the
14765 				 * acceptability check of the ACK).
14766 				 * We can only get here if the send
14767 				 * queue is corrupted.
14768 				 *
14769 				 * Terminate the connection and
14770 				 * panic the system.  It is better
14771 				 * for us to panic instead of
14772 				 * continuing to avoid other disaster.
14773 				 */
14774 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14775 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14776 				panic("Memory corruption "
14777 				    "detected for connection %s.",
14778 				    tcp_display(tcp, NULL,
14779 				    DISP_ADDR_AND_PORT));
14780 				/*NOTREACHED*/
14781 			}
14782 			goto pre_swnd_update;
14783 		}
14784 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14785 	}
14786 	if (tcp->tcp_unsent) {
14787 		flags |= TH_XMIT_NEEDED;
14788 	}
14789 pre_swnd_update:
14790 	tcp->tcp_xmit_head = mp1;
14791 swnd_update:
14792 	/*
14793 	 * The following check is different from most other implementations.
14794 	 * For bi-directional transfer, when segments are dropped, the
14795 	 * "normal" check will not accept a window update in those
14796 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14797 	 * segments which are outside receiver's window.  As TCP accepts
14798 	 * the ack in those retransmitted segments, if the window update in
14799 	 * the same segment is not accepted, TCP will incorrectly calculates
14800 	 * that it can send more segments.  This can create a deadlock
14801 	 * with the receiver if its window becomes zero.
14802 	 */
14803 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14804 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14805 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14806 		/*
14807 		 * The criteria for update is:
14808 		 *
14809 		 * 1. the segment acknowledges some data.  Or
14810 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14811 		 * 3. the segment is not old and the advertised window is
14812 		 * larger than the previous advertised window.
14813 		 */
14814 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14815 			flags |= TH_XMIT_NEEDED;
14816 		tcp->tcp_swnd = new_swnd;
14817 		if (new_swnd > tcp->tcp_max_swnd)
14818 			tcp->tcp_max_swnd = new_swnd;
14819 		tcp->tcp_swl1 = seg_seq;
14820 		tcp->tcp_swl2 = seg_ack;
14821 	}
14822 est:
14823 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14824 
14825 		switch (tcp->tcp_state) {
14826 		case TCPS_FIN_WAIT_1:
14827 			if (tcp->tcp_fin_acked) {
14828 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14829 				/*
14830 				 * We implement the non-standard BSD/SunOS
14831 				 * FIN_WAIT_2 flushing algorithm.
14832 				 * If there is no user attached to this
14833 				 * TCP endpoint, then this TCP struct
14834 				 * could hang around forever in FIN_WAIT_2
14835 				 * state if the peer forgets to send us
14836 				 * a FIN.  To prevent this, we wait only
14837 				 * 2*MSL (a convenient time value) for
14838 				 * the FIN to arrive.  If it doesn't show up,
14839 				 * we flush the TCP endpoint.  This algorithm,
14840 				 * though a violation of RFC-793, has worked
14841 				 * for over 10 years in BSD systems.
14842 				 * Note: SunOS 4.x waits 675 seconds before
14843 				 * flushing the FIN_WAIT_2 connection.
14844 				 */
14845 				TCP_TIMER_RESTART(tcp,
14846 				    tcps->tcps_fin_wait_2_flush_interval);
14847 			}
14848 			break;
14849 		case TCPS_FIN_WAIT_2:
14850 			break;	/* Shutdown hook? */
14851 		case TCPS_LAST_ACK:
14852 			freemsg(mp);
14853 			if (tcp->tcp_fin_acked) {
14854 				(void) tcp_clean_death(tcp, 0, 19);
14855 				return;
14856 			}
14857 			goto xmit_check;
14858 		case TCPS_CLOSING:
14859 			if (tcp->tcp_fin_acked) {
14860 				tcp->tcp_state = TCPS_TIME_WAIT;
14861 				/*
14862 				 * Unconditionally clear the exclusive binding
14863 				 * bit so this TIME-WAIT connection won't
14864 				 * interfere with new ones.
14865 				 */
14866 				tcp->tcp_exclbind = 0;
14867 				if (!TCP_IS_DETACHED(tcp)) {
14868 					TCP_TIMER_RESTART(tcp,
14869 					    tcps->tcps_time_wait_interval);
14870 				} else {
14871 					tcp_time_wait_append(tcp);
14872 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14873 				}
14874 			}
14875 			/*FALLTHRU*/
14876 		case TCPS_CLOSE_WAIT:
14877 			freemsg(mp);
14878 			goto xmit_check;
14879 		default:
14880 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14881 			break;
14882 		}
14883 	}
14884 	if (flags & TH_FIN) {
14885 		/* Make sure we ack the fin */
14886 		flags |= TH_ACK_NEEDED;
14887 		if (!tcp->tcp_fin_rcvd) {
14888 			tcp->tcp_fin_rcvd = B_TRUE;
14889 			tcp->tcp_rnxt++;
14890 			tcph = tcp->tcp_tcph;
14891 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14892 
14893 			/*
14894 			 * Generate the ordrel_ind at the end unless we
14895 			 * are an eager guy.
14896 			 * In the eager case tcp_rsrv will do this when run
14897 			 * after tcp_accept is done.
14898 			 */
14899 			if (tcp->tcp_listener == NULL &&
14900 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14901 				flags |= TH_ORDREL_NEEDED;
14902 			switch (tcp->tcp_state) {
14903 			case TCPS_SYN_RCVD:
14904 			case TCPS_ESTABLISHED:
14905 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14906 				/* Keepalive? */
14907 				break;
14908 			case TCPS_FIN_WAIT_1:
14909 				if (!tcp->tcp_fin_acked) {
14910 					tcp->tcp_state = TCPS_CLOSING;
14911 					break;
14912 				}
14913 				/* FALLTHRU */
14914 			case TCPS_FIN_WAIT_2:
14915 				tcp->tcp_state = TCPS_TIME_WAIT;
14916 				/*
14917 				 * Unconditionally clear the exclusive binding
14918 				 * bit so this TIME-WAIT connection won't
14919 				 * interfere with new ones.
14920 				 */
14921 				tcp->tcp_exclbind = 0;
14922 				if (!TCP_IS_DETACHED(tcp)) {
14923 					TCP_TIMER_RESTART(tcp,
14924 					    tcps->tcps_time_wait_interval);
14925 				} else {
14926 					tcp_time_wait_append(tcp);
14927 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14928 				}
14929 				if (seg_len) {
14930 					/*
14931 					 * implies data piggybacked on FIN.
14932 					 * break to handle data.
14933 					 */
14934 					break;
14935 				}
14936 				freemsg(mp);
14937 				goto ack_check;
14938 			}
14939 		}
14940 	}
14941 	if (mp == NULL)
14942 		goto xmit_check;
14943 	if (seg_len == 0) {
14944 		freemsg(mp);
14945 		goto xmit_check;
14946 	}
14947 	if (mp->b_rptr == mp->b_wptr) {
14948 		/*
14949 		 * The header has been consumed, so we remove the
14950 		 * zero-length mblk here.
14951 		 */
14952 		mp1 = mp;
14953 		mp = mp->b_cont;
14954 		freeb(mp1);
14955 	}
14956 update_ack:
14957 	tcph = tcp->tcp_tcph;
14958 	tcp->tcp_rack_cnt++;
14959 	{
14960 		uint32_t cur_max;
14961 
14962 		cur_max = tcp->tcp_rack_cur_max;
14963 		if (tcp->tcp_rack_cnt >= cur_max) {
14964 			/*
14965 			 * We have more unacked data than we should - send
14966 			 * an ACK now.
14967 			 */
14968 			flags |= TH_ACK_NEEDED;
14969 			cur_max++;
14970 			if (cur_max > tcp->tcp_rack_abs_max)
14971 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14972 			else
14973 				tcp->tcp_rack_cur_max = cur_max;
14974 		} else if (TCP_IS_DETACHED(tcp)) {
14975 			/* We don't have an ACK timer for detached TCP. */
14976 			flags |= TH_ACK_NEEDED;
14977 		} else if (seg_len < mss) {
14978 			/*
14979 			 * If we get a segment that is less than an mss, and we
14980 			 * already have unacknowledged data, and the amount
14981 			 * unacknowledged is not a multiple of mss, then we
14982 			 * better generate an ACK now.  Otherwise, this may be
14983 			 * the tail piece of a transaction, and we would rather
14984 			 * wait for the response.
14985 			 */
14986 			uint32_t udif;
14987 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14988 			    (uintptr_t)INT_MAX);
14989 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14990 			if (udif && (udif % mss))
14991 				flags |= TH_ACK_NEEDED;
14992 			else
14993 				flags |= TH_ACK_TIMER_NEEDED;
14994 		} else {
14995 			/* Start delayed ack timer */
14996 			flags |= TH_ACK_TIMER_NEEDED;
14997 		}
14998 	}
14999 	tcp->tcp_rnxt += seg_len;
15000 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15001 
15002 	if (mp == NULL)
15003 		goto xmit_check;
15004 
15005 	/* Update SACK list */
15006 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15007 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15008 		    &(tcp->tcp_num_sack_blk));
15009 	}
15010 
15011 	if (tcp->tcp_urp_mp) {
15012 		tcp->tcp_urp_mp->b_cont = mp;
15013 		mp = tcp->tcp_urp_mp;
15014 		tcp->tcp_urp_mp = NULL;
15015 		/* Ready for a new signal. */
15016 		tcp->tcp_urp_last_valid = B_FALSE;
15017 #ifdef DEBUG
15018 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15019 		    "tcp_rput: sending exdata_ind %s",
15020 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15021 #endif /* DEBUG */
15022 	}
15023 
15024 	/*
15025 	 * Check for ancillary data changes compared to last segment.
15026 	 */
15027 	if (tcp->tcp_ipv6_recvancillary != 0) {
15028 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15029 		ASSERT(mp != NULL);
15030 	}
15031 
15032 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15033 		/*
15034 		 * Side queue inbound data until the accept happens.
15035 		 * tcp_accept/tcp_rput drains this when the accept happens.
15036 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15037 		 * T_EXDATA_IND) it is queued on b_next.
15038 		 * XXX Make urgent data use this. Requires:
15039 		 *	Removing tcp_listener check for TH_URG
15040 		 *	Making M_PCPROTO and MARK messages skip the eager case
15041 		 */
15042 
15043 		if (tcp->tcp_kssl_pending) {
15044 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
15045 			    mblk_t *, mp);
15046 			tcp_kssl_input(tcp, mp);
15047 		} else {
15048 			tcp_rcv_enqueue(tcp, mp, seg_len);
15049 		}
15050 	} else {
15051 		sodirect_t	*sodp = tcp->tcp_sodirect;
15052 
15053 		/*
15054 		 * If an sodirect connection and an enabled sodirect_t then
15055 		 * sodp will be set to point to the tcp_t/sonode_t shared
15056 		 * sodirect_t and the sodirect_t's lock will be held.
15057 		 */
15058 		if (sodp != NULL) {
15059 			mutex_enter(sodp->sod_lockp);
15060 			if (!(sodp->sod_state & SOD_ENABLED) ||
15061 			    (tcp->tcp_kssl_ctx != NULL &&
15062 			    DB_TYPE(mp) == M_DATA)) {
15063 				mutex_exit(sodp->sod_lockp);
15064 				sodp = NULL;
15065 			} else {
15066 				mutex_exit(sodp->sod_lockp);
15067 			}
15068 		}
15069 		if (mp->b_datap->db_type != M_DATA ||
15070 		    (flags & TH_MARKNEXT_NEEDED)) {
15071 			if (IPCL_IS_NONSTR(connp)) {
15072 				int error;
15073 
15074 				if ((*connp->conn_upcalls->su_recv)
15075 				    (connp->conn_upper_handle, mp,
15076 				    seg_len, 0, &error, NULL) <= 0) {
15077 					/*
15078 					 * We should never be in middle of a
15079 					 * fallback, the squeue guarantees that.
15080 					 */
15081 					ASSERT(error != EOPNOTSUPP);
15082 					if (error == ENOSPC)
15083 						tcp->tcp_rwnd -= seg_len;
15084 				}
15085 			} else if (sodp != NULL) {
15086 				mutex_enter(sodp->sod_lockp);
15087 				SOD_UIOAFINI(sodp);
15088 				if (!SOD_QEMPTY(sodp) &&
15089 				    (sodp->sod_state & SOD_WAKE_NOT)) {
15090 					flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15091 					/* sod_wakeup() did the mutex_exit() */
15092 				} else {
15093 					mutex_exit(sodp->sod_lockp);
15094 				}
15095 			} else if (tcp->tcp_rcv_list != NULL) {
15096 				flags |= tcp_rcv_drain(tcp);
15097 			}
15098 			ASSERT(tcp->tcp_rcv_list == NULL ||
15099 			    tcp->tcp_fused_sigurg);
15100 
15101 			if (flags & TH_MARKNEXT_NEEDED) {
15102 #ifdef DEBUG
15103 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15104 				    "tcp_rput: sending MSGMARKNEXT %s",
15105 				    tcp_display(tcp, NULL,
15106 				    DISP_PORT_ONLY));
15107 #endif /* DEBUG */
15108 				mp->b_flag |= MSGMARKNEXT;
15109 				flags &= ~TH_MARKNEXT_NEEDED;
15110 			}
15111 
15112 			/* Does this need SSL processing first? */
15113 			if ((tcp->tcp_kssl_ctx != NULL) &&
15114 			    (DB_TYPE(mp) == M_DATA)) {
15115 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15116 				    mblk_t *, mp);
15117 				tcp_kssl_input(tcp, mp);
15118 			} else if (!IPCL_IS_NONSTR(connp)) {
15119 				/* Already handled non-STREAMS case. */
15120 				putnext(tcp->tcp_rq, mp);
15121 				if (!canputnext(tcp->tcp_rq))
15122 					tcp->tcp_rwnd -= seg_len;
15123 			}
15124 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15125 		    (DB_TYPE(mp) == M_DATA)) {
15126 			/* Does this need SSL processing first? */
15127 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
15128 			tcp_kssl_input(tcp, mp);
15129 		} else if (IPCL_IS_NONSTR(connp)) {
15130 			/* Non-STREAMS socket */
15131 			boolean_t push = flags & (TH_PUSH|TH_FIN);
15132 			int	error;
15133 
15134 			if ((*connp->conn_upcalls->su_recv)(
15135 			    connp->conn_upper_handle,
15136 			    mp, seg_len, 0, &error, &push) <= 0) {
15137 				/*
15138 				 * We should never be in middle of a
15139 				 * fallback, the squeue guarantees that.
15140 				 */
15141 				ASSERT(error != EOPNOTSUPP);
15142 				if (error == ENOSPC)
15143 					tcp->tcp_rwnd -= seg_len;
15144 			} else if (push) {
15145 				/*
15146 				 * PUSH bit set and sockfs is not
15147 				 * flow controlled
15148 				 */
15149 				flags |= tcp_rwnd_reopen(tcp);
15150 			}
15151 		} else if (sodp != NULL) {
15152 			/*
15153 			 * Sodirect so all mblk_t's are queued on the
15154 			 * socket directly, check for wakeup of blocked
15155 			 * reader (if any), and last if flow-controled.
15156 			 */
15157 			mutex_enter(sodp->sod_lockp);
15158 			flags |= tcp_rcv_sod_enqueue(tcp, sodp, mp, seg_len);
15159 			if ((sodp->sod_state & SOD_WAKE_NEED) ||
15160 			    (flags & (TH_PUSH|TH_FIN))) {
15161 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15162 				/* sod_wakeup() did the mutex_exit() */
15163 			} else {
15164 				if (SOD_QFULL(sodp)) {
15165 					/* Q is full, need backenable */
15166 					SOD_QSETBE(sodp);
15167 				}
15168 				mutex_exit(sodp->sod_lockp);
15169 			}
15170 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15171 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_recv_hiwater >> 3) {
15172 			if (tcp->tcp_rcv_list != NULL) {
15173 				/*
15174 				 * Enqueue the new segment first and then
15175 				 * call tcp_rcv_drain() to send all data
15176 				 * up.  The other way to do this is to
15177 				 * send all queued data up and then call
15178 				 * putnext() to send the new segment up.
15179 				 * This way can remove the else part later
15180 				 * on.
15181 				 *
15182 				 * We don't do this to avoid one more call to
15183 				 * canputnext() as tcp_rcv_drain() needs to
15184 				 * call canputnext().
15185 				 */
15186 				tcp_rcv_enqueue(tcp, mp, seg_len);
15187 				flags |= tcp_rcv_drain(tcp);
15188 			} else {
15189 				putnext(tcp->tcp_rq, mp);
15190 				if (!canputnext(tcp->tcp_rq))
15191 					tcp->tcp_rwnd -= seg_len;
15192 			}
15193 		} else {
15194 			/*
15195 			 * Enqueue all packets when processing an mblk
15196 			 * from the co queue and also enqueue normal packets.
15197 			 * For packets which belong to SSL stream do SSL
15198 			 * processing first.
15199 			 */
15200 			tcp_rcv_enqueue(tcp, mp, seg_len);
15201 		}
15202 		/*
15203 		 * Make sure the timer is running if we have data waiting
15204 		 * for a push bit. This provides resiliency against
15205 		 * implementations that do not correctly generate push bits.
15206 		 *
15207 		 * Note, for sodirect if Q isn't empty and there's not a
15208 		 * pending wakeup then we need a timer. Also note that sodp
15209 		 * is assumed to be still valid after exit()ing the sod_lockp
15210 		 * above and while the SOD state can change it can only change
15211 		 * such that the Q is empty now even though data was added
15212 		 * above.
15213 		 */
15214 		if (!IPCL_IS_NONSTR(connp) &&
15215 		    ((sodp != NULL && !SOD_QEMPTY(sodp) &&
15216 		    (sodp->sod_state & SOD_WAKE_NOT)) ||
15217 		    (sodp == NULL && tcp->tcp_rcv_list != NULL)) &&
15218 		    tcp->tcp_push_tid == 0) {
15219 			/*
15220 			 * The connection may be closed at this point, so don't
15221 			 * do anything for a detached tcp.
15222 			 */
15223 			if (!TCP_IS_DETACHED(tcp))
15224 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15225 				    tcp_push_timer,
15226 				    MSEC_TO_TICK(
15227 				    tcps->tcps_push_timer_interval));
15228 		}
15229 	}
15230 
15231 xmit_check:
15232 	/* Is there anything left to do? */
15233 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15234 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15235 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15236 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15237 		goto done;
15238 
15239 	/* Any transmit work to do and a non-zero window? */
15240 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15241 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15242 		if (flags & TH_REXMIT_NEEDED) {
15243 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15244 
15245 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15246 			if (snd_size > mss)
15247 				snd_size = mss;
15248 			if (snd_size > tcp->tcp_swnd)
15249 				snd_size = tcp->tcp_swnd;
15250 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15251 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15252 			    B_TRUE);
15253 
15254 			if (mp1 != NULL) {
15255 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15256 				tcp->tcp_csuna = tcp->tcp_snxt;
15257 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15258 				UPDATE_MIB(&tcps->tcps_mib,
15259 				    tcpRetransBytes, snd_size);
15260 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15261 			}
15262 		}
15263 		if (flags & TH_NEED_SACK_REXMIT) {
15264 			tcp_sack_rxmit(tcp, &flags);
15265 		}
15266 		/*
15267 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15268 		 * out new segment.  Note that tcp_rexmit should not be
15269 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15270 		 */
15271 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15272 			if (!tcp->tcp_rexmit) {
15273 				tcp_wput_data(tcp, NULL, B_FALSE);
15274 			} else {
15275 				tcp_ss_rexmit(tcp);
15276 			}
15277 		}
15278 		/*
15279 		 * Adjust tcp_cwnd back to normal value after sending
15280 		 * new data segments.
15281 		 */
15282 		if (flags & TH_LIMIT_XMIT) {
15283 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15284 			/*
15285 			 * This will restart the timer.  Restarting the
15286 			 * timer is used to avoid a timeout before the
15287 			 * limited transmitted segment's ACK gets back.
15288 			 */
15289 			if (tcp->tcp_xmit_head != NULL)
15290 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15291 		}
15292 
15293 		/* Anything more to do? */
15294 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15295 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15296 			goto done;
15297 	}
15298 ack_check:
15299 	if (flags & TH_SEND_URP_MARK) {
15300 		ASSERT(tcp->tcp_urp_mark_mp);
15301 		ASSERT(!IPCL_IS_NONSTR(connp));
15302 		/*
15303 		 * Send up any queued data and then send the mark message
15304 		 */
15305 		sodirect_t *sodp;
15306 
15307 		SOD_PTR_ENTER(tcp, sodp);
15308 
15309 		mp1 = tcp->tcp_urp_mark_mp;
15310 		tcp->tcp_urp_mark_mp = NULL;
15311 		if (sodp != NULL) {
15312 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15313 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15314 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15315 			}
15316 			ASSERT(tcp->tcp_rcv_list == NULL);
15317 
15318 			flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15319 			/* sod_wakeup() does the mutex_exit() */
15320 		} else if (tcp->tcp_rcv_list != NULL) {
15321 			flags |= tcp_rcv_drain(tcp);
15322 
15323 			ASSERT(tcp->tcp_rcv_list == NULL ||
15324 			    tcp->tcp_fused_sigurg);
15325 
15326 		}
15327 		putnext(tcp->tcp_rq, mp1);
15328 #ifdef DEBUG
15329 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15330 		    "tcp_rput: sending zero-length %s %s",
15331 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15332 		    "MSGNOTMARKNEXT"),
15333 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15334 #endif /* DEBUG */
15335 		flags &= ~TH_SEND_URP_MARK;
15336 	}
15337 	if (flags & TH_ACK_NEEDED) {
15338 		/*
15339 		 * Time to send an ack for some reason.
15340 		 */
15341 		mp1 = tcp_ack_mp(tcp);
15342 
15343 		if (mp1 != NULL) {
15344 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15345 			BUMP_LOCAL(tcp->tcp_obsegs);
15346 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15347 		}
15348 		if (tcp->tcp_ack_tid != 0) {
15349 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15350 			tcp->tcp_ack_tid = 0;
15351 		}
15352 	}
15353 	if (flags & TH_ACK_TIMER_NEEDED) {
15354 		/*
15355 		 * Arrange for deferred ACK or push wait timeout.
15356 		 * Start timer if it is not already running.
15357 		 */
15358 		if (tcp->tcp_ack_tid == 0) {
15359 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15360 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15361 			    (clock_t)tcps->tcps_local_dack_interval :
15362 			    (clock_t)tcps->tcps_deferred_ack_interval));
15363 		}
15364 	}
15365 	if (flags & TH_ORDREL_NEEDED) {
15366 		/*
15367 		 * Send up the ordrel_ind unless we are an eager guy.
15368 		 * In the eager case tcp_rsrv will do this when run
15369 		 * after tcp_accept is done.
15370 		 */
15371 		sodirect_t *sodp;
15372 
15373 		ASSERT(tcp->tcp_listener == NULL);
15374 
15375 		if (IPCL_IS_NONSTR(connp)) {
15376 			ASSERT(tcp->tcp_ordrel_mp == NULL);
15377 			tcp->tcp_ordrel_done = B_TRUE;
15378 			(*connp->conn_upcalls->su_opctl)
15379 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
15380 			goto done;
15381 		}
15382 
15383 		SOD_PTR_ENTER(tcp, sodp);
15384 		if (sodp != NULL) {
15385 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15386 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15387 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15388 			}
15389 			/* No more sodirect */
15390 			tcp->tcp_sodirect = NULL;
15391 			if (!SOD_QEMPTY(sodp)) {
15392 				/* Mblk(s) to process, notify */
15393 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15394 				/* sod_wakeup() does the mutex_exit() */
15395 			} else {
15396 				/* Nothing to process */
15397 				mutex_exit(sodp->sod_lockp);
15398 			}
15399 		} else if (tcp->tcp_rcv_list != NULL) {
15400 			/*
15401 			 * Push any mblk(s) enqueued from co processing.
15402 			 */
15403 			flags |= tcp_rcv_drain(tcp);
15404 
15405 			ASSERT(tcp->tcp_rcv_list == NULL ||
15406 			    tcp->tcp_fused_sigurg);
15407 		}
15408 
15409 		mp1 = tcp->tcp_ordrel_mp;
15410 		tcp->tcp_ordrel_mp = NULL;
15411 		tcp->tcp_ordrel_done = B_TRUE;
15412 		putnext(tcp->tcp_rq, mp1);
15413 	}
15414 done:
15415 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15416 }
15417 
15418 /*
15419  * This function does PAWS protection check. Returns B_TRUE if the
15420  * segment passes the PAWS test, else returns B_FALSE.
15421  */
15422 boolean_t
15423 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15424 {
15425 	uint8_t	flags;
15426 	int	options;
15427 	uint8_t *up;
15428 
15429 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15430 	/*
15431 	 * If timestamp option is aligned nicely, get values inline,
15432 	 * otherwise call general routine to parse.  Only do that
15433 	 * if timestamp is the only option.
15434 	 */
15435 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15436 	    TCPOPT_REAL_TS_LEN &&
15437 	    OK_32PTR((up = ((uint8_t *)tcph) +
15438 	    TCP_MIN_HEADER_LENGTH)) &&
15439 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15440 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15441 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15442 
15443 		options = TCP_OPT_TSTAMP_PRESENT;
15444 	} else {
15445 		if (tcp->tcp_snd_sack_ok) {
15446 			tcpoptp->tcp = tcp;
15447 		} else {
15448 			tcpoptp->tcp = NULL;
15449 		}
15450 		options = tcp_parse_options(tcph, tcpoptp);
15451 	}
15452 
15453 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15454 		/*
15455 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15456 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15457 		 */
15458 		if ((flags & TH_RST) == 0 &&
15459 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15460 		    tcp->tcp_ts_recent)) {
15461 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15462 			    PAWS_TIMEOUT)) {
15463 				/* This segment is not acceptable. */
15464 				return (B_FALSE);
15465 			} else {
15466 				/*
15467 				 * Connection has been idle for
15468 				 * too long.  Reset the timestamp
15469 				 * and assume the segment is valid.
15470 				 */
15471 				tcp->tcp_ts_recent =
15472 				    tcpoptp->tcp_opt_ts_val;
15473 			}
15474 		}
15475 	} else {
15476 		/*
15477 		 * If we don't get a timestamp on every packet, we
15478 		 * figure we can't really trust 'em, so we stop sending
15479 		 * and parsing them.
15480 		 */
15481 		tcp->tcp_snd_ts_ok = B_FALSE;
15482 
15483 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15484 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15485 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15486 		/*
15487 		 * Adjust the tcp_mss accordingly. We also need to
15488 		 * adjust tcp_cwnd here in accordance with the new mss.
15489 		 * But we avoid doing a slow start here so as to not
15490 		 * to lose on the transfer rate built up so far.
15491 		 */
15492 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15493 		if (tcp->tcp_snd_sack_ok) {
15494 			ASSERT(tcp->tcp_sack_info != NULL);
15495 			tcp->tcp_max_sack_blk = 4;
15496 		}
15497 	}
15498 	return (B_TRUE);
15499 }
15500 
15501 /*
15502  * Attach ancillary data to a received TCP segments for the
15503  * ancillary pieces requested by the application that are
15504  * different than they were in the previous data segment.
15505  *
15506  * Save the "current" values once memory allocation is ok so that
15507  * when memory allocation fails we can just wait for the next data segment.
15508  */
15509 static mblk_t *
15510 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15511 {
15512 	struct T_optdata_ind *todi;
15513 	int optlen;
15514 	uchar_t *optptr;
15515 	struct T_opthdr *toh;
15516 	uint_t addflag;	/* Which pieces to add */
15517 	mblk_t *mp1;
15518 
15519 	optlen = 0;
15520 	addflag = 0;
15521 	/* If app asked for pktinfo and the index has changed ... */
15522 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15523 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15524 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15525 		optlen += sizeof (struct T_opthdr) +
15526 		    sizeof (struct in6_pktinfo);
15527 		addflag |= TCP_IPV6_RECVPKTINFO;
15528 	}
15529 	/* If app asked for hoplimit and it has changed ... */
15530 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15531 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15532 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15533 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15534 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15535 	}
15536 	/* If app asked for tclass and it has changed ... */
15537 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15538 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15539 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15540 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15541 		addflag |= TCP_IPV6_RECVTCLASS;
15542 	}
15543 	/*
15544 	 * If app asked for hopbyhop headers and it has changed ...
15545 	 * For security labels, note that (1) security labels can't change on
15546 	 * a connected socket at all, (2) we're connected to at most one peer,
15547 	 * (3) if anything changes, then it must be some other extra option.
15548 	 */
15549 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15550 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15551 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15552 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15553 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15554 		    tcp->tcp_label_len;
15555 		addflag |= TCP_IPV6_RECVHOPOPTS;
15556 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15557 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15558 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15559 			return (mp);
15560 	}
15561 	/* If app asked for dst headers before routing headers ... */
15562 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15563 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15564 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15565 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15566 		optlen += sizeof (struct T_opthdr) +
15567 		    ipp->ipp_rtdstoptslen;
15568 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15569 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15570 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15571 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15572 			return (mp);
15573 	}
15574 	/* If app asked for routing headers and it has changed ... */
15575 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15576 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15577 	    (ipp->ipp_fields & IPPF_RTHDR),
15578 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15579 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15580 		addflag |= TCP_IPV6_RECVRTHDR;
15581 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15582 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15583 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15584 			return (mp);
15585 	}
15586 	/* If app asked for dest headers and it has changed ... */
15587 	if ((tcp->tcp_ipv6_recvancillary &
15588 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15589 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15590 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15591 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15592 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15593 		addflag |= TCP_IPV6_RECVDSTOPTS;
15594 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15595 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15596 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15597 			return (mp);
15598 	}
15599 
15600 	if (optlen == 0) {
15601 		/* Nothing to add */
15602 		return (mp);
15603 	}
15604 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15605 	if (mp1 == NULL) {
15606 		/*
15607 		 * Defer sending ancillary data until the next TCP segment
15608 		 * arrives.
15609 		 */
15610 		return (mp);
15611 	}
15612 	mp1->b_cont = mp;
15613 	mp = mp1;
15614 	mp->b_wptr += sizeof (*todi) + optlen;
15615 	mp->b_datap->db_type = M_PROTO;
15616 	todi = (struct T_optdata_ind *)mp->b_rptr;
15617 	todi->PRIM_type = T_OPTDATA_IND;
15618 	todi->DATA_flag = 1;	/* MORE data */
15619 	todi->OPT_length = optlen;
15620 	todi->OPT_offset = sizeof (*todi);
15621 	optptr = (uchar_t *)&todi[1];
15622 	/*
15623 	 * If app asked for pktinfo and the index has changed ...
15624 	 * Note that the local address never changes for the connection.
15625 	 */
15626 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15627 		struct in6_pktinfo *pkti;
15628 
15629 		toh = (struct T_opthdr *)optptr;
15630 		toh->level = IPPROTO_IPV6;
15631 		toh->name = IPV6_PKTINFO;
15632 		toh->len = sizeof (*toh) + sizeof (*pkti);
15633 		toh->status = 0;
15634 		optptr += sizeof (*toh);
15635 		pkti = (struct in6_pktinfo *)optptr;
15636 		if (tcp->tcp_ipversion == IPV6_VERSION)
15637 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15638 		else
15639 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15640 			    &pkti->ipi6_addr);
15641 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15642 		optptr += sizeof (*pkti);
15643 		ASSERT(OK_32PTR(optptr));
15644 		/* Save as "last" value */
15645 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15646 	}
15647 	/* If app asked for hoplimit and it has changed ... */
15648 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15649 		toh = (struct T_opthdr *)optptr;
15650 		toh->level = IPPROTO_IPV6;
15651 		toh->name = IPV6_HOPLIMIT;
15652 		toh->len = sizeof (*toh) + sizeof (uint_t);
15653 		toh->status = 0;
15654 		optptr += sizeof (*toh);
15655 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15656 		optptr += sizeof (uint_t);
15657 		ASSERT(OK_32PTR(optptr));
15658 		/* Save as "last" value */
15659 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15660 	}
15661 	/* If app asked for tclass and it has changed ... */
15662 	if (addflag & TCP_IPV6_RECVTCLASS) {
15663 		toh = (struct T_opthdr *)optptr;
15664 		toh->level = IPPROTO_IPV6;
15665 		toh->name = IPV6_TCLASS;
15666 		toh->len = sizeof (*toh) + sizeof (uint_t);
15667 		toh->status = 0;
15668 		optptr += sizeof (*toh);
15669 		*(uint_t *)optptr = ipp->ipp_tclass;
15670 		optptr += sizeof (uint_t);
15671 		ASSERT(OK_32PTR(optptr));
15672 		/* Save as "last" value */
15673 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15674 	}
15675 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15676 		toh = (struct T_opthdr *)optptr;
15677 		toh->level = IPPROTO_IPV6;
15678 		toh->name = IPV6_HOPOPTS;
15679 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15680 		    tcp->tcp_label_len;
15681 		toh->status = 0;
15682 		optptr += sizeof (*toh);
15683 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15684 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15685 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15686 		ASSERT(OK_32PTR(optptr));
15687 		/* Save as last value */
15688 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15689 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15690 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15691 	}
15692 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15693 		toh = (struct T_opthdr *)optptr;
15694 		toh->level = IPPROTO_IPV6;
15695 		toh->name = IPV6_RTHDRDSTOPTS;
15696 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15697 		toh->status = 0;
15698 		optptr += sizeof (*toh);
15699 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15700 		optptr += ipp->ipp_rtdstoptslen;
15701 		ASSERT(OK_32PTR(optptr));
15702 		/* Save as last value */
15703 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15704 		    &tcp->tcp_rtdstoptslen,
15705 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15706 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15707 	}
15708 	if (addflag & TCP_IPV6_RECVRTHDR) {
15709 		toh = (struct T_opthdr *)optptr;
15710 		toh->level = IPPROTO_IPV6;
15711 		toh->name = IPV6_RTHDR;
15712 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15713 		toh->status = 0;
15714 		optptr += sizeof (*toh);
15715 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15716 		optptr += ipp->ipp_rthdrlen;
15717 		ASSERT(OK_32PTR(optptr));
15718 		/* Save as last value */
15719 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15720 		    (ipp->ipp_fields & IPPF_RTHDR),
15721 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15722 	}
15723 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15724 		toh = (struct T_opthdr *)optptr;
15725 		toh->level = IPPROTO_IPV6;
15726 		toh->name = IPV6_DSTOPTS;
15727 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15728 		toh->status = 0;
15729 		optptr += sizeof (*toh);
15730 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15731 		optptr += ipp->ipp_dstoptslen;
15732 		ASSERT(OK_32PTR(optptr));
15733 		/* Save as last value */
15734 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15735 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15736 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15737 	}
15738 	ASSERT(optptr == mp->b_wptr);
15739 	return (mp);
15740 }
15741 
15742 /*
15743  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15744  * messages.
15745  */
15746 void
15747 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15748 {
15749 	uchar_t	*rptr = mp->b_rptr;
15750 	queue_t	*q = tcp->tcp_rq;
15751 	struct T_error_ack *tea;
15752 
15753 	switch (mp->b_datap->db_type) {
15754 	case M_PROTO:
15755 	case M_PCPROTO:
15756 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15757 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15758 			break;
15759 		tea = (struct T_error_ack *)rptr;
15760 		ASSERT(tea->PRIM_type != T_BIND_ACK);
15761 		ASSERT(tea->ERROR_prim != O_T_BIND_REQ &&
15762 		    tea->ERROR_prim != T_BIND_REQ);
15763 		switch (tea->PRIM_type) {
15764 		case T_ERROR_ACK:
15765 			if (tcp->tcp_debug) {
15766 				(void) strlog(TCP_MOD_ID, 0, 1,
15767 				    SL_TRACE|SL_ERROR,
15768 				    "tcp_rput_other: case T_ERROR_ACK, "
15769 				    "ERROR_prim == %d",
15770 				    tea->ERROR_prim);
15771 			}
15772 			switch (tea->ERROR_prim) {
15773 			case T_SVR4_OPTMGMT_REQ:
15774 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15775 					/* T_OPTMGMT_REQ generated by TCP */
15776 					printf("T_SVR4_OPTMGMT_REQ failed "
15777 					    "%d/%d - dropped (cnt %d)\n",
15778 					    tea->TLI_error, tea->UNIX_error,
15779 					    tcp->tcp_drop_opt_ack_cnt);
15780 					freemsg(mp);
15781 					tcp->tcp_drop_opt_ack_cnt--;
15782 					return;
15783 				}
15784 				break;
15785 			}
15786 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15787 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15788 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15789 				    "- dropped (cnt %d)\n",
15790 				    tea->TLI_error, tea->UNIX_error,
15791 				    tcp->tcp_drop_opt_ack_cnt);
15792 				freemsg(mp);
15793 				tcp->tcp_drop_opt_ack_cnt--;
15794 				return;
15795 			}
15796 			break;
15797 		case T_OPTMGMT_ACK:
15798 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15799 				/* T_OPTMGMT_REQ generated by TCP */
15800 				freemsg(mp);
15801 				tcp->tcp_drop_opt_ack_cnt--;
15802 				return;
15803 			}
15804 			break;
15805 		default:
15806 			ASSERT(tea->ERROR_prim != T_UNBIND_REQ);
15807 			break;
15808 		}
15809 		break;
15810 	case M_FLUSH:
15811 		if (*rptr & FLUSHR)
15812 			flushq(q, FLUSHDATA);
15813 		break;
15814 	default:
15815 		/* M_CTL will be directly sent to tcp_icmp_error() */
15816 		ASSERT(DB_TYPE(mp) != M_CTL);
15817 		break;
15818 	}
15819 	/*
15820 	 * Make sure we set this bit before sending the ACK for
15821 	 * bind. Otherwise accept could possibly run and free
15822 	 * this tcp struct.
15823 	 */
15824 	ASSERT(q != NULL);
15825 	putnext(q, mp);
15826 }
15827 
15828 /* ARGSUSED */
15829 static void
15830 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15831 {
15832 	conn_t	*connp = (conn_t *)arg;
15833 	tcp_t	*tcp = connp->conn_tcp;
15834 	queue_t	*q = tcp->tcp_rq;
15835 	uint_t	thwin;
15836 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15837 	sodirect_t	*sodp;
15838 	boolean_t	fc;
15839 
15840 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15841 	tcp->tcp_rsrv_mp = mp;
15842 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15843 
15844 	TCP_STAT(tcps, tcp_rsrv_calls);
15845 
15846 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15847 		return;
15848 	}
15849 
15850 	if (tcp->tcp_fused) {
15851 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15852 
15853 		ASSERT(tcp->tcp_fused);
15854 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15855 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15856 		ASSERT(!TCP_IS_DETACHED(tcp));
15857 		ASSERT(tcp->tcp_connp->conn_sqp ==
15858 		    peer_tcp->tcp_connp->conn_sqp);
15859 
15860 		/*
15861 		 * Normally we would not get backenabled in synchronous
15862 		 * streams mode, but in case this happens, we need to plug
15863 		 * synchronous streams during our drain to prevent a race
15864 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
15865 		 */
15866 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
15867 		if (tcp->tcp_rcv_list != NULL)
15868 			(void) tcp_rcv_drain(tcp);
15869 
15870 		if (peer_tcp > tcp) {
15871 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15872 			mutex_enter(&tcp->tcp_non_sq_lock);
15873 		} else {
15874 			mutex_enter(&tcp->tcp_non_sq_lock);
15875 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15876 		}
15877 
15878 		if (peer_tcp->tcp_flow_stopped &&
15879 		    (TCP_UNSENT_BYTES(peer_tcp) <=
15880 		    peer_tcp->tcp_xmit_lowater)) {
15881 			tcp_clrqfull(peer_tcp);
15882 		}
15883 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
15884 		mutex_exit(&tcp->tcp_non_sq_lock);
15885 
15886 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
15887 		TCP_STAT(tcps, tcp_fusion_backenabled);
15888 		return;
15889 	}
15890 
15891 	SOD_PTR_ENTER(tcp, sodp);
15892 	if (sodp != NULL) {
15893 		/* An sodirect connection */
15894 		if (SOD_QFULL(sodp)) {
15895 			/* Flow-controlled, need another back-enable */
15896 			fc = B_TRUE;
15897 			SOD_QSETBE(sodp);
15898 		} else {
15899 			/* Not flow-controlled */
15900 			fc = B_FALSE;
15901 		}
15902 		mutex_exit(sodp->sod_lockp);
15903 	} else if (canputnext(q)) {
15904 		/* STREAMS, not flow-controlled */
15905 		fc = B_FALSE;
15906 	} else {
15907 		/* STREAMS, flow-controlled */
15908 		fc = B_TRUE;
15909 	}
15910 	if (!fc) {
15911 		/* Not flow-controlled, open rwnd */
15912 		tcp->tcp_rwnd = q->q_hiwat;
15913 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15914 		    << tcp->tcp_rcv_ws;
15915 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15916 		/*
15917 		 * Send back a window update immediately if TCP is above
15918 		 * ESTABLISHED state and the increase of the rcv window
15919 		 * that the other side knows is at least 1 MSS after flow
15920 		 * control is lifted.
15921 		 */
15922 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15923 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15924 			tcp_xmit_ctl(NULL, tcp,
15925 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15926 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15927 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
15928 		}
15929 	}
15930 }
15931 
15932 /*
15933  * The read side service routine is called mostly when we get back-enabled as a
15934  * result of flow control relief.  Since we don't actually queue anything in
15935  * TCP, we have no data to send out of here.  What we do is clear the receive
15936  * window, and send out a window update.
15937  */
15938 static void
15939 tcp_rsrv(queue_t *q)
15940 {
15941 	conn_t		*connp = Q_TO_CONN(q);
15942 	tcp_t		*tcp = connp->conn_tcp;
15943 	mblk_t		*mp;
15944 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15945 
15946 	/* No code does a putq on the read side */
15947 	ASSERT(q->q_first == NULL);
15948 
15949 	/* Nothing to do for the default queue */
15950 	if (q == tcps->tcps_g_q) {
15951 		return;
15952 	}
15953 
15954 	/*
15955 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
15956 	 * been run.  So just return.
15957 	 */
15958 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15959 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
15960 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
15961 		return;
15962 	}
15963 	tcp->tcp_rsrv_mp = NULL;
15964 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15965 
15966 	CONN_INC_REF(connp);
15967 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15968 	    SQ_PROCESS, SQTAG_TCP_RSRV);
15969 }
15970 
15971 /*
15972  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15973  * We do not allow the receive window to shrink.  After setting rwnd,
15974  * set the flow control hiwat of the stream.
15975  *
15976  * This function is called in 2 cases:
15977  *
15978  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15979  *    connection (passive open) and in tcp_rput_data() for active connect.
15980  *    This is called after tcp_mss_set() when the desired MSS value is known.
15981  *    This makes sure that our window size is a mutiple of the other side's
15982  *    MSS.
15983  * 2) Handling SO_RCVBUF option.
15984  *
15985  * It is ASSUMED that the requested size is a multiple of the current MSS.
15986  *
15987  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15988  * user requests so.
15989  */
15990 static int
15991 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15992 {
15993 	uint32_t	mss = tcp->tcp_mss;
15994 	uint32_t	old_max_rwnd;
15995 	uint32_t	max_transmittable_rwnd;
15996 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15997 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15998 
15999 	if (tcp->tcp_fused) {
16000 		size_t sth_hiwat;
16001 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16002 
16003 		ASSERT(peer_tcp != NULL);
16004 		/*
16005 		 * Record the stream head's high water mark for
16006 		 * this endpoint; this is used for flow-control
16007 		 * purposes in tcp_fuse_output().
16008 		 */
16009 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16010 		if (!tcp_detached) {
16011 			(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
16012 			    sth_hiwat);
16013 			if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
16014 				conn_t *connp = tcp->tcp_connp;
16015 				struct sock_proto_props sopp;
16016 
16017 				sopp.sopp_flags = SOCKOPT_RCVTHRESH;
16018 				sopp.sopp_rcvthresh = sth_hiwat >> 3;
16019 
16020 				(*connp->conn_upcalls->su_set_proto_props)
16021 				    (connp->conn_upper_handle, &sopp);
16022 			}
16023 		}
16024 
16025 		/*
16026 		 * In the fusion case, the maxpsz stream head value of
16027 		 * our peer is set according to its send buffer size
16028 		 * and our receive buffer size; since the latter may
16029 		 * have changed we need to update the peer's maxpsz.
16030 		 */
16031 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16032 		return (rwnd);
16033 	}
16034 
16035 	if (tcp_detached) {
16036 		old_max_rwnd = tcp->tcp_rwnd;
16037 	} else {
16038 		old_max_rwnd = tcp->tcp_recv_hiwater;
16039 	}
16040 
16041 	/*
16042 	 * Insist on a receive window that is at least
16043 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16044 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16045 	 * and delayed acknowledgement.
16046 	 */
16047 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16048 
16049 	/*
16050 	 * If window size info has already been exchanged, TCP should not
16051 	 * shrink the window.  Shrinking window is doable if done carefully.
16052 	 * We may add that support later.  But so far there is not a real
16053 	 * need to do that.
16054 	 */
16055 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16056 		/* MSS may have changed, do a round up again. */
16057 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16058 	}
16059 
16060 	/*
16061 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16062 	 * can be applied even before the window scale option is decided.
16063 	 */
16064 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16065 	if (rwnd > max_transmittable_rwnd) {
16066 		rwnd = max_transmittable_rwnd -
16067 		    (max_transmittable_rwnd % mss);
16068 		if (rwnd < mss)
16069 			rwnd = max_transmittable_rwnd;
16070 		/*
16071 		 * If we're over the limit we may have to back down tcp_rwnd.
16072 		 * The increment below won't work for us. So we set all three
16073 		 * here and the increment below will have no effect.
16074 		 */
16075 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16076 	}
16077 	if (tcp->tcp_localnet) {
16078 		tcp->tcp_rack_abs_max =
16079 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16080 	} else {
16081 		/*
16082 		 * For a remote host on a different subnet (through a router),
16083 		 * we ack every other packet to be conforming to RFC1122.
16084 		 * tcp_deferred_acks_max is default to 2.
16085 		 */
16086 		tcp->tcp_rack_abs_max =
16087 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16088 	}
16089 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16090 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16091 	else
16092 		tcp->tcp_rack_cur_max = 0;
16093 	/*
16094 	 * Increment the current rwnd by the amount the maximum grew (we
16095 	 * can not overwrite it since we might be in the middle of a
16096 	 * connection.)
16097 	 */
16098 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16099 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16100 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16101 		tcp->tcp_cwnd_max = rwnd;
16102 
16103 	if (tcp_detached)
16104 		return (rwnd);
16105 	/*
16106 	 * We set the maximum receive window into rq->q_hiwat if it is
16107 	 * a STREAMS socket.
16108 	 * This is not actually used for flow control.
16109 	 */
16110 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
16111 		tcp->tcp_rq->q_hiwat = rwnd;
16112 	tcp->tcp_recv_hiwater = rwnd;
16113 	/*
16114 	 * Set the STREAM head high water mark. This doesn't have to be
16115 	 * here, since we are simply using default values, but we would
16116 	 * prefer to choose these values algorithmically, with a likely
16117 	 * relationship to rwnd.
16118 	 */
16119 	(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
16120 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16121 	return (rwnd);
16122 }
16123 
16124 /*
16125  * Return SNMP stuff in buffer in mpdata.
16126  */
16127 mblk_t *
16128 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16129 {
16130 	mblk_t			*mpdata;
16131 	mblk_t			*mp_conn_ctl = NULL;
16132 	mblk_t			*mp_conn_tail;
16133 	mblk_t			*mp_attr_ctl = NULL;
16134 	mblk_t			*mp_attr_tail;
16135 	mblk_t			*mp6_conn_ctl = NULL;
16136 	mblk_t			*mp6_conn_tail;
16137 	mblk_t			*mp6_attr_ctl = NULL;
16138 	mblk_t			*mp6_attr_tail;
16139 	struct opthdr		*optp;
16140 	mib2_tcpConnEntry_t	tce;
16141 	mib2_tcp6ConnEntry_t	tce6;
16142 	mib2_transportMLPEntry_t mlp;
16143 	connf_t			*connfp;
16144 	int			i;
16145 	boolean_t 		ispriv;
16146 	zoneid_t 		zoneid;
16147 	int			v4_conn_idx;
16148 	int			v6_conn_idx;
16149 	conn_t			*connp = Q_TO_CONN(q);
16150 	tcp_stack_t		*tcps;
16151 	ip_stack_t		*ipst;
16152 	mblk_t			*mp2ctl;
16153 
16154 	/*
16155 	 * make a copy of the original message
16156 	 */
16157 	mp2ctl = copymsg(mpctl);
16158 
16159 	if (mpctl == NULL ||
16160 	    (mpdata = mpctl->b_cont) == NULL ||
16161 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16162 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16163 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16164 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16165 		freemsg(mp_conn_ctl);
16166 		freemsg(mp_attr_ctl);
16167 		freemsg(mp6_conn_ctl);
16168 		freemsg(mp6_attr_ctl);
16169 		freemsg(mpctl);
16170 		freemsg(mp2ctl);
16171 		return (NULL);
16172 	}
16173 
16174 	ipst = connp->conn_netstack->netstack_ip;
16175 	tcps = connp->conn_netstack->netstack_tcp;
16176 
16177 	/* build table of connections -- need count in fixed part */
16178 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16179 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16180 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16181 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16182 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16183 
16184 	ispriv =
16185 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16186 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16187 
16188 	v4_conn_idx = v6_conn_idx = 0;
16189 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16190 
16191 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16192 		ipst = tcps->tcps_netstack->netstack_ip;
16193 
16194 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16195 
16196 		connp = NULL;
16197 
16198 		while ((connp =
16199 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16200 			tcp_t *tcp;
16201 			boolean_t needattr;
16202 
16203 			if (connp->conn_zoneid != zoneid)
16204 				continue;	/* not in this zone */
16205 
16206 			tcp = connp->conn_tcp;
16207 			UPDATE_MIB(&tcps->tcps_mib,
16208 			    tcpHCInSegs, tcp->tcp_ibsegs);
16209 			tcp->tcp_ibsegs = 0;
16210 			UPDATE_MIB(&tcps->tcps_mib,
16211 			    tcpHCOutSegs, tcp->tcp_obsegs);
16212 			tcp->tcp_obsegs = 0;
16213 
16214 			tce6.tcp6ConnState = tce.tcpConnState =
16215 			    tcp_snmp_state(tcp);
16216 			if (tce.tcpConnState == MIB2_TCP_established ||
16217 			    tce.tcpConnState == MIB2_TCP_closeWait)
16218 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16219 
16220 			needattr = B_FALSE;
16221 			bzero(&mlp, sizeof (mlp));
16222 			if (connp->conn_mlp_type != mlptSingle) {
16223 				if (connp->conn_mlp_type == mlptShared ||
16224 				    connp->conn_mlp_type == mlptBoth)
16225 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16226 				if (connp->conn_mlp_type == mlptPrivate ||
16227 				    connp->conn_mlp_type == mlptBoth)
16228 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16229 				needattr = B_TRUE;
16230 			}
16231 			if (connp->conn_peercred != NULL) {
16232 				ts_label_t *tsl;
16233 
16234 				tsl = crgetlabel(connp->conn_peercred);
16235 				mlp.tme_doi = label2doi(tsl);
16236 				mlp.tme_label = *label2bslabel(tsl);
16237 				needattr = B_TRUE;
16238 			}
16239 
16240 			/* Create a message to report on IPv6 entries */
16241 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16242 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16243 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16244 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16245 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16246 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16247 			/* Don't want just anybody seeing these... */
16248 			if (ispriv) {
16249 				tce6.tcp6ConnEntryInfo.ce_snxt =
16250 				    tcp->tcp_snxt;
16251 				tce6.tcp6ConnEntryInfo.ce_suna =
16252 				    tcp->tcp_suna;
16253 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16254 				    tcp->tcp_rnxt;
16255 				tce6.tcp6ConnEntryInfo.ce_rack =
16256 				    tcp->tcp_rack;
16257 			} else {
16258 				/*
16259 				 * Netstat, unfortunately, uses this to
16260 				 * get send/receive queue sizes.  How to fix?
16261 				 * Why not compute the difference only?
16262 				 */
16263 				tce6.tcp6ConnEntryInfo.ce_snxt =
16264 				    tcp->tcp_snxt - tcp->tcp_suna;
16265 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16266 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16267 				    tcp->tcp_rnxt - tcp->tcp_rack;
16268 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16269 			}
16270 
16271 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16272 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16273 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16274 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16275 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16276 
16277 			tce6.tcp6ConnCreationProcess =
16278 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16279 			    tcp->tcp_cpid;
16280 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16281 
16282 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16283 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16284 
16285 			mlp.tme_connidx = v6_conn_idx++;
16286 			if (needattr)
16287 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16288 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16289 			}
16290 			/*
16291 			 * Create an IPv4 table entry for IPv4 entries and also
16292 			 * for IPv6 entries which are bound to in6addr_any
16293 			 * but don't have IPV6_V6ONLY set.
16294 			 * (i.e. anything an IPv4 peer could connect to)
16295 			 */
16296 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16297 			    (tcp->tcp_state <= TCPS_LISTEN &&
16298 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16299 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16300 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16301 					tce.tcpConnRemAddress = INADDR_ANY;
16302 					tce.tcpConnLocalAddress = INADDR_ANY;
16303 				} else {
16304 					tce.tcpConnRemAddress =
16305 					    tcp->tcp_remote;
16306 					tce.tcpConnLocalAddress =
16307 					    tcp->tcp_ip_src;
16308 				}
16309 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16310 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16311 				/* Don't want just anybody seeing these... */
16312 				if (ispriv) {
16313 					tce.tcpConnEntryInfo.ce_snxt =
16314 					    tcp->tcp_snxt;
16315 					tce.tcpConnEntryInfo.ce_suna =
16316 					    tcp->tcp_suna;
16317 					tce.tcpConnEntryInfo.ce_rnxt =
16318 					    tcp->tcp_rnxt;
16319 					tce.tcpConnEntryInfo.ce_rack =
16320 					    tcp->tcp_rack;
16321 				} else {
16322 					/*
16323 					 * Netstat, unfortunately, uses this to
16324 					 * get send/receive queue sizes.  How
16325 					 * to fix?
16326 					 * Why not compute the difference only?
16327 					 */
16328 					tce.tcpConnEntryInfo.ce_snxt =
16329 					    tcp->tcp_snxt - tcp->tcp_suna;
16330 					tce.tcpConnEntryInfo.ce_suna = 0;
16331 					tce.tcpConnEntryInfo.ce_rnxt =
16332 					    tcp->tcp_rnxt - tcp->tcp_rack;
16333 					tce.tcpConnEntryInfo.ce_rack = 0;
16334 				}
16335 
16336 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16337 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16338 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16339 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16340 				tce.tcpConnEntryInfo.ce_state =
16341 				    tcp->tcp_state;
16342 
16343 				tce.tcpConnCreationProcess =
16344 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16345 				    tcp->tcp_cpid;
16346 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16347 
16348 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16349 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16350 
16351 				mlp.tme_connidx = v4_conn_idx++;
16352 				if (needattr)
16353 					(void) snmp_append_data2(
16354 					    mp_attr_ctl->b_cont,
16355 					    &mp_attr_tail, (char *)&mlp,
16356 					    sizeof (mlp));
16357 			}
16358 		}
16359 	}
16360 
16361 	/* fixed length structure for IPv4 and IPv6 counters */
16362 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16363 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16364 	    sizeof (mib2_tcp6ConnEntry_t));
16365 	/* synchronize 32- and 64-bit counters */
16366 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16367 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16368 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16369 	optp->level = MIB2_TCP;
16370 	optp->name = 0;
16371 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16372 	    sizeof (tcps->tcps_mib));
16373 	optp->len = msgdsize(mpdata);
16374 	qreply(q, mpctl);
16375 
16376 	/* table of connections... */
16377 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16378 	    sizeof (struct T_optmgmt_ack)];
16379 	optp->level = MIB2_TCP;
16380 	optp->name = MIB2_TCP_CONN;
16381 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16382 	qreply(q, mp_conn_ctl);
16383 
16384 	/* table of MLP attributes... */
16385 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16386 	    sizeof (struct T_optmgmt_ack)];
16387 	optp->level = MIB2_TCP;
16388 	optp->name = EXPER_XPORT_MLP;
16389 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16390 	if (optp->len == 0)
16391 		freemsg(mp_attr_ctl);
16392 	else
16393 		qreply(q, mp_attr_ctl);
16394 
16395 	/* table of IPv6 connections... */
16396 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16397 	    sizeof (struct T_optmgmt_ack)];
16398 	optp->level = MIB2_TCP6;
16399 	optp->name = MIB2_TCP6_CONN;
16400 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16401 	qreply(q, mp6_conn_ctl);
16402 
16403 	/* table of IPv6 MLP attributes... */
16404 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16405 	    sizeof (struct T_optmgmt_ack)];
16406 	optp->level = MIB2_TCP6;
16407 	optp->name = EXPER_XPORT_MLP;
16408 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16409 	if (optp->len == 0)
16410 		freemsg(mp6_attr_ctl);
16411 	else
16412 		qreply(q, mp6_attr_ctl);
16413 	return (mp2ctl);
16414 }
16415 
16416 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16417 /* ARGSUSED */
16418 int
16419 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16420 {
16421 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16422 
16423 	switch (level) {
16424 	case MIB2_TCP:
16425 		switch (name) {
16426 		case 13:
16427 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16428 				return (0);
16429 			/* TODO: delete entry defined by tce */
16430 			return (1);
16431 		default:
16432 			return (0);
16433 		}
16434 	default:
16435 		return (1);
16436 	}
16437 }
16438 
16439 /* Translate TCP state to MIB2 TCP state. */
16440 static int
16441 tcp_snmp_state(tcp_t *tcp)
16442 {
16443 	if (tcp == NULL)
16444 		return (0);
16445 
16446 	switch (tcp->tcp_state) {
16447 	case TCPS_CLOSED:
16448 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16449 	case TCPS_BOUND:
16450 		return (MIB2_TCP_closed);
16451 	case TCPS_LISTEN:
16452 		return (MIB2_TCP_listen);
16453 	case TCPS_SYN_SENT:
16454 		return (MIB2_TCP_synSent);
16455 	case TCPS_SYN_RCVD:
16456 		return (MIB2_TCP_synReceived);
16457 	case TCPS_ESTABLISHED:
16458 		return (MIB2_TCP_established);
16459 	case TCPS_CLOSE_WAIT:
16460 		return (MIB2_TCP_closeWait);
16461 	case TCPS_FIN_WAIT_1:
16462 		return (MIB2_TCP_finWait1);
16463 	case TCPS_CLOSING:
16464 		return (MIB2_TCP_closing);
16465 	case TCPS_LAST_ACK:
16466 		return (MIB2_TCP_lastAck);
16467 	case TCPS_FIN_WAIT_2:
16468 		return (MIB2_TCP_finWait2);
16469 	case TCPS_TIME_WAIT:
16470 		return (MIB2_TCP_timeWait);
16471 	default:
16472 		return (0);
16473 	}
16474 }
16475 
16476 /*
16477  * tcp_timer is the timer service routine.  It handles the retransmission,
16478  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16479  * from the state of the tcp instance what kind of action needs to be done
16480  * at the time it is called.
16481  */
16482 static void
16483 tcp_timer(void *arg)
16484 {
16485 	mblk_t		*mp;
16486 	clock_t		first_threshold;
16487 	clock_t		second_threshold;
16488 	clock_t		ms;
16489 	uint32_t	mss;
16490 	conn_t		*connp = (conn_t *)arg;
16491 	tcp_t		*tcp = connp->conn_tcp;
16492 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16493 
16494 	tcp->tcp_timer_tid = 0;
16495 
16496 	if (tcp->tcp_fused)
16497 		return;
16498 
16499 	first_threshold =  tcp->tcp_first_timer_threshold;
16500 	second_threshold = tcp->tcp_second_timer_threshold;
16501 	switch (tcp->tcp_state) {
16502 	case TCPS_IDLE:
16503 	case TCPS_BOUND:
16504 	case TCPS_LISTEN:
16505 		return;
16506 	case TCPS_SYN_RCVD: {
16507 		tcp_t	*listener = tcp->tcp_listener;
16508 
16509 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16510 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16511 			/* it's our first timeout */
16512 			tcp->tcp_syn_rcvd_timeout = 1;
16513 			mutex_enter(&listener->tcp_eager_lock);
16514 			listener->tcp_syn_rcvd_timeout++;
16515 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16516 				/*
16517 				 * Make this eager available for drop if we
16518 				 * need to drop one to accomodate a new
16519 				 * incoming SYN request.
16520 				 */
16521 				MAKE_DROPPABLE(listener, tcp);
16522 			}
16523 			if (!listener->tcp_syn_defense &&
16524 			    (listener->tcp_syn_rcvd_timeout >
16525 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
16526 			    (tcps->tcps_conn_req_max_q0 > 200)) {
16527 				/* We may be under attack. Put on a defense. */
16528 				listener->tcp_syn_defense = B_TRUE;
16529 				cmn_err(CE_WARN, "High TCP connect timeout "
16530 				    "rate! System (port %d) may be under a "
16531 				    "SYN flood attack!",
16532 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16533 
16534 				listener->tcp_ip_addr_cache = kmem_zalloc(
16535 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16536 				    KM_NOSLEEP);
16537 			}
16538 			mutex_exit(&listener->tcp_eager_lock);
16539 		} else if (listener != NULL) {
16540 			mutex_enter(&listener->tcp_eager_lock);
16541 			tcp->tcp_syn_rcvd_timeout++;
16542 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
16543 			    !tcp->tcp_closemp_used) {
16544 				/*
16545 				 * This is our second timeout. Put the tcp in
16546 				 * the list of droppable eagers to allow it to
16547 				 * be dropped, if needed. We don't check
16548 				 * whether tcp_dontdrop is set or not to
16549 				 * protect ourselve from a SYN attack where a
16550 				 * remote host can spoof itself as one of the
16551 				 * good IP source and continue to hold
16552 				 * resources too long.
16553 				 */
16554 				MAKE_DROPPABLE(listener, tcp);
16555 			}
16556 			mutex_exit(&listener->tcp_eager_lock);
16557 		}
16558 	}
16559 		/* FALLTHRU */
16560 	case TCPS_SYN_SENT:
16561 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16562 		second_threshold = tcp->tcp_second_ctimer_threshold;
16563 		break;
16564 	case TCPS_ESTABLISHED:
16565 	case TCPS_FIN_WAIT_1:
16566 	case TCPS_CLOSING:
16567 	case TCPS_CLOSE_WAIT:
16568 	case TCPS_LAST_ACK:
16569 		/* If we have data to rexmit */
16570 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16571 			clock_t	time_to_wait;
16572 
16573 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
16574 			if (!tcp->tcp_xmit_head)
16575 				break;
16576 			time_to_wait = lbolt -
16577 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16578 			time_to_wait = tcp->tcp_rto -
16579 			    TICK_TO_MSEC(time_to_wait);
16580 			/*
16581 			 * If the timer fires too early, 1 clock tick earlier,
16582 			 * restart the timer.
16583 			 */
16584 			if (time_to_wait > msec_per_tick) {
16585 				TCP_STAT(tcps, tcp_timer_fire_early);
16586 				TCP_TIMER_RESTART(tcp, time_to_wait);
16587 				return;
16588 			}
16589 			/*
16590 			 * When we probe zero windows, we force the swnd open.
16591 			 * If our peer acks with a closed window swnd will be
16592 			 * set to zero by tcp_rput(). As long as we are
16593 			 * receiving acks tcp_rput will
16594 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16595 			 * first and second interval actions.  NOTE: the timer
16596 			 * interval is allowed to continue its exponential
16597 			 * backoff.
16598 			 */
16599 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16600 				if (tcp->tcp_debug) {
16601 					(void) strlog(TCP_MOD_ID, 0, 1,
16602 					    SL_TRACE, "tcp_timer: zero win");
16603 				}
16604 			} else {
16605 				/*
16606 				 * After retransmission, we need to do
16607 				 * slow start.  Set the ssthresh to one
16608 				 * half of current effective window and
16609 				 * cwnd to one MSS.  Also reset
16610 				 * tcp_cwnd_cnt.
16611 				 *
16612 				 * Note that if tcp_ssthresh is reduced because
16613 				 * of ECN, do not reduce it again unless it is
16614 				 * already one window of data away (tcp_cwr
16615 				 * should then be cleared) or this is a
16616 				 * timeout for a retransmitted segment.
16617 				 */
16618 				uint32_t npkt;
16619 
16620 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16621 					npkt = ((tcp->tcp_timer_backoff ?
16622 					    tcp->tcp_cwnd_ssthresh :
16623 					    tcp->tcp_snxt -
16624 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16625 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16626 					    tcp->tcp_mss;
16627 				}
16628 				tcp->tcp_cwnd = tcp->tcp_mss;
16629 				tcp->tcp_cwnd_cnt = 0;
16630 				if (tcp->tcp_ecn_ok) {
16631 					tcp->tcp_cwr = B_TRUE;
16632 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16633 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16634 				}
16635 			}
16636 			break;
16637 		}
16638 		/*
16639 		 * We have something to send yet we cannot send.  The
16640 		 * reason can be:
16641 		 *
16642 		 * 1. Zero send window: we need to do zero window probe.
16643 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16644 		 * segments.
16645 		 * 3. SWS avoidance: receiver may have shrunk window,
16646 		 * reset our knowledge.
16647 		 *
16648 		 * Note that condition 2 can happen with either 1 or
16649 		 * 3.  But 1 and 3 are exclusive.
16650 		 */
16651 		if (tcp->tcp_unsent != 0) {
16652 			if (tcp->tcp_cwnd == 0) {
16653 				/*
16654 				 * Set tcp_cwnd to 1 MSS so that a
16655 				 * new segment can be sent out.  We
16656 				 * are "clocking out" new data when
16657 				 * the network is really congested.
16658 				 */
16659 				ASSERT(tcp->tcp_ecn_ok);
16660 				tcp->tcp_cwnd = tcp->tcp_mss;
16661 			}
16662 			if (tcp->tcp_swnd == 0) {
16663 				/* Extend window for zero window probe */
16664 				tcp->tcp_swnd++;
16665 				tcp->tcp_zero_win_probe = B_TRUE;
16666 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
16667 			} else {
16668 				/*
16669 				 * Handle timeout from sender SWS avoidance.
16670 				 * Reset our knowledge of the max send window
16671 				 * since the receiver might have reduced its
16672 				 * receive buffer.  Avoid setting tcp_max_swnd
16673 				 * to one since that will essentially disable
16674 				 * the SWS checks.
16675 				 *
16676 				 * Note that since we don't have a SWS
16677 				 * state variable, if the timeout is set
16678 				 * for ECN but not for SWS, this
16679 				 * code will also be executed.  This is
16680 				 * fine as tcp_max_swnd is updated
16681 				 * constantly and it will not affect
16682 				 * anything.
16683 				 */
16684 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16685 			}
16686 			tcp_wput_data(tcp, NULL, B_FALSE);
16687 			return;
16688 		}
16689 		/* Is there a FIN that needs to be to re retransmitted? */
16690 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16691 		    !tcp->tcp_fin_acked)
16692 			break;
16693 		/* Nothing to do, return without restarting timer. */
16694 		TCP_STAT(tcps, tcp_timer_fire_miss);
16695 		return;
16696 	case TCPS_FIN_WAIT_2:
16697 		/*
16698 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16699 		 * We waited some time for for peer's FIN, but it hasn't
16700 		 * arrived.  We flush the connection now to avoid
16701 		 * case where the peer has rebooted.
16702 		 */
16703 		if (TCP_IS_DETACHED(tcp)) {
16704 			(void) tcp_clean_death(tcp, 0, 23);
16705 		} else {
16706 			TCP_TIMER_RESTART(tcp,
16707 			    tcps->tcps_fin_wait_2_flush_interval);
16708 		}
16709 		return;
16710 	case TCPS_TIME_WAIT:
16711 		(void) tcp_clean_death(tcp, 0, 24);
16712 		return;
16713 	default:
16714 		if (tcp->tcp_debug) {
16715 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16716 			    "tcp_timer: strange state (%d) %s",
16717 			    tcp->tcp_state, tcp_display(tcp, NULL,
16718 			    DISP_PORT_ONLY));
16719 		}
16720 		return;
16721 	}
16722 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16723 		/*
16724 		 * For zero window probe, we need to send indefinitely,
16725 		 * unless we have not heard from the other side for some
16726 		 * time...
16727 		 */
16728 		if ((tcp->tcp_zero_win_probe == 0) ||
16729 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16730 		    second_threshold)) {
16731 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
16732 			/*
16733 			 * If TCP is in SYN_RCVD state, send back a
16734 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16735 			 * should be zero in TCPS_SYN_RCVD state.
16736 			 */
16737 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16738 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16739 				    "in SYN_RCVD",
16740 				    tcp, tcp->tcp_snxt,
16741 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16742 			}
16743 			(void) tcp_clean_death(tcp,
16744 			    tcp->tcp_client_errno ?
16745 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16746 			return;
16747 		} else {
16748 			/*
16749 			 * Set tcp_ms_we_have_waited to second_threshold
16750 			 * so that in next timeout, we will do the above
16751 			 * check (lbolt - tcp_last_recv_time).  This is
16752 			 * also to avoid overflow.
16753 			 *
16754 			 * We don't need to decrement tcp_timer_backoff
16755 			 * to avoid overflow because it will be decremented
16756 			 * later if new timeout value is greater than
16757 			 * tcp_rexmit_interval_max.  In the case when
16758 			 * tcp_rexmit_interval_max is greater than
16759 			 * second_threshold, it means that we will wait
16760 			 * longer than second_threshold to send the next
16761 			 * window probe.
16762 			 */
16763 			tcp->tcp_ms_we_have_waited = second_threshold;
16764 		}
16765 	} else if (ms > first_threshold) {
16766 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16767 		    tcp->tcp_xmit_head != NULL) {
16768 			tcp->tcp_xmit_head =
16769 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16770 		}
16771 		/*
16772 		 * We have been retransmitting for too long...  The RTT
16773 		 * we calculated is probably incorrect.  Reinitialize it.
16774 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16775 		 * tcp_rtt_update so that we won't accidentally cache a
16776 		 * bad value.  But only do this if this is not a zero
16777 		 * window probe.
16778 		 */
16779 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16780 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16781 			    (tcp->tcp_rtt_sa >> 5);
16782 			tcp->tcp_rtt_sa = 0;
16783 			tcp_ip_notify(tcp);
16784 			tcp->tcp_rtt_update = 0;
16785 		}
16786 	}
16787 	tcp->tcp_timer_backoff++;
16788 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16789 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16790 	    tcps->tcps_rexmit_interval_min) {
16791 		/*
16792 		 * This means the original RTO is tcp_rexmit_interval_min.
16793 		 * So we will use tcp_rexmit_interval_min as the RTO value
16794 		 * and do the backoff.
16795 		 */
16796 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
16797 	} else {
16798 		ms <<= tcp->tcp_timer_backoff;
16799 	}
16800 	if (ms > tcps->tcps_rexmit_interval_max) {
16801 		ms = tcps->tcps_rexmit_interval_max;
16802 		/*
16803 		 * ms is at max, decrement tcp_timer_backoff to avoid
16804 		 * overflow.
16805 		 */
16806 		tcp->tcp_timer_backoff--;
16807 	}
16808 	tcp->tcp_ms_we_have_waited += ms;
16809 	if (tcp->tcp_zero_win_probe == 0) {
16810 		tcp->tcp_rto = ms;
16811 	}
16812 	TCP_TIMER_RESTART(tcp, ms);
16813 	/*
16814 	 * This is after a timeout and tcp_rto is backed off.  Set
16815 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16816 	 * restart the timer with a correct value.
16817 	 */
16818 	tcp->tcp_set_timer = 1;
16819 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16820 	if (mss > tcp->tcp_mss)
16821 		mss = tcp->tcp_mss;
16822 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16823 		mss = tcp->tcp_swnd;
16824 
16825 	if ((mp = tcp->tcp_xmit_head) != NULL)
16826 		mp->b_prev = (mblk_t *)lbolt;
16827 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16828 	    B_TRUE);
16829 
16830 	/*
16831 	 * When slow start after retransmission begins, start with
16832 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16833 	 * start phase.  tcp_snd_burst controls how many segments
16834 	 * can be sent because of an ack.
16835 	 */
16836 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16837 	tcp->tcp_snd_burst = TCP_CWND_SS;
16838 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16839 	    (tcp->tcp_unsent == 0)) {
16840 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16841 	} else {
16842 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16843 	}
16844 	tcp->tcp_rexmit = B_TRUE;
16845 	tcp->tcp_dupack_cnt = 0;
16846 
16847 	/*
16848 	 * Remove all rexmit SACK blk to start from fresh.
16849 	 */
16850 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16851 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
16852 		tcp->tcp_num_notsack_blk = 0;
16853 		tcp->tcp_cnt_notsack_list = 0;
16854 	}
16855 	if (mp == NULL) {
16856 		return;
16857 	}
16858 	/*
16859 	 * Attach credentials to retransmitted initial SYNs.
16860 	 * In theory we should use the credentials from the connect()
16861 	 * call to ensure that getpeerucred() on the peer will be correct.
16862 	 * But we assume that SYN's are not dropped for loopback connections.
16863 	 */
16864 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16865 		mblk_setcred(mp, tcp->tcp_cred, tcp->tcp_cpid);
16866 	}
16867 
16868 	tcp->tcp_csuna = tcp->tcp_snxt;
16869 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
16870 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
16871 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16872 
16873 }
16874 
16875 static int
16876 tcp_do_unbind(conn_t *connp)
16877 {
16878 	tcp_t *tcp = connp->conn_tcp;
16879 	int error = 0;
16880 
16881 	switch (tcp->tcp_state) {
16882 	case TCPS_BOUND:
16883 	case TCPS_LISTEN:
16884 		break;
16885 	default:
16886 		return (-TOUTSTATE);
16887 	}
16888 
16889 	/*
16890 	 * Need to clean up all the eagers since after the unbind, segments
16891 	 * will no longer be delivered to this listener stream.
16892 	 */
16893 	mutex_enter(&tcp->tcp_eager_lock);
16894 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16895 		tcp_eager_cleanup(tcp, 0);
16896 	}
16897 	mutex_exit(&tcp->tcp_eager_lock);
16898 
16899 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16900 		tcp->tcp_ipha->ipha_src = 0;
16901 	} else {
16902 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16903 	}
16904 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16905 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16906 	tcp_bind_hash_remove(tcp);
16907 	tcp->tcp_state = TCPS_IDLE;
16908 	tcp->tcp_mdt = B_FALSE;
16909 
16910 	connp = tcp->tcp_connp;
16911 	connp->conn_mdt_ok = B_FALSE;
16912 	ipcl_hash_remove(connp);
16913 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16914 
16915 	return (error);
16916 }
16917 
16918 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16919 static void
16920 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
16921 {
16922 	int error = tcp_do_unbind(tcp->tcp_connp);
16923 
16924 	if (error > 0) {
16925 		tcp_err_ack(tcp, mp, TSYSERR, error);
16926 	} else if (error < 0) {
16927 		tcp_err_ack(tcp, mp, -error, 0);
16928 	} else {
16929 		/* Send M_FLUSH according to TPI */
16930 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16931 
16932 		mp = mi_tpi_ok_ack_alloc(mp);
16933 		putnext(tcp->tcp_rq, mp);
16934 	}
16935 }
16936 
16937 /*
16938  * Don't let port fall into the privileged range.
16939  * Since the extra privileged ports can be arbitrary we also
16940  * ensure that we exclude those from consideration.
16941  * tcp_g_epriv_ports is not sorted thus we loop over it until
16942  * there are no changes.
16943  *
16944  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16945  * but instead the code relies on:
16946  * - the fact that the address of the array and its size never changes
16947  * - the atomic assignment of the elements of the array
16948  *
16949  * Returns 0 if there are no more ports available.
16950  *
16951  * TS note: skip multilevel ports.
16952  */
16953 static in_port_t
16954 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
16955 {
16956 	int i;
16957 	boolean_t restart = B_FALSE;
16958 	tcp_stack_t *tcps = tcp->tcp_tcps;
16959 
16960 	if (random && tcp_random_anon_port != 0) {
16961 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16962 		    sizeof (in_port_t));
16963 		/*
16964 		 * Unless changed by a sys admin, the smallest anon port
16965 		 * is 32768 and the largest anon port is 65535.  It is
16966 		 * very likely (50%) for the random port to be smaller
16967 		 * than the smallest anon port.  When that happens,
16968 		 * add port % (anon port range) to the smallest anon
16969 		 * port to get the random port.  It should fall into the
16970 		 * valid anon port range.
16971 		 */
16972 		if (port < tcps->tcps_smallest_anon_port) {
16973 			port = tcps->tcps_smallest_anon_port +
16974 			    port % (tcps->tcps_largest_anon_port -
16975 			    tcps->tcps_smallest_anon_port);
16976 		}
16977 	}
16978 
16979 retry:
16980 	if (port < tcps->tcps_smallest_anon_port)
16981 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16982 
16983 	if (port > tcps->tcps_largest_anon_port) {
16984 		if (restart)
16985 			return (0);
16986 		restart = B_TRUE;
16987 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16988 	}
16989 
16990 	if (port < tcps->tcps_smallest_nonpriv_port)
16991 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
16992 
16993 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
16994 		if (port == tcps->tcps_g_epriv_ports[i]) {
16995 			port++;
16996 			/*
16997 			 * Make sure whether the port is in the
16998 			 * valid range.
16999 			 */
17000 			goto retry;
17001 		}
17002 	}
17003 	if (is_system_labeled() &&
17004 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17005 	    IPPROTO_TCP, B_TRUE)) != 0) {
17006 		port = i;
17007 		goto retry;
17008 	}
17009 	return (port);
17010 }
17011 
17012 /*
17013  * Return the next anonymous port in the privileged port range for
17014  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17015  * downwards.  This is the same behavior as documented in the userland
17016  * library call rresvport(3N).
17017  *
17018  * TS note: skip multilevel ports.
17019  */
17020 static in_port_t
17021 tcp_get_next_priv_port(const tcp_t *tcp)
17022 {
17023 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17024 	in_port_t nextport;
17025 	boolean_t restart = B_FALSE;
17026 	tcp_stack_t *tcps = tcp->tcp_tcps;
17027 retry:
17028 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17029 	    next_priv_port >= IPPORT_RESERVED) {
17030 		next_priv_port = IPPORT_RESERVED - 1;
17031 		if (restart)
17032 			return (0);
17033 		restart = B_TRUE;
17034 	}
17035 	if (is_system_labeled() &&
17036 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17037 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17038 		next_priv_port = nextport;
17039 		goto retry;
17040 	}
17041 	return (next_priv_port--);
17042 }
17043 
17044 /* The write side r/w procedure. */
17045 
17046 #if CCS_STATS
17047 struct {
17048 	struct {
17049 		int64_t count, bytes;
17050 	} tot, hit;
17051 } wrw_stats;
17052 #endif
17053 
17054 /*
17055  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17056  * messages.
17057  */
17058 /* ARGSUSED */
17059 static void
17060 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17061 {
17062 	conn_t	*connp = (conn_t *)arg;
17063 	tcp_t	*tcp = connp->conn_tcp;
17064 	queue_t	*q = tcp->tcp_wq;
17065 
17066 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17067 	/*
17068 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17069 	 * Once the close starts, streamhead and sockfs will not let any data
17070 	 * packets come down (close ensures that there are no threads using the
17071 	 * queue and no new threads will come down) but since qprocsoff()
17072 	 * hasn't happened yet, a M_FLUSH or some non data message might
17073 	 * get reflected back (in response to our own FLUSHRW) and get
17074 	 * processed after tcp_close() is done. The conn would still be valid
17075 	 * because a ref would have added but we need to check the state
17076 	 * before actually processing the packet.
17077 	 */
17078 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17079 		freemsg(mp);
17080 		return;
17081 	}
17082 
17083 	switch (DB_TYPE(mp)) {
17084 	case M_IOCDATA:
17085 		tcp_wput_iocdata(tcp, mp);
17086 		break;
17087 	case M_FLUSH:
17088 		tcp_wput_flush(tcp, mp);
17089 		break;
17090 	default:
17091 		CALL_IP_WPUT(connp, q, mp);
17092 		break;
17093 	}
17094 }
17095 
17096 /*
17097  * The TCP fast path write put procedure.
17098  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17099  */
17100 /* ARGSUSED */
17101 void
17102 tcp_output(void *arg, mblk_t *mp, void *arg2)
17103 {
17104 	int		len;
17105 	int		hdrlen;
17106 	int		plen;
17107 	mblk_t		*mp1;
17108 	uchar_t		*rptr;
17109 	uint32_t	snxt;
17110 	tcph_t		*tcph;
17111 	struct datab	*db;
17112 	uint32_t	suna;
17113 	uint32_t	mss;
17114 	ipaddr_t	*dst;
17115 	ipaddr_t	*src;
17116 	uint32_t	sum;
17117 	int		usable;
17118 	conn_t		*connp = (conn_t *)arg;
17119 	tcp_t		*tcp = connp->conn_tcp;
17120 	uint32_t	msize;
17121 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17122 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17123 
17124 	/*
17125 	 * Try and ASSERT the minimum possible references on the
17126 	 * conn early enough. Since we are executing on write side,
17127 	 * the connection is obviously not detached and that means
17128 	 * there is a ref each for TCP and IP. Since we are behind
17129 	 * the squeue, the minimum references needed are 3. If the
17130 	 * conn is in classifier hash list, there should be an
17131 	 * extra ref for that (we check both the possibilities).
17132 	 */
17133 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17134 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17135 
17136 	ASSERT(DB_TYPE(mp) == M_DATA);
17137 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17138 
17139 	mutex_enter(&tcp->tcp_non_sq_lock);
17140 	tcp->tcp_squeue_bytes -= msize;
17141 	mutex_exit(&tcp->tcp_non_sq_lock);
17142 
17143 	/* Check to see if this connection wants to be re-fused. */
17144 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
17145 		if (tcp->tcp_ipversion == IPV4_VERSION) {
17146 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
17147 			    &tcp->tcp_saved_tcph);
17148 		} else {
17149 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
17150 			    &tcp->tcp_saved_tcph);
17151 		}
17152 	}
17153 	/* Bypass tcp protocol for fused tcp loopback */
17154 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17155 		return;
17156 
17157 	mss = tcp->tcp_mss;
17158 	if (tcp->tcp_xmit_zc_clean)
17159 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17160 
17161 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17162 	len = (int)(mp->b_wptr - mp->b_rptr);
17163 
17164 	/*
17165 	 * Criteria for fast path:
17166 	 *
17167 	 *   1. no unsent data
17168 	 *   2. single mblk in request
17169 	 *   3. connection established
17170 	 *   4. data in mblk
17171 	 *   5. len <= mss
17172 	 *   6. no tcp_valid bits
17173 	 */
17174 	if ((tcp->tcp_unsent != 0) ||
17175 	    (tcp->tcp_cork) ||
17176 	    (mp->b_cont != NULL) ||
17177 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17178 	    (len == 0) ||
17179 	    (len > mss) ||
17180 	    (tcp->tcp_valid_bits != 0)) {
17181 		tcp_wput_data(tcp, mp, B_FALSE);
17182 		return;
17183 	}
17184 
17185 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17186 	ASSERT(tcp->tcp_fin_sent == 0);
17187 
17188 	/* queue new packet onto retransmission queue */
17189 	if (tcp->tcp_xmit_head == NULL) {
17190 		tcp->tcp_xmit_head = mp;
17191 	} else {
17192 		tcp->tcp_xmit_last->b_cont = mp;
17193 	}
17194 	tcp->tcp_xmit_last = mp;
17195 	tcp->tcp_xmit_tail = mp;
17196 
17197 	/* find out how much we can send */
17198 	/* BEGIN CSTYLED */
17199 	/*
17200 	 *    un-acked	   usable
17201 	 *  |--------------|-----------------|
17202 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
17203 	 */
17204 	/* END CSTYLED */
17205 
17206 	/* start sending from tcp_snxt */
17207 	snxt = tcp->tcp_snxt;
17208 
17209 	/*
17210 	 * Check to see if this connection has been idled for some
17211 	 * time and no ACK is expected.  If it is, we need to slow
17212 	 * start again to get back the connection's "self-clock" as
17213 	 * described in VJ's paper.
17214 	 *
17215 	 * Refer to the comment in tcp_mss_set() for the calculation
17216 	 * of tcp_cwnd after idle.
17217 	 */
17218 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17219 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17220 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
17221 	}
17222 
17223 	usable = tcp->tcp_swnd;		/* tcp window size */
17224 	if (usable > tcp->tcp_cwnd)
17225 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17226 	usable -= snxt;		/* subtract stuff already sent */
17227 	suna = tcp->tcp_suna;
17228 	usable += suna;
17229 	/* usable can be < 0 if the congestion window is smaller */
17230 	if (len > usable) {
17231 		/* Can't send complete M_DATA in one shot */
17232 		goto slow;
17233 	}
17234 
17235 	mutex_enter(&tcp->tcp_non_sq_lock);
17236 	if (tcp->tcp_flow_stopped &&
17237 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17238 		tcp_clrqfull(tcp);
17239 	}
17240 	mutex_exit(&tcp->tcp_non_sq_lock);
17241 
17242 	/*
17243 	 * determine if anything to send (Nagle).
17244 	 *
17245 	 *   1. len < tcp_mss (i.e. small)
17246 	 *   2. unacknowledged data present
17247 	 *   3. len < nagle limit
17248 	 *   4. last packet sent < nagle limit (previous packet sent)
17249 	 */
17250 	if ((len < mss) && (snxt != suna) &&
17251 	    (len < (int)tcp->tcp_naglim) &&
17252 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17253 		/*
17254 		 * This was the first unsent packet and normally
17255 		 * mss < xmit_hiwater so there is no need to worry
17256 		 * about flow control. The next packet will go
17257 		 * through the flow control check in tcp_wput_data().
17258 		 */
17259 		/* leftover work from above */
17260 		tcp->tcp_unsent = len;
17261 		tcp->tcp_xmit_tail_unsent = len;
17262 
17263 		return;
17264 	}
17265 
17266 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17267 
17268 	if (snxt == suna) {
17269 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17270 	}
17271 
17272 	/* we have always sent something */
17273 	tcp->tcp_rack_cnt = 0;
17274 
17275 	tcp->tcp_snxt = snxt + len;
17276 	tcp->tcp_rack = tcp->tcp_rnxt;
17277 
17278 	if ((mp1 = dupb(mp)) == 0)
17279 		goto no_memory;
17280 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17281 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17282 
17283 	/* adjust tcp header information */
17284 	tcph = tcp->tcp_tcph;
17285 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17286 
17287 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17288 	sum = (sum >> 16) + (sum & 0xFFFF);
17289 	U16_TO_ABE16(sum, tcph->th_sum);
17290 
17291 	U32_TO_ABE32(snxt, tcph->th_seq);
17292 
17293 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17294 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17295 	BUMP_LOCAL(tcp->tcp_obsegs);
17296 
17297 	/* Update the latest receive window size in TCP header. */
17298 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17299 	    tcph->th_win);
17300 
17301 	tcp->tcp_last_sent_len = (ushort_t)len;
17302 
17303 	plen = len + tcp->tcp_hdr_len;
17304 
17305 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17306 		tcp->tcp_ipha->ipha_length = htons(plen);
17307 	} else {
17308 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17309 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17310 	}
17311 
17312 	/* see if we need to allocate a mblk for the headers */
17313 	hdrlen = tcp->tcp_hdr_len;
17314 	rptr = mp1->b_rptr - hdrlen;
17315 	db = mp1->b_datap;
17316 	if ((db->db_ref != 2) || rptr < db->db_base ||
17317 	    (!OK_32PTR(rptr))) {
17318 		/* NOTE: we assume allocb returns an OK_32PTR */
17319 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17320 		    tcps->tcps_wroff_xtra, BPRI_MED);
17321 		if (!mp) {
17322 			freemsg(mp1);
17323 			goto no_memory;
17324 		}
17325 		mp->b_cont = mp1;
17326 		mp1 = mp;
17327 		/* Leave room for Link Level header */
17328 		/* hdrlen = tcp->tcp_hdr_len; */
17329 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17330 		mp1->b_wptr = &rptr[hdrlen];
17331 	}
17332 	mp1->b_rptr = rptr;
17333 
17334 	/* Fill in the timestamp option. */
17335 	if (tcp->tcp_snd_ts_ok) {
17336 		U32_TO_BE32((uint32_t)lbolt,
17337 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17338 		U32_TO_BE32(tcp->tcp_ts_recent,
17339 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17340 	} else {
17341 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17342 	}
17343 
17344 	/* copy header into outgoing packet */
17345 	dst = (ipaddr_t *)rptr;
17346 	src = (ipaddr_t *)tcp->tcp_iphc;
17347 	dst[0] = src[0];
17348 	dst[1] = src[1];
17349 	dst[2] = src[2];
17350 	dst[3] = src[3];
17351 	dst[4] = src[4];
17352 	dst[5] = src[5];
17353 	dst[6] = src[6];
17354 	dst[7] = src[7];
17355 	dst[8] = src[8];
17356 	dst[9] = src[9];
17357 	if (hdrlen -= 40) {
17358 		hdrlen >>= 2;
17359 		dst += 10;
17360 		src += 10;
17361 		do {
17362 			*dst++ = *src++;
17363 		} while (--hdrlen);
17364 	}
17365 
17366 	/*
17367 	 * Set the ECN info in the TCP header.  Note that this
17368 	 * is not the template header.
17369 	 */
17370 	if (tcp->tcp_ecn_ok) {
17371 		SET_ECT(tcp, rptr);
17372 
17373 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17374 		if (tcp->tcp_ecn_echo_on)
17375 			tcph->th_flags[0] |= TH_ECE;
17376 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17377 			tcph->th_flags[0] |= TH_CWR;
17378 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17379 		}
17380 	}
17381 
17382 	if (tcp->tcp_ip_forward_progress) {
17383 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17384 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17385 		tcp->tcp_ip_forward_progress = B_FALSE;
17386 	}
17387 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17388 	return;
17389 
17390 	/*
17391 	 * If we ran out of memory, we pretend to have sent the packet
17392 	 * and that it was lost on the wire.
17393 	 */
17394 no_memory:
17395 	return;
17396 
17397 slow:
17398 	/* leftover work from above */
17399 	tcp->tcp_unsent = len;
17400 	tcp->tcp_xmit_tail_unsent = len;
17401 	tcp_wput_data(tcp, NULL, B_FALSE);
17402 }
17403 
17404 /* ARGSUSED */
17405 void
17406 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17407 {
17408 	conn_t			*connp = (conn_t *)arg;
17409 	tcp_t			*tcp = connp->conn_tcp;
17410 	queue_t			*q = tcp->tcp_rq;
17411 	struct tcp_options	*tcpopt;
17412 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17413 
17414 	/* socket options */
17415 	uint_t 			sopp_flags;
17416 	ssize_t			sopp_rxhiwat;
17417 	ssize_t			sopp_maxblk;
17418 	ushort_t		sopp_wroff;
17419 	ushort_t		sopp_tail;
17420 	ushort_t		sopp_copyopt;
17421 
17422 	tcpopt = (struct tcp_options *)mp->b_rptr;
17423 
17424 	/*
17425 	 * Drop the eager's ref on the listener, that was placed when
17426 	 * this eager began life in tcp_conn_request.
17427 	 */
17428 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17429 	if (IPCL_IS_NONSTR(connp)) {
17430 		/* Safe to free conn_ind message */
17431 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17432 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17433 	}
17434 
17435 	tcp->tcp_detached = B_FALSE;
17436 
17437 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17438 		/*
17439 		 * Someone blewoff the eager before we could finish
17440 		 * the accept.
17441 		 *
17442 		 * The only reason eager exists it because we put in
17443 		 * a ref on it when conn ind went up. We need to send
17444 		 * a disconnect indication up while the last reference
17445 		 * on the eager will be dropped by the squeue when we
17446 		 * return.
17447 		 */
17448 		ASSERT(tcp->tcp_listener == NULL);
17449 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17450 			if (IPCL_IS_NONSTR(connp)) {
17451 				ASSERT(tcp->tcp_issocket);
17452 				(*connp->conn_upcalls->su_disconnected)(
17453 				    connp->conn_upper_handle, tcp->tcp_connid,
17454 				    ECONNREFUSED);
17455 				freemsg(mp);
17456 			} else {
17457 				struct	T_discon_ind	*tdi;
17458 
17459 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17460 				/*
17461 				 * Let us reuse the incoming mblk to avoid
17462 				 * memory allocation failure problems. We know
17463 				 * that the size of the incoming mblk i.e.
17464 				 * stroptions is greater than sizeof
17465 				 * T_discon_ind. So the reallocb below can't
17466 				 * fail.
17467 				 */
17468 				freemsg(mp->b_cont);
17469 				mp->b_cont = NULL;
17470 				ASSERT(DB_REF(mp) == 1);
17471 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17472 				    B_FALSE);
17473 				ASSERT(mp != NULL);
17474 				DB_TYPE(mp) = M_PROTO;
17475 				((union T_primitives *)mp->b_rptr)->type =
17476 				    T_DISCON_IND;
17477 				tdi = (struct T_discon_ind *)mp->b_rptr;
17478 				if (tcp->tcp_issocket) {
17479 					tdi->DISCON_reason = ECONNREFUSED;
17480 					tdi->SEQ_number = 0;
17481 				} else {
17482 					tdi->DISCON_reason = ENOPROTOOPT;
17483 					tdi->SEQ_number =
17484 					    tcp->tcp_conn_req_seqnum;
17485 				}
17486 				mp->b_wptr = mp->b_rptr +
17487 				    sizeof (struct T_discon_ind);
17488 				putnext(q, mp);
17489 				return;
17490 			}
17491 		}
17492 		if (tcp->tcp_hard_binding) {
17493 			tcp->tcp_hard_binding = B_FALSE;
17494 			tcp->tcp_hard_bound = B_TRUE;
17495 		}
17496 		return;
17497 	}
17498 
17499 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
17500 		int boundif = tcpopt->to_boundif;
17501 		uint_t len = sizeof (int);
17502 
17503 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17504 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
17505 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred, NULL);
17506 	}
17507 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
17508 		uint_t on = 1;
17509 		uint_t len = sizeof (uint_t);
17510 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17511 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
17512 		    (uchar_t *)&on, NULL, tcp->tcp_cred, NULL);
17513 	}
17514 
17515 	/*
17516 	 * For a loopback connection with tcp_direct_sockfs on, note that
17517 	 * we don't have to protect tcp_rcv_list yet because synchronous
17518 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17519 	 * possibly race with us.
17520 	 */
17521 
17522 	/*
17523 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17524 	 * properly.  This is the first time we know of the acceptor'
17525 	 * queue.  So we do it here.
17526 	 *
17527 	 * XXX
17528 	 */
17529 	if (tcp->tcp_rcv_list == NULL) {
17530 		/*
17531 		 * Recv queue is empty, tcp_rwnd should not have changed.
17532 		 * That means it should be equal to the listener's tcp_rwnd.
17533 		 */
17534 		if (!IPCL_IS_NONSTR(connp))
17535 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17536 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
17537 	} else {
17538 #ifdef DEBUG
17539 		mblk_t *tmp;
17540 		mblk_t	*mp1;
17541 		uint_t	cnt = 0;
17542 
17543 		mp1 = tcp->tcp_rcv_list;
17544 		while ((tmp = mp1) != NULL) {
17545 			mp1 = tmp->b_next;
17546 			cnt += msgdsize(tmp);
17547 		}
17548 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17549 #endif
17550 		/* There is some data, add them back to get the max. */
17551 		if (!IPCL_IS_NONSTR(connp))
17552 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17553 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17554 	}
17555 	/*
17556 	 * This is the first time we run on the correct
17557 	 * queue after tcp_accept. So fix all the q parameters
17558 	 * here.
17559 	 */
17560 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
17561 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17562 
17563 	/*
17564 	 * Record the stream head's high water mark for this endpoint;
17565 	 * this is used for flow-control purposes.
17566 	 */
17567 	sopp_rxhiwat = tcp->tcp_fused ?
17568 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
17569 	    MAX(tcp->tcp_recv_hiwater, tcps->tcps_sth_rcv_hiwat);
17570 
17571 	/*
17572 	 * Determine what write offset value to use depending on SACK and
17573 	 * whether the endpoint is fused or not.
17574 	 */
17575 	if (tcp->tcp_fused) {
17576 		ASSERT(tcp->tcp_loopback);
17577 		ASSERT(tcp->tcp_loopback_peer != NULL);
17578 		/*
17579 		 * For fused tcp loopback, set the stream head's write
17580 		 * offset value to zero since we won't be needing any room
17581 		 * for TCP/IP headers.  This would also improve performance
17582 		 * since it would reduce the amount of work done by kmem.
17583 		 * Non-fused tcp loopback case is handled separately below.
17584 		 */
17585 		sopp_wroff = 0;
17586 		/*
17587 		 * Update the peer's transmit parameters according to
17588 		 * our recently calculated high water mark value.
17589 		 */
17590 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17591 	} else if (tcp->tcp_snd_sack_ok) {
17592 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17593 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
17594 	} else {
17595 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17596 		    tcps->tcps_wroff_xtra);
17597 	}
17598 
17599 	/*
17600 	 * If this is endpoint is handling SSL, then reserve extra
17601 	 * offset and space at the end.
17602 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17603 	 * overriding the previous setting. The extra cost of signing and
17604 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17605 	 * instead of a single contiguous one by the stream head
17606 	 * largely outweighs the statistical reduction of ACKs, when
17607 	 * applicable. The peer will also save on decryption and verification
17608 	 * costs.
17609 	 */
17610 	if (tcp->tcp_kssl_ctx != NULL) {
17611 		sopp_wroff += SSL3_WROFFSET;
17612 
17613 		sopp_flags |= SOCKOPT_TAIL;
17614 		sopp_tail = SSL3_MAX_TAIL_LEN;
17615 
17616 		sopp_flags |= SOCKOPT_ZCOPY;
17617 		sopp_copyopt = ZCVMUNSAFE;
17618 
17619 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
17620 	}
17621 
17622 	/* Send the options up */
17623 	if (IPCL_IS_NONSTR(connp)) {
17624 		struct sock_proto_props sopp;
17625 
17626 		sopp.sopp_flags = sopp_flags;
17627 		sopp.sopp_wroff = sopp_wroff;
17628 		sopp.sopp_maxblk = sopp_maxblk;
17629 		sopp.sopp_rxhiwat = sopp_rxhiwat;
17630 		if (sopp_flags & SOCKOPT_TAIL) {
17631 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17632 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
17633 			sopp.sopp_tail = sopp_tail;
17634 			sopp.sopp_zcopyflag = sopp_copyopt;
17635 		}
17636 		(*connp->conn_upcalls->su_set_proto_props)
17637 		    (connp->conn_upper_handle, &sopp);
17638 	} else {
17639 		struct stroptions *stropt;
17640 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17641 		if (stropt_mp == NULL) {
17642 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
17643 			return;
17644 		}
17645 		DB_TYPE(stropt_mp) = M_SETOPTS;
17646 		stropt = (struct stroptions *)stropt_mp->b_rptr;
17647 		stropt_mp->b_wptr += sizeof (struct stroptions);
17648 		stropt = (struct stroptions *)stropt_mp->b_rptr;
17649 		stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
17650 		stropt->so_hiwat = sopp_rxhiwat;
17651 		stropt->so_wroff = sopp_wroff;
17652 		stropt->so_maxblk = sopp_maxblk;
17653 
17654 		if (sopp_flags & SOCKOPT_TAIL) {
17655 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17656 
17657 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
17658 			stropt->so_tail = sopp_tail;
17659 			stropt->so_copyopt = sopp_copyopt;
17660 		}
17661 
17662 		/* Send the options up */
17663 		putnext(q, stropt_mp);
17664 	}
17665 
17666 	freemsg(mp);
17667 	/*
17668 	 * Pass up any data and/or a fin that has been received.
17669 	 *
17670 	 * Adjust receive window in case it had decreased
17671 	 * (because there is data <=> tcp_rcv_list != NULL)
17672 	 * while the connection was detached. Note that
17673 	 * in case the eager was flow-controlled, w/o this
17674 	 * code, the rwnd may never open up again!
17675 	 */
17676 	if (tcp->tcp_rcv_list != NULL) {
17677 		if (IPCL_IS_NONSTR(connp)) {
17678 			mblk_t *mp;
17679 			int space_left;
17680 			int error;
17681 			boolean_t push = B_TRUE;
17682 
17683 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
17684 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
17685 			    &push) >= 0) {
17686 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
17687 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17688 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17689 					tcp_xmit_ctl(NULL,
17690 					    tcp, (tcp->tcp_swnd == 0) ?
17691 					    tcp->tcp_suna : tcp->tcp_snxt,
17692 					    tcp->tcp_rnxt, TH_ACK);
17693 				}
17694 			}
17695 			while ((mp = tcp->tcp_rcv_list) != NULL) {
17696 				push = B_TRUE;
17697 				tcp->tcp_rcv_list = mp->b_next;
17698 				mp->b_next = NULL;
17699 				space_left = (*connp->conn_upcalls->su_recv)
17700 				    (connp->conn_upper_handle, mp, msgdsize(mp),
17701 				    0, &error, &push);
17702 				if (space_left < 0) {
17703 					/*
17704 					 * We should never be in middle of a
17705 					 * fallback, the squeue guarantees that.
17706 					 */
17707 					ASSERT(error != EOPNOTSUPP);
17708 				}
17709 			}
17710 			tcp->tcp_rcv_last_head = NULL;
17711 			tcp->tcp_rcv_last_tail = NULL;
17712 			tcp->tcp_rcv_cnt = 0;
17713 		} else {
17714 			/* We drain directly in case of fused tcp loopback */
17715 			sodirect_t *sodp;
17716 
17717 			if (!tcp->tcp_fused && canputnext(q)) {
17718 				tcp->tcp_rwnd = q->q_hiwat;
17719 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17720 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17721 					tcp_xmit_ctl(NULL,
17722 					    tcp, (tcp->tcp_swnd == 0) ?
17723 					    tcp->tcp_suna : tcp->tcp_snxt,
17724 					    tcp->tcp_rnxt, TH_ACK);
17725 				}
17726 			}
17727 
17728 			SOD_PTR_ENTER(tcp, sodp);
17729 			if (sodp != NULL) {
17730 				/* Sodirect, move from rcv_list */
17731 				ASSERT(!tcp->tcp_fused);
17732 				while ((mp = tcp->tcp_rcv_list) != NULL) {
17733 					tcp->tcp_rcv_list = mp->b_next;
17734 					mp->b_next = NULL;
17735 					(void) tcp_rcv_sod_enqueue(tcp, sodp,
17736 					    mp, msgdsize(mp));
17737 				}
17738 				tcp->tcp_rcv_last_head = NULL;
17739 				tcp->tcp_rcv_last_tail = NULL;
17740 				tcp->tcp_rcv_cnt = 0;
17741 				(void) tcp_rcv_sod_wakeup(tcp, sodp);
17742 				/* sod_wakeup() did the mutex_exit() */
17743 			} else {
17744 				/* Not sodirect, drain */
17745 				(void) tcp_rcv_drain(tcp);
17746 			}
17747 		}
17748 
17749 		/*
17750 		 * For fused tcp loopback, back-enable peer endpoint
17751 		 * if it's currently flow-controlled.
17752 		 */
17753 		if (tcp->tcp_fused) {
17754 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17755 
17756 			ASSERT(peer_tcp != NULL);
17757 			ASSERT(peer_tcp->tcp_fused);
17758 			/*
17759 			 * In order to change the peer's tcp_flow_stopped,
17760 			 * we need to take locks for both end points. The
17761 			 * highest address is taken first.
17762 			 */
17763 			if (peer_tcp > tcp) {
17764 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
17765 				mutex_enter(&tcp->tcp_non_sq_lock);
17766 			} else {
17767 				mutex_enter(&tcp->tcp_non_sq_lock);
17768 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
17769 			}
17770 			if (peer_tcp->tcp_flow_stopped) {
17771 				tcp_clrqfull(peer_tcp);
17772 				TCP_STAT(tcps, tcp_fusion_backenabled);
17773 			}
17774 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
17775 			mutex_exit(&tcp->tcp_non_sq_lock);
17776 		}
17777 	}
17778 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17779 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17780 		tcp->tcp_ordrel_done = B_TRUE;
17781 		if (IPCL_IS_NONSTR(connp)) {
17782 			ASSERT(tcp->tcp_ordrel_mp == NULL);
17783 			(*connp->conn_upcalls->su_opctl)(
17784 			    connp->conn_upper_handle,
17785 			    SOCK_OPCTL_SHUT_RECV, 0);
17786 		} else {
17787 			mp = tcp->tcp_ordrel_mp;
17788 			tcp->tcp_ordrel_mp = NULL;
17789 			putnext(q, mp);
17790 		}
17791 	}
17792 	if (tcp->tcp_hard_binding) {
17793 		tcp->tcp_hard_binding = B_FALSE;
17794 		tcp->tcp_hard_bound = B_TRUE;
17795 	}
17796 
17797 	/* We can enable synchronous streams for STREAMS tcp endpoint now */
17798 	if (tcp->tcp_fused && !IPCL_IS_NONSTR(connp) &&
17799 	    tcp->tcp_loopback_peer != NULL &&
17800 	    !IPCL_IS_NONSTR(tcp->tcp_loopback_peer->tcp_connp)) {
17801 		tcp_fuse_syncstr_enable_pair(tcp);
17802 	}
17803 
17804 	if (tcp->tcp_ka_enabled) {
17805 		tcp->tcp_ka_last_intrvl = 0;
17806 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17807 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17808 	}
17809 
17810 	/*
17811 	 * At this point, eager is fully established and will
17812 	 * have the following references -
17813 	 *
17814 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17815 	 * 1 reference for the squeue which will be dropped by the squeue as
17816 	 *	soon as this function returns.
17817 	 * There will be 1 additonal reference for being in classifier
17818 	 *	hash list provided something bad hasn't happened.
17819 	 */
17820 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17821 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17822 }
17823 
17824 /*
17825  * The function called through squeue to get behind listener's perimeter to
17826  * send a deffered conn_ind.
17827  */
17828 /* ARGSUSED */
17829 void
17830 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17831 {
17832 	conn_t	*connp = (conn_t *)arg;
17833 	tcp_t *listener = connp->conn_tcp;
17834 	struct T_conn_ind *conn_ind;
17835 	tcp_t *tcp;
17836 
17837 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
17838 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17839 	    conn_ind->OPT_length);
17840 
17841 	if (listener->tcp_state == TCPS_CLOSED ||
17842 	    TCP_IS_DETACHED(listener)) {
17843 		/*
17844 		 * If listener has closed, it would have caused a
17845 		 * a cleanup/blowoff to happen for the eager.
17846 		 *
17847 		 * We need to drop the ref on eager that was put
17848 		 * tcp_rput_data() before trying to send the conn_ind
17849 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
17850 		 * and tcp_wput_accept() is sending this deferred conn_ind but
17851 		 * listener is closed so we drop the ref.
17852 		 */
17853 		CONN_DEC_REF(tcp->tcp_connp);
17854 		freemsg(mp);
17855 		return;
17856 	}
17857 
17858 	tcp_ulp_newconn(connp, tcp->tcp_connp, mp);
17859 }
17860 
17861 /* ARGSUSED */
17862 static int
17863 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
17864 {
17865 	tcp_t *listener, *eager;
17866 	mblk_t *opt_mp;
17867 	struct tcp_options *tcpopt;
17868 
17869 	listener = lconnp->conn_tcp;
17870 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17871 	eager = econnp->conn_tcp;
17872 	ASSERT(eager->tcp_listener != NULL);
17873 
17874 	ASSERT(eager->tcp_rq != NULL);
17875 
17876 	/* If tcp_fused and sodirect enabled disable it */
17877 	if (eager->tcp_fused && eager->tcp_sodirect != NULL) {
17878 		/* Fused, disable sodirect */
17879 		mutex_enter(eager->tcp_sodirect->sod_lockp);
17880 		SOD_DISABLE(eager->tcp_sodirect);
17881 		mutex_exit(eager->tcp_sodirect->sod_lockp);
17882 		eager->tcp_sodirect = NULL;
17883 	}
17884 
17885 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
17886 	if (opt_mp == NULL) {
17887 		return (-TPROTO);
17888 	}
17889 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
17890 	eager->tcp_issocket = B_TRUE;
17891 
17892 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17893 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
17894 	ASSERT(econnp->conn_netstack ==
17895 	    listener->tcp_connp->conn_netstack);
17896 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
17897 
17898 	/* Put the ref for IP */
17899 	CONN_INC_REF(econnp);
17900 
17901 	/*
17902 	 * We should have minimum of 3 references on the conn
17903 	 * at this point. One each for TCP and IP and one for
17904 	 * the T_conn_ind that was sent up when the 3-way handshake
17905 	 * completed. In the normal case we would also have another
17906 	 * reference (making a total of 4) for the conn being in the
17907 	 * classifier hash list. However the eager could have received
17908 	 * an RST subsequently and tcp_closei_local could have removed
17909 	 * the eager from the classifier hash list, hence we can't
17910 	 * assert that reference.
17911 	 */
17912 	ASSERT(econnp->conn_ref >= 3);
17913 
17914 	opt_mp->b_datap->db_type = M_SETOPTS;
17915 	opt_mp->b_wptr += sizeof (struct tcp_options);
17916 
17917 	/*
17918 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17919 	 * from listener to acceptor.
17920 	 */
17921 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
17922 	tcpopt->to_flags = 0;
17923 
17924 	if (listener->tcp_bound_if != 0) {
17925 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
17926 		tcpopt->to_boundif = listener->tcp_bound_if;
17927 	}
17928 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17929 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
17930 	}
17931 
17932 	mutex_enter(&listener->tcp_eager_lock);
17933 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17934 
17935 		tcp_t *tail;
17936 		tcp_t *tcp;
17937 		mblk_t *mp1;
17938 
17939 		tcp = listener->tcp_eager_prev_q0;
17940 		/*
17941 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
17942 		 * deferred T_conn_ind queue. We need to get to the head
17943 		 * of the queue in order to send up T_conn_ind the same
17944 		 * order as how the 3WHS is completed.
17945 		 */
17946 		while (tcp != listener) {
17947 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17948 			    !tcp->tcp_kssl_pending)
17949 				break;
17950 			else
17951 				tcp = tcp->tcp_eager_prev_q0;
17952 		}
17953 		/* None of the pending eagers can be sent up now */
17954 		if (tcp == listener)
17955 			goto no_more_eagers;
17956 
17957 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17958 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17959 		/* Move from q0 to q */
17960 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17961 		listener->tcp_conn_req_cnt_q0--;
17962 		listener->tcp_conn_req_cnt_q++;
17963 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17964 		    tcp->tcp_eager_prev_q0;
17965 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17966 		    tcp->tcp_eager_next_q0;
17967 		tcp->tcp_eager_prev_q0 = NULL;
17968 		tcp->tcp_eager_next_q0 = NULL;
17969 		tcp->tcp_conn_def_q0 = B_FALSE;
17970 
17971 		/* Make sure the tcp isn't in the list of droppables */
17972 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
17973 		    tcp->tcp_eager_prev_drop_q0 == NULL);
17974 
17975 		/*
17976 		 * Insert at end of the queue because sockfs sends
17977 		 * down T_CONN_RES in chronological order. Leaving
17978 		 * the older conn indications at front of the queue
17979 		 * helps reducing search time.
17980 		 */
17981 		tail = listener->tcp_eager_last_q;
17982 		if (tail != NULL) {
17983 			tail->tcp_eager_next_q = tcp;
17984 		} else {
17985 			listener->tcp_eager_next_q = tcp;
17986 		}
17987 		listener->tcp_eager_last_q = tcp;
17988 		tcp->tcp_eager_next_q = NULL;
17989 
17990 		/* Need to get inside the listener perimeter */
17991 		CONN_INC_REF(listener->tcp_connp);
17992 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
17993 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
17994 		    SQTAG_TCP_SEND_PENDING);
17995 	}
17996 no_more_eagers:
17997 	tcp_eager_unlink(eager);
17998 	mutex_exit(&listener->tcp_eager_lock);
17999 
18000 	/*
18001 	 * At this point, the eager is detached from the listener
18002 	 * but we still have an extra refs on eager (apart from the
18003 	 * usual tcp references). The ref was placed in tcp_rput_data
18004 	 * before sending the conn_ind in tcp_send_conn_ind.
18005 	 * The ref will be dropped in tcp_accept_finish().
18006 	 */
18007 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
18008 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
18009 	return (0);
18010 }
18011 
18012 int
18013 tcp_accept(sock_lower_handle_t lproto_handle,
18014     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
18015     cred_t *cr)
18016 {
18017 	conn_t *lconnp, *econnp;
18018 	tcp_t *listener, *eager;
18019 	tcp_stack_t	*tcps;
18020 
18021 	lconnp = (conn_t *)lproto_handle;
18022 	listener = lconnp->conn_tcp;
18023 	ASSERT(listener->tcp_state == TCPS_LISTEN);
18024 	econnp = (conn_t *)eproto_handle;
18025 	eager = econnp->conn_tcp;
18026 	ASSERT(eager->tcp_listener != NULL);
18027 	tcps = eager->tcp_tcps;
18028 
18029 	/*
18030 	 * It is OK to manipulate these fields outside the eager's squeue
18031 	 * because they will not start being used until tcp_accept_finish
18032 	 * has been called.
18033 	 */
18034 	ASSERT(lconnp->conn_upper_handle != NULL);
18035 	ASSERT(econnp->conn_upper_handle == NULL);
18036 	econnp->conn_upper_handle = sock_handle;
18037 	econnp->conn_upcalls = lconnp->conn_upcalls;
18038 	ASSERT(IPCL_IS_NONSTR(econnp));
18039 	/*
18040 	 * Create helper stream if it is a non-TPI TCP connection.
18041 	 */
18042 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
18043 		ip1dbg(("tcp_accept: create of IP helper stream"
18044 		    " failed\n"));
18045 		return (EPROTO);
18046 	}
18047 	eager->tcp_rq = econnp->conn_rq;
18048 	eager->tcp_wq = econnp->conn_wq;
18049 
18050 	ASSERT(eager->tcp_rq != NULL);
18051 
18052 	eager->tcp_sodirect = SOD_SOTOSODP(sock_handle);
18053 	return (tcp_accept_common(lconnp, econnp, cr));
18054 }
18055 
18056 
18057 /*
18058  * This is the STREAMS entry point for T_CONN_RES coming down on
18059  * Acceptor STREAM when  sockfs listener does accept processing.
18060  * Read the block comment on top of tcp_conn_request().
18061  */
18062 void
18063 tcp_tpi_accept(queue_t *q, mblk_t *mp)
18064 {
18065 	queue_t *rq = RD(q);
18066 	struct T_conn_res *conn_res;
18067 	tcp_t *eager;
18068 	tcp_t *listener;
18069 	struct T_ok_ack *ok;
18070 	t_scalar_t PRIM_type;
18071 	conn_t *econnp;
18072 	cred_t *cr;
18073 
18074 	ASSERT(DB_TYPE(mp) == M_PROTO);
18075 
18076 	/*
18077 	 * All Solaris components should pass a db_credp
18078 	 * for this TPI message, hence we ASSERT.
18079 	 * But in case there is some other M_PROTO that looks
18080 	 * like a TPI message sent by some other kernel
18081 	 * component, we check and return an error.
18082 	 */
18083 	cr = msg_getcred(mp, NULL);
18084 	ASSERT(cr != NULL);
18085 	if (cr == NULL) {
18086 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
18087 		if (mp != NULL)
18088 			putnext(rq, mp);
18089 		return;
18090 	}
18091 	conn_res = (struct T_conn_res *)mp->b_rptr;
18092 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18093 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18094 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18095 		if (mp != NULL)
18096 			putnext(rq, mp);
18097 		return;
18098 	}
18099 	switch (conn_res->PRIM_type) {
18100 	case O_T_CONN_RES:
18101 	case T_CONN_RES:
18102 		/*
18103 		 * We pass up an err ack if allocb fails. This will
18104 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18105 		 * tcp_eager_blowoff to be called. sockfs will then call
18106 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18107 		 * we need to do the allocb up here because we have to
18108 		 * make sure rq->q_qinfo->qi_qclose still points to the
18109 		 * correct function (tcpclose_accept) in case allocb
18110 		 * fails.
18111 		 */
18112 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18113 		    &eager, conn_res->OPT_length);
18114 		PRIM_type = conn_res->PRIM_type;
18115 		mp->b_datap->db_type = M_PCPROTO;
18116 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18117 		ok = (struct T_ok_ack *)mp->b_rptr;
18118 		ok->PRIM_type = T_OK_ACK;
18119 		ok->CORRECT_prim = PRIM_type;
18120 		econnp = eager->tcp_connp;
18121 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
18122 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
18123 		eager->tcp_rq = rq;
18124 		eager->tcp_wq = q;
18125 		rq->q_ptr = econnp;
18126 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
18127 		q->q_ptr = econnp;
18128 		q->q_qinfo = &tcp_winit;
18129 		listener = eager->tcp_listener;
18130 
18131 		/*
18132 		 * TCP is _D_SODIRECT and sockfs is directly above so
18133 		 * save shared sodirect_t pointer (if any).
18134 		 */
18135 		eager->tcp_sodirect = SOD_QTOSODP(eager->tcp_rq);
18136 		if (tcp_accept_common(listener->tcp_connp,
18137 		    econnp, cr) < 0) {
18138 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18139 			if (mp != NULL)
18140 				putnext(rq, mp);
18141 			return;
18142 		}
18143 
18144 		/*
18145 		 * Send the new local address also up to sockfs. There
18146 		 * should already be enough space in the mp that came
18147 		 * down from soaccept().
18148 		 */
18149 		if (eager->tcp_family == AF_INET) {
18150 			sin_t *sin;
18151 
18152 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18153 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18154 			sin = (sin_t *)mp->b_wptr;
18155 			mp->b_wptr += sizeof (sin_t);
18156 			sin->sin_family = AF_INET;
18157 			sin->sin_port = eager->tcp_lport;
18158 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18159 		} else {
18160 			sin6_t *sin6;
18161 
18162 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18163 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18164 			sin6 = (sin6_t *)mp->b_wptr;
18165 			mp->b_wptr += sizeof (sin6_t);
18166 			sin6->sin6_family = AF_INET6;
18167 			sin6->sin6_port = eager->tcp_lport;
18168 			if (eager->tcp_ipversion == IPV4_VERSION) {
18169 				sin6->sin6_flowinfo = 0;
18170 				IN6_IPADDR_TO_V4MAPPED(
18171 				    eager->tcp_ipha->ipha_src,
18172 				    &sin6->sin6_addr);
18173 			} else {
18174 				ASSERT(eager->tcp_ip6h != NULL);
18175 				sin6->sin6_flowinfo =
18176 				    eager->tcp_ip6h->ip6_vcf &
18177 				    ~IPV6_VERS_AND_FLOW_MASK;
18178 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18179 			}
18180 			sin6->sin6_scope_id = 0;
18181 			sin6->__sin6_src_id = 0;
18182 		}
18183 
18184 		putnext(rq, mp);
18185 		return;
18186 	default:
18187 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18188 		if (mp != NULL)
18189 			putnext(rq, mp);
18190 		return;
18191 	}
18192 }
18193 
18194 static int
18195 tcp_do_getsockname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18196 {
18197 	sin_t *sin = (sin_t *)sa;
18198 	sin6_t *sin6 = (sin6_t *)sa;
18199 
18200 	switch (tcp->tcp_family) {
18201 	case AF_INET:
18202 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18203 
18204 		if (*salenp < sizeof (sin_t))
18205 			return (EINVAL);
18206 
18207 		*sin = sin_null;
18208 		sin->sin_family = AF_INET;
18209 		if (tcp->tcp_state >= TCPS_BOUND) {
18210 			sin->sin_port = tcp->tcp_lport;
18211 			sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
18212 		}
18213 		*salenp = sizeof (sin_t);
18214 		break;
18215 
18216 	case AF_INET6:
18217 		if (*salenp < sizeof (sin6_t))
18218 			return (EINVAL);
18219 
18220 		*sin6 = sin6_null;
18221 		sin6->sin6_family = AF_INET6;
18222 		if (tcp->tcp_state >= TCPS_BOUND) {
18223 			sin6->sin6_port = tcp->tcp_lport;
18224 			if (tcp->tcp_ipversion == IPV4_VERSION) {
18225 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
18226 				    &sin6->sin6_addr);
18227 			} else {
18228 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
18229 			}
18230 		}
18231 		*salenp = sizeof (sin6_t);
18232 		break;
18233 	}
18234 
18235 	return (0);
18236 }
18237 
18238 static int
18239 tcp_do_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18240 {
18241 	sin_t *sin = (sin_t *)sa;
18242 	sin6_t *sin6 = (sin6_t *)sa;
18243 
18244 	if (tcp->tcp_state < TCPS_SYN_RCVD)
18245 		return (ENOTCONN);
18246 
18247 	switch (tcp->tcp_family) {
18248 	case AF_INET:
18249 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18250 
18251 		if (*salenp < sizeof (sin_t))
18252 			return (EINVAL);
18253 
18254 		*sin = sin_null;
18255 		sin->sin_family = AF_INET;
18256 		sin->sin_port = tcp->tcp_fport;
18257 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
18258 		    sin->sin_addr.s_addr);
18259 		*salenp = sizeof (sin_t);
18260 		break;
18261 
18262 	case AF_INET6:
18263 		if (*salenp < sizeof (sin6_t))
18264 			return (EINVAL);
18265 
18266 		*sin6 = sin6_null;
18267 		sin6->sin6_family = AF_INET6;
18268 		sin6->sin6_port = tcp->tcp_fport;
18269 		sin6->sin6_addr = tcp->tcp_remote_v6;
18270 		if (tcp->tcp_ipversion == IPV6_VERSION) {
18271 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
18272 			    ~IPV6_VERS_AND_FLOW_MASK;
18273 		}
18274 		*salenp = sizeof (sin6_t);
18275 		break;
18276 	}
18277 
18278 	return (0);
18279 }
18280 
18281 /*
18282  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
18283  */
18284 static void
18285 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
18286 {
18287 	void	*data;
18288 	mblk_t	*datamp = mp->b_cont;
18289 	tcp_t	*tcp = Q_TO_TCP(q);
18290 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
18291 
18292 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
18293 		cmdp->cb_error = EPROTO;
18294 		qreply(q, mp);
18295 		return;
18296 	}
18297 
18298 	data = datamp->b_rptr;
18299 
18300 	switch (cmdp->cb_cmd) {
18301 	case TI_GETPEERNAME:
18302 		cmdp->cb_error = tcp_do_getpeername(tcp, data, &cmdp->cb_len);
18303 		break;
18304 	case TI_GETMYNAME:
18305 		cmdp->cb_error = tcp_do_getsockname(tcp, data, &cmdp->cb_len);
18306 		break;
18307 	default:
18308 		cmdp->cb_error = EINVAL;
18309 		break;
18310 	}
18311 
18312 	qreply(q, mp);
18313 }
18314 
18315 void
18316 tcp_wput(queue_t *q, mblk_t *mp)
18317 {
18318 	conn_t	*connp = Q_TO_CONN(q);
18319 	tcp_t	*tcp;
18320 	void (*output_proc)();
18321 	t_scalar_t type;
18322 	uchar_t *rptr;
18323 	struct iocblk	*iocp;
18324 	size_t size;
18325 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18326 
18327 	ASSERT(connp->conn_ref >= 2);
18328 
18329 	switch (DB_TYPE(mp)) {
18330 	case M_DATA:
18331 		tcp = connp->conn_tcp;
18332 		ASSERT(tcp != NULL);
18333 
18334 		size = msgdsize(mp);
18335 
18336 		mutex_enter(&tcp->tcp_non_sq_lock);
18337 		tcp->tcp_squeue_bytes += size;
18338 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18339 			tcp_setqfull(tcp);
18340 		}
18341 		mutex_exit(&tcp->tcp_non_sq_lock);
18342 
18343 		CONN_INC_REF(connp);
18344 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18345 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18346 		return;
18347 
18348 	case M_CMD:
18349 		tcp_wput_cmdblk(q, mp);
18350 		return;
18351 
18352 	case M_PROTO:
18353 	case M_PCPROTO:
18354 		/*
18355 		 * if it is a snmp message, don't get behind the squeue
18356 		 */
18357 		tcp = connp->conn_tcp;
18358 		rptr = mp->b_rptr;
18359 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18360 			type = ((union T_primitives *)rptr)->type;
18361 		} else {
18362 			if (tcp->tcp_debug) {
18363 				(void) strlog(TCP_MOD_ID, 0, 1,
18364 				    SL_ERROR|SL_TRACE,
18365 				    "tcp_wput_proto, dropping one...");
18366 			}
18367 			freemsg(mp);
18368 			return;
18369 		}
18370 		if (type == T_SVR4_OPTMGMT_REQ) {
18371 			/*
18372 			 * All Solaris components should pass a db_credp
18373 			 * for this TPI message, hence we ASSERT.
18374 			 * But in case there is some other M_PROTO that looks
18375 			 * like a TPI message sent by some other kernel
18376 			 * component, we check and return an error.
18377 			 */
18378 			cred_t	*cr = msg_getcred(mp, NULL);
18379 
18380 			ASSERT(cr != NULL);
18381 			if (cr == NULL) {
18382 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
18383 				return;
18384 			}
18385 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18386 			    cr)) {
18387 				/*
18388 				 * This was a SNMP request
18389 				 */
18390 				return;
18391 			} else {
18392 				output_proc = tcp_wput_proto;
18393 			}
18394 		} else {
18395 			output_proc = tcp_wput_proto;
18396 		}
18397 		break;
18398 	case M_IOCTL:
18399 		/*
18400 		 * Most ioctls can be processed right away without going via
18401 		 * squeues - process them right here. Those that do require
18402 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18403 		 * are processed by tcp_wput_ioctl().
18404 		 */
18405 		iocp = (struct iocblk *)mp->b_rptr;
18406 		tcp = connp->conn_tcp;
18407 
18408 		switch (iocp->ioc_cmd) {
18409 		case TCP_IOC_ABORT_CONN:
18410 			tcp_ioctl_abort_conn(q, mp);
18411 			return;
18412 		case TI_GETPEERNAME:
18413 		case TI_GETMYNAME:
18414 			mi_copyin(q, mp, NULL,
18415 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18416 			return;
18417 		case ND_SET:
18418 			/* nd_getset does the necessary checks */
18419 		case ND_GET:
18420 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18421 				CALL_IP_WPUT(connp, q, mp);
18422 				return;
18423 			}
18424 			qreply(q, mp);
18425 			return;
18426 		case TCP_IOC_DEFAULT_Q:
18427 			/*
18428 			 * Wants to be the default wq. Check the credentials
18429 			 * first, the rest is executed via squeue.
18430 			 */
18431 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18432 				iocp->ioc_error = EPERM;
18433 				iocp->ioc_count = 0;
18434 				mp->b_datap->db_type = M_IOCACK;
18435 				qreply(q, mp);
18436 				return;
18437 			}
18438 			output_proc = tcp_wput_ioctl;
18439 			break;
18440 		default:
18441 			output_proc = tcp_wput_ioctl;
18442 			break;
18443 		}
18444 		break;
18445 	default:
18446 		output_proc = tcp_wput_nondata;
18447 		break;
18448 	}
18449 
18450 	CONN_INC_REF(connp);
18451 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18452 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18453 }
18454 
18455 /*
18456  * Initial STREAMS write side put() procedure for sockets. It tries to
18457  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18458  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18459  * are handled by tcp_wput() as usual.
18460  *
18461  * All further messages will also be handled by tcp_wput() because we cannot
18462  * be sure that the above short cut is safe later.
18463  */
18464 static void
18465 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18466 {
18467 	conn_t			*connp = Q_TO_CONN(wq);
18468 	tcp_t			*tcp = connp->conn_tcp;
18469 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18470 
18471 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18472 	wq->q_qinfo = &tcp_winit;
18473 
18474 	ASSERT(IPCL_IS_TCP(connp));
18475 	ASSERT(TCP_IS_SOCKET(tcp));
18476 
18477 	if (DB_TYPE(mp) == M_PCPROTO &&
18478 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18479 	    car->PRIM_type == T_CAPABILITY_REQ) {
18480 		tcp_capability_req(tcp, mp);
18481 		return;
18482 	}
18483 
18484 	tcp_wput(wq, mp);
18485 }
18486 
18487 /* ARGSUSED */
18488 static void
18489 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18490 {
18491 #ifdef DEBUG
18492 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18493 #endif
18494 	freemsg(mp);
18495 }
18496 
18497 static boolean_t
18498 tcp_zcopy_check(tcp_t *tcp)
18499 {
18500 	conn_t	*connp = tcp->tcp_connp;
18501 	ire_t	*ire;
18502 	boolean_t	zc_enabled = B_FALSE;
18503 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18504 
18505 	if (do_tcpzcopy == 2)
18506 		zc_enabled = B_TRUE;
18507 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18508 	    IPCL_IS_CONNECTED(connp) &&
18509 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18510 	    connp->conn_dontroute == 0 &&
18511 	    !connp->conn_nexthop_set &&
18512 	    connp->conn_outgoing_ill == NULL &&
18513 	    do_tcpzcopy == 1) {
18514 		/*
18515 		 * the checks above  closely resemble the fast path checks
18516 		 * in tcp_send_data().
18517 		 */
18518 		mutex_enter(&connp->conn_lock);
18519 		ire = connp->conn_ire_cache;
18520 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18521 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18522 			IRE_REFHOLD(ire);
18523 			if (ire->ire_stq != NULL) {
18524 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18525 
18526 				zc_enabled = ill && (ill->ill_capabilities &
18527 				    ILL_CAPAB_ZEROCOPY) &&
18528 				    (ill->ill_zerocopy_capab->
18529 				    ill_zerocopy_flags != 0);
18530 			}
18531 			IRE_REFRELE(ire);
18532 		}
18533 		mutex_exit(&connp->conn_lock);
18534 	}
18535 	tcp->tcp_snd_zcopy_on = zc_enabled;
18536 	if (!TCP_IS_DETACHED(tcp)) {
18537 		if (zc_enabled) {
18538 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18539 			    ZCVMSAFE);
18540 			TCP_STAT(tcps, tcp_zcopy_on);
18541 		} else {
18542 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18543 			    ZCVMUNSAFE);
18544 			TCP_STAT(tcps, tcp_zcopy_off);
18545 		}
18546 	}
18547 	return (zc_enabled);
18548 }
18549 
18550 static mblk_t *
18551 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18552 {
18553 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18554 
18555 	if (do_tcpzcopy == 2)
18556 		return (bp);
18557 	else if (tcp->tcp_snd_zcopy_on) {
18558 		tcp->tcp_snd_zcopy_on = B_FALSE;
18559 		if (!TCP_IS_DETACHED(tcp)) {
18560 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
18561 			    ZCVMUNSAFE);
18562 			TCP_STAT(tcps, tcp_zcopy_disable);
18563 		}
18564 	}
18565 	return (tcp_zcopy_backoff(tcp, bp, 0));
18566 }
18567 
18568 /*
18569  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18570  * the original desballoca'ed segmapped mblk.
18571  */
18572 static mblk_t *
18573 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18574 {
18575 	mblk_t *head, *tail, *nbp;
18576 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18577 
18578 	if (IS_VMLOANED_MBLK(bp)) {
18579 		TCP_STAT(tcps, tcp_zcopy_backoff);
18580 		if ((head = copyb(bp)) == NULL) {
18581 			/* fail to backoff; leave it for the next backoff */
18582 			tcp->tcp_xmit_zc_clean = B_FALSE;
18583 			return (bp);
18584 		}
18585 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18586 			if (fix_xmitlist)
18587 				tcp_zcopy_notify(tcp);
18588 			else
18589 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18590 		}
18591 		nbp = bp->b_cont;
18592 		if (fix_xmitlist) {
18593 			head->b_prev = bp->b_prev;
18594 			head->b_next = bp->b_next;
18595 			if (tcp->tcp_xmit_tail == bp)
18596 				tcp->tcp_xmit_tail = head;
18597 		}
18598 		bp->b_next = NULL;
18599 		bp->b_prev = NULL;
18600 		freeb(bp);
18601 	} else {
18602 		head = bp;
18603 		nbp = bp->b_cont;
18604 	}
18605 	tail = head;
18606 	while (nbp) {
18607 		if (IS_VMLOANED_MBLK(nbp)) {
18608 			TCP_STAT(tcps, tcp_zcopy_backoff);
18609 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18610 				tcp->tcp_xmit_zc_clean = B_FALSE;
18611 				tail->b_cont = nbp;
18612 				return (head);
18613 			}
18614 			tail = tail->b_cont;
18615 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18616 				if (fix_xmitlist)
18617 					tcp_zcopy_notify(tcp);
18618 				else
18619 					tail->b_datap->db_struioflag |=
18620 					    STRUIO_ZCNOTIFY;
18621 			}
18622 			bp = nbp;
18623 			nbp = nbp->b_cont;
18624 			if (fix_xmitlist) {
18625 				tail->b_prev = bp->b_prev;
18626 				tail->b_next = bp->b_next;
18627 				if (tcp->tcp_xmit_tail == bp)
18628 					tcp->tcp_xmit_tail = tail;
18629 			}
18630 			bp->b_next = NULL;
18631 			bp->b_prev = NULL;
18632 			freeb(bp);
18633 		} else {
18634 			tail->b_cont = nbp;
18635 			tail = nbp;
18636 			nbp = nbp->b_cont;
18637 		}
18638 	}
18639 	if (fix_xmitlist) {
18640 		tcp->tcp_xmit_last = tail;
18641 		tcp->tcp_xmit_zc_clean = B_TRUE;
18642 	}
18643 	return (head);
18644 }
18645 
18646 static void
18647 tcp_zcopy_notify(tcp_t *tcp)
18648 {
18649 	struct stdata	*stp;
18650 	conn_t *connp;
18651 
18652 	if (tcp->tcp_detached)
18653 		return;
18654 	connp = tcp->tcp_connp;
18655 	if (IPCL_IS_NONSTR(connp)) {
18656 		(*connp->conn_upcalls->su_zcopy_notify)
18657 		    (connp->conn_upper_handle);
18658 		return;
18659 	}
18660 	stp = STREAM(tcp->tcp_rq);
18661 	mutex_enter(&stp->sd_lock);
18662 	stp->sd_flag |= STZCNOTIFY;
18663 	cv_broadcast(&stp->sd_zcopy_wait);
18664 	mutex_exit(&stp->sd_lock);
18665 }
18666 
18667 static boolean_t
18668 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
18669 {
18670 	ire_t	*ire;
18671 	conn_t	*connp = tcp->tcp_connp;
18672 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18673 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18674 
18675 	mutex_enter(&connp->conn_lock);
18676 	ire = connp->conn_ire_cache;
18677 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18678 
18679 	if ((ire != NULL) &&
18680 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
18681 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
18682 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18683 		IRE_REFHOLD(ire);
18684 		mutex_exit(&connp->conn_lock);
18685 	} else {
18686 		boolean_t cached = B_FALSE;
18687 		ts_label_t *tsl;
18688 
18689 		/* force a recheck later on */
18690 		tcp->tcp_ire_ill_check_done = B_FALSE;
18691 
18692 		TCP_DBGSTAT(tcps, tcp_ire_null1);
18693 		connp->conn_ire_cache = NULL;
18694 		mutex_exit(&connp->conn_lock);
18695 
18696 		if (ire != NULL)
18697 			IRE_REFRELE_NOTR(ire);
18698 
18699 		tsl = crgetlabel(CONN_CRED(connp));
18700 		ire = (dst ?
18701 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
18702 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18703 		    connp->conn_zoneid, tsl, ipst));
18704 
18705 		if (ire == NULL) {
18706 			TCP_STAT(tcps, tcp_ire_null);
18707 			return (B_FALSE);
18708 		}
18709 
18710 		IRE_REFHOLD_NOTR(ire);
18711 
18712 		mutex_enter(&connp->conn_lock);
18713 		if (CONN_CACHE_IRE(connp)) {
18714 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18715 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18716 				TCP_CHECK_IREINFO(tcp, ire);
18717 				connp->conn_ire_cache = ire;
18718 				cached = B_TRUE;
18719 			}
18720 			rw_exit(&ire->ire_bucket->irb_lock);
18721 		}
18722 		mutex_exit(&connp->conn_lock);
18723 
18724 		/*
18725 		 * We can continue to use the ire but since it was
18726 		 * not cached, we should drop the extra reference.
18727 		 */
18728 		if (!cached)
18729 			IRE_REFRELE_NOTR(ire);
18730 
18731 		/*
18732 		 * Rampart note: no need to select a new label here, since
18733 		 * labels are not allowed to change during the life of a TCP
18734 		 * connection.
18735 		 */
18736 	}
18737 
18738 	*irep = ire;
18739 
18740 	return (B_TRUE);
18741 }
18742 
18743 /*
18744  * Called from tcp_send() or tcp_send_data() to find workable IRE.
18745  *
18746  * 0 = success;
18747  * 1 = failed to find ire and ill.
18748  */
18749 static boolean_t
18750 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
18751 {
18752 	ipha_t		*ipha;
18753 	ipaddr_t	dst;
18754 	ire_t		*ire;
18755 	ill_t		*ill;
18756 	mblk_t		*ire_fp_mp;
18757 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18758 
18759 	if (mp != NULL)
18760 		ipha = (ipha_t *)mp->b_rptr;
18761 	else
18762 		ipha = tcp->tcp_ipha;
18763 	dst = ipha->ipha_dst;
18764 
18765 	if (!tcp_send_find_ire(tcp, &dst, &ire))
18766 		return (B_FALSE);
18767 
18768 	if ((ire->ire_flags & RTF_MULTIRT) ||
18769 	    (ire->ire_stq == NULL) ||
18770 	    (ire->ire_nce == NULL) ||
18771 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18772 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18773 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
18774 		TCP_STAT(tcps, tcp_ip_ire_send);
18775 		IRE_REFRELE(ire);
18776 		return (B_FALSE);
18777 	}
18778 
18779 	ill = ire_to_ill(ire);
18780 	ASSERT(ill != NULL);
18781 
18782 	if (!tcp->tcp_ire_ill_check_done) {
18783 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18784 		tcp->tcp_ire_ill_check_done = B_TRUE;
18785 	}
18786 
18787 	*irep = ire;
18788 	*illp = ill;
18789 
18790 	return (B_TRUE);
18791 }
18792 
18793 static void
18794 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18795 {
18796 	ipha_t		*ipha;
18797 	ipaddr_t	src;
18798 	ipaddr_t	dst;
18799 	uint32_t	cksum;
18800 	ire_t		*ire;
18801 	uint16_t	*up;
18802 	ill_t		*ill;
18803 	conn_t		*connp = tcp->tcp_connp;
18804 	uint32_t	hcksum_txflags = 0;
18805 	mblk_t		*ire_fp_mp;
18806 	uint_t		ire_fp_mp_len;
18807 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18808 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18809 	cred_t		*cr;
18810 	pid_t		cpid;
18811 
18812 	ASSERT(DB_TYPE(mp) == M_DATA);
18813 
18814 	/*
18815 	 * Here we need to handle the overloading of the cred_t for
18816 	 * both getpeerucred and TX.
18817 	 * If this is a SYN then the caller already set db_credp so
18818 	 * that getpeerucred will work. But if TX is in use we might have
18819 	 * a conn_peercred which is different, and we need to use that cred
18820 	 * to make TX use the correct label and label dependent route.
18821 	 */
18822 	if (is_system_labeled()) {
18823 		cr = msg_getcred(mp, &cpid);
18824 		if (cr == NULL || connp->conn_peercred != NULL)
18825 			mblk_setcred(mp, CONN_CRED(connp), cpid);
18826 	}
18827 
18828 	ipha = (ipha_t *)mp->b_rptr;
18829 	src = ipha->ipha_src;
18830 	dst = ipha->ipha_dst;
18831 
18832 	ASSERT(q != NULL);
18833 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
18834 
18835 	/*
18836 	 * Drop off fast path for IPv6 and also if options are present or
18837 	 * we need to resolve a TS label.
18838 	 */
18839 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18840 	    !IPCL_IS_CONNECTED(connp) ||
18841 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
18842 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18843 	    !connp->conn_ulp_labeled ||
18844 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18845 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18846 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
18847 		if (tcp->tcp_snd_zcopy_aware)
18848 			mp = tcp_zcopy_disable(tcp, mp);
18849 		TCP_STAT(tcps, tcp_ip_send);
18850 		CALL_IP_WPUT(connp, q, mp);
18851 		return;
18852 	}
18853 
18854 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
18855 		if (tcp->tcp_snd_zcopy_aware)
18856 			mp = tcp_zcopy_backoff(tcp, mp, 0);
18857 		CALL_IP_WPUT(connp, q, mp);
18858 		return;
18859 	}
18860 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
18861 	ire_fp_mp_len = MBLKL(ire_fp_mp);
18862 
18863 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18864 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18865 #ifndef _BIG_ENDIAN
18866 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18867 #endif
18868 
18869 	/*
18870 	 * Check to see if we need to re-enable LSO/MDT for this connection
18871 	 * because it was previously disabled due to changes in the ill;
18872 	 * note that by doing it here, this re-enabling only applies when
18873 	 * the packet is not dispatched through CALL_IP_WPUT().
18874 	 *
18875 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
18876 	 * case, since that's how we ended up here.  For IPv6, we do the
18877 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18878 	 */
18879 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
18880 		/*
18881 		 * Restore LSO for this connection, so that next time around
18882 		 * it is eligible to go through tcp_lsosend() path again.
18883 		 */
18884 		TCP_STAT(tcps, tcp_lso_enabled);
18885 		tcp->tcp_lso = B_TRUE;
18886 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
18887 		    "interface %s\n", (void *)connp, ill->ill_name));
18888 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18889 		/*
18890 		 * Restore MDT for this connection, so that next time around
18891 		 * it is eligible to go through tcp_multisend() path again.
18892 		 */
18893 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
18894 		tcp->tcp_mdt = B_TRUE;
18895 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18896 		    "interface %s\n", (void *)connp, ill->ill_name));
18897 	}
18898 
18899 	if (tcp->tcp_snd_zcopy_aware) {
18900 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18901 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18902 			mp = tcp_zcopy_disable(tcp, mp);
18903 		/*
18904 		 * we shouldn't need to reset ipha as the mp containing
18905 		 * ipha should never be a zero-copy mp.
18906 		 */
18907 	}
18908 
18909 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18910 		ASSERT(ill->ill_hcksum_capab != NULL);
18911 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18912 	}
18913 
18914 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18915 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18916 
18917 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18918 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18919 
18920 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18921 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18922 
18923 	/* Software checksum? */
18924 	if (DB_CKSUMFLAGS(mp) == 0) {
18925 		TCP_STAT(tcps, tcp_out_sw_cksum);
18926 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
18927 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18928 	}
18929 
18930 	/* Calculate IP header checksum if hardware isn't capable */
18931 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18932 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18933 		    ((uint16_t *)ipha)[4]);
18934 	}
18935 
18936 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18937 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18938 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18939 
18940 	UPDATE_OB_PKT_COUNT(ire);
18941 	ire->ire_last_used_time = lbolt;
18942 
18943 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
18944 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
18945 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
18946 	    ntohs(ipha->ipha_length));
18947 
18948 	DTRACE_PROBE4(ip4__physical__out__start,
18949 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
18950 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
18951 	    ipst->ips_ipv4firewall_physical_out,
18952 	    NULL, ill, ipha, mp, mp, 0, ipst);
18953 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
18954 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
18955 
18956 	if (mp != NULL) {
18957 		if (ipst->ips_ipobs_enabled) {
18958 			zoneid_t szone;
18959 
18960 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
18961 			    ipst, ALL_ZONES);
18962 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
18963 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
18964 		}
18965 
18966 		ILL_SEND_TX(ill, ire, connp, mp, 0, NULL);
18967 	}
18968 
18969 	IRE_REFRELE(ire);
18970 }
18971 
18972 /*
18973  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18974  * if the receiver shrinks the window, i.e. moves the right window to the
18975  * left, the we should not send new data, but should retransmit normally the
18976  * old unacked data between suna and suna + swnd. We might has sent data
18977  * that is now outside the new window, pretend that we didn't send  it.
18978  */
18979 static void
18980 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18981 {
18982 	uint32_t	snxt = tcp->tcp_snxt;
18983 	mblk_t		*xmit_tail;
18984 	int32_t		offset;
18985 
18986 	ASSERT(shrunk_count > 0);
18987 
18988 	/* Pretend we didn't send the data outside the window */
18989 	snxt -= shrunk_count;
18990 
18991 	/* Get the mblk and the offset in it per the shrunk window */
18992 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
18993 
18994 	ASSERT(xmit_tail != NULL);
18995 
18996 	/* Reset all the values per the now shrunk window */
18997 	tcp->tcp_snxt = snxt;
18998 	tcp->tcp_xmit_tail = xmit_tail;
18999 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19000 	    offset;
19001 	tcp->tcp_unsent += shrunk_count;
19002 
19003 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19004 		/*
19005 		 * Make sure the timer is running so that we will probe a zero
19006 		 * window.
19007 		 */
19008 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19009 }
19010 
19011 
19012 /*
19013  * The TCP normal data output path.
19014  * NOTE: the logic of the fast path is duplicated from this function.
19015  */
19016 static void
19017 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19018 {
19019 	int		len;
19020 	mblk_t		*local_time;
19021 	mblk_t		*mp1;
19022 	uint32_t	snxt;
19023 	int		tail_unsent;
19024 	int		tcpstate;
19025 	int		usable = 0;
19026 	mblk_t		*xmit_tail;
19027 	queue_t		*q = tcp->tcp_wq;
19028 	int32_t		mss;
19029 	int32_t		num_sack_blk = 0;
19030 	int32_t		tcp_hdr_len;
19031 	int32_t		tcp_tcp_hdr_len;
19032 	int		mdt_thres;
19033 	int		rc;
19034 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19035 	ip_stack_t	*ipst;
19036 
19037 	tcpstate = tcp->tcp_state;
19038 	if (mp == NULL) {
19039 		/*
19040 		 * tcp_wput_data() with NULL mp should only be called when
19041 		 * there is unsent data.
19042 		 */
19043 		ASSERT(tcp->tcp_unsent > 0);
19044 		/* Really tacky... but we need this for detached closes. */
19045 		len = tcp->tcp_unsent;
19046 		goto data_null;
19047 	}
19048 
19049 #if CCS_STATS
19050 	wrw_stats.tot.count++;
19051 	wrw_stats.tot.bytes += msgdsize(mp);
19052 #endif
19053 	ASSERT(mp->b_datap->db_type == M_DATA);
19054 	/*
19055 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19056 	 * or before a connection attempt has begun.
19057 	 */
19058 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19059 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19060 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19061 #ifdef DEBUG
19062 			cmn_err(CE_WARN,
19063 			    "tcp_wput_data: data after ordrel, %s",
19064 			    tcp_display(tcp, NULL,
19065 			    DISP_ADDR_AND_PORT));
19066 #else
19067 			if (tcp->tcp_debug) {
19068 				(void) strlog(TCP_MOD_ID, 0, 1,
19069 				    SL_TRACE|SL_ERROR,
19070 				    "tcp_wput_data: data after ordrel, %s\n",
19071 				    tcp_display(tcp, NULL,
19072 				    DISP_ADDR_AND_PORT));
19073 			}
19074 #endif /* DEBUG */
19075 		}
19076 		if (tcp->tcp_snd_zcopy_aware &&
19077 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19078 			tcp_zcopy_notify(tcp);
19079 		freemsg(mp);
19080 		mutex_enter(&tcp->tcp_non_sq_lock);
19081 		if (tcp->tcp_flow_stopped &&
19082 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19083 			tcp_clrqfull(tcp);
19084 		}
19085 		mutex_exit(&tcp->tcp_non_sq_lock);
19086 		return;
19087 	}
19088 
19089 	/* Strip empties */
19090 	for (;;) {
19091 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19092 		    (uintptr_t)INT_MAX);
19093 		len = (int)(mp->b_wptr - mp->b_rptr);
19094 		if (len > 0)
19095 			break;
19096 		mp1 = mp;
19097 		mp = mp->b_cont;
19098 		freeb(mp1);
19099 		if (!mp) {
19100 			return;
19101 		}
19102 	}
19103 
19104 	/* If we are the first on the list ... */
19105 	if (tcp->tcp_xmit_head == NULL) {
19106 		tcp->tcp_xmit_head = mp;
19107 		tcp->tcp_xmit_tail = mp;
19108 		tcp->tcp_xmit_tail_unsent = len;
19109 	} else {
19110 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19111 		struct datab *dp;
19112 
19113 		mp1 = tcp->tcp_xmit_last;
19114 		if (len < tcp_tx_pull_len &&
19115 		    (dp = mp1->b_datap)->db_ref == 1 &&
19116 		    dp->db_lim - mp1->b_wptr >= len) {
19117 			ASSERT(len > 0);
19118 			ASSERT(!mp1->b_cont);
19119 			if (len == 1) {
19120 				*mp1->b_wptr++ = *mp->b_rptr;
19121 			} else {
19122 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19123 				mp1->b_wptr += len;
19124 			}
19125 			if (mp1 == tcp->tcp_xmit_tail)
19126 				tcp->tcp_xmit_tail_unsent += len;
19127 			mp1->b_cont = mp->b_cont;
19128 			if (tcp->tcp_snd_zcopy_aware &&
19129 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19130 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19131 			freeb(mp);
19132 			mp = mp1;
19133 		} else {
19134 			tcp->tcp_xmit_last->b_cont = mp;
19135 		}
19136 		len += tcp->tcp_unsent;
19137 	}
19138 
19139 	/* Tack on however many more positive length mblks we have */
19140 	if ((mp1 = mp->b_cont) != NULL) {
19141 		do {
19142 			int tlen;
19143 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19144 			    (uintptr_t)INT_MAX);
19145 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19146 			if (tlen <= 0) {
19147 				mp->b_cont = mp1->b_cont;
19148 				freeb(mp1);
19149 			} else {
19150 				len += tlen;
19151 				mp = mp1;
19152 			}
19153 		} while ((mp1 = mp->b_cont) != NULL);
19154 	}
19155 	tcp->tcp_xmit_last = mp;
19156 	tcp->tcp_unsent = len;
19157 
19158 	if (urgent)
19159 		usable = 1;
19160 
19161 data_null:
19162 	snxt = tcp->tcp_snxt;
19163 	xmit_tail = tcp->tcp_xmit_tail;
19164 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19165 
19166 	/*
19167 	 * Note that tcp_mss has been adjusted to take into account the
19168 	 * timestamp option if applicable.  Because SACK options do not
19169 	 * appear in every TCP segments and they are of variable lengths,
19170 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19171 	 * the actual segment length when we need to send a segment which
19172 	 * includes SACK options.
19173 	 */
19174 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19175 		int32_t	opt_len;
19176 
19177 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19178 		    tcp->tcp_num_sack_blk);
19179 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19180 		    2 + TCPOPT_HEADER_LEN;
19181 		mss = tcp->tcp_mss - opt_len;
19182 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19183 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19184 	} else {
19185 		mss = tcp->tcp_mss;
19186 		tcp_hdr_len = tcp->tcp_hdr_len;
19187 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19188 	}
19189 
19190 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19191 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19192 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19193 	}
19194 	if (tcpstate == TCPS_SYN_RCVD) {
19195 		/*
19196 		 * The three-way connection establishment handshake is not
19197 		 * complete yet. We want to queue the data for transmission
19198 		 * after entering ESTABLISHED state (RFC793). A jump to
19199 		 * "done" label effectively leaves data on the queue.
19200 		 */
19201 		goto done;
19202 	} else {
19203 		int usable_r;
19204 
19205 		/*
19206 		 * In the special case when cwnd is zero, which can only
19207 		 * happen if the connection is ECN capable, return now.
19208 		 * New segments is sent using tcp_timer().  The timer
19209 		 * is set in tcp_rput_data().
19210 		 */
19211 		if (tcp->tcp_cwnd == 0) {
19212 			/*
19213 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19214 			 * finished.
19215 			 */
19216 			ASSERT(tcp->tcp_ecn_ok ||
19217 			    tcp->tcp_state < TCPS_ESTABLISHED);
19218 			return;
19219 		}
19220 
19221 		/* NOTE: trouble if xmitting while SYN not acked? */
19222 		usable_r = snxt - tcp->tcp_suna;
19223 		usable_r = tcp->tcp_swnd - usable_r;
19224 
19225 		/*
19226 		 * Check if the receiver has shrunk the window.  If
19227 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19228 		 * cannot be set as there is unsent data, so FIN cannot
19229 		 * be sent out.  Otherwise, we need to take into account
19230 		 * of FIN as it consumes an "invisible" sequence number.
19231 		 */
19232 		ASSERT(tcp->tcp_fin_sent == 0);
19233 		if (usable_r < 0) {
19234 			/*
19235 			 * The receiver has shrunk the window and we have sent
19236 			 * -usable_r date beyond the window, re-adjust.
19237 			 *
19238 			 * If TCP window scaling is enabled, there can be
19239 			 * round down error as the advertised receive window
19240 			 * is actually right shifted n bits.  This means that
19241 			 * the lower n bits info is wiped out.  It will look
19242 			 * like the window is shrunk.  Do a check here to
19243 			 * see if the shrunk amount is actually within the
19244 			 * error in window calculation.  If it is, just
19245 			 * return.  Note that this check is inside the
19246 			 * shrunk window check.  This makes sure that even
19247 			 * though tcp_process_shrunk_swnd() is not called,
19248 			 * we will stop further processing.
19249 			 */
19250 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19251 				tcp_process_shrunk_swnd(tcp, -usable_r);
19252 			}
19253 			return;
19254 		}
19255 
19256 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19257 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19258 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19259 
19260 		/* usable = MIN(usable, unsent) */
19261 		if (usable_r > len)
19262 			usable_r = len;
19263 
19264 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19265 		if (usable_r > 0) {
19266 			usable = usable_r;
19267 		} else {
19268 			/* Bypass all other unnecessary processing. */
19269 			goto done;
19270 		}
19271 	}
19272 
19273 	local_time = (mblk_t *)lbolt;
19274 
19275 	/*
19276 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19277 	 * BSD.  This is more in line with the true intent of Nagle.
19278 	 *
19279 	 * The conditions are:
19280 	 * 1. The amount of unsent data (or amount of data which can be
19281 	 *    sent, whichever is smaller) is less than Nagle limit.
19282 	 * 2. The last sent size is also less than Nagle limit.
19283 	 * 3. There is unack'ed data.
19284 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19285 	 *    Nagle algorithm.  This reduces the probability that urgent
19286 	 *    bytes get "merged" together.
19287 	 * 5. The app has not closed the connection.  This eliminates the
19288 	 *    wait time of the receiving side waiting for the last piece of
19289 	 *    (small) data.
19290 	 *
19291 	 * If all are satisified, exit without sending anything.  Note
19292 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19293 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19294 	 * 4095).
19295 	 */
19296 	if (usable < (int)tcp->tcp_naglim &&
19297 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19298 	    snxt != tcp->tcp_suna &&
19299 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19300 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19301 		goto done;
19302 	}
19303 
19304 	if (tcp->tcp_cork) {
19305 		/*
19306 		 * if the tcp->tcp_cork option is set, then we have to force
19307 		 * TCP not to send partial segment (smaller than MSS bytes).
19308 		 * We are calculating the usable now based on full mss and
19309 		 * will save the rest of remaining data for later.
19310 		 */
19311 		if (usable < mss)
19312 			goto done;
19313 		usable = (usable / mss) * mss;
19314 	}
19315 
19316 	/* Update the latest receive window size in TCP header. */
19317 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19318 	    tcp->tcp_tcph->th_win);
19319 
19320 	/*
19321 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19322 	 *
19323 	 * 1. Simple TCP/IP{v4,v6} (no options).
19324 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19325 	 * 3. If the TCP connection is in ESTABLISHED state.
19326 	 * 4. The TCP is not detached.
19327 	 *
19328 	 * If any of the above conditions have changed during the
19329 	 * connection, stop using LSO/MDT and restore the stream head
19330 	 * parameters accordingly.
19331 	 */
19332 	ipst = tcps->tcps_netstack->netstack_ip;
19333 
19334 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19335 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19336 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19337 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19338 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19339 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19340 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19341 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19342 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19343 		if (tcp->tcp_lso) {
19344 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19345 			tcp->tcp_lso = B_FALSE;
19346 		} else {
19347 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19348 			tcp->tcp_mdt = B_FALSE;
19349 		}
19350 
19351 		/* Anything other than detached is considered pathological */
19352 		if (!TCP_IS_DETACHED(tcp)) {
19353 			if (tcp->tcp_lso)
19354 				TCP_STAT(tcps, tcp_lso_disabled);
19355 			else
19356 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19357 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19358 		}
19359 	}
19360 
19361 	/* Use MDT if sendable amount is greater than the threshold */
19362 	if (tcp->tcp_mdt &&
19363 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19364 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19365 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19366 	    (tcp->tcp_valid_bits == 0 ||
19367 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19368 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19369 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19370 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19371 		    local_time, mdt_thres);
19372 	} else {
19373 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19374 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19375 		    local_time, INT_MAX);
19376 	}
19377 
19378 	/* Pretend that all we were trying to send really got sent */
19379 	if (rc < 0 && tail_unsent < 0) {
19380 		do {
19381 			xmit_tail = xmit_tail->b_cont;
19382 			xmit_tail->b_prev = local_time;
19383 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19384 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19385 			tail_unsent += (int)(xmit_tail->b_wptr -
19386 			    xmit_tail->b_rptr);
19387 		} while (tail_unsent < 0);
19388 	}
19389 done:;
19390 	tcp->tcp_xmit_tail = xmit_tail;
19391 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19392 	len = tcp->tcp_snxt - snxt;
19393 	if (len) {
19394 		/*
19395 		 * If new data was sent, need to update the notsack
19396 		 * list, which is, afterall, data blocks that have
19397 		 * not been sack'ed by the receiver.  New data is
19398 		 * not sack'ed.
19399 		 */
19400 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19401 			/* len is a negative value. */
19402 			tcp->tcp_pipe -= len;
19403 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19404 			    tcp->tcp_snxt, snxt,
19405 			    &(tcp->tcp_num_notsack_blk),
19406 			    &(tcp->tcp_cnt_notsack_list));
19407 		}
19408 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19409 		tcp->tcp_rack = tcp->tcp_rnxt;
19410 		tcp->tcp_rack_cnt = 0;
19411 		if ((snxt + len) == tcp->tcp_suna) {
19412 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19413 		}
19414 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19415 		/*
19416 		 * Didn't send anything. Make sure the timer is running
19417 		 * so that we will probe a zero window.
19418 		 */
19419 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19420 	}
19421 	/* Note that len is the amount we just sent but with a negative sign */
19422 	tcp->tcp_unsent += len;
19423 	mutex_enter(&tcp->tcp_non_sq_lock);
19424 	if (tcp->tcp_flow_stopped) {
19425 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19426 			tcp_clrqfull(tcp);
19427 		}
19428 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19429 		tcp_setqfull(tcp);
19430 	}
19431 	mutex_exit(&tcp->tcp_non_sq_lock);
19432 }
19433 
19434 /*
19435  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19436  * outgoing TCP header with the template header, as well as other
19437  * options such as time-stamp, ECN and/or SACK.
19438  */
19439 static void
19440 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19441 {
19442 	tcph_t *tcp_tmpl, *tcp_h;
19443 	uint32_t *dst, *src;
19444 	int hdrlen;
19445 
19446 	ASSERT(OK_32PTR(rptr));
19447 
19448 	/* Template header */
19449 	tcp_tmpl = tcp->tcp_tcph;
19450 
19451 	/* Header of outgoing packet */
19452 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19453 
19454 	/* dst and src are opaque 32-bit fields, used for copying */
19455 	dst = (uint32_t *)rptr;
19456 	src = (uint32_t *)tcp->tcp_iphc;
19457 	hdrlen = tcp->tcp_hdr_len;
19458 
19459 	/* Fill time-stamp option if needed */
19460 	if (tcp->tcp_snd_ts_ok) {
19461 		U32_TO_BE32((uint32_t)now,
19462 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19463 		U32_TO_BE32(tcp->tcp_ts_recent,
19464 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19465 	} else {
19466 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19467 	}
19468 
19469 	/*
19470 	 * Copy the template header; is this really more efficient than
19471 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19472 	 * but perhaps not for other scenarios.
19473 	 */
19474 	dst[0] = src[0];
19475 	dst[1] = src[1];
19476 	dst[2] = src[2];
19477 	dst[3] = src[3];
19478 	dst[4] = src[4];
19479 	dst[5] = src[5];
19480 	dst[6] = src[6];
19481 	dst[7] = src[7];
19482 	dst[8] = src[8];
19483 	dst[9] = src[9];
19484 	if (hdrlen -= 40) {
19485 		hdrlen >>= 2;
19486 		dst += 10;
19487 		src += 10;
19488 		do {
19489 			*dst++ = *src++;
19490 		} while (--hdrlen);
19491 	}
19492 
19493 	/*
19494 	 * Set the ECN info in the TCP header if it is not a zero
19495 	 * window probe.  Zero window probe is only sent in
19496 	 * tcp_wput_data() and tcp_timer().
19497 	 */
19498 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19499 		SET_ECT(tcp, rptr);
19500 
19501 		if (tcp->tcp_ecn_echo_on)
19502 			tcp_h->th_flags[0] |= TH_ECE;
19503 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19504 			tcp_h->th_flags[0] |= TH_CWR;
19505 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19506 		}
19507 	}
19508 
19509 	/* Fill in SACK options */
19510 	if (num_sack_blk > 0) {
19511 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19512 		sack_blk_t *tmp;
19513 		int32_t	i;
19514 
19515 		wptr[0] = TCPOPT_NOP;
19516 		wptr[1] = TCPOPT_NOP;
19517 		wptr[2] = TCPOPT_SACK;
19518 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19519 		    sizeof (sack_blk_t);
19520 		wptr += TCPOPT_REAL_SACK_LEN;
19521 
19522 		tmp = tcp->tcp_sack_list;
19523 		for (i = 0; i < num_sack_blk; i++) {
19524 			U32_TO_BE32(tmp[i].begin, wptr);
19525 			wptr += sizeof (tcp_seq);
19526 			U32_TO_BE32(tmp[i].end, wptr);
19527 			wptr += sizeof (tcp_seq);
19528 		}
19529 		tcp_h->th_offset_and_rsrvd[0] +=
19530 		    ((num_sack_blk * 2 + 1) << 4);
19531 	}
19532 }
19533 
19534 /*
19535  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19536  * the destination address and SAP attribute, and if necessary, the
19537  * hardware checksum offload attribute to a Multidata message.
19538  */
19539 static int
19540 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19541     const uint32_t start, const uint32_t stuff, const uint32_t end,
19542     const uint32_t flags, tcp_stack_t *tcps)
19543 {
19544 	/* Add global destination address & SAP attribute */
19545 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19546 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19547 		    "destination address+SAP\n"));
19548 
19549 		if (dlmp != NULL)
19550 			TCP_STAT(tcps, tcp_mdt_allocfail);
19551 		return (-1);
19552 	}
19553 
19554 	/* Add global hwcksum attribute */
19555 	if (hwcksum &&
19556 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19557 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19558 		    "checksum attribute\n"));
19559 
19560 		TCP_STAT(tcps, tcp_mdt_allocfail);
19561 		return (-1);
19562 	}
19563 
19564 	return (0);
19565 }
19566 
19567 /*
19568  * Smaller and private version of pdescinfo_t used specifically for TCP,
19569  * which allows for only two payload spans per packet.
19570  */
19571 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19572 
19573 /*
19574  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19575  * scheme, and returns one the following:
19576  *
19577  * -1 = failed allocation.
19578  *  0 = success; burst count reached, or usable send window is too small,
19579  *      and that we'd rather wait until later before sending again.
19580  */
19581 static int
19582 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19583     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19584     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19585     const int mdt_thres)
19586 {
19587 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19588 	multidata_t	*mmd;
19589 	uint_t		obsegs, obbytes, hdr_frag_sz;
19590 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19591 	int		num_burst_seg, max_pld;
19592 	pdesc_t		*pkt;
19593 	tcp_pdescinfo_t	tcp_pkt_info;
19594 	pdescinfo_t	*pkt_info;
19595 	int		pbuf_idx, pbuf_idx_nxt;
19596 	int		seg_len, len, spill, af;
19597 	boolean_t	add_buffer, zcopy, clusterwide;
19598 	boolean_t	rconfirm = B_FALSE;
19599 	boolean_t	done = B_FALSE;
19600 	uint32_t	cksum;
19601 	uint32_t	hwcksum_flags;
19602 	ire_t		*ire = NULL;
19603 	ill_t		*ill;
19604 	ipha_t		*ipha;
19605 	ip6_t		*ip6h;
19606 	ipaddr_t	src, dst;
19607 	ill_zerocopy_capab_t *zc_cap = NULL;
19608 	uint16_t	*up;
19609 	int		err;
19610 	conn_t		*connp;
19611 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19612 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19613 	int		usable_mmd, tail_unsent_mmd;
19614 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
19615 	mblk_t		*xmit_tail_mmd;
19616 	netstackid_t	stack_id;
19617 
19618 #ifdef	_BIG_ENDIAN
19619 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19620 #else
19621 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19622 #endif
19623 
19624 #define	PREP_NEW_MULTIDATA() {			\
19625 	mmd = NULL;				\
19626 	md_mp = md_hbuf = NULL;			\
19627 	cur_hdr_off = 0;			\
19628 	max_pld = tcp->tcp_mdt_max_pld;		\
19629 	pbuf_idx = pbuf_idx_nxt = -1;		\
19630 	add_buffer = B_TRUE;			\
19631 	zcopy = B_FALSE;			\
19632 }
19633 
19634 #define	PREP_NEW_PBUF() {			\
19635 	md_pbuf = md_pbuf_nxt = NULL;		\
19636 	pbuf_idx = pbuf_idx_nxt = -1;		\
19637 	cur_pld_off = 0;			\
19638 	first_snxt = *snxt;			\
19639 	ASSERT(*tail_unsent > 0);		\
19640 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19641 }
19642 
19643 	ASSERT(mdt_thres >= mss);
19644 	ASSERT(*usable > 0 && *usable > mdt_thres);
19645 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19646 	ASSERT(!TCP_IS_DETACHED(tcp));
19647 	ASSERT(tcp->tcp_valid_bits == 0 ||
19648 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19649 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19650 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19651 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19652 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19653 
19654 	connp = tcp->tcp_connp;
19655 	ASSERT(connp != NULL);
19656 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
19657 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19658 
19659 	stack_id = connp->conn_netstack->netstack_stackid;
19660 
19661 	usable_mmd = tail_unsent_mmd = 0;
19662 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
19663 	xmit_tail_mmd = NULL;
19664 	/*
19665 	 * Note that tcp will only declare at most 2 payload spans per
19666 	 * packet, which is much lower than the maximum allowable number
19667 	 * of packet spans per Multidata.  For this reason, we use the
19668 	 * privately declared and smaller descriptor info structure, in
19669 	 * order to save some stack space.
19670 	 */
19671 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19672 
19673 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19674 	if (af == AF_INET) {
19675 		dst = tcp->tcp_ipha->ipha_dst;
19676 		src = tcp->tcp_ipha->ipha_src;
19677 		ASSERT(!CLASSD(dst));
19678 	}
19679 	ASSERT(af == AF_INET ||
19680 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19681 
19682 	obsegs = obbytes = 0;
19683 	num_burst_seg = tcp->tcp_snd_burst;
19684 	md_mp_head = NULL;
19685 	PREP_NEW_MULTIDATA();
19686 
19687 	/*
19688 	 * Before we go on further, make sure there is an IRE that we can
19689 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19690 	 * in proceeding any further, and we should just hand everything
19691 	 * off to the legacy path.
19692 	 */
19693 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
19694 		goto legacy_send_no_md;
19695 
19696 	ASSERT(ire != NULL);
19697 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19698 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19699 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19700 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19701 	/*
19702 	 * If we do support loopback for MDT (which requires modifications
19703 	 * to the receiving paths), the following assertions should go away,
19704 	 * and we would be sending the Multidata to loopback conn later on.
19705 	 */
19706 	ASSERT(!IRE_IS_LOCAL(ire));
19707 	ASSERT(ire->ire_stq != NULL);
19708 
19709 	ill = ire_to_ill(ire);
19710 	ASSERT(ill != NULL);
19711 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19712 
19713 	if (!tcp->tcp_ire_ill_check_done) {
19714 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19715 		tcp->tcp_ire_ill_check_done = B_TRUE;
19716 	}
19717 
19718 	/*
19719 	 * If the underlying interface conditions have changed, or if the
19720 	 * new interface does not support MDT, go back to legacy path.
19721 	 */
19722 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19723 		/* don't go through this path anymore for this connection */
19724 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
19725 		tcp->tcp_mdt = B_FALSE;
19726 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19727 		    "interface %s\n", (void *)connp, ill->ill_name));
19728 		/* IRE will be released prior to returning */
19729 		goto legacy_send_no_md;
19730 	}
19731 
19732 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19733 		zc_cap = ill->ill_zerocopy_capab;
19734 
19735 	/*
19736 	 * Check if we can take tcp fast-path. Note that "incomplete"
19737 	 * ire's (where the link-layer for next hop is not resolved
19738 	 * or where the fast-path header in nce_fp_mp is not available
19739 	 * yet) are sent down the legacy (slow) path.
19740 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19741 	 */
19742 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19743 		/* IRE will be released prior to returning */
19744 		goto legacy_send_no_md;
19745 	}
19746 
19747 	/* go to legacy path if interface doesn't support zerocopy */
19748 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19749 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19750 		/* IRE will be released prior to returning */
19751 		goto legacy_send_no_md;
19752 	}
19753 
19754 	/* does the interface support hardware checksum offload? */
19755 	hwcksum_flags = 0;
19756 	if (ILL_HCKSUM_CAPABLE(ill) &&
19757 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19758 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19759 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19760 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19761 		    HCKSUM_IPHDRCKSUM)
19762 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19763 
19764 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19765 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19766 			hwcksum_flags |= HCK_FULLCKSUM;
19767 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19768 		    HCKSUM_INET_PARTIAL)
19769 			hwcksum_flags |= HCK_PARTIALCKSUM;
19770 	}
19771 
19772 	/*
19773 	 * Each header fragment consists of the leading extra space,
19774 	 * followed by the TCP/IP header, and the trailing extra space.
19775 	 * We make sure that each header fragment begins on a 32-bit
19776 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19777 	 * aligned in tcp_mdt_update).
19778 	 */
19779 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19780 	    tcp->tcp_mdt_hdr_tail), 4);
19781 
19782 	/* are we starting from the beginning of data block? */
19783 	if (*tail_unsent == 0) {
19784 		*xmit_tail = (*xmit_tail)->b_cont;
19785 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19786 		*tail_unsent = (int)MBLKL(*xmit_tail);
19787 	}
19788 
19789 	/*
19790 	 * Here we create one or more Multidata messages, each made up of
19791 	 * one header buffer and up to N payload buffers.  This entire
19792 	 * operation is done within two loops:
19793 	 *
19794 	 * The outer loop mostly deals with creating the Multidata message,
19795 	 * as well as the header buffer that gets added to it.  It also
19796 	 * links the Multidata messages together such that all of them can
19797 	 * be sent down to the lower layer in a single putnext call; this
19798 	 * linking behavior depends on the tcp_mdt_chain tunable.
19799 	 *
19800 	 * The inner loop takes an existing Multidata message, and adds
19801 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19802 	 * packetizes those buffers by filling up the corresponding header
19803 	 * buffer fragments with the proper IP and TCP headers, and by
19804 	 * describing the layout of each packet in the packet descriptors
19805 	 * that get added to the Multidata.
19806 	 */
19807 	do {
19808 		/*
19809 		 * If usable send window is too small, or data blocks in
19810 		 * transmit list are smaller than our threshold (i.e. app
19811 		 * performs large writes followed by small ones), we hand
19812 		 * off the control over to the legacy path.  Note that we'll
19813 		 * get back the control once it encounters a large block.
19814 		 */
19815 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19816 		    (*xmit_tail)->b_cont != NULL &&
19817 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19818 			/* send down what we've got so far */
19819 			if (md_mp_head != NULL) {
19820 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19821 				    obsegs, obbytes, &rconfirm);
19822 			}
19823 			/*
19824 			 * Pass control over to tcp_send(), but tell it to
19825 			 * return to us once a large-size transmission is
19826 			 * possible.
19827 			 */
19828 			TCP_STAT(tcps, tcp_mdt_legacy_small);
19829 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19830 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19831 			    tail_unsent, xmit_tail, local_time,
19832 			    mdt_thres)) <= 0) {
19833 				/* burst count reached, or alloc failed */
19834 				IRE_REFRELE(ire);
19835 				return (err);
19836 			}
19837 
19838 			/* tcp_send() may have sent everything, so check */
19839 			if (*usable <= 0) {
19840 				IRE_REFRELE(ire);
19841 				return (0);
19842 			}
19843 
19844 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
19845 			/*
19846 			 * We may have delivered the Multidata, so make sure
19847 			 * to re-initialize before the next round.
19848 			 */
19849 			md_mp_head = NULL;
19850 			obsegs = obbytes = 0;
19851 			num_burst_seg = tcp->tcp_snd_burst;
19852 			PREP_NEW_MULTIDATA();
19853 
19854 			/* are we starting from the beginning of data block? */
19855 			if (*tail_unsent == 0) {
19856 				*xmit_tail = (*xmit_tail)->b_cont;
19857 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19858 				    (uintptr_t)INT_MAX);
19859 				*tail_unsent = (int)MBLKL(*xmit_tail);
19860 			}
19861 		}
19862 		/*
19863 		 * Record current values for parameters we may need to pass
19864 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
19865 		 * each iteration of the outer loop (each multidata message
19866 		 * creation). If we have a failure in the inner loop, we send
19867 		 * any complete multidata messages we have before reverting
19868 		 * to using the traditional non-md path.
19869 		 */
19870 		snxt_mmd = *snxt;
19871 		usable_mmd = *usable;
19872 		xmit_tail_mmd = *xmit_tail;
19873 		tail_unsent_mmd = *tail_unsent;
19874 		obsegs_mmd = obsegs;
19875 		obbytes_mmd = obbytes;
19876 
19877 		/*
19878 		 * max_pld limits the number of mblks in tcp's transmit
19879 		 * queue that can be added to a Multidata message.  Once
19880 		 * this counter reaches zero, no more additional mblks
19881 		 * can be added to it.  What happens afterwards depends
19882 		 * on whether or not we are set to chain the Multidata
19883 		 * messages.  If we are to link them together, reset
19884 		 * max_pld to its original value (tcp_mdt_max_pld) and
19885 		 * prepare to create a new Multidata message which will
19886 		 * get linked to md_mp_head.  Else, leave it alone and
19887 		 * let the inner loop break on its own.
19888 		 */
19889 		if (tcp_mdt_chain && max_pld == 0)
19890 			PREP_NEW_MULTIDATA();
19891 
19892 		/* adding a payload buffer; re-initialize values */
19893 		if (add_buffer)
19894 			PREP_NEW_PBUF();
19895 
19896 		/*
19897 		 * If we don't have a Multidata, either because we just
19898 		 * (re)entered this outer loop, or after we branched off
19899 		 * to tcp_send above, setup the Multidata and header
19900 		 * buffer to be used.
19901 		 */
19902 		if (md_mp == NULL) {
19903 			int md_hbuflen;
19904 			uint32_t start, stuff;
19905 
19906 			/*
19907 			 * Calculate Multidata header buffer size large enough
19908 			 * to hold all of the headers that can possibly be
19909 			 * sent at this moment.  We'd rather over-estimate
19910 			 * the size than running out of space; this is okay
19911 			 * since this buffer is small anyway.
19912 			 */
19913 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19914 
19915 			/*
19916 			 * Start and stuff offset for partial hardware
19917 			 * checksum offload; these are currently for IPv4.
19918 			 * For full checksum offload, they are set to zero.
19919 			 */
19920 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19921 				if (af == AF_INET) {
19922 					start = IP_SIMPLE_HDR_LENGTH;
19923 					stuff = IP_SIMPLE_HDR_LENGTH +
19924 					    TCP_CHECKSUM_OFFSET;
19925 				} else {
19926 					start = IPV6_HDR_LEN;
19927 					stuff = IPV6_HDR_LEN +
19928 					    TCP_CHECKSUM_OFFSET;
19929 				}
19930 			} else {
19931 				start = stuff = 0;
19932 			}
19933 
19934 			/*
19935 			 * Create the header buffer, Multidata, as well as
19936 			 * any necessary attributes (destination address,
19937 			 * SAP and hardware checksum offload) that should
19938 			 * be associated with the Multidata message.
19939 			 */
19940 			ASSERT(cur_hdr_off == 0);
19941 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19942 			    ((md_hbuf->b_wptr += md_hbuflen),
19943 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19944 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19945 			    /* fastpath mblk */
19946 			    ire->ire_nce->nce_res_mp,
19947 			    /* hardware checksum enabled */
19948 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19949 			    /* hardware checksum offsets */
19950 			    start, stuff, 0,
19951 			    /* hardware checksum flag */
19952 			    hwcksum_flags, tcps) != 0)) {
19953 legacy_send:
19954 				/*
19955 				 * We arrive here from a failure within the
19956 				 * inner (packetizer) loop or we fail one of
19957 				 * the conditionals above. We restore the
19958 				 * previously checkpointed values for:
19959 				 *    xmit_tail
19960 				 *    usable
19961 				 *    tail_unsent
19962 				 *    snxt
19963 				 *    obbytes
19964 				 *    obsegs
19965 				 * We should then be able to dispatch any
19966 				 * complete multidata before reverting to the
19967 				 * traditional path with consistent parameters
19968 				 * (the inner loop updates these as it
19969 				 * iterates).
19970 				 */
19971 				*xmit_tail = xmit_tail_mmd;
19972 				*usable = usable_mmd;
19973 				*tail_unsent = tail_unsent_mmd;
19974 				*snxt = snxt_mmd;
19975 				obbytes = obbytes_mmd;
19976 				obsegs = obsegs_mmd;
19977 				if (md_mp != NULL) {
19978 					/* Unlink message from the chain */
19979 					if (md_mp_head != NULL) {
19980 						err = (intptr_t)rmvb(md_mp_head,
19981 						    md_mp);
19982 						/*
19983 						 * We can't assert that rmvb
19984 						 * did not return -1, since we
19985 						 * may get here before linkb
19986 						 * happens.  We do, however,
19987 						 * check if we just removed the
19988 						 * only element in the list.
19989 						 */
19990 						if (err == 0)
19991 							md_mp_head = NULL;
19992 					}
19993 					/* md_hbuf gets freed automatically */
19994 					TCP_STAT(tcps, tcp_mdt_discarded);
19995 					freeb(md_mp);
19996 				} else {
19997 					/* Either allocb or mmd_alloc failed */
19998 					TCP_STAT(tcps, tcp_mdt_allocfail);
19999 					if (md_hbuf != NULL)
20000 						freeb(md_hbuf);
20001 				}
20002 
20003 				/* send down what we've got so far */
20004 				if (md_mp_head != NULL) {
20005 					tcp_multisend_data(tcp, ire, ill,
20006 					    md_mp_head, obsegs, obbytes,
20007 					    &rconfirm);
20008 				}
20009 legacy_send_no_md:
20010 				if (ire != NULL)
20011 					IRE_REFRELE(ire);
20012 				/*
20013 				 * Too bad; let the legacy path handle this.
20014 				 * We specify INT_MAX for the threshold, since
20015 				 * we gave up with the Multidata processings
20016 				 * and let the old path have it all.
20017 				 */
20018 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20019 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20020 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20021 				    snxt, tail_unsent, xmit_tail, local_time,
20022 				    INT_MAX));
20023 			}
20024 
20025 			/* link to any existing ones, if applicable */
20026 			TCP_STAT(tcps, tcp_mdt_allocd);
20027 			if (md_mp_head == NULL) {
20028 				md_mp_head = md_mp;
20029 			} else if (tcp_mdt_chain) {
20030 				TCP_STAT(tcps, tcp_mdt_linked);
20031 				linkb(md_mp_head, md_mp);
20032 			}
20033 		}
20034 
20035 		ASSERT(md_mp_head != NULL);
20036 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20037 		ASSERT(md_mp != NULL && mmd != NULL);
20038 		ASSERT(md_hbuf != NULL);
20039 
20040 		/*
20041 		 * Packetize the transmittable portion of the data block;
20042 		 * each data block is essentially added to the Multidata
20043 		 * as a payload buffer.  We also deal with adding more
20044 		 * than one payload buffers, which happens when the remaining
20045 		 * packetized portion of the current payload buffer is less
20046 		 * than MSS, while the next data block in transmit queue
20047 		 * has enough data to make up for one.  This "spillover"
20048 		 * case essentially creates a split-packet, where portions
20049 		 * of the packet's payload fragments may span across two
20050 		 * virtually discontiguous address blocks.
20051 		 */
20052 		seg_len = mss;
20053 		do {
20054 			len = seg_len;
20055 
20056 			/* one must remain NULL for DTRACE_IP_FASTPATH */
20057 			ipha = NULL;
20058 			ip6h = NULL;
20059 
20060 			ASSERT(len > 0);
20061 			ASSERT(max_pld >= 0);
20062 			ASSERT(!add_buffer || cur_pld_off == 0);
20063 
20064 			/*
20065 			 * First time around for this payload buffer; note
20066 			 * in the case of a spillover, the following has
20067 			 * been done prior to adding the split-packet
20068 			 * descriptor to Multidata, and we don't want to
20069 			 * repeat the process.
20070 			 */
20071 			if (add_buffer) {
20072 				ASSERT(mmd != NULL);
20073 				ASSERT(md_pbuf == NULL);
20074 				ASSERT(md_pbuf_nxt == NULL);
20075 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20076 
20077 				/*
20078 				 * Have we reached the limit?  We'd get to
20079 				 * this case when we're not chaining the
20080 				 * Multidata messages together, and since
20081 				 * we're done, terminate this loop.
20082 				 */
20083 				if (max_pld == 0)
20084 					break; /* done */
20085 
20086 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20087 					TCP_STAT(tcps, tcp_mdt_allocfail);
20088 					goto legacy_send; /* out_of_mem */
20089 				}
20090 
20091 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20092 				    zc_cap != NULL) {
20093 					if (!ip_md_zcopy_attr(mmd, NULL,
20094 					    zc_cap->ill_zerocopy_flags)) {
20095 						freeb(md_pbuf);
20096 						TCP_STAT(tcps,
20097 						    tcp_mdt_allocfail);
20098 						/* out_of_mem */
20099 						goto legacy_send;
20100 					}
20101 					zcopy = B_TRUE;
20102 				}
20103 
20104 				md_pbuf->b_rptr += base_pld_off;
20105 
20106 				/*
20107 				 * Add a payload buffer to the Multidata; this
20108 				 * operation must not fail, or otherwise our
20109 				 * logic in this routine is broken.  There
20110 				 * is no memory allocation done by the
20111 				 * routine, so any returned failure simply
20112 				 * tells us that we've done something wrong.
20113 				 *
20114 				 * A failure tells us that either we're adding
20115 				 * the same payload buffer more than once, or
20116 				 * we're trying to add more buffers than
20117 				 * allowed (max_pld calculation is wrong).
20118 				 * None of the above cases should happen, and
20119 				 * we panic because either there's horrible
20120 				 * heap corruption, and/or programming mistake.
20121 				 */
20122 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20123 				if (pbuf_idx < 0) {
20124 					cmn_err(CE_PANIC, "tcp_multisend: "
20125 					    "payload buffer logic error "
20126 					    "detected for tcp %p mmd %p "
20127 					    "pbuf %p (%d)\n",
20128 					    (void *)tcp, (void *)mmd,
20129 					    (void *)md_pbuf, pbuf_idx);
20130 				}
20131 
20132 				ASSERT(max_pld > 0);
20133 				--max_pld;
20134 				add_buffer = B_FALSE;
20135 			}
20136 
20137 			ASSERT(md_mp_head != NULL);
20138 			ASSERT(md_pbuf != NULL);
20139 			ASSERT(md_pbuf_nxt == NULL);
20140 			ASSERT(pbuf_idx != -1);
20141 			ASSERT(pbuf_idx_nxt == -1);
20142 			ASSERT(*usable > 0);
20143 
20144 			/*
20145 			 * We spillover to the next payload buffer only
20146 			 * if all of the following is true:
20147 			 *
20148 			 *   1. There is not enough data on the current
20149 			 *	payload buffer to make up `len',
20150 			 *   2. We are allowed to send `len',
20151 			 *   3. The next payload buffer length is large
20152 			 *	enough to accomodate `spill'.
20153 			 */
20154 			if ((spill = len - *tail_unsent) > 0 &&
20155 			    *usable >= len &&
20156 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20157 			    max_pld > 0) {
20158 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20159 				if (md_pbuf_nxt == NULL) {
20160 					TCP_STAT(tcps, tcp_mdt_allocfail);
20161 					goto legacy_send; /* out_of_mem */
20162 				}
20163 
20164 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20165 				    zc_cap != NULL) {
20166 					if (!ip_md_zcopy_attr(mmd, NULL,
20167 					    zc_cap->ill_zerocopy_flags)) {
20168 						freeb(md_pbuf_nxt);
20169 						TCP_STAT(tcps,
20170 						    tcp_mdt_allocfail);
20171 						/* out_of_mem */
20172 						goto legacy_send;
20173 					}
20174 					zcopy = B_TRUE;
20175 				}
20176 
20177 				/*
20178 				 * See comments above on the first call to
20179 				 * mmd_addpldbuf for explanation on the panic.
20180 				 */
20181 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20182 				if (pbuf_idx_nxt < 0) {
20183 					panic("tcp_multisend: "
20184 					    "next payload buffer logic error "
20185 					    "detected for tcp %p mmd %p "
20186 					    "pbuf %p (%d)\n",
20187 					    (void *)tcp, (void *)mmd,
20188 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20189 				}
20190 
20191 				ASSERT(max_pld > 0);
20192 				--max_pld;
20193 			} else if (spill > 0) {
20194 				/*
20195 				 * If there's a spillover, but the following
20196 				 * xmit_tail couldn't give us enough octets
20197 				 * to reach "len", then stop the current
20198 				 * Multidata creation and let the legacy
20199 				 * tcp_send() path take over.  We don't want
20200 				 * to send the tiny segment as part of this
20201 				 * Multidata for performance reasons; instead,
20202 				 * we let the legacy path deal with grouping
20203 				 * it with the subsequent small mblks.
20204 				 */
20205 				if (*usable >= len &&
20206 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20207 					max_pld = 0;
20208 					break;	/* done */
20209 				}
20210 
20211 				/*
20212 				 * We can't spillover, and we are near
20213 				 * the end of the current payload buffer,
20214 				 * so send what's left.
20215 				 */
20216 				ASSERT(*tail_unsent > 0);
20217 				len = *tail_unsent;
20218 			}
20219 
20220 			/* tail_unsent is negated if there is a spillover */
20221 			*tail_unsent -= len;
20222 			*usable -= len;
20223 			ASSERT(*usable >= 0);
20224 
20225 			if (*usable < mss)
20226 				seg_len = *usable;
20227 			/*
20228 			 * Sender SWS avoidance; see comments in tcp_send();
20229 			 * everything else is the same, except that we only
20230 			 * do this here if there is no more data to be sent
20231 			 * following the current xmit_tail.  We don't check
20232 			 * for 1-byte urgent data because we shouldn't get
20233 			 * here if TCP_URG_VALID is set.
20234 			 */
20235 			if (*usable > 0 && *usable < mss &&
20236 			    ((md_pbuf_nxt == NULL &&
20237 			    (*xmit_tail)->b_cont == NULL) ||
20238 			    (md_pbuf_nxt != NULL &&
20239 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20240 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20241 			    (tcp->tcp_unsent -
20242 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20243 			    !tcp->tcp_zero_win_probe) {
20244 				if ((*snxt + len) == tcp->tcp_snxt &&
20245 				    (*snxt + len) == tcp->tcp_suna) {
20246 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20247 				}
20248 				done = B_TRUE;
20249 			}
20250 
20251 			/*
20252 			 * Prime pump for IP's checksumming on our behalf;
20253 			 * include the adjustment for a source route if any.
20254 			 * Do this only for software/partial hardware checksum
20255 			 * offload, as this field gets zeroed out later for
20256 			 * the full hardware checksum offload case.
20257 			 */
20258 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20259 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20260 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20261 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20262 			}
20263 
20264 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20265 			*snxt += len;
20266 
20267 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20268 			/*
20269 			 * We set the PUSH bit only if TCP has no more buffered
20270 			 * data to be transmitted (or if sender SWS avoidance
20271 			 * takes place), as opposed to setting it for every
20272 			 * last packet in the burst.
20273 			 */
20274 			if (done ||
20275 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20276 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20277 
20278 			/*
20279 			 * Set FIN bit if this is our last segment; snxt
20280 			 * already includes its length, and it will not
20281 			 * be adjusted after this point.
20282 			 */
20283 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20284 			    *snxt == tcp->tcp_fss) {
20285 				if (!tcp->tcp_fin_acked) {
20286 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20287 					BUMP_MIB(&tcps->tcps_mib,
20288 					    tcpOutControl);
20289 				}
20290 				if (!tcp->tcp_fin_sent) {
20291 					tcp->tcp_fin_sent = B_TRUE;
20292 					/*
20293 					 * tcp state must be ESTABLISHED
20294 					 * in order for us to get here in
20295 					 * the first place.
20296 					 */
20297 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20298 
20299 					/*
20300 					 * Upon returning from this routine,
20301 					 * tcp_wput_data() will set tcp_snxt
20302 					 * to be equal to snxt + tcp_fin_sent.
20303 					 * This is essentially the same as
20304 					 * setting it to tcp_fss + 1.
20305 					 */
20306 				}
20307 			}
20308 
20309 			tcp->tcp_last_sent_len = (ushort_t)len;
20310 
20311 			len += tcp_hdr_len;
20312 			if (tcp->tcp_ipversion == IPV4_VERSION)
20313 				tcp->tcp_ipha->ipha_length = htons(len);
20314 			else
20315 				tcp->tcp_ip6h->ip6_plen = htons(len -
20316 				    ((char *)&tcp->tcp_ip6h[1] -
20317 				    tcp->tcp_iphc));
20318 
20319 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20320 
20321 			/* setup header fragment */
20322 			PDESC_HDR_ADD(pkt_info,
20323 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20324 			    tcp->tcp_mdt_hdr_head,		/* head room */
20325 			    tcp_hdr_len,			/* len */
20326 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20327 
20328 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20329 			    hdr_frag_sz);
20330 			ASSERT(MBLKIN(md_hbuf,
20331 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20332 			    PDESC_HDRSIZE(pkt_info)));
20333 
20334 			/* setup first payload fragment */
20335 			PDESC_PLD_INIT(pkt_info);
20336 			PDESC_PLD_SPAN_ADD(pkt_info,
20337 			    pbuf_idx,				/* index */
20338 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20339 			    tcp->tcp_last_sent_len);		/* len */
20340 
20341 			/* create a split-packet in case of a spillover */
20342 			if (md_pbuf_nxt != NULL) {
20343 				ASSERT(spill > 0);
20344 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20345 				ASSERT(!add_buffer);
20346 
20347 				md_pbuf = md_pbuf_nxt;
20348 				md_pbuf_nxt = NULL;
20349 				pbuf_idx = pbuf_idx_nxt;
20350 				pbuf_idx_nxt = -1;
20351 				cur_pld_off = spill;
20352 
20353 				/* trim out first payload fragment */
20354 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20355 
20356 				/* setup second payload fragment */
20357 				PDESC_PLD_SPAN_ADD(pkt_info,
20358 				    pbuf_idx,			/* index */
20359 				    md_pbuf->b_rptr,		/* start */
20360 				    spill);			/* len */
20361 
20362 				if ((*xmit_tail)->b_next == NULL) {
20363 					/*
20364 					 * Store the lbolt used for RTT
20365 					 * estimation. We can only record one
20366 					 * timestamp per mblk so we do it when
20367 					 * we reach the end of the payload
20368 					 * buffer.  Also we only take a new
20369 					 * timestamp sample when the previous
20370 					 * timed data from the same mblk has
20371 					 * been ack'ed.
20372 					 */
20373 					(*xmit_tail)->b_prev = local_time;
20374 					(*xmit_tail)->b_next =
20375 					    (mblk_t *)(uintptr_t)first_snxt;
20376 				}
20377 
20378 				first_snxt = *snxt - spill;
20379 
20380 				/*
20381 				 * Advance xmit_tail; usable could be 0 by
20382 				 * the time we got here, but we made sure
20383 				 * above that we would only spillover to
20384 				 * the next data block if usable includes
20385 				 * the spilled-over amount prior to the
20386 				 * subtraction.  Therefore, we are sure
20387 				 * that xmit_tail->b_cont can't be NULL.
20388 				 */
20389 				ASSERT((*xmit_tail)->b_cont != NULL);
20390 				*xmit_tail = (*xmit_tail)->b_cont;
20391 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20392 				    (uintptr_t)INT_MAX);
20393 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20394 			} else {
20395 				cur_pld_off += tcp->tcp_last_sent_len;
20396 			}
20397 
20398 			/*
20399 			 * Fill in the header using the template header, and
20400 			 * add options such as time-stamp, ECN and/or SACK,
20401 			 * as needed.
20402 			 */
20403 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20404 			    (clock_t)local_time, num_sack_blk);
20405 
20406 			/* take care of some IP header businesses */
20407 			if (af == AF_INET) {
20408 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20409 
20410 				ASSERT(OK_32PTR((uchar_t *)ipha));
20411 				ASSERT(PDESC_HDRL(pkt_info) >=
20412 				    IP_SIMPLE_HDR_LENGTH);
20413 				ASSERT(ipha->ipha_version_and_hdr_length ==
20414 				    IP_SIMPLE_HDR_VERSION);
20415 
20416 				/*
20417 				 * Assign ident value for current packet; see
20418 				 * related comments in ip_wput_ire() about the
20419 				 * contract private interface with clustering
20420 				 * group.
20421 				 */
20422 				clusterwide = B_FALSE;
20423 				if (cl_inet_ipident != NULL) {
20424 					ASSERT(cl_inet_isclusterwide != NULL);
20425 					if ((*cl_inet_isclusterwide)(stack_id,
20426 					    IPPROTO_IP, AF_INET,
20427 					    (uint8_t *)(uintptr_t)src, NULL)) {
20428 						ipha->ipha_ident =
20429 						    (*cl_inet_ipident)(stack_id,
20430 						    IPPROTO_IP, AF_INET,
20431 						    (uint8_t *)(uintptr_t)src,
20432 						    (uint8_t *)(uintptr_t)dst,
20433 						    NULL);
20434 						clusterwide = B_TRUE;
20435 					}
20436 				}
20437 
20438 				if (!clusterwide) {
20439 					ipha->ipha_ident = (uint16_t)
20440 					    atomic_add_32_nv(
20441 						&ire->ire_ident, 1);
20442 				}
20443 #ifndef _BIG_ENDIAN
20444 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20445 				    (ipha->ipha_ident >> 8);
20446 #endif
20447 			} else {
20448 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20449 
20450 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20451 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20452 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20453 				ASSERT(PDESC_HDRL(pkt_info) >=
20454 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20455 				    TCP_CHECKSUM_SIZE));
20456 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20457 
20458 				if (tcp->tcp_ip_forward_progress) {
20459 					rconfirm = B_TRUE;
20460 					tcp->tcp_ip_forward_progress = B_FALSE;
20461 				}
20462 			}
20463 
20464 			/* at least one payload span, and at most two */
20465 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20466 
20467 			/* add the packet descriptor to Multidata */
20468 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20469 			    KM_NOSLEEP)) == NULL) {
20470 				/*
20471 				 * Any failure other than ENOMEM indicates
20472 				 * that we have passed in invalid pkt_info
20473 				 * or parameters to mmd_addpdesc, which must
20474 				 * not happen.
20475 				 *
20476 				 * EINVAL is a result of failure on boundary
20477 				 * checks against the pkt_info contents.  It
20478 				 * should not happen, and we panic because
20479 				 * either there's horrible heap corruption,
20480 				 * and/or programming mistake.
20481 				 */
20482 				if (err != ENOMEM) {
20483 					cmn_err(CE_PANIC, "tcp_multisend: "
20484 					    "pdesc logic error detected for "
20485 					    "tcp %p mmd %p pinfo %p (%d)\n",
20486 					    (void *)tcp, (void *)mmd,
20487 					    (void *)pkt_info, err);
20488 				}
20489 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20490 				goto legacy_send; /* out_of_mem */
20491 			}
20492 			ASSERT(pkt != NULL);
20493 
20494 			/* calculate IP header and TCP checksums */
20495 			if (af == AF_INET) {
20496 				/* calculate pseudo-header checksum */
20497 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20498 				    (src >> 16) + (src & 0xFFFF);
20499 
20500 				/* offset for TCP header checksum */
20501 				up = IPH_TCPH_CHECKSUMP(ipha,
20502 				    IP_SIMPLE_HDR_LENGTH);
20503 			} else {
20504 				up = (uint16_t *)&ip6h->ip6_src;
20505 
20506 				/* calculate pseudo-header checksum */
20507 				cksum = up[0] + up[1] + up[2] + up[3] +
20508 				    up[4] + up[5] + up[6] + up[7] +
20509 				    up[8] + up[9] + up[10] + up[11] +
20510 				    up[12] + up[13] + up[14] + up[15];
20511 
20512 				/* Fold the initial sum */
20513 				cksum = (cksum & 0xffff) + (cksum >> 16);
20514 
20515 				up = (uint16_t *)(((uchar_t *)ip6h) +
20516 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20517 			}
20518 
20519 			if (hwcksum_flags & HCK_FULLCKSUM) {
20520 				/* clear checksum field for hardware */
20521 				*up = 0;
20522 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20523 				uint32_t sum;
20524 
20525 				/* pseudo-header checksumming */
20526 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20527 				sum = (sum & 0xFFFF) + (sum >> 16);
20528 				*up = (sum & 0xFFFF) + (sum >> 16);
20529 			} else {
20530 				/* software checksumming */
20531 				TCP_STAT(tcps, tcp_out_sw_cksum);
20532 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20533 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20534 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20535 				    cksum + IP_TCP_CSUM_COMP);
20536 				if (*up == 0)
20537 					*up = 0xFFFF;
20538 			}
20539 
20540 			/* IPv4 header checksum */
20541 			if (af == AF_INET) {
20542 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20543 					ipha->ipha_hdr_checksum = 0;
20544 				} else {
20545 					IP_HDR_CKSUM(ipha, cksum,
20546 					    ((uint32_t *)ipha)[0],
20547 					    ((uint16_t *)ipha)[4]);
20548 				}
20549 			}
20550 
20551 			if (af == AF_INET &&
20552 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20553 			    af == AF_INET6 &&
20554 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20555 				mblk_t	*mp, *mp1;
20556 				uchar_t	*hdr_rptr, *hdr_wptr;
20557 				uchar_t	*pld_rptr, *pld_wptr;
20558 
20559 				/*
20560 				 * We reconstruct a pseudo packet for the hooks
20561 				 * framework using mmd_transform_link().
20562 				 * If it is a split packet we pullup the
20563 				 * payload. FW_HOOKS expects a pkt comprising
20564 				 * of two mblks: a header and the payload.
20565 				 */
20566 				if ((mp = mmd_transform_link(pkt)) == NULL) {
20567 					TCP_STAT(tcps, tcp_mdt_allocfail);
20568 					goto legacy_send;
20569 				}
20570 
20571 				if (pkt_info->pld_cnt > 1) {
20572 					/* split payload, more than one pld */
20573 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
20574 					    NULL) {
20575 						freemsg(mp);
20576 						TCP_STAT(tcps,
20577 						    tcp_mdt_allocfail);
20578 						goto legacy_send;
20579 					}
20580 					freemsg(mp->b_cont);
20581 					mp->b_cont = mp1;
20582 				} else {
20583 					mp1 = mp->b_cont;
20584 				}
20585 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
20586 
20587 				/*
20588 				 * Remember the message offsets. This is so we
20589 				 * can detect changes when we return from the
20590 				 * FW_HOOKS callbacks.
20591 				 */
20592 				hdr_rptr = mp->b_rptr;
20593 				hdr_wptr = mp->b_wptr;
20594 				pld_rptr = mp->b_cont->b_rptr;
20595 				pld_wptr = mp->b_cont->b_wptr;
20596 
20597 				if (af == AF_INET) {
20598 					DTRACE_PROBE4(
20599 					    ip4__physical__out__start,
20600 					    ill_t *, NULL,
20601 					    ill_t *, ill,
20602 					    ipha_t *, ipha,
20603 					    mblk_t *, mp);
20604 					FW_HOOKS(
20605 					    ipst->ips_ip4_physical_out_event,
20606 					    ipst->ips_ipv4firewall_physical_out,
20607 					    NULL, ill, ipha, mp, mp, 0, ipst);
20608 					DTRACE_PROBE1(
20609 					    ip4__physical__out__end,
20610 					    mblk_t *, mp);
20611 				} else {
20612 					DTRACE_PROBE4(
20613 					    ip6__physical__out_start,
20614 					    ill_t *, NULL,
20615 					    ill_t *, ill,
20616 					    ip6_t *, ip6h,
20617 					    mblk_t *, mp);
20618 					FW_HOOKS6(
20619 					    ipst->ips_ip6_physical_out_event,
20620 					    ipst->ips_ipv6firewall_physical_out,
20621 					    NULL, ill, ip6h, mp, mp, 0, ipst);
20622 					DTRACE_PROBE1(
20623 					    ip6__physical__out__end,
20624 					    mblk_t *, mp);
20625 				}
20626 
20627 				if (mp == NULL ||
20628 				    (mp1 = mp->b_cont) == NULL ||
20629 				    mp->b_rptr != hdr_rptr ||
20630 				    mp->b_wptr != hdr_wptr ||
20631 				    mp1->b_rptr != pld_rptr ||
20632 				    mp1->b_wptr != pld_wptr ||
20633 				    mp1->b_cont != NULL) {
20634 					/*
20635 					 * We abandon multidata processing and
20636 					 * return to the normal path, either
20637 					 * when a packet is blocked, or when
20638 					 * the boundaries of header buffer or
20639 					 * payload buffer have been changed by
20640 					 * FW_HOOKS[6].
20641 					 */
20642 					if (mp != NULL)
20643 						freemsg(mp);
20644 					goto legacy_send;
20645 				}
20646 				/* Finished with the pseudo packet */
20647 				freemsg(mp);
20648 			}
20649 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
20650 			    ill, ipha, ip6h);
20651 			/* advance header offset */
20652 			cur_hdr_off += hdr_frag_sz;
20653 
20654 			obbytes += tcp->tcp_last_sent_len;
20655 			++obsegs;
20656 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20657 		    *tail_unsent > 0);
20658 
20659 		if ((*xmit_tail)->b_next == NULL) {
20660 			/*
20661 			 * Store the lbolt used for RTT estimation. We can only
20662 			 * record one timestamp per mblk so we do it when we
20663 			 * reach the end of the payload buffer. Also we only
20664 			 * take a new timestamp sample when the previous timed
20665 			 * data from the same mblk has been ack'ed.
20666 			 */
20667 			(*xmit_tail)->b_prev = local_time;
20668 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20669 		}
20670 
20671 		ASSERT(*tail_unsent >= 0);
20672 		if (*tail_unsent > 0) {
20673 			/*
20674 			 * We got here because we broke out of the above
20675 			 * loop due to of one of the following cases:
20676 			 *
20677 			 *   1. len < adjusted MSS (i.e. small),
20678 			 *   2. Sender SWS avoidance,
20679 			 *   3. max_pld is zero.
20680 			 *
20681 			 * We are done for this Multidata, so trim our
20682 			 * last payload buffer (if any) accordingly.
20683 			 */
20684 			if (md_pbuf != NULL)
20685 				md_pbuf->b_wptr -= *tail_unsent;
20686 		} else if (*usable > 0) {
20687 			*xmit_tail = (*xmit_tail)->b_cont;
20688 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20689 			    (uintptr_t)INT_MAX);
20690 			*tail_unsent = (int)MBLKL(*xmit_tail);
20691 			add_buffer = B_TRUE;
20692 		}
20693 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20694 	    (tcp_mdt_chain || max_pld > 0));
20695 
20696 	if (md_mp_head != NULL) {
20697 		/* send everything down */
20698 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20699 		    &rconfirm);
20700 	}
20701 
20702 #undef PREP_NEW_MULTIDATA
20703 #undef PREP_NEW_PBUF
20704 #undef IPVER
20705 
20706 	IRE_REFRELE(ire);
20707 	return (0);
20708 }
20709 
20710 /*
20711  * A wrapper function for sending one or more Multidata messages down to
20712  * the module below ip; this routine does not release the reference of the
20713  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20714  */
20715 static void
20716 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20717     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20718 {
20719 	uint64_t delta;
20720 	nce_t *nce;
20721 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20722 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20723 
20724 	ASSERT(ire != NULL && ill != NULL);
20725 	ASSERT(ire->ire_stq != NULL);
20726 	ASSERT(md_mp_head != NULL);
20727 	ASSERT(rconfirm != NULL);
20728 
20729 	/* adjust MIBs and IRE timestamp */
20730 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
20731 	tcp->tcp_obsegs += obsegs;
20732 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
20733 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
20734 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
20735 
20736 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20737 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
20738 	} else {
20739 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
20740 	}
20741 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
20742 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
20743 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
20744 
20745 	ire->ire_ob_pkt_count += obsegs;
20746 	if (ire->ire_ipif != NULL)
20747 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20748 	ire->ire_last_used_time = lbolt;
20749 
20750 	if (ipst->ips_ipobs_enabled) {
20751 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
20752 		pdesc_t *dl_pkt;
20753 		pdescinfo_t pinfo;
20754 		mblk_t *nmp;
20755 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
20756 
20757 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
20758 		    (dl_pkt != NULL);
20759 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
20760 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
20761 				continue;
20762 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
20763 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
20764 			freemsg(nmp);
20765 		}
20766 	}
20767 
20768 	/* send it down */
20769 	putnext(ire->ire_stq, md_mp_head);
20770 
20771 	/* we're done for TCP/IPv4 */
20772 	if (tcp->tcp_ipversion == IPV4_VERSION)
20773 		return;
20774 
20775 	nce = ire->ire_nce;
20776 
20777 	ASSERT(nce != NULL);
20778 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20779 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20780 
20781 	/* reachability confirmation? */
20782 	if (*rconfirm) {
20783 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20784 		if (nce->nce_state != ND_REACHABLE) {
20785 			mutex_enter(&nce->nce_lock);
20786 			nce->nce_state = ND_REACHABLE;
20787 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20788 			mutex_exit(&nce->nce_lock);
20789 			(void) untimeout(nce->nce_timeout_id);
20790 			if (ip_debug > 2) {
20791 				/* ip1dbg */
20792 				pr_addr_dbg("tcp_multisend_data: state "
20793 				    "for %s changed to REACHABLE\n",
20794 				    AF_INET6, &ire->ire_addr_v6);
20795 			}
20796 		}
20797 		/* reset transport reachability confirmation */
20798 		*rconfirm = B_FALSE;
20799 	}
20800 
20801 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20802 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20803 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20804 
20805 	if (delta > (uint64_t)ill->ill_reachable_time) {
20806 		mutex_enter(&nce->nce_lock);
20807 		switch (nce->nce_state) {
20808 		case ND_REACHABLE:
20809 		case ND_STALE:
20810 			/*
20811 			 * ND_REACHABLE is identical to ND_STALE in this
20812 			 * specific case. If reachable time has expired for
20813 			 * this neighbor (delta is greater than reachable
20814 			 * time), conceptually, the neighbor cache is no
20815 			 * longer in REACHABLE state, but already in STALE
20816 			 * state.  So the correct transition here is to
20817 			 * ND_DELAY.
20818 			 */
20819 			nce->nce_state = ND_DELAY;
20820 			mutex_exit(&nce->nce_lock);
20821 			NDP_RESTART_TIMER(nce,
20822 			    ipst->ips_delay_first_probe_time);
20823 			if (ip_debug > 3) {
20824 				/* ip2dbg */
20825 				pr_addr_dbg("tcp_multisend_data: state "
20826 				    "for %s changed to DELAY\n",
20827 				    AF_INET6, &ire->ire_addr_v6);
20828 			}
20829 			break;
20830 		case ND_DELAY:
20831 		case ND_PROBE:
20832 			mutex_exit(&nce->nce_lock);
20833 			/* Timers have already started */
20834 			break;
20835 		case ND_UNREACHABLE:
20836 			/*
20837 			 * ndp timer has detected that this nce is
20838 			 * unreachable and initiated deleting this nce
20839 			 * and all its associated IREs. This is a race
20840 			 * where we found the ire before it was deleted
20841 			 * and have just sent out a packet using this
20842 			 * unreachable nce.
20843 			 */
20844 			mutex_exit(&nce->nce_lock);
20845 			break;
20846 		default:
20847 			ASSERT(0);
20848 		}
20849 	}
20850 }
20851 
20852 /*
20853  * Derived from tcp_send_data().
20854  */
20855 static void
20856 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
20857     int num_lso_seg)
20858 {
20859 	ipha_t		*ipha;
20860 	mblk_t		*ire_fp_mp;
20861 	uint_t		ire_fp_mp_len;
20862 	uint32_t	hcksum_txflags = 0;
20863 	ipaddr_t	src;
20864 	ipaddr_t	dst;
20865 	uint32_t	cksum;
20866 	uint16_t	*up;
20867 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20868 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20869 
20870 	ASSERT(DB_TYPE(mp) == M_DATA);
20871 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20872 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
20873 	ASSERT(tcp->tcp_connp != NULL);
20874 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
20875 
20876 	ipha = (ipha_t *)mp->b_rptr;
20877 	src = ipha->ipha_src;
20878 	dst = ipha->ipha_dst;
20879 
20880 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
20881 
20882 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20883 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
20884 	    num_lso_seg);
20885 #ifndef _BIG_ENDIAN
20886 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20887 #endif
20888 	if (tcp->tcp_snd_zcopy_aware) {
20889 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
20890 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
20891 			mp = tcp_zcopy_disable(tcp, mp);
20892 	}
20893 
20894 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
20895 		ASSERT(ill->ill_hcksum_capab != NULL);
20896 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
20897 	}
20898 
20899 	/*
20900 	 * Since the TCP checksum should be recalculated by h/w, we can just
20901 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
20902 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
20903 	 * The partial pseudo-header excludes TCP length, that was calculated
20904 	 * in tcp_send(), so to zero *up before further processing.
20905 	 */
20906 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20907 
20908 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
20909 	*up = 0;
20910 
20911 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
20912 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
20913 
20914 	/*
20915 	 * Append LSO flags and mss to the mp.
20916 	 */
20917 	lso_info_set(mp, mss, HW_LSO);
20918 
20919 	ipha->ipha_fragment_offset_and_flags |=
20920 	    (uint32_t)htons(ire->ire_frag_flag);
20921 
20922 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
20923 	ire_fp_mp_len = MBLKL(ire_fp_mp);
20924 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
20925 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
20926 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
20927 
20928 	UPDATE_OB_PKT_COUNT(ire);
20929 	ire->ire_last_used_time = lbolt;
20930 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
20931 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
20932 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
20933 	    ntohs(ipha->ipha_length));
20934 
20935 	DTRACE_PROBE4(ip4__physical__out__start,
20936 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
20937 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
20938 	    ipst->ips_ipv4firewall_physical_out, NULL,
20939 	    ill, ipha, mp, mp, 0, ipst);
20940 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
20941 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
20942 
20943 	if (mp != NULL) {
20944 		if (ipst->ips_ipobs_enabled) {
20945 			zoneid_t szone;
20946 
20947 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
20948 			    ipst, ALL_ZONES);
20949 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
20950 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
20951 		}
20952 
20953 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0, NULL);
20954 	}
20955 }
20956 
20957 /*
20958  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20959  * scheme, and returns one of the following:
20960  *
20961  * -1 = failed allocation.
20962  *  0 = success; burst count reached, or usable send window is too small,
20963  *      and that we'd rather wait until later before sending again.
20964  *  1 = success; we are called from tcp_multisend(), and both usable send
20965  *      window and tail_unsent are greater than the MDT threshold, and thus
20966  *      Multidata Transmit should be used instead.
20967  */
20968 static int
20969 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20970     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20971     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20972     const int mdt_thres)
20973 {
20974 	int num_burst_seg = tcp->tcp_snd_burst;
20975 	ire_t		*ire = NULL;
20976 	ill_t		*ill = NULL;
20977 	mblk_t		*ire_fp_mp = NULL;
20978 	uint_t		ire_fp_mp_len = 0;
20979 	int		num_lso_seg = 1;
20980 	uint_t		lso_usable;
20981 	boolean_t	do_lso_send = B_FALSE;
20982 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20983 
20984 	/*
20985 	 * Check LSO capability before any further work. And the similar check
20986 	 * need to be done in for(;;) loop.
20987 	 * LSO will be deployed when therer is more than one mss of available
20988 	 * data and a burst transmission is allowed.
20989 	 */
20990 	if (tcp->tcp_lso &&
20991 	    (tcp->tcp_valid_bits == 0 ||
20992 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
20993 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20994 		/*
20995 		 * Try to find usable IRE/ILL and do basic check to the ILL.
20996 		 * Double check LSO usability before going further, since the
20997 		 * underlying interface could have been changed. In case of any
20998 		 * change of LSO capability, set tcp_ire_ill_check_done to
20999 		 * B_FALSE to force to check the ILL with the next send.
21000 		 */
21001 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill) &&
21002 		    tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
21003 			/*
21004 			 * Enable LSO with this transmission.
21005 			 * Since IRE has been hold in tcp_send_find_ire_ill(),
21006 			 * IRE_REFRELE(ire) should be called before return.
21007 			 */
21008 			do_lso_send = B_TRUE;
21009 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21010 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21011 			/* Round up to multiple of 4 */
21012 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21013 		} else {
21014 			tcp->tcp_lso = B_FALSE;
21015 			tcp->tcp_ire_ill_check_done = B_FALSE;
21016 			do_lso_send = B_FALSE;
21017 			ill = NULL;
21018 		}
21019 	}
21020 
21021 	for (;;) {
21022 		struct datab	*db;
21023 		tcph_t		*tcph;
21024 		uint32_t	sum;
21025 		mblk_t		*mp, *mp1;
21026 		uchar_t		*rptr;
21027 		int		len;
21028 
21029 		/*
21030 		 * If we're called by tcp_multisend(), and the amount of
21031 		 * sendable data as well as the size of current xmit_tail
21032 		 * is beyond the MDT threshold, return to the caller and
21033 		 * let the large data transmit be done using MDT.
21034 		 */
21035 		if (*usable > 0 && *usable > mdt_thres &&
21036 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21037 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21038 			ASSERT(tcp->tcp_mdt);
21039 			return (1);	/* success; do large send */
21040 		}
21041 
21042 		if (num_burst_seg == 0)
21043 			break;		/* success; burst count reached */
21044 
21045 		/*
21046 		 * Calculate the maximum payload length we can send in *one*
21047 		 * time.
21048 		 */
21049 		if (do_lso_send) {
21050 			/*
21051 			 * Check whether need to do LSO any more.
21052 			 */
21053 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21054 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21055 				lso_usable = MIN(lso_usable,
21056 				    num_burst_seg * mss);
21057 
21058 				num_lso_seg = lso_usable / mss;
21059 				if (lso_usable % mss) {
21060 					num_lso_seg++;
21061 					tcp->tcp_last_sent_len = (ushort_t)
21062 					    (lso_usable % mss);
21063 				} else {
21064 					tcp->tcp_last_sent_len = (ushort_t)mss;
21065 				}
21066 			} else {
21067 				do_lso_send = B_FALSE;
21068 				num_lso_seg = 1;
21069 				lso_usable = mss;
21070 			}
21071 		}
21072 
21073 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21074 
21075 		/*
21076 		 * Adjust num_burst_seg here.
21077 		 */
21078 		num_burst_seg -= num_lso_seg;
21079 
21080 		len = mss;
21081 		if (len > *usable) {
21082 			ASSERT(do_lso_send == B_FALSE);
21083 
21084 			len = *usable;
21085 			if (len <= 0) {
21086 				/* Terminate the loop */
21087 				break;	/* success; too small */
21088 			}
21089 			/*
21090 			 * Sender silly-window avoidance.
21091 			 * Ignore this if we are going to send a
21092 			 * zero window probe out.
21093 			 *
21094 			 * TODO: force data into microscopic window?
21095 			 *	==> (!pushed || (unsent > usable))
21096 			 */
21097 			if (len < (tcp->tcp_max_swnd >> 1) &&
21098 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21099 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21100 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21101 				/*
21102 				 * If the retransmit timer is not running
21103 				 * we start it so that we will retransmit
21104 				 * in the case when the the receiver has
21105 				 * decremented the window.
21106 				 */
21107 				if (*snxt == tcp->tcp_snxt &&
21108 				    *snxt == tcp->tcp_suna) {
21109 					/*
21110 					 * We are not supposed to send
21111 					 * anything.  So let's wait a little
21112 					 * bit longer before breaking SWS
21113 					 * avoidance.
21114 					 *
21115 					 * What should the value be?
21116 					 * Suggestion: MAX(init rexmit time,
21117 					 * tcp->tcp_rto)
21118 					 */
21119 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21120 				}
21121 				break;	/* success; too small */
21122 			}
21123 		}
21124 
21125 		tcph = tcp->tcp_tcph;
21126 
21127 		/*
21128 		 * The reason to adjust len here is that we need to set flags
21129 		 * and calculate checksum.
21130 		 */
21131 		if (do_lso_send)
21132 			len = lso_usable;
21133 
21134 		*usable -= len; /* Approximate - can be adjusted later */
21135 		if (*usable > 0)
21136 			tcph->th_flags[0] = TH_ACK;
21137 		else
21138 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21139 
21140 		/*
21141 		 * Prime pump for IP's checksumming on our behalf
21142 		 * Include the adjustment for a source route if any.
21143 		 */
21144 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21145 		sum = (sum >> 16) + (sum & 0xFFFF);
21146 		U16_TO_ABE16(sum, tcph->th_sum);
21147 
21148 		U32_TO_ABE32(*snxt, tcph->th_seq);
21149 
21150 		/*
21151 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21152 		 * set.  For the case when TCP_FSS_VALID is the only valid
21153 		 * bit (normal active close), branch off only when we think
21154 		 * that the FIN flag needs to be set.  Note for this case,
21155 		 * that (snxt + len) may not reflect the actual seg_len,
21156 		 * as len may be further reduced in tcp_xmit_mp().  If len
21157 		 * gets modified, we will end up here again.
21158 		 */
21159 		if (tcp->tcp_valid_bits != 0 &&
21160 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21161 		    ((*snxt + len) == tcp->tcp_fss))) {
21162 			uchar_t		*prev_rptr;
21163 			uint32_t	prev_snxt = tcp->tcp_snxt;
21164 
21165 			if (*tail_unsent == 0) {
21166 				ASSERT((*xmit_tail)->b_cont != NULL);
21167 				*xmit_tail = (*xmit_tail)->b_cont;
21168 				prev_rptr = (*xmit_tail)->b_rptr;
21169 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21170 				    (*xmit_tail)->b_rptr);
21171 			} else {
21172 				prev_rptr = (*xmit_tail)->b_rptr;
21173 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21174 				    *tail_unsent;
21175 			}
21176 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21177 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21178 			/* Restore tcp_snxt so we get amount sent right. */
21179 			tcp->tcp_snxt = prev_snxt;
21180 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21181 				/*
21182 				 * If the previous timestamp is still in use,
21183 				 * don't stomp on it.
21184 				 */
21185 				if ((*xmit_tail)->b_next == NULL) {
21186 					(*xmit_tail)->b_prev = local_time;
21187 					(*xmit_tail)->b_next =
21188 					    (mblk_t *)(uintptr_t)(*snxt);
21189 				}
21190 			} else
21191 				(*xmit_tail)->b_rptr = prev_rptr;
21192 
21193 			if (mp == NULL) {
21194 				if (ire != NULL)
21195 					IRE_REFRELE(ire);
21196 				return (-1);
21197 			}
21198 			mp1 = mp->b_cont;
21199 
21200 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21201 				tcp->tcp_last_sent_len = (ushort_t)len;
21202 			while (mp1->b_cont) {
21203 				*xmit_tail = (*xmit_tail)->b_cont;
21204 				(*xmit_tail)->b_prev = local_time;
21205 				(*xmit_tail)->b_next =
21206 				    (mblk_t *)(uintptr_t)(*snxt);
21207 				mp1 = mp1->b_cont;
21208 			}
21209 			*snxt += len;
21210 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21211 			BUMP_LOCAL(tcp->tcp_obsegs);
21212 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21213 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21214 			tcp_send_data(tcp, q, mp);
21215 			continue;
21216 		}
21217 
21218 		*snxt += len;	/* Adjust later if we don't send all of len */
21219 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21220 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21221 
21222 		if (*tail_unsent) {
21223 			/* Are the bytes above us in flight? */
21224 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21225 			if (rptr != (*xmit_tail)->b_rptr) {
21226 				*tail_unsent -= len;
21227 				if (len <= mss) /* LSO is unusable */
21228 					tcp->tcp_last_sent_len = (ushort_t)len;
21229 				len += tcp_hdr_len;
21230 				if (tcp->tcp_ipversion == IPV4_VERSION)
21231 					tcp->tcp_ipha->ipha_length = htons(len);
21232 				else
21233 					tcp->tcp_ip6h->ip6_plen =
21234 					    htons(len -
21235 					    ((char *)&tcp->tcp_ip6h[1] -
21236 					    tcp->tcp_iphc));
21237 				mp = dupb(*xmit_tail);
21238 				if (mp == NULL) {
21239 					if (ire != NULL)
21240 						IRE_REFRELE(ire);
21241 					return (-1);	/* out_of_mem */
21242 				}
21243 				mp->b_rptr = rptr;
21244 				/*
21245 				 * If the old timestamp is no longer in use,
21246 				 * sample a new timestamp now.
21247 				 */
21248 				if ((*xmit_tail)->b_next == NULL) {
21249 					(*xmit_tail)->b_prev = local_time;
21250 					(*xmit_tail)->b_next =
21251 					    (mblk_t *)(uintptr_t)(*snxt-len);
21252 				}
21253 				goto must_alloc;
21254 			}
21255 		} else {
21256 			*xmit_tail = (*xmit_tail)->b_cont;
21257 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21258 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21259 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21260 			    (*xmit_tail)->b_rptr);
21261 		}
21262 
21263 		(*xmit_tail)->b_prev = local_time;
21264 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21265 
21266 		*tail_unsent -= len;
21267 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21268 			tcp->tcp_last_sent_len = (ushort_t)len;
21269 
21270 		len += tcp_hdr_len;
21271 		if (tcp->tcp_ipversion == IPV4_VERSION)
21272 			tcp->tcp_ipha->ipha_length = htons(len);
21273 		else
21274 			tcp->tcp_ip6h->ip6_plen = htons(len -
21275 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21276 
21277 		mp = dupb(*xmit_tail);
21278 		if (mp == NULL) {
21279 			if (ire != NULL)
21280 				IRE_REFRELE(ire);
21281 			return (-1);	/* out_of_mem */
21282 		}
21283 
21284 		len = tcp_hdr_len;
21285 		/*
21286 		 * There are four reasons to allocate a new hdr mblk:
21287 		 *  1) The bytes above us are in use by another packet
21288 		 *  2) We don't have good alignment
21289 		 *  3) The mblk is being shared
21290 		 *  4) We don't have enough room for a header
21291 		 */
21292 		rptr = mp->b_rptr - len;
21293 		if (!OK_32PTR(rptr) ||
21294 		    ((db = mp->b_datap), db->db_ref != 2) ||
21295 		    rptr < db->db_base + ire_fp_mp_len) {
21296 			/* NOTE: we assume allocb returns an OK_32PTR */
21297 
21298 		must_alloc:;
21299 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21300 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21301 			if (mp1 == NULL) {
21302 				freemsg(mp);
21303 				if (ire != NULL)
21304 					IRE_REFRELE(ire);
21305 				return (-1);	/* out_of_mem */
21306 			}
21307 			mp1->b_cont = mp;
21308 			mp = mp1;
21309 			/* Leave room for Link Level header */
21310 			len = tcp_hdr_len;
21311 			rptr =
21312 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21313 			mp->b_wptr = &rptr[len];
21314 		}
21315 
21316 		/*
21317 		 * Fill in the header using the template header, and add
21318 		 * options such as time-stamp, ECN and/or SACK, as needed.
21319 		 */
21320 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21321 
21322 		mp->b_rptr = rptr;
21323 
21324 		if (*tail_unsent) {
21325 			int spill = *tail_unsent;
21326 
21327 			mp1 = mp->b_cont;
21328 			if (mp1 == NULL)
21329 				mp1 = mp;
21330 
21331 			/*
21332 			 * If we're a little short, tack on more mblks until
21333 			 * there is no more spillover.
21334 			 */
21335 			while (spill < 0) {
21336 				mblk_t *nmp;
21337 				int nmpsz;
21338 
21339 				nmp = (*xmit_tail)->b_cont;
21340 				nmpsz = MBLKL(nmp);
21341 
21342 				/*
21343 				 * Excess data in mblk; can we split it?
21344 				 * If MDT is enabled for the connection,
21345 				 * keep on splitting as this is a transient
21346 				 * send path.
21347 				 */
21348 				if (!do_lso_send && !tcp->tcp_mdt &&
21349 				    (spill + nmpsz > 0)) {
21350 					/*
21351 					 * Don't split if stream head was
21352 					 * told to break up larger writes
21353 					 * into smaller ones.
21354 					 */
21355 					if (tcp->tcp_maxpsz > 0)
21356 						break;
21357 
21358 					/*
21359 					 * Next mblk is less than SMSS/2
21360 					 * rounded up to nearest 64-byte;
21361 					 * let it get sent as part of the
21362 					 * next segment.
21363 					 */
21364 					if (tcp->tcp_localnet &&
21365 					    !tcp->tcp_cork &&
21366 					    (nmpsz < roundup((mss >> 1), 64)))
21367 						break;
21368 				}
21369 
21370 				*xmit_tail = nmp;
21371 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21372 				/* Stash for rtt use later */
21373 				(*xmit_tail)->b_prev = local_time;
21374 				(*xmit_tail)->b_next =
21375 				    (mblk_t *)(uintptr_t)(*snxt - len);
21376 				mp1->b_cont = dupb(*xmit_tail);
21377 				mp1 = mp1->b_cont;
21378 
21379 				spill += nmpsz;
21380 				if (mp1 == NULL) {
21381 					*tail_unsent = spill;
21382 					freemsg(mp);
21383 					if (ire != NULL)
21384 						IRE_REFRELE(ire);
21385 					return (-1);	/* out_of_mem */
21386 				}
21387 			}
21388 
21389 			/* Trim back any surplus on the last mblk */
21390 			if (spill >= 0) {
21391 				mp1->b_wptr -= spill;
21392 				*tail_unsent = spill;
21393 			} else {
21394 				/*
21395 				 * We did not send everything we could in
21396 				 * order to remain within the b_cont limit.
21397 				 */
21398 				*usable -= spill;
21399 				*snxt += spill;
21400 				tcp->tcp_last_sent_len += spill;
21401 				UPDATE_MIB(&tcps->tcps_mib,
21402 				    tcpOutDataBytes, spill);
21403 				/*
21404 				 * Adjust the checksum
21405 				 */
21406 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21407 				sum += spill;
21408 				sum = (sum >> 16) + (sum & 0xFFFF);
21409 				U16_TO_ABE16(sum, tcph->th_sum);
21410 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21411 					sum = ntohs(
21412 					    ((ipha_t *)rptr)->ipha_length) +
21413 					    spill;
21414 					((ipha_t *)rptr)->ipha_length =
21415 					    htons(sum);
21416 				} else {
21417 					sum = ntohs(
21418 					    ((ip6_t *)rptr)->ip6_plen) +
21419 					    spill;
21420 					((ip6_t *)rptr)->ip6_plen =
21421 					    htons(sum);
21422 				}
21423 				*tail_unsent = 0;
21424 			}
21425 		}
21426 		if (tcp->tcp_ip_forward_progress) {
21427 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21428 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21429 			tcp->tcp_ip_forward_progress = B_FALSE;
21430 		}
21431 
21432 		if (do_lso_send) {
21433 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21434 			    num_lso_seg);
21435 			tcp->tcp_obsegs += num_lso_seg;
21436 
21437 			TCP_STAT(tcps, tcp_lso_times);
21438 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21439 		} else {
21440 			tcp_send_data(tcp, q, mp);
21441 			BUMP_LOCAL(tcp->tcp_obsegs);
21442 		}
21443 	}
21444 
21445 	if (ire != NULL)
21446 		IRE_REFRELE(ire);
21447 	return (0);
21448 }
21449 
21450 /* Unlink and return any mblk that looks like it contains a MDT info */
21451 static mblk_t *
21452 tcp_mdt_info_mp(mblk_t *mp)
21453 {
21454 	mblk_t	*prev_mp;
21455 
21456 	for (;;) {
21457 		prev_mp = mp;
21458 		/* no more to process? */
21459 		if ((mp = mp->b_cont) == NULL)
21460 			break;
21461 
21462 		switch (DB_TYPE(mp)) {
21463 		case M_CTL:
21464 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21465 				continue;
21466 			ASSERT(prev_mp != NULL);
21467 			prev_mp->b_cont = mp->b_cont;
21468 			mp->b_cont = NULL;
21469 			return (mp);
21470 		default:
21471 			break;
21472 		}
21473 	}
21474 	return (mp);
21475 }
21476 
21477 /* MDT info update routine, called when IP notifies us about MDT */
21478 static void
21479 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21480 {
21481 	boolean_t prev_state;
21482 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21483 
21484 	/*
21485 	 * IP is telling us to abort MDT on this connection?  We know
21486 	 * this because the capability is only turned off when IP
21487 	 * encounters some pathological cases, e.g. link-layer change
21488 	 * where the new driver doesn't support MDT, or in situation
21489 	 * where MDT usage on the link-layer has been switched off.
21490 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21491 	 * if the link-layer doesn't support MDT, and if it does, it
21492 	 * will indicate that the feature is to be turned on.
21493 	 */
21494 	prev_state = tcp->tcp_mdt;
21495 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21496 	if (!tcp->tcp_mdt && !first) {
21497 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21498 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21499 		    (void *)tcp->tcp_connp));
21500 	}
21501 
21502 	/*
21503 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21504 	 * so disable MDT otherwise.  The checks are done here
21505 	 * and in tcp_wput_data().
21506 	 */
21507 	if (tcp->tcp_mdt &&
21508 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21509 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21510 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21511 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21512 		tcp->tcp_mdt = B_FALSE;
21513 
21514 	if (tcp->tcp_mdt) {
21515 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21516 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21517 			    "version (%d), expected version is %d",
21518 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21519 			tcp->tcp_mdt = B_FALSE;
21520 			return;
21521 		}
21522 
21523 		/*
21524 		 * We need the driver to be able to handle at least three
21525 		 * spans per packet in order for tcp MDT to be utilized.
21526 		 * The first is for the header portion, while the rest are
21527 		 * needed to handle a packet that straddles across two
21528 		 * virtually non-contiguous buffers; a typical tcp packet
21529 		 * therefore consists of only two spans.  Note that we take
21530 		 * a zero as "don't care".
21531 		 */
21532 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21533 		    mdt_capab->ill_mdt_span_limit < 3) {
21534 			tcp->tcp_mdt = B_FALSE;
21535 			return;
21536 		}
21537 
21538 		/* a zero means driver wants default value */
21539 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21540 		    tcps->tcps_mdt_max_pbufs);
21541 		if (tcp->tcp_mdt_max_pld == 0)
21542 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21543 
21544 		/* ensure 32-bit alignment */
21545 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21546 		    mdt_capab->ill_mdt_hdr_head), 4);
21547 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21548 		    mdt_capab->ill_mdt_hdr_tail), 4);
21549 
21550 		if (!first && !prev_state) {
21551 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21552 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21553 			    (void *)tcp->tcp_connp));
21554 		}
21555 	}
21556 }
21557 
21558 /* Unlink and return any mblk that looks like it contains a LSO info */
21559 static mblk_t *
21560 tcp_lso_info_mp(mblk_t *mp)
21561 {
21562 	mblk_t	*prev_mp;
21563 
21564 	for (;;) {
21565 		prev_mp = mp;
21566 		/* no more to process? */
21567 		if ((mp = mp->b_cont) == NULL)
21568 			break;
21569 
21570 		switch (DB_TYPE(mp)) {
21571 		case M_CTL:
21572 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21573 				continue;
21574 			ASSERT(prev_mp != NULL);
21575 			prev_mp->b_cont = mp->b_cont;
21576 			mp->b_cont = NULL;
21577 			return (mp);
21578 		default:
21579 			break;
21580 		}
21581 	}
21582 
21583 	return (mp);
21584 }
21585 
21586 /* LSO info update routine, called when IP notifies us about LSO */
21587 static void
21588 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21589 {
21590 	tcp_stack_t *tcps = tcp->tcp_tcps;
21591 
21592 	/*
21593 	 * IP is telling us to abort LSO on this connection?  We know
21594 	 * this because the capability is only turned off when IP
21595 	 * encounters some pathological cases, e.g. link-layer change
21596 	 * where the new NIC/driver doesn't support LSO, or in situation
21597 	 * where LSO usage on the link-layer has been switched off.
21598 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21599 	 * if the link-layer doesn't support LSO, and if it does, it
21600 	 * will indicate that the feature is to be turned on.
21601 	 */
21602 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21603 	TCP_STAT(tcps, tcp_lso_enabled);
21604 
21605 	/*
21606 	 * We currently only support LSO on simple TCP/IPv4,
21607 	 * so disable LSO otherwise.  The checks are done here
21608 	 * and in tcp_wput_data().
21609 	 */
21610 	if (tcp->tcp_lso &&
21611 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21612 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21613 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21614 		tcp->tcp_lso = B_FALSE;
21615 		TCP_STAT(tcps, tcp_lso_disabled);
21616 	} else {
21617 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21618 		    lso_capab->ill_lso_max);
21619 	}
21620 }
21621 
21622 static void
21623 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21624 {
21625 	conn_t *connp = tcp->tcp_connp;
21626 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21627 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21628 
21629 	ASSERT(ire != NULL);
21630 
21631 	/*
21632 	 * We may be in the fastpath here, and although we essentially do
21633 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21634 	 * we try to keep things as brief as possible.  After all, these
21635 	 * are only best-effort checks, and we do more thorough ones prior
21636 	 * to calling tcp_send()/tcp_multisend().
21637 	 */
21638 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
21639 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21640 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21641 	    !(ire->ire_flags & RTF_MULTIRT) &&
21642 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
21643 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21644 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21645 			/* Cache the result */
21646 			connp->conn_lso_ok = B_TRUE;
21647 
21648 			ASSERT(ill->ill_lso_capab != NULL);
21649 			if (!ill->ill_lso_capab->ill_lso_on) {
21650 				ill->ill_lso_capab->ill_lso_on = 1;
21651 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21652 				    "LSO for interface %s\n", (void *)connp,
21653 				    ill->ill_name));
21654 			}
21655 			tcp_lso_update(tcp, ill->ill_lso_capab);
21656 		} else if (ipst->ips_ip_multidata_outbound &&
21657 		    ILL_MDT_CAPABLE(ill)) {
21658 			/* Cache the result */
21659 			connp->conn_mdt_ok = B_TRUE;
21660 
21661 			ASSERT(ill->ill_mdt_capab != NULL);
21662 			if (!ill->ill_mdt_capab->ill_mdt_on) {
21663 				ill->ill_mdt_capab->ill_mdt_on = 1;
21664 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21665 				    "MDT for interface %s\n", (void *)connp,
21666 				    ill->ill_name));
21667 			}
21668 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21669 		}
21670 	}
21671 
21672 	/*
21673 	 * The goal is to reduce the number of generated tcp segments by
21674 	 * setting the maxpsz multiplier to 0; this will have an affect on
21675 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21676 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21677 	 * of outbound segments and incoming ACKs, thus allowing for better
21678 	 * network and system performance.  In contrast the legacy behavior
21679 	 * may result in sending less than SMSS size, because the last mblk
21680 	 * for some packets may have more data than needed to make up SMSS,
21681 	 * and the legacy code refused to "split" it.
21682 	 *
21683 	 * We apply the new behavior on following situations:
21684 	 *
21685 	 *   1) Loopback connections,
21686 	 *   2) Connections in which the remote peer is not on local subnet,
21687 	 *   3) Local subnet connections over the bge interface (see below).
21688 	 *
21689 	 * Ideally, we would like this behavior to apply for interfaces other
21690 	 * than bge.  However, doing so would negatively impact drivers which
21691 	 * perform dynamic mapping and unmapping of DMA resources, which are
21692 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21693 	 * packet will be generated by tcp).  The bge driver does not suffer
21694 	 * from this, as it copies the mblks into pre-mapped buffers, and
21695 	 * therefore does not require more I/O resources than before.
21696 	 *
21697 	 * Otherwise, this behavior is present on all network interfaces when
21698 	 * the destination endpoint is non-local, since reducing the number
21699 	 * of packets in general is good for the network.
21700 	 *
21701 	 * TODO We need to remove this hard-coded conditional for bge once
21702 	 *	a better "self-tuning" mechanism, or a way to comprehend
21703 	 *	the driver transmit strategy is devised.  Until the solution
21704 	 *	is found and well understood, we live with this hack.
21705 	 */
21706 	if (!tcp_static_maxpsz &&
21707 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21708 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21709 		/* override the default value */
21710 		tcp->tcp_maxpsz = 0;
21711 
21712 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21713 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21714 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21715 	}
21716 
21717 	/* set the stream head parameters accordingly */
21718 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21719 }
21720 
21721 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21722 static void
21723 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21724 {
21725 	uchar_t	fval = *mp->b_rptr;
21726 	mblk_t	*tail;
21727 	queue_t	*q = tcp->tcp_wq;
21728 
21729 	/* TODO: How should flush interact with urgent data? */
21730 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21731 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21732 		/*
21733 		 * Flush only data that has not yet been put on the wire.  If
21734 		 * we flush data that we have already transmitted, life, as we
21735 		 * know it, may come to an end.
21736 		 */
21737 		tail = tcp->tcp_xmit_tail;
21738 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21739 		tcp->tcp_xmit_tail_unsent = 0;
21740 		tcp->tcp_unsent = 0;
21741 		if (tail->b_wptr != tail->b_rptr)
21742 			tail = tail->b_cont;
21743 		if (tail) {
21744 			mblk_t **excess = &tcp->tcp_xmit_head;
21745 			for (;;) {
21746 				mblk_t *mp1 = *excess;
21747 				if (mp1 == tail)
21748 					break;
21749 				tcp->tcp_xmit_tail = mp1;
21750 				tcp->tcp_xmit_last = mp1;
21751 				excess = &mp1->b_cont;
21752 			}
21753 			*excess = NULL;
21754 			tcp_close_mpp(&tail);
21755 			if (tcp->tcp_snd_zcopy_aware)
21756 				tcp_zcopy_notify(tcp);
21757 		}
21758 		/*
21759 		 * We have no unsent data, so unsent must be less than
21760 		 * tcp_xmit_lowater, so re-enable flow.
21761 		 */
21762 		mutex_enter(&tcp->tcp_non_sq_lock);
21763 		if (tcp->tcp_flow_stopped) {
21764 			tcp_clrqfull(tcp);
21765 		}
21766 		mutex_exit(&tcp->tcp_non_sq_lock);
21767 	}
21768 	/*
21769 	 * TODO: you can't just flush these, you have to increase rwnd for one
21770 	 * thing.  For another, how should urgent data interact?
21771 	 */
21772 	if (fval & FLUSHR) {
21773 		*mp->b_rptr = fval & ~FLUSHW;
21774 		/* XXX */
21775 		qreply(q, mp);
21776 		return;
21777 	}
21778 	freemsg(mp);
21779 }
21780 
21781 /*
21782  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21783  * messages.
21784  */
21785 static void
21786 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21787 {
21788 	mblk_t	*mp1;
21789 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
21790 	STRUCT_HANDLE(strbuf, sb);
21791 	queue_t *q = tcp->tcp_wq;
21792 	int	error;
21793 	uint_t	addrlen;
21794 
21795 	/* Make sure it is one of ours. */
21796 	switch (iocp->ioc_cmd) {
21797 	case TI_GETMYNAME:
21798 	case TI_GETPEERNAME:
21799 		break;
21800 	default:
21801 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21802 		return;
21803 	}
21804 	switch (mi_copy_state(q, mp, &mp1)) {
21805 	case -1:
21806 		return;
21807 	case MI_COPY_CASE(MI_COPY_IN, 1):
21808 		break;
21809 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21810 		/* Copy out the strbuf. */
21811 		mi_copyout(q, mp);
21812 		return;
21813 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21814 		/* All done. */
21815 		mi_copy_done(q, mp, 0);
21816 		return;
21817 	default:
21818 		mi_copy_done(q, mp, EPROTO);
21819 		return;
21820 	}
21821 	/* Check alignment of the strbuf */
21822 	if (!OK_32PTR(mp1->b_rptr)) {
21823 		mi_copy_done(q, mp, EINVAL);
21824 		return;
21825 	}
21826 
21827 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
21828 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21829 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21830 		mi_copy_done(q, mp, EINVAL);
21831 		return;
21832 	}
21833 
21834 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21835 	if (mp1 == NULL)
21836 		return;
21837 
21838 	switch (iocp->ioc_cmd) {
21839 	case TI_GETMYNAME:
21840 		error = tcp_do_getsockname(tcp, (void *)mp1->b_rptr, &addrlen);
21841 		break;
21842 	case TI_GETPEERNAME:
21843 		error = tcp_do_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
21844 		break;
21845 	}
21846 
21847 	if (error != 0) {
21848 		mi_copy_done(q, mp, error);
21849 	} else {
21850 		mp1->b_wptr += addrlen;
21851 		STRUCT_FSET(sb, len, addrlen);
21852 
21853 		/* Copy out the address */
21854 		mi_copyout(q, mp);
21855 	}
21856 }
21857 
21858 static void
21859 tcp_disable_direct_sockfs(tcp_t *tcp)
21860 {
21861 #ifdef	_ILP32
21862 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
21863 #else
21864 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21865 #endif
21866 	/*
21867 	 * Insert this socket into the acceptor hash.
21868 	 * We might need it for T_CONN_RES message
21869 	 */
21870 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21871 
21872 	if (tcp->tcp_fused) {
21873 		/*
21874 		 * This is a fused loopback tcp; disable
21875 		 * read-side synchronous streams interface
21876 		 * and drain any queued data.  It is okay
21877 		 * to do this for non-synchronous streams
21878 		 * fused tcp as well.
21879 		 */
21880 		tcp_fuse_disable_pair(tcp, B_FALSE);
21881 	}
21882 	tcp->tcp_issocket = B_FALSE;
21883 	tcp->tcp_sodirect = NULL;
21884 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
21885 }
21886 
21887 /*
21888  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21889  * messages.
21890  */
21891 /* ARGSUSED */
21892 static void
21893 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21894 {
21895 	conn_t 	*connp = (conn_t *)arg;
21896 	tcp_t	*tcp = connp->conn_tcp;
21897 	queue_t	*q = tcp->tcp_wq;
21898 	struct iocblk	*iocp;
21899 
21900 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21901 	/*
21902 	 * Try and ASSERT the minimum possible references on the
21903 	 * conn early enough. Since we are executing on write side,
21904 	 * the connection is obviously not detached and that means
21905 	 * there is a ref each for TCP and IP. Since we are behind
21906 	 * the squeue, the minimum references needed are 3. If the
21907 	 * conn is in classifier hash list, there should be an
21908 	 * extra ref for that (we check both the possibilities).
21909 	 */
21910 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21911 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21912 
21913 	iocp = (struct iocblk *)mp->b_rptr;
21914 	switch (iocp->ioc_cmd) {
21915 	case TCP_IOC_DEFAULT_Q:
21916 		/* Wants to be the default wq. */
21917 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
21918 			iocp->ioc_error = EPERM;
21919 			iocp->ioc_count = 0;
21920 			mp->b_datap->db_type = M_IOCACK;
21921 			qreply(q, mp);
21922 			return;
21923 		}
21924 		tcp_def_q_set(tcp, mp);
21925 		return;
21926 	case _SIOCSOCKFALLBACK:
21927 		/*
21928 		 * Either sockmod is about to be popped and the socket
21929 		 * would now be treated as a plain stream, or a module
21930 		 * is about to be pushed so we could no longer use read-
21931 		 * side synchronous streams for fused loopback tcp.
21932 		 * Drain any queued data and disable direct sockfs
21933 		 * interface from now on.
21934 		 */
21935 		if (!tcp->tcp_issocket) {
21936 			DB_TYPE(mp) = M_IOCNAK;
21937 			iocp->ioc_error = EINVAL;
21938 		} else {
21939 			tcp_disable_direct_sockfs(tcp);
21940 			DB_TYPE(mp) = M_IOCACK;
21941 			iocp->ioc_error = 0;
21942 		}
21943 		iocp->ioc_count = 0;
21944 		iocp->ioc_rval = 0;
21945 		qreply(q, mp);
21946 		return;
21947 	}
21948 	CALL_IP_WPUT(connp, q, mp);
21949 }
21950 
21951 /*
21952  * This routine is called by tcp_wput() to handle all TPI requests.
21953  */
21954 /* ARGSUSED */
21955 static void
21956 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21957 {
21958 	conn_t 	*connp = (conn_t *)arg;
21959 	tcp_t	*tcp = connp->conn_tcp;
21960 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21961 	uchar_t *rptr;
21962 	t_scalar_t type;
21963 	cred_t *cr;
21964 
21965 	/*
21966 	 * Try and ASSERT the minimum possible references on the
21967 	 * conn early enough. Since we are executing on write side,
21968 	 * the connection is obviously not detached and that means
21969 	 * there is a ref each for TCP and IP. Since we are behind
21970 	 * the squeue, the minimum references needed are 3. If the
21971 	 * conn is in classifier hash list, there should be an
21972 	 * extra ref for that (we check both the possibilities).
21973 	 */
21974 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21975 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21976 
21977 	rptr = mp->b_rptr;
21978 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21979 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21980 		type = ((union T_primitives *)rptr)->type;
21981 		if (type == T_EXDATA_REQ) {
21982 			tcp_output_urgent(connp, mp->b_cont, arg2);
21983 			freeb(mp);
21984 		} else if (type != T_DATA_REQ) {
21985 			goto non_urgent_data;
21986 		} else {
21987 			/* TODO: options, flags, ... from user */
21988 			/* Set length to zero for reclamation below */
21989 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21990 			freeb(mp);
21991 		}
21992 		return;
21993 	} else {
21994 		if (tcp->tcp_debug) {
21995 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21996 			    "tcp_wput_proto, dropping one...");
21997 		}
21998 		freemsg(mp);
21999 		return;
22000 	}
22001 
22002 non_urgent_data:
22003 
22004 	switch ((int)tprim->type) {
22005 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22006 		/*
22007 		 * save the kssl_ent_t from the next block, and convert this
22008 		 * back to a normal bind_req.
22009 		 */
22010 		if (mp->b_cont != NULL) {
22011 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22012 
22013 			if (tcp->tcp_kssl_ent != NULL) {
22014 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22015 				    KSSL_NO_PROXY);
22016 				tcp->tcp_kssl_ent = NULL;
22017 			}
22018 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22019 			    sizeof (kssl_ent_t));
22020 			kssl_hold_ent(tcp->tcp_kssl_ent);
22021 			freemsg(mp->b_cont);
22022 			mp->b_cont = NULL;
22023 		}
22024 		tprim->type = T_BIND_REQ;
22025 
22026 	/* FALLTHROUGH */
22027 	case O_T_BIND_REQ:	/* bind request */
22028 	case T_BIND_REQ:	/* new semantics bind request */
22029 		tcp_tpi_bind(tcp, mp);
22030 		break;
22031 	case T_UNBIND_REQ:	/* unbind request */
22032 		tcp_tpi_unbind(tcp, mp);
22033 		break;
22034 	case O_T_CONN_RES:	/* old connection response XXX */
22035 	case T_CONN_RES:	/* connection response */
22036 		tcp_tli_accept(tcp, mp);
22037 		break;
22038 	case T_CONN_REQ:	/* connection request */
22039 		tcp_tpi_connect(tcp, mp);
22040 		break;
22041 	case T_DISCON_REQ:	/* disconnect request */
22042 		tcp_disconnect(tcp, mp);
22043 		break;
22044 	case T_CAPABILITY_REQ:
22045 		tcp_capability_req(tcp, mp);	/* capability request */
22046 		break;
22047 	case T_INFO_REQ:	/* information request */
22048 		tcp_info_req(tcp, mp);
22049 		break;
22050 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22051 	case T_OPTMGMT_REQ:
22052 		/*
22053 		 * Note:  no support for snmpcom_req() through new
22054 		 * T_OPTMGMT_REQ. See comments in ip.c
22055 		 */
22056 
22057 		/*
22058 		 * All Solaris components should pass a db_credp
22059 		 * for this TPI message, hence we ASSERT.
22060 		 * But in case there is some other M_PROTO that looks
22061 		 * like a TPI message sent by some other kernel
22062 		 * component, we check and return an error.
22063 		 */
22064 		cr = msg_getcred(mp, NULL);
22065 		ASSERT(cr != NULL);
22066 		if (cr == NULL) {
22067 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
22068 			return;
22069 		}
22070 		/*
22071 		 * If EINPROGRESS is returned, the request has been queued
22072 		 * for subsequent processing by ip_restart_optmgmt(), which
22073 		 * will do the CONN_DEC_REF().
22074 		 */
22075 		CONN_INC_REF(connp);
22076 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
22077 			if (svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22078 			    B_TRUE) != EINPROGRESS) {
22079 				CONN_DEC_REF(connp);
22080 			}
22081 		} else {
22082 			if (tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22083 			    B_TRUE) != EINPROGRESS) {
22084 				CONN_DEC_REF(connp);
22085 			}
22086 		}
22087 		break;
22088 
22089 	case T_UNITDATA_REQ:	/* unitdata request */
22090 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22091 		break;
22092 	case T_ORDREL_REQ:	/* orderly release req */
22093 		freemsg(mp);
22094 
22095 		if (tcp->tcp_fused)
22096 			tcp_unfuse(tcp);
22097 
22098 		if (tcp_xmit_end(tcp) != 0) {
22099 			/*
22100 			 * We were crossing FINs and got a reset from
22101 			 * the other side. Just ignore it.
22102 			 */
22103 			if (tcp->tcp_debug) {
22104 				(void) strlog(TCP_MOD_ID, 0, 1,
22105 				    SL_ERROR|SL_TRACE,
22106 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22107 				    "state %s",
22108 				    tcp_display(tcp, NULL,
22109 				    DISP_ADDR_AND_PORT));
22110 			}
22111 		}
22112 		break;
22113 	case T_ADDR_REQ:
22114 		tcp_addr_req(tcp, mp);
22115 		break;
22116 	default:
22117 		if (tcp->tcp_debug) {
22118 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22119 			    "tcp_wput_proto, bogus TPI msg, type %d",
22120 			    tprim->type);
22121 		}
22122 		/*
22123 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22124 		 * to recover.
22125 		 */
22126 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22127 		break;
22128 	}
22129 }
22130 
22131 /*
22132  * The TCP write service routine should never be called...
22133  */
22134 /* ARGSUSED */
22135 static void
22136 tcp_wsrv(queue_t *q)
22137 {
22138 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22139 
22140 	TCP_STAT(tcps, tcp_wsrv_called);
22141 }
22142 
22143 /* Non overlapping byte exchanger */
22144 static void
22145 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22146 {
22147 	uchar_t	uch;
22148 
22149 	while (len-- > 0) {
22150 		uch = a[len];
22151 		a[len] = b[len];
22152 		b[len] = uch;
22153 	}
22154 }
22155 
22156 /*
22157  * Send out a control packet on the tcp connection specified.  This routine
22158  * is typically called where we need a simple ACK or RST generated.
22159  */
22160 static void
22161 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22162 {
22163 	uchar_t		*rptr;
22164 	tcph_t		*tcph;
22165 	ipha_t		*ipha = NULL;
22166 	ip6_t		*ip6h = NULL;
22167 	uint32_t	sum;
22168 	int		tcp_hdr_len;
22169 	int		tcp_ip_hdr_len;
22170 	mblk_t		*mp;
22171 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22172 
22173 	/*
22174 	 * Save sum for use in source route later.
22175 	 */
22176 	ASSERT(tcp != NULL);
22177 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22178 	tcp_hdr_len = tcp->tcp_hdr_len;
22179 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22180 
22181 	/* If a text string is passed in with the request, pass it to strlog. */
22182 	if (str != NULL && tcp->tcp_debug) {
22183 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22184 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22185 		    str, seq, ack, ctl);
22186 	}
22187 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22188 	    BPRI_MED);
22189 	if (mp == NULL) {
22190 		return;
22191 	}
22192 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22193 	mp->b_rptr = rptr;
22194 	mp->b_wptr = &rptr[tcp_hdr_len];
22195 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22196 
22197 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22198 		ipha = (ipha_t *)rptr;
22199 		ipha->ipha_length = htons(tcp_hdr_len);
22200 	} else {
22201 		ip6h = (ip6_t *)rptr;
22202 		ASSERT(tcp != NULL);
22203 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22204 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22205 	}
22206 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22207 	tcph->th_flags[0] = (uint8_t)ctl;
22208 	if (ctl & TH_RST) {
22209 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22210 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22211 		/*
22212 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22213 		 */
22214 		if (tcp->tcp_snd_ts_ok &&
22215 		    tcp->tcp_state > TCPS_SYN_SENT) {
22216 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22217 			*(mp->b_wptr) = TCPOPT_EOL;
22218 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22219 				ipha->ipha_length = htons(tcp_hdr_len -
22220 				    TCPOPT_REAL_TS_LEN);
22221 			} else {
22222 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22223 				    TCPOPT_REAL_TS_LEN);
22224 			}
22225 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22226 			sum -= TCPOPT_REAL_TS_LEN;
22227 		}
22228 	}
22229 	if (ctl & TH_ACK) {
22230 		if (tcp->tcp_snd_ts_ok) {
22231 			U32_TO_BE32(lbolt,
22232 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22233 			U32_TO_BE32(tcp->tcp_ts_recent,
22234 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22235 		}
22236 
22237 		/* Update the latest receive window size in TCP header. */
22238 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22239 		    tcph->th_win);
22240 		tcp->tcp_rack = ack;
22241 		tcp->tcp_rack_cnt = 0;
22242 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22243 	}
22244 	BUMP_LOCAL(tcp->tcp_obsegs);
22245 	U32_TO_BE32(seq, tcph->th_seq);
22246 	U32_TO_BE32(ack, tcph->th_ack);
22247 	/*
22248 	 * Include the adjustment for a source route if any.
22249 	 */
22250 	sum = (sum >> 16) + (sum & 0xFFFF);
22251 	U16_TO_BE16(sum, tcph->th_sum);
22252 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22253 }
22254 
22255 /*
22256  * If this routine returns B_TRUE, TCP can generate a RST in response
22257  * to a segment.  If it returns B_FALSE, TCP should not respond.
22258  */
22259 static boolean_t
22260 tcp_send_rst_chk(tcp_stack_t *tcps)
22261 {
22262 	clock_t	now;
22263 
22264 	/*
22265 	 * TCP needs to protect itself from generating too many RSTs.
22266 	 * This can be a DoS attack by sending us random segments
22267 	 * soliciting RSTs.
22268 	 *
22269 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22270 	 * in each 1 second interval.  In this way, TCP still generate
22271 	 * RSTs in normal cases but when under attack, the impact is
22272 	 * limited.
22273 	 */
22274 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22275 		now = lbolt;
22276 		/* lbolt can wrap around. */
22277 		if ((tcps->tcps_last_rst_intrvl > now) ||
22278 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22279 		    1*SECONDS)) {
22280 			tcps->tcps_last_rst_intrvl = now;
22281 			tcps->tcps_rst_cnt = 1;
22282 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22283 			return (B_FALSE);
22284 		}
22285 	}
22286 	return (B_TRUE);
22287 }
22288 
22289 /*
22290  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22291  */
22292 static void
22293 tcp_ip_ire_mark_advice(tcp_t *tcp)
22294 {
22295 	mblk_t *mp;
22296 	ipic_t *ipic;
22297 
22298 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22299 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22300 		    &ipic);
22301 	} else {
22302 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22303 		    &ipic);
22304 	}
22305 	if (mp == NULL)
22306 		return;
22307 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22308 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22309 }
22310 
22311 /*
22312  * Return an IP advice ioctl mblk and set ipic to be the pointer
22313  * to the advice structure.
22314  */
22315 static mblk_t *
22316 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22317 {
22318 	struct iocblk *ioc;
22319 	mblk_t *mp, *mp1;
22320 
22321 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22322 	if (mp == NULL)
22323 		return (NULL);
22324 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22325 	*ipic = (ipic_t *)mp->b_rptr;
22326 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22327 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22328 
22329 	bcopy(addr, *ipic + 1, addr_len);
22330 
22331 	(*ipic)->ipic_addr_length = addr_len;
22332 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22333 
22334 	mp1 = mkiocb(IP_IOCTL);
22335 	if (mp1 == NULL) {
22336 		freemsg(mp);
22337 		return (NULL);
22338 	}
22339 	mp1->b_cont = mp;
22340 	ioc = (struct iocblk *)mp1->b_rptr;
22341 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22342 
22343 	return (mp1);
22344 }
22345 
22346 /*
22347  * Generate a reset based on an inbound packet, connp is set by caller
22348  * when RST is in response to an unexpected inbound packet for which
22349  * there is active tcp state in the system.
22350  *
22351  * IPSEC NOTE : Try to send the reply with the same protection as it came
22352  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22353  * the packet will go out at the same level of protection as it came in by
22354  * converting the IPSEC_IN to IPSEC_OUT.
22355  */
22356 static void
22357 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22358     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22359     tcp_stack_t *tcps, conn_t *connp)
22360 {
22361 	ipha_t		*ipha = NULL;
22362 	ip6_t		*ip6h = NULL;
22363 	ushort_t	len;
22364 	tcph_t		*tcph;
22365 	int		i;
22366 	mblk_t		*ipsec_mp;
22367 	boolean_t	mctl_present;
22368 	ipic_t		*ipic;
22369 	ipaddr_t	v4addr;
22370 	in6_addr_t	v6addr;
22371 	int		addr_len;
22372 	void		*addr;
22373 	queue_t		*q = tcps->tcps_g_q;
22374 	tcp_t		*tcp;
22375 	cred_t		*cr;
22376 	mblk_t		*nmp;
22377 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22378 
22379 	if (tcps->tcps_g_q == NULL) {
22380 		/*
22381 		 * For non-zero stackids the default queue isn't created
22382 		 * until the first open, thus there can be a need to send
22383 		 * a reset before then. But we can't do that, hence we just
22384 		 * drop the packet. Later during boot, when the default queue
22385 		 * has been setup, a retransmitted packet from the peer
22386 		 * will result in a reset.
22387 		 */
22388 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22389 		    GLOBAL_NETSTACKID);
22390 		freemsg(mp);
22391 		return;
22392 	}
22393 
22394 	if (connp != NULL)
22395 		tcp = connp->conn_tcp;
22396 	else
22397 		tcp = Q_TO_TCP(q);
22398 
22399 	if (!tcp_send_rst_chk(tcps)) {
22400 		tcps->tcps_rst_unsent++;
22401 		freemsg(mp);
22402 		return;
22403 	}
22404 
22405 	if (mp->b_datap->db_type == M_CTL) {
22406 		ipsec_mp = mp;
22407 		mp = mp->b_cont;
22408 		mctl_present = B_TRUE;
22409 	} else {
22410 		ipsec_mp = mp;
22411 		mctl_present = B_FALSE;
22412 	}
22413 
22414 	if (str && q && tcps->tcps_dbg) {
22415 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22416 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22417 		    "flags 0x%x",
22418 		    str, seq, ack, ctl);
22419 	}
22420 	if (mp->b_datap->db_ref != 1) {
22421 		mblk_t *mp1 = copyb(mp);
22422 		freemsg(mp);
22423 		mp = mp1;
22424 		if (!mp) {
22425 			if (mctl_present)
22426 				freeb(ipsec_mp);
22427 			return;
22428 		} else {
22429 			if (mctl_present) {
22430 				ipsec_mp->b_cont = mp;
22431 			} else {
22432 				ipsec_mp = mp;
22433 			}
22434 		}
22435 	} else if (mp->b_cont) {
22436 		freemsg(mp->b_cont);
22437 		mp->b_cont = NULL;
22438 	}
22439 	/*
22440 	 * We skip reversing source route here.
22441 	 * (for now we replace all IP options with EOL)
22442 	 */
22443 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22444 		ipha = (ipha_t *)mp->b_rptr;
22445 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22446 			mp->b_rptr[i] = IPOPT_EOL;
22447 		/*
22448 		 * Make sure that src address isn't flagrantly invalid.
22449 		 * Not all broadcast address checking for the src address
22450 		 * is possible, since we don't know the netmask of the src
22451 		 * addr.  No check for destination address is done, since
22452 		 * IP will not pass up a packet with a broadcast dest
22453 		 * address to TCP.  Similar checks are done below for IPv6.
22454 		 */
22455 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22456 		    CLASSD(ipha->ipha_src)) {
22457 			freemsg(ipsec_mp);
22458 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22459 			return;
22460 		}
22461 	} else {
22462 		ip6h = (ip6_t *)mp->b_rptr;
22463 
22464 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22465 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22466 			freemsg(ipsec_mp);
22467 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22468 			return;
22469 		}
22470 
22471 		/* Remove any extension headers assuming partial overlay */
22472 		if (ip_hdr_len > IPV6_HDR_LEN) {
22473 			uint8_t *to;
22474 
22475 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22476 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22477 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22478 			ip_hdr_len = IPV6_HDR_LEN;
22479 			ip6h = (ip6_t *)mp->b_rptr;
22480 			ip6h->ip6_nxt = IPPROTO_TCP;
22481 		}
22482 	}
22483 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22484 	if (tcph->th_flags[0] & TH_RST) {
22485 		freemsg(ipsec_mp);
22486 		return;
22487 	}
22488 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22489 	len = ip_hdr_len + sizeof (tcph_t);
22490 	mp->b_wptr = &mp->b_rptr[len];
22491 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22492 		ipha->ipha_length = htons(len);
22493 		/* Swap addresses */
22494 		v4addr = ipha->ipha_src;
22495 		ipha->ipha_src = ipha->ipha_dst;
22496 		ipha->ipha_dst = v4addr;
22497 		ipha->ipha_ident = 0;
22498 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22499 		addr_len = IP_ADDR_LEN;
22500 		addr = &v4addr;
22501 	} else {
22502 		/* No ip6i_t in this case */
22503 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22504 		/* Swap addresses */
22505 		v6addr = ip6h->ip6_src;
22506 		ip6h->ip6_src = ip6h->ip6_dst;
22507 		ip6h->ip6_dst = v6addr;
22508 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22509 		addr_len = IPV6_ADDR_LEN;
22510 		addr = &v6addr;
22511 	}
22512 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22513 	U32_TO_BE32(ack, tcph->th_ack);
22514 	U32_TO_BE32(seq, tcph->th_seq);
22515 	U16_TO_BE16(0, tcph->th_win);
22516 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22517 	tcph->th_flags[0] = (uint8_t)ctl;
22518 	if (ctl & TH_RST) {
22519 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22520 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22521 	}
22522 
22523 	/* IP trusts us to set up labels when required. */
22524 	if (is_system_labeled() && (cr = msg_getcred(mp, NULL)) != NULL &&
22525 	    crgetlabel(cr) != NULL) {
22526 		int err;
22527 
22528 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22529 			err = tsol_check_label(cr, &mp,
22530 			    tcp->tcp_connp->conn_mac_exempt,
22531 			    tcps->tcps_netstack->netstack_ip);
22532 		else
22533 			err = tsol_check_label_v6(cr, &mp,
22534 			    tcp->tcp_connp->conn_mac_exempt,
22535 			    tcps->tcps_netstack->netstack_ip);
22536 		if (mctl_present)
22537 			ipsec_mp->b_cont = mp;
22538 		else
22539 			ipsec_mp = mp;
22540 		if (err != 0) {
22541 			freemsg(ipsec_mp);
22542 			return;
22543 		}
22544 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22545 			ipha = (ipha_t *)mp->b_rptr;
22546 		} else {
22547 			ip6h = (ip6_t *)mp->b_rptr;
22548 		}
22549 	}
22550 
22551 	if (mctl_present) {
22552 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22553 
22554 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22555 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22556 			return;
22557 		}
22558 	}
22559 	if (zoneid == ALL_ZONES)
22560 		zoneid = GLOBAL_ZONEID;
22561 
22562 	/* Add the zoneid so ip_output routes it properly */
22563 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22564 		freemsg(ipsec_mp);
22565 		return;
22566 	}
22567 	ipsec_mp = nmp;
22568 
22569 	/*
22570 	 * NOTE:  one might consider tracing a TCP packet here, but
22571 	 * this function has no active TCP state and no tcp structure
22572 	 * that has a trace buffer.  If we traced here, we would have
22573 	 * to keep a local trace buffer in tcp_record_trace().
22574 	 *
22575 	 * TSol note: The mblk that contains the incoming packet was
22576 	 * reused by tcp_xmit_listener_reset, so it already contains
22577 	 * the right credentials and we don't need to call mblk_setcred.
22578 	 * Also the conn's cred is not right since it is associated
22579 	 * with tcps_g_q.
22580 	 */
22581 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22582 
22583 	/*
22584 	 * Tell IP to mark the IRE used for this destination temporary.
22585 	 * This way, we can limit our exposure to DoS attack because IP
22586 	 * creates an IRE for each destination.  If there are too many,
22587 	 * the time to do any routing lookup will be extremely long.  And
22588 	 * the lookup can be in interrupt context.
22589 	 *
22590 	 * Note that in normal circumstances, this marking should not
22591 	 * affect anything.  It would be nice if only 1 message is
22592 	 * needed to inform IP that the IRE created for this RST should
22593 	 * not be added to the cache table.  But there is currently
22594 	 * not such communication mechanism between TCP and IP.  So
22595 	 * the best we can do now is to send the advice ioctl to IP
22596 	 * to mark the IRE temporary.
22597 	 */
22598 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22599 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22600 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22601 	}
22602 }
22603 
22604 /*
22605  * Initiate closedown sequence on an active connection.  (May be called as
22606  * writer.)  Return value zero for OK return, non-zero for error return.
22607  */
22608 static int
22609 tcp_xmit_end(tcp_t *tcp)
22610 {
22611 	ipic_t	*ipic;
22612 	mblk_t	*mp;
22613 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22614 
22615 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22616 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22617 		/*
22618 		 * Invalid state, only states TCPS_SYN_RCVD,
22619 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22620 		 */
22621 		return (-1);
22622 	}
22623 
22624 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22625 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22626 	/*
22627 	 * If there is nothing more unsent, send the FIN now.
22628 	 * Otherwise, it will go out with the last segment.
22629 	 */
22630 	if (tcp->tcp_unsent == 0) {
22631 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22632 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22633 
22634 		if (mp) {
22635 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22636 		} else {
22637 			/*
22638 			 * Couldn't allocate msg.  Pretend we got it out.
22639 			 * Wait for rexmit timeout.
22640 			 */
22641 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22642 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22643 		}
22644 
22645 		/*
22646 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22647 		 * changed.
22648 		 */
22649 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22650 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22651 		}
22652 	} else {
22653 		/*
22654 		 * If tcp->tcp_cork is set, then the data will not get sent,
22655 		 * so we have to check that and unset it first.
22656 		 */
22657 		if (tcp->tcp_cork)
22658 			tcp->tcp_cork = B_FALSE;
22659 		tcp_wput_data(tcp, NULL, B_FALSE);
22660 	}
22661 
22662 	/*
22663 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22664 	 * is 0, don't update the cache.
22665 	 */
22666 	if (tcps->tcps_rtt_updates == 0 ||
22667 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
22668 		return (0);
22669 
22670 	/*
22671 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22672 	 * different from the destination.
22673 	 */
22674 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22675 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22676 			return (0);
22677 		}
22678 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22679 		    &ipic);
22680 	} else {
22681 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22682 		    &tcp->tcp_ip6h->ip6_dst))) {
22683 			return (0);
22684 		}
22685 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22686 		    &ipic);
22687 	}
22688 
22689 	/* Record route attributes in the IRE for use by future connections. */
22690 	if (mp == NULL)
22691 		return (0);
22692 
22693 	/*
22694 	 * We do not have a good algorithm to update ssthresh at this time.
22695 	 * So don't do any update.
22696 	 */
22697 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22698 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22699 
22700 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22701 
22702 	return (0);
22703 }
22704 
22705 /* ARGSUSED */
22706 void
22707 tcp_xmit_reset(void *arg, mblk_t *mp, void *arg2)
22708 {
22709 	conn_t *connp = (conn_t *)arg;
22710 	mblk_t *mp1;
22711 	tcp_t *tcp = connp->conn_tcp;
22712 	tcp_xmit_reset_event_t *eventp;
22713 
22714 	ASSERT(mp->b_datap->db_type == M_PROTO &&
22715 	    MBLKL(mp) == sizeof (tcp_xmit_reset_event_t));
22716 
22717 	if (tcp->tcp_state != TCPS_LISTEN) {
22718 		freemsg(mp);
22719 		return;
22720 	}
22721 
22722 	mp1 = mp->b_cont;
22723 	mp->b_cont = NULL;
22724 	eventp = (tcp_xmit_reset_event_t *)mp->b_rptr;
22725 	ASSERT(eventp->tcp_xre_tcps->tcps_netstack ==
22726 	    connp->conn_netstack);
22727 
22728 	tcp_xmit_listeners_reset(mp1, eventp->tcp_xre_iphdrlen,
22729 	    eventp->tcp_xre_zoneid, eventp->tcp_xre_tcps, connp);
22730 	freemsg(mp);
22731 }
22732 
22733 /*
22734  * Generate a "no listener here" RST in response to an "unknown" segment.
22735  * connp is set by caller when RST is in response to an unexpected
22736  * inbound packet for which there is active tcp state in the system.
22737  * Note that we are reusing the incoming mp to construct the outgoing RST.
22738  */
22739 void
22740 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
22741     tcp_stack_t *tcps, conn_t *connp)
22742 {
22743 	uchar_t		*rptr;
22744 	uint32_t	seg_len;
22745 	tcph_t		*tcph;
22746 	uint32_t	seg_seq;
22747 	uint32_t	seg_ack;
22748 	uint_t		flags;
22749 	mblk_t		*ipsec_mp;
22750 	ipha_t 		*ipha;
22751 	ip6_t 		*ip6h;
22752 	boolean_t	mctl_present = B_FALSE;
22753 	boolean_t	check = B_TRUE;
22754 	boolean_t	policy_present;
22755 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
22756 
22757 	TCP_STAT(tcps, tcp_no_listener);
22758 
22759 	ipsec_mp = mp;
22760 
22761 	if (mp->b_datap->db_type == M_CTL) {
22762 		ipsec_in_t *ii;
22763 
22764 		mctl_present = B_TRUE;
22765 		mp = mp->b_cont;
22766 
22767 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22768 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22769 		if (ii->ipsec_in_dont_check) {
22770 			check = B_FALSE;
22771 			if (!ii->ipsec_in_secure) {
22772 				freeb(ipsec_mp);
22773 				mctl_present = B_FALSE;
22774 				ipsec_mp = mp;
22775 			}
22776 		}
22777 	}
22778 
22779 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22780 		policy_present = ipss->ipsec_inbound_v4_policy_present;
22781 		ipha = (ipha_t *)mp->b_rptr;
22782 		ip6h = NULL;
22783 	} else {
22784 		policy_present = ipss->ipsec_inbound_v6_policy_present;
22785 		ipha = NULL;
22786 		ip6h = (ip6_t *)mp->b_rptr;
22787 	}
22788 
22789 	if (check && policy_present) {
22790 		/*
22791 		 * The conn_t parameter is NULL because we already know
22792 		 * nobody's home.
22793 		 */
22794 		ipsec_mp = ipsec_check_global_policy(
22795 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
22796 		    tcps->tcps_netstack);
22797 		if (ipsec_mp == NULL)
22798 			return;
22799 	}
22800 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22801 		DTRACE_PROBE2(
22802 		    tx__ip__log__error__nolistener__tcp,
22803 		    char *, "Could not reply with RST to mp(1)",
22804 		    mblk_t *, mp);
22805 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22806 		freemsg(ipsec_mp);
22807 		return;
22808 	}
22809 
22810 	rptr = mp->b_rptr;
22811 
22812 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22813 	seg_seq = BE32_TO_U32(tcph->th_seq);
22814 	seg_ack = BE32_TO_U32(tcph->th_ack);
22815 	flags = tcph->th_flags[0];
22816 
22817 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22818 	if (flags & TH_RST) {
22819 		freemsg(ipsec_mp);
22820 	} else if (flags & TH_ACK) {
22821 		tcp_xmit_early_reset("no tcp, reset",
22822 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
22823 		    connp);
22824 	} else {
22825 		if (flags & TH_SYN) {
22826 			seg_len++;
22827 		} else {
22828 			/*
22829 			 * Here we violate the RFC.  Note that a normal
22830 			 * TCP will never send a segment without the ACK
22831 			 * flag, except for RST or SYN segment.  This
22832 			 * segment is neither.  Just drop it on the
22833 			 * floor.
22834 			 */
22835 			freemsg(ipsec_mp);
22836 			tcps->tcps_rst_unsent++;
22837 			return;
22838 		}
22839 
22840 		tcp_xmit_early_reset("no tcp, reset/ack",
22841 		    ipsec_mp, 0, seg_seq + seg_len,
22842 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
22843 	}
22844 }
22845 
22846 /*
22847  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22848  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22849  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22850  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22851  * otherwise it will dup partial mblks.)
22852  * Otherwise, an appropriate ACK packet will be generated.  This
22853  * routine is not usually called to send new data for the first time.  It
22854  * is mostly called out of the timer for retransmits, and to generate ACKs.
22855  *
22856  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22857  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22858  * of the original mblk chain will be returned in *offset and *end_mp.
22859  */
22860 mblk_t *
22861 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22862     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22863     boolean_t rexmit)
22864 {
22865 	int	data_length;
22866 	int32_t	off = 0;
22867 	uint_t	flags;
22868 	mblk_t	*mp1;
22869 	mblk_t	*mp2;
22870 	uchar_t	*rptr;
22871 	tcph_t	*tcph;
22872 	int32_t	num_sack_blk = 0;
22873 	int32_t	sack_opt_len = 0;
22874 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22875 
22876 	/* Allocate for our maximum TCP header + link-level */
22877 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
22878 	    tcps->tcps_wroff_xtra, BPRI_MED);
22879 	if (!mp1)
22880 		return (NULL);
22881 	data_length = 0;
22882 
22883 	/*
22884 	 * Note that tcp_mss has been adjusted to take into account the
22885 	 * timestamp option if applicable.  Because SACK options do not
22886 	 * appear in every TCP segments and they are of variable lengths,
22887 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22888 	 * the actual segment length when we need to send a segment which
22889 	 * includes SACK options.
22890 	 */
22891 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22892 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22893 		    tcp->tcp_num_sack_blk);
22894 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22895 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22896 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22897 			max_to_send -= sack_opt_len;
22898 	}
22899 
22900 	if (offset != NULL) {
22901 		off = *offset;
22902 		/* We use offset as an indicator that end_mp is not NULL. */
22903 		*end_mp = NULL;
22904 	}
22905 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22906 		/* This could be faster with cooperation from downstream */
22907 		if (mp2 != mp1 && !sendall &&
22908 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22909 		    max_to_send)
22910 			/*
22911 			 * Don't send the next mblk since the whole mblk
22912 			 * does not fit.
22913 			 */
22914 			break;
22915 		mp2->b_cont = dupb(mp);
22916 		mp2 = mp2->b_cont;
22917 		if (!mp2) {
22918 			freemsg(mp1);
22919 			return (NULL);
22920 		}
22921 		mp2->b_rptr += off;
22922 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22923 		    (uintptr_t)INT_MAX);
22924 
22925 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22926 		if (data_length > max_to_send) {
22927 			mp2->b_wptr -= data_length - max_to_send;
22928 			data_length = max_to_send;
22929 			off = mp2->b_wptr - mp->b_rptr;
22930 			break;
22931 		} else {
22932 			off = 0;
22933 		}
22934 	}
22935 	if (offset != NULL) {
22936 		*offset = off;
22937 		*end_mp = mp;
22938 	}
22939 	if (seg_len != NULL) {
22940 		*seg_len = data_length;
22941 	}
22942 
22943 	/* Update the latest receive window size in TCP header. */
22944 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22945 	    tcp->tcp_tcph->th_win);
22946 
22947 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
22948 	mp1->b_rptr = rptr;
22949 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22950 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22951 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22952 	U32_TO_ABE32(seq, tcph->th_seq);
22953 
22954 	/*
22955 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22956 	 * that this function was called from tcp_wput_data. Thus, when called
22957 	 * to retransmit data the setting of the PUSH bit may appear some
22958 	 * what random in that it might get set when it should not. This
22959 	 * should not pose any performance issues.
22960 	 */
22961 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22962 	    tcp->tcp_unsent == data_length)) {
22963 		flags = TH_ACK | TH_PUSH;
22964 	} else {
22965 		flags = TH_ACK;
22966 	}
22967 
22968 	if (tcp->tcp_ecn_ok) {
22969 		if (tcp->tcp_ecn_echo_on)
22970 			flags |= TH_ECE;
22971 
22972 		/*
22973 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22974 		 * There is no TCP flow control for non-data segments, and
22975 		 * only data segment is transmitted reliably.
22976 		 */
22977 		if (data_length > 0 && !rexmit) {
22978 			SET_ECT(tcp, rptr);
22979 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
22980 				flags |= TH_CWR;
22981 				tcp->tcp_ecn_cwr_sent = B_TRUE;
22982 			}
22983 		}
22984 	}
22985 
22986 	if (tcp->tcp_valid_bits) {
22987 		uint32_t u1;
22988 
22989 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
22990 		    seq == tcp->tcp_iss) {
22991 			uchar_t	*wptr;
22992 
22993 			/*
22994 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
22995 			 * TCP can only be in SYN-SENT, SYN-RCVD or
22996 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
22997 			 * our SYN is not ack'ed but the app closes this
22998 			 * TCP connection.
22999 			 */
23000 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23001 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23002 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23003 
23004 			/*
23005 			 * Tack on the MSS option.  It is always needed
23006 			 * for both active and passive open.
23007 			 *
23008 			 * MSS option value should be interface MTU - MIN
23009 			 * TCP/IP header according to RFC 793 as it means
23010 			 * the maximum segment size TCP can receive.  But
23011 			 * to get around some broken middle boxes/end hosts
23012 			 * out there, we allow the option value to be the
23013 			 * same as the MSS option size on the peer side.
23014 			 * In this way, the other side will not send
23015 			 * anything larger than they can receive.
23016 			 *
23017 			 * Note that for SYN_SENT state, the ndd param
23018 			 * tcp_use_smss_as_mss_opt has no effect as we
23019 			 * don't know the peer's MSS option value. So
23020 			 * the only case we need to take care of is in
23021 			 * SYN_RCVD state, which is done later.
23022 			 */
23023 			wptr = mp1->b_wptr;
23024 			wptr[0] = TCPOPT_MAXSEG;
23025 			wptr[1] = TCPOPT_MAXSEG_LEN;
23026 			wptr += 2;
23027 			u1 = tcp->tcp_if_mtu -
23028 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23029 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23030 			    TCP_MIN_HEADER_LENGTH;
23031 			U16_TO_BE16(u1, wptr);
23032 			mp1->b_wptr = wptr + 2;
23033 			/* Update the offset to cover the additional word */
23034 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23035 
23036 			/*
23037 			 * Note that the following way of filling in
23038 			 * TCP options are not optimal.  Some NOPs can
23039 			 * be saved.  But there is no need at this time
23040 			 * to optimize it.  When it is needed, we will
23041 			 * do it.
23042 			 */
23043 			switch (tcp->tcp_state) {
23044 			case TCPS_SYN_SENT:
23045 				flags = TH_SYN;
23046 
23047 				if (tcp->tcp_snd_ts_ok) {
23048 					uint32_t llbolt = (uint32_t)lbolt;
23049 
23050 					wptr = mp1->b_wptr;
23051 					wptr[0] = TCPOPT_NOP;
23052 					wptr[1] = TCPOPT_NOP;
23053 					wptr[2] = TCPOPT_TSTAMP;
23054 					wptr[3] = TCPOPT_TSTAMP_LEN;
23055 					wptr += 4;
23056 					U32_TO_BE32(llbolt, wptr);
23057 					wptr += 4;
23058 					ASSERT(tcp->tcp_ts_recent == 0);
23059 					U32_TO_BE32(0L, wptr);
23060 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23061 					tcph->th_offset_and_rsrvd[0] +=
23062 					    (3 << 4);
23063 				}
23064 
23065 				/*
23066 				 * Set up all the bits to tell other side
23067 				 * we are ECN capable.
23068 				 */
23069 				if (tcp->tcp_ecn_ok) {
23070 					flags |= (TH_ECE | TH_CWR);
23071 				}
23072 				break;
23073 			case TCPS_SYN_RCVD:
23074 				flags |= TH_SYN;
23075 
23076 				/*
23077 				 * Reset the MSS option value to be SMSS
23078 				 * We should probably add back the bytes
23079 				 * for timestamp option and IPsec.  We
23080 				 * don't do that as this is a workaround
23081 				 * for broken middle boxes/end hosts, it
23082 				 * is better for us to be more cautious.
23083 				 * They may not take these things into
23084 				 * account in their SMSS calculation.  Thus
23085 				 * the peer's calculated SMSS may be smaller
23086 				 * than what it can be.  This should be OK.
23087 				 */
23088 				if (tcps->tcps_use_smss_as_mss_opt) {
23089 					u1 = tcp->tcp_mss;
23090 					U16_TO_BE16(u1, wptr);
23091 				}
23092 
23093 				/*
23094 				 * If the other side is ECN capable, reply
23095 				 * that we are also ECN capable.
23096 				 */
23097 				if (tcp->tcp_ecn_ok)
23098 					flags |= TH_ECE;
23099 				break;
23100 			default:
23101 				/*
23102 				 * The above ASSERT() makes sure that this
23103 				 * must be FIN-WAIT-1 state.  Our SYN has
23104 				 * not been ack'ed so retransmit it.
23105 				 */
23106 				flags |= TH_SYN;
23107 				break;
23108 			}
23109 
23110 			if (tcp->tcp_snd_ws_ok) {
23111 				wptr = mp1->b_wptr;
23112 				wptr[0] =  TCPOPT_NOP;
23113 				wptr[1] =  TCPOPT_WSCALE;
23114 				wptr[2] =  TCPOPT_WS_LEN;
23115 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23116 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23117 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23118 			}
23119 
23120 			if (tcp->tcp_snd_sack_ok) {
23121 				wptr = mp1->b_wptr;
23122 				wptr[0] = TCPOPT_NOP;
23123 				wptr[1] = TCPOPT_NOP;
23124 				wptr[2] = TCPOPT_SACK_PERMITTED;
23125 				wptr[3] = TCPOPT_SACK_OK_LEN;
23126 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23127 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23128 			}
23129 
23130 			/* allocb() of adequate mblk assures space */
23131 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23132 			    (uintptr_t)INT_MAX);
23133 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23134 			/*
23135 			 * Get IP set to checksum on our behalf
23136 			 * Include the adjustment for a source route if any.
23137 			 */
23138 			u1 += tcp->tcp_sum;
23139 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23140 			U16_TO_BE16(u1, tcph->th_sum);
23141 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23142 		}
23143 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23144 		    (seq + data_length) == tcp->tcp_fss) {
23145 			if (!tcp->tcp_fin_acked) {
23146 				flags |= TH_FIN;
23147 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23148 			}
23149 			if (!tcp->tcp_fin_sent) {
23150 				tcp->tcp_fin_sent = B_TRUE;
23151 				switch (tcp->tcp_state) {
23152 				case TCPS_SYN_RCVD:
23153 				case TCPS_ESTABLISHED:
23154 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23155 					break;
23156 				case TCPS_CLOSE_WAIT:
23157 					tcp->tcp_state = TCPS_LAST_ACK;
23158 					break;
23159 				}
23160 				if (tcp->tcp_suna == tcp->tcp_snxt)
23161 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23162 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23163 			}
23164 		}
23165 		/*
23166 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23167 		 * is smaller than seq, u1 will become a very huge value.
23168 		 * So the comparison will fail.  Also note that tcp_urp
23169 		 * should be positive, see RFC 793 page 17.
23170 		 */
23171 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23172 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23173 		    u1 < (uint32_t)(64 * 1024)) {
23174 			flags |= TH_URG;
23175 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23176 			U32_TO_ABE16(u1, tcph->th_urp);
23177 		}
23178 	}
23179 	tcph->th_flags[0] = (uchar_t)flags;
23180 	tcp->tcp_rack = tcp->tcp_rnxt;
23181 	tcp->tcp_rack_cnt = 0;
23182 
23183 	if (tcp->tcp_snd_ts_ok) {
23184 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23185 			uint32_t llbolt = (uint32_t)lbolt;
23186 
23187 			U32_TO_BE32(llbolt,
23188 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23189 			U32_TO_BE32(tcp->tcp_ts_recent,
23190 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23191 		}
23192 	}
23193 
23194 	if (num_sack_blk > 0) {
23195 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23196 		sack_blk_t *tmp;
23197 		int32_t	i;
23198 
23199 		wptr[0] = TCPOPT_NOP;
23200 		wptr[1] = TCPOPT_NOP;
23201 		wptr[2] = TCPOPT_SACK;
23202 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23203 		    sizeof (sack_blk_t);
23204 		wptr += TCPOPT_REAL_SACK_LEN;
23205 
23206 		tmp = tcp->tcp_sack_list;
23207 		for (i = 0; i < num_sack_blk; i++) {
23208 			U32_TO_BE32(tmp[i].begin, wptr);
23209 			wptr += sizeof (tcp_seq);
23210 			U32_TO_BE32(tmp[i].end, wptr);
23211 			wptr += sizeof (tcp_seq);
23212 		}
23213 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23214 	}
23215 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23216 	data_length += (int)(mp1->b_wptr - rptr);
23217 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23218 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23219 	} else {
23220 		ip6_t *ip6 = (ip6_t *)(rptr +
23221 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23222 		    sizeof (ip6i_t) : 0));
23223 
23224 		ip6->ip6_plen = htons(data_length -
23225 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23226 	}
23227 
23228 	/*
23229 	 * Prime pump for IP
23230 	 * Include the adjustment for a source route if any.
23231 	 */
23232 	data_length -= tcp->tcp_ip_hdr_len;
23233 	data_length += tcp->tcp_sum;
23234 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23235 	U16_TO_ABE16(data_length, tcph->th_sum);
23236 	if (tcp->tcp_ip_forward_progress) {
23237 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23238 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23239 		tcp->tcp_ip_forward_progress = B_FALSE;
23240 	}
23241 	return (mp1);
23242 }
23243 
23244 /* This function handles the push timeout. */
23245 void
23246 tcp_push_timer(void *arg)
23247 {
23248 	conn_t	*connp = (conn_t *)arg;
23249 	tcp_t *tcp = connp->conn_tcp;
23250 	uint_t		flags;
23251 	sodirect_t	*sodp;
23252 
23253 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
23254 
23255 	ASSERT(tcp->tcp_listener == NULL);
23256 
23257 	ASSERT(!IPCL_IS_NONSTR(connp));
23258 
23259 	/*
23260 	 * We need to plug synchronous streams during our drain to prevent
23261 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23262 	 */
23263 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23264 	tcp->tcp_push_tid = 0;
23265 
23266 	SOD_PTR_ENTER(tcp, sodp);
23267 	if (sodp != NULL) {
23268 		flags = tcp_rcv_sod_wakeup(tcp, sodp);
23269 		/* sod_wakeup() does the mutex_exit() */
23270 	} else if (tcp->tcp_rcv_list != NULL) {
23271 		flags = tcp_rcv_drain(tcp);
23272 	}
23273 	if (flags == TH_ACK_NEEDED)
23274 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23275 
23276 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23277 }
23278 
23279 /*
23280  * This function handles delayed ACK timeout.
23281  */
23282 static void
23283 tcp_ack_timer(void *arg)
23284 {
23285 	conn_t	*connp = (conn_t *)arg;
23286 	tcp_t *tcp = connp->conn_tcp;
23287 	mblk_t *mp;
23288 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23289 
23290 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23291 
23292 	tcp->tcp_ack_tid = 0;
23293 
23294 	if (tcp->tcp_fused)
23295 		return;
23296 
23297 	/*
23298 	 * Do not send ACK if there is no outstanding unack'ed data.
23299 	 */
23300 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23301 		return;
23302 	}
23303 
23304 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23305 		/*
23306 		 * Make sure we don't allow deferred ACKs to result in
23307 		 * timer-based ACKing.  If we have held off an ACK
23308 		 * when there was more than an mss here, and the timer
23309 		 * goes off, we have to worry about the possibility
23310 		 * that the sender isn't doing slow-start, or is out
23311 		 * of step with us for some other reason.  We fall
23312 		 * permanently back in the direction of
23313 		 * ACK-every-other-packet as suggested in RFC 1122.
23314 		 */
23315 		if (tcp->tcp_rack_abs_max > 2)
23316 			tcp->tcp_rack_abs_max--;
23317 		tcp->tcp_rack_cur_max = 2;
23318 	}
23319 	mp = tcp_ack_mp(tcp);
23320 
23321 	if (mp != NULL) {
23322 		BUMP_LOCAL(tcp->tcp_obsegs);
23323 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23324 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23325 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23326 	}
23327 }
23328 
23329 
23330 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23331 static mblk_t *
23332 tcp_ack_mp(tcp_t *tcp)
23333 {
23334 	uint32_t	seq_no;
23335 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23336 
23337 	/*
23338 	 * There are a few cases to be considered while setting the sequence no.
23339 	 * Essentially, we can come here while processing an unacceptable pkt
23340 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23341 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23342 	 * If we are here for a zero window probe, stick with suna. In all
23343 	 * other cases, we check if suna + swnd encompasses snxt and set
23344 	 * the sequence number to snxt, if so. If snxt falls outside the
23345 	 * window (the receiver probably shrunk its window), we will go with
23346 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23347 	 * receiver.
23348 	 */
23349 	if (tcp->tcp_zero_win_probe) {
23350 		seq_no = tcp->tcp_suna;
23351 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23352 		ASSERT(tcp->tcp_swnd == 0);
23353 		seq_no = tcp->tcp_snxt;
23354 	} else {
23355 		seq_no = SEQ_GT(tcp->tcp_snxt,
23356 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23357 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23358 	}
23359 
23360 	if (tcp->tcp_valid_bits) {
23361 		/*
23362 		 * For the complex case where we have to send some
23363 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23364 		 */
23365 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23366 		    NULL, B_FALSE));
23367 	} else {
23368 		/* Generate a simple ACK */
23369 		int	data_length;
23370 		uchar_t	*rptr;
23371 		tcph_t	*tcph;
23372 		mblk_t	*mp1;
23373 		int32_t	tcp_hdr_len;
23374 		int32_t	tcp_tcp_hdr_len;
23375 		int32_t	num_sack_blk = 0;
23376 		int32_t sack_opt_len;
23377 
23378 		/*
23379 		 * Allocate space for TCP + IP headers
23380 		 * and link-level header
23381 		 */
23382 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23383 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23384 			    tcp->tcp_num_sack_blk);
23385 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23386 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23387 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23388 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23389 		} else {
23390 			tcp_hdr_len = tcp->tcp_hdr_len;
23391 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23392 		}
23393 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23394 		if (!mp1)
23395 			return (NULL);
23396 
23397 		/* Update the latest receive window size in TCP header. */
23398 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23399 		    tcp->tcp_tcph->th_win);
23400 		/* copy in prototype TCP + IP header */
23401 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23402 		mp1->b_rptr = rptr;
23403 		mp1->b_wptr = rptr + tcp_hdr_len;
23404 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23405 
23406 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23407 
23408 		/* Set the TCP sequence number. */
23409 		U32_TO_ABE32(seq_no, tcph->th_seq);
23410 
23411 		/* Set up the TCP flag field. */
23412 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23413 		if (tcp->tcp_ecn_echo_on)
23414 			tcph->th_flags[0] |= TH_ECE;
23415 
23416 		tcp->tcp_rack = tcp->tcp_rnxt;
23417 		tcp->tcp_rack_cnt = 0;
23418 
23419 		/* fill in timestamp option if in use */
23420 		if (tcp->tcp_snd_ts_ok) {
23421 			uint32_t llbolt = (uint32_t)lbolt;
23422 
23423 			U32_TO_BE32(llbolt,
23424 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23425 			U32_TO_BE32(tcp->tcp_ts_recent,
23426 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23427 		}
23428 
23429 		/* Fill in SACK options */
23430 		if (num_sack_blk > 0) {
23431 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23432 			sack_blk_t *tmp;
23433 			int32_t	i;
23434 
23435 			wptr[0] = TCPOPT_NOP;
23436 			wptr[1] = TCPOPT_NOP;
23437 			wptr[2] = TCPOPT_SACK;
23438 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23439 			    sizeof (sack_blk_t);
23440 			wptr += TCPOPT_REAL_SACK_LEN;
23441 
23442 			tmp = tcp->tcp_sack_list;
23443 			for (i = 0; i < num_sack_blk; i++) {
23444 				U32_TO_BE32(tmp[i].begin, wptr);
23445 				wptr += sizeof (tcp_seq);
23446 				U32_TO_BE32(tmp[i].end, wptr);
23447 				wptr += sizeof (tcp_seq);
23448 			}
23449 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23450 			    << 4);
23451 		}
23452 
23453 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23454 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23455 		} else {
23456 			/* Check for ip6i_t header in sticky hdrs */
23457 			ip6_t *ip6 = (ip6_t *)(rptr +
23458 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23459 			    sizeof (ip6i_t) : 0));
23460 
23461 			ip6->ip6_plen = htons(tcp_hdr_len -
23462 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23463 		}
23464 
23465 		/*
23466 		 * Prime pump for checksum calculation in IP.  Include the
23467 		 * adjustment for a source route if any.
23468 		 */
23469 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23470 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23471 		U16_TO_ABE16(data_length, tcph->th_sum);
23472 
23473 		if (tcp->tcp_ip_forward_progress) {
23474 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23475 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23476 			tcp->tcp_ip_forward_progress = B_FALSE;
23477 		}
23478 		return (mp1);
23479 	}
23480 }
23481 
23482 /*
23483  * Hash list insertion routine for tcp_t structures. Each hash bucket
23484  * contains a list of tcp_t entries, and each entry is bound to a unique
23485  * port. If there are multiple tcp_t's that are bound to the same port, then
23486  * one of them will be linked into the hash bucket list, and the rest will
23487  * hang off of that one entry. For each port, entries bound to a specific IP
23488  * address will be inserted before those those bound to INADDR_ANY.
23489  */
23490 static void
23491 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23492 {
23493 	tcp_t	**tcpp;
23494 	tcp_t	*tcpnext;
23495 	tcp_t	*tcphash;
23496 
23497 	if (tcp->tcp_ptpbhn != NULL) {
23498 		ASSERT(!caller_holds_lock);
23499 		tcp_bind_hash_remove(tcp);
23500 	}
23501 	tcpp = &tbf->tf_tcp;
23502 	if (!caller_holds_lock) {
23503 		mutex_enter(&tbf->tf_lock);
23504 	} else {
23505 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23506 	}
23507 	tcphash = tcpp[0];
23508 	tcpnext = NULL;
23509 	if (tcphash != NULL) {
23510 		/* Look for an entry using the same port */
23511 		while ((tcphash = tcpp[0]) != NULL &&
23512 		    tcp->tcp_lport != tcphash->tcp_lport)
23513 			tcpp = &(tcphash->tcp_bind_hash);
23514 
23515 		/* The port was not found, just add to the end */
23516 		if (tcphash == NULL)
23517 			goto insert;
23518 
23519 		/*
23520 		 * OK, there already exists an entry bound to the
23521 		 * same port.
23522 		 *
23523 		 * If the new tcp bound to the INADDR_ANY address
23524 		 * and the first one in the list is not bound to
23525 		 * INADDR_ANY we skip all entries until we find the
23526 		 * first one bound to INADDR_ANY.
23527 		 * This makes sure that applications binding to a
23528 		 * specific address get preference over those binding to
23529 		 * INADDR_ANY.
23530 		 */
23531 		tcpnext = tcphash;
23532 		tcphash = NULL;
23533 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23534 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23535 			while ((tcpnext = tcpp[0]) != NULL &&
23536 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23537 				tcpp = &(tcpnext->tcp_bind_hash_port);
23538 
23539 			if (tcpnext) {
23540 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23541 				tcphash = tcpnext->tcp_bind_hash;
23542 				if (tcphash != NULL) {
23543 					tcphash->tcp_ptpbhn =
23544 					    &(tcp->tcp_bind_hash);
23545 					tcpnext->tcp_bind_hash = NULL;
23546 				}
23547 			}
23548 		} else {
23549 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23550 			tcphash = tcpnext->tcp_bind_hash;
23551 			if (tcphash != NULL) {
23552 				tcphash->tcp_ptpbhn =
23553 				    &(tcp->tcp_bind_hash);
23554 				tcpnext->tcp_bind_hash = NULL;
23555 			}
23556 		}
23557 	}
23558 insert:
23559 	tcp->tcp_bind_hash_port = tcpnext;
23560 	tcp->tcp_bind_hash = tcphash;
23561 	tcp->tcp_ptpbhn = tcpp;
23562 	tcpp[0] = tcp;
23563 	if (!caller_holds_lock)
23564 		mutex_exit(&tbf->tf_lock);
23565 }
23566 
23567 /*
23568  * Hash list removal routine for tcp_t structures.
23569  */
23570 static void
23571 tcp_bind_hash_remove(tcp_t *tcp)
23572 {
23573 	tcp_t	*tcpnext;
23574 	kmutex_t *lockp;
23575 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23576 
23577 	if (tcp->tcp_ptpbhn == NULL)
23578 		return;
23579 
23580 	/*
23581 	 * Extract the lock pointer in case there are concurrent
23582 	 * hash_remove's for this instance.
23583 	 */
23584 	ASSERT(tcp->tcp_lport != 0);
23585 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23586 
23587 	ASSERT(lockp != NULL);
23588 	mutex_enter(lockp);
23589 	if (tcp->tcp_ptpbhn) {
23590 		tcpnext = tcp->tcp_bind_hash_port;
23591 		if (tcpnext != NULL) {
23592 			tcp->tcp_bind_hash_port = NULL;
23593 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23594 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
23595 			if (tcpnext->tcp_bind_hash != NULL) {
23596 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
23597 				    &(tcpnext->tcp_bind_hash);
23598 				tcp->tcp_bind_hash = NULL;
23599 			}
23600 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
23601 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23602 			tcp->tcp_bind_hash = NULL;
23603 		}
23604 		*tcp->tcp_ptpbhn = tcpnext;
23605 		tcp->tcp_ptpbhn = NULL;
23606 	}
23607 	mutex_exit(lockp);
23608 }
23609 
23610 
23611 /*
23612  * Hash list lookup routine for tcp_t structures.
23613  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23614  */
23615 static tcp_t *
23616 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23617 {
23618 	tf_t	*tf;
23619 	tcp_t	*tcp;
23620 
23621 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23622 	mutex_enter(&tf->tf_lock);
23623 	for (tcp = tf->tf_tcp; tcp != NULL;
23624 	    tcp = tcp->tcp_acceptor_hash) {
23625 		if (tcp->tcp_acceptor_id == id) {
23626 			CONN_INC_REF(tcp->tcp_connp);
23627 			mutex_exit(&tf->tf_lock);
23628 			return (tcp);
23629 		}
23630 	}
23631 	mutex_exit(&tf->tf_lock);
23632 	return (NULL);
23633 }
23634 
23635 
23636 /*
23637  * Hash list insertion routine for tcp_t structures.
23638  */
23639 void
23640 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23641 {
23642 	tf_t	*tf;
23643 	tcp_t	**tcpp;
23644 	tcp_t	*tcpnext;
23645 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23646 
23647 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23648 
23649 	if (tcp->tcp_ptpahn != NULL)
23650 		tcp_acceptor_hash_remove(tcp);
23651 	tcpp = &tf->tf_tcp;
23652 	mutex_enter(&tf->tf_lock);
23653 	tcpnext = tcpp[0];
23654 	if (tcpnext)
23655 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23656 	tcp->tcp_acceptor_hash = tcpnext;
23657 	tcp->tcp_ptpahn = tcpp;
23658 	tcpp[0] = tcp;
23659 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23660 	mutex_exit(&tf->tf_lock);
23661 }
23662 
23663 /*
23664  * Hash list removal routine for tcp_t structures.
23665  */
23666 static void
23667 tcp_acceptor_hash_remove(tcp_t *tcp)
23668 {
23669 	tcp_t	*tcpnext;
23670 	kmutex_t *lockp;
23671 
23672 	/*
23673 	 * Extract the lock pointer in case there are concurrent
23674 	 * hash_remove's for this instance.
23675 	 */
23676 	lockp = tcp->tcp_acceptor_lockp;
23677 
23678 	if (tcp->tcp_ptpahn == NULL)
23679 		return;
23680 
23681 	ASSERT(lockp != NULL);
23682 	mutex_enter(lockp);
23683 	if (tcp->tcp_ptpahn) {
23684 		tcpnext = tcp->tcp_acceptor_hash;
23685 		if (tcpnext) {
23686 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23687 			tcp->tcp_acceptor_hash = NULL;
23688 		}
23689 		*tcp->tcp_ptpahn = tcpnext;
23690 		tcp->tcp_ptpahn = NULL;
23691 	}
23692 	mutex_exit(lockp);
23693 	tcp->tcp_acceptor_lockp = NULL;
23694 }
23695 
23696 /*
23697  * Type three generator adapted from the random() function in 4.4 BSD:
23698  */
23699 
23700 /*
23701  * Copyright (c) 1983, 1993
23702  *	The Regents of the University of California.  All rights reserved.
23703  *
23704  * Redistribution and use in source and binary forms, with or without
23705  * modification, are permitted provided that the following conditions
23706  * are met:
23707  * 1. Redistributions of source code must retain the above copyright
23708  *    notice, this list of conditions and the following disclaimer.
23709  * 2. Redistributions in binary form must reproduce the above copyright
23710  *    notice, this list of conditions and the following disclaimer in the
23711  *    documentation and/or other materials provided with the distribution.
23712  * 3. All advertising materials mentioning features or use of this software
23713  *    must display the following acknowledgement:
23714  *	This product includes software developed by the University of
23715  *	California, Berkeley and its contributors.
23716  * 4. Neither the name of the University nor the names of its contributors
23717  *    may be used to endorse or promote products derived from this software
23718  *    without specific prior written permission.
23719  *
23720  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23721  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23722  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23723  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23724  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23725  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23726  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23727  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23728  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23729  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23730  * SUCH DAMAGE.
23731  */
23732 
23733 /* Type 3 -- x**31 + x**3 + 1 */
23734 #define	DEG_3		31
23735 #define	SEP_3		3
23736 
23737 
23738 /* Protected by tcp_random_lock */
23739 static int tcp_randtbl[DEG_3 + 1];
23740 
23741 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23742 static int *tcp_random_rptr = &tcp_randtbl[1];
23743 
23744 static int *tcp_random_state = &tcp_randtbl[1];
23745 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23746 
23747 kmutex_t tcp_random_lock;
23748 
23749 void
23750 tcp_random_init(void)
23751 {
23752 	int i;
23753 	hrtime_t hrt;
23754 	time_t wallclock;
23755 	uint64_t result;
23756 
23757 	/*
23758 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23759 	 * a longlong, which may contain resolution down to nanoseconds.
23760 	 * The current time will either be a 32-bit or a 64-bit quantity.
23761 	 * XOR the two together in a 64-bit result variable.
23762 	 * Convert the result to a 32-bit value by multiplying the high-order
23763 	 * 32-bits by the low-order 32-bits.
23764 	 */
23765 
23766 	hrt = gethrtime();
23767 	(void) drv_getparm(TIME, &wallclock);
23768 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23769 	mutex_enter(&tcp_random_lock);
23770 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23771 	    (result & 0xffffffff);
23772 
23773 	for (i = 1; i < DEG_3; i++)
23774 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23775 		    + 12345;
23776 	tcp_random_fptr = &tcp_random_state[SEP_3];
23777 	tcp_random_rptr = &tcp_random_state[0];
23778 	mutex_exit(&tcp_random_lock);
23779 	for (i = 0; i < 10 * DEG_3; i++)
23780 		(void) tcp_random();
23781 }
23782 
23783 /*
23784  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23785  * This range is selected to be approximately centered on TCP_ISS / 2,
23786  * and easy to compute. We get this value by generating a 32-bit random
23787  * number, selecting out the high-order 17 bits, and then adding one so
23788  * that we never return zero.
23789  */
23790 int
23791 tcp_random(void)
23792 {
23793 	int i;
23794 
23795 	mutex_enter(&tcp_random_lock);
23796 	*tcp_random_fptr += *tcp_random_rptr;
23797 
23798 	/*
23799 	 * The high-order bits are more random than the low-order bits,
23800 	 * so we select out the high-order 17 bits and add one so that
23801 	 * we never return zero.
23802 	 */
23803 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23804 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23805 		tcp_random_fptr = tcp_random_state;
23806 		++tcp_random_rptr;
23807 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23808 		tcp_random_rptr = tcp_random_state;
23809 
23810 	mutex_exit(&tcp_random_lock);
23811 	return (i);
23812 }
23813 
23814 static int
23815 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23816     int *t_errorp, int *sys_errorp)
23817 {
23818 	int error;
23819 	int is_absreq_failure;
23820 	t_scalar_t *opt_lenp;
23821 	t_scalar_t opt_offset;
23822 	int prim_type;
23823 	struct T_conn_req *tcreqp;
23824 	struct T_conn_res *tcresp;
23825 	cred_t *cr;
23826 
23827 	/*
23828 	 * All Solaris components should pass a db_credp
23829 	 * for this TPI message, hence we ASSERT.
23830 	 * But in case there is some other M_PROTO that looks
23831 	 * like a TPI message sent by some other kernel
23832 	 * component, we check and return an error.
23833 	 */
23834 	cr = msg_getcred(mp, NULL);
23835 	ASSERT(cr != NULL);
23836 	if (cr == NULL)
23837 		return (-1);
23838 
23839 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23840 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23841 	    prim_type == T_CONN_RES);
23842 
23843 	switch (prim_type) {
23844 	case T_CONN_REQ:
23845 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23846 		opt_offset = tcreqp->OPT_offset;
23847 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23848 		break;
23849 	case O_T_CONN_RES:
23850 	case T_CONN_RES:
23851 		tcresp = (struct T_conn_res *)mp->b_rptr;
23852 		opt_offset = tcresp->OPT_offset;
23853 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23854 		break;
23855 	}
23856 
23857 	*t_errorp = 0;
23858 	*sys_errorp = 0;
23859 	*do_disconnectp = 0;
23860 
23861 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23862 	    opt_offset, cr, &tcp_opt_obj,
23863 	    NULL, &is_absreq_failure);
23864 
23865 	switch (error) {
23866 	case  0:		/* no error */
23867 		ASSERT(is_absreq_failure == 0);
23868 		return (0);
23869 	case ENOPROTOOPT:
23870 		*t_errorp = TBADOPT;
23871 		break;
23872 	case EACCES:
23873 		*t_errorp = TACCES;
23874 		break;
23875 	default:
23876 		*t_errorp = TSYSERR; *sys_errorp = error;
23877 		break;
23878 	}
23879 	if (is_absreq_failure != 0) {
23880 		/*
23881 		 * The connection request should get the local ack
23882 		 * T_OK_ACK and then a T_DISCON_IND.
23883 		 */
23884 		*do_disconnectp = 1;
23885 	}
23886 	return (-1);
23887 }
23888 
23889 /*
23890  * Split this function out so that if the secret changes, I'm okay.
23891  *
23892  * Initialize the tcp_iss_cookie and tcp_iss_key.
23893  */
23894 
23895 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23896 
23897 static void
23898 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
23899 {
23900 	struct {
23901 		int32_t current_time;
23902 		uint32_t randnum;
23903 		uint16_t pad;
23904 		uint8_t ether[6];
23905 		uint8_t passwd[PASSWD_SIZE];
23906 	} tcp_iss_cookie;
23907 	time_t t;
23908 
23909 	/*
23910 	 * Start with the current absolute time.
23911 	 */
23912 	(void) drv_getparm(TIME, &t);
23913 	tcp_iss_cookie.current_time = t;
23914 
23915 	/*
23916 	 * XXX - Need a more random number per RFC 1750, not this crap.
23917 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23918 	 */
23919 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23920 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23921 
23922 	/*
23923 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23924 	 * as a good template.
23925 	 */
23926 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23927 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23928 
23929 	/*
23930 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23931 	 */
23932 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23933 
23934 	/*
23935 	 * See 4010593 if this section becomes a problem again,
23936 	 * but the local ethernet address is useful here.
23937 	 */
23938 	(void) localetheraddr(NULL,
23939 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23940 
23941 	/*
23942 	 * Hash 'em all together.  The MD5Final is called per-connection.
23943 	 */
23944 	mutex_enter(&tcps->tcps_iss_key_lock);
23945 	MD5Init(&tcps->tcps_iss_key);
23946 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
23947 	    sizeof (tcp_iss_cookie));
23948 	mutex_exit(&tcps->tcps_iss_key_lock);
23949 }
23950 
23951 /*
23952  * Set the RFC 1948 pass phrase
23953  */
23954 /* ARGSUSED */
23955 static int
23956 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23957     cred_t *cr)
23958 {
23959 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
23960 
23961 	/*
23962 	 * Basically, value contains a new pass phrase.  Pass it along!
23963 	 */
23964 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
23965 	return (0);
23966 }
23967 
23968 /* ARGSUSED */
23969 static int
23970 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23971 {
23972 	bzero(buf, sizeof (tcp_sack_info_t));
23973 	return (0);
23974 }
23975 
23976 /* ARGSUSED */
23977 static int
23978 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23979 {
23980 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23981 	return (0);
23982 }
23983 
23984 /*
23985  * Make sure we wait until the default queue is setup, yet allow
23986  * tcp_g_q_create() to open a TCP stream.
23987  * We need to allow tcp_g_q_create() do do an open
23988  * of tcp, hence we compare curhread.
23989  * All others have to wait until the tcps_g_q has been
23990  * setup.
23991  */
23992 void
23993 tcp_g_q_setup(tcp_stack_t *tcps)
23994 {
23995 	mutex_enter(&tcps->tcps_g_q_lock);
23996 	if (tcps->tcps_g_q != NULL) {
23997 		mutex_exit(&tcps->tcps_g_q_lock);
23998 		return;
23999 	}
24000 	if (tcps->tcps_g_q_creator == NULL) {
24001 		/* This thread will set it up */
24002 		tcps->tcps_g_q_creator = curthread;
24003 		mutex_exit(&tcps->tcps_g_q_lock);
24004 		tcp_g_q_create(tcps);
24005 		mutex_enter(&tcps->tcps_g_q_lock);
24006 		ASSERT(tcps->tcps_g_q_creator == curthread);
24007 		tcps->tcps_g_q_creator = NULL;
24008 		cv_signal(&tcps->tcps_g_q_cv);
24009 		ASSERT(tcps->tcps_g_q != NULL);
24010 		mutex_exit(&tcps->tcps_g_q_lock);
24011 		return;
24012 	}
24013 	/* Everybody but the creator has to wait */
24014 	if (tcps->tcps_g_q_creator != curthread) {
24015 		while (tcps->tcps_g_q == NULL)
24016 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24017 	}
24018 	mutex_exit(&tcps->tcps_g_q_lock);
24019 }
24020 
24021 #define	IP	"ip"
24022 
24023 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24024 
24025 /*
24026  * Create a default tcp queue here instead of in strplumb
24027  */
24028 void
24029 tcp_g_q_create(tcp_stack_t *tcps)
24030 {
24031 	int error;
24032 	ldi_handle_t	lh = NULL;
24033 	ldi_ident_t	li = NULL;
24034 	int		rval;
24035 	cred_t		*cr;
24036 	major_t IP_MAJ;
24037 
24038 #ifdef NS_DEBUG
24039 	(void) printf("tcp_g_q_create()\n");
24040 #endif
24041 
24042 	IP_MAJ = ddi_name_to_major(IP);
24043 
24044 	ASSERT(tcps->tcps_g_q_creator == curthread);
24045 
24046 	error = ldi_ident_from_major(IP_MAJ, &li);
24047 	if (error) {
24048 #ifdef DEBUG
24049 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24050 		    error);
24051 #endif
24052 		return;
24053 	}
24054 
24055 	cr = zone_get_kcred(netstackid_to_zoneid(
24056 	    tcps->tcps_netstack->netstack_stackid));
24057 	ASSERT(cr != NULL);
24058 	/*
24059 	 * We set the tcp default queue to IPv6 because IPv4 falls
24060 	 * back to IPv6 when it can't find a client, but
24061 	 * IPv6 does not fall back to IPv4.
24062 	 */
24063 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24064 	if (error) {
24065 #ifdef DEBUG
24066 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24067 		    error);
24068 #endif
24069 		goto out;
24070 	}
24071 
24072 	/*
24073 	 * This ioctl causes the tcp framework to cache a pointer to
24074 	 * this stream, so we don't want to close the stream after
24075 	 * this operation.
24076 	 * Use the kernel credentials that are for the zone we're in.
24077 	 */
24078 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24079 	    (intptr_t)0, FKIOCTL, cr, &rval);
24080 	if (error) {
24081 #ifdef DEBUG
24082 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24083 		    "error %d\n", error);
24084 #endif
24085 		goto out;
24086 	}
24087 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24088 	lh = NULL;
24089 out:
24090 	/* Close layered handles */
24091 	if (li)
24092 		ldi_ident_release(li);
24093 	/* Keep cred around until _inactive needs it */
24094 	tcps->tcps_g_q_cr = cr;
24095 }
24096 
24097 /*
24098  * We keep tcp_g_q set until all other tcp_t's in the zone
24099  * has gone away, and then when tcp_g_q_inactive() is called
24100  * we clear it.
24101  */
24102 void
24103 tcp_g_q_destroy(tcp_stack_t *tcps)
24104 {
24105 #ifdef NS_DEBUG
24106 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24107 	    tcps->tcps_netstack->netstack_stackid);
24108 #endif
24109 
24110 	if (tcps->tcps_g_q == NULL) {
24111 		return;	/* Nothing to cleanup */
24112 	}
24113 	/*
24114 	 * Drop reference corresponding to the default queue.
24115 	 * This reference was added from tcp_open when the default queue
24116 	 * was created, hence we compensate for this extra drop in
24117 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24118 	 * the default queue was the last one to be open, in which
24119 	 * case, then tcp_g_q_inactive will be
24120 	 * called as a result of the refrele.
24121 	 */
24122 	TCPS_REFRELE(tcps);
24123 }
24124 
24125 /*
24126  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24127  * Run by tcp_q_q_inactive using a taskq.
24128  */
24129 static void
24130 tcp_g_q_close(void *arg)
24131 {
24132 	tcp_stack_t *tcps = arg;
24133 	int error;
24134 	ldi_handle_t	lh = NULL;
24135 	ldi_ident_t	li = NULL;
24136 	cred_t		*cr;
24137 	major_t IP_MAJ;
24138 
24139 	IP_MAJ = ddi_name_to_major(IP);
24140 
24141 #ifdef NS_DEBUG
24142 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24143 	    tcps->tcps_netstack->netstack_stackid,
24144 	    tcps->tcps_netstack->netstack_refcnt);
24145 #endif
24146 	lh = tcps->tcps_g_q_lh;
24147 	if (lh == NULL)
24148 		return;	/* Nothing to cleanup */
24149 
24150 	ASSERT(tcps->tcps_refcnt == 1);
24151 	ASSERT(tcps->tcps_g_q != NULL);
24152 
24153 	error = ldi_ident_from_major(IP_MAJ, &li);
24154 	if (error) {
24155 #ifdef DEBUG
24156 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
24157 		    error);
24158 #endif
24159 		return;
24160 	}
24161 
24162 	cr = tcps->tcps_g_q_cr;
24163 	tcps->tcps_g_q_cr = NULL;
24164 	ASSERT(cr != NULL);
24165 
24166 	/*
24167 	 * Make sure we can break the recursion when tcp_close decrements
24168 	 * the reference count causing g_q_inactive to be called again.
24169 	 */
24170 	tcps->tcps_g_q_lh = NULL;
24171 
24172 	/* close the default queue */
24173 	(void) ldi_close(lh, FREAD|FWRITE, cr);
24174 	/*
24175 	 * At this point in time tcps and the rest of netstack_t might
24176 	 * have been deleted.
24177 	 */
24178 	tcps = NULL;
24179 
24180 	/* Close layered handles */
24181 	ldi_ident_release(li);
24182 	crfree(cr);
24183 }
24184 
24185 /*
24186  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24187  *
24188  * Have to ensure that the ldi routines are not used by an
24189  * interrupt thread by using a taskq.
24190  */
24191 void
24192 tcp_g_q_inactive(tcp_stack_t *tcps)
24193 {
24194 	if (tcps->tcps_g_q_lh == NULL)
24195 		return;	/* Nothing to cleanup */
24196 
24197 	ASSERT(tcps->tcps_refcnt == 0);
24198 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
24199 
24200 	if (servicing_interrupt()) {
24201 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
24202 		    (void *) tcps, TQ_SLEEP);
24203 	} else {
24204 		tcp_g_q_close(tcps);
24205 	}
24206 }
24207 
24208 /*
24209  * Called by IP when IP is loaded into the kernel
24210  */
24211 void
24212 tcp_ddi_g_init(void)
24213 {
24214 	tcp_timercache = kmem_cache_create("tcp_timercache",
24215 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24216 	    NULL, NULL, NULL, NULL, NULL, 0);
24217 
24218 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24219 	    sizeof (tcp_sack_info_t), 0,
24220 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24221 
24222 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24223 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24224 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24225 
24226 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24227 
24228 	/* Initialize the random number generator */
24229 	tcp_random_init();
24230 
24231 	/* A single callback independently of how many netstacks we have */
24232 	ip_squeue_init(tcp_squeue_add);
24233 
24234 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
24235 
24236 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
24237 	    TASKQ_PREPOPULATE);
24238 
24239 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
24240 
24241 	/*
24242 	 * We want to be informed each time a stack is created or
24243 	 * destroyed in the kernel, so we can maintain the
24244 	 * set of tcp_stack_t's.
24245 	 */
24246 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
24247 	    tcp_stack_fini);
24248 }
24249 
24250 
24251 #define	INET_NAME	"ip"
24252 
24253 /*
24254  * Initialize the TCP stack instance.
24255  */
24256 static void *
24257 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
24258 {
24259 	tcp_stack_t	*tcps;
24260 	tcpparam_t	*pa;
24261 	int		i;
24262 	int		error = 0;
24263 	major_t		major;
24264 
24265 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
24266 	tcps->tcps_netstack = ns;
24267 
24268 	/* Initialize locks */
24269 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24270 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
24271 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24272 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24273 
24274 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
24275 	tcps->tcps_g_epriv_ports[0] = 2049;
24276 	tcps->tcps_g_epriv_ports[1] = 4045;
24277 	tcps->tcps_min_anonpriv_port = 512;
24278 
24279 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
24280 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
24281 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
24282 	    TCP_FANOUT_SIZE, KM_SLEEP);
24283 
24284 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24285 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
24286 		    MUTEX_DEFAULT, NULL);
24287 	}
24288 
24289 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24290 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
24291 		    MUTEX_DEFAULT, NULL);
24292 	}
24293 
24294 	/* TCP's IPsec code calls the packet dropper. */
24295 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
24296 
24297 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
24298 	tcps->tcps_params = pa;
24299 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24300 
24301 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
24302 	    A_CNT(lcl_tcp_param_arr), tcps);
24303 
24304 	/*
24305 	 * Note: To really walk the device tree you need the devinfo
24306 	 * pointer to your device which is only available after probe/attach.
24307 	 * The following is safe only because it uses ddi_root_node()
24308 	 */
24309 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24310 	    tcp_opt_obj.odb_opt_arr_cnt);
24311 
24312 	/*
24313 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24314 	 * by the boot scripts.
24315 	 *
24316 	 * Use NULL name, as the name is caught by the new lockstats.
24317 	 *
24318 	 * Initialize with some random, non-guessable string, like the global
24319 	 * T_INFO_ACK.
24320 	 */
24321 
24322 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24323 	    sizeof (tcp_g_t_info_ack), tcps);
24324 
24325 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
24326 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
24327 
24328 	major = mod_name_to_major(INET_NAME);
24329 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
24330 	ASSERT(error == 0);
24331 	return (tcps);
24332 }
24333 
24334 /*
24335  * Called when the IP module is about to be unloaded.
24336  */
24337 void
24338 tcp_ddi_g_destroy(void)
24339 {
24340 	tcp_g_kstat_fini(tcp_g_kstat);
24341 	tcp_g_kstat = NULL;
24342 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
24343 
24344 	mutex_destroy(&tcp_random_lock);
24345 
24346 	kmem_cache_destroy(tcp_timercache);
24347 	kmem_cache_destroy(tcp_sack_info_cache);
24348 	kmem_cache_destroy(tcp_iphc_cache);
24349 
24350 	netstack_unregister(NS_TCP);
24351 	taskq_destroy(tcp_taskq);
24352 }
24353 
24354 /*
24355  * Shut down the TCP stack instance.
24356  */
24357 /* ARGSUSED */
24358 static void
24359 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24360 {
24361 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24362 
24363 	tcp_g_q_destroy(tcps);
24364 }
24365 
24366 /*
24367  * Free the TCP stack instance.
24368  */
24369 static void
24370 tcp_stack_fini(netstackid_t stackid, void *arg)
24371 {
24372 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24373 	int i;
24374 
24375 	nd_free(&tcps->tcps_g_nd);
24376 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24377 	tcps->tcps_params = NULL;
24378 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24379 	tcps->tcps_wroff_xtra_param = NULL;
24380 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24381 	tcps->tcps_mdt_head_param = NULL;
24382 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24383 	tcps->tcps_mdt_tail_param = NULL;
24384 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24385 	tcps->tcps_mdt_max_pbufs_param = NULL;
24386 
24387 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24388 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24389 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24390 	}
24391 
24392 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24393 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
24394 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
24395 	}
24396 
24397 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
24398 	tcps->tcps_bind_fanout = NULL;
24399 
24400 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
24401 	tcps->tcps_acceptor_fanout = NULL;
24402 
24403 	mutex_destroy(&tcps->tcps_iss_key_lock);
24404 	mutex_destroy(&tcps->tcps_g_q_lock);
24405 	cv_destroy(&tcps->tcps_g_q_cv);
24406 	mutex_destroy(&tcps->tcps_epriv_port_lock);
24407 
24408 	ip_drop_unregister(&tcps->tcps_dropper);
24409 
24410 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
24411 	tcps->tcps_kstat = NULL;
24412 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
24413 
24414 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
24415 	tcps->tcps_mibkp = NULL;
24416 
24417 	ldi_ident_release(tcps->tcps_ldi_ident);
24418 	kmem_free(tcps, sizeof (*tcps));
24419 }
24420 
24421 /*
24422  * Generate ISS, taking into account NDD changes may happen halfway through.
24423  * (If the iss is not zero, set it.)
24424  */
24425 
24426 static void
24427 tcp_iss_init(tcp_t *tcp)
24428 {
24429 	MD5_CTX context;
24430 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24431 	uint32_t answer[4];
24432 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24433 
24434 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
24435 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
24436 	switch (tcps->tcps_strong_iss) {
24437 	case 2:
24438 		mutex_enter(&tcps->tcps_iss_key_lock);
24439 		context = tcps->tcps_iss_key;
24440 		mutex_exit(&tcps->tcps_iss_key_lock);
24441 		arg.ports = tcp->tcp_ports;
24442 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24443 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24444 			    &arg.src);
24445 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24446 			    &arg.dst);
24447 		} else {
24448 			arg.src = tcp->tcp_ip6h->ip6_src;
24449 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24450 		}
24451 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24452 		MD5Final((uchar_t *)answer, &context);
24453 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24454 		/*
24455 		 * Now that we've hashed into a unique per-connection sequence
24456 		 * space, add a random increment per strong_iss == 1.  So I
24457 		 * guess we'll have to...
24458 		 */
24459 		/* FALLTHRU */
24460 	case 1:
24461 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24462 		break;
24463 	default:
24464 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24465 		break;
24466 	}
24467 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24468 	tcp->tcp_fss = tcp->tcp_iss - 1;
24469 	tcp->tcp_suna = tcp->tcp_iss;
24470 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24471 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24472 	tcp->tcp_csuna = tcp->tcp_snxt;
24473 }
24474 
24475 /*
24476  * Exported routine for extracting active tcp connection status.
24477  *
24478  * This is used by the Solaris Cluster Networking software to
24479  * gather a list of connections that need to be forwarded to
24480  * specific nodes in the cluster when configuration changes occur.
24481  *
24482  * The callback is invoked for each tcp_t structure from all netstacks,
24483  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
24484  * from the netstack with the specified stack_id. Returning
24485  * non-zero from the callback routine terminates the search.
24486  */
24487 int
24488 cl_tcp_walk_list(netstackid_t stack_id,
24489     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
24490 {
24491 	netstack_handle_t nh;
24492 	netstack_t *ns;
24493 	int ret = 0;
24494 
24495 	if (stack_id >= 0) {
24496 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
24497 			return (EINVAL);
24498 
24499 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24500 		    ns->netstack_tcp);
24501 		netstack_rele(ns);
24502 		return (ret);
24503 	}
24504 
24505 	netstack_next_init(&nh);
24506 	while ((ns = netstack_next(&nh)) != NULL) {
24507 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24508 		    ns->netstack_tcp);
24509 		netstack_rele(ns);
24510 	}
24511 	netstack_next_fini(&nh);
24512 	return (ret);
24513 }
24514 
24515 static int
24516 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
24517     tcp_stack_t *tcps)
24518 {
24519 	tcp_t *tcp;
24520 	cl_tcp_info_t	cl_tcpi;
24521 	connf_t	*connfp;
24522 	conn_t	*connp;
24523 	int	i;
24524 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24525 
24526 	ASSERT(callback != NULL);
24527 
24528 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24529 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
24530 		connp = NULL;
24531 
24532 		while ((connp =
24533 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24534 
24535 			tcp = connp->conn_tcp;
24536 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
24537 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
24538 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
24539 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
24540 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
24541 			/*
24542 			 * The macros tcp_laddr and tcp_faddr give the IPv4
24543 			 * addresses. They are copied implicitly below as
24544 			 * mapped addresses.
24545 			 */
24546 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
24547 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24548 				cl_tcpi.cl_tcpi_faddr =
24549 				    tcp->tcp_ipha->ipha_dst;
24550 			} else {
24551 				cl_tcpi.cl_tcpi_faddr_v6 =
24552 				    tcp->tcp_ip6h->ip6_dst;
24553 			}
24554 
24555 			/*
24556 			 * If the callback returns non-zero
24557 			 * we terminate the traversal.
24558 			 */
24559 			if ((*callback)(&cl_tcpi, arg) != 0) {
24560 				CONN_DEC_REF(tcp->tcp_connp);
24561 				return (1);
24562 			}
24563 		}
24564 	}
24565 
24566 	return (0);
24567 }
24568 
24569 /*
24570  * Macros used for accessing the different types of sockaddr
24571  * structures inside a tcp_ioc_abort_conn_t.
24572  */
24573 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
24574 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
24575 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
24576 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
24577 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
24578 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
24579 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
24580 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
24581 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
24582 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
24583 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
24584 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
24585 
24586 /*
24587  * Return the correct error code to mimic the behavior
24588  * of a connection reset.
24589  */
24590 #define	TCP_AC_GET_ERRCODE(state, err) {	\
24591 		switch ((state)) {		\
24592 		case TCPS_SYN_SENT:		\
24593 		case TCPS_SYN_RCVD:		\
24594 			(err) = ECONNREFUSED;	\
24595 			break;			\
24596 		case TCPS_ESTABLISHED:		\
24597 		case TCPS_FIN_WAIT_1:		\
24598 		case TCPS_FIN_WAIT_2:		\
24599 		case TCPS_CLOSE_WAIT:		\
24600 			(err) = ECONNRESET;	\
24601 			break;			\
24602 		case TCPS_CLOSING:		\
24603 		case TCPS_LAST_ACK:		\
24604 		case TCPS_TIME_WAIT:		\
24605 			(err) = 0;		\
24606 			break;			\
24607 		default:			\
24608 			(err) = ENXIO;		\
24609 		}				\
24610 	}
24611 
24612 /*
24613  * Check if a tcp structure matches the info in acp.
24614  */
24615 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24616 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24617 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24618 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24619 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24620 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24621 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24622 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24623 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24624 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24625 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24626 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24627 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24628 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24629 	&(tcp)->tcp_ip_src_v6)) &&				\
24630 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24631 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24632 	&(tcp)->tcp_remote_v6)) &&				\
24633 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24634 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24635 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24636 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24637 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24638 	(acp)->ac_end >= (tcp)->tcp_state))
24639 
24640 #define	TCP_AC_MATCH(acp, tcp)					\
24641 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24642 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24643 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24644 
24645 /*
24646  * Build a message containing a tcp_ioc_abort_conn_t structure
24647  * which is filled in with information from acp and tp.
24648  */
24649 static mblk_t *
24650 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24651 {
24652 	mblk_t *mp;
24653 	tcp_ioc_abort_conn_t *tacp;
24654 
24655 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24656 	if (mp == NULL)
24657 		return (NULL);
24658 
24659 	mp->b_datap->db_type = M_CTL;
24660 
24661 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24662 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24663 	    sizeof (uint32_t));
24664 
24665 	tacp->ac_start = acp->ac_start;
24666 	tacp->ac_end = acp->ac_end;
24667 	tacp->ac_zoneid = acp->ac_zoneid;
24668 
24669 	if (acp->ac_local.ss_family == AF_INET) {
24670 		tacp->ac_local.ss_family = AF_INET;
24671 		tacp->ac_remote.ss_family = AF_INET;
24672 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24673 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24674 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24675 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24676 	} else {
24677 		tacp->ac_local.ss_family = AF_INET6;
24678 		tacp->ac_remote.ss_family = AF_INET6;
24679 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24680 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24681 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24682 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24683 	}
24684 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24685 	return (mp);
24686 }
24687 
24688 /*
24689  * Print a tcp_ioc_abort_conn_t structure.
24690  */
24691 static void
24692 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24693 {
24694 	char lbuf[128];
24695 	char rbuf[128];
24696 	sa_family_t af;
24697 	in_port_t lport, rport;
24698 	ushort_t logflags;
24699 
24700 	af = acp->ac_local.ss_family;
24701 
24702 	if (af == AF_INET) {
24703 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24704 		    lbuf, 128);
24705 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24706 		    rbuf, 128);
24707 		lport = ntohs(TCP_AC_V4LPORT(acp));
24708 		rport = ntohs(TCP_AC_V4RPORT(acp));
24709 	} else {
24710 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24711 		    lbuf, 128);
24712 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24713 		    rbuf, 128);
24714 		lport = ntohs(TCP_AC_V6LPORT(acp));
24715 		rport = ntohs(TCP_AC_V6RPORT(acp));
24716 	}
24717 
24718 	logflags = SL_TRACE | SL_NOTE;
24719 	/*
24720 	 * Don't print this message to the console if the operation was done
24721 	 * to a non-global zone.
24722 	 */
24723 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24724 		logflags |= SL_CONSOLE;
24725 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
24726 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24727 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24728 	    acp->ac_start, acp->ac_end);
24729 }
24730 
24731 /*
24732  * Called inside tcp_rput when a message built using
24733  * tcp_ioctl_abort_build_msg is put into a queue.
24734  * Note that when we get here there is no wildcard in acp any more.
24735  */
24736 static void
24737 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24738 {
24739 	tcp_ioc_abort_conn_t *acp;
24740 
24741 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24742 	if (tcp->tcp_state <= acp->ac_end) {
24743 		/*
24744 		 * If we get here, we are already on the correct
24745 		 * squeue. This ioctl follows the following path
24746 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24747 		 * ->tcp_ioctl_abort->squeue_enter (if on a
24748 		 * different squeue)
24749 		 */
24750 		int errcode;
24751 
24752 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24753 		(void) tcp_clean_death(tcp, errcode, 26);
24754 	}
24755 	freemsg(mp);
24756 }
24757 
24758 /*
24759  * Abort all matching connections on a hash chain.
24760  */
24761 static int
24762 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24763     boolean_t exact, tcp_stack_t *tcps)
24764 {
24765 	int nmatch, err = 0;
24766 	tcp_t *tcp;
24767 	MBLKP mp, last, listhead = NULL;
24768 	conn_t	*tconnp;
24769 	connf_t	*connfp;
24770 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24771 
24772 	connfp = &ipst->ips_ipcl_conn_fanout[index];
24773 
24774 startover:
24775 	nmatch = 0;
24776 
24777 	mutex_enter(&connfp->connf_lock);
24778 	for (tconnp = connfp->connf_head; tconnp != NULL;
24779 	    tconnp = tconnp->conn_next) {
24780 		tcp = tconnp->conn_tcp;
24781 		if (TCP_AC_MATCH(acp, tcp)) {
24782 			CONN_INC_REF(tcp->tcp_connp);
24783 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24784 			if (mp == NULL) {
24785 				err = ENOMEM;
24786 				CONN_DEC_REF(tcp->tcp_connp);
24787 				break;
24788 			}
24789 			mp->b_prev = (mblk_t *)tcp;
24790 
24791 			if (listhead == NULL) {
24792 				listhead = mp;
24793 				last = mp;
24794 			} else {
24795 				last->b_next = mp;
24796 				last = mp;
24797 			}
24798 			nmatch++;
24799 			if (exact)
24800 				break;
24801 		}
24802 
24803 		/* Avoid holding lock for too long. */
24804 		if (nmatch >= 500)
24805 			break;
24806 	}
24807 	mutex_exit(&connfp->connf_lock);
24808 
24809 	/* Pass mp into the correct tcp */
24810 	while ((mp = listhead) != NULL) {
24811 		listhead = listhead->b_next;
24812 		tcp = (tcp_t *)mp->b_prev;
24813 		mp->b_next = mp->b_prev = NULL;
24814 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
24815 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
24816 	}
24817 
24818 	*count += nmatch;
24819 	if (nmatch >= 500 && err == 0)
24820 		goto startover;
24821 	return (err);
24822 }
24823 
24824 /*
24825  * Abort all connections that matches the attributes specified in acp.
24826  */
24827 static int
24828 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
24829 {
24830 	sa_family_t af;
24831 	uint32_t  ports;
24832 	uint16_t *pports;
24833 	int err = 0, count = 0;
24834 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24835 	int index = -1;
24836 	ushort_t logflags;
24837 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24838 
24839 	af = acp->ac_local.ss_family;
24840 
24841 	if (af == AF_INET) {
24842 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24843 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24844 			pports = (uint16_t *)&ports;
24845 			pports[1] = TCP_AC_V4LPORT(acp);
24846 			pports[0] = TCP_AC_V4RPORT(acp);
24847 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24848 		}
24849 	} else {
24850 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24851 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24852 			pports = (uint16_t *)&ports;
24853 			pports[1] = TCP_AC_V6LPORT(acp);
24854 			pports[0] = TCP_AC_V6RPORT(acp);
24855 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24856 		}
24857 	}
24858 
24859 	/*
24860 	 * For cases where remote addr, local port, and remote port are non-
24861 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24862 	 */
24863 	if (index != -1) {
24864 		err = tcp_ioctl_abort_bucket(acp, index,
24865 		    &count, exact, tcps);
24866 	} else {
24867 		/*
24868 		 * loop through all entries for wildcard case
24869 		 */
24870 		for (index = 0;
24871 		    index < ipst->ips_ipcl_conn_fanout_size;
24872 		    index++) {
24873 			err = tcp_ioctl_abort_bucket(acp, index,
24874 			    &count, exact, tcps);
24875 			if (err != 0)
24876 				break;
24877 		}
24878 	}
24879 
24880 	logflags = SL_TRACE | SL_NOTE;
24881 	/*
24882 	 * Don't print this message to the console if the operation was done
24883 	 * to a non-global zone.
24884 	 */
24885 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24886 		logflags |= SL_CONSOLE;
24887 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24888 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24889 	if (err == 0 && count == 0)
24890 		err = ENOENT;
24891 	return (err);
24892 }
24893 
24894 /*
24895  * Process the TCP_IOC_ABORT_CONN ioctl request.
24896  */
24897 static void
24898 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24899 {
24900 	int	err;
24901 	IOCP    iocp;
24902 	MBLKP   mp1;
24903 	sa_family_t laf, raf;
24904 	tcp_ioc_abort_conn_t *acp;
24905 	zone_t		*zptr;
24906 	conn_t		*connp = Q_TO_CONN(q);
24907 	zoneid_t	zoneid = connp->conn_zoneid;
24908 	tcp_t		*tcp = connp->conn_tcp;
24909 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24910 
24911 	iocp = (IOCP)mp->b_rptr;
24912 
24913 	if ((mp1 = mp->b_cont) == NULL ||
24914 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24915 		err = EINVAL;
24916 		goto out;
24917 	}
24918 
24919 	/* check permissions */
24920 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
24921 		err = EPERM;
24922 		goto out;
24923 	}
24924 
24925 	if (mp1->b_cont != NULL) {
24926 		freemsg(mp1->b_cont);
24927 		mp1->b_cont = NULL;
24928 	}
24929 
24930 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24931 	laf = acp->ac_local.ss_family;
24932 	raf = acp->ac_remote.ss_family;
24933 
24934 	/* check that a zone with the supplied zoneid exists */
24935 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24936 		zptr = zone_find_by_id(zoneid);
24937 		if (zptr != NULL) {
24938 			zone_rele(zptr);
24939 		} else {
24940 			err = EINVAL;
24941 			goto out;
24942 		}
24943 	}
24944 
24945 	/*
24946 	 * For exclusive stacks we set the zoneid to zero
24947 	 * to make TCP operate as if in the global zone.
24948 	 */
24949 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
24950 		acp->ac_zoneid = GLOBAL_ZONEID;
24951 
24952 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24953 	    acp->ac_start > acp->ac_end || laf != raf ||
24954 	    (laf != AF_INET && laf != AF_INET6)) {
24955 		err = EINVAL;
24956 		goto out;
24957 	}
24958 
24959 	tcp_ioctl_abort_dump(acp);
24960 	err = tcp_ioctl_abort(acp, tcps);
24961 
24962 out:
24963 	if (mp1 != NULL) {
24964 		freemsg(mp1);
24965 		mp->b_cont = NULL;
24966 	}
24967 
24968 	if (err != 0)
24969 		miocnak(q, mp, 0, err);
24970 	else
24971 		miocack(q, mp, 0, 0);
24972 }
24973 
24974 /*
24975  * tcp_time_wait_processing() handles processing of incoming packets when
24976  * the tcp is in the TIME_WAIT state.
24977  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24978  * on the time wait list.
24979  */
24980 void
24981 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24982     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24983 {
24984 	int32_t		bytes_acked;
24985 	int32_t		gap;
24986 	int32_t		rgap;
24987 	tcp_opt_t	tcpopt;
24988 	uint_t		flags;
24989 	uint32_t	new_swnd = 0;
24990 	conn_t		*connp;
24991 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24992 
24993 	BUMP_LOCAL(tcp->tcp_ibsegs);
24994 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
24995 
24996 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24997 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24998 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24999 	if (tcp->tcp_snd_ts_ok) {
25000 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25001 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25002 			    tcp->tcp_rnxt, TH_ACK);
25003 			goto done;
25004 		}
25005 	}
25006 	gap = seg_seq - tcp->tcp_rnxt;
25007 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25008 	if (gap < 0) {
25009 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25010 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25011 		    (seg_len > -gap ? -gap : seg_len));
25012 		seg_len += gap;
25013 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25014 			if (flags & TH_RST) {
25015 				goto done;
25016 			}
25017 			if ((flags & TH_FIN) && seg_len == -1) {
25018 				/*
25019 				 * When TCP receives a duplicate FIN in
25020 				 * TIME_WAIT state, restart the 2 MSL timer.
25021 				 * See page 73 in RFC 793. Make sure this TCP
25022 				 * is already on the TIME_WAIT list. If not,
25023 				 * just restart the timer.
25024 				 */
25025 				if (TCP_IS_DETACHED(tcp)) {
25026 					if (tcp_time_wait_remove(tcp, NULL) ==
25027 					    B_TRUE) {
25028 						tcp_time_wait_append(tcp);
25029 						TCP_DBGSTAT(tcps,
25030 						    tcp_rput_time_wait);
25031 					}
25032 				} else {
25033 					ASSERT(tcp != NULL);
25034 					TCP_TIMER_RESTART(tcp,
25035 					    tcps->tcps_time_wait_interval);
25036 				}
25037 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25038 				    tcp->tcp_rnxt, TH_ACK);
25039 				goto done;
25040 			}
25041 			flags |=  TH_ACK_NEEDED;
25042 			seg_len = 0;
25043 			goto process_ack;
25044 		}
25045 
25046 		/* Fix seg_seq, and chew the gap off the front. */
25047 		seg_seq = tcp->tcp_rnxt;
25048 	}
25049 
25050 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25051 		/*
25052 		 * Make sure that when we accept the connection, pick
25053 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25054 		 * old connection.
25055 		 *
25056 		 * The next ISS generated is equal to tcp_iss_incr_extra
25057 		 * + ISS_INCR/2 + other components depending on the
25058 		 * value of tcp_strong_iss.  We pre-calculate the new
25059 		 * ISS here and compare with tcp_snxt to determine if
25060 		 * we need to make adjustment to tcp_iss_incr_extra.
25061 		 *
25062 		 * The above calculation is ugly and is a
25063 		 * waste of CPU cycles...
25064 		 */
25065 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25066 		int32_t adj;
25067 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25068 
25069 		switch (tcps->tcps_strong_iss) {
25070 		case 2: {
25071 			/* Add time and MD5 components. */
25072 			uint32_t answer[4];
25073 			struct {
25074 				uint32_t ports;
25075 				in6_addr_t src;
25076 				in6_addr_t dst;
25077 			} arg;
25078 			MD5_CTX context;
25079 
25080 			mutex_enter(&tcps->tcps_iss_key_lock);
25081 			context = tcps->tcps_iss_key;
25082 			mutex_exit(&tcps->tcps_iss_key_lock);
25083 			arg.ports = tcp->tcp_ports;
25084 			/* We use MAPPED addresses in tcp_iss_init */
25085 			arg.src = tcp->tcp_ip_src_v6;
25086 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25087 				IN6_IPADDR_TO_V4MAPPED(
25088 				    tcp->tcp_ipha->ipha_dst,
25089 				    &arg.dst);
25090 			} else {
25091 				arg.dst =
25092 				    tcp->tcp_ip6h->ip6_dst;
25093 			}
25094 			MD5Update(&context, (uchar_t *)&arg,
25095 			    sizeof (arg));
25096 			MD5Final((uchar_t *)answer, &context);
25097 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25098 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25099 			break;
25100 		}
25101 		case 1:
25102 			/* Add time component and min random (i.e. 1). */
25103 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25104 			break;
25105 		default:
25106 			/* Add only time component. */
25107 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25108 			break;
25109 		}
25110 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25111 			/*
25112 			 * New ISS not guaranteed to be ISS_INCR/2
25113 			 * ahead of the current tcp_snxt, so add the
25114 			 * difference to tcp_iss_incr_extra.
25115 			 */
25116 			tcps->tcps_iss_incr_extra += adj;
25117 		}
25118 		/*
25119 		 * If tcp_clean_death() can not perform the task now,
25120 		 * drop the SYN packet and let the other side re-xmit.
25121 		 * Otherwise pass the SYN packet back in, since the
25122 		 * old tcp state has been cleaned up or freed.
25123 		 */
25124 		if (tcp_clean_death(tcp, 0, 27) == -1)
25125 			goto done;
25126 		/*
25127 		 * We will come back to tcp_rput_data
25128 		 * on the global queue. Packets destined
25129 		 * for the global queue will be checked
25130 		 * with global policy. But the policy for
25131 		 * this packet has already been checked as
25132 		 * this was destined for the detached
25133 		 * connection. We need to bypass policy
25134 		 * check this time by attaching a dummy
25135 		 * ipsec_in with ipsec_in_dont_check set.
25136 		 */
25137 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25138 		if (connp != NULL) {
25139 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25140 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25141 			return;
25142 		}
25143 		goto done;
25144 	}
25145 
25146 	/*
25147 	 * rgap is the amount of stuff received out of window.  A negative
25148 	 * value is the amount out of window.
25149 	 */
25150 	if (rgap < 0) {
25151 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25152 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
25153 		/* Fix seg_len and make sure there is something left. */
25154 		seg_len += rgap;
25155 		if (seg_len <= 0) {
25156 			if (flags & TH_RST) {
25157 				goto done;
25158 			}
25159 			flags |=  TH_ACK_NEEDED;
25160 			seg_len = 0;
25161 			goto process_ack;
25162 		}
25163 	}
25164 	/*
25165 	 * Check whether we can update tcp_ts_recent.  This test is
25166 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
25167 	 * Extensions for High Performance: An Update", Internet Draft.
25168 	 */
25169 	if (tcp->tcp_snd_ts_ok &&
25170 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
25171 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
25172 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
25173 		tcp->tcp_last_rcv_lbolt = lbolt64;
25174 	}
25175 
25176 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
25177 		/* Always ack out of order packets */
25178 		flags |= TH_ACK_NEEDED;
25179 		seg_len = 0;
25180 	} else if (seg_len > 0) {
25181 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
25182 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
25183 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
25184 	}
25185 	if (flags & TH_RST) {
25186 		(void) tcp_clean_death(tcp, 0, 28);
25187 		goto done;
25188 	}
25189 	if (flags & TH_SYN) {
25190 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
25191 		    TH_RST|TH_ACK);
25192 		/*
25193 		 * Do not delete the TCP structure if it is in
25194 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
25195 		 */
25196 		goto done;
25197 	}
25198 process_ack:
25199 	if (flags & TH_ACK) {
25200 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
25201 		if (bytes_acked <= 0) {
25202 			if (bytes_acked == 0 && seg_len == 0 &&
25203 			    new_swnd == tcp->tcp_swnd)
25204 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
25205 		} else {
25206 			/* Acks something not sent */
25207 			flags |= TH_ACK_NEEDED;
25208 		}
25209 	}
25210 	if (flags & TH_ACK_NEEDED) {
25211 		/*
25212 		 * Time to send an ack for some reason.
25213 		 */
25214 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25215 		    tcp->tcp_rnxt, TH_ACK);
25216 	}
25217 done:
25218 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25219 		DB_CKSUMSTART(mp) = 0;
25220 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
25221 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
25222 	}
25223 	freemsg(mp);
25224 }
25225 
25226 /*
25227  * TCP Timers Implementation.
25228  */
25229 timeout_id_t
25230 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25231 {
25232 	mblk_t *mp;
25233 	tcp_timer_t *tcpt;
25234 	tcp_t *tcp = connp->conn_tcp;
25235 
25236 	ASSERT(connp->conn_sqp != NULL);
25237 
25238 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
25239 
25240 	if (tcp->tcp_timercache == NULL) {
25241 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25242 	} else {
25243 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
25244 		mp = tcp->tcp_timercache;
25245 		tcp->tcp_timercache = mp->b_next;
25246 		mp->b_next = NULL;
25247 		ASSERT(mp->b_wptr == NULL);
25248 	}
25249 
25250 	CONN_INC_REF(connp);
25251 	tcpt = (tcp_timer_t *)mp->b_rptr;
25252 	tcpt->connp = connp;
25253 	tcpt->tcpt_proc = f;
25254 	/*
25255 	 * TCP timers are normal timeouts. Plus, they do not require more than
25256 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
25257 	 * rounding up the expiration to the next resolution boundary, we can
25258 	 * batch timers in the callout subsystem to make TCP timers more
25259 	 * efficient. The roundup also protects short timers from expiring too
25260 	 * early before they have a chance to be cancelled.
25261 	 */
25262 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
25263 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
25264 
25265 	return ((timeout_id_t)mp);
25266 }
25267 
25268 static void
25269 tcp_timer_callback(void *arg)
25270 {
25271 	mblk_t *mp = (mblk_t *)arg;
25272 	tcp_timer_t *tcpt;
25273 	conn_t	*connp;
25274 
25275 	tcpt = (tcp_timer_t *)mp->b_rptr;
25276 	connp = tcpt->connp;
25277 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
25278 	    SQ_FILL, SQTAG_TCP_TIMER);
25279 }
25280 
25281 static void
25282 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
25283 {
25284 	tcp_timer_t *tcpt;
25285 	conn_t *connp = (conn_t *)arg;
25286 	tcp_t *tcp = connp->conn_tcp;
25287 
25288 	tcpt = (tcp_timer_t *)mp->b_rptr;
25289 	ASSERT(connp == tcpt->connp);
25290 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
25291 
25292 	/*
25293 	 * If the TCP has reached the closed state, don't proceed any
25294 	 * further. This TCP logically does not exist on the system.
25295 	 * tcpt_proc could for example access queues, that have already
25296 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
25297 	 */
25298 	if (tcp->tcp_state != TCPS_CLOSED) {
25299 		(*tcpt->tcpt_proc)(connp);
25300 	} else {
25301 		tcp->tcp_timer_tid = 0;
25302 	}
25303 	tcp_timer_free(connp->conn_tcp, mp);
25304 }
25305 
25306 /*
25307  * There is potential race with untimeout and the handler firing at the same
25308  * time. The mblock may be freed by the handler while we are trying to use
25309  * it. But since both should execute on the same squeue, this race should not
25310  * occur.
25311  */
25312 clock_t
25313 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
25314 {
25315 	mblk_t	*mp = (mblk_t *)id;
25316 	tcp_timer_t *tcpt;
25317 	clock_t delta;
25318 
25319 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
25320 
25321 	if (mp == NULL)
25322 		return (-1);
25323 
25324 	tcpt = (tcp_timer_t *)mp->b_rptr;
25325 	ASSERT(tcpt->connp == connp);
25326 
25327 	delta = untimeout_default(tcpt->tcpt_tid, 0);
25328 
25329 	if (delta >= 0) {
25330 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
25331 		tcp_timer_free(connp->conn_tcp, mp);
25332 		CONN_DEC_REF(connp);
25333 	}
25334 
25335 	return (delta);
25336 }
25337 
25338 /*
25339  * Allocate space for the timer event. The allocation looks like mblk, but it is
25340  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25341  *
25342  * Dealing with failures: If we can't allocate from the timer cache we try
25343  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25344  * points to b_rptr.
25345  * If we can't allocate anything using allocb_tryhard(), we perform a last
25346  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25347  * save the actual allocation size in b_datap.
25348  */
25349 mblk_t *
25350 tcp_timermp_alloc(int kmflags)
25351 {
25352 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25353 	    kmflags & ~KM_PANIC);
25354 
25355 	if (mp != NULL) {
25356 		mp->b_next = mp->b_prev = NULL;
25357 		mp->b_rptr = (uchar_t *)(&mp[1]);
25358 		mp->b_wptr = NULL;
25359 		mp->b_datap = NULL;
25360 		mp->b_queue = NULL;
25361 		mp->b_cont = NULL;
25362 	} else if (kmflags & KM_PANIC) {
25363 		/*
25364 		 * Failed to allocate memory for the timer. Try allocating from
25365 		 * dblock caches.
25366 		 */
25367 		/* ipclassifier calls this from a constructor - hence no tcps */
25368 		TCP_G_STAT(tcp_timermp_allocfail);
25369 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25370 		if (mp == NULL) {
25371 			size_t size = 0;
25372 			/*
25373 			 * Memory is really low. Try tryhard allocation.
25374 			 *
25375 			 * ipclassifier calls this from a constructor -
25376 			 * hence no tcps
25377 			 */
25378 			TCP_G_STAT(tcp_timermp_allocdblfail);
25379 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25380 			    sizeof (tcp_timer_t), &size, kmflags);
25381 			mp->b_rptr = (uchar_t *)(&mp[1]);
25382 			mp->b_next = mp->b_prev = NULL;
25383 			mp->b_wptr = (uchar_t *)-1;
25384 			mp->b_datap = (dblk_t *)size;
25385 			mp->b_queue = NULL;
25386 			mp->b_cont = NULL;
25387 		}
25388 		ASSERT(mp->b_wptr != NULL);
25389 	}
25390 	/* ipclassifier calls this from a constructor - hence no tcps */
25391 	TCP_G_DBGSTAT(tcp_timermp_alloced);
25392 
25393 	return (mp);
25394 }
25395 
25396 /*
25397  * Free per-tcp timer cache.
25398  * It can only contain entries from tcp_timercache.
25399  */
25400 void
25401 tcp_timermp_free(tcp_t *tcp)
25402 {
25403 	mblk_t *mp;
25404 
25405 	while ((mp = tcp->tcp_timercache) != NULL) {
25406 		ASSERT(mp->b_wptr == NULL);
25407 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25408 		kmem_cache_free(tcp_timercache, mp);
25409 	}
25410 }
25411 
25412 /*
25413  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25414  * events there already (currently at most two events are cached).
25415  * If the event is not allocated from the timer cache, free it right away.
25416  */
25417 static void
25418 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25419 {
25420 	mblk_t *mp1 = tcp->tcp_timercache;
25421 
25422 	if (mp->b_wptr != NULL) {
25423 		/*
25424 		 * This allocation is not from a timer cache, free it right
25425 		 * away.
25426 		 */
25427 		if (mp->b_wptr != (uchar_t *)-1)
25428 			freeb(mp);
25429 		else
25430 			kmem_free(mp, (size_t)mp->b_datap);
25431 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25432 		/* Cache this timer block for future allocations */
25433 		mp->b_rptr = (uchar_t *)(&mp[1]);
25434 		mp->b_next = mp1;
25435 		tcp->tcp_timercache = mp;
25436 	} else {
25437 		kmem_cache_free(tcp_timercache, mp);
25438 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
25439 	}
25440 }
25441 
25442 /*
25443  * End of TCP Timers implementation.
25444  */
25445 
25446 /*
25447  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25448  * on the specified backing STREAMS q. Note, the caller may make the
25449  * decision to call based on the tcp_t.tcp_flow_stopped value which
25450  * when check outside the q's lock is only an advisory check ...
25451  */
25452 void
25453 tcp_setqfull(tcp_t *tcp)
25454 {
25455 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25456 	conn_t	*connp = tcp->tcp_connp;
25457 
25458 	if (tcp->tcp_closed)
25459 		return;
25460 
25461 	if (IPCL_IS_NONSTR(connp)) {
25462 		(*connp->conn_upcalls->su_txq_full)
25463 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
25464 		tcp->tcp_flow_stopped = B_TRUE;
25465 	} else {
25466 		queue_t *q = tcp->tcp_wq;
25467 
25468 		if (!(q->q_flag & QFULL)) {
25469 			mutex_enter(QLOCK(q));
25470 			if (!(q->q_flag & QFULL)) {
25471 				/* still need to set QFULL */
25472 				q->q_flag |= QFULL;
25473 				tcp->tcp_flow_stopped = B_TRUE;
25474 				mutex_exit(QLOCK(q));
25475 				TCP_STAT(tcps, tcp_flwctl_on);
25476 			} else {
25477 				mutex_exit(QLOCK(q));
25478 			}
25479 		}
25480 	}
25481 }
25482 
25483 void
25484 tcp_clrqfull(tcp_t *tcp)
25485 {
25486 	conn_t  *connp = tcp->tcp_connp;
25487 
25488 	if (tcp->tcp_closed)
25489 		return;
25490 
25491 	if (IPCL_IS_NONSTR(connp)) {
25492 		(*connp->conn_upcalls->su_txq_full)
25493 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
25494 		tcp->tcp_flow_stopped = B_FALSE;
25495 	} else {
25496 		queue_t *q = tcp->tcp_wq;
25497 
25498 		if (q->q_flag & QFULL) {
25499 			mutex_enter(QLOCK(q));
25500 			if (q->q_flag & QFULL) {
25501 				q->q_flag &= ~QFULL;
25502 				tcp->tcp_flow_stopped = B_FALSE;
25503 				mutex_exit(QLOCK(q));
25504 				if (q->q_flag & QWANTW)
25505 					qbackenable(q, 0);
25506 			} else {
25507 				mutex_exit(QLOCK(q));
25508 			}
25509 		}
25510 	}
25511 }
25512 
25513 /*
25514  * kstats related to squeues i.e. not per IP instance
25515  */
25516 static void *
25517 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
25518 {
25519 	kstat_t *ksp;
25520 
25521 	tcp_g_stat_t template = {
25522 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
25523 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
25524 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
25525 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
25526 	};
25527 
25528 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
25529 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25530 	    KSTAT_FLAG_VIRTUAL);
25531 
25532 	if (ksp == NULL)
25533 		return (NULL);
25534 
25535 	bcopy(&template, tcp_g_statp, sizeof (template));
25536 	ksp->ks_data = (void *)tcp_g_statp;
25537 
25538 	kstat_install(ksp);
25539 	return (ksp);
25540 }
25541 
25542 static void
25543 tcp_g_kstat_fini(kstat_t *ksp)
25544 {
25545 	if (ksp != NULL) {
25546 		kstat_delete(ksp);
25547 	}
25548 }
25549 
25550 
25551 static void *
25552 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
25553 {
25554 	kstat_t *ksp;
25555 
25556 	tcp_stat_t template = {
25557 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
25558 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
25559 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
25560 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
25561 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
25562 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
25563 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
25564 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
25565 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
25566 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
25567 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
25568 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
25569 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
25570 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
25571 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
25572 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
25573 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
25574 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
25575 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
25576 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
25577 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
25578 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
25579 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
25580 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
25581 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
25582 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
25583 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
25584 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
25585 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
25586 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
25587 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
25588 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
25589 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
25590 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
25591 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
25592 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
25593 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
25594 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
25595 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
25596 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
25597 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
25598 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
25599 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
25600 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
25601 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
25602 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
25603 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
25604 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
25605 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
25606 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
25607 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
25608 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
25609 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
25610 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
25611 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
25612 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
25613 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
25614 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
25615 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
25616 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
25617 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
25618 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
25619 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
25620 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
25621 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
25622 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
25623 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
25624 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
25625 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
25626 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
25627 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
25628 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
25629 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
25630 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
25631 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
25632 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
25633 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
25634 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
25635 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
25636 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
25637 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
25638 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
25639 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
25640 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
25641 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
25642 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
25643 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
25644 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
25645 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
25646 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
25647 	};
25648 
25649 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
25650 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25651 	    KSTAT_FLAG_VIRTUAL, stackid);
25652 
25653 	if (ksp == NULL)
25654 		return (NULL);
25655 
25656 	bcopy(&template, tcps_statisticsp, sizeof (template));
25657 	ksp->ks_data = (void *)tcps_statisticsp;
25658 	ksp->ks_private = (void *)(uintptr_t)stackid;
25659 
25660 	kstat_install(ksp);
25661 	return (ksp);
25662 }
25663 
25664 static void
25665 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
25666 {
25667 	if (ksp != NULL) {
25668 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25669 		kstat_delete_netstack(ksp, stackid);
25670 	}
25671 }
25672 
25673 /*
25674  * TCP Kstats implementation
25675  */
25676 static void *
25677 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
25678 {
25679 	kstat_t	*ksp;
25680 
25681 	tcp_named_kstat_t template = {
25682 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
25683 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
25684 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
25685 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
25686 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
25687 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
25688 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
25689 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
25690 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
25691 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
25692 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
25693 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
25694 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
25695 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
25696 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
25697 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
25698 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
25699 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
25700 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
25701 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
25702 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
25703 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
25704 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
25705 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
25706 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
25707 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
25708 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
25709 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
25710 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
25711 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
25712 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
25713 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
25714 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
25715 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
25716 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
25717 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
25718 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
25719 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
25720 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
25721 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
25722 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
25723 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
25724 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
25725 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
25726 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
25727 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
25728 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
25729 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
25730 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
25731 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
25732 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
25733 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
25734 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
25735 	};
25736 
25737 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
25738 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
25739 
25740 	if (ksp == NULL)
25741 		return (NULL);
25742 
25743 	template.rtoAlgorithm.value.ui32 = 4;
25744 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
25745 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
25746 	template.maxConn.value.i32 = -1;
25747 
25748 	bcopy(&template, ksp->ks_data, sizeof (template));
25749 	ksp->ks_update = tcp_kstat_update;
25750 	ksp->ks_private = (void *)(uintptr_t)stackid;
25751 
25752 	kstat_install(ksp);
25753 	return (ksp);
25754 }
25755 
25756 static void
25757 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
25758 {
25759 	if (ksp != NULL) {
25760 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25761 		kstat_delete_netstack(ksp, stackid);
25762 	}
25763 }
25764 
25765 static int
25766 tcp_kstat_update(kstat_t *kp, int rw)
25767 {
25768 	tcp_named_kstat_t *tcpkp;
25769 	tcp_t		*tcp;
25770 	connf_t		*connfp;
25771 	conn_t		*connp;
25772 	int 		i;
25773 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
25774 	netstack_t	*ns;
25775 	tcp_stack_t	*tcps;
25776 	ip_stack_t	*ipst;
25777 
25778 	if ((kp == NULL) || (kp->ks_data == NULL))
25779 		return (EIO);
25780 
25781 	if (rw == KSTAT_WRITE)
25782 		return (EACCES);
25783 
25784 	ns = netstack_find_by_stackid(stackid);
25785 	if (ns == NULL)
25786 		return (-1);
25787 	tcps = ns->netstack_tcp;
25788 	if (tcps == NULL) {
25789 		netstack_rele(ns);
25790 		return (-1);
25791 	}
25792 
25793 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25794 
25795 	tcpkp->currEstab.value.ui32 = 0;
25796 
25797 	ipst = ns->netstack_ip;
25798 
25799 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25800 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25801 		connp = NULL;
25802 		while ((connp =
25803 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25804 			tcp = connp->conn_tcp;
25805 			switch (tcp_snmp_state(tcp)) {
25806 			case MIB2_TCP_established:
25807 			case MIB2_TCP_closeWait:
25808 				tcpkp->currEstab.value.ui32++;
25809 				break;
25810 			}
25811 		}
25812 	}
25813 
25814 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
25815 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
25816 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
25817 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
25818 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
25819 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
25820 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
25821 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
25822 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
25823 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
25824 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
25825 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
25826 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
25827 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
25828 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
25829 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
25830 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
25831 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
25832 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
25833 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
25834 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
25835 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
25836 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
25837 	tcpkp->inDataInorderSegs.value.ui32 =
25838 	    tcps->tcps_mib.tcpInDataInorderSegs;
25839 	tcpkp->inDataInorderBytes.value.ui32 =
25840 	    tcps->tcps_mib.tcpInDataInorderBytes;
25841 	tcpkp->inDataUnorderSegs.value.ui32 =
25842 	    tcps->tcps_mib.tcpInDataUnorderSegs;
25843 	tcpkp->inDataUnorderBytes.value.ui32 =
25844 	    tcps->tcps_mib.tcpInDataUnorderBytes;
25845 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
25846 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
25847 	tcpkp->inDataPartDupSegs.value.ui32 =
25848 	    tcps->tcps_mib.tcpInDataPartDupSegs;
25849 	tcpkp->inDataPartDupBytes.value.ui32 =
25850 	    tcps->tcps_mib.tcpInDataPartDupBytes;
25851 	tcpkp->inDataPastWinSegs.value.ui32 =
25852 	    tcps->tcps_mib.tcpInDataPastWinSegs;
25853 	tcpkp->inDataPastWinBytes.value.ui32 =
25854 	    tcps->tcps_mib.tcpInDataPastWinBytes;
25855 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
25856 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
25857 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
25858 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
25859 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
25860 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
25861 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
25862 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
25863 	tcpkp->timKeepaliveProbe.value.ui32 =
25864 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
25865 	tcpkp->timKeepaliveDrop.value.ui32 =
25866 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
25867 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
25868 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
25869 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
25870 	tcpkp->outSackRetransSegs.value.ui32 =
25871 	    tcps->tcps_mib.tcpOutSackRetransSegs;
25872 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
25873 
25874 	netstack_rele(ns);
25875 	return (0);
25876 }
25877 
25878 void
25879 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25880 {
25881 	uint16_t	hdr_len;
25882 	ipha_t		*ipha;
25883 	uint8_t		*nexthdrp;
25884 	tcph_t		*tcph;
25885 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
25886 
25887 	/* Already has an eager */
25888 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25889 		TCP_STAT(tcps, tcp_reinput_syn);
25890 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25891 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
25892 		return;
25893 	}
25894 
25895 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25896 	case IPV4_VERSION:
25897 		ipha = (ipha_t *)mp->b_rptr;
25898 		hdr_len = IPH_HDR_LENGTH(ipha);
25899 		break;
25900 	case IPV6_VERSION:
25901 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25902 		    &hdr_len, &nexthdrp)) {
25903 			CONN_DEC_REF(connp);
25904 			freemsg(mp);
25905 			return;
25906 		}
25907 		break;
25908 	}
25909 
25910 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25911 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25912 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25913 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
25914 	}
25915 
25916 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25917 	    SQ_FILL, SQTAG_TCP_REINPUT);
25918 }
25919 
25920 static int
25921 tcp_squeue_switch(int val)
25922 {
25923 	int rval = SQ_FILL;
25924 
25925 	switch (val) {
25926 	case 1:
25927 		rval = SQ_NODRAIN;
25928 		break;
25929 	case 2:
25930 		rval = SQ_PROCESS;
25931 		break;
25932 	default:
25933 		break;
25934 	}
25935 	return (rval);
25936 }
25937 
25938 /*
25939  * This is called once for each squeue - globally for all stack
25940  * instances.
25941  */
25942 static void
25943 tcp_squeue_add(squeue_t *sqp)
25944 {
25945 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25946 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
25947 
25948 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25949 	tcp_time_wait->tcp_time_wait_tid =
25950 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
25951 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
25952 	    CALLOUT_FLAG_ROUNDUP);
25953 	if (tcp_free_list_max_cnt == 0) {
25954 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
25955 		    max_ncpus : boot_max_ncpus);
25956 
25957 		/*
25958 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
25959 		 */
25960 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
25961 		    (tcp_ncpus * sizeof (tcp_t) * 100);
25962 	}
25963 	tcp_time_wait->tcp_free_list_cnt = 0;
25964 }
25965 
25966 static int
25967 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error, cred_t *cr, pid_t pid)
25968 {
25969 	mblk_t	*ire_mp = NULL;
25970 	mblk_t	*syn_mp;
25971 	mblk_t	*mdti;
25972 	mblk_t	*lsoi;
25973 	int	retval;
25974 	tcph_t	*tcph;
25975 	uint32_t	mss;
25976 	queue_t	*q = tcp->tcp_rq;
25977 	conn_t	*connp = tcp->tcp_connp;
25978 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25979 
25980 	if (error == 0) {
25981 		/*
25982 		 * Adapt Multidata information, if any.  The
25983 		 * following tcp_mdt_update routine will free
25984 		 * the message.
25985 		 */
25986 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
25987 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
25988 			    b_rptr)->mdt_capab, B_TRUE);
25989 			freemsg(mdti);
25990 		}
25991 
25992 		/*
25993 		 * Check to update LSO information with tcp, and
25994 		 * tcp_lso_update routine will free the message.
25995 		 */
25996 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
25997 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
25998 			    b_rptr)->lso_capab);
25999 			freemsg(lsoi);
26000 		}
26001 
26002 		/* Get the IRE, if we had requested for it */
26003 		if (mp != NULL)
26004 			ire_mp = tcp_ire_mp(&mp);
26005 
26006 		if (tcp->tcp_hard_binding) {
26007 			tcp->tcp_hard_binding = B_FALSE;
26008 			tcp->tcp_hard_bound = B_TRUE;
26009 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
26010 			if (retval != 0) {
26011 				error = EADDRINUSE;
26012 				goto bind_failed;
26013 			}
26014 		} else {
26015 			if (ire_mp != NULL)
26016 				freeb(ire_mp);
26017 			goto after_syn_sent;
26018 		}
26019 
26020 		retval = tcp_adapt_ire(tcp, ire_mp);
26021 		if (ire_mp != NULL)
26022 			freeb(ire_mp);
26023 		if (retval == 0) {
26024 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
26025 			    ENETUNREACH : EADDRNOTAVAIL);
26026 			goto ipcl_rm;
26027 		}
26028 		/*
26029 		 * Don't let an endpoint connect to itself.
26030 		 * Also checked in tcp_connect() but that
26031 		 * check can't handle the case when the
26032 		 * local IP address is INADDR_ANY.
26033 		 */
26034 		if (tcp->tcp_ipversion == IPV4_VERSION) {
26035 			if ((tcp->tcp_ipha->ipha_dst ==
26036 			    tcp->tcp_ipha->ipha_src) &&
26037 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26038 			    tcp->tcp_tcph->th_fport))) {
26039 				error = EADDRNOTAVAIL;
26040 				goto ipcl_rm;
26041 			}
26042 		} else {
26043 			if (IN6_ARE_ADDR_EQUAL(
26044 			    &tcp->tcp_ip6h->ip6_dst,
26045 			    &tcp->tcp_ip6h->ip6_src) &&
26046 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26047 			    tcp->tcp_tcph->th_fport))) {
26048 				error = EADDRNOTAVAIL;
26049 				goto ipcl_rm;
26050 			}
26051 		}
26052 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
26053 		/*
26054 		 * This should not be possible!  Just for
26055 		 * defensive coding...
26056 		 */
26057 		if (tcp->tcp_state != TCPS_SYN_SENT)
26058 			goto after_syn_sent;
26059 
26060 		if (is_system_labeled() &&
26061 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
26062 			error = EHOSTUNREACH;
26063 			goto ipcl_rm;
26064 		}
26065 
26066 		/*
26067 		 * tcp_adapt_ire() does not adjust
26068 		 * for TCP/IP header length.
26069 		 */
26070 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
26071 
26072 		/*
26073 		 * Just make sure our rwnd is at
26074 		 * least tcp_recv_hiwat_mss * MSS
26075 		 * large, and round up to the nearest
26076 		 * MSS.
26077 		 *
26078 		 * We do the round up here because
26079 		 * we need to get the interface
26080 		 * MTU first before we can do the
26081 		 * round up.
26082 		 */
26083 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
26084 		    tcps->tcps_recv_hiwat_minmss * mss);
26085 		if (!IPCL_IS_NONSTR(connp))
26086 			q->q_hiwat = tcp->tcp_rwnd;
26087 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
26088 		tcp_set_ws_value(tcp);
26089 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
26090 		    tcp->tcp_tcph->th_win);
26091 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
26092 			tcp->tcp_snd_ws_ok = B_TRUE;
26093 
26094 		/*
26095 		 * Set tcp_snd_ts_ok to true
26096 		 * so that tcp_xmit_mp will
26097 		 * include the timestamp
26098 		 * option in the SYN segment.
26099 		 */
26100 		if (tcps->tcps_tstamp_always ||
26101 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
26102 			tcp->tcp_snd_ts_ok = B_TRUE;
26103 		}
26104 
26105 		/*
26106 		 * tcp_snd_sack_ok can be set in
26107 		 * tcp_adapt_ire() if the sack metric
26108 		 * is set.  So check it here also.
26109 		 */
26110 		if (tcps->tcps_sack_permitted == 2 ||
26111 		    tcp->tcp_snd_sack_ok) {
26112 			if (tcp->tcp_sack_info == NULL) {
26113 				tcp->tcp_sack_info =
26114 				    kmem_cache_alloc(tcp_sack_info_cache,
26115 				    KM_SLEEP);
26116 			}
26117 			tcp->tcp_snd_sack_ok = B_TRUE;
26118 		}
26119 
26120 		/*
26121 		 * Should we use ECN?  Note that the current
26122 		 * default value (SunOS 5.9) of tcp_ecn_permitted
26123 		 * is 1.  The reason for doing this is that there
26124 		 * are equipments out there that will drop ECN
26125 		 * enabled IP packets.  Setting it to 1 avoids
26126 		 * compatibility problems.
26127 		 */
26128 		if (tcps->tcps_ecn_permitted == 2)
26129 			tcp->tcp_ecn_ok = B_TRUE;
26130 
26131 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
26132 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
26133 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
26134 		if (syn_mp) {
26135 			if (cr == NULL) {
26136 				cr = tcp->tcp_cred;
26137 				pid = tcp->tcp_cpid;
26138 			}
26139 			mblk_setcred(syn_mp, cr, pid);
26140 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
26141 		}
26142 	after_syn_sent:
26143 		if (mp != NULL) {
26144 			ASSERT(mp->b_cont == NULL);
26145 			freeb(mp);
26146 		}
26147 		return (error);
26148 	} else {
26149 		/* error */
26150 		if (tcp->tcp_debug) {
26151 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
26152 			    "tcp_post_ip_bind: error == %d", error);
26153 		}
26154 		if (mp != NULL) {
26155 			freeb(mp);
26156 		}
26157 	}
26158 
26159 ipcl_rm:
26160 	/*
26161 	 * Need to unbind with classifier since we were just
26162 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
26163 	 */
26164 	tcp->tcp_hard_bound = B_FALSE;
26165 	tcp->tcp_hard_binding = B_FALSE;
26166 
26167 	ipcl_hash_remove(connp);
26168 
26169 bind_failed:
26170 	tcp->tcp_state = TCPS_IDLE;
26171 	if (tcp->tcp_ipversion == IPV4_VERSION)
26172 		tcp->tcp_ipha->ipha_src = 0;
26173 	else
26174 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
26175 	/*
26176 	 * Copy of the src addr. in tcp_t is needed since
26177 	 * the lookup funcs. can only look at tcp_t
26178 	 */
26179 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
26180 
26181 	tcph = tcp->tcp_tcph;
26182 	tcph->th_lport[0] = 0;
26183 	tcph->th_lport[1] = 0;
26184 	tcp_bind_hash_remove(tcp);
26185 	bzero(&connp->u_port, sizeof (connp->u_port));
26186 	/* blow away saved option results if any */
26187 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26188 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26189 
26190 	conn_delete_ire(tcp->tcp_connp, NULL);
26191 
26192 	return (error);
26193 }
26194 
26195 static int
26196 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
26197     boolean_t bind_to_req_port_only, cred_t *cr)
26198 {
26199 	in_port_t	mlp_port;
26200 	mlp_type_t 	addrtype, mlptype;
26201 	boolean_t	user_specified;
26202 	in_port_t	allocated_port;
26203 	in_port_t	requested_port = *requested_port_ptr;
26204 	conn_t		*connp;
26205 	zone_t		*zone;
26206 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26207 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
26208 
26209 	/*
26210 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
26211 	 */
26212 	if (cr == NULL)
26213 		cr = tcp->tcp_cred;
26214 	/*
26215 	 * Get a valid port (within the anonymous range and should not
26216 	 * be a privileged one) to use if the user has not given a port.
26217 	 * If multiple threads are here, they may all start with
26218 	 * with the same initial port. But, it should be fine as long as
26219 	 * tcp_bindi will ensure that no two threads will be assigned
26220 	 * the same port.
26221 	 *
26222 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
26223 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
26224 	 * unless TCP_ANONPRIVBIND option is set.
26225 	 */
26226 	mlptype = mlptSingle;
26227 	mlp_port = requested_port;
26228 	if (requested_port == 0) {
26229 		requested_port = tcp->tcp_anon_priv_bind ?
26230 		    tcp_get_next_priv_port(tcp) :
26231 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
26232 		    tcp, B_TRUE);
26233 		if (requested_port == 0) {
26234 			return (-TNOADDR);
26235 		}
26236 		user_specified = B_FALSE;
26237 
26238 		/*
26239 		 * If the user went through one of the RPC interfaces to create
26240 		 * this socket and RPC is MLP in this zone, then give him an
26241 		 * anonymous MLP.
26242 		 */
26243 		connp = tcp->tcp_connp;
26244 		if (connp->conn_anon_mlp && is_system_labeled()) {
26245 			zone = crgetzone(cr);
26246 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26247 			    IPV6_VERSION, &v6addr,
26248 			    tcps->tcps_netstack->netstack_ip);
26249 			if (addrtype == mlptSingle) {
26250 				return (-TNOADDR);
26251 			}
26252 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26253 			    PMAPPORT, addrtype);
26254 			mlp_port = PMAPPORT;
26255 		}
26256 	} else {
26257 		int i;
26258 		boolean_t priv = B_FALSE;
26259 
26260 		/*
26261 		 * If the requested_port is in the well-known privileged range,
26262 		 * verify that the stream was opened by a privileged user.
26263 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
26264 		 * but instead the code relies on:
26265 		 * - the fact that the address of the array and its size never
26266 		 *   changes
26267 		 * - the atomic assignment of the elements of the array
26268 		 */
26269 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
26270 			priv = B_TRUE;
26271 		} else {
26272 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
26273 				if (requested_port ==
26274 				    tcps->tcps_g_epriv_ports[i]) {
26275 					priv = B_TRUE;
26276 					break;
26277 				}
26278 			}
26279 		}
26280 		if (priv) {
26281 			if (secpolicy_net_privaddr(cr, requested_port,
26282 			    IPPROTO_TCP) != 0) {
26283 				if (tcp->tcp_debug) {
26284 					(void) strlog(TCP_MOD_ID, 0, 1,
26285 					    SL_ERROR|SL_TRACE,
26286 					    "tcp_bind: no priv for port %d",
26287 					    requested_port);
26288 				}
26289 				return (-TACCES);
26290 			}
26291 		}
26292 		user_specified = B_TRUE;
26293 
26294 		connp = tcp->tcp_connp;
26295 		if (is_system_labeled()) {
26296 			zone = crgetzone(cr);
26297 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26298 			    IPV6_VERSION, &v6addr,
26299 			    tcps->tcps_netstack->netstack_ip);
26300 			if (addrtype == mlptSingle) {
26301 				return (-TNOADDR);
26302 			}
26303 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26304 			    requested_port, addrtype);
26305 		}
26306 	}
26307 
26308 	if (mlptype != mlptSingle) {
26309 		if (secpolicy_net_bindmlp(cr) != 0) {
26310 			if (tcp->tcp_debug) {
26311 				(void) strlog(TCP_MOD_ID, 0, 1,
26312 				    SL_ERROR|SL_TRACE,
26313 				    "tcp_bind: no priv for multilevel port %d",
26314 				    requested_port);
26315 			}
26316 			return (-TACCES);
26317 		}
26318 
26319 		/*
26320 		 * If we're specifically binding a shared IP address and the
26321 		 * port is MLP on shared addresses, then check to see if this
26322 		 * zone actually owns the MLP.  Reject if not.
26323 		 */
26324 		if (mlptype == mlptShared && addrtype == mlptShared) {
26325 			/*
26326 			 * No need to handle exclusive-stack zones since
26327 			 * ALL_ZONES only applies to the shared stack.
26328 			 */
26329 			zoneid_t mlpzone;
26330 
26331 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26332 			    htons(mlp_port));
26333 			if (connp->conn_zoneid != mlpzone) {
26334 				if (tcp->tcp_debug) {
26335 					(void) strlog(TCP_MOD_ID, 0, 1,
26336 					    SL_ERROR|SL_TRACE,
26337 					    "tcp_bind: attempt to bind port "
26338 					    "%d on shared addr in zone %d "
26339 					    "(should be %d)",
26340 					    mlp_port, connp->conn_zoneid,
26341 					    mlpzone);
26342 				}
26343 				return (-TACCES);
26344 			}
26345 		}
26346 
26347 		if (!user_specified) {
26348 			int err;
26349 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26350 			    requested_port, B_TRUE);
26351 			if (err != 0) {
26352 				if (tcp->tcp_debug) {
26353 					(void) strlog(TCP_MOD_ID, 0, 1,
26354 					    SL_ERROR|SL_TRACE,
26355 					    "tcp_bind: cannot establish anon "
26356 					    "MLP for port %d",
26357 					    requested_port);
26358 				}
26359 				return (err);
26360 			}
26361 			connp->conn_anon_port = B_TRUE;
26362 		}
26363 		connp->conn_mlp_type = mlptype;
26364 	}
26365 
26366 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26367 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26368 
26369 	if (allocated_port == 0) {
26370 		connp->conn_mlp_type = mlptSingle;
26371 		if (connp->conn_anon_port) {
26372 			connp->conn_anon_port = B_FALSE;
26373 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26374 			    requested_port, B_FALSE);
26375 		}
26376 		if (bind_to_req_port_only) {
26377 			if (tcp->tcp_debug) {
26378 				(void) strlog(TCP_MOD_ID, 0, 1,
26379 				    SL_ERROR|SL_TRACE,
26380 				    "tcp_bind: requested addr busy");
26381 			}
26382 			return (-TADDRBUSY);
26383 		} else {
26384 			/* If we are out of ports, fail the bind. */
26385 			if (tcp->tcp_debug) {
26386 				(void) strlog(TCP_MOD_ID, 0, 1,
26387 				    SL_ERROR|SL_TRACE,
26388 				    "tcp_bind: out of ports?");
26389 			}
26390 			return (-TNOADDR);
26391 		}
26392 	}
26393 
26394 	/* Pass the allocated port back */
26395 	*requested_port_ptr = allocated_port;
26396 	return (0);
26397 }
26398 
26399 static int
26400 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26401     boolean_t bind_to_req_port_only)
26402 {
26403 	tcp_t	*tcp = connp->conn_tcp;
26404 	sin_t	*sin;
26405 	sin6_t  *sin6;
26406 	sin6_t	sin6addr;
26407 	in_port_t requested_port;
26408 	ipaddr_t	v4addr;
26409 	in6_addr_t	v6addr;
26410 	uint_t	origipversion;
26411 	int	error = 0;
26412 
26413 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
26414 
26415 	if (tcp->tcp_state == TCPS_BOUND) {
26416 		return (0);
26417 	} else if (tcp->tcp_state > TCPS_BOUND) {
26418 		if (tcp->tcp_debug) {
26419 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26420 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26421 		}
26422 		return (-TOUTSTATE);
26423 	}
26424 	origipversion = tcp->tcp_ipversion;
26425 
26426 	if (sa != NULL && !OK_32PTR((char *)sa)) {
26427 		if (tcp->tcp_debug) {
26428 			(void) strlog(TCP_MOD_ID, 0, 1,
26429 			    SL_ERROR|SL_TRACE,
26430 			    "tcp_bind: bad address parameter, "
26431 			    "address %p, len %d",
26432 			    (void *)sa, len);
26433 		}
26434 		return (-TPROTO);
26435 	}
26436 
26437 	switch (len) {
26438 	case 0:		/* request for a generic port */
26439 		if (tcp->tcp_family == AF_INET) {
26440 			sin = (sin_t *)&sin6addr;
26441 			*sin = sin_null;
26442 			sin->sin_family = AF_INET;
26443 			tcp->tcp_ipversion = IPV4_VERSION;
26444 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
26445 		} else {
26446 			ASSERT(tcp->tcp_family == AF_INET6);
26447 			sin6 = (sin6_t *)&sin6addr;
26448 			*sin6 = sin6_null;
26449 			sin6->sin6_family = AF_INET6;
26450 			tcp->tcp_ipversion = IPV6_VERSION;
26451 			V6_SET_ZERO(v6addr);
26452 		}
26453 		requested_port = 0;
26454 		break;
26455 
26456 	case sizeof (sin_t):	/* Complete IPv4 address */
26457 		sin = (sin_t *)sa;
26458 		/*
26459 		 * With sockets sockfs will accept bogus sin_family in
26460 		 * bind() and replace it with the family used in the socket
26461 		 * call.
26462 		 */
26463 		if (sin->sin_family != AF_INET ||
26464 		    tcp->tcp_family != AF_INET) {
26465 			return (EAFNOSUPPORT);
26466 		}
26467 		requested_port = ntohs(sin->sin_port);
26468 		tcp->tcp_ipversion = IPV4_VERSION;
26469 		v4addr = sin->sin_addr.s_addr;
26470 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
26471 		break;
26472 
26473 	case sizeof (sin6_t): /* Complete IPv6 address */
26474 		sin6 = (sin6_t *)sa;
26475 		if (sin6->sin6_family != AF_INET6 ||
26476 		    tcp->tcp_family != AF_INET6) {
26477 			return (EAFNOSUPPORT);
26478 		}
26479 		requested_port = ntohs(sin6->sin6_port);
26480 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
26481 		    IPV4_VERSION : IPV6_VERSION;
26482 		v6addr = sin6->sin6_addr;
26483 		break;
26484 
26485 	default:
26486 		if (tcp->tcp_debug) {
26487 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26488 			    "tcp_bind: bad address length, %d", len);
26489 		}
26490 		return (EAFNOSUPPORT);
26491 		/* return (-TBADADDR); */
26492 	}
26493 
26494 	tcp->tcp_bound_source_v6 = v6addr;
26495 
26496 	/* Check for change in ipversion */
26497 	if (origipversion != tcp->tcp_ipversion) {
26498 		ASSERT(tcp->tcp_family == AF_INET6);
26499 		error = tcp->tcp_ipversion == IPV6_VERSION ?
26500 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
26501 		if (error) {
26502 			return (ENOMEM);
26503 		}
26504 	}
26505 
26506 	/*
26507 	 * Initialize family specific fields. Copy of the src addr.
26508 	 * in tcp_t is needed for the lookup funcs.
26509 	 */
26510 	if (tcp->tcp_ipversion == IPV6_VERSION) {
26511 		tcp->tcp_ip6h->ip6_src = v6addr;
26512 	} else {
26513 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
26514 	}
26515 	tcp->tcp_ip_src_v6 = v6addr;
26516 
26517 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
26518 
26519 	error = tcp_bind_select_lport(tcp, &requested_port,
26520 	    bind_to_req_port_only, cr);
26521 
26522 	return (error);
26523 }
26524 
26525 /*
26526  * Return unix error is tli error is TSYSERR, otherwise return a negative
26527  * tli error.
26528  */
26529 int
26530 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26531     boolean_t bind_to_req_port_only)
26532 {
26533 	int error;
26534 	tcp_t *tcp = connp->conn_tcp;
26535 
26536 	if (tcp->tcp_state >= TCPS_BOUND) {
26537 		if (tcp->tcp_debug) {
26538 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26539 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26540 		}
26541 		return (-TOUTSTATE);
26542 	}
26543 
26544 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
26545 	if (error != 0)
26546 		return (error);
26547 
26548 	ASSERT(tcp->tcp_state == TCPS_BOUND);
26549 
26550 	tcp->tcp_conn_req_max = 0;
26551 
26552 	/*
26553 	 * We need to make sure that the conn_recv is set to a non-null
26554 	 * value before we insert the conn into the classifier table.
26555 	 * This is to avoid a race with an incoming packet which does an
26556 	 * ipcl_classify().
26557 	 */
26558 	connp->conn_recv = tcp_conn_request;
26559 
26560 	if (tcp->tcp_family == AF_INET6) {
26561 		ASSERT(tcp->tcp_connp->conn_af_isv6);
26562 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
26563 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
26564 	} else {
26565 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
26566 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
26567 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
26568 	}
26569 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
26570 }
26571 
26572 int
26573 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
26574     socklen_t len, cred_t *cr)
26575 {
26576 	int 		error;
26577 	conn_t		*connp = (conn_t *)proto_handle;
26578 	squeue_t	*sqp = connp->conn_sqp;
26579 
26580 	/* All Solaris components should pass a cred for this operation. */
26581 	ASSERT(cr != NULL);
26582 
26583 	ASSERT(sqp != NULL);
26584 	ASSERT(connp->conn_upper_handle != NULL);
26585 
26586 	error = squeue_synch_enter(sqp, connp, 0);
26587 	if (error != 0) {
26588 		/* failed to enter */
26589 		return (ENOSR);
26590 	}
26591 
26592 	/* binding to a NULL address really means unbind */
26593 	if (sa == NULL) {
26594 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
26595 			error = tcp_do_unbind(connp);
26596 		else
26597 			error = EINVAL;
26598 	} else {
26599 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
26600 	}
26601 
26602 	squeue_synch_exit(sqp, connp);
26603 
26604 	if (error < 0) {
26605 		if (error == -TOUTSTATE)
26606 			error = EINVAL;
26607 		else
26608 			error = proto_tlitosyserr(-error);
26609 	}
26610 
26611 	return (error);
26612 }
26613 
26614 /*
26615  * If the return value from this function is positive, it's a UNIX error.
26616  * Otherwise, if it's negative, then the absolute value is a TLI error.
26617  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
26618  */
26619 int
26620 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
26621     cred_t *cr, pid_t pid)
26622 {
26623 	tcp_t		*tcp = connp->conn_tcp;
26624 	sin_t		*sin = (sin_t *)sa;
26625 	sin6_t		*sin6 = (sin6_t *)sa;
26626 	ipaddr_t	*dstaddrp;
26627 	in_port_t	dstport;
26628 	uint_t		srcid;
26629 	int		error = 0;
26630 
26631 	switch (len) {
26632 	default:
26633 		/*
26634 		 * Should never happen
26635 		 */
26636 		return (EINVAL);
26637 
26638 	case sizeof (sin_t):
26639 		sin = (sin_t *)sa;
26640 		if (sin->sin_port == 0) {
26641 			return (-TBADADDR);
26642 		}
26643 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
26644 			return (EAFNOSUPPORT);
26645 		}
26646 		break;
26647 
26648 	case sizeof (sin6_t):
26649 		sin6 = (sin6_t *)sa;
26650 		if (sin6->sin6_port == 0) {
26651 			return (-TBADADDR);
26652 		}
26653 		break;
26654 	}
26655 	/*
26656 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
26657 	 * make sure that the template IP header in the tcp structure is an
26658 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
26659 	 * need to this before we call tcp_bindi() so that the port lookup
26660 	 * code will look for ports in the correct port space (IPv4 and
26661 	 * IPv6 have separate port spaces).
26662 	 */
26663 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
26664 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26665 		int err = 0;
26666 
26667 		err = tcp_header_init_ipv4(tcp);
26668 			if (err != 0) {
26669 				error = ENOMEM;
26670 				goto connect_failed;
26671 			}
26672 		if (tcp->tcp_lport != 0)
26673 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
26674 	}
26675 
26676 	switch (tcp->tcp_state) {
26677 	case TCPS_LISTEN:
26678 		/*
26679 		 * Listening sockets are not allowed to issue connect().
26680 		 */
26681 		if (IPCL_IS_NONSTR(connp))
26682 			return (EOPNOTSUPP);
26683 		/* FALLTHRU */
26684 	case TCPS_IDLE:
26685 		/*
26686 		 * We support quick connect, refer to comments in
26687 		 * tcp_connect_*()
26688 		 */
26689 		/* FALLTHRU */
26690 	case TCPS_BOUND:
26691 		/*
26692 		 * We must bump the generation before the operation start.
26693 		 * This is done to ensure that any upcall made later on sends
26694 		 * up the right generation to the socket.
26695 		 */
26696 		SOCK_CONNID_BUMP(tcp->tcp_connid);
26697 
26698 		if (tcp->tcp_family == AF_INET6) {
26699 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26700 				return (tcp_connect_ipv6(tcp,
26701 				    &sin6->sin6_addr,
26702 				    sin6->sin6_port, sin6->sin6_flowinfo,
26703 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
26704 				    cr, pid));
26705 			}
26706 			/*
26707 			 * Destination adress is mapped IPv6 address.
26708 			 * Source bound address should be unspecified or
26709 			 * IPv6 mapped address as well.
26710 			 */
26711 			if (!IN6_IS_ADDR_UNSPECIFIED(
26712 			    &tcp->tcp_bound_source_v6) &&
26713 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
26714 				return (EADDRNOTAVAIL);
26715 			}
26716 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
26717 			dstport = sin6->sin6_port;
26718 			srcid = sin6->__sin6_src_id;
26719 		} else {
26720 			dstaddrp = &sin->sin_addr.s_addr;
26721 			dstport = sin->sin_port;
26722 			srcid = 0;
26723 		}
26724 
26725 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
26726 		    pid);
26727 		break;
26728 	default:
26729 		return (-TOUTSTATE);
26730 	}
26731 	/*
26732 	 * Note: Code below is the "failure" case
26733 	 */
26734 connect_failed:
26735 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26736 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26737 	return (error);
26738 }
26739 
26740 int
26741 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
26742     socklen_t len, sock_connid_t *id, cred_t *cr)
26743 {
26744 	conn_t		*connp = (conn_t *)proto_handle;
26745 	tcp_t		*tcp = connp->conn_tcp;
26746 	squeue_t	*sqp = connp->conn_sqp;
26747 	int		error;
26748 
26749 	ASSERT(connp->conn_upper_handle != NULL);
26750 
26751 	/* All Solaris components should pass a cred for this operation. */
26752 	ASSERT(cr != NULL);
26753 
26754 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
26755 	if (error != 0) {
26756 		return (error);
26757 	}
26758 
26759 	error = squeue_synch_enter(sqp, connp, 0);
26760 	if (error != 0) {
26761 		/* failed to enter */
26762 		return (ENOSR);
26763 	}
26764 
26765 	/*
26766 	 * TCP supports quick connect, so no need to do an implicit bind
26767 	 */
26768 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
26769 	if (error == 0) {
26770 		*id = connp->conn_tcp->tcp_connid;
26771 	} else if (error < 0) {
26772 		if (error == -TOUTSTATE) {
26773 			switch (connp->conn_tcp->tcp_state) {
26774 			case TCPS_SYN_SENT:
26775 				error = EALREADY;
26776 				break;
26777 			case TCPS_ESTABLISHED:
26778 				error = EISCONN;
26779 				break;
26780 			case TCPS_LISTEN:
26781 				error = EOPNOTSUPP;
26782 				break;
26783 			default:
26784 				error = EINVAL;
26785 				break;
26786 			}
26787 		} else {
26788 			error = proto_tlitosyserr(-error);
26789 		}
26790 	}
26791 done:
26792 	squeue_synch_exit(sqp, connp);
26793 
26794 	return ((error == 0) ? EINPROGRESS : error);
26795 }
26796 
26797 /* ARGSUSED */
26798 sock_lower_handle_t
26799 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
26800     uint_t *smodep, int *errorp, int flags, cred_t *credp)
26801 {
26802 	conn_t		*connp;
26803 	boolean_t	isv6 = family == AF_INET6;
26804 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
26805 	    (proto != 0 && proto != IPPROTO_TCP)) {
26806 		*errorp = EPROTONOSUPPORT;
26807 		return (NULL);
26808 	}
26809 
26810 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
26811 	if (connp == NULL) {
26812 		return (NULL);
26813 	}
26814 
26815 	/*
26816 	 * Put the ref for TCP. Ref for IP was already put
26817 	 * by ipcl_conn_create. Also Make the conn_t globally
26818 	 * visible to walkers
26819 	 */
26820 	mutex_enter(&connp->conn_lock);
26821 	CONN_INC_REF_LOCKED(connp);
26822 	ASSERT(connp->conn_ref == 2);
26823 	connp->conn_state_flags &= ~CONN_INCIPIENT;
26824 
26825 	connp->conn_flags |= IPCL_NONSTR;
26826 	mutex_exit(&connp->conn_lock);
26827 
26828 	ASSERT(errorp != NULL);
26829 	*errorp = 0;
26830 	*sock_downcalls = &sock_tcp_downcalls;
26831 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
26832 	    SM_SENDFILESUPP;
26833 
26834 	return ((sock_lower_handle_t)connp);
26835 }
26836 
26837 /* ARGSUSED */
26838 void
26839 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
26840     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
26841 {
26842 	conn_t *connp = (conn_t *)proto_handle;
26843 	struct sock_proto_props sopp;
26844 
26845 	ASSERT(connp->conn_upper_handle == NULL);
26846 
26847 	/* All Solaris components should pass a cred for this operation. */
26848 	ASSERT(cr != NULL);
26849 
26850 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
26851 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
26852 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
26853 
26854 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
26855 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
26856 	sopp.sopp_maxpsz = INFPSZ;
26857 	sopp.sopp_maxblk = INFPSZ;
26858 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
26859 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
26860 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
26861 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
26862 	    tcp_rinfo.mi_minpsz;
26863 
26864 	connp->conn_upcalls = sock_upcalls;
26865 	connp->conn_upper_handle = sock_handle;
26866 
26867 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
26868 }
26869 
26870 /* ARGSUSED */
26871 int
26872 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
26873 {
26874 	conn_t *connp = (conn_t *)proto_handle;
26875 
26876 	ASSERT(connp->conn_upper_handle != NULL);
26877 
26878 	/* All Solaris components should pass a cred for this operation. */
26879 	ASSERT(cr != NULL);
26880 
26881 	tcp_close_common(connp, flags);
26882 
26883 	ip_free_helper_stream(connp);
26884 
26885 	/*
26886 	 * Drop IP's reference on the conn. This is the last reference
26887 	 * on the connp if the state was less than established. If the
26888 	 * connection has gone into timewait state, then we will have
26889 	 * one ref for the TCP and one more ref (total of two) for the
26890 	 * classifier connected hash list (a timewait connections stays
26891 	 * in connected hash till closed).
26892 	 *
26893 	 * We can't assert the references because there might be other
26894 	 * transient reference places because of some walkers or queued
26895 	 * packets in squeue for the timewait state.
26896 	 */
26897 	CONN_DEC_REF(connp);
26898 	return (0);
26899 }
26900 
26901 /* ARGSUSED */
26902 int
26903 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
26904     cred_t *cr)
26905 {
26906 	tcp_t		*tcp;
26907 	uint32_t	msize;
26908 	conn_t *connp = (conn_t *)proto_handle;
26909 	int32_t		tcpstate;
26910 
26911 	/* All Solaris components should pass a cred for this operation. */
26912 	ASSERT(cr != NULL);
26913 
26914 	ASSERT(connp->conn_ref >= 2);
26915 	ASSERT(connp->conn_upper_handle != NULL);
26916 
26917 	if (msg->msg_controllen != 0) {
26918 		return (EOPNOTSUPP);
26919 
26920 	}
26921 	switch (DB_TYPE(mp)) {
26922 	case M_DATA:
26923 		tcp = connp->conn_tcp;
26924 		ASSERT(tcp != NULL);
26925 
26926 		tcpstate = tcp->tcp_state;
26927 		if (tcpstate < TCPS_ESTABLISHED) {
26928 			freemsg(mp);
26929 			return (ENOTCONN);
26930 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
26931 			freemsg(mp);
26932 			return (EPIPE);
26933 		}
26934 
26935 		msize = msgdsize(mp);
26936 
26937 		mutex_enter(&tcp->tcp_non_sq_lock);
26938 		tcp->tcp_squeue_bytes += msize;
26939 		/*
26940 		 * Squeue Flow Control
26941 		 */
26942 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
26943 			tcp_setqfull(tcp);
26944 		}
26945 		mutex_exit(&tcp->tcp_non_sq_lock);
26946 
26947 		/*
26948 		 * The application may pass in an address in the msghdr, but
26949 		 * we ignore the address on connection-oriented sockets.
26950 		 * Just like BSD this code does not generate an error for
26951 		 * TCP (a CONNREQUIRED socket) when sending to an address
26952 		 * passed in with sendto/sendmsg. Instead the data is
26953 		 * delivered on the connection as if no address had been
26954 		 * supplied.
26955 		 */
26956 		CONN_INC_REF(connp);
26957 
26958 		if (msg != NULL && msg->msg_flags & MSG_OOB) {
26959 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
26960 			    tcp_output_urgent, connp, tcp_squeue_flag,
26961 			    SQTAG_TCP_OUTPUT);
26962 		} else {
26963 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
26964 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
26965 		}
26966 
26967 		return (0);
26968 
26969 	default:
26970 		ASSERT(0);
26971 	}
26972 
26973 	freemsg(mp);
26974 	return (0);
26975 }
26976 
26977 /* ARGSUSED */
26978 void
26979 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
26980 {
26981 	int len;
26982 	uint32_t msize;
26983 	conn_t *connp = (conn_t *)arg;
26984 	tcp_t *tcp = connp->conn_tcp;
26985 
26986 	msize = msgdsize(mp);
26987 
26988 	len = msize - 1;
26989 	if (len < 0) {
26990 		freemsg(mp);
26991 		return;
26992 	}
26993 
26994 	/*
26995 	 * Try to force urgent data out on the wire.
26996 	 * Even if we have unsent data this will
26997 	 * at least send the urgent flag.
26998 	 * XXX does not handle more flag correctly.
26999 	 */
27000 	len += tcp->tcp_unsent;
27001 	len += tcp->tcp_snxt;
27002 	tcp->tcp_urg = len;
27003 	tcp->tcp_valid_bits |= TCP_URG_VALID;
27004 
27005 	/* Bypass tcp protocol for fused tcp loopback */
27006 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
27007 		return;
27008 	tcp_wput_data(tcp, mp, B_TRUE);
27009 }
27010 
27011 /* ARGSUSED */
27012 int
27013 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27014     socklen_t *addrlenp, cred_t *cr)
27015 {
27016 	conn_t	*connp = (conn_t *)proto_handle;
27017 	tcp_t	*tcp = connp->conn_tcp;
27018 
27019 	ASSERT(connp->conn_upper_handle != NULL);
27020 	/* All Solaris components should pass a cred for this operation. */
27021 	ASSERT(cr != NULL);
27022 
27023 	ASSERT(tcp != NULL);
27024 
27025 	return (tcp_do_getpeername(tcp, addr, addrlenp));
27026 }
27027 
27028 /* ARGSUSED */
27029 int
27030 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27031     socklen_t *addrlenp, cred_t *cr)
27032 {
27033 	conn_t	*connp = (conn_t *)proto_handle;
27034 	tcp_t	*tcp = connp->conn_tcp;
27035 
27036 	/* All Solaris components should pass a cred for this operation. */
27037 	ASSERT(cr != NULL);
27038 
27039 	ASSERT(connp->conn_upper_handle != NULL);
27040 
27041 	return (tcp_do_getsockname(tcp, addr, addrlenp));
27042 }
27043 
27044 /*
27045  * tcp_fallback
27046  *
27047  * A direct socket is falling back to using STREAMS. The queue
27048  * that is being passed down was created using tcp_open() with
27049  * the SO_FALLBACK flag set. As a result, the queue is not
27050  * associated with a conn, and the q_ptrs instead contain the
27051  * dev and minor area that should be used.
27052  *
27053  * The 'direct_sockfs' flag indicates whether the FireEngine
27054  * optimizations should be used. The common case would be that
27055  * optimizations are enabled, and they might be subsequently
27056  * disabled using the _SIOCSOCKFALLBACK ioctl.
27057  */
27058 
27059 /*
27060  * An active connection is falling back to TPI. Gather all the information
27061  * required by the STREAM head and TPI sonode and send it up.
27062  */
27063 void
27064 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
27065     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
27066 {
27067 	conn_t			*connp = tcp->tcp_connp;
27068 	struct stroptions	*stropt;
27069 	struct T_capability_ack tca;
27070 	struct sockaddr_in6	laddr, faddr;
27071 	socklen_t 		laddrlen, faddrlen;
27072 	short			opts;
27073 	int			error;
27074 	mblk_t			*mp;
27075 
27076 	/* Disable I/OAT during fallback */
27077 	tcp->tcp_sodirect = NULL;
27078 
27079 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
27080 	connp->conn_minor_arena = WR(q)->q_ptr;
27081 
27082 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
27083 
27084 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
27085 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
27086 
27087 	WR(q)->q_qinfo = &tcp_sock_winit;
27088 
27089 	if (!direct_sockfs)
27090 		tcp_disable_direct_sockfs(tcp);
27091 
27092 	/*
27093 	 * free the helper stream
27094 	 */
27095 	ip_free_helper_stream(connp);
27096 
27097 	/*
27098 	 * Notify the STREAM head about options
27099 	 */
27100 	DB_TYPE(stropt_mp) = M_SETOPTS;
27101 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27102 	stropt_mp->b_wptr += sizeof (struct stroptions);
27103 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27104 	stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
27105 
27106 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
27107 	    tcp->tcp_tcps->tcps_wroff_xtra);
27108 	if (tcp->tcp_snd_sack_ok)
27109 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
27110 	stropt->so_hiwat = tcp->tcp_fused ?
27111 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
27112 	    MAX(tcp->tcp_recv_hiwater, tcp->tcp_tcps->tcps_sth_rcv_hiwat);
27113 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
27114 
27115 	putnext(RD(q), stropt_mp);
27116 
27117 	/*
27118 	 * Collect the information needed to sync with the sonode
27119 	 */
27120 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
27121 
27122 	laddrlen = faddrlen = sizeof (sin6_t);
27123 	(void) tcp_do_getsockname(tcp, (struct sockaddr *)&laddr, &laddrlen);
27124 	error = tcp_do_getpeername(tcp, (struct sockaddr *)&faddr, &faddrlen);
27125 	if (error != 0)
27126 		faddrlen = 0;
27127 
27128 	opts = 0;
27129 	if (tcp->tcp_oobinline)
27130 		opts |= SO_OOBINLINE;
27131 	if (tcp->tcp_dontroute)
27132 		opts |= SO_DONTROUTE;
27133 
27134 	/*
27135 	 * Notify the socket that the protocol is now quiescent,
27136 	 * and it's therefore safe move data from the socket
27137 	 * to the stream head.
27138 	 */
27139 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
27140 	    (struct sockaddr *)&laddr, laddrlen,
27141 	    (struct sockaddr *)&faddr, faddrlen, opts);
27142 
27143 	while ((mp = tcp->tcp_rcv_list) != NULL) {
27144 		tcp->tcp_rcv_list = mp->b_next;
27145 		mp->b_next = NULL;
27146 		putnext(q, mp);
27147 	}
27148 	tcp->tcp_rcv_last_head = NULL;
27149 	tcp->tcp_rcv_last_tail = NULL;
27150 	tcp->tcp_rcv_cnt = 0;
27151 }
27152 
27153 /*
27154  * An eager is falling back to TPI. All we have to do is send
27155  * up a T_CONN_IND.
27156  */
27157 void
27158 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
27159 {
27160 	tcp_t *listener = eager->tcp_listener;
27161 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
27162 
27163 	ASSERT(listener != NULL);
27164 	ASSERT(mp != NULL);
27165 
27166 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
27167 
27168 	/*
27169 	 * TLI/XTI applications will get confused by
27170 	 * sending eager as an option since it violates
27171 	 * the option semantics. So remove the eager as
27172 	 * option since TLI/XTI app doesn't need it anyway.
27173 	 */
27174 	if (!direct_sockfs) {
27175 		struct T_conn_ind *conn_ind;
27176 
27177 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
27178 		conn_ind->OPT_length = 0;
27179 		conn_ind->OPT_offset = 0;
27180 	}
27181 
27182 	/*
27183 	 * Sockfs guarantees that the listener will not be closed
27184 	 * during fallback. So we can safely use the listener's queue.
27185 	 */
27186 	putnext(listener->tcp_rq, mp);
27187 }
27188 
27189 int
27190 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
27191     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
27192 {
27193 	tcp_t			*tcp;
27194 	conn_t 			*connp = (conn_t *)proto_handle;
27195 	int			error;
27196 	mblk_t			*stropt_mp;
27197 	mblk_t			*ordrel_mp;
27198 	mblk_t			*fused_sigurp_mp;
27199 
27200 	tcp = connp->conn_tcp;
27201 
27202 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
27203 	    NULL);
27204 
27205 	/* Pre-allocate the T_ordrel_ind mblk. */
27206 	ASSERT(tcp->tcp_ordrel_mp == NULL);
27207 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
27208 	    STR_NOSIG, NULL);
27209 	ordrel_mp->b_datap->db_type = M_PROTO;
27210 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
27211 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
27212 
27213 	/* Pre-allocate the M_PCSIG used by fusion */
27214 	fused_sigurp_mp = allocb_wait(1, BPRI_HI, STR_NOSIG, NULL);
27215 
27216 	/*
27217 	 * Enter the squeue so that no new packets can come in
27218 	 */
27219 	error = squeue_synch_enter(connp->conn_sqp, connp, 0);
27220 	if (error != 0) {
27221 		/* failed to enter, free all the pre-allocated messages. */
27222 		freeb(stropt_mp);
27223 		freeb(ordrel_mp);
27224 		freeb(fused_sigurp_mp);
27225 		/*
27226 		 * We cannot process the eager, so at least send out a
27227 		 * RST so the peer can reconnect.
27228 		 */
27229 		if (tcp->tcp_listener != NULL) {
27230 			(void) tcp_eager_blowoff(tcp->tcp_listener,
27231 			    tcp->tcp_conn_req_seqnum);
27232 		}
27233 		return (ENOMEM);
27234 	}
27235 
27236 	/*
27237 	 * No longer a direct socket
27238 	 */
27239 	connp->conn_flags &= ~IPCL_NONSTR;
27240 
27241 	tcp->tcp_ordrel_mp = ordrel_mp;
27242 
27243 	if (tcp->tcp_fused) {
27244 		ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
27245 		tcp->tcp_fused_sigurg_mp = fused_sigurp_mp;
27246 	} else {
27247 		freeb(fused_sigurp_mp);
27248 	}
27249 
27250 	if (tcp->tcp_listener != NULL) {
27251 		/* The eager will deal with opts when accept() is called */
27252 		freeb(stropt_mp);
27253 		tcp_fallback_eager(tcp, direct_sockfs);
27254 	} else {
27255 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
27256 		    quiesced_cb);
27257 	}
27258 
27259 	/*
27260 	 * There should be atleast two ref's (IP + TCP)
27261 	 */
27262 	ASSERT(connp->conn_ref >= 2);
27263 	squeue_synch_exit(connp->conn_sqp, connp);
27264 
27265 	return (0);
27266 }
27267 
27268 /* ARGSUSED */
27269 static void
27270 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
27271 {
27272 	conn_t 	*connp = (conn_t *)arg;
27273 	tcp_t	*tcp = connp->conn_tcp;
27274 
27275 	freemsg(mp);
27276 
27277 	if (tcp->tcp_fused)
27278 		tcp_unfuse(tcp);
27279 
27280 	if (tcp_xmit_end(tcp) != 0) {
27281 		/*
27282 		 * We were crossing FINs and got a reset from
27283 		 * the other side. Just ignore it.
27284 		 */
27285 		if (tcp->tcp_debug) {
27286 			(void) strlog(TCP_MOD_ID, 0, 1,
27287 			    SL_ERROR|SL_TRACE,
27288 			    "tcp_shutdown_output() out of state %s",
27289 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
27290 		}
27291 	}
27292 }
27293 
27294 /* ARGSUSED */
27295 int
27296 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
27297 {
27298 	conn_t  *connp = (conn_t *)proto_handle;
27299 	tcp_t   *tcp = connp->conn_tcp;
27300 
27301 	ASSERT(connp->conn_upper_handle != NULL);
27302 
27303 	/* All Solaris components should pass a cred for this operation. */
27304 	ASSERT(cr != NULL);
27305 
27306 	/*
27307 	 * X/Open requires that we check the connected state.
27308 	 */
27309 	if (tcp->tcp_state < TCPS_SYN_SENT)
27310 		return (ENOTCONN);
27311 
27312 	/* shutdown the send side */
27313 	if (how != SHUT_RD) {
27314 		mblk_t *bp;
27315 
27316 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
27317 		CONN_INC_REF(connp);
27318 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
27319 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
27320 
27321 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27322 		    SOCK_OPCTL_SHUT_SEND, 0);
27323 	}
27324 
27325 	/* shutdown the recv side */
27326 	if (how != SHUT_WR)
27327 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27328 		    SOCK_OPCTL_SHUT_RECV, 0);
27329 
27330 	return (0);
27331 }
27332 
27333 /*
27334  * SOP_LISTEN() calls into tcp_listen().
27335  */
27336 /* ARGSUSED */
27337 int
27338 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27339 {
27340 	conn_t	*connp = (conn_t *)proto_handle;
27341 	int 	error;
27342 	squeue_t *sqp = connp->conn_sqp;
27343 
27344 	ASSERT(connp->conn_upper_handle != NULL);
27345 
27346 	/* All Solaris components should pass a cred for this operation. */
27347 	ASSERT(cr != NULL);
27348 
27349 	error = squeue_synch_enter(sqp, connp, 0);
27350 	if (error != 0) {
27351 		/* failed to enter */
27352 		return (ENOBUFS);
27353 	}
27354 
27355 	error = tcp_do_listen(connp, backlog, cr);
27356 	if (error == 0) {
27357 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27358 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
27359 	} else if (error < 0) {
27360 		if (error == -TOUTSTATE)
27361 			error = EINVAL;
27362 		else
27363 			error = proto_tlitosyserr(-error);
27364 	}
27365 	squeue_synch_exit(sqp, connp);
27366 	return (error);
27367 }
27368 
27369 static int
27370 tcp_do_listen(conn_t *connp, int backlog, cred_t *cr)
27371 {
27372 	tcp_t		*tcp = connp->conn_tcp;
27373 	sin_t		*sin;
27374 	sin6_t  	*sin6;
27375 	int		error = 0;
27376 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27377 
27378 	/* All Solaris components should pass a cred for this operation. */
27379 	ASSERT(cr != NULL);
27380 
27381 	if (tcp->tcp_state >= TCPS_BOUND) {
27382 		if ((tcp->tcp_state == TCPS_BOUND ||
27383 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
27384 			/*
27385 			 * Handle listen() increasing backlog.
27386 			 * This is more "liberal" then what the TPI spec
27387 			 * requires but is needed to avoid a t_unbind
27388 			 * when handling listen() since the port number
27389 			 * might be "stolen" between the unbind and bind.
27390 			 */
27391 			goto do_listen;
27392 		}
27393 		if (tcp->tcp_debug) {
27394 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27395 			    "tcp_listen: bad state, %d", tcp->tcp_state);
27396 		}
27397 		return (-TOUTSTATE);
27398 	} else {
27399 		int32_t len;
27400 		sin6_t	addr;
27401 
27402 		/* Do an implicit bind: Request for a generic port. */
27403 		if (tcp->tcp_family == AF_INET) {
27404 			len = sizeof (sin_t);
27405 			sin = (sin_t *)&addr;
27406 			*sin = sin_null;
27407 			sin->sin_family = AF_INET;
27408 			tcp->tcp_ipversion = IPV4_VERSION;
27409 		} else {
27410 			ASSERT(tcp->tcp_family == AF_INET6);
27411 			len = sizeof (sin6_t);
27412 			sin6 = (sin6_t *)&addr;
27413 			*sin6 = sin6_null;
27414 			sin6->sin6_family = AF_INET6;
27415 			tcp->tcp_ipversion = IPV6_VERSION;
27416 		}
27417 
27418 		error = tcp_bind_check(connp, (struct sockaddr *)&addr, len,
27419 		    cr, B_FALSE);
27420 		if (error)
27421 			return (error);
27422 		/* Fall through and do the fanout insertion */
27423 	}
27424 
27425 do_listen:
27426 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
27427 	tcp->tcp_conn_req_max = backlog;
27428 	if (tcp->tcp_conn_req_max) {
27429 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
27430 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
27431 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
27432 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
27433 		/*
27434 		 * If this is a listener, do not reset the eager list
27435 		 * and other stuffs.  Note that we don't check if the
27436 		 * existing eager list meets the new tcp_conn_req_max
27437 		 * requirement.
27438 		 */
27439 		if (tcp->tcp_state != TCPS_LISTEN) {
27440 			tcp->tcp_state = TCPS_LISTEN;
27441 			/* Initialize the chain. Don't need the eager_lock */
27442 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
27443 			tcp->tcp_eager_next_drop_q0 = tcp;
27444 			tcp->tcp_eager_prev_drop_q0 = tcp;
27445 			tcp->tcp_second_ctimer_threshold =
27446 			    tcps->tcps_ip_abort_linterval;
27447 		}
27448 	}
27449 
27450 	/*
27451 	 * We can call ip_bind directly, the processing continues
27452 	 * in tcp_post_ip_bind().
27453 	 *
27454 	 * We need to make sure that the conn_recv is set to a non-null
27455 	 * value before we insert the conn into the classifier table.
27456 	 * This is to avoid a race with an incoming packet which does an
27457 	 * ipcl_classify().
27458 	 */
27459 	connp->conn_recv = tcp_conn_request;
27460 	if (tcp->tcp_family == AF_INET) {
27461 		error = ip_proto_bind_laddr_v4(connp, NULL,
27462 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
27463 	} else {
27464 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27465 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
27466 	}
27467 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27468 }
27469 
27470 void
27471 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
27472 {
27473 	conn_t  *connp = (conn_t *)proto_handle;
27474 	tcp_t	*tcp = connp->conn_tcp;
27475 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27476 	uint_t thwin;
27477 
27478 	ASSERT(connp->conn_upper_handle != NULL);
27479 
27480 	(void) squeue_synch_enter(connp->conn_sqp, connp, 0);
27481 
27482 	/* Flow control condition has been removed. */
27483 	tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
27484 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
27485 	    << tcp->tcp_rcv_ws;
27486 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
27487 	/*
27488 	 * Send back a window update immediately if TCP is above
27489 	 * ESTABLISHED state and the increase of the rcv window
27490 	 * that the other side knows is at least 1 MSS after flow
27491 	 * control is lifted.
27492 	 */
27493 	if (tcp->tcp_state >= TCPS_ESTABLISHED &&
27494 	    (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss)) {
27495 		tcp_xmit_ctl(NULL, tcp,
27496 		    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
27497 		    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
27498 		BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
27499 	}
27500 
27501 	squeue_synch_exit(connp->conn_sqp, connp);
27502 }
27503 
27504 /* ARGSUSED */
27505 int
27506 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
27507     int mode, int32_t *rvalp, cred_t *cr)
27508 {
27509 	conn_t  	*connp = (conn_t *)proto_handle;
27510 	int		error;
27511 
27512 	ASSERT(connp->conn_upper_handle != NULL);
27513 
27514 	/* All Solaris components should pass a cred for this operation. */
27515 	ASSERT(cr != NULL);
27516 
27517 	switch (cmd) {
27518 		case ND_SET:
27519 		case ND_GET:
27520 		case TCP_IOC_DEFAULT_Q:
27521 		case _SIOCSOCKFALLBACK:
27522 		case TCP_IOC_ABORT_CONN:
27523 		case TI_GETPEERNAME:
27524 		case TI_GETMYNAME:
27525 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
27526 			    cmd));
27527 			error = EINVAL;
27528 			break;
27529 		default:
27530 			/*
27531 			 * Pass on to IP using helper stream
27532 			 */
27533 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
27534 			    cmd, arg, mode, cr, rvalp);
27535 			break;
27536 	}
27537 	return (error);
27538 }
27539 
27540 sock_downcalls_t sock_tcp_downcalls = {
27541 	tcp_activate,
27542 	tcp_accept,
27543 	tcp_bind,
27544 	tcp_listen,
27545 	tcp_connect,
27546 	tcp_getpeername,
27547 	tcp_getsockname,
27548 	tcp_getsockopt,
27549 	tcp_setsockopt,
27550 	tcp_sendmsg,
27551 	NULL,
27552 	NULL,
27553 	NULL,
27554 	tcp_shutdown,
27555 	tcp_clr_flowctrl,
27556 	tcp_ioctl,
27557 	tcp_close,
27558 };
27559