xref: /titanic_51/usr/src/uts/common/inet/tcp/tcp.c (revision 43412a427a2387ef15ab084d8f30a56a13e32cf7)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/strsun.h>
31 #include <sys/strsubr.h>
32 #include <sys/stropts.h>
33 #include <sys/strlog.h>
34 #include <sys/strsun.h>
35 #define	_SUN_TPI_VERSION 2
36 #include <sys/tihdr.h>
37 #include <sys/timod.h>
38 #include <sys/ddi.h>
39 #include <sys/sunddi.h>
40 #include <sys/suntpi.h>
41 #include <sys/xti_inet.h>
42 #include <sys/cmn_err.h>
43 #include <sys/debug.h>
44 #include <sys/sdt.h>
45 #include <sys/vtrace.h>
46 #include <sys/kmem.h>
47 #include <sys/ethernet.h>
48 #include <sys/cpuvar.h>
49 #include <sys/dlpi.h>
50 #include <sys/multidata.h>
51 #include <sys/multidata_impl.h>
52 #include <sys/pattr.h>
53 #include <sys/policy.h>
54 #include <sys/priv.h>
55 #include <sys/zone.h>
56 #include <sys/sunldi.h>
57 
58 #include <sys/errno.h>
59 #include <sys/signal.h>
60 #include <sys/socket.h>
61 #include <sys/socketvar.h>
62 #include <sys/sockio.h>
63 #include <sys/isa_defs.h>
64 #include <sys/md5.h>
65 #include <sys/random.h>
66 #include <sys/sodirect.h>
67 #include <sys/uio.h>
68 #include <sys/systm.h>
69 #include <netinet/in.h>
70 #include <netinet/tcp.h>
71 #include <netinet/ip6.h>
72 #include <netinet/icmp6.h>
73 #include <net/if.h>
74 #include <net/route.h>
75 #include <inet/ipsec_impl.h>
76 
77 #include <inet/common.h>
78 #include <inet/ip.h>
79 #include <inet/ip_impl.h>
80 #include <inet/ip6.h>
81 #include <inet/ip_ndp.h>
82 #include <inet/proto_set.h>
83 #include <inet/mib2.h>
84 #include <inet/nd.h>
85 #include <inet/optcom.h>
86 #include <inet/snmpcom.h>
87 #include <inet/kstatcom.h>
88 #include <inet/tcp.h>
89 #include <inet/tcp_impl.h>
90 #include <net/pfkeyv2.h>
91 #include <inet/ipsec_info.h>
92 #include <inet/ipdrop.h>
93 
94 #include <inet/ipclassifier.h>
95 #include <inet/ip_ire.h>
96 #include <inet/ip_ftable.h>
97 #include <inet/ip_if.h>
98 #include <inet/ipp_common.h>
99 #include <inet/ip_netinfo.h>
100 #include <sys/squeue_impl.h>
101 #include <sys/squeue.h>
102 #include <inet/kssl/ksslapi.h>
103 #include <sys/tsol/label.h>
104 #include <sys/tsol/tnet.h>
105 #include <rpc/pmap_prot.h>
106 #include <sys/callo.h>
107 
108 /*
109  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
110  *
111  * (Read the detailed design doc in PSARC case directory)
112  *
113  * The entire tcp state is contained in tcp_t and conn_t structure
114  * which are allocated in tandem using ipcl_conn_create() and passing
115  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
116  * the references on the tcp_t. The tcp_t structure is never compressed
117  * and packets always land on the correct TCP perimeter from the time
118  * eager is created till the time tcp_t dies (as such the old mentat
119  * TCP global queue is not used for detached state and no IPSEC checking
120  * is required). The global queue is still allocated to send out resets
121  * for connection which have no listeners and IP directly calls
122  * tcp_xmit_listeners_reset() which does any policy check.
123  *
124  * Protection and Synchronisation mechanism:
125  *
126  * The tcp data structure does not use any kind of lock for protecting
127  * its state but instead uses 'squeues' for mutual exclusion from various
128  * read and write side threads. To access a tcp member, the thread should
129  * always be behind squeue (via squeue_enter with flags as SQ_FILL, SQ_PROCESS,
130  * or SQ_NODRAIN). Since the squeues allow a direct function call, caller
131  * can pass any tcp function having prototype of edesc_t as argument
132  * (different from traditional STREAMs model where packets come in only
133  * designated entry points). The list of functions that can be directly
134  * called via squeue are listed before the usual function prototype.
135  *
136  * Referencing:
137  *
138  * TCP is MT-Hot and we use a reference based scheme to make sure that the
139  * tcp structure doesn't disappear when its needed. When the application
140  * creates an outgoing connection or accepts an incoming connection, we
141  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
142  * The IP reference is just a symbolic reference since ip_tcpclose()
143  * looks at tcp structure after tcp_close_output() returns which could
144  * have dropped the last TCP reference. So as long as the connection is
145  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
146  * conn_t. The classifier puts its own reference when the connection is
147  * inserted in listen or connected hash. Anytime a thread needs to enter
148  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
149  * on write side or by doing a classify on read side and then puts a
150  * reference on the conn before doing squeue_enter/tryenter/fill. For
151  * read side, the classifier itself puts the reference under fanout lock
152  * to make sure that tcp can't disappear before it gets processed. The
153  * squeue will drop this reference automatically so the called function
154  * doesn't have to do a DEC_REF.
155  *
156  * Opening a new connection:
157  *
158  * The outgoing connection open is pretty simple. tcp_open() does the
159  * work in creating the conn/tcp structure and initializing it. The
160  * squeue assignment is done based on the CPU the application
161  * is running on. So for outbound connections, processing is always done
162  * on application CPU which might be different from the incoming CPU
163  * being interrupted by the NIC. An optimal way would be to figure out
164  * the NIC <-> CPU binding at listen time, and assign the outgoing
165  * connection to the squeue attached to the CPU that will be interrupted
166  * for incoming packets (we know the NIC based on the bind IP address).
167  * This might seem like a problem if more data is going out but the
168  * fact is that in most cases the transmit is ACK driven transmit where
169  * the outgoing data normally sits on TCP's xmit queue waiting to be
170  * transmitted.
171  *
172  * Accepting a connection:
173  *
174  * This is a more interesting case because of various races involved in
175  * establishing a eager in its own perimeter. Read the meta comment on
176  * top of tcp_conn_request(). But briefly, the squeue is picked by
177  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
178  *
179  * Closing a connection:
180  *
181  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
182  * via squeue to do the close and mark the tcp as detached if the connection
183  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
184  * reference but tcp_close() drop IP's reference always. So if tcp was
185  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
186  * and 1 because it is in classifier's connected hash. This is the condition
187  * we use to determine that its OK to clean up the tcp outside of squeue
188  * when time wait expires (check the ref under fanout and conn_lock and
189  * if it is 2, remove it from fanout hash and kill it).
190  *
191  * Although close just drops the necessary references and marks the
192  * tcp_detached state, tcp_close needs to know the tcp_detached has been
193  * set (under squeue) before letting the STREAM go away (because a
194  * inbound packet might attempt to go up the STREAM while the close
195  * has happened and tcp_detached is not set). So a special lock and
196  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
197  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
198  * tcp_detached.
199  *
200  * Special provisions and fast paths:
201  *
202  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
203  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
204  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
205  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
206  * check to send packets directly to tcp_rput_data via squeue. Everyone
207  * else comes through tcp_input() on the read side.
208  *
209  * We also make special provisions for sockfs by marking tcp_issocket
210  * whenever we have only sockfs on top of TCP. This allows us to skip
211  * putting the tcp in acceptor hash since a sockfs listener can never
212  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
213  * since eager has already been allocated and the accept now happens
214  * on acceptor STREAM. There is a big blob of comment on top of
215  * tcp_conn_request explaining the new accept. When socket is POP'd,
216  * sockfs sends us an ioctl to mark the fact and we go back to old
217  * behaviour. Once tcp_issocket is unset, its never set for the
218  * life of that connection.
219  *
220  * In support of on-board asynchronous DMA hardware (e.g. Intel I/OAT)
221  * two consoldiation private KAPIs are used to enqueue M_DATA mblk_t's
222  * directly to the socket (sodirect) and start an asynchronous copyout
223  * to a user-land receive-side buffer (uioa) when a blocking socket read
224  * (e.g. read, recv, ...) is pending.
225  *
226  * This is accomplished when tcp_issocket is set and tcp_sodirect is not
227  * NULL so points to an sodirect_t and if marked enabled then we enqueue
228  * all mblk_t's directly to the socket.
229  *
230  * Further, if the sodirect_t sod_uioa and if marked enabled (due to a
231  * blocking socket read, e.g. user-land read, recv, ...) then an asynchronous
232  * copyout will be started directly to the user-land uio buffer. Also, as we
233  * have a pending read, TCP's push logic can take into account the number of
234  * bytes to be received and only awake the blocked read()er when the uioa_t
235  * byte count has been satisfied.
236  *
237  * IPsec notes :
238  *
239  * Since a packet is always executed on the correct TCP perimeter
240  * all IPsec processing is defered to IP including checking new
241  * connections and setting IPSEC policies for new connection. The
242  * only exception is tcp_xmit_listeners_reset() which is called
243  * directly from IP and needs to policy check to see if TH_RST
244  * can be sent out.
245  *
246  * PFHooks notes :
247  *
248  * For mdt case, one meta buffer contains multiple packets. Mblks for every
249  * packet are assembled and passed to the hooks. When packets are blocked,
250  * or boundary of any packet is changed, the mdt processing is stopped, and
251  * packets of the meta buffer are send to the IP path one by one.
252  */
253 
254 /*
255  * Values for squeue switch:
256  * 1: SQ_NODRAIN
257  * 2: SQ_PROCESS
258  * 3: SQ_FILL
259  */
260 int tcp_squeue_wput = 2;	/* /etc/systems */
261 int tcp_squeue_flag;
262 
263 /*
264  * Macros for sodirect:
265  *
266  * SOD_PTR_ENTER(tcp, sodp) - for the tcp_t pointer "tcp" set the
267  * sodirect_t pointer "sodp" to the socket/tcp shared sodirect_t
268  * if it exists and is enabled, else to NULL. Note, in the current
269  * sodirect implementation the sod_lockp must not be held across any
270  * STREAMS call (e.g. putnext) else a "recursive mutex_enter" PANIC
271  * will result as sod_lockp is the streamhead stdata.sd_lock.
272  *
273  * SOD_NOT_ENABLED(tcp) - return true if not a sodirect tcp_t or the
274  * sodirect_t isn't enabled, usefull for ASSERT()ing that a recieve
275  * side tcp code path dealing with a tcp_rcv_list or putnext() isn't
276  * being used when sodirect code paths should be.
277  */
278 
279 #define	SOD_PTR_ENTER(tcp, sodp)					\
280 	(sodp) = (tcp)->tcp_sodirect;					\
281 									\
282 	if ((sodp) != NULL) {						\
283 		mutex_enter((sodp)->sod_lockp);				\
284 		if (!((sodp)->sod_state & SOD_ENABLED)) {		\
285 			mutex_exit((sodp)->sod_lockp);			\
286 			(sodp) = NULL;					\
287 		}							\
288 	}
289 
290 #define	SOD_NOT_ENABLED(tcp)						\
291 	((tcp)->tcp_sodirect == NULL ||					\
292 	    !((tcp)->tcp_sodirect->sod_state & SOD_ENABLED))
293 
294 /*
295  * This controls how tiny a write must be before we try to copy it
296  * into the the mblk on the tail of the transmit queue.  Not much
297  * speedup is observed for values larger than sixteen.  Zero will
298  * disable the optimisation.
299  */
300 int tcp_tx_pull_len = 16;
301 
302 /*
303  * TCP Statistics.
304  *
305  * How TCP statistics work.
306  *
307  * There are two types of statistics invoked by two macros.
308  *
309  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
310  * supposed to be used in non MT-hot paths of the code.
311  *
312  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
313  * supposed to be used for DEBUG purposes and may be used on a hot path.
314  *
315  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
316  * (use "kstat tcp" to get them).
317  *
318  * There is also additional debugging facility that marks tcp_clean_death()
319  * instances and saves them in tcp_t structure. It is triggered by
320  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
321  * tcp_clean_death() calls that counts the number of times each tag was hit. It
322  * is triggered by TCP_CLD_COUNTERS define.
323  *
324  * How to add new counters.
325  *
326  * 1) Add a field in the tcp_stat structure describing your counter.
327  * 2) Add a line in the template in tcp_kstat2_init() with the name
328  *    of the counter.
329  *
330  *    IMPORTANT!! - make sure that both are in sync !!
331  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
332  *
333  * Please avoid using private counters which are not kstat-exported.
334  *
335  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
336  * in tcp_t structure.
337  *
338  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
339  */
340 
341 #ifndef TCP_DEBUG_COUNTER
342 #ifdef DEBUG
343 #define	TCP_DEBUG_COUNTER 1
344 #else
345 #define	TCP_DEBUG_COUNTER 0
346 #endif
347 #endif
348 
349 #define	TCP_CLD_COUNTERS 0
350 
351 #define	TCP_TAG_CLEAN_DEATH 1
352 #define	TCP_MAX_CLEAN_DEATH_TAG 32
353 
354 #ifdef lint
355 static int _lint_dummy_;
356 #endif
357 
358 #if TCP_CLD_COUNTERS
359 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
360 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
361 #elif defined(lint)
362 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
363 #else
364 #define	TCP_CLD_STAT(x)
365 #endif
366 
367 #if TCP_DEBUG_COUNTER
368 #define	TCP_DBGSTAT(tcps, x)	\
369 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
370 #define	TCP_G_DBGSTAT(x)	\
371 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
372 #elif defined(lint)
373 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
374 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
375 #else
376 #define	TCP_DBGSTAT(tcps, x)
377 #define	TCP_G_DBGSTAT(x)
378 #endif
379 
380 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
381 
382 tcp_g_stat_t	tcp_g_statistics;
383 kstat_t		*tcp_g_kstat;
384 
385 /*
386  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
387  * tcp write side.
388  */
389 #define	CALL_IP_WPUT(connp, q, mp) {					\
390 	ASSERT(((q)->q_flag & QREADR) == 0);				\
391 	TCP_DBGSTAT(connp->conn_netstack->netstack_tcp, tcp_ip_output);	\
392 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
393 }
394 
395 /* Macros for timestamp comparisons */
396 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
397 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
398 
399 /*
400  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
401  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
402  * by adding three components: a time component which grows by 1 every 4096
403  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
404  * a per-connection component which grows by 125000 for every new connection;
405  * and an "extra" component that grows by a random amount centered
406  * approximately on 64000.  This causes the the ISS generator to cycle every
407  * 4.89 hours if no TCP connections are made, and faster if connections are
408  * made.
409  *
410  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
411  * components: a time component which grows by 250000 every second; and
412  * a per-connection component which grows by 125000 for every new connections.
413  *
414  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
415  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
416  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
417  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
418  * password.
419  */
420 #define	ISS_INCR	250000
421 #define	ISS_NSEC_SHT	12
422 
423 static sin_t	sin_null;	/* Zero address for quick clears */
424 static sin6_t	sin6_null;	/* Zero address for quick clears */
425 
426 /*
427  * This implementation follows the 4.3BSD interpretation of the urgent
428  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
429  * incompatible changes in protocols like telnet and rlogin.
430  */
431 #define	TCP_OLD_URP_INTERPRETATION	1
432 
433 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
434 	(TCP_IS_DETACHED(tcp) && \
435 	    (!(tcp)->tcp_hard_binding))
436 
437 /*
438  * TCP reassembly macros.  We hide starting and ending sequence numbers in
439  * b_next and b_prev of messages on the reassembly queue.  The messages are
440  * chained using b_cont.  These macros are used in tcp_reass() so we don't
441  * have to see the ugly casts and assignments.
442  */
443 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
444 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
445 					(mblk_t *)(uintptr_t)(u))
446 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
447 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
448 					(mblk_t *)(uintptr_t)(u))
449 
450 /*
451  * Implementation of TCP Timers.
452  * =============================
453  *
454  * INTERFACE:
455  *
456  * There are two basic functions dealing with tcp timers:
457  *
458  *	timeout_id_t	tcp_timeout(connp, func, time)
459  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
460  *	TCP_TIMER_RESTART(tcp, intvl)
461  *
462  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
463  * after 'time' ticks passed. The function called by timeout() must adhere to
464  * the same restrictions as a driver soft interrupt handler - it must not sleep
465  * or call other functions that might sleep. The value returned is the opaque
466  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
467  * cancel the request. The call to tcp_timeout() may fail in which case it
468  * returns zero. This is different from the timeout(9F) function which never
469  * fails.
470  *
471  * The call-back function 'func' always receives 'connp' as its single
472  * argument. It is always executed in the squeue corresponding to the tcp
473  * structure. The tcp structure is guaranteed to be present at the time the
474  * call-back is called.
475  *
476  * NOTE: The call-back function 'func' is never called if tcp is in
477  * 	the TCPS_CLOSED state.
478  *
479  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
480  * request. locks acquired by the call-back routine should not be held across
481  * the call to tcp_timeout_cancel() or a deadlock may result.
482  *
483  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
484  * Otherwise, it returns an integer value greater than or equal to 0. In
485  * particular, if the call-back function is already placed on the squeue, it can
486  * not be canceled.
487  *
488  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
489  * 	within squeue context corresponding to the tcp instance. Since the
490  *	call-back is also called via the same squeue, there are no race
491  *	conditions described in untimeout(9F) manual page since all calls are
492  *	strictly serialized.
493  *
494  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
495  *	stored in tcp_timer_tid and starts a new one using
496  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
497  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
498  *	field.
499  *
500  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
501  *	call-back may still be called, so it is possible tcp_timer() will be
502  *	called several times. This should not be a problem since tcp_timer()
503  *	should always check the tcp instance state.
504  *
505  *
506  * IMPLEMENTATION:
507  *
508  * TCP timers are implemented using three-stage process. The call to
509  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
510  * when the timer expires. The tcp_timer_callback() arranges the call of the
511  * tcp_timer_handler() function via squeue corresponding to the tcp
512  * instance. The tcp_timer_handler() calls actual requested timeout call-back
513  * and passes tcp instance as an argument to it. Information is passed between
514  * stages using the tcp_timer_t structure which contains the connp pointer, the
515  * tcp call-back to call and the timeout id returned by the timeout(9F).
516  *
517  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
518  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
519  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
520  * returns the pointer to this mblk.
521  *
522  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
523  * looks like a normal mblk without actual dblk attached to it.
524  *
525  * To optimize performance each tcp instance holds a small cache of timer
526  * mblocks. In the current implementation it caches up to two timer mblocks per
527  * tcp instance. The cache is preserved over tcp frees and is only freed when
528  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
529  * timer processing happens on a corresponding squeue, the cache manipulation
530  * does not require any locks. Experiments show that majority of timer mblocks
531  * allocations are satisfied from the tcp cache and do not involve kmem calls.
532  *
533  * The tcp_timeout() places a refhold on the connp instance which guarantees
534  * that it will be present at the time the call-back function fires. The
535  * tcp_timer_handler() drops the reference after calling the call-back, so the
536  * call-back function does not need to manipulate the references explicitly.
537  */
538 
539 typedef struct tcp_timer_s {
540 	conn_t	*connp;
541 	void 	(*tcpt_proc)(void *);
542 	callout_id_t   tcpt_tid;
543 } tcp_timer_t;
544 
545 static kmem_cache_t *tcp_timercache;
546 kmem_cache_t	*tcp_sack_info_cache;
547 kmem_cache_t	*tcp_iphc_cache;
548 
549 /*
550  * For scalability, we must not run a timer for every TCP connection
551  * in TIME_WAIT state.  To see why, consider (for time wait interval of
552  * 4 minutes):
553  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
554  *
555  * This list is ordered by time, so you need only delete from the head
556  * until you get to entries which aren't old enough to delete yet.
557  * The list consists of only the detached TIME_WAIT connections.
558  *
559  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
560  * becomes detached TIME_WAIT (either by changing the state and already
561  * being detached or the other way around). This means that the TIME_WAIT
562  * state can be extended (up to doubled) if the connection doesn't become
563  * detached for a long time.
564  *
565  * The list manipulations (including tcp_time_wait_next/prev)
566  * are protected by the tcp_time_wait_lock. The content of the
567  * detached TIME_WAIT connections is protected by the normal perimeters.
568  *
569  * This list is per squeue and squeues are shared across the tcp_stack_t's.
570  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
571  * and conn_netstack.
572  * The tcp_t's that are added to tcp_free_list are disassociated and
573  * have NULL tcp_tcps and conn_netstack pointers.
574  */
575 typedef struct tcp_squeue_priv_s {
576 	kmutex_t	tcp_time_wait_lock;
577 	callout_id_t	tcp_time_wait_tid;
578 	tcp_t		*tcp_time_wait_head;
579 	tcp_t		*tcp_time_wait_tail;
580 	tcp_t		*tcp_free_list;
581 	uint_t		tcp_free_list_cnt;
582 } tcp_squeue_priv_t;
583 
584 /*
585  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
586  * Running it every 5 seconds seems to give the best results.
587  */
588 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
589 
590 /*
591  * To prevent memory hog, limit the number of entries in tcp_free_list
592  * to 1% of available memory / number of cpus
593  */
594 uint_t tcp_free_list_max_cnt = 0;
595 
596 #define	TCP_XMIT_LOWATER	4096
597 #define	TCP_XMIT_HIWATER	49152
598 #define	TCP_RECV_LOWATER	2048
599 #define	TCP_RECV_HIWATER	49152
600 
601 /*
602  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
603  */
604 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
605 
606 #define	TIDUSZ	4096	/* transport interface data unit size */
607 
608 /*
609  * Bind hash list size and has function.  It has to be a power of 2 for
610  * hashing.
611  */
612 #define	TCP_BIND_FANOUT_SIZE	512
613 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
614 /*
615  * Size of listen and acceptor hash list.  It has to be a power of 2 for
616  * hashing.
617  */
618 #define	TCP_FANOUT_SIZE		256
619 
620 #ifdef	_ILP32
621 #define	TCP_ACCEPTOR_HASH(accid)					\
622 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
623 #else
624 #define	TCP_ACCEPTOR_HASH(accid)					\
625 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
626 #endif	/* _ILP32 */
627 
628 #define	IP_ADDR_CACHE_SIZE	2048
629 #define	IP_ADDR_CACHE_HASH(faddr)					\
630 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
631 
632 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
633 #define	TCP_HSP_HASH_SIZE 256
634 
635 #define	TCP_HSP_HASH(addr)					\
636 	(((addr>>24) ^ (addr >>16) ^			\
637 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
638 
639 /*
640  * TCP options struct returned from tcp_parse_options.
641  */
642 typedef struct tcp_opt_s {
643 	uint32_t	tcp_opt_mss;
644 	uint32_t	tcp_opt_wscale;
645 	uint32_t	tcp_opt_ts_val;
646 	uint32_t	tcp_opt_ts_ecr;
647 	tcp_t		*tcp;
648 } tcp_opt_t;
649 
650 /*
651  * TCP option struct passing information b/w lisenter and eager.
652  */
653 struct tcp_options {
654 	uint_t			to_flags;
655 	ssize_t			to_boundif;	/* IPV6_BOUND_IF */
656 	sock_upper_handle_t	to_handle;
657 };
658 
659 #define	TCPOPT_BOUNDIF		0x00000001	/* set IPV6_BOUND_IF */
660 #define	TCPOPT_RECVPKTINFO	0x00000002	/* set IPV6_RECVPKTINFO */
661 #define	TCPOPT_UPPERHANDLE	0x00000004	/* set upper handle */
662 
663 /*
664  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
665  */
666 
667 #ifdef _BIG_ENDIAN
668 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
669 	(TCPOPT_TSTAMP << 8) | 10)
670 #else
671 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
672 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
673 #endif
674 
675 /*
676  * Flags returned from tcp_parse_options.
677  */
678 #define	TCP_OPT_MSS_PRESENT	1
679 #define	TCP_OPT_WSCALE_PRESENT	2
680 #define	TCP_OPT_TSTAMP_PRESENT	4
681 #define	TCP_OPT_SACK_OK_PRESENT	8
682 #define	TCP_OPT_SACK_PRESENT	16
683 
684 /* TCP option length */
685 #define	TCPOPT_NOP_LEN		1
686 #define	TCPOPT_MAXSEG_LEN	4
687 #define	TCPOPT_WS_LEN		3
688 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
689 #define	TCPOPT_TSTAMP_LEN	10
690 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
691 #define	TCPOPT_SACK_OK_LEN	2
692 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
693 #define	TCPOPT_REAL_SACK_LEN	4
694 #define	TCPOPT_MAX_SACK_LEN	36
695 #define	TCPOPT_HEADER_LEN	2
696 
697 /* TCP cwnd burst factor. */
698 #define	TCP_CWND_INFINITE	65535
699 #define	TCP_CWND_SS		3
700 #define	TCP_CWND_NORMAL		5
701 
702 /* Maximum TCP initial cwin (start/restart). */
703 #define	TCP_MAX_INIT_CWND	8
704 
705 /*
706  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
707  * either tcp_slow_start_initial or tcp_slow_start_after idle
708  * depending on the caller.  If the upper layer has not used the
709  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
710  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
711  * If the upper layer has changed set the tcp_init_cwnd, just use
712  * it to calculate the tcp_cwnd.
713  */
714 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
715 {									\
716 	if ((tcp)->tcp_init_cwnd == 0) {				\
717 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
718 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
719 	} else {							\
720 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
721 	}								\
722 	tcp->tcp_cwnd_cnt = 0;						\
723 }
724 
725 /* TCP Timer control structure */
726 typedef struct tcpt_s {
727 	pfv_t	tcpt_pfv;	/* The routine we are to call */
728 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
729 } tcpt_t;
730 
731 /* Host Specific Parameter structure */
732 typedef struct tcp_hsp {
733 	struct tcp_hsp	*tcp_hsp_next;
734 	in6_addr_t	tcp_hsp_addr_v6;
735 	in6_addr_t	tcp_hsp_subnet_v6;
736 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
737 	int32_t		tcp_hsp_sendspace;
738 	int32_t		tcp_hsp_recvspace;
739 	int32_t		tcp_hsp_tstamp;
740 } tcp_hsp_t;
741 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
742 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
743 
744 /*
745  * Functions called directly via squeue having a prototype of edesc_t.
746  */
747 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
748 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
749 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
750 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
751 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
752 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
753 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
754 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
755 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
756 void		tcp_output_urgent(void *arg, mblk_t *mp, void *arg2);
757 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
758 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
759 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
760 
761 
762 /* Prototype for TCP functions */
763 static void	tcp_random_init(void);
764 int		tcp_random(void);
765 static void	tcp_tli_accept(tcp_t *tcp, mblk_t *mp);
766 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
767 		    tcp_t *eager);
768 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
769 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
770     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
771     boolean_t user_specified);
772 static void	tcp_closei_local(tcp_t *tcp);
773 static void	tcp_close_detached(tcp_t *tcp);
774 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
775 			mblk_t *idmp, mblk_t **defermp);
776 static void	tcp_tpi_connect(tcp_t *tcp, mblk_t *mp);
777 static int	tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
778 		    in_port_t dstport, uint_t srcid, cred_t *cr, pid_t pid);
779 static int 	tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
780 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
781 		    uint32_t scope_id, cred_t *cr, pid_t pid);
782 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
783 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
784 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
785 static char	*tcp_display(tcp_t *tcp, char *, char);
786 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
787 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
788 static void	tcp_eager_unlink(tcp_t *tcp);
789 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
790 		    int unixerr);
791 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
792 		    int tlierr, int unixerr);
793 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
794 		    cred_t *cr);
795 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
796 		    char *value, caddr_t cp, cred_t *cr);
797 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
798 		    char *value, caddr_t cp, cred_t *cr);
799 static int	tcp_tpistate(tcp_t *tcp);
800 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
801     int caller_holds_lock);
802 static void	tcp_bind_hash_remove(tcp_t *tcp);
803 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
804 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
805 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
806 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
807 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
808 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
809 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
810 void		tcp_g_q_setup(tcp_stack_t *);
811 void		tcp_g_q_create(tcp_stack_t *);
812 void		tcp_g_q_destroy(tcp_stack_t *);
813 static int	tcp_header_init_ipv4(tcp_t *tcp);
814 static int	tcp_header_init_ipv6(tcp_t *tcp);
815 int		tcp_init(tcp_t *tcp, queue_t *q);
816 static int	tcp_init_values(tcp_t *tcp);
817 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
818 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
819 static void	tcp_ip_notify(tcp_t *tcp);
820 static mblk_t	*tcp_ire_mp(mblk_t **mpp);
821 static void	tcp_iss_init(tcp_t *tcp);
822 static void	tcp_keepalive_killer(void *arg);
823 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
824 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
825 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
826 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
827 static boolean_t tcp_allow_connopt_set(int level, int name);
828 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
829 int		tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
830 int		tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level,
831 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
832 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
833 		    mblk_t *mblk);
834 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
835 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
836 		    uchar_t *ptr, uint_t len);
837 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
838 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
839     tcp_stack_t *);
840 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
841 		    caddr_t cp, cred_t *cr);
842 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
843 		    caddr_t cp, cred_t *cr);
844 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
845 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
846 		    caddr_t cp, cred_t *cr);
847 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
848 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
849 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
850 static void	tcp_reinit(tcp_t *tcp);
851 static void	tcp_reinit_values(tcp_t *tcp);
852 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
853 		    tcp_t *thisstream, cred_t *cr);
854 
855 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
856 static uint_t	tcp_rcv_drain(tcp_t *tcp);
857 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
858 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
859 static void	tcp_ss_rexmit(tcp_t *tcp);
860 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
861 static void	tcp_process_options(tcp_t *, tcph_t *);
862 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
863 static void	tcp_rsrv(queue_t *q);
864 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
865 static int	tcp_snmp_state(tcp_t *tcp);
866 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
867 		    cred_t *cr);
868 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
869 		    cred_t *cr);
870 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
871 		    cred_t *cr);
872 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
873 		    cred_t *cr);
874 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
875 		    cred_t *cr);
876 static void	tcp_timer(void *arg);
877 static void	tcp_timer_callback(void *);
878 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
879     boolean_t random);
880 static in_port_t tcp_get_next_priv_port(const tcp_t *);
881 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
882 static void	tcp_wput_fallback(queue_t *q, mblk_t *mp);
883 void		tcp_tpi_accept(queue_t *q, mblk_t *mp);
884 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
885 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
886 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
887 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
888 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
889 		    const int num_sack_blk, int *usable, uint_t *snxt,
890 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
891 		    const int mdt_thres);
892 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
893 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
894 		    const int num_sack_blk, int *usable, uint_t *snxt,
895 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
896 		    const int mdt_thres);
897 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
898 		    int num_sack_blk);
899 static void	tcp_wsrv(queue_t *q);
900 static int	tcp_xmit_end(tcp_t *tcp);
901 static void	tcp_ack_timer(void *arg);
902 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
903 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
904 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
905 		    zoneid_t zoneid, tcp_stack_t *, conn_t *connp);
906 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
907 		    uint32_t ack, int ctl);
908 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *);
909 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr, tcp_stack_t *);
910 static int	setmaxps(queue_t *q, int maxpsz);
911 static void	tcp_set_rto(tcp_t *, time_t);
912 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
913 		    boolean_t, boolean_t);
914 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
915 		    boolean_t ipsec_mctl);
916 static int	tcp_build_hdrs(tcp_t *);
917 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
918 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
919 		    tcph_t *tcph);
920 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
921 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
922 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
923 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
924 		    const boolean_t, const uint32_t, const uint32_t,
925 		    const uint32_t, const uint32_t, tcp_stack_t *);
926 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
927 		    const uint_t, const uint_t, boolean_t *);
928 static mblk_t	*tcp_lso_info_mp(mblk_t *);
929 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
930 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
931 extern mblk_t	*tcp_timermp_alloc(int);
932 extern void	tcp_timermp_free(tcp_t *);
933 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
934 static void	tcp_stop_lingering(tcp_t *tcp);
935 static void	tcp_close_linger_timeout(void *arg);
936 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
937 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
938 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
939 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
940 static void	tcp_g_kstat_fini(kstat_t *);
941 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
942 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
943 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
944 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
945 static int	tcp_kstat_update(kstat_t *kp, int rw);
946 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
947 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
948 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
949 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
950 			tcph_t *tcph, mblk_t *idmp);
951 static int	tcp_squeue_switch(int);
952 
953 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
954 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
955 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
956 static int	tcp_tpi_close(queue_t *, int);
957 static int	tcpclose_accept(queue_t *);
958 
959 static void	tcp_squeue_add(squeue_t *);
960 static boolean_t tcp_zcopy_check(tcp_t *);
961 static void	tcp_zcopy_notify(tcp_t *);
962 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
963 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
964 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
965 
966 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
967 
968 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
969 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
970 
971 static int tcp_accept(sock_lower_handle_t, sock_lower_handle_t,
972 	    sock_upper_handle_t, cred_t *);
973 static int tcp_listen(sock_lower_handle_t, int, cred_t *);
974 static int tcp_post_ip_bind(tcp_t *, mblk_t *, int, cred_t *, pid_t);
975 static int tcp_do_listen(conn_t *, int, cred_t *);
976 static int tcp_do_connect(conn_t *, const struct sockaddr *, socklen_t,
977     cred_t *, pid_t);
978 static int tcp_do_bind(conn_t *, struct sockaddr *, socklen_t, cred_t *,
979     boolean_t);
980 static int tcp_do_unbind(conn_t *);
981 static int tcp_bind_check(conn_t *, struct sockaddr *, socklen_t, cred_t *,
982     boolean_t);
983 
984 /*
985  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
986  *
987  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
988  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
989  * (defined in tcp.h) needs to be filled in and passed into the kernel
990  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
991  * structure contains the four-tuple of a TCP connection and a range of TCP
992  * states (specified by ac_start and ac_end). The use of wildcard addresses
993  * and ports is allowed. Connections with a matching four tuple and a state
994  * within the specified range will be aborted. The valid states for the
995  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
996  * inclusive.
997  *
998  * An application which has its connection aborted by this ioctl will receive
999  * an error that is dependent on the connection state at the time of the abort.
1000  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
1001  * though a RST packet has been received.  If the connection state is equal to
1002  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
1003  * and all resources associated with the connection will be freed.
1004  */
1005 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
1006 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
1007 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
1008 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
1009 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
1010 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
1011     boolean_t, tcp_stack_t *);
1012 
1013 static struct module_info tcp_rinfo =  {
1014 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
1015 };
1016 
1017 static struct module_info tcp_winfo =  {
1018 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
1019 };
1020 
1021 /*
1022  * Entry points for TCP as a device. The normal case which supports
1023  * the TCP functionality.
1024  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
1025  */
1026 struct qinit tcp_rinitv4 = {
1027 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, NULL, &tcp_rinfo
1028 };
1029 
1030 struct qinit tcp_rinitv6 = {
1031 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_tpi_close, NULL, &tcp_rinfo
1032 };
1033 
1034 struct qinit tcp_winit = {
1035 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1036 };
1037 
1038 /* Initial entry point for TCP in socket mode. */
1039 struct qinit tcp_sock_winit = {
1040 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1041 };
1042 
1043 /* TCP entry point during fallback */
1044 struct qinit tcp_fallback_sock_winit = {
1045 	(pfi_t)tcp_wput_fallback, NULL, NULL, NULL, NULL, &tcp_winfo
1046 };
1047 
1048 /*
1049  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1050  * an accept. Avoid allocating data structures since eager has already
1051  * been created.
1052  */
1053 struct qinit tcp_acceptor_rinit = {
1054 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1055 };
1056 
1057 struct qinit tcp_acceptor_winit = {
1058 	(pfi_t)tcp_tpi_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1059 };
1060 
1061 /*
1062  * Entry points for TCP loopback (read side only)
1063  * The open routine is only used for reopens, thus no need to
1064  * have a separate one for tcp_openv6.
1065  */
1066 struct qinit tcp_loopback_rinit = {
1067 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, (pfi_t)0,
1068 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1069 };
1070 
1071 /* For AF_INET aka /dev/tcp */
1072 struct streamtab tcpinfov4 = {
1073 	&tcp_rinitv4, &tcp_winit
1074 };
1075 
1076 /* For AF_INET6 aka /dev/tcp6 */
1077 struct streamtab tcpinfov6 = {
1078 	&tcp_rinitv6, &tcp_winit
1079 };
1080 
1081 sock_downcalls_t sock_tcp_downcalls;
1082 
1083 /*
1084  * Have to ensure that tcp_g_q_close is not done by an
1085  * interrupt thread.
1086  */
1087 static taskq_t *tcp_taskq;
1088 
1089 /* Setable only in /etc/system. Move to ndd? */
1090 boolean_t tcp_icmp_source_quench = B_FALSE;
1091 
1092 /*
1093  * Following assumes TPI alignment requirements stay along 32 bit
1094  * boundaries
1095  */
1096 #define	ROUNDUP32(x) \
1097 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1098 
1099 /* Template for response to info request. */
1100 static struct T_info_ack tcp_g_t_info_ack = {
1101 	T_INFO_ACK,		/* PRIM_type */
1102 	0,			/* TSDU_size */
1103 	T_INFINITE,		/* ETSDU_size */
1104 	T_INVALID,		/* CDATA_size */
1105 	T_INVALID,		/* DDATA_size */
1106 	sizeof (sin_t),		/* ADDR_size */
1107 	0,			/* OPT_size - not initialized here */
1108 	TIDUSZ,			/* TIDU_size */
1109 	T_COTS_ORD,		/* SERV_type */
1110 	TCPS_IDLE,		/* CURRENT_state */
1111 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1112 };
1113 
1114 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1115 	T_INFO_ACK,		/* PRIM_type */
1116 	0,			/* TSDU_size */
1117 	T_INFINITE,		/* ETSDU_size */
1118 	T_INVALID,		/* CDATA_size */
1119 	T_INVALID,		/* DDATA_size */
1120 	sizeof (sin6_t),	/* ADDR_size */
1121 	0,			/* OPT_size - not initialized here */
1122 	TIDUSZ,		/* TIDU_size */
1123 	T_COTS_ORD,		/* SERV_type */
1124 	TCPS_IDLE,		/* CURRENT_state */
1125 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1126 };
1127 
1128 #define	MS	1L
1129 #define	SECONDS	(1000 * MS)
1130 #define	MINUTES	(60 * SECONDS)
1131 #define	HOURS	(60 * MINUTES)
1132 #define	DAYS	(24 * HOURS)
1133 
1134 #define	PARAM_MAX (~(uint32_t)0)
1135 
1136 /* Max size IP datagram is 64k - 1 */
1137 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1138 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1139 /* Max of the above */
1140 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1141 
1142 /* Largest TCP port number */
1143 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1144 
1145 /*
1146  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1147  * layer header.  It has to be a multiple of 4.
1148  */
1149 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1150 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1151 
1152 /*
1153  * All of these are alterable, within the min/max values given, at run time.
1154  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1155  * per the TCP spec.
1156  */
1157 /* BEGIN CSTYLED */
1158 static tcpparam_t	lcl_tcp_param_arr[] = {
1159  /*min		max		value		name */
1160  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1161  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1162  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1163  { 1,		1024,		1,		"tcp_conn_req_min" },
1164  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1165  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1166  { 0,		10,		0,		"tcp_debug" },
1167  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1168  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1169  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1170  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1171  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1172  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1173  { 1,		255,		64,		"tcp_ipv4_ttl"},
1174  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1175  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1176  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1177  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1178  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1179  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1180  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1181  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1182  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1183  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1184  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1185  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1186  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1187  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1188  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1189  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1190  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1191  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1192  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1193  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1194  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1195  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1196  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1197 /*
1198  * Question:  What default value should I set for tcp_strong_iss?
1199  */
1200  { 0,		2,		1,		"tcp_strong_iss"},
1201  { 0,		65536,		20,		"tcp_rtt_updates"},
1202  { 0,		1,		1,		"tcp_wscale_always"},
1203  { 0,		1,		0,		"tcp_tstamp_always"},
1204  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1205  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1206  { 0,		16,		2,		"tcp_deferred_acks_max"},
1207  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1208  { 1,		4,		4,		"tcp_slow_start_initial"},
1209  { 0,		2,		2,		"tcp_sack_permitted"},
1210  { 0,		1,		1,		"tcp_compression_enabled"},
1211  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1212  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1213  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1214  { 0,		1,		0,		"tcp_rev_src_routes"},
1215  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1216  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1217  { 0,		16,		8,		"tcp_local_dacks_max"},
1218  { 0,		2,		1,		"tcp_ecn_permitted"},
1219  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1220  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1221  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1222  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1223  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1224 };
1225 /* END CSTYLED */
1226 
1227 /*
1228  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1229  * each header fragment in the header buffer.  Each parameter value has
1230  * to be a multiple of 4 (32-bit aligned).
1231  */
1232 static tcpparam_t lcl_tcp_mdt_head_param =
1233 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1234 static tcpparam_t lcl_tcp_mdt_tail_param =
1235 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1236 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1237 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1238 
1239 /*
1240  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1241  * the maximum number of payload buffers associated per Multidata.
1242  */
1243 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1244 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1245 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1246 
1247 /* Round up the value to the nearest mss. */
1248 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1249 
1250 /*
1251  * Set ECN capable transport (ECT) code point in IP header.
1252  *
1253  * Note that there are 2 ECT code points '01' and '10', which are called
1254  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1255  * point ECT(0) for TCP as described in RFC 2481.
1256  */
1257 #define	SET_ECT(tcp, iph) \
1258 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1259 		/* We need to clear the code point first. */ \
1260 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1261 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1262 	} else { \
1263 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1264 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1265 	}
1266 
1267 /*
1268  * The format argument to pass to tcp_display().
1269  * DISP_PORT_ONLY means that the returned string has only port info.
1270  * DISP_ADDR_AND_PORT means that the returned string also contains the
1271  * remote and local IP address.
1272  */
1273 #define	DISP_PORT_ONLY		1
1274 #define	DISP_ADDR_AND_PORT	2
1275 
1276 #define	NDD_TOO_QUICK_MSG \
1277 	"ndd get info rate too high for non-privileged users, try again " \
1278 	"later.\n"
1279 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1280 
1281 #define	IS_VMLOANED_MBLK(mp) \
1282 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1283 
1284 
1285 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1286 boolean_t tcp_mdt_chain = B_TRUE;
1287 
1288 /*
1289  * MDT threshold in the form of effective send MSS multiplier; we take
1290  * the MDT path if the amount of unsent data exceeds the threshold value
1291  * (default threshold is 1*SMSS).
1292  */
1293 uint_t tcp_mdt_smss_threshold = 1;
1294 
1295 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1296 
1297 /*
1298  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1299  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1300  * determined dynamically during tcp_adapt_ire(), which is the default.
1301  */
1302 boolean_t tcp_static_maxpsz = B_FALSE;
1303 
1304 /* Setable in /etc/system */
1305 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1306 uint32_t tcp_random_anon_port = 1;
1307 
1308 /*
1309  * To reach to an eager in Q0 which can be dropped due to an incoming
1310  * new SYN request when Q0 is full, a new doubly linked list is
1311  * introduced. This list allows to select an eager from Q0 in O(1) time.
1312  * This is needed to avoid spending too much time walking through the
1313  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1314  * this new list has to be a member of Q0.
1315  * This list is headed by listener's tcp_t. When the list is empty,
1316  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1317  * of listener's tcp_t point to listener's tcp_t itself.
1318  *
1319  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1320  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1321  * These macros do not affect the eager's membership to Q0.
1322  */
1323 
1324 
1325 #define	MAKE_DROPPABLE(listener, eager)					\
1326 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1327 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1328 		    = (eager);						\
1329 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1330 		(eager)->tcp_eager_next_drop_q0 =			\
1331 		    (listener)->tcp_eager_next_drop_q0;			\
1332 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1333 	}
1334 
1335 #define	MAKE_UNDROPPABLE(eager)						\
1336 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1337 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1338 		    = (eager)->tcp_eager_prev_drop_q0;			\
1339 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1340 		    = (eager)->tcp_eager_next_drop_q0;			\
1341 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1342 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1343 	}
1344 
1345 /*
1346  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1347  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1348  * data, TCP will not respond with an ACK.  RFC 793 requires that
1349  * TCP responds with an ACK for such a bogus ACK.  By not following
1350  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1351  * an attacker successfully spoofs an acceptable segment to our
1352  * peer; or when our peer is "confused."
1353  */
1354 uint32_t tcp_drop_ack_unsent_cnt = 10;
1355 
1356 /*
1357  * Hook functions to enable cluster networking
1358  * On non-clustered systems these vectors must always be NULL.
1359  */
1360 
1361 void (*cl_inet_listen)(netstackid_t stack_id, uint8_t protocol,
1362 			    sa_family_t addr_family, uint8_t *laddrp,
1363 			    in_port_t lport, void *args) = NULL;
1364 void (*cl_inet_unlisten)(netstackid_t stack_id, uint8_t protocol,
1365 			    sa_family_t addr_family, uint8_t *laddrp,
1366 			    in_port_t lport, void *args) = NULL;
1367 
1368 int (*cl_inet_connect2)(netstackid_t stack_id, uint8_t protocol,
1369 			    boolean_t is_outgoing,
1370 			    sa_family_t addr_family,
1371 			    uint8_t *laddrp, in_port_t lport,
1372 			    uint8_t *faddrp, in_port_t fport,
1373 			    void *args) = NULL;
1374 
1375 void (*cl_inet_disconnect)(netstackid_t stack_id, uint8_t protocol,
1376 			    sa_family_t addr_family, uint8_t *laddrp,
1377 			    in_port_t lport, uint8_t *faddrp,
1378 			    in_port_t fport, void *args) = NULL;
1379 
1380 /*
1381  * The following are defined in ip.c
1382  */
1383 extern int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
1384 			    sa_family_t addr_family, uint8_t *laddrp,
1385 			    void *args);
1386 extern uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
1387 			    sa_family_t addr_family, uint8_t *laddrp,
1388 			    uint8_t *faddrp, void *args);
1389 
1390 
1391 /*
1392  * int CL_INET_CONNECT(conn_t *cp, tcp_t *tcp, boolean_t is_outgoing, int err)
1393  */
1394 #define	CL_INET_CONNECT(connp, tcp, is_outgoing, err) {		\
1395 	(err) = 0;						\
1396 	if (cl_inet_connect2 != NULL) {				\
1397 		/*						\
1398 		 * Running in cluster mode - register active connection	\
1399 		 * information						\
1400 		 */							\
1401 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1402 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1403 				(err) = (*cl_inet_connect2)(		\
1404 				    (connp)->conn_netstack->netstack_stackid,\
1405 				    IPPROTO_TCP, is_outgoing, AF_INET,	\
1406 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1407 				    (in_port_t)(tcp)->tcp_lport,	\
1408 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1409 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1410 			}						\
1411 		} else {						\
1412 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1413 			    &(tcp)->tcp_ip6h->ip6_src)) {		\
1414 				(err) = (*cl_inet_connect2)(		\
1415 				    (connp)->conn_netstack->netstack_stackid,\
1416 				    IPPROTO_TCP, is_outgoing, AF_INET6,	\
1417 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1418 				    (in_port_t)(tcp)->tcp_lport,	\
1419 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1420 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1421 			}						\
1422 		}							\
1423 	}								\
1424 }
1425 
1426 #define	CL_INET_DISCONNECT(connp, tcp)	{				\
1427 	if (cl_inet_disconnect != NULL) {				\
1428 		/*							\
1429 		 * Running in cluster mode - deregister active		\
1430 		 * connection information				\
1431 		 */							\
1432 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1433 			if ((tcp)->tcp_ip_src != 0) {			\
1434 				(*cl_inet_disconnect)(			\
1435 				    (connp)->conn_netstack->netstack_stackid,\
1436 				    IPPROTO_TCP, AF_INET,		\
1437 				    (uint8_t *)(&((tcp)->tcp_ip_src)),	\
1438 				    (in_port_t)(tcp)->tcp_lport,	\
1439 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1440 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1441 			}						\
1442 		} else {						\
1443 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1444 			    &(tcp)->tcp_ip_src_v6)) {			\
1445 				(*cl_inet_disconnect)(			\
1446 				    (connp)->conn_netstack->netstack_stackid,\
1447 				    IPPROTO_TCP, AF_INET6,		\
1448 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1449 				    (in_port_t)(tcp)->tcp_lport,	\
1450 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1451 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1452 			}						\
1453 		}							\
1454 	}								\
1455 }
1456 
1457 /*
1458  * Cluster networking hook for traversing current connection list.
1459  * This routine is used to extract the current list of live connections
1460  * which must continue to to be dispatched to this node.
1461  */
1462 int cl_tcp_walk_list(netstackid_t stack_id,
1463     int (*callback)(cl_tcp_info_t *, void *), void *arg);
1464 
1465 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1466     void *arg, tcp_stack_t *tcps);
1467 
1468 #define	DTRACE_IP_FASTPATH(mp, iph, ill, ipha, ip6h) 			\
1469 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,	\
1470 	    iph, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha,		\
1471 	    ip6_t *, ip6h, int, 0);
1472 
1473 /*
1474  * Figure out the value of window scale opton.  Note that the rwnd is
1475  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1476  * We cannot find the scale value and then do a round up of tcp_rwnd
1477  * because the scale value may not be correct after that.
1478  *
1479  * Set the compiler flag to make this function inline.
1480  */
1481 static void
1482 tcp_set_ws_value(tcp_t *tcp)
1483 {
1484 	int i;
1485 	uint32_t rwnd = tcp->tcp_rwnd;
1486 
1487 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1488 	    i++, rwnd >>= 1)
1489 		;
1490 	tcp->tcp_rcv_ws = i;
1491 }
1492 
1493 /*
1494  * Remove a connection from the list of detached TIME_WAIT connections.
1495  * It returns B_FALSE if it can't remove the connection from the list
1496  * as the connection has already been removed from the list due to an
1497  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1498  */
1499 static boolean_t
1500 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1501 {
1502 	boolean_t	locked = B_FALSE;
1503 
1504 	if (tcp_time_wait == NULL) {
1505 		tcp_time_wait = *((tcp_squeue_priv_t **)
1506 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1507 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1508 		locked = B_TRUE;
1509 	} else {
1510 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1511 	}
1512 
1513 	if (tcp->tcp_time_wait_expire == 0) {
1514 		ASSERT(tcp->tcp_time_wait_next == NULL);
1515 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1516 		if (locked)
1517 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1518 		return (B_FALSE);
1519 	}
1520 	ASSERT(TCP_IS_DETACHED(tcp));
1521 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1522 
1523 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1524 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1525 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1526 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1527 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1528 			    NULL;
1529 		} else {
1530 			tcp_time_wait->tcp_time_wait_tail = NULL;
1531 		}
1532 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1533 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1534 		ASSERT(tcp->tcp_time_wait_next == NULL);
1535 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1536 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1537 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1538 	} else {
1539 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1540 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1541 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1542 		    tcp->tcp_time_wait_next;
1543 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1544 		    tcp->tcp_time_wait_prev;
1545 	}
1546 	tcp->tcp_time_wait_next = NULL;
1547 	tcp->tcp_time_wait_prev = NULL;
1548 	tcp->tcp_time_wait_expire = 0;
1549 
1550 	if (locked)
1551 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1552 	return (B_TRUE);
1553 }
1554 
1555 /*
1556  * Add a connection to the list of detached TIME_WAIT connections
1557  * and set its time to expire.
1558  */
1559 static void
1560 tcp_time_wait_append(tcp_t *tcp)
1561 {
1562 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1563 	tcp_squeue_priv_t *tcp_time_wait =
1564 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1565 	    SQPRIVATE_TCP));
1566 
1567 	tcp_timers_stop(tcp);
1568 
1569 	/* Freed above */
1570 	ASSERT(tcp->tcp_timer_tid == 0);
1571 	ASSERT(tcp->tcp_ack_tid == 0);
1572 
1573 	/* must have happened at the time of detaching the tcp */
1574 	ASSERT(tcp->tcp_ptpahn == NULL);
1575 	ASSERT(tcp->tcp_flow_stopped == 0);
1576 	ASSERT(tcp->tcp_time_wait_next == NULL);
1577 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1578 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1579 	ASSERT(tcp->tcp_listener == NULL);
1580 
1581 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1582 	/*
1583 	 * The value computed below in tcp->tcp_time_wait_expire may
1584 	 * appear negative or wrap around. That is ok since our
1585 	 * interest is only in the difference between the current lbolt
1586 	 * value and tcp->tcp_time_wait_expire. But the value should not
1587 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1588 	 * The corresponding comparison in tcp_time_wait_collector() uses
1589 	 * modular arithmetic.
1590 	 */
1591 	tcp->tcp_time_wait_expire +=
1592 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1593 	if (tcp->tcp_time_wait_expire == 0)
1594 		tcp->tcp_time_wait_expire = 1;
1595 
1596 	ASSERT(TCP_IS_DETACHED(tcp));
1597 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1598 	ASSERT(tcp->tcp_time_wait_next == NULL);
1599 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1600 	TCP_DBGSTAT(tcps, tcp_time_wait);
1601 
1602 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1603 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1604 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1605 		tcp_time_wait->tcp_time_wait_head = tcp;
1606 	} else {
1607 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1608 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1609 		    TCPS_TIME_WAIT);
1610 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1611 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1612 	}
1613 	tcp_time_wait->tcp_time_wait_tail = tcp;
1614 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1615 }
1616 
1617 /* ARGSUSED */
1618 void
1619 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1620 {
1621 	conn_t	*connp = (conn_t *)arg;
1622 	tcp_t	*tcp = connp->conn_tcp;
1623 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1624 
1625 	ASSERT(tcp != NULL);
1626 	if (tcp->tcp_state == TCPS_CLOSED) {
1627 		return;
1628 	}
1629 
1630 	ASSERT((tcp->tcp_family == AF_INET &&
1631 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1632 	    (tcp->tcp_family == AF_INET6 &&
1633 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1634 	    tcp->tcp_ipversion == IPV6_VERSION)));
1635 	ASSERT(!tcp->tcp_listener);
1636 
1637 	TCP_STAT(tcps, tcp_time_wait_reap);
1638 	ASSERT(TCP_IS_DETACHED(tcp));
1639 
1640 	/*
1641 	 * Because they have no upstream client to rebind or tcp_close()
1642 	 * them later, we axe the connection here and now.
1643 	 */
1644 	tcp_close_detached(tcp);
1645 }
1646 
1647 /*
1648  * Remove cached/latched IPsec references.
1649  */
1650 void
1651 tcp_ipsec_cleanup(tcp_t *tcp)
1652 {
1653 	conn_t		*connp = tcp->tcp_connp;
1654 
1655 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1656 
1657 	if (connp->conn_latch != NULL) {
1658 		IPLATCH_REFRELE(connp->conn_latch,
1659 		    connp->conn_netstack);
1660 		connp->conn_latch = NULL;
1661 	}
1662 	if (connp->conn_policy != NULL) {
1663 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1664 		connp->conn_policy = NULL;
1665 	}
1666 }
1667 
1668 /*
1669  * Cleaup before placing on free list.
1670  * Disassociate from the netstack/tcp_stack_t since the freelist
1671  * is per squeue and not per netstack.
1672  */
1673 void
1674 tcp_cleanup(tcp_t *tcp)
1675 {
1676 	mblk_t		*mp;
1677 	char		*tcp_iphc;
1678 	int		tcp_iphc_len;
1679 	int		tcp_hdr_grown;
1680 	tcp_sack_info_t	*tcp_sack_info;
1681 	conn_t		*connp = tcp->tcp_connp;
1682 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1683 	netstack_t	*ns = tcps->tcps_netstack;
1684 	mblk_t		*tcp_rsrv_mp;
1685 
1686 	tcp_bind_hash_remove(tcp);
1687 
1688 	/* Cleanup that which needs the netstack first */
1689 	tcp_ipsec_cleanup(tcp);
1690 
1691 	tcp_free(tcp);
1692 
1693 	/* Release any SSL context */
1694 	if (tcp->tcp_kssl_ent != NULL) {
1695 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1696 		tcp->tcp_kssl_ent = NULL;
1697 	}
1698 
1699 	if (tcp->tcp_kssl_ctx != NULL) {
1700 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1701 		tcp->tcp_kssl_ctx = NULL;
1702 	}
1703 	tcp->tcp_kssl_pending = B_FALSE;
1704 
1705 	conn_delete_ire(connp, NULL);
1706 
1707 	/*
1708 	 * Since we will bzero the entire structure, we need to
1709 	 * remove it and reinsert it in global hash list. We
1710 	 * know the walkers can't get to this conn because we
1711 	 * had set CONDEMNED flag earlier and checked reference
1712 	 * under conn_lock so walker won't pick it and when we
1713 	 * go the ipcl_globalhash_remove() below, no walker
1714 	 * can get to it.
1715 	 */
1716 	ipcl_globalhash_remove(connp);
1717 
1718 	/*
1719 	 * Now it is safe to decrement the reference counts.
1720 	 * This might be the last reference on the netstack and TCPS
1721 	 * in which case it will cause the tcp_g_q_close and
1722 	 * the freeing of the IP Instance.
1723 	 */
1724 	connp->conn_netstack = NULL;
1725 	netstack_rele(ns);
1726 	ASSERT(tcps != NULL);
1727 	tcp->tcp_tcps = NULL;
1728 	TCPS_REFRELE(tcps);
1729 
1730 	/* Save some state */
1731 	mp = tcp->tcp_timercache;
1732 
1733 	tcp_sack_info = tcp->tcp_sack_info;
1734 	tcp_iphc = tcp->tcp_iphc;
1735 	tcp_iphc_len = tcp->tcp_iphc_len;
1736 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1737 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1738 
1739 	if (connp->conn_cred != NULL) {
1740 		crfree(connp->conn_cred);
1741 		connp->conn_cred = NULL;
1742 	}
1743 	if (connp->conn_peercred != NULL) {
1744 		crfree(connp->conn_peercred);
1745 		connp->conn_peercred = NULL;
1746 	}
1747 	ipcl_conn_cleanup(connp);
1748 	connp->conn_flags = IPCL_TCPCONN;
1749 	bzero(tcp, sizeof (tcp_t));
1750 
1751 	/* restore the state */
1752 	tcp->tcp_timercache = mp;
1753 
1754 	tcp->tcp_sack_info = tcp_sack_info;
1755 	tcp->tcp_iphc = tcp_iphc;
1756 	tcp->tcp_iphc_len = tcp_iphc_len;
1757 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1758 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1759 
1760 	tcp->tcp_connp = connp;
1761 
1762 	ASSERT(connp->conn_tcp == tcp);
1763 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1764 	connp->conn_state_flags = CONN_INCIPIENT;
1765 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1766 	ASSERT(connp->conn_ref == 1);
1767 }
1768 
1769 /*
1770  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1771  * is done forwards from the head.
1772  * This walks all stack instances since
1773  * tcp_time_wait remains global across all stacks.
1774  */
1775 /* ARGSUSED */
1776 void
1777 tcp_time_wait_collector(void *arg)
1778 {
1779 	tcp_t *tcp;
1780 	clock_t now;
1781 	mblk_t *mp;
1782 	conn_t *connp;
1783 	kmutex_t *lock;
1784 	boolean_t removed;
1785 
1786 	squeue_t *sqp = (squeue_t *)arg;
1787 	tcp_squeue_priv_t *tcp_time_wait =
1788 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1789 
1790 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1791 	tcp_time_wait->tcp_time_wait_tid = 0;
1792 
1793 	if (tcp_time_wait->tcp_free_list != NULL &&
1794 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1795 		TCP_G_STAT(tcp_freelist_cleanup);
1796 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1797 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1798 			tcp->tcp_time_wait_next = NULL;
1799 			tcp_time_wait->tcp_free_list_cnt--;
1800 			ASSERT(tcp->tcp_tcps == NULL);
1801 			CONN_DEC_REF(tcp->tcp_connp);
1802 		}
1803 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1804 	}
1805 
1806 	/*
1807 	 * In order to reap time waits reliably, we should use a
1808 	 * source of time that is not adjustable by the user -- hence
1809 	 * the call to ddi_get_lbolt().
1810 	 */
1811 	now = ddi_get_lbolt();
1812 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1813 		/*
1814 		 * Compare times using modular arithmetic, since
1815 		 * lbolt can wrapover.
1816 		 */
1817 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1818 			break;
1819 		}
1820 
1821 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1822 		ASSERT(removed);
1823 
1824 		connp = tcp->tcp_connp;
1825 		ASSERT(connp->conn_fanout != NULL);
1826 		lock = &connp->conn_fanout->connf_lock;
1827 		/*
1828 		 * This is essentially a TW reclaim fast path optimization for
1829 		 * performance where the timewait collector checks under the
1830 		 * fanout lock (so that no one else can get access to the
1831 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1832 		 * the classifier hash list. If ref count is indeed 2, we can
1833 		 * just remove the conn under the fanout lock and avoid
1834 		 * cleaning up the conn under the squeue, provided that
1835 		 * clustering callbacks are not enabled. If clustering is
1836 		 * enabled, we need to make the clustering callback before
1837 		 * setting the CONDEMNED flag and after dropping all locks and
1838 		 * so we forego this optimization and fall back to the slow
1839 		 * path. Also please see the comments in tcp_closei_local
1840 		 * regarding the refcnt logic.
1841 		 *
1842 		 * Since we are holding the tcp_time_wait_lock, its better
1843 		 * not to block on the fanout_lock because other connections
1844 		 * can't add themselves to time_wait list. So we do a
1845 		 * tryenter instead of mutex_enter.
1846 		 */
1847 		if (mutex_tryenter(lock)) {
1848 			mutex_enter(&connp->conn_lock);
1849 			if ((connp->conn_ref == 2) &&
1850 			    (cl_inet_disconnect == NULL)) {
1851 				ipcl_hash_remove_locked(connp,
1852 				    connp->conn_fanout);
1853 				/*
1854 				 * Set the CONDEMNED flag now itself so that
1855 				 * the refcnt cannot increase due to any
1856 				 * walker. But we have still not cleaned up
1857 				 * conn_ire_cache. This is still ok since
1858 				 * we are going to clean it up in tcp_cleanup
1859 				 * immediately and any interface unplumb
1860 				 * thread will wait till the ire is blown away
1861 				 */
1862 				connp->conn_state_flags |= CONN_CONDEMNED;
1863 				mutex_exit(lock);
1864 				mutex_exit(&connp->conn_lock);
1865 				if (tcp_time_wait->tcp_free_list_cnt <
1866 				    tcp_free_list_max_cnt) {
1867 					/* Add to head of tcp_free_list */
1868 					mutex_exit(
1869 					    &tcp_time_wait->tcp_time_wait_lock);
1870 					tcp_cleanup(tcp);
1871 					ASSERT(connp->conn_latch == NULL);
1872 					ASSERT(connp->conn_policy == NULL);
1873 					ASSERT(tcp->tcp_tcps == NULL);
1874 					ASSERT(connp->conn_netstack == NULL);
1875 
1876 					mutex_enter(
1877 					    &tcp_time_wait->tcp_time_wait_lock);
1878 					tcp->tcp_time_wait_next =
1879 					    tcp_time_wait->tcp_free_list;
1880 					tcp_time_wait->tcp_free_list = tcp;
1881 					tcp_time_wait->tcp_free_list_cnt++;
1882 					continue;
1883 				} else {
1884 					/* Do not add to tcp_free_list */
1885 					mutex_exit(
1886 					    &tcp_time_wait->tcp_time_wait_lock);
1887 					tcp_bind_hash_remove(tcp);
1888 					conn_delete_ire(tcp->tcp_connp, NULL);
1889 					tcp_ipsec_cleanup(tcp);
1890 					CONN_DEC_REF(tcp->tcp_connp);
1891 				}
1892 			} else {
1893 				CONN_INC_REF_LOCKED(connp);
1894 				mutex_exit(lock);
1895 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1896 				mutex_exit(&connp->conn_lock);
1897 				/*
1898 				 * We can reuse the closemp here since conn has
1899 				 * detached (otherwise we wouldn't even be in
1900 				 * time_wait list). tcp_closemp_used can safely
1901 				 * be changed without taking a lock as no other
1902 				 * thread can concurrently access it at this
1903 				 * point in the connection lifecycle.
1904 				 */
1905 
1906 				if (tcp->tcp_closemp.b_prev == NULL)
1907 					tcp->tcp_closemp_used = B_TRUE;
1908 				else
1909 					cmn_err(CE_PANIC,
1910 					    "tcp_timewait_collector: "
1911 					    "concurrent use of tcp_closemp: "
1912 					    "connp %p tcp %p\n", (void *)connp,
1913 					    (void *)tcp);
1914 
1915 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1916 				mp = &tcp->tcp_closemp;
1917 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1918 				    tcp_timewait_output, connp,
1919 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1920 			}
1921 		} else {
1922 			mutex_enter(&connp->conn_lock);
1923 			CONN_INC_REF_LOCKED(connp);
1924 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1925 			mutex_exit(&connp->conn_lock);
1926 			/*
1927 			 * We can reuse the closemp here since conn has
1928 			 * detached (otherwise we wouldn't even be in
1929 			 * time_wait list). tcp_closemp_used can safely
1930 			 * be changed without taking a lock as no other
1931 			 * thread can concurrently access it at this
1932 			 * point in the connection lifecycle.
1933 			 */
1934 
1935 			if (tcp->tcp_closemp.b_prev == NULL)
1936 				tcp->tcp_closemp_used = B_TRUE;
1937 			else
1938 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1939 				    "concurrent use of tcp_closemp: "
1940 				    "connp %p tcp %p\n", (void *)connp,
1941 				    (void *)tcp);
1942 
1943 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1944 			mp = &tcp->tcp_closemp;
1945 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1946 			    tcp_timewait_output, connp,
1947 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1948 		}
1949 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1950 	}
1951 
1952 	if (tcp_time_wait->tcp_free_list != NULL)
1953 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1954 
1955 	tcp_time_wait->tcp_time_wait_tid =
1956 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1957 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1958 	    CALLOUT_FLAG_ROUNDUP);
1959 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1960 }
1961 
1962 /*
1963  * Reply to a clients T_CONN_RES TPI message. This function
1964  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1965  * on the acceptor STREAM and processed in tcp_wput_accept().
1966  * Read the block comment on top of tcp_conn_request().
1967  */
1968 static void
1969 tcp_tli_accept(tcp_t *listener, mblk_t *mp)
1970 {
1971 	tcp_t	*acceptor;
1972 	tcp_t	*eager;
1973 	tcp_t   *tcp;
1974 	struct T_conn_res	*tcr;
1975 	t_uscalar_t	acceptor_id;
1976 	t_scalar_t	seqnum;
1977 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1978 	struct tcp_options *tcpopt;
1979 	mblk_t	*ok_mp;
1980 	mblk_t	*mp1;
1981 	tcp_stack_t	*tcps = listener->tcp_tcps;
1982 
1983 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1984 		tcp_err_ack(listener, mp, TPROTO, 0);
1985 		return;
1986 	}
1987 	tcr = (struct T_conn_res *)mp->b_rptr;
1988 
1989 	/*
1990 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1991 	 * read side queue of the streams device underneath us i.e. the
1992 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1993 	 * look it up in the queue_hash.  Under LP64 it sends down the
1994 	 * minor_t of the accepting endpoint.
1995 	 *
1996 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1997 	 * fanout hash lock is held.
1998 	 * This prevents any thread from entering the acceptor queue from
1999 	 * below (since it has not been hard bound yet i.e. any inbound
2000 	 * packets will arrive on the listener or default tcp queue and
2001 	 * go through tcp_lookup).
2002 	 * The CONN_INC_REF will prevent the acceptor from closing.
2003 	 *
2004 	 * XXX It is still possible for a tli application to send down data
2005 	 * on the accepting stream while another thread calls t_accept.
2006 	 * This should not be a problem for well-behaved applications since
2007 	 * the T_OK_ACK is sent after the queue swapping is completed.
2008 	 *
2009 	 * If the accepting fd is the same as the listening fd, avoid
2010 	 * queue hash lookup since that will return an eager listener in a
2011 	 * already established state.
2012 	 */
2013 	acceptor_id = tcr->ACCEPTOR_id;
2014 	mutex_enter(&listener->tcp_eager_lock);
2015 	if (listener->tcp_acceptor_id == acceptor_id) {
2016 		eager = listener->tcp_eager_next_q;
2017 		/* only count how many T_CONN_INDs so don't count q0 */
2018 		if ((listener->tcp_conn_req_cnt_q != 1) ||
2019 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
2020 			mutex_exit(&listener->tcp_eager_lock);
2021 			tcp_err_ack(listener, mp, TBADF, 0);
2022 			return;
2023 		}
2024 		if (listener->tcp_conn_req_cnt_q0 != 0) {
2025 			/* Throw away all the eagers on q0. */
2026 			tcp_eager_cleanup(listener, 1);
2027 		}
2028 		if (listener->tcp_syn_defense) {
2029 			listener->tcp_syn_defense = B_FALSE;
2030 			if (listener->tcp_ip_addr_cache != NULL) {
2031 				kmem_free(listener->tcp_ip_addr_cache,
2032 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
2033 				listener->tcp_ip_addr_cache = NULL;
2034 			}
2035 		}
2036 		/*
2037 		 * Transfer tcp_conn_req_max to the eager so that when
2038 		 * a disconnect occurs we can revert the endpoint to the
2039 		 * listen state.
2040 		 */
2041 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
2042 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
2043 		/*
2044 		 * Get a reference on the acceptor just like the
2045 		 * tcp_acceptor_hash_lookup below.
2046 		 */
2047 		acceptor = listener;
2048 		CONN_INC_REF(acceptor->tcp_connp);
2049 	} else {
2050 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
2051 		if (acceptor == NULL) {
2052 			if (listener->tcp_debug) {
2053 				(void) strlog(TCP_MOD_ID, 0, 1,
2054 				    SL_ERROR|SL_TRACE,
2055 				    "tcp_accept: did not find acceptor 0x%x\n",
2056 				    acceptor_id);
2057 			}
2058 			mutex_exit(&listener->tcp_eager_lock);
2059 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2060 			return;
2061 		}
2062 		/*
2063 		 * Verify acceptor state. The acceptable states for an acceptor
2064 		 * include TCPS_IDLE and TCPS_BOUND.
2065 		 */
2066 		switch (acceptor->tcp_state) {
2067 		case TCPS_IDLE:
2068 			/* FALLTHRU */
2069 		case TCPS_BOUND:
2070 			break;
2071 		default:
2072 			CONN_DEC_REF(acceptor->tcp_connp);
2073 			mutex_exit(&listener->tcp_eager_lock);
2074 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2075 			return;
2076 		}
2077 	}
2078 
2079 	/* The listener must be in TCPS_LISTEN */
2080 	if (listener->tcp_state != TCPS_LISTEN) {
2081 		CONN_DEC_REF(acceptor->tcp_connp);
2082 		mutex_exit(&listener->tcp_eager_lock);
2083 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2084 		return;
2085 	}
2086 
2087 	/*
2088 	 * Rendezvous with an eager connection request packet hanging off
2089 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2090 	 * tcp structure when the connection packet arrived in
2091 	 * tcp_conn_request().
2092 	 */
2093 	seqnum = tcr->SEQ_number;
2094 	eager = listener;
2095 	do {
2096 		eager = eager->tcp_eager_next_q;
2097 		if (eager == NULL) {
2098 			CONN_DEC_REF(acceptor->tcp_connp);
2099 			mutex_exit(&listener->tcp_eager_lock);
2100 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2101 			return;
2102 		}
2103 	} while (eager->tcp_conn_req_seqnum != seqnum);
2104 	mutex_exit(&listener->tcp_eager_lock);
2105 
2106 	/*
2107 	 * At this point, both acceptor and listener have 2 ref
2108 	 * that they begin with. Acceptor has one additional ref
2109 	 * we placed in lookup while listener has 3 additional
2110 	 * ref for being behind the squeue (tcp_accept() is
2111 	 * done on listener's squeue); being in classifier hash;
2112 	 * and eager's ref on listener.
2113 	 */
2114 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2115 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2116 
2117 	/*
2118 	 * The eager at this point is set in its own squeue and
2119 	 * could easily have been killed (tcp_accept_finish will
2120 	 * deal with that) because of a TH_RST so we can only
2121 	 * ASSERT for a single ref.
2122 	 */
2123 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2124 
2125 	/* Pre allocate the stroptions mblk also */
2126 	opt_mp = allocb(MAX(sizeof (struct tcp_options),
2127 	    sizeof (struct T_conn_res)), BPRI_HI);
2128 	if (opt_mp == NULL) {
2129 		CONN_DEC_REF(acceptor->tcp_connp);
2130 		CONN_DEC_REF(eager->tcp_connp);
2131 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2132 		return;
2133 	}
2134 	DB_TYPE(opt_mp) = M_SETOPTS;
2135 	opt_mp->b_wptr += sizeof (struct tcp_options);
2136 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
2137 	tcpopt->to_flags = 0;
2138 
2139 	/*
2140 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2141 	 * from listener to acceptor.
2142 	 */
2143 	if (listener->tcp_bound_if != 0) {
2144 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
2145 		tcpopt->to_boundif = listener->tcp_bound_if;
2146 	}
2147 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2148 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
2149 	}
2150 
2151 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2152 	if ((mp1 = copymsg(mp)) == NULL) {
2153 		CONN_DEC_REF(acceptor->tcp_connp);
2154 		CONN_DEC_REF(eager->tcp_connp);
2155 		freemsg(opt_mp);
2156 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2157 		return;
2158 	}
2159 
2160 	tcr = (struct T_conn_res *)mp1->b_rptr;
2161 
2162 	/*
2163 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2164 	 * which allocates a larger mblk and appends the new
2165 	 * local address to the ok_ack.  The address is copied by
2166 	 * soaccept() for getsockname().
2167 	 */
2168 	{
2169 		int extra;
2170 
2171 		extra = (eager->tcp_family == AF_INET) ?
2172 		    sizeof (sin_t) : sizeof (sin6_t);
2173 
2174 		/*
2175 		 * Try to re-use mp, if possible.  Otherwise, allocate
2176 		 * an mblk and return it as ok_mp.  In any case, mp
2177 		 * is no longer usable upon return.
2178 		 */
2179 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2180 			CONN_DEC_REF(acceptor->tcp_connp);
2181 			CONN_DEC_REF(eager->tcp_connp);
2182 			freemsg(opt_mp);
2183 			/* Original mp has been freed by now, so use mp1 */
2184 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2185 			return;
2186 		}
2187 
2188 		mp = NULL;	/* We should never use mp after this point */
2189 
2190 		switch (extra) {
2191 		case sizeof (sin_t): {
2192 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2193 
2194 				ok_mp->b_wptr += extra;
2195 				sin->sin_family = AF_INET;
2196 				sin->sin_port = eager->tcp_lport;
2197 				sin->sin_addr.s_addr =
2198 				    eager->tcp_ipha->ipha_src;
2199 				break;
2200 			}
2201 		case sizeof (sin6_t): {
2202 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2203 
2204 				ok_mp->b_wptr += extra;
2205 				sin6->sin6_family = AF_INET6;
2206 				sin6->sin6_port = eager->tcp_lport;
2207 				if (eager->tcp_ipversion == IPV4_VERSION) {
2208 					sin6->sin6_flowinfo = 0;
2209 					IN6_IPADDR_TO_V4MAPPED(
2210 					    eager->tcp_ipha->ipha_src,
2211 					    &sin6->sin6_addr);
2212 				} else {
2213 					ASSERT(eager->tcp_ip6h != NULL);
2214 					sin6->sin6_flowinfo =
2215 					    eager->tcp_ip6h->ip6_vcf &
2216 					    ~IPV6_VERS_AND_FLOW_MASK;
2217 					sin6->sin6_addr =
2218 					    eager->tcp_ip6h->ip6_src;
2219 				}
2220 				sin6->sin6_scope_id = 0;
2221 				sin6->__sin6_src_id = 0;
2222 				break;
2223 			}
2224 		default:
2225 			break;
2226 		}
2227 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2228 	}
2229 
2230 	/*
2231 	 * If there are no options we know that the T_CONN_RES will
2232 	 * succeed. However, we can't send the T_OK_ACK upstream until
2233 	 * the tcp_accept_swap is done since it would be dangerous to
2234 	 * let the application start using the new fd prior to the swap.
2235 	 */
2236 	tcp_accept_swap(listener, acceptor, eager);
2237 
2238 	/*
2239 	 * tcp_accept_swap unlinks eager from listener but does not drop
2240 	 * the eager's reference on the listener.
2241 	 */
2242 	ASSERT(eager->tcp_listener == NULL);
2243 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2244 
2245 	/*
2246 	 * The eager is now associated with its own queue. Insert in
2247 	 * the hash so that the connection can be reused for a future
2248 	 * T_CONN_RES.
2249 	 */
2250 	tcp_acceptor_hash_insert(acceptor_id, eager);
2251 
2252 	/*
2253 	 * We now do the processing of options with T_CONN_RES.
2254 	 * We delay till now since we wanted to have queue to pass to
2255 	 * option processing routines that points back to the right
2256 	 * instance structure which does not happen until after
2257 	 * tcp_accept_swap().
2258 	 *
2259 	 * Note:
2260 	 * The sanity of the logic here assumes that whatever options
2261 	 * are appropriate to inherit from listner=>eager are done
2262 	 * before this point, and whatever were to be overridden (or not)
2263 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2264 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2265 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2266 	 * This may not be true at this point in time but can be fixed
2267 	 * independently. This option processing code starts with
2268 	 * the instantiated acceptor instance and the final queue at
2269 	 * this point.
2270 	 */
2271 
2272 	if (tcr->OPT_length != 0) {
2273 		/* Options to process */
2274 		int t_error = 0;
2275 		int sys_error = 0;
2276 		int do_disconnect = 0;
2277 
2278 		if (tcp_conprim_opt_process(eager, mp1,
2279 		    &do_disconnect, &t_error, &sys_error) < 0) {
2280 			eager->tcp_accept_error = 1;
2281 			if (do_disconnect) {
2282 				/*
2283 				 * An option failed which does not allow
2284 				 * connection to be accepted.
2285 				 *
2286 				 * We allow T_CONN_RES to succeed and
2287 				 * put a T_DISCON_IND on the eager queue.
2288 				 */
2289 				ASSERT(t_error == 0 && sys_error == 0);
2290 				eager->tcp_send_discon_ind = 1;
2291 			} else {
2292 				ASSERT(t_error != 0);
2293 				freemsg(ok_mp);
2294 				/*
2295 				 * Original mp was either freed or set
2296 				 * to ok_mp above, so use mp1 instead.
2297 				 */
2298 				tcp_err_ack(listener, mp1, t_error, sys_error);
2299 				goto finish;
2300 			}
2301 		}
2302 		/*
2303 		 * Most likely success in setting options (except if
2304 		 * eager->tcp_send_discon_ind set).
2305 		 * mp1 option buffer represented by OPT_length/offset
2306 		 * potentially modified and contains results of setting
2307 		 * options at this point
2308 		 */
2309 	}
2310 
2311 	/* We no longer need mp1, since all options processing has passed */
2312 	freemsg(mp1);
2313 
2314 	putnext(listener->tcp_rq, ok_mp);
2315 
2316 	mutex_enter(&listener->tcp_eager_lock);
2317 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2318 		tcp_t	*tail;
2319 		mblk_t	*conn_ind;
2320 
2321 		/*
2322 		 * This path should not be executed if listener and
2323 		 * acceptor streams are the same.
2324 		 */
2325 		ASSERT(listener != acceptor);
2326 
2327 		tcp = listener->tcp_eager_prev_q0;
2328 		/*
2329 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2330 		 * deferred T_conn_ind queue. We need to get to the head of
2331 		 * the queue in order to send up T_conn_ind the same order as
2332 		 * how the 3WHS is completed.
2333 		 */
2334 		while (tcp != listener) {
2335 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2336 				break;
2337 			else
2338 				tcp = tcp->tcp_eager_prev_q0;
2339 		}
2340 		ASSERT(tcp != listener);
2341 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2342 		ASSERT(conn_ind != NULL);
2343 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2344 
2345 		/* Move from q0 to q */
2346 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2347 		listener->tcp_conn_req_cnt_q0--;
2348 		listener->tcp_conn_req_cnt_q++;
2349 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2350 		    tcp->tcp_eager_prev_q0;
2351 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2352 		    tcp->tcp_eager_next_q0;
2353 		tcp->tcp_eager_prev_q0 = NULL;
2354 		tcp->tcp_eager_next_q0 = NULL;
2355 		tcp->tcp_conn_def_q0 = B_FALSE;
2356 
2357 		/* Make sure the tcp isn't in the list of droppables */
2358 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2359 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2360 
2361 		/*
2362 		 * Insert at end of the queue because sockfs sends
2363 		 * down T_CONN_RES in chronological order. Leaving
2364 		 * the older conn indications at front of the queue
2365 		 * helps reducing search time.
2366 		 */
2367 		tail = listener->tcp_eager_last_q;
2368 		if (tail != NULL)
2369 			tail->tcp_eager_next_q = tcp;
2370 		else
2371 			listener->tcp_eager_next_q = tcp;
2372 		listener->tcp_eager_last_q = tcp;
2373 		tcp->tcp_eager_next_q = NULL;
2374 		mutex_exit(&listener->tcp_eager_lock);
2375 		putnext(tcp->tcp_rq, conn_ind);
2376 	} else {
2377 		mutex_exit(&listener->tcp_eager_lock);
2378 	}
2379 
2380 	/*
2381 	 * Done with the acceptor - free it
2382 	 *
2383 	 * Note: from this point on, no access to listener should be made
2384 	 * as listener can be equal to acceptor.
2385 	 */
2386 finish:
2387 	ASSERT(acceptor->tcp_detached);
2388 	ASSERT(tcps->tcps_g_q != NULL);
2389 	ASSERT(!IPCL_IS_NONSTR(acceptor->tcp_connp));
2390 	acceptor->tcp_rq = tcps->tcps_g_q;
2391 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2392 	(void) tcp_clean_death(acceptor, 0, 2);
2393 	CONN_DEC_REF(acceptor->tcp_connp);
2394 
2395 	/*
2396 	 * In case we already received a FIN we have to make tcp_rput send
2397 	 * the ordrel_ind. This will also send up a window update if the window
2398 	 * has opened up.
2399 	 *
2400 	 * In the normal case of a successful connection acceptance
2401 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2402 	 * indication that this was just accepted. This tells tcp_rput to
2403 	 * pass up any data queued in tcp_rcv_list.
2404 	 *
2405 	 * In the fringe case where options sent with T_CONN_RES failed and
2406 	 * we required, we would be indicating a T_DISCON_IND to blow
2407 	 * away this connection.
2408 	 */
2409 
2410 	/*
2411 	 * XXX: we currently have a problem if XTI application closes the
2412 	 * acceptor stream in between. This problem exists in on10-gate also
2413 	 * and is well know but nothing can be done short of major rewrite
2414 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2415 	 * eager same squeue as listener (we can distinguish non socket
2416 	 * listeners at the time of handling a SYN in tcp_conn_request)
2417 	 * and do most of the work that tcp_accept_finish does here itself
2418 	 * and then get behind the acceptor squeue to access the acceptor
2419 	 * queue.
2420 	 */
2421 	/*
2422 	 * We already have a ref on tcp so no need to do one before squeue_enter
2423 	 */
2424 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, opt_mp, tcp_accept_finish,
2425 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_ACCEPT_FINISH);
2426 }
2427 
2428 /*
2429  * Swap information between the eager and acceptor for a TLI/XTI client.
2430  * The sockfs accept is done on the acceptor stream and control goes
2431  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2432  * called. In either case, both the eager and listener are in their own
2433  * perimeter (squeue) and the code has to deal with potential race.
2434  *
2435  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2436  */
2437 static void
2438 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2439 {
2440 	conn_t	*econnp, *aconnp;
2441 
2442 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2443 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2444 	ASSERT(!eager->tcp_hard_bound);
2445 	ASSERT(!TCP_IS_SOCKET(acceptor));
2446 	ASSERT(!TCP_IS_SOCKET(eager));
2447 	ASSERT(!TCP_IS_SOCKET(listener));
2448 
2449 	acceptor->tcp_detached = B_TRUE;
2450 	/*
2451 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2452 	 * the acceptor id.
2453 	 */
2454 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2455 
2456 	/* remove eager from listen list... */
2457 	mutex_enter(&listener->tcp_eager_lock);
2458 	tcp_eager_unlink(eager);
2459 	ASSERT(eager->tcp_eager_next_q == NULL &&
2460 	    eager->tcp_eager_last_q == NULL);
2461 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2462 	    eager->tcp_eager_prev_q0 == NULL);
2463 	mutex_exit(&listener->tcp_eager_lock);
2464 	eager->tcp_rq = acceptor->tcp_rq;
2465 	eager->tcp_wq = acceptor->tcp_wq;
2466 
2467 	econnp = eager->tcp_connp;
2468 	aconnp = acceptor->tcp_connp;
2469 
2470 	eager->tcp_rq->q_ptr = econnp;
2471 	eager->tcp_wq->q_ptr = econnp;
2472 
2473 	/*
2474 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2475 	 * which might be a different squeue from our peer TCP instance.
2476 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2477 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2478 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2479 	 * above reach global visibility prior to the clearing of tcp_detached.
2480 	 */
2481 	membar_producer();
2482 	eager->tcp_detached = B_FALSE;
2483 
2484 	ASSERT(eager->tcp_ack_tid == 0);
2485 
2486 	econnp->conn_dev = aconnp->conn_dev;
2487 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2488 	ASSERT(econnp->conn_minor_arena != NULL);
2489 	if (eager->tcp_cred != NULL)
2490 		crfree(eager->tcp_cred);
2491 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2492 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2493 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2494 
2495 	aconnp->conn_cred = NULL;
2496 
2497 	econnp->conn_zoneid = aconnp->conn_zoneid;
2498 	econnp->conn_allzones = aconnp->conn_allzones;
2499 
2500 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2501 	aconnp->conn_mac_exempt = B_FALSE;
2502 
2503 	ASSERT(aconnp->conn_peercred == NULL);
2504 
2505 	/* Do the IPC initialization */
2506 	CONN_INC_REF(econnp);
2507 
2508 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2509 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2510 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2511 
2512 	/* Done with old IPC. Drop its ref on its connp */
2513 	CONN_DEC_REF(aconnp);
2514 }
2515 
2516 
2517 /*
2518  * Adapt to the information, such as rtt and rtt_sd, provided from the
2519  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2520  *
2521  * Checks for multicast and broadcast destination address.
2522  * Returns zero on failure; non-zero if ok.
2523  *
2524  * Note that the MSS calculation here is based on the info given in
2525  * the IRE.  We do not do any calculation based on TCP options.  They
2526  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2527  * knows which options to use.
2528  *
2529  * Note on how TCP gets its parameters for a connection.
2530  *
2531  * When a tcp_t structure is allocated, it gets all the default parameters.
2532  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2533  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2534  * default.
2535  *
2536  * An incoming SYN with a multicast or broadcast destination address, is dropped
2537  * in 1 of 2 places.
2538  *
2539  * 1. If the packet was received over the wire it is dropped in
2540  * ip_rput_process_broadcast()
2541  *
2542  * 2. If the packet was received through internal IP loopback, i.e. the packet
2543  * was generated and received on the same machine, it is dropped in
2544  * ip_wput_local()
2545  *
2546  * An incoming SYN with a multicast or broadcast source address is always
2547  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2548  * reject an attempt to connect to a broadcast or multicast (destination)
2549  * address.
2550  */
2551 static int
2552 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2553 {
2554 	tcp_hsp_t	*hsp;
2555 	ire_t		*ire;
2556 	ire_t		*sire = NULL;
2557 	iulp_t		*ire_uinfo = NULL;
2558 	uint32_t	mss_max;
2559 	uint32_t	mss;
2560 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2561 	conn_t		*connp = tcp->tcp_connp;
2562 	boolean_t	ire_cacheable = B_FALSE;
2563 	zoneid_t	zoneid = connp->conn_zoneid;
2564 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2565 	    MATCH_IRE_SECATTR;
2566 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2567 	ill_t		*ill = NULL;
2568 	boolean_t	incoming = (ire_mp == NULL);
2569 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2570 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2571 
2572 	ASSERT(connp->conn_ire_cache == NULL);
2573 
2574 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2575 
2576 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2577 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2578 			return (0);
2579 		}
2580 		/*
2581 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2582 		 * for the destination with the nexthop as gateway.
2583 		 * ire_ctable_lookup() is used because this particular
2584 		 * ire, if it exists, will be marked private.
2585 		 * If that is not available, use the interface ire
2586 		 * for the nexthop.
2587 		 *
2588 		 * TSol: tcp_update_label will detect label mismatches based
2589 		 * only on the destination's label, but that would not
2590 		 * detect label mismatches based on the security attributes
2591 		 * of routes or next hop gateway. Hence we need to pass the
2592 		 * label to ire_ftable_lookup below in order to locate the
2593 		 * right prefix (and/or) ire cache. Similarly we also need
2594 		 * pass the label to the ire_cache_lookup below to locate
2595 		 * the right ire that also matches on the label.
2596 		 */
2597 		if (tcp->tcp_connp->conn_nexthop_set) {
2598 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2599 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2600 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2601 			    ipst);
2602 			if (ire == NULL) {
2603 				ire = ire_ftable_lookup(
2604 				    tcp->tcp_connp->conn_nexthop_v4,
2605 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2606 				    tsl, match_flags, ipst);
2607 				if (ire == NULL)
2608 					return (0);
2609 			} else {
2610 				ire_uinfo = &ire->ire_uinfo;
2611 			}
2612 		} else {
2613 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2614 			    zoneid, tsl, ipst);
2615 			if (ire != NULL) {
2616 				ire_cacheable = B_TRUE;
2617 				ire_uinfo = (ire_mp != NULL) ?
2618 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2619 				    &ire->ire_uinfo;
2620 
2621 			} else {
2622 				if (ire_mp == NULL) {
2623 					ire = ire_ftable_lookup(
2624 					    tcp->tcp_connp->conn_rem,
2625 					    0, 0, 0, NULL, &sire, zoneid, 0,
2626 					    tsl, (MATCH_IRE_RECURSIVE |
2627 					    MATCH_IRE_DEFAULT), ipst);
2628 					if (ire == NULL)
2629 						return (0);
2630 					ire_uinfo = (sire != NULL) ?
2631 					    &sire->ire_uinfo :
2632 					    &ire->ire_uinfo;
2633 				} else {
2634 					ire = (ire_t *)ire_mp->b_rptr;
2635 					ire_uinfo =
2636 					    &((ire_t *)
2637 					    ire_mp->b_rptr)->ire_uinfo;
2638 				}
2639 			}
2640 		}
2641 		ASSERT(ire != NULL);
2642 
2643 		if ((ire->ire_src_addr == INADDR_ANY) ||
2644 		    (ire->ire_type & IRE_BROADCAST)) {
2645 			/*
2646 			 * ire->ire_mp is non null when ire_mp passed in is used
2647 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2648 			 */
2649 			if (ire->ire_mp == NULL)
2650 				ire_refrele(ire);
2651 			if (sire != NULL)
2652 				ire_refrele(sire);
2653 			return (0);
2654 		}
2655 
2656 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2657 			ipaddr_t src_addr;
2658 
2659 			/*
2660 			 * ip_bind_connected() has stored the correct source
2661 			 * address in conn_src.
2662 			 */
2663 			src_addr = tcp->tcp_connp->conn_src;
2664 			tcp->tcp_ipha->ipha_src = src_addr;
2665 			/*
2666 			 * Copy of the src addr. in tcp_t is needed
2667 			 * for the lookup funcs.
2668 			 */
2669 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2670 		}
2671 		/*
2672 		 * Set the fragment bit so that IP will tell us if the MTU
2673 		 * should change. IP tells us the latest setting of
2674 		 * ip_path_mtu_discovery through ire_frag_flag.
2675 		 */
2676 		if (ipst->ips_ip_path_mtu_discovery) {
2677 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2678 			    htons(IPH_DF);
2679 		}
2680 		/*
2681 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2682 		 * for IP_NEXTHOP. No cache ire has been found for the
2683 		 * destination and we are working with the nexthop's
2684 		 * interface ire. Since we need to forward all packets
2685 		 * to the nexthop first, we "blindly" set tcp_localnet
2686 		 * to false, eventhough the destination may also be
2687 		 * onlink.
2688 		 */
2689 		if (ire_uinfo == NULL)
2690 			tcp->tcp_localnet = 0;
2691 		else
2692 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2693 	} else {
2694 		/*
2695 		 * For incoming connection ire_mp = NULL
2696 		 * For outgoing connection ire_mp != NULL
2697 		 * Technically we should check conn_incoming_ill
2698 		 * when ire_mp is NULL and conn_outgoing_ill when
2699 		 * ire_mp is non-NULL. But this is performance
2700 		 * critical path and for IPV*_BOUND_IF, outgoing
2701 		 * and incoming ill are always set to the same value.
2702 		 */
2703 		ill_t	*dst_ill = NULL;
2704 		ipif_t  *dst_ipif = NULL;
2705 
2706 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2707 
2708 		if (connp->conn_outgoing_ill != NULL) {
2709 			/* Outgoing or incoming path */
2710 			int   err;
2711 
2712 			dst_ill = conn_get_held_ill(connp,
2713 			    &connp->conn_outgoing_ill, &err);
2714 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2715 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2716 				return (0);
2717 			}
2718 			match_flags |= MATCH_IRE_ILL;
2719 			dst_ipif = dst_ill->ill_ipif;
2720 		}
2721 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2722 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2723 
2724 		if (ire != NULL) {
2725 			ire_cacheable = B_TRUE;
2726 			ire_uinfo = (ire_mp != NULL) ?
2727 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2728 			    &ire->ire_uinfo;
2729 		} else {
2730 			if (ire_mp == NULL) {
2731 				ire = ire_ftable_lookup_v6(
2732 				    &tcp->tcp_connp->conn_remv6,
2733 				    0, 0, 0, dst_ipif, &sire, zoneid,
2734 				    0, tsl, match_flags, ipst);
2735 				if (ire == NULL) {
2736 					if (dst_ill != NULL)
2737 						ill_refrele(dst_ill);
2738 					return (0);
2739 				}
2740 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2741 				    &ire->ire_uinfo;
2742 			} else {
2743 				ire = (ire_t *)ire_mp->b_rptr;
2744 				ire_uinfo =
2745 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2746 			}
2747 		}
2748 		if (dst_ill != NULL)
2749 			ill_refrele(dst_ill);
2750 
2751 		ASSERT(ire != NULL);
2752 		ASSERT(ire_uinfo != NULL);
2753 
2754 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2755 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2756 			/*
2757 			 * ire->ire_mp is non null when ire_mp passed in is used
2758 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2759 			 */
2760 			if (ire->ire_mp == NULL)
2761 				ire_refrele(ire);
2762 			if (sire != NULL)
2763 				ire_refrele(sire);
2764 			return (0);
2765 		}
2766 
2767 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2768 			in6_addr_t	src_addr;
2769 
2770 			/*
2771 			 * ip_bind_connected_v6() has stored the correct source
2772 			 * address per IPv6 addr. selection policy in
2773 			 * conn_src_v6.
2774 			 */
2775 			src_addr = tcp->tcp_connp->conn_srcv6;
2776 
2777 			tcp->tcp_ip6h->ip6_src = src_addr;
2778 			/*
2779 			 * Copy of the src addr. in tcp_t is needed
2780 			 * for the lookup funcs.
2781 			 */
2782 			tcp->tcp_ip_src_v6 = src_addr;
2783 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2784 			    &connp->conn_srcv6));
2785 		}
2786 		tcp->tcp_localnet =
2787 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2788 	}
2789 
2790 	/*
2791 	 * This allows applications to fail quickly when connections are made
2792 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2793 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2794 	 */
2795 	if ((ire->ire_flags & RTF_REJECT) &&
2796 	    (ire->ire_flags & RTF_PRIVATE))
2797 		goto error;
2798 
2799 	/*
2800 	 * Make use of the cached rtt and rtt_sd values to calculate the
2801 	 * initial RTO.  Note that they are already initialized in
2802 	 * tcp_init_values().
2803 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2804 	 * IP_NEXTHOP, but instead are using the interface ire for the
2805 	 * nexthop, then we do not use the ire_uinfo from that ire to
2806 	 * do any initializations.
2807 	 */
2808 	if (ire_uinfo != NULL) {
2809 		if (ire_uinfo->iulp_rtt != 0) {
2810 			clock_t	rto;
2811 
2812 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2813 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2814 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2815 			    tcps->tcps_rexmit_interval_extra +
2816 			    (tcp->tcp_rtt_sa >> 5);
2817 
2818 			if (rto > tcps->tcps_rexmit_interval_max) {
2819 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2820 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2821 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2822 			} else {
2823 				tcp->tcp_rto = rto;
2824 			}
2825 		}
2826 		if (ire_uinfo->iulp_ssthresh != 0)
2827 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2828 		else
2829 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2830 		if (ire_uinfo->iulp_spipe > 0) {
2831 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2832 			    tcps->tcps_max_buf);
2833 			if (tcps->tcps_snd_lowat_fraction != 0)
2834 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2835 				    tcps->tcps_snd_lowat_fraction;
2836 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2837 		}
2838 		/*
2839 		 * Note that up till now, acceptor always inherits receive
2840 		 * window from the listener.  But if there is a metrics
2841 		 * associated with a host, we should use that instead of
2842 		 * inheriting it from listener. Thus we need to pass this
2843 		 * info back to the caller.
2844 		 */
2845 		if (ire_uinfo->iulp_rpipe > 0) {
2846 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2847 			    tcps->tcps_max_buf);
2848 		}
2849 
2850 		if (ire_uinfo->iulp_rtomax > 0) {
2851 			tcp->tcp_second_timer_threshold =
2852 			    ire_uinfo->iulp_rtomax;
2853 		}
2854 
2855 		/*
2856 		 * Use the metric option settings, iulp_tstamp_ok and
2857 		 * iulp_wscale_ok, only for active open. What this means
2858 		 * is that if the other side uses timestamp or window
2859 		 * scale option, TCP will also use those options. That
2860 		 * is for passive open.  If the application sets a
2861 		 * large window, window scale is enabled regardless of
2862 		 * the value in iulp_wscale_ok.  This is the behavior
2863 		 * since 2.6.  So we keep it.
2864 		 * The only case left in passive open processing is the
2865 		 * check for SACK.
2866 		 * For ECN, it should probably be like SACK.  But the
2867 		 * current value is binary, so we treat it like the other
2868 		 * cases.  The metric only controls active open.For passive
2869 		 * open, the ndd param, tcp_ecn_permitted, controls the
2870 		 * behavior.
2871 		 */
2872 		if (!tcp_detached) {
2873 			/*
2874 			 * The if check means that the following can only
2875 			 * be turned on by the metrics only IRE, but not off.
2876 			 */
2877 			if (ire_uinfo->iulp_tstamp_ok)
2878 				tcp->tcp_snd_ts_ok = B_TRUE;
2879 			if (ire_uinfo->iulp_wscale_ok)
2880 				tcp->tcp_snd_ws_ok = B_TRUE;
2881 			if (ire_uinfo->iulp_sack == 2)
2882 				tcp->tcp_snd_sack_ok = B_TRUE;
2883 			if (ire_uinfo->iulp_ecn_ok)
2884 				tcp->tcp_ecn_ok = B_TRUE;
2885 		} else {
2886 			/*
2887 			 * Passive open.
2888 			 *
2889 			 * As above, the if check means that SACK can only be
2890 			 * turned on by the metric only IRE.
2891 			 */
2892 			if (ire_uinfo->iulp_sack > 0) {
2893 				tcp->tcp_snd_sack_ok = B_TRUE;
2894 			}
2895 		}
2896 	}
2897 
2898 
2899 	/*
2900 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2901 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2902 	 * length of all those options exceeds 28 bytes.  But because
2903 	 * of the tcp_mss_min check below, we may not have a problem if
2904 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2905 	 * the negative problem still exists.  And the check defeats PMTUd.
2906 	 * In fact, if PMTUd finds that the MSS should be smaller than
2907 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2908 	 * value.
2909 	 *
2910 	 * We do not deal with that now.  All those problems related to
2911 	 * PMTUd will be fixed later.
2912 	 */
2913 	ASSERT(ire->ire_max_frag != 0);
2914 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2915 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2916 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2917 			mss = MIN(mss, IPV6_MIN_MTU);
2918 		}
2919 	}
2920 
2921 	/* Sanity check for MSS value. */
2922 	if (tcp->tcp_ipversion == IPV4_VERSION)
2923 		mss_max = tcps->tcps_mss_max_ipv4;
2924 	else
2925 		mss_max = tcps->tcps_mss_max_ipv6;
2926 
2927 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2928 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2929 		/*
2930 		 * After receiving an ICMPv6 "packet too big" message with a
2931 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2932 		 * will insert a 8-byte fragment header in every packet; we
2933 		 * reduce the MSS by that amount here.
2934 		 */
2935 		mss -= sizeof (ip6_frag_t);
2936 	}
2937 
2938 	if (tcp->tcp_ipsec_overhead == 0)
2939 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2940 
2941 	mss -= tcp->tcp_ipsec_overhead;
2942 
2943 	if (mss < tcps->tcps_mss_min)
2944 		mss = tcps->tcps_mss_min;
2945 	if (mss > mss_max)
2946 		mss = mss_max;
2947 
2948 	/* Note that this is the maximum MSS, excluding all options. */
2949 	tcp->tcp_mss = mss;
2950 
2951 	/*
2952 	 * Initialize the ISS here now that we have the full connection ID.
2953 	 * The RFC 1948 method of initial sequence number generation requires
2954 	 * knowledge of the full connection ID before setting the ISS.
2955 	 */
2956 
2957 	tcp_iss_init(tcp);
2958 
2959 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2960 		tcp->tcp_loopback = B_TRUE;
2961 
2962 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2963 		hsp = tcp_hsp_lookup(tcp->tcp_remote, tcps);
2964 	} else {
2965 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6, tcps);
2966 	}
2967 
2968 	if (hsp != NULL) {
2969 		/* Only modify if we're going to make them bigger */
2970 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2971 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2972 			if (tcps->tcps_snd_lowat_fraction != 0)
2973 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2974 				    tcps->tcps_snd_lowat_fraction;
2975 		}
2976 
2977 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2978 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2979 		}
2980 
2981 		/* Copy timestamp flag only for active open */
2982 		if (!tcp_detached)
2983 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2984 	}
2985 
2986 	if (sire != NULL)
2987 		IRE_REFRELE(sire);
2988 
2989 	/*
2990 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2991 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2992 	 */
2993 	if (tcp->tcp_loopback ||
2994 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2995 		/*
2996 		 * For incoming, see if this tcp may be MDT-capable.  For
2997 		 * outgoing, this process has been taken care of through
2998 		 * tcp_rput_other.
2999 		 */
3000 		tcp_ire_ill_check(tcp, ire, ill, incoming);
3001 		tcp->tcp_ire_ill_check_done = B_TRUE;
3002 	}
3003 
3004 	mutex_enter(&connp->conn_lock);
3005 	/*
3006 	 * Make sure that conn is not marked incipient
3007 	 * for incoming connections. A blind
3008 	 * removal of incipient flag is cheaper than
3009 	 * check and removal.
3010 	 */
3011 	connp->conn_state_flags &= ~CONN_INCIPIENT;
3012 
3013 	/*
3014 	 * Must not cache forwarding table routes
3015 	 * or recache an IRE after the conn_t has
3016 	 * had conn_ire_cache cleared and is flagged
3017 	 * unusable, (see the CONN_CACHE_IRE() macro).
3018 	 */
3019 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
3020 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
3021 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
3022 			connp->conn_ire_cache = ire;
3023 			IRE_UNTRACE_REF(ire);
3024 			rw_exit(&ire->ire_bucket->irb_lock);
3025 			mutex_exit(&connp->conn_lock);
3026 			return (1);
3027 		}
3028 		rw_exit(&ire->ire_bucket->irb_lock);
3029 	}
3030 	mutex_exit(&connp->conn_lock);
3031 
3032 	if (ire->ire_mp == NULL)
3033 		ire_refrele(ire);
3034 	return (1);
3035 
3036 error:
3037 	if (ire->ire_mp == NULL)
3038 		ire_refrele(ire);
3039 	if (sire != NULL)
3040 		ire_refrele(sire);
3041 	return (0);
3042 }
3043 
3044 static void
3045 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
3046 {
3047 	int	error;
3048 	conn_t	*connp = tcp->tcp_connp;
3049 	struct sockaddr	*sa;
3050 	mblk_t  *mp1;
3051 	struct T_bind_req *tbr;
3052 	int	backlog;
3053 	socklen_t	len;
3054 	sin_t	*sin;
3055 	sin6_t	*sin6;
3056 
3057 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3058 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3059 		if (tcp->tcp_debug) {
3060 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3061 			    "tcp_tpi_bind: bad req, len %u",
3062 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3063 		}
3064 		tcp_err_ack(tcp, mp, TPROTO, 0);
3065 		return;
3066 	}
3067 	/* Make sure the largest address fits */
3068 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3069 	if (mp1 == NULL) {
3070 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3071 		return;
3072 	}
3073 	mp = mp1;
3074 	tbr = (struct T_bind_req *)mp->b_rptr;
3075 
3076 	backlog = tbr->CONIND_number;
3077 	len = tbr->ADDR_length;
3078 
3079 	switch (len) {
3080 	case 0:		/* request for a generic port */
3081 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3082 		if (tcp->tcp_family == AF_INET) {
3083 			tbr->ADDR_length = sizeof (sin_t);
3084 			sin = (sin_t *)&tbr[1];
3085 			*sin = sin_null;
3086 			sin->sin_family = AF_INET;
3087 			sa = (struct sockaddr *)sin;
3088 			len = sizeof (sin_t);
3089 			mp->b_wptr = (uchar_t *)&sin[1];
3090 		} else {
3091 			ASSERT(tcp->tcp_family == AF_INET6);
3092 			tbr->ADDR_length = sizeof (sin6_t);
3093 			sin6 = (sin6_t *)&tbr[1];
3094 			*sin6 = sin6_null;
3095 			sin6->sin6_family = AF_INET6;
3096 			sa = (struct sockaddr *)sin6;
3097 			len = sizeof (sin6_t);
3098 			mp->b_wptr = (uchar_t *)&sin6[1];
3099 		}
3100 		break;
3101 
3102 	case sizeof (sin_t):    /* Complete IPv4 address */
3103 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
3104 		    sizeof (sin_t));
3105 		break;
3106 
3107 	case sizeof (sin6_t): /* Complete IPv6 address */
3108 		sa = (struct sockaddr *)mi_offset_param(mp,
3109 		    tbr->ADDR_offset, sizeof (sin6_t));
3110 		break;
3111 
3112 	default:
3113 		if (tcp->tcp_debug) {
3114 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3115 			    "tcp_tpi_bind: bad address length, %d",
3116 			    tbr->ADDR_length);
3117 		}
3118 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3119 		return;
3120 	}
3121 
3122 	error = tcp_bind_check(connp, sa, len, DB_CRED(mp),
3123 	    tbr->PRIM_type != O_T_BIND_REQ);
3124 	if (error == 0) {
3125 		if (tcp->tcp_family == AF_INET) {
3126 			sin = (sin_t *)sa;
3127 			sin->sin_port = tcp->tcp_lport;
3128 		} else {
3129 			sin6 = (sin6_t *)sa;
3130 			sin6->sin6_port = tcp->tcp_lport;
3131 		}
3132 
3133 		if (backlog > 0) {
3134 			error = tcp_do_listen(connp, backlog, DB_CRED(mp));
3135 		}
3136 	}
3137 done:
3138 	if (error > 0) {
3139 		tcp_err_ack(tcp, mp, TSYSERR, error);
3140 	} else if (error < 0) {
3141 		tcp_err_ack(tcp, mp, -error, 0);
3142 	} else {
3143 		mp->b_datap->db_type = M_PCPROTO;
3144 		tbr->PRIM_type = T_BIND_ACK;
3145 		putnext(tcp->tcp_rq, mp);
3146 	}
3147 }
3148 
3149 /*
3150  * If the "bind_to_req_port_only" parameter is set, if the requested port
3151  * number is available, return it, If not return 0
3152  *
3153  * If "bind_to_req_port_only" parameter is not set and
3154  * If the requested port number is available, return it.  If not, return
3155  * the first anonymous port we happen across.  If no anonymous ports are
3156  * available, return 0. addr is the requested local address, if any.
3157  *
3158  * In either case, when succeeding update the tcp_t to record the port number
3159  * and insert it in the bind hash table.
3160  *
3161  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3162  * without setting SO_REUSEADDR. This is needed so that they
3163  * can be viewed as two independent transport protocols.
3164  */
3165 static in_port_t
3166 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3167     int reuseaddr, boolean_t quick_connect,
3168     boolean_t bind_to_req_port_only, boolean_t user_specified)
3169 {
3170 	/* number of times we have run around the loop */
3171 	int count = 0;
3172 	/* maximum number of times to run around the loop */
3173 	int loopmax;
3174 	conn_t *connp = tcp->tcp_connp;
3175 	zoneid_t zoneid = connp->conn_zoneid;
3176 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3177 
3178 	/*
3179 	 * Lookup for free addresses is done in a loop and "loopmax"
3180 	 * influences how long we spin in the loop
3181 	 */
3182 	if (bind_to_req_port_only) {
3183 		/*
3184 		 * If the requested port is busy, don't bother to look
3185 		 * for a new one. Setting loop maximum count to 1 has
3186 		 * that effect.
3187 		 */
3188 		loopmax = 1;
3189 	} else {
3190 		/*
3191 		 * If the requested port is busy, look for a free one
3192 		 * in the anonymous port range.
3193 		 * Set loopmax appropriately so that one does not look
3194 		 * forever in the case all of the anonymous ports are in use.
3195 		 */
3196 		if (tcp->tcp_anon_priv_bind) {
3197 			/*
3198 			 * loopmax =
3199 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3200 			 */
3201 			loopmax = IPPORT_RESERVED -
3202 			    tcps->tcps_min_anonpriv_port;
3203 		} else {
3204 			loopmax = (tcps->tcps_largest_anon_port -
3205 			    tcps->tcps_smallest_anon_port + 1);
3206 		}
3207 	}
3208 	do {
3209 		uint16_t	lport;
3210 		tf_t		*tbf;
3211 		tcp_t		*ltcp;
3212 		conn_t		*lconnp;
3213 
3214 		lport = htons(port);
3215 
3216 		/*
3217 		 * Ensure that the tcp_t is not currently in the bind hash.
3218 		 * Hold the lock on the hash bucket to ensure that
3219 		 * the duplicate check plus the insertion is an atomic
3220 		 * operation.
3221 		 *
3222 		 * This function does an inline lookup on the bind hash list
3223 		 * Make sure that we access only members of tcp_t
3224 		 * and that we don't look at tcp_tcp, since we are not
3225 		 * doing a CONN_INC_REF.
3226 		 */
3227 		tcp_bind_hash_remove(tcp);
3228 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3229 		mutex_enter(&tbf->tf_lock);
3230 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3231 		    ltcp = ltcp->tcp_bind_hash) {
3232 			if (lport == ltcp->tcp_lport)
3233 				break;
3234 		}
3235 
3236 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
3237 			boolean_t not_socket;
3238 			boolean_t exclbind;
3239 
3240 			lconnp = ltcp->tcp_connp;
3241 
3242 			/*
3243 			 * On a labeled system, we must treat bindings to ports
3244 			 * on shared IP addresses by sockets with MAC exemption
3245 			 * privilege as being in all zones, as there's
3246 			 * otherwise no way to identify the right receiver.
3247 			 */
3248 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3249 			    IPCL_ZONE_MATCH(connp,
3250 			    ltcp->tcp_connp->conn_zoneid)) &&
3251 			    !lconnp->conn_mac_exempt &&
3252 			    !connp->conn_mac_exempt)
3253 				continue;
3254 
3255 			/*
3256 			 * If TCP_EXCLBIND is set for either the bound or
3257 			 * binding endpoint, the semantics of bind
3258 			 * is changed according to the following.
3259 			 *
3260 			 * spec = specified address (v4 or v6)
3261 			 * unspec = unspecified address (v4 or v6)
3262 			 * A = specified addresses are different for endpoints
3263 			 *
3264 			 * bound	bind to		allowed
3265 			 * -------------------------------------
3266 			 * unspec	unspec		no
3267 			 * unspec	spec		no
3268 			 * spec		unspec		no
3269 			 * spec		spec		yes if A
3270 			 *
3271 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3272 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3273 			 *
3274 			 * Note:
3275 			 *
3276 			 * 1. Because of TLI semantics, an endpoint can go
3277 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3278 			 * TCPS_BOUND, depending on whether it is originally
3279 			 * a listener or not.  That is why we need to check
3280 			 * for states greater than or equal to TCPS_BOUND
3281 			 * here.
3282 			 *
3283 			 * 2. Ideally, we should only check for state equals
3284 			 * to TCPS_LISTEN. And the following check should be
3285 			 * added.
3286 			 *
3287 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3288 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3289 			 *		...
3290 			 * }
3291 			 *
3292 			 * The semantics will be changed to this.  If the
3293 			 * endpoint on the list is in state not equal to
3294 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3295 			 * set, let the bind succeed.
3296 			 *
3297 			 * Because of (1), we cannot do that for TLI
3298 			 * endpoints.  But we can do that for socket endpoints.
3299 			 * If in future, we can change this going back
3300 			 * semantics, we can use the above check for TLI also.
3301 			 */
3302 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3303 			    TCP_IS_SOCKET(tcp));
3304 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3305 
3306 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3307 			    (exclbind && (not_socket ||
3308 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3309 				if (V6_OR_V4_INADDR_ANY(
3310 				    ltcp->tcp_bound_source_v6) ||
3311 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3312 				    IN6_ARE_ADDR_EQUAL(laddr,
3313 				    &ltcp->tcp_bound_source_v6)) {
3314 					break;
3315 				}
3316 				continue;
3317 			}
3318 
3319 			/*
3320 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3321 			 * have disjoint port number spaces, if *_EXCLBIND
3322 			 * is not set and only if the application binds to a
3323 			 * specific port. We use the same autoassigned port
3324 			 * number space for IPv4 and IPv6 sockets.
3325 			 */
3326 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3327 			    bind_to_req_port_only)
3328 				continue;
3329 
3330 			/*
3331 			 * Ideally, we should make sure that the source
3332 			 * address, remote address, and remote port in the
3333 			 * four tuple for this tcp-connection is unique.
3334 			 * However, trying to find out the local source
3335 			 * address would require too much code duplication
3336 			 * with IP, since IP needs needs to have that code
3337 			 * to support userland TCP implementations.
3338 			 */
3339 			if (quick_connect &&
3340 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3341 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3342 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3343 			    &ltcp->tcp_remote_v6)))
3344 				continue;
3345 
3346 			if (!reuseaddr) {
3347 				/*
3348 				 * No socket option SO_REUSEADDR.
3349 				 * If existing port is bound to
3350 				 * a non-wildcard IP address
3351 				 * and the requesting stream is
3352 				 * bound to a distinct
3353 				 * different IP addresses
3354 				 * (non-wildcard, also), keep
3355 				 * going.
3356 				 */
3357 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3358 				    !V6_OR_V4_INADDR_ANY(
3359 				    ltcp->tcp_bound_source_v6) &&
3360 				    !IN6_ARE_ADDR_EQUAL(laddr,
3361 				    &ltcp->tcp_bound_source_v6))
3362 					continue;
3363 				if (ltcp->tcp_state >= TCPS_BOUND) {
3364 					/*
3365 					 * This port is being used and
3366 					 * its state is >= TCPS_BOUND,
3367 					 * so we can't bind to it.
3368 					 */
3369 					break;
3370 				}
3371 			} else {
3372 				/*
3373 				 * socket option SO_REUSEADDR is set on the
3374 				 * binding tcp_t.
3375 				 *
3376 				 * If two streams are bound to
3377 				 * same IP address or both addr
3378 				 * and bound source are wildcards
3379 				 * (INADDR_ANY), we want to stop
3380 				 * searching.
3381 				 * We have found a match of IP source
3382 				 * address and source port, which is
3383 				 * refused regardless of the
3384 				 * SO_REUSEADDR setting, so we break.
3385 				 */
3386 				if (IN6_ARE_ADDR_EQUAL(laddr,
3387 				    &ltcp->tcp_bound_source_v6) &&
3388 				    (ltcp->tcp_state == TCPS_LISTEN ||
3389 				    ltcp->tcp_state == TCPS_BOUND))
3390 					break;
3391 			}
3392 		}
3393 		if (ltcp != NULL) {
3394 			/* The port number is busy */
3395 			mutex_exit(&tbf->tf_lock);
3396 		} else {
3397 			/*
3398 			 * This port is ours. Insert in fanout and mark as
3399 			 * bound to prevent others from getting the port
3400 			 * number.
3401 			 */
3402 			tcp->tcp_state = TCPS_BOUND;
3403 			tcp->tcp_lport = htons(port);
3404 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3405 
3406 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3407 			    tcp->tcp_lport)] == tbf);
3408 			tcp_bind_hash_insert(tbf, tcp, 1);
3409 
3410 			mutex_exit(&tbf->tf_lock);
3411 
3412 			/*
3413 			 * We don't want tcp_next_port_to_try to "inherit"
3414 			 * a port number supplied by the user in a bind.
3415 			 */
3416 			if (user_specified)
3417 				return (port);
3418 
3419 			/*
3420 			 * This is the only place where tcp_next_port_to_try
3421 			 * is updated. After the update, it may or may not
3422 			 * be in the valid range.
3423 			 */
3424 			if (!tcp->tcp_anon_priv_bind)
3425 				tcps->tcps_next_port_to_try = port + 1;
3426 			return (port);
3427 		}
3428 
3429 		if (tcp->tcp_anon_priv_bind) {
3430 			port = tcp_get_next_priv_port(tcp);
3431 		} else {
3432 			if (count == 0 && user_specified) {
3433 				/*
3434 				 * We may have to return an anonymous port. So
3435 				 * get one to start with.
3436 				 */
3437 				port =
3438 				    tcp_update_next_port(
3439 				    tcps->tcps_next_port_to_try,
3440 				    tcp, B_TRUE);
3441 				user_specified = B_FALSE;
3442 			} else {
3443 				port = tcp_update_next_port(port + 1, tcp,
3444 				    B_FALSE);
3445 			}
3446 		}
3447 		if (port == 0)
3448 			break;
3449 
3450 		/*
3451 		 * Don't let this loop run forever in the case where
3452 		 * all of the anonymous ports are in use.
3453 		 */
3454 	} while (++count < loopmax);
3455 	return (0);
3456 }
3457 
3458 /*
3459  * tcp_clean_death / tcp_close_detached must not be called more than once
3460  * on a tcp. Thus every function that potentially calls tcp_clean_death
3461  * must check for the tcp state before calling tcp_clean_death.
3462  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3463  * tcp_timer_handler, all check for the tcp state.
3464  */
3465 /* ARGSUSED */
3466 void
3467 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3468 {
3469 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3470 
3471 	freemsg(mp);
3472 	if (tcp->tcp_state > TCPS_BOUND)
3473 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3474 		    ETIMEDOUT, 5);
3475 }
3476 
3477 /*
3478  * We are dying for some reason.  Try to do it gracefully.  (May be called
3479  * as writer.)
3480  *
3481  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3482  * done by a service procedure).
3483  * TBD - Should the return value distinguish between the tcp_t being
3484  * freed and it being reinitialized?
3485  */
3486 static int
3487 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3488 {
3489 	mblk_t	*mp;
3490 	queue_t	*q;
3491 	conn_t	*connp = tcp->tcp_connp;
3492 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3493 	sodirect_t	*sodp;
3494 
3495 	TCP_CLD_STAT(tag);
3496 
3497 #if TCP_TAG_CLEAN_DEATH
3498 	tcp->tcp_cleandeathtag = tag;
3499 #endif
3500 
3501 	if (tcp->tcp_fused)
3502 		tcp_unfuse(tcp);
3503 
3504 	if (tcp->tcp_linger_tid != 0 &&
3505 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3506 		tcp_stop_lingering(tcp);
3507 	}
3508 
3509 	ASSERT(tcp != NULL);
3510 	ASSERT((tcp->tcp_family == AF_INET &&
3511 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3512 	    (tcp->tcp_family == AF_INET6 &&
3513 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3514 	    tcp->tcp_ipversion == IPV6_VERSION)));
3515 
3516 	if (TCP_IS_DETACHED(tcp)) {
3517 		if (tcp->tcp_hard_binding) {
3518 			/*
3519 			 * Its an eager that we are dealing with. We close the
3520 			 * eager but in case a conn_ind has already gone to the
3521 			 * listener, let tcp_accept_finish() send a discon_ind
3522 			 * to the listener and drop the last reference. If the
3523 			 * listener doesn't even know about the eager i.e. the
3524 			 * conn_ind hasn't gone up, blow away the eager and drop
3525 			 * the last reference as well. If the conn_ind has gone
3526 			 * up, state should be BOUND. tcp_accept_finish
3527 			 * will figure out that the connection has received a
3528 			 * RST and will send a DISCON_IND to the application.
3529 			 */
3530 			tcp_closei_local(tcp);
3531 			if (!tcp->tcp_tconnind_started) {
3532 				CONN_DEC_REF(connp);
3533 			} else {
3534 				tcp->tcp_state = TCPS_BOUND;
3535 			}
3536 		} else {
3537 			tcp_close_detached(tcp);
3538 		}
3539 		return (0);
3540 	}
3541 
3542 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3543 
3544 	/* If sodirect, not anymore */
3545 	SOD_PTR_ENTER(tcp, sodp);
3546 	if (sodp != NULL) {
3547 		tcp->tcp_sodirect = NULL;
3548 		mutex_exit(sodp->sod_lockp);
3549 	}
3550 
3551 	q = tcp->tcp_rq;
3552 
3553 	/* Trash all inbound data */
3554 	if (!IPCL_IS_NONSTR(connp)) {
3555 		ASSERT(q != NULL);
3556 		flushq(q, FLUSHALL);
3557 	}
3558 
3559 	/*
3560 	 * If we are at least part way open and there is error
3561 	 * (err==0 implies no error)
3562 	 * notify our client by a T_DISCON_IND.
3563 	 */
3564 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3565 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3566 		    !TCP_IS_SOCKET(tcp)) {
3567 			/*
3568 			 * Send M_FLUSH according to TPI. Because sockets will
3569 			 * (and must) ignore FLUSHR we do that only for TPI
3570 			 * endpoints and sockets in STREAMS mode.
3571 			 */
3572 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3573 		}
3574 		if (tcp->tcp_debug) {
3575 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3576 			    "tcp_clean_death: discon err %d", err);
3577 		}
3578 		if (IPCL_IS_NONSTR(connp)) {
3579 			/* Direct socket, use upcall */
3580 			(*connp->conn_upcalls->su_disconnected)(
3581 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3582 		} else {
3583 			mp = mi_tpi_discon_ind(NULL, err, 0);
3584 			if (mp != NULL) {
3585 				putnext(q, mp);
3586 			} else {
3587 				if (tcp->tcp_debug) {
3588 					(void) strlog(TCP_MOD_ID, 0, 1,
3589 					    SL_ERROR|SL_TRACE,
3590 					    "tcp_clean_death, sending M_ERROR");
3591 				}
3592 				(void) putnextctl1(q, M_ERROR, EPROTO);
3593 			}
3594 		}
3595 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3596 			/* SYN_SENT or SYN_RCVD */
3597 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3598 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3599 			/* ESTABLISHED or CLOSE_WAIT */
3600 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3601 		}
3602 	}
3603 
3604 	tcp_reinit(tcp);
3605 	if (IPCL_IS_NONSTR(connp))
3606 		(void) tcp_do_unbind(connp);
3607 
3608 	return (-1);
3609 }
3610 
3611 /*
3612  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3613  * to expire, stop the wait and finish the close.
3614  */
3615 static void
3616 tcp_stop_lingering(tcp_t *tcp)
3617 {
3618 	clock_t	delta = 0;
3619 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3620 
3621 	tcp->tcp_linger_tid = 0;
3622 	if (tcp->tcp_state > TCPS_LISTEN) {
3623 		tcp_acceptor_hash_remove(tcp);
3624 		mutex_enter(&tcp->tcp_non_sq_lock);
3625 		if (tcp->tcp_flow_stopped) {
3626 			tcp_clrqfull(tcp);
3627 		}
3628 		mutex_exit(&tcp->tcp_non_sq_lock);
3629 
3630 		if (tcp->tcp_timer_tid != 0) {
3631 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3632 			tcp->tcp_timer_tid = 0;
3633 		}
3634 		/*
3635 		 * Need to cancel those timers which will not be used when
3636 		 * TCP is detached.  This has to be done before the tcp_wq
3637 		 * is set to the global queue.
3638 		 */
3639 		tcp_timers_stop(tcp);
3640 
3641 		tcp->tcp_detached = B_TRUE;
3642 		ASSERT(tcps->tcps_g_q != NULL);
3643 		tcp->tcp_rq = tcps->tcps_g_q;
3644 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3645 
3646 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3647 			tcp_time_wait_append(tcp);
3648 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3649 			goto finish;
3650 		}
3651 
3652 		/*
3653 		 * If delta is zero the timer event wasn't executed and was
3654 		 * successfully canceled. In this case we need to restart it
3655 		 * with the minimal delta possible.
3656 		 */
3657 		if (delta >= 0) {
3658 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3659 			    delta ? delta : 1);
3660 		}
3661 	} else {
3662 		tcp_closei_local(tcp);
3663 		CONN_DEC_REF(tcp->tcp_connp);
3664 	}
3665 finish:
3666 	/* Signal closing thread that it can complete close */
3667 	mutex_enter(&tcp->tcp_closelock);
3668 	tcp->tcp_detached = B_TRUE;
3669 	ASSERT(tcps->tcps_g_q != NULL);
3670 
3671 	tcp->tcp_rq = tcps->tcps_g_q;
3672 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3673 
3674 	tcp->tcp_closed = 1;
3675 	cv_signal(&tcp->tcp_closecv);
3676 	mutex_exit(&tcp->tcp_closelock);
3677 }
3678 
3679 /*
3680  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3681  * expires.
3682  */
3683 static void
3684 tcp_close_linger_timeout(void *arg)
3685 {
3686 	conn_t	*connp = (conn_t *)arg;
3687 	tcp_t 	*tcp = connp->conn_tcp;
3688 
3689 	tcp->tcp_client_errno = ETIMEDOUT;
3690 	tcp_stop_lingering(tcp);
3691 }
3692 
3693 static void
3694 tcp_close_common(conn_t *connp, int flags)
3695 {
3696 	tcp_t		*tcp = connp->conn_tcp;
3697 	mblk_t 		*mp = &tcp->tcp_closemp;
3698 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3699 	mblk_t		*bp;
3700 
3701 	ASSERT(connp->conn_ref >= 2);
3702 
3703 	/*
3704 	 * Mark the conn as closing. ill_pending_mp_add will not
3705 	 * add any mp to the pending mp list, after this conn has
3706 	 * started closing. Same for sq_pending_mp_add
3707 	 */
3708 	mutex_enter(&connp->conn_lock);
3709 	connp->conn_state_flags |= CONN_CLOSING;
3710 	if (connp->conn_oper_pending_ill != NULL)
3711 		conn_ioctl_cleanup_reqd = B_TRUE;
3712 	CONN_INC_REF_LOCKED(connp);
3713 	mutex_exit(&connp->conn_lock);
3714 	tcp->tcp_closeflags = (uint8_t)flags;
3715 	ASSERT(connp->conn_ref >= 3);
3716 
3717 	/*
3718 	 * tcp_closemp_used is used below without any protection of a lock
3719 	 * as we don't expect any one else to use it concurrently at this
3720 	 * point otherwise it would be a major defect.
3721 	 */
3722 
3723 	if (mp->b_prev == NULL)
3724 		tcp->tcp_closemp_used = B_TRUE;
3725 	else
3726 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3727 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3728 
3729 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3730 
3731 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3732 	    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3733 
3734 	mutex_enter(&tcp->tcp_closelock);
3735 	while (!tcp->tcp_closed) {
3736 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3737 			/*
3738 			 * The cv_wait_sig() was interrupted. We now do the
3739 			 * following:
3740 			 *
3741 			 * 1) If the endpoint was lingering, we allow this
3742 			 * to be interrupted by cancelling the linger timeout
3743 			 * and closing normally.
3744 			 *
3745 			 * 2) Revert to calling cv_wait()
3746 			 *
3747 			 * We revert to using cv_wait() to avoid an
3748 			 * infinite loop which can occur if the calling
3749 			 * thread is higher priority than the squeue worker
3750 			 * thread and is bound to the same cpu.
3751 			 */
3752 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
3753 				mutex_exit(&tcp->tcp_closelock);
3754 				/* Entering squeue, bump ref count. */
3755 				CONN_INC_REF(connp);
3756 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3757 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3758 				    tcp_linger_interrupted, connp,
3759 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3760 				mutex_enter(&tcp->tcp_closelock);
3761 			}
3762 			break;
3763 		}
3764 	}
3765 	while (!tcp->tcp_closed)
3766 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3767 	mutex_exit(&tcp->tcp_closelock);
3768 
3769 	/*
3770 	 * In the case of listener streams that have eagers in the q or q0
3771 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3772 	 * tcp_wq of the eagers point to our queues. By waiting for the
3773 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3774 	 * up their queue pointers and also dropped their references to us.
3775 	 */
3776 	if (tcp->tcp_wait_for_eagers) {
3777 		mutex_enter(&connp->conn_lock);
3778 		while (connp->conn_ref != 1) {
3779 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3780 		}
3781 		mutex_exit(&connp->conn_lock);
3782 	}
3783 	/*
3784 	 * ioctl cleanup. The mp is queued in the
3785 	 * ill_pending_mp or in the sq_pending_mp.
3786 	 */
3787 	if (conn_ioctl_cleanup_reqd)
3788 		conn_ioctl_cleanup(connp);
3789 
3790 	tcp->tcp_cpid = -1;
3791 }
3792 
3793 static int
3794 tcp_tpi_close(queue_t *q, int flags)
3795 {
3796 	conn_t		*connp;
3797 
3798 	ASSERT(WR(q)->q_next == NULL);
3799 
3800 	if (flags & SO_FALLBACK) {
3801 		/*
3802 		 * stream is being closed while in fallback
3803 		 * simply free the resources that were allocated
3804 		 */
3805 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3806 		qprocsoff(q);
3807 		goto done;
3808 	}
3809 
3810 	connp = Q_TO_CONN(q);
3811 	/*
3812 	 * We are being closed as /dev/tcp or /dev/tcp6.
3813 	 */
3814 	tcp_close_common(connp, flags);
3815 
3816 	qprocsoff(q);
3817 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3818 
3819 	/*
3820 	 * Drop IP's reference on the conn. This is the last reference
3821 	 * on the connp if the state was less than established. If the
3822 	 * connection has gone into timewait state, then we will have
3823 	 * one ref for the TCP and one more ref (total of two) for the
3824 	 * classifier connected hash list (a timewait connections stays
3825 	 * in connected hash till closed).
3826 	 *
3827 	 * We can't assert the references because there might be other
3828 	 * transient reference places because of some walkers or queued
3829 	 * packets in squeue for the timewait state.
3830 	 */
3831 	CONN_DEC_REF(connp);
3832 done:
3833 	q->q_ptr = WR(q)->q_ptr = NULL;
3834 	return (0);
3835 }
3836 
3837 static int
3838 tcpclose_accept(queue_t *q)
3839 {
3840 	vmem_t	*minor_arena;
3841 	dev_t	conn_dev;
3842 
3843 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3844 
3845 	/*
3846 	 * We had opened an acceptor STREAM for sockfs which is
3847 	 * now being closed due to some error.
3848 	 */
3849 	qprocsoff(q);
3850 
3851 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3852 	conn_dev = (dev_t)RD(q)->q_ptr;
3853 	ASSERT(minor_arena != NULL);
3854 	ASSERT(conn_dev != 0);
3855 	inet_minor_free(minor_arena, conn_dev);
3856 	q->q_ptr = WR(q)->q_ptr = NULL;
3857 	return (0);
3858 }
3859 
3860 /*
3861  * Called by tcp_close() routine via squeue when lingering is
3862  * interrupted by a signal.
3863  */
3864 
3865 /* ARGSUSED */
3866 static void
3867 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
3868 {
3869 	conn_t	*connp = (conn_t *)arg;
3870 	tcp_t	*tcp = connp->conn_tcp;
3871 
3872 	freeb(mp);
3873 	if (tcp->tcp_linger_tid != 0 &&
3874 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3875 		tcp_stop_lingering(tcp);
3876 		tcp->tcp_client_errno = EINTR;
3877 	}
3878 }
3879 
3880 /*
3881  * Called by streams close routine via squeues when our client blows off her
3882  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3883  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3884  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3885  * acked.
3886  *
3887  * NOTE: tcp_close potentially returns error when lingering.
3888  * However, the stream head currently does not pass these errors
3889  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3890  * errors to the application (from tsleep()) and not errors
3891  * like ECONNRESET caused by receiving a reset packet.
3892  */
3893 
3894 /* ARGSUSED */
3895 static void
3896 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3897 {
3898 	char	*msg;
3899 	conn_t	*connp = (conn_t *)arg;
3900 	tcp_t	*tcp = connp->conn_tcp;
3901 	clock_t	delta = 0;
3902 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3903 
3904 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3905 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3906 
3907 	mutex_enter(&tcp->tcp_eager_lock);
3908 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3909 		/* Cleanup for listener */
3910 		tcp_eager_cleanup(tcp, 0);
3911 		tcp->tcp_wait_for_eagers = 1;
3912 	}
3913 	mutex_exit(&tcp->tcp_eager_lock);
3914 
3915 	connp->conn_mdt_ok = B_FALSE;
3916 	tcp->tcp_mdt = B_FALSE;
3917 
3918 	connp->conn_lso_ok = B_FALSE;
3919 	tcp->tcp_lso = B_FALSE;
3920 
3921 	msg = NULL;
3922 	switch (tcp->tcp_state) {
3923 	case TCPS_CLOSED:
3924 	case TCPS_IDLE:
3925 	case TCPS_BOUND:
3926 	case TCPS_LISTEN:
3927 		break;
3928 	case TCPS_SYN_SENT:
3929 		msg = "tcp_close, during connect";
3930 		break;
3931 	case TCPS_SYN_RCVD:
3932 		/*
3933 		 * Close during the connect 3-way handshake
3934 		 * but here there may or may not be pending data
3935 		 * already on queue. Process almost same as in
3936 		 * the ESTABLISHED state.
3937 		 */
3938 		/* FALLTHRU */
3939 	default:
3940 		if (tcp->tcp_sodirect != NULL) {
3941 			/* Ok, no more sodirect */
3942 			tcp->tcp_sodirect = NULL;
3943 		}
3944 
3945 		if (tcp->tcp_fused)
3946 			tcp_unfuse(tcp);
3947 
3948 		/*
3949 		 * If SO_LINGER has set a zero linger time, abort the
3950 		 * connection with a reset.
3951 		 */
3952 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3953 			msg = "tcp_close, zero lingertime";
3954 			break;
3955 		}
3956 
3957 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3958 		/*
3959 		 * Abort connection if there is unread data queued.
3960 		 */
3961 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3962 			msg = "tcp_close, unread data";
3963 			break;
3964 		}
3965 		/*
3966 		 * tcp_hard_bound is now cleared thus all packets go through
3967 		 * tcp_lookup. This fact is used by tcp_detach below.
3968 		 *
3969 		 * We have done a qwait() above which could have possibly
3970 		 * drained more messages in turn causing transition to a
3971 		 * different state. Check whether we have to do the rest
3972 		 * of the processing or not.
3973 		 */
3974 		if (tcp->tcp_state <= TCPS_LISTEN)
3975 			break;
3976 
3977 		/*
3978 		 * Transmit the FIN before detaching the tcp_t.
3979 		 * After tcp_detach returns this queue/perimeter
3980 		 * no longer owns the tcp_t thus others can modify it.
3981 		 */
3982 		(void) tcp_xmit_end(tcp);
3983 
3984 		/*
3985 		 * If lingering on close then wait until the fin is acked,
3986 		 * the SO_LINGER time passes, or a reset is sent/received.
3987 		 */
3988 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
3989 		    !(tcp->tcp_fin_acked) &&
3990 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3991 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3992 				tcp->tcp_client_errno = EWOULDBLOCK;
3993 			} else if (tcp->tcp_client_errno == 0) {
3994 
3995 				ASSERT(tcp->tcp_linger_tid == 0);
3996 
3997 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3998 				    tcp_close_linger_timeout,
3999 				    tcp->tcp_lingertime * hz);
4000 
4001 				/* tcp_close_linger_timeout will finish close */
4002 				if (tcp->tcp_linger_tid == 0)
4003 					tcp->tcp_client_errno = ENOSR;
4004 				else
4005 					return;
4006 			}
4007 
4008 			/*
4009 			 * Check if we need to detach or just close
4010 			 * the instance.
4011 			 */
4012 			if (tcp->tcp_state <= TCPS_LISTEN)
4013 				break;
4014 		}
4015 
4016 		/*
4017 		 * Make sure that no other thread will access the tcp_rq of
4018 		 * this instance (through lookups etc.) as tcp_rq will go
4019 		 * away shortly.
4020 		 */
4021 		tcp_acceptor_hash_remove(tcp);
4022 
4023 		mutex_enter(&tcp->tcp_non_sq_lock);
4024 		if (tcp->tcp_flow_stopped) {
4025 			tcp_clrqfull(tcp);
4026 		}
4027 		mutex_exit(&tcp->tcp_non_sq_lock);
4028 
4029 		if (tcp->tcp_timer_tid != 0) {
4030 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4031 			tcp->tcp_timer_tid = 0;
4032 		}
4033 		/*
4034 		 * Need to cancel those timers which will not be used when
4035 		 * TCP is detached.  This has to be done before the tcp_wq
4036 		 * is set to the global queue.
4037 		 */
4038 		tcp_timers_stop(tcp);
4039 
4040 		tcp->tcp_detached = B_TRUE;
4041 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4042 			tcp_time_wait_append(tcp);
4043 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
4044 			ASSERT(connp->conn_ref >= 3);
4045 			goto finish;
4046 		}
4047 
4048 		/*
4049 		 * If delta is zero the timer event wasn't executed and was
4050 		 * successfully canceled. In this case we need to restart it
4051 		 * with the minimal delta possible.
4052 		 */
4053 		if (delta >= 0)
4054 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4055 			    delta ? delta : 1);
4056 
4057 		ASSERT(connp->conn_ref >= 3);
4058 		goto finish;
4059 	}
4060 
4061 	/* Detach did not complete. Still need to remove q from stream. */
4062 	if (msg) {
4063 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4064 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4065 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4066 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4067 		    tcp->tcp_state == TCPS_SYN_RCVD)
4068 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4069 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4070 	}
4071 
4072 	tcp_closei_local(tcp);
4073 	CONN_DEC_REF(connp);
4074 	ASSERT(connp->conn_ref >= 2);
4075 
4076 finish:
4077 	/*
4078 	 * Although packets are always processed on the correct
4079 	 * tcp's perimeter and access is serialized via squeue's,
4080 	 * IP still needs a queue when sending packets in time_wait
4081 	 * state so use WR(tcps_g_q) till ip_output() can be
4082 	 * changed to deal with just connp. For read side, we
4083 	 * could have set tcp_rq to NULL but there are some cases
4084 	 * in tcp_rput_data() from early days of this code which
4085 	 * do a putnext without checking if tcp is closed. Those
4086 	 * need to be identified before both tcp_rq and tcp_wq
4087 	 * can be set to NULL and tcps_g_q can disappear forever.
4088 	 */
4089 	mutex_enter(&tcp->tcp_closelock);
4090 	/*
4091 	 * Don't change the queues in the case of a listener that has
4092 	 * eagers in its q or q0. It could surprise the eagers.
4093 	 * Instead wait for the eagers outside the squeue.
4094 	 */
4095 	if (!tcp->tcp_wait_for_eagers) {
4096 		tcp->tcp_detached = B_TRUE;
4097 		/*
4098 		 * When default queue is closing we set tcps_g_q to NULL
4099 		 * after the close is done.
4100 		 */
4101 		ASSERT(tcps->tcps_g_q != NULL);
4102 		tcp->tcp_rq = tcps->tcps_g_q;
4103 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4104 	}
4105 
4106 	/* Signal tcp_close() to finish closing. */
4107 	tcp->tcp_closed = 1;
4108 	cv_signal(&tcp->tcp_closecv);
4109 	mutex_exit(&tcp->tcp_closelock);
4110 }
4111 
4112 
4113 /*
4114  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4115  * Some stream heads get upset if they see these later on as anything but NULL.
4116  */
4117 static void
4118 tcp_close_mpp(mblk_t **mpp)
4119 {
4120 	mblk_t	*mp;
4121 
4122 	if ((mp = *mpp) != NULL) {
4123 		do {
4124 			mp->b_next = NULL;
4125 			mp->b_prev = NULL;
4126 		} while ((mp = mp->b_cont) != NULL);
4127 
4128 		mp = *mpp;
4129 		*mpp = NULL;
4130 		freemsg(mp);
4131 	}
4132 }
4133 
4134 /* Do detached close. */
4135 static void
4136 tcp_close_detached(tcp_t *tcp)
4137 {
4138 	if (tcp->tcp_fused)
4139 		tcp_unfuse(tcp);
4140 
4141 	/*
4142 	 * Clustering code serializes TCP disconnect callbacks and
4143 	 * cluster tcp list walks by blocking a TCP disconnect callback
4144 	 * if a cluster tcp list walk is in progress. This ensures
4145 	 * accurate accounting of TCPs in the cluster code even though
4146 	 * the TCP list walk itself is not atomic.
4147 	 */
4148 	tcp_closei_local(tcp);
4149 	CONN_DEC_REF(tcp->tcp_connp);
4150 }
4151 
4152 /*
4153  * Stop all TCP timers, and free the timer mblks if requested.
4154  */
4155 void
4156 tcp_timers_stop(tcp_t *tcp)
4157 {
4158 	if (tcp->tcp_timer_tid != 0) {
4159 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4160 		tcp->tcp_timer_tid = 0;
4161 	}
4162 	if (tcp->tcp_ka_tid != 0) {
4163 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4164 		tcp->tcp_ka_tid = 0;
4165 	}
4166 	if (tcp->tcp_ack_tid != 0) {
4167 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4168 		tcp->tcp_ack_tid = 0;
4169 	}
4170 	if (tcp->tcp_push_tid != 0) {
4171 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4172 		tcp->tcp_push_tid = 0;
4173 	}
4174 }
4175 
4176 /*
4177  * The tcp_t is going away. Remove it from all lists and set it
4178  * to TCPS_CLOSED. The freeing up of memory is deferred until
4179  * tcp_inactive. This is needed since a thread in tcp_rput might have
4180  * done a CONN_INC_REF on this structure before it was removed from the
4181  * hashes.
4182  */
4183 static void
4184 tcp_closei_local(tcp_t *tcp)
4185 {
4186 	ire_t 	*ire;
4187 	conn_t	*connp = tcp->tcp_connp;
4188 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4189 
4190 	if (!TCP_IS_SOCKET(tcp))
4191 		tcp_acceptor_hash_remove(tcp);
4192 
4193 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4194 	tcp->tcp_ibsegs = 0;
4195 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4196 	tcp->tcp_obsegs = 0;
4197 
4198 	/*
4199 	 * If we are an eager connection hanging off a listener that
4200 	 * hasn't formally accepted the connection yet, get off his
4201 	 * list and blow off any data that we have accumulated.
4202 	 */
4203 	if (tcp->tcp_listener != NULL) {
4204 		tcp_t	*listener = tcp->tcp_listener;
4205 		mutex_enter(&listener->tcp_eager_lock);
4206 		/*
4207 		 * tcp_tconnind_started == B_TRUE means that the
4208 		 * conn_ind has already gone to listener. At
4209 		 * this point, eager will be closed but we
4210 		 * leave it in listeners eager list so that
4211 		 * if listener decides to close without doing
4212 		 * accept, we can clean this up. In tcp_wput_accept
4213 		 * we take care of the case of accept on closed
4214 		 * eager.
4215 		 */
4216 		if (!tcp->tcp_tconnind_started) {
4217 			tcp_eager_unlink(tcp);
4218 			mutex_exit(&listener->tcp_eager_lock);
4219 			/*
4220 			 * We don't want to have any pointers to the
4221 			 * listener queue, after we have released our
4222 			 * reference on the listener
4223 			 */
4224 			ASSERT(tcps->tcps_g_q != NULL);
4225 			tcp->tcp_rq = tcps->tcps_g_q;
4226 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4227 			CONN_DEC_REF(listener->tcp_connp);
4228 		} else {
4229 			mutex_exit(&listener->tcp_eager_lock);
4230 		}
4231 	}
4232 
4233 	/* Stop all the timers */
4234 	tcp_timers_stop(tcp);
4235 
4236 	if (tcp->tcp_state == TCPS_LISTEN) {
4237 		if (tcp->tcp_ip_addr_cache) {
4238 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4239 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4240 			tcp->tcp_ip_addr_cache = NULL;
4241 		}
4242 	}
4243 	mutex_enter(&tcp->tcp_non_sq_lock);
4244 	if (tcp->tcp_flow_stopped)
4245 		tcp_clrqfull(tcp);
4246 	mutex_exit(&tcp->tcp_non_sq_lock);
4247 
4248 	tcp_bind_hash_remove(tcp);
4249 	/*
4250 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4251 	 * is trying to remove this tcp from the time wait list, we will
4252 	 * block in tcp_time_wait_remove while trying to acquire the
4253 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4254 	 * requires the ipcl_hash_remove to be ordered after the
4255 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4256 	 */
4257 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4258 		(void) tcp_time_wait_remove(tcp, NULL);
4259 	CL_INET_DISCONNECT(connp, tcp);
4260 	ipcl_hash_remove(connp);
4261 
4262 	/*
4263 	 * Delete the cached ire in conn_ire_cache and also mark
4264 	 * the conn as CONDEMNED
4265 	 */
4266 	mutex_enter(&connp->conn_lock);
4267 	connp->conn_state_flags |= CONN_CONDEMNED;
4268 	ire = connp->conn_ire_cache;
4269 	connp->conn_ire_cache = NULL;
4270 	mutex_exit(&connp->conn_lock);
4271 	if (ire != NULL)
4272 		IRE_REFRELE_NOTR(ire);
4273 
4274 	/* Need to cleanup any pending ioctls */
4275 	ASSERT(tcp->tcp_time_wait_next == NULL);
4276 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4277 	ASSERT(tcp->tcp_time_wait_expire == 0);
4278 	tcp->tcp_state = TCPS_CLOSED;
4279 
4280 	/* Release any SSL context */
4281 	if (tcp->tcp_kssl_ent != NULL) {
4282 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4283 		tcp->tcp_kssl_ent = NULL;
4284 	}
4285 	if (tcp->tcp_kssl_ctx != NULL) {
4286 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4287 		tcp->tcp_kssl_ctx = NULL;
4288 	}
4289 	tcp->tcp_kssl_pending = B_FALSE;
4290 
4291 	tcp_ipsec_cleanup(tcp);
4292 }
4293 
4294 /*
4295  * tcp is dying (called from ipcl_conn_destroy and error cases).
4296  * Free the tcp_t in either case.
4297  */
4298 void
4299 tcp_free(tcp_t *tcp)
4300 {
4301 	mblk_t	*mp;
4302 	ip6_pkt_t	*ipp;
4303 
4304 	ASSERT(tcp != NULL);
4305 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4306 
4307 	tcp->tcp_rq = NULL;
4308 	tcp->tcp_wq = NULL;
4309 
4310 	tcp_close_mpp(&tcp->tcp_xmit_head);
4311 	tcp_close_mpp(&tcp->tcp_reass_head);
4312 	if (tcp->tcp_rcv_list != NULL) {
4313 		/* Free b_next chain */
4314 		tcp_close_mpp(&tcp->tcp_rcv_list);
4315 	}
4316 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4317 		freemsg(mp);
4318 	}
4319 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4320 		freemsg(mp);
4321 	}
4322 
4323 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4324 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4325 		freeb(tcp->tcp_fused_sigurg_mp);
4326 		tcp->tcp_fused_sigurg_mp = NULL;
4327 	}
4328 
4329 	if (tcp->tcp_ordrel_mp != NULL) {
4330 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4331 		freeb(tcp->tcp_ordrel_mp);
4332 		tcp->tcp_ordrel_mp = NULL;
4333 	}
4334 
4335 	if (tcp->tcp_sack_info != NULL) {
4336 		if (tcp->tcp_notsack_list != NULL) {
4337 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4338 		}
4339 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4340 	}
4341 
4342 	if (tcp->tcp_hopopts != NULL) {
4343 		mi_free(tcp->tcp_hopopts);
4344 		tcp->tcp_hopopts = NULL;
4345 		tcp->tcp_hopoptslen = 0;
4346 	}
4347 	ASSERT(tcp->tcp_hopoptslen == 0);
4348 	if (tcp->tcp_dstopts != NULL) {
4349 		mi_free(tcp->tcp_dstopts);
4350 		tcp->tcp_dstopts = NULL;
4351 		tcp->tcp_dstoptslen = 0;
4352 	}
4353 	ASSERT(tcp->tcp_dstoptslen == 0);
4354 	if (tcp->tcp_rtdstopts != NULL) {
4355 		mi_free(tcp->tcp_rtdstopts);
4356 		tcp->tcp_rtdstopts = NULL;
4357 		tcp->tcp_rtdstoptslen = 0;
4358 	}
4359 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4360 	if (tcp->tcp_rthdr != NULL) {
4361 		mi_free(tcp->tcp_rthdr);
4362 		tcp->tcp_rthdr = NULL;
4363 		tcp->tcp_rthdrlen = 0;
4364 	}
4365 	ASSERT(tcp->tcp_rthdrlen == 0);
4366 
4367 	ipp = &tcp->tcp_sticky_ipp;
4368 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4369 	    IPPF_RTHDR))
4370 		ip6_pkt_free(ipp);
4371 
4372 	/*
4373 	 * Free memory associated with the tcp/ip header template.
4374 	 */
4375 
4376 	if (tcp->tcp_iphc != NULL)
4377 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4378 
4379 	/*
4380 	 * Following is really a blowing away a union.
4381 	 * It happens to have exactly two members of identical size
4382 	 * the following code is enough.
4383 	 */
4384 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4385 }
4386 
4387 
4388 /*
4389  * Put a connection confirmation message upstream built from the
4390  * address information within 'iph' and 'tcph'.  Report our success or failure.
4391  */
4392 static boolean_t
4393 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4394     mblk_t **defermp)
4395 {
4396 	sin_t	sin;
4397 	sin6_t	sin6;
4398 	mblk_t	*mp;
4399 	char	*optp = NULL;
4400 	int	optlen = 0;
4401 	cred_t	*cr;
4402 
4403 	if (defermp != NULL)
4404 		*defermp = NULL;
4405 
4406 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4407 		/*
4408 		 * Return in T_CONN_CON results of option negotiation through
4409 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4410 		 * negotiation, then what is received from remote end needs
4411 		 * to be taken into account but there is no such thing (yet?)
4412 		 * in our TCP/IP.
4413 		 * Note: We do not use mi_offset_param() here as
4414 		 * tcp_opts_conn_req contents do not directly come from
4415 		 * an application and are either generated in kernel or
4416 		 * from user input that was already verified.
4417 		 */
4418 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4419 		optp = (char *)(mp->b_rptr +
4420 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4421 		optlen = (int)
4422 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4423 	}
4424 
4425 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4426 		ipha_t *ipha = (ipha_t *)iphdr;
4427 
4428 		/* packet is IPv4 */
4429 		if (tcp->tcp_family == AF_INET) {
4430 			sin = sin_null;
4431 			sin.sin_addr.s_addr = ipha->ipha_src;
4432 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4433 			sin.sin_family = AF_INET;
4434 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4435 			    (int)sizeof (sin_t), optp, optlen);
4436 		} else {
4437 			sin6 = sin6_null;
4438 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4439 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4440 			sin6.sin6_family = AF_INET6;
4441 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4442 			    (int)sizeof (sin6_t), optp, optlen);
4443 
4444 		}
4445 	} else {
4446 		ip6_t	*ip6h = (ip6_t *)iphdr;
4447 
4448 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4449 		ASSERT(tcp->tcp_family == AF_INET6);
4450 		sin6 = sin6_null;
4451 		sin6.sin6_addr = ip6h->ip6_src;
4452 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4453 		sin6.sin6_family = AF_INET6;
4454 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4455 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4456 		    (int)sizeof (sin6_t), optp, optlen);
4457 	}
4458 
4459 	if (!mp)
4460 		return (B_FALSE);
4461 
4462 	if ((cr = DB_CRED(idmp)) != NULL) {
4463 		mblk_setcred(mp, cr);
4464 		DB_CPID(mp) = DB_CPID(idmp);
4465 	}
4466 
4467 	if (defermp == NULL) {
4468 		conn_t *connp = tcp->tcp_connp;
4469 		if (IPCL_IS_NONSTR(connp)) {
4470 			(*connp->conn_upcalls->su_connected)
4471 			    (connp->conn_upper_handle, tcp->tcp_connid, cr,
4472 			    DB_CPID(mp));
4473 			freemsg(mp);
4474 		} else {
4475 			putnext(tcp->tcp_rq, mp);
4476 		}
4477 	} else {
4478 		*defermp = mp;
4479 	}
4480 
4481 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4482 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4483 	return (B_TRUE);
4484 }
4485 
4486 /*
4487  * Defense for the SYN attack -
4488  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4489  *    one from the list of droppable eagers. This list is a subset of q0.
4490  *    see comments before the definition of MAKE_DROPPABLE().
4491  * 2. Don't drop a SYN request before its first timeout. This gives every
4492  *    request at least til the first timeout to complete its 3-way handshake.
4493  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4494  *    requests currently on the queue that has timed out. This will be used
4495  *    as an indicator of whether an attack is under way, so that appropriate
4496  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4497  *    either when eager goes into ESTABLISHED, or gets freed up.)
4498  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4499  *    # of timeout drops back to <= q0len/32 => SYN alert off
4500  */
4501 static boolean_t
4502 tcp_drop_q0(tcp_t *tcp)
4503 {
4504 	tcp_t	*eager;
4505 	mblk_t	*mp;
4506 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4507 
4508 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4509 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4510 
4511 	/* Pick oldest eager from the list of droppable eagers */
4512 	eager = tcp->tcp_eager_prev_drop_q0;
4513 
4514 	/* If list is empty. return B_FALSE */
4515 	if (eager == tcp) {
4516 		return (B_FALSE);
4517 	}
4518 
4519 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4520 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4521 		return (B_FALSE);
4522 
4523 	/*
4524 	 * Take this eager out from the list of droppable eagers since we are
4525 	 * going to drop it.
4526 	 */
4527 	MAKE_UNDROPPABLE(eager);
4528 
4529 	if (tcp->tcp_debug) {
4530 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4531 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4532 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4533 		    tcp->tcp_conn_req_cnt_q0,
4534 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4535 	}
4536 
4537 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4538 
4539 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4540 	CONN_INC_REF(eager->tcp_connp);
4541 
4542 	/* Mark the IRE created for this SYN request temporary */
4543 	tcp_ip_ire_mark_advice(eager);
4544 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4545 	    tcp_clean_death_wrapper, eager->tcp_connp,
4546 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4547 
4548 	return (B_TRUE);
4549 }
4550 
4551 int
4552 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4553     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4554 {
4555 	tcp_t 		*ltcp = lconnp->conn_tcp;
4556 	tcp_t		*tcp = connp->conn_tcp;
4557 	mblk_t		*tpi_mp;
4558 	ipha_t		*ipha;
4559 	ip6_t		*ip6h;
4560 	sin6_t 		sin6;
4561 	in6_addr_t 	v6dst;
4562 	int		err;
4563 	int		ifindex = 0;
4564 	cred_t		*cr;
4565 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4566 
4567 	if (ipvers == IPV4_VERSION) {
4568 		ipha = (ipha_t *)mp->b_rptr;
4569 
4570 		connp->conn_send = ip_output;
4571 		connp->conn_recv = tcp_input;
4572 
4573 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4574 		    &connp->conn_bound_source_v6);
4575 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4576 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4577 
4578 		sin6 = sin6_null;
4579 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4580 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4581 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4582 		sin6.sin6_family = AF_INET6;
4583 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4584 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4585 		if (tcp->tcp_recvdstaddr) {
4586 			sin6_t	sin6d;
4587 
4588 			sin6d = sin6_null;
4589 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4590 			    &sin6d.sin6_addr);
4591 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4592 			sin6d.sin6_family = AF_INET;
4593 			tpi_mp = mi_tpi_extconn_ind(NULL,
4594 			    (char *)&sin6d, sizeof (sin6_t),
4595 			    (char *)&tcp,
4596 			    (t_scalar_t)sizeof (intptr_t),
4597 			    (char *)&sin6d, sizeof (sin6_t),
4598 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4599 		} else {
4600 			tpi_mp = mi_tpi_conn_ind(NULL,
4601 			    (char *)&sin6, sizeof (sin6_t),
4602 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4603 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4604 		}
4605 	} else {
4606 		ip6h = (ip6_t *)mp->b_rptr;
4607 
4608 		connp->conn_send = ip_output_v6;
4609 		connp->conn_recv = tcp_input;
4610 
4611 		connp->conn_bound_source_v6 = ip6h->ip6_dst;
4612 		connp->conn_srcv6 = ip6h->ip6_dst;
4613 		connp->conn_remv6 = ip6h->ip6_src;
4614 
4615 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4616 		ifindex = (int)DB_CKSUMSTUFF(mp);
4617 		DB_CKSUMSTUFF(mp) = 0;
4618 
4619 		sin6 = sin6_null;
4620 		sin6.sin6_addr = ip6h->ip6_src;
4621 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4622 		sin6.sin6_family = AF_INET6;
4623 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4624 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4625 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4626 
4627 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4628 			/* Pass up the scope_id of remote addr */
4629 			sin6.sin6_scope_id = ifindex;
4630 		} else {
4631 			sin6.sin6_scope_id = 0;
4632 		}
4633 		if (tcp->tcp_recvdstaddr) {
4634 			sin6_t	sin6d;
4635 
4636 			sin6d = sin6_null;
4637 			sin6.sin6_addr = ip6h->ip6_dst;
4638 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4639 			sin6d.sin6_family = AF_INET;
4640 			tpi_mp = mi_tpi_extconn_ind(NULL,
4641 			    (char *)&sin6d, sizeof (sin6_t),
4642 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4643 			    (char *)&sin6d, sizeof (sin6_t),
4644 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4645 		} else {
4646 			tpi_mp = mi_tpi_conn_ind(NULL,
4647 			    (char *)&sin6, sizeof (sin6_t),
4648 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4649 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4650 		}
4651 	}
4652 
4653 	if (tpi_mp == NULL)
4654 		return (ENOMEM);
4655 
4656 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4657 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4658 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4659 	connp->conn_fully_bound = B_FALSE;
4660 
4661 	/* Inherit information from the "parent" */
4662 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4663 	tcp->tcp_family = ltcp->tcp_family;
4664 
4665 	tcp->tcp_wq = ltcp->tcp_wq;
4666 	tcp->tcp_rq = ltcp->tcp_rq;
4667 
4668 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4669 	tcp->tcp_detached = B_TRUE;
4670 	SOCK_CONNID_INIT(tcp->tcp_connid);
4671 	if ((err = tcp_init_values(tcp)) != 0) {
4672 		freemsg(tpi_mp);
4673 		return (err);
4674 	}
4675 
4676 	if (ipvers == IPV4_VERSION) {
4677 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4678 			freemsg(tpi_mp);
4679 			return (err);
4680 		}
4681 		ASSERT(tcp->tcp_ipha != NULL);
4682 	} else {
4683 		/* ifindex must be already set */
4684 		ASSERT(ifindex != 0);
4685 
4686 		if (ltcp->tcp_bound_if != 0) {
4687 			/*
4688 			 * Set newtcp's bound_if equal to
4689 			 * listener's value. If ifindex is
4690 			 * not the same as ltcp->tcp_bound_if,
4691 			 * it must be a packet for the ipmp group
4692 			 * of interfaces
4693 			 */
4694 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4695 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4696 			tcp->tcp_bound_if = ifindex;
4697 		}
4698 
4699 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4700 		tcp->tcp_recvifindex = 0;
4701 		tcp->tcp_recvhops = 0xffffffffU;
4702 		ASSERT(tcp->tcp_ip6h != NULL);
4703 	}
4704 
4705 	tcp->tcp_lport = ltcp->tcp_lport;
4706 
4707 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4708 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4709 			/*
4710 			 * Listener had options of some sort; eager inherits.
4711 			 * Free up the eager template and allocate one
4712 			 * of the right size.
4713 			 */
4714 			if (tcp->tcp_hdr_grown) {
4715 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4716 			} else {
4717 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4718 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4719 			}
4720 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4721 			    KM_NOSLEEP);
4722 			if (tcp->tcp_iphc == NULL) {
4723 				tcp->tcp_iphc_len = 0;
4724 				freemsg(tpi_mp);
4725 				return (ENOMEM);
4726 			}
4727 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4728 			tcp->tcp_hdr_grown = B_TRUE;
4729 		}
4730 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4731 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4732 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4733 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4734 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4735 
4736 		/*
4737 		 * Copy the IP+TCP header template from listener to eager
4738 		 */
4739 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4740 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4741 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4742 			    IPPROTO_RAW) {
4743 				tcp->tcp_ip6h =
4744 				    (ip6_t *)(tcp->tcp_iphc +
4745 				    sizeof (ip6i_t));
4746 			} else {
4747 				tcp->tcp_ip6h =
4748 				    (ip6_t *)(tcp->tcp_iphc);
4749 			}
4750 			tcp->tcp_ipha = NULL;
4751 		} else {
4752 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4753 			tcp->tcp_ip6h = NULL;
4754 		}
4755 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4756 		    tcp->tcp_ip_hdr_len);
4757 	} else {
4758 		/*
4759 		 * only valid case when ipversion of listener and
4760 		 * eager differ is when listener is IPv6 and
4761 		 * eager is IPv4.
4762 		 * Eager header template has been initialized to the
4763 		 * maximum v4 header sizes, which includes space for
4764 		 * TCP and IP options.
4765 		 */
4766 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4767 		    (tcp->tcp_ipversion == IPV4_VERSION));
4768 		ASSERT(tcp->tcp_iphc_len >=
4769 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4770 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4771 		/* copy IP header fields individually */
4772 		tcp->tcp_ipha->ipha_ttl =
4773 		    ltcp->tcp_ip6h->ip6_hops;
4774 		bcopy(ltcp->tcp_tcph->th_lport,
4775 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4776 	}
4777 
4778 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4779 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4780 	    sizeof (in_port_t));
4781 
4782 	if (ltcp->tcp_lport == 0) {
4783 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4784 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4785 		    sizeof (in_port_t));
4786 	}
4787 
4788 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4789 		ASSERT(ipha != NULL);
4790 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4791 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4792 
4793 		/* Source routing option copyover (reverse it) */
4794 		if (tcps->tcps_rev_src_routes)
4795 			tcp_opt_reverse(tcp, ipha);
4796 	} else {
4797 		ASSERT(ip6h != NULL);
4798 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4799 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4800 	}
4801 
4802 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4803 	ASSERT(!tcp->tcp_tconnind_started);
4804 	/*
4805 	 * If the SYN contains a credential, it's a loopback packet; attach
4806 	 * the credential to the TPI message.
4807 	 */
4808 	if ((cr = DB_CRED(idmp)) != NULL) {
4809 		mblk_setcred(tpi_mp, cr);
4810 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4811 	}
4812 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4813 
4814 	/* Inherit the listener's SSL protection state */
4815 
4816 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4817 		kssl_hold_ent(tcp->tcp_kssl_ent);
4818 		tcp->tcp_kssl_pending = B_TRUE;
4819 	}
4820 
4821 	/* Inherit the listener's non-STREAMS flag */
4822 	if (IPCL_IS_NONSTR(lconnp)) {
4823 		connp->conn_flags |= IPCL_NONSTR;
4824 		connp->conn_upcalls = lconnp->conn_upcalls;
4825 	}
4826 
4827 	return (0);
4828 }
4829 
4830 
4831 int
4832 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4833     tcph_t *tcph, mblk_t *idmp)
4834 {
4835 	tcp_t 		*ltcp = lconnp->conn_tcp;
4836 	tcp_t		*tcp = connp->conn_tcp;
4837 	sin_t		sin;
4838 	mblk_t		*tpi_mp = NULL;
4839 	int		err;
4840 	cred_t		*cr;
4841 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4842 
4843 	sin = sin_null;
4844 	sin.sin_addr.s_addr = ipha->ipha_src;
4845 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4846 	sin.sin_family = AF_INET;
4847 	if (ltcp->tcp_recvdstaddr) {
4848 		sin_t	sind;
4849 
4850 		sind = sin_null;
4851 		sind.sin_addr.s_addr = ipha->ipha_dst;
4852 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4853 		sind.sin_family = AF_INET;
4854 		tpi_mp = mi_tpi_extconn_ind(NULL,
4855 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4856 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4857 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4858 	} else {
4859 		tpi_mp = mi_tpi_conn_ind(NULL,
4860 		    (char *)&sin, sizeof (sin_t),
4861 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4862 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4863 	}
4864 
4865 	if (tpi_mp == NULL) {
4866 		return (ENOMEM);
4867 	}
4868 
4869 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4870 	connp->conn_send = ip_output;
4871 	connp->conn_recv = tcp_input;
4872 	connp->conn_fully_bound = B_FALSE;
4873 
4874 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_bound_source_v6);
4875 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4876 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4877 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4878 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4879 
4880 	/* Inherit information from the "parent" */
4881 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4882 	tcp->tcp_family = ltcp->tcp_family;
4883 	tcp->tcp_wq = ltcp->tcp_wq;
4884 	tcp->tcp_rq = ltcp->tcp_rq;
4885 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4886 	tcp->tcp_detached = B_TRUE;
4887 	SOCK_CONNID_INIT(tcp->tcp_connid);
4888 	if ((err = tcp_init_values(tcp)) != 0) {
4889 		freemsg(tpi_mp);
4890 		return (err);
4891 	}
4892 
4893 	/*
4894 	 * Let's make sure that eager tcp template has enough space to
4895 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4896 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4897 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4898 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4899 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4900 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4901 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4902 	 */
4903 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4904 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4905 
4906 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4907 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4908 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4909 	tcp->tcp_ttl = ltcp->tcp_ttl;
4910 	tcp->tcp_tos = ltcp->tcp_tos;
4911 
4912 	/* Copy the IP+TCP header template from listener to eager */
4913 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4914 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4915 	tcp->tcp_ip6h = NULL;
4916 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4917 	    tcp->tcp_ip_hdr_len);
4918 
4919 	/* Initialize the IP addresses and Ports */
4920 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4921 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4922 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4923 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4924 
4925 	/* Source routing option copyover (reverse it) */
4926 	if (tcps->tcps_rev_src_routes)
4927 		tcp_opt_reverse(tcp, ipha);
4928 
4929 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4930 	ASSERT(!tcp->tcp_tconnind_started);
4931 
4932 	/*
4933 	 * If the SYN contains a credential, it's a loopback packet; attach
4934 	 * the credential to the TPI message.
4935 	 */
4936 	if ((cr = DB_CRED(idmp)) != NULL) {
4937 		mblk_setcred(tpi_mp, cr);
4938 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4939 	}
4940 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4941 
4942 	/* Inherit the listener's SSL protection state */
4943 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4944 		kssl_hold_ent(tcp->tcp_kssl_ent);
4945 		tcp->tcp_kssl_pending = B_TRUE;
4946 	}
4947 
4948 	/* Inherit the listener's non-STREAMS flag */
4949 	if (IPCL_IS_NONSTR(lconnp)) {
4950 		connp->conn_flags |= IPCL_NONSTR;
4951 		connp->conn_upcalls = lconnp->conn_upcalls;
4952 	}
4953 
4954 	return (0);
4955 }
4956 
4957 /*
4958  * sets up conn for ipsec.
4959  * if the first mblk is M_CTL it is consumed and mpp is updated.
4960  * in case of error mpp is freed.
4961  */
4962 conn_t *
4963 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4964 {
4965 	conn_t 		*connp = tcp->tcp_connp;
4966 	conn_t 		*econnp;
4967 	squeue_t 	*new_sqp;
4968 	mblk_t 		*first_mp = *mpp;
4969 	mblk_t		*mp = *mpp;
4970 	boolean_t	mctl_present = B_FALSE;
4971 	uint_t		ipvers;
4972 
4973 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
4974 	if (econnp == NULL) {
4975 		freemsg(first_mp);
4976 		return (NULL);
4977 	}
4978 	if (DB_TYPE(mp) == M_CTL) {
4979 		if (mp->b_cont == NULL ||
4980 		    mp->b_cont->b_datap->db_type != M_DATA) {
4981 			freemsg(first_mp);
4982 			return (NULL);
4983 		}
4984 		mp = mp->b_cont;
4985 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4986 			freemsg(first_mp);
4987 			return (NULL);
4988 		}
4989 
4990 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4991 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4992 		mctl_present = B_TRUE;
4993 	} else {
4994 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4995 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4996 	}
4997 
4998 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4999 	DB_CKSUMSTART(mp) = 0;
5000 
5001 	ASSERT(OK_32PTR(mp->b_rptr));
5002 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5003 	if (ipvers == IPV4_VERSION) {
5004 		uint16_t  	*up;
5005 		uint32_t	ports;
5006 		ipha_t		*ipha;
5007 
5008 		ipha = (ipha_t *)mp->b_rptr;
5009 		up = (uint16_t *)((uchar_t *)ipha +
5010 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5011 		ports = *(uint32_t *)up;
5012 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5013 		    ipha->ipha_dst, ipha->ipha_src, ports);
5014 	} else {
5015 		uint16_t  	*up;
5016 		uint32_t	ports;
5017 		uint16_t	ip_hdr_len;
5018 		uint8_t		*nexthdrp;
5019 		ip6_t 		*ip6h;
5020 		tcph_t		*tcph;
5021 
5022 		ip6h = (ip6_t *)mp->b_rptr;
5023 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5024 			ip_hdr_len = IPV6_HDR_LEN;
5025 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5026 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5027 			CONN_DEC_REF(econnp);
5028 			freemsg(first_mp);
5029 			return (NULL);
5030 		}
5031 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5032 		up = (uint16_t *)tcph->th_lport;
5033 		ports = *(uint32_t *)up;
5034 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5035 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5036 	}
5037 
5038 	/*
5039 	 * The caller already ensured that there is a sqp present.
5040 	 */
5041 	econnp->conn_sqp = new_sqp;
5042 	econnp->conn_initial_sqp = new_sqp;
5043 
5044 	if (connp->conn_policy != NULL) {
5045 		ipsec_in_t *ii;
5046 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5047 		ASSERT(ii->ipsec_in_policy == NULL);
5048 		IPPH_REFHOLD(connp->conn_policy);
5049 		ii->ipsec_in_policy = connp->conn_policy;
5050 
5051 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5052 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5053 			CONN_DEC_REF(econnp);
5054 			freemsg(first_mp);
5055 			return (NULL);
5056 		}
5057 	}
5058 
5059 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5060 		CONN_DEC_REF(econnp);
5061 		freemsg(first_mp);
5062 		return (NULL);
5063 	}
5064 
5065 	/*
5066 	 * If we know we have some policy, pass the "IPSEC"
5067 	 * options size TCP uses this adjust the MSS.
5068 	 */
5069 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5070 	if (mctl_present) {
5071 		freeb(first_mp);
5072 		*mpp = mp;
5073 	}
5074 
5075 	return (econnp);
5076 }
5077 
5078 /*
5079  * tcp_get_conn/tcp_free_conn
5080  *
5081  * tcp_get_conn is used to get a clean tcp connection structure.
5082  * It tries to reuse the connections put on the freelist by the
5083  * time_wait_collector failing which it goes to kmem_cache. This
5084  * way has two benefits compared to just allocating from and
5085  * freeing to kmem_cache.
5086  * 1) The time_wait_collector can free (which includes the cleanup)
5087  * outside the squeue. So when the interrupt comes, we have a clean
5088  * connection sitting in the freelist. Obviously, this buys us
5089  * performance.
5090  *
5091  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5092  * has multiple disadvantages - tying up the squeue during alloc, and the
5093  * fact that IPSec policy initialization has to happen here which
5094  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5095  * But allocating the conn/tcp in IP land is also not the best since
5096  * we can't check the 'q' and 'q0' which are protected by squeue and
5097  * blindly allocate memory which might have to be freed here if we are
5098  * not allowed to accept the connection. By using the freelist and
5099  * putting the conn/tcp back in freelist, we don't pay a penalty for
5100  * allocating memory without checking 'q/q0' and freeing it if we can't
5101  * accept the connection.
5102  *
5103  * Care should be taken to put the conn back in the same squeue's freelist
5104  * from which it was allocated. Best results are obtained if conn is
5105  * allocated from listener's squeue and freed to the same. Time wait
5106  * collector will free up the freelist is the connection ends up sitting
5107  * there for too long.
5108  */
5109 void *
5110 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5111 {
5112 	tcp_t			*tcp = NULL;
5113 	conn_t			*connp = NULL;
5114 	squeue_t		*sqp = (squeue_t *)arg;
5115 	tcp_squeue_priv_t 	*tcp_time_wait;
5116 	netstack_t		*ns;
5117 
5118 	tcp_time_wait =
5119 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5120 
5121 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5122 	tcp = tcp_time_wait->tcp_free_list;
5123 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5124 	if (tcp != NULL) {
5125 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5126 		tcp_time_wait->tcp_free_list_cnt--;
5127 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5128 		tcp->tcp_time_wait_next = NULL;
5129 		connp = tcp->tcp_connp;
5130 		connp->conn_flags |= IPCL_REUSED;
5131 
5132 		ASSERT(tcp->tcp_tcps == NULL);
5133 		ASSERT(connp->conn_netstack == NULL);
5134 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5135 		ns = tcps->tcps_netstack;
5136 		netstack_hold(ns);
5137 		connp->conn_netstack = ns;
5138 		tcp->tcp_tcps = tcps;
5139 		TCPS_REFHOLD(tcps);
5140 		ipcl_globalhash_insert(connp);
5141 		return ((void *)connp);
5142 	}
5143 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5144 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5145 	    tcps->tcps_netstack)) == NULL)
5146 		return (NULL);
5147 	tcp = connp->conn_tcp;
5148 	/*
5149 	 * Pre-allocate the tcp_rsrv_mp.  This mblk will not be freed
5150 	 * until this conn_t/tcp_t is freed at ipcl_conn_destroy().
5151 	 */
5152 	if ((tcp->tcp_rsrv_mp = allocb(0, BPRI_HI)) == NULL) {
5153 		ipcl_conn_destroy(connp);
5154 		return (NULL);
5155 	}
5156 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5157 	tcp->tcp_tcps = tcps;
5158 	TCPS_REFHOLD(tcps);
5159 
5160 	return ((void *)connp);
5161 }
5162 
5163 /*
5164  * Update the cached label for the given tcp_t.  This should be called once per
5165  * connection, and before any packets are sent or tcp_process_options is
5166  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5167  */
5168 static boolean_t
5169 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5170 {
5171 	conn_t *connp = tcp->tcp_connp;
5172 
5173 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5174 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5175 		int added;
5176 
5177 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5178 		    connp->conn_mac_exempt,
5179 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5180 			return (B_FALSE);
5181 
5182 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5183 		if (added == -1)
5184 			return (B_FALSE);
5185 		tcp->tcp_hdr_len += added;
5186 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5187 		tcp->tcp_ip_hdr_len += added;
5188 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5189 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5190 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5191 			    tcp->tcp_hdr_len);
5192 			if (added == -1)
5193 				return (B_FALSE);
5194 			tcp->tcp_hdr_len += added;
5195 			tcp->tcp_tcph = (tcph_t *)
5196 			    ((uchar_t *)tcp->tcp_tcph + added);
5197 			tcp->tcp_ip_hdr_len += added;
5198 		}
5199 	} else {
5200 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5201 
5202 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5203 		    connp->conn_mac_exempt,
5204 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5205 			return (B_FALSE);
5206 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5207 		    &tcp->tcp_label_len, optbuf) != 0)
5208 			return (B_FALSE);
5209 		if (tcp_build_hdrs(tcp) != 0)
5210 			return (B_FALSE);
5211 	}
5212 
5213 	connp->conn_ulp_labeled = 1;
5214 
5215 	return (B_TRUE);
5216 }
5217 
5218 /* BEGIN CSTYLED */
5219 /*
5220  *
5221  * The sockfs ACCEPT path:
5222  * =======================
5223  *
5224  * The eager is now established in its own perimeter as soon as SYN is
5225  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5226  * completes the accept processing on the acceptor STREAM. The sending
5227  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5228  * listener but a TLI/XTI listener completes the accept processing
5229  * on the listener perimeter.
5230  *
5231  * Common control flow for 3 way handshake:
5232  * ----------------------------------------
5233  *
5234  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5235  *					-> tcp_conn_request()
5236  *
5237  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5238  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5239  *
5240  * Sockfs ACCEPT Path:
5241  * -------------------
5242  *
5243  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5244  * as STREAM entry point)
5245  *
5246  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5247  *
5248  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5249  * association (we are not behind eager's squeue but sockfs is protecting us
5250  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5251  * is changed to point at tcp_wput().
5252  *
5253  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5254  * listener (done on listener's perimeter).
5255  *
5256  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5257  * accept.
5258  *
5259  * TLI/XTI client ACCEPT path:
5260  * ---------------------------
5261  *
5262  * soaccept() sends T_CONN_RES on the listener STREAM.
5263  *
5264  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5265  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5266  *
5267  * Locks:
5268  * ======
5269  *
5270  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5271  * and listeners->tcp_eager_next_q.
5272  *
5273  * Referencing:
5274  * ============
5275  *
5276  * 1) We start out in tcp_conn_request by eager placing a ref on
5277  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5278  *
5279  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5280  * doing so we place a ref on the eager. This ref is finally dropped at the
5281  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5282  * reference is dropped by the squeue framework.
5283  *
5284  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5285  *
5286  * The reference must be released by the same entity that added the reference
5287  * In the above scheme, the eager is the entity that adds and releases the
5288  * references. Note that tcp_accept_finish executes in the squeue of the eager
5289  * (albeit after it is attached to the acceptor stream). Though 1. executes
5290  * in the listener's squeue, the eager is nascent at this point and the
5291  * reference can be considered to have been added on behalf of the eager.
5292  *
5293  * Eager getting a Reset or listener closing:
5294  * ==========================================
5295  *
5296  * Once the listener and eager are linked, the listener never does the unlink.
5297  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5298  * a message on all eager perimeter. The eager then does the unlink, clears
5299  * any pointers to the listener's queue and drops the reference to the
5300  * listener. The listener waits in tcp_close outside the squeue until its
5301  * refcount has dropped to 1. This ensures that the listener has waited for
5302  * all eagers to clear their association with the listener.
5303  *
5304  * Similarly, if eager decides to go away, it can unlink itself and close.
5305  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5306  * the reference to eager is still valid because of the extra ref we put
5307  * in tcp_send_conn_ind.
5308  *
5309  * Listener can always locate the eager under the protection
5310  * of the listener->tcp_eager_lock, and then do a refhold
5311  * on the eager during the accept processing.
5312  *
5313  * The acceptor stream accesses the eager in the accept processing
5314  * based on the ref placed on eager before sending T_conn_ind.
5315  * The only entity that can negate this refhold is a listener close
5316  * which is mutually exclusive with an active acceptor stream.
5317  *
5318  * Eager's reference on the listener
5319  * ===================================
5320  *
5321  * If the accept happens (even on a closed eager) the eager drops its
5322  * reference on the listener at the start of tcp_accept_finish. If the
5323  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5324  * the reference is dropped in tcp_closei_local. If the listener closes,
5325  * the reference is dropped in tcp_eager_kill. In all cases the reference
5326  * is dropped while executing in the eager's context (squeue).
5327  */
5328 /* END CSTYLED */
5329 
5330 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5331 
5332 /*
5333  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5334  * tcp_rput_data will not see any SYN packets.
5335  */
5336 /* ARGSUSED */
5337 void
5338 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5339 {
5340 	tcph_t		*tcph;
5341 	uint32_t	seg_seq;
5342 	tcp_t		*eager;
5343 	uint_t		ipvers;
5344 	ipha_t		*ipha;
5345 	ip6_t		*ip6h;
5346 	int		err;
5347 	conn_t		*econnp = NULL;
5348 	squeue_t	*new_sqp;
5349 	mblk_t		*mp1;
5350 	uint_t 		ip_hdr_len;
5351 	conn_t		*connp = (conn_t *)arg;
5352 	tcp_t		*tcp = connp->conn_tcp;
5353 	cred_t		*credp;
5354 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5355 	ip_stack_t	*ipst;
5356 
5357 	if (tcp->tcp_state != TCPS_LISTEN)
5358 		goto error2;
5359 
5360 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5361 
5362 	mutex_enter(&tcp->tcp_eager_lock);
5363 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5364 		mutex_exit(&tcp->tcp_eager_lock);
5365 		TCP_STAT(tcps, tcp_listendrop);
5366 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5367 		if (tcp->tcp_debug) {
5368 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5369 			    "tcp_conn_request: listen backlog (max=%d) "
5370 			    "overflow (%d pending) on %s",
5371 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5372 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5373 		}
5374 		goto error2;
5375 	}
5376 
5377 	if (tcp->tcp_conn_req_cnt_q0 >=
5378 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5379 		/*
5380 		 * Q0 is full. Drop a pending half-open req from the queue
5381 		 * to make room for the new SYN req. Also mark the time we
5382 		 * drop a SYN.
5383 		 *
5384 		 * A more aggressive defense against SYN attack will
5385 		 * be to set the "tcp_syn_defense" flag now.
5386 		 */
5387 		TCP_STAT(tcps, tcp_listendropq0);
5388 		tcp->tcp_last_rcv_lbolt = lbolt64;
5389 		if (!tcp_drop_q0(tcp)) {
5390 			mutex_exit(&tcp->tcp_eager_lock);
5391 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5392 			if (tcp->tcp_debug) {
5393 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5394 				    "tcp_conn_request: listen half-open queue "
5395 				    "(max=%d) full (%d pending) on %s",
5396 				    tcps->tcps_conn_req_max_q0,
5397 				    tcp->tcp_conn_req_cnt_q0,
5398 				    tcp_display(tcp, NULL,
5399 				    DISP_PORT_ONLY));
5400 			}
5401 			goto error2;
5402 		}
5403 	}
5404 	mutex_exit(&tcp->tcp_eager_lock);
5405 
5406 	/*
5407 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5408 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5409 	 * link local address.  If IPSec is enabled, db_struioflag has
5410 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5411 	 * otherwise an error case if neither of them is set.
5412 	 */
5413 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5414 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5415 		DB_CKSUMSTART(mp) = 0;
5416 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5417 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5418 		if (econnp == NULL)
5419 			goto error2;
5420 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5421 		econnp->conn_sqp = new_sqp;
5422 		econnp->conn_initial_sqp = new_sqp;
5423 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5424 		/*
5425 		 * mp is updated in tcp_get_ipsec_conn().
5426 		 */
5427 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5428 		if (econnp == NULL) {
5429 			/*
5430 			 * mp freed by tcp_get_ipsec_conn.
5431 			 */
5432 			return;
5433 		}
5434 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5435 	} else {
5436 		goto error2;
5437 	}
5438 
5439 	ASSERT(DB_TYPE(mp) == M_DATA);
5440 
5441 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5442 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5443 	ASSERT(OK_32PTR(mp->b_rptr));
5444 	if (ipvers == IPV4_VERSION) {
5445 		ipha = (ipha_t *)mp->b_rptr;
5446 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5447 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5448 	} else {
5449 		ip6h = (ip6_t *)mp->b_rptr;
5450 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5451 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5452 	}
5453 
5454 	if (tcp->tcp_family == AF_INET) {
5455 		ASSERT(ipvers == IPV4_VERSION);
5456 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5457 	} else {
5458 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5459 	}
5460 
5461 	if (err)
5462 		goto error3;
5463 
5464 	eager = econnp->conn_tcp;
5465 
5466 	/*
5467 	 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that at close
5468 	 * time, we will always have that to send up.  Otherwise, we need to do
5469 	 * special handling in case the allocation fails at that time.
5470 	 */
5471 	ASSERT(eager->tcp_ordrel_mp == NULL);
5472 	if (!IPCL_IS_NONSTR(econnp) &&
5473 	    (eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5474 		goto error3;
5475 
5476 	/* Inherit various TCP parameters from the listener */
5477 	eager->tcp_naglim = tcp->tcp_naglim;
5478 	eager->tcp_first_timer_threshold =
5479 	    tcp->tcp_first_timer_threshold;
5480 	eager->tcp_second_timer_threshold =
5481 	    tcp->tcp_second_timer_threshold;
5482 
5483 	eager->tcp_first_ctimer_threshold =
5484 	    tcp->tcp_first_ctimer_threshold;
5485 	eager->tcp_second_ctimer_threshold =
5486 	    tcp->tcp_second_ctimer_threshold;
5487 
5488 	/*
5489 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5490 	 * If it does not, the eager's receive window will be set to the
5491 	 * listener's receive window later in this function.
5492 	 */
5493 	eager->tcp_rwnd = 0;
5494 
5495 	/*
5496 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5497 	 * calling tcp_process_options() where tcp_mss_set() is called
5498 	 * to set the initial cwnd.
5499 	 */
5500 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5501 
5502 	/*
5503 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5504 	 * zone id before the accept is completed in tcp_wput_accept().
5505 	 */
5506 	econnp->conn_zoneid = connp->conn_zoneid;
5507 	econnp->conn_allzones = connp->conn_allzones;
5508 
5509 	/* Copy nexthop information from listener to eager */
5510 	if (connp->conn_nexthop_set) {
5511 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5512 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5513 	}
5514 
5515 	/*
5516 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5517 	 * eager is accepted
5518 	 */
5519 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5520 	crhold(credp);
5521 
5522 	/*
5523 	 * If the caller has the process-wide flag set, then default to MAC
5524 	 * exempt mode.  This allows read-down to unlabeled hosts.
5525 	 */
5526 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5527 		econnp->conn_mac_exempt = B_TRUE;
5528 
5529 	if (is_system_labeled()) {
5530 		cred_t *cr;
5531 
5532 		if (connp->conn_mlp_type != mlptSingle) {
5533 			cr = econnp->conn_peercred = DB_CRED(mp);
5534 			if (cr != NULL)
5535 				crhold(cr);
5536 			else
5537 				cr = econnp->conn_cred;
5538 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5539 			    econnp, cred_t *, cr)
5540 		} else {
5541 			cr = econnp->conn_cred;
5542 			DTRACE_PROBE2(syn_accept, conn_t *,
5543 			    econnp, cred_t *, cr)
5544 		}
5545 
5546 		if (!tcp_update_label(eager, cr)) {
5547 			DTRACE_PROBE3(
5548 			    tx__ip__log__error__connrequest__tcp,
5549 			    char *, "eager connp(1) label on SYN mp(2) failed",
5550 			    conn_t *, econnp, mblk_t *, mp);
5551 			goto error3;
5552 		}
5553 	}
5554 
5555 	eager->tcp_hard_binding = B_TRUE;
5556 
5557 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5558 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5559 
5560 	CL_INET_CONNECT(connp, eager, B_FALSE, err);
5561 	if (err != 0) {
5562 		tcp_bind_hash_remove(eager);
5563 		goto error3;
5564 	}
5565 
5566 	/*
5567 	 * No need to check for multicast destination since ip will only pass
5568 	 * up multicasts to those that have expressed interest
5569 	 * TODO: what about rejecting broadcasts?
5570 	 * Also check that source is not a multicast or broadcast address.
5571 	 */
5572 	eager->tcp_state = TCPS_SYN_RCVD;
5573 
5574 
5575 	/*
5576 	 * There should be no ire in the mp as we are being called after
5577 	 * receiving the SYN.
5578 	 */
5579 	ASSERT(tcp_ire_mp(&mp) == NULL);
5580 
5581 	/*
5582 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5583 	 */
5584 
5585 	if (tcp_adapt_ire(eager, NULL) == 0) {
5586 		/* Undo the bind_hash_insert */
5587 		tcp_bind_hash_remove(eager);
5588 		goto error3;
5589 	}
5590 
5591 	/* Process all TCP options. */
5592 	tcp_process_options(eager, tcph);
5593 
5594 	/* Is the other end ECN capable? */
5595 	if (tcps->tcps_ecn_permitted >= 1 &&
5596 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5597 		eager->tcp_ecn_ok = B_TRUE;
5598 	}
5599 
5600 	/*
5601 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5602 	 * window size changed via SO_RCVBUF option.  First round up the
5603 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5604 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5605 	 * setting.
5606 	 *
5607 	 * Note if there is a rpipe metric associated with the remote host,
5608 	 * we should not inherit receive window size from listener.
5609 	 */
5610 	eager->tcp_rwnd = MSS_ROUNDUP(
5611 	    (eager->tcp_rwnd == 0 ? tcp->tcp_recv_hiwater:
5612 	    eager->tcp_rwnd), eager->tcp_mss);
5613 	if (eager->tcp_snd_ws_ok)
5614 		tcp_set_ws_value(eager);
5615 	/*
5616 	 * Note that this is the only place tcp_rwnd_set() is called for
5617 	 * accepting a connection.  We need to call it here instead of
5618 	 * after the 3-way handshake because we need to tell the other
5619 	 * side our rwnd in the SYN-ACK segment.
5620 	 */
5621 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5622 
5623 	/*
5624 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5625 	 * via soaccept()->soinheritoptions() which essentially applies
5626 	 * all the listener options to the new STREAM. The options that we
5627 	 * need to take care of are:
5628 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5629 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5630 	 * SO_SNDBUF, SO_RCVBUF.
5631 	 *
5632 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5633 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5634 	 *		tcp_maxpsz_set() gets called later from
5635 	 *		tcp_accept_finish(), the option takes effect.
5636 	 *
5637 	 */
5638 	/* Set the TCP options */
5639 	eager->tcp_recv_hiwater = tcp->tcp_recv_hiwater;
5640 	eager->tcp_recv_lowater = tcp->tcp_recv_lowater;
5641 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5642 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5643 	eager->tcp_oobinline = tcp->tcp_oobinline;
5644 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5645 	eager->tcp_broadcast = tcp->tcp_broadcast;
5646 	eager->tcp_useloopback = tcp->tcp_useloopback;
5647 	eager->tcp_dontroute = tcp->tcp_dontroute;
5648 	eager->tcp_debug = tcp->tcp_debug;
5649 	eager->tcp_linger = tcp->tcp_linger;
5650 	eager->tcp_lingertime = tcp->tcp_lingertime;
5651 	if (tcp->tcp_ka_enabled)
5652 		eager->tcp_ka_enabled = 1;
5653 
5654 	/* Set the IP options */
5655 	econnp->conn_broadcast = connp->conn_broadcast;
5656 	econnp->conn_loopback = connp->conn_loopback;
5657 	econnp->conn_dontroute = connp->conn_dontroute;
5658 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5659 
5660 	/* Put a ref on the listener for the eager. */
5661 	CONN_INC_REF(connp);
5662 	mutex_enter(&tcp->tcp_eager_lock);
5663 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5664 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5665 	tcp->tcp_eager_next_q0 = eager;
5666 	eager->tcp_eager_prev_q0 = tcp;
5667 
5668 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5669 	eager->tcp_listener = tcp;
5670 	eager->tcp_saved_listener = tcp;
5671 
5672 	/*
5673 	 * Tag this detached tcp vector for later retrieval
5674 	 * by our listener client in tcp_accept().
5675 	 */
5676 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5677 	tcp->tcp_conn_req_cnt_q0++;
5678 	if (++tcp->tcp_conn_req_seqnum == -1) {
5679 		/*
5680 		 * -1 is "special" and defined in TPI as something
5681 		 * that should never be used in T_CONN_IND
5682 		 */
5683 		++tcp->tcp_conn_req_seqnum;
5684 	}
5685 	mutex_exit(&tcp->tcp_eager_lock);
5686 
5687 	if (tcp->tcp_syn_defense) {
5688 		/* Don't drop the SYN that comes from a good IP source */
5689 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5690 		if (addr_cache != NULL && eager->tcp_remote ==
5691 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5692 			eager->tcp_dontdrop = B_TRUE;
5693 		}
5694 	}
5695 
5696 	/*
5697 	 * We need to insert the eager in its own perimeter but as soon
5698 	 * as we do that, we expose the eager to the classifier and
5699 	 * should not touch any field outside the eager's perimeter.
5700 	 * So do all the work necessary before inserting the eager
5701 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5702 	 * will succeed but undo everything if it fails.
5703 	 */
5704 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5705 	eager->tcp_irs = seg_seq;
5706 	eager->tcp_rack = seg_seq;
5707 	eager->tcp_rnxt = seg_seq + 1;
5708 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5709 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5710 	eager->tcp_state = TCPS_SYN_RCVD;
5711 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5712 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5713 	if (mp1 == NULL) {
5714 		/*
5715 		 * Increment the ref count as we are going to
5716 		 * enqueueing an mp in squeue
5717 		 */
5718 		CONN_INC_REF(econnp);
5719 		goto error;
5720 	}
5721 
5722 	DB_CPID(mp1) = tcp->tcp_cpid;
5723 	mblk_setcred(mp1, CONN_CRED(eager->tcp_connp));
5724 	eager->tcp_cpid = tcp->tcp_cpid;
5725 	eager->tcp_open_time = lbolt64;
5726 
5727 	/*
5728 	 * We need to start the rto timer. In normal case, we start
5729 	 * the timer after sending the packet on the wire (or at
5730 	 * least believing that packet was sent by waiting for
5731 	 * CALL_IP_WPUT() to return). Since this is the first packet
5732 	 * being sent on the wire for the eager, our initial tcp_rto
5733 	 * is at least tcp_rexmit_interval_min which is a fairly
5734 	 * large value to allow the algorithm to adjust slowly to large
5735 	 * fluctuations of RTT during first few transmissions.
5736 	 *
5737 	 * Starting the timer first and then sending the packet in this
5738 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5739 	 * is of the order of several 100ms and starting the timer
5740 	 * first and then sending the packet will result in difference
5741 	 * of few micro seconds.
5742 	 *
5743 	 * Without this optimization, we are forced to hold the fanout
5744 	 * lock across the ipcl_bind_insert() and sending the packet
5745 	 * so that we don't race against an incoming packet (maybe RST)
5746 	 * for this eager.
5747 	 *
5748 	 * It is necessary to acquire an extra reference on the eager
5749 	 * at this point and hold it until after tcp_send_data() to
5750 	 * ensure against an eager close race.
5751 	 */
5752 
5753 	CONN_INC_REF(eager->tcp_connp);
5754 
5755 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5756 
5757 	/*
5758 	 * Insert the eager in its own perimeter now. We are ready to deal
5759 	 * with any packets on eager.
5760 	 */
5761 	if (eager->tcp_ipversion == IPV4_VERSION) {
5762 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5763 			goto error;
5764 		}
5765 	} else {
5766 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5767 			goto error;
5768 		}
5769 	}
5770 
5771 	/* mark conn as fully-bound */
5772 	econnp->conn_fully_bound = B_TRUE;
5773 
5774 	/* Send the SYN-ACK */
5775 	tcp_send_data(eager, eager->tcp_wq, mp1);
5776 	CONN_DEC_REF(eager->tcp_connp);
5777 	freemsg(mp);
5778 
5779 	return;
5780 error:
5781 	freemsg(mp1);
5782 	eager->tcp_closemp_used = B_TRUE;
5783 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5784 	mp1 = &eager->tcp_closemp;
5785 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5786 	    econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5787 
5788 	/*
5789 	 * If a connection already exists, send the mp to that connections so
5790 	 * that it can be appropriately dealt with.
5791 	 */
5792 	ipst = tcps->tcps_netstack->netstack_ip;
5793 
5794 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
5795 		if (!IPCL_IS_CONNECTED(econnp)) {
5796 			/*
5797 			 * Something bad happened. ipcl_conn_insert()
5798 			 * failed because a connection already existed
5799 			 * in connected hash but we can't find it
5800 			 * anymore (someone blew it away). Just
5801 			 * free this message and hopefully remote
5802 			 * will retransmit at which time the SYN can be
5803 			 * treated as a new connection or dealth with
5804 			 * a TH_RST if a connection already exists.
5805 			 */
5806 			CONN_DEC_REF(econnp);
5807 			freemsg(mp);
5808 		} else {
5809 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp,
5810 			    tcp_input, econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5811 		}
5812 	} else {
5813 		/* Nobody wants this packet */
5814 		freemsg(mp);
5815 	}
5816 	return;
5817 error3:
5818 	CONN_DEC_REF(econnp);
5819 error2:
5820 	freemsg(mp);
5821 }
5822 
5823 /*
5824  * In an ideal case of vertical partition in NUMA architecture, its
5825  * beneficial to have the listener and all the incoming connections
5826  * tied to the same squeue. The other constraint is that incoming
5827  * connections should be tied to the squeue attached to interrupted
5828  * CPU for obvious locality reason so this leaves the listener to
5829  * be tied to the same squeue. Our only problem is that when listener
5830  * is binding, the CPU that will get interrupted by the NIC whose
5831  * IP address the listener is binding to is not even known. So
5832  * the code below allows us to change that binding at the time the
5833  * CPU is interrupted by virtue of incoming connection's squeue.
5834  *
5835  * This is usefull only in case of a listener bound to a specific IP
5836  * address. For other kind of listeners, they get bound the
5837  * very first time and there is no attempt to rebind them.
5838  */
5839 void
5840 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5841 {
5842 	conn_t		*connp = (conn_t *)arg;
5843 	squeue_t	*sqp = (squeue_t *)arg2;
5844 	squeue_t	*new_sqp;
5845 	uint32_t	conn_flags;
5846 
5847 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5848 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5849 	} else {
5850 		goto done;
5851 	}
5852 
5853 	if (connp->conn_fanout == NULL)
5854 		goto done;
5855 
5856 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5857 		mutex_enter(&connp->conn_fanout->connf_lock);
5858 		mutex_enter(&connp->conn_lock);
5859 		/*
5860 		 * No one from read or write side can access us now
5861 		 * except for already queued packets on this squeue.
5862 		 * But since we haven't changed the squeue yet, they
5863 		 * can't execute. If they are processed after we have
5864 		 * changed the squeue, they are sent back to the
5865 		 * correct squeue down below.
5866 		 * But a listner close can race with processing of
5867 		 * incoming SYN. If incoming SYN processing changes
5868 		 * the squeue then the listener close which is waiting
5869 		 * to enter the squeue would operate on the wrong
5870 		 * squeue. Hence we don't change the squeue here unless
5871 		 * the refcount is exactly the minimum refcount. The
5872 		 * minimum refcount of 4 is counted as - 1 each for
5873 		 * TCP and IP, 1 for being in the classifier hash, and
5874 		 * 1 for the mblk being processed.
5875 		 */
5876 
5877 		if (connp->conn_ref != 4 ||
5878 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5879 			mutex_exit(&connp->conn_lock);
5880 			mutex_exit(&connp->conn_fanout->connf_lock);
5881 			goto done;
5882 		}
5883 		if (connp->conn_sqp != new_sqp) {
5884 			while (connp->conn_sqp != new_sqp)
5885 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5886 		}
5887 
5888 		do {
5889 			conn_flags = connp->conn_flags;
5890 			conn_flags |= IPCL_FULLY_BOUND;
5891 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5892 			    conn_flags);
5893 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5894 
5895 		mutex_exit(&connp->conn_fanout->connf_lock);
5896 		mutex_exit(&connp->conn_lock);
5897 	}
5898 
5899 done:
5900 	if (connp->conn_sqp != sqp) {
5901 		CONN_INC_REF(connp);
5902 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5903 		    SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5904 	} else {
5905 		tcp_conn_request(connp, mp, sqp);
5906 	}
5907 }
5908 
5909 /*
5910  * Successful connect request processing begins when our client passes
5911  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5912  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5913  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_tpi_connect() -> IP
5914  *   upstream <- tcp_rput()		<- IP
5915  * After various error checks are completed, tcp_tpi_connect() lays
5916  * the target address and port into the composite header template,
5917  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5918  * request followed by an IRE request, and passes the three mblk message
5919  * down to IP looking like this:
5920  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5921  * Processing continues in tcp_rput() when we receive the following message:
5922  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5923  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5924  * to fire off the connection request, and then passes the T_OK_ACK mblk
5925  * upstream that we filled in below.  There are, of course, numerous
5926  * error conditions along the way which truncate the processing described
5927  * above.
5928  */
5929 static void
5930 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5931 {
5932 	sin_t		*sin;
5933 	queue_t		*q = tcp->tcp_wq;
5934 	struct T_conn_req	*tcr;
5935 	struct sockaddr	*sa;
5936 	socklen_t	len;
5937 	int		error;
5938 
5939 	tcr = (struct T_conn_req *)mp->b_rptr;
5940 
5941 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5942 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5943 		tcp_err_ack(tcp, mp, TPROTO, 0);
5944 		return;
5945 	}
5946 
5947 	/*
5948 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5949 	 * will always have that to send up.  Otherwise, we need to do
5950 	 * special handling in case the allocation fails at that time.
5951 	 * If the end point is TPI, the tcp_t can be reused and the
5952 	 * tcp_ordrel_mp may be allocated already.
5953 	 */
5954 	if (tcp->tcp_ordrel_mp == NULL) {
5955 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5956 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5957 			return;
5958 		}
5959 	}
5960 
5961 	/*
5962 	 * Determine packet type based on type of address passed in
5963 	 * the request should contain an IPv4 or IPv6 address.
5964 	 * Make sure that address family matches the type of
5965 	 * family of the the address passed down
5966 	 */
5967 	switch (tcr->DEST_length) {
5968 	default:
5969 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5970 		return;
5971 
5972 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5973 		/*
5974 		 * XXX: The check for valid DEST_length was not there
5975 		 * in earlier releases and some buggy
5976 		 * TLI apps (e.g Sybase) got away with not feeding
5977 		 * in sin_zero part of address.
5978 		 * We allow that bug to keep those buggy apps humming.
5979 		 * Test suites require the check on DEST_length.
5980 		 * We construct a new mblk with valid DEST_length
5981 		 * free the original so the rest of the code does
5982 		 * not have to keep track of this special shorter
5983 		 * length address case.
5984 		 */
5985 		mblk_t *nmp;
5986 		struct T_conn_req *ntcr;
5987 		sin_t *nsin;
5988 
5989 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5990 		    tcr->OPT_length, BPRI_HI);
5991 		if (nmp == NULL) {
5992 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5993 			return;
5994 		}
5995 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5996 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5997 		ntcr->PRIM_type = T_CONN_REQ;
5998 		ntcr->DEST_length = sizeof (sin_t);
5999 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6000 
6001 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6002 		*nsin = sin_null;
6003 		/* Get pointer to shorter address to copy from original mp */
6004 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6005 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6006 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6007 			freemsg(nmp);
6008 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6009 			return;
6010 		}
6011 		nsin->sin_family = sin->sin_family;
6012 		nsin->sin_port = sin->sin_port;
6013 		nsin->sin_addr = sin->sin_addr;
6014 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6015 		nmp->b_wptr = (uchar_t *)&nsin[1];
6016 		if (tcr->OPT_length != 0) {
6017 			ntcr->OPT_length = tcr->OPT_length;
6018 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6019 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6020 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6021 			    tcr->OPT_length);
6022 			nmp->b_wptr += tcr->OPT_length;
6023 		}
6024 		freemsg(mp);	/* original mp freed */
6025 		mp = nmp;	/* re-initialize original variables */
6026 		tcr = ntcr;
6027 	}
6028 	/* FALLTHRU */
6029 
6030 	case sizeof (sin_t):
6031 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6032 		    sizeof (sin_t));
6033 		len = sizeof (sin_t);
6034 		break;
6035 
6036 	case sizeof (sin6_t):
6037 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6038 		    sizeof (sin6_t));
6039 		len = sizeof (sin6_t);
6040 		break;
6041 	}
6042 
6043 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
6044 	if (error != 0) {
6045 		tcp_err_ack(tcp, mp, TSYSERR, error);
6046 		return;
6047 	}
6048 
6049 	/*
6050 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6051 	 * should key on their sequence number and cut them loose.
6052 	 */
6053 
6054 	/*
6055 	 * If options passed in, feed it for verification and handling
6056 	 */
6057 	if (tcr->OPT_length != 0) {
6058 		mblk_t	*ok_mp;
6059 		mblk_t	*discon_mp;
6060 		mblk_t  *conn_opts_mp;
6061 		int t_error, sys_error, do_disconnect;
6062 
6063 		conn_opts_mp = NULL;
6064 
6065 		if (tcp_conprim_opt_process(tcp, mp,
6066 		    &do_disconnect, &t_error, &sys_error) < 0) {
6067 			if (do_disconnect) {
6068 				ASSERT(t_error == 0 && sys_error == 0);
6069 				discon_mp = mi_tpi_discon_ind(NULL,
6070 				    ECONNREFUSED, 0);
6071 				if (!discon_mp) {
6072 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6073 					    TSYSERR, ENOMEM);
6074 					return;
6075 				}
6076 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6077 				if (!ok_mp) {
6078 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6079 					    TSYSERR, ENOMEM);
6080 					return;
6081 				}
6082 				qreply(q, ok_mp);
6083 				qreply(q, discon_mp); /* no flush! */
6084 			} else {
6085 				ASSERT(t_error != 0);
6086 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6087 				    sys_error);
6088 			}
6089 			return;
6090 		}
6091 		/*
6092 		 * Success in setting options, the mp option buffer represented
6093 		 * by OPT_length/offset has been potentially modified and
6094 		 * contains results of option processing. We copy it in
6095 		 * another mp to save it for potentially influencing returning
6096 		 * it in T_CONN_CONN.
6097 		 */
6098 		if (tcr->OPT_length != 0) { /* there are resulting options */
6099 			conn_opts_mp = copyb(mp);
6100 			if (!conn_opts_mp) {
6101 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6102 				    TSYSERR, ENOMEM);
6103 				return;
6104 			}
6105 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6106 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6107 			/*
6108 			 * Note:
6109 			 * These resulting option negotiation can include any
6110 			 * end-to-end negotiation options but there no such
6111 			 * thing (yet?) in our TCP/IP.
6112 			 */
6113 		}
6114 	}
6115 
6116 	/* call the non-TPI version */
6117 	error = tcp_do_connect(tcp->tcp_connp, sa, len, DB_CRED(mp),
6118 	    DB_CPID(mp));
6119 	if (error < 0) {
6120 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
6121 	} else if (error > 0) {
6122 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
6123 	} else {
6124 		mp = mi_tpi_ok_ack_alloc(mp);
6125 	}
6126 
6127 	/*
6128 	 * Note: Code below is the "failure" case
6129 	 */
6130 	/* return error ack and blow away saved option results if any */
6131 connect_failed:
6132 	if (mp != NULL)
6133 		putnext(tcp->tcp_rq, mp);
6134 	else {
6135 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6136 		    TSYSERR, ENOMEM);
6137 	}
6138 }
6139 
6140 /*
6141  * Handle connect to IPv4 destinations, including connections for AF_INET6
6142  * sockets connecting to IPv4 mapped IPv6 destinations.
6143  */
6144 static int
6145 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
6146     uint_t srcid, cred_t *cr, pid_t pid)
6147 {
6148 	tcph_t	*tcph;
6149 	mblk_t	*mp;
6150 	ipaddr_t dstaddr = *dstaddrp;
6151 	int32_t	oldstate;
6152 	uint16_t lport;
6153 	int	error = 0;
6154 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6155 
6156 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6157 
6158 	/* Check for attempt to connect to INADDR_ANY */
6159 	if (dstaddr == INADDR_ANY)  {
6160 		/*
6161 		 * SunOS 4.x and 4.3 BSD allow an application
6162 		 * to connect a TCP socket to INADDR_ANY.
6163 		 * When they do this, the kernel picks the
6164 		 * address of one interface and uses it
6165 		 * instead.  The kernel usually ends up
6166 		 * picking the address of the loopback
6167 		 * interface.  This is an undocumented feature.
6168 		 * However, we provide the same thing here
6169 		 * in order to have source and binary
6170 		 * compatibility with SunOS 4.x.
6171 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6172 		 * generate the T_CONN_CON.
6173 		 */
6174 		dstaddr = htonl(INADDR_LOOPBACK);
6175 		*dstaddrp = dstaddr;
6176 	}
6177 
6178 	/* Handle __sin6_src_id if socket not bound to an IP address */
6179 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6180 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6181 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6182 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6183 		    tcp->tcp_ipha->ipha_src);
6184 	}
6185 
6186 	/*
6187 	 * Don't let an endpoint connect to itself.  Note that
6188 	 * the test here does not catch the case where the
6189 	 * source IP addr was left unspecified by the user. In
6190 	 * this case, the source addr is set in tcp_adapt_ire()
6191 	 * using the reply to the T_BIND message that we send
6192 	 * down to IP here and the check is repeated in tcp_rput_other.
6193 	 */
6194 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6195 	    dstport == tcp->tcp_lport) {
6196 		error = -TBADADDR;
6197 		goto failed;
6198 	}
6199 
6200 	tcp->tcp_ipha->ipha_dst = dstaddr;
6201 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6202 
6203 	/*
6204 	 * Massage a source route if any putting the first hop
6205 	 * in iph_dst. Compute a starting value for the checksum which
6206 	 * takes into account that the original iph_dst should be
6207 	 * included in the checksum but that ip will include the
6208 	 * first hop in the source route in the tcp checksum.
6209 	 */
6210 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6211 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6212 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6213 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6214 	if ((int)tcp->tcp_sum < 0)
6215 		tcp->tcp_sum--;
6216 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6217 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6218 	    (tcp->tcp_sum >> 16));
6219 	tcph = tcp->tcp_tcph;
6220 	*(uint16_t *)tcph->th_fport = dstport;
6221 	tcp->tcp_fport = dstport;
6222 
6223 	oldstate = tcp->tcp_state;
6224 	/*
6225 	 * At this point the remote destination address and remote port fields
6226 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6227 	 * have to see which state tcp was in so we can take apropriate action.
6228 	 */
6229 	if (oldstate == TCPS_IDLE) {
6230 		/*
6231 		 * We support a quick connect capability here, allowing
6232 		 * clients to transition directly from IDLE to SYN_SENT
6233 		 * tcp_bindi will pick an unused port, insert the connection
6234 		 * in the bind hash and transition to BOUND state.
6235 		 */
6236 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6237 		    tcp, B_TRUE);
6238 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6239 		    B_FALSE, B_FALSE);
6240 		if (lport == 0) {
6241 			error = -TNOADDR;
6242 			goto failed;
6243 		}
6244 	}
6245 	tcp->tcp_state = TCPS_SYN_SENT;
6246 
6247 	mp = allocb(sizeof (ire_t), BPRI_HI);
6248 	if (mp == NULL) {
6249 		tcp->tcp_state = oldstate;
6250 		error = ENOMEM;
6251 		goto failed;
6252 	}
6253 
6254 	mp->b_wptr += sizeof (ire_t);
6255 	mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6256 	tcp->tcp_hard_binding = 1;
6257 
6258 	/*
6259 	 * We need to make sure that the conn_recv is set to a non-null
6260 	 * value before we insert the conn_t into the classifier table.
6261 	 * This is to avoid a race with an incoming packet which does
6262 	 * an ipcl_classify().
6263 	 */
6264 	tcp->tcp_connp->conn_recv = tcp_input;
6265 
6266 	if (tcp->tcp_family == AF_INET) {
6267 		error = ip_proto_bind_connected_v4(tcp->tcp_connp, &mp,
6268 		    IPPROTO_TCP, &tcp->tcp_ipha->ipha_src, tcp->tcp_lport,
6269 		    tcp->tcp_remote, tcp->tcp_fport, B_TRUE, B_TRUE);
6270 	} else {
6271 		in6_addr_t v6src;
6272 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6273 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6274 		} else {
6275 			v6src = tcp->tcp_ip6h->ip6_src;
6276 		}
6277 		error = ip_proto_bind_connected_v6(tcp->tcp_connp, &mp,
6278 		    IPPROTO_TCP, &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6279 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE);
6280 	}
6281 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6282 	tcp->tcp_active_open = 1;
6283 
6284 
6285 	return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6286 failed:
6287 	/* return error ack and blow away saved option results if any */
6288 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6289 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6290 	return (error);
6291 }
6292 
6293 /*
6294  * Handle connect to IPv6 destinations.
6295  */
6296 static int
6297 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
6298     uint32_t flowinfo, uint_t srcid, uint32_t scope_id, cred_t *cr, pid_t pid)
6299 {
6300 	tcph_t	*tcph;
6301 	mblk_t	*mp;
6302 	ip6_rthdr_t *rth;
6303 	int32_t  oldstate;
6304 	uint16_t lport;
6305 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6306 	int	error = 0;
6307 	conn_t	*connp = tcp->tcp_connp;
6308 
6309 	ASSERT(tcp->tcp_family == AF_INET6);
6310 
6311 	/*
6312 	 * If we're here, it means that the destination address is a native
6313 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6314 	 * reason why it might not be IPv6 is if the socket was bound to an
6315 	 * IPv4-mapped IPv6 address.
6316 	 */
6317 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6318 		return (-TBADADDR);
6319 	}
6320 
6321 	/*
6322 	 * Interpret a zero destination to mean loopback.
6323 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6324 	 * generate the T_CONN_CON.
6325 	 */
6326 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6327 		*dstaddrp = ipv6_loopback;
6328 	}
6329 
6330 	/* Handle __sin6_src_id if socket not bound to an IP address */
6331 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6332 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6333 		    connp->conn_zoneid, tcps->tcps_netstack);
6334 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6335 	}
6336 
6337 	/*
6338 	 * Take care of the scope_id now and add ip6i_t
6339 	 * if ip6i_t is not already allocated through TCP
6340 	 * sticky options. At this point tcp_ip6h does not
6341 	 * have dst info, thus use dstaddrp.
6342 	 */
6343 	if (scope_id != 0 &&
6344 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6345 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6346 		ip6i_t  *ip6i;
6347 
6348 		ipp->ipp_ifindex = scope_id;
6349 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6350 
6351 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6352 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6353 			/* Already allocated */
6354 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6355 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6356 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6357 		} else {
6358 			int reterr;
6359 
6360 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6361 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6362 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6363 			reterr = tcp_build_hdrs(tcp);
6364 			if (reterr != 0)
6365 				goto failed;
6366 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6367 		}
6368 	}
6369 
6370 	/*
6371 	 * Don't let an endpoint connect to itself.  Note that
6372 	 * the test here does not catch the case where the
6373 	 * source IP addr was left unspecified by the user. In
6374 	 * this case, the source addr is set in tcp_adapt_ire()
6375 	 * using the reply to the T_BIND message that we send
6376 	 * down to IP here and the check is repeated in tcp_rput_other.
6377 	 */
6378 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6379 	    (dstport == tcp->tcp_lport)) {
6380 		error = -TBADADDR;
6381 		goto failed;
6382 	}
6383 
6384 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6385 	tcp->tcp_remote_v6 = *dstaddrp;
6386 	tcp->tcp_ip6h->ip6_vcf =
6387 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6388 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6389 
6390 	/*
6391 	 * Massage a routing header (if present) putting the first hop
6392 	 * in ip6_dst. Compute a starting value for the checksum which
6393 	 * takes into account that the original ip6_dst should be
6394 	 * included in the checksum but that ip will include the
6395 	 * first hop in the source route in the tcp checksum.
6396 	 */
6397 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6398 	if (rth != NULL) {
6399 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6400 		    tcps->tcps_netstack);
6401 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6402 		    (tcp->tcp_sum >> 16));
6403 	} else {
6404 		tcp->tcp_sum = 0;
6405 	}
6406 
6407 	tcph = tcp->tcp_tcph;
6408 	*(uint16_t *)tcph->th_fport = dstport;
6409 	tcp->tcp_fport = dstport;
6410 
6411 	oldstate = tcp->tcp_state;
6412 	/*
6413 	 * At this point the remote destination address and remote port fields
6414 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6415 	 * have to see which state tcp was in so we can take apropriate action.
6416 	 */
6417 	if (oldstate == TCPS_IDLE) {
6418 		/*
6419 		 * We support a quick connect capability here, allowing
6420 		 * clients to transition directly from IDLE to SYN_SENT
6421 		 * tcp_bindi will pick an unused port, insert the connection
6422 		 * in the bind hash and transition to BOUND state.
6423 		 */
6424 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6425 		    tcp, B_TRUE);
6426 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6427 		    B_FALSE, B_FALSE);
6428 		if (lport == 0) {
6429 			error = -TNOADDR;
6430 			goto failed;
6431 		}
6432 	}
6433 	tcp->tcp_state = TCPS_SYN_SENT;
6434 
6435 	mp = allocb(sizeof (ire_t), BPRI_HI);
6436 	if (mp != NULL) {
6437 		in6_addr_t v6src;
6438 
6439 		mp->b_wptr += sizeof (ire_t);
6440 		mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6441 
6442 		tcp->tcp_hard_binding = 1;
6443 
6444 		/*
6445 		 * We need to make sure that the conn_recv is set to a non-null
6446 		 * value before we insert the conn_t into the classifier table.
6447 		 * This is to avoid a race with an incoming packet which does
6448 		 * an ipcl_classify().
6449 		 */
6450 		tcp->tcp_connp->conn_recv = tcp_input;
6451 
6452 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6453 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6454 		} else {
6455 			v6src = tcp->tcp_ip6h->ip6_src;
6456 		}
6457 		error = ip_proto_bind_connected_v6(connp, &mp, IPPROTO_TCP,
6458 		    &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6459 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE);
6460 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6461 		tcp->tcp_active_open = 1;
6462 
6463 		return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6464 	}
6465 	/* Error case */
6466 	tcp->tcp_state = oldstate;
6467 	error = ENOMEM;
6468 
6469 failed:
6470 	/* return error ack and blow away saved option results if any */
6471 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6472 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6473 	return (error);
6474 }
6475 
6476 /*
6477  * We need a stream q for detached closing tcp connections
6478  * to use.  Our client hereby indicates that this q is the
6479  * one to use.
6480  */
6481 static void
6482 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6483 {
6484 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6485 	queue_t	*q = tcp->tcp_wq;
6486 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6487 
6488 #ifdef NS_DEBUG
6489 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6490 	    tcps->tcps_netstack->netstack_stackid);
6491 #endif
6492 	mp->b_datap->db_type = M_IOCACK;
6493 	iocp->ioc_count = 0;
6494 	mutex_enter(&tcps->tcps_g_q_lock);
6495 	if (tcps->tcps_g_q != NULL) {
6496 		mutex_exit(&tcps->tcps_g_q_lock);
6497 		iocp->ioc_error = EALREADY;
6498 	} else {
6499 		int error = 0;
6500 		conn_t *connp = tcp->tcp_connp;
6501 		ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
6502 
6503 		tcps->tcps_g_q = tcp->tcp_rq;
6504 		mutex_exit(&tcps->tcps_g_q_lock);
6505 		iocp->ioc_error = 0;
6506 		iocp->ioc_rval = 0;
6507 		/*
6508 		 * We are passing tcp_sticky_ipp as NULL
6509 		 * as it is not useful for tcp_default queue
6510 		 *
6511 		 * Set conn_recv just in case.
6512 		 */
6513 		tcp->tcp_connp->conn_recv = tcp_conn_request;
6514 
6515 		ASSERT(connp->conn_af_isv6);
6516 		connp->conn_ulp = IPPROTO_TCP;
6517 
6518 		if (ipst->ips_ipcl_proto_fanout_v6[IPPROTO_TCP].connf_head !=
6519 		    NULL || connp->conn_mac_exempt) {
6520 			error = -TBADADDR;
6521 		} else {
6522 			connp->conn_srcv6 = ipv6_all_zeros;
6523 			ipcl_proto_insert_v6(connp, IPPROTO_TCP);
6524 		}
6525 
6526 		(void) tcp_post_ip_bind(tcp, NULL, error, NULL, 0);
6527 	}
6528 	qreply(q, mp);
6529 }
6530 
6531 static int
6532 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
6533 {
6534 	tcp_t	*ltcp = NULL;
6535 	conn_t	*connp;
6536 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6537 
6538 	/*
6539 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6540 	 * when the stream is in BOUND state. Do not send a reset,
6541 	 * since the destination IP address is not valid, and it can
6542 	 * be the initialized value of all zeros (broadcast address).
6543 	 *
6544 	 * XXX There won't be any pending bind request to IP.
6545 	 */
6546 	if (tcp->tcp_state <= TCPS_BOUND) {
6547 		if (tcp->tcp_debug) {
6548 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6549 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6550 		}
6551 		return (TOUTSTATE);
6552 	}
6553 
6554 
6555 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6556 
6557 		/*
6558 		 * According to TPI, for non-listeners, ignore seqnum
6559 		 * and disconnect.
6560 		 * Following interpretation of -1 seqnum is historical
6561 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6562 		 * a valid seqnum should not be -1).
6563 		 *
6564 		 *	-1 means disconnect everything
6565 		 *	regardless even on a listener.
6566 		 */
6567 
6568 		int old_state = tcp->tcp_state;
6569 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6570 
6571 		/*
6572 		 * The connection can't be on the tcp_time_wait_head list
6573 		 * since it is not detached.
6574 		 */
6575 		ASSERT(tcp->tcp_time_wait_next == NULL);
6576 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6577 		ASSERT(tcp->tcp_time_wait_expire == 0);
6578 		ltcp = NULL;
6579 		/*
6580 		 * If it used to be a listener, check to make sure no one else
6581 		 * has taken the port before switching back to LISTEN state.
6582 		 */
6583 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6584 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6585 			    tcp->tcp_ipha->ipha_src,
6586 			    tcp->tcp_connp->conn_zoneid, ipst);
6587 			if (connp != NULL)
6588 				ltcp = connp->conn_tcp;
6589 		} else {
6590 			/* Allow tcp_bound_if listeners? */
6591 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6592 			    &tcp->tcp_ip6h->ip6_src, 0,
6593 			    tcp->tcp_connp->conn_zoneid, ipst);
6594 			if (connp != NULL)
6595 				ltcp = connp->conn_tcp;
6596 		}
6597 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6598 			tcp->tcp_state = TCPS_LISTEN;
6599 		} else if (old_state > TCPS_BOUND) {
6600 			tcp->tcp_conn_req_max = 0;
6601 			tcp->tcp_state = TCPS_BOUND;
6602 		}
6603 		if (ltcp != NULL)
6604 			CONN_DEC_REF(ltcp->tcp_connp);
6605 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6606 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6607 		} else if (old_state == TCPS_ESTABLISHED ||
6608 		    old_state == TCPS_CLOSE_WAIT) {
6609 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6610 		}
6611 
6612 		if (tcp->tcp_fused)
6613 			tcp_unfuse(tcp);
6614 
6615 		mutex_enter(&tcp->tcp_eager_lock);
6616 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6617 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6618 			tcp_eager_cleanup(tcp, 0);
6619 		}
6620 		mutex_exit(&tcp->tcp_eager_lock);
6621 
6622 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6623 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6624 
6625 		tcp_reinit(tcp);
6626 
6627 		return (0);
6628 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6629 		return (TBADSEQ);
6630 	}
6631 	return (0);
6632 }
6633 
6634 /*
6635  * Our client hereby directs us to reject the connection request
6636  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6637  * of sending the appropriate RST, not an ICMP error.
6638  */
6639 static void
6640 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6641 {
6642 	t_scalar_t seqnum;
6643 	int	error;
6644 
6645 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6646 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6647 		tcp_err_ack(tcp, mp, TPROTO, 0);
6648 		return;
6649 	}
6650 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6651 	error = tcp_disconnect_common(tcp, seqnum);
6652 	if (error != 0)
6653 		tcp_err_ack(tcp, mp, error, 0);
6654 	else {
6655 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6656 			/* Send M_FLUSH according to TPI */
6657 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6658 		}
6659 		mp = mi_tpi_ok_ack_alloc(mp);
6660 		if (mp)
6661 			putnext(tcp->tcp_rq, mp);
6662 	}
6663 }
6664 
6665 /*
6666  * Diagnostic routine used to return a string associated with the tcp state.
6667  * Note that if the caller does not supply a buffer, it will use an internal
6668  * static string.  This means that if multiple threads call this function at
6669  * the same time, output can be corrupted...  Note also that this function
6670  * does not check the size of the supplied buffer.  The caller has to make
6671  * sure that it is big enough.
6672  */
6673 static char *
6674 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6675 {
6676 	char		buf1[30];
6677 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6678 	char		*buf;
6679 	char		*cp;
6680 	in6_addr_t	local, remote;
6681 	char		local_addrbuf[INET6_ADDRSTRLEN];
6682 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6683 
6684 	if (sup_buf != NULL)
6685 		buf = sup_buf;
6686 	else
6687 		buf = priv_buf;
6688 
6689 	if (tcp == NULL)
6690 		return ("NULL_TCP");
6691 	switch (tcp->tcp_state) {
6692 	case TCPS_CLOSED:
6693 		cp = "TCP_CLOSED";
6694 		break;
6695 	case TCPS_IDLE:
6696 		cp = "TCP_IDLE";
6697 		break;
6698 	case TCPS_BOUND:
6699 		cp = "TCP_BOUND";
6700 		break;
6701 	case TCPS_LISTEN:
6702 		cp = "TCP_LISTEN";
6703 		break;
6704 	case TCPS_SYN_SENT:
6705 		cp = "TCP_SYN_SENT";
6706 		break;
6707 	case TCPS_SYN_RCVD:
6708 		cp = "TCP_SYN_RCVD";
6709 		break;
6710 	case TCPS_ESTABLISHED:
6711 		cp = "TCP_ESTABLISHED";
6712 		break;
6713 	case TCPS_CLOSE_WAIT:
6714 		cp = "TCP_CLOSE_WAIT";
6715 		break;
6716 	case TCPS_FIN_WAIT_1:
6717 		cp = "TCP_FIN_WAIT_1";
6718 		break;
6719 	case TCPS_CLOSING:
6720 		cp = "TCP_CLOSING";
6721 		break;
6722 	case TCPS_LAST_ACK:
6723 		cp = "TCP_LAST_ACK";
6724 		break;
6725 	case TCPS_FIN_WAIT_2:
6726 		cp = "TCP_FIN_WAIT_2";
6727 		break;
6728 	case TCPS_TIME_WAIT:
6729 		cp = "TCP_TIME_WAIT";
6730 		break;
6731 	default:
6732 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6733 		cp = buf1;
6734 		break;
6735 	}
6736 	switch (format) {
6737 	case DISP_ADDR_AND_PORT:
6738 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6739 			/*
6740 			 * Note that we use the remote address in the tcp_b
6741 			 * structure.  This means that it will print out
6742 			 * the real destination address, not the next hop's
6743 			 * address if source routing is used.
6744 			 */
6745 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6746 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6747 
6748 		} else {
6749 			local = tcp->tcp_ip_src_v6;
6750 			remote = tcp->tcp_remote_v6;
6751 		}
6752 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6753 		    sizeof (local_addrbuf));
6754 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6755 		    sizeof (remote_addrbuf));
6756 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6757 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6758 		    ntohs(tcp->tcp_fport), cp);
6759 		break;
6760 	case DISP_PORT_ONLY:
6761 	default:
6762 		(void) mi_sprintf(buf, "[%u, %u] %s",
6763 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6764 		break;
6765 	}
6766 
6767 	return (buf);
6768 }
6769 
6770 /*
6771  * Called via squeue to get on to eager's perimeter. It sends a
6772  * TH_RST if eager is in the fanout table. The listener wants the
6773  * eager to disappear either by means of tcp_eager_blowoff() or
6774  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
6775  * called (via squeue) if the eager cannot be inserted in the
6776  * fanout table in tcp_conn_request().
6777  */
6778 /* ARGSUSED */
6779 void
6780 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6781 {
6782 	conn_t	*econnp = (conn_t *)arg;
6783 	tcp_t	*eager = econnp->conn_tcp;
6784 	tcp_t	*listener = eager->tcp_listener;
6785 	tcp_stack_t	*tcps = eager->tcp_tcps;
6786 
6787 	/*
6788 	 * We could be called because listener is closing. Since
6789 	 * the eager is using listener's queue's, its not safe.
6790 	 * Better use the default queue just to send the TH_RST
6791 	 * out.
6792 	 */
6793 	ASSERT(tcps->tcps_g_q != NULL);
6794 	eager->tcp_rq = tcps->tcps_g_q;
6795 	eager->tcp_wq = WR(tcps->tcps_g_q);
6796 
6797 	/*
6798 	 * An eager's conn_fanout will be NULL if it's a duplicate
6799 	 * for an existing 4-tuples in the conn fanout table.
6800 	 * We don't want to send an RST out in such case.
6801 	 */
6802 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
6803 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6804 		    eager, eager->tcp_snxt, 0, TH_RST);
6805 	}
6806 
6807 	/* We are here because listener wants this eager gone */
6808 	if (listener != NULL) {
6809 		mutex_enter(&listener->tcp_eager_lock);
6810 		tcp_eager_unlink(eager);
6811 		if (eager->tcp_tconnind_started) {
6812 			/*
6813 			 * The eager has sent a conn_ind up to the
6814 			 * listener but listener decides to close
6815 			 * instead. We need to drop the extra ref
6816 			 * placed on eager in tcp_rput_data() before
6817 			 * sending the conn_ind to listener.
6818 			 */
6819 			CONN_DEC_REF(econnp);
6820 		}
6821 		mutex_exit(&listener->tcp_eager_lock);
6822 		CONN_DEC_REF(listener->tcp_connp);
6823 	}
6824 
6825 	if (eager->tcp_state > TCPS_BOUND)
6826 		tcp_close_detached(eager);
6827 }
6828 
6829 /*
6830  * Reset any eager connection hanging off this listener marked
6831  * with 'seqnum' and then reclaim it's resources.
6832  */
6833 static boolean_t
6834 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6835 {
6836 	tcp_t	*eager;
6837 	mblk_t 	*mp;
6838 	tcp_stack_t	*tcps = listener->tcp_tcps;
6839 
6840 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
6841 	eager = listener;
6842 	mutex_enter(&listener->tcp_eager_lock);
6843 	do {
6844 		eager = eager->tcp_eager_next_q;
6845 		if (eager == NULL) {
6846 			mutex_exit(&listener->tcp_eager_lock);
6847 			return (B_FALSE);
6848 		}
6849 	} while (eager->tcp_conn_req_seqnum != seqnum);
6850 
6851 	if (eager->tcp_closemp_used) {
6852 		mutex_exit(&listener->tcp_eager_lock);
6853 		return (B_TRUE);
6854 	}
6855 	eager->tcp_closemp_used = B_TRUE;
6856 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6857 	CONN_INC_REF(eager->tcp_connp);
6858 	mutex_exit(&listener->tcp_eager_lock);
6859 	mp = &eager->tcp_closemp;
6860 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6861 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
6862 	return (B_TRUE);
6863 }
6864 
6865 /*
6866  * Reset any eager connection hanging off this listener
6867  * and then reclaim it's resources.
6868  */
6869 static void
6870 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6871 {
6872 	tcp_t	*eager;
6873 	mblk_t	*mp;
6874 	tcp_stack_t	*tcps = listener->tcp_tcps;
6875 
6876 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6877 
6878 	if (!q0_only) {
6879 		/* First cleanup q */
6880 		TCP_STAT(tcps, tcp_eager_blowoff_q);
6881 		eager = listener->tcp_eager_next_q;
6882 		while (eager != NULL) {
6883 			if (!eager->tcp_closemp_used) {
6884 				eager->tcp_closemp_used = B_TRUE;
6885 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6886 				CONN_INC_REF(eager->tcp_connp);
6887 				mp = &eager->tcp_closemp;
6888 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6889 				    tcp_eager_kill, eager->tcp_connp,
6890 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
6891 			}
6892 			eager = eager->tcp_eager_next_q;
6893 		}
6894 	}
6895 	/* Then cleanup q0 */
6896 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6897 	eager = listener->tcp_eager_next_q0;
6898 	while (eager != listener) {
6899 		if (!eager->tcp_closemp_used) {
6900 			eager->tcp_closemp_used = B_TRUE;
6901 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6902 			CONN_INC_REF(eager->tcp_connp);
6903 			mp = &eager->tcp_closemp;
6904 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6905 			    tcp_eager_kill, eager->tcp_connp, SQ_FILL,
6906 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6907 		}
6908 		eager = eager->tcp_eager_next_q0;
6909 	}
6910 }
6911 
6912 /*
6913  * If we are an eager connection hanging off a listener that hasn't
6914  * formally accepted the connection yet, get off his list and blow off
6915  * any data that we have accumulated.
6916  */
6917 static void
6918 tcp_eager_unlink(tcp_t *tcp)
6919 {
6920 	tcp_t	*listener = tcp->tcp_listener;
6921 
6922 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6923 	ASSERT(listener != NULL);
6924 	if (tcp->tcp_eager_next_q0 != NULL) {
6925 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6926 
6927 		/* Remove the eager tcp from q0 */
6928 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6929 		    tcp->tcp_eager_prev_q0;
6930 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6931 		    tcp->tcp_eager_next_q0;
6932 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6933 		listener->tcp_conn_req_cnt_q0--;
6934 
6935 		tcp->tcp_eager_next_q0 = NULL;
6936 		tcp->tcp_eager_prev_q0 = NULL;
6937 
6938 		/*
6939 		 * Take the eager out, if it is in the list of droppable
6940 		 * eagers.
6941 		 */
6942 		MAKE_UNDROPPABLE(tcp);
6943 
6944 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6945 			/* we have timed out before */
6946 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6947 			listener->tcp_syn_rcvd_timeout--;
6948 		}
6949 	} else {
6950 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6951 		tcp_t	*prev = NULL;
6952 
6953 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6954 			if (tcpp[0] == tcp) {
6955 				if (listener->tcp_eager_last_q == tcp) {
6956 					/*
6957 					 * If we are unlinking the last
6958 					 * element on the list, adjust
6959 					 * tail pointer. Set tail pointer
6960 					 * to nil when list is empty.
6961 					 */
6962 					ASSERT(tcp->tcp_eager_next_q == NULL);
6963 					if (listener->tcp_eager_last_q ==
6964 					    listener->tcp_eager_next_q) {
6965 						listener->tcp_eager_last_q =
6966 						    NULL;
6967 					} else {
6968 						/*
6969 						 * We won't get here if there
6970 						 * is only one eager in the
6971 						 * list.
6972 						 */
6973 						ASSERT(prev != NULL);
6974 						listener->tcp_eager_last_q =
6975 						    prev;
6976 					}
6977 				}
6978 				tcpp[0] = tcp->tcp_eager_next_q;
6979 				tcp->tcp_eager_next_q = NULL;
6980 				tcp->tcp_eager_last_q = NULL;
6981 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6982 				listener->tcp_conn_req_cnt_q--;
6983 				break;
6984 			}
6985 			prev = tcpp[0];
6986 		}
6987 	}
6988 	tcp->tcp_listener = NULL;
6989 }
6990 
6991 /* Shorthand to generate and send TPI error acks to our client */
6992 static void
6993 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6994 {
6995 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6996 		putnext(tcp->tcp_rq, mp);
6997 }
6998 
6999 /* Shorthand to generate and send TPI error acks to our client */
7000 static void
7001 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7002     int t_error, int sys_error)
7003 {
7004 	struct T_error_ack	*teackp;
7005 
7006 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7007 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7008 		teackp = (struct T_error_ack *)mp->b_rptr;
7009 		teackp->ERROR_prim = primitive;
7010 		teackp->TLI_error = t_error;
7011 		teackp->UNIX_error = sys_error;
7012 		putnext(tcp->tcp_rq, mp);
7013 	}
7014 }
7015 
7016 /*
7017  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7018  * but instead the code relies on:
7019  * - the fact that the address of the array and its size never changes
7020  * - the atomic assignment of the elements of the array
7021  */
7022 /* ARGSUSED */
7023 static int
7024 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7025 {
7026 	int i;
7027 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7028 
7029 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7030 		if (tcps->tcps_g_epriv_ports[i] != 0)
7031 			(void) mi_mpprintf(mp, "%d ",
7032 			    tcps->tcps_g_epriv_ports[i]);
7033 	}
7034 	return (0);
7035 }
7036 
7037 /*
7038  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7039  * threads from changing it at the same time.
7040  */
7041 /* ARGSUSED */
7042 static int
7043 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7044     cred_t *cr)
7045 {
7046 	long	new_value;
7047 	int	i;
7048 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7049 
7050 	/*
7051 	 * Fail the request if the new value does not lie within the
7052 	 * port number limits.
7053 	 */
7054 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7055 	    new_value <= 0 || new_value >= 65536) {
7056 		return (EINVAL);
7057 	}
7058 
7059 	mutex_enter(&tcps->tcps_epriv_port_lock);
7060 	/* Check if the value is already in the list */
7061 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7062 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7063 			mutex_exit(&tcps->tcps_epriv_port_lock);
7064 			return (EEXIST);
7065 		}
7066 	}
7067 	/* Find an empty slot */
7068 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7069 		if (tcps->tcps_g_epriv_ports[i] == 0)
7070 			break;
7071 	}
7072 	if (i == tcps->tcps_g_num_epriv_ports) {
7073 		mutex_exit(&tcps->tcps_epriv_port_lock);
7074 		return (EOVERFLOW);
7075 	}
7076 	/* Set the new value */
7077 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7078 	mutex_exit(&tcps->tcps_epriv_port_lock);
7079 	return (0);
7080 }
7081 
7082 /*
7083  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7084  * threads from changing it at the same time.
7085  */
7086 /* ARGSUSED */
7087 static int
7088 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7089     cred_t *cr)
7090 {
7091 	long	new_value;
7092 	int	i;
7093 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7094 
7095 	/*
7096 	 * Fail the request if the new value does not lie within the
7097 	 * port number limits.
7098 	 */
7099 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7100 	    new_value >= 65536) {
7101 		return (EINVAL);
7102 	}
7103 
7104 	mutex_enter(&tcps->tcps_epriv_port_lock);
7105 	/* Check that the value is already in the list */
7106 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7107 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7108 			break;
7109 	}
7110 	if (i == tcps->tcps_g_num_epriv_ports) {
7111 		mutex_exit(&tcps->tcps_epriv_port_lock);
7112 		return (ESRCH);
7113 	}
7114 	/* Clear the value */
7115 	tcps->tcps_g_epriv_ports[i] = 0;
7116 	mutex_exit(&tcps->tcps_epriv_port_lock);
7117 	return (0);
7118 }
7119 
7120 /* Return the TPI/TLI equivalent of our current tcp_state */
7121 static int
7122 tcp_tpistate(tcp_t *tcp)
7123 {
7124 	switch (tcp->tcp_state) {
7125 	case TCPS_IDLE:
7126 		return (TS_UNBND);
7127 	case TCPS_LISTEN:
7128 		/*
7129 		 * Return whether there are outstanding T_CONN_IND waiting
7130 		 * for the matching T_CONN_RES. Therefore don't count q0.
7131 		 */
7132 		if (tcp->tcp_conn_req_cnt_q > 0)
7133 			return (TS_WRES_CIND);
7134 		else
7135 			return (TS_IDLE);
7136 	case TCPS_BOUND:
7137 		return (TS_IDLE);
7138 	case TCPS_SYN_SENT:
7139 		return (TS_WCON_CREQ);
7140 	case TCPS_SYN_RCVD:
7141 		/*
7142 		 * Note: assumption: this has to the active open SYN_RCVD.
7143 		 * The passive instance is detached in SYN_RCVD stage of
7144 		 * incoming connection processing so we cannot get request
7145 		 * for T_info_ack on it.
7146 		 */
7147 		return (TS_WACK_CRES);
7148 	case TCPS_ESTABLISHED:
7149 		return (TS_DATA_XFER);
7150 	case TCPS_CLOSE_WAIT:
7151 		return (TS_WREQ_ORDREL);
7152 	case TCPS_FIN_WAIT_1:
7153 		return (TS_WIND_ORDREL);
7154 	case TCPS_FIN_WAIT_2:
7155 		return (TS_WIND_ORDREL);
7156 
7157 	case TCPS_CLOSING:
7158 	case TCPS_LAST_ACK:
7159 	case TCPS_TIME_WAIT:
7160 	case TCPS_CLOSED:
7161 		/*
7162 		 * Following TS_WACK_DREQ7 is a rendition of "not
7163 		 * yet TS_IDLE" TPI state. There is no best match to any
7164 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7165 		 * choose a value chosen that will map to TLI/XTI level
7166 		 * state of TSTATECHNG (state is process of changing) which
7167 		 * captures what this dummy state represents.
7168 		 */
7169 		return (TS_WACK_DREQ7);
7170 	default:
7171 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7172 		    tcp->tcp_state, tcp_display(tcp, NULL,
7173 		    DISP_PORT_ONLY));
7174 		return (TS_UNBND);
7175 	}
7176 }
7177 
7178 static void
7179 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7180 {
7181 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7182 
7183 	if (tcp->tcp_family == AF_INET6)
7184 		*tia = tcp_g_t_info_ack_v6;
7185 	else
7186 		*tia = tcp_g_t_info_ack;
7187 	tia->CURRENT_state = tcp_tpistate(tcp);
7188 	tia->OPT_size = tcp_max_optsize;
7189 	if (tcp->tcp_mss == 0) {
7190 		/* Not yet set - tcp_open does not set mss */
7191 		if (tcp->tcp_ipversion == IPV4_VERSION)
7192 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7193 		else
7194 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7195 	} else {
7196 		tia->TIDU_size = tcp->tcp_mss;
7197 	}
7198 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7199 }
7200 
7201 static void
7202 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
7203     t_uscalar_t cap_bits1)
7204 {
7205 	tcap->CAP_bits1 = 0;
7206 
7207 	if (cap_bits1 & TC1_INFO) {
7208 		tcp_copy_info(&tcap->INFO_ack, tcp);
7209 		tcap->CAP_bits1 |= TC1_INFO;
7210 	}
7211 
7212 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7213 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7214 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7215 	}
7216 
7217 }
7218 
7219 /*
7220  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7221  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7222  * tcp_g_t_info_ack.  The current state of the stream is copied from
7223  * tcp_state.
7224  */
7225 static void
7226 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7227 {
7228 	t_uscalar_t		cap_bits1;
7229 	struct T_capability_ack	*tcap;
7230 
7231 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7232 		freemsg(mp);
7233 		return;
7234 	}
7235 
7236 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7237 
7238 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7239 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7240 	if (mp == NULL)
7241 		return;
7242 
7243 	tcap = (struct T_capability_ack *)mp->b_rptr;
7244 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
7245 
7246 	putnext(tcp->tcp_rq, mp);
7247 }
7248 
7249 /*
7250  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7251  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7252  * The current state of the stream is copied from tcp_state.
7253  */
7254 static void
7255 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7256 {
7257 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7258 	    T_INFO_ACK);
7259 	if (!mp) {
7260 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7261 		return;
7262 	}
7263 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7264 	putnext(tcp->tcp_rq, mp);
7265 }
7266 
7267 /* Respond to the TPI addr request */
7268 static void
7269 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7270 {
7271 	sin_t	*sin;
7272 	mblk_t	*ackmp;
7273 	struct T_addr_ack *taa;
7274 
7275 	/* Make it large enough for worst case */
7276 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7277 	    2 * sizeof (sin6_t), 1);
7278 	if (ackmp == NULL) {
7279 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7280 		return;
7281 	}
7282 
7283 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7284 		tcp_addr_req_ipv6(tcp, ackmp);
7285 		return;
7286 	}
7287 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7288 
7289 	bzero(taa, sizeof (struct T_addr_ack));
7290 	ackmp->b_wptr = (uchar_t *)&taa[1];
7291 
7292 	taa->PRIM_type = T_ADDR_ACK;
7293 	ackmp->b_datap->db_type = M_PCPROTO;
7294 
7295 	/*
7296 	 * Note: Following code assumes 32 bit alignment of basic
7297 	 * data structures like sin_t and struct T_addr_ack.
7298 	 */
7299 	if (tcp->tcp_state >= TCPS_BOUND) {
7300 		/*
7301 		 * Fill in local address
7302 		 */
7303 		taa->LOCADDR_length = sizeof (sin_t);
7304 		taa->LOCADDR_offset = sizeof (*taa);
7305 
7306 		sin = (sin_t *)&taa[1];
7307 
7308 		/* Fill zeroes and then intialize non-zero fields */
7309 		*sin = sin_null;
7310 
7311 		sin->sin_family = AF_INET;
7312 
7313 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7314 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7315 
7316 		ackmp->b_wptr = (uchar_t *)&sin[1];
7317 
7318 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7319 			/*
7320 			 * Fill in Remote address
7321 			 */
7322 			taa->REMADDR_length = sizeof (sin_t);
7323 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7324 			    taa->LOCADDR_length);
7325 
7326 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7327 			*sin = sin_null;
7328 			sin->sin_family = AF_INET;
7329 			sin->sin_addr.s_addr = tcp->tcp_remote;
7330 			sin->sin_port = tcp->tcp_fport;
7331 
7332 			ackmp->b_wptr = (uchar_t *)&sin[1];
7333 		}
7334 	}
7335 	putnext(tcp->tcp_rq, ackmp);
7336 }
7337 
7338 /* Assumes that tcp_addr_req gets enough space and alignment */
7339 static void
7340 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7341 {
7342 	sin6_t	*sin6;
7343 	struct T_addr_ack *taa;
7344 
7345 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7346 	ASSERT(OK_32PTR(ackmp->b_rptr));
7347 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7348 	    2 * sizeof (sin6_t));
7349 
7350 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7351 
7352 	bzero(taa, sizeof (struct T_addr_ack));
7353 	ackmp->b_wptr = (uchar_t *)&taa[1];
7354 
7355 	taa->PRIM_type = T_ADDR_ACK;
7356 	ackmp->b_datap->db_type = M_PCPROTO;
7357 
7358 	/*
7359 	 * Note: Following code assumes 32 bit alignment of basic
7360 	 * data structures like sin6_t and struct T_addr_ack.
7361 	 */
7362 	if (tcp->tcp_state >= TCPS_BOUND) {
7363 		/*
7364 		 * Fill in local address
7365 		 */
7366 		taa->LOCADDR_length = sizeof (sin6_t);
7367 		taa->LOCADDR_offset = sizeof (*taa);
7368 
7369 		sin6 = (sin6_t *)&taa[1];
7370 		*sin6 = sin6_null;
7371 
7372 		sin6->sin6_family = AF_INET6;
7373 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7374 		sin6->sin6_port = tcp->tcp_lport;
7375 
7376 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7377 
7378 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7379 			/*
7380 			 * Fill in Remote address
7381 			 */
7382 			taa->REMADDR_length = sizeof (sin6_t);
7383 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7384 			    taa->LOCADDR_length);
7385 
7386 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7387 			*sin6 = sin6_null;
7388 			sin6->sin6_family = AF_INET6;
7389 			sin6->sin6_flowinfo =
7390 			    tcp->tcp_ip6h->ip6_vcf &
7391 			    ~IPV6_VERS_AND_FLOW_MASK;
7392 			sin6->sin6_addr = tcp->tcp_remote_v6;
7393 			sin6->sin6_port = tcp->tcp_fport;
7394 
7395 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7396 		}
7397 	}
7398 	putnext(tcp->tcp_rq, ackmp);
7399 }
7400 
7401 /*
7402  * Handle reinitialization of a tcp structure.
7403  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7404  */
7405 static void
7406 tcp_reinit(tcp_t *tcp)
7407 {
7408 	mblk_t	*mp;
7409 	int 	err;
7410 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7411 
7412 	TCP_STAT(tcps, tcp_reinit_calls);
7413 
7414 	/* tcp_reinit should never be called for detached tcp_t's */
7415 	ASSERT(tcp->tcp_listener == NULL);
7416 	ASSERT((tcp->tcp_family == AF_INET &&
7417 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7418 	    (tcp->tcp_family == AF_INET6 &&
7419 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7420 	    tcp->tcp_ipversion == IPV6_VERSION)));
7421 
7422 	/* Cancel outstanding timers */
7423 	tcp_timers_stop(tcp);
7424 
7425 	/*
7426 	 * Reset everything in the state vector, after updating global
7427 	 * MIB data from instance counters.
7428 	 */
7429 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7430 	tcp->tcp_ibsegs = 0;
7431 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7432 	tcp->tcp_obsegs = 0;
7433 
7434 	tcp_close_mpp(&tcp->tcp_xmit_head);
7435 	if (tcp->tcp_snd_zcopy_aware)
7436 		tcp_zcopy_notify(tcp);
7437 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7438 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7439 	mutex_enter(&tcp->tcp_non_sq_lock);
7440 	if (tcp->tcp_flow_stopped &&
7441 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7442 		tcp_clrqfull(tcp);
7443 	}
7444 	mutex_exit(&tcp->tcp_non_sq_lock);
7445 	tcp_close_mpp(&tcp->tcp_reass_head);
7446 	tcp->tcp_reass_tail = NULL;
7447 	if (tcp->tcp_rcv_list != NULL) {
7448 		/* Free b_next chain */
7449 		tcp_close_mpp(&tcp->tcp_rcv_list);
7450 		tcp->tcp_rcv_last_head = NULL;
7451 		tcp->tcp_rcv_last_tail = NULL;
7452 		tcp->tcp_rcv_cnt = 0;
7453 	}
7454 	tcp->tcp_rcv_last_tail = NULL;
7455 
7456 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7457 		freemsg(mp);
7458 		tcp->tcp_urp_mp = NULL;
7459 	}
7460 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7461 		freemsg(mp);
7462 		tcp->tcp_urp_mark_mp = NULL;
7463 	}
7464 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7465 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7466 		freeb(tcp->tcp_fused_sigurg_mp);
7467 		tcp->tcp_fused_sigurg_mp = NULL;
7468 	}
7469 	if (tcp->tcp_ordrel_mp != NULL) {
7470 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7471 		freeb(tcp->tcp_ordrel_mp);
7472 		tcp->tcp_ordrel_mp = NULL;
7473 	}
7474 
7475 	/*
7476 	 * Following is a union with two members which are
7477 	 * identical types and size so the following cleanup
7478 	 * is enough.
7479 	 */
7480 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7481 
7482 	CL_INET_DISCONNECT(tcp->tcp_connp, tcp);
7483 
7484 	/*
7485 	 * The connection can't be on the tcp_time_wait_head list
7486 	 * since it is not detached.
7487 	 */
7488 	ASSERT(tcp->tcp_time_wait_next == NULL);
7489 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7490 	ASSERT(tcp->tcp_time_wait_expire == 0);
7491 
7492 	if (tcp->tcp_kssl_pending) {
7493 		tcp->tcp_kssl_pending = B_FALSE;
7494 
7495 		/* Don't reset if the initialized by bind. */
7496 		if (tcp->tcp_kssl_ent != NULL) {
7497 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7498 			    KSSL_NO_PROXY);
7499 		}
7500 	}
7501 	if (tcp->tcp_kssl_ctx != NULL) {
7502 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7503 		tcp->tcp_kssl_ctx = NULL;
7504 	}
7505 
7506 	/*
7507 	 * Reset/preserve other values
7508 	 */
7509 	tcp_reinit_values(tcp);
7510 	ipcl_hash_remove(tcp->tcp_connp);
7511 	conn_delete_ire(tcp->tcp_connp, NULL);
7512 	tcp_ipsec_cleanup(tcp);
7513 
7514 	if (tcp->tcp_conn_req_max != 0) {
7515 		/*
7516 		 * This is the case when a TLI program uses the same
7517 		 * transport end point to accept a connection.  This
7518 		 * makes the TCP both a listener and acceptor.  When
7519 		 * this connection is closed, we need to set the state
7520 		 * back to TCPS_LISTEN.  Make sure that the eager list
7521 		 * is reinitialized.
7522 		 *
7523 		 * Note that this stream is still bound to the four
7524 		 * tuples of the previous connection in IP.  If a new
7525 		 * SYN with different foreign address comes in, IP will
7526 		 * not find it and will send it to the global queue.  In
7527 		 * the global queue, TCP will do a tcp_lookup_listener()
7528 		 * to find this stream.  This works because this stream
7529 		 * is only removed from connected hash.
7530 		 *
7531 		 */
7532 		tcp->tcp_state = TCPS_LISTEN;
7533 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7534 		tcp->tcp_eager_next_drop_q0 = tcp;
7535 		tcp->tcp_eager_prev_drop_q0 = tcp;
7536 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7537 		if (tcp->tcp_family == AF_INET6) {
7538 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7539 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7540 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7541 		} else {
7542 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7543 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7544 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7545 		}
7546 	} else {
7547 		tcp->tcp_state = TCPS_BOUND;
7548 	}
7549 
7550 	/*
7551 	 * Initialize to default values
7552 	 * Can't fail since enough header template space already allocated
7553 	 * at open().
7554 	 */
7555 	err = tcp_init_values(tcp);
7556 	ASSERT(err == 0);
7557 	/* Restore state in tcp_tcph */
7558 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7559 	if (tcp->tcp_ipversion == IPV4_VERSION)
7560 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7561 	else
7562 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7563 	/*
7564 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7565 	 * since the lookup funcs can only lookup on tcp_t
7566 	 */
7567 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7568 
7569 	ASSERT(tcp->tcp_ptpbhn != NULL);
7570 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
7571 		tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7572 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
7573 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
7574 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7575 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7576 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7577 }
7578 
7579 /*
7580  * Force values to zero that need be zero.
7581  * Do not touch values asociated with the BOUND or LISTEN state
7582  * since the connection will end up in that state after the reinit.
7583  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7584  * structure!
7585  */
7586 static void
7587 tcp_reinit_values(tcp)
7588 	tcp_t *tcp;
7589 {
7590 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7591 
7592 #ifndef	lint
7593 #define	DONTCARE(x)
7594 #define	PRESERVE(x)
7595 #else
7596 #define	DONTCARE(x)	((x) = (x))
7597 #define	PRESERVE(x)	((x) = (x))
7598 #endif	/* lint */
7599 
7600 	PRESERVE(tcp->tcp_bind_hash_port);
7601 	PRESERVE(tcp->tcp_bind_hash);
7602 	PRESERVE(tcp->tcp_ptpbhn);
7603 	PRESERVE(tcp->tcp_acceptor_hash);
7604 	PRESERVE(tcp->tcp_ptpahn);
7605 
7606 	/* Should be ASSERT NULL on these with new code! */
7607 	ASSERT(tcp->tcp_time_wait_next == NULL);
7608 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7609 	ASSERT(tcp->tcp_time_wait_expire == 0);
7610 	PRESERVE(tcp->tcp_state);
7611 	PRESERVE(tcp->tcp_rq);
7612 	PRESERVE(tcp->tcp_wq);
7613 
7614 	ASSERT(tcp->tcp_xmit_head == NULL);
7615 	ASSERT(tcp->tcp_xmit_last == NULL);
7616 	ASSERT(tcp->tcp_unsent == 0);
7617 	ASSERT(tcp->tcp_xmit_tail == NULL);
7618 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7619 
7620 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7621 	tcp->tcp_suna = 0;			/* Displayed in mib */
7622 	tcp->tcp_swnd = 0;
7623 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7624 
7625 	ASSERT(tcp->tcp_ibsegs == 0);
7626 	ASSERT(tcp->tcp_obsegs == 0);
7627 
7628 	if (tcp->tcp_iphc != NULL) {
7629 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7630 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7631 	}
7632 
7633 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7634 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7635 	DONTCARE(tcp->tcp_ipha);
7636 	DONTCARE(tcp->tcp_ip6h);
7637 	DONTCARE(tcp->tcp_ip_hdr_len);
7638 	DONTCARE(tcp->tcp_tcph);
7639 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7640 	tcp->tcp_valid_bits = 0;
7641 
7642 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7643 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7644 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7645 	tcp->tcp_last_rcv_lbolt = 0;
7646 
7647 	tcp->tcp_init_cwnd = 0;
7648 
7649 	tcp->tcp_urp_last_valid = 0;
7650 	tcp->tcp_hard_binding = 0;
7651 	tcp->tcp_hard_bound = 0;
7652 	PRESERVE(tcp->tcp_cred);
7653 	PRESERVE(tcp->tcp_cpid);
7654 	PRESERVE(tcp->tcp_open_time);
7655 	PRESERVE(tcp->tcp_exclbind);
7656 
7657 	tcp->tcp_fin_acked = 0;
7658 	tcp->tcp_fin_rcvd = 0;
7659 	tcp->tcp_fin_sent = 0;
7660 	tcp->tcp_ordrel_done = 0;
7661 
7662 	tcp->tcp_debug = 0;
7663 	tcp->tcp_dontroute = 0;
7664 	tcp->tcp_broadcast = 0;
7665 
7666 	tcp->tcp_useloopback = 0;
7667 	tcp->tcp_reuseaddr = 0;
7668 	tcp->tcp_oobinline = 0;
7669 	tcp->tcp_dgram_errind = 0;
7670 
7671 	tcp->tcp_detached = 0;
7672 	tcp->tcp_bind_pending = 0;
7673 	tcp->tcp_unbind_pending = 0;
7674 
7675 	tcp->tcp_snd_ws_ok = B_FALSE;
7676 	tcp->tcp_snd_ts_ok = B_FALSE;
7677 	tcp->tcp_linger = 0;
7678 	tcp->tcp_ka_enabled = 0;
7679 	tcp->tcp_zero_win_probe = 0;
7680 
7681 	tcp->tcp_loopback = 0;
7682 	tcp->tcp_refuse = 0;
7683 	tcp->tcp_localnet = 0;
7684 	tcp->tcp_syn_defense = 0;
7685 	tcp->tcp_set_timer = 0;
7686 
7687 	tcp->tcp_active_open = 0;
7688 	tcp->tcp_rexmit = B_FALSE;
7689 	tcp->tcp_xmit_zc_clean = B_FALSE;
7690 
7691 	tcp->tcp_snd_sack_ok = B_FALSE;
7692 	PRESERVE(tcp->tcp_recvdstaddr);
7693 	tcp->tcp_hwcksum = B_FALSE;
7694 
7695 	tcp->tcp_ire_ill_check_done = B_FALSE;
7696 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7697 
7698 	tcp->tcp_mdt = B_FALSE;
7699 	tcp->tcp_mdt_hdr_head = 0;
7700 	tcp->tcp_mdt_hdr_tail = 0;
7701 
7702 	tcp->tcp_conn_def_q0 = 0;
7703 	tcp->tcp_ip_forward_progress = B_FALSE;
7704 	tcp->tcp_anon_priv_bind = 0;
7705 	tcp->tcp_ecn_ok = B_FALSE;
7706 
7707 	tcp->tcp_cwr = B_FALSE;
7708 	tcp->tcp_ecn_echo_on = B_FALSE;
7709 
7710 	if (tcp->tcp_sack_info != NULL) {
7711 		if (tcp->tcp_notsack_list != NULL) {
7712 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7713 		}
7714 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7715 		tcp->tcp_sack_info = NULL;
7716 	}
7717 
7718 	tcp->tcp_rcv_ws = 0;
7719 	tcp->tcp_snd_ws = 0;
7720 	tcp->tcp_ts_recent = 0;
7721 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7722 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7723 	tcp->tcp_if_mtu = 0;
7724 
7725 	ASSERT(tcp->tcp_reass_head == NULL);
7726 	ASSERT(tcp->tcp_reass_tail == NULL);
7727 
7728 	tcp->tcp_cwnd_cnt = 0;
7729 
7730 	ASSERT(tcp->tcp_rcv_list == NULL);
7731 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7732 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7733 	ASSERT(tcp->tcp_rcv_cnt == 0);
7734 
7735 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7736 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7737 	tcp->tcp_csuna = 0;
7738 
7739 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7740 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7741 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7742 	tcp->tcp_rtt_update = 0;
7743 
7744 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7745 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7746 
7747 	tcp->tcp_rack = 0;			/* Displayed in mib */
7748 	tcp->tcp_rack_cnt = 0;
7749 	tcp->tcp_rack_cur_max = 0;
7750 	tcp->tcp_rack_abs_max = 0;
7751 
7752 	tcp->tcp_max_swnd = 0;
7753 
7754 	ASSERT(tcp->tcp_listener == NULL);
7755 
7756 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7757 
7758 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7759 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7760 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7761 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7762 
7763 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7764 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7765 	PRESERVE(tcp->tcp_conn_req_max);
7766 	PRESERVE(tcp->tcp_conn_req_seqnum);
7767 
7768 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7769 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7770 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7771 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7772 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7773 
7774 	tcp->tcp_lingertime = 0;
7775 
7776 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7777 	ASSERT(tcp->tcp_urp_mp == NULL);
7778 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7779 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7780 
7781 	ASSERT(tcp->tcp_eager_next_q == NULL);
7782 	ASSERT(tcp->tcp_eager_last_q == NULL);
7783 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7784 	    tcp->tcp_eager_prev_q0 == NULL) ||
7785 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7786 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7787 
7788 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
7789 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
7790 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
7791 
7792 	tcp->tcp_client_errno = 0;
7793 
7794 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7795 
7796 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7797 
7798 	PRESERVE(tcp->tcp_bound_source_v6);
7799 	tcp->tcp_last_sent_len = 0;
7800 	tcp->tcp_dupack_cnt = 0;
7801 
7802 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7803 	PRESERVE(tcp->tcp_lport);
7804 
7805 	PRESERVE(tcp->tcp_acceptor_lockp);
7806 
7807 	ASSERT(tcp->tcp_ordrel_mp == NULL);
7808 	PRESERVE(tcp->tcp_acceptor_id);
7809 	DONTCARE(tcp->tcp_ipsec_overhead);
7810 
7811 	PRESERVE(tcp->tcp_family);
7812 	if (tcp->tcp_family == AF_INET6) {
7813 		tcp->tcp_ipversion = IPV6_VERSION;
7814 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7815 	} else {
7816 		tcp->tcp_ipversion = IPV4_VERSION;
7817 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7818 	}
7819 
7820 	tcp->tcp_bound_if = 0;
7821 	tcp->tcp_ipv6_recvancillary = 0;
7822 	tcp->tcp_recvifindex = 0;
7823 	tcp->tcp_recvhops = 0;
7824 	tcp->tcp_closed = 0;
7825 	tcp->tcp_cleandeathtag = 0;
7826 	if (tcp->tcp_hopopts != NULL) {
7827 		mi_free(tcp->tcp_hopopts);
7828 		tcp->tcp_hopopts = NULL;
7829 		tcp->tcp_hopoptslen = 0;
7830 	}
7831 	ASSERT(tcp->tcp_hopoptslen == 0);
7832 	if (tcp->tcp_dstopts != NULL) {
7833 		mi_free(tcp->tcp_dstopts);
7834 		tcp->tcp_dstopts = NULL;
7835 		tcp->tcp_dstoptslen = 0;
7836 	}
7837 	ASSERT(tcp->tcp_dstoptslen == 0);
7838 	if (tcp->tcp_rtdstopts != NULL) {
7839 		mi_free(tcp->tcp_rtdstopts);
7840 		tcp->tcp_rtdstopts = NULL;
7841 		tcp->tcp_rtdstoptslen = 0;
7842 	}
7843 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7844 	if (tcp->tcp_rthdr != NULL) {
7845 		mi_free(tcp->tcp_rthdr);
7846 		tcp->tcp_rthdr = NULL;
7847 		tcp->tcp_rthdrlen = 0;
7848 	}
7849 	ASSERT(tcp->tcp_rthdrlen == 0);
7850 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7851 
7852 	/* Reset fusion-related fields */
7853 	tcp->tcp_fused = B_FALSE;
7854 	tcp->tcp_unfusable = B_FALSE;
7855 	tcp->tcp_fused_sigurg = B_FALSE;
7856 	tcp->tcp_direct_sockfs = B_FALSE;
7857 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7858 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7859 	tcp->tcp_loopback_peer = NULL;
7860 	tcp->tcp_fuse_rcv_hiwater = 0;
7861 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7862 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7863 
7864 	tcp->tcp_lso = B_FALSE;
7865 
7866 	tcp->tcp_in_ack_unsent = 0;
7867 	tcp->tcp_cork = B_FALSE;
7868 	tcp->tcp_tconnind_started = B_FALSE;
7869 
7870 	PRESERVE(tcp->tcp_squeue_bytes);
7871 
7872 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7873 	ASSERT(!tcp->tcp_kssl_pending);
7874 	PRESERVE(tcp->tcp_kssl_ent);
7875 
7876 	/* Sodirect */
7877 	tcp->tcp_sodirect = NULL;
7878 
7879 	tcp->tcp_closemp_used = B_FALSE;
7880 
7881 	PRESERVE(tcp->tcp_rsrv_mp);
7882 	PRESERVE(tcp->tcp_rsrv_mp_lock);
7883 
7884 #ifdef DEBUG
7885 	DONTCARE(tcp->tcmp_stk[0]);
7886 #endif
7887 
7888 	PRESERVE(tcp->tcp_connid);
7889 
7890 
7891 #undef	DONTCARE
7892 #undef	PRESERVE
7893 }
7894 
7895 /*
7896  * Allocate necessary resources and initialize state vector.
7897  * Guaranteed not to fail so that when an error is returned,
7898  * the caller doesn't need to do any additional cleanup.
7899  */
7900 int
7901 tcp_init(tcp_t *tcp, queue_t *q)
7902 {
7903 	int	err;
7904 
7905 	tcp->tcp_rq = q;
7906 	tcp->tcp_wq = WR(q);
7907 	tcp->tcp_state = TCPS_IDLE;
7908 	if ((err = tcp_init_values(tcp)) != 0)
7909 		tcp_timers_stop(tcp);
7910 	return (err);
7911 }
7912 
7913 static int
7914 tcp_init_values(tcp_t *tcp)
7915 {
7916 	int	err;
7917 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7918 
7919 	ASSERT((tcp->tcp_family == AF_INET &&
7920 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7921 	    (tcp->tcp_family == AF_INET6 &&
7922 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7923 	    tcp->tcp_ipversion == IPV6_VERSION)));
7924 
7925 	/*
7926 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7927 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7928 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7929 	 * during first few transmissions of a connection as seen in slow
7930 	 * links.
7931 	 */
7932 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
7933 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
7934 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7935 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7936 	    tcps->tcps_conn_grace_period;
7937 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
7938 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
7939 	tcp->tcp_timer_backoff = 0;
7940 	tcp->tcp_ms_we_have_waited = 0;
7941 	tcp->tcp_last_recv_time = lbolt;
7942 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
7943 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7944 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7945 
7946 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
7947 
7948 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
7949 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
7950 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
7951 	/*
7952 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7953 	 * passive open.
7954 	 */
7955 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
7956 
7957 	tcp->tcp_naglim = tcps->tcps_naglim_def;
7958 
7959 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7960 
7961 	tcp->tcp_mdt_hdr_head = 0;
7962 	tcp->tcp_mdt_hdr_tail = 0;
7963 
7964 	/* Reset fusion-related fields */
7965 	tcp->tcp_fused = B_FALSE;
7966 	tcp->tcp_unfusable = B_FALSE;
7967 	tcp->tcp_fused_sigurg = B_FALSE;
7968 	tcp->tcp_direct_sockfs = B_FALSE;
7969 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7970 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7971 	tcp->tcp_loopback_peer = NULL;
7972 	tcp->tcp_fuse_rcv_hiwater = 0;
7973 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7974 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7975 
7976 	/* Sodirect */
7977 	tcp->tcp_sodirect = NULL;
7978 
7979 	/* Initialize the header template */
7980 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7981 		err = tcp_header_init_ipv4(tcp);
7982 	} else {
7983 		err = tcp_header_init_ipv6(tcp);
7984 	}
7985 	if (err)
7986 		return (err);
7987 
7988 	/*
7989 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7990 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7991 	 */
7992 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7993 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
7994 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
7995 
7996 	tcp->tcp_cork = B_FALSE;
7997 	/*
7998 	 * Init the tcp_debug option.  This value determines whether TCP
7999 	 * calls strlog() to print out debug messages.  Doing this
8000 	 * initialization here means that this value is not inherited thru
8001 	 * tcp_reinit().
8002 	 */
8003 	tcp->tcp_debug = tcps->tcps_dbg;
8004 
8005 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8006 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8007 
8008 	return (0);
8009 }
8010 
8011 /*
8012  * Initialize the IPv4 header. Loses any record of any IP options.
8013  */
8014 static int
8015 tcp_header_init_ipv4(tcp_t *tcp)
8016 {
8017 	tcph_t		*tcph;
8018 	uint32_t	sum;
8019 	conn_t		*connp;
8020 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8021 
8022 	/*
8023 	 * This is a simple initialization. If there's
8024 	 * already a template, it should never be too small,
8025 	 * so reuse it.  Otherwise, allocate space for the new one.
8026 	 */
8027 	if (tcp->tcp_iphc == NULL) {
8028 		ASSERT(tcp->tcp_iphc_len == 0);
8029 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8030 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8031 		if (tcp->tcp_iphc == NULL) {
8032 			tcp->tcp_iphc_len = 0;
8033 			return (ENOMEM);
8034 		}
8035 	}
8036 
8037 	/* options are gone; may need a new label */
8038 	connp = tcp->tcp_connp;
8039 	connp->conn_mlp_type = mlptSingle;
8040 	connp->conn_ulp_labeled = !is_system_labeled();
8041 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8042 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8043 	tcp->tcp_ip6h = NULL;
8044 	tcp->tcp_ipversion = IPV4_VERSION;
8045 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8046 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8047 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8048 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8049 	tcp->tcp_ipha->ipha_version_and_hdr_length
8050 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8051 	tcp->tcp_ipha->ipha_ident = 0;
8052 
8053 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8054 	tcp->tcp_tos = 0;
8055 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8056 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8057 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8058 
8059 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8060 	tcp->tcp_tcph = tcph;
8061 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8062 	/*
8063 	 * IP wants our header length in the checksum field to
8064 	 * allow it to perform a single pseudo-header+checksum
8065 	 * calculation on behalf of TCP.
8066 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8067 	 */
8068 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8069 	sum = (sum >> 16) + (sum & 0xFFFF);
8070 	U16_TO_ABE16(sum, tcph->th_sum);
8071 	return (0);
8072 }
8073 
8074 /*
8075  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8076  */
8077 static int
8078 tcp_header_init_ipv6(tcp_t *tcp)
8079 {
8080 	tcph_t	*tcph;
8081 	uint32_t	sum;
8082 	conn_t	*connp;
8083 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8084 
8085 	/*
8086 	 * This is a simple initialization. If there's
8087 	 * already a template, it should never be too small,
8088 	 * so reuse it. Otherwise, allocate space for the new one.
8089 	 * Ensure that there is enough space to "downgrade" the tcp_t
8090 	 * to an IPv4 tcp_t. This requires having space for a full load
8091 	 * of IPv4 options, as well as a full load of TCP options
8092 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8093 	 * than a v6 header and a TCP header with a full load of TCP options
8094 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8095 	 * We want to avoid reallocation in the "downgraded" case when
8096 	 * processing outbound IPv4 options.
8097 	 */
8098 	if (tcp->tcp_iphc == NULL) {
8099 		ASSERT(tcp->tcp_iphc_len == 0);
8100 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8101 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8102 		if (tcp->tcp_iphc == NULL) {
8103 			tcp->tcp_iphc_len = 0;
8104 			return (ENOMEM);
8105 		}
8106 	}
8107 
8108 	/* options are gone; may need a new label */
8109 	connp = tcp->tcp_connp;
8110 	connp->conn_mlp_type = mlptSingle;
8111 	connp->conn_ulp_labeled = !is_system_labeled();
8112 
8113 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8114 	tcp->tcp_ipversion = IPV6_VERSION;
8115 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8116 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8117 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8118 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8119 	tcp->tcp_ipha = NULL;
8120 
8121 	/* Initialize the header template */
8122 
8123 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8124 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8125 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8126 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8127 
8128 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8129 	tcp->tcp_tcph = tcph;
8130 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8131 	/*
8132 	 * IP wants our header length in the checksum field to
8133 	 * allow it to perform a single psuedo-header+checksum
8134 	 * calculation on behalf of TCP.
8135 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8136 	 */
8137 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8138 	sum = (sum >> 16) + (sum & 0xFFFF);
8139 	U16_TO_ABE16(sum, tcph->th_sum);
8140 	return (0);
8141 }
8142 
8143 /* At minimum we need 8 bytes in the TCP header for the lookup */
8144 #define	ICMP_MIN_TCP_HDR	8
8145 
8146 /*
8147  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8148  * passed up by IP. The message is always received on the correct tcp_t.
8149  * Assumes that IP has pulled up everything up to and including the ICMP header.
8150  */
8151 void
8152 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8153 {
8154 	icmph_t *icmph;
8155 	ipha_t	*ipha;
8156 	int	iph_hdr_length;
8157 	tcph_t	*tcph;
8158 	boolean_t ipsec_mctl = B_FALSE;
8159 	boolean_t secure;
8160 	mblk_t *first_mp = mp;
8161 	int32_t new_mss;
8162 	uint32_t ratio;
8163 	size_t mp_size = MBLKL(mp);
8164 	uint32_t seg_seq;
8165 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8166 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8167 
8168 	/* Assume IP provides aligned packets - otherwise toss */
8169 	if (!OK_32PTR(mp->b_rptr)) {
8170 		freemsg(mp);
8171 		return;
8172 	}
8173 
8174 	/*
8175 	 * Since ICMP errors are normal data marked with M_CTL when sent
8176 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8177 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8178 	 */
8179 	if ((mp_size == sizeof (ipsec_info_t)) &&
8180 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8181 		ASSERT(mp->b_cont != NULL);
8182 		mp = mp->b_cont;
8183 		/* IP should have done this */
8184 		ASSERT(OK_32PTR(mp->b_rptr));
8185 		mp_size = MBLKL(mp);
8186 		ipsec_mctl = B_TRUE;
8187 	}
8188 
8189 	/*
8190 	 * Verify that we have a complete outer IP header. If not, drop it.
8191 	 */
8192 	if (mp_size < sizeof (ipha_t)) {
8193 noticmpv4:
8194 		freemsg(first_mp);
8195 		return;
8196 	}
8197 
8198 	ipha = (ipha_t *)mp->b_rptr;
8199 	/*
8200 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8201 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8202 	 */
8203 	switch (IPH_HDR_VERSION(ipha)) {
8204 	case IPV6_VERSION:
8205 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8206 		return;
8207 	case IPV4_VERSION:
8208 		break;
8209 	default:
8210 		goto noticmpv4;
8211 	}
8212 
8213 	/* Skip past the outer IP and ICMP headers */
8214 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8215 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8216 	/*
8217 	 * If we don't have the correct outer IP header length or if the ULP
8218 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8219 	 * send it upstream.
8220 	 */
8221 	if (iph_hdr_length < sizeof (ipha_t) ||
8222 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8223 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8224 		goto noticmpv4;
8225 	}
8226 	ipha = (ipha_t *)&icmph[1];
8227 
8228 	/* Skip past the inner IP and find the ULP header */
8229 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8230 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8231 	/*
8232 	 * If we don't have the correct inner IP header length or if the ULP
8233 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8234 	 * bytes of TCP header, drop it.
8235 	 */
8236 	if (iph_hdr_length < sizeof (ipha_t) ||
8237 	    ipha->ipha_protocol != IPPROTO_TCP ||
8238 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8239 		goto noticmpv4;
8240 	}
8241 
8242 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8243 		if (ipsec_mctl) {
8244 			secure = ipsec_in_is_secure(first_mp);
8245 		} else {
8246 			secure = B_FALSE;
8247 		}
8248 		if (secure) {
8249 			/*
8250 			 * If we are willing to accept this in clear
8251 			 * we don't have to verify policy.
8252 			 */
8253 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8254 				if (!tcp_check_policy(tcp, first_mp,
8255 				    ipha, NULL, secure, ipsec_mctl)) {
8256 					/*
8257 					 * tcp_check_policy called
8258 					 * ip_drop_packet() on failure.
8259 					 */
8260 					return;
8261 				}
8262 			}
8263 		}
8264 	} else if (ipsec_mctl) {
8265 		/*
8266 		 * This is a hard_bound connection. IP has already
8267 		 * verified policy. We don't have to do it again.
8268 		 */
8269 		freeb(first_mp);
8270 		first_mp = mp;
8271 		ipsec_mctl = B_FALSE;
8272 	}
8273 
8274 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8275 	/*
8276 	 * TCP SHOULD check that the TCP sequence number contained in
8277 	 * payload of the ICMP error message is within the range
8278 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8279 	 */
8280 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8281 		/*
8282 		 * The ICMP message is bogus, just drop it.  But if this is
8283 		 * an ICMP too big message, IP has already changed
8284 		 * the ire_max_frag to the bogus value.  We need to change
8285 		 * it back.
8286 		 */
8287 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8288 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8289 			conn_t *connp = tcp->tcp_connp;
8290 			ire_t *ire;
8291 			int flag;
8292 
8293 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8294 				flag = tcp->tcp_ipha->
8295 				    ipha_fragment_offset_and_flags;
8296 			} else {
8297 				flag = 0;
8298 			}
8299 			mutex_enter(&connp->conn_lock);
8300 			if ((ire = connp->conn_ire_cache) != NULL) {
8301 				mutex_enter(&ire->ire_lock);
8302 				mutex_exit(&connp->conn_lock);
8303 				ire->ire_max_frag = tcp->tcp_if_mtu;
8304 				ire->ire_frag_flag |= flag;
8305 				mutex_exit(&ire->ire_lock);
8306 			} else {
8307 				mutex_exit(&connp->conn_lock);
8308 			}
8309 		}
8310 		goto noticmpv4;
8311 	}
8312 
8313 	switch (icmph->icmph_type) {
8314 	case ICMP_DEST_UNREACHABLE:
8315 		switch (icmph->icmph_code) {
8316 		case ICMP_FRAGMENTATION_NEEDED:
8317 			/*
8318 			 * Reduce the MSS based on the new MTU.  This will
8319 			 * eliminate any fragmentation locally.
8320 			 * N.B.  There may well be some funny side-effects on
8321 			 * the local send policy and the remote receive policy.
8322 			 * Pending further research, we provide
8323 			 * tcp_ignore_path_mtu just in case this proves
8324 			 * disastrous somewhere.
8325 			 *
8326 			 * After updating the MSS, retransmit part of the
8327 			 * dropped segment using the new mss by calling
8328 			 * tcp_wput_data().  Need to adjust all those
8329 			 * params to make sure tcp_wput_data() work properly.
8330 			 */
8331 			if (tcps->tcps_ignore_path_mtu ||
8332 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8333 				break;
8334 
8335 			/*
8336 			 * Decrease the MSS by time stamp options
8337 			 * IP options and IPSEC options. tcp_hdr_len
8338 			 * includes time stamp option and IP option
8339 			 * length.  Note that new_mss may be negative
8340 			 * if tcp_ipsec_overhead is large and the
8341 			 * icmph_du_mtu is the minimum value, which is 68.
8342 			 */
8343 			new_mss = ntohs(icmph->icmph_du_mtu) -
8344 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8345 
8346 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8347 			    new_mss);
8348 
8349 			/*
8350 			 * Only update the MSS if the new one is
8351 			 * smaller than the previous one.  This is
8352 			 * to avoid problems when getting multiple
8353 			 * ICMP errors for the same MTU.
8354 			 */
8355 			if (new_mss >= tcp->tcp_mss)
8356 				break;
8357 
8358 			/*
8359 			 * Note that we are using the template header's DF
8360 			 * bit in the fast path sending.  So we need to compare
8361 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8362 			 * And stop doing IPv4 PMTUd if new_mss is less than
8363 			 * MAX(tcps_mss_min, ip_pmtu_min).
8364 			 */
8365 			if (new_mss < tcps->tcps_mss_min ||
8366 			    new_mss < ipst->ips_ip_pmtu_min) {
8367 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8368 				    0;
8369 			}
8370 
8371 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8372 			ASSERT(ratio >= 1);
8373 			tcp_mss_set(tcp, new_mss, B_TRUE);
8374 
8375 			/*
8376 			 * Make sure we have something to
8377 			 * send.
8378 			 */
8379 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8380 			    (tcp->tcp_xmit_head != NULL)) {
8381 				/*
8382 				 * Shrink tcp_cwnd in
8383 				 * proportion to the old MSS/new MSS.
8384 				 */
8385 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8386 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8387 				    (tcp->tcp_unsent == 0)) {
8388 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8389 				} else {
8390 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8391 				}
8392 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8393 				tcp->tcp_rexmit = B_TRUE;
8394 				tcp->tcp_dupack_cnt = 0;
8395 				tcp->tcp_snd_burst = TCP_CWND_SS;
8396 				tcp_ss_rexmit(tcp);
8397 			}
8398 			break;
8399 		case ICMP_PORT_UNREACHABLE:
8400 		case ICMP_PROTOCOL_UNREACHABLE:
8401 			switch (tcp->tcp_state) {
8402 			case TCPS_SYN_SENT:
8403 			case TCPS_SYN_RCVD:
8404 				/*
8405 				 * ICMP can snipe away incipient
8406 				 * TCP connections as long as
8407 				 * seq number is same as initial
8408 				 * send seq number.
8409 				 */
8410 				if (seg_seq == tcp->tcp_iss) {
8411 					(void) tcp_clean_death(tcp,
8412 					    ECONNREFUSED, 6);
8413 				}
8414 				break;
8415 			}
8416 			break;
8417 		case ICMP_HOST_UNREACHABLE:
8418 		case ICMP_NET_UNREACHABLE:
8419 			/* Record the error in case we finally time out. */
8420 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8421 				tcp->tcp_client_errno = EHOSTUNREACH;
8422 			else
8423 				tcp->tcp_client_errno = ENETUNREACH;
8424 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8425 				if (tcp->tcp_listener != NULL &&
8426 				    tcp->tcp_listener->tcp_syn_defense) {
8427 					/*
8428 					 * Ditch the half-open connection if we
8429 					 * suspect a SYN attack is under way.
8430 					 */
8431 					tcp_ip_ire_mark_advice(tcp);
8432 					(void) tcp_clean_death(tcp,
8433 					    tcp->tcp_client_errno, 7);
8434 				}
8435 			}
8436 			break;
8437 		default:
8438 			break;
8439 		}
8440 		break;
8441 	case ICMP_SOURCE_QUENCH: {
8442 		/*
8443 		 * use a global boolean to control
8444 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8445 		 * The default is false.
8446 		 */
8447 		if (tcp_icmp_source_quench) {
8448 			/*
8449 			 * Reduce the sending rate as if we got a
8450 			 * retransmit timeout
8451 			 */
8452 			uint32_t npkt;
8453 
8454 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8455 			    tcp->tcp_mss;
8456 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8457 			tcp->tcp_cwnd = tcp->tcp_mss;
8458 			tcp->tcp_cwnd_cnt = 0;
8459 		}
8460 		break;
8461 	}
8462 	}
8463 	freemsg(first_mp);
8464 }
8465 
8466 /*
8467  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8468  * error messages passed up by IP.
8469  * Assumes that IP has pulled up all the extension headers as well
8470  * as the ICMPv6 header.
8471  */
8472 static void
8473 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8474 {
8475 	icmp6_t *icmp6;
8476 	ip6_t	*ip6h;
8477 	uint16_t	iph_hdr_length;
8478 	tcpha_t	*tcpha;
8479 	uint8_t	*nexthdrp;
8480 	uint32_t new_mss;
8481 	uint32_t ratio;
8482 	boolean_t secure;
8483 	mblk_t *first_mp = mp;
8484 	size_t mp_size;
8485 	uint32_t seg_seq;
8486 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8487 
8488 	/*
8489 	 * The caller has determined if this is an IPSEC_IN packet and
8490 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8491 	 */
8492 	if (ipsec_mctl)
8493 		mp = mp->b_cont;
8494 
8495 	mp_size = MBLKL(mp);
8496 
8497 	/*
8498 	 * Verify that we have a complete IP header. If not, send it upstream.
8499 	 */
8500 	if (mp_size < sizeof (ip6_t)) {
8501 noticmpv6:
8502 		freemsg(first_mp);
8503 		return;
8504 	}
8505 
8506 	/*
8507 	 * Verify this is an ICMPV6 packet, else send it upstream.
8508 	 */
8509 	ip6h = (ip6_t *)mp->b_rptr;
8510 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8511 		iph_hdr_length = IPV6_HDR_LEN;
8512 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8513 	    &nexthdrp) ||
8514 	    *nexthdrp != IPPROTO_ICMPV6) {
8515 		goto noticmpv6;
8516 	}
8517 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8518 	ip6h = (ip6_t *)&icmp6[1];
8519 	/*
8520 	 * Verify if we have a complete ICMP and inner IP header.
8521 	 */
8522 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8523 		goto noticmpv6;
8524 
8525 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8526 		goto noticmpv6;
8527 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8528 	/*
8529 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8530 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8531 	 * packet.
8532 	 */
8533 	if ((*nexthdrp != IPPROTO_TCP) ||
8534 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8535 		goto noticmpv6;
8536 	}
8537 
8538 	/*
8539 	 * ICMP errors come on the right queue or come on
8540 	 * listener/global queue for detached connections and
8541 	 * get switched to the right queue. If it comes on the
8542 	 * right queue, policy check has already been done by IP
8543 	 * and thus free the first_mp without verifying the policy.
8544 	 * If it has come for a non-hard bound connection, we need
8545 	 * to verify policy as IP may not have done it.
8546 	 */
8547 	if (!tcp->tcp_hard_bound) {
8548 		if (ipsec_mctl) {
8549 			secure = ipsec_in_is_secure(first_mp);
8550 		} else {
8551 			secure = B_FALSE;
8552 		}
8553 		if (secure) {
8554 			/*
8555 			 * If we are willing to accept this in clear
8556 			 * we don't have to verify policy.
8557 			 */
8558 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8559 				if (!tcp_check_policy(tcp, first_mp,
8560 				    NULL, ip6h, secure, ipsec_mctl)) {
8561 					/*
8562 					 * tcp_check_policy called
8563 					 * ip_drop_packet() on failure.
8564 					 */
8565 					return;
8566 				}
8567 			}
8568 		}
8569 	} else if (ipsec_mctl) {
8570 		/*
8571 		 * This is a hard_bound connection. IP has already
8572 		 * verified policy. We don't have to do it again.
8573 		 */
8574 		freeb(first_mp);
8575 		first_mp = mp;
8576 		ipsec_mctl = B_FALSE;
8577 	}
8578 
8579 	seg_seq = ntohl(tcpha->tha_seq);
8580 	/*
8581 	 * TCP SHOULD check that the TCP sequence number contained in
8582 	 * payload of the ICMP error message is within the range
8583 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8584 	 */
8585 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8586 		/*
8587 		 * If the ICMP message is bogus, should we kill the
8588 		 * connection, or should we just drop the bogus ICMP
8589 		 * message? It would probably make more sense to just
8590 		 * drop the message so that if this one managed to get
8591 		 * in, the real connection should not suffer.
8592 		 */
8593 		goto noticmpv6;
8594 	}
8595 
8596 	switch (icmp6->icmp6_type) {
8597 	case ICMP6_PACKET_TOO_BIG:
8598 		/*
8599 		 * Reduce the MSS based on the new MTU.  This will
8600 		 * eliminate any fragmentation locally.
8601 		 * N.B.  There may well be some funny side-effects on
8602 		 * the local send policy and the remote receive policy.
8603 		 * Pending further research, we provide
8604 		 * tcp_ignore_path_mtu just in case this proves
8605 		 * disastrous somewhere.
8606 		 *
8607 		 * After updating the MSS, retransmit part of the
8608 		 * dropped segment using the new mss by calling
8609 		 * tcp_wput_data().  Need to adjust all those
8610 		 * params to make sure tcp_wput_data() work properly.
8611 		 */
8612 		if (tcps->tcps_ignore_path_mtu)
8613 			break;
8614 
8615 		/*
8616 		 * Decrease the MSS by time stamp options
8617 		 * IP options and IPSEC options. tcp_hdr_len
8618 		 * includes time stamp option and IP option
8619 		 * length.
8620 		 */
8621 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8622 		    tcp->tcp_ipsec_overhead;
8623 
8624 		/*
8625 		 * Only update the MSS if the new one is
8626 		 * smaller than the previous one.  This is
8627 		 * to avoid problems when getting multiple
8628 		 * ICMP errors for the same MTU.
8629 		 */
8630 		if (new_mss >= tcp->tcp_mss)
8631 			break;
8632 
8633 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8634 		ASSERT(ratio >= 1);
8635 		tcp_mss_set(tcp, new_mss, B_TRUE);
8636 
8637 		/*
8638 		 * Make sure we have something to
8639 		 * send.
8640 		 */
8641 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8642 		    (tcp->tcp_xmit_head != NULL)) {
8643 			/*
8644 			 * Shrink tcp_cwnd in
8645 			 * proportion to the old MSS/new MSS.
8646 			 */
8647 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8648 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8649 			    (tcp->tcp_unsent == 0)) {
8650 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8651 			} else {
8652 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8653 			}
8654 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8655 			tcp->tcp_rexmit = B_TRUE;
8656 			tcp->tcp_dupack_cnt = 0;
8657 			tcp->tcp_snd_burst = TCP_CWND_SS;
8658 			tcp_ss_rexmit(tcp);
8659 		}
8660 		break;
8661 
8662 	case ICMP6_DST_UNREACH:
8663 		switch (icmp6->icmp6_code) {
8664 		case ICMP6_DST_UNREACH_NOPORT:
8665 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8666 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8667 			    (seg_seq == tcp->tcp_iss)) {
8668 				(void) tcp_clean_death(tcp,
8669 				    ECONNREFUSED, 8);
8670 			}
8671 			break;
8672 
8673 		case ICMP6_DST_UNREACH_ADMIN:
8674 		case ICMP6_DST_UNREACH_NOROUTE:
8675 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8676 		case ICMP6_DST_UNREACH_ADDR:
8677 			/* Record the error in case we finally time out. */
8678 			tcp->tcp_client_errno = EHOSTUNREACH;
8679 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8680 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8681 			    (seg_seq == tcp->tcp_iss)) {
8682 				if (tcp->tcp_listener != NULL &&
8683 				    tcp->tcp_listener->tcp_syn_defense) {
8684 					/*
8685 					 * Ditch the half-open connection if we
8686 					 * suspect a SYN attack is under way.
8687 					 */
8688 					tcp_ip_ire_mark_advice(tcp);
8689 					(void) tcp_clean_death(tcp,
8690 					    tcp->tcp_client_errno, 9);
8691 				}
8692 			}
8693 
8694 
8695 			break;
8696 		default:
8697 			break;
8698 		}
8699 		break;
8700 
8701 	case ICMP6_PARAM_PROB:
8702 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8703 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8704 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8705 		    (uchar_t *)nexthdrp) {
8706 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8707 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8708 				(void) tcp_clean_death(tcp,
8709 				    ECONNREFUSED, 10);
8710 			}
8711 			break;
8712 		}
8713 		break;
8714 
8715 	case ICMP6_TIME_EXCEEDED:
8716 	default:
8717 		break;
8718 	}
8719 	freemsg(first_mp);
8720 }
8721 
8722 /*
8723  * Notify IP that we are having trouble with this connection.  IP should
8724  * blow the IRE away and start over.
8725  */
8726 static void
8727 tcp_ip_notify(tcp_t *tcp)
8728 {
8729 	struct iocblk	*iocp;
8730 	ipid_t	*ipid;
8731 	mblk_t	*mp;
8732 
8733 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8734 	if (tcp->tcp_ipversion == IPV6_VERSION)
8735 		return;
8736 
8737 	mp = mkiocb(IP_IOCTL);
8738 	if (mp == NULL)
8739 		return;
8740 
8741 	iocp = (struct iocblk *)mp->b_rptr;
8742 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8743 
8744 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8745 	if (!mp->b_cont) {
8746 		freeb(mp);
8747 		return;
8748 	}
8749 
8750 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8751 	mp->b_cont->b_wptr += iocp->ioc_count;
8752 	bzero(ipid, sizeof (*ipid));
8753 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8754 	ipid->ipid_ire_type = IRE_CACHE;
8755 	ipid->ipid_addr_offset = sizeof (ipid_t);
8756 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8757 	/*
8758 	 * Note: in the case of source routing we want to blow away the
8759 	 * route to the first source route hop.
8760 	 */
8761 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8762 	    sizeof (tcp->tcp_ipha->ipha_dst));
8763 
8764 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8765 }
8766 
8767 /* Unlink and return any mblk that looks like it contains an ire */
8768 static mblk_t *
8769 tcp_ire_mp(mblk_t **mpp)
8770 {
8771 	mblk_t 	*mp = *mpp;
8772 	mblk_t	*prev_mp = NULL;
8773 
8774 	for (;;) {
8775 		switch (DB_TYPE(mp)) {
8776 		case IRE_DB_TYPE:
8777 		case IRE_DB_REQ_TYPE:
8778 			if (mp == *mpp) {
8779 				*mpp = mp->b_cont;
8780 			} else {
8781 				prev_mp->b_cont = mp->b_cont;
8782 			}
8783 			mp->b_cont = NULL;
8784 			return (mp);
8785 		default:
8786 			break;
8787 		}
8788 		prev_mp = mp;
8789 		mp = mp->b_cont;
8790 		if (mp == NULL)
8791 			break;
8792 	}
8793 	return (mp);
8794 }
8795 
8796 /*
8797  * Timer callback routine for keepalive probe.  We do a fake resend of
8798  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8799  * check to see if we have heard anything from the other end for the last
8800  * RTO period.  If we have, set the timer to expire for another
8801  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8802  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8803  * the timeout if we have not heard from the other side.  If for more than
8804  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8805  * kill the connection unless the keepalive abort threshold is 0.  In
8806  * that case, we will probe "forever."
8807  */
8808 static void
8809 tcp_keepalive_killer(void *arg)
8810 {
8811 	mblk_t	*mp;
8812 	conn_t	*connp = (conn_t *)arg;
8813 	tcp_t  	*tcp = connp->conn_tcp;
8814 	int32_t	firetime;
8815 	int32_t	idletime;
8816 	int32_t	ka_intrvl;
8817 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8818 
8819 	tcp->tcp_ka_tid = 0;
8820 
8821 	if (tcp->tcp_fused)
8822 		return;
8823 
8824 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
8825 	ka_intrvl = tcp->tcp_ka_interval;
8826 
8827 	/*
8828 	 * Keepalive probe should only be sent if the application has not
8829 	 * done a close on the connection.
8830 	 */
8831 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8832 		return;
8833 	}
8834 	/* Timer fired too early, restart it. */
8835 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8836 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8837 		    MSEC_TO_TICK(ka_intrvl));
8838 		return;
8839 	}
8840 
8841 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8842 	/*
8843 	 * If we have not heard from the other side for a long
8844 	 * time, kill the connection unless the keepalive abort
8845 	 * threshold is 0.  In that case, we will probe "forever."
8846 	 */
8847 	if (tcp->tcp_ka_abort_thres != 0 &&
8848 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8849 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
8850 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8851 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8852 		return;
8853 	}
8854 
8855 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8856 	    idletime >= ka_intrvl) {
8857 		/* Fake resend of last ACKed byte. */
8858 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8859 
8860 		if (mp1 != NULL) {
8861 			*mp1->b_wptr++ = '\0';
8862 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8863 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8864 			freeb(mp1);
8865 			/*
8866 			 * if allocation failed, fall through to start the
8867 			 * timer back.
8868 			 */
8869 			if (mp != NULL) {
8870 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8871 				BUMP_MIB(&tcps->tcps_mib,
8872 				    tcpTimKeepaliveProbe);
8873 				if (tcp->tcp_ka_last_intrvl != 0) {
8874 					int max;
8875 					/*
8876 					 * We should probe again at least
8877 					 * in ka_intrvl, but not more than
8878 					 * tcp_rexmit_interval_max.
8879 					 */
8880 					max = tcps->tcps_rexmit_interval_max;
8881 					firetime = MIN(ka_intrvl - 1,
8882 					    tcp->tcp_ka_last_intrvl << 1);
8883 					if (firetime > max)
8884 						firetime = max;
8885 				} else {
8886 					firetime = tcp->tcp_rto;
8887 				}
8888 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8889 				    tcp_keepalive_killer,
8890 				    MSEC_TO_TICK(firetime));
8891 				tcp->tcp_ka_last_intrvl = firetime;
8892 				return;
8893 			}
8894 		}
8895 	} else {
8896 		tcp->tcp_ka_last_intrvl = 0;
8897 	}
8898 
8899 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8900 	if ((firetime = ka_intrvl - idletime) < 0) {
8901 		firetime = ka_intrvl;
8902 	}
8903 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8904 	    MSEC_TO_TICK(firetime));
8905 }
8906 
8907 int
8908 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8909 {
8910 	queue_t	*q = tcp->tcp_rq;
8911 	int32_t	mss = tcp->tcp_mss;
8912 	int	maxpsz;
8913 	conn_t	*connp = tcp->tcp_connp;
8914 
8915 	if (TCP_IS_DETACHED(tcp))
8916 		return (mss);
8917 	if (tcp->tcp_fused) {
8918 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8919 		mss = INFPSZ;
8920 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
8921 		/*
8922 		 * Set the sd_qn_maxpsz according to the socket send buffer
8923 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8924 		 * instruct the stream head to copyin user data into contiguous
8925 		 * kernel-allocated buffers without breaking it up into smaller
8926 		 * chunks.  We round up the buffer size to the nearest SMSS.
8927 		 */
8928 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8929 		if (tcp->tcp_kssl_ctx == NULL)
8930 			mss = INFPSZ;
8931 		else
8932 			mss = SSL3_MAX_RECORD_LEN;
8933 	} else {
8934 		/*
8935 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8936 		 * (and a multiple of the mss).  This instructs the stream
8937 		 * head to break down larger than SMSS writes into SMSS-
8938 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8939 		 */
8940 		/* XXX tune this with ndd tcp_maxpsz_multiplier */
8941 		maxpsz = tcp->tcp_maxpsz * mss;
8942 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8943 			maxpsz = tcp->tcp_xmit_hiwater/2;
8944 			/* Round up to nearest mss */
8945 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8946 		}
8947 	}
8948 
8949 	(void) proto_set_maxpsz(q, connp, maxpsz);
8950 	if (!(IPCL_IS_NONSTR(connp))) {
8951 		/* XXX do it in set_maxpsz()? */
8952 		tcp->tcp_wq->q_maxpsz = maxpsz;
8953 	}
8954 
8955 	if (set_maxblk)
8956 		(void) proto_set_tx_maxblk(q, connp, mss);
8957 	return (mss);
8958 }
8959 
8960 /*
8961  * Extract option values from a tcp header.  We put any found values into the
8962  * tcpopt struct and return a bitmask saying which options were found.
8963  */
8964 static int
8965 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8966 {
8967 	uchar_t		*endp;
8968 	int		len;
8969 	uint32_t	mss;
8970 	uchar_t		*up = (uchar_t *)tcph;
8971 	int		found = 0;
8972 	int32_t		sack_len;
8973 	tcp_seq		sack_begin, sack_end;
8974 	tcp_t		*tcp;
8975 
8976 	endp = up + TCP_HDR_LENGTH(tcph);
8977 	up += TCP_MIN_HEADER_LENGTH;
8978 	while (up < endp) {
8979 		len = endp - up;
8980 		switch (*up) {
8981 		case TCPOPT_EOL:
8982 			break;
8983 
8984 		case TCPOPT_NOP:
8985 			up++;
8986 			continue;
8987 
8988 		case TCPOPT_MAXSEG:
8989 			if (len < TCPOPT_MAXSEG_LEN ||
8990 			    up[1] != TCPOPT_MAXSEG_LEN)
8991 				break;
8992 
8993 			mss = BE16_TO_U16(up+2);
8994 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
8995 			tcpopt->tcp_opt_mss = mss;
8996 			found |= TCP_OPT_MSS_PRESENT;
8997 
8998 			up += TCPOPT_MAXSEG_LEN;
8999 			continue;
9000 
9001 		case TCPOPT_WSCALE:
9002 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9003 				break;
9004 
9005 			if (up[2] > TCP_MAX_WINSHIFT)
9006 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9007 			else
9008 				tcpopt->tcp_opt_wscale = up[2];
9009 			found |= TCP_OPT_WSCALE_PRESENT;
9010 
9011 			up += TCPOPT_WS_LEN;
9012 			continue;
9013 
9014 		case TCPOPT_SACK_PERMITTED:
9015 			if (len < TCPOPT_SACK_OK_LEN ||
9016 			    up[1] != TCPOPT_SACK_OK_LEN)
9017 				break;
9018 			found |= TCP_OPT_SACK_OK_PRESENT;
9019 			up += TCPOPT_SACK_OK_LEN;
9020 			continue;
9021 
9022 		case TCPOPT_SACK:
9023 			if (len <= 2 || up[1] <= 2 || len < up[1])
9024 				break;
9025 
9026 			/* If TCP is not interested in SACK blks... */
9027 			if ((tcp = tcpopt->tcp) == NULL) {
9028 				up += up[1];
9029 				continue;
9030 			}
9031 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9032 			up += TCPOPT_HEADER_LEN;
9033 
9034 			/*
9035 			 * If the list is empty, allocate one and assume
9036 			 * nothing is sack'ed.
9037 			 */
9038 			ASSERT(tcp->tcp_sack_info != NULL);
9039 			if (tcp->tcp_notsack_list == NULL) {
9040 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9041 				    tcp->tcp_suna, tcp->tcp_snxt,
9042 				    &(tcp->tcp_num_notsack_blk),
9043 				    &(tcp->tcp_cnt_notsack_list));
9044 
9045 				/*
9046 				 * Make sure tcp_notsack_list is not NULL.
9047 				 * This happens when kmem_alloc(KM_NOSLEEP)
9048 				 * returns NULL.
9049 				 */
9050 				if (tcp->tcp_notsack_list == NULL) {
9051 					up += sack_len;
9052 					continue;
9053 				}
9054 				tcp->tcp_fack = tcp->tcp_suna;
9055 			}
9056 
9057 			while (sack_len > 0) {
9058 				if (up + 8 > endp) {
9059 					up = endp;
9060 					break;
9061 				}
9062 				sack_begin = BE32_TO_U32(up);
9063 				up += 4;
9064 				sack_end = BE32_TO_U32(up);
9065 				up += 4;
9066 				sack_len -= 8;
9067 				/*
9068 				 * Bounds checking.  Make sure the SACK
9069 				 * info is within tcp_suna and tcp_snxt.
9070 				 * If this SACK blk is out of bound, ignore
9071 				 * it but continue to parse the following
9072 				 * blks.
9073 				 */
9074 				if (SEQ_LEQ(sack_end, sack_begin) ||
9075 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9076 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9077 					continue;
9078 				}
9079 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9080 				    sack_begin, sack_end,
9081 				    &(tcp->tcp_num_notsack_blk),
9082 				    &(tcp->tcp_cnt_notsack_list));
9083 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9084 					tcp->tcp_fack = sack_end;
9085 				}
9086 			}
9087 			found |= TCP_OPT_SACK_PRESENT;
9088 			continue;
9089 
9090 		case TCPOPT_TSTAMP:
9091 			if (len < TCPOPT_TSTAMP_LEN ||
9092 			    up[1] != TCPOPT_TSTAMP_LEN)
9093 				break;
9094 
9095 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9096 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9097 
9098 			found |= TCP_OPT_TSTAMP_PRESENT;
9099 
9100 			up += TCPOPT_TSTAMP_LEN;
9101 			continue;
9102 
9103 		default:
9104 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9105 				break;
9106 			up += up[1];
9107 			continue;
9108 		}
9109 		break;
9110 	}
9111 	return (found);
9112 }
9113 
9114 /*
9115  * Set the mss associated with a particular tcp based on its current value,
9116  * and a new one passed in. Observe minimums and maximums, and reset
9117  * other state variables that we want to view as multiples of mss.
9118  *
9119  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9120  * highwater marks etc. need to be initialized or adjusted.
9121  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9122  *    packet arrives.
9123  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9124  *    ICMP6_PACKET_TOO_BIG arrives.
9125  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9126  *    to increase the MSS to use the extra bytes available.
9127  *
9128  * Callers except tcp_paws_check() ensure that they only reduce mss.
9129  */
9130 static void
9131 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9132 {
9133 	uint32_t	mss_max;
9134 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9135 
9136 	if (tcp->tcp_ipversion == IPV4_VERSION)
9137 		mss_max = tcps->tcps_mss_max_ipv4;
9138 	else
9139 		mss_max = tcps->tcps_mss_max_ipv6;
9140 
9141 	if (mss < tcps->tcps_mss_min)
9142 		mss = tcps->tcps_mss_min;
9143 	if (mss > mss_max)
9144 		mss = mss_max;
9145 	/*
9146 	 * Unless naglim has been set by our client to
9147 	 * a non-mss value, force naglim to track mss.
9148 	 * This can help to aggregate small writes.
9149 	 */
9150 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9151 		tcp->tcp_naglim = mss;
9152 	/*
9153 	 * TCP should be able to buffer at least 4 MSS data for obvious
9154 	 * performance reason.
9155 	 */
9156 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9157 		tcp->tcp_xmit_hiwater = mss << 2;
9158 
9159 	if (do_ss) {
9160 		/*
9161 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9162 		 * changing due to a reduction in MTU, presumably as a
9163 		 * result of a new path component, reset cwnd to its
9164 		 * "initial" value, as a multiple of the new mss.
9165 		 */
9166 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9167 	} else {
9168 		/*
9169 		 * Called by tcp_paws_check(), the mss increased
9170 		 * marginally to allow use of space previously taken
9171 		 * by the timestamp option. It would be inappropriate
9172 		 * to apply slow start or tcp_init_cwnd values to
9173 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9174 		 */
9175 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9176 		tcp->tcp_cwnd_cnt = 0;
9177 	}
9178 	tcp->tcp_mss = mss;
9179 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9180 }
9181 
9182 /* For /dev/tcp aka AF_INET open */
9183 static int
9184 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9185 {
9186 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9187 }
9188 
9189 /* For /dev/tcp6 aka AF_INET6 open */
9190 static int
9191 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9192 {
9193 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9194 }
9195 
9196 static conn_t *
9197 tcp_create_common(queue_t *q, cred_t *credp, boolean_t isv6,
9198     boolean_t issocket, int *errorp)
9199 {
9200 	tcp_t		*tcp = NULL;
9201 	conn_t		*connp;
9202 	int		err;
9203 	zoneid_t	zoneid;
9204 	tcp_stack_t	*tcps;
9205 	squeue_t	*sqp;
9206 
9207 	ASSERT(errorp != NULL);
9208 	/*
9209 	 * Find the proper zoneid and netstack.
9210 	 */
9211 	/*
9212 	 * Special case for install: miniroot needs to be able to
9213 	 * access files via NFS as though it were always in the
9214 	 * global zone.
9215 	 */
9216 	if (credp == kcred && nfs_global_client_only != 0) {
9217 		zoneid = GLOBAL_ZONEID;
9218 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9219 		    netstack_tcp;
9220 		ASSERT(tcps != NULL);
9221 	} else {
9222 		netstack_t *ns;
9223 
9224 		ns = netstack_find_by_cred(credp);
9225 		ASSERT(ns != NULL);
9226 		tcps = ns->netstack_tcp;
9227 		ASSERT(tcps != NULL);
9228 
9229 		/*
9230 		 * For exclusive stacks we set the zoneid to zero
9231 		 * to make TCP operate as if in the global zone.
9232 		 */
9233 		if (tcps->tcps_netstack->netstack_stackid !=
9234 		    GLOBAL_NETSTACKID)
9235 			zoneid = GLOBAL_ZONEID;
9236 		else
9237 			zoneid = crgetzoneid(credp);
9238 	}
9239 	/*
9240 	 * For stackid zero this is done from strplumb.c, but
9241 	 * non-zero stackids are handled here.
9242 	 */
9243 	if (tcps->tcps_g_q == NULL &&
9244 	    tcps->tcps_netstack->netstack_stackid !=
9245 	    GLOBAL_NETSTACKID) {
9246 		tcp_g_q_setup(tcps);
9247 	}
9248 
9249 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
9250 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
9251 	/*
9252 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9253 	 * so we drop it by one.
9254 	 */
9255 	netstack_rele(tcps->tcps_netstack);
9256 	if (connp == NULL) {
9257 		*errorp = ENOSR;
9258 		return (NULL);
9259 	}
9260 	connp->conn_sqp = sqp;
9261 	connp->conn_initial_sqp = connp->conn_sqp;
9262 	tcp = connp->conn_tcp;
9263 
9264 	if (isv6) {
9265 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9266 		connp->conn_send = ip_output_v6;
9267 		connp->conn_af_isv6 = B_TRUE;
9268 		connp->conn_pkt_isv6 = B_TRUE;
9269 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9270 		tcp->tcp_ipversion = IPV6_VERSION;
9271 		tcp->tcp_family = AF_INET6;
9272 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9273 	} else {
9274 		connp->conn_flags |= IPCL_TCP4;
9275 		connp->conn_send = ip_output;
9276 		connp->conn_af_isv6 = B_FALSE;
9277 		connp->conn_pkt_isv6 = B_FALSE;
9278 		tcp->tcp_ipversion = IPV4_VERSION;
9279 		tcp->tcp_family = AF_INET;
9280 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9281 	}
9282 
9283 	/*
9284 	 * TCP keeps a copy of cred for cache locality reasons but
9285 	 * we put a reference only once. If connp->conn_cred
9286 	 * becomes invalid, tcp_cred should also be set to NULL.
9287 	 */
9288 	tcp->tcp_cred = connp->conn_cred = credp;
9289 	crhold(connp->conn_cred);
9290 	tcp->tcp_cpid = curproc->p_pid;
9291 	tcp->tcp_open_time = lbolt64;
9292 	connp->conn_zoneid = zoneid;
9293 	connp->conn_mlp_type = mlptSingle;
9294 	connp->conn_ulp_labeled = !is_system_labeled();
9295 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9296 	ASSERT(tcp->tcp_tcps == tcps);
9297 
9298 	/*
9299 	 * If the caller has the process-wide flag set, then default to MAC
9300 	 * exempt mode.  This allows read-down to unlabeled hosts.
9301 	 */
9302 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9303 		connp->conn_mac_exempt = B_TRUE;
9304 
9305 	connp->conn_dev = NULL;
9306 	if (issocket) {
9307 		connp->conn_flags |= IPCL_SOCKET;
9308 		tcp->tcp_issocket = 1;
9309 	}
9310 
9311 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
9312 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9313 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
9314 
9315 	/* Non-zero default values */
9316 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9317 
9318 	if (q == NULL) {
9319 		/*
9320 		 * Create a helper stream for non-STREAMS socket.
9321 		 */
9322 		err = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
9323 		if (err != 0) {
9324 			ip1dbg(("tcp_create_common: create of IP helper stream "
9325 			    "failed\n"));
9326 			CONN_DEC_REF(connp);
9327 			*errorp = err;
9328 			return (NULL);
9329 		}
9330 		q = connp->conn_rq;
9331 	} else {
9332 		RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9333 	}
9334 
9335 	SOCK_CONNID_INIT(tcp->tcp_connid);
9336 	err = tcp_init(tcp, q);
9337 	if (err != 0) {
9338 		CONN_DEC_REF(connp);
9339 		*errorp = err;
9340 		return (NULL);
9341 	}
9342 
9343 	return (connp);
9344 }
9345 
9346 static int
9347 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9348     boolean_t isv6)
9349 {
9350 	tcp_t		*tcp = NULL;
9351 	conn_t		*connp = NULL;
9352 	int		err;
9353 	vmem_t		*minor_arena = NULL;
9354 	dev_t		conn_dev;
9355 	boolean_t	issocket;
9356 
9357 	if (q->q_ptr != NULL)
9358 		return (0);
9359 
9360 	if (sflag == MODOPEN)
9361 		return (EINVAL);
9362 
9363 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9364 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9365 		minor_arena = ip_minor_arena_la;
9366 	} else {
9367 		/*
9368 		 * Either minor numbers in the large arena were exhausted
9369 		 * or a non socket application is doing the open.
9370 		 * Try to allocate from the small arena.
9371 		 */
9372 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9373 			return (EBUSY);
9374 		}
9375 		minor_arena = ip_minor_arena_sa;
9376 	}
9377 
9378 	ASSERT(minor_arena != NULL);
9379 
9380 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
9381 
9382 	if (flag & SO_FALLBACK) {
9383 		/*
9384 		 * Non streams socket needs a stream to fallback to
9385 		 */
9386 		RD(q)->q_ptr = (void *)conn_dev;
9387 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
9388 		WR(q)->q_ptr = (void *)minor_arena;
9389 		qprocson(q);
9390 		return (0);
9391 	} else if (flag & SO_ACCEPTOR) {
9392 		q->q_qinfo = &tcp_acceptor_rinit;
9393 		/*
9394 		 * the conn_dev and minor_arena will be subsequently used by
9395 		 * tcp_wput_accept() and tcpclose_accept() to figure out the
9396 		 * minor device number for this connection from the q_ptr.
9397 		 */
9398 		RD(q)->q_ptr = (void *)conn_dev;
9399 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9400 		WR(q)->q_ptr = (void *)minor_arena;
9401 		qprocson(q);
9402 		return (0);
9403 	}
9404 
9405 	issocket = flag & SO_SOCKSTR;
9406 	connp = tcp_create_common(q, credp, isv6, issocket, &err);
9407 
9408 	if (connp == NULL) {
9409 		inet_minor_free(minor_arena, conn_dev);
9410 		q->q_ptr = WR(q)->q_ptr = NULL;
9411 		return (err);
9412 	}
9413 
9414 	q->q_ptr = WR(q)->q_ptr = connp;
9415 
9416 	connp->conn_dev = conn_dev;
9417 	connp->conn_minor_arena = minor_arena;
9418 
9419 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9420 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9421 
9422 	if (issocket) {
9423 		WR(q)->q_qinfo = &tcp_sock_winit;
9424 	} else {
9425 		tcp = connp->conn_tcp;
9426 #ifdef  _ILP32
9427 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9428 #else
9429 		tcp->tcp_acceptor_id = conn_dev;
9430 #endif  /* _ILP32 */
9431 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9432 	}
9433 
9434 	/*
9435 	 * Put the ref for TCP. Ref for IP was already put
9436 	 * by ipcl_conn_create. Also Make the conn_t globally
9437 	 * visible to walkers
9438 	 */
9439 	mutex_enter(&connp->conn_lock);
9440 	CONN_INC_REF_LOCKED(connp);
9441 	ASSERT(connp->conn_ref == 2);
9442 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9443 	mutex_exit(&connp->conn_lock);
9444 
9445 	qprocson(q);
9446 	return (0);
9447 }
9448 
9449 /*
9450  * Some TCP options can be "set" by requesting them in the option
9451  * buffer. This is needed for XTI feature test though we do not
9452  * allow it in general. We interpret that this mechanism is more
9453  * applicable to OSI protocols and need not be allowed in general.
9454  * This routine filters out options for which it is not allowed (most)
9455  * and lets through those (few) for which it is. [ The XTI interface
9456  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9457  * ever implemented will have to be allowed here ].
9458  */
9459 static boolean_t
9460 tcp_allow_connopt_set(int level, int name)
9461 {
9462 
9463 	switch (level) {
9464 	case IPPROTO_TCP:
9465 		switch (name) {
9466 		case TCP_NODELAY:
9467 			return (B_TRUE);
9468 		default:
9469 			return (B_FALSE);
9470 		}
9471 		/*NOTREACHED*/
9472 	default:
9473 		return (B_FALSE);
9474 	}
9475 	/*NOTREACHED*/
9476 }
9477 
9478 /*
9479  * this routine gets default values of certain options whose default
9480  * values are maintained by protocol specific code
9481  */
9482 /* ARGSUSED */
9483 int
9484 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9485 {
9486 	int32_t	*i1 = (int32_t *)ptr;
9487 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9488 
9489 	switch (level) {
9490 	case IPPROTO_TCP:
9491 		switch (name) {
9492 		case TCP_NOTIFY_THRESHOLD:
9493 			*i1 = tcps->tcps_ip_notify_interval;
9494 			break;
9495 		case TCP_ABORT_THRESHOLD:
9496 			*i1 = tcps->tcps_ip_abort_interval;
9497 			break;
9498 		case TCP_CONN_NOTIFY_THRESHOLD:
9499 			*i1 = tcps->tcps_ip_notify_cinterval;
9500 			break;
9501 		case TCP_CONN_ABORT_THRESHOLD:
9502 			*i1 = tcps->tcps_ip_abort_cinterval;
9503 			break;
9504 		default:
9505 			return (-1);
9506 		}
9507 		break;
9508 	case IPPROTO_IP:
9509 		switch (name) {
9510 		case IP_TTL:
9511 			*i1 = tcps->tcps_ipv4_ttl;
9512 			break;
9513 		default:
9514 			return (-1);
9515 		}
9516 		break;
9517 	case IPPROTO_IPV6:
9518 		switch (name) {
9519 		case IPV6_UNICAST_HOPS:
9520 			*i1 = tcps->tcps_ipv6_hoplimit;
9521 			break;
9522 		default:
9523 			return (-1);
9524 		}
9525 		break;
9526 	default:
9527 		return (-1);
9528 	}
9529 	return (sizeof (int));
9530 }
9531 
9532 static int
9533 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
9534 {
9535 	int		*i1 = (int *)ptr;
9536 	tcp_t		*tcp = connp->conn_tcp;
9537 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9538 
9539 	switch (level) {
9540 	case SOL_SOCKET:
9541 		switch (name) {
9542 		case SO_LINGER:	{
9543 			struct linger *lgr = (struct linger *)ptr;
9544 
9545 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9546 			lgr->l_linger = tcp->tcp_lingertime;
9547 			}
9548 			return (sizeof (struct linger));
9549 		case SO_DEBUG:
9550 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9551 			break;
9552 		case SO_KEEPALIVE:
9553 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9554 			break;
9555 		case SO_DONTROUTE:
9556 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9557 			break;
9558 		case SO_USELOOPBACK:
9559 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9560 			break;
9561 		case SO_BROADCAST:
9562 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9563 			break;
9564 		case SO_REUSEADDR:
9565 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9566 			break;
9567 		case SO_OOBINLINE:
9568 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9569 			break;
9570 		case SO_DGRAM_ERRIND:
9571 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9572 			break;
9573 		case SO_TYPE:
9574 			*i1 = SOCK_STREAM;
9575 			break;
9576 		case SO_SNDBUF:
9577 			*i1 = tcp->tcp_xmit_hiwater;
9578 			break;
9579 		case SO_RCVBUF:
9580 			*i1 = tcp->tcp_recv_hiwater;
9581 			break;
9582 		case SO_SND_COPYAVOID:
9583 			*i1 = tcp->tcp_snd_zcopy_on ?
9584 			    SO_SND_COPYAVOID : 0;
9585 			break;
9586 		case SO_ALLZONES:
9587 			*i1 = connp->conn_allzones ? 1 : 0;
9588 			break;
9589 		case SO_ANON_MLP:
9590 			*i1 = connp->conn_anon_mlp;
9591 			break;
9592 		case SO_MAC_EXEMPT:
9593 			*i1 = connp->conn_mac_exempt;
9594 			break;
9595 		case SO_EXCLBIND:
9596 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9597 			break;
9598 		case SO_PROTOTYPE:
9599 			*i1 = IPPROTO_TCP;
9600 			break;
9601 		case SO_DOMAIN:
9602 			*i1 = tcp->tcp_family;
9603 			break;
9604 		case SO_ACCEPTCONN:
9605 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
9606 		default:
9607 			return (-1);
9608 		}
9609 		break;
9610 	case IPPROTO_TCP:
9611 		switch (name) {
9612 		case TCP_NODELAY:
9613 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9614 			break;
9615 		case TCP_MAXSEG:
9616 			*i1 = tcp->tcp_mss;
9617 			break;
9618 		case TCP_NOTIFY_THRESHOLD:
9619 			*i1 = (int)tcp->tcp_first_timer_threshold;
9620 			break;
9621 		case TCP_ABORT_THRESHOLD:
9622 			*i1 = tcp->tcp_second_timer_threshold;
9623 			break;
9624 		case TCP_CONN_NOTIFY_THRESHOLD:
9625 			*i1 = tcp->tcp_first_ctimer_threshold;
9626 			break;
9627 		case TCP_CONN_ABORT_THRESHOLD:
9628 			*i1 = tcp->tcp_second_ctimer_threshold;
9629 			break;
9630 		case TCP_RECVDSTADDR:
9631 			*i1 = tcp->tcp_recvdstaddr;
9632 			break;
9633 		case TCP_ANONPRIVBIND:
9634 			*i1 = tcp->tcp_anon_priv_bind;
9635 			break;
9636 		case TCP_EXCLBIND:
9637 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9638 			break;
9639 		case TCP_INIT_CWND:
9640 			*i1 = tcp->tcp_init_cwnd;
9641 			break;
9642 		case TCP_KEEPALIVE_THRESHOLD:
9643 			*i1 = tcp->tcp_ka_interval;
9644 			break;
9645 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9646 			*i1 = tcp->tcp_ka_abort_thres;
9647 			break;
9648 		case TCP_CORK:
9649 			*i1 = tcp->tcp_cork;
9650 			break;
9651 		default:
9652 			return (-1);
9653 		}
9654 		break;
9655 	case IPPROTO_IP:
9656 		if (tcp->tcp_family != AF_INET)
9657 			return (-1);
9658 		switch (name) {
9659 		case IP_OPTIONS:
9660 		case T_IP_OPTIONS: {
9661 			/*
9662 			 * This is compatible with BSD in that in only return
9663 			 * the reverse source route with the final destination
9664 			 * as the last entry. The first 4 bytes of the option
9665 			 * will contain the final destination.
9666 			 */
9667 			int	opt_len;
9668 
9669 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9670 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9671 			ASSERT(opt_len >= 0);
9672 			/* Caller ensures enough space */
9673 			if (opt_len > 0) {
9674 				/*
9675 				 * TODO: Do we have to handle getsockopt on an
9676 				 * initiator as well?
9677 				 */
9678 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9679 			}
9680 			return (0);
9681 			}
9682 		case IP_TOS:
9683 		case T_IP_TOS:
9684 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9685 			break;
9686 		case IP_TTL:
9687 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9688 			break;
9689 		case IP_NEXTHOP:
9690 			/* Handled at IP level */
9691 			return (-EINVAL);
9692 		default:
9693 			return (-1);
9694 		}
9695 		break;
9696 	case IPPROTO_IPV6:
9697 		/*
9698 		 * IPPROTO_IPV6 options are only supported for sockets
9699 		 * that are using IPv6 on the wire.
9700 		 */
9701 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9702 			return (-1);
9703 		}
9704 		switch (name) {
9705 		case IPV6_UNICAST_HOPS:
9706 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9707 			break;	/* goto sizeof (int) option return */
9708 		case IPV6_BOUND_IF:
9709 			/* Zero if not set */
9710 			*i1 = tcp->tcp_bound_if;
9711 			break;	/* goto sizeof (int) option return */
9712 		case IPV6_RECVPKTINFO:
9713 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9714 				*i1 = 1;
9715 			else
9716 				*i1 = 0;
9717 			break;	/* goto sizeof (int) option return */
9718 		case IPV6_RECVTCLASS:
9719 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9720 				*i1 = 1;
9721 			else
9722 				*i1 = 0;
9723 			break;	/* goto sizeof (int) option return */
9724 		case IPV6_RECVHOPLIMIT:
9725 			if (tcp->tcp_ipv6_recvancillary &
9726 			    TCP_IPV6_RECVHOPLIMIT)
9727 				*i1 = 1;
9728 			else
9729 				*i1 = 0;
9730 			break;	/* goto sizeof (int) option return */
9731 		case IPV6_RECVHOPOPTS:
9732 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9733 				*i1 = 1;
9734 			else
9735 				*i1 = 0;
9736 			break;	/* goto sizeof (int) option return */
9737 		case IPV6_RECVDSTOPTS:
9738 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9739 				*i1 = 1;
9740 			else
9741 				*i1 = 0;
9742 			break;	/* goto sizeof (int) option return */
9743 		case _OLD_IPV6_RECVDSTOPTS:
9744 			if (tcp->tcp_ipv6_recvancillary &
9745 			    TCP_OLD_IPV6_RECVDSTOPTS)
9746 				*i1 = 1;
9747 			else
9748 				*i1 = 0;
9749 			break;	/* goto sizeof (int) option return */
9750 		case IPV6_RECVRTHDR:
9751 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9752 				*i1 = 1;
9753 			else
9754 				*i1 = 0;
9755 			break;	/* goto sizeof (int) option return */
9756 		case IPV6_RECVRTHDRDSTOPTS:
9757 			if (tcp->tcp_ipv6_recvancillary &
9758 			    TCP_IPV6_RECVRTDSTOPTS)
9759 				*i1 = 1;
9760 			else
9761 				*i1 = 0;
9762 			break;	/* goto sizeof (int) option return */
9763 		case IPV6_PKTINFO: {
9764 			/* XXX assumes that caller has room for max size! */
9765 			struct in6_pktinfo *pkti;
9766 
9767 			pkti = (struct in6_pktinfo *)ptr;
9768 			if (ipp->ipp_fields & IPPF_IFINDEX)
9769 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9770 			else
9771 				pkti->ipi6_ifindex = 0;
9772 			if (ipp->ipp_fields & IPPF_ADDR)
9773 				pkti->ipi6_addr = ipp->ipp_addr;
9774 			else
9775 				pkti->ipi6_addr = ipv6_all_zeros;
9776 			return (sizeof (struct in6_pktinfo));
9777 		}
9778 		case IPV6_TCLASS:
9779 			if (ipp->ipp_fields & IPPF_TCLASS)
9780 				*i1 = ipp->ipp_tclass;
9781 			else
9782 				*i1 = IPV6_FLOW_TCLASS(
9783 				    IPV6_DEFAULT_VERS_AND_FLOW);
9784 			break;	/* goto sizeof (int) option return */
9785 		case IPV6_NEXTHOP: {
9786 			sin6_t *sin6 = (sin6_t *)ptr;
9787 
9788 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9789 				return (0);
9790 			*sin6 = sin6_null;
9791 			sin6->sin6_family = AF_INET6;
9792 			sin6->sin6_addr = ipp->ipp_nexthop;
9793 			return (sizeof (sin6_t));
9794 		}
9795 		case IPV6_HOPOPTS:
9796 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9797 				return (0);
9798 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9799 				return (0);
9800 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9801 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9802 			if (tcp->tcp_label_len > 0) {
9803 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9804 				ptr[1] = (ipp->ipp_hopoptslen -
9805 				    tcp->tcp_label_len + 7) / 8 - 1;
9806 			}
9807 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9808 		case IPV6_RTHDRDSTOPTS:
9809 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9810 				return (0);
9811 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9812 			return (ipp->ipp_rtdstoptslen);
9813 		case IPV6_RTHDR:
9814 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9815 				return (0);
9816 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9817 			return (ipp->ipp_rthdrlen);
9818 		case IPV6_DSTOPTS:
9819 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9820 				return (0);
9821 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9822 			return (ipp->ipp_dstoptslen);
9823 		case IPV6_SRC_PREFERENCES:
9824 			return (ip6_get_src_preferences(connp,
9825 			    (uint32_t *)ptr));
9826 		case IPV6_PATHMTU: {
9827 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9828 
9829 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9830 				return (-1);
9831 
9832 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9833 			    connp->conn_fport, mtuinfo,
9834 			    connp->conn_netstack));
9835 		}
9836 		default:
9837 			return (-1);
9838 		}
9839 		break;
9840 	default:
9841 		return (-1);
9842 	}
9843 	return (sizeof (int));
9844 }
9845 
9846 /*
9847  * TCP routine to get the values of options.
9848  */
9849 int
9850 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
9851 {
9852 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
9853 }
9854 
9855 /* returns UNIX error, the optlen is a value-result arg */
9856 int
9857 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
9858     void *optvalp, socklen_t *optlen, cred_t *cr)
9859 {
9860 	conn_t		*connp = (conn_t *)proto_handle;
9861 	squeue_t	*sqp = connp->conn_sqp;
9862 	int		error;
9863 	t_uscalar_t	max_optbuf_len;
9864 	void		*optvalp_buf;
9865 	int		len;
9866 
9867 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
9868 	    tcp_opt_obj.odb_opt_des_arr,
9869 	    tcp_opt_obj.odb_opt_arr_cnt,
9870 	    tcp_opt_obj.odb_topmost_tpiprovider,
9871 	    B_FALSE, B_TRUE, cr);
9872 	if (error != 0) {
9873 		if (error < 0) {
9874 			error = proto_tlitosyserr(-error);
9875 		}
9876 		return (error);
9877 	}
9878 
9879 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
9880 
9881 	error = squeue_synch_enter(sqp, connp, 0);
9882 	if (error == ENOMEM) {
9883 		return (ENOMEM);
9884 	}
9885 
9886 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
9887 	squeue_synch_exit(sqp, connp);
9888 
9889 	if (len < 0) {
9890 		/*
9891 		 * Pass on to IP
9892 		 */
9893 		kmem_free(optvalp_buf, max_optbuf_len);
9894 		return (ip_get_options(connp, level, option_name,
9895 		    optvalp, optlen, cr));
9896 	} else {
9897 		/*
9898 		 * update optlen and copy option value
9899 		 */
9900 		t_uscalar_t size = MIN(len, *optlen);
9901 		bcopy(optvalp_buf, optvalp, size);
9902 		bcopy(&size, optlen, sizeof (size));
9903 
9904 		kmem_free(optvalp_buf, max_optbuf_len);
9905 		return (0);
9906 	}
9907 }
9908 
9909 /*
9910  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9911  * Parameters are assumed to be verified by the caller.
9912  */
9913 /* ARGSUSED */
9914 int
9915 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
9916     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9917     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9918 {
9919 	tcp_t	*tcp = connp->conn_tcp;
9920 	int	*i1 = (int *)invalp;
9921 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9922 	boolean_t checkonly;
9923 	int	reterr;
9924 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9925 
9926 	switch (optset_context) {
9927 	case SETFN_OPTCOM_CHECKONLY:
9928 		checkonly = B_TRUE;
9929 		/*
9930 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9931 		 * inlen != 0 implies value supplied and
9932 		 * 	we have to "pretend" to set it.
9933 		 * inlen == 0 implies that there is no
9934 		 * 	value part in T_CHECK request and just validation
9935 		 * done elsewhere should be enough, we just return here.
9936 		 */
9937 		if (inlen == 0) {
9938 			*outlenp = 0;
9939 			return (0);
9940 		}
9941 		break;
9942 	case SETFN_OPTCOM_NEGOTIATE:
9943 		checkonly = B_FALSE;
9944 		break;
9945 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9946 	case SETFN_CONN_NEGOTIATE:
9947 		checkonly = B_FALSE;
9948 		/*
9949 		 * Negotiating local and "association-related" options
9950 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9951 		 * primitives is allowed by XTI, but we choose
9952 		 * to not implement this style negotiation for Internet
9953 		 * protocols (We interpret it is a must for OSI world but
9954 		 * optional for Internet protocols) for all options.
9955 		 * [ Will do only for the few options that enable test
9956 		 * suites that our XTI implementation of this feature
9957 		 * works for transports that do allow it ]
9958 		 */
9959 		if (!tcp_allow_connopt_set(level, name)) {
9960 			*outlenp = 0;
9961 			return (EINVAL);
9962 		}
9963 		break;
9964 	default:
9965 		/*
9966 		 * We should never get here
9967 		 */
9968 		*outlenp = 0;
9969 		return (EINVAL);
9970 	}
9971 
9972 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9973 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9974 
9975 	/*
9976 	 * For TCP, we should have no ancillary data sent down
9977 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9978 	 * has to be zero.
9979 	 */
9980 	ASSERT(thisdg_attrs == NULL);
9981 
9982 	/*
9983 	 * For fixed length options, no sanity check
9984 	 * of passed in length is done. It is assumed *_optcom_req()
9985 	 * routines do the right thing.
9986 	 */
9987 	switch (level) {
9988 	case SOL_SOCKET:
9989 		switch (name) {
9990 		case SO_LINGER: {
9991 			struct linger *lgr = (struct linger *)invalp;
9992 
9993 			if (!checkonly) {
9994 				if (lgr->l_onoff) {
9995 					tcp->tcp_linger = 1;
9996 					tcp->tcp_lingertime = lgr->l_linger;
9997 				} else {
9998 					tcp->tcp_linger = 0;
9999 					tcp->tcp_lingertime = 0;
10000 				}
10001 				/* struct copy */
10002 				*(struct linger *)outvalp = *lgr;
10003 			} else {
10004 				if (!lgr->l_onoff) {
10005 					((struct linger *)
10006 					    outvalp)->l_onoff = 0;
10007 					((struct linger *)
10008 					    outvalp)->l_linger = 0;
10009 				} else {
10010 					/* struct copy */
10011 					*(struct linger *)outvalp = *lgr;
10012 				}
10013 			}
10014 			*outlenp = sizeof (struct linger);
10015 			return (0);
10016 		}
10017 		case SO_DEBUG:
10018 			if (!checkonly)
10019 				tcp->tcp_debug = onoff;
10020 			break;
10021 		case SO_KEEPALIVE:
10022 			if (checkonly) {
10023 				/* check only case */
10024 				break;
10025 			}
10026 
10027 			if (!onoff) {
10028 				if (tcp->tcp_ka_enabled) {
10029 					if (tcp->tcp_ka_tid != 0) {
10030 						(void) TCP_TIMER_CANCEL(tcp,
10031 						    tcp->tcp_ka_tid);
10032 						tcp->tcp_ka_tid = 0;
10033 					}
10034 					tcp->tcp_ka_enabled = 0;
10035 				}
10036 				break;
10037 			}
10038 			if (!tcp->tcp_ka_enabled) {
10039 				/* Crank up the keepalive timer */
10040 				tcp->tcp_ka_last_intrvl = 0;
10041 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10042 				    tcp_keepalive_killer,
10043 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10044 				tcp->tcp_ka_enabled = 1;
10045 			}
10046 			break;
10047 		case SO_DONTROUTE:
10048 			/*
10049 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10050 			 * only of interest to IP.  We track them here only so
10051 			 * that we can report their current value.
10052 			 */
10053 			if (!checkonly) {
10054 				tcp->tcp_dontroute = onoff;
10055 				tcp->tcp_connp->conn_dontroute = onoff;
10056 			}
10057 			break;
10058 		case SO_USELOOPBACK:
10059 			if (!checkonly) {
10060 				tcp->tcp_useloopback = onoff;
10061 				tcp->tcp_connp->conn_loopback = onoff;
10062 			}
10063 			break;
10064 		case SO_BROADCAST:
10065 			if (!checkonly) {
10066 				tcp->tcp_broadcast = onoff;
10067 				tcp->tcp_connp->conn_broadcast = onoff;
10068 			}
10069 			break;
10070 		case SO_REUSEADDR:
10071 			if (!checkonly) {
10072 				tcp->tcp_reuseaddr = onoff;
10073 				tcp->tcp_connp->conn_reuseaddr = onoff;
10074 			}
10075 			break;
10076 		case SO_OOBINLINE:
10077 			if (!checkonly) {
10078 				tcp->tcp_oobinline = onoff;
10079 				if (IPCL_IS_NONSTR(tcp->tcp_connp))
10080 					proto_set_rx_oob_opt(connp, onoff);
10081 			}
10082 			break;
10083 		case SO_DGRAM_ERRIND:
10084 			if (!checkonly)
10085 				tcp->tcp_dgram_errind = onoff;
10086 			break;
10087 		case SO_SNDBUF: {
10088 			if (*i1 > tcps->tcps_max_buf) {
10089 				*outlenp = 0;
10090 				return (ENOBUFS);
10091 			}
10092 			if (checkonly)
10093 				break;
10094 
10095 			tcp->tcp_xmit_hiwater = *i1;
10096 			if (tcps->tcps_snd_lowat_fraction != 0)
10097 				tcp->tcp_xmit_lowater =
10098 				    tcp->tcp_xmit_hiwater /
10099 				    tcps->tcps_snd_lowat_fraction;
10100 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10101 			/*
10102 			 * If we are flow-controlled, recheck the condition.
10103 			 * There are apps that increase SO_SNDBUF size when
10104 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10105 			 * control condition to be lifted right away.
10106 			 */
10107 			mutex_enter(&tcp->tcp_non_sq_lock);
10108 			if (tcp->tcp_flow_stopped &&
10109 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10110 				tcp_clrqfull(tcp);
10111 			}
10112 			mutex_exit(&tcp->tcp_non_sq_lock);
10113 			break;
10114 		}
10115 		case SO_RCVBUF:
10116 			if (*i1 > tcps->tcps_max_buf) {
10117 				*outlenp = 0;
10118 				return (ENOBUFS);
10119 			}
10120 			/* Silently ignore zero */
10121 			if (!checkonly && *i1 != 0) {
10122 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10123 				(void) tcp_rwnd_set(tcp, *i1);
10124 			}
10125 			/*
10126 			 * XXX should we return the rwnd here
10127 			 * and tcp_opt_get ?
10128 			 */
10129 			break;
10130 		case SO_SND_COPYAVOID:
10131 			if (!checkonly) {
10132 				/* we only allow enable at most once for now */
10133 				if (tcp->tcp_loopback ||
10134 				    (tcp->tcp_kssl_ctx != NULL) ||
10135 				    (!tcp->tcp_snd_zcopy_aware &&
10136 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10137 					*outlenp = 0;
10138 					return (EOPNOTSUPP);
10139 				}
10140 				tcp->tcp_snd_zcopy_aware = 1;
10141 			}
10142 			break;
10143 		case SO_ALLZONES:
10144 			/* Pass option along to IP level for handling */
10145 			return (-EINVAL);
10146 		case SO_ANON_MLP:
10147 			/* Pass option along to IP level for handling */
10148 			return (-EINVAL);
10149 		case SO_MAC_EXEMPT:
10150 			/* Pass option along to IP level for handling */
10151 			return (-EINVAL);
10152 		case SO_EXCLBIND:
10153 			if (!checkonly)
10154 				tcp->tcp_exclbind = onoff;
10155 			break;
10156 		default:
10157 			*outlenp = 0;
10158 			return (EINVAL);
10159 		}
10160 		break;
10161 	case IPPROTO_TCP:
10162 		switch (name) {
10163 		case TCP_NODELAY:
10164 			if (!checkonly)
10165 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10166 			break;
10167 		case TCP_NOTIFY_THRESHOLD:
10168 			if (!checkonly)
10169 				tcp->tcp_first_timer_threshold = *i1;
10170 			break;
10171 		case TCP_ABORT_THRESHOLD:
10172 			if (!checkonly)
10173 				tcp->tcp_second_timer_threshold = *i1;
10174 			break;
10175 		case TCP_CONN_NOTIFY_THRESHOLD:
10176 			if (!checkonly)
10177 				tcp->tcp_first_ctimer_threshold = *i1;
10178 			break;
10179 		case TCP_CONN_ABORT_THRESHOLD:
10180 			if (!checkonly)
10181 				tcp->tcp_second_ctimer_threshold = *i1;
10182 			break;
10183 		case TCP_RECVDSTADDR:
10184 			if (tcp->tcp_state > TCPS_LISTEN)
10185 				return (EOPNOTSUPP);
10186 			if (!checkonly)
10187 				tcp->tcp_recvdstaddr = onoff;
10188 			break;
10189 		case TCP_ANONPRIVBIND:
10190 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10191 			    IPPROTO_TCP)) != 0) {
10192 				*outlenp = 0;
10193 				return (reterr);
10194 			}
10195 			if (!checkonly) {
10196 				tcp->tcp_anon_priv_bind = onoff;
10197 			}
10198 			break;
10199 		case TCP_EXCLBIND:
10200 			if (!checkonly)
10201 				tcp->tcp_exclbind = onoff;
10202 			break;	/* goto sizeof (int) option return */
10203 		case TCP_INIT_CWND: {
10204 			uint32_t init_cwnd = *((uint32_t *)invalp);
10205 
10206 			if (checkonly)
10207 				break;
10208 
10209 			/*
10210 			 * Only allow socket with network configuration
10211 			 * privilege to set the initial cwnd to be larger
10212 			 * than allowed by RFC 3390.
10213 			 */
10214 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10215 				tcp->tcp_init_cwnd = init_cwnd;
10216 				break;
10217 			}
10218 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10219 				*outlenp = 0;
10220 				return (reterr);
10221 			}
10222 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10223 				*outlenp = 0;
10224 				return (EINVAL);
10225 			}
10226 			tcp->tcp_init_cwnd = init_cwnd;
10227 			break;
10228 		}
10229 		case TCP_KEEPALIVE_THRESHOLD:
10230 			if (checkonly)
10231 				break;
10232 
10233 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10234 			    *i1 > tcps->tcps_keepalive_interval_high) {
10235 				*outlenp = 0;
10236 				return (EINVAL);
10237 			}
10238 			if (*i1 != tcp->tcp_ka_interval) {
10239 				tcp->tcp_ka_interval = *i1;
10240 				/*
10241 				 * Check if we need to restart the
10242 				 * keepalive timer.
10243 				 */
10244 				if (tcp->tcp_ka_tid != 0) {
10245 					ASSERT(tcp->tcp_ka_enabled);
10246 					(void) TCP_TIMER_CANCEL(tcp,
10247 					    tcp->tcp_ka_tid);
10248 					tcp->tcp_ka_last_intrvl = 0;
10249 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10250 					    tcp_keepalive_killer,
10251 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10252 				}
10253 			}
10254 			break;
10255 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10256 			if (!checkonly) {
10257 				if (*i1 <
10258 				    tcps->tcps_keepalive_abort_interval_low ||
10259 				    *i1 >
10260 				    tcps->tcps_keepalive_abort_interval_high) {
10261 					*outlenp = 0;
10262 					return (EINVAL);
10263 				}
10264 				tcp->tcp_ka_abort_thres = *i1;
10265 			}
10266 			break;
10267 		case TCP_CORK:
10268 			if (!checkonly) {
10269 				/*
10270 				 * if tcp->tcp_cork was set and is now
10271 				 * being unset, we have to make sure that
10272 				 * the remaining data gets sent out. Also
10273 				 * unset tcp->tcp_cork so that tcp_wput_data()
10274 				 * can send data even if it is less than mss
10275 				 */
10276 				if (tcp->tcp_cork && onoff == 0 &&
10277 				    tcp->tcp_unsent > 0) {
10278 					tcp->tcp_cork = B_FALSE;
10279 					tcp_wput_data(tcp, NULL, B_FALSE);
10280 				}
10281 				tcp->tcp_cork = onoff;
10282 			}
10283 			break;
10284 		default:
10285 			*outlenp = 0;
10286 			return (EINVAL);
10287 		}
10288 		break;
10289 	case IPPROTO_IP:
10290 		if (tcp->tcp_family != AF_INET) {
10291 			*outlenp = 0;
10292 			return (ENOPROTOOPT);
10293 		}
10294 		switch (name) {
10295 		case IP_OPTIONS:
10296 		case T_IP_OPTIONS:
10297 			reterr = tcp_opt_set_header(tcp, checkonly,
10298 			    invalp, inlen);
10299 			if (reterr) {
10300 				*outlenp = 0;
10301 				return (reterr);
10302 			}
10303 			/* OK return - copy input buffer into output buffer */
10304 			if (invalp != outvalp) {
10305 				/* don't trust bcopy for identical src/dst */
10306 				bcopy(invalp, outvalp, inlen);
10307 			}
10308 			*outlenp = inlen;
10309 			return (0);
10310 		case IP_TOS:
10311 		case T_IP_TOS:
10312 			if (!checkonly) {
10313 				tcp->tcp_ipha->ipha_type_of_service =
10314 				    (uchar_t)*i1;
10315 				tcp->tcp_tos = (uchar_t)*i1;
10316 			}
10317 			break;
10318 		case IP_TTL:
10319 			if (!checkonly) {
10320 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10321 				tcp->tcp_ttl = (uchar_t)*i1;
10322 			}
10323 			break;
10324 		case IP_BOUND_IF:
10325 		case IP_NEXTHOP:
10326 			/* Handled at the IP level */
10327 			return (-EINVAL);
10328 		case IP_SEC_OPT:
10329 			/*
10330 			 * We should not allow policy setting after
10331 			 * we start listening for connections.
10332 			 */
10333 			if (tcp->tcp_state == TCPS_LISTEN) {
10334 				return (EINVAL);
10335 			} else {
10336 				/* Handled at the IP level */
10337 				return (-EINVAL);
10338 			}
10339 		default:
10340 			*outlenp = 0;
10341 			return (EINVAL);
10342 		}
10343 		break;
10344 	case IPPROTO_IPV6: {
10345 		ip6_pkt_t		*ipp;
10346 
10347 		/*
10348 		 * IPPROTO_IPV6 options are only supported for sockets
10349 		 * that are using IPv6 on the wire.
10350 		 */
10351 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10352 			*outlenp = 0;
10353 			return (ENOPROTOOPT);
10354 		}
10355 		/*
10356 		 * Only sticky options; no ancillary data
10357 		 */
10358 		ipp = &tcp->tcp_sticky_ipp;
10359 
10360 		switch (name) {
10361 		case IPV6_UNICAST_HOPS:
10362 			/* -1 means use default */
10363 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10364 				*outlenp = 0;
10365 				return (EINVAL);
10366 			}
10367 			if (!checkonly) {
10368 				if (*i1 == -1) {
10369 					tcp->tcp_ip6h->ip6_hops =
10370 					    ipp->ipp_unicast_hops =
10371 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10372 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10373 					/* Pass modified value to IP. */
10374 					*i1 = tcp->tcp_ip6h->ip6_hops;
10375 				} else {
10376 					tcp->tcp_ip6h->ip6_hops =
10377 					    ipp->ipp_unicast_hops =
10378 					    (uint8_t)*i1;
10379 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10380 				}
10381 				reterr = tcp_build_hdrs(tcp);
10382 				if (reterr != 0)
10383 					return (reterr);
10384 			}
10385 			break;
10386 		case IPV6_BOUND_IF:
10387 			if (!checkonly) {
10388 				tcp->tcp_bound_if = *i1;
10389 				PASS_OPT_TO_IP(connp);
10390 			}
10391 			break;
10392 		/*
10393 		 * Set boolean switches for ancillary data delivery
10394 		 */
10395 		case IPV6_RECVPKTINFO:
10396 			if (!checkonly) {
10397 				if (onoff)
10398 					tcp->tcp_ipv6_recvancillary |=
10399 					    TCP_IPV6_RECVPKTINFO;
10400 				else
10401 					tcp->tcp_ipv6_recvancillary &=
10402 					    ~TCP_IPV6_RECVPKTINFO;
10403 				/* Force it to be sent up with the next msg */
10404 				tcp->tcp_recvifindex = 0;
10405 				PASS_OPT_TO_IP(connp);
10406 			}
10407 			break;
10408 		case IPV6_RECVTCLASS:
10409 			if (!checkonly) {
10410 				if (onoff)
10411 					tcp->tcp_ipv6_recvancillary |=
10412 					    TCP_IPV6_RECVTCLASS;
10413 				else
10414 					tcp->tcp_ipv6_recvancillary &=
10415 					    ~TCP_IPV6_RECVTCLASS;
10416 				PASS_OPT_TO_IP(connp);
10417 			}
10418 			break;
10419 		case IPV6_RECVHOPLIMIT:
10420 			if (!checkonly) {
10421 				if (onoff)
10422 					tcp->tcp_ipv6_recvancillary |=
10423 					    TCP_IPV6_RECVHOPLIMIT;
10424 				else
10425 					tcp->tcp_ipv6_recvancillary &=
10426 					    ~TCP_IPV6_RECVHOPLIMIT;
10427 				/* Force it to be sent up with the next msg */
10428 				tcp->tcp_recvhops = 0xffffffffU;
10429 				PASS_OPT_TO_IP(connp);
10430 			}
10431 			break;
10432 		case IPV6_RECVHOPOPTS:
10433 			if (!checkonly) {
10434 				if (onoff)
10435 					tcp->tcp_ipv6_recvancillary |=
10436 					    TCP_IPV6_RECVHOPOPTS;
10437 				else
10438 					tcp->tcp_ipv6_recvancillary &=
10439 					    ~TCP_IPV6_RECVHOPOPTS;
10440 				PASS_OPT_TO_IP(connp);
10441 			}
10442 			break;
10443 		case IPV6_RECVDSTOPTS:
10444 			if (!checkonly) {
10445 				if (onoff)
10446 					tcp->tcp_ipv6_recvancillary |=
10447 					    TCP_IPV6_RECVDSTOPTS;
10448 				else
10449 					tcp->tcp_ipv6_recvancillary &=
10450 					    ~TCP_IPV6_RECVDSTOPTS;
10451 				PASS_OPT_TO_IP(connp);
10452 			}
10453 			break;
10454 		case _OLD_IPV6_RECVDSTOPTS:
10455 			if (!checkonly) {
10456 				if (onoff)
10457 					tcp->tcp_ipv6_recvancillary |=
10458 					    TCP_OLD_IPV6_RECVDSTOPTS;
10459 				else
10460 					tcp->tcp_ipv6_recvancillary &=
10461 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10462 			}
10463 			break;
10464 		case IPV6_RECVRTHDR:
10465 			if (!checkonly) {
10466 				if (onoff)
10467 					tcp->tcp_ipv6_recvancillary |=
10468 					    TCP_IPV6_RECVRTHDR;
10469 				else
10470 					tcp->tcp_ipv6_recvancillary &=
10471 					    ~TCP_IPV6_RECVRTHDR;
10472 				PASS_OPT_TO_IP(connp);
10473 			}
10474 			break;
10475 		case IPV6_RECVRTHDRDSTOPTS:
10476 			if (!checkonly) {
10477 				if (onoff)
10478 					tcp->tcp_ipv6_recvancillary |=
10479 					    TCP_IPV6_RECVRTDSTOPTS;
10480 				else
10481 					tcp->tcp_ipv6_recvancillary &=
10482 					    ~TCP_IPV6_RECVRTDSTOPTS;
10483 				PASS_OPT_TO_IP(connp);
10484 			}
10485 			break;
10486 		case IPV6_PKTINFO:
10487 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10488 				return (EINVAL);
10489 			if (checkonly)
10490 				break;
10491 
10492 			if (inlen == 0) {
10493 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10494 			} else {
10495 				struct in6_pktinfo *pkti;
10496 
10497 				pkti = (struct in6_pktinfo *)invalp;
10498 				/*
10499 				 * RFC 3542 states that ipi6_addr must be
10500 				 * the unspecified address when setting the
10501 				 * IPV6_PKTINFO sticky socket option on a
10502 				 * TCP socket.
10503 				 */
10504 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10505 					return (EINVAL);
10506 				/*
10507 				 * IP will validate the source address and
10508 				 * interface index.
10509 				 */
10510 				if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
10511 					reterr = ip_set_options(tcp->tcp_connp,
10512 					    level, name, invalp, inlen, cr);
10513 				} else {
10514 					reterr = ip6_set_pktinfo(cr,
10515 					    tcp->tcp_connp, pkti, mblk);
10516 				}
10517 				if (reterr != 0)
10518 					return (reterr);
10519 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10520 				ipp->ipp_addr = pkti->ipi6_addr;
10521 				if (ipp->ipp_ifindex != 0)
10522 					ipp->ipp_fields |= IPPF_IFINDEX;
10523 				else
10524 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10525 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10526 					ipp->ipp_fields |= IPPF_ADDR;
10527 				else
10528 					ipp->ipp_fields &= ~IPPF_ADDR;
10529 			}
10530 			reterr = tcp_build_hdrs(tcp);
10531 			if (reterr != 0)
10532 				return (reterr);
10533 			break;
10534 		case IPV6_TCLASS:
10535 			if (inlen != 0 && inlen != sizeof (int))
10536 				return (EINVAL);
10537 			if (checkonly)
10538 				break;
10539 
10540 			if (inlen == 0) {
10541 				ipp->ipp_fields &= ~IPPF_TCLASS;
10542 			} else {
10543 				if (*i1 > 255 || *i1 < -1)
10544 					return (EINVAL);
10545 				if (*i1 == -1) {
10546 					ipp->ipp_tclass = 0;
10547 					*i1 = 0;
10548 				} else {
10549 					ipp->ipp_tclass = *i1;
10550 				}
10551 				ipp->ipp_fields |= IPPF_TCLASS;
10552 			}
10553 			reterr = tcp_build_hdrs(tcp);
10554 			if (reterr != 0)
10555 				return (reterr);
10556 			break;
10557 		case IPV6_NEXTHOP:
10558 			/*
10559 			 * IP will verify that the nexthop is reachable
10560 			 * and fail for sticky options.
10561 			 */
10562 			if (inlen != 0 && inlen != sizeof (sin6_t))
10563 				return (EINVAL);
10564 			if (checkonly)
10565 				break;
10566 
10567 			if (inlen == 0) {
10568 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10569 			} else {
10570 				sin6_t *sin6 = (sin6_t *)invalp;
10571 
10572 				if (sin6->sin6_family != AF_INET6)
10573 					return (EAFNOSUPPORT);
10574 				if (IN6_IS_ADDR_V4MAPPED(
10575 				    &sin6->sin6_addr))
10576 					return (EADDRNOTAVAIL);
10577 				ipp->ipp_nexthop = sin6->sin6_addr;
10578 				if (!IN6_IS_ADDR_UNSPECIFIED(
10579 				    &ipp->ipp_nexthop))
10580 					ipp->ipp_fields |= IPPF_NEXTHOP;
10581 				else
10582 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10583 			}
10584 			reterr = tcp_build_hdrs(tcp);
10585 			if (reterr != 0)
10586 				return (reterr);
10587 			PASS_OPT_TO_IP(connp);
10588 			break;
10589 		case IPV6_HOPOPTS: {
10590 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10591 
10592 			/*
10593 			 * Sanity checks - minimum size, size a multiple of
10594 			 * eight bytes, and matching size passed in.
10595 			 */
10596 			if (inlen != 0 &&
10597 			    inlen != (8 * (hopts->ip6h_len + 1)))
10598 				return (EINVAL);
10599 
10600 			if (checkonly)
10601 				break;
10602 
10603 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10604 			    (uchar_t **)&ipp->ipp_hopopts,
10605 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10606 			if (reterr != 0)
10607 				return (reterr);
10608 			if (ipp->ipp_hopoptslen == 0)
10609 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10610 			else
10611 				ipp->ipp_fields |= IPPF_HOPOPTS;
10612 			reterr = tcp_build_hdrs(tcp);
10613 			if (reterr != 0)
10614 				return (reterr);
10615 			break;
10616 		}
10617 		case IPV6_RTHDRDSTOPTS: {
10618 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10619 
10620 			/*
10621 			 * Sanity checks - minimum size, size a multiple of
10622 			 * eight bytes, and matching size passed in.
10623 			 */
10624 			if (inlen != 0 &&
10625 			    inlen != (8 * (dopts->ip6d_len + 1)))
10626 				return (EINVAL);
10627 
10628 			if (checkonly)
10629 				break;
10630 
10631 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10632 			    (uchar_t **)&ipp->ipp_rtdstopts,
10633 			    &ipp->ipp_rtdstoptslen, 0);
10634 			if (reterr != 0)
10635 				return (reterr);
10636 			if (ipp->ipp_rtdstoptslen == 0)
10637 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10638 			else
10639 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10640 			reterr = tcp_build_hdrs(tcp);
10641 			if (reterr != 0)
10642 				return (reterr);
10643 			break;
10644 		}
10645 		case IPV6_DSTOPTS: {
10646 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10647 
10648 			/*
10649 			 * Sanity checks - minimum size, size a multiple of
10650 			 * eight bytes, and matching size passed in.
10651 			 */
10652 			if (inlen != 0 &&
10653 			    inlen != (8 * (dopts->ip6d_len + 1)))
10654 				return (EINVAL);
10655 
10656 			if (checkonly)
10657 				break;
10658 
10659 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10660 			    (uchar_t **)&ipp->ipp_dstopts,
10661 			    &ipp->ipp_dstoptslen, 0);
10662 			if (reterr != 0)
10663 				return (reterr);
10664 			if (ipp->ipp_dstoptslen == 0)
10665 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10666 			else
10667 				ipp->ipp_fields |= IPPF_DSTOPTS;
10668 			reterr = tcp_build_hdrs(tcp);
10669 			if (reterr != 0)
10670 				return (reterr);
10671 			break;
10672 		}
10673 		case IPV6_RTHDR: {
10674 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10675 
10676 			/*
10677 			 * Sanity checks - minimum size, size a multiple of
10678 			 * eight bytes, and matching size passed in.
10679 			 */
10680 			if (inlen != 0 &&
10681 			    inlen != (8 * (rt->ip6r_len + 1)))
10682 				return (EINVAL);
10683 
10684 			if (checkonly)
10685 				break;
10686 
10687 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10688 			    (uchar_t **)&ipp->ipp_rthdr,
10689 			    &ipp->ipp_rthdrlen, 0);
10690 			if (reterr != 0)
10691 				return (reterr);
10692 			if (ipp->ipp_rthdrlen == 0)
10693 				ipp->ipp_fields &= ~IPPF_RTHDR;
10694 			else
10695 				ipp->ipp_fields |= IPPF_RTHDR;
10696 			reterr = tcp_build_hdrs(tcp);
10697 			if (reterr != 0)
10698 				return (reterr);
10699 			break;
10700 		}
10701 		case IPV6_V6ONLY:
10702 			if (!checkonly) {
10703 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10704 			}
10705 			break;
10706 		case IPV6_USE_MIN_MTU:
10707 			if (inlen != sizeof (int))
10708 				return (EINVAL);
10709 
10710 			if (*i1 < -1 || *i1 > 1)
10711 				return (EINVAL);
10712 
10713 			if (checkonly)
10714 				break;
10715 
10716 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10717 			ipp->ipp_use_min_mtu = *i1;
10718 			break;
10719 		case IPV6_BOUND_PIF:
10720 			/* Handled at the IP level */
10721 			return (-EINVAL);
10722 		case IPV6_SEC_OPT:
10723 			/*
10724 			 * We should not allow policy setting after
10725 			 * we start listening for connections.
10726 			 */
10727 			if (tcp->tcp_state == TCPS_LISTEN) {
10728 				return (EINVAL);
10729 			} else {
10730 				/* Handled at the IP level */
10731 				return (-EINVAL);
10732 			}
10733 		case IPV6_SRC_PREFERENCES:
10734 			if (inlen != sizeof (uint32_t))
10735 				return (EINVAL);
10736 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10737 			    *(uint32_t *)invalp);
10738 			if (reterr != 0) {
10739 				*outlenp = 0;
10740 				return (reterr);
10741 			}
10742 			break;
10743 		default:
10744 			*outlenp = 0;
10745 			return (EINVAL);
10746 		}
10747 		break;
10748 	}		/* end IPPROTO_IPV6 */
10749 	default:
10750 		*outlenp = 0;
10751 		return (EINVAL);
10752 	}
10753 	/*
10754 	 * Common case of OK return with outval same as inval
10755 	 */
10756 	if (invalp != outvalp) {
10757 		/* don't trust bcopy for identical src/dst */
10758 		(void) bcopy(invalp, outvalp, inlen);
10759 	}
10760 	*outlenp = inlen;
10761 	return (0);
10762 }
10763 
10764 /* ARGSUSED */
10765 int
10766 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10767     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10768     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10769 {
10770 	conn_t	*connp =  Q_TO_CONN(q);
10771 
10772 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
10773 	    outlenp, outvalp, thisdg_attrs, cr, mblk));
10774 }
10775 
10776 int
10777 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
10778     const void *optvalp, socklen_t optlen, cred_t *cr)
10779 {
10780 	conn_t		*connp = (conn_t *)proto_handle;
10781 	squeue_t	*sqp = connp->conn_sqp;
10782 	int		error;
10783 
10784 	/*
10785 	 * Entering the squeue synchronously can result in a context switch,
10786 	 * which can cause a rather sever performance degradation. So we try to
10787 	 * handle whatever options we can without entering the squeue.
10788 	 */
10789 	if (level == IPPROTO_TCP) {
10790 		switch (option_name) {
10791 		case TCP_NODELAY:
10792 			if (optlen != sizeof (int32_t))
10793 				return (EINVAL);
10794 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
10795 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
10796 			    connp->conn_tcp->tcp_mss;
10797 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
10798 			return (0);
10799 		default:
10800 			break;
10801 		}
10802 	}
10803 
10804 	error = squeue_synch_enter(sqp, connp, 0);
10805 	if (error == ENOMEM) {
10806 		return (ENOMEM);
10807 	}
10808 
10809 	error = proto_opt_check(level, option_name, optlen, NULL,
10810 	    tcp_opt_obj.odb_opt_des_arr,
10811 	    tcp_opt_obj.odb_opt_arr_cnt,
10812 	    tcp_opt_obj.odb_topmost_tpiprovider,
10813 	    B_TRUE, B_FALSE, cr);
10814 
10815 	if (error != 0) {
10816 		if (error < 0) {
10817 			error = proto_tlitosyserr(-error);
10818 		}
10819 		squeue_synch_exit(sqp, connp);
10820 		return (error);
10821 	}
10822 
10823 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
10824 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
10825 	    NULL, cr, NULL);
10826 	squeue_synch_exit(sqp, connp);
10827 
10828 	if (error < 0) {
10829 		/*
10830 		 * Pass on to ip
10831 		 */
10832 		error = ip_set_options(connp, level, option_name, optvalp,
10833 		    optlen, cr);
10834 	}
10835 	return (error);
10836 }
10837 
10838 /*
10839  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10840  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10841  * headers, and the maximum size tcp header (to avoid reallocation
10842  * on the fly for additional tcp options).
10843  * Returns failure if can't allocate memory.
10844  */
10845 static int
10846 tcp_build_hdrs(tcp_t *tcp)
10847 {
10848 	char	*hdrs;
10849 	uint_t	hdrs_len;
10850 	ip6i_t	*ip6i;
10851 	char	buf[TCP_MAX_HDR_LENGTH];
10852 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10853 	in6_addr_t src, dst;
10854 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10855 	conn_t *connp = tcp->tcp_connp;
10856 
10857 	/*
10858 	 * save the existing tcp header and source/dest IP addresses
10859 	 */
10860 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10861 	src = tcp->tcp_ip6h->ip6_src;
10862 	dst = tcp->tcp_ip6h->ip6_dst;
10863 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10864 	ASSERT(hdrs_len != 0);
10865 	if (hdrs_len > tcp->tcp_iphc_len) {
10866 		/* Need to reallocate */
10867 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10868 		if (hdrs == NULL)
10869 			return (ENOMEM);
10870 		if (tcp->tcp_iphc != NULL) {
10871 			if (tcp->tcp_hdr_grown) {
10872 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10873 			} else {
10874 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10875 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10876 			}
10877 			tcp->tcp_iphc_len = 0;
10878 		}
10879 		ASSERT(tcp->tcp_iphc_len == 0);
10880 		tcp->tcp_iphc = hdrs;
10881 		tcp->tcp_iphc_len = hdrs_len;
10882 		tcp->tcp_hdr_grown = B_TRUE;
10883 	}
10884 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10885 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10886 
10887 	/* Set header fields not in ipp */
10888 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10889 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10890 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10891 	} else {
10892 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10893 	}
10894 	/*
10895 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10896 	 *
10897 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10898 	 */
10899 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10900 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10901 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10902 
10903 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10904 
10905 	tcp->tcp_ip6h->ip6_src = src;
10906 	tcp->tcp_ip6h->ip6_dst = dst;
10907 
10908 	/*
10909 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10910 	 * the default value for TCP.
10911 	 */
10912 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10913 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
10914 
10915 	/*
10916 	 * If we're setting extension headers after a connection
10917 	 * has been established, and if we have a routing header
10918 	 * among the extension headers, call ip_massage_options_v6 to
10919 	 * manipulate the routing header/ip6_dst set the checksum
10920 	 * difference in the tcp header template.
10921 	 * (This happens in tcp_connect_ipv6 if the routing header
10922 	 * is set prior to the connect.)
10923 	 * Set the tcp_sum to zero first in case we've cleared a
10924 	 * routing header or don't have one at all.
10925 	 */
10926 	tcp->tcp_sum = 0;
10927 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10928 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10929 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10930 		    (uint8_t *)tcp->tcp_tcph);
10931 		if (rth != NULL) {
10932 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10933 			    rth, tcps->tcps_netstack);
10934 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10935 			    (tcp->tcp_sum >> 16));
10936 		}
10937 	}
10938 
10939 	/* Try to get everything in a single mblk */
10940 	(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
10941 	    hdrs_len + tcps->tcps_wroff_xtra);
10942 	return (0);
10943 }
10944 
10945 /*
10946  * Transfer any source route option from ipha to buf/dst in reversed form.
10947  */
10948 static int
10949 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10950 {
10951 	ipoptp_t	opts;
10952 	uchar_t		*opt;
10953 	uint8_t		optval;
10954 	uint8_t		optlen;
10955 	uint32_t	len = 0;
10956 
10957 	for (optval = ipoptp_first(&opts, ipha);
10958 	    optval != IPOPT_EOL;
10959 	    optval = ipoptp_next(&opts)) {
10960 		opt = opts.ipoptp_cur;
10961 		optlen = opts.ipoptp_len;
10962 		switch (optval) {
10963 			int	off1, off2;
10964 		case IPOPT_SSRR:
10965 		case IPOPT_LSRR:
10966 
10967 			/* Reverse source route */
10968 			/*
10969 			 * First entry should be the next to last one in the
10970 			 * current source route (the last entry is our
10971 			 * address.)
10972 			 * The last entry should be the final destination.
10973 			 */
10974 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10975 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10976 			off1 = IPOPT_MINOFF_SR - 1;
10977 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10978 			if (off2 < 0) {
10979 				/* No entries in source route */
10980 				break;
10981 			}
10982 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10983 			/*
10984 			 * Note: use src since ipha has not had its src
10985 			 * and dst reversed (it is in the state it was
10986 			 * received.
10987 			 */
10988 			bcopy(&ipha->ipha_src, buf + off2,
10989 			    IP_ADDR_LEN);
10990 			off2 -= IP_ADDR_LEN;
10991 
10992 			while (off2 > 0) {
10993 				bcopy(opt + off2, buf + off1,
10994 				    IP_ADDR_LEN);
10995 				off1 += IP_ADDR_LEN;
10996 				off2 -= IP_ADDR_LEN;
10997 			}
10998 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
10999 			buf += optlen;
11000 			len += optlen;
11001 			break;
11002 		}
11003 	}
11004 done:
11005 	/* Pad the resulting options */
11006 	while (len & 0x3) {
11007 		*buf++ = IPOPT_EOL;
11008 		len++;
11009 	}
11010 	return (len);
11011 }
11012 
11013 
11014 /*
11015  * Extract and revert a source route from ipha (if any)
11016  * and then update the relevant fields in both tcp_t and the standard header.
11017  */
11018 static void
11019 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11020 {
11021 	char	buf[TCP_MAX_HDR_LENGTH];
11022 	uint_t	tcph_len;
11023 	int	len;
11024 
11025 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11026 	len = IPH_HDR_LENGTH(ipha);
11027 	if (len == IP_SIMPLE_HDR_LENGTH)
11028 		/* Nothing to do */
11029 		return;
11030 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11031 	    (len & 0x3))
11032 		return;
11033 
11034 	tcph_len = tcp->tcp_tcp_hdr_len;
11035 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11036 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11037 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11038 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11039 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11040 	len += IP_SIMPLE_HDR_LENGTH;
11041 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11042 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11043 	if ((int)tcp->tcp_sum < 0)
11044 		tcp->tcp_sum--;
11045 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11046 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11047 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11048 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11049 	tcp->tcp_ip_hdr_len = len;
11050 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11051 	    (IP_VERSION << 4) | (len >> 2);
11052 	len += tcph_len;
11053 	tcp->tcp_hdr_len = len;
11054 }
11055 
11056 /*
11057  * Copy the standard header into its new location,
11058  * lay in the new options and then update the relevant
11059  * fields in both tcp_t and the standard header.
11060  */
11061 static int
11062 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11063 {
11064 	uint_t	tcph_len;
11065 	uint8_t	*ip_optp;
11066 	tcph_t	*new_tcph;
11067 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11068 	conn_t	*connp = tcp->tcp_connp;
11069 
11070 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11071 		return (EINVAL);
11072 
11073 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11074 		return (EINVAL);
11075 
11076 	if (checkonly) {
11077 		/*
11078 		 * do not really set, just pretend to - T_CHECK
11079 		 */
11080 		return (0);
11081 	}
11082 
11083 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11084 	if (tcp->tcp_label_len > 0) {
11085 		int padlen;
11086 		uint8_t opt;
11087 
11088 		/* convert list termination to no-ops */
11089 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11090 		ip_optp += ip_optp[IPOPT_OLEN];
11091 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11092 		while (--padlen >= 0)
11093 			*ip_optp++ = opt;
11094 	}
11095 	tcph_len = tcp->tcp_tcp_hdr_len;
11096 	new_tcph = (tcph_t *)(ip_optp + len);
11097 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11098 	tcp->tcp_tcph = new_tcph;
11099 	bcopy(ptr, ip_optp, len);
11100 
11101 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11102 
11103 	tcp->tcp_ip_hdr_len = len;
11104 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11105 	    (IP_VERSION << 4) | (len >> 2);
11106 	tcp->tcp_hdr_len = len + tcph_len;
11107 	if (!TCP_IS_DETACHED(tcp)) {
11108 		/* Always allocate room for all options. */
11109 		(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
11110 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11111 	}
11112 	return (0);
11113 }
11114 
11115 /* Get callback routine passed to nd_load by tcp_param_register */
11116 /* ARGSUSED */
11117 static int
11118 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11119 {
11120 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11121 
11122 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11123 	return (0);
11124 }
11125 
11126 /*
11127  * Walk through the param array specified registering each element with the
11128  * named dispatch handler.
11129  */
11130 static boolean_t
11131 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11132 {
11133 	for (; cnt-- > 0; tcppa++) {
11134 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11135 			if (!nd_load(ndp, tcppa->tcp_param_name,
11136 			    tcp_param_get, tcp_param_set,
11137 			    (caddr_t)tcppa)) {
11138 				nd_free(ndp);
11139 				return (B_FALSE);
11140 			}
11141 		}
11142 	}
11143 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11144 	    KM_SLEEP);
11145 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11146 	    sizeof (tcpparam_t));
11147 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11148 	    tcp_param_get, tcp_param_set_aligned,
11149 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11150 		nd_free(ndp);
11151 		return (B_FALSE);
11152 	}
11153 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11154 	    KM_SLEEP);
11155 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11156 	    sizeof (tcpparam_t));
11157 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11158 	    tcp_param_get, tcp_param_set_aligned,
11159 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11160 		nd_free(ndp);
11161 		return (B_FALSE);
11162 	}
11163 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11164 	    KM_SLEEP);
11165 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11166 	    sizeof (tcpparam_t));
11167 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11168 	    tcp_param_get, tcp_param_set_aligned,
11169 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11170 		nd_free(ndp);
11171 		return (B_FALSE);
11172 	}
11173 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11174 	    KM_SLEEP);
11175 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11176 	    sizeof (tcpparam_t));
11177 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11178 	    tcp_param_get, tcp_param_set_aligned,
11179 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11180 		nd_free(ndp);
11181 		return (B_FALSE);
11182 	}
11183 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11184 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11185 		nd_free(ndp);
11186 		return (B_FALSE);
11187 	}
11188 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11189 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11190 		nd_free(ndp);
11191 		return (B_FALSE);
11192 	}
11193 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11194 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11195 		nd_free(ndp);
11196 		return (B_FALSE);
11197 	}
11198 	if (!nd_load(ndp, "tcp_status", tcp_status_report, NULL,
11199 	    NULL)) {
11200 		nd_free(ndp);
11201 		return (B_FALSE);
11202 	}
11203 	if (!nd_load(ndp, "tcp_bind_hash", tcp_bind_hash_report,
11204 	    NULL, NULL)) {
11205 		nd_free(ndp);
11206 		return (B_FALSE);
11207 	}
11208 	if (!nd_load(ndp, "tcp_listen_hash",
11209 	    tcp_listen_hash_report, NULL, NULL)) {
11210 		nd_free(ndp);
11211 		return (B_FALSE);
11212 	}
11213 	if (!nd_load(ndp, "tcp_conn_hash", tcp_conn_hash_report,
11214 	    NULL, NULL)) {
11215 		nd_free(ndp);
11216 		return (B_FALSE);
11217 	}
11218 	if (!nd_load(ndp, "tcp_acceptor_hash",
11219 	    tcp_acceptor_hash_report, NULL, NULL)) {
11220 		nd_free(ndp);
11221 		return (B_FALSE);
11222 	}
11223 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11224 	    tcp_1948_phrase_set, NULL)) {
11225 		nd_free(ndp);
11226 		return (B_FALSE);
11227 	}
11228 	/*
11229 	 * Dummy ndd variables - only to convey obsolescence information
11230 	 * through printing of their name (no get or set routines)
11231 	 * XXX Remove in future releases ?
11232 	 */
11233 	if (!nd_load(ndp,
11234 	    "tcp_close_wait_interval(obsoleted - "
11235 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11236 		nd_free(ndp);
11237 		return (B_FALSE);
11238 	}
11239 	return (B_TRUE);
11240 }
11241 
11242 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11243 /* ARGSUSED */
11244 static int
11245 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11246     cred_t *cr)
11247 {
11248 	long new_value;
11249 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11250 
11251 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11252 	    new_value < tcppa->tcp_param_min ||
11253 	    new_value > tcppa->tcp_param_max) {
11254 		return (EINVAL);
11255 	}
11256 	/*
11257 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11258 	 * round it up.  For future 64 bit requirement, we actually make it
11259 	 * a multiple of 8.
11260 	 */
11261 	if (new_value & 0x7) {
11262 		new_value = (new_value & ~0x7) + 0x8;
11263 	}
11264 	tcppa->tcp_param_val = new_value;
11265 	return (0);
11266 }
11267 
11268 /* Set callback routine passed to nd_load by tcp_param_register */
11269 /* ARGSUSED */
11270 static int
11271 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11272 {
11273 	long	new_value;
11274 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11275 
11276 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11277 	    new_value < tcppa->tcp_param_min ||
11278 	    new_value > tcppa->tcp_param_max) {
11279 		return (EINVAL);
11280 	}
11281 	tcppa->tcp_param_val = new_value;
11282 	return (0);
11283 }
11284 
11285 /*
11286  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11287  * is filled, return as much as we can.  The message passed in may be
11288  * multi-part, chained using b_cont.  "start" is the starting sequence
11289  * number for this piece.
11290  */
11291 static mblk_t *
11292 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11293 {
11294 	uint32_t	end;
11295 	mblk_t		*mp1;
11296 	mblk_t		*mp2;
11297 	mblk_t		*next_mp;
11298 	uint32_t	u1;
11299 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11300 
11301 	/* Walk through all the new pieces. */
11302 	do {
11303 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11304 		    (uintptr_t)INT_MAX);
11305 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11306 		next_mp = mp->b_cont;
11307 		if (start == end) {
11308 			/* Empty.  Blast it. */
11309 			freeb(mp);
11310 			continue;
11311 		}
11312 		mp->b_cont = NULL;
11313 		TCP_REASS_SET_SEQ(mp, start);
11314 		TCP_REASS_SET_END(mp, end);
11315 		mp1 = tcp->tcp_reass_tail;
11316 		if (!mp1) {
11317 			tcp->tcp_reass_tail = mp;
11318 			tcp->tcp_reass_head = mp;
11319 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11320 			UPDATE_MIB(&tcps->tcps_mib,
11321 			    tcpInDataUnorderBytes, end - start);
11322 			continue;
11323 		}
11324 		/* New stuff completely beyond tail? */
11325 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11326 			/* Link it on end. */
11327 			mp1->b_cont = mp;
11328 			tcp->tcp_reass_tail = mp;
11329 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11330 			UPDATE_MIB(&tcps->tcps_mib,
11331 			    tcpInDataUnorderBytes, end - start);
11332 			continue;
11333 		}
11334 		mp1 = tcp->tcp_reass_head;
11335 		u1 = TCP_REASS_SEQ(mp1);
11336 		/* New stuff at the front? */
11337 		if (SEQ_LT(start, u1)) {
11338 			/* Yes... Check for overlap. */
11339 			mp->b_cont = mp1;
11340 			tcp->tcp_reass_head = mp;
11341 			tcp_reass_elim_overlap(tcp, mp);
11342 			continue;
11343 		}
11344 		/*
11345 		 * The new piece fits somewhere between the head and tail.
11346 		 * We find our slot, where mp1 precedes us and mp2 trails.
11347 		 */
11348 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11349 			u1 = TCP_REASS_SEQ(mp2);
11350 			if (SEQ_LEQ(start, u1))
11351 				break;
11352 		}
11353 		/* Link ourselves in */
11354 		mp->b_cont = mp2;
11355 		mp1->b_cont = mp;
11356 
11357 		/* Trim overlap with following mblk(s) first */
11358 		tcp_reass_elim_overlap(tcp, mp);
11359 
11360 		/* Trim overlap with preceding mblk */
11361 		tcp_reass_elim_overlap(tcp, mp1);
11362 
11363 	} while (start = end, mp = next_mp);
11364 	mp1 = tcp->tcp_reass_head;
11365 	/* Anything ready to go? */
11366 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11367 		return (NULL);
11368 	/* Eat what we can off the queue */
11369 	for (;;) {
11370 		mp = mp1->b_cont;
11371 		end = TCP_REASS_END(mp1);
11372 		TCP_REASS_SET_SEQ(mp1, 0);
11373 		TCP_REASS_SET_END(mp1, 0);
11374 		if (!mp) {
11375 			tcp->tcp_reass_tail = NULL;
11376 			break;
11377 		}
11378 		if (end != TCP_REASS_SEQ(mp)) {
11379 			mp1->b_cont = NULL;
11380 			break;
11381 		}
11382 		mp1 = mp;
11383 	}
11384 	mp1 = tcp->tcp_reass_head;
11385 	tcp->tcp_reass_head = mp;
11386 	return (mp1);
11387 }
11388 
11389 /* Eliminate any overlap that mp may have over later mblks */
11390 static void
11391 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11392 {
11393 	uint32_t	end;
11394 	mblk_t		*mp1;
11395 	uint32_t	u1;
11396 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11397 
11398 	end = TCP_REASS_END(mp);
11399 	while ((mp1 = mp->b_cont) != NULL) {
11400 		u1 = TCP_REASS_SEQ(mp1);
11401 		if (!SEQ_GT(end, u1))
11402 			break;
11403 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11404 			mp->b_wptr -= end - u1;
11405 			TCP_REASS_SET_END(mp, u1);
11406 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11407 			UPDATE_MIB(&tcps->tcps_mib,
11408 			    tcpInDataPartDupBytes, end - u1);
11409 			break;
11410 		}
11411 		mp->b_cont = mp1->b_cont;
11412 		TCP_REASS_SET_SEQ(mp1, 0);
11413 		TCP_REASS_SET_END(mp1, 0);
11414 		freeb(mp1);
11415 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11416 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11417 	}
11418 	if (!mp1)
11419 		tcp->tcp_reass_tail = mp;
11420 }
11421 
11422 static uint_t
11423 tcp_rwnd_reopen(tcp_t *tcp)
11424 {
11425 	uint_t ret = 0;
11426 	uint_t thwin;
11427 
11428 	/* Learn the latest rwnd information that we sent to the other side. */
11429 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11430 	    << tcp->tcp_rcv_ws;
11431 	/* This is peer's calculated send window (our receive window). */
11432 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11433 	/*
11434 	 * Increase the receive window to max.  But we need to do receiver
11435 	 * SWS avoidance.  This means that we need to check the increase of
11436 	 * of receive window is at least 1 MSS.
11437 	 */
11438 	if (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss) {
11439 		/*
11440 		 * If the window that the other side knows is less than max
11441 		 * deferred acks segments, send an update immediately.
11442 		 */
11443 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11444 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
11445 			ret = TH_ACK_NEEDED;
11446 		}
11447 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
11448 	}
11449 	return (ret);
11450 }
11451 
11452 /*
11453  * Send up all messages queued on tcp_rcv_list.
11454  */
11455 static uint_t
11456 tcp_rcv_drain(tcp_t *tcp)
11457 {
11458 	mblk_t *mp;
11459 	uint_t ret = 0;
11460 #ifdef DEBUG
11461 	uint_t cnt = 0;
11462 #endif
11463 	queue_t	*q = tcp->tcp_rq;
11464 
11465 	/* Can't drain on an eager connection */
11466 	if (tcp->tcp_listener != NULL)
11467 		return (ret);
11468 
11469 	/* Can't be a non-STREAMS connection or sodirect enabled */
11470 	ASSERT((!IPCL_IS_NONSTR(tcp->tcp_connp)) && SOD_NOT_ENABLED(tcp));
11471 
11472 	/* No need for the push timer now. */
11473 	if (tcp->tcp_push_tid != 0) {
11474 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11475 		tcp->tcp_push_tid = 0;
11476 	}
11477 
11478 	/*
11479 	 * Handle two cases here: we are currently fused or we were
11480 	 * previously fused and have some urgent data to be delivered
11481 	 * upstream.  The latter happens because we either ran out of
11482 	 * memory or were detached and therefore sending the SIGURG was
11483 	 * deferred until this point.  In either case we pass control
11484 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11485 	 * some work.
11486 	 */
11487 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11488 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
11489 		    tcp->tcp_fused_sigurg_mp != NULL);
11490 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11491 		    &tcp->tcp_fused_sigurg_mp))
11492 			return (ret);
11493 	}
11494 
11495 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11496 		tcp->tcp_rcv_list = mp->b_next;
11497 		mp->b_next = NULL;
11498 #ifdef DEBUG
11499 		cnt += msgdsize(mp);
11500 #endif
11501 		/* Does this need SSL processing first? */
11502 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11503 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11504 			    mblk_t *, mp);
11505 			tcp_kssl_input(tcp, mp);
11506 			continue;
11507 		}
11508 		putnext(q, mp);
11509 	}
11510 #ifdef DEBUG
11511 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11512 #endif
11513 	tcp->tcp_rcv_last_head = NULL;
11514 	tcp->tcp_rcv_last_tail = NULL;
11515 	tcp->tcp_rcv_cnt = 0;
11516 
11517 	if (canputnext(q))
11518 		return (tcp_rwnd_reopen(tcp));
11519 
11520 	return (ret);
11521 }
11522 
11523 /*
11524  * Queue data on tcp_rcv_list which is a b_next chain.
11525  * tcp_rcv_last_head/tail is the last element of this chain.
11526  * Each element of the chain is a b_cont chain.
11527  *
11528  * M_DATA messages are added to the current element.
11529  * Other messages are added as new (b_next) elements.
11530  */
11531 void
11532 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11533 {
11534 	ASSERT(seg_len == msgdsize(mp));
11535 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11536 
11537 	if (tcp->tcp_rcv_list == NULL) {
11538 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11539 		tcp->tcp_rcv_list = mp;
11540 		tcp->tcp_rcv_last_head = mp;
11541 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11542 		tcp->tcp_rcv_last_tail->b_cont = mp;
11543 	} else {
11544 		tcp->tcp_rcv_last_head->b_next = mp;
11545 		tcp->tcp_rcv_last_head = mp;
11546 	}
11547 
11548 	while (mp->b_cont)
11549 		mp = mp->b_cont;
11550 
11551 	tcp->tcp_rcv_last_tail = mp;
11552 	tcp->tcp_rcv_cnt += seg_len;
11553 	tcp->tcp_rwnd -= seg_len;
11554 }
11555 
11556 /*
11557  * The tcp_rcv_sod_XXX() functions enqueue data directly to the socket
11558  * above, in addition when uioa is enabled schedule an asynchronous uio
11559  * prior to enqueuing. They implement the combinhed semantics of the
11560  * tcp_rcv_XXX() functions, tcp_rcv_list push logic, and STREAMS putnext()
11561  * canputnext(), i.e. flow-control with backenable.
11562  *
11563  * tcp_sod_wakeup() is called where tcp_rcv_drain() would be called in the
11564  * non sodirect connection but as there are no tcp_tcv_list mblk_t's we deal
11565  * with the rcv_wnd and push timer and call the sodirect wakeup function.
11566  *
11567  * Must be called with sodp->sod_lockp held and will return with the lock
11568  * released.
11569  */
11570 static uint_t
11571 tcp_rcv_sod_wakeup(tcp_t *tcp, sodirect_t *sodp)
11572 {
11573 	queue_t		*q = tcp->tcp_rq;
11574 	uint_t		thwin;
11575 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11576 	uint_t		ret = 0;
11577 
11578 	/* Can't be an eager connection */
11579 	ASSERT(tcp->tcp_listener == NULL);
11580 
11581 	/* Caller must have lock held */
11582 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11583 
11584 	/* Sodirect mode so must not be a tcp_rcv_list */
11585 	ASSERT(tcp->tcp_rcv_list == NULL);
11586 
11587 	if (SOD_QFULL(sodp)) {
11588 		/* Q is full, mark Q for need backenable */
11589 		SOD_QSETBE(sodp);
11590 	}
11591 	/* Last advertised rwnd, i.e. rwnd last sent in a packet */
11592 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11593 	    << tcp->tcp_rcv_ws;
11594 	/* This is peer's calculated send window (our available rwnd). */
11595 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11596 	/*
11597 	 * Increase the receive window to max.  But we need to do receiver
11598 	 * SWS avoidance.  This means that we need to check the increase of
11599 	 * of receive window is at least 1 MSS.
11600 	 */
11601 	if (!SOD_QFULL(sodp) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11602 		/*
11603 		 * If the window that the other side knows is less than max
11604 		 * deferred acks segments, send an update immediately.
11605 		 */
11606 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11607 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11608 			ret = TH_ACK_NEEDED;
11609 		}
11610 		tcp->tcp_rwnd = q->q_hiwat;
11611 	}
11612 
11613 	if (!SOD_QEMPTY(sodp)) {
11614 		/* Wakeup to socket */
11615 		sodp->sod_state &= SOD_WAKE_CLR;
11616 		sodp->sod_state |= SOD_WAKE_DONE;
11617 		(sodp->sod_wakeup)(sodp);
11618 		/* wakeup() does the mutex_ext() */
11619 	} else {
11620 		/* Q is empty, no need to wake */
11621 		sodp->sod_state &= SOD_WAKE_CLR;
11622 		sodp->sod_state |= SOD_WAKE_NOT;
11623 		mutex_exit(sodp->sod_lockp);
11624 	}
11625 
11626 	/* No need for the push timer now. */
11627 	if (tcp->tcp_push_tid != 0) {
11628 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11629 		tcp->tcp_push_tid = 0;
11630 	}
11631 
11632 	return (ret);
11633 }
11634 
11635 /*
11636  * Called where tcp_rcv_enqueue()/putnext(RD(q)) would be. For M_DATA
11637  * mblk_t's if uioa enabled then start a uioa asynchronous copy directly
11638  * to the user-land buffer and flag the mblk_t as such.
11639  *
11640  * Also, handle tcp_rwnd.
11641  */
11642 uint_t
11643 tcp_rcv_sod_enqueue(tcp_t *tcp, sodirect_t *sodp, mblk_t *mp, uint_t seg_len)
11644 {
11645 	uioa_t		*uioap = &sodp->sod_uioa;
11646 	boolean_t	qfull;
11647 	uint_t		thwin;
11648 
11649 	/* Can't be an eager connection */
11650 	ASSERT(tcp->tcp_listener == NULL);
11651 
11652 	/* Caller must have lock held */
11653 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11654 
11655 	/* Sodirect mode so must not be a tcp_rcv_list */
11656 	ASSERT(tcp->tcp_rcv_list == NULL);
11657 
11658 	/* Passed in segment length must be equal to mblk_t chain data size */
11659 	ASSERT(seg_len == msgdsize(mp));
11660 
11661 	if (DB_TYPE(mp) != M_DATA) {
11662 		/* Only process M_DATA mblk_t's */
11663 		goto enq;
11664 	}
11665 	if (uioap->uioa_state & UIOA_ENABLED) {
11666 		/* Uioa is enabled */
11667 		mblk_t		*mp1 = mp;
11668 		mblk_t		*lmp = NULL;
11669 
11670 		if (seg_len > uioap->uio_resid) {
11671 			/*
11672 			 * There isn't enough uio space for the mblk_t chain
11673 			 * so disable uioa such that this and any additional
11674 			 * mblk_t data is handled by the socket and schedule
11675 			 * the socket for wakeup to finish this uioa.
11676 			 */
11677 			uioap->uioa_state &= UIOA_CLR;
11678 			uioap->uioa_state |= UIOA_FINI;
11679 			if (sodp->sod_state & SOD_WAKE_NOT) {
11680 				sodp->sod_state &= SOD_WAKE_CLR;
11681 				sodp->sod_state |= SOD_WAKE_NEED;
11682 			}
11683 			goto enq;
11684 		}
11685 		do {
11686 			uint32_t	len = MBLKL(mp1);
11687 
11688 			if (!uioamove(mp1->b_rptr, len, UIO_READ, uioap)) {
11689 				/* Scheduled, mark dblk_t as such */
11690 				DB_FLAGS(mp1) |= DBLK_UIOA;
11691 			} else {
11692 				/* Error, turn off async processing */
11693 				uioap->uioa_state &= UIOA_CLR;
11694 				uioap->uioa_state |= UIOA_FINI;
11695 				break;
11696 			}
11697 			lmp = mp1;
11698 		} while ((mp1 = mp1->b_cont) != NULL);
11699 
11700 		if (mp1 != NULL || uioap->uio_resid == 0) {
11701 			/*
11702 			 * Not all mblk_t(s) uioamoved (error) or all uio
11703 			 * space has been consumed so schedule the socket
11704 			 * for wakeup to finish this uio.
11705 			 */
11706 			sodp->sod_state &= SOD_WAKE_CLR;
11707 			sodp->sod_state |= SOD_WAKE_NEED;
11708 
11709 			/* Break the mblk chain if neccessary. */
11710 			if (mp1 != NULL && lmp != NULL) {
11711 				mp->b_next = mp1;
11712 				lmp->b_cont = NULL;
11713 			}
11714 		}
11715 	} else if (uioap->uioa_state & UIOA_FINI) {
11716 		/*
11717 		 * Post UIO_ENABLED waiting for socket to finish processing
11718 		 * so just enqueue and update tcp_rwnd.
11719 		 */
11720 		if (SOD_QFULL(sodp))
11721 			tcp->tcp_rwnd -= seg_len;
11722 	} else if (sodp->sod_want > 0) {
11723 		/*
11724 		 * Uioa isn't enabled but sodirect has a pending read().
11725 		 */
11726 		if (SOD_QCNT(sodp) + seg_len >= sodp->sod_want) {
11727 			if (sodp->sod_state & SOD_WAKE_NOT) {
11728 				/* Schedule socket for wakeup */
11729 				sodp->sod_state &= SOD_WAKE_CLR;
11730 				sodp->sod_state |= SOD_WAKE_NEED;
11731 			}
11732 			tcp->tcp_rwnd -= seg_len;
11733 		}
11734 	} else if (SOD_QCNT(sodp) + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
11735 		/*
11736 		 * No pending sodirect read() so used the default
11737 		 * TCP push logic to guess that a push is needed.
11738 		 */
11739 		if (sodp->sod_state & SOD_WAKE_NOT) {
11740 			/* Schedule socket for wakeup */
11741 			sodp->sod_state &= SOD_WAKE_CLR;
11742 			sodp->sod_state |= SOD_WAKE_NEED;
11743 		}
11744 		tcp->tcp_rwnd -= seg_len;
11745 	} else {
11746 		/* Just update tcp_rwnd */
11747 		tcp->tcp_rwnd -= seg_len;
11748 	}
11749 enq:
11750 	qfull = SOD_QFULL(sodp);
11751 
11752 	(sodp->sod_enqueue)(sodp, mp);
11753 
11754 	if (! qfull && SOD_QFULL(sodp)) {
11755 		/* Wasn't QFULL, now QFULL, need back-enable */
11756 		SOD_QSETBE(sodp);
11757 	}
11758 
11759 	/*
11760 	 * Check to see if remote avail swnd < mss due to delayed ACK,
11761 	 * first get advertised rwnd.
11762 	 */
11763 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win));
11764 	/* Minus delayed ACK count */
11765 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11766 	if (thwin < tcp->tcp_mss) {
11767 		/* Remote avail swnd < mss, need ACK now */
11768 		return (TH_ACK_NEEDED);
11769 	}
11770 
11771 	return (0);
11772 }
11773 
11774 /*
11775  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11776  *
11777  * This is the default entry function into TCP on the read side. TCP is
11778  * always entered via squeue i.e. using squeue's for mutual exclusion.
11779  * When classifier does a lookup to find the tcp, it also puts a reference
11780  * on the conn structure associated so the tcp is guaranteed to exist
11781  * when we come here. We still need to check the state because it might
11782  * as well has been closed. The squeue processing function i.e. squeue_enter,
11783  * is responsible for doing the CONN_DEC_REF.
11784  *
11785  * Apart from the default entry point, IP also sends packets directly to
11786  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11787  * connections.
11788  */
11789 boolean_t tcp_outbound_squeue_switch = B_FALSE;
11790 void
11791 tcp_input(void *arg, mblk_t *mp, void *arg2)
11792 {
11793 	conn_t	*connp = (conn_t *)arg;
11794 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11795 
11796 	/* arg2 is the sqp */
11797 	ASSERT(arg2 != NULL);
11798 	ASSERT(mp != NULL);
11799 
11800 	/*
11801 	 * Don't accept any input on a closed tcp as this TCP logically does
11802 	 * not exist on the system. Don't proceed further with this TCP.
11803 	 * For eg. this packet could trigger another close of this tcp
11804 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11805 	 * tcp_clean_death / tcp_closei_local must be called at most once
11806 	 * on a TCP. In this case we need to refeed the packet into the
11807 	 * classifier and figure out where the packet should go. Need to
11808 	 * preserve the recv_ill somehow. Until we figure that out, for
11809 	 * now just drop the packet if we can't classify the packet.
11810 	 */
11811 	if (tcp->tcp_state == TCPS_CLOSED ||
11812 	    tcp->tcp_state == TCPS_BOUND) {
11813 		conn_t	*new_connp;
11814 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11815 
11816 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11817 		if (new_connp != NULL) {
11818 			tcp_reinput(new_connp, mp, arg2);
11819 			return;
11820 		}
11821 		/* We failed to classify. For now just drop the packet */
11822 		freemsg(mp);
11823 		return;
11824 	}
11825 
11826 	if (DB_TYPE(mp) != M_DATA) {
11827 		tcp_rput_common(tcp, mp);
11828 		return;
11829 	}
11830 
11831 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
11832 		squeue_t	*final_sqp;
11833 
11834 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
11835 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
11836 		DB_CKSUMSTART(mp) = 0;
11837 		if (tcp->tcp_state == TCPS_SYN_SENT &&
11838 		    connp->conn_final_sqp == NULL &&
11839 		    tcp_outbound_squeue_switch) {
11840 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
11841 			connp->conn_final_sqp = final_sqp;
11842 			if (connp->conn_final_sqp != connp->conn_sqp) {
11843 				CONN_INC_REF(connp);
11844 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
11845 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
11846 				    tcp_rput_data, connp, ip_squeue_flag,
11847 				    SQTAG_CONNECT_FINISH);
11848 				return;
11849 			}
11850 		}
11851 	}
11852 	tcp_rput_data(connp, mp, arg2);
11853 }
11854 
11855 /*
11856  * The read side put procedure.
11857  * The packets passed up by ip are assume to be aligned according to
11858  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11859  */
11860 static void
11861 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11862 {
11863 	/*
11864 	 * tcp_rput_data() does not expect M_CTL except for the case
11865 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11866 	 * type. Need to make sure that any other M_CTLs don't make
11867 	 * it to tcp_rput_data since it is not expecting any and doesn't
11868 	 * check for it.
11869 	 */
11870 	if (DB_TYPE(mp) == M_CTL) {
11871 		switch (*(uint32_t *)(mp->b_rptr)) {
11872 		case TCP_IOC_ABORT_CONN:
11873 			/*
11874 			 * Handle connection abort request.
11875 			 */
11876 			tcp_ioctl_abort_handler(tcp, mp);
11877 			return;
11878 		case IPSEC_IN:
11879 			/*
11880 			 * Only secure icmp arrive in TCP and they
11881 			 * don't go through data path.
11882 			 */
11883 			tcp_icmp_error(tcp, mp);
11884 			return;
11885 		case IN_PKTINFO:
11886 			/*
11887 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11888 			 * sockets that are receiving IPv4 traffic. tcp
11889 			 */
11890 			ASSERT(tcp->tcp_family == AF_INET6);
11891 			ASSERT(tcp->tcp_ipv6_recvancillary &
11892 			    TCP_IPV6_RECVPKTINFO);
11893 			tcp_rput_data(tcp->tcp_connp, mp,
11894 			    tcp->tcp_connp->conn_sqp);
11895 			return;
11896 		case MDT_IOC_INFO_UPDATE:
11897 			/*
11898 			 * Handle Multidata information update; the
11899 			 * following routine will free the message.
11900 			 */
11901 			if (tcp->tcp_connp->conn_mdt_ok) {
11902 				tcp_mdt_update(tcp,
11903 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11904 				    B_FALSE);
11905 			}
11906 			freemsg(mp);
11907 			return;
11908 		case LSO_IOC_INFO_UPDATE:
11909 			/*
11910 			 * Handle LSO information update; the following
11911 			 * routine will free the message.
11912 			 */
11913 			if (tcp->tcp_connp->conn_lso_ok) {
11914 				tcp_lso_update(tcp,
11915 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11916 			}
11917 			freemsg(mp);
11918 			return;
11919 		default:
11920 			/*
11921 			 * tcp_icmp_err() will process the M_CTL packets.
11922 			 * Non-ICMP packets, if any, will be discarded in
11923 			 * tcp_icmp_err(). We will process the ICMP packet
11924 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11925 			 * incoming ICMP packet may result in changing
11926 			 * the tcp_mss, which we would need if we have
11927 			 * packets to retransmit.
11928 			 */
11929 			tcp_icmp_error(tcp, mp);
11930 			return;
11931 		}
11932 	}
11933 
11934 	/* No point processing the message if tcp is already closed */
11935 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11936 		freemsg(mp);
11937 		return;
11938 	}
11939 
11940 	tcp_rput_other(tcp, mp);
11941 }
11942 
11943 
11944 /* The minimum of smoothed mean deviation in RTO calculation. */
11945 #define	TCP_SD_MIN	400
11946 
11947 /*
11948  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11949  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11950  * are the same as those in Appendix A.2 of that paper.
11951  *
11952  * m = new measurement
11953  * sa = smoothed RTT average (8 * average estimates).
11954  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11955  */
11956 static void
11957 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11958 {
11959 	long m = TICK_TO_MSEC(rtt);
11960 	clock_t sa = tcp->tcp_rtt_sa;
11961 	clock_t sv = tcp->tcp_rtt_sd;
11962 	clock_t rto;
11963 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11964 
11965 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11966 	tcp->tcp_rtt_update++;
11967 
11968 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11969 	if (sa != 0) {
11970 		/*
11971 		 * Update average estimator:
11972 		 *	new rtt = 7/8 old rtt + 1/8 Error
11973 		 */
11974 
11975 		/* m is now Error in estimate. */
11976 		m -= sa >> 3;
11977 		if ((sa += m) <= 0) {
11978 			/*
11979 			 * Don't allow the smoothed average to be negative.
11980 			 * We use 0 to denote reinitialization of the
11981 			 * variables.
11982 			 */
11983 			sa = 1;
11984 		}
11985 
11986 		/*
11987 		 * Update deviation estimator:
11988 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11989 		 */
11990 		if (m < 0)
11991 			m = -m;
11992 		m -= sv >> 2;
11993 		sv += m;
11994 	} else {
11995 		/*
11996 		 * This follows BSD's implementation.  So the reinitialized
11997 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11998 		 * link is bandwidth dominated, doubling the window size
11999 		 * during slow start means doubling the RTT.  We want to be
12000 		 * more conservative when we reinitialize our estimates.  3
12001 		 * is just a convenient number.
12002 		 */
12003 		sa = m << 3;
12004 		sv = m << 1;
12005 	}
12006 	if (sv < TCP_SD_MIN) {
12007 		/*
12008 		 * We do not know that if sa captures the delay ACK
12009 		 * effect as in a long train of segments, a receiver
12010 		 * does not delay its ACKs.  So set the minimum of sv
12011 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
12012 		 * of BSD DATO.  That means the minimum of mean
12013 		 * deviation is 100 ms.
12014 		 *
12015 		 */
12016 		sv = TCP_SD_MIN;
12017 	}
12018 	tcp->tcp_rtt_sa = sa;
12019 	tcp->tcp_rtt_sd = sv;
12020 	/*
12021 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
12022 	 *
12023 	 * Add tcp_rexmit_interval extra in case of extreme environment
12024 	 * where the algorithm fails to work.  The default value of
12025 	 * tcp_rexmit_interval_extra should be 0.
12026 	 *
12027 	 * As we use a finer grained clock than BSD and update
12028 	 * RTO for every ACKs, add in another .25 of RTT to the
12029 	 * deviation of RTO to accomodate burstiness of 1/4 of
12030 	 * window size.
12031 	 */
12032 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
12033 
12034 	if (rto > tcps->tcps_rexmit_interval_max) {
12035 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
12036 	} else if (rto < tcps->tcps_rexmit_interval_min) {
12037 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
12038 	} else {
12039 		tcp->tcp_rto = rto;
12040 	}
12041 
12042 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12043 	tcp->tcp_timer_backoff = 0;
12044 }
12045 
12046 /*
12047  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12048  * send queue which starts at the given seq. no.
12049  *
12050  * Parameters:
12051  *	tcp_t *tcp: the tcp instance pointer.
12052  *	uint32_t seq: the starting seq. no of the requested segment.
12053  *	int32_t *off: after the execution, *off will be the offset to
12054  *		the returned mblk which points to the requested seq no.
12055  *		It is the caller's responsibility to send in a non-null off.
12056  *
12057  * Return:
12058  *	A mblk_t pointer pointing to the requested segment in send queue.
12059  */
12060 static mblk_t *
12061 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12062 {
12063 	int32_t	cnt;
12064 	mblk_t	*mp;
12065 
12066 	/* Defensive coding.  Make sure we don't send incorrect data. */
12067 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12068 		return (NULL);
12069 
12070 	cnt = seq - tcp->tcp_suna;
12071 	mp = tcp->tcp_xmit_head;
12072 	while (cnt > 0 && mp != NULL) {
12073 		cnt -= mp->b_wptr - mp->b_rptr;
12074 		if (cnt < 0) {
12075 			cnt += mp->b_wptr - mp->b_rptr;
12076 			break;
12077 		}
12078 		mp = mp->b_cont;
12079 	}
12080 	ASSERT(mp != NULL);
12081 	*off = cnt;
12082 	return (mp);
12083 }
12084 
12085 /*
12086  * This function handles all retransmissions if SACK is enabled for this
12087  * connection.  First it calculates how many segments can be retransmitted
12088  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12089  * segments.  A segment is eligible if sack_cnt for that segment is greater
12090  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12091  * all eligible segments, it checks to see if TCP can send some new segments
12092  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12093  *
12094  * Parameters:
12095  *	tcp_t *tcp: the tcp structure of the connection.
12096  *	uint_t *flags: in return, appropriate value will be set for
12097  *	tcp_rput_data().
12098  */
12099 static void
12100 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12101 {
12102 	notsack_blk_t	*notsack_blk;
12103 	int32_t		usable_swnd;
12104 	int32_t		mss;
12105 	uint32_t	seg_len;
12106 	mblk_t		*xmit_mp;
12107 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12108 
12109 	ASSERT(tcp->tcp_sack_info != NULL);
12110 	ASSERT(tcp->tcp_notsack_list != NULL);
12111 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12112 
12113 	/* Defensive coding in case there is a bug... */
12114 	if (tcp->tcp_notsack_list == NULL) {
12115 		return;
12116 	}
12117 	notsack_blk = tcp->tcp_notsack_list;
12118 	mss = tcp->tcp_mss;
12119 
12120 	/*
12121 	 * Limit the num of outstanding data in the network to be
12122 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12123 	 */
12124 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12125 
12126 	/* At least retransmit 1 MSS of data. */
12127 	if (usable_swnd <= 0) {
12128 		usable_swnd = mss;
12129 	}
12130 
12131 	/* Make sure no new RTT samples will be taken. */
12132 	tcp->tcp_csuna = tcp->tcp_snxt;
12133 
12134 	notsack_blk = tcp->tcp_notsack_list;
12135 	while (usable_swnd > 0) {
12136 		mblk_t		*snxt_mp, *tmp_mp;
12137 		tcp_seq		begin = tcp->tcp_sack_snxt;
12138 		tcp_seq		end;
12139 		int32_t		off;
12140 
12141 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12142 			if (SEQ_GT(notsack_blk->end, begin) &&
12143 			    (notsack_blk->sack_cnt >=
12144 			    tcps->tcps_dupack_fast_retransmit)) {
12145 				end = notsack_blk->end;
12146 				if (SEQ_LT(begin, notsack_blk->begin)) {
12147 					begin = notsack_blk->begin;
12148 				}
12149 				break;
12150 			}
12151 		}
12152 		/*
12153 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12154 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12155 		 * set to tcp_cwnd_ssthresh.
12156 		 */
12157 		if (notsack_blk == NULL) {
12158 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12159 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12160 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12161 				ASSERT(tcp->tcp_cwnd > 0);
12162 				return;
12163 			} else {
12164 				usable_swnd = usable_swnd / mss;
12165 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12166 				    MAX(usable_swnd * mss, mss);
12167 				*flags |= TH_XMIT_NEEDED;
12168 				return;
12169 			}
12170 		}
12171 
12172 		/*
12173 		 * Note that we may send more than usable_swnd allows here
12174 		 * because of round off, but no more than 1 MSS of data.
12175 		 */
12176 		seg_len = end - begin;
12177 		if (seg_len > mss)
12178 			seg_len = mss;
12179 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12180 		ASSERT(snxt_mp != NULL);
12181 		/* This should not happen.  Defensive coding again... */
12182 		if (snxt_mp == NULL) {
12183 			return;
12184 		}
12185 
12186 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12187 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12188 		if (xmit_mp == NULL)
12189 			return;
12190 
12191 		usable_swnd -= seg_len;
12192 		tcp->tcp_pipe += seg_len;
12193 		tcp->tcp_sack_snxt = begin + seg_len;
12194 
12195 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12196 
12197 		/*
12198 		 * Update the send timestamp to avoid false retransmission.
12199 		 */
12200 		snxt_mp->b_prev = (mblk_t *)lbolt;
12201 
12202 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12203 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12204 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12205 		/*
12206 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12207 		 * This happens when new data sent during fast recovery is
12208 		 * also lost.  If TCP retransmits those new data, it needs
12209 		 * to extend SACK recover phase to avoid starting another
12210 		 * fast retransmit/recovery unnecessarily.
12211 		 */
12212 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12213 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12214 		}
12215 	}
12216 }
12217 
12218 /*
12219  * This function handles policy checking at TCP level for non-hard_bound/
12220  * detached connections.
12221  */
12222 static boolean_t
12223 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12224     boolean_t secure, boolean_t mctl_present)
12225 {
12226 	ipsec_latch_t *ipl = NULL;
12227 	ipsec_action_t *act = NULL;
12228 	mblk_t *data_mp;
12229 	ipsec_in_t *ii;
12230 	const char *reason;
12231 	kstat_named_t *counter;
12232 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12233 	ipsec_stack_t	*ipss;
12234 	ip_stack_t	*ipst;
12235 
12236 	ASSERT(mctl_present || !secure);
12237 
12238 	ASSERT((ipha == NULL && ip6h != NULL) ||
12239 	    (ip6h == NULL && ipha != NULL));
12240 
12241 	/*
12242 	 * We don't necessarily have an ipsec_in_act action to verify
12243 	 * policy because of assymetrical policy where we have only
12244 	 * outbound policy and no inbound policy (possible with global
12245 	 * policy).
12246 	 */
12247 	if (!secure) {
12248 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12249 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12250 			return (B_TRUE);
12251 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12252 		    "tcp_check_policy", ipha, ip6h, secure,
12253 		    tcps->tcps_netstack);
12254 		ipss = tcps->tcps_netstack->netstack_ipsec;
12255 
12256 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12257 		    DROPPER(ipss, ipds_tcp_clear),
12258 		    &tcps->tcps_dropper);
12259 		return (B_FALSE);
12260 	}
12261 
12262 	/*
12263 	 * We have a secure packet.
12264 	 */
12265 	if (act == NULL) {
12266 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12267 		    "tcp_check_policy", ipha, ip6h, secure,
12268 		    tcps->tcps_netstack);
12269 		ipss = tcps->tcps_netstack->netstack_ipsec;
12270 
12271 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12272 		    DROPPER(ipss, ipds_tcp_secure),
12273 		    &tcps->tcps_dropper);
12274 		return (B_FALSE);
12275 	}
12276 
12277 	/*
12278 	 * XXX This whole routine is currently incorrect.  ipl should
12279 	 * be set to the latch pointer, but is currently not set, so
12280 	 * we initialize it to NULL to avoid picking up random garbage.
12281 	 */
12282 	if (ipl == NULL)
12283 		return (B_TRUE);
12284 
12285 	data_mp = first_mp->b_cont;
12286 
12287 	ii = (ipsec_in_t *)first_mp->b_rptr;
12288 
12289 	ipst = tcps->tcps_netstack->netstack_ip;
12290 
12291 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12292 	    &counter, tcp->tcp_connp)) {
12293 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12294 		return (B_TRUE);
12295 	}
12296 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12297 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12298 	    reason);
12299 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12300 
12301 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12302 	    &tcps->tcps_dropper);
12303 	return (B_FALSE);
12304 }
12305 
12306 /*
12307  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12308  * retransmission after a timeout.
12309  *
12310  * To limit the number of duplicate segments, we limit the number of segment
12311  * to be sent in one time to tcp_snd_burst, the burst variable.
12312  */
12313 static void
12314 tcp_ss_rexmit(tcp_t *tcp)
12315 {
12316 	uint32_t	snxt;
12317 	uint32_t	smax;
12318 	int32_t		win;
12319 	int32_t		mss;
12320 	int32_t		off;
12321 	int32_t		burst = tcp->tcp_snd_burst;
12322 	mblk_t		*snxt_mp;
12323 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12324 
12325 	/*
12326 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12327 	 * all unack'ed segments.
12328 	 */
12329 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12330 		smax = tcp->tcp_rexmit_max;
12331 		snxt = tcp->tcp_rexmit_nxt;
12332 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12333 			snxt = tcp->tcp_suna;
12334 		}
12335 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12336 		win -= snxt - tcp->tcp_suna;
12337 		mss = tcp->tcp_mss;
12338 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12339 
12340 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12341 		    (burst > 0) && (snxt_mp != NULL)) {
12342 			mblk_t	*xmit_mp;
12343 			mblk_t	*old_snxt_mp = snxt_mp;
12344 			uint32_t cnt = mss;
12345 
12346 			if (win < cnt) {
12347 				cnt = win;
12348 			}
12349 			if (SEQ_GT(snxt + cnt, smax)) {
12350 				cnt = smax - snxt;
12351 			}
12352 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12353 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12354 			if (xmit_mp == NULL)
12355 				return;
12356 
12357 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12358 
12359 			snxt += cnt;
12360 			win -= cnt;
12361 			/*
12362 			 * Update the send timestamp to avoid false
12363 			 * retransmission.
12364 			 */
12365 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12366 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12367 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12368 
12369 			tcp->tcp_rexmit_nxt = snxt;
12370 			burst--;
12371 		}
12372 		/*
12373 		 * If we have transmitted all we have at the time
12374 		 * we started the retranmission, we can leave
12375 		 * the rest of the job to tcp_wput_data().  But we
12376 		 * need to check the send window first.  If the
12377 		 * win is not 0, go on with tcp_wput_data().
12378 		 */
12379 		if (SEQ_LT(snxt, smax) || win == 0) {
12380 			return;
12381 		}
12382 	}
12383 	/* Only call tcp_wput_data() if there is data to be sent. */
12384 	if (tcp->tcp_unsent) {
12385 		tcp_wput_data(tcp, NULL, B_FALSE);
12386 	}
12387 }
12388 
12389 /*
12390  * Process all TCP option in SYN segment.  Note that this function should
12391  * be called after tcp_adapt_ire() is called so that the necessary info
12392  * from IRE is already set in the tcp structure.
12393  *
12394  * This function sets up the correct tcp_mss value according to the
12395  * MSS option value and our header size.  It also sets up the window scale
12396  * and timestamp values, and initialize SACK info blocks.  But it does not
12397  * change receive window size after setting the tcp_mss value.  The caller
12398  * should do the appropriate change.
12399  */
12400 void
12401 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12402 {
12403 	int options;
12404 	tcp_opt_t tcpopt;
12405 	uint32_t mss_max;
12406 	char *tmp_tcph;
12407 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12408 
12409 	tcpopt.tcp = NULL;
12410 	options = tcp_parse_options(tcph, &tcpopt);
12411 
12412 	/*
12413 	 * Process MSS option.  Note that MSS option value does not account
12414 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12415 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12416 	 * IPv6.
12417 	 */
12418 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12419 		if (tcp->tcp_ipversion == IPV4_VERSION)
12420 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12421 		else
12422 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12423 	} else {
12424 		if (tcp->tcp_ipversion == IPV4_VERSION)
12425 			mss_max = tcps->tcps_mss_max_ipv4;
12426 		else
12427 			mss_max = tcps->tcps_mss_max_ipv6;
12428 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12429 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12430 		else if (tcpopt.tcp_opt_mss > mss_max)
12431 			tcpopt.tcp_opt_mss = mss_max;
12432 	}
12433 
12434 	/* Process Window Scale option. */
12435 	if (options & TCP_OPT_WSCALE_PRESENT) {
12436 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12437 		tcp->tcp_snd_ws_ok = B_TRUE;
12438 	} else {
12439 		tcp->tcp_snd_ws = B_FALSE;
12440 		tcp->tcp_snd_ws_ok = B_FALSE;
12441 		tcp->tcp_rcv_ws = B_FALSE;
12442 	}
12443 
12444 	/* Process Timestamp option. */
12445 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12446 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12447 		tmp_tcph = (char *)tcp->tcp_tcph;
12448 
12449 		tcp->tcp_snd_ts_ok = B_TRUE;
12450 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12451 		tcp->tcp_last_rcv_lbolt = lbolt64;
12452 		ASSERT(OK_32PTR(tmp_tcph));
12453 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12454 
12455 		/* Fill in our template header with basic timestamp option. */
12456 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12457 		tmp_tcph[0] = TCPOPT_NOP;
12458 		tmp_tcph[1] = TCPOPT_NOP;
12459 		tmp_tcph[2] = TCPOPT_TSTAMP;
12460 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12461 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12462 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12463 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12464 	} else {
12465 		tcp->tcp_snd_ts_ok = B_FALSE;
12466 	}
12467 
12468 	/*
12469 	 * Process SACK options.  If SACK is enabled for this connection,
12470 	 * then allocate the SACK info structure.  Note the following ways
12471 	 * when tcp_snd_sack_ok is set to true.
12472 	 *
12473 	 * For active connection: in tcp_adapt_ire() called in
12474 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12475 	 * is checked.
12476 	 *
12477 	 * For passive connection: in tcp_adapt_ire() called in
12478 	 * tcp_accept_comm().
12479 	 *
12480 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12481 	 * That check makes sure that if we did not send a SACK OK option,
12482 	 * we will not enable SACK for this connection even though the other
12483 	 * side sends us SACK OK option.  For active connection, the SACK
12484 	 * info structure has already been allocated.  So we need to free
12485 	 * it if SACK is disabled.
12486 	 */
12487 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12488 	    (tcp->tcp_snd_sack_ok ||
12489 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12490 		/* This should be true only in the passive case. */
12491 		if (tcp->tcp_sack_info == NULL) {
12492 			ASSERT(TCP_IS_DETACHED(tcp));
12493 			tcp->tcp_sack_info =
12494 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12495 		}
12496 		if (tcp->tcp_sack_info == NULL) {
12497 			tcp->tcp_snd_sack_ok = B_FALSE;
12498 		} else {
12499 			tcp->tcp_snd_sack_ok = B_TRUE;
12500 			if (tcp->tcp_snd_ts_ok) {
12501 				tcp->tcp_max_sack_blk = 3;
12502 			} else {
12503 				tcp->tcp_max_sack_blk = 4;
12504 			}
12505 		}
12506 	} else {
12507 		/*
12508 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12509 		 * no SACK info will be used for this
12510 		 * connection.  This assumes that SACK usage
12511 		 * permission is negotiated.  This may need
12512 		 * to be changed once this is clarified.
12513 		 */
12514 		if (tcp->tcp_sack_info != NULL) {
12515 			ASSERT(tcp->tcp_notsack_list == NULL);
12516 			kmem_cache_free(tcp_sack_info_cache,
12517 			    tcp->tcp_sack_info);
12518 			tcp->tcp_sack_info = NULL;
12519 		}
12520 		tcp->tcp_snd_sack_ok = B_FALSE;
12521 	}
12522 
12523 	/*
12524 	 * Now we know the exact TCP/IP header length, subtract
12525 	 * that from tcp_mss to get our side's MSS.
12526 	 */
12527 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12528 	/*
12529 	 * Here we assume that the other side's header size will be equal to
12530 	 * our header size.  We calculate the real MSS accordingly.  Need to
12531 	 * take into additional stuffs IPsec puts in.
12532 	 *
12533 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12534 	 */
12535 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12536 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12537 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12538 
12539 	/*
12540 	 * Set MSS to the smaller one of both ends of the connection.
12541 	 * We should not have called tcp_mss_set() before, but our
12542 	 * side of the MSS should have been set to a proper value
12543 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12544 	 * STREAM head parameters properly.
12545 	 *
12546 	 * If we have a larger-than-16-bit window but the other side
12547 	 * didn't want to do window scale, tcp_rwnd_set() will take
12548 	 * care of that.
12549 	 */
12550 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12551 }
12552 
12553 /*
12554  * Sends the T_CONN_IND to the listener. The caller calls this
12555  * functions via squeue to get inside the listener's perimeter
12556  * once the 3 way hand shake is done a T_CONN_IND needs to be
12557  * sent. As an optimization, the caller can call this directly
12558  * if listener's perimeter is same as eager's.
12559  */
12560 /* ARGSUSED */
12561 void
12562 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12563 {
12564 	conn_t			*lconnp = (conn_t *)arg;
12565 	tcp_t			*listener = lconnp->conn_tcp;
12566 	tcp_t			*tcp;
12567 	struct T_conn_ind	*conn_ind;
12568 	ipaddr_t 		*addr_cache;
12569 	boolean_t		need_send_conn_ind = B_FALSE;
12570 	tcp_stack_t		*tcps = listener->tcp_tcps;
12571 
12572 	/* retrieve the eager */
12573 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12574 	ASSERT(conn_ind->OPT_offset != 0 &&
12575 	    conn_ind->OPT_length == sizeof (intptr_t));
12576 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12577 	    conn_ind->OPT_length);
12578 
12579 	/*
12580 	 * TLI/XTI applications will get confused by
12581 	 * sending eager as an option since it violates
12582 	 * the option semantics. So remove the eager as
12583 	 * option since TLI/XTI app doesn't need it anyway.
12584 	 */
12585 	if (!TCP_IS_SOCKET(listener)) {
12586 		conn_ind->OPT_length = 0;
12587 		conn_ind->OPT_offset = 0;
12588 	}
12589 	if (listener->tcp_state == TCPS_CLOSED ||
12590 	    TCP_IS_DETACHED(listener)) {
12591 		/*
12592 		 * If listener has closed, it would have caused a
12593 		 * a cleanup/blowoff to happen for the eager. We
12594 		 * just need to return.
12595 		 */
12596 		freemsg(mp);
12597 		return;
12598 	}
12599 
12600 
12601 	/*
12602 	 * if the conn_req_q is full defer passing up the
12603 	 * T_CONN_IND until space is availabe after t_accept()
12604 	 * processing
12605 	 */
12606 	mutex_enter(&listener->tcp_eager_lock);
12607 
12608 	/*
12609 	 * Take the eager out, if it is in the list of droppable eagers
12610 	 * as we are here because the 3W handshake is over.
12611 	 */
12612 	MAKE_UNDROPPABLE(tcp);
12613 
12614 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12615 		tcp_t *tail;
12616 
12617 		/*
12618 		 * The eager already has an extra ref put in tcp_rput_data
12619 		 * so that it stays till accept comes back even though it
12620 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12621 		 */
12622 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12623 		listener->tcp_conn_req_cnt_q0--;
12624 		listener->tcp_conn_req_cnt_q++;
12625 
12626 		/* Move from SYN_RCVD to ESTABLISHED list  */
12627 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12628 		    tcp->tcp_eager_prev_q0;
12629 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12630 		    tcp->tcp_eager_next_q0;
12631 		tcp->tcp_eager_prev_q0 = NULL;
12632 		tcp->tcp_eager_next_q0 = NULL;
12633 
12634 		/*
12635 		 * Insert at end of the queue because sockfs
12636 		 * sends down T_CONN_RES in chronological
12637 		 * order. Leaving the older conn indications
12638 		 * at front of the queue helps reducing search
12639 		 * time.
12640 		 */
12641 		tail = listener->tcp_eager_last_q;
12642 		if (tail != NULL)
12643 			tail->tcp_eager_next_q = tcp;
12644 		else
12645 			listener->tcp_eager_next_q = tcp;
12646 		listener->tcp_eager_last_q = tcp;
12647 		tcp->tcp_eager_next_q = NULL;
12648 		/*
12649 		 * Delay sending up the T_conn_ind until we are
12650 		 * done with the eager. Once we have have sent up
12651 		 * the T_conn_ind, the accept can potentially complete
12652 		 * any time and release the refhold we have on the eager.
12653 		 */
12654 		need_send_conn_ind = B_TRUE;
12655 	} else {
12656 		/*
12657 		 * Defer connection on q0 and set deferred
12658 		 * connection bit true
12659 		 */
12660 		tcp->tcp_conn_def_q0 = B_TRUE;
12661 
12662 		/* take tcp out of q0 ... */
12663 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12664 		    tcp->tcp_eager_next_q0;
12665 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12666 		    tcp->tcp_eager_prev_q0;
12667 
12668 		/* ... and place it at the end of q0 */
12669 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12670 		tcp->tcp_eager_next_q0 = listener;
12671 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12672 		listener->tcp_eager_prev_q0 = tcp;
12673 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12674 	}
12675 
12676 	/* we have timed out before */
12677 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12678 		tcp->tcp_syn_rcvd_timeout = 0;
12679 		listener->tcp_syn_rcvd_timeout--;
12680 		if (listener->tcp_syn_defense &&
12681 		    listener->tcp_syn_rcvd_timeout <=
12682 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12683 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12684 		    listener->tcp_last_rcv_lbolt)) {
12685 			/*
12686 			 * Turn off the defense mode if we
12687 			 * believe the SYN attack is over.
12688 			 */
12689 			listener->tcp_syn_defense = B_FALSE;
12690 			if (listener->tcp_ip_addr_cache) {
12691 				kmem_free((void *)listener->tcp_ip_addr_cache,
12692 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12693 				listener->tcp_ip_addr_cache = NULL;
12694 			}
12695 		}
12696 	}
12697 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12698 	if (addr_cache != NULL) {
12699 		/*
12700 		 * We have finished a 3-way handshake with this
12701 		 * remote host. This proves the IP addr is good.
12702 		 * Cache it!
12703 		 */
12704 		addr_cache[IP_ADDR_CACHE_HASH(
12705 		    tcp->tcp_remote)] = tcp->tcp_remote;
12706 	}
12707 	mutex_exit(&listener->tcp_eager_lock);
12708 	if (need_send_conn_ind) {
12709 		if (IPCL_IS_NONSTR(lconnp)) {
12710 			ASSERT(tcp->tcp_listener == listener);
12711 			ASSERT(tcp->tcp_saved_listener == listener);
12712 			if ((*lconnp->conn_upcalls->su_newconn)
12713 			    (lconnp->conn_upper_handle,
12714 			    (sock_lower_handle_t)tcp->tcp_connp,
12715 			    &sock_tcp_downcalls, DB_CRED(mp), DB_CPID(mp),
12716 			    &tcp->tcp_connp->conn_upcalls) != NULL) {
12717 				/*
12718 				 * Keep the message around
12719 				 * in case of fallback
12720 				 */
12721 				tcp->tcp_conn.tcp_eager_conn_ind = mp;
12722 			} else {
12723 				freemsg(mp);
12724 			}
12725 		} else {
12726 			putnext(listener->tcp_rq, mp);
12727 		}
12728 	}
12729 }
12730 
12731 mblk_t *
12732 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12733     uint_t *ifindexp, ip6_pkt_t *ippp)
12734 {
12735 	ip_pktinfo_t	*pinfo;
12736 	ip6_t		*ip6h;
12737 	uchar_t		*rptr;
12738 	mblk_t		*first_mp = mp;
12739 	boolean_t	mctl_present = B_FALSE;
12740 	uint_t 		ifindex = 0;
12741 	ip6_pkt_t	ipp;
12742 	uint_t		ipvers;
12743 	uint_t		ip_hdr_len;
12744 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12745 
12746 	rptr = mp->b_rptr;
12747 	ASSERT(OK_32PTR(rptr));
12748 	ASSERT(tcp != NULL);
12749 	ipp.ipp_fields = 0;
12750 
12751 	switch DB_TYPE(mp) {
12752 	case M_CTL:
12753 		mp = mp->b_cont;
12754 		if (mp == NULL) {
12755 			freemsg(first_mp);
12756 			return (NULL);
12757 		}
12758 		if (DB_TYPE(mp) != M_DATA) {
12759 			freemsg(first_mp);
12760 			return (NULL);
12761 		}
12762 		mctl_present = B_TRUE;
12763 		break;
12764 	case M_DATA:
12765 		break;
12766 	default:
12767 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12768 		freemsg(mp);
12769 		return (NULL);
12770 	}
12771 	ipvers = IPH_HDR_VERSION(rptr);
12772 	if (ipvers == IPV4_VERSION) {
12773 		if (tcp == NULL) {
12774 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12775 			goto done;
12776 		}
12777 
12778 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12779 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12780 
12781 		/*
12782 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12783 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12784 		 */
12785 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12786 		    mctl_present) {
12787 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12788 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12789 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12790 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12791 				ipp.ipp_fields |= IPPF_IFINDEX;
12792 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12793 				ifindex = pinfo->ip_pkt_ifindex;
12794 			}
12795 			freeb(first_mp);
12796 			mctl_present = B_FALSE;
12797 		}
12798 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12799 	} else {
12800 		ip6h = (ip6_t *)rptr;
12801 
12802 		ASSERT(ipvers == IPV6_VERSION);
12803 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12804 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12805 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12806 
12807 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12808 			uint8_t	nexthdrp;
12809 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12810 
12811 			/* Look for ifindex information */
12812 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12813 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12814 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12815 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12816 					freemsg(first_mp);
12817 					return (NULL);
12818 				}
12819 
12820 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12821 					ASSERT(ip6i->ip6i_ifindex != 0);
12822 					ipp.ipp_fields |= IPPF_IFINDEX;
12823 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12824 					ifindex = ip6i->ip6i_ifindex;
12825 				}
12826 				rptr = (uchar_t *)&ip6i[1];
12827 				mp->b_rptr = rptr;
12828 				if (rptr == mp->b_wptr) {
12829 					mblk_t *mp1;
12830 					mp1 = mp->b_cont;
12831 					freeb(mp);
12832 					mp = mp1;
12833 					rptr = mp->b_rptr;
12834 				}
12835 				if (MBLKL(mp) < IPV6_HDR_LEN +
12836 				    sizeof (tcph_t)) {
12837 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12838 					freemsg(first_mp);
12839 					return (NULL);
12840 				}
12841 				ip6h = (ip6_t *)rptr;
12842 			}
12843 
12844 			/*
12845 			 * Find any potentially interesting extension headers
12846 			 * as well as the length of the IPv6 + extension
12847 			 * headers.
12848 			 */
12849 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12850 			/* Verify if this is a TCP packet */
12851 			if (nexthdrp != IPPROTO_TCP) {
12852 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12853 				freemsg(first_mp);
12854 				return (NULL);
12855 			}
12856 		} else {
12857 			ip_hdr_len = IPV6_HDR_LEN;
12858 		}
12859 	}
12860 
12861 done:
12862 	if (ipversp != NULL)
12863 		*ipversp = ipvers;
12864 	if (ip_hdr_lenp != NULL)
12865 		*ip_hdr_lenp = ip_hdr_len;
12866 	if (ippp != NULL)
12867 		*ippp = ipp;
12868 	if (ifindexp != NULL)
12869 		*ifindexp = ifindex;
12870 	if (mctl_present) {
12871 		freeb(first_mp);
12872 	}
12873 	return (mp);
12874 }
12875 
12876 /*
12877  * Handle M_DATA messages from IP. Its called directly from IP via
12878  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12879  * in this path.
12880  *
12881  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12882  * v4 and v6), we are called through tcp_input() and a M_CTL can
12883  * be present for options but tcp_find_pktinfo() deals with it. We
12884  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12885  *
12886  * The first argument is always the connp/tcp to which the mp belongs.
12887  * There are no exceptions to this rule. The caller has already put
12888  * a reference on this connp/tcp and once tcp_rput_data() returns,
12889  * the squeue will do the refrele.
12890  *
12891  * The TH_SYN for the listener directly go to tcp_conn_request via
12892  * squeue.
12893  *
12894  * sqp: NULL = recursive, sqp != NULL means called from squeue
12895  */
12896 void
12897 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12898 {
12899 	int32_t		bytes_acked;
12900 	int32_t		gap;
12901 	mblk_t		*mp1;
12902 	uint_t		flags;
12903 	uint32_t	new_swnd = 0;
12904 	uchar_t		*iphdr;
12905 	uchar_t		*rptr;
12906 	int32_t		rgap;
12907 	uint32_t	seg_ack;
12908 	int		seg_len;
12909 	uint_t		ip_hdr_len;
12910 	uint32_t	seg_seq;
12911 	tcph_t		*tcph;
12912 	int		urp;
12913 	tcp_opt_t	tcpopt;
12914 	uint_t		ipvers;
12915 	ip6_pkt_t	ipp;
12916 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12917 	uint32_t	cwnd;
12918 	uint32_t	add;
12919 	int		npkt;
12920 	int		mss;
12921 	conn_t		*connp = (conn_t *)arg;
12922 	squeue_t	*sqp = (squeue_t *)arg2;
12923 	tcp_t		*tcp = connp->conn_tcp;
12924 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12925 
12926 	/*
12927 	 * RST from fused tcp loopback peer should trigger an unfuse.
12928 	 */
12929 	if (tcp->tcp_fused) {
12930 		TCP_STAT(tcps, tcp_fusion_aborted);
12931 		tcp_unfuse(tcp);
12932 	}
12933 
12934 	iphdr = mp->b_rptr;
12935 	rptr = mp->b_rptr;
12936 	ASSERT(OK_32PTR(rptr));
12937 
12938 	/*
12939 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12940 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12941 	 * necessary information.
12942 	 */
12943 	if (IPCL_IS_TCP4(connp)) {
12944 		ipvers = IPV4_VERSION;
12945 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12946 	} else {
12947 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12948 		    NULL, &ipp);
12949 		if (mp == NULL) {
12950 			TCP_STAT(tcps, tcp_rput_v6_error);
12951 			return;
12952 		}
12953 		iphdr = mp->b_rptr;
12954 		rptr = mp->b_rptr;
12955 	}
12956 	ASSERT(DB_TYPE(mp) == M_DATA);
12957 	ASSERT(mp->b_next == NULL);
12958 
12959 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12960 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12961 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12962 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12963 	seg_len = (int)(mp->b_wptr - rptr) -
12964 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12965 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12966 		do {
12967 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12968 			    (uintptr_t)INT_MAX);
12969 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12970 		} while ((mp1 = mp1->b_cont) != NULL &&
12971 		    mp1->b_datap->db_type == M_DATA);
12972 	}
12973 
12974 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12975 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12976 		    seg_len, tcph);
12977 		return;
12978 	}
12979 
12980 	if (sqp != NULL) {
12981 		/*
12982 		 * This is the correct place to update tcp_last_recv_time. Note
12983 		 * that it is also updated for tcp structure that belongs to
12984 		 * global and listener queues which do not really need updating.
12985 		 * But that should not cause any harm.  And it is updated for
12986 		 * all kinds of incoming segments, not only for data segments.
12987 		 */
12988 		tcp->tcp_last_recv_time = lbolt;
12989 	}
12990 
12991 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12992 
12993 	BUMP_LOCAL(tcp->tcp_ibsegs);
12994 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
12995 
12996 	if ((flags & TH_URG) && sqp != NULL) {
12997 		/*
12998 		 * TCP can't handle urgent pointers that arrive before
12999 		 * the connection has been accept()ed since it can't
13000 		 * buffer OOB data.  Discard segment if this happens.
13001 		 *
13002 		 * We can't just rely on a non-null tcp_listener to indicate
13003 		 * that the accept() has completed since unlinking of the
13004 		 * eager and completion of the accept are not atomic.
13005 		 * tcp_detached, when it is not set (B_FALSE) indicates
13006 		 * that the accept() has completed.
13007 		 *
13008 		 * Nor can it reassemble urgent pointers, so discard
13009 		 * if it's not the next segment expected.
13010 		 *
13011 		 * Otherwise, collapse chain into one mblk (discard if
13012 		 * that fails).  This makes sure the headers, retransmitted
13013 		 * data, and new data all are in the same mblk.
13014 		 */
13015 		ASSERT(mp != NULL);
13016 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
13017 			freemsg(mp);
13018 			return;
13019 		}
13020 		/* Update pointers into message */
13021 		iphdr = rptr = mp->b_rptr;
13022 		tcph = (tcph_t *)&rptr[ip_hdr_len];
13023 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
13024 			/*
13025 			 * Since we can't handle any data with this urgent
13026 			 * pointer that is out of sequence, we expunge
13027 			 * the data.  This allows us to still register
13028 			 * the urgent mark and generate the M_PCSIG,
13029 			 * which we can do.
13030 			 */
13031 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13032 			seg_len = 0;
13033 		}
13034 	}
13035 
13036 	switch (tcp->tcp_state) {
13037 	case TCPS_SYN_SENT:
13038 		if (flags & TH_ACK) {
13039 			/*
13040 			 * Note that our stack cannot send data before a
13041 			 * connection is established, therefore the
13042 			 * following check is valid.  Otherwise, it has
13043 			 * to be changed.
13044 			 */
13045 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13046 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13047 				freemsg(mp);
13048 				if (flags & TH_RST)
13049 					return;
13050 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13051 				    tcp, seg_ack, 0, TH_RST);
13052 				return;
13053 			}
13054 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13055 		}
13056 		if (flags & TH_RST) {
13057 			freemsg(mp);
13058 			if (flags & TH_ACK)
13059 				(void) tcp_clean_death(tcp,
13060 				    ECONNREFUSED, 13);
13061 			return;
13062 		}
13063 		if (!(flags & TH_SYN)) {
13064 			freemsg(mp);
13065 			return;
13066 		}
13067 
13068 		/* Process all TCP options. */
13069 		tcp_process_options(tcp, tcph);
13070 		/*
13071 		 * The following changes our rwnd to be a multiple of the
13072 		 * MIN(peer MSS, our MSS) for performance reason.
13073 		 */
13074 		(void) tcp_rwnd_set(tcp,
13075 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
13076 
13077 		/* Is the other end ECN capable? */
13078 		if (tcp->tcp_ecn_ok) {
13079 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13080 				tcp->tcp_ecn_ok = B_FALSE;
13081 			}
13082 		}
13083 		/*
13084 		 * Clear ECN flags because it may interfere with later
13085 		 * processing.
13086 		 */
13087 		flags &= ~(TH_ECE|TH_CWR);
13088 
13089 		tcp->tcp_irs = seg_seq;
13090 		tcp->tcp_rack = seg_seq;
13091 		tcp->tcp_rnxt = seg_seq + 1;
13092 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13093 		if (!TCP_IS_DETACHED(tcp)) {
13094 			/* Allocate room for SACK options if needed. */
13095 			if (tcp->tcp_snd_sack_ok) {
13096 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13097 				    tcp->tcp_hdr_len +
13098 				    TCPOPT_MAX_SACK_LEN +
13099 				    (tcp->tcp_loopback ? 0 :
13100 				    tcps->tcps_wroff_xtra));
13101 			} else {
13102 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13103 				    tcp->tcp_hdr_len +
13104 				    (tcp->tcp_loopback ? 0 :
13105 				    tcps->tcps_wroff_xtra));
13106 			}
13107 		}
13108 		if (flags & TH_ACK) {
13109 			/*
13110 			 * If we can't get the confirmation upstream, pretend
13111 			 * we didn't even see this one.
13112 			 *
13113 			 * XXX: how can we pretend we didn't see it if we
13114 			 * have updated rnxt et. al.
13115 			 *
13116 			 * For loopback we defer sending up the T_CONN_CON
13117 			 * until after some checks below.
13118 			 */
13119 			mp1 = NULL;
13120 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13121 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13122 				freemsg(mp);
13123 				return;
13124 			}
13125 			/* SYN was acked - making progress */
13126 			if (tcp->tcp_ipversion == IPV6_VERSION)
13127 				tcp->tcp_ip_forward_progress = B_TRUE;
13128 
13129 			/* One for the SYN */
13130 			tcp->tcp_suna = tcp->tcp_iss + 1;
13131 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13132 			tcp->tcp_state = TCPS_ESTABLISHED;
13133 
13134 			/*
13135 			 * If SYN was retransmitted, need to reset all
13136 			 * retransmission info.  This is because this
13137 			 * segment will be treated as a dup ACK.
13138 			 */
13139 			if (tcp->tcp_rexmit) {
13140 				tcp->tcp_rexmit = B_FALSE;
13141 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13142 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13143 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13144 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13145 				tcp->tcp_ms_we_have_waited = 0;
13146 
13147 				/*
13148 				 * Set tcp_cwnd back to 1 MSS, per
13149 				 * recommendation from
13150 				 * draft-floyd-incr-init-win-01.txt,
13151 				 * Increasing TCP's Initial Window.
13152 				 */
13153 				tcp->tcp_cwnd = tcp->tcp_mss;
13154 			}
13155 
13156 			tcp->tcp_swl1 = seg_seq;
13157 			tcp->tcp_swl2 = seg_ack;
13158 
13159 			new_swnd = BE16_TO_U16(tcph->th_win);
13160 			tcp->tcp_swnd = new_swnd;
13161 			if (new_swnd > tcp->tcp_max_swnd)
13162 				tcp->tcp_max_swnd = new_swnd;
13163 
13164 			/*
13165 			 * Always send the three-way handshake ack immediately
13166 			 * in order to make the connection complete as soon as
13167 			 * possible on the accepting host.
13168 			 */
13169 			flags |= TH_ACK_NEEDED;
13170 
13171 			/*
13172 			 * Special case for loopback.  At this point we have
13173 			 * received SYN-ACK from the remote endpoint.  In
13174 			 * order to ensure that both endpoints reach the
13175 			 * fused state prior to any data exchange, the final
13176 			 * ACK needs to be sent before we indicate T_CONN_CON
13177 			 * to the module upstream.
13178 			 */
13179 			if (tcp->tcp_loopback) {
13180 				mblk_t *ack_mp;
13181 
13182 				ASSERT(!tcp->tcp_unfusable);
13183 				ASSERT(mp1 != NULL);
13184 				/*
13185 				 * For loopback, we always get a pure SYN-ACK
13186 				 * and only need to send back the final ACK
13187 				 * with no data (this is because the other
13188 				 * tcp is ours and we don't do T/TCP).  This
13189 				 * final ACK triggers the passive side to
13190 				 * perform fusion in ESTABLISHED state.
13191 				 */
13192 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13193 					if (tcp->tcp_ack_tid != 0) {
13194 						(void) TCP_TIMER_CANCEL(tcp,
13195 						    tcp->tcp_ack_tid);
13196 						tcp->tcp_ack_tid = 0;
13197 					}
13198 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13199 					BUMP_LOCAL(tcp->tcp_obsegs);
13200 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13201 
13202 					if (!IPCL_IS_NONSTR(connp)) {
13203 						/* Send up T_CONN_CON */
13204 						putnext(tcp->tcp_rq, mp1);
13205 					} else {
13206 						(*connp->conn_upcalls->
13207 						    su_connected)
13208 						    (connp->conn_upper_handle,
13209 						    tcp->tcp_connid,
13210 						    DB_CRED(mp1),
13211 						    DB_CPID(mp1));
13212 						freemsg(mp1);
13213 					}
13214 
13215 					freemsg(mp);
13216 					return;
13217 				}
13218 				/*
13219 				 * Forget fusion; we need to handle more
13220 				 * complex cases below.  Send the deferred
13221 				 * T_CONN_CON message upstream and proceed
13222 				 * as usual.  Mark this tcp as not capable
13223 				 * of fusion.
13224 				 */
13225 				TCP_STAT(tcps, tcp_fusion_unfusable);
13226 				tcp->tcp_unfusable = B_TRUE;
13227 				if (!IPCL_IS_NONSTR(connp)) {
13228 					putnext(tcp->tcp_rq, mp1);
13229 				} else {
13230 					(*connp->conn_upcalls->su_connected)
13231 					    (connp->conn_upper_handle,
13232 					    tcp->tcp_connid, DB_CRED(mp1),
13233 					    DB_CPID(mp1));
13234 					freemsg(mp1);
13235 				}
13236 			}
13237 
13238 			/*
13239 			 * Check to see if there is data to be sent.  If
13240 			 * yes, set the transmit flag.  Then check to see
13241 			 * if received data processing needs to be done.
13242 			 * If not, go straight to xmit_check.  This short
13243 			 * cut is OK as we don't support T/TCP.
13244 			 */
13245 			if (tcp->tcp_unsent)
13246 				flags |= TH_XMIT_NEEDED;
13247 
13248 			if (seg_len == 0 && !(flags & TH_URG)) {
13249 				freemsg(mp);
13250 				goto xmit_check;
13251 			}
13252 
13253 			flags &= ~TH_SYN;
13254 			seg_seq++;
13255 			break;
13256 		}
13257 		tcp->tcp_state = TCPS_SYN_RCVD;
13258 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13259 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13260 		if (mp1) {
13261 			DB_CPID(mp1) = tcp->tcp_cpid;
13262 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13263 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13264 		}
13265 		freemsg(mp);
13266 		return;
13267 	case TCPS_SYN_RCVD:
13268 		if (flags & TH_ACK) {
13269 			/*
13270 			 * In this state, a SYN|ACK packet is either bogus
13271 			 * because the other side must be ACKing our SYN which
13272 			 * indicates it has seen the ACK for their SYN and
13273 			 * shouldn't retransmit it or we're crossing SYNs
13274 			 * on active open.
13275 			 */
13276 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13277 				freemsg(mp);
13278 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13279 				    tcp, seg_ack, 0, TH_RST);
13280 				return;
13281 			}
13282 			/*
13283 			 * NOTE: RFC 793 pg. 72 says this should be
13284 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13285 			 * but that would mean we have an ack that ignored
13286 			 * our SYN.
13287 			 */
13288 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13289 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13290 				freemsg(mp);
13291 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13292 				    tcp, seg_ack, 0, TH_RST);
13293 				return;
13294 			}
13295 		}
13296 		break;
13297 	case TCPS_LISTEN:
13298 		/*
13299 		 * Only a TLI listener can come through this path when a
13300 		 * acceptor is going back to be a listener and a packet
13301 		 * for the acceptor hits the classifier. For a socket
13302 		 * listener, this can never happen because a listener
13303 		 * can never accept connection on itself and hence a
13304 		 * socket acceptor can not go back to being a listener.
13305 		 */
13306 		ASSERT(!TCP_IS_SOCKET(tcp));
13307 		/*FALLTHRU*/
13308 	case TCPS_CLOSED:
13309 	case TCPS_BOUND: {
13310 		conn_t	*new_connp;
13311 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13312 
13313 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13314 		if (new_connp != NULL) {
13315 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13316 			return;
13317 		}
13318 		/* We failed to classify. For now just drop the packet */
13319 		freemsg(mp);
13320 		return;
13321 	}
13322 	case TCPS_IDLE:
13323 		/*
13324 		 * Handle the case where the tcp_clean_death() has happened
13325 		 * on a connection (application hasn't closed yet) but a packet
13326 		 * was already queued on squeue before tcp_clean_death()
13327 		 * was processed. Calling tcp_clean_death() twice on same
13328 		 * connection can result in weird behaviour.
13329 		 */
13330 		freemsg(mp);
13331 		return;
13332 	default:
13333 		break;
13334 	}
13335 
13336 	/*
13337 	 * Already on the correct queue/perimeter.
13338 	 * If this is a detached connection and not an eager
13339 	 * connection hanging off a listener then new data
13340 	 * (past the FIN) will cause a reset.
13341 	 * We do a special check here where it
13342 	 * is out of the main line, rather than check
13343 	 * if we are detached every time we see new
13344 	 * data down below.
13345 	 */
13346 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13347 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13348 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13349 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13350 
13351 		freemsg(mp);
13352 		/*
13353 		 * This could be an SSL closure alert. We're detached so just
13354 		 * acknowledge it this last time.
13355 		 */
13356 		if (tcp->tcp_kssl_ctx != NULL) {
13357 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13358 			tcp->tcp_kssl_ctx = NULL;
13359 
13360 			tcp->tcp_rnxt += seg_len;
13361 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13362 			flags |= TH_ACK_NEEDED;
13363 			goto ack_check;
13364 		}
13365 
13366 		tcp_xmit_ctl("new data when detached", tcp,
13367 		    tcp->tcp_snxt, 0, TH_RST);
13368 		(void) tcp_clean_death(tcp, EPROTO, 12);
13369 		return;
13370 	}
13371 
13372 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13373 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13374 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13375 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13376 
13377 	if (tcp->tcp_snd_ts_ok) {
13378 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13379 			/*
13380 			 * This segment is not acceptable.
13381 			 * Drop it and send back an ACK.
13382 			 */
13383 			freemsg(mp);
13384 			flags |= TH_ACK_NEEDED;
13385 			goto ack_check;
13386 		}
13387 	} else if (tcp->tcp_snd_sack_ok) {
13388 		ASSERT(tcp->tcp_sack_info != NULL);
13389 		tcpopt.tcp = tcp;
13390 		/*
13391 		 * SACK info in already updated in tcp_parse_options.  Ignore
13392 		 * all other TCP options...
13393 		 */
13394 		(void) tcp_parse_options(tcph, &tcpopt);
13395 	}
13396 try_again:;
13397 	mss = tcp->tcp_mss;
13398 	gap = seg_seq - tcp->tcp_rnxt;
13399 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13400 	/*
13401 	 * gap is the amount of sequence space between what we expect to see
13402 	 * and what we got for seg_seq.  A positive value for gap means
13403 	 * something got lost.  A negative value means we got some old stuff.
13404 	 */
13405 	if (gap < 0) {
13406 		/* Old stuff present.  Is the SYN in there? */
13407 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13408 		    (seg_len != 0)) {
13409 			flags &= ~TH_SYN;
13410 			seg_seq++;
13411 			urp--;
13412 			/* Recompute the gaps after noting the SYN. */
13413 			goto try_again;
13414 		}
13415 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13416 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13417 		    (seg_len > -gap ? -gap : seg_len));
13418 		/* Remove the old stuff from seg_len. */
13419 		seg_len += gap;
13420 		/*
13421 		 * Anything left?
13422 		 * Make sure to check for unack'd FIN when rest of data
13423 		 * has been previously ack'd.
13424 		 */
13425 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13426 			/*
13427 			 * Resets are only valid if they lie within our offered
13428 			 * window.  If the RST bit is set, we just ignore this
13429 			 * segment.
13430 			 */
13431 			if (flags & TH_RST) {
13432 				freemsg(mp);
13433 				return;
13434 			}
13435 
13436 			/*
13437 			 * The arriving of dup data packets indicate that we
13438 			 * may have postponed an ack for too long, or the other
13439 			 * side's RTT estimate is out of shape. Start acking
13440 			 * more often.
13441 			 */
13442 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13443 			    tcp->tcp_rack_cnt >= 1 &&
13444 			    tcp->tcp_rack_abs_max > 2) {
13445 				tcp->tcp_rack_abs_max--;
13446 			}
13447 			tcp->tcp_rack_cur_max = 1;
13448 
13449 			/*
13450 			 * This segment is "unacceptable".  None of its
13451 			 * sequence space lies within our advertized window.
13452 			 *
13453 			 * Adjust seg_len to the original value for tracing.
13454 			 */
13455 			seg_len -= gap;
13456 			if (tcp->tcp_debug) {
13457 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13458 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13459 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13460 				    "seg_len %d, rnxt %u, snxt %u, %s",
13461 				    gap, rgap, flags, seg_seq, seg_ack,
13462 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13463 				    tcp_display(tcp, NULL,
13464 				    DISP_ADDR_AND_PORT));
13465 			}
13466 
13467 			/*
13468 			 * Arrange to send an ACK in response to the
13469 			 * unacceptable segment per RFC 793 page 69. There
13470 			 * is only one small difference between ours and the
13471 			 * acceptability test in the RFC - we accept ACK-only
13472 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13473 			 * will be generated.
13474 			 *
13475 			 * Note that we have to ACK an ACK-only packet at least
13476 			 * for stacks that send 0-length keep-alives with
13477 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13478 			 * section 4.2.3.6. As long as we don't ever generate
13479 			 * an unacceptable packet in response to an incoming
13480 			 * packet that is unacceptable, it should not cause
13481 			 * "ACK wars".
13482 			 */
13483 			flags |=  TH_ACK_NEEDED;
13484 
13485 			/*
13486 			 * Continue processing this segment in order to use the
13487 			 * ACK information it contains, but skip all other
13488 			 * sequence-number processing.	Processing the ACK
13489 			 * information is necessary in order to
13490 			 * re-synchronize connections that may have lost
13491 			 * synchronization.
13492 			 *
13493 			 * We clear seg_len and flag fields related to
13494 			 * sequence number processing as they are not
13495 			 * to be trusted for an unacceptable segment.
13496 			 */
13497 			seg_len = 0;
13498 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13499 			goto process_ack;
13500 		}
13501 
13502 		/* Fix seg_seq, and chew the gap off the front. */
13503 		seg_seq = tcp->tcp_rnxt;
13504 		urp += gap;
13505 		do {
13506 			mblk_t	*mp2;
13507 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13508 			    (uintptr_t)UINT_MAX);
13509 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13510 			if (gap > 0) {
13511 				mp->b_rptr = mp->b_wptr - gap;
13512 				break;
13513 			}
13514 			mp2 = mp;
13515 			mp = mp->b_cont;
13516 			freeb(mp2);
13517 		} while (gap < 0);
13518 		/*
13519 		 * If the urgent data has already been acknowledged, we
13520 		 * should ignore TH_URG below
13521 		 */
13522 		if (urp < 0)
13523 			flags &= ~TH_URG;
13524 	}
13525 	/*
13526 	 * rgap is the amount of stuff received out of window.  A negative
13527 	 * value is the amount out of window.
13528 	 */
13529 	if (rgap < 0) {
13530 		mblk_t	*mp2;
13531 
13532 		if (tcp->tcp_rwnd == 0) {
13533 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13534 		} else {
13535 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13536 			UPDATE_MIB(&tcps->tcps_mib,
13537 			    tcpInDataPastWinBytes, -rgap);
13538 		}
13539 
13540 		/*
13541 		 * seg_len does not include the FIN, so if more than
13542 		 * just the FIN is out of window, we act like we don't
13543 		 * see it.  (If just the FIN is out of window, rgap
13544 		 * will be zero and we will go ahead and acknowledge
13545 		 * the FIN.)
13546 		 */
13547 		flags &= ~TH_FIN;
13548 
13549 		/* Fix seg_len and make sure there is something left. */
13550 		seg_len += rgap;
13551 		if (seg_len <= 0) {
13552 			/*
13553 			 * Resets are only valid if they lie within our offered
13554 			 * window.  If the RST bit is set, we just ignore this
13555 			 * segment.
13556 			 */
13557 			if (flags & TH_RST) {
13558 				freemsg(mp);
13559 				return;
13560 			}
13561 
13562 			/* Per RFC 793, we need to send back an ACK. */
13563 			flags |= TH_ACK_NEEDED;
13564 
13565 			/*
13566 			 * Send SIGURG as soon as possible i.e. even
13567 			 * if the TH_URG was delivered in a window probe
13568 			 * packet (which will be unacceptable).
13569 			 *
13570 			 * We generate a signal if none has been generated
13571 			 * for this connection or if this is a new urgent
13572 			 * byte. Also send a zero-length "unmarked" message
13573 			 * to inform SIOCATMARK that this is not the mark.
13574 			 *
13575 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13576 			 * is sent up. This plus the check for old data
13577 			 * (gap >= 0) handles the wraparound of the sequence
13578 			 * number space without having to always track the
13579 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13580 			 * this max in its rcv_up variable).
13581 			 *
13582 			 * This prevents duplicate SIGURGS due to a "late"
13583 			 * zero-window probe when the T_EXDATA_IND has already
13584 			 * been sent up.
13585 			 */
13586 			if ((flags & TH_URG) &&
13587 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13588 			    tcp->tcp_urp_last))) {
13589 				if (IPCL_IS_NONSTR(connp)) {
13590 					if (!TCP_IS_DETACHED(tcp)) {
13591 						(*connp->conn_upcalls->
13592 						    su_signal_oob)
13593 						    (connp->conn_upper_handle,
13594 						    urp);
13595 					}
13596 				} else {
13597 					mp1 = allocb(0, BPRI_MED);
13598 					if (mp1 == NULL) {
13599 						freemsg(mp);
13600 						return;
13601 					}
13602 					if (!TCP_IS_DETACHED(tcp) &&
13603 					    !putnextctl1(tcp->tcp_rq,
13604 					    M_PCSIG, SIGURG)) {
13605 						/* Try again on the rexmit. */
13606 						freemsg(mp1);
13607 						freemsg(mp);
13608 						return;
13609 					}
13610 					/*
13611 					 * If the next byte would be the mark
13612 					 * then mark with MARKNEXT else mark
13613 					 * with NOTMARKNEXT.
13614 					 */
13615 					if (gap == 0 && urp == 0)
13616 						mp1->b_flag |= MSGMARKNEXT;
13617 					else
13618 						mp1->b_flag |= MSGNOTMARKNEXT;
13619 					freemsg(tcp->tcp_urp_mark_mp);
13620 					tcp->tcp_urp_mark_mp = mp1;
13621 					flags |= TH_SEND_URP_MARK;
13622 				}
13623 				tcp->tcp_urp_last_valid = B_TRUE;
13624 				tcp->tcp_urp_last = urp + seg_seq;
13625 			}
13626 			/*
13627 			 * If this is a zero window probe, continue to
13628 			 * process the ACK part.  But we need to set seg_len
13629 			 * to 0 to avoid data processing.  Otherwise just
13630 			 * drop the segment and send back an ACK.
13631 			 */
13632 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13633 				flags &= ~(TH_SYN | TH_URG);
13634 				seg_len = 0;
13635 				goto process_ack;
13636 			} else {
13637 				freemsg(mp);
13638 				goto ack_check;
13639 			}
13640 		}
13641 		/* Pitch out of window stuff off the end. */
13642 		rgap = seg_len;
13643 		mp2 = mp;
13644 		do {
13645 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13646 			    (uintptr_t)INT_MAX);
13647 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13648 			if (rgap < 0) {
13649 				mp2->b_wptr += rgap;
13650 				if ((mp1 = mp2->b_cont) != NULL) {
13651 					mp2->b_cont = NULL;
13652 					freemsg(mp1);
13653 				}
13654 				break;
13655 			}
13656 		} while ((mp2 = mp2->b_cont) != NULL);
13657 	}
13658 ok:;
13659 	/*
13660 	 * TCP should check ECN info for segments inside the window only.
13661 	 * Therefore the check should be done here.
13662 	 */
13663 	if (tcp->tcp_ecn_ok) {
13664 		if (flags & TH_CWR) {
13665 			tcp->tcp_ecn_echo_on = B_FALSE;
13666 		}
13667 		/*
13668 		 * Note that both ECN_CE and CWR can be set in the
13669 		 * same segment.  In this case, we once again turn
13670 		 * on ECN_ECHO.
13671 		 */
13672 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13673 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13674 
13675 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13676 				tcp->tcp_ecn_echo_on = B_TRUE;
13677 			}
13678 		} else {
13679 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13680 
13681 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13682 			    htonl(IPH_ECN_CE << 20)) {
13683 				tcp->tcp_ecn_echo_on = B_TRUE;
13684 			}
13685 		}
13686 	}
13687 
13688 	/*
13689 	 * Check whether we can update tcp_ts_recent.  This test is
13690 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13691 	 * Extensions for High Performance: An Update", Internet Draft.
13692 	 */
13693 	if (tcp->tcp_snd_ts_ok &&
13694 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13695 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13696 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13697 		tcp->tcp_last_rcv_lbolt = lbolt64;
13698 	}
13699 
13700 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13701 		/*
13702 		 * FIN in an out of order segment.  We record this in
13703 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13704 		 * Clear the FIN so that any check on FIN flag will fail.
13705 		 * Remember that FIN also counts in the sequence number
13706 		 * space.  So we need to ack out of order FIN only segments.
13707 		 */
13708 		if (flags & TH_FIN) {
13709 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13710 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13711 			flags &= ~TH_FIN;
13712 			flags |= TH_ACK_NEEDED;
13713 		}
13714 		if (seg_len > 0) {
13715 			/* Fill in the SACK blk list. */
13716 			if (tcp->tcp_snd_sack_ok) {
13717 				ASSERT(tcp->tcp_sack_info != NULL);
13718 				tcp_sack_insert(tcp->tcp_sack_list,
13719 				    seg_seq, seg_seq + seg_len,
13720 				    &(tcp->tcp_num_sack_blk));
13721 			}
13722 
13723 			/*
13724 			 * Attempt reassembly and see if we have something
13725 			 * ready to go.
13726 			 */
13727 			mp = tcp_reass(tcp, mp, seg_seq);
13728 			/* Always ack out of order packets */
13729 			flags |= TH_ACK_NEEDED | TH_PUSH;
13730 			if (mp) {
13731 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13732 				    (uintptr_t)INT_MAX);
13733 				seg_len = mp->b_cont ? msgdsize(mp) :
13734 				    (int)(mp->b_wptr - mp->b_rptr);
13735 				seg_seq = tcp->tcp_rnxt;
13736 				/*
13737 				 * A gap is filled and the seq num and len
13738 				 * of the gap match that of a previously
13739 				 * received FIN, put the FIN flag back in.
13740 				 */
13741 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13742 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13743 					flags |= TH_FIN;
13744 					tcp->tcp_valid_bits &=
13745 					    ~TCP_OFO_FIN_VALID;
13746 				}
13747 			} else {
13748 				/*
13749 				 * Keep going even with NULL mp.
13750 				 * There may be a useful ACK or something else
13751 				 * we don't want to miss.
13752 				 *
13753 				 * But TCP should not perform fast retransmit
13754 				 * because of the ack number.  TCP uses
13755 				 * seg_len == 0 to determine if it is a pure
13756 				 * ACK.  And this is not a pure ACK.
13757 				 */
13758 				seg_len = 0;
13759 				ofo_seg = B_TRUE;
13760 			}
13761 		}
13762 	} else if (seg_len > 0) {
13763 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13764 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13765 		/*
13766 		 * If an out of order FIN was received before, and the seq
13767 		 * num and len of the new segment match that of the FIN,
13768 		 * put the FIN flag back in.
13769 		 */
13770 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13771 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13772 			flags |= TH_FIN;
13773 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13774 		}
13775 	}
13776 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13777 	if (flags & TH_RST) {
13778 		freemsg(mp);
13779 		switch (tcp->tcp_state) {
13780 		case TCPS_SYN_RCVD:
13781 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13782 			break;
13783 		case TCPS_ESTABLISHED:
13784 		case TCPS_FIN_WAIT_1:
13785 		case TCPS_FIN_WAIT_2:
13786 		case TCPS_CLOSE_WAIT:
13787 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13788 			break;
13789 		case TCPS_CLOSING:
13790 		case TCPS_LAST_ACK:
13791 			(void) tcp_clean_death(tcp, 0, 16);
13792 			break;
13793 		default:
13794 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13795 			(void) tcp_clean_death(tcp, ENXIO, 17);
13796 			break;
13797 		}
13798 		return;
13799 	}
13800 	if (flags & TH_SYN) {
13801 		/*
13802 		 * See RFC 793, Page 71
13803 		 *
13804 		 * The seq number must be in the window as it should
13805 		 * be "fixed" above.  If it is outside window, it should
13806 		 * be already rejected.  Note that we allow seg_seq to be
13807 		 * rnxt + rwnd because we want to accept 0 window probe.
13808 		 */
13809 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13810 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13811 		freemsg(mp);
13812 		/*
13813 		 * If the ACK flag is not set, just use our snxt as the
13814 		 * seq number of the RST segment.
13815 		 */
13816 		if (!(flags & TH_ACK)) {
13817 			seg_ack = tcp->tcp_snxt;
13818 		}
13819 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13820 		    TH_RST|TH_ACK);
13821 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13822 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13823 		return;
13824 	}
13825 	/*
13826 	 * urp could be -1 when the urp field in the packet is 0
13827 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13828 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13829 	 */
13830 	if (flags & TH_URG && urp >= 0) {
13831 		if (!tcp->tcp_urp_last_valid ||
13832 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13833 			if (IPCL_IS_NONSTR(connp)) {
13834 				if (!TCP_IS_DETACHED(tcp)) {
13835 					(*connp->conn_upcalls->su_signal_oob)
13836 					    (connp->conn_upper_handle, urp);
13837 				}
13838 			} else {
13839 				/*
13840 				 * If we haven't generated the signal yet for
13841 				 * this urgent pointer value, do it now.  Also,
13842 				 * send up a zero-length M_DATA indicating
13843 				 * whether or not this is the mark. The latter
13844 				 * is not needed when a T_EXDATA_IND is sent up.
13845 				 * However, if there are allocation failures
13846 				 * this code relies on the sender retransmitting
13847 				 * and the socket code for determining the mark
13848 				 * should not block waiting for the peer to
13849 				 * transmit. Thus, for simplicity we always
13850 				 * send up the mark indication.
13851 				 */
13852 				mp1 = allocb(0, BPRI_MED);
13853 				if (mp1 == NULL) {
13854 					freemsg(mp);
13855 					return;
13856 				}
13857 				if (!TCP_IS_DETACHED(tcp) &&
13858 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13859 				    SIGURG)) {
13860 					/* Try again on the rexmit. */
13861 					freemsg(mp1);
13862 					freemsg(mp);
13863 					return;
13864 				}
13865 				/*
13866 				 * Mark with NOTMARKNEXT for now.
13867 				 * The code below will change this to MARKNEXT
13868 				 * if we are at the mark.
13869 				 *
13870 				 * If there are allocation failures (e.g. in
13871 				 * dupmsg below) the next time tcp_rput_data
13872 				 * sees the urgent segment it will send up the
13873 				 * MSGMARKNEXT message.
13874 				 */
13875 				mp1->b_flag |= MSGNOTMARKNEXT;
13876 				freemsg(tcp->tcp_urp_mark_mp);
13877 				tcp->tcp_urp_mark_mp = mp1;
13878 				flags |= TH_SEND_URP_MARK;
13879 #ifdef DEBUG
13880 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13881 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13882 				    "last %x, %s",
13883 				    seg_seq, urp, tcp->tcp_urp_last,
13884 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13885 #endif /* DEBUG */
13886 			}
13887 			tcp->tcp_urp_last_valid = B_TRUE;
13888 			tcp->tcp_urp_last = urp + seg_seq;
13889 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13890 			/*
13891 			 * An allocation failure prevented the previous
13892 			 * tcp_rput_data from sending up the allocated
13893 			 * MSG*MARKNEXT message - send it up this time
13894 			 * around.
13895 			 */
13896 			flags |= TH_SEND_URP_MARK;
13897 		}
13898 
13899 		/*
13900 		 * If the urgent byte is in this segment, make sure that it is
13901 		 * all by itself.  This makes it much easier to deal with the
13902 		 * possibility of an allocation failure on the T_exdata_ind.
13903 		 * Note that seg_len is the number of bytes in the segment, and
13904 		 * urp is the offset into the segment of the urgent byte.
13905 		 * urp < seg_len means that the urgent byte is in this segment.
13906 		 */
13907 		if (urp < seg_len) {
13908 			if (seg_len != 1) {
13909 				uint32_t  tmp_rnxt;
13910 				/*
13911 				 * Break it up and feed it back in.
13912 				 * Re-attach the IP header.
13913 				 */
13914 				mp->b_rptr = iphdr;
13915 				if (urp > 0) {
13916 					/*
13917 					 * There is stuff before the urgent
13918 					 * byte.
13919 					 */
13920 					mp1 = dupmsg(mp);
13921 					if (!mp1) {
13922 						/*
13923 						 * Trim from urgent byte on.
13924 						 * The rest will come back.
13925 						 */
13926 						(void) adjmsg(mp,
13927 						    urp - seg_len);
13928 						tcp_rput_data(connp,
13929 						    mp, NULL);
13930 						return;
13931 					}
13932 					(void) adjmsg(mp1, urp - seg_len);
13933 					/* Feed this piece back in. */
13934 					tmp_rnxt = tcp->tcp_rnxt;
13935 					tcp_rput_data(connp, mp1, NULL);
13936 					/*
13937 					 * If the data passed back in was not
13938 					 * processed (ie: bad ACK) sending
13939 					 * the remainder back in will cause a
13940 					 * loop. In this case, drop the
13941 					 * packet and let the sender try
13942 					 * sending a good packet.
13943 					 */
13944 					if (tmp_rnxt == tcp->tcp_rnxt) {
13945 						freemsg(mp);
13946 						return;
13947 					}
13948 				}
13949 				if (urp != seg_len - 1) {
13950 					uint32_t  tmp_rnxt;
13951 					/*
13952 					 * There is stuff after the urgent
13953 					 * byte.
13954 					 */
13955 					mp1 = dupmsg(mp);
13956 					if (!mp1) {
13957 						/*
13958 						 * Trim everything beyond the
13959 						 * urgent byte.  The rest will
13960 						 * come back.
13961 						 */
13962 						(void) adjmsg(mp,
13963 						    urp + 1 - seg_len);
13964 						tcp_rput_data(connp,
13965 						    mp, NULL);
13966 						return;
13967 					}
13968 					(void) adjmsg(mp1, urp + 1 - seg_len);
13969 					tmp_rnxt = tcp->tcp_rnxt;
13970 					tcp_rput_data(connp, mp1, NULL);
13971 					/*
13972 					 * If the data passed back in was not
13973 					 * processed (ie: bad ACK) sending
13974 					 * the remainder back in will cause a
13975 					 * loop. In this case, drop the
13976 					 * packet and let the sender try
13977 					 * sending a good packet.
13978 					 */
13979 					if (tmp_rnxt == tcp->tcp_rnxt) {
13980 						freemsg(mp);
13981 						return;
13982 					}
13983 				}
13984 				tcp_rput_data(connp, mp, NULL);
13985 				return;
13986 			}
13987 			/*
13988 			 * This segment contains only the urgent byte.  We
13989 			 * have to allocate the T_exdata_ind, if we can.
13990 			 */
13991 			if (IPCL_IS_NONSTR(connp)) {
13992 				int error;
13993 
13994 				(*connp->conn_upcalls->su_recv)
13995 				    (connp->conn_upper_handle, mp, seg_len,
13996 				    MSG_OOB, &error, NULL);
13997 				mp = NULL;
13998 				goto update_ack;
13999 			} else if (!tcp->tcp_urp_mp) {
14000 				struct T_exdata_ind *tei;
14001 				mp1 = allocb(sizeof (struct T_exdata_ind),
14002 				    BPRI_MED);
14003 				if (!mp1) {
14004 					/*
14005 					 * Sigh... It'll be back.
14006 					 * Generate any MSG*MARK message now.
14007 					 */
14008 					freemsg(mp);
14009 					seg_len = 0;
14010 					if (flags & TH_SEND_URP_MARK) {
14011 
14012 
14013 						ASSERT(tcp->tcp_urp_mark_mp);
14014 						tcp->tcp_urp_mark_mp->b_flag &=
14015 						    ~MSGNOTMARKNEXT;
14016 						tcp->tcp_urp_mark_mp->b_flag |=
14017 						    MSGMARKNEXT;
14018 					}
14019 					goto ack_check;
14020 				}
14021 				mp1->b_datap->db_type = M_PROTO;
14022 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14023 				tei->PRIM_type = T_EXDATA_IND;
14024 				tei->MORE_flag = 0;
14025 				mp1->b_wptr = (uchar_t *)&tei[1];
14026 				tcp->tcp_urp_mp = mp1;
14027 #ifdef DEBUG
14028 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14029 				    "tcp_rput: allocated exdata_ind %s",
14030 				    tcp_display(tcp, NULL,
14031 				    DISP_PORT_ONLY));
14032 #endif /* DEBUG */
14033 				/*
14034 				 * There is no need to send a separate MSG*MARK
14035 				 * message since the T_EXDATA_IND will be sent
14036 				 * now.
14037 				 */
14038 				flags &= ~TH_SEND_URP_MARK;
14039 				freemsg(tcp->tcp_urp_mark_mp);
14040 				tcp->tcp_urp_mark_mp = NULL;
14041 			}
14042 			/*
14043 			 * Now we are all set.  On the next putnext upstream,
14044 			 * tcp_urp_mp will be non-NULL and will get prepended
14045 			 * to what has to be this piece containing the urgent
14046 			 * byte.  If for any reason we abort this segment below,
14047 			 * if it comes back, we will have this ready, or it
14048 			 * will get blown off in close.
14049 			 */
14050 		} else if (urp == seg_len) {
14051 			/*
14052 			 * The urgent byte is the next byte after this sequence
14053 			 * number. If there is data it is marked with
14054 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14055 			 * since it is not needed. Otherwise, if the code
14056 			 * above just allocated a zero-length tcp_urp_mark_mp
14057 			 * message, that message is tagged with MSGMARKNEXT.
14058 			 * Sending up these MSGMARKNEXT messages makes
14059 			 * SIOCATMARK work correctly even though
14060 			 * the T_EXDATA_IND will not be sent up until the
14061 			 * urgent byte arrives.
14062 			 */
14063 			if (seg_len != 0) {
14064 				flags |= TH_MARKNEXT_NEEDED;
14065 				freemsg(tcp->tcp_urp_mark_mp);
14066 				tcp->tcp_urp_mark_mp = NULL;
14067 				flags &= ~TH_SEND_URP_MARK;
14068 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14069 				flags |= TH_SEND_URP_MARK;
14070 				tcp->tcp_urp_mark_mp->b_flag &=
14071 				    ~MSGNOTMARKNEXT;
14072 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14073 			}
14074 #ifdef DEBUG
14075 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14076 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14077 			    seg_len, flags,
14078 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14079 #endif /* DEBUG */
14080 		}
14081 #ifdef DEBUG
14082 		else {
14083 			/* Data left until we hit mark */
14084 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14085 			    "tcp_rput: URP %d bytes left, %s",
14086 			    urp - seg_len, tcp_display(tcp, NULL,
14087 			    DISP_PORT_ONLY));
14088 		}
14089 #endif /* DEBUG */
14090 	}
14091 
14092 process_ack:
14093 	if (!(flags & TH_ACK)) {
14094 		freemsg(mp);
14095 		goto xmit_check;
14096 	}
14097 	}
14098 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14099 
14100 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14101 		tcp->tcp_ip_forward_progress = B_TRUE;
14102 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14103 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
14104 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
14105 			/* 3-way handshake complete - pass up the T_CONN_IND */
14106 			tcp_t	*listener = tcp->tcp_listener;
14107 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14108 
14109 			tcp->tcp_tconnind_started = B_TRUE;
14110 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14111 			/*
14112 			 * We are here means eager is fine but it can
14113 			 * get a TH_RST at any point between now and till
14114 			 * accept completes and disappear. We need to
14115 			 * ensure that reference to eager is valid after
14116 			 * we get out of eager's perimeter. So we do
14117 			 * an extra refhold.
14118 			 */
14119 			CONN_INC_REF(connp);
14120 
14121 			/*
14122 			 * The listener also exists because of the refhold
14123 			 * done in tcp_conn_request. Its possible that it
14124 			 * might have closed. We will check that once we
14125 			 * get inside listeners context.
14126 			 */
14127 			CONN_INC_REF(listener->tcp_connp);
14128 			if (listener->tcp_connp->conn_sqp ==
14129 			    connp->conn_sqp) {
14130 				/*
14131 				 * We optimize by not calling an SQUEUE_ENTER
14132 				 * on the listener since we know that the
14133 				 * listener and eager squeues are the same.
14134 				 * We are able to make this check safely only
14135 				 * because neither the eager nor the listener
14136 				 * can change its squeue. Only an active connect
14137 				 * can change its squeue
14138 				 */
14139 				tcp_send_conn_ind(listener->tcp_connp, mp,
14140 				    listener->tcp_connp->conn_sqp);
14141 				CONN_DEC_REF(listener->tcp_connp);
14142 			} else if (!tcp->tcp_loopback) {
14143 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14144 				    mp, tcp_send_conn_ind,
14145 				    listener->tcp_connp, SQ_FILL,
14146 				    SQTAG_TCP_CONN_IND);
14147 			} else {
14148 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14149 				    mp, tcp_send_conn_ind,
14150 				    listener->tcp_connp, SQ_PROCESS,
14151 				    SQTAG_TCP_CONN_IND);
14152 			}
14153 		}
14154 
14155 		if (tcp->tcp_active_open) {
14156 			/*
14157 			 * We are seeing the final ack in the three way
14158 			 * hand shake of a active open'ed connection
14159 			 * so we must send up a T_CONN_CON
14160 			 */
14161 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14162 				freemsg(mp);
14163 				return;
14164 			}
14165 			/*
14166 			 * Don't fuse the loopback endpoints for
14167 			 * simultaneous active opens.
14168 			 */
14169 			if (tcp->tcp_loopback) {
14170 				TCP_STAT(tcps, tcp_fusion_unfusable);
14171 				tcp->tcp_unfusable = B_TRUE;
14172 			}
14173 		}
14174 
14175 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14176 		bytes_acked--;
14177 		/* SYN was acked - making progress */
14178 		if (tcp->tcp_ipversion == IPV6_VERSION)
14179 			tcp->tcp_ip_forward_progress = B_TRUE;
14180 
14181 		/*
14182 		 * If SYN was retransmitted, need to reset all
14183 		 * retransmission info as this segment will be
14184 		 * treated as a dup ACK.
14185 		 */
14186 		if (tcp->tcp_rexmit) {
14187 			tcp->tcp_rexmit = B_FALSE;
14188 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14189 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14190 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14191 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14192 			tcp->tcp_ms_we_have_waited = 0;
14193 			tcp->tcp_cwnd = mss;
14194 		}
14195 
14196 		/*
14197 		 * We set the send window to zero here.
14198 		 * This is needed if there is data to be
14199 		 * processed already on the queue.
14200 		 * Later (at swnd_update label), the
14201 		 * "new_swnd > tcp_swnd" condition is satisfied
14202 		 * the XMIT_NEEDED flag is set in the current
14203 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14204 		 * called if there is already data on queue in
14205 		 * this state.
14206 		 */
14207 		tcp->tcp_swnd = 0;
14208 
14209 		if (new_swnd > tcp->tcp_max_swnd)
14210 			tcp->tcp_max_swnd = new_swnd;
14211 		tcp->tcp_swl1 = seg_seq;
14212 		tcp->tcp_swl2 = seg_ack;
14213 		tcp->tcp_state = TCPS_ESTABLISHED;
14214 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14215 
14216 		/* Fuse when both sides are in ESTABLISHED state */
14217 		if (tcp->tcp_loopback && do_tcp_fusion)
14218 			tcp_fuse(tcp, iphdr, tcph);
14219 
14220 	}
14221 	/* This code follows 4.4BSD-Lite2 mostly. */
14222 	if (bytes_acked < 0)
14223 		goto est;
14224 
14225 	/*
14226 	 * If TCP is ECN capable and the congestion experience bit is
14227 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14228 	 * done once per window (or more loosely, per RTT).
14229 	 */
14230 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14231 		tcp->tcp_cwr = B_FALSE;
14232 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14233 		if (!tcp->tcp_cwr) {
14234 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14235 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14236 			tcp->tcp_cwnd = npkt * mss;
14237 			/*
14238 			 * If the cwnd is 0, use the timer to clock out
14239 			 * new segments.  This is required by the ECN spec.
14240 			 */
14241 			if (npkt == 0) {
14242 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14243 				/*
14244 				 * This makes sure that when the ACK comes
14245 				 * back, we will increase tcp_cwnd by 1 MSS.
14246 				 */
14247 				tcp->tcp_cwnd_cnt = 0;
14248 			}
14249 			tcp->tcp_cwr = B_TRUE;
14250 			/*
14251 			 * This marks the end of the current window of in
14252 			 * flight data.  That is why we don't use
14253 			 * tcp_suna + tcp_swnd.  Only data in flight can
14254 			 * provide ECN info.
14255 			 */
14256 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14257 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14258 		}
14259 	}
14260 
14261 	mp1 = tcp->tcp_xmit_head;
14262 	if (bytes_acked == 0) {
14263 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14264 			int dupack_cnt;
14265 
14266 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14267 			/*
14268 			 * Fast retransmit.  When we have seen exactly three
14269 			 * identical ACKs while we have unacked data
14270 			 * outstanding we take it as a hint that our peer
14271 			 * dropped something.
14272 			 *
14273 			 * If TCP is retransmitting, don't do fast retransmit.
14274 			 */
14275 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14276 			    ! tcp->tcp_rexmit) {
14277 				/* Do Limited Transmit */
14278 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14279 				    tcps->tcps_dupack_fast_retransmit) {
14280 					/*
14281 					 * RFC 3042
14282 					 *
14283 					 * What we need to do is temporarily
14284 					 * increase tcp_cwnd so that new
14285 					 * data can be sent if it is allowed
14286 					 * by the receive window (tcp_rwnd).
14287 					 * tcp_wput_data() will take care of
14288 					 * the rest.
14289 					 *
14290 					 * If the connection is SACK capable,
14291 					 * only do limited xmit when there
14292 					 * is SACK info.
14293 					 *
14294 					 * Note how tcp_cwnd is incremented.
14295 					 * The first dup ACK will increase
14296 					 * it by 1 MSS.  The second dup ACK
14297 					 * will increase it by 2 MSS.  This
14298 					 * means that only 1 new segment will
14299 					 * be sent for each dup ACK.
14300 					 */
14301 					if (tcp->tcp_unsent > 0 &&
14302 					    (!tcp->tcp_snd_sack_ok ||
14303 					    (tcp->tcp_snd_sack_ok &&
14304 					    tcp->tcp_notsack_list != NULL))) {
14305 						tcp->tcp_cwnd += mss <<
14306 						    (tcp->tcp_dupack_cnt - 1);
14307 						flags |= TH_LIMIT_XMIT;
14308 					}
14309 				} else if (dupack_cnt ==
14310 				    tcps->tcps_dupack_fast_retransmit) {
14311 
14312 				/*
14313 				 * If we have reduced tcp_ssthresh
14314 				 * because of ECN, do not reduce it again
14315 				 * unless it is already one window of data
14316 				 * away.  After one window of data, tcp_cwr
14317 				 * should then be cleared.  Note that
14318 				 * for non ECN capable connection, tcp_cwr
14319 				 * should always be false.
14320 				 *
14321 				 * Adjust cwnd since the duplicate
14322 				 * ack indicates that a packet was
14323 				 * dropped (due to congestion.)
14324 				 */
14325 				if (!tcp->tcp_cwr) {
14326 					npkt = ((tcp->tcp_snxt -
14327 					    tcp->tcp_suna) >> 1) / mss;
14328 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14329 					    mss;
14330 					tcp->tcp_cwnd = (npkt +
14331 					    tcp->tcp_dupack_cnt) * mss;
14332 				}
14333 				if (tcp->tcp_ecn_ok) {
14334 					tcp->tcp_cwr = B_TRUE;
14335 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14336 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14337 				}
14338 
14339 				/*
14340 				 * We do Hoe's algorithm.  Refer to her
14341 				 * paper "Improving the Start-up Behavior
14342 				 * of a Congestion Control Scheme for TCP,"
14343 				 * appeared in SIGCOMM'96.
14344 				 *
14345 				 * Save highest seq no we have sent so far.
14346 				 * Be careful about the invisible FIN byte.
14347 				 */
14348 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14349 				    (tcp->tcp_unsent == 0)) {
14350 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14351 				} else {
14352 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14353 				}
14354 
14355 				/*
14356 				 * Do not allow bursty traffic during.
14357 				 * fast recovery.  Refer to Fall and Floyd's
14358 				 * paper "Simulation-based Comparisons of
14359 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14360 				 * This is a best current practise.
14361 				 */
14362 				tcp->tcp_snd_burst = TCP_CWND_SS;
14363 
14364 				/*
14365 				 * For SACK:
14366 				 * Calculate tcp_pipe, which is the
14367 				 * estimated number of bytes in
14368 				 * network.
14369 				 *
14370 				 * tcp_fack is the highest sack'ed seq num
14371 				 * TCP has received.
14372 				 *
14373 				 * tcp_pipe is explained in the above quoted
14374 				 * Fall and Floyd's paper.  tcp_fack is
14375 				 * explained in Mathis and Mahdavi's
14376 				 * "Forward Acknowledgment: Refining TCP
14377 				 * Congestion Control" in SIGCOMM '96.
14378 				 */
14379 				if (tcp->tcp_snd_sack_ok) {
14380 					ASSERT(tcp->tcp_sack_info != NULL);
14381 					if (tcp->tcp_notsack_list != NULL) {
14382 						tcp->tcp_pipe = tcp->tcp_snxt -
14383 						    tcp->tcp_fack;
14384 						tcp->tcp_sack_snxt = seg_ack;
14385 						flags |= TH_NEED_SACK_REXMIT;
14386 					} else {
14387 						/*
14388 						 * Always initialize tcp_pipe
14389 						 * even though we don't have
14390 						 * any SACK info.  If later
14391 						 * we get SACK info and
14392 						 * tcp_pipe is not initialized,
14393 						 * funny things will happen.
14394 						 */
14395 						tcp->tcp_pipe =
14396 						    tcp->tcp_cwnd_ssthresh;
14397 					}
14398 				} else {
14399 					flags |= TH_REXMIT_NEEDED;
14400 				} /* tcp_snd_sack_ok */
14401 
14402 				} else {
14403 					/*
14404 					 * Here we perform congestion
14405 					 * avoidance, but NOT slow start.
14406 					 * This is known as the Fast
14407 					 * Recovery Algorithm.
14408 					 */
14409 					if (tcp->tcp_snd_sack_ok &&
14410 					    tcp->tcp_notsack_list != NULL) {
14411 						flags |= TH_NEED_SACK_REXMIT;
14412 						tcp->tcp_pipe -= mss;
14413 						if (tcp->tcp_pipe < 0)
14414 							tcp->tcp_pipe = 0;
14415 					} else {
14416 					/*
14417 					 * We know that one more packet has
14418 					 * left the pipe thus we can update
14419 					 * cwnd.
14420 					 */
14421 					cwnd = tcp->tcp_cwnd + mss;
14422 					if (cwnd > tcp->tcp_cwnd_max)
14423 						cwnd = tcp->tcp_cwnd_max;
14424 					tcp->tcp_cwnd = cwnd;
14425 					if (tcp->tcp_unsent > 0)
14426 						flags |= TH_XMIT_NEEDED;
14427 					}
14428 				}
14429 			}
14430 		} else if (tcp->tcp_zero_win_probe) {
14431 			/*
14432 			 * If the window has opened, need to arrange
14433 			 * to send additional data.
14434 			 */
14435 			if (new_swnd != 0) {
14436 				/* tcp_suna != tcp_snxt */
14437 				/* Packet contains a window update */
14438 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14439 				tcp->tcp_zero_win_probe = 0;
14440 				tcp->tcp_timer_backoff = 0;
14441 				tcp->tcp_ms_we_have_waited = 0;
14442 
14443 				/*
14444 				 * Transmit starting with tcp_suna since
14445 				 * the one byte probe is not ack'ed.
14446 				 * If TCP has sent more than one identical
14447 				 * probe, tcp_rexmit will be set.  That means
14448 				 * tcp_ss_rexmit() will send out the one
14449 				 * byte along with new data.  Otherwise,
14450 				 * fake the retransmission.
14451 				 */
14452 				flags |= TH_XMIT_NEEDED;
14453 				if (!tcp->tcp_rexmit) {
14454 					tcp->tcp_rexmit = B_TRUE;
14455 					tcp->tcp_dupack_cnt = 0;
14456 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14457 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14458 				}
14459 			}
14460 		}
14461 		goto swnd_update;
14462 	}
14463 
14464 	/*
14465 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14466 	 * If the ACK value acks something that we have not yet sent, it might
14467 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14468 	 * other side.
14469 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14470 	 * state is handled above, so we can always just drop the segment and
14471 	 * send an ACK here.
14472 	 *
14473 	 * Should we send ACKs in response to ACK only segments?
14474 	 */
14475 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14476 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14477 		/* drop the received segment */
14478 		freemsg(mp);
14479 
14480 		/*
14481 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14482 		 * greater than 0, check if the number of such
14483 		 * bogus ACks is greater than that count.  If yes,
14484 		 * don't send back any ACK.  This prevents TCP from
14485 		 * getting into an ACK storm if somehow an attacker
14486 		 * successfully spoofs an acceptable segment to our
14487 		 * peer.
14488 		 */
14489 		if (tcp_drop_ack_unsent_cnt > 0 &&
14490 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14491 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14492 			return;
14493 		}
14494 		mp = tcp_ack_mp(tcp);
14495 		if (mp != NULL) {
14496 			BUMP_LOCAL(tcp->tcp_obsegs);
14497 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14498 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14499 		}
14500 		return;
14501 	}
14502 
14503 	/*
14504 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14505 	 * blocks that are covered by this ACK.
14506 	 */
14507 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14508 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14509 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14510 	}
14511 
14512 	/*
14513 	 * If we got an ACK after fast retransmit, check to see
14514 	 * if it is a partial ACK.  If it is not and the congestion
14515 	 * window was inflated to account for the other side's
14516 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14517 	 */
14518 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14519 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14520 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14521 			tcp->tcp_dupack_cnt = 0;
14522 			/*
14523 			 * Restore the orig tcp_cwnd_ssthresh after
14524 			 * fast retransmit phase.
14525 			 */
14526 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14527 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14528 			}
14529 			tcp->tcp_rexmit_max = seg_ack;
14530 			tcp->tcp_cwnd_cnt = 0;
14531 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14532 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14533 
14534 			/*
14535 			 * Remove all notsack info to avoid confusion with
14536 			 * the next fast retrasnmit/recovery phase.
14537 			 */
14538 			if (tcp->tcp_snd_sack_ok &&
14539 			    tcp->tcp_notsack_list != NULL) {
14540 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14541 			}
14542 		} else {
14543 			if (tcp->tcp_snd_sack_ok &&
14544 			    tcp->tcp_notsack_list != NULL) {
14545 				flags |= TH_NEED_SACK_REXMIT;
14546 				tcp->tcp_pipe -= mss;
14547 				if (tcp->tcp_pipe < 0)
14548 					tcp->tcp_pipe = 0;
14549 			} else {
14550 				/*
14551 				 * Hoe's algorithm:
14552 				 *
14553 				 * Retransmit the unack'ed segment and
14554 				 * restart fast recovery.  Note that we
14555 				 * need to scale back tcp_cwnd to the
14556 				 * original value when we started fast
14557 				 * recovery.  This is to prevent overly
14558 				 * aggressive behaviour in sending new
14559 				 * segments.
14560 				 */
14561 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14562 				    tcps->tcps_dupack_fast_retransmit * mss;
14563 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14564 				flags |= TH_REXMIT_NEEDED;
14565 			}
14566 		}
14567 	} else {
14568 		tcp->tcp_dupack_cnt = 0;
14569 		if (tcp->tcp_rexmit) {
14570 			/*
14571 			 * TCP is retranmitting.  If the ACK ack's all
14572 			 * outstanding data, update tcp_rexmit_max and
14573 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14574 			 * to the correct value.
14575 			 *
14576 			 * Note that SEQ_LEQ() is used.  This is to avoid
14577 			 * unnecessary fast retransmit caused by dup ACKs
14578 			 * received when TCP does slow start retransmission
14579 			 * after a time out.  During this phase, TCP may
14580 			 * send out segments which are already received.
14581 			 * This causes dup ACKs to be sent back.
14582 			 */
14583 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14584 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14585 					tcp->tcp_rexmit_nxt = seg_ack;
14586 				}
14587 				if (seg_ack != tcp->tcp_rexmit_max) {
14588 					flags |= TH_XMIT_NEEDED;
14589 				}
14590 			} else {
14591 				tcp->tcp_rexmit = B_FALSE;
14592 				tcp->tcp_xmit_zc_clean = B_FALSE;
14593 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14594 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14595 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14596 			}
14597 			tcp->tcp_ms_we_have_waited = 0;
14598 		}
14599 	}
14600 
14601 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14602 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14603 	tcp->tcp_suna = seg_ack;
14604 	if (tcp->tcp_zero_win_probe != 0) {
14605 		tcp->tcp_zero_win_probe = 0;
14606 		tcp->tcp_timer_backoff = 0;
14607 	}
14608 
14609 	/*
14610 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14611 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14612 	 * will not reach here.
14613 	 */
14614 	if (mp1 == NULL) {
14615 		goto fin_acked;
14616 	}
14617 
14618 	/*
14619 	 * Update the congestion window.
14620 	 *
14621 	 * If TCP is not ECN capable or TCP is ECN capable but the
14622 	 * congestion experience bit is not set, increase the tcp_cwnd as
14623 	 * usual.
14624 	 */
14625 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14626 		cwnd = tcp->tcp_cwnd;
14627 		add = mss;
14628 
14629 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14630 			/*
14631 			 * This is to prevent an increase of less than 1 MSS of
14632 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14633 			 * may send out tinygrams in order to preserve mblk
14634 			 * boundaries.
14635 			 *
14636 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14637 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14638 			 * increased by 1 MSS for every RTTs.
14639 			 */
14640 			if (tcp->tcp_cwnd_cnt <= 0) {
14641 				tcp->tcp_cwnd_cnt = cwnd + add;
14642 			} else {
14643 				tcp->tcp_cwnd_cnt -= add;
14644 				add = 0;
14645 			}
14646 		}
14647 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14648 	}
14649 
14650 	/* See if the latest urgent data has been acknowledged */
14651 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14652 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14653 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14654 
14655 	/* Can we update the RTT estimates? */
14656 	if (tcp->tcp_snd_ts_ok) {
14657 		/* Ignore zero timestamp echo-reply. */
14658 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14659 			tcp_set_rto(tcp, (int32_t)lbolt -
14660 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14661 		}
14662 
14663 		/* If needed, restart the timer. */
14664 		if (tcp->tcp_set_timer == 1) {
14665 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14666 			tcp->tcp_set_timer = 0;
14667 		}
14668 		/*
14669 		 * Update tcp_csuna in case the other side stops sending
14670 		 * us timestamps.
14671 		 */
14672 		tcp->tcp_csuna = tcp->tcp_snxt;
14673 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14674 		/*
14675 		 * An ACK sequence we haven't seen before, so get the RTT
14676 		 * and update the RTO. But first check if the timestamp is
14677 		 * valid to use.
14678 		 */
14679 		if ((mp1->b_next != NULL) &&
14680 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14681 			tcp_set_rto(tcp, (int32_t)lbolt -
14682 			    (int32_t)(intptr_t)mp1->b_prev);
14683 		else
14684 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14685 
14686 		/* Remeber the last sequence to be ACKed */
14687 		tcp->tcp_csuna = seg_ack;
14688 		if (tcp->tcp_set_timer == 1) {
14689 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14690 			tcp->tcp_set_timer = 0;
14691 		}
14692 	} else {
14693 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14694 	}
14695 
14696 	/* Eat acknowledged bytes off the xmit queue. */
14697 	for (;;) {
14698 		mblk_t	*mp2;
14699 		uchar_t	*wptr;
14700 
14701 		wptr = mp1->b_wptr;
14702 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14703 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14704 		if (bytes_acked < 0) {
14705 			mp1->b_rptr = wptr + bytes_acked;
14706 			/*
14707 			 * Set a new timestamp if all the bytes timed by the
14708 			 * old timestamp have been ack'ed.
14709 			 */
14710 			if (SEQ_GT(seg_ack,
14711 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14712 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14713 				mp1->b_next = NULL;
14714 			}
14715 			break;
14716 		}
14717 		mp1->b_next = NULL;
14718 		mp1->b_prev = NULL;
14719 		mp2 = mp1;
14720 		mp1 = mp1->b_cont;
14721 
14722 		/*
14723 		 * This notification is required for some zero-copy
14724 		 * clients to maintain a copy semantic. After the data
14725 		 * is ack'ed, client is safe to modify or reuse the buffer.
14726 		 */
14727 		if (tcp->tcp_snd_zcopy_aware &&
14728 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14729 			tcp_zcopy_notify(tcp);
14730 		freeb(mp2);
14731 		if (bytes_acked == 0) {
14732 			if (mp1 == NULL) {
14733 				/* Everything is ack'ed, clear the tail. */
14734 				tcp->tcp_xmit_tail = NULL;
14735 				/*
14736 				 * Cancel the timer unless we are still
14737 				 * waiting for an ACK for the FIN packet.
14738 				 */
14739 				if (tcp->tcp_timer_tid != 0 &&
14740 				    tcp->tcp_snxt == tcp->tcp_suna) {
14741 					(void) TCP_TIMER_CANCEL(tcp,
14742 					    tcp->tcp_timer_tid);
14743 					tcp->tcp_timer_tid = 0;
14744 				}
14745 				goto pre_swnd_update;
14746 			}
14747 			if (mp2 != tcp->tcp_xmit_tail)
14748 				break;
14749 			tcp->tcp_xmit_tail = mp1;
14750 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14751 			    (uintptr_t)INT_MAX);
14752 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14753 			    mp1->b_rptr);
14754 			break;
14755 		}
14756 		if (mp1 == NULL) {
14757 			/*
14758 			 * More was acked but there is nothing more
14759 			 * outstanding.  This means that the FIN was
14760 			 * just acked or that we're talking to a clown.
14761 			 */
14762 fin_acked:
14763 			ASSERT(tcp->tcp_fin_sent);
14764 			tcp->tcp_xmit_tail = NULL;
14765 			if (tcp->tcp_fin_sent) {
14766 				/* FIN was acked - making progress */
14767 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14768 				    !tcp->tcp_fin_acked)
14769 					tcp->tcp_ip_forward_progress = B_TRUE;
14770 				tcp->tcp_fin_acked = B_TRUE;
14771 				if (tcp->tcp_linger_tid != 0 &&
14772 				    TCP_TIMER_CANCEL(tcp,
14773 				    tcp->tcp_linger_tid) >= 0) {
14774 					tcp_stop_lingering(tcp);
14775 					freemsg(mp);
14776 					mp = NULL;
14777 				}
14778 			} else {
14779 				/*
14780 				 * We should never get here because
14781 				 * we have already checked that the
14782 				 * number of bytes ack'ed should be
14783 				 * smaller than or equal to what we
14784 				 * have sent so far (it is the
14785 				 * acceptability check of the ACK).
14786 				 * We can only get here if the send
14787 				 * queue is corrupted.
14788 				 *
14789 				 * Terminate the connection and
14790 				 * panic the system.  It is better
14791 				 * for us to panic instead of
14792 				 * continuing to avoid other disaster.
14793 				 */
14794 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14795 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14796 				panic("Memory corruption "
14797 				    "detected for connection %s.",
14798 				    tcp_display(tcp, NULL,
14799 				    DISP_ADDR_AND_PORT));
14800 				/*NOTREACHED*/
14801 			}
14802 			goto pre_swnd_update;
14803 		}
14804 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14805 	}
14806 	if (tcp->tcp_unsent) {
14807 		flags |= TH_XMIT_NEEDED;
14808 	}
14809 pre_swnd_update:
14810 	tcp->tcp_xmit_head = mp1;
14811 swnd_update:
14812 	/*
14813 	 * The following check is different from most other implementations.
14814 	 * For bi-directional transfer, when segments are dropped, the
14815 	 * "normal" check will not accept a window update in those
14816 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14817 	 * segments which are outside receiver's window.  As TCP accepts
14818 	 * the ack in those retransmitted segments, if the window update in
14819 	 * the same segment is not accepted, TCP will incorrectly calculates
14820 	 * that it can send more segments.  This can create a deadlock
14821 	 * with the receiver if its window becomes zero.
14822 	 */
14823 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14824 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14825 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14826 		/*
14827 		 * The criteria for update is:
14828 		 *
14829 		 * 1. the segment acknowledges some data.  Or
14830 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14831 		 * 3. the segment is not old and the advertised window is
14832 		 * larger than the previous advertised window.
14833 		 */
14834 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14835 			flags |= TH_XMIT_NEEDED;
14836 		tcp->tcp_swnd = new_swnd;
14837 		if (new_swnd > tcp->tcp_max_swnd)
14838 			tcp->tcp_max_swnd = new_swnd;
14839 		tcp->tcp_swl1 = seg_seq;
14840 		tcp->tcp_swl2 = seg_ack;
14841 	}
14842 est:
14843 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14844 
14845 		switch (tcp->tcp_state) {
14846 		case TCPS_FIN_WAIT_1:
14847 			if (tcp->tcp_fin_acked) {
14848 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14849 				/*
14850 				 * We implement the non-standard BSD/SunOS
14851 				 * FIN_WAIT_2 flushing algorithm.
14852 				 * If there is no user attached to this
14853 				 * TCP endpoint, then this TCP struct
14854 				 * could hang around forever in FIN_WAIT_2
14855 				 * state if the peer forgets to send us
14856 				 * a FIN.  To prevent this, we wait only
14857 				 * 2*MSL (a convenient time value) for
14858 				 * the FIN to arrive.  If it doesn't show up,
14859 				 * we flush the TCP endpoint.  This algorithm,
14860 				 * though a violation of RFC-793, has worked
14861 				 * for over 10 years in BSD systems.
14862 				 * Note: SunOS 4.x waits 675 seconds before
14863 				 * flushing the FIN_WAIT_2 connection.
14864 				 */
14865 				TCP_TIMER_RESTART(tcp,
14866 				    tcps->tcps_fin_wait_2_flush_interval);
14867 			}
14868 			break;
14869 		case TCPS_FIN_WAIT_2:
14870 			break;	/* Shutdown hook? */
14871 		case TCPS_LAST_ACK:
14872 			freemsg(mp);
14873 			if (tcp->tcp_fin_acked) {
14874 				(void) tcp_clean_death(tcp, 0, 19);
14875 				return;
14876 			}
14877 			goto xmit_check;
14878 		case TCPS_CLOSING:
14879 			if (tcp->tcp_fin_acked) {
14880 				tcp->tcp_state = TCPS_TIME_WAIT;
14881 				/*
14882 				 * Unconditionally clear the exclusive binding
14883 				 * bit so this TIME-WAIT connection won't
14884 				 * interfere with new ones.
14885 				 */
14886 				tcp->tcp_exclbind = 0;
14887 				if (!TCP_IS_DETACHED(tcp)) {
14888 					TCP_TIMER_RESTART(tcp,
14889 					    tcps->tcps_time_wait_interval);
14890 				} else {
14891 					tcp_time_wait_append(tcp);
14892 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14893 				}
14894 			}
14895 			/*FALLTHRU*/
14896 		case TCPS_CLOSE_WAIT:
14897 			freemsg(mp);
14898 			goto xmit_check;
14899 		default:
14900 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14901 			break;
14902 		}
14903 	}
14904 	if (flags & TH_FIN) {
14905 		/* Make sure we ack the fin */
14906 		flags |= TH_ACK_NEEDED;
14907 		if (!tcp->tcp_fin_rcvd) {
14908 			tcp->tcp_fin_rcvd = B_TRUE;
14909 			tcp->tcp_rnxt++;
14910 			tcph = tcp->tcp_tcph;
14911 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14912 
14913 			/*
14914 			 * Generate the ordrel_ind at the end unless we
14915 			 * are an eager guy.
14916 			 * In the eager case tcp_rsrv will do this when run
14917 			 * after tcp_accept is done.
14918 			 */
14919 			if (tcp->tcp_listener == NULL &&
14920 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14921 				flags |= TH_ORDREL_NEEDED;
14922 			switch (tcp->tcp_state) {
14923 			case TCPS_SYN_RCVD:
14924 			case TCPS_ESTABLISHED:
14925 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14926 				/* Keepalive? */
14927 				break;
14928 			case TCPS_FIN_WAIT_1:
14929 				if (!tcp->tcp_fin_acked) {
14930 					tcp->tcp_state = TCPS_CLOSING;
14931 					break;
14932 				}
14933 				/* FALLTHRU */
14934 			case TCPS_FIN_WAIT_2:
14935 				tcp->tcp_state = TCPS_TIME_WAIT;
14936 				/*
14937 				 * Unconditionally clear the exclusive binding
14938 				 * bit so this TIME-WAIT connection won't
14939 				 * interfere with new ones.
14940 				 */
14941 				tcp->tcp_exclbind = 0;
14942 				if (!TCP_IS_DETACHED(tcp)) {
14943 					TCP_TIMER_RESTART(tcp,
14944 					    tcps->tcps_time_wait_interval);
14945 				} else {
14946 					tcp_time_wait_append(tcp);
14947 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14948 				}
14949 				if (seg_len) {
14950 					/*
14951 					 * implies data piggybacked on FIN.
14952 					 * break to handle data.
14953 					 */
14954 					break;
14955 				}
14956 				freemsg(mp);
14957 				goto ack_check;
14958 			}
14959 		}
14960 	}
14961 	if (mp == NULL)
14962 		goto xmit_check;
14963 	if (seg_len == 0) {
14964 		freemsg(mp);
14965 		goto xmit_check;
14966 	}
14967 	if (mp->b_rptr == mp->b_wptr) {
14968 		/*
14969 		 * The header has been consumed, so we remove the
14970 		 * zero-length mblk here.
14971 		 */
14972 		mp1 = mp;
14973 		mp = mp->b_cont;
14974 		freeb(mp1);
14975 	}
14976 update_ack:
14977 	tcph = tcp->tcp_tcph;
14978 	tcp->tcp_rack_cnt++;
14979 	{
14980 		uint32_t cur_max;
14981 
14982 		cur_max = tcp->tcp_rack_cur_max;
14983 		if (tcp->tcp_rack_cnt >= cur_max) {
14984 			/*
14985 			 * We have more unacked data than we should - send
14986 			 * an ACK now.
14987 			 */
14988 			flags |= TH_ACK_NEEDED;
14989 			cur_max++;
14990 			if (cur_max > tcp->tcp_rack_abs_max)
14991 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14992 			else
14993 				tcp->tcp_rack_cur_max = cur_max;
14994 		} else if (TCP_IS_DETACHED(tcp)) {
14995 			/* We don't have an ACK timer for detached TCP. */
14996 			flags |= TH_ACK_NEEDED;
14997 		} else if (seg_len < mss) {
14998 			/*
14999 			 * If we get a segment that is less than an mss, and we
15000 			 * already have unacknowledged data, and the amount
15001 			 * unacknowledged is not a multiple of mss, then we
15002 			 * better generate an ACK now.  Otherwise, this may be
15003 			 * the tail piece of a transaction, and we would rather
15004 			 * wait for the response.
15005 			 */
15006 			uint32_t udif;
15007 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
15008 			    (uintptr_t)INT_MAX);
15009 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
15010 			if (udif && (udif % mss))
15011 				flags |= TH_ACK_NEEDED;
15012 			else
15013 				flags |= TH_ACK_TIMER_NEEDED;
15014 		} else {
15015 			/* Start delayed ack timer */
15016 			flags |= TH_ACK_TIMER_NEEDED;
15017 		}
15018 	}
15019 	tcp->tcp_rnxt += seg_len;
15020 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15021 
15022 	if (mp == NULL)
15023 		goto xmit_check;
15024 
15025 	/* Update SACK list */
15026 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15027 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15028 		    &(tcp->tcp_num_sack_blk));
15029 	}
15030 
15031 	if (tcp->tcp_urp_mp) {
15032 		tcp->tcp_urp_mp->b_cont = mp;
15033 		mp = tcp->tcp_urp_mp;
15034 		tcp->tcp_urp_mp = NULL;
15035 		/* Ready for a new signal. */
15036 		tcp->tcp_urp_last_valid = B_FALSE;
15037 #ifdef DEBUG
15038 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15039 		    "tcp_rput: sending exdata_ind %s",
15040 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15041 #endif /* DEBUG */
15042 	}
15043 
15044 	/*
15045 	 * Check for ancillary data changes compared to last segment.
15046 	 */
15047 	if (tcp->tcp_ipv6_recvancillary != 0) {
15048 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15049 		ASSERT(mp != NULL);
15050 	}
15051 
15052 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15053 		/*
15054 		 * Side queue inbound data until the accept happens.
15055 		 * tcp_accept/tcp_rput drains this when the accept happens.
15056 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15057 		 * T_EXDATA_IND) it is queued on b_next.
15058 		 * XXX Make urgent data use this. Requires:
15059 		 *	Removing tcp_listener check for TH_URG
15060 		 *	Making M_PCPROTO and MARK messages skip the eager case
15061 		 */
15062 
15063 		if (tcp->tcp_kssl_pending) {
15064 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
15065 			    mblk_t *, mp);
15066 			tcp_kssl_input(tcp, mp);
15067 		} else {
15068 			tcp_rcv_enqueue(tcp, mp, seg_len);
15069 		}
15070 	} else {
15071 		sodirect_t	*sodp = tcp->tcp_sodirect;
15072 
15073 		/*
15074 		 * If an sodirect connection and an enabled sodirect_t then
15075 		 * sodp will be set to point to the tcp_t/sonode_t shared
15076 		 * sodirect_t and the sodirect_t's lock will be held.
15077 		 */
15078 		if (sodp != NULL) {
15079 			mutex_enter(sodp->sod_lockp);
15080 			if (!(sodp->sod_state & SOD_ENABLED) ||
15081 			    (tcp->tcp_kssl_ctx != NULL &&
15082 			    DB_TYPE(mp) == M_DATA)) {
15083 				sodp = NULL;
15084 			}
15085 			mutex_exit(sodp->sod_lockp);
15086 		}
15087 		if (mp->b_datap->db_type != M_DATA ||
15088 		    (flags & TH_MARKNEXT_NEEDED)) {
15089 			if (IPCL_IS_NONSTR(connp)) {
15090 				int error;
15091 
15092 				if ((*connp->conn_upcalls->su_recv)
15093 				    (connp->conn_upper_handle, mp,
15094 				    seg_len, 0, &error, NULL) <= 0) {
15095 					if (error == ENOSPC) {
15096 						tcp->tcp_rwnd -= seg_len;
15097 					} else if (error == EOPNOTSUPP) {
15098 						tcp_rcv_enqueue(tcp, mp,
15099 						    seg_len);
15100 					}
15101 				}
15102 			} else if (sodp != NULL) {
15103 				mutex_enter(sodp->sod_lockp);
15104 				SOD_UIOAFINI(sodp);
15105 				if (!SOD_QEMPTY(sodp) &&
15106 				    (sodp->sod_state & SOD_WAKE_NOT)) {
15107 					flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15108 					/* sod_wakeup() did the mutex_exit() */
15109 				} else {
15110 					mutex_exit(sodp->sod_lockp);
15111 				}
15112 			} else if (tcp->tcp_rcv_list != NULL) {
15113 				flags |= tcp_rcv_drain(tcp);
15114 			}
15115 			ASSERT(tcp->tcp_rcv_list == NULL ||
15116 			    tcp->tcp_fused_sigurg);
15117 
15118 			if (flags & TH_MARKNEXT_NEEDED) {
15119 #ifdef DEBUG
15120 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15121 				    "tcp_rput: sending MSGMARKNEXT %s",
15122 				    tcp_display(tcp, NULL,
15123 				    DISP_PORT_ONLY));
15124 #endif /* DEBUG */
15125 				mp->b_flag |= MSGMARKNEXT;
15126 				flags &= ~TH_MARKNEXT_NEEDED;
15127 			}
15128 
15129 			/* Does this need SSL processing first? */
15130 			if ((tcp->tcp_kssl_ctx != NULL) &&
15131 			    (DB_TYPE(mp) == M_DATA)) {
15132 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15133 				    mblk_t *, mp);
15134 				tcp_kssl_input(tcp, mp);
15135 			} else if (!IPCL_IS_NONSTR(connp)) {
15136 				/* Already handled non-STREAMS case. */
15137 				putnext(tcp->tcp_rq, mp);
15138 				if (!canputnext(tcp->tcp_rq))
15139 					tcp->tcp_rwnd -= seg_len;
15140 			}
15141 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15142 		    (DB_TYPE(mp) == M_DATA)) {
15143 			/* Does this need SSL processing first? */
15144 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
15145 			tcp_kssl_input(tcp, mp);
15146 		} else if (IPCL_IS_NONSTR(connp)) {
15147 			/* Non-STREAMS socket */
15148 			boolean_t push = flags & (TH_PUSH|TH_FIN);
15149 			int	error;
15150 
15151 			if ((*connp->conn_upcalls->su_recv)(
15152 			    connp->conn_upper_handle,
15153 			    mp, seg_len, 0, &error, &push) <= 0) {
15154 				if (error == ENOSPC) {
15155 					tcp->tcp_rwnd -= seg_len;
15156 				} else if (error == EOPNOTSUPP) {
15157 					tcp_rcv_enqueue(tcp, mp, seg_len);
15158 				}
15159 			} else if (push) {
15160 				/*
15161 				 * PUSH bit set and sockfs is not
15162 				 * flow controlled
15163 				 */
15164 				flags |= tcp_rwnd_reopen(tcp);
15165 			}
15166 		} else if (sodp != NULL) {
15167 			/*
15168 			 * Sodirect so all mblk_t's are queued on the
15169 			 * socket directly, check for wakeup of blocked
15170 			 * reader (if any), and last if flow-controled.
15171 			 */
15172 			mutex_enter(sodp->sod_lockp);
15173 			flags |= tcp_rcv_sod_enqueue(tcp, sodp, mp, seg_len);
15174 			if ((sodp->sod_state & SOD_WAKE_NEED) ||
15175 			    (flags & (TH_PUSH|TH_FIN))) {
15176 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15177 				/* sod_wakeup() did the mutex_exit() */
15178 			} else {
15179 				if (SOD_QFULL(sodp)) {
15180 					/* Q is full, need backenable */
15181 					SOD_QSETBE(sodp);
15182 				}
15183 				mutex_exit(sodp->sod_lockp);
15184 			}
15185 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15186 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_recv_hiwater >> 3) {
15187 			if (tcp->tcp_rcv_list != NULL) {
15188 				/*
15189 				 * Enqueue the new segment first and then
15190 				 * call tcp_rcv_drain() to send all data
15191 				 * up.  The other way to do this is to
15192 				 * send all queued data up and then call
15193 				 * putnext() to send the new segment up.
15194 				 * This way can remove the else part later
15195 				 * on.
15196 				 *
15197 				 * We don't do this to avoid one more call to
15198 				 * canputnext() as tcp_rcv_drain() needs to
15199 				 * call canputnext().
15200 				 */
15201 				tcp_rcv_enqueue(tcp, mp, seg_len);
15202 				flags |= tcp_rcv_drain(tcp);
15203 			} else {
15204 				putnext(tcp->tcp_rq, mp);
15205 				if (!canputnext(tcp->tcp_rq))
15206 					tcp->tcp_rwnd -= seg_len;
15207 			}
15208 		} else {
15209 			/*
15210 			 * Enqueue all packets when processing an mblk
15211 			 * from the co queue and also enqueue normal packets.
15212 			 * For packets which belong to SSL stream do SSL
15213 			 * processing first.
15214 			 */
15215 			tcp_rcv_enqueue(tcp, mp, seg_len);
15216 		}
15217 		/*
15218 		 * Make sure the timer is running if we have data waiting
15219 		 * for a push bit. This provides resiliency against
15220 		 * implementations that do not correctly generate push bits.
15221 		 *
15222 		 * Note, for sodirect if Q isn't empty and there's not a
15223 		 * pending wakeup then we need a timer. Also note that sodp
15224 		 * is assumed to be still valid after exit()ing the sod_lockp
15225 		 * above and while the SOD state can change it can only change
15226 		 * such that the Q is empty now even though data was added
15227 		 * above.
15228 		 */
15229 		if (!IPCL_IS_NONSTR(connp) &&
15230 		    ((sodp != NULL && !SOD_QEMPTY(sodp) &&
15231 		    (sodp->sod_state & SOD_WAKE_NOT)) ||
15232 		    (sodp == NULL && tcp->tcp_rcv_list != NULL)) &&
15233 		    tcp->tcp_push_tid == 0) {
15234 			/*
15235 			 * The connection may be closed at this point, so don't
15236 			 * do anything for a detached tcp.
15237 			 */
15238 			if (!TCP_IS_DETACHED(tcp))
15239 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15240 				    tcp_push_timer,
15241 				    MSEC_TO_TICK(
15242 				    tcps->tcps_push_timer_interval));
15243 		}
15244 	}
15245 
15246 xmit_check:
15247 	/* Is there anything left to do? */
15248 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15249 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15250 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15251 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15252 		goto done;
15253 
15254 	/* Any transmit work to do and a non-zero window? */
15255 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15256 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15257 		if (flags & TH_REXMIT_NEEDED) {
15258 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15259 
15260 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15261 			if (snd_size > mss)
15262 				snd_size = mss;
15263 			if (snd_size > tcp->tcp_swnd)
15264 				snd_size = tcp->tcp_swnd;
15265 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15266 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15267 			    B_TRUE);
15268 
15269 			if (mp1 != NULL) {
15270 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15271 				tcp->tcp_csuna = tcp->tcp_snxt;
15272 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15273 				UPDATE_MIB(&tcps->tcps_mib,
15274 				    tcpRetransBytes, snd_size);
15275 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15276 			}
15277 		}
15278 		if (flags & TH_NEED_SACK_REXMIT) {
15279 			tcp_sack_rxmit(tcp, &flags);
15280 		}
15281 		/*
15282 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15283 		 * out new segment.  Note that tcp_rexmit should not be
15284 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15285 		 */
15286 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15287 			if (!tcp->tcp_rexmit) {
15288 				tcp_wput_data(tcp, NULL, B_FALSE);
15289 			} else {
15290 				tcp_ss_rexmit(tcp);
15291 			}
15292 		}
15293 		/*
15294 		 * Adjust tcp_cwnd back to normal value after sending
15295 		 * new data segments.
15296 		 */
15297 		if (flags & TH_LIMIT_XMIT) {
15298 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15299 			/*
15300 			 * This will restart the timer.  Restarting the
15301 			 * timer is used to avoid a timeout before the
15302 			 * limited transmitted segment's ACK gets back.
15303 			 */
15304 			if (tcp->tcp_xmit_head != NULL)
15305 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15306 		}
15307 
15308 		/* Anything more to do? */
15309 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15310 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15311 			goto done;
15312 	}
15313 ack_check:
15314 	if (flags & TH_SEND_URP_MARK) {
15315 		ASSERT(tcp->tcp_urp_mark_mp);
15316 		ASSERT(!IPCL_IS_NONSTR(connp));
15317 		/*
15318 		 * Send up any queued data and then send the mark message
15319 		 */
15320 		sodirect_t *sodp;
15321 
15322 		SOD_PTR_ENTER(tcp, sodp);
15323 
15324 		mp1 = tcp->tcp_urp_mark_mp;
15325 		tcp->tcp_urp_mark_mp = NULL;
15326 		if (sodp != NULL) {
15327 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15328 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15329 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15330 			}
15331 			ASSERT(tcp->tcp_rcv_list == NULL);
15332 
15333 			flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15334 			/* sod_wakeup() does the mutex_exit() */
15335 		} else if (tcp->tcp_rcv_list != NULL) {
15336 			flags |= tcp_rcv_drain(tcp);
15337 
15338 			ASSERT(tcp->tcp_rcv_list == NULL ||
15339 			    tcp->tcp_fused_sigurg);
15340 
15341 		}
15342 		putnext(tcp->tcp_rq, mp1);
15343 #ifdef DEBUG
15344 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15345 		    "tcp_rput: sending zero-length %s %s",
15346 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15347 		    "MSGNOTMARKNEXT"),
15348 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15349 #endif /* DEBUG */
15350 		flags &= ~TH_SEND_URP_MARK;
15351 	}
15352 	if (flags & TH_ACK_NEEDED) {
15353 		/*
15354 		 * Time to send an ack for some reason.
15355 		 */
15356 		mp1 = tcp_ack_mp(tcp);
15357 
15358 		if (mp1 != NULL) {
15359 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15360 			BUMP_LOCAL(tcp->tcp_obsegs);
15361 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15362 		}
15363 		if (tcp->tcp_ack_tid != 0) {
15364 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15365 			tcp->tcp_ack_tid = 0;
15366 		}
15367 	}
15368 	if (flags & TH_ACK_TIMER_NEEDED) {
15369 		/*
15370 		 * Arrange for deferred ACK or push wait timeout.
15371 		 * Start timer if it is not already running.
15372 		 */
15373 		if (tcp->tcp_ack_tid == 0) {
15374 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15375 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15376 			    (clock_t)tcps->tcps_local_dack_interval :
15377 			    (clock_t)tcps->tcps_deferred_ack_interval));
15378 		}
15379 	}
15380 	if (flags & TH_ORDREL_NEEDED) {
15381 		/*
15382 		 * Send up the ordrel_ind unless we are an eager guy.
15383 		 * In the eager case tcp_rsrv will do this when run
15384 		 * after tcp_accept is done.
15385 		 */
15386 		sodirect_t *sodp;
15387 
15388 		ASSERT(tcp->tcp_listener == NULL);
15389 
15390 		if (IPCL_IS_NONSTR(connp)) {
15391 			ASSERT(tcp->tcp_ordrel_mp == NULL);
15392 			tcp->tcp_ordrel_done = B_TRUE;
15393 			(*connp->conn_upcalls->su_opctl)
15394 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
15395 			goto done;
15396 		}
15397 
15398 		SOD_PTR_ENTER(tcp, sodp);
15399 		if (sodp != NULL) {
15400 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15401 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15402 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15403 			}
15404 			/* No more sodirect */
15405 			tcp->tcp_sodirect = NULL;
15406 			if (!SOD_QEMPTY(sodp)) {
15407 				/* Mblk(s) to process, notify */
15408 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15409 				/* sod_wakeup() does the mutex_exit() */
15410 			} else {
15411 				/* Nothing to process */
15412 				mutex_exit(sodp->sod_lockp);
15413 			}
15414 		} else if (tcp->tcp_rcv_list != NULL) {
15415 			/*
15416 			 * Push any mblk(s) enqueued from co processing.
15417 			 */
15418 			flags |= tcp_rcv_drain(tcp);
15419 
15420 			ASSERT(tcp->tcp_rcv_list == NULL ||
15421 			    tcp->tcp_fused_sigurg);
15422 		}
15423 
15424 		mp1 = tcp->tcp_ordrel_mp;
15425 		tcp->tcp_ordrel_mp = NULL;
15426 		tcp->tcp_ordrel_done = B_TRUE;
15427 		putnext(tcp->tcp_rq, mp1);
15428 	}
15429 done:
15430 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15431 }
15432 
15433 /*
15434  * This function does PAWS protection check. Returns B_TRUE if the
15435  * segment passes the PAWS test, else returns B_FALSE.
15436  */
15437 boolean_t
15438 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15439 {
15440 	uint8_t	flags;
15441 	int	options;
15442 	uint8_t *up;
15443 
15444 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15445 	/*
15446 	 * If timestamp option is aligned nicely, get values inline,
15447 	 * otherwise call general routine to parse.  Only do that
15448 	 * if timestamp is the only option.
15449 	 */
15450 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15451 	    TCPOPT_REAL_TS_LEN &&
15452 	    OK_32PTR((up = ((uint8_t *)tcph) +
15453 	    TCP_MIN_HEADER_LENGTH)) &&
15454 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15455 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15456 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15457 
15458 		options = TCP_OPT_TSTAMP_PRESENT;
15459 	} else {
15460 		if (tcp->tcp_snd_sack_ok) {
15461 			tcpoptp->tcp = tcp;
15462 		} else {
15463 			tcpoptp->tcp = NULL;
15464 		}
15465 		options = tcp_parse_options(tcph, tcpoptp);
15466 	}
15467 
15468 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15469 		/*
15470 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15471 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15472 		 */
15473 		if ((flags & TH_RST) == 0 &&
15474 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15475 		    tcp->tcp_ts_recent)) {
15476 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15477 			    PAWS_TIMEOUT)) {
15478 				/* This segment is not acceptable. */
15479 				return (B_FALSE);
15480 			} else {
15481 				/*
15482 				 * Connection has been idle for
15483 				 * too long.  Reset the timestamp
15484 				 * and assume the segment is valid.
15485 				 */
15486 				tcp->tcp_ts_recent =
15487 				    tcpoptp->tcp_opt_ts_val;
15488 			}
15489 		}
15490 	} else {
15491 		/*
15492 		 * If we don't get a timestamp on every packet, we
15493 		 * figure we can't really trust 'em, so we stop sending
15494 		 * and parsing them.
15495 		 */
15496 		tcp->tcp_snd_ts_ok = B_FALSE;
15497 
15498 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15499 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15500 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15501 		/*
15502 		 * Adjust the tcp_mss accordingly. We also need to
15503 		 * adjust tcp_cwnd here in accordance with the new mss.
15504 		 * But we avoid doing a slow start here so as to not
15505 		 * to lose on the transfer rate built up so far.
15506 		 */
15507 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15508 		if (tcp->tcp_snd_sack_ok) {
15509 			ASSERT(tcp->tcp_sack_info != NULL);
15510 			tcp->tcp_max_sack_blk = 4;
15511 		}
15512 	}
15513 	return (B_TRUE);
15514 }
15515 
15516 /*
15517  * Attach ancillary data to a received TCP segments for the
15518  * ancillary pieces requested by the application that are
15519  * different than they were in the previous data segment.
15520  *
15521  * Save the "current" values once memory allocation is ok so that
15522  * when memory allocation fails we can just wait for the next data segment.
15523  */
15524 static mblk_t *
15525 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15526 {
15527 	struct T_optdata_ind *todi;
15528 	int optlen;
15529 	uchar_t *optptr;
15530 	struct T_opthdr *toh;
15531 	uint_t addflag;	/* Which pieces to add */
15532 	mblk_t *mp1;
15533 
15534 	optlen = 0;
15535 	addflag = 0;
15536 	/* If app asked for pktinfo and the index has changed ... */
15537 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15538 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15539 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15540 		optlen += sizeof (struct T_opthdr) +
15541 		    sizeof (struct in6_pktinfo);
15542 		addflag |= TCP_IPV6_RECVPKTINFO;
15543 	}
15544 	/* If app asked for hoplimit and it has changed ... */
15545 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15546 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15547 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15548 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15549 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15550 	}
15551 	/* If app asked for tclass and it has changed ... */
15552 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15553 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15554 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15555 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15556 		addflag |= TCP_IPV6_RECVTCLASS;
15557 	}
15558 	/*
15559 	 * If app asked for hopbyhop headers and it has changed ...
15560 	 * For security labels, note that (1) security labels can't change on
15561 	 * a connected socket at all, (2) we're connected to at most one peer,
15562 	 * (3) if anything changes, then it must be some other extra option.
15563 	 */
15564 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15565 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15566 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15567 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15568 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15569 		    tcp->tcp_label_len;
15570 		addflag |= TCP_IPV6_RECVHOPOPTS;
15571 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15572 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15573 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15574 			return (mp);
15575 	}
15576 	/* If app asked for dst headers before routing headers ... */
15577 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15578 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15579 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15580 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15581 		optlen += sizeof (struct T_opthdr) +
15582 		    ipp->ipp_rtdstoptslen;
15583 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15584 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15585 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15586 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15587 			return (mp);
15588 	}
15589 	/* If app asked for routing headers and it has changed ... */
15590 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15591 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15592 	    (ipp->ipp_fields & IPPF_RTHDR),
15593 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15594 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15595 		addflag |= TCP_IPV6_RECVRTHDR;
15596 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15597 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15598 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15599 			return (mp);
15600 	}
15601 	/* If app asked for dest headers and it has changed ... */
15602 	if ((tcp->tcp_ipv6_recvancillary &
15603 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15604 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15605 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15606 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15607 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15608 		addflag |= TCP_IPV6_RECVDSTOPTS;
15609 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15610 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15611 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15612 			return (mp);
15613 	}
15614 
15615 	if (optlen == 0) {
15616 		/* Nothing to add */
15617 		return (mp);
15618 	}
15619 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15620 	if (mp1 == NULL) {
15621 		/*
15622 		 * Defer sending ancillary data until the next TCP segment
15623 		 * arrives.
15624 		 */
15625 		return (mp);
15626 	}
15627 	mp1->b_cont = mp;
15628 	mp = mp1;
15629 	mp->b_wptr += sizeof (*todi) + optlen;
15630 	mp->b_datap->db_type = M_PROTO;
15631 	todi = (struct T_optdata_ind *)mp->b_rptr;
15632 	todi->PRIM_type = T_OPTDATA_IND;
15633 	todi->DATA_flag = 1;	/* MORE data */
15634 	todi->OPT_length = optlen;
15635 	todi->OPT_offset = sizeof (*todi);
15636 	optptr = (uchar_t *)&todi[1];
15637 	/*
15638 	 * If app asked for pktinfo and the index has changed ...
15639 	 * Note that the local address never changes for the connection.
15640 	 */
15641 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15642 		struct in6_pktinfo *pkti;
15643 
15644 		toh = (struct T_opthdr *)optptr;
15645 		toh->level = IPPROTO_IPV6;
15646 		toh->name = IPV6_PKTINFO;
15647 		toh->len = sizeof (*toh) + sizeof (*pkti);
15648 		toh->status = 0;
15649 		optptr += sizeof (*toh);
15650 		pkti = (struct in6_pktinfo *)optptr;
15651 		if (tcp->tcp_ipversion == IPV6_VERSION)
15652 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15653 		else
15654 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15655 			    &pkti->ipi6_addr);
15656 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15657 		optptr += sizeof (*pkti);
15658 		ASSERT(OK_32PTR(optptr));
15659 		/* Save as "last" value */
15660 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15661 	}
15662 	/* If app asked for hoplimit and it has changed ... */
15663 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15664 		toh = (struct T_opthdr *)optptr;
15665 		toh->level = IPPROTO_IPV6;
15666 		toh->name = IPV6_HOPLIMIT;
15667 		toh->len = sizeof (*toh) + sizeof (uint_t);
15668 		toh->status = 0;
15669 		optptr += sizeof (*toh);
15670 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15671 		optptr += sizeof (uint_t);
15672 		ASSERT(OK_32PTR(optptr));
15673 		/* Save as "last" value */
15674 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15675 	}
15676 	/* If app asked for tclass and it has changed ... */
15677 	if (addflag & TCP_IPV6_RECVTCLASS) {
15678 		toh = (struct T_opthdr *)optptr;
15679 		toh->level = IPPROTO_IPV6;
15680 		toh->name = IPV6_TCLASS;
15681 		toh->len = sizeof (*toh) + sizeof (uint_t);
15682 		toh->status = 0;
15683 		optptr += sizeof (*toh);
15684 		*(uint_t *)optptr = ipp->ipp_tclass;
15685 		optptr += sizeof (uint_t);
15686 		ASSERT(OK_32PTR(optptr));
15687 		/* Save as "last" value */
15688 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15689 	}
15690 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15691 		toh = (struct T_opthdr *)optptr;
15692 		toh->level = IPPROTO_IPV6;
15693 		toh->name = IPV6_HOPOPTS;
15694 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15695 		    tcp->tcp_label_len;
15696 		toh->status = 0;
15697 		optptr += sizeof (*toh);
15698 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15699 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15700 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15701 		ASSERT(OK_32PTR(optptr));
15702 		/* Save as last value */
15703 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15704 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15705 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15706 	}
15707 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15708 		toh = (struct T_opthdr *)optptr;
15709 		toh->level = IPPROTO_IPV6;
15710 		toh->name = IPV6_RTHDRDSTOPTS;
15711 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15712 		toh->status = 0;
15713 		optptr += sizeof (*toh);
15714 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15715 		optptr += ipp->ipp_rtdstoptslen;
15716 		ASSERT(OK_32PTR(optptr));
15717 		/* Save as last value */
15718 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15719 		    &tcp->tcp_rtdstoptslen,
15720 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15721 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15722 	}
15723 	if (addflag & TCP_IPV6_RECVRTHDR) {
15724 		toh = (struct T_opthdr *)optptr;
15725 		toh->level = IPPROTO_IPV6;
15726 		toh->name = IPV6_RTHDR;
15727 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15728 		toh->status = 0;
15729 		optptr += sizeof (*toh);
15730 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15731 		optptr += ipp->ipp_rthdrlen;
15732 		ASSERT(OK_32PTR(optptr));
15733 		/* Save as last value */
15734 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15735 		    (ipp->ipp_fields & IPPF_RTHDR),
15736 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15737 	}
15738 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15739 		toh = (struct T_opthdr *)optptr;
15740 		toh->level = IPPROTO_IPV6;
15741 		toh->name = IPV6_DSTOPTS;
15742 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15743 		toh->status = 0;
15744 		optptr += sizeof (*toh);
15745 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15746 		optptr += ipp->ipp_dstoptslen;
15747 		ASSERT(OK_32PTR(optptr));
15748 		/* Save as last value */
15749 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15750 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15751 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15752 	}
15753 	ASSERT(optptr == mp->b_wptr);
15754 	return (mp);
15755 }
15756 
15757 /*
15758  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15759  * messages.
15760  */
15761 void
15762 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15763 {
15764 	uchar_t	*rptr = mp->b_rptr;
15765 	queue_t	*q = tcp->tcp_rq;
15766 	struct T_error_ack *tea;
15767 
15768 	switch (mp->b_datap->db_type) {
15769 	case M_PROTO:
15770 	case M_PCPROTO:
15771 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15772 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15773 			break;
15774 		tea = (struct T_error_ack *)rptr;
15775 		ASSERT(tea->PRIM_type != T_BIND_ACK);
15776 		ASSERT(tea->ERROR_prim != O_T_BIND_REQ &&
15777 		    tea->ERROR_prim != T_BIND_REQ);
15778 		switch (tea->PRIM_type) {
15779 		case T_ERROR_ACK:
15780 			if (tcp->tcp_debug) {
15781 				(void) strlog(TCP_MOD_ID, 0, 1,
15782 				    SL_TRACE|SL_ERROR,
15783 				    "tcp_rput_other: case T_ERROR_ACK, "
15784 				    "ERROR_prim == %d",
15785 				    tea->ERROR_prim);
15786 			}
15787 			switch (tea->ERROR_prim) {
15788 			case T_SVR4_OPTMGMT_REQ:
15789 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15790 					/* T_OPTMGMT_REQ generated by TCP */
15791 					printf("T_SVR4_OPTMGMT_REQ failed "
15792 					    "%d/%d - dropped (cnt %d)\n",
15793 					    tea->TLI_error, tea->UNIX_error,
15794 					    tcp->tcp_drop_opt_ack_cnt);
15795 					freemsg(mp);
15796 					tcp->tcp_drop_opt_ack_cnt--;
15797 					return;
15798 				}
15799 				break;
15800 			}
15801 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15802 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15803 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15804 				    "- dropped (cnt %d)\n",
15805 				    tea->TLI_error, tea->UNIX_error,
15806 				    tcp->tcp_drop_opt_ack_cnt);
15807 				freemsg(mp);
15808 				tcp->tcp_drop_opt_ack_cnt--;
15809 				return;
15810 			}
15811 			break;
15812 		case T_OPTMGMT_ACK:
15813 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15814 				/* T_OPTMGMT_REQ generated by TCP */
15815 				freemsg(mp);
15816 				tcp->tcp_drop_opt_ack_cnt--;
15817 				return;
15818 			}
15819 			break;
15820 		default:
15821 			ASSERT(tea->ERROR_prim != T_UNBIND_REQ);
15822 			break;
15823 		}
15824 		break;
15825 	case M_FLUSH:
15826 		if (*rptr & FLUSHR)
15827 			flushq(q, FLUSHDATA);
15828 		break;
15829 	default:
15830 		/* M_CTL will be directly sent to tcp_icmp_error() */
15831 		ASSERT(DB_TYPE(mp) != M_CTL);
15832 		break;
15833 	}
15834 	/*
15835 	 * Make sure we set this bit before sending the ACK for
15836 	 * bind. Otherwise accept could possibly run and free
15837 	 * this tcp struct.
15838 	 */
15839 	ASSERT(q != NULL);
15840 	putnext(q, mp);
15841 }
15842 
15843 /* ARGSUSED */
15844 static void
15845 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15846 {
15847 	conn_t	*connp = (conn_t *)arg;
15848 	tcp_t	*tcp = connp->conn_tcp;
15849 	queue_t	*q = tcp->tcp_rq;
15850 	uint_t	thwin;
15851 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15852 	sodirect_t	*sodp;
15853 	boolean_t	fc;
15854 
15855 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15856 	tcp->tcp_rsrv_mp = mp;
15857 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15858 
15859 	TCP_STAT(tcps, tcp_rsrv_calls);
15860 
15861 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15862 		return;
15863 	}
15864 
15865 	if (tcp->tcp_fused) {
15866 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15867 
15868 		ASSERT(tcp->tcp_fused);
15869 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15870 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15871 		ASSERT(!TCP_IS_DETACHED(tcp));
15872 		ASSERT(tcp->tcp_connp->conn_sqp ==
15873 		    peer_tcp->tcp_connp->conn_sqp);
15874 
15875 		/*
15876 		 * Normally we would not get backenabled in synchronous
15877 		 * streams mode, but in case this happens, we need to plug
15878 		 * synchronous streams during our drain to prevent a race
15879 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
15880 		 */
15881 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
15882 		if (tcp->tcp_rcv_list != NULL)
15883 			(void) tcp_rcv_drain(tcp);
15884 
15885 		if (peer_tcp > tcp) {
15886 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15887 			mutex_enter(&tcp->tcp_non_sq_lock);
15888 		} else {
15889 			mutex_enter(&tcp->tcp_non_sq_lock);
15890 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15891 		}
15892 
15893 		if (peer_tcp->tcp_flow_stopped &&
15894 		    (TCP_UNSENT_BYTES(peer_tcp) <=
15895 		    peer_tcp->tcp_xmit_lowater)) {
15896 			tcp_clrqfull(peer_tcp);
15897 		}
15898 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
15899 		mutex_exit(&tcp->tcp_non_sq_lock);
15900 
15901 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
15902 		TCP_STAT(tcps, tcp_fusion_backenabled);
15903 		return;
15904 	}
15905 
15906 	SOD_PTR_ENTER(tcp, sodp);
15907 	if (sodp != NULL) {
15908 		/* An sodirect connection */
15909 		if (SOD_QFULL(sodp)) {
15910 			/* Flow-controlled, need another back-enable */
15911 			fc = B_TRUE;
15912 			SOD_QSETBE(sodp);
15913 		} else {
15914 			/* Not flow-controlled */
15915 			fc = B_FALSE;
15916 		}
15917 		mutex_exit(sodp->sod_lockp);
15918 	} else if (canputnext(q)) {
15919 		/* STREAMS, not flow-controlled */
15920 		fc = B_FALSE;
15921 	} else {
15922 		/* STREAMS, flow-controlled */
15923 		fc = B_TRUE;
15924 	}
15925 	if (!fc) {
15926 		/* Not flow-controlled, open rwnd */
15927 		tcp->tcp_rwnd = q->q_hiwat;
15928 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15929 		    << tcp->tcp_rcv_ws;
15930 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15931 		/*
15932 		 * Send back a window update immediately if TCP is above
15933 		 * ESTABLISHED state and the increase of the rcv window
15934 		 * that the other side knows is at least 1 MSS after flow
15935 		 * control is lifted.
15936 		 */
15937 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15938 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15939 			tcp_xmit_ctl(NULL, tcp,
15940 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15941 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15942 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
15943 		}
15944 	}
15945 }
15946 
15947 /*
15948  * The read side service routine is called mostly when we get back-enabled as a
15949  * result of flow control relief.  Since we don't actually queue anything in
15950  * TCP, we have no data to send out of here.  What we do is clear the receive
15951  * window, and send out a window update.
15952  */
15953 static void
15954 tcp_rsrv(queue_t *q)
15955 {
15956 	conn_t		*connp = Q_TO_CONN(q);
15957 	tcp_t		*tcp = connp->conn_tcp;
15958 	mblk_t		*mp;
15959 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15960 
15961 	/* No code does a putq on the read side */
15962 	ASSERT(q->q_first == NULL);
15963 
15964 	/* Nothing to do for the default queue */
15965 	if (q == tcps->tcps_g_q) {
15966 		return;
15967 	}
15968 
15969 	/*
15970 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
15971 	 * been run.  So just return.
15972 	 */
15973 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15974 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
15975 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
15976 		return;
15977 	}
15978 	tcp->tcp_rsrv_mp = NULL;
15979 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15980 
15981 	CONN_INC_REF(connp);
15982 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15983 	    SQ_PROCESS, SQTAG_TCP_RSRV);
15984 }
15985 
15986 /*
15987  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15988  * We do not allow the receive window to shrink.  After setting rwnd,
15989  * set the flow control hiwat of the stream.
15990  *
15991  * This function is called in 2 cases:
15992  *
15993  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15994  *    connection (passive open) and in tcp_rput_data() for active connect.
15995  *    This is called after tcp_mss_set() when the desired MSS value is known.
15996  *    This makes sure that our window size is a mutiple of the other side's
15997  *    MSS.
15998  * 2) Handling SO_RCVBUF option.
15999  *
16000  * It is ASSUMED that the requested size is a multiple of the current MSS.
16001  *
16002  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16003  * user requests so.
16004  */
16005 static int
16006 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16007 {
16008 	uint32_t	mss = tcp->tcp_mss;
16009 	uint32_t	old_max_rwnd;
16010 	uint32_t	max_transmittable_rwnd;
16011 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16012 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16013 
16014 	if (tcp->tcp_fused) {
16015 		size_t sth_hiwat;
16016 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16017 
16018 		ASSERT(peer_tcp != NULL);
16019 		/*
16020 		 * Record the stream head's high water mark for
16021 		 * this endpoint; this is used for flow-control
16022 		 * purposes in tcp_fuse_output().
16023 		 */
16024 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16025 		if (!tcp_detached) {
16026 			(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
16027 			    sth_hiwat);
16028 			if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
16029 				conn_t *connp = tcp->tcp_connp;
16030 				struct sock_proto_props sopp;
16031 
16032 				sopp.sopp_flags = SOCKOPT_RCVTHRESH;
16033 				sopp.sopp_rcvthresh = sth_hiwat >> 3;
16034 
16035 				(*connp->conn_upcalls->su_set_proto_props)
16036 				    (connp->conn_upper_handle, &sopp);
16037 			}
16038 		}
16039 
16040 		/*
16041 		 * In the fusion case, the maxpsz stream head value of
16042 		 * our peer is set according to its send buffer size
16043 		 * and our receive buffer size; since the latter may
16044 		 * have changed we need to update the peer's maxpsz.
16045 		 */
16046 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16047 		return (rwnd);
16048 	}
16049 
16050 	if (tcp_detached) {
16051 		old_max_rwnd = tcp->tcp_rwnd;
16052 	} else {
16053 		old_max_rwnd = tcp->tcp_recv_hiwater;
16054 	}
16055 
16056 	/*
16057 	 * Insist on a receive window that is at least
16058 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16059 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16060 	 * and delayed acknowledgement.
16061 	 */
16062 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16063 
16064 	/*
16065 	 * If window size info has already been exchanged, TCP should not
16066 	 * shrink the window.  Shrinking window is doable if done carefully.
16067 	 * We may add that support later.  But so far there is not a real
16068 	 * need to do that.
16069 	 */
16070 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16071 		/* MSS may have changed, do a round up again. */
16072 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16073 	}
16074 
16075 	/*
16076 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16077 	 * can be applied even before the window scale option is decided.
16078 	 */
16079 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16080 	if (rwnd > max_transmittable_rwnd) {
16081 		rwnd = max_transmittable_rwnd -
16082 		    (max_transmittable_rwnd % mss);
16083 		if (rwnd < mss)
16084 			rwnd = max_transmittable_rwnd;
16085 		/*
16086 		 * If we're over the limit we may have to back down tcp_rwnd.
16087 		 * The increment below won't work for us. So we set all three
16088 		 * here and the increment below will have no effect.
16089 		 */
16090 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16091 	}
16092 	if (tcp->tcp_localnet) {
16093 		tcp->tcp_rack_abs_max =
16094 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16095 	} else {
16096 		/*
16097 		 * For a remote host on a different subnet (through a router),
16098 		 * we ack every other packet to be conforming to RFC1122.
16099 		 * tcp_deferred_acks_max is default to 2.
16100 		 */
16101 		tcp->tcp_rack_abs_max =
16102 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16103 	}
16104 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16105 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16106 	else
16107 		tcp->tcp_rack_cur_max = 0;
16108 	/*
16109 	 * Increment the current rwnd by the amount the maximum grew (we
16110 	 * can not overwrite it since we might be in the middle of a
16111 	 * connection.)
16112 	 */
16113 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16114 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16115 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16116 		tcp->tcp_cwnd_max = rwnd;
16117 
16118 	if (tcp_detached)
16119 		return (rwnd);
16120 	/*
16121 	 * We set the maximum receive window into rq->q_hiwat if it is
16122 	 * a STREAMS socket.
16123 	 * This is not actually used for flow control.
16124 	 */
16125 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
16126 		tcp->tcp_rq->q_hiwat = rwnd;
16127 	tcp->tcp_recv_hiwater = rwnd;
16128 	/*
16129 	 * Set the STREAM head high water mark. This doesn't have to be
16130 	 * here, since we are simply using default values, but we would
16131 	 * prefer to choose these values algorithmically, with a likely
16132 	 * relationship to rwnd.
16133 	 */
16134 	(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
16135 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16136 	return (rwnd);
16137 }
16138 
16139 /*
16140  * Return SNMP stuff in buffer in mpdata.
16141  */
16142 mblk_t *
16143 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16144 {
16145 	mblk_t			*mpdata;
16146 	mblk_t			*mp_conn_ctl = NULL;
16147 	mblk_t			*mp_conn_tail;
16148 	mblk_t			*mp_attr_ctl = NULL;
16149 	mblk_t			*mp_attr_tail;
16150 	mblk_t			*mp6_conn_ctl = NULL;
16151 	mblk_t			*mp6_conn_tail;
16152 	mblk_t			*mp6_attr_ctl = NULL;
16153 	mblk_t			*mp6_attr_tail;
16154 	struct opthdr		*optp;
16155 	mib2_tcpConnEntry_t	tce;
16156 	mib2_tcp6ConnEntry_t	tce6;
16157 	mib2_transportMLPEntry_t mlp;
16158 	connf_t			*connfp;
16159 	int			i;
16160 	boolean_t 		ispriv;
16161 	zoneid_t 		zoneid;
16162 	int			v4_conn_idx;
16163 	int			v6_conn_idx;
16164 	conn_t			*connp = Q_TO_CONN(q);
16165 	tcp_stack_t		*tcps;
16166 	ip_stack_t		*ipst;
16167 	mblk_t			*mp2ctl;
16168 
16169 	/*
16170 	 * make a copy of the original message
16171 	 */
16172 	mp2ctl = copymsg(mpctl);
16173 
16174 	if (mpctl == NULL ||
16175 	    (mpdata = mpctl->b_cont) == NULL ||
16176 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16177 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16178 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16179 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16180 		freemsg(mp_conn_ctl);
16181 		freemsg(mp_attr_ctl);
16182 		freemsg(mp6_conn_ctl);
16183 		freemsg(mp6_attr_ctl);
16184 		freemsg(mpctl);
16185 		freemsg(mp2ctl);
16186 		return (NULL);
16187 	}
16188 
16189 	ipst = connp->conn_netstack->netstack_ip;
16190 	tcps = connp->conn_netstack->netstack_tcp;
16191 
16192 	/* build table of connections -- need count in fixed part */
16193 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16194 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16195 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16196 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16197 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16198 
16199 	ispriv =
16200 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16201 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16202 
16203 	v4_conn_idx = v6_conn_idx = 0;
16204 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16205 
16206 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16207 		ipst = tcps->tcps_netstack->netstack_ip;
16208 
16209 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16210 
16211 		connp = NULL;
16212 
16213 		while ((connp =
16214 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16215 			tcp_t *tcp;
16216 			boolean_t needattr;
16217 
16218 			if (connp->conn_zoneid != zoneid)
16219 				continue;	/* not in this zone */
16220 
16221 			tcp = connp->conn_tcp;
16222 			UPDATE_MIB(&tcps->tcps_mib,
16223 			    tcpHCInSegs, tcp->tcp_ibsegs);
16224 			tcp->tcp_ibsegs = 0;
16225 			UPDATE_MIB(&tcps->tcps_mib,
16226 			    tcpHCOutSegs, tcp->tcp_obsegs);
16227 			tcp->tcp_obsegs = 0;
16228 
16229 			tce6.tcp6ConnState = tce.tcpConnState =
16230 			    tcp_snmp_state(tcp);
16231 			if (tce.tcpConnState == MIB2_TCP_established ||
16232 			    tce.tcpConnState == MIB2_TCP_closeWait)
16233 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16234 
16235 			needattr = B_FALSE;
16236 			bzero(&mlp, sizeof (mlp));
16237 			if (connp->conn_mlp_type != mlptSingle) {
16238 				if (connp->conn_mlp_type == mlptShared ||
16239 				    connp->conn_mlp_type == mlptBoth)
16240 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16241 				if (connp->conn_mlp_type == mlptPrivate ||
16242 				    connp->conn_mlp_type == mlptBoth)
16243 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16244 				needattr = B_TRUE;
16245 			}
16246 			if (connp->conn_peercred != NULL) {
16247 				ts_label_t *tsl;
16248 
16249 				tsl = crgetlabel(connp->conn_peercred);
16250 				mlp.tme_doi = label2doi(tsl);
16251 				mlp.tme_label = *label2bslabel(tsl);
16252 				needattr = B_TRUE;
16253 			}
16254 
16255 			/* Create a message to report on IPv6 entries */
16256 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16257 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16258 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16259 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16260 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16261 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16262 			/* Don't want just anybody seeing these... */
16263 			if (ispriv) {
16264 				tce6.tcp6ConnEntryInfo.ce_snxt =
16265 				    tcp->tcp_snxt;
16266 				tce6.tcp6ConnEntryInfo.ce_suna =
16267 				    tcp->tcp_suna;
16268 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16269 				    tcp->tcp_rnxt;
16270 				tce6.tcp6ConnEntryInfo.ce_rack =
16271 				    tcp->tcp_rack;
16272 			} else {
16273 				/*
16274 				 * Netstat, unfortunately, uses this to
16275 				 * get send/receive queue sizes.  How to fix?
16276 				 * Why not compute the difference only?
16277 				 */
16278 				tce6.tcp6ConnEntryInfo.ce_snxt =
16279 				    tcp->tcp_snxt - tcp->tcp_suna;
16280 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16281 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16282 				    tcp->tcp_rnxt - tcp->tcp_rack;
16283 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16284 			}
16285 
16286 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16287 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16288 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16289 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16290 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16291 
16292 			tce6.tcp6ConnCreationProcess =
16293 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16294 			    tcp->tcp_cpid;
16295 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16296 
16297 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16298 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16299 
16300 			mlp.tme_connidx = v6_conn_idx++;
16301 			if (needattr)
16302 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16303 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16304 			}
16305 			/*
16306 			 * Create an IPv4 table entry for IPv4 entries and also
16307 			 * for IPv6 entries which are bound to in6addr_any
16308 			 * but don't have IPV6_V6ONLY set.
16309 			 * (i.e. anything an IPv4 peer could connect to)
16310 			 */
16311 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16312 			    (tcp->tcp_state <= TCPS_LISTEN &&
16313 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16314 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16315 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16316 					tce.tcpConnRemAddress = INADDR_ANY;
16317 					tce.tcpConnLocalAddress = INADDR_ANY;
16318 				} else {
16319 					tce.tcpConnRemAddress =
16320 					    tcp->tcp_remote;
16321 					tce.tcpConnLocalAddress =
16322 					    tcp->tcp_ip_src;
16323 				}
16324 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16325 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16326 				/* Don't want just anybody seeing these... */
16327 				if (ispriv) {
16328 					tce.tcpConnEntryInfo.ce_snxt =
16329 					    tcp->tcp_snxt;
16330 					tce.tcpConnEntryInfo.ce_suna =
16331 					    tcp->tcp_suna;
16332 					tce.tcpConnEntryInfo.ce_rnxt =
16333 					    tcp->tcp_rnxt;
16334 					tce.tcpConnEntryInfo.ce_rack =
16335 					    tcp->tcp_rack;
16336 				} else {
16337 					/*
16338 					 * Netstat, unfortunately, uses this to
16339 					 * get send/receive queue sizes.  How
16340 					 * to fix?
16341 					 * Why not compute the difference only?
16342 					 */
16343 					tce.tcpConnEntryInfo.ce_snxt =
16344 					    tcp->tcp_snxt - tcp->tcp_suna;
16345 					tce.tcpConnEntryInfo.ce_suna = 0;
16346 					tce.tcpConnEntryInfo.ce_rnxt =
16347 					    tcp->tcp_rnxt - tcp->tcp_rack;
16348 					tce.tcpConnEntryInfo.ce_rack = 0;
16349 				}
16350 
16351 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16352 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16353 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16354 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16355 				tce.tcpConnEntryInfo.ce_state =
16356 				    tcp->tcp_state;
16357 
16358 				tce.tcpConnCreationProcess =
16359 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16360 				    tcp->tcp_cpid;
16361 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16362 
16363 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16364 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16365 
16366 				mlp.tme_connidx = v4_conn_idx++;
16367 				if (needattr)
16368 					(void) snmp_append_data2(
16369 					    mp_attr_ctl->b_cont,
16370 					    &mp_attr_tail, (char *)&mlp,
16371 					    sizeof (mlp));
16372 			}
16373 		}
16374 	}
16375 
16376 	/* fixed length structure for IPv4 and IPv6 counters */
16377 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16378 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16379 	    sizeof (mib2_tcp6ConnEntry_t));
16380 	/* synchronize 32- and 64-bit counters */
16381 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16382 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16383 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16384 	optp->level = MIB2_TCP;
16385 	optp->name = 0;
16386 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16387 	    sizeof (tcps->tcps_mib));
16388 	optp->len = msgdsize(mpdata);
16389 	qreply(q, mpctl);
16390 
16391 	/* table of connections... */
16392 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16393 	    sizeof (struct T_optmgmt_ack)];
16394 	optp->level = MIB2_TCP;
16395 	optp->name = MIB2_TCP_CONN;
16396 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16397 	qreply(q, mp_conn_ctl);
16398 
16399 	/* table of MLP attributes... */
16400 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16401 	    sizeof (struct T_optmgmt_ack)];
16402 	optp->level = MIB2_TCP;
16403 	optp->name = EXPER_XPORT_MLP;
16404 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16405 	if (optp->len == 0)
16406 		freemsg(mp_attr_ctl);
16407 	else
16408 		qreply(q, mp_attr_ctl);
16409 
16410 	/* table of IPv6 connections... */
16411 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16412 	    sizeof (struct T_optmgmt_ack)];
16413 	optp->level = MIB2_TCP6;
16414 	optp->name = MIB2_TCP6_CONN;
16415 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16416 	qreply(q, mp6_conn_ctl);
16417 
16418 	/* table of IPv6 MLP attributes... */
16419 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16420 	    sizeof (struct T_optmgmt_ack)];
16421 	optp->level = MIB2_TCP6;
16422 	optp->name = EXPER_XPORT_MLP;
16423 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16424 	if (optp->len == 0)
16425 		freemsg(mp6_attr_ctl);
16426 	else
16427 		qreply(q, mp6_attr_ctl);
16428 	return (mp2ctl);
16429 }
16430 
16431 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16432 /* ARGSUSED */
16433 int
16434 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16435 {
16436 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16437 
16438 	switch (level) {
16439 	case MIB2_TCP:
16440 		switch (name) {
16441 		case 13:
16442 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16443 				return (0);
16444 			/* TODO: delete entry defined by tce */
16445 			return (1);
16446 		default:
16447 			return (0);
16448 		}
16449 	default:
16450 		return (1);
16451 	}
16452 }
16453 
16454 /* Translate TCP state to MIB2 TCP state. */
16455 static int
16456 tcp_snmp_state(tcp_t *tcp)
16457 {
16458 	if (tcp == NULL)
16459 		return (0);
16460 
16461 	switch (tcp->tcp_state) {
16462 	case TCPS_CLOSED:
16463 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16464 	case TCPS_BOUND:
16465 		return (MIB2_TCP_closed);
16466 	case TCPS_LISTEN:
16467 		return (MIB2_TCP_listen);
16468 	case TCPS_SYN_SENT:
16469 		return (MIB2_TCP_synSent);
16470 	case TCPS_SYN_RCVD:
16471 		return (MIB2_TCP_synReceived);
16472 	case TCPS_ESTABLISHED:
16473 		return (MIB2_TCP_established);
16474 	case TCPS_CLOSE_WAIT:
16475 		return (MIB2_TCP_closeWait);
16476 	case TCPS_FIN_WAIT_1:
16477 		return (MIB2_TCP_finWait1);
16478 	case TCPS_CLOSING:
16479 		return (MIB2_TCP_closing);
16480 	case TCPS_LAST_ACK:
16481 		return (MIB2_TCP_lastAck);
16482 	case TCPS_FIN_WAIT_2:
16483 		return (MIB2_TCP_finWait2);
16484 	case TCPS_TIME_WAIT:
16485 		return (MIB2_TCP_timeWait);
16486 	default:
16487 		return (0);
16488 	}
16489 }
16490 
16491 static char tcp_report_header[] =
16492 	"TCP     " MI_COL_HDRPAD_STR
16493 	"zone dest	    snxt     suna     "
16494 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16495 	"recent   [lport,fport] state";
16496 
16497 /*
16498  * TCP status report triggered via the Named Dispatch mechanism.
16499  */
16500 /* ARGSUSED */
16501 static void
16502 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16503     cred_t *cr)
16504 {
16505 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16506 	boolean_t ispriv = secpolicy_ip_config(cr, B_TRUE) == 0;
16507 	char cflag;
16508 	in6_addr_t	v6dst;
16509 	char buf[80];
16510 	uint_t print_len, buf_len;
16511 
16512 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16513 	if (buf_len <= 0)
16514 		return;
16515 
16516 	if (hashval >= 0)
16517 		(void) sprintf(hash, "%03d ", hashval);
16518 	else
16519 		hash[0] = '\0';
16520 
16521 	/*
16522 	 * Note that we use the remote address in the tcp_b  structure.
16523 	 * This means that it will print out the real destination address,
16524 	 * not the next hop's address if source routing is used.  This
16525 	 * avoid the confusion on the output because user may not
16526 	 * know that source routing is used for a connection.
16527 	 */
16528 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16529 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16530 	} else {
16531 		v6dst = tcp->tcp_remote_v6;
16532 	}
16533 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16534 	/*
16535 	 * the ispriv checks are so that normal users cannot determine
16536 	 * sequence number information using NDD.
16537 	 */
16538 
16539 	if (TCP_IS_DETACHED(tcp))
16540 		cflag = '*';
16541 	else
16542 		cflag = ' ';
16543 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16544 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16545 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16546 	    hash,
16547 	    (void *)tcp,
16548 	    tcp->tcp_connp->conn_zoneid,
16549 	    addrbuf,
16550 	    (ispriv) ? tcp->tcp_snxt : 0,
16551 	    (ispriv) ? tcp->tcp_suna : 0,
16552 	    tcp->tcp_swnd,
16553 	    (ispriv) ? tcp->tcp_rnxt : 0,
16554 	    (ispriv) ? tcp->tcp_rack : 0,
16555 	    tcp->tcp_rwnd,
16556 	    tcp->tcp_rto,
16557 	    tcp->tcp_mss,
16558 	    tcp->tcp_snd_ws_ok,
16559 	    tcp->tcp_snd_ws,
16560 	    tcp->tcp_rcv_ws,
16561 	    tcp->tcp_snd_ts_ok,
16562 	    tcp->tcp_ts_recent,
16563 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16564 	if (print_len < buf_len) {
16565 		((mblk_t *)mp)->b_wptr += print_len;
16566 	} else {
16567 		((mblk_t *)mp)->b_wptr += buf_len;
16568 	}
16569 }
16570 
16571 /*
16572  * TCP status report (for listeners only) triggered via the Named Dispatch
16573  * mechanism.
16574  */
16575 /* ARGSUSED */
16576 static void
16577 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16578 {
16579 	char addrbuf[INET6_ADDRSTRLEN];
16580 	in6_addr_t	v6dst;
16581 	uint_t print_len, buf_len;
16582 
16583 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16584 	if (buf_len <= 0)
16585 		return;
16586 
16587 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16588 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16589 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16590 	} else {
16591 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16592 		    addrbuf, sizeof (addrbuf));
16593 	}
16594 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16595 	    "%03d "
16596 	    MI_COL_PTRFMT_STR
16597 	    "%d %s %05u %08u %d/%d/%d%c\n",
16598 	    hashval, (void *)tcp,
16599 	    tcp->tcp_connp->conn_zoneid,
16600 	    addrbuf,
16601 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16602 	    tcp->tcp_conn_req_seqnum,
16603 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16604 	    tcp->tcp_conn_req_max,
16605 	    tcp->tcp_syn_defense ? '*' : ' ');
16606 	if (print_len < buf_len) {
16607 		((mblk_t *)mp)->b_wptr += print_len;
16608 	} else {
16609 		((mblk_t *)mp)->b_wptr += buf_len;
16610 	}
16611 }
16612 
16613 /* TCP status report triggered via the Named Dispatch mechanism. */
16614 /* ARGSUSED */
16615 static int
16616 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16617 {
16618 	tcp_t	*tcp;
16619 	int	i;
16620 	conn_t	*connp;
16621 	connf_t	*connfp;
16622 	zoneid_t zoneid;
16623 	tcp_stack_t *tcps;
16624 	ip_stack_t *ipst;
16625 
16626 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16627 	tcps = Q_TO_TCP(q)->tcp_tcps;
16628 
16629 	/*
16630 	 * Because of the ndd constraint, at most we can have 64K buffer
16631 	 * to put in all TCP info.  So to be more efficient, just
16632 	 * allocate a 64K buffer here, assuming we need that large buffer.
16633 	 * This may be a problem as any user can read tcp_status.  Therefore
16634 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16635 	 * This should be OK as normal users should not do this too often.
16636 	 */
16637 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16638 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16639 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16640 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16641 			return (0);
16642 		}
16643 	}
16644 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16645 		/* The following may work even if we cannot get a large buf. */
16646 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16647 		return (0);
16648 	}
16649 
16650 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16651 
16652 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16653 
16654 		ipst = tcps->tcps_netstack->netstack_ip;
16655 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16656 
16657 		connp = NULL;
16658 
16659 		while ((connp =
16660 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16661 			tcp = connp->conn_tcp;
16662 			if (zoneid != GLOBAL_ZONEID &&
16663 			    zoneid != connp->conn_zoneid)
16664 				continue;
16665 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16666 			    cr);
16667 		}
16668 
16669 	}
16670 
16671 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16672 	return (0);
16673 }
16674 
16675 /* TCP status report triggered via the Named Dispatch mechanism. */
16676 /* ARGSUSED */
16677 static int
16678 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16679 {
16680 	tf_t	*tbf;
16681 	tcp_t	*tcp, *ltcp;
16682 	int	i;
16683 	zoneid_t zoneid;
16684 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
16685 
16686 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16687 
16688 	/* Refer to comments in tcp_status_report(). */
16689 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16690 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16691 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16692 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16693 			return (0);
16694 		}
16695 	}
16696 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16697 		/* The following may work even if we cannot get a large buf. */
16698 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16699 		return (0);
16700 	}
16701 
16702 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16703 
16704 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
16705 		tbf = &tcps->tcps_bind_fanout[i];
16706 		mutex_enter(&tbf->tf_lock);
16707 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
16708 		    ltcp = ltcp->tcp_bind_hash) {
16709 			for (tcp = ltcp; tcp != NULL;
16710 			    tcp = tcp->tcp_bind_hash_port) {
16711 				if (zoneid != GLOBAL_ZONEID &&
16712 				    zoneid != tcp->tcp_connp->conn_zoneid)
16713 					continue;
16714 				CONN_INC_REF(tcp->tcp_connp);
16715 				tcp_report_item(mp->b_cont, tcp, i,
16716 				    Q_TO_TCP(q), cr);
16717 				CONN_DEC_REF(tcp->tcp_connp);
16718 			}
16719 		}
16720 		mutex_exit(&tbf->tf_lock);
16721 	}
16722 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16723 	return (0);
16724 }
16725 
16726 /* TCP status report triggered via the Named Dispatch mechanism. */
16727 /* ARGSUSED */
16728 static int
16729 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16730 {
16731 	connf_t	*connfp;
16732 	conn_t	*connp;
16733 	tcp_t	*tcp;
16734 	int	i;
16735 	zoneid_t zoneid;
16736 	tcp_stack_t *tcps;
16737 	ip_stack_t	*ipst;
16738 
16739 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16740 	tcps = Q_TO_TCP(q)->tcp_tcps;
16741 
16742 	/* Refer to comments in tcp_status_report(). */
16743 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16744 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16745 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16746 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16747 			return (0);
16748 		}
16749 	}
16750 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16751 		/* The following may work even if we cannot get a large buf. */
16752 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16753 		return (0);
16754 	}
16755 
16756 	(void) mi_mpprintf(mp,
16757 	    "    TCP    " MI_COL_HDRPAD_STR
16758 	    "zone IP addr	 port  seqnum   backlog (q0/q/max)");
16759 
16760 	ipst = tcps->tcps_netstack->netstack_ip;
16761 
16762 	for (i = 0; i < ipst->ips_ipcl_bind_fanout_size; i++) {
16763 		connfp = &ipst->ips_ipcl_bind_fanout[i];
16764 		connp = NULL;
16765 		while ((connp =
16766 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16767 			tcp = connp->conn_tcp;
16768 			if (zoneid != GLOBAL_ZONEID &&
16769 			    zoneid != connp->conn_zoneid)
16770 				continue;
16771 			tcp_report_listener(mp->b_cont, tcp, i);
16772 		}
16773 	}
16774 
16775 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16776 	return (0);
16777 }
16778 
16779 /* TCP status report triggered via the Named Dispatch mechanism. */
16780 /* ARGSUSED */
16781 static int
16782 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16783 {
16784 	connf_t	*connfp;
16785 	conn_t	*connp;
16786 	tcp_t	*tcp;
16787 	int	i;
16788 	zoneid_t zoneid;
16789 	tcp_stack_t *tcps;
16790 	ip_stack_t *ipst;
16791 
16792 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16793 	tcps = Q_TO_TCP(q)->tcp_tcps;
16794 	ipst = tcps->tcps_netstack->netstack_ip;
16795 
16796 	/* Refer to comments in tcp_status_report(). */
16797 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16798 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16799 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16800 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16801 			return (0);
16802 		}
16803 	}
16804 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16805 		/* The following may work even if we cannot get a large buf. */
16806 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16807 		return (0);
16808 	}
16809 
16810 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16811 	    ipst->ips_ipcl_conn_fanout_size);
16812 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16813 
16814 	for (i = 0; i < ipst->ips_ipcl_conn_fanout_size; i++) {
16815 		connfp =  &ipst->ips_ipcl_conn_fanout[i];
16816 		connp = NULL;
16817 		while ((connp =
16818 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16819 			tcp = connp->conn_tcp;
16820 			if (zoneid != GLOBAL_ZONEID &&
16821 			    zoneid != connp->conn_zoneid)
16822 				continue;
16823 			tcp_report_item(mp->b_cont, tcp, i,
16824 			    Q_TO_TCP(q), cr);
16825 		}
16826 	}
16827 
16828 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16829 	return (0);
16830 }
16831 
16832 /* TCP status report triggered via the Named Dispatch mechanism. */
16833 /* ARGSUSED */
16834 static int
16835 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16836 {
16837 	tf_t	*tf;
16838 	tcp_t	*tcp;
16839 	int	i;
16840 	zoneid_t zoneid;
16841 	tcp_stack_t	*tcps;
16842 
16843 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16844 	tcps = Q_TO_TCP(q)->tcp_tcps;
16845 
16846 	/* Refer to comments in tcp_status_report(). */
16847 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16848 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16849 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16850 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16851 			return (0);
16852 		}
16853 	}
16854 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16855 		/* The following may work even if we cannot get a large buf. */
16856 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16857 		return (0);
16858 	}
16859 
16860 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16861 
16862 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
16863 		tf = &tcps->tcps_acceptor_fanout[i];
16864 		mutex_enter(&tf->tf_lock);
16865 		for (tcp = tf->tf_tcp; tcp != NULL;
16866 		    tcp = tcp->tcp_acceptor_hash) {
16867 			if (zoneid != GLOBAL_ZONEID &&
16868 			    zoneid != tcp->tcp_connp->conn_zoneid)
16869 				continue;
16870 			tcp_report_item(mp->b_cont, tcp, i,
16871 			    Q_TO_TCP(q), cr);
16872 		}
16873 		mutex_exit(&tf->tf_lock);
16874 	}
16875 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16876 	return (0);
16877 }
16878 
16879 /*
16880  * tcp_timer is the timer service routine.  It handles the retransmission,
16881  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16882  * from the state of the tcp instance what kind of action needs to be done
16883  * at the time it is called.
16884  */
16885 static void
16886 tcp_timer(void *arg)
16887 {
16888 	mblk_t		*mp;
16889 	clock_t		first_threshold;
16890 	clock_t		second_threshold;
16891 	clock_t		ms;
16892 	uint32_t	mss;
16893 	conn_t		*connp = (conn_t *)arg;
16894 	tcp_t		*tcp = connp->conn_tcp;
16895 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16896 
16897 	tcp->tcp_timer_tid = 0;
16898 
16899 	if (tcp->tcp_fused)
16900 		return;
16901 
16902 	first_threshold =  tcp->tcp_first_timer_threshold;
16903 	second_threshold = tcp->tcp_second_timer_threshold;
16904 	switch (tcp->tcp_state) {
16905 	case TCPS_IDLE:
16906 	case TCPS_BOUND:
16907 	case TCPS_LISTEN:
16908 		return;
16909 	case TCPS_SYN_RCVD: {
16910 		tcp_t	*listener = tcp->tcp_listener;
16911 
16912 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16913 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16914 			/* it's our first timeout */
16915 			tcp->tcp_syn_rcvd_timeout = 1;
16916 			mutex_enter(&listener->tcp_eager_lock);
16917 			listener->tcp_syn_rcvd_timeout++;
16918 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16919 				/*
16920 				 * Make this eager available for drop if we
16921 				 * need to drop one to accomodate a new
16922 				 * incoming SYN request.
16923 				 */
16924 				MAKE_DROPPABLE(listener, tcp);
16925 			}
16926 			if (!listener->tcp_syn_defense &&
16927 			    (listener->tcp_syn_rcvd_timeout >
16928 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
16929 			    (tcps->tcps_conn_req_max_q0 > 200)) {
16930 				/* We may be under attack. Put on a defense. */
16931 				listener->tcp_syn_defense = B_TRUE;
16932 				cmn_err(CE_WARN, "High TCP connect timeout "
16933 				    "rate! System (port %d) may be under a "
16934 				    "SYN flood attack!",
16935 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16936 
16937 				listener->tcp_ip_addr_cache = kmem_zalloc(
16938 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16939 				    KM_NOSLEEP);
16940 			}
16941 			mutex_exit(&listener->tcp_eager_lock);
16942 		} else if (listener != NULL) {
16943 			mutex_enter(&listener->tcp_eager_lock);
16944 			tcp->tcp_syn_rcvd_timeout++;
16945 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
16946 			    !tcp->tcp_closemp_used) {
16947 				/*
16948 				 * This is our second timeout. Put the tcp in
16949 				 * the list of droppable eagers to allow it to
16950 				 * be dropped, if needed. We don't check
16951 				 * whether tcp_dontdrop is set or not to
16952 				 * protect ourselve from a SYN attack where a
16953 				 * remote host can spoof itself as one of the
16954 				 * good IP source and continue to hold
16955 				 * resources too long.
16956 				 */
16957 				MAKE_DROPPABLE(listener, tcp);
16958 			}
16959 			mutex_exit(&listener->tcp_eager_lock);
16960 		}
16961 	}
16962 		/* FALLTHRU */
16963 	case TCPS_SYN_SENT:
16964 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16965 		second_threshold = tcp->tcp_second_ctimer_threshold;
16966 		break;
16967 	case TCPS_ESTABLISHED:
16968 	case TCPS_FIN_WAIT_1:
16969 	case TCPS_CLOSING:
16970 	case TCPS_CLOSE_WAIT:
16971 	case TCPS_LAST_ACK:
16972 		/* If we have data to rexmit */
16973 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16974 			clock_t	time_to_wait;
16975 
16976 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
16977 			if (!tcp->tcp_xmit_head)
16978 				break;
16979 			time_to_wait = lbolt -
16980 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16981 			time_to_wait = tcp->tcp_rto -
16982 			    TICK_TO_MSEC(time_to_wait);
16983 			/*
16984 			 * If the timer fires too early, 1 clock tick earlier,
16985 			 * restart the timer.
16986 			 */
16987 			if (time_to_wait > msec_per_tick) {
16988 				TCP_STAT(tcps, tcp_timer_fire_early);
16989 				TCP_TIMER_RESTART(tcp, time_to_wait);
16990 				return;
16991 			}
16992 			/*
16993 			 * When we probe zero windows, we force the swnd open.
16994 			 * If our peer acks with a closed window swnd will be
16995 			 * set to zero by tcp_rput(). As long as we are
16996 			 * receiving acks tcp_rput will
16997 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16998 			 * first and second interval actions.  NOTE: the timer
16999 			 * interval is allowed to continue its exponential
17000 			 * backoff.
17001 			 */
17002 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
17003 				if (tcp->tcp_debug) {
17004 					(void) strlog(TCP_MOD_ID, 0, 1,
17005 					    SL_TRACE, "tcp_timer: zero win");
17006 				}
17007 			} else {
17008 				/*
17009 				 * After retransmission, we need to do
17010 				 * slow start.  Set the ssthresh to one
17011 				 * half of current effective window and
17012 				 * cwnd to one MSS.  Also reset
17013 				 * tcp_cwnd_cnt.
17014 				 *
17015 				 * Note that if tcp_ssthresh is reduced because
17016 				 * of ECN, do not reduce it again unless it is
17017 				 * already one window of data away (tcp_cwr
17018 				 * should then be cleared) or this is a
17019 				 * timeout for a retransmitted segment.
17020 				 */
17021 				uint32_t npkt;
17022 
17023 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
17024 					npkt = ((tcp->tcp_timer_backoff ?
17025 					    tcp->tcp_cwnd_ssthresh :
17026 					    tcp->tcp_snxt -
17027 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
17028 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
17029 					    tcp->tcp_mss;
17030 				}
17031 				tcp->tcp_cwnd = tcp->tcp_mss;
17032 				tcp->tcp_cwnd_cnt = 0;
17033 				if (tcp->tcp_ecn_ok) {
17034 					tcp->tcp_cwr = B_TRUE;
17035 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17036 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17037 				}
17038 			}
17039 			break;
17040 		}
17041 		/*
17042 		 * We have something to send yet we cannot send.  The
17043 		 * reason can be:
17044 		 *
17045 		 * 1. Zero send window: we need to do zero window probe.
17046 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17047 		 * segments.
17048 		 * 3. SWS avoidance: receiver may have shrunk window,
17049 		 * reset our knowledge.
17050 		 *
17051 		 * Note that condition 2 can happen with either 1 or
17052 		 * 3.  But 1 and 3 are exclusive.
17053 		 */
17054 		if (tcp->tcp_unsent != 0) {
17055 			if (tcp->tcp_cwnd == 0) {
17056 				/*
17057 				 * Set tcp_cwnd to 1 MSS so that a
17058 				 * new segment can be sent out.  We
17059 				 * are "clocking out" new data when
17060 				 * the network is really congested.
17061 				 */
17062 				ASSERT(tcp->tcp_ecn_ok);
17063 				tcp->tcp_cwnd = tcp->tcp_mss;
17064 			}
17065 			if (tcp->tcp_swnd == 0) {
17066 				/* Extend window for zero window probe */
17067 				tcp->tcp_swnd++;
17068 				tcp->tcp_zero_win_probe = B_TRUE;
17069 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
17070 			} else {
17071 				/*
17072 				 * Handle timeout from sender SWS avoidance.
17073 				 * Reset our knowledge of the max send window
17074 				 * since the receiver might have reduced its
17075 				 * receive buffer.  Avoid setting tcp_max_swnd
17076 				 * to one since that will essentially disable
17077 				 * the SWS checks.
17078 				 *
17079 				 * Note that since we don't have a SWS
17080 				 * state variable, if the timeout is set
17081 				 * for ECN but not for SWS, this
17082 				 * code will also be executed.  This is
17083 				 * fine as tcp_max_swnd is updated
17084 				 * constantly and it will not affect
17085 				 * anything.
17086 				 */
17087 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17088 			}
17089 			tcp_wput_data(tcp, NULL, B_FALSE);
17090 			return;
17091 		}
17092 		/* Is there a FIN that needs to be to re retransmitted? */
17093 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17094 		    !tcp->tcp_fin_acked)
17095 			break;
17096 		/* Nothing to do, return without restarting timer. */
17097 		TCP_STAT(tcps, tcp_timer_fire_miss);
17098 		return;
17099 	case TCPS_FIN_WAIT_2:
17100 		/*
17101 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17102 		 * We waited some time for for peer's FIN, but it hasn't
17103 		 * arrived.  We flush the connection now to avoid
17104 		 * case where the peer has rebooted.
17105 		 */
17106 		if (TCP_IS_DETACHED(tcp)) {
17107 			(void) tcp_clean_death(tcp, 0, 23);
17108 		} else {
17109 			TCP_TIMER_RESTART(tcp,
17110 			    tcps->tcps_fin_wait_2_flush_interval);
17111 		}
17112 		return;
17113 	case TCPS_TIME_WAIT:
17114 		(void) tcp_clean_death(tcp, 0, 24);
17115 		return;
17116 	default:
17117 		if (tcp->tcp_debug) {
17118 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
17119 			    "tcp_timer: strange state (%d) %s",
17120 			    tcp->tcp_state, tcp_display(tcp, NULL,
17121 			    DISP_PORT_ONLY));
17122 		}
17123 		return;
17124 	}
17125 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17126 		/*
17127 		 * For zero window probe, we need to send indefinitely,
17128 		 * unless we have not heard from the other side for some
17129 		 * time...
17130 		 */
17131 		if ((tcp->tcp_zero_win_probe == 0) ||
17132 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17133 		    second_threshold)) {
17134 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
17135 			/*
17136 			 * If TCP is in SYN_RCVD state, send back a
17137 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17138 			 * should be zero in TCPS_SYN_RCVD state.
17139 			 */
17140 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17141 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17142 				    "in SYN_RCVD",
17143 				    tcp, tcp->tcp_snxt,
17144 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17145 			}
17146 			(void) tcp_clean_death(tcp,
17147 			    tcp->tcp_client_errno ?
17148 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17149 			return;
17150 		} else {
17151 			/*
17152 			 * Set tcp_ms_we_have_waited to second_threshold
17153 			 * so that in next timeout, we will do the above
17154 			 * check (lbolt - tcp_last_recv_time).  This is
17155 			 * also to avoid overflow.
17156 			 *
17157 			 * We don't need to decrement tcp_timer_backoff
17158 			 * to avoid overflow because it will be decremented
17159 			 * later if new timeout value is greater than
17160 			 * tcp_rexmit_interval_max.  In the case when
17161 			 * tcp_rexmit_interval_max is greater than
17162 			 * second_threshold, it means that we will wait
17163 			 * longer than second_threshold to send the next
17164 			 * window probe.
17165 			 */
17166 			tcp->tcp_ms_we_have_waited = second_threshold;
17167 		}
17168 	} else if (ms > first_threshold) {
17169 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17170 		    tcp->tcp_xmit_head != NULL) {
17171 			tcp->tcp_xmit_head =
17172 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17173 		}
17174 		/*
17175 		 * We have been retransmitting for too long...  The RTT
17176 		 * we calculated is probably incorrect.  Reinitialize it.
17177 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17178 		 * tcp_rtt_update so that we won't accidentally cache a
17179 		 * bad value.  But only do this if this is not a zero
17180 		 * window probe.
17181 		 */
17182 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17183 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17184 			    (tcp->tcp_rtt_sa >> 5);
17185 			tcp->tcp_rtt_sa = 0;
17186 			tcp_ip_notify(tcp);
17187 			tcp->tcp_rtt_update = 0;
17188 		}
17189 	}
17190 	tcp->tcp_timer_backoff++;
17191 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17192 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17193 	    tcps->tcps_rexmit_interval_min) {
17194 		/*
17195 		 * This means the original RTO is tcp_rexmit_interval_min.
17196 		 * So we will use tcp_rexmit_interval_min as the RTO value
17197 		 * and do the backoff.
17198 		 */
17199 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
17200 	} else {
17201 		ms <<= tcp->tcp_timer_backoff;
17202 	}
17203 	if (ms > tcps->tcps_rexmit_interval_max) {
17204 		ms = tcps->tcps_rexmit_interval_max;
17205 		/*
17206 		 * ms is at max, decrement tcp_timer_backoff to avoid
17207 		 * overflow.
17208 		 */
17209 		tcp->tcp_timer_backoff--;
17210 	}
17211 	tcp->tcp_ms_we_have_waited += ms;
17212 	if (tcp->tcp_zero_win_probe == 0) {
17213 		tcp->tcp_rto = ms;
17214 	}
17215 	TCP_TIMER_RESTART(tcp, ms);
17216 	/*
17217 	 * This is after a timeout and tcp_rto is backed off.  Set
17218 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17219 	 * restart the timer with a correct value.
17220 	 */
17221 	tcp->tcp_set_timer = 1;
17222 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17223 	if (mss > tcp->tcp_mss)
17224 		mss = tcp->tcp_mss;
17225 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17226 		mss = tcp->tcp_swnd;
17227 
17228 	if ((mp = tcp->tcp_xmit_head) != NULL)
17229 		mp->b_prev = (mblk_t *)lbolt;
17230 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17231 	    B_TRUE);
17232 
17233 	/*
17234 	 * When slow start after retransmission begins, start with
17235 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17236 	 * start phase.  tcp_snd_burst controls how many segments
17237 	 * can be sent because of an ack.
17238 	 */
17239 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17240 	tcp->tcp_snd_burst = TCP_CWND_SS;
17241 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17242 	    (tcp->tcp_unsent == 0)) {
17243 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17244 	} else {
17245 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17246 	}
17247 	tcp->tcp_rexmit = B_TRUE;
17248 	tcp->tcp_dupack_cnt = 0;
17249 
17250 	/*
17251 	 * Remove all rexmit SACK blk to start from fresh.
17252 	 */
17253 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17254 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17255 		tcp->tcp_num_notsack_blk = 0;
17256 		tcp->tcp_cnt_notsack_list = 0;
17257 	}
17258 	if (mp == NULL) {
17259 		return;
17260 	}
17261 	/* Attach credentials to retransmitted initial SYNs. */
17262 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17263 		mblk_setcred(mp, tcp->tcp_cred);
17264 		DB_CPID(mp) = tcp->tcp_cpid;
17265 	}
17266 
17267 	tcp->tcp_csuna = tcp->tcp_snxt;
17268 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17269 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17270 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17271 
17272 }
17273 
17274 static int
17275 tcp_do_unbind(conn_t *connp)
17276 {
17277 	tcp_t *tcp = connp->conn_tcp;
17278 	int error = 0;
17279 
17280 	switch (tcp->tcp_state) {
17281 	case TCPS_BOUND:
17282 	case TCPS_LISTEN:
17283 		break;
17284 	default:
17285 		return (-TOUTSTATE);
17286 	}
17287 
17288 	/*
17289 	 * Need to clean up all the eagers since after the unbind, segments
17290 	 * will no longer be delivered to this listener stream.
17291 	 */
17292 	mutex_enter(&tcp->tcp_eager_lock);
17293 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17294 		tcp_eager_cleanup(tcp, 0);
17295 	}
17296 	mutex_exit(&tcp->tcp_eager_lock);
17297 
17298 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17299 		tcp->tcp_ipha->ipha_src = 0;
17300 	} else {
17301 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17302 	}
17303 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17304 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17305 	tcp_bind_hash_remove(tcp);
17306 	tcp->tcp_state = TCPS_IDLE;
17307 	tcp->tcp_mdt = B_FALSE;
17308 
17309 	connp = tcp->tcp_connp;
17310 	connp->conn_mdt_ok = B_FALSE;
17311 	ipcl_hash_remove(connp);
17312 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17313 
17314 	return (error);
17315 }
17316 
17317 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17318 static void
17319 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
17320 {
17321 	int error = tcp_do_unbind(tcp->tcp_connp);
17322 
17323 	if (error > 0) {
17324 		tcp_err_ack(tcp, mp, TSYSERR, error);
17325 	} else if (error < 0) {
17326 		tcp_err_ack(tcp, mp, -error, 0);
17327 	} else {
17328 		/* Send M_FLUSH according to TPI */
17329 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17330 
17331 		mp = mi_tpi_ok_ack_alloc(mp);
17332 		putnext(tcp->tcp_rq, mp);
17333 	}
17334 }
17335 
17336 /*
17337  * Don't let port fall into the privileged range.
17338  * Since the extra privileged ports can be arbitrary we also
17339  * ensure that we exclude those from consideration.
17340  * tcp_g_epriv_ports is not sorted thus we loop over it until
17341  * there are no changes.
17342  *
17343  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17344  * but instead the code relies on:
17345  * - the fact that the address of the array and its size never changes
17346  * - the atomic assignment of the elements of the array
17347  *
17348  * Returns 0 if there are no more ports available.
17349  *
17350  * TS note: skip multilevel ports.
17351  */
17352 static in_port_t
17353 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17354 {
17355 	int i;
17356 	boolean_t restart = B_FALSE;
17357 	tcp_stack_t *tcps = tcp->tcp_tcps;
17358 
17359 	if (random && tcp_random_anon_port != 0) {
17360 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17361 		    sizeof (in_port_t));
17362 		/*
17363 		 * Unless changed by a sys admin, the smallest anon port
17364 		 * is 32768 and the largest anon port is 65535.  It is
17365 		 * very likely (50%) for the random port to be smaller
17366 		 * than the smallest anon port.  When that happens,
17367 		 * add port % (anon port range) to the smallest anon
17368 		 * port to get the random port.  It should fall into the
17369 		 * valid anon port range.
17370 		 */
17371 		if (port < tcps->tcps_smallest_anon_port) {
17372 			port = tcps->tcps_smallest_anon_port +
17373 			    port % (tcps->tcps_largest_anon_port -
17374 			    tcps->tcps_smallest_anon_port);
17375 		}
17376 	}
17377 
17378 retry:
17379 	if (port < tcps->tcps_smallest_anon_port)
17380 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17381 
17382 	if (port > tcps->tcps_largest_anon_port) {
17383 		if (restart)
17384 			return (0);
17385 		restart = B_TRUE;
17386 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17387 	}
17388 
17389 	if (port < tcps->tcps_smallest_nonpriv_port)
17390 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17391 
17392 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17393 		if (port == tcps->tcps_g_epriv_ports[i]) {
17394 			port++;
17395 			/*
17396 			 * Make sure whether the port is in the
17397 			 * valid range.
17398 			 */
17399 			goto retry;
17400 		}
17401 	}
17402 	if (is_system_labeled() &&
17403 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17404 	    IPPROTO_TCP, B_TRUE)) != 0) {
17405 		port = i;
17406 		goto retry;
17407 	}
17408 	return (port);
17409 }
17410 
17411 /*
17412  * Return the next anonymous port in the privileged port range for
17413  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17414  * downwards.  This is the same behavior as documented in the userland
17415  * library call rresvport(3N).
17416  *
17417  * TS note: skip multilevel ports.
17418  */
17419 static in_port_t
17420 tcp_get_next_priv_port(const tcp_t *tcp)
17421 {
17422 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17423 	in_port_t nextport;
17424 	boolean_t restart = B_FALSE;
17425 	tcp_stack_t *tcps = tcp->tcp_tcps;
17426 retry:
17427 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17428 	    next_priv_port >= IPPORT_RESERVED) {
17429 		next_priv_port = IPPORT_RESERVED - 1;
17430 		if (restart)
17431 			return (0);
17432 		restart = B_TRUE;
17433 	}
17434 	if (is_system_labeled() &&
17435 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17436 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17437 		next_priv_port = nextport;
17438 		goto retry;
17439 	}
17440 	return (next_priv_port--);
17441 }
17442 
17443 /* The write side r/w procedure. */
17444 
17445 #if CCS_STATS
17446 struct {
17447 	struct {
17448 		int64_t count, bytes;
17449 	} tot, hit;
17450 } wrw_stats;
17451 #endif
17452 
17453 /*
17454  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17455  * messages.
17456  */
17457 /* ARGSUSED */
17458 static void
17459 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17460 {
17461 	conn_t	*connp = (conn_t *)arg;
17462 	tcp_t	*tcp = connp->conn_tcp;
17463 	queue_t	*q = tcp->tcp_wq;
17464 
17465 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17466 	/*
17467 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17468 	 * Once the close starts, streamhead and sockfs will not let any data
17469 	 * packets come down (close ensures that there are no threads using the
17470 	 * queue and no new threads will come down) but since qprocsoff()
17471 	 * hasn't happened yet, a M_FLUSH or some non data message might
17472 	 * get reflected back (in response to our own FLUSHRW) and get
17473 	 * processed after tcp_close() is done. The conn would still be valid
17474 	 * because a ref would have added but we need to check the state
17475 	 * before actually processing the packet.
17476 	 */
17477 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17478 		freemsg(mp);
17479 		return;
17480 	}
17481 
17482 	switch (DB_TYPE(mp)) {
17483 	case M_IOCDATA:
17484 		tcp_wput_iocdata(tcp, mp);
17485 		break;
17486 	case M_FLUSH:
17487 		tcp_wput_flush(tcp, mp);
17488 		break;
17489 	default:
17490 		CALL_IP_WPUT(connp, q, mp);
17491 		break;
17492 	}
17493 }
17494 
17495 /*
17496  * The TCP fast path write put procedure.
17497  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17498  */
17499 /* ARGSUSED */
17500 void
17501 tcp_output(void *arg, mblk_t *mp, void *arg2)
17502 {
17503 	int		len;
17504 	int		hdrlen;
17505 	int		plen;
17506 	mblk_t		*mp1;
17507 	uchar_t		*rptr;
17508 	uint32_t	snxt;
17509 	tcph_t		*tcph;
17510 	struct datab	*db;
17511 	uint32_t	suna;
17512 	uint32_t	mss;
17513 	ipaddr_t	*dst;
17514 	ipaddr_t	*src;
17515 	uint32_t	sum;
17516 	int		usable;
17517 	conn_t		*connp = (conn_t *)arg;
17518 	tcp_t		*tcp = connp->conn_tcp;
17519 	uint32_t	msize;
17520 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17521 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17522 
17523 	/*
17524 	 * Try and ASSERT the minimum possible references on the
17525 	 * conn early enough. Since we are executing on write side,
17526 	 * the connection is obviously not detached and that means
17527 	 * there is a ref each for TCP and IP. Since we are behind
17528 	 * the squeue, the minimum references needed are 3. If the
17529 	 * conn is in classifier hash list, there should be an
17530 	 * extra ref for that (we check both the possibilities).
17531 	 */
17532 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17533 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17534 
17535 	ASSERT(DB_TYPE(mp) == M_DATA);
17536 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17537 
17538 	mutex_enter(&tcp->tcp_non_sq_lock);
17539 	tcp->tcp_squeue_bytes -= msize;
17540 	mutex_exit(&tcp->tcp_non_sq_lock);
17541 
17542 	/* Check to see if this connection wants to be re-fused. */
17543 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
17544 		if (tcp->tcp_ipversion == IPV4_VERSION) {
17545 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
17546 			    &tcp->tcp_saved_tcph);
17547 		} else {
17548 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
17549 			    &tcp->tcp_saved_tcph);
17550 		}
17551 	}
17552 	/* Bypass tcp protocol for fused tcp loopback */
17553 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17554 		return;
17555 
17556 	mss = tcp->tcp_mss;
17557 	if (tcp->tcp_xmit_zc_clean)
17558 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17559 
17560 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17561 	len = (int)(mp->b_wptr - mp->b_rptr);
17562 
17563 	/*
17564 	 * Criteria for fast path:
17565 	 *
17566 	 *   1. no unsent data
17567 	 *   2. single mblk in request
17568 	 *   3. connection established
17569 	 *   4. data in mblk
17570 	 *   5. len <= mss
17571 	 *   6. no tcp_valid bits
17572 	 */
17573 	if ((tcp->tcp_unsent != 0) ||
17574 	    (tcp->tcp_cork) ||
17575 	    (mp->b_cont != NULL) ||
17576 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17577 	    (len == 0) ||
17578 	    (len > mss) ||
17579 	    (tcp->tcp_valid_bits != 0)) {
17580 		tcp_wput_data(tcp, mp, B_FALSE);
17581 		return;
17582 	}
17583 
17584 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17585 	ASSERT(tcp->tcp_fin_sent == 0);
17586 
17587 	/* queue new packet onto retransmission queue */
17588 	if (tcp->tcp_xmit_head == NULL) {
17589 		tcp->tcp_xmit_head = mp;
17590 	} else {
17591 		tcp->tcp_xmit_last->b_cont = mp;
17592 	}
17593 	tcp->tcp_xmit_last = mp;
17594 	tcp->tcp_xmit_tail = mp;
17595 
17596 	/* find out how much we can send */
17597 	/* BEGIN CSTYLED */
17598 	/*
17599 	 *    un-acked	   usable
17600 	 *  |--------------|-----------------|
17601 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
17602 	 */
17603 	/* END CSTYLED */
17604 
17605 	/* start sending from tcp_snxt */
17606 	snxt = tcp->tcp_snxt;
17607 
17608 	/*
17609 	 * Check to see if this connection has been idled for some
17610 	 * time and no ACK is expected.  If it is, we need to slow
17611 	 * start again to get back the connection's "self-clock" as
17612 	 * described in VJ's paper.
17613 	 *
17614 	 * Refer to the comment in tcp_mss_set() for the calculation
17615 	 * of tcp_cwnd after idle.
17616 	 */
17617 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17618 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17619 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
17620 	}
17621 
17622 	usable = tcp->tcp_swnd;		/* tcp window size */
17623 	if (usable > tcp->tcp_cwnd)
17624 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17625 	usable -= snxt;		/* subtract stuff already sent */
17626 	suna = tcp->tcp_suna;
17627 	usable += suna;
17628 	/* usable can be < 0 if the congestion window is smaller */
17629 	if (len > usable) {
17630 		/* Can't send complete M_DATA in one shot */
17631 		goto slow;
17632 	}
17633 
17634 	mutex_enter(&tcp->tcp_non_sq_lock);
17635 	if (tcp->tcp_flow_stopped &&
17636 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17637 		tcp_clrqfull(tcp);
17638 	}
17639 	mutex_exit(&tcp->tcp_non_sq_lock);
17640 
17641 	/*
17642 	 * determine if anything to send (Nagle).
17643 	 *
17644 	 *   1. len < tcp_mss (i.e. small)
17645 	 *   2. unacknowledged data present
17646 	 *   3. len < nagle limit
17647 	 *   4. last packet sent < nagle limit (previous packet sent)
17648 	 */
17649 	if ((len < mss) && (snxt != suna) &&
17650 	    (len < (int)tcp->tcp_naglim) &&
17651 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17652 		/*
17653 		 * This was the first unsent packet and normally
17654 		 * mss < xmit_hiwater so there is no need to worry
17655 		 * about flow control. The next packet will go
17656 		 * through the flow control check in tcp_wput_data().
17657 		 */
17658 		/* leftover work from above */
17659 		tcp->tcp_unsent = len;
17660 		tcp->tcp_xmit_tail_unsent = len;
17661 
17662 		return;
17663 	}
17664 
17665 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17666 
17667 	if (snxt == suna) {
17668 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17669 	}
17670 
17671 	/* we have always sent something */
17672 	tcp->tcp_rack_cnt = 0;
17673 
17674 	tcp->tcp_snxt = snxt + len;
17675 	tcp->tcp_rack = tcp->tcp_rnxt;
17676 
17677 	if ((mp1 = dupb(mp)) == 0)
17678 		goto no_memory;
17679 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17680 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17681 
17682 	/* adjust tcp header information */
17683 	tcph = tcp->tcp_tcph;
17684 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17685 
17686 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17687 	sum = (sum >> 16) + (sum & 0xFFFF);
17688 	U16_TO_ABE16(sum, tcph->th_sum);
17689 
17690 	U32_TO_ABE32(snxt, tcph->th_seq);
17691 
17692 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17693 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17694 	BUMP_LOCAL(tcp->tcp_obsegs);
17695 
17696 	/* Update the latest receive window size in TCP header. */
17697 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17698 	    tcph->th_win);
17699 
17700 	tcp->tcp_last_sent_len = (ushort_t)len;
17701 
17702 	plen = len + tcp->tcp_hdr_len;
17703 
17704 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17705 		tcp->tcp_ipha->ipha_length = htons(plen);
17706 	} else {
17707 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17708 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17709 	}
17710 
17711 	/* see if we need to allocate a mblk for the headers */
17712 	hdrlen = tcp->tcp_hdr_len;
17713 	rptr = mp1->b_rptr - hdrlen;
17714 	db = mp1->b_datap;
17715 	if ((db->db_ref != 2) || rptr < db->db_base ||
17716 	    (!OK_32PTR(rptr))) {
17717 		/* NOTE: we assume allocb returns an OK_32PTR */
17718 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17719 		    tcps->tcps_wroff_xtra, BPRI_MED);
17720 		if (!mp) {
17721 			freemsg(mp1);
17722 			goto no_memory;
17723 		}
17724 		mp->b_cont = mp1;
17725 		mp1 = mp;
17726 		/* Leave room for Link Level header */
17727 		/* hdrlen = tcp->tcp_hdr_len; */
17728 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17729 		mp1->b_wptr = &rptr[hdrlen];
17730 	}
17731 	mp1->b_rptr = rptr;
17732 
17733 	/* Fill in the timestamp option. */
17734 	if (tcp->tcp_snd_ts_ok) {
17735 		U32_TO_BE32((uint32_t)lbolt,
17736 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17737 		U32_TO_BE32(tcp->tcp_ts_recent,
17738 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17739 	} else {
17740 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17741 	}
17742 
17743 	/* copy header into outgoing packet */
17744 	dst = (ipaddr_t *)rptr;
17745 	src = (ipaddr_t *)tcp->tcp_iphc;
17746 	dst[0] = src[0];
17747 	dst[1] = src[1];
17748 	dst[2] = src[2];
17749 	dst[3] = src[3];
17750 	dst[4] = src[4];
17751 	dst[5] = src[5];
17752 	dst[6] = src[6];
17753 	dst[7] = src[7];
17754 	dst[8] = src[8];
17755 	dst[9] = src[9];
17756 	if (hdrlen -= 40) {
17757 		hdrlen >>= 2;
17758 		dst += 10;
17759 		src += 10;
17760 		do {
17761 			*dst++ = *src++;
17762 		} while (--hdrlen);
17763 	}
17764 
17765 	/*
17766 	 * Set the ECN info in the TCP header.  Note that this
17767 	 * is not the template header.
17768 	 */
17769 	if (tcp->tcp_ecn_ok) {
17770 		SET_ECT(tcp, rptr);
17771 
17772 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17773 		if (tcp->tcp_ecn_echo_on)
17774 			tcph->th_flags[0] |= TH_ECE;
17775 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17776 			tcph->th_flags[0] |= TH_CWR;
17777 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17778 		}
17779 	}
17780 
17781 	if (tcp->tcp_ip_forward_progress) {
17782 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17783 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17784 		tcp->tcp_ip_forward_progress = B_FALSE;
17785 	}
17786 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17787 	return;
17788 
17789 	/*
17790 	 * If we ran out of memory, we pretend to have sent the packet
17791 	 * and that it was lost on the wire.
17792 	 */
17793 no_memory:
17794 	return;
17795 
17796 slow:
17797 	/* leftover work from above */
17798 	tcp->tcp_unsent = len;
17799 	tcp->tcp_xmit_tail_unsent = len;
17800 	tcp_wput_data(tcp, NULL, B_FALSE);
17801 }
17802 
17803 /* ARGSUSED */
17804 void
17805 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17806 {
17807 	conn_t			*connp = (conn_t *)arg;
17808 	tcp_t			*tcp = connp->conn_tcp;
17809 	queue_t			*q = tcp->tcp_rq;
17810 	struct tcp_options	*tcpopt;
17811 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17812 
17813 	/* socket options */
17814 	uint_t 			sopp_flags;
17815 	ssize_t			sopp_rxhiwat;
17816 	ssize_t			sopp_maxblk;
17817 	ushort_t		sopp_wroff;
17818 	ushort_t		sopp_tail;
17819 	ushort_t		sopp_copyopt;
17820 
17821 	tcpopt = (struct tcp_options *)mp->b_rptr;
17822 
17823 	/*
17824 	 * Drop the eager's ref on the listener, that was placed when
17825 	 * this eager began life in tcp_conn_request.
17826 	 */
17827 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17828 	if (IPCL_IS_NONSTR(connp)) {
17829 		/* Safe to free conn_ind message */
17830 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17831 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17832 
17833 		/* The listener tells us which upper handle to use */
17834 		ASSERT(tcpopt->to_flags & TCPOPT_UPPERHANDLE);
17835 		connp->conn_upper_handle = tcpopt->to_handle;
17836 	}
17837 
17838 	tcp->tcp_detached = B_FALSE;
17839 
17840 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17841 		/*
17842 		 * Someone blewoff the eager before we could finish
17843 		 * the accept.
17844 		 *
17845 		 * The only reason eager exists it because we put in
17846 		 * a ref on it when conn ind went up. We need to send
17847 		 * a disconnect indication up while the last reference
17848 		 * on the eager will be dropped by the squeue when we
17849 		 * return.
17850 		 */
17851 		ASSERT(tcp->tcp_listener == NULL);
17852 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17853 			if (IPCL_IS_NONSTR(connp)) {
17854 				ASSERT(tcp->tcp_issocket);
17855 				(*connp->conn_upcalls->su_disconnected)(
17856 				    connp->conn_upper_handle, tcp->tcp_connid,
17857 				    ECONNREFUSED);
17858 				freemsg(mp);
17859 			} else {
17860 				struct	T_discon_ind	*tdi;
17861 
17862 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17863 				/*
17864 				 * Let us reuse the incoming mblk to avoid
17865 				 * memory allocation failure problems. We know
17866 				 * that the size of the incoming mblk i.e.
17867 				 * stroptions is greater than sizeof
17868 				 * T_discon_ind. So the reallocb below can't
17869 				 * fail.
17870 				 */
17871 				freemsg(mp->b_cont);
17872 				mp->b_cont = NULL;
17873 				ASSERT(DB_REF(mp) == 1);
17874 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17875 				    B_FALSE);
17876 				ASSERT(mp != NULL);
17877 				DB_TYPE(mp) = M_PROTO;
17878 				((union T_primitives *)mp->b_rptr)->type =
17879 				    T_DISCON_IND;
17880 				tdi = (struct T_discon_ind *)mp->b_rptr;
17881 				if (tcp->tcp_issocket) {
17882 					tdi->DISCON_reason = ECONNREFUSED;
17883 					tdi->SEQ_number = 0;
17884 				} else {
17885 					tdi->DISCON_reason = ENOPROTOOPT;
17886 					tdi->SEQ_number =
17887 					    tcp->tcp_conn_req_seqnum;
17888 				}
17889 				mp->b_wptr = mp->b_rptr +
17890 				    sizeof (struct T_discon_ind);
17891 				putnext(q, mp);
17892 				return;
17893 			}
17894 		}
17895 		if (tcp->tcp_hard_binding) {
17896 			tcp->tcp_hard_binding = B_FALSE;
17897 			tcp->tcp_hard_bound = B_TRUE;
17898 		}
17899 		return;
17900 	}
17901 
17902 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
17903 		int boundif = tcpopt->to_boundif;
17904 		uint_t len = sizeof (int);
17905 
17906 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17907 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
17908 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred, NULL);
17909 	}
17910 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
17911 		uint_t on = 1;
17912 		uint_t len = sizeof (uint_t);
17913 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17914 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
17915 		    (uchar_t *)&on, NULL, tcp->tcp_cred, NULL);
17916 	}
17917 
17918 	/*
17919 	 * For a loopback connection with tcp_direct_sockfs on, note that
17920 	 * we don't have to protect tcp_rcv_list yet because synchronous
17921 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17922 	 * possibly race with us.
17923 	 */
17924 
17925 	/*
17926 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17927 	 * properly.  This is the first time we know of the acceptor'
17928 	 * queue.  So we do it here.
17929 	 *
17930 	 * XXX
17931 	 */
17932 	if (tcp->tcp_rcv_list == NULL) {
17933 		/*
17934 		 * Recv queue is empty, tcp_rwnd should not have changed.
17935 		 * That means it should be equal to the listener's tcp_rwnd.
17936 		 */
17937 		if (!IPCL_IS_NONSTR(connp))
17938 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17939 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
17940 	} else {
17941 #ifdef DEBUG
17942 		mblk_t *tmp;
17943 		mblk_t	*mp1;
17944 		uint_t	cnt = 0;
17945 
17946 		mp1 = tcp->tcp_rcv_list;
17947 		while ((tmp = mp1) != NULL) {
17948 			mp1 = tmp->b_next;
17949 			cnt += msgdsize(tmp);
17950 		}
17951 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17952 #endif
17953 		/* There is some data, add them back to get the max. */
17954 		if (!IPCL_IS_NONSTR(connp))
17955 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17956 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17957 	}
17958 	/*
17959 	 * This is the first time we run on the correct
17960 	 * queue after tcp_accept. So fix all the q parameters
17961 	 * here.
17962 	 */
17963 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
17964 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17965 
17966 	/*
17967 	 * Record the stream head's high water mark for this endpoint;
17968 	 * this is used for flow-control purposes.
17969 	 */
17970 	sopp_rxhiwat = tcp->tcp_fused ?
17971 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
17972 	    MAX(tcp->tcp_recv_hiwater, tcps->tcps_sth_rcv_hiwat);
17973 
17974 	/*
17975 	 * Determine what write offset value to use depending on SACK and
17976 	 * whether the endpoint is fused or not.
17977 	 */
17978 	if (tcp->tcp_fused) {
17979 		ASSERT(tcp->tcp_loopback);
17980 		ASSERT(tcp->tcp_loopback_peer != NULL);
17981 		/*
17982 		 * For fused tcp loopback, set the stream head's write
17983 		 * offset value to zero since we won't be needing any room
17984 		 * for TCP/IP headers.  This would also improve performance
17985 		 * since it would reduce the amount of work done by kmem.
17986 		 * Non-fused tcp loopback case is handled separately below.
17987 		 */
17988 		sopp_wroff = 0;
17989 		/*
17990 		 * Update the peer's transmit parameters according to
17991 		 * our recently calculated high water mark value.
17992 		 */
17993 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17994 	} else if (tcp->tcp_snd_sack_ok) {
17995 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17996 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
17997 	} else {
17998 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17999 		    tcps->tcps_wroff_xtra);
18000 	}
18001 
18002 	/*
18003 	 * If this is endpoint is handling SSL, then reserve extra
18004 	 * offset and space at the end.
18005 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
18006 	 * overriding the previous setting. The extra cost of signing and
18007 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
18008 	 * instead of a single contiguous one by the stream head
18009 	 * largely outweighs the statistical reduction of ACKs, when
18010 	 * applicable. The peer will also save on decryption and verification
18011 	 * costs.
18012 	 */
18013 	if (tcp->tcp_kssl_ctx != NULL) {
18014 		sopp_wroff += SSL3_WROFFSET;
18015 
18016 		sopp_flags |= SOCKOPT_TAIL;
18017 		sopp_tail = SSL3_MAX_TAIL_LEN;
18018 
18019 		sopp_flags |= SOCKOPT_ZCOPY;
18020 		sopp_copyopt = ZCVMUNSAFE;
18021 
18022 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
18023 	}
18024 
18025 	/* Send the options up */
18026 	if (IPCL_IS_NONSTR(connp)) {
18027 		struct sock_proto_props sopp;
18028 
18029 		sopp.sopp_flags = sopp_flags;
18030 		sopp.sopp_wroff = sopp_wroff;
18031 		sopp.sopp_maxblk = sopp_maxblk;
18032 		sopp.sopp_rxhiwat = sopp_rxhiwat;
18033 		if (sopp_flags & SOCKOPT_TAIL) {
18034 			ASSERT(tcp->tcp_kssl_ctx != NULL);
18035 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
18036 			sopp.sopp_tail = sopp_tail;
18037 			sopp.sopp_zcopyflag = sopp_copyopt;
18038 		}
18039 		(*connp->conn_upcalls->su_set_proto_props)
18040 		    (connp->conn_upper_handle, &sopp);
18041 	} else {
18042 		struct stroptions *stropt;
18043 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18044 		if (stropt_mp == NULL) {
18045 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
18046 			return;
18047 		}
18048 		DB_TYPE(stropt_mp) = M_SETOPTS;
18049 		stropt = (struct stroptions *)stropt_mp->b_rptr;
18050 		stropt_mp->b_wptr += sizeof (struct stroptions);
18051 		stropt = (struct stroptions *)stropt_mp->b_rptr;
18052 		stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
18053 		stropt->so_hiwat = sopp_rxhiwat;
18054 		stropt->so_wroff = sopp_wroff;
18055 		stropt->so_maxblk = sopp_maxblk;
18056 
18057 		if (sopp_flags & SOCKOPT_TAIL) {
18058 			ASSERT(tcp->tcp_kssl_ctx != NULL);
18059 
18060 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
18061 			stropt->so_tail = sopp_tail;
18062 			stropt->so_copyopt = sopp_copyopt;
18063 		}
18064 
18065 		/* Send the options up */
18066 		putnext(q, stropt_mp);
18067 	}
18068 
18069 	freemsg(mp);
18070 	/*
18071 	 * Pass up any data and/or a fin that has been received.
18072 	 *
18073 	 * Adjust receive window in case it had decreased
18074 	 * (because there is data <=> tcp_rcv_list != NULL)
18075 	 * while the connection was detached. Note that
18076 	 * in case the eager was flow-controlled, w/o this
18077 	 * code, the rwnd may never open up again!
18078 	 */
18079 	if (tcp->tcp_rcv_list != NULL) {
18080 		if (IPCL_IS_NONSTR(connp)) {
18081 			mblk_t *mp;
18082 			int space_left;
18083 			int error;
18084 			boolean_t push = B_TRUE;
18085 
18086 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
18087 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
18088 			    &push) >= 0) {
18089 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
18090 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18091 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
18092 					tcp_xmit_ctl(NULL,
18093 					    tcp, (tcp->tcp_swnd == 0) ?
18094 					    tcp->tcp_suna : tcp->tcp_snxt,
18095 					    tcp->tcp_rnxt, TH_ACK);
18096 				}
18097 			}
18098 			while ((mp = tcp->tcp_rcv_list) != NULL) {
18099 				push = B_TRUE;
18100 				tcp->tcp_rcv_list = mp->b_next;
18101 				mp->b_next = NULL;
18102 				space_left = (*connp->conn_upcalls->su_recv)
18103 				    (connp->conn_upper_handle, mp, msgdsize(mp),
18104 				    0, &error, &push);
18105 				if (space_left < 0) {
18106 					/*
18107 					 * At this point the eager is not
18108 					 * visible to anyone, so fallback
18109 					 * can not happen.
18110 					 */
18111 					ASSERT(error != EOPNOTSUPP);
18112 				}
18113 			}
18114 			tcp->tcp_rcv_last_head = NULL;
18115 			tcp->tcp_rcv_last_tail = NULL;
18116 			tcp->tcp_rcv_cnt = 0;
18117 		} else {
18118 			/* We drain directly in case of fused tcp loopback */
18119 			sodirect_t *sodp;
18120 
18121 			if (!tcp->tcp_fused && canputnext(q)) {
18122 				tcp->tcp_rwnd = q->q_hiwat;
18123 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18124 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
18125 					tcp_xmit_ctl(NULL,
18126 					    tcp, (tcp->tcp_swnd == 0) ?
18127 					    tcp->tcp_suna : tcp->tcp_snxt,
18128 					    tcp->tcp_rnxt, TH_ACK);
18129 				}
18130 			}
18131 
18132 			SOD_PTR_ENTER(tcp, sodp);
18133 			if (sodp != NULL) {
18134 				/* Sodirect, move from rcv_list */
18135 				ASSERT(!tcp->tcp_fused);
18136 				while ((mp = tcp->tcp_rcv_list) != NULL) {
18137 					tcp->tcp_rcv_list = mp->b_next;
18138 					mp->b_next = NULL;
18139 					(void) tcp_rcv_sod_enqueue(tcp, sodp,
18140 					    mp, msgdsize(mp));
18141 				}
18142 				tcp->tcp_rcv_last_head = NULL;
18143 				tcp->tcp_rcv_last_tail = NULL;
18144 				tcp->tcp_rcv_cnt = 0;
18145 				(void) tcp_rcv_sod_wakeup(tcp, sodp);
18146 				/* sod_wakeup() did the mutex_exit() */
18147 			} else {
18148 				/* Not sodirect, drain */
18149 				(void) tcp_rcv_drain(tcp);
18150 			}
18151 		}
18152 
18153 		/*
18154 		 * For fused tcp loopback, back-enable peer endpoint
18155 		 * if it's currently flow-controlled.
18156 		 */
18157 		if (tcp->tcp_fused) {
18158 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18159 
18160 			ASSERT(peer_tcp != NULL);
18161 			ASSERT(peer_tcp->tcp_fused);
18162 			/*
18163 			 * In order to change the peer's tcp_flow_stopped,
18164 			 * we need to take locks for both end points. The
18165 			 * highest address is taken first.
18166 			 */
18167 			if (peer_tcp > tcp) {
18168 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18169 				mutex_enter(&tcp->tcp_non_sq_lock);
18170 			} else {
18171 				mutex_enter(&tcp->tcp_non_sq_lock);
18172 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18173 			}
18174 			if (peer_tcp->tcp_flow_stopped) {
18175 				tcp_clrqfull(peer_tcp);
18176 				TCP_STAT(tcps, tcp_fusion_backenabled);
18177 			}
18178 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18179 			mutex_exit(&tcp->tcp_non_sq_lock);
18180 		}
18181 	}
18182 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18183 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18184 		tcp->tcp_ordrel_done = B_TRUE;
18185 		if (IPCL_IS_NONSTR(connp)) {
18186 			ASSERT(tcp->tcp_ordrel_mp == NULL);
18187 			(*connp->conn_upcalls->su_opctl)(
18188 			    connp->conn_upper_handle,
18189 			    SOCK_OPCTL_SHUT_RECV, 0);
18190 		} else {
18191 			mp = tcp->tcp_ordrel_mp;
18192 			tcp->tcp_ordrel_mp = NULL;
18193 			putnext(q, mp);
18194 		}
18195 	}
18196 	if (tcp->tcp_hard_binding) {
18197 		tcp->tcp_hard_binding = B_FALSE;
18198 		tcp->tcp_hard_bound = B_TRUE;
18199 	}
18200 
18201 	/* We can enable synchronous streams for STREAMS tcp endpoint now */
18202 	if (tcp->tcp_fused && !IPCL_IS_NONSTR(connp) &&
18203 	    tcp->tcp_loopback_peer != NULL &&
18204 	    !IPCL_IS_NONSTR(tcp->tcp_loopback_peer->tcp_connp)) {
18205 		tcp_fuse_syncstr_enable_pair(tcp);
18206 	}
18207 
18208 	if (tcp->tcp_ka_enabled) {
18209 		tcp->tcp_ka_last_intrvl = 0;
18210 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18211 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18212 	}
18213 
18214 	/*
18215 	 * At this point, eager is fully established and will
18216 	 * have the following references -
18217 	 *
18218 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18219 	 * 1 reference for the squeue which will be dropped by the squeue as
18220 	 *	soon as this function returns.
18221 	 * There will be 1 additonal reference for being in classifier
18222 	 *	hash list provided something bad hasn't happened.
18223 	 */
18224 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18225 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18226 }
18227 
18228 /*
18229  * The function called through squeue to get behind listener's perimeter to
18230  * send a deffered conn_ind.
18231  */
18232 /* ARGSUSED */
18233 void
18234 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18235 {
18236 	conn_t	*connp = (conn_t *)arg;
18237 	tcp_t *listener = connp->conn_tcp;
18238 	struct T_conn_ind *conn_ind;
18239 	tcp_t *tcp;
18240 
18241 	if (listener->tcp_state == TCPS_CLOSED ||
18242 	    TCP_IS_DETACHED(listener)) {
18243 		/*
18244 		 * If listener has closed, it would have caused a
18245 		 * a cleanup/blowoff to happen for the eager.
18246 		 */
18247 
18248 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18249 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18250 		    conn_ind->OPT_length);
18251 		/*
18252 		 * We need to drop the ref on eager that was put
18253 		 * tcp_rput_data() before trying to send the conn_ind
18254 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18255 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18256 		 * listener is closed so we drop the ref.
18257 		 */
18258 		CONN_DEC_REF(tcp->tcp_connp);
18259 		freemsg(mp);
18260 		return;
18261 	}
18262 	if (IPCL_IS_NONSTR(connp)) {
18263 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18264 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18265 		    conn_ind->OPT_length);
18266 
18267 		if ((*connp->conn_upcalls->su_newconn)
18268 		    (connp->conn_upper_handle,
18269 		    (sock_lower_handle_t)tcp->tcp_connp,
18270 		    &sock_tcp_downcalls, DB_CRED(mp), DB_CPID(mp),
18271 		    &tcp->tcp_connp->conn_upcalls) != NULL) {
18272 			/* Keep the message around in case of fallback */
18273 			tcp->tcp_conn.tcp_eager_conn_ind = mp;
18274 		} else {
18275 			freemsg(mp);
18276 		}
18277 	} else {
18278 		putnext(listener->tcp_rq, mp);
18279 	}
18280 }
18281 
18282 /* ARGSUSED */
18283 static int
18284 tcp_accept_common(conn_t *lconnp, conn_t *econnp,
18285     sock_upper_handle_t sock_handle, cred_t *cr)
18286 {
18287 	tcp_t *listener, *eager;
18288 	mblk_t *opt_mp;
18289 	struct tcp_options *tcpopt;
18290 
18291 	listener = lconnp->conn_tcp;
18292 	ASSERT(listener->tcp_state == TCPS_LISTEN);
18293 	eager = econnp->conn_tcp;
18294 	ASSERT(eager->tcp_listener != NULL);
18295 
18296 	ASSERT(eager->tcp_rq != NULL);
18297 
18298 	/* If tcp_fused and sodirect enabled disable it */
18299 	if (eager->tcp_fused && eager->tcp_sodirect != NULL) {
18300 		/* Fused, disable sodirect */
18301 		mutex_enter(eager->tcp_sodirect->sod_lockp);
18302 		SOD_DISABLE(eager->tcp_sodirect);
18303 		mutex_exit(eager->tcp_sodirect->sod_lockp);
18304 		eager->tcp_sodirect = NULL;
18305 	}
18306 
18307 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
18308 	if (opt_mp == NULL) {
18309 		return (-TPROTO);
18310 	}
18311 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
18312 	eager->tcp_issocket = B_TRUE;
18313 
18314 	econnp->conn_upcalls = lconnp->conn_upcalls;
18315 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18316 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18317 	ASSERT(econnp->conn_netstack ==
18318 	    listener->tcp_connp->conn_netstack);
18319 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18320 
18321 	/* Put the ref for IP */
18322 	CONN_INC_REF(econnp);
18323 
18324 	/*
18325 	 * We should have minimum of 3 references on the conn
18326 	 * at this point. One each for TCP and IP and one for
18327 	 * the T_conn_ind that was sent up when the 3-way handshake
18328 	 * completed. In the normal case we would also have another
18329 	 * reference (making a total of 4) for the conn being in the
18330 	 * classifier hash list. However the eager could have received
18331 	 * an RST subsequently and tcp_closei_local could have removed
18332 	 * the eager from the classifier hash list, hence we can't
18333 	 * assert that reference.
18334 	 */
18335 	ASSERT(econnp->conn_ref >= 3);
18336 
18337 	opt_mp->b_datap->db_type = M_SETOPTS;
18338 	opt_mp->b_wptr += sizeof (struct tcp_options);
18339 
18340 	/*
18341 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18342 	 * from listener to acceptor. In case of non-STREAMS sockets,
18343 	 * we also need to pass the upper handle along.
18344 	 */
18345 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
18346 	tcpopt->to_flags = 0;
18347 
18348 	if (IPCL_IS_NONSTR(econnp)) {
18349 		ASSERT(sock_handle != NULL);
18350 		tcpopt->to_flags |= TCPOPT_UPPERHANDLE;
18351 		tcpopt->to_handle = sock_handle;
18352 	}
18353 	if (listener->tcp_bound_if != 0) {
18354 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
18355 		tcpopt->to_boundif = listener->tcp_bound_if;
18356 	}
18357 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18358 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
18359 	}
18360 
18361 	mutex_enter(&listener->tcp_eager_lock);
18362 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18363 
18364 		tcp_t *tail;
18365 		tcp_t *tcp;
18366 		mblk_t *mp1;
18367 
18368 		tcp = listener->tcp_eager_prev_q0;
18369 		/*
18370 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
18371 		 * deferred T_conn_ind queue. We need to get to the head
18372 		 * of the queue in order to send up T_conn_ind the same
18373 		 * order as how the 3WHS is completed.
18374 		 */
18375 		while (tcp != listener) {
18376 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18377 			    !tcp->tcp_kssl_pending)
18378 				break;
18379 			else
18380 				tcp = tcp->tcp_eager_prev_q0;
18381 		}
18382 		/* None of the pending eagers can be sent up now */
18383 		if (tcp == listener)
18384 			goto no_more_eagers;
18385 
18386 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18387 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18388 		/* Move from q0 to q */
18389 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18390 		listener->tcp_conn_req_cnt_q0--;
18391 		listener->tcp_conn_req_cnt_q++;
18392 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18393 		    tcp->tcp_eager_prev_q0;
18394 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18395 		    tcp->tcp_eager_next_q0;
18396 		tcp->tcp_eager_prev_q0 = NULL;
18397 		tcp->tcp_eager_next_q0 = NULL;
18398 		tcp->tcp_conn_def_q0 = B_FALSE;
18399 
18400 		/* Make sure the tcp isn't in the list of droppables */
18401 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18402 		    tcp->tcp_eager_prev_drop_q0 == NULL);
18403 
18404 		/*
18405 		 * Insert at end of the queue because sockfs sends
18406 		 * down T_CONN_RES in chronological order. Leaving
18407 		 * the older conn indications at front of the queue
18408 		 * helps reducing search time.
18409 		 */
18410 		tail = listener->tcp_eager_last_q;
18411 		if (tail != NULL) {
18412 			tail->tcp_eager_next_q = tcp;
18413 		} else {
18414 			listener->tcp_eager_next_q = tcp;
18415 		}
18416 		listener->tcp_eager_last_q = tcp;
18417 		tcp->tcp_eager_next_q = NULL;
18418 
18419 		/* Need to get inside the listener perimeter */
18420 		CONN_INC_REF(listener->tcp_connp);
18421 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
18422 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
18423 		    SQTAG_TCP_SEND_PENDING);
18424 	}
18425 no_more_eagers:
18426 	tcp_eager_unlink(eager);
18427 	mutex_exit(&listener->tcp_eager_lock);
18428 
18429 	/*
18430 	 * At this point, the eager is detached from the listener
18431 	 * but we still have an extra refs on eager (apart from the
18432 	 * usual tcp references). The ref was placed in tcp_rput_data
18433 	 * before sending the conn_ind in tcp_send_conn_ind.
18434 	 * The ref will be dropped in tcp_accept_finish().
18435 	 */
18436 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
18437 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
18438 	return (0);
18439 }
18440 
18441 int
18442 tcp_accept(sock_lower_handle_t lproto_handle,
18443     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
18444     cred_t *cr)
18445 {
18446 	conn_t *lconnp, *econnp;
18447 	tcp_t *listener, *eager;
18448 	tcp_stack_t	*tcps;
18449 
18450 	lconnp = (conn_t *)lproto_handle;
18451 	listener = lconnp->conn_tcp;
18452 	ASSERT(listener->tcp_state == TCPS_LISTEN);
18453 	econnp = (conn_t *)eproto_handle;
18454 	eager = econnp->conn_tcp;
18455 	ASSERT(eager->tcp_listener != NULL);
18456 	tcps = eager->tcp_tcps;
18457 
18458 	ASSERT(IPCL_IS_NONSTR(econnp));
18459 	/*
18460 	 * Create helper stream if it is a non-TPI TCP connection.
18461 	 */
18462 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
18463 		ip1dbg(("tcp_accept: create of IP helper stream"
18464 		    " failed\n"));
18465 		return (EPROTO);
18466 	}
18467 	eager->tcp_rq = econnp->conn_rq;
18468 	eager->tcp_wq = econnp->conn_wq;
18469 
18470 	ASSERT(eager->tcp_rq != NULL);
18471 
18472 	eager->tcp_sodirect = SOD_SOTOSODP(sock_handle);
18473 	return (tcp_accept_common(lconnp, econnp, sock_handle, cr));
18474 }
18475 
18476 
18477 /*
18478  * This is the STREAMS entry point for T_CONN_RES coming down on
18479  * Acceptor STREAM when  sockfs listener does accept processing.
18480  * Read the block comment on top of tcp_conn_request().
18481  */
18482 void
18483 tcp_tpi_accept(queue_t *q, mblk_t *mp)
18484 {
18485 	queue_t *rq = RD(q);
18486 	struct T_conn_res *conn_res;
18487 	tcp_t *eager;
18488 	tcp_t *listener;
18489 	struct T_ok_ack *ok;
18490 	t_scalar_t PRIM_type;
18491 	conn_t *econnp;
18492 
18493 	ASSERT(DB_TYPE(mp) == M_PROTO);
18494 
18495 	conn_res = (struct T_conn_res *)mp->b_rptr;
18496 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18497 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18498 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18499 		if (mp != NULL)
18500 			putnext(rq, mp);
18501 		return;
18502 	}
18503 	switch (conn_res->PRIM_type) {
18504 	case O_T_CONN_RES:
18505 	case T_CONN_RES:
18506 		/*
18507 		 * We pass up an err ack if allocb fails. This will
18508 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18509 		 * tcp_eager_blowoff to be called. sockfs will then call
18510 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18511 		 * we need to do the allocb up here because we have to
18512 		 * make sure rq->q_qinfo->qi_qclose still points to the
18513 		 * correct function (tcpclose_accept) in case allocb
18514 		 * fails.
18515 		 */
18516 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18517 		    &eager, conn_res->OPT_length);
18518 		PRIM_type = conn_res->PRIM_type;
18519 		mp->b_datap->db_type = M_PCPROTO;
18520 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18521 		ok = (struct T_ok_ack *)mp->b_rptr;
18522 		ok->PRIM_type = T_OK_ACK;
18523 		ok->CORRECT_prim = PRIM_type;
18524 		econnp = eager->tcp_connp;
18525 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
18526 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
18527 		eager->tcp_rq = rq;
18528 		eager->tcp_wq = q;
18529 		rq->q_ptr = econnp;
18530 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
18531 		q->q_ptr = econnp;
18532 		q->q_qinfo = &tcp_winit;
18533 		listener = eager->tcp_listener;
18534 
18535 		/*
18536 		 * TCP is _D_SODIRECT and sockfs is directly above so
18537 		 * save shared sodirect_t pointer (if any).
18538 		 */
18539 		eager->tcp_sodirect = SOD_QTOSODP(eager->tcp_rq);
18540 		if (tcp_accept_common(listener->tcp_connp,
18541 		    econnp, NULL, CRED()) < 0) {
18542 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18543 			if (mp != NULL)
18544 				putnext(rq, mp);
18545 			return;
18546 		}
18547 
18548 		/*
18549 		 * Send the new local address also up to sockfs. There
18550 		 * should already be enough space in the mp that came
18551 		 * down from soaccept().
18552 		 */
18553 		if (eager->tcp_family == AF_INET) {
18554 			sin_t *sin;
18555 
18556 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18557 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18558 			sin = (sin_t *)mp->b_wptr;
18559 			mp->b_wptr += sizeof (sin_t);
18560 			sin->sin_family = AF_INET;
18561 			sin->sin_port = eager->tcp_lport;
18562 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18563 		} else {
18564 			sin6_t *sin6;
18565 
18566 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18567 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18568 			sin6 = (sin6_t *)mp->b_wptr;
18569 			mp->b_wptr += sizeof (sin6_t);
18570 			sin6->sin6_family = AF_INET6;
18571 			sin6->sin6_port = eager->tcp_lport;
18572 			if (eager->tcp_ipversion == IPV4_VERSION) {
18573 				sin6->sin6_flowinfo = 0;
18574 				IN6_IPADDR_TO_V4MAPPED(
18575 				    eager->tcp_ipha->ipha_src,
18576 				    &sin6->sin6_addr);
18577 			} else {
18578 				ASSERT(eager->tcp_ip6h != NULL);
18579 				sin6->sin6_flowinfo =
18580 				    eager->tcp_ip6h->ip6_vcf &
18581 				    ~IPV6_VERS_AND_FLOW_MASK;
18582 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18583 			}
18584 			sin6->sin6_scope_id = 0;
18585 			sin6->__sin6_src_id = 0;
18586 		}
18587 
18588 		putnext(rq, mp);
18589 		return;
18590 	default:
18591 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18592 		if (mp != NULL)
18593 			putnext(rq, mp);
18594 		return;
18595 	}
18596 }
18597 
18598 static int
18599 tcp_getmyname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18600 {
18601 	sin_t *sin = (sin_t *)sa;
18602 	sin6_t *sin6 = (sin6_t *)sa;
18603 
18604 	switch (tcp->tcp_family) {
18605 	case AF_INET:
18606 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18607 
18608 		if (*salenp < sizeof (sin_t))
18609 			return (EINVAL);
18610 
18611 		*sin = sin_null;
18612 		sin->sin_family = AF_INET;
18613 		sin->sin_port = tcp->tcp_lport;
18614 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
18615 		break;
18616 
18617 	case AF_INET6:
18618 		if (*salenp < sizeof (sin6_t))
18619 			return (EINVAL);
18620 
18621 		*sin6 = sin6_null;
18622 		sin6->sin6_family = AF_INET6;
18623 		sin6->sin6_port = tcp->tcp_lport;
18624 		if (tcp->tcp_ipversion == IPV4_VERSION) {
18625 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
18626 			    &sin6->sin6_addr);
18627 		} else {
18628 			sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
18629 		}
18630 		break;
18631 	}
18632 
18633 	return (0);
18634 }
18635 
18636 static int
18637 i_tcp_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18638 {
18639 	sin_t *sin = (sin_t *)sa;
18640 	sin6_t *sin6 = (sin6_t *)sa;
18641 
18642 	if (tcp->tcp_state < TCPS_SYN_RCVD)
18643 		return (ENOTCONN);
18644 
18645 	switch (tcp->tcp_family) {
18646 	case AF_INET:
18647 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18648 
18649 		if (*salenp < sizeof (sin_t))
18650 			return (EINVAL);
18651 
18652 		*sin = sin_null;
18653 		sin->sin_family = AF_INET;
18654 		sin->sin_port = tcp->tcp_fport;
18655 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
18656 		    sin->sin_addr.s_addr);
18657 		*salenp = sizeof (sin_t);
18658 		break;
18659 
18660 	case AF_INET6:
18661 		if (*salenp < sizeof (sin6_t))
18662 			return (EINVAL);
18663 
18664 		*sin6 = sin6_null;
18665 		sin6->sin6_family = AF_INET6;
18666 		sin6->sin6_port = tcp->tcp_fport;
18667 		sin6->sin6_addr = tcp->tcp_remote_v6;
18668 		if (tcp->tcp_ipversion == IPV6_VERSION) {
18669 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
18670 			    ~IPV6_VERS_AND_FLOW_MASK;
18671 		}
18672 		*salenp = sizeof (sin6_t);
18673 		break;
18674 	}
18675 
18676 	return (0);
18677 }
18678 
18679 /*
18680  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
18681  */
18682 static void
18683 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
18684 {
18685 	void	*data;
18686 	mblk_t	*datamp = mp->b_cont;
18687 	tcp_t	*tcp = Q_TO_TCP(q);
18688 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
18689 
18690 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
18691 		cmdp->cb_error = EPROTO;
18692 		qreply(q, mp);
18693 		return;
18694 	}
18695 
18696 	data = datamp->b_rptr;
18697 
18698 	switch (cmdp->cb_cmd) {
18699 	case TI_GETPEERNAME:
18700 		cmdp->cb_error = i_tcp_getpeername(tcp, data, &cmdp->cb_len);
18701 		break;
18702 	case TI_GETMYNAME:
18703 		cmdp->cb_error = tcp_getmyname(tcp, data, &cmdp->cb_len);
18704 		break;
18705 	default:
18706 		cmdp->cb_error = EINVAL;
18707 		break;
18708 	}
18709 
18710 	qreply(q, mp);
18711 }
18712 
18713 void
18714 tcp_wput(queue_t *q, mblk_t *mp)
18715 {
18716 	conn_t	*connp = Q_TO_CONN(q);
18717 	tcp_t	*tcp;
18718 	void (*output_proc)();
18719 	t_scalar_t type;
18720 	uchar_t *rptr;
18721 	struct iocblk	*iocp;
18722 	size_t size;
18723 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18724 
18725 	ASSERT(connp->conn_ref >= 2);
18726 
18727 	switch (DB_TYPE(mp)) {
18728 	case M_DATA:
18729 		tcp = connp->conn_tcp;
18730 		ASSERT(tcp != NULL);
18731 
18732 		size = msgdsize(mp);
18733 
18734 		mutex_enter(&tcp->tcp_non_sq_lock);
18735 		tcp->tcp_squeue_bytes += size;
18736 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18737 			tcp_setqfull(tcp);
18738 		}
18739 		mutex_exit(&tcp->tcp_non_sq_lock);
18740 
18741 		CONN_INC_REF(connp);
18742 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18743 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18744 		return;
18745 
18746 	case M_CMD:
18747 		tcp_wput_cmdblk(q, mp);
18748 		return;
18749 
18750 	case M_PROTO:
18751 	case M_PCPROTO:
18752 		/*
18753 		 * if it is a snmp message, don't get behind the squeue
18754 		 */
18755 		tcp = connp->conn_tcp;
18756 		rptr = mp->b_rptr;
18757 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18758 			type = ((union T_primitives *)rptr)->type;
18759 		} else {
18760 			if (tcp->tcp_debug) {
18761 				(void) strlog(TCP_MOD_ID, 0, 1,
18762 				    SL_ERROR|SL_TRACE,
18763 				    "tcp_wput_proto, dropping one...");
18764 			}
18765 			freemsg(mp);
18766 			return;
18767 		}
18768 		if (type == T_SVR4_OPTMGMT_REQ) {
18769 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
18770 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18771 			    cr)) {
18772 				/*
18773 				 * This was a SNMP request
18774 				 */
18775 				return;
18776 			} else {
18777 				output_proc = tcp_wput_proto;
18778 			}
18779 		} else {
18780 			output_proc = tcp_wput_proto;
18781 		}
18782 		break;
18783 	case M_IOCTL:
18784 		/*
18785 		 * Most ioctls can be processed right away without going via
18786 		 * squeues - process them right here. Those that do require
18787 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18788 		 * are processed by tcp_wput_ioctl().
18789 		 */
18790 		iocp = (struct iocblk *)mp->b_rptr;
18791 		tcp = connp->conn_tcp;
18792 
18793 		switch (iocp->ioc_cmd) {
18794 		case TCP_IOC_ABORT_CONN:
18795 			tcp_ioctl_abort_conn(q, mp);
18796 			return;
18797 		case TI_GETPEERNAME:
18798 		case TI_GETMYNAME:
18799 			mi_copyin(q, mp, NULL,
18800 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18801 			return;
18802 		case ND_SET:
18803 			/* nd_getset does the necessary checks */
18804 		case ND_GET:
18805 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18806 				CALL_IP_WPUT(connp, q, mp);
18807 				return;
18808 			}
18809 			qreply(q, mp);
18810 			return;
18811 		case TCP_IOC_DEFAULT_Q:
18812 			/*
18813 			 * Wants to be the default wq. Check the credentials
18814 			 * first, the rest is executed via squeue.
18815 			 */
18816 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18817 				iocp->ioc_error = EPERM;
18818 				iocp->ioc_count = 0;
18819 				mp->b_datap->db_type = M_IOCACK;
18820 				qreply(q, mp);
18821 				return;
18822 			}
18823 			output_proc = tcp_wput_ioctl;
18824 			break;
18825 		default:
18826 			output_proc = tcp_wput_ioctl;
18827 			break;
18828 		}
18829 		break;
18830 	default:
18831 		output_proc = tcp_wput_nondata;
18832 		break;
18833 	}
18834 
18835 	CONN_INC_REF(connp);
18836 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18837 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18838 }
18839 
18840 /*
18841  * Initial STREAMS write side put() procedure for sockets. It tries to
18842  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18843  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18844  * are handled by tcp_wput() as usual.
18845  *
18846  * All further messages will also be handled by tcp_wput() because we cannot
18847  * be sure that the above short cut is safe later.
18848  */
18849 static void
18850 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18851 {
18852 	conn_t			*connp = Q_TO_CONN(wq);
18853 	tcp_t			*tcp = connp->conn_tcp;
18854 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18855 
18856 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18857 	wq->q_qinfo = &tcp_winit;
18858 
18859 	ASSERT(IPCL_IS_TCP(connp));
18860 	ASSERT(TCP_IS_SOCKET(tcp));
18861 
18862 	if (DB_TYPE(mp) == M_PCPROTO &&
18863 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18864 	    car->PRIM_type == T_CAPABILITY_REQ) {
18865 		tcp_capability_req(tcp, mp);
18866 		return;
18867 	}
18868 
18869 	tcp_wput(wq, mp);
18870 }
18871 
18872 /* ARGSUSED */
18873 static void
18874 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18875 {
18876 #ifdef DEBUG
18877 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18878 #endif
18879 	freemsg(mp);
18880 }
18881 
18882 static boolean_t
18883 tcp_zcopy_check(tcp_t *tcp)
18884 {
18885 	conn_t	*connp = tcp->tcp_connp;
18886 	ire_t	*ire;
18887 	boolean_t	zc_enabled = B_FALSE;
18888 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18889 
18890 	if (do_tcpzcopy == 2)
18891 		zc_enabled = B_TRUE;
18892 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18893 	    IPCL_IS_CONNECTED(connp) &&
18894 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18895 	    connp->conn_dontroute == 0 &&
18896 	    !connp->conn_nexthop_set &&
18897 	    connp->conn_outgoing_ill == NULL &&
18898 	    connp->conn_nofailover_ill == NULL &&
18899 	    do_tcpzcopy == 1) {
18900 		/*
18901 		 * the checks above  closely resemble the fast path checks
18902 		 * in tcp_send_data().
18903 		 */
18904 		mutex_enter(&connp->conn_lock);
18905 		ire = connp->conn_ire_cache;
18906 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18907 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18908 			IRE_REFHOLD(ire);
18909 			if (ire->ire_stq != NULL) {
18910 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18911 
18912 				zc_enabled = ill && (ill->ill_capabilities &
18913 				    ILL_CAPAB_ZEROCOPY) &&
18914 				    (ill->ill_zerocopy_capab->
18915 				    ill_zerocopy_flags != 0);
18916 			}
18917 			IRE_REFRELE(ire);
18918 		}
18919 		mutex_exit(&connp->conn_lock);
18920 	}
18921 	tcp->tcp_snd_zcopy_on = zc_enabled;
18922 	if (!TCP_IS_DETACHED(tcp)) {
18923 		if (zc_enabled) {
18924 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18925 			    ZCVMSAFE);
18926 			TCP_STAT(tcps, tcp_zcopy_on);
18927 		} else {
18928 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18929 			    ZCVMUNSAFE);
18930 			TCP_STAT(tcps, tcp_zcopy_off);
18931 		}
18932 	}
18933 	return (zc_enabled);
18934 }
18935 
18936 static mblk_t *
18937 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18938 {
18939 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18940 
18941 	if (do_tcpzcopy == 2)
18942 		return (bp);
18943 	else if (tcp->tcp_snd_zcopy_on) {
18944 		tcp->tcp_snd_zcopy_on = B_FALSE;
18945 		if (!TCP_IS_DETACHED(tcp)) {
18946 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
18947 			    ZCVMUNSAFE);
18948 			TCP_STAT(tcps, tcp_zcopy_disable);
18949 		}
18950 	}
18951 	return (tcp_zcopy_backoff(tcp, bp, 0));
18952 }
18953 
18954 /*
18955  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18956  * the original desballoca'ed segmapped mblk.
18957  */
18958 static mblk_t *
18959 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18960 {
18961 	mblk_t *head, *tail, *nbp;
18962 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18963 
18964 	if (IS_VMLOANED_MBLK(bp)) {
18965 		TCP_STAT(tcps, tcp_zcopy_backoff);
18966 		if ((head = copyb(bp)) == NULL) {
18967 			/* fail to backoff; leave it for the next backoff */
18968 			tcp->tcp_xmit_zc_clean = B_FALSE;
18969 			return (bp);
18970 		}
18971 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18972 			if (fix_xmitlist)
18973 				tcp_zcopy_notify(tcp);
18974 			else
18975 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18976 		}
18977 		nbp = bp->b_cont;
18978 		if (fix_xmitlist) {
18979 			head->b_prev = bp->b_prev;
18980 			head->b_next = bp->b_next;
18981 			if (tcp->tcp_xmit_tail == bp)
18982 				tcp->tcp_xmit_tail = head;
18983 		}
18984 		bp->b_next = NULL;
18985 		bp->b_prev = NULL;
18986 		freeb(bp);
18987 	} else {
18988 		head = bp;
18989 		nbp = bp->b_cont;
18990 	}
18991 	tail = head;
18992 	while (nbp) {
18993 		if (IS_VMLOANED_MBLK(nbp)) {
18994 			TCP_STAT(tcps, tcp_zcopy_backoff);
18995 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18996 				tcp->tcp_xmit_zc_clean = B_FALSE;
18997 				tail->b_cont = nbp;
18998 				return (head);
18999 			}
19000 			tail = tail->b_cont;
19001 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19002 				if (fix_xmitlist)
19003 					tcp_zcopy_notify(tcp);
19004 				else
19005 					tail->b_datap->db_struioflag |=
19006 					    STRUIO_ZCNOTIFY;
19007 			}
19008 			bp = nbp;
19009 			nbp = nbp->b_cont;
19010 			if (fix_xmitlist) {
19011 				tail->b_prev = bp->b_prev;
19012 				tail->b_next = bp->b_next;
19013 				if (tcp->tcp_xmit_tail == bp)
19014 					tcp->tcp_xmit_tail = tail;
19015 			}
19016 			bp->b_next = NULL;
19017 			bp->b_prev = NULL;
19018 			freeb(bp);
19019 		} else {
19020 			tail->b_cont = nbp;
19021 			tail = nbp;
19022 			nbp = nbp->b_cont;
19023 		}
19024 	}
19025 	if (fix_xmitlist) {
19026 		tcp->tcp_xmit_last = tail;
19027 		tcp->tcp_xmit_zc_clean = B_TRUE;
19028 	}
19029 	return (head);
19030 }
19031 
19032 static void
19033 tcp_zcopy_notify(tcp_t *tcp)
19034 {
19035 	struct stdata	*stp;
19036 	conn_t *connp;
19037 
19038 	if (tcp->tcp_detached)
19039 		return;
19040 	connp = tcp->tcp_connp;
19041 	if (IPCL_IS_NONSTR(connp)) {
19042 		(*connp->conn_upcalls->su_zcopy_notify)
19043 		    (connp->conn_upper_handle);
19044 		return;
19045 	}
19046 	stp = STREAM(tcp->tcp_rq);
19047 	mutex_enter(&stp->sd_lock);
19048 	stp->sd_flag |= STZCNOTIFY;
19049 	cv_broadcast(&stp->sd_zcopy_wait);
19050 	mutex_exit(&stp->sd_lock);
19051 }
19052 
19053 static boolean_t
19054 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
19055 {
19056 	ire_t	*ire;
19057 	conn_t	*connp = tcp->tcp_connp;
19058 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19059 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19060 
19061 	mutex_enter(&connp->conn_lock);
19062 	ire = connp->conn_ire_cache;
19063 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19064 
19065 	if ((ire != NULL) &&
19066 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
19067 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
19068 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19069 		IRE_REFHOLD(ire);
19070 		mutex_exit(&connp->conn_lock);
19071 	} else {
19072 		boolean_t cached = B_FALSE;
19073 		ts_label_t *tsl;
19074 
19075 		/* force a recheck later on */
19076 		tcp->tcp_ire_ill_check_done = B_FALSE;
19077 
19078 		TCP_DBGSTAT(tcps, tcp_ire_null1);
19079 		connp->conn_ire_cache = NULL;
19080 		mutex_exit(&connp->conn_lock);
19081 
19082 		if (ire != NULL)
19083 			IRE_REFRELE_NOTR(ire);
19084 
19085 		tsl = crgetlabel(CONN_CRED(connp));
19086 		ire = (dst ?
19087 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
19088 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19089 		    connp->conn_zoneid, tsl, ipst));
19090 
19091 		if (ire == NULL) {
19092 			TCP_STAT(tcps, tcp_ire_null);
19093 			return (B_FALSE);
19094 		}
19095 
19096 		IRE_REFHOLD_NOTR(ire);
19097 
19098 		mutex_enter(&connp->conn_lock);
19099 		if (CONN_CACHE_IRE(connp)) {
19100 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19101 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19102 				TCP_CHECK_IREINFO(tcp, ire);
19103 				connp->conn_ire_cache = ire;
19104 				cached = B_TRUE;
19105 			}
19106 			rw_exit(&ire->ire_bucket->irb_lock);
19107 		}
19108 		mutex_exit(&connp->conn_lock);
19109 
19110 		/*
19111 		 * We can continue to use the ire but since it was
19112 		 * not cached, we should drop the extra reference.
19113 		 */
19114 		if (!cached)
19115 			IRE_REFRELE_NOTR(ire);
19116 
19117 		/*
19118 		 * Rampart note: no need to select a new label here, since
19119 		 * labels are not allowed to change during the life of a TCP
19120 		 * connection.
19121 		 */
19122 	}
19123 
19124 	*irep = ire;
19125 
19126 	return (B_TRUE);
19127 }
19128 
19129 /*
19130  * Called from tcp_send() or tcp_send_data() to find workable IRE.
19131  *
19132  * 0 = success;
19133  * 1 = failed to find ire and ill.
19134  */
19135 static boolean_t
19136 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
19137 {
19138 	ipha_t		*ipha;
19139 	ipaddr_t	dst;
19140 	ire_t		*ire;
19141 	ill_t		*ill;
19142 	conn_t		*connp = tcp->tcp_connp;
19143 	mblk_t		*ire_fp_mp;
19144 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19145 
19146 	if (mp != NULL)
19147 		ipha = (ipha_t *)mp->b_rptr;
19148 	else
19149 		ipha = tcp->tcp_ipha;
19150 	dst = ipha->ipha_dst;
19151 
19152 	if (!tcp_send_find_ire(tcp, &dst, &ire))
19153 		return (B_FALSE);
19154 
19155 	if ((ire->ire_flags & RTF_MULTIRT) ||
19156 	    (ire->ire_stq == NULL) ||
19157 	    (ire->ire_nce == NULL) ||
19158 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
19159 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
19160 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
19161 		TCP_STAT(tcps, tcp_ip_ire_send);
19162 		IRE_REFRELE(ire);
19163 		return (B_FALSE);
19164 	}
19165 
19166 	ill = ire_to_ill(ire);
19167 	if (connp->conn_outgoing_ill != NULL) {
19168 		ill_t *conn_outgoing_ill = NULL;
19169 		/*
19170 		 * Choose a good ill in the group to send the packets on.
19171 		 */
19172 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
19173 		ill = ire_to_ill(ire);
19174 	}
19175 	ASSERT(ill != NULL);
19176 
19177 	if (!tcp->tcp_ire_ill_check_done) {
19178 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19179 		tcp->tcp_ire_ill_check_done = B_TRUE;
19180 	}
19181 
19182 	*irep = ire;
19183 	*illp = ill;
19184 
19185 	return (B_TRUE);
19186 }
19187 
19188 static void
19189 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
19190 {
19191 	ipha_t		*ipha;
19192 	ipaddr_t	src;
19193 	ipaddr_t	dst;
19194 	uint32_t	cksum;
19195 	ire_t		*ire;
19196 	uint16_t	*up;
19197 	ill_t		*ill;
19198 	conn_t		*connp = tcp->tcp_connp;
19199 	uint32_t	hcksum_txflags = 0;
19200 	mblk_t		*ire_fp_mp;
19201 	uint_t		ire_fp_mp_len;
19202 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19203 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19204 
19205 	ASSERT(DB_TYPE(mp) == M_DATA);
19206 
19207 	if (is_system_labeled() && DB_CRED(mp) == NULL)
19208 		mblk_setcred(mp, CONN_CRED(tcp->tcp_connp));
19209 
19210 	ipha = (ipha_t *)mp->b_rptr;
19211 	src = ipha->ipha_src;
19212 	dst = ipha->ipha_dst;
19213 
19214 	ASSERT(q != NULL);
19215 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
19216 
19217 	/*
19218 	 * Drop off fast path for IPv6 and also if options are present or
19219 	 * we need to resolve a TS label.
19220 	 */
19221 	if (tcp->tcp_ipversion != IPV4_VERSION ||
19222 	    !IPCL_IS_CONNECTED(connp) ||
19223 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
19224 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
19225 	    !connp->conn_ulp_labeled ||
19226 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
19227 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
19228 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
19229 		if (tcp->tcp_snd_zcopy_aware)
19230 			mp = tcp_zcopy_disable(tcp, mp);
19231 		TCP_STAT(tcps, tcp_ip_send);
19232 		CALL_IP_WPUT(connp, q, mp);
19233 		return;
19234 	}
19235 
19236 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
19237 		if (tcp->tcp_snd_zcopy_aware)
19238 			mp = tcp_zcopy_backoff(tcp, mp, 0);
19239 		CALL_IP_WPUT(connp, q, mp);
19240 		return;
19241 	}
19242 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
19243 	ire_fp_mp_len = MBLKL(ire_fp_mp);
19244 
19245 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19246 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19247 #ifndef _BIG_ENDIAN
19248 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19249 #endif
19250 
19251 	/*
19252 	 * Check to see if we need to re-enable LSO/MDT for this connection
19253 	 * because it was previously disabled due to changes in the ill;
19254 	 * note that by doing it here, this re-enabling only applies when
19255 	 * the packet is not dispatched through CALL_IP_WPUT().
19256 	 *
19257 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
19258 	 * case, since that's how we ended up here.  For IPv6, we do the
19259 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
19260 	 */
19261 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
19262 		/*
19263 		 * Restore LSO for this connection, so that next time around
19264 		 * it is eligible to go through tcp_lsosend() path again.
19265 		 */
19266 		TCP_STAT(tcps, tcp_lso_enabled);
19267 		tcp->tcp_lso = B_TRUE;
19268 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
19269 		    "interface %s\n", (void *)connp, ill->ill_name));
19270 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
19271 		/*
19272 		 * Restore MDT for this connection, so that next time around
19273 		 * it is eligible to go through tcp_multisend() path again.
19274 		 */
19275 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
19276 		tcp->tcp_mdt = B_TRUE;
19277 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
19278 		    "interface %s\n", (void *)connp, ill->ill_name));
19279 	}
19280 
19281 	if (tcp->tcp_snd_zcopy_aware) {
19282 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
19283 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
19284 			mp = tcp_zcopy_disable(tcp, mp);
19285 		/*
19286 		 * we shouldn't need to reset ipha as the mp containing
19287 		 * ipha should never be a zero-copy mp.
19288 		 */
19289 	}
19290 
19291 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
19292 		ASSERT(ill->ill_hcksum_capab != NULL);
19293 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
19294 	}
19295 
19296 	/* pseudo-header checksum (do it in parts for IP header checksum) */
19297 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19298 
19299 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
19300 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
19301 
19302 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
19303 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
19304 
19305 	/* Software checksum? */
19306 	if (DB_CKSUMFLAGS(mp) == 0) {
19307 		TCP_STAT(tcps, tcp_out_sw_cksum);
19308 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
19309 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
19310 	}
19311 
19312 	/* Calculate IP header checksum if hardware isn't capable */
19313 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
19314 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
19315 		    ((uint16_t *)ipha)[4]);
19316 	}
19317 
19318 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
19319 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
19320 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
19321 
19322 	UPDATE_OB_PKT_COUNT(ire);
19323 	ire->ire_last_used_time = lbolt;
19324 
19325 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
19326 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
19327 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
19328 	    ntohs(ipha->ipha_length));
19329 
19330 	DTRACE_PROBE4(ip4__physical__out__start,
19331 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
19332 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
19333 	    ipst->ips_ipv4firewall_physical_out,
19334 	    NULL, ill, ipha, mp, mp, 0, ipst);
19335 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19336 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
19337 
19338 	if (mp != NULL) {
19339 		if (ipst->ips_ipobs_enabled) {
19340 			zoneid_t szone;
19341 
19342 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
19343 			    ipst, ALL_ZONES);
19344 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
19345 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
19346 		}
19347 
19348 		ILL_SEND_TX(ill, ire, connp, mp, 0);
19349 	}
19350 
19351 	IRE_REFRELE(ire);
19352 }
19353 
19354 /*
19355  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19356  * if the receiver shrinks the window, i.e. moves the right window to the
19357  * left, the we should not send new data, but should retransmit normally the
19358  * old unacked data between suna and suna + swnd. We might has sent data
19359  * that is now outside the new window, pretend that we didn't send  it.
19360  */
19361 static void
19362 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19363 {
19364 	uint32_t	snxt = tcp->tcp_snxt;
19365 	mblk_t		*xmit_tail;
19366 	int32_t		offset;
19367 
19368 	ASSERT(shrunk_count > 0);
19369 
19370 	/* Pretend we didn't send the data outside the window */
19371 	snxt -= shrunk_count;
19372 
19373 	/* Get the mblk and the offset in it per the shrunk window */
19374 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19375 
19376 	ASSERT(xmit_tail != NULL);
19377 
19378 	/* Reset all the values per the now shrunk window */
19379 	tcp->tcp_snxt = snxt;
19380 	tcp->tcp_xmit_tail = xmit_tail;
19381 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19382 	    offset;
19383 	tcp->tcp_unsent += shrunk_count;
19384 
19385 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19386 		/*
19387 		 * Make sure the timer is running so that we will probe a zero
19388 		 * window.
19389 		 */
19390 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19391 }
19392 
19393 
19394 /*
19395  * The TCP normal data output path.
19396  * NOTE: the logic of the fast path is duplicated from this function.
19397  */
19398 static void
19399 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19400 {
19401 	int		len;
19402 	mblk_t		*local_time;
19403 	mblk_t		*mp1;
19404 	uint32_t	snxt;
19405 	int		tail_unsent;
19406 	int		tcpstate;
19407 	int		usable = 0;
19408 	mblk_t		*xmit_tail;
19409 	queue_t		*q = tcp->tcp_wq;
19410 	int32_t		mss;
19411 	int32_t		num_sack_blk = 0;
19412 	int32_t		tcp_hdr_len;
19413 	int32_t		tcp_tcp_hdr_len;
19414 	int		mdt_thres;
19415 	int		rc;
19416 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19417 	ip_stack_t	*ipst;
19418 
19419 	tcpstate = tcp->tcp_state;
19420 	if (mp == NULL) {
19421 		/*
19422 		 * tcp_wput_data() with NULL mp should only be called when
19423 		 * there is unsent data.
19424 		 */
19425 		ASSERT(tcp->tcp_unsent > 0);
19426 		/* Really tacky... but we need this for detached closes. */
19427 		len = tcp->tcp_unsent;
19428 		goto data_null;
19429 	}
19430 
19431 #if CCS_STATS
19432 	wrw_stats.tot.count++;
19433 	wrw_stats.tot.bytes += msgdsize(mp);
19434 #endif
19435 	ASSERT(mp->b_datap->db_type == M_DATA);
19436 	/*
19437 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19438 	 * or before a connection attempt has begun.
19439 	 */
19440 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19441 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19442 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19443 #ifdef DEBUG
19444 			cmn_err(CE_WARN,
19445 			    "tcp_wput_data: data after ordrel, %s",
19446 			    tcp_display(tcp, NULL,
19447 			    DISP_ADDR_AND_PORT));
19448 #else
19449 			if (tcp->tcp_debug) {
19450 				(void) strlog(TCP_MOD_ID, 0, 1,
19451 				    SL_TRACE|SL_ERROR,
19452 				    "tcp_wput_data: data after ordrel, %s\n",
19453 				    tcp_display(tcp, NULL,
19454 				    DISP_ADDR_AND_PORT));
19455 			}
19456 #endif /* DEBUG */
19457 		}
19458 		if (tcp->tcp_snd_zcopy_aware &&
19459 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19460 			tcp_zcopy_notify(tcp);
19461 		freemsg(mp);
19462 		mutex_enter(&tcp->tcp_non_sq_lock);
19463 		if (tcp->tcp_flow_stopped &&
19464 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19465 			tcp_clrqfull(tcp);
19466 		}
19467 		mutex_exit(&tcp->tcp_non_sq_lock);
19468 		return;
19469 	}
19470 
19471 	/* Strip empties */
19472 	for (;;) {
19473 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19474 		    (uintptr_t)INT_MAX);
19475 		len = (int)(mp->b_wptr - mp->b_rptr);
19476 		if (len > 0)
19477 			break;
19478 		mp1 = mp;
19479 		mp = mp->b_cont;
19480 		freeb(mp1);
19481 		if (!mp) {
19482 			return;
19483 		}
19484 	}
19485 
19486 	/* If we are the first on the list ... */
19487 	if (tcp->tcp_xmit_head == NULL) {
19488 		tcp->tcp_xmit_head = mp;
19489 		tcp->tcp_xmit_tail = mp;
19490 		tcp->tcp_xmit_tail_unsent = len;
19491 	} else {
19492 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19493 		struct datab *dp;
19494 
19495 		mp1 = tcp->tcp_xmit_last;
19496 		if (len < tcp_tx_pull_len &&
19497 		    (dp = mp1->b_datap)->db_ref == 1 &&
19498 		    dp->db_lim - mp1->b_wptr >= len) {
19499 			ASSERT(len > 0);
19500 			ASSERT(!mp1->b_cont);
19501 			if (len == 1) {
19502 				*mp1->b_wptr++ = *mp->b_rptr;
19503 			} else {
19504 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19505 				mp1->b_wptr += len;
19506 			}
19507 			if (mp1 == tcp->tcp_xmit_tail)
19508 				tcp->tcp_xmit_tail_unsent += len;
19509 			mp1->b_cont = mp->b_cont;
19510 			if (tcp->tcp_snd_zcopy_aware &&
19511 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19512 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19513 			freeb(mp);
19514 			mp = mp1;
19515 		} else {
19516 			tcp->tcp_xmit_last->b_cont = mp;
19517 		}
19518 		len += tcp->tcp_unsent;
19519 	}
19520 
19521 	/* Tack on however many more positive length mblks we have */
19522 	if ((mp1 = mp->b_cont) != NULL) {
19523 		do {
19524 			int tlen;
19525 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19526 			    (uintptr_t)INT_MAX);
19527 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19528 			if (tlen <= 0) {
19529 				mp->b_cont = mp1->b_cont;
19530 				freeb(mp1);
19531 			} else {
19532 				len += tlen;
19533 				mp = mp1;
19534 			}
19535 		} while ((mp1 = mp->b_cont) != NULL);
19536 	}
19537 	tcp->tcp_xmit_last = mp;
19538 	tcp->tcp_unsent = len;
19539 
19540 	if (urgent)
19541 		usable = 1;
19542 
19543 data_null:
19544 	snxt = tcp->tcp_snxt;
19545 	xmit_tail = tcp->tcp_xmit_tail;
19546 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19547 
19548 	/*
19549 	 * Note that tcp_mss has been adjusted to take into account the
19550 	 * timestamp option if applicable.  Because SACK options do not
19551 	 * appear in every TCP segments and they are of variable lengths,
19552 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19553 	 * the actual segment length when we need to send a segment which
19554 	 * includes SACK options.
19555 	 */
19556 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19557 		int32_t	opt_len;
19558 
19559 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19560 		    tcp->tcp_num_sack_blk);
19561 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19562 		    2 + TCPOPT_HEADER_LEN;
19563 		mss = tcp->tcp_mss - opt_len;
19564 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19565 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19566 	} else {
19567 		mss = tcp->tcp_mss;
19568 		tcp_hdr_len = tcp->tcp_hdr_len;
19569 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19570 	}
19571 
19572 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19573 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19574 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19575 	}
19576 	if (tcpstate == TCPS_SYN_RCVD) {
19577 		/*
19578 		 * The three-way connection establishment handshake is not
19579 		 * complete yet. We want to queue the data for transmission
19580 		 * after entering ESTABLISHED state (RFC793). A jump to
19581 		 * "done" label effectively leaves data on the queue.
19582 		 */
19583 		goto done;
19584 	} else {
19585 		int usable_r;
19586 
19587 		/*
19588 		 * In the special case when cwnd is zero, which can only
19589 		 * happen if the connection is ECN capable, return now.
19590 		 * New segments is sent using tcp_timer().  The timer
19591 		 * is set in tcp_rput_data().
19592 		 */
19593 		if (tcp->tcp_cwnd == 0) {
19594 			/*
19595 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19596 			 * finished.
19597 			 */
19598 			ASSERT(tcp->tcp_ecn_ok ||
19599 			    tcp->tcp_state < TCPS_ESTABLISHED);
19600 			return;
19601 		}
19602 
19603 		/* NOTE: trouble if xmitting while SYN not acked? */
19604 		usable_r = snxt - tcp->tcp_suna;
19605 		usable_r = tcp->tcp_swnd - usable_r;
19606 
19607 		/*
19608 		 * Check if the receiver has shrunk the window.  If
19609 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19610 		 * cannot be set as there is unsent data, so FIN cannot
19611 		 * be sent out.  Otherwise, we need to take into account
19612 		 * of FIN as it consumes an "invisible" sequence number.
19613 		 */
19614 		ASSERT(tcp->tcp_fin_sent == 0);
19615 		if (usable_r < 0) {
19616 			/*
19617 			 * The receiver has shrunk the window and we have sent
19618 			 * -usable_r date beyond the window, re-adjust.
19619 			 *
19620 			 * If TCP window scaling is enabled, there can be
19621 			 * round down error as the advertised receive window
19622 			 * is actually right shifted n bits.  This means that
19623 			 * the lower n bits info is wiped out.  It will look
19624 			 * like the window is shrunk.  Do a check here to
19625 			 * see if the shrunk amount is actually within the
19626 			 * error in window calculation.  If it is, just
19627 			 * return.  Note that this check is inside the
19628 			 * shrunk window check.  This makes sure that even
19629 			 * though tcp_process_shrunk_swnd() is not called,
19630 			 * we will stop further processing.
19631 			 */
19632 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19633 				tcp_process_shrunk_swnd(tcp, -usable_r);
19634 			}
19635 			return;
19636 		}
19637 
19638 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19639 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19640 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19641 
19642 		/* usable = MIN(usable, unsent) */
19643 		if (usable_r > len)
19644 			usable_r = len;
19645 
19646 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19647 		if (usable_r > 0) {
19648 			usable = usable_r;
19649 		} else {
19650 			/* Bypass all other unnecessary processing. */
19651 			goto done;
19652 		}
19653 	}
19654 
19655 	local_time = (mblk_t *)lbolt;
19656 
19657 	/*
19658 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19659 	 * BSD.  This is more in line with the true intent of Nagle.
19660 	 *
19661 	 * The conditions are:
19662 	 * 1. The amount of unsent data (or amount of data which can be
19663 	 *    sent, whichever is smaller) is less than Nagle limit.
19664 	 * 2. The last sent size is also less than Nagle limit.
19665 	 * 3. There is unack'ed data.
19666 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19667 	 *    Nagle algorithm.  This reduces the probability that urgent
19668 	 *    bytes get "merged" together.
19669 	 * 5. The app has not closed the connection.  This eliminates the
19670 	 *    wait time of the receiving side waiting for the last piece of
19671 	 *    (small) data.
19672 	 *
19673 	 * If all are satisified, exit without sending anything.  Note
19674 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19675 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19676 	 * 4095).
19677 	 */
19678 	if (usable < (int)tcp->tcp_naglim &&
19679 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19680 	    snxt != tcp->tcp_suna &&
19681 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19682 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19683 		goto done;
19684 	}
19685 
19686 	if (tcp->tcp_cork) {
19687 		/*
19688 		 * if the tcp->tcp_cork option is set, then we have to force
19689 		 * TCP not to send partial segment (smaller than MSS bytes).
19690 		 * We are calculating the usable now based on full mss and
19691 		 * will save the rest of remaining data for later.
19692 		 */
19693 		if (usable < mss)
19694 			goto done;
19695 		usable = (usable / mss) * mss;
19696 	}
19697 
19698 	/* Update the latest receive window size in TCP header. */
19699 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19700 	    tcp->tcp_tcph->th_win);
19701 
19702 	/*
19703 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19704 	 *
19705 	 * 1. Simple TCP/IP{v4,v6} (no options).
19706 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19707 	 * 3. If the TCP connection is in ESTABLISHED state.
19708 	 * 4. The TCP is not detached.
19709 	 *
19710 	 * If any of the above conditions have changed during the
19711 	 * connection, stop using LSO/MDT and restore the stream head
19712 	 * parameters accordingly.
19713 	 */
19714 	ipst = tcps->tcps_netstack->netstack_ip;
19715 
19716 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19717 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19718 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19719 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19720 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19721 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19722 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19723 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19724 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19725 		if (tcp->tcp_lso) {
19726 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19727 			tcp->tcp_lso = B_FALSE;
19728 		} else {
19729 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19730 			tcp->tcp_mdt = B_FALSE;
19731 		}
19732 
19733 		/* Anything other than detached is considered pathological */
19734 		if (!TCP_IS_DETACHED(tcp)) {
19735 			if (tcp->tcp_lso)
19736 				TCP_STAT(tcps, tcp_lso_disabled);
19737 			else
19738 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19739 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19740 		}
19741 	}
19742 
19743 	/* Use MDT if sendable amount is greater than the threshold */
19744 	if (tcp->tcp_mdt &&
19745 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19746 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19747 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19748 	    (tcp->tcp_valid_bits == 0 ||
19749 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19750 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19751 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19752 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19753 		    local_time, mdt_thres);
19754 	} else {
19755 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19756 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19757 		    local_time, INT_MAX);
19758 	}
19759 
19760 	/* Pretend that all we were trying to send really got sent */
19761 	if (rc < 0 && tail_unsent < 0) {
19762 		do {
19763 			xmit_tail = xmit_tail->b_cont;
19764 			xmit_tail->b_prev = local_time;
19765 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19766 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19767 			tail_unsent += (int)(xmit_tail->b_wptr -
19768 			    xmit_tail->b_rptr);
19769 		} while (tail_unsent < 0);
19770 	}
19771 done:;
19772 	tcp->tcp_xmit_tail = xmit_tail;
19773 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19774 	len = tcp->tcp_snxt - snxt;
19775 	if (len) {
19776 		/*
19777 		 * If new data was sent, need to update the notsack
19778 		 * list, which is, afterall, data blocks that have
19779 		 * not been sack'ed by the receiver.  New data is
19780 		 * not sack'ed.
19781 		 */
19782 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19783 			/* len is a negative value. */
19784 			tcp->tcp_pipe -= len;
19785 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19786 			    tcp->tcp_snxt, snxt,
19787 			    &(tcp->tcp_num_notsack_blk),
19788 			    &(tcp->tcp_cnt_notsack_list));
19789 		}
19790 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19791 		tcp->tcp_rack = tcp->tcp_rnxt;
19792 		tcp->tcp_rack_cnt = 0;
19793 		if ((snxt + len) == tcp->tcp_suna) {
19794 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19795 		}
19796 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19797 		/*
19798 		 * Didn't send anything. Make sure the timer is running
19799 		 * so that we will probe a zero window.
19800 		 */
19801 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19802 	}
19803 	/* Note that len is the amount we just sent but with a negative sign */
19804 	tcp->tcp_unsent += len;
19805 	mutex_enter(&tcp->tcp_non_sq_lock);
19806 	if (tcp->tcp_flow_stopped) {
19807 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19808 			tcp_clrqfull(tcp);
19809 		}
19810 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19811 		tcp_setqfull(tcp);
19812 	}
19813 	mutex_exit(&tcp->tcp_non_sq_lock);
19814 }
19815 
19816 /*
19817  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19818  * outgoing TCP header with the template header, as well as other
19819  * options such as time-stamp, ECN and/or SACK.
19820  */
19821 static void
19822 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19823 {
19824 	tcph_t *tcp_tmpl, *tcp_h;
19825 	uint32_t *dst, *src;
19826 	int hdrlen;
19827 
19828 	ASSERT(OK_32PTR(rptr));
19829 
19830 	/* Template header */
19831 	tcp_tmpl = tcp->tcp_tcph;
19832 
19833 	/* Header of outgoing packet */
19834 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19835 
19836 	/* dst and src are opaque 32-bit fields, used for copying */
19837 	dst = (uint32_t *)rptr;
19838 	src = (uint32_t *)tcp->tcp_iphc;
19839 	hdrlen = tcp->tcp_hdr_len;
19840 
19841 	/* Fill time-stamp option if needed */
19842 	if (tcp->tcp_snd_ts_ok) {
19843 		U32_TO_BE32((uint32_t)now,
19844 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19845 		U32_TO_BE32(tcp->tcp_ts_recent,
19846 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19847 	} else {
19848 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19849 	}
19850 
19851 	/*
19852 	 * Copy the template header; is this really more efficient than
19853 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19854 	 * but perhaps not for other scenarios.
19855 	 */
19856 	dst[0] = src[0];
19857 	dst[1] = src[1];
19858 	dst[2] = src[2];
19859 	dst[3] = src[3];
19860 	dst[4] = src[4];
19861 	dst[5] = src[5];
19862 	dst[6] = src[6];
19863 	dst[7] = src[7];
19864 	dst[8] = src[8];
19865 	dst[9] = src[9];
19866 	if (hdrlen -= 40) {
19867 		hdrlen >>= 2;
19868 		dst += 10;
19869 		src += 10;
19870 		do {
19871 			*dst++ = *src++;
19872 		} while (--hdrlen);
19873 	}
19874 
19875 	/*
19876 	 * Set the ECN info in the TCP header if it is not a zero
19877 	 * window probe.  Zero window probe is only sent in
19878 	 * tcp_wput_data() and tcp_timer().
19879 	 */
19880 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19881 		SET_ECT(tcp, rptr);
19882 
19883 		if (tcp->tcp_ecn_echo_on)
19884 			tcp_h->th_flags[0] |= TH_ECE;
19885 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19886 			tcp_h->th_flags[0] |= TH_CWR;
19887 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19888 		}
19889 	}
19890 
19891 	/* Fill in SACK options */
19892 	if (num_sack_blk > 0) {
19893 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19894 		sack_blk_t *tmp;
19895 		int32_t	i;
19896 
19897 		wptr[0] = TCPOPT_NOP;
19898 		wptr[1] = TCPOPT_NOP;
19899 		wptr[2] = TCPOPT_SACK;
19900 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19901 		    sizeof (sack_blk_t);
19902 		wptr += TCPOPT_REAL_SACK_LEN;
19903 
19904 		tmp = tcp->tcp_sack_list;
19905 		for (i = 0; i < num_sack_blk; i++) {
19906 			U32_TO_BE32(tmp[i].begin, wptr);
19907 			wptr += sizeof (tcp_seq);
19908 			U32_TO_BE32(tmp[i].end, wptr);
19909 			wptr += sizeof (tcp_seq);
19910 		}
19911 		tcp_h->th_offset_and_rsrvd[0] +=
19912 		    ((num_sack_blk * 2 + 1) << 4);
19913 	}
19914 }
19915 
19916 /*
19917  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19918  * the destination address and SAP attribute, and if necessary, the
19919  * hardware checksum offload attribute to a Multidata message.
19920  */
19921 static int
19922 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19923     const uint32_t start, const uint32_t stuff, const uint32_t end,
19924     const uint32_t flags, tcp_stack_t *tcps)
19925 {
19926 	/* Add global destination address & SAP attribute */
19927 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19928 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19929 		    "destination address+SAP\n"));
19930 
19931 		if (dlmp != NULL)
19932 			TCP_STAT(tcps, tcp_mdt_allocfail);
19933 		return (-1);
19934 	}
19935 
19936 	/* Add global hwcksum attribute */
19937 	if (hwcksum &&
19938 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19939 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19940 		    "checksum attribute\n"));
19941 
19942 		TCP_STAT(tcps, tcp_mdt_allocfail);
19943 		return (-1);
19944 	}
19945 
19946 	return (0);
19947 }
19948 
19949 /*
19950  * Smaller and private version of pdescinfo_t used specifically for TCP,
19951  * which allows for only two payload spans per packet.
19952  */
19953 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19954 
19955 /*
19956  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19957  * scheme, and returns one the following:
19958  *
19959  * -1 = failed allocation.
19960  *  0 = success; burst count reached, or usable send window is too small,
19961  *      and that we'd rather wait until later before sending again.
19962  */
19963 static int
19964 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19965     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19966     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19967     const int mdt_thres)
19968 {
19969 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19970 	multidata_t	*mmd;
19971 	uint_t		obsegs, obbytes, hdr_frag_sz;
19972 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19973 	int		num_burst_seg, max_pld;
19974 	pdesc_t		*pkt;
19975 	tcp_pdescinfo_t	tcp_pkt_info;
19976 	pdescinfo_t	*pkt_info;
19977 	int		pbuf_idx, pbuf_idx_nxt;
19978 	int		seg_len, len, spill, af;
19979 	boolean_t	add_buffer, zcopy, clusterwide;
19980 	boolean_t	rconfirm = B_FALSE;
19981 	boolean_t	done = B_FALSE;
19982 	uint32_t	cksum;
19983 	uint32_t	hwcksum_flags;
19984 	ire_t		*ire = NULL;
19985 	ill_t		*ill;
19986 	ipha_t		*ipha;
19987 	ip6_t		*ip6h;
19988 	ipaddr_t	src, dst;
19989 	ill_zerocopy_capab_t *zc_cap = NULL;
19990 	uint16_t	*up;
19991 	int		err;
19992 	conn_t		*connp;
19993 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19994 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19995 	int		usable_mmd, tail_unsent_mmd;
19996 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
19997 	mblk_t		*xmit_tail_mmd;
19998 	netstackid_t	stack_id;
19999 
20000 #ifdef	_BIG_ENDIAN
20001 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
20002 #else
20003 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
20004 #endif
20005 
20006 #define	PREP_NEW_MULTIDATA() {			\
20007 	mmd = NULL;				\
20008 	md_mp = md_hbuf = NULL;			\
20009 	cur_hdr_off = 0;			\
20010 	max_pld = tcp->tcp_mdt_max_pld;		\
20011 	pbuf_idx = pbuf_idx_nxt = -1;		\
20012 	add_buffer = B_TRUE;			\
20013 	zcopy = B_FALSE;			\
20014 }
20015 
20016 #define	PREP_NEW_PBUF() {			\
20017 	md_pbuf = md_pbuf_nxt = NULL;		\
20018 	pbuf_idx = pbuf_idx_nxt = -1;		\
20019 	cur_pld_off = 0;			\
20020 	first_snxt = *snxt;			\
20021 	ASSERT(*tail_unsent > 0);		\
20022 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
20023 }
20024 
20025 	ASSERT(mdt_thres >= mss);
20026 	ASSERT(*usable > 0 && *usable > mdt_thres);
20027 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20028 	ASSERT(!TCP_IS_DETACHED(tcp));
20029 	ASSERT(tcp->tcp_valid_bits == 0 ||
20030 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
20031 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
20032 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
20033 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20034 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
20035 
20036 	connp = tcp->tcp_connp;
20037 	ASSERT(connp != NULL);
20038 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
20039 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
20040 
20041 	stack_id = connp->conn_netstack->netstack_stackid;
20042 
20043 	usable_mmd = tail_unsent_mmd = 0;
20044 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
20045 	xmit_tail_mmd = NULL;
20046 	/*
20047 	 * Note that tcp will only declare at most 2 payload spans per
20048 	 * packet, which is much lower than the maximum allowable number
20049 	 * of packet spans per Multidata.  For this reason, we use the
20050 	 * privately declared and smaller descriptor info structure, in
20051 	 * order to save some stack space.
20052 	 */
20053 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
20054 
20055 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
20056 	if (af == AF_INET) {
20057 		dst = tcp->tcp_ipha->ipha_dst;
20058 		src = tcp->tcp_ipha->ipha_src;
20059 		ASSERT(!CLASSD(dst));
20060 	}
20061 	ASSERT(af == AF_INET ||
20062 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
20063 
20064 	obsegs = obbytes = 0;
20065 	num_burst_seg = tcp->tcp_snd_burst;
20066 	md_mp_head = NULL;
20067 	PREP_NEW_MULTIDATA();
20068 
20069 	/*
20070 	 * Before we go on further, make sure there is an IRE that we can
20071 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
20072 	 * in proceeding any further, and we should just hand everything
20073 	 * off to the legacy path.
20074 	 */
20075 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
20076 		goto legacy_send_no_md;
20077 
20078 	ASSERT(ire != NULL);
20079 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
20080 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
20081 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
20082 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
20083 	/*
20084 	 * If we do support loopback for MDT (which requires modifications
20085 	 * to the receiving paths), the following assertions should go away,
20086 	 * and we would be sending the Multidata to loopback conn later on.
20087 	 */
20088 	ASSERT(!IRE_IS_LOCAL(ire));
20089 	ASSERT(ire->ire_stq != NULL);
20090 
20091 	ill = ire_to_ill(ire);
20092 	ASSERT(ill != NULL);
20093 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
20094 
20095 	if (!tcp->tcp_ire_ill_check_done) {
20096 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
20097 		tcp->tcp_ire_ill_check_done = B_TRUE;
20098 	}
20099 
20100 	/*
20101 	 * If the underlying interface conditions have changed, or if the
20102 	 * new interface does not support MDT, go back to legacy path.
20103 	 */
20104 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
20105 		/* don't go through this path anymore for this connection */
20106 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
20107 		tcp->tcp_mdt = B_FALSE;
20108 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
20109 		    "interface %s\n", (void *)connp, ill->ill_name));
20110 		/* IRE will be released prior to returning */
20111 		goto legacy_send_no_md;
20112 	}
20113 
20114 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
20115 		zc_cap = ill->ill_zerocopy_capab;
20116 
20117 	/*
20118 	 * Check if we can take tcp fast-path. Note that "incomplete"
20119 	 * ire's (where the link-layer for next hop is not resolved
20120 	 * or where the fast-path header in nce_fp_mp is not available
20121 	 * yet) are sent down the legacy (slow) path.
20122 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
20123 	 */
20124 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
20125 		/* IRE will be released prior to returning */
20126 		goto legacy_send_no_md;
20127 	}
20128 
20129 	/* go to legacy path if interface doesn't support zerocopy */
20130 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
20131 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
20132 		/* IRE will be released prior to returning */
20133 		goto legacy_send_no_md;
20134 	}
20135 
20136 	/* does the interface support hardware checksum offload? */
20137 	hwcksum_flags = 0;
20138 	if (ILL_HCKSUM_CAPABLE(ill) &&
20139 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
20140 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
20141 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
20142 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20143 		    HCKSUM_IPHDRCKSUM)
20144 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
20145 
20146 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20147 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
20148 			hwcksum_flags |= HCK_FULLCKSUM;
20149 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20150 		    HCKSUM_INET_PARTIAL)
20151 			hwcksum_flags |= HCK_PARTIALCKSUM;
20152 	}
20153 
20154 	/*
20155 	 * Each header fragment consists of the leading extra space,
20156 	 * followed by the TCP/IP header, and the trailing extra space.
20157 	 * We make sure that each header fragment begins on a 32-bit
20158 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
20159 	 * aligned in tcp_mdt_update).
20160 	 */
20161 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
20162 	    tcp->tcp_mdt_hdr_tail), 4);
20163 
20164 	/* are we starting from the beginning of data block? */
20165 	if (*tail_unsent == 0) {
20166 		*xmit_tail = (*xmit_tail)->b_cont;
20167 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
20168 		*tail_unsent = (int)MBLKL(*xmit_tail);
20169 	}
20170 
20171 	/*
20172 	 * Here we create one or more Multidata messages, each made up of
20173 	 * one header buffer and up to N payload buffers.  This entire
20174 	 * operation is done within two loops:
20175 	 *
20176 	 * The outer loop mostly deals with creating the Multidata message,
20177 	 * as well as the header buffer that gets added to it.  It also
20178 	 * links the Multidata messages together such that all of them can
20179 	 * be sent down to the lower layer in a single putnext call; this
20180 	 * linking behavior depends on the tcp_mdt_chain tunable.
20181 	 *
20182 	 * The inner loop takes an existing Multidata message, and adds
20183 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
20184 	 * packetizes those buffers by filling up the corresponding header
20185 	 * buffer fragments with the proper IP and TCP headers, and by
20186 	 * describing the layout of each packet in the packet descriptors
20187 	 * that get added to the Multidata.
20188 	 */
20189 	do {
20190 		/*
20191 		 * If usable send window is too small, or data blocks in
20192 		 * transmit list are smaller than our threshold (i.e. app
20193 		 * performs large writes followed by small ones), we hand
20194 		 * off the control over to the legacy path.  Note that we'll
20195 		 * get back the control once it encounters a large block.
20196 		 */
20197 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
20198 		    (*xmit_tail)->b_cont != NULL &&
20199 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
20200 			/* send down what we've got so far */
20201 			if (md_mp_head != NULL) {
20202 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
20203 				    obsegs, obbytes, &rconfirm);
20204 			}
20205 			/*
20206 			 * Pass control over to tcp_send(), but tell it to
20207 			 * return to us once a large-size transmission is
20208 			 * possible.
20209 			 */
20210 			TCP_STAT(tcps, tcp_mdt_legacy_small);
20211 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
20212 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
20213 			    tail_unsent, xmit_tail, local_time,
20214 			    mdt_thres)) <= 0) {
20215 				/* burst count reached, or alloc failed */
20216 				IRE_REFRELE(ire);
20217 				return (err);
20218 			}
20219 
20220 			/* tcp_send() may have sent everything, so check */
20221 			if (*usable <= 0) {
20222 				IRE_REFRELE(ire);
20223 				return (0);
20224 			}
20225 
20226 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
20227 			/*
20228 			 * We may have delivered the Multidata, so make sure
20229 			 * to re-initialize before the next round.
20230 			 */
20231 			md_mp_head = NULL;
20232 			obsegs = obbytes = 0;
20233 			num_burst_seg = tcp->tcp_snd_burst;
20234 			PREP_NEW_MULTIDATA();
20235 
20236 			/* are we starting from the beginning of data block? */
20237 			if (*tail_unsent == 0) {
20238 				*xmit_tail = (*xmit_tail)->b_cont;
20239 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20240 				    (uintptr_t)INT_MAX);
20241 				*tail_unsent = (int)MBLKL(*xmit_tail);
20242 			}
20243 		}
20244 		/*
20245 		 * Record current values for parameters we may need to pass
20246 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
20247 		 * each iteration of the outer loop (each multidata message
20248 		 * creation). If we have a failure in the inner loop, we send
20249 		 * any complete multidata messages we have before reverting
20250 		 * to using the traditional non-md path.
20251 		 */
20252 		snxt_mmd = *snxt;
20253 		usable_mmd = *usable;
20254 		xmit_tail_mmd = *xmit_tail;
20255 		tail_unsent_mmd = *tail_unsent;
20256 		obsegs_mmd = obsegs;
20257 		obbytes_mmd = obbytes;
20258 
20259 		/*
20260 		 * max_pld limits the number of mblks in tcp's transmit
20261 		 * queue that can be added to a Multidata message.  Once
20262 		 * this counter reaches zero, no more additional mblks
20263 		 * can be added to it.  What happens afterwards depends
20264 		 * on whether or not we are set to chain the Multidata
20265 		 * messages.  If we are to link them together, reset
20266 		 * max_pld to its original value (tcp_mdt_max_pld) and
20267 		 * prepare to create a new Multidata message which will
20268 		 * get linked to md_mp_head.  Else, leave it alone and
20269 		 * let the inner loop break on its own.
20270 		 */
20271 		if (tcp_mdt_chain && max_pld == 0)
20272 			PREP_NEW_MULTIDATA();
20273 
20274 		/* adding a payload buffer; re-initialize values */
20275 		if (add_buffer)
20276 			PREP_NEW_PBUF();
20277 
20278 		/*
20279 		 * If we don't have a Multidata, either because we just
20280 		 * (re)entered this outer loop, or after we branched off
20281 		 * to tcp_send above, setup the Multidata and header
20282 		 * buffer to be used.
20283 		 */
20284 		if (md_mp == NULL) {
20285 			int md_hbuflen;
20286 			uint32_t start, stuff;
20287 
20288 			/*
20289 			 * Calculate Multidata header buffer size large enough
20290 			 * to hold all of the headers that can possibly be
20291 			 * sent at this moment.  We'd rather over-estimate
20292 			 * the size than running out of space; this is okay
20293 			 * since this buffer is small anyway.
20294 			 */
20295 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
20296 
20297 			/*
20298 			 * Start and stuff offset for partial hardware
20299 			 * checksum offload; these are currently for IPv4.
20300 			 * For full checksum offload, they are set to zero.
20301 			 */
20302 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
20303 				if (af == AF_INET) {
20304 					start = IP_SIMPLE_HDR_LENGTH;
20305 					stuff = IP_SIMPLE_HDR_LENGTH +
20306 					    TCP_CHECKSUM_OFFSET;
20307 				} else {
20308 					start = IPV6_HDR_LEN;
20309 					stuff = IPV6_HDR_LEN +
20310 					    TCP_CHECKSUM_OFFSET;
20311 				}
20312 			} else {
20313 				start = stuff = 0;
20314 			}
20315 
20316 			/*
20317 			 * Create the header buffer, Multidata, as well as
20318 			 * any necessary attributes (destination address,
20319 			 * SAP and hardware checksum offload) that should
20320 			 * be associated with the Multidata message.
20321 			 */
20322 			ASSERT(cur_hdr_off == 0);
20323 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
20324 			    ((md_hbuf->b_wptr += md_hbuflen),
20325 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
20326 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
20327 			    /* fastpath mblk */
20328 			    ire->ire_nce->nce_res_mp,
20329 			    /* hardware checksum enabled */
20330 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
20331 			    /* hardware checksum offsets */
20332 			    start, stuff, 0,
20333 			    /* hardware checksum flag */
20334 			    hwcksum_flags, tcps) != 0)) {
20335 legacy_send:
20336 				/*
20337 				 * We arrive here from a failure within the
20338 				 * inner (packetizer) loop or we fail one of
20339 				 * the conditionals above. We restore the
20340 				 * previously checkpointed values for:
20341 				 *    xmit_tail
20342 				 *    usable
20343 				 *    tail_unsent
20344 				 *    snxt
20345 				 *    obbytes
20346 				 *    obsegs
20347 				 * We should then be able to dispatch any
20348 				 * complete multidata before reverting to the
20349 				 * traditional path with consistent parameters
20350 				 * (the inner loop updates these as it
20351 				 * iterates).
20352 				 */
20353 				*xmit_tail = xmit_tail_mmd;
20354 				*usable = usable_mmd;
20355 				*tail_unsent = tail_unsent_mmd;
20356 				*snxt = snxt_mmd;
20357 				obbytes = obbytes_mmd;
20358 				obsegs = obsegs_mmd;
20359 				if (md_mp != NULL) {
20360 					/* Unlink message from the chain */
20361 					if (md_mp_head != NULL) {
20362 						err = (intptr_t)rmvb(md_mp_head,
20363 						    md_mp);
20364 						/*
20365 						 * We can't assert that rmvb
20366 						 * did not return -1, since we
20367 						 * may get here before linkb
20368 						 * happens.  We do, however,
20369 						 * check if we just removed the
20370 						 * only element in the list.
20371 						 */
20372 						if (err == 0)
20373 							md_mp_head = NULL;
20374 					}
20375 					/* md_hbuf gets freed automatically */
20376 					TCP_STAT(tcps, tcp_mdt_discarded);
20377 					freeb(md_mp);
20378 				} else {
20379 					/* Either allocb or mmd_alloc failed */
20380 					TCP_STAT(tcps, tcp_mdt_allocfail);
20381 					if (md_hbuf != NULL)
20382 						freeb(md_hbuf);
20383 				}
20384 
20385 				/* send down what we've got so far */
20386 				if (md_mp_head != NULL) {
20387 					tcp_multisend_data(tcp, ire, ill,
20388 					    md_mp_head, obsegs, obbytes,
20389 					    &rconfirm);
20390 				}
20391 legacy_send_no_md:
20392 				if (ire != NULL)
20393 					IRE_REFRELE(ire);
20394 				/*
20395 				 * Too bad; let the legacy path handle this.
20396 				 * We specify INT_MAX for the threshold, since
20397 				 * we gave up with the Multidata processings
20398 				 * and let the old path have it all.
20399 				 */
20400 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20401 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20402 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20403 				    snxt, tail_unsent, xmit_tail, local_time,
20404 				    INT_MAX));
20405 			}
20406 
20407 			/* link to any existing ones, if applicable */
20408 			TCP_STAT(tcps, tcp_mdt_allocd);
20409 			if (md_mp_head == NULL) {
20410 				md_mp_head = md_mp;
20411 			} else if (tcp_mdt_chain) {
20412 				TCP_STAT(tcps, tcp_mdt_linked);
20413 				linkb(md_mp_head, md_mp);
20414 			}
20415 		}
20416 
20417 		ASSERT(md_mp_head != NULL);
20418 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20419 		ASSERT(md_mp != NULL && mmd != NULL);
20420 		ASSERT(md_hbuf != NULL);
20421 
20422 		/*
20423 		 * Packetize the transmittable portion of the data block;
20424 		 * each data block is essentially added to the Multidata
20425 		 * as a payload buffer.  We also deal with adding more
20426 		 * than one payload buffers, which happens when the remaining
20427 		 * packetized portion of the current payload buffer is less
20428 		 * than MSS, while the next data block in transmit queue
20429 		 * has enough data to make up for one.  This "spillover"
20430 		 * case essentially creates a split-packet, where portions
20431 		 * of the packet's payload fragments may span across two
20432 		 * virtually discontiguous address blocks.
20433 		 */
20434 		seg_len = mss;
20435 		do {
20436 			len = seg_len;
20437 
20438 			/* one must remain NULL for DTRACE_IP_FASTPATH */
20439 			ipha = NULL;
20440 			ip6h = NULL;
20441 
20442 			ASSERT(len > 0);
20443 			ASSERT(max_pld >= 0);
20444 			ASSERT(!add_buffer || cur_pld_off == 0);
20445 
20446 			/*
20447 			 * First time around for this payload buffer; note
20448 			 * in the case of a spillover, the following has
20449 			 * been done prior to adding the split-packet
20450 			 * descriptor to Multidata, and we don't want to
20451 			 * repeat the process.
20452 			 */
20453 			if (add_buffer) {
20454 				ASSERT(mmd != NULL);
20455 				ASSERT(md_pbuf == NULL);
20456 				ASSERT(md_pbuf_nxt == NULL);
20457 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20458 
20459 				/*
20460 				 * Have we reached the limit?  We'd get to
20461 				 * this case when we're not chaining the
20462 				 * Multidata messages together, and since
20463 				 * we're done, terminate this loop.
20464 				 */
20465 				if (max_pld == 0)
20466 					break; /* done */
20467 
20468 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20469 					TCP_STAT(tcps, tcp_mdt_allocfail);
20470 					goto legacy_send; /* out_of_mem */
20471 				}
20472 
20473 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20474 				    zc_cap != NULL) {
20475 					if (!ip_md_zcopy_attr(mmd, NULL,
20476 					    zc_cap->ill_zerocopy_flags)) {
20477 						freeb(md_pbuf);
20478 						TCP_STAT(tcps,
20479 						    tcp_mdt_allocfail);
20480 						/* out_of_mem */
20481 						goto legacy_send;
20482 					}
20483 					zcopy = B_TRUE;
20484 				}
20485 
20486 				md_pbuf->b_rptr += base_pld_off;
20487 
20488 				/*
20489 				 * Add a payload buffer to the Multidata; this
20490 				 * operation must not fail, or otherwise our
20491 				 * logic in this routine is broken.  There
20492 				 * is no memory allocation done by the
20493 				 * routine, so any returned failure simply
20494 				 * tells us that we've done something wrong.
20495 				 *
20496 				 * A failure tells us that either we're adding
20497 				 * the same payload buffer more than once, or
20498 				 * we're trying to add more buffers than
20499 				 * allowed (max_pld calculation is wrong).
20500 				 * None of the above cases should happen, and
20501 				 * we panic because either there's horrible
20502 				 * heap corruption, and/or programming mistake.
20503 				 */
20504 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20505 				if (pbuf_idx < 0) {
20506 					cmn_err(CE_PANIC, "tcp_multisend: "
20507 					    "payload buffer logic error "
20508 					    "detected for tcp %p mmd %p "
20509 					    "pbuf %p (%d)\n",
20510 					    (void *)tcp, (void *)mmd,
20511 					    (void *)md_pbuf, pbuf_idx);
20512 				}
20513 
20514 				ASSERT(max_pld > 0);
20515 				--max_pld;
20516 				add_buffer = B_FALSE;
20517 			}
20518 
20519 			ASSERT(md_mp_head != NULL);
20520 			ASSERT(md_pbuf != NULL);
20521 			ASSERT(md_pbuf_nxt == NULL);
20522 			ASSERT(pbuf_idx != -1);
20523 			ASSERT(pbuf_idx_nxt == -1);
20524 			ASSERT(*usable > 0);
20525 
20526 			/*
20527 			 * We spillover to the next payload buffer only
20528 			 * if all of the following is true:
20529 			 *
20530 			 *   1. There is not enough data on the current
20531 			 *	payload buffer to make up `len',
20532 			 *   2. We are allowed to send `len',
20533 			 *   3. The next payload buffer length is large
20534 			 *	enough to accomodate `spill'.
20535 			 */
20536 			if ((spill = len - *tail_unsent) > 0 &&
20537 			    *usable >= len &&
20538 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20539 			    max_pld > 0) {
20540 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20541 				if (md_pbuf_nxt == NULL) {
20542 					TCP_STAT(tcps, tcp_mdt_allocfail);
20543 					goto legacy_send; /* out_of_mem */
20544 				}
20545 
20546 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20547 				    zc_cap != NULL) {
20548 					if (!ip_md_zcopy_attr(mmd, NULL,
20549 					    zc_cap->ill_zerocopy_flags)) {
20550 						freeb(md_pbuf_nxt);
20551 						TCP_STAT(tcps,
20552 						    tcp_mdt_allocfail);
20553 						/* out_of_mem */
20554 						goto legacy_send;
20555 					}
20556 					zcopy = B_TRUE;
20557 				}
20558 
20559 				/*
20560 				 * See comments above on the first call to
20561 				 * mmd_addpldbuf for explanation on the panic.
20562 				 */
20563 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20564 				if (pbuf_idx_nxt < 0) {
20565 					panic("tcp_multisend: "
20566 					    "next payload buffer logic error "
20567 					    "detected for tcp %p mmd %p "
20568 					    "pbuf %p (%d)\n",
20569 					    (void *)tcp, (void *)mmd,
20570 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20571 				}
20572 
20573 				ASSERT(max_pld > 0);
20574 				--max_pld;
20575 			} else if (spill > 0) {
20576 				/*
20577 				 * If there's a spillover, but the following
20578 				 * xmit_tail couldn't give us enough octets
20579 				 * to reach "len", then stop the current
20580 				 * Multidata creation and let the legacy
20581 				 * tcp_send() path take over.  We don't want
20582 				 * to send the tiny segment as part of this
20583 				 * Multidata for performance reasons; instead,
20584 				 * we let the legacy path deal with grouping
20585 				 * it with the subsequent small mblks.
20586 				 */
20587 				if (*usable >= len &&
20588 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20589 					max_pld = 0;
20590 					break;	/* done */
20591 				}
20592 
20593 				/*
20594 				 * We can't spillover, and we are near
20595 				 * the end of the current payload buffer,
20596 				 * so send what's left.
20597 				 */
20598 				ASSERT(*tail_unsent > 0);
20599 				len = *tail_unsent;
20600 			}
20601 
20602 			/* tail_unsent is negated if there is a spillover */
20603 			*tail_unsent -= len;
20604 			*usable -= len;
20605 			ASSERT(*usable >= 0);
20606 
20607 			if (*usable < mss)
20608 				seg_len = *usable;
20609 			/*
20610 			 * Sender SWS avoidance; see comments in tcp_send();
20611 			 * everything else is the same, except that we only
20612 			 * do this here if there is no more data to be sent
20613 			 * following the current xmit_tail.  We don't check
20614 			 * for 1-byte urgent data because we shouldn't get
20615 			 * here if TCP_URG_VALID is set.
20616 			 */
20617 			if (*usable > 0 && *usable < mss &&
20618 			    ((md_pbuf_nxt == NULL &&
20619 			    (*xmit_tail)->b_cont == NULL) ||
20620 			    (md_pbuf_nxt != NULL &&
20621 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20622 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20623 			    (tcp->tcp_unsent -
20624 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20625 			    !tcp->tcp_zero_win_probe) {
20626 				if ((*snxt + len) == tcp->tcp_snxt &&
20627 				    (*snxt + len) == tcp->tcp_suna) {
20628 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20629 				}
20630 				done = B_TRUE;
20631 			}
20632 
20633 			/*
20634 			 * Prime pump for IP's checksumming on our behalf;
20635 			 * include the adjustment for a source route if any.
20636 			 * Do this only for software/partial hardware checksum
20637 			 * offload, as this field gets zeroed out later for
20638 			 * the full hardware checksum offload case.
20639 			 */
20640 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20641 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20642 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20643 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20644 			}
20645 
20646 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20647 			*snxt += len;
20648 
20649 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20650 			/*
20651 			 * We set the PUSH bit only if TCP has no more buffered
20652 			 * data to be transmitted (or if sender SWS avoidance
20653 			 * takes place), as opposed to setting it for every
20654 			 * last packet in the burst.
20655 			 */
20656 			if (done ||
20657 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20658 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20659 
20660 			/*
20661 			 * Set FIN bit if this is our last segment; snxt
20662 			 * already includes its length, and it will not
20663 			 * be adjusted after this point.
20664 			 */
20665 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20666 			    *snxt == tcp->tcp_fss) {
20667 				if (!tcp->tcp_fin_acked) {
20668 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20669 					BUMP_MIB(&tcps->tcps_mib,
20670 					    tcpOutControl);
20671 				}
20672 				if (!tcp->tcp_fin_sent) {
20673 					tcp->tcp_fin_sent = B_TRUE;
20674 					/*
20675 					 * tcp state must be ESTABLISHED
20676 					 * in order for us to get here in
20677 					 * the first place.
20678 					 */
20679 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20680 
20681 					/*
20682 					 * Upon returning from this routine,
20683 					 * tcp_wput_data() will set tcp_snxt
20684 					 * to be equal to snxt + tcp_fin_sent.
20685 					 * This is essentially the same as
20686 					 * setting it to tcp_fss + 1.
20687 					 */
20688 				}
20689 			}
20690 
20691 			tcp->tcp_last_sent_len = (ushort_t)len;
20692 
20693 			len += tcp_hdr_len;
20694 			if (tcp->tcp_ipversion == IPV4_VERSION)
20695 				tcp->tcp_ipha->ipha_length = htons(len);
20696 			else
20697 				tcp->tcp_ip6h->ip6_plen = htons(len -
20698 				    ((char *)&tcp->tcp_ip6h[1] -
20699 				    tcp->tcp_iphc));
20700 
20701 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20702 
20703 			/* setup header fragment */
20704 			PDESC_HDR_ADD(pkt_info,
20705 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20706 			    tcp->tcp_mdt_hdr_head,		/* head room */
20707 			    tcp_hdr_len,			/* len */
20708 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20709 
20710 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20711 			    hdr_frag_sz);
20712 			ASSERT(MBLKIN(md_hbuf,
20713 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20714 			    PDESC_HDRSIZE(pkt_info)));
20715 
20716 			/* setup first payload fragment */
20717 			PDESC_PLD_INIT(pkt_info);
20718 			PDESC_PLD_SPAN_ADD(pkt_info,
20719 			    pbuf_idx,				/* index */
20720 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20721 			    tcp->tcp_last_sent_len);		/* len */
20722 
20723 			/* create a split-packet in case of a spillover */
20724 			if (md_pbuf_nxt != NULL) {
20725 				ASSERT(spill > 0);
20726 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20727 				ASSERT(!add_buffer);
20728 
20729 				md_pbuf = md_pbuf_nxt;
20730 				md_pbuf_nxt = NULL;
20731 				pbuf_idx = pbuf_idx_nxt;
20732 				pbuf_idx_nxt = -1;
20733 				cur_pld_off = spill;
20734 
20735 				/* trim out first payload fragment */
20736 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20737 
20738 				/* setup second payload fragment */
20739 				PDESC_PLD_SPAN_ADD(pkt_info,
20740 				    pbuf_idx,			/* index */
20741 				    md_pbuf->b_rptr,		/* start */
20742 				    spill);			/* len */
20743 
20744 				if ((*xmit_tail)->b_next == NULL) {
20745 					/*
20746 					 * Store the lbolt used for RTT
20747 					 * estimation. We can only record one
20748 					 * timestamp per mblk so we do it when
20749 					 * we reach the end of the payload
20750 					 * buffer.  Also we only take a new
20751 					 * timestamp sample when the previous
20752 					 * timed data from the same mblk has
20753 					 * been ack'ed.
20754 					 */
20755 					(*xmit_tail)->b_prev = local_time;
20756 					(*xmit_tail)->b_next =
20757 					    (mblk_t *)(uintptr_t)first_snxt;
20758 				}
20759 
20760 				first_snxt = *snxt - spill;
20761 
20762 				/*
20763 				 * Advance xmit_tail; usable could be 0 by
20764 				 * the time we got here, but we made sure
20765 				 * above that we would only spillover to
20766 				 * the next data block if usable includes
20767 				 * the spilled-over amount prior to the
20768 				 * subtraction.  Therefore, we are sure
20769 				 * that xmit_tail->b_cont can't be NULL.
20770 				 */
20771 				ASSERT((*xmit_tail)->b_cont != NULL);
20772 				*xmit_tail = (*xmit_tail)->b_cont;
20773 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20774 				    (uintptr_t)INT_MAX);
20775 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20776 			} else {
20777 				cur_pld_off += tcp->tcp_last_sent_len;
20778 			}
20779 
20780 			/*
20781 			 * Fill in the header using the template header, and
20782 			 * add options such as time-stamp, ECN and/or SACK,
20783 			 * as needed.
20784 			 */
20785 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20786 			    (clock_t)local_time, num_sack_blk);
20787 
20788 			/* take care of some IP header businesses */
20789 			if (af == AF_INET) {
20790 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20791 
20792 				ASSERT(OK_32PTR((uchar_t *)ipha));
20793 				ASSERT(PDESC_HDRL(pkt_info) >=
20794 				    IP_SIMPLE_HDR_LENGTH);
20795 				ASSERT(ipha->ipha_version_and_hdr_length ==
20796 				    IP_SIMPLE_HDR_VERSION);
20797 
20798 				/*
20799 				 * Assign ident value for current packet; see
20800 				 * related comments in ip_wput_ire() about the
20801 				 * contract private interface with clustering
20802 				 * group.
20803 				 */
20804 				clusterwide = B_FALSE;
20805 				if (cl_inet_ipident != NULL) {
20806 					ASSERT(cl_inet_isclusterwide != NULL);
20807 					if ((*cl_inet_isclusterwide)(stack_id,
20808 					    IPPROTO_IP, AF_INET,
20809 					    (uint8_t *)(uintptr_t)src, NULL)) {
20810 						ipha->ipha_ident =
20811 						    (*cl_inet_ipident)(stack_id,
20812 						    IPPROTO_IP, AF_INET,
20813 						    (uint8_t *)(uintptr_t)src,
20814 						    (uint8_t *)(uintptr_t)dst,
20815 						    NULL);
20816 						clusterwide = B_TRUE;
20817 					}
20818 				}
20819 
20820 				if (!clusterwide) {
20821 					ipha->ipha_ident = (uint16_t)
20822 					    atomic_add_32_nv(
20823 						&ire->ire_ident, 1);
20824 				}
20825 #ifndef _BIG_ENDIAN
20826 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20827 				    (ipha->ipha_ident >> 8);
20828 #endif
20829 			} else {
20830 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20831 
20832 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20833 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20834 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20835 				ASSERT(PDESC_HDRL(pkt_info) >=
20836 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20837 				    TCP_CHECKSUM_SIZE));
20838 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20839 
20840 				if (tcp->tcp_ip_forward_progress) {
20841 					rconfirm = B_TRUE;
20842 					tcp->tcp_ip_forward_progress = B_FALSE;
20843 				}
20844 			}
20845 
20846 			/* at least one payload span, and at most two */
20847 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20848 
20849 			/* add the packet descriptor to Multidata */
20850 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20851 			    KM_NOSLEEP)) == NULL) {
20852 				/*
20853 				 * Any failure other than ENOMEM indicates
20854 				 * that we have passed in invalid pkt_info
20855 				 * or parameters to mmd_addpdesc, which must
20856 				 * not happen.
20857 				 *
20858 				 * EINVAL is a result of failure on boundary
20859 				 * checks against the pkt_info contents.  It
20860 				 * should not happen, and we panic because
20861 				 * either there's horrible heap corruption,
20862 				 * and/or programming mistake.
20863 				 */
20864 				if (err != ENOMEM) {
20865 					cmn_err(CE_PANIC, "tcp_multisend: "
20866 					    "pdesc logic error detected for "
20867 					    "tcp %p mmd %p pinfo %p (%d)\n",
20868 					    (void *)tcp, (void *)mmd,
20869 					    (void *)pkt_info, err);
20870 				}
20871 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20872 				goto legacy_send; /* out_of_mem */
20873 			}
20874 			ASSERT(pkt != NULL);
20875 
20876 			/* calculate IP header and TCP checksums */
20877 			if (af == AF_INET) {
20878 				/* calculate pseudo-header checksum */
20879 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20880 				    (src >> 16) + (src & 0xFFFF);
20881 
20882 				/* offset for TCP header checksum */
20883 				up = IPH_TCPH_CHECKSUMP(ipha,
20884 				    IP_SIMPLE_HDR_LENGTH);
20885 			} else {
20886 				up = (uint16_t *)&ip6h->ip6_src;
20887 
20888 				/* calculate pseudo-header checksum */
20889 				cksum = up[0] + up[1] + up[2] + up[3] +
20890 				    up[4] + up[5] + up[6] + up[7] +
20891 				    up[8] + up[9] + up[10] + up[11] +
20892 				    up[12] + up[13] + up[14] + up[15];
20893 
20894 				/* Fold the initial sum */
20895 				cksum = (cksum & 0xffff) + (cksum >> 16);
20896 
20897 				up = (uint16_t *)(((uchar_t *)ip6h) +
20898 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20899 			}
20900 
20901 			if (hwcksum_flags & HCK_FULLCKSUM) {
20902 				/* clear checksum field for hardware */
20903 				*up = 0;
20904 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20905 				uint32_t sum;
20906 
20907 				/* pseudo-header checksumming */
20908 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20909 				sum = (sum & 0xFFFF) + (sum >> 16);
20910 				*up = (sum & 0xFFFF) + (sum >> 16);
20911 			} else {
20912 				/* software checksumming */
20913 				TCP_STAT(tcps, tcp_out_sw_cksum);
20914 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20915 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20916 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20917 				    cksum + IP_TCP_CSUM_COMP);
20918 				if (*up == 0)
20919 					*up = 0xFFFF;
20920 			}
20921 
20922 			/* IPv4 header checksum */
20923 			if (af == AF_INET) {
20924 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20925 					ipha->ipha_hdr_checksum = 0;
20926 				} else {
20927 					IP_HDR_CKSUM(ipha, cksum,
20928 					    ((uint32_t *)ipha)[0],
20929 					    ((uint16_t *)ipha)[4]);
20930 				}
20931 			}
20932 
20933 			if (af == AF_INET &&
20934 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20935 			    af == AF_INET6 &&
20936 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20937 				mblk_t	*mp, *mp1;
20938 				uchar_t	*hdr_rptr, *hdr_wptr;
20939 				uchar_t	*pld_rptr, *pld_wptr;
20940 
20941 				/*
20942 				 * We reconstruct a pseudo packet for the hooks
20943 				 * framework using mmd_transform_link().
20944 				 * If it is a split packet we pullup the
20945 				 * payload. FW_HOOKS expects a pkt comprising
20946 				 * of two mblks: a header and the payload.
20947 				 */
20948 				if ((mp = mmd_transform_link(pkt)) == NULL) {
20949 					TCP_STAT(tcps, tcp_mdt_allocfail);
20950 					goto legacy_send;
20951 				}
20952 
20953 				if (pkt_info->pld_cnt > 1) {
20954 					/* split payload, more than one pld */
20955 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
20956 					    NULL) {
20957 						freemsg(mp);
20958 						TCP_STAT(tcps,
20959 						    tcp_mdt_allocfail);
20960 						goto legacy_send;
20961 					}
20962 					freemsg(mp->b_cont);
20963 					mp->b_cont = mp1;
20964 				} else {
20965 					mp1 = mp->b_cont;
20966 				}
20967 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
20968 
20969 				/*
20970 				 * Remember the message offsets. This is so we
20971 				 * can detect changes when we return from the
20972 				 * FW_HOOKS callbacks.
20973 				 */
20974 				hdr_rptr = mp->b_rptr;
20975 				hdr_wptr = mp->b_wptr;
20976 				pld_rptr = mp->b_cont->b_rptr;
20977 				pld_wptr = mp->b_cont->b_wptr;
20978 
20979 				if (af == AF_INET) {
20980 					DTRACE_PROBE4(
20981 					    ip4__physical__out__start,
20982 					    ill_t *, NULL,
20983 					    ill_t *, ill,
20984 					    ipha_t *, ipha,
20985 					    mblk_t *, mp);
20986 					FW_HOOKS(
20987 					    ipst->ips_ip4_physical_out_event,
20988 					    ipst->ips_ipv4firewall_physical_out,
20989 					    NULL, ill, ipha, mp, mp, 0, ipst);
20990 					DTRACE_PROBE1(
20991 					    ip4__physical__out__end,
20992 					    mblk_t *, mp);
20993 				} else {
20994 					DTRACE_PROBE4(
20995 					    ip6__physical__out_start,
20996 					    ill_t *, NULL,
20997 					    ill_t *, ill,
20998 					    ip6_t *, ip6h,
20999 					    mblk_t *, mp);
21000 					FW_HOOKS6(
21001 					    ipst->ips_ip6_physical_out_event,
21002 					    ipst->ips_ipv6firewall_physical_out,
21003 					    NULL, ill, ip6h, mp, mp, 0, ipst);
21004 					DTRACE_PROBE1(
21005 					    ip6__physical__out__end,
21006 					    mblk_t *, mp);
21007 				}
21008 
21009 				if (mp == NULL ||
21010 				    (mp1 = mp->b_cont) == NULL ||
21011 				    mp->b_rptr != hdr_rptr ||
21012 				    mp->b_wptr != hdr_wptr ||
21013 				    mp1->b_rptr != pld_rptr ||
21014 				    mp1->b_wptr != pld_wptr ||
21015 				    mp1->b_cont != NULL) {
21016 					/*
21017 					 * We abandon multidata processing and
21018 					 * return to the normal path, either
21019 					 * when a packet is blocked, or when
21020 					 * the boundaries of header buffer or
21021 					 * payload buffer have been changed by
21022 					 * FW_HOOKS[6].
21023 					 */
21024 					if (mp != NULL)
21025 						freemsg(mp);
21026 					goto legacy_send;
21027 				}
21028 				/* Finished with the pseudo packet */
21029 				freemsg(mp);
21030 			}
21031 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
21032 			    ill, ipha, ip6h);
21033 			/* advance header offset */
21034 			cur_hdr_off += hdr_frag_sz;
21035 
21036 			obbytes += tcp->tcp_last_sent_len;
21037 			++obsegs;
21038 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
21039 		    *tail_unsent > 0);
21040 
21041 		if ((*xmit_tail)->b_next == NULL) {
21042 			/*
21043 			 * Store the lbolt used for RTT estimation. We can only
21044 			 * record one timestamp per mblk so we do it when we
21045 			 * reach the end of the payload buffer. Also we only
21046 			 * take a new timestamp sample when the previous timed
21047 			 * data from the same mblk has been ack'ed.
21048 			 */
21049 			(*xmit_tail)->b_prev = local_time;
21050 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
21051 		}
21052 
21053 		ASSERT(*tail_unsent >= 0);
21054 		if (*tail_unsent > 0) {
21055 			/*
21056 			 * We got here because we broke out of the above
21057 			 * loop due to of one of the following cases:
21058 			 *
21059 			 *   1. len < adjusted MSS (i.e. small),
21060 			 *   2. Sender SWS avoidance,
21061 			 *   3. max_pld is zero.
21062 			 *
21063 			 * We are done for this Multidata, so trim our
21064 			 * last payload buffer (if any) accordingly.
21065 			 */
21066 			if (md_pbuf != NULL)
21067 				md_pbuf->b_wptr -= *tail_unsent;
21068 		} else if (*usable > 0) {
21069 			*xmit_tail = (*xmit_tail)->b_cont;
21070 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
21071 			    (uintptr_t)INT_MAX);
21072 			*tail_unsent = (int)MBLKL(*xmit_tail);
21073 			add_buffer = B_TRUE;
21074 		}
21075 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
21076 	    (tcp_mdt_chain || max_pld > 0));
21077 
21078 	if (md_mp_head != NULL) {
21079 		/* send everything down */
21080 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
21081 		    &rconfirm);
21082 	}
21083 
21084 #undef PREP_NEW_MULTIDATA
21085 #undef PREP_NEW_PBUF
21086 #undef IPVER
21087 
21088 	IRE_REFRELE(ire);
21089 	return (0);
21090 }
21091 
21092 /*
21093  * A wrapper function for sending one or more Multidata messages down to
21094  * the module below ip; this routine does not release the reference of the
21095  * IRE (caller does that).  This routine is analogous to tcp_send_data().
21096  */
21097 static void
21098 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
21099     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
21100 {
21101 	uint64_t delta;
21102 	nce_t *nce;
21103 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21104 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21105 
21106 	ASSERT(ire != NULL && ill != NULL);
21107 	ASSERT(ire->ire_stq != NULL);
21108 	ASSERT(md_mp_head != NULL);
21109 	ASSERT(rconfirm != NULL);
21110 
21111 	/* adjust MIBs and IRE timestamp */
21112 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
21113 	tcp->tcp_obsegs += obsegs;
21114 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
21115 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
21116 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
21117 
21118 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21119 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
21120 	} else {
21121 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
21122 	}
21123 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
21124 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
21125 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
21126 
21127 	ire->ire_ob_pkt_count += obsegs;
21128 	if (ire->ire_ipif != NULL)
21129 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
21130 	ire->ire_last_used_time = lbolt;
21131 
21132 	if (ipst->ips_ipobs_enabled) {
21133 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
21134 		pdesc_t *dl_pkt;
21135 		pdescinfo_t pinfo;
21136 		mblk_t *nmp;
21137 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
21138 
21139 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
21140 		    (dl_pkt != NULL);
21141 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
21142 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
21143 				continue;
21144 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
21145 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
21146 			freemsg(nmp);
21147 		}
21148 	}
21149 
21150 	/* send it down */
21151 	putnext(ire->ire_stq, md_mp_head);
21152 
21153 	/* we're done for TCP/IPv4 */
21154 	if (tcp->tcp_ipversion == IPV4_VERSION)
21155 		return;
21156 
21157 	nce = ire->ire_nce;
21158 
21159 	ASSERT(nce != NULL);
21160 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
21161 	ASSERT(nce->nce_state != ND_INCOMPLETE);
21162 
21163 	/* reachability confirmation? */
21164 	if (*rconfirm) {
21165 		nce->nce_last = TICK_TO_MSEC(lbolt64);
21166 		if (nce->nce_state != ND_REACHABLE) {
21167 			mutex_enter(&nce->nce_lock);
21168 			nce->nce_state = ND_REACHABLE;
21169 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
21170 			mutex_exit(&nce->nce_lock);
21171 			(void) untimeout(nce->nce_timeout_id);
21172 			if (ip_debug > 2) {
21173 				/* ip1dbg */
21174 				pr_addr_dbg("tcp_multisend_data: state "
21175 				    "for %s changed to REACHABLE\n",
21176 				    AF_INET6, &ire->ire_addr_v6);
21177 			}
21178 		}
21179 		/* reset transport reachability confirmation */
21180 		*rconfirm = B_FALSE;
21181 	}
21182 
21183 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
21184 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
21185 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
21186 
21187 	if (delta > (uint64_t)ill->ill_reachable_time) {
21188 		mutex_enter(&nce->nce_lock);
21189 		switch (nce->nce_state) {
21190 		case ND_REACHABLE:
21191 		case ND_STALE:
21192 			/*
21193 			 * ND_REACHABLE is identical to ND_STALE in this
21194 			 * specific case. If reachable time has expired for
21195 			 * this neighbor (delta is greater than reachable
21196 			 * time), conceptually, the neighbor cache is no
21197 			 * longer in REACHABLE state, but already in STALE
21198 			 * state.  So the correct transition here is to
21199 			 * ND_DELAY.
21200 			 */
21201 			nce->nce_state = ND_DELAY;
21202 			mutex_exit(&nce->nce_lock);
21203 			NDP_RESTART_TIMER(nce,
21204 			    ipst->ips_delay_first_probe_time);
21205 			if (ip_debug > 3) {
21206 				/* ip2dbg */
21207 				pr_addr_dbg("tcp_multisend_data: state "
21208 				    "for %s changed to DELAY\n",
21209 				    AF_INET6, &ire->ire_addr_v6);
21210 			}
21211 			break;
21212 		case ND_DELAY:
21213 		case ND_PROBE:
21214 			mutex_exit(&nce->nce_lock);
21215 			/* Timers have already started */
21216 			break;
21217 		case ND_UNREACHABLE:
21218 			/*
21219 			 * ndp timer has detected that this nce is
21220 			 * unreachable and initiated deleting this nce
21221 			 * and all its associated IREs. This is a race
21222 			 * where we found the ire before it was deleted
21223 			 * and have just sent out a packet using this
21224 			 * unreachable nce.
21225 			 */
21226 			mutex_exit(&nce->nce_lock);
21227 			break;
21228 		default:
21229 			ASSERT(0);
21230 		}
21231 	}
21232 }
21233 
21234 /*
21235  * Derived from tcp_send_data().
21236  */
21237 static void
21238 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
21239     int num_lso_seg)
21240 {
21241 	ipha_t		*ipha;
21242 	mblk_t		*ire_fp_mp;
21243 	uint_t		ire_fp_mp_len;
21244 	uint32_t	hcksum_txflags = 0;
21245 	ipaddr_t	src;
21246 	ipaddr_t	dst;
21247 	uint32_t	cksum;
21248 	uint16_t	*up;
21249 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21250 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21251 
21252 	ASSERT(DB_TYPE(mp) == M_DATA);
21253 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
21254 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
21255 	ASSERT(tcp->tcp_connp != NULL);
21256 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
21257 
21258 	ipha = (ipha_t *)mp->b_rptr;
21259 	src = ipha->ipha_src;
21260 	dst = ipha->ipha_dst;
21261 
21262 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
21263 
21264 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21265 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
21266 	    num_lso_seg);
21267 #ifndef _BIG_ENDIAN
21268 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21269 #endif
21270 	if (tcp->tcp_snd_zcopy_aware) {
21271 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
21272 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
21273 			mp = tcp_zcopy_disable(tcp, mp);
21274 	}
21275 
21276 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
21277 		ASSERT(ill->ill_hcksum_capab != NULL);
21278 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
21279 	}
21280 
21281 	/*
21282 	 * Since the TCP checksum should be recalculated by h/w, we can just
21283 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
21284 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
21285 	 * The partial pseudo-header excludes TCP length, that was calculated
21286 	 * in tcp_send(), so to zero *up before further processing.
21287 	 */
21288 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21289 
21290 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
21291 	*up = 0;
21292 
21293 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
21294 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
21295 
21296 	/*
21297 	 * Append LSO flags and mss to the mp.
21298 	 */
21299 	lso_info_set(mp, mss, HW_LSO);
21300 
21301 	ipha->ipha_fragment_offset_and_flags |=
21302 	    (uint32_t)htons(ire->ire_frag_flag);
21303 
21304 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
21305 	ire_fp_mp_len = MBLKL(ire_fp_mp);
21306 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
21307 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
21308 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
21309 
21310 	UPDATE_OB_PKT_COUNT(ire);
21311 	ire->ire_last_used_time = lbolt;
21312 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
21313 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
21314 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
21315 	    ntohs(ipha->ipha_length));
21316 
21317 	DTRACE_PROBE4(ip4__physical__out__start,
21318 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
21319 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
21320 	    ipst->ips_ipv4firewall_physical_out, NULL,
21321 	    ill, ipha, mp, mp, 0, ipst);
21322 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21323 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
21324 
21325 	if (mp != NULL) {
21326 		if (ipst->ips_ipobs_enabled) {
21327 			zoneid_t szone;
21328 
21329 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
21330 			    ipst, ALL_ZONES);
21331 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
21332 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
21333 		}
21334 
21335 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0);
21336 	}
21337 }
21338 
21339 /*
21340  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
21341  * scheme, and returns one of the following:
21342  *
21343  * -1 = failed allocation.
21344  *  0 = success; burst count reached, or usable send window is too small,
21345  *      and that we'd rather wait until later before sending again.
21346  *  1 = success; we are called from tcp_multisend(), and both usable send
21347  *      window and tail_unsent are greater than the MDT threshold, and thus
21348  *      Multidata Transmit should be used instead.
21349  */
21350 static int
21351 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
21352     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
21353     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
21354     const int mdt_thres)
21355 {
21356 	int num_burst_seg = tcp->tcp_snd_burst;
21357 	ire_t		*ire = NULL;
21358 	ill_t		*ill = NULL;
21359 	mblk_t		*ire_fp_mp = NULL;
21360 	uint_t		ire_fp_mp_len = 0;
21361 	int		num_lso_seg = 1;
21362 	uint_t		lso_usable;
21363 	boolean_t	do_lso_send = B_FALSE;
21364 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21365 
21366 	/*
21367 	 * Check LSO capability before any further work. And the similar check
21368 	 * need to be done in for(;;) loop.
21369 	 * LSO will be deployed when therer is more than one mss of available
21370 	 * data and a burst transmission is allowed.
21371 	 */
21372 	if (tcp->tcp_lso &&
21373 	    (tcp->tcp_valid_bits == 0 ||
21374 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21375 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21376 		/*
21377 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21378 		 */
21379 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
21380 			/*
21381 			 * Enable LSO with this transmission.
21382 			 * Since IRE has been hold in
21383 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
21384 			 * should be called before return.
21385 			 */
21386 			do_lso_send = B_TRUE;
21387 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21388 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21389 			/* Round up to multiple of 4 */
21390 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21391 		} else {
21392 			do_lso_send = B_FALSE;
21393 			ill = NULL;
21394 		}
21395 	}
21396 
21397 	for (;;) {
21398 		struct datab	*db;
21399 		tcph_t		*tcph;
21400 		uint32_t	sum;
21401 		mblk_t		*mp, *mp1;
21402 		uchar_t		*rptr;
21403 		int		len;
21404 
21405 		/*
21406 		 * If we're called by tcp_multisend(), and the amount of
21407 		 * sendable data as well as the size of current xmit_tail
21408 		 * is beyond the MDT threshold, return to the caller and
21409 		 * let the large data transmit be done using MDT.
21410 		 */
21411 		if (*usable > 0 && *usable > mdt_thres &&
21412 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21413 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21414 			ASSERT(tcp->tcp_mdt);
21415 			return (1);	/* success; do large send */
21416 		}
21417 
21418 		if (num_burst_seg == 0)
21419 			break;		/* success; burst count reached */
21420 
21421 		/*
21422 		 * Calculate the maximum payload length we can send in *one*
21423 		 * time.
21424 		 */
21425 		if (do_lso_send) {
21426 			/*
21427 			 * Check whether need to do LSO any more.
21428 			 */
21429 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21430 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21431 				lso_usable = MIN(lso_usable,
21432 				    num_burst_seg * mss);
21433 
21434 				num_lso_seg = lso_usable / mss;
21435 				if (lso_usable % mss) {
21436 					num_lso_seg++;
21437 					tcp->tcp_last_sent_len = (ushort_t)
21438 					    (lso_usable % mss);
21439 				} else {
21440 					tcp->tcp_last_sent_len = (ushort_t)mss;
21441 				}
21442 			} else {
21443 				do_lso_send = B_FALSE;
21444 				num_lso_seg = 1;
21445 				lso_usable = mss;
21446 			}
21447 		}
21448 
21449 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21450 
21451 		/*
21452 		 * Adjust num_burst_seg here.
21453 		 */
21454 		num_burst_seg -= num_lso_seg;
21455 
21456 		len = mss;
21457 		if (len > *usable) {
21458 			ASSERT(do_lso_send == B_FALSE);
21459 
21460 			len = *usable;
21461 			if (len <= 0) {
21462 				/* Terminate the loop */
21463 				break;	/* success; too small */
21464 			}
21465 			/*
21466 			 * Sender silly-window avoidance.
21467 			 * Ignore this if we are going to send a
21468 			 * zero window probe out.
21469 			 *
21470 			 * TODO: force data into microscopic window?
21471 			 *	==> (!pushed || (unsent > usable))
21472 			 */
21473 			if (len < (tcp->tcp_max_swnd >> 1) &&
21474 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21475 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21476 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21477 				/*
21478 				 * If the retransmit timer is not running
21479 				 * we start it so that we will retransmit
21480 				 * in the case when the the receiver has
21481 				 * decremented the window.
21482 				 */
21483 				if (*snxt == tcp->tcp_snxt &&
21484 				    *snxt == tcp->tcp_suna) {
21485 					/*
21486 					 * We are not supposed to send
21487 					 * anything.  So let's wait a little
21488 					 * bit longer before breaking SWS
21489 					 * avoidance.
21490 					 *
21491 					 * What should the value be?
21492 					 * Suggestion: MAX(init rexmit time,
21493 					 * tcp->tcp_rto)
21494 					 */
21495 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21496 				}
21497 				break;	/* success; too small */
21498 			}
21499 		}
21500 
21501 		tcph = tcp->tcp_tcph;
21502 
21503 		/*
21504 		 * The reason to adjust len here is that we need to set flags
21505 		 * and calculate checksum.
21506 		 */
21507 		if (do_lso_send)
21508 			len = lso_usable;
21509 
21510 		*usable -= len; /* Approximate - can be adjusted later */
21511 		if (*usable > 0)
21512 			tcph->th_flags[0] = TH_ACK;
21513 		else
21514 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21515 
21516 		/*
21517 		 * Prime pump for IP's checksumming on our behalf
21518 		 * Include the adjustment for a source route if any.
21519 		 */
21520 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21521 		sum = (sum >> 16) + (sum & 0xFFFF);
21522 		U16_TO_ABE16(sum, tcph->th_sum);
21523 
21524 		U32_TO_ABE32(*snxt, tcph->th_seq);
21525 
21526 		/*
21527 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21528 		 * set.  For the case when TCP_FSS_VALID is the only valid
21529 		 * bit (normal active close), branch off only when we think
21530 		 * that the FIN flag needs to be set.  Note for this case,
21531 		 * that (snxt + len) may not reflect the actual seg_len,
21532 		 * as len may be further reduced in tcp_xmit_mp().  If len
21533 		 * gets modified, we will end up here again.
21534 		 */
21535 		if (tcp->tcp_valid_bits != 0 &&
21536 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21537 		    ((*snxt + len) == tcp->tcp_fss))) {
21538 			uchar_t		*prev_rptr;
21539 			uint32_t	prev_snxt = tcp->tcp_snxt;
21540 
21541 			if (*tail_unsent == 0) {
21542 				ASSERT((*xmit_tail)->b_cont != NULL);
21543 				*xmit_tail = (*xmit_tail)->b_cont;
21544 				prev_rptr = (*xmit_tail)->b_rptr;
21545 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21546 				    (*xmit_tail)->b_rptr);
21547 			} else {
21548 				prev_rptr = (*xmit_tail)->b_rptr;
21549 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21550 				    *tail_unsent;
21551 			}
21552 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21553 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21554 			/* Restore tcp_snxt so we get amount sent right. */
21555 			tcp->tcp_snxt = prev_snxt;
21556 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21557 				/*
21558 				 * If the previous timestamp is still in use,
21559 				 * don't stomp on it.
21560 				 */
21561 				if ((*xmit_tail)->b_next == NULL) {
21562 					(*xmit_tail)->b_prev = local_time;
21563 					(*xmit_tail)->b_next =
21564 					    (mblk_t *)(uintptr_t)(*snxt);
21565 				}
21566 			} else
21567 				(*xmit_tail)->b_rptr = prev_rptr;
21568 
21569 			if (mp == NULL) {
21570 				if (ire != NULL)
21571 					IRE_REFRELE(ire);
21572 				return (-1);
21573 			}
21574 			mp1 = mp->b_cont;
21575 
21576 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21577 				tcp->tcp_last_sent_len = (ushort_t)len;
21578 			while (mp1->b_cont) {
21579 				*xmit_tail = (*xmit_tail)->b_cont;
21580 				(*xmit_tail)->b_prev = local_time;
21581 				(*xmit_tail)->b_next =
21582 				    (mblk_t *)(uintptr_t)(*snxt);
21583 				mp1 = mp1->b_cont;
21584 			}
21585 			*snxt += len;
21586 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21587 			BUMP_LOCAL(tcp->tcp_obsegs);
21588 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21589 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21590 			tcp_send_data(tcp, q, mp);
21591 			continue;
21592 		}
21593 
21594 		*snxt += len;	/* Adjust later if we don't send all of len */
21595 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21596 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21597 
21598 		if (*tail_unsent) {
21599 			/* Are the bytes above us in flight? */
21600 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21601 			if (rptr != (*xmit_tail)->b_rptr) {
21602 				*tail_unsent -= len;
21603 				if (len <= mss) /* LSO is unusable */
21604 					tcp->tcp_last_sent_len = (ushort_t)len;
21605 				len += tcp_hdr_len;
21606 				if (tcp->tcp_ipversion == IPV4_VERSION)
21607 					tcp->tcp_ipha->ipha_length = htons(len);
21608 				else
21609 					tcp->tcp_ip6h->ip6_plen =
21610 					    htons(len -
21611 					    ((char *)&tcp->tcp_ip6h[1] -
21612 					    tcp->tcp_iphc));
21613 				mp = dupb(*xmit_tail);
21614 				if (mp == NULL) {
21615 					if (ire != NULL)
21616 						IRE_REFRELE(ire);
21617 					return (-1);	/* out_of_mem */
21618 				}
21619 				mp->b_rptr = rptr;
21620 				/*
21621 				 * If the old timestamp is no longer in use,
21622 				 * sample a new timestamp now.
21623 				 */
21624 				if ((*xmit_tail)->b_next == NULL) {
21625 					(*xmit_tail)->b_prev = local_time;
21626 					(*xmit_tail)->b_next =
21627 					    (mblk_t *)(uintptr_t)(*snxt-len);
21628 				}
21629 				goto must_alloc;
21630 			}
21631 		} else {
21632 			*xmit_tail = (*xmit_tail)->b_cont;
21633 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21634 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21635 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21636 			    (*xmit_tail)->b_rptr);
21637 		}
21638 
21639 		(*xmit_tail)->b_prev = local_time;
21640 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21641 
21642 		*tail_unsent -= len;
21643 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21644 			tcp->tcp_last_sent_len = (ushort_t)len;
21645 
21646 		len += tcp_hdr_len;
21647 		if (tcp->tcp_ipversion == IPV4_VERSION)
21648 			tcp->tcp_ipha->ipha_length = htons(len);
21649 		else
21650 			tcp->tcp_ip6h->ip6_plen = htons(len -
21651 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21652 
21653 		mp = dupb(*xmit_tail);
21654 		if (mp == NULL) {
21655 			if (ire != NULL)
21656 				IRE_REFRELE(ire);
21657 			return (-1);	/* out_of_mem */
21658 		}
21659 
21660 		len = tcp_hdr_len;
21661 		/*
21662 		 * There are four reasons to allocate a new hdr mblk:
21663 		 *  1) The bytes above us are in use by another packet
21664 		 *  2) We don't have good alignment
21665 		 *  3) The mblk is being shared
21666 		 *  4) We don't have enough room for a header
21667 		 */
21668 		rptr = mp->b_rptr - len;
21669 		if (!OK_32PTR(rptr) ||
21670 		    ((db = mp->b_datap), db->db_ref != 2) ||
21671 		    rptr < db->db_base + ire_fp_mp_len) {
21672 			/* NOTE: we assume allocb returns an OK_32PTR */
21673 
21674 		must_alloc:;
21675 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21676 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21677 			if (mp1 == NULL) {
21678 				freemsg(mp);
21679 				if (ire != NULL)
21680 					IRE_REFRELE(ire);
21681 				return (-1);	/* out_of_mem */
21682 			}
21683 			mp1->b_cont = mp;
21684 			mp = mp1;
21685 			/* Leave room for Link Level header */
21686 			len = tcp_hdr_len;
21687 			rptr =
21688 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21689 			mp->b_wptr = &rptr[len];
21690 		}
21691 
21692 		/*
21693 		 * Fill in the header using the template header, and add
21694 		 * options such as time-stamp, ECN and/or SACK, as needed.
21695 		 */
21696 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21697 
21698 		mp->b_rptr = rptr;
21699 
21700 		if (*tail_unsent) {
21701 			int spill = *tail_unsent;
21702 
21703 			mp1 = mp->b_cont;
21704 			if (mp1 == NULL)
21705 				mp1 = mp;
21706 
21707 			/*
21708 			 * If we're a little short, tack on more mblks until
21709 			 * there is no more spillover.
21710 			 */
21711 			while (spill < 0) {
21712 				mblk_t *nmp;
21713 				int nmpsz;
21714 
21715 				nmp = (*xmit_tail)->b_cont;
21716 				nmpsz = MBLKL(nmp);
21717 
21718 				/*
21719 				 * Excess data in mblk; can we split it?
21720 				 * If MDT is enabled for the connection,
21721 				 * keep on splitting as this is a transient
21722 				 * send path.
21723 				 */
21724 				if (!do_lso_send && !tcp->tcp_mdt &&
21725 				    (spill + nmpsz > 0)) {
21726 					/*
21727 					 * Don't split if stream head was
21728 					 * told to break up larger writes
21729 					 * into smaller ones.
21730 					 */
21731 					if (tcp->tcp_maxpsz > 0)
21732 						break;
21733 
21734 					/*
21735 					 * Next mblk is less than SMSS/2
21736 					 * rounded up to nearest 64-byte;
21737 					 * let it get sent as part of the
21738 					 * next segment.
21739 					 */
21740 					if (tcp->tcp_localnet &&
21741 					    !tcp->tcp_cork &&
21742 					    (nmpsz < roundup((mss >> 1), 64)))
21743 						break;
21744 				}
21745 
21746 				*xmit_tail = nmp;
21747 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21748 				/* Stash for rtt use later */
21749 				(*xmit_tail)->b_prev = local_time;
21750 				(*xmit_tail)->b_next =
21751 				    (mblk_t *)(uintptr_t)(*snxt - len);
21752 				mp1->b_cont = dupb(*xmit_tail);
21753 				mp1 = mp1->b_cont;
21754 
21755 				spill += nmpsz;
21756 				if (mp1 == NULL) {
21757 					*tail_unsent = spill;
21758 					freemsg(mp);
21759 					if (ire != NULL)
21760 						IRE_REFRELE(ire);
21761 					return (-1);	/* out_of_mem */
21762 				}
21763 			}
21764 
21765 			/* Trim back any surplus on the last mblk */
21766 			if (spill >= 0) {
21767 				mp1->b_wptr -= spill;
21768 				*tail_unsent = spill;
21769 			} else {
21770 				/*
21771 				 * We did not send everything we could in
21772 				 * order to remain within the b_cont limit.
21773 				 */
21774 				*usable -= spill;
21775 				*snxt += spill;
21776 				tcp->tcp_last_sent_len += spill;
21777 				UPDATE_MIB(&tcps->tcps_mib,
21778 				    tcpOutDataBytes, spill);
21779 				/*
21780 				 * Adjust the checksum
21781 				 */
21782 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21783 				sum += spill;
21784 				sum = (sum >> 16) + (sum & 0xFFFF);
21785 				U16_TO_ABE16(sum, tcph->th_sum);
21786 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21787 					sum = ntohs(
21788 					    ((ipha_t *)rptr)->ipha_length) +
21789 					    spill;
21790 					((ipha_t *)rptr)->ipha_length =
21791 					    htons(sum);
21792 				} else {
21793 					sum = ntohs(
21794 					    ((ip6_t *)rptr)->ip6_plen) +
21795 					    spill;
21796 					((ip6_t *)rptr)->ip6_plen =
21797 					    htons(sum);
21798 				}
21799 				*tail_unsent = 0;
21800 			}
21801 		}
21802 		if (tcp->tcp_ip_forward_progress) {
21803 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21804 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21805 			tcp->tcp_ip_forward_progress = B_FALSE;
21806 		}
21807 
21808 		if (do_lso_send) {
21809 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21810 			    num_lso_seg);
21811 			tcp->tcp_obsegs += num_lso_seg;
21812 
21813 			TCP_STAT(tcps, tcp_lso_times);
21814 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21815 		} else {
21816 			tcp_send_data(tcp, q, mp);
21817 			BUMP_LOCAL(tcp->tcp_obsegs);
21818 		}
21819 	}
21820 
21821 	if (ire != NULL)
21822 		IRE_REFRELE(ire);
21823 	return (0);
21824 }
21825 
21826 /* Unlink and return any mblk that looks like it contains a MDT info */
21827 static mblk_t *
21828 tcp_mdt_info_mp(mblk_t *mp)
21829 {
21830 	mblk_t	*prev_mp;
21831 
21832 	for (;;) {
21833 		prev_mp = mp;
21834 		/* no more to process? */
21835 		if ((mp = mp->b_cont) == NULL)
21836 			break;
21837 
21838 		switch (DB_TYPE(mp)) {
21839 		case M_CTL:
21840 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21841 				continue;
21842 			ASSERT(prev_mp != NULL);
21843 			prev_mp->b_cont = mp->b_cont;
21844 			mp->b_cont = NULL;
21845 			return (mp);
21846 		default:
21847 			break;
21848 		}
21849 	}
21850 	return (mp);
21851 }
21852 
21853 /* MDT info update routine, called when IP notifies us about MDT */
21854 static void
21855 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21856 {
21857 	boolean_t prev_state;
21858 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21859 
21860 	/*
21861 	 * IP is telling us to abort MDT on this connection?  We know
21862 	 * this because the capability is only turned off when IP
21863 	 * encounters some pathological cases, e.g. link-layer change
21864 	 * where the new driver doesn't support MDT, or in situation
21865 	 * where MDT usage on the link-layer has been switched off.
21866 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21867 	 * if the link-layer doesn't support MDT, and if it does, it
21868 	 * will indicate that the feature is to be turned on.
21869 	 */
21870 	prev_state = tcp->tcp_mdt;
21871 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21872 	if (!tcp->tcp_mdt && !first) {
21873 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21874 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21875 		    (void *)tcp->tcp_connp));
21876 	}
21877 
21878 	/*
21879 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21880 	 * so disable MDT otherwise.  The checks are done here
21881 	 * and in tcp_wput_data().
21882 	 */
21883 	if (tcp->tcp_mdt &&
21884 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21885 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21886 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21887 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21888 		tcp->tcp_mdt = B_FALSE;
21889 
21890 	if (tcp->tcp_mdt) {
21891 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21892 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21893 			    "version (%d), expected version is %d",
21894 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21895 			tcp->tcp_mdt = B_FALSE;
21896 			return;
21897 		}
21898 
21899 		/*
21900 		 * We need the driver to be able to handle at least three
21901 		 * spans per packet in order for tcp MDT to be utilized.
21902 		 * The first is for the header portion, while the rest are
21903 		 * needed to handle a packet that straddles across two
21904 		 * virtually non-contiguous buffers; a typical tcp packet
21905 		 * therefore consists of only two spans.  Note that we take
21906 		 * a zero as "don't care".
21907 		 */
21908 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21909 		    mdt_capab->ill_mdt_span_limit < 3) {
21910 			tcp->tcp_mdt = B_FALSE;
21911 			return;
21912 		}
21913 
21914 		/* a zero means driver wants default value */
21915 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21916 		    tcps->tcps_mdt_max_pbufs);
21917 		if (tcp->tcp_mdt_max_pld == 0)
21918 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21919 
21920 		/* ensure 32-bit alignment */
21921 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21922 		    mdt_capab->ill_mdt_hdr_head), 4);
21923 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21924 		    mdt_capab->ill_mdt_hdr_tail), 4);
21925 
21926 		if (!first && !prev_state) {
21927 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21928 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21929 			    (void *)tcp->tcp_connp));
21930 		}
21931 	}
21932 }
21933 
21934 /* Unlink and return any mblk that looks like it contains a LSO info */
21935 static mblk_t *
21936 tcp_lso_info_mp(mblk_t *mp)
21937 {
21938 	mblk_t	*prev_mp;
21939 
21940 	for (;;) {
21941 		prev_mp = mp;
21942 		/* no more to process? */
21943 		if ((mp = mp->b_cont) == NULL)
21944 			break;
21945 
21946 		switch (DB_TYPE(mp)) {
21947 		case M_CTL:
21948 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21949 				continue;
21950 			ASSERT(prev_mp != NULL);
21951 			prev_mp->b_cont = mp->b_cont;
21952 			mp->b_cont = NULL;
21953 			return (mp);
21954 		default:
21955 			break;
21956 		}
21957 	}
21958 
21959 	return (mp);
21960 }
21961 
21962 /* LSO info update routine, called when IP notifies us about LSO */
21963 static void
21964 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21965 {
21966 	tcp_stack_t *tcps = tcp->tcp_tcps;
21967 
21968 	/*
21969 	 * IP is telling us to abort LSO on this connection?  We know
21970 	 * this because the capability is only turned off when IP
21971 	 * encounters some pathological cases, e.g. link-layer change
21972 	 * where the new NIC/driver doesn't support LSO, or in situation
21973 	 * where LSO usage on the link-layer has been switched off.
21974 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21975 	 * if the link-layer doesn't support LSO, and if it does, it
21976 	 * will indicate that the feature is to be turned on.
21977 	 */
21978 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21979 	TCP_STAT(tcps, tcp_lso_enabled);
21980 
21981 	/*
21982 	 * We currently only support LSO on simple TCP/IPv4,
21983 	 * so disable LSO otherwise.  The checks are done here
21984 	 * and in tcp_wput_data().
21985 	 */
21986 	if (tcp->tcp_lso &&
21987 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21988 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21989 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21990 		tcp->tcp_lso = B_FALSE;
21991 		TCP_STAT(tcps, tcp_lso_disabled);
21992 	} else {
21993 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21994 		    lso_capab->ill_lso_max);
21995 	}
21996 }
21997 
21998 static void
21999 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
22000 {
22001 	conn_t *connp = tcp->tcp_connp;
22002 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22003 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22004 
22005 	ASSERT(ire != NULL);
22006 
22007 	/*
22008 	 * We may be in the fastpath here, and although we essentially do
22009 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
22010 	 * we try to keep things as brief as possible.  After all, these
22011 	 * are only best-effort checks, and we do more thorough ones prior
22012 	 * to calling tcp_send()/tcp_multisend().
22013 	 */
22014 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
22015 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
22016 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
22017 	    !(ire->ire_flags & RTF_MULTIRT) &&
22018 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
22019 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
22020 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
22021 			/* Cache the result */
22022 			connp->conn_lso_ok = B_TRUE;
22023 
22024 			ASSERT(ill->ill_lso_capab != NULL);
22025 			if (!ill->ill_lso_capab->ill_lso_on) {
22026 				ill->ill_lso_capab->ill_lso_on = 1;
22027 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22028 				    "LSO for interface %s\n", (void *)connp,
22029 				    ill->ill_name));
22030 			}
22031 			tcp_lso_update(tcp, ill->ill_lso_capab);
22032 		} else if (ipst->ips_ip_multidata_outbound &&
22033 		    ILL_MDT_CAPABLE(ill)) {
22034 			/* Cache the result */
22035 			connp->conn_mdt_ok = B_TRUE;
22036 
22037 			ASSERT(ill->ill_mdt_capab != NULL);
22038 			if (!ill->ill_mdt_capab->ill_mdt_on) {
22039 				ill->ill_mdt_capab->ill_mdt_on = 1;
22040 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22041 				    "MDT for interface %s\n", (void *)connp,
22042 				    ill->ill_name));
22043 			}
22044 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
22045 		}
22046 	}
22047 
22048 	/*
22049 	 * The goal is to reduce the number of generated tcp segments by
22050 	 * setting the maxpsz multiplier to 0; this will have an affect on
22051 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
22052 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
22053 	 * of outbound segments and incoming ACKs, thus allowing for better
22054 	 * network and system performance.  In contrast the legacy behavior
22055 	 * may result in sending less than SMSS size, because the last mblk
22056 	 * for some packets may have more data than needed to make up SMSS,
22057 	 * and the legacy code refused to "split" it.
22058 	 *
22059 	 * We apply the new behavior on following situations:
22060 	 *
22061 	 *   1) Loopback connections,
22062 	 *   2) Connections in which the remote peer is not on local subnet,
22063 	 *   3) Local subnet connections over the bge interface (see below).
22064 	 *
22065 	 * Ideally, we would like this behavior to apply for interfaces other
22066 	 * than bge.  However, doing so would negatively impact drivers which
22067 	 * perform dynamic mapping and unmapping of DMA resources, which are
22068 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
22069 	 * packet will be generated by tcp).  The bge driver does not suffer
22070 	 * from this, as it copies the mblks into pre-mapped buffers, and
22071 	 * therefore does not require more I/O resources than before.
22072 	 *
22073 	 * Otherwise, this behavior is present on all network interfaces when
22074 	 * the destination endpoint is non-local, since reducing the number
22075 	 * of packets in general is good for the network.
22076 	 *
22077 	 * TODO We need to remove this hard-coded conditional for bge once
22078 	 *	a better "self-tuning" mechanism, or a way to comprehend
22079 	 *	the driver transmit strategy is devised.  Until the solution
22080 	 *	is found and well understood, we live with this hack.
22081 	 */
22082 	if (!tcp_static_maxpsz &&
22083 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
22084 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
22085 		/* override the default value */
22086 		tcp->tcp_maxpsz = 0;
22087 
22088 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
22089 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
22090 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
22091 	}
22092 
22093 	/* set the stream head parameters accordingly */
22094 	(void) tcp_maxpsz_set(tcp, B_TRUE);
22095 }
22096 
22097 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
22098 static void
22099 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
22100 {
22101 	uchar_t	fval = *mp->b_rptr;
22102 	mblk_t	*tail;
22103 	queue_t	*q = tcp->tcp_wq;
22104 
22105 	/* TODO: How should flush interact with urgent data? */
22106 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
22107 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
22108 		/*
22109 		 * Flush only data that has not yet been put on the wire.  If
22110 		 * we flush data that we have already transmitted, life, as we
22111 		 * know it, may come to an end.
22112 		 */
22113 		tail = tcp->tcp_xmit_tail;
22114 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
22115 		tcp->tcp_xmit_tail_unsent = 0;
22116 		tcp->tcp_unsent = 0;
22117 		if (tail->b_wptr != tail->b_rptr)
22118 			tail = tail->b_cont;
22119 		if (tail) {
22120 			mblk_t **excess = &tcp->tcp_xmit_head;
22121 			for (;;) {
22122 				mblk_t *mp1 = *excess;
22123 				if (mp1 == tail)
22124 					break;
22125 				tcp->tcp_xmit_tail = mp1;
22126 				tcp->tcp_xmit_last = mp1;
22127 				excess = &mp1->b_cont;
22128 			}
22129 			*excess = NULL;
22130 			tcp_close_mpp(&tail);
22131 			if (tcp->tcp_snd_zcopy_aware)
22132 				tcp_zcopy_notify(tcp);
22133 		}
22134 		/*
22135 		 * We have no unsent data, so unsent must be less than
22136 		 * tcp_xmit_lowater, so re-enable flow.
22137 		 */
22138 		mutex_enter(&tcp->tcp_non_sq_lock);
22139 		if (tcp->tcp_flow_stopped) {
22140 			tcp_clrqfull(tcp);
22141 		}
22142 		mutex_exit(&tcp->tcp_non_sq_lock);
22143 	}
22144 	/*
22145 	 * TODO: you can't just flush these, you have to increase rwnd for one
22146 	 * thing.  For another, how should urgent data interact?
22147 	 */
22148 	if (fval & FLUSHR) {
22149 		*mp->b_rptr = fval & ~FLUSHW;
22150 		/* XXX */
22151 		qreply(q, mp);
22152 		return;
22153 	}
22154 	freemsg(mp);
22155 }
22156 
22157 /*
22158  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
22159  * messages.
22160  */
22161 static void
22162 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
22163 {
22164 	mblk_t	*mp1;
22165 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
22166 	STRUCT_HANDLE(strbuf, sb);
22167 	queue_t *q = tcp->tcp_wq;
22168 	int	error;
22169 	uint_t	addrlen;
22170 
22171 	/* Make sure it is one of ours. */
22172 	switch (iocp->ioc_cmd) {
22173 	case TI_GETMYNAME:
22174 	case TI_GETPEERNAME:
22175 		break;
22176 	default:
22177 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
22178 		return;
22179 	}
22180 	switch (mi_copy_state(q, mp, &mp1)) {
22181 	case -1:
22182 		return;
22183 	case MI_COPY_CASE(MI_COPY_IN, 1):
22184 		break;
22185 	case MI_COPY_CASE(MI_COPY_OUT, 1):
22186 		/* Copy out the strbuf. */
22187 		mi_copyout(q, mp);
22188 		return;
22189 	case MI_COPY_CASE(MI_COPY_OUT, 2):
22190 		/* All done. */
22191 		mi_copy_done(q, mp, 0);
22192 		return;
22193 	default:
22194 		mi_copy_done(q, mp, EPROTO);
22195 		return;
22196 	}
22197 	/* Check alignment of the strbuf */
22198 	if (!OK_32PTR(mp1->b_rptr)) {
22199 		mi_copy_done(q, mp, EINVAL);
22200 		return;
22201 	}
22202 
22203 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
22204 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
22205 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
22206 		mi_copy_done(q, mp, EINVAL);
22207 		return;
22208 	}
22209 
22210 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
22211 	if (mp1 == NULL)
22212 		return;
22213 
22214 	switch (iocp->ioc_cmd) {
22215 	case TI_GETMYNAME:
22216 		error = tcp_getmyname(tcp, (void *)mp1->b_rptr, &addrlen);
22217 		break;
22218 	case TI_GETPEERNAME:
22219 		error = i_tcp_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
22220 		break;
22221 	}
22222 
22223 	if (error != 0) {
22224 		mi_copy_done(q, mp, error);
22225 	} else {
22226 		mp1->b_wptr += addrlen;
22227 		STRUCT_FSET(sb, len, addrlen);
22228 
22229 		/* Copy out the address */
22230 		mi_copyout(q, mp);
22231 	}
22232 }
22233 
22234 static void
22235 tcp_disable_direct_sockfs(tcp_t *tcp)
22236 {
22237 #ifdef	_ILP32
22238 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
22239 #else
22240 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
22241 #endif
22242 	/*
22243 	 * Insert this socket into the acceptor hash.
22244 	 * We might need it for T_CONN_RES message
22245 	 */
22246 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
22247 
22248 	if (tcp->tcp_fused) {
22249 		/*
22250 		 * This is a fused loopback tcp; disable
22251 		 * read-side synchronous streams interface
22252 		 * and drain any queued data.  It is okay
22253 		 * to do this for non-synchronous streams
22254 		 * fused tcp as well.
22255 		 */
22256 		tcp_fuse_disable_pair(tcp, B_FALSE);
22257 	}
22258 	tcp->tcp_issocket = B_FALSE;
22259 	tcp->tcp_sodirect = NULL;
22260 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
22261 }
22262 
22263 /*
22264  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
22265  * messages.
22266  */
22267 /* ARGSUSED */
22268 static void
22269 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
22270 {
22271 	conn_t 	*connp = (conn_t *)arg;
22272 	tcp_t	*tcp = connp->conn_tcp;
22273 	queue_t	*q = tcp->tcp_wq;
22274 	struct iocblk	*iocp;
22275 
22276 	ASSERT(DB_TYPE(mp) == M_IOCTL);
22277 	/*
22278 	 * Try and ASSERT the minimum possible references on the
22279 	 * conn early enough. Since we are executing on write side,
22280 	 * the connection is obviously not detached and that means
22281 	 * there is a ref each for TCP and IP. Since we are behind
22282 	 * the squeue, the minimum references needed are 3. If the
22283 	 * conn is in classifier hash list, there should be an
22284 	 * extra ref for that (we check both the possibilities).
22285 	 */
22286 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22287 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22288 
22289 	iocp = (struct iocblk *)mp->b_rptr;
22290 	switch (iocp->ioc_cmd) {
22291 	case TCP_IOC_DEFAULT_Q:
22292 		/* Wants to be the default wq. */
22293 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
22294 			iocp->ioc_error = EPERM;
22295 			iocp->ioc_count = 0;
22296 			mp->b_datap->db_type = M_IOCACK;
22297 			qreply(q, mp);
22298 			return;
22299 		}
22300 		tcp_def_q_set(tcp, mp);
22301 		return;
22302 	case _SIOCSOCKFALLBACK:
22303 		/*
22304 		 * Either sockmod is about to be popped and the socket
22305 		 * would now be treated as a plain stream, or a module
22306 		 * is about to be pushed so we could no longer use read-
22307 		 * side synchronous streams for fused loopback tcp.
22308 		 * Drain any queued data and disable direct sockfs
22309 		 * interface from now on.
22310 		 */
22311 		if (!tcp->tcp_issocket) {
22312 			DB_TYPE(mp) = M_IOCNAK;
22313 			iocp->ioc_error = EINVAL;
22314 		} else {
22315 			tcp_disable_direct_sockfs(tcp);
22316 			DB_TYPE(mp) = M_IOCACK;
22317 			iocp->ioc_error = 0;
22318 		}
22319 		iocp->ioc_count = 0;
22320 		iocp->ioc_rval = 0;
22321 		qreply(q, mp);
22322 		return;
22323 	}
22324 	CALL_IP_WPUT(connp, q, mp);
22325 }
22326 
22327 /*
22328  * This routine is called by tcp_wput() to handle all TPI requests.
22329  */
22330 /* ARGSUSED */
22331 static void
22332 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22333 {
22334 	conn_t 	*connp = (conn_t *)arg;
22335 	tcp_t	*tcp = connp->conn_tcp;
22336 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22337 	uchar_t *rptr;
22338 	t_scalar_t type;
22339 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
22340 
22341 	/*
22342 	 * Try and ASSERT the minimum possible references on the
22343 	 * conn early enough. Since we are executing on write side,
22344 	 * the connection is obviously not detached and that means
22345 	 * there is a ref each for TCP and IP. Since we are behind
22346 	 * the squeue, the minimum references needed are 3. If the
22347 	 * conn is in classifier hash list, there should be an
22348 	 * extra ref for that (we check both the possibilities).
22349 	 */
22350 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22351 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22352 
22353 	rptr = mp->b_rptr;
22354 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22355 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22356 		type = ((union T_primitives *)rptr)->type;
22357 		if (type == T_EXDATA_REQ) {
22358 			tcp_output_urgent(connp, mp->b_cont, arg2);
22359 			freeb(mp);
22360 		} else if (type != T_DATA_REQ) {
22361 			goto non_urgent_data;
22362 		} else {
22363 			/* TODO: options, flags, ... from user */
22364 			/* Set length to zero for reclamation below */
22365 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22366 			freeb(mp);
22367 		}
22368 		return;
22369 	} else {
22370 		if (tcp->tcp_debug) {
22371 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22372 			    "tcp_wput_proto, dropping one...");
22373 		}
22374 		freemsg(mp);
22375 		return;
22376 	}
22377 
22378 non_urgent_data:
22379 
22380 	switch ((int)tprim->type) {
22381 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22382 		/*
22383 		 * save the kssl_ent_t from the next block, and convert this
22384 		 * back to a normal bind_req.
22385 		 */
22386 		if (mp->b_cont != NULL) {
22387 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22388 
22389 			if (tcp->tcp_kssl_ent != NULL) {
22390 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22391 				    KSSL_NO_PROXY);
22392 				tcp->tcp_kssl_ent = NULL;
22393 			}
22394 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22395 			    sizeof (kssl_ent_t));
22396 			kssl_hold_ent(tcp->tcp_kssl_ent);
22397 			freemsg(mp->b_cont);
22398 			mp->b_cont = NULL;
22399 		}
22400 		tprim->type = T_BIND_REQ;
22401 
22402 	/* FALLTHROUGH */
22403 	case O_T_BIND_REQ:	/* bind request */
22404 	case T_BIND_REQ:	/* new semantics bind request */
22405 		tcp_tpi_bind(tcp, mp);
22406 		break;
22407 	case T_UNBIND_REQ:	/* unbind request */
22408 		tcp_tpi_unbind(tcp, mp);
22409 		break;
22410 	case O_T_CONN_RES:	/* old connection response XXX */
22411 	case T_CONN_RES:	/* connection response */
22412 		tcp_tli_accept(tcp, mp);
22413 		break;
22414 	case T_CONN_REQ:	/* connection request */
22415 		tcp_tpi_connect(tcp, mp);
22416 		break;
22417 	case T_DISCON_REQ:	/* disconnect request */
22418 		tcp_disconnect(tcp, mp);
22419 		break;
22420 	case T_CAPABILITY_REQ:
22421 		tcp_capability_req(tcp, mp);	/* capability request */
22422 		break;
22423 	case T_INFO_REQ:	/* information request */
22424 		tcp_info_req(tcp, mp);
22425 		break;
22426 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22427 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr,
22428 		    &tcp_opt_obj, B_TRUE);
22429 		break;
22430 	case T_OPTMGMT_REQ:
22431 		/*
22432 		 * Note:  no support for snmpcom_req() through new
22433 		 * T_OPTMGMT_REQ. See comments in ip.c
22434 		 */
22435 		/* Only IP is allowed to return meaningful value */
22436 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22437 		    B_TRUE);
22438 		break;
22439 
22440 	case T_UNITDATA_REQ:	/* unitdata request */
22441 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22442 		break;
22443 	case T_ORDREL_REQ:	/* orderly release req */
22444 		freemsg(mp);
22445 
22446 		if (tcp->tcp_fused)
22447 			tcp_unfuse(tcp);
22448 
22449 		if (tcp_xmit_end(tcp) != 0) {
22450 			/*
22451 			 * We were crossing FINs and got a reset from
22452 			 * the other side. Just ignore it.
22453 			 */
22454 			if (tcp->tcp_debug) {
22455 				(void) strlog(TCP_MOD_ID, 0, 1,
22456 				    SL_ERROR|SL_TRACE,
22457 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22458 				    "state %s",
22459 				    tcp_display(tcp, NULL,
22460 				    DISP_ADDR_AND_PORT));
22461 			}
22462 		}
22463 		break;
22464 	case T_ADDR_REQ:
22465 		tcp_addr_req(tcp, mp);
22466 		break;
22467 	default:
22468 		if (tcp->tcp_debug) {
22469 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22470 			    "tcp_wput_proto, bogus TPI msg, type %d",
22471 			    tprim->type);
22472 		}
22473 		/*
22474 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22475 		 * to recover.
22476 		 */
22477 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22478 		break;
22479 	}
22480 }
22481 
22482 /*
22483  * The TCP write service routine should never be called...
22484  */
22485 /* ARGSUSED */
22486 static void
22487 tcp_wsrv(queue_t *q)
22488 {
22489 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22490 
22491 	TCP_STAT(tcps, tcp_wsrv_called);
22492 }
22493 
22494 /* Non overlapping byte exchanger */
22495 static void
22496 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22497 {
22498 	uchar_t	uch;
22499 
22500 	while (len-- > 0) {
22501 		uch = a[len];
22502 		a[len] = b[len];
22503 		b[len] = uch;
22504 	}
22505 }
22506 
22507 /*
22508  * Send out a control packet on the tcp connection specified.  This routine
22509  * is typically called where we need a simple ACK or RST generated.
22510  */
22511 static void
22512 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22513 {
22514 	uchar_t		*rptr;
22515 	tcph_t		*tcph;
22516 	ipha_t		*ipha = NULL;
22517 	ip6_t		*ip6h = NULL;
22518 	uint32_t	sum;
22519 	int		tcp_hdr_len;
22520 	int		tcp_ip_hdr_len;
22521 	mblk_t		*mp;
22522 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22523 
22524 	/*
22525 	 * Save sum for use in source route later.
22526 	 */
22527 	ASSERT(tcp != NULL);
22528 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22529 	tcp_hdr_len = tcp->tcp_hdr_len;
22530 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22531 
22532 	/* If a text string is passed in with the request, pass it to strlog. */
22533 	if (str != NULL && tcp->tcp_debug) {
22534 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22535 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22536 		    str, seq, ack, ctl);
22537 	}
22538 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22539 	    BPRI_MED);
22540 	if (mp == NULL) {
22541 		return;
22542 	}
22543 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22544 	mp->b_rptr = rptr;
22545 	mp->b_wptr = &rptr[tcp_hdr_len];
22546 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22547 
22548 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22549 		ipha = (ipha_t *)rptr;
22550 		ipha->ipha_length = htons(tcp_hdr_len);
22551 	} else {
22552 		ip6h = (ip6_t *)rptr;
22553 		ASSERT(tcp != NULL);
22554 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22555 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22556 	}
22557 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22558 	tcph->th_flags[0] = (uint8_t)ctl;
22559 	if (ctl & TH_RST) {
22560 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22561 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22562 		/*
22563 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22564 		 */
22565 		if (tcp->tcp_snd_ts_ok &&
22566 		    tcp->tcp_state > TCPS_SYN_SENT) {
22567 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22568 			*(mp->b_wptr) = TCPOPT_EOL;
22569 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22570 				ipha->ipha_length = htons(tcp_hdr_len -
22571 				    TCPOPT_REAL_TS_LEN);
22572 			} else {
22573 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22574 				    TCPOPT_REAL_TS_LEN);
22575 			}
22576 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22577 			sum -= TCPOPT_REAL_TS_LEN;
22578 		}
22579 	}
22580 	if (ctl & TH_ACK) {
22581 		if (tcp->tcp_snd_ts_ok) {
22582 			U32_TO_BE32(lbolt,
22583 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22584 			U32_TO_BE32(tcp->tcp_ts_recent,
22585 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22586 		}
22587 
22588 		/* Update the latest receive window size in TCP header. */
22589 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22590 		    tcph->th_win);
22591 		tcp->tcp_rack = ack;
22592 		tcp->tcp_rack_cnt = 0;
22593 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22594 	}
22595 	BUMP_LOCAL(tcp->tcp_obsegs);
22596 	U32_TO_BE32(seq, tcph->th_seq);
22597 	U32_TO_BE32(ack, tcph->th_ack);
22598 	/*
22599 	 * Include the adjustment for a source route if any.
22600 	 */
22601 	sum = (sum >> 16) + (sum & 0xFFFF);
22602 	U16_TO_BE16(sum, tcph->th_sum);
22603 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22604 }
22605 
22606 /*
22607  * If this routine returns B_TRUE, TCP can generate a RST in response
22608  * to a segment.  If it returns B_FALSE, TCP should not respond.
22609  */
22610 static boolean_t
22611 tcp_send_rst_chk(tcp_stack_t *tcps)
22612 {
22613 	clock_t	now;
22614 
22615 	/*
22616 	 * TCP needs to protect itself from generating too many RSTs.
22617 	 * This can be a DoS attack by sending us random segments
22618 	 * soliciting RSTs.
22619 	 *
22620 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22621 	 * in each 1 second interval.  In this way, TCP still generate
22622 	 * RSTs in normal cases but when under attack, the impact is
22623 	 * limited.
22624 	 */
22625 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22626 		now = lbolt;
22627 		/* lbolt can wrap around. */
22628 		if ((tcps->tcps_last_rst_intrvl > now) ||
22629 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22630 		    1*SECONDS)) {
22631 			tcps->tcps_last_rst_intrvl = now;
22632 			tcps->tcps_rst_cnt = 1;
22633 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22634 			return (B_FALSE);
22635 		}
22636 	}
22637 	return (B_TRUE);
22638 }
22639 
22640 /*
22641  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22642  */
22643 static void
22644 tcp_ip_ire_mark_advice(tcp_t *tcp)
22645 {
22646 	mblk_t *mp;
22647 	ipic_t *ipic;
22648 
22649 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22650 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22651 		    &ipic);
22652 	} else {
22653 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22654 		    &ipic);
22655 	}
22656 	if (mp == NULL)
22657 		return;
22658 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22659 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22660 }
22661 
22662 /*
22663  * Return an IP advice ioctl mblk and set ipic to be the pointer
22664  * to the advice structure.
22665  */
22666 static mblk_t *
22667 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22668 {
22669 	struct iocblk *ioc;
22670 	mblk_t *mp, *mp1;
22671 
22672 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22673 	if (mp == NULL)
22674 		return (NULL);
22675 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22676 	*ipic = (ipic_t *)mp->b_rptr;
22677 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22678 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22679 
22680 	bcopy(addr, *ipic + 1, addr_len);
22681 
22682 	(*ipic)->ipic_addr_length = addr_len;
22683 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22684 
22685 	mp1 = mkiocb(IP_IOCTL);
22686 	if (mp1 == NULL) {
22687 		freemsg(mp);
22688 		return (NULL);
22689 	}
22690 	mp1->b_cont = mp;
22691 	ioc = (struct iocblk *)mp1->b_rptr;
22692 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22693 
22694 	return (mp1);
22695 }
22696 
22697 /*
22698  * Generate a reset based on an inbound packet, connp is set by caller
22699  * when RST is in response to an unexpected inbound packet for which
22700  * there is active tcp state in the system.
22701  *
22702  * IPSEC NOTE : Try to send the reply with the same protection as it came
22703  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22704  * the packet will go out at the same level of protection as it came in by
22705  * converting the IPSEC_IN to IPSEC_OUT.
22706  */
22707 static void
22708 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22709     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22710     tcp_stack_t *tcps, conn_t *connp)
22711 {
22712 	ipha_t		*ipha = NULL;
22713 	ip6_t		*ip6h = NULL;
22714 	ushort_t	len;
22715 	tcph_t		*tcph;
22716 	int		i;
22717 	mblk_t		*ipsec_mp;
22718 	boolean_t	mctl_present;
22719 	ipic_t		*ipic;
22720 	ipaddr_t	v4addr;
22721 	in6_addr_t	v6addr;
22722 	int		addr_len;
22723 	void		*addr;
22724 	queue_t		*q = tcps->tcps_g_q;
22725 	tcp_t		*tcp;
22726 	cred_t		*cr;
22727 	mblk_t		*nmp;
22728 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22729 
22730 	if (tcps->tcps_g_q == NULL) {
22731 		/*
22732 		 * For non-zero stackids the default queue isn't created
22733 		 * until the first open, thus there can be a need to send
22734 		 * a reset before then. But we can't do that, hence we just
22735 		 * drop the packet. Later during boot, when the default queue
22736 		 * has been setup, a retransmitted packet from the peer
22737 		 * will result in a reset.
22738 		 */
22739 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22740 		    GLOBAL_NETSTACKID);
22741 		freemsg(mp);
22742 		return;
22743 	}
22744 
22745 	if (connp != NULL)
22746 		tcp = connp->conn_tcp;
22747 	else
22748 		tcp = Q_TO_TCP(q);
22749 
22750 	if (!tcp_send_rst_chk(tcps)) {
22751 		tcps->tcps_rst_unsent++;
22752 		freemsg(mp);
22753 		return;
22754 	}
22755 
22756 	if (mp->b_datap->db_type == M_CTL) {
22757 		ipsec_mp = mp;
22758 		mp = mp->b_cont;
22759 		mctl_present = B_TRUE;
22760 	} else {
22761 		ipsec_mp = mp;
22762 		mctl_present = B_FALSE;
22763 	}
22764 
22765 	if (str && q && tcps->tcps_dbg) {
22766 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22767 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22768 		    "flags 0x%x",
22769 		    str, seq, ack, ctl);
22770 	}
22771 	if (mp->b_datap->db_ref != 1) {
22772 		mblk_t *mp1 = copyb(mp);
22773 		freemsg(mp);
22774 		mp = mp1;
22775 		if (!mp) {
22776 			if (mctl_present)
22777 				freeb(ipsec_mp);
22778 			return;
22779 		} else {
22780 			if (mctl_present) {
22781 				ipsec_mp->b_cont = mp;
22782 			} else {
22783 				ipsec_mp = mp;
22784 			}
22785 		}
22786 	} else if (mp->b_cont) {
22787 		freemsg(mp->b_cont);
22788 		mp->b_cont = NULL;
22789 	}
22790 	/*
22791 	 * We skip reversing source route here.
22792 	 * (for now we replace all IP options with EOL)
22793 	 */
22794 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22795 		ipha = (ipha_t *)mp->b_rptr;
22796 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22797 			mp->b_rptr[i] = IPOPT_EOL;
22798 		/*
22799 		 * Make sure that src address isn't flagrantly invalid.
22800 		 * Not all broadcast address checking for the src address
22801 		 * is possible, since we don't know the netmask of the src
22802 		 * addr.  No check for destination address is done, since
22803 		 * IP will not pass up a packet with a broadcast dest
22804 		 * address to TCP.  Similar checks are done below for IPv6.
22805 		 */
22806 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22807 		    CLASSD(ipha->ipha_src)) {
22808 			freemsg(ipsec_mp);
22809 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22810 			return;
22811 		}
22812 	} else {
22813 		ip6h = (ip6_t *)mp->b_rptr;
22814 
22815 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22816 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22817 			freemsg(ipsec_mp);
22818 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22819 			return;
22820 		}
22821 
22822 		/* Remove any extension headers assuming partial overlay */
22823 		if (ip_hdr_len > IPV6_HDR_LEN) {
22824 			uint8_t *to;
22825 
22826 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22827 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22828 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22829 			ip_hdr_len = IPV6_HDR_LEN;
22830 			ip6h = (ip6_t *)mp->b_rptr;
22831 			ip6h->ip6_nxt = IPPROTO_TCP;
22832 		}
22833 	}
22834 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22835 	if (tcph->th_flags[0] & TH_RST) {
22836 		freemsg(ipsec_mp);
22837 		return;
22838 	}
22839 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22840 	len = ip_hdr_len + sizeof (tcph_t);
22841 	mp->b_wptr = &mp->b_rptr[len];
22842 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22843 		ipha->ipha_length = htons(len);
22844 		/* Swap addresses */
22845 		v4addr = ipha->ipha_src;
22846 		ipha->ipha_src = ipha->ipha_dst;
22847 		ipha->ipha_dst = v4addr;
22848 		ipha->ipha_ident = 0;
22849 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22850 		addr_len = IP_ADDR_LEN;
22851 		addr = &v4addr;
22852 	} else {
22853 		/* No ip6i_t in this case */
22854 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22855 		/* Swap addresses */
22856 		v6addr = ip6h->ip6_src;
22857 		ip6h->ip6_src = ip6h->ip6_dst;
22858 		ip6h->ip6_dst = v6addr;
22859 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22860 		addr_len = IPV6_ADDR_LEN;
22861 		addr = &v6addr;
22862 	}
22863 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22864 	U32_TO_BE32(ack, tcph->th_ack);
22865 	U32_TO_BE32(seq, tcph->th_seq);
22866 	U16_TO_BE16(0, tcph->th_win);
22867 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22868 	tcph->th_flags[0] = (uint8_t)ctl;
22869 	if (ctl & TH_RST) {
22870 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22871 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22872 	}
22873 
22874 	/* IP trusts us to set up labels when required. */
22875 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
22876 	    crgetlabel(cr) != NULL) {
22877 		int err;
22878 
22879 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22880 			err = tsol_check_label(cr, &mp,
22881 			    tcp->tcp_connp->conn_mac_exempt,
22882 			    tcps->tcps_netstack->netstack_ip);
22883 		else
22884 			err = tsol_check_label_v6(cr, &mp,
22885 			    tcp->tcp_connp->conn_mac_exempt,
22886 			    tcps->tcps_netstack->netstack_ip);
22887 		if (mctl_present)
22888 			ipsec_mp->b_cont = mp;
22889 		else
22890 			ipsec_mp = mp;
22891 		if (err != 0) {
22892 			freemsg(ipsec_mp);
22893 			return;
22894 		}
22895 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22896 			ipha = (ipha_t *)mp->b_rptr;
22897 		} else {
22898 			ip6h = (ip6_t *)mp->b_rptr;
22899 		}
22900 	}
22901 
22902 	if (mctl_present) {
22903 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22904 
22905 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22906 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22907 			return;
22908 		}
22909 	}
22910 	if (zoneid == ALL_ZONES)
22911 		zoneid = GLOBAL_ZONEID;
22912 
22913 	/* Add the zoneid so ip_output routes it properly */
22914 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22915 		freemsg(ipsec_mp);
22916 		return;
22917 	}
22918 	ipsec_mp = nmp;
22919 
22920 	/*
22921 	 * NOTE:  one might consider tracing a TCP packet here, but
22922 	 * this function has no active TCP state and no tcp structure
22923 	 * that has a trace buffer.  If we traced here, we would have
22924 	 * to keep a local trace buffer in tcp_record_trace().
22925 	 *
22926 	 * TSol note: The mblk that contains the incoming packet was
22927 	 * reused by tcp_xmit_listener_reset, so it already contains
22928 	 * the right credentials and we don't need to call mblk_setcred.
22929 	 * Also the conn's cred is not right since it is associated
22930 	 * with tcps_g_q.
22931 	 */
22932 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22933 
22934 	/*
22935 	 * Tell IP to mark the IRE used for this destination temporary.
22936 	 * This way, we can limit our exposure to DoS attack because IP
22937 	 * creates an IRE for each destination.  If there are too many,
22938 	 * the time to do any routing lookup will be extremely long.  And
22939 	 * the lookup can be in interrupt context.
22940 	 *
22941 	 * Note that in normal circumstances, this marking should not
22942 	 * affect anything.  It would be nice if only 1 message is
22943 	 * needed to inform IP that the IRE created for this RST should
22944 	 * not be added to the cache table.  But there is currently
22945 	 * not such communication mechanism between TCP and IP.  So
22946 	 * the best we can do now is to send the advice ioctl to IP
22947 	 * to mark the IRE temporary.
22948 	 */
22949 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22950 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22951 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22952 	}
22953 }
22954 
22955 /*
22956  * Initiate closedown sequence on an active connection.  (May be called as
22957  * writer.)  Return value zero for OK return, non-zero for error return.
22958  */
22959 static int
22960 tcp_xmit_end(tcp_t *tcp)
22961 {
22962 	ipic_t	*ipic;
22963 	mblk_t	*mp;
22964 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22965 
22966 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22967 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22968 		/*
22969 		 * Invalid state, only states TCPS_SYN_RCVD,
22970 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22971 		 */
22972 		return (-1);
22973 	}
22974 
22975 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22976 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22977 	/*
22978 	 * If there is nothing more unsent, send the FIN now.
22979 	 * Otherwise, it will go out with the last segment.
22980 	 */
22981 	if (tcp->tcp_unsent == 0) {
22982 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22983 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22984 
22985 		if (mp) {
22986 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22987 		} else {
22988 			/*
22989 			 * Couldn't allocate msg.  Pretend we got it out.
22990 			 * Wait for rexmit timeout.
22991 			 */
22992 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22993 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22994 		}
22995 
22996 		/*
22997 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22998 		 * changed.
22999 		 */
23000 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
23001 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23002 		}
23003 	} else {
23004 		/*
23005 		 * If tcp->tcp_cork is set, then the data will not get sent,
23006 		 * so we have to check that and unset it first.
23007 		 */
23008 		if (tcp->tcp_cork)
23009 			tcp->tcp_cork = B_FALSE;
23010 		tcp_wput_data(tcp, NULL, B_FALSE);
23011 	}
23012 
23013 	/*
23014 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
23015 	 * is 0, don't update the cache.
23016 	 */
23017 	if (tcps->tcps_rtt_updates == 0 ||
23018 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
23019 		return (0);
23020 
23021 	/*
23022 	 * NOTE: should not update if source routes i.e. if tcp_remote if
23023 	 * different from the destination.
23024 	 */
23025 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23026 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
23027 			return (0);
23028 		}
23029 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
23030 		    &ipic);
23031 	} else {
23032 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
23033 		    &tcp->tcp_ip6h->ip6_dst))) {
23034 			return (0);
23035 		}
23036 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
23037 		    &ipic);
23038 	}
23039 
23040 	/* Record route attributes in the IRE for use by future connections. */
23041 	if (mp == NULL)
23042 		return (0);
23043 
23044 	/*
23045 	 * We do not have a good algorithm to update ssthresh at this time.
23046 	 * So don't do any update.
23047 	 */
23048 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
23049 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
23050 
23051 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23052 
23053 	return (0);
23054 }
23055 
23056 /*
23057  * Generate a "no listener here" RST in response to an "unknown" segment.
23058  * connp is set by caller when RST is in response to an unexpected
23059  * inbound packet for which there is active tcp state in the system.
23060  * Note that we are reusing the incoming mp to construct the outgoing RST.
23061  */
23062 void
23063 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
23064     tcp_stack_t *tcps, conn_t *connp)
23065 {
23066 	uchar_t		*rptr;
23067 	uint32_t	seg_len;
23068 	tcph_t		*tcph;
23069 	uint32_t	seg_seq;
23070 	uint32_t	seg_ack;
23071 	uint_t		flags;
23072 	mblk_t		*ipsec_mp;
23073 	ipha_t 		*ipha;
23074 	ip6_t 		*ip6h;
23075 	boolean_t	mctl_present = B_FALSE;
23076 	boolean_t	check = B_TRUE;
23077 	boolean_t	policy_present;
23078 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
23079 
23080 	TCP_STAT(tcps, tcp_no_listener);
23081 
23082 	ipsec_mp = mp;
23083 
23084 	if (mp->b_datap->db_type == M_CTL) {
23085 		ipsec_in_t *ii;
23086 
23087 		mctl_present = B_TRUE;
23088 		mp = mp->b_cont;
23089 
23090 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23091 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23092 		if (ii->ipsec_in_dont_check) {
23093 			check = B_FALSE;
23094 			if (!ii->ipsec_in_secure) {
23095 				freeb(ipsec_mp);
23096 				mctl_present = B_FALSE;
23097 				ipsec_mp = mp;
23098 			}
23099 		}
23100 	}
23101 
23102 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23103 		policy_present = ipss->ipsec_inbound_v4_policy_present;
23104 		ipha = (ipha_t *)mp->b_rptr;
23105 		ip6h = NULL;
23106 	} else {
23107 		policy_present = ipss->ipsec_inbound_v6_policy_present;
23108 		ipha = NULL;
23109 		ip6h = (ip6_t *)mp->b_rptr;
23110 	}
23111 
23112 	if (check && policy_present) {
23113 		/*
23114 		 * The conn_t parameter is NULL because we already know
23115 		 * nobody's home.
23116 		 */
23117 		ipsec_mp = ipsec_check_global_policy(
23118 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
23119 		    tcps->tcps_netstack);
23120 		if (ipsec_mp == NULL)
23121 			return;
23122 	}
23123 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
23124 		DTRACE_PROBE2(
23125 		    tx__ip__log__error__nolistener__tcp,
23126 		    char *, "Could not reply with RST to mp(1)",
23127 		    mblk_t *, mp);
23128 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
23129 		freemsg(ipsec_mp);
23130 		return;
23131 	}
23132 
23133 	rptr = mp->b_rptr;
23134 
23135 	tcph = (tcph_t *)&rptr[ip_hdr_len];
23136 	seg_seq = BE32_TO_U32(tcph->th_seq);
23137 	seg_ack = BE32_TO_U32(tcph->th_ack);
23138 	flags = tcph->th_flags[0];
23139 
23140 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
23141 	if (flags & TH_RST) {
23142 		freemsg(ipsec_mp);
23143 	} else if (flags & TH_ACK) {
23144 		tcp_xmit_early_reset("no tcp, reset",
23145 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
23146 		    connp);
23147 	} else {
23148 		if (flags & TH_SYN) {
23149 			seg_len++;
23150 		} else {
23151 			/*
23152 			 * Here we violate the RFC.  Note that a normal
23153 			 * TCP will never send a segment without the ACK
23154 			 * flag, except for RST or SYN segment.  This
23155 			 * segment is neither.  Just drop it on the
23156 			 * floor.
23157 			 */
23158 			freemsg(ipsec_mp);
23159 			tcps->tcps_rst_unsent++;
23160 			return;
23161 		}
23162 
23163 		tcp_xmit_early_reset("no tcp, reset/ack",
23164 		    ipsec_mp, 0, seg_seq + seg_len,
23165 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
23166 	}
23167 }
23168 
23169 /*
23170  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
23171  * ip and tcp header ready to pass down to IP.  If the mp passed in is
23172  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
23173  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
23174  * otherwise it will dup partial mblks.)
23175  * Otherwise, an appropriate ACK packet will be generated.  This
23176  * routine is not usually called to send new data for the first time.  It
23177  * is mostly called out of the timer for retransmits, and to generate ACKs.
23178  *
23179  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
23180  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
23181  * of the original mblk chain will be returned in *offset and *end_mp.
23182  */
23183 mblk_t *
23184 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
23185     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
23186     boolean_t rexmit)
23187 {
23188 	int	data_length;
23189 	int32_t	off = 0;
23190 	uint_t	flags;
23191 	mblk_t	*mp1;
23192 	mblk_t	*mp2;
23193 	uchar_t	*rptr;
23194 	tcph_t	*tcph;
23195 	int32_t	num_sack_blk = 0;
23196 	int32_t	sack_opt_len = 0;
23197 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23198 
23199 	/* Allocate for our maximum TCP header + link-level */
23200 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
23201 	    tcps->tcps_wroff_xtra, BPRI_MED);
23202 	if (!mp1)
23203 		return (NULL);
23204 	data_length = 0;
23205 
23206 	/*
23207 	 * Note that tcp_mss has been adjusted to take into account the
23208 	 * timestamp option if applicable.  Because SACK options do not
23209 	 * appear in every TCP segments and they are of variable lengths,
23210 	 * they cannot be included in tcp_mss.  Thus we need to calculate
23211 	 * the actual segment length when we need to send a segment which
23212 	 * includes SACK options.
23213 	 */
23214 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23215 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23216 		    tcp->tcp_num_sack_blk);
23217 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23218 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23219 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
23220 			max_to_send -= sack_opt_len;
23221 	}
23222 
23223 	if (offset != NULL) {
23224 		off = *offset;
23225 		/* We use offset as an indicator that end_mp is not NULL. */
23226 		*end_mp = NULL;
23227 	}
23228 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
23229 		/* This could be faster with cooperation from downstream */
23230 		if (mp2 != mp1 && !sendall &&
23231 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
23232 		    max_to_send)
23233 			/*
23234 			 * Don't send the next mblk since the whole mblk
23235 			 * does not fit.
23236 			 */
23237 			break;
23238 		mp2->b_cont = dupb(mp);
23239 		mp2 = mp2->b_cont;
23240 		if (!mp2) {
23241 			freemsg(mp1);
23242 			return (NULL);
23243 		}
23244 		mp2->b_rptr += off;
23245 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
23246 		    (uintptr_t)INT_MAX);
23247 
23248 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
23249 		if (data_length > max_to_send) {
23250 			mp2->b_wptr -= data_length - max_to_send;
23251 			data_length = max_to_send;
23252 			off = mp2->b_wptr - mp->b_rptr;
23253 			break;
23254 		} else {
23255 			off = 0;
23256 		}
23257 	}
23258 	if (offset != NULL) {
23259 		*offset = off;
23260 		*end_mp = mp;
23261 	}
23262 	if (seg_len != NULL) {
23263 		*seg_len = data_length;
23264 	}
23265 
23266 	/* Update the latest receive window size in TCP header. */
23267 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23268 	    tcp->tcp_tcph->th_win);
23269 
23270 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23271 	mp1->b_rptr = rptr;
23272 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
23273 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23274 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23275 	U32_TO_ABE32(seq, tcph->th_seq);
23276 
23277 	/*
23278 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
23279 	 * that this function was called from tcp_wput_data. Thus, when called
23280 	 * to retransmit data the setting of the PUSH bit may appear some
23281 	 * what random in that it might get set when it should not. This
23282 	 * should not pose any performance issues.
23283 	 */
23284 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
23285 	    tcp->tcp_unsent == data_length)) {
23286 		flags = TH_ACK | TH_PUSH;
23287 	} else {
23288 		flags = TH_ACK;
23289 	}
23290 
23291 	if (tcp->tcp_ecn_ok) {
23292 		if (tcp->tcp_ecn_echo_on)
23293 			flags |= TH_ECE;
23294 
23295 		/*
23296 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
23297 		 * There is no TCP flow control for non-data segments, and
23298 		 * only data segment is transmitted reliably.
23299 		 */
23300 		if (data_length > 0 && !rexmit) {
23301 			SET_ECT(tcp, rptr);
23302 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23303 				flags |= TH_CWR;
23304 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23305 			}
23306 		}
23307 	}
23308 
23309 	if (tcp->tcp_valid_bits) {
23310 		uint32_t u1;
23311 
23312 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23313 		    seq == tcp->tcp_iss) {
23314 			uchar_t	*wptr;
23315 
23316 			/*
23317 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23318 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23319 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23320 			 * our SYN is not ack'ed but the app closes this
23321 			 * TCP connection.
23322 			 */
23323 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23324 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23325 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23326 
23327 			/*
23328 			 * Tack on the MSS option.  It is always needed
23329 			 * for both active and passive open.
23330 			 *
23331 			 * MSS option value should be interface MTU - MIN
23332 			 * TCP/IP header according to RFC 793 as it means
23333 			 * the maximum segment size TCP can receive.  But
23334 			 * to get around some broken middle boxes/end hosts
23335 			 * out there, we allow the option value to be the
23336 			 * same as the MSS option size on the peer side.
23337 			 * In this way, the other side will not send
23338 			 * anything larger than they can receive.
23339 			 *
23340 			 * Note that for SYN_SENT state, the ndd param
23341 			 * tcp_use_smss_as_mss_opt has no effect as we
23342 			 * don't know the peer's MSS option value. So
23343 			 * the only case we need to take care of is in
23344 			 * SYN_RCVD state, which is done later.
23345 			 */
23346 			wptr = mp1->b_wptr;
23347 			wptr[0] = TCPOPT_MAXSEG;
23348 			wptr[1] = TCPOPT_MAXSEG_LEN;
23349 			wptr += 2;
23350 			u1 = tcp->tcp_if_mtu -
23351 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23352 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23353 			    TCP_MIN_HEADER_LENGTH;
23354 			U16_TO_BE16(u1, wptr);
23355 			mp1->b_wptr = wptr + 2;
23356 			/* Update the offset to cover the additional word */
23357 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23358 
23359 			/*
23360 			 * Note that the following way of filling in
23361 			 * TCP options are not optimal.  Some NOPs can
23362 			 * be saved.  But there is no need at this time
23363 			 * to optimize it.  When it is needed, we will
23364 			 * do it.
23365 			 */
23366 			switch (tcp->tcp_state) {
23367 			case TCPS_SYN_SENT:
23368 				flags = TH_SYN;
23369 
23370 				if (tcp->tcp_snd_ts_ok) {
23371 					uint32_t llbolt = (uint32_t)lbolt;
23372 
23373 					wptr = mp1->b_wptr;
23374 					wptr[0] = TCPOPT_NOP;
23375 					wptr[1] = TCPOPT_NOP;
23376 					wptr[2] = TCPOPT_TSTAMP;
23377 					wptr[3] = TCPOPT_TSTAMP_LEN;
23378 					wptr += 4;
23379 					U32_TO_BE32(llbolt, wptr);
23380 					wptr += 4;
23381 					ASSERT(tcp->tcp_ts_recent == 0);
23382 					U32_TO_BE32(0L, wptr);
23383 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23384 					tcph->th_offset_and_rsrvd[0] +=
23385 					    (3 << 4);
23386 				}
23387 
23388 				/*
23389 				 * Set up all the bits to tell other side
23390 				 * we are ECN capable.
23391 				 */
23392 				if (tcp->tcp_ecn_ok) {
23393 					flags |= (TH_ECE | TH_CWR);
23394 				}
23395 				break;
23396 			case TCPS_SYN_RCVD:
23397 				flags |= TH_SYN;
23398 
23399 				/*
23400 				 * Reset the MSS option value to be SMSS
23401 				 * We should probably add back the bytes
23402 				 * for timestamp option and IPsec.  We
23403 				 * don't do that as this is a workaround
23404 				 * for broken middle boxes/end hosts, it
23405 				 * is better for us to be more cautious.
23406 				 * They may not take these things into
23407 				 * account in their SMSS calculation.  Thus
23408 				 * the peer's calculated SMSS may be smaller
23409 				 * than what it can be.  This should be OK.
23410 				 */
23411 				if (tcps->tcps_use_smss_as_mss_opt) {
23412 					u1 = tcp->tcp_mss;
23413 					U16_TO_BE16(u1, wptr);
23414 				}
23415 
23416 				/*
23417 				 * If the other side is ECN capable, reply
23418 				 * that we are also ECN capable.
23419 				 */
23420 				if (tcp->tcp_ecn_ok)
23421 					flags |= TH_ECE;
23422 				break;
23423 			default:
23424 				/*
23425 				 * The above ASSERT() makes sure that this
23426 				 * must be FIN-WAIT-1 state.  Our SYN has
23427 				 * not been ack'ed so retransmit it.
23428 				 */
23429 				flags |= TH_SYN;
23430 				break;
23431 			}
23432 
23433 			if (tcp->tcp_snd_ws_ok) {
23434 				wptr = mp1->b_wptr;
23435 				wptr[0] =  TCPOPT_NOP;
23436 				wptr[1] =  TCPOPT_WSCALE;
23437 				wptr[2] =  TCPOPT_WS_LEN;
23438 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23439 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23440 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23441 			}
23442 
23443 			if (tcp->tcp_snd_sack_ok) {
23444 				wptr = mp1->b_wptr;
23445 				wptr[0] = TCPOPT_NOP;
23446 				wptr[1] = TCPOPT_NOP;
23447 				wptr[2] = TCPOPT_SACK_PERMITTED;
23448 				wptr[3] = TCPOPT_SACK_OK_LEN;
23449 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23450 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23451 			}
23452 
23453 			/* allocb() of adequate mblk assures space */
23454 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23455 			    (uintptr_t)INT_MAX);
23456 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23457 			/*
23458 			 * Get IP set to checksum on our behalf
23459 			 * Include the adjustment for a source route if any.
23460 			 */
23461 			u1 += tcp->tcp_sum;
23462 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23463 			U16_TO_BE16(u1, tcph->th_sum);
23464 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23465 		}
23466 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23467 		    (seq + data_length) == tcp->tcp_fss) {
23468 			if (!tcp->tcp_fin_acked) {
23469 				flags |= TH_FIN;
23470 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23471 			}
23472 			if (!tcp->tcp_fin_sent) {
23473 				tcp->tcp_fin_sent = B_TRUE;
23474 				switch (tcp->tcp_state) {
23475 				case TCPS_SYN_RCVD:
23476 				case TCPS_ESTABLISHED:
23477 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23478 					break;
23479 				case TCPS_CLOSE_WAIT:
23480 					tcp->tcp_state = TCPS_LAST_ACK;
23481 					break;
23482 				}
23483 				if (tcp->tcp_suna == tcp->tcp_snxt)
23484 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23485 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23486 			}
23487 		}
23488 		/*
23489 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23490 		 * is smaller than seq, u1 will become a very huge value.
23491 		 * So the comparison will fail.  Also note that tcp_urp
23492 		 * should be positive, see RFC 793 page 17.
23493 		 */
23494 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23495 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23496 		    u1 < (uint32_t)(64 * 1024)) {
23497 			flags |= TH_URG;
23498 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23499 			U32_TO_ABE16(u1, tcph->th_urp);
23500 		}
23501 	}
23502 	tcph->th_flags[0] = (uchar_t)flags;
23503 	tcp->tcp_rack = tcp->tcp_rnxt;
23504 	tcp->tcp_rack_cnt = 0;
23505 
23506 	if (tcp->tcp_snd_ts_ok) {
23507 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23508 			uint32_t llbolt = (uint32_t)lbolt;
23509 
23510 			U32_TO_BE32(llbolt,
23511 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23512 			U32_TO_BE32(tcp->tcp_ts_recent,
23513 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23514 		}
23515 	}
23516 
23517 	if (num_sack_blk > 0) {
23518 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23519 		sack_blk_t *tmp;
23520 		int32_t	i;
23521 
23522 		wptr[0] = TCPOPT_NOP;
23523 		wptr[1] = TCPOPT_NOP;
23524 		wptr[2] = TCPOPT_SACK;
23525 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23526 		    sizeof (sack_blk_t);
23527 		wptr += TCPOPT_REAL_SACK_LEN;
23528 
23529 		tmp = tcp->tcp_sack_list;
23530 		for (i = 0; i < num_sack_blk; i++) {
23531 			U32_TO_BE32(tmp[i].begin, wptr);
23532 			wptr += sizeof (tcp_seq);
23533 			U32_TO_BE32(tmp[i].end, wptr);
23534 			wptr += sizeof (tcp_seq);
23535 		}
23536 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23537 	}
23538 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23539 	data_length += (int)(mp1->b_wptr - rptr);
23540 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23541 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23542 	} else {
23543 		ip6_t *ip6 = (ip6_t *)(rptr +
23544 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23545 		    sizeof (ip6i_t) : 0));
23546 
23547 		ip6->ip6_plen = htons(data_length -
23548 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23549 	}
23550 
23551 	/*
23552 	 * Prime pump for IP
23553 	 * Include the adjustment for a source route if any.
23554 	 */
23555 	data_length -= tcp->tcp_ip_hdr_len;
23556 	data_length += tcp->tcp_sum;
23557 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23558 	U16_TO_ABE16(data_length, tcph->th_sum);
23559 	if (tcp->tcp_ip_forward_progress) {
23560 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23561 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23562 		tcp->tcp_ip_forward_progress = B_FALSE;
23563 	}
23564 	return (mp1);
23565 }
23566 
23567 /* This function handles the push timeout. */
23568 void
23569 tcp_push_timer(void *arg)
23570 {
23571 	conn_t	*connp = (conn_t *)arg;
23572 	tcp_t *tcp = connp->conn_tcp;
23573 	uint_t		flags;
23574 	sodirect_t	*sodp;
23575 
23576 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
23577 
23578 	ASSERT(tcp->tcp_listener == NULL);
23579 
23580 	ASSERT(!IPCL_IS_NONSTR(connp));
23581 
23582 	/*
23583 	 * We need to plug synchronous streams during our drain to prevent
23584 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23585 	 */
23586 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23587 	tcp->tcp_push_tid = 0;
23588 
23589 	SOD_PTR_ENTER(tcp, sodp);
23590 	if (sodp != NULL) {
23591 		flags = tcp_rcv_sod_wakeup(tcp, sodp);
23592 		/* sod_wakeup() does the mutex_exit() */
23593 	} else if (tcp->tcp_rcv_list != NULL) {
23594 		flags = tcp_rcv_drain(tcp);
23595 	}
23596 	if (flags == TH_ACK_NEEDED)
23597 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23598 
23599 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23600 }
23601 
23602 /*
23603  * This function handles delayed ACK timeout.
23604  */
23605 static void
23606 tcp_ack_timer(void *arg)
23607 {
23608 	conn_t	*connp = (conn_t *)arg;
23609 	tcp_t *tcp = connp->conn_tcp;
23610 	mblk_t *mp;
23611 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23612 
23613 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23614 
23615 	tcp->tcp_ack_tid = 0;
23616 
23617 	if (tcp->tcp_fused)
23618 		return;
23619 
23620 	/*
23621 	 * Do not send ACK if there is no outstanding unack'ed data.
23622 	 */
23623 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23624 		return;
23625 	}
23626 
23627 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23628 		/*
23629 		 * Make sure we don't allow deferred ACKs to result in
23630 		 * timer-based ACKing.  If we have held off an ACK
23631 		 * when there was more than an mss here, and the timer
23632 		 * goes off, we have to worry about the possibility
23633 		 * that the sender isn't doing slow-start, or is out
23634 		 * of step with us for some other reason.  We fall
23635 		 * permanently back in the direction of
23636 		 * ACK-every-other-packet as suggested in RFC 1122.
23637 		 */
23638 		if (tcp->tcp_rack_abs_max > 2)
23639 			tcp->tcp_rack_abs_max--;
23640 		tcp->tcp_rack_cur_max = 2;
23641 	}
23642 	mp = tcp_ack_mp(tcp);
23643 
23644 	if (mp != NULL) {
23645 		BUMP_LOCAL(tcp->tcp_obsegs);
23646 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23647 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23648 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23649 	}
23650 }
23651 
23652 
23653 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23654 static mblk_t *
23655 tcp_ack_mp(tcp_t *tcp)
23656 {
23657 	uint32_t	seq_no;
23658 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23659 
23660 	/*
23661 	 * There are a few cases to be considered while setting the sequence no.
23662 	 * Essentially, we can come here while processing an unacceptable pkt
23663 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23664 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23665 	 * If we are here for a zero window probe, stick with suna. In all
23666 	 * other cases, we check if suna + swnd encompasses snxt and set
23667 	 * the sequence number to snxt, if so. If snxt falls outside the
23668 	 * window (the receiver probably shrunk its window), we will go with
23669 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23670 	 * receiver.
23671 	 */
23672 	if (tcp->tcp_zero_win_probe) {
23673 		seq_no = tcp->tcp_suna;
23674 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23675 		ASSERT(tcp->tcp_swnd == 0);
23676 		seq_no = tcp->tcp_snxt;
23677 	} else {
23678 		seq_no = SEQ_GT(tcp->tcp_snxt,
23679 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23680 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23681 	}
23682 
23683 	if (tcp->tcp_valid_bits) {
23684 		/*
23685 		 * For the complex case where we have to send some
23686 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23687 		 */
23688 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23689 		    NULL, B_FALSE));
23690 	} else {
23691 		/* Generate a simple ACK */
23692 		int	data_length;
23693 		uchar_t	*rptr;
23694 		tcph_t	*tcph;
23695 		mblk_t	*mp1;
23696 		int32_t	tcp_hdr_len;
23697 		int32_t	tcp_tcp_hdr_len;
23698 		int32_t	num_sack_blk = 0;
23699 		int32_t sack_opt_len;
23700 
23701 		/*
23702 		 * Allocate space for TCP + IP headers
23703 		 * and link-level header
23704 		 */
23705 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23706 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23707 			    tcp->tcp_num_sack_blk);
23708 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23709 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23710 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23711 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23712 		} else {
23713 			tcp_hdr_len = tcp->tcp_hdr_len;
23714 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23715 		}
23716 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23717 		if (!mp1)
23718 			return (NULL);
23719 
23720 		/* Update the latest receive window size in TCP header. */
23721 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23722 		    tcp->tcp_tcph->th_win);
23723 		/* copy in prototype TCP + IP header */
23724 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23725 		mp1->b_rptr = rptr;
23726 		mp1->b_wptr = rptr + tcp_hdr_len;
23727 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23728 
23729 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23730 
23731 		/* Set the TCP sequence number. */
23732 		U32_TO_ABE32(seq_no, tcph->th_seq);
23733 
23734 		/* Set up the TCP flag field. */
23735 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23736 		if (tcp->tcp_ecn_echo_on)
23737 			tcph->th_flags[0] |= TH_ECE;
23738 
23739 		tcp->tcp_rack = tcp->tcp_rnxt;
23740 		tcp->tcp_rack_cnt = 0;
23741 
23742 		/* fill in timestamp option if in use */
23743 		if (tcp->tcp_snd_ts_ok) {
23744 			uint32_t llbolt = (uint32_t)lbolt;
23745 
23746 			U32_TO_BE32(llbolt,
23747 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23748 			U32_TO_BE32(tcp->tcp_ts_recent,
23749 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23750 		}
23751 
23752 		/* Fill in SACK options */
23753 		if (num_sack_blk > 0) {
23754 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23755 			sack_blk_t *tmp;
23756 			int32_t	i;
23757 
23758 			wptr[0] = TCPOPT_NOP;
23759 			wptr[1] = TCPOPT_NOP;
23760 			wptr[2] = TCPOPT_SACK;
23761 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23762 			    sizeof (sack_blk_t);
23763 			wptr += TCPOPT_REAL_SACK_LEN;
23764 
23765 			tmp = tcp->tcp_sack_list;
23766 			for (i = 0; i < num_sack_blk; i++) {
23767 				U32_TO_BE32(tmp[i].begin, wptr);
23768 				wptr += sizeof (tcp_seq);
23769 				U32_TO_BE32(tmp[i].end, wptr);
23770 				wptr += sizeof (tcp_seq);
23771 			}
23772 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23773 			    << 4);
23774 		}
23775 
23776 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23777 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23778 		} else {
23779 			/* Check for ip6i_t header in sticky hdrs */
23780 			ip6_t *ip6 = (ip6_t *)(rptr +
23781 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23782 			    sizeof (ip6i_t) : 0));
23783 
23784 			ip6->ip6_plen = htons(tcp_hdr_len -
23785 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23786 		}
23787 
23788 		/*
23789 		 * Prime pump for checksum calculation in IP.  Include the
23790 		 * adjustment for a source route if any.
23791 		 */
23792 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23793 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23794 		U16_TO_ABE16(data_length, tcph->th_sum);
23795 
23796 		if (tcp->tcp_ip_forward_progress) {
23797 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23798 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23799 			tcp->tcp_ip_forward_progress = B_FALSE;
23800 		}
23801 		return (mp1);
23802 	}
23803 }
23804 
23805 /*
23806  * Hash list insertion routine for tcp_t structures. Each hash bucket
23807  * contains a list of tcp_t entries, and each entry is bound to a unique
23808  * port. If there are multiple tcp_t's that are bound to the same port, then
23809  * one of them will be linked into the hash bucket list, and the rest will
23810  * hang off of that one entry. For each port, entries bound to a specific IP
23811  * address will be inserted before those those bound to INADDR_ANY.
23812  */
23813 static void
23814 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23815 {
23816 	tcp_t	**tcpp;
23817 	tcp_t	*tcpnext;
23818 	tcp_t	*tcphash;
23819 
23820 	if (tcp->tcp_ptpbhn != NULL) {
23821 		ASSERT(!caller_holds_lock);
23822 		tcp_bind_hash_remove(tcp);
23823 	}
23824 	tcpp = &tbf->tf_tcp;
23825 	if (!caller_holds_lock) {
23826 		mutex_enter(&tbf->tf_lock);
23827 	} else {
23828 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23829 	}
23830 	tcphash = tcpp[0];
23831 	tcpnext = NULL;
23832 	if (tcphash != NULL) {
23833 		/* Look for an entry using the same port */
23834 		while ((tcphash = tcpp[0]) != NULL &&
23835 		    tcp->tcp_lport != tcphash->tcp_lport)
23836 			tcpp = &(tcphash->tcp_bind_hash);
23837 
23838 		/* The port was not found, just add to the end */
23839 		if (tcphash == NULL)
23840 			goto insert;
23841 
23842 		/*
23843 		 * OK, there already exists an entry bound to the
23844 		 * same port.
23845 		 *
23846 		 * If the new tcp bound to the INADDR_ANY address
23847 		 * and the first one in the list is not bound to
23848 		 * INADDR_ANY we skip all entries until we find the
23849 		 * first one bound to INADDR_ANY.
23850 		 * This makes sure that applications binding to a
23851 		 * specific address get preference over those binding to
23852 		 * INADDR_ANY.
23853 		 */
23854 		tcpnext = tcphash;
23855 		tcphash = NULL;
23856 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23857 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23858 			while ((tcpnext = tcpp[0]) != NULL &&
23859 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23860 				tcpp = &(tcpnext->tcp_bind_hash_port);
23861 
23862 			if (tcpnext) {
23863 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23864 				tcphash = tcpnext->tcp_bind_hash;
23865 				if (tcphash != NULL) {
23866 					tcphash->tcp_ptpbhn =
23867 					    &(tcp->tcp_bind_hash);
23868 					tcpnext->tcp_bind_hash = NULL;
23869 				}
23870 			}
23871 		} else {
23872 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23873 			tcphash = tcpnext->tcp_bind_hash;
23874 			if (tcphash != NULL) {
23875 				tcphash->tcp_ptpbhn =
23876 				    &(tcp->tcp_bind_hash);
23877 				tcpnext->tcp_bind_hash = NULL;
23878 			}
23879 		}
23880 	}
23881 insert:
23882 	tcp->tcp_bind_hash_port = tcpnext;
23883 	tcp->tcp_bind_hash = tcphash;
23884 	tcp->tcp_ptpbhn = tcpp;
23885 	tcpp[0] = tcp;
23886 	if (!caller_holds_lock)
23887 		mutex_exit(&tbf->tf_lock);
23888 }
23889 
23890 /*
23891  * Hash list removal routine for tcp_t structures.
23892  */
23893 static void
23894 tcp_bind_hash_remove(tcp_t *tcp)
23895 {
23896 	tcp_t	*tcpnext;
23897 	kmutex_t *lockp;
23898 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23899 
23900 	if (tcp->tcp_ptpbhn == NULL)
23901 		return;
23902 
23903 	/*
23904 	 * Extract the lock pointer in case there are concurrent
23905 	 * hash_remove's for this instance.
23906 	 */
23907 	ASSERT(tcp->tcp_lport != 0);
23908 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23909 
23910 	ASSERT(lockp != NULL);
23911 	mutex_enter(lockp);
23912 	if (tcp->tcp_ptpbhn) {
23913 		tcpnext = tcp->tcp_bind_hash_port;
23914 		if (tcpnext != NULL) {
23915 			tcp->tcp_bind_hash_port = NULL;
23916 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23917 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
23918 			if (tcpnext->tcp_bind_hash != NULL) {
23919 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
23920 				    &(tcpnext->tcp_bind_hash);
23921 				tcp->tcp_bind_hash = NULL;
23922 			}
23923 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
23924 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23925 			tcp->tcp_bind_hash = NULL;
23926 		}
23927 		*tcp->tcp_ptpbhn = tcpnext;
23928 		tcp->tcp_ptpbhn = NULL;
23929 	}
23930 	mutex_exit(lockp);
23931 }
23932 
23933 
23934 /*
23935  * Hash list lookup routine for tcp_t structures.
23936  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23937  */
23938 static tcp_t *
23939 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23940 {
23941 	tf_t	*tf;
23942 	tcp_t	*tcp;
23943 
23944 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23945 	mutex_enter(&tf->tf_lock);
23946 	for (tcp = tf->tf_tcp; tcp != NULL;
23947 	    tcp = tcp->tcp_acceptor_hash) {
23948 		if (tcp->tcp_acceptor_id == id) {
23949 			CONN_INC_REF(tcp->tcp_connp);
23950 			mutex_exit(&tf->tf_lock);
23951 			return (tcp);
23952 		}
23953 	}
23954 	mutex_exit(&tf->tf_lock);
23955 	return (NULL);
23956 }
23957 
23958 
23959 /*
23960  * Hash list insertion routine for tcp_t structures.
23961  */
23962 void
23963 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23964 {
23965 	tf_t	*tf;
23966 	tcp_t	**tcpp;
23967 	tcp_t	*tcpnext;
23968 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23969 
23970 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23971 
23972 	if (tcp->tcp_ptpahn != NULL)
23973 		tcp_acceptor_hash_remove(tcp);
23974 	tcpp = &tf->tf_tcp;
23975 	mutex_enter(&tf->tf_lock);
23976 	tcpnext = tcpp[0];
23977 	if (tcpnext)
23978 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23979 	tcp->tcp_acceptor_hash = tcpnext;
23980 	tcp->tcp_ptpahn = tcpp;
23981 	tcpp[0] = tcp;
23982 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23983 	mutex_exit(&tf->tf_lock);
23984 }
23985 
23986 /*
23987  * Hash list removal routine for tcp_t structures.
23988  */
23989 static void
23990 tcp_acceptor_hash_remove(tcp_t *tcp)
23991 {
23992 	tcp_t	*tcpnext;
23993 	kmutex_t *lockp;
23994 
23995 	/*
23996 	 * Extract the lock pointer in case there are concurrent
23997 	 * hash_remove's for this instance.
23998 	 */
23999 	lockp = tcp->tcp_acceptor_lockp;
24000 
24001 	if (tcp->tcp_ptpahn == NULL)
24002 		return;
24003 
24004 	ASSERT(lockp != NULL);
24005 	mutex_enter(lockp);
24006 	if (tcp->tcp_ptpahn) {
24007 		tcpnext = tcp->tcp_acceptor_hash;
24008 		if (tcpnext) {
24009 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
24010 			tcp->tcp_acceptor_hash = NULL;
24011 		}
24012 		*tcp->tcp_ptpahn = tcpnext;
24013 		tcp->tcp_ptpahn = NULL;
24014 	}
24015 	mutex_exit(lockp);
24016 	tcp->tcp_acceptor_lockp = NULL;
24017 }
24018 
24019 /* Data for fast netmask macro used by tcp_hsp_lookup */
24020 
24021 static ipaddr_t netmasks[] = {
24022 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24023 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24024 };
24025 
24026 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24027 
24028 /*
24029  * XXX This routine should go away and instead we should use the metrics
24030  * associated with the routes to determine the default sndspace and rcvspace.
24031  */
24032 static tcp_hsp_t *
24033 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24034 {
24035 	tcp_hsp_t *hsp = NULL;
24036 
24037 	/* Quick check without acquiring the lock. */
24038 	if (tcps->tcps_hsp_hash == NULL)
24039 		return (NULL);
24040 
24041 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24042 
24043 	/* This routine finds the best-matching HSP for address addr. */
24044 
24045 	if (tcps->tcps_hsp_hash) {
24046 		int i;
24047 		ipaddr_t srchaddr;
24048 		tcp_hsp_t *hsp_net;
24049 
24050 		/* We do three passes: host, network, and subnet. */
24051 
24052 		srchaddr = addr;
24053 
24054 		for (i = 1; i <= 3; i++) {
24055 			/* Look for exact match on srchaddr */
24056 
24057 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24058 			while (hsp) {
24059 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24060 				    hsp->tcp_hsp_addr == srchaddr)
24061 					break;
24062 				hsp = hsp->tcp_hsp_next;
24063 			}
24064 			ASSERT(hsp == NULL ||
24065 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24066 
24067 			/*
24068 			 * If this is the first pass:
24069 			 *   If we found a match, great, return it.
24070 			 *   If not, search for the network on the second pass.
24071 			 */
24072 
24073 			if (i == 1)
24074 				if (hsp)
24075 					break;
24076 				else
24077 				{
24078 					srchaddr = addr & netmask(addr);
24079 					continue;
24080 				}
24081 
24082 			/*
24083 			 * If this is the second pass:
24084 			 *   If we found a match, but there's a subnet mask,
24085 			 *    save the match but try again using the subnet
24086 			 *    mask on the third pass.
24087 			 *   Otherwise, return whatever we found.
24088 			 */
24089 
24090 			if (i == 2) {
24091 				if (hsp && hsp->tcp_hsp_subnet) {
24092 					hsp_net = hsp;
24093 					srchaddr = addr & hsp->tcp_hsp_subnet;
24094 					continue;
24095 				} else {
24096 					break;
24097 				}
24098 			}
24099 
24100 			/*
24101 			 * This must be the third pass.  If we didn't find
24102 			 * anything, return the saved network HSP instead.
24103 			 */
24104 
24105 			if (!hsp)
24106 				hsp = hsp_net;
24107 		}
24108 	}
24109 
24110 	rw_exit(&tcps->tcps_hsp_lock);
24111 	return (hsp);
24112 }
24113 
24114 /*
24115  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24116  * match lookup.
24117  */
24118 static tcp_hsp_t *
24119 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
24120 {
24121 	tcp_hsp_t *hsp = NULL;
24122 
24123 	/* Quick check without acquiring the lock. */
24124 	if (tcps->tcps_hsp_hash == NULL)
24125 		return (NULL);
24126 
24127 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24128 
24129 	/* This routine finds the best-matching HSP for address addr. */
24130 
24131 	if (tcps->tcps_hsp_hash) {
24132 		int i;
24133 		in6_addr_t v6srchaddr;
24134 		tcp_hsp_t *hsp_net;
24135 
24136 		/* We do three passes: host, network, and subnet. */
24137 
24138 		v6srchaddr = *v6addr;
24139 
24140 		for (i = 1; i <= 3; i++) {
24141 			/* Look for exact match on srchaddr */
24142 
24143 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
24144 			    V4_PART_OF_V6(v6srchaddr))];
24145 			while (hsp) {
24146 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24147 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24148 				    &v6srchaddr))
24149 					break;
24150 				hsp = hsp->tcp_hsp_next;
24151 			}
24152 
24153 			/*
24154 			 * If this is the first pass:
24155 			 *   If we found a match, great, return it.
24156 			 *   If not, search for the network on the second pass.
24157 			 */
24158 
24159 			if (i == 1)
24160 				if (hsp)
24161 					break;
24162 				else {
24163 					/* Assume a 64 bit mask */
24164 					v6srchaddr.s6_addr32[0] =
24165 					    v6addr->s6_addr32[0];
24166 					v6srchaddr.s6_addr32[1] =
24167 					    v6addr->s6_addr32[1];
24168 					v6srchaddr.s6_addr32[2] = 0;
24169 					v6srchaddr.s6_addr32[3] = 0;
24170 					continue;
24171 				}
24172 
24173 			/*
24174 			 * If this is the second pass:
24175 			 *   If we found a match, but there's a subnet mask,
24176 			 *    save the match but try again using the subnet
24177 			 *    mask on the third pass.
24178 			 *   Otherwise, return whatever we found.
24179 			 */
24180 
24181 			if (i == 2) {
24182 				ASSERT(hsp == NULL ||
24183 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24184 				if (hsp &&
24185 				    !IN6_IS_ADDR_UNSPECIFIED(
24186 				    &hsp->tcp_hsp_subnet_v6)) {
24187 					hsp_net = hsp;
24188 					V6_MASK_COPY(*v6addr,
24189 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24190 					continue;
24191 				} else {
24192 					break;
24193 				}
24194 			}
24195 
24196 			/*
24197 			 * This must be the third pass.  If we didn't find
24198 			 * anything, return the saved network HSP instead.
24199 			 */
24200 
24201 			if (!hsp)
24202 				hsp = hsp_net;
24203 		}
24204 	}
24205 
24206 	rw_exit(&tcps->tcps_hsp_lock);
24207 	return (hsp);
24208 }
24209 
24210 /*
24211  * Type three generator adapted from the random() function in 4.4 BSD:
24212  */
24213 
24214 /*
24215  * Copyright (c) 1983, 1993
24216  *	The Regents of the University of California.  All rights reserved.
24217  *
24218  * Redistribution and use in source and binary forms, with or without
24219  * modification, are permitted provided that the following conditions
24220  * are met:
24221  * 1. Redistributions of source code must retain the above copyright
24222  *    notice, this list of conditions and the following disclaimer.
24223  * 2. Redistributions in binary form must reproduce the above copyright
24224  *    notice, this list of conditions and the following disclaimer in the
24225  *    documentation and/or other materials provided with the distribution.
24226  * 3. All advertising materials mentioning features or use of this software
24227  *    must display the following acknowledgement:
24228  *	This product includes software developed by the University of
24229  *	California, Berkeley and its contributors.
24230  * 4. Neither the name of the University nor the names of its contributors
24231  *    may be used to endorse or promote products derived from this software
24232  *    without specific prior written permission.
24233  *
24234  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24235  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24236  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24237  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24238  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24239  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24240  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24241  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24242  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24243  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24244  * SUCH DAMAGE.
24245  */
24246 
24247 /* Type 3 -- x**31 + x**3 + 1 */
24248 #define	DEG_3		31
24249 #define	SEP_3		3
24250 
24251 
24252 /* Protected by tcp_random_lock */
24253 static int tcp_randtbl[DEG_3 + 1];
24254 
24255 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24256 static int *tcp_random_rptr = &tcp_randtbl[1];
24257 
24258 static int *tcp_random_state = &tcp_randtbl[1];
24259 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24260 
24261 kmutex_t tcp_random_lock;
24262 
24263 void
24264 tcp_random_init(void)
24265 {
24266 	int i;
24267 	hrtime_t hrt;
24268 	time_t wallclock;
24269 	uint64_t result;
24270 
24271 	/*
24272 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24273 	 * a longlong, which may contain resolution down to nanoseconds.
24274 	 * The current time will either be a 32-bit or a 64-bit quantity.
24275 	 * XOR the two together in a 64-bit result variable.
24276 	 * Convert the result to a 32-bit value by multiplying the high-order
24277 	 * 32-bits by the low-order 32-bits.
24278 	 */
24279 
24280 	hrt = gethrtime();
24281 	(void) drv_getparm(TIME, &wallclock);
24282 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24283 	mutex_enter(&tcp_random_lock);
24284 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24285 	    (result & 0xffffffff);
24286 
24287 	for (i = 1; i < DEG_3; i++)
24288 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24289 		    + 12345;
24290 	tcp_random_fptr = &tcp_random_state[SEP_3];
24291 	tcp_random_rptr = &tcp_random_state[0];
24292 	mutex_exit(&tcp_random_lock);
24293 	for (i = 0; i < 10 * DEG_3; i++)
24294 		(void) tcp_random();
24295 }
24296 
24297 /*
24298  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24299  * This range is selected to be approximately centered on TCP_ISS / 2,
24300  * and easy to compute. We get this value by generating a 32-bit random
24301  * number, selecting out the high-order 17 bits, and then adding one so
24302  * that we never return zero.
24303  */
24304 int
24305 tcp_random(void)
24306 {
24307 	int i;
24308 
24309 	mutex_enter(&tcp_random_lock);
24310 	*tcp_random_fptr += *tcp_random_rptr;
24311 
24312 	/*
24313 	 * The high-order bits are more random than the low-order bits,
24314 	 * so we select out the high-order 17 bits and add one so that
24315 	 * we never return zero.
24316 	 */
24317 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24318 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24319 		tcp_random_fptr = tcp_random_state;
24320 		++tcp_random_rptr;
24321 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24322 		tcp_random_rptr = tcp_random_state;
24323 
24324 	mutex_exit(&tcp_random_lock);
24325 	return (i);
24326 }
24327 
24328 static int
24329 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24330     int *t_errorp, int *sys_errorp)
24331 {
24332 	int error;
24333 	int is_absreq_failure;
24334 	t_scalar_t *opt_lenp;
24335 	t_scalar_t opt_offset;
24336 	int prim_type;
24337 	struct T_conn_req *tcreqp;
24338 	struct T_conn_res *tcresp;
24339 	cred_t *cr;
24340 
24341 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
24342 
24343 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24344 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24345 	    prim_type == T_CONN_RES);
24346 
24347 	switch (prim_type) {
24348 	case T_CONN_REQ:
24349 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24350 		opt_offset = tcreqp->OPT_offset;
24351 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24352 		break;
24353 	case O_T_CONN_RES:
24354 	case T_CONN_RES:
24355 		tcresp = (struct T_conn_res *)mp->b_rptr;
24356 		opt_offset = tcresp->OPT_offset;
24357 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24358 		break;
24359 	}
24360 
24361 	*t_errorp = 0;
24362 	*sys_errorp = 0;
24363 	*do_disconnectp = 0;
24364 
24365 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24366 	    opt_offset, cr, &tcp_opt_obj,
24367 	    NULL, &is_absreq_failure);
24368 
24369 	switch (error) {
24370 	case  0:		/* no error */
24371 		ASSERT(is_absreq_failure == 0);
24372 		return (0);
24373 	case ENOPROTOOPT:
24374 		*t_errorp = TBADOPT;
24375 		break;
24376 	case EACCES:
24377 		*t_errorp = TACCES;
24378 		break;
24379 	default:
24380 		*t_errorp = TSYSERR; *sys_errorp = error;
24381 		break;
24382 	}
24383 	if (is_absreq_failure != 0) {
24384 		/*
24385 		 * The connection request should get the local ack
24386 		 * T_OK_ACK and then a T_DISCON_IND.
24387 		 */
24388 		*do_disconnectp = 1;
24389 	}
24390 	return (-1);
24391 }
24392 
24393 /*
24394  * Split this function out so that if the secret changes, I'm okay.
24395  *
24396  * Initialize the tcp_iss_cookie and tcp_iss_key.
24397  */
24398 
24399 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24400 
24401 static void
24402 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
24403 {
24404 	struct {
24405 		int32_t current_time;
24406 		uint32_t randnum;
24407 		uint16_t pad;
24408 		uint8_t ether[6];
24409 		uint8_t passwd[PASSWD_SIZE];
24410 	} tcp_iss_cookie;
24411 	time_t t;
24412 
24413 	/*
24414 	 * Start with the current absolute time.
24415 	 */
24416 	(void) drv_getparm(TIME, &t);
24417 	tcp_iss_cookie.current_time = t;
24418 
24419 	/*
24420 	 * XXX - Need a more random number per RFC 1750, not this crap.
24421 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24422 	 */
24423 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24424 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24425 
24426 	/*
24427 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24428 	 * as a good template.
24429 	 */
24430 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24431 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24432 
24433 	/*
24434 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24435 	 */
24436 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24437 
24438 	/*
24439 	 * See 4010593 if this section becomes a problem again,
24440 	 * but the local ethernet address is useful here.
24441 	 */
24442 	(void) localetheraddr(NULL,
24443 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24444 
24445 	/*
24446 	 * Hash 'em all together.  The MD5Final is called per-connection.
24447 	 */
24448 	mutex_enter(&tcps->tcps_iss_key_lock);
24449 	MD5Init(&tcps->tcps_iss_key);
24450 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
24451 	    sizeof (tcp_iss_cookie));
24452 	mutex_exit(&tcps->tcps_iss_key_lock);
24453 }
24454 
24455 /*
24456  * Set the RFC 1948 pass phrase
24457  */
24458 /* ARGSUSED */
24459 static int
24460 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24461     cred_t *cr)
24462 {
24463 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24464 
24465 	/*
24466 	 * Basically, value contains a new pass phrase.  Pass it along!
24467 	 */
24468 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
24469 	return (0);
24470 }
24471 
24472 /* ARGSUSED */
24473 static int
24474 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24475 {
24476 	bzero(buf, sizeof (tcp_sack_info_t));
24477 	return (0);
24478 }
24479 
24480 /* ARGSUSED */
24481 static int
24482 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24483 {
24484 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24485 	return (0);
24486 }
24487 
24488 /*
24489  * Make sure we wait until the default queue is setup, yet allow
24490  * tcp_g_q_create() to open a TCP stream.
24491  * We need to allow tcp_g_q_create() do do an open
24492  * of tcp, hence we compare curhread.
24493  * All others have to wait until the tcps_g_q has been
24494  * setup.
24495  */
24496 void
24497 tcp_g_q_setup(tcp_stack_t *tcps)
24498 {
24499 	mutex_enter(&tcps->tcps_g_q_lock);
24500 	if (tcps->tcps_g_q != NULL) {
24501 		mutex_exit(&tcps->tcps_g_q_lock);
24502 		return;
24503 	}
24504 	if (tcps->tcps_g_q_creator == NULL) {
24505 		/* This thread will set it up */
24506 		tcps->tcps_g_q_creator = curthread;
24507 		mutex_exit(&tcps->tcps_g_q_lock);
24508 		tcp_g_q_create(tcps);
24509 		mutex_enter(&tcps->tcps_g_q_lock);
24510 		ASSERT(tcps->tcps_g_q_creator == curthread);
24511 		tcps->tcps_g_q_creator = NULL;
24512 		cv_signal(&tcps->tcps_g_q_cv);
24513 		ASSERT(tcps->tcps_g_q != NULL);
24514 		mutex_exit(&tcps->tcps_g_q_lock);
24515 		return;
24516 	}
24517 	/* Everybody but the creator has to wait */
24518 	if (tcps->tcps_g_q_creator != curthread) {
24519 		while (tcps->tcps_g_q == NULL)
24520 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24521 	}
24522 	mutex_exit(&tcps->tcps_g_q_lock);
24523 }
24524 
24525 #define	IP	"ip"
24526 
24527 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24528 
24529 /*
24530  * Create a default tcp queue here instead of in strplumb
24531  */
24532 void
24533 tcp_g_q_create(tcp_stack_t *tcps)
24534 {
24535 	int error;
24536 	ldi_handle_t	lh = NULL;
24537 	ldi_ident_t	li = NULL;
24538 	int		rval;
24539 	cred_t		*cr;
24540 	major_t IP_MAJ;
24541 
24542 #ifdef NS_DEBUG
24543 	(void) printf("tcp_g_q_create()\n");
24544 #endif
24545 
24546 	IP_MAJ = ddi_name_to_major(IP);
24547 
24548 	ASSERT(tcps->tcps_g_q_creator == curthread);
24549 
24550 	error = ldi_ident_from_major(IP_MAJ, &li);
24551 	if (error) {
24552 #ifdef DEBUG
24553 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24554 		    error);
24555 #endif
24556 		return;
24557 	}
24558 
24559 	cr = zone_get_kcred(netstackid_to_zoneid(
24560 	    tcps->tcps_netstack->netstack_stackid));
24561 	ASSERT(cr != NULL);
24562 	/*
24563 	 * We set the tcp default queue to IPv6 because IPv4 falls
24564 	 * back to IPv6 when it can't find a client, but
24565 	 * IPv6 does not fall back to IPv4.
24566 	 */
24567 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24568 	if (error) {
24569 #ifdef DEBUG
24570 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24571 		    error);
24572 #endif
24573 		goto out;
24574 	}
24575 
24576 	/*
24577 	 * This ioctl causes the tcp framework to cache a pointer to
24578 	 * this stream, so we don't want to close the stream after
24579 	 * this operation.
24580 	 * Use the kernel credentials that are for the zone we're in.
24581 	 */
24582 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24583 	    (intptr_t)0, FKIOCTL, cr, &rval);
24584 	if (error) {
24585 #ifdef DEBUG
24586 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24587 		    "error %d\n", error);
24588 #endif
24589 		goto out;
24590 	}
24591 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24592 	lh = NULL;
24593 out:
24594 	/* Close layered handles */
24595 	if (li)
24596 		ldi_ident_release(li);
24597 	/* Keep cred around until _inactive needs it */
24598 	tcps->tcps_g_q_cr = cr;
24599 }
24600 
24601 /*
24602  * We keep tcp_g_q set until all other tcp_t's in the zone
24603  * has gone away, and then when tcp_g_q_inactive() is called
24604  * we clear it.
24605  */
24606 void
24607 tcp_g_q_destroy(tcp_stack_t *tcps)
24608 {
24609 #ifdef NS_DEBUG
24610 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24611 	    tcps->tcps_netstack->netstack_stackid);
24612 #endif
24613 
24614 	if (tcps->tcps_g_q == NULL) {
24615 		return;	/* Nothing to cleanup */
24616 	}
24617 	/*
24618 	 * Drop reference corresponding to the default queue.
24619 	 * This reference was added from tcp_open when the default queue
24620 	 * was created, hence we compensate for this extra drop in
24621 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24622 	 * the default queue was the last one to be open, in which
24623 	 * case, then tcp_g_q_inactive will be
24624 	 * called as a result of the refrele.
24625 	 */
24626 	TCPS_REFRELE(tcps);
24627 }
24628 
24629 /*
24630  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24631  * Run by tcp_q_q_inactive using a taskq.
24632  */
24633 static void
24634 tcp_g_q_close(void *arg)
24635 {
24636 	tcp_stack_t *tcps = arg;
24637 	int error;
24638 	ldi_handle_t	lh = NULL;
24639 	ldi_ident_t	li = NULL;
24640 	cred_t		*cr;
24641 	major_t IP_MAJ;
24642 
24643 	IP_MAJ = ddi_name_to_major(IP);
24644 
24645 #ifdef NS_DEBUG
24646 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24647 	    tcps->tcps_netstack->netstack_stackid,
24648 	    tcps->tcps_netstack->netstack_refcnt);
24649 #endif
24650 	lh = tcps->tcps_g_q_lh;
24651 	if (lh == NULL)
24652 		return;	/* Nothing to cleanup */
24653 
24654 	ASSERT(tcps->tcps_refcnt == 1);
24655 	ASSERT(tcps->tcps_g_q != NULL);
24656 
24657 	error = ldi_ident_from_major(IP_MAJ, &li);
24658 	if (error) {
24659 #ifdef DEBUG
24660 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
24661 		    error);
24662 #endif
24663 		return;
24664 	}
24665 
24666 	cr = tcps->tcps_g_q_cr;
24667 	tcps->tcps_g_q_cr = NULL;
24668 	ASSERT(cr != NULL);
24669 
24670 	/*
24671 	 * Make sure we can break the recursion when tcp_close decrements
24672 	 * the reference count causing g_q_inactive to be called again.
24673 	 */
24674 	tcps->tcps_g_q_lh = NULL;
24675 
24676 	/* close the default queue */
24677 	(void) ldi_close(lh, FREAD|FWRITE, cr);
24678 	/*
24679 	 * At this point in time tcps and the rest of netstack_t might
24680 	 * have been deleted.
24681 	 */
24682 	tcps = NULL;
24683 
24684 	/* Close layered handles */
24685 	ldi_ident_release(li);
24686 	crfree(cr);
24687 }
24688 
24689 /*
24690  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24691  *
24692  * Have to ensure that the ldi routines are not used by an
24693  * interrupt thread by using a taskq.
24694  */
24695 void
24696 tcp_g_q_inactive(tcp_stack_t *tcps)
24697 {
24698 	if (tcps->tcps_g_q_lh == NULL)
24699 		return;	/* Nothing to cleanup */
24700 
24701 	ASSERT(tcps->tcps_refcnt == 0);
24702 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
24703 
24704 	if (servicing_interrupt()) {
24705 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
24706 		    (void *) tcps, TQ_SLEEP);
24707 	} else {
24708 		tcp_g_q_close(tcps);
24709 	}
24710 }
24711 
24712 /*
24713  * Called by IP when IP is loaded into the kernel
24714  */
24715 void
24716 tcp_ddi_g_init(void)
24717 {
24718 	tcp_timercache = kmem_cache_create("tcp_timercache",
24719 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24720 	    NULL, NULL, NULL, NULL, NULL, 0);
24721 
24722 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24723 	    sizeof (tcp_sack_info_t), 0,
24724 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24725 
24726 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24727 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24728 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24729 
24730 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24731 
24732 	/* Initialize the random number generator */
24733 	tcp_random_init();
24734 
24735 	/* A single callback independently of how many netstacks we have */
24736 	ip_squeue_init(tcp_squeue_add);
24737 
24738 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
24739 
24740 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
24741 	    TASKQ_PREPOPULATE);
24742 
24743 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
24744 
24745 	/*
24746 	 * We want to be informed each time a stack is created or
24747 	 * destroyed in the kernel, so we can maintain the
24748 	 * set of tcp_stack_t's.
24749 	 */
24750 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
24751 	    tcp_stack_fini);
24752 }
24753 
24754 
24755 #define	INET_NAME	"ip"
24756 
24757 /*
24758  * Initialize the TCP stack instance.
24759  */
24760 static void *
24761 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
24762 {
24763 	tcp_stack_t	*tcps;
24764 	tcpparam_t	*pa;
24765 	int		i;
24766 	int		error = 0;
24767 	major_t		major;
24768 
24769 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
24770 	tcps->tcps_netstack = ns;
24771 
24772 	/* Initialize locks */
24773 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
24774 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24775 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
24776 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24777 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24778 
24779 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
24780 	tcps->tcps_g_epriv_ports[0] = 2049;
24781 	tcps->tcps_g_epriv_ports[1] = 4045;
24782 	tcps->tcps_min_anonpriv_port = 512;
24783 
24784 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
24785 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
24786 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
24787 	    TCP_FANOUT_SIZE, KM_SLEEP);
24788 
24789 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24790 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
24791 		    MUTEX_DEFAULT, NULL);
24792 	}
24793 
24794 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24795 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
24796 		    MUTEX_DEFAULT, NULL);
24797 	}
24798 
24799 	/* TCP's IPsec code calls the packet dropper. */
24800 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
24801 
24802 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
24803 	tcps->tcps_params = pa;
24804 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24805 
24806 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
24807 	    A_CNT(lcl_tcp_param_arr), tcps);
24808 
24809 	/*
24810 	 * Note: To really walk the device tree you need the devinfo
24811 	 * pointer to your device which is only available after probe/attach.
24812 	 * The following is safe only because it uses ddi_root_node()
24813 	 */
24814 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24815 	    tcp_opt_obj.odb_opt_arr_cnt);
24816 
24817 	/*
24818 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24819 	 * by the boot scripts.
24820 	 *
24821 	 * Use NULL name, as the name is caught by the new lockstats.
24822 	 *
24823 	 * Initialize with some random, non-guessable string, like the global
24824 	 * T_INFO_ACK.
24825 	 */
24826 
24827 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24828 	    sizeof (tcp_g_t_info_ack), tcps);
24829 
24830 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
24831 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
24832 
24833 	major = mod_name_to_major(INET_NAME);
24834 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
24835 	ASSERT(error == 0);
24836 	return (tcps);
24837 }
24838 
24839 /*
24840  * Called when the IP module is about to be unloaded.
24841  */
24842 void
24843 tcp_ddi_g_destroy(void)
24844 {
24845 	tcp_g_kstat_fini(tcp_g_kstat);
24846 	tcp_g_kstat = NULL;
24847 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
24848 
24849 	mutex_destroy(&tcp_random_lock);
24850 
24851 	kmem_cache_destroy(tcp_timercache);
24852 	kmem_cache_destroy(tcp_sack_info_cache);
24853 	kmem_cache_destroy(tcp_iphc_cache);
24854 
24855 	netstack_unregister(NS_TCP);
24856 	taskq_destroy(tcp_taskq);
24857 }
24858 
24859 /*
24860  * Shut down the TCP stack instance.
24861  */
24862 /* ARGSUSED */
24863 static void
24864 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24865 {
24866 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24867 
24868 	tcp_g_q_destroy(tcps);
24869 }
24870 
24871 /*
24872  * Free the TCP stack instance.
24873  */
24874 static void
24875 tcp_stack_fini(netstackid_t stackid, void *arg)
24876 {
24877 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24878 	int i;
24879 
24880 	nd_free(&tcps->tcps_g_nd);
24881 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24882 	tcps->tcps_params = NULL;
24883 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24884 	tcps->tcps_wroff_xtra_param = NULL;
24885 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24886 	tcps->tcps_mdt_head_param = NULL;
24887 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24888 	tcps->tcps_mdt_tail_param = NULL;
24889 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24890 	tcps->tcps_mdt_max_pbufs_param = NULL;
24891 
24892 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24893 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24894 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24895 	}
24896 
24897 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24898 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
24899 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
24900 	}
24901 
24902 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
24903 	tcps->tcps_bind_fanout = NULL;
24904 
24905 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
24906 	tcps->tcps_acceptor_fanout = NULL;
24907 
24908 	mutex_destroy(&tcps->tcps_iss_key_lock);
24909 	rw_destroy(&tcps->tcps_hsp_lock);
24910 	mutex_destroy(&tcps->tcps_g_q_lock);
24911 	cv_destroy(&tcps->tcps_g_q_cv);
24912 	mutex_destroy(&tcps->tcps_epriv_port_lock);
24913 
24914 	ip_drop_unregister(&tcps->tcps_dropper);
24915 
24916 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
24917 	tcps->tcps_kstat = NULL;
24918 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
24919 
24920 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
24921 	tcps->tcps_mibkp = NULL;
24922 
24923 	ldi_ident_release(tcps->tcps_ldi_ident);
24924 	kmem_free(tcps, sizeof (*tcps));
24925 }
24926 
24927 /*
24928  * Generate ISS, taking into account NDD changes may happen halfway through.
24929  * (If the iss is not zero, set it.)
24930  */
24931 
24932 static void
24933 tcp_iss_init(tcp_t *tcp)
24934 {
24935 	MD5_CTX context;
24936 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24937 	uint32_t answer[4];
24938 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24939 
24940 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
24941 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
24942 	switch (tcps->tcps_strong_iss) {
24943 	case 2:
24944 		mutex_enter(&tcps->tcps_iss_key_lock);
24945 		context = tcps->tcps_iss_key;
24946 		mutex_exit(&tcps->tcps_iss_key_lock);
24947 		arg.ports = tcp->tcp_ports;
24948 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24949 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24950 			    &arg.src);
24951 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24952 			    &arg.dst);
24953 		} else {
24954 			arg.src = tcp->tcp_ip6h->ip6_src;
24955 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24956 		}
24957 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24958 		MD5Final((uchar_t *)answer, &context);
24959 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24960 		/*
24961 		 * Now that we've hashed into a unique per-connection sequence
24962 		 * space, add a random increment per strong_iss == 1.  So I
24963 		 * guess we'll have to...
24964 		 */
24965 		/* FALLTHRU */
24966 	case 1:
24967 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24968 		break;
24969 	default:
24970 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24971 		break;
24972 	}
24973 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24974 	tcp->tcp_fss = tcp->tcp_iss - 1;
24975 	tcp->tcp_suna = tcp->tcp_iss;
24976 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24977 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24978 	tcp->tcp_csuna = tcp->tcp_snxt;
24979 }
24980 
24981 /*
24982  * Exported routine for extracting active tcp connection status.
24983  *
24984  * This is used by the Solaris Cluster Networking software to
24985  * gather a list of connections that need to be forwarded to
24986  * specific nodes in the cluster when configuration changes occur.
24987  *
24988  * The callback is invoked for each tcp_t structure from all netstacks,
24989  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
24990  * from the netstack with the specified stack_id. Returning
24991  * non-zero from the callback routine terminates the search.
24992  */
24993 int
24994 cl_tcp_walk_list(netstackid_t stack_id,
24995     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
24996 {
24997 	netstack_handle_t nh;
24998 	netstack_t *ns;
24999 	int ret = 0;
25000 
25001 	if (stack_id >= 0) {
25002 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
25003 			return (EINVAL);
25004 
25005 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25006 		    ns->netstack_tcp);
25007 		netstack_rele(ns);
25008 		return (ret);
25009 	}
25010 
25011 	netstack_next_init(&nh);
25012 	while ((ns = netstack_next(&nh)) != NULL) {
25013 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25014 		    ns->netstack_tcp);
25015 		netstack_rele(ns);
25016 	}
25017 	netstack_next_fini(&nh);
25018 	return (ret);
25019 }
25020 
25021 static int
25022 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25023     tcp_stack_t *tcps)
25024 {
25025 	tcp_t *tcp;
25026 	cl_tcp_info_t	cl_tcpi;
25027 	connf_t	*connfp;
25028 	conn_t	*connp;
25029 	int	i;
25030 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25031 
25032 	ASSERT(callback != NULL);
25033 
25034 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25035 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25036 		connp = NULL;
25037 
25038 		while ((connp =
25039 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25040 
25041 			tcp = connp->conn_tcp;
25042 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
25043 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
25044 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
25045 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
25046 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
25047 			/*
25048 			 * The macros tcp_laddr and tcp_faddr give the IPv4
25049 			 * addresses. They are copied implicitly below as
25050 			 * mapped addresses.
25051 			 */
25052 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
25053 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25054 				cl_tcpi.cl_tcpi_faddr =
25055 				    tcp->tcp_ipha->ipha_dst;
25056 			} else {
25057 				cl_tcpi.cl_tcpi_faddr_v6 =
25058 				    tcp->tcp_ip6h->ip6_dst;
25059 			}
25060 
25061 			/*
25062 			 * If the callback returns non-zero
25063 			 * we terminate the traversal.
25064 			 */
25065 			if ((*callback)(&cl_tcpi, arg) != 0) {
25066 				CONN_DEC_REF(tcp->tcp_connp);
25067 				return (1);
25068 			}
25069 		}
25070 	}
25071 
25072 	return (0);
25073 }
25074 
25075 /*
25076  * Macros used for accessing the different types of sockaddr
25077  * structures inside a tcp_ioc_abort_conn_t.
25078  */
25079 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
25080 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
25081 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
25082 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
25083 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
25084 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
25085 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
25086 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
25087 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
25088 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
25089 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
25090 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
25091 
25092 /*
25093  * Return the correct error code to mimic the behavior
25094  * of a connection reset.
25095  */
25096 #define	TCP_AC_GET_ERRCODE(state, err) {	\
25097 		switch ((state)) {		\
25098 		case TCPS_SYN_SENT:		\
25099 		case TCPS_SYN_RCVD:		\
25100 			(err) = ECONNREFUSED;	\
25101 			break;			\
25102 		case TCPS_ESTABLISHED:		\
25103 		case TCPS_FIN_WAIT_1:		\
25104 		case TCPS_FIN_WAIT_2:		\
25105 		case TCPS_CLOSE_WAIT:		\
25106 			(err) = ECONNRESET;	\
25107 			break;			\
25108 		case TCPS_CLOSING:		\
25109 		case TCPS_LAST_ACK:		\
25110 		case TCPS_TIME_WAIT:		\
25111 			(err) = 0;		\
25112 			break;			\
25113 		default:			\
25114 			(err) = ENXIO;		\
25115 		}				\
25116 	}
25117 
25118 /*
25119  * Check if a tcp structure matches the info in acp.
25120  */
25121 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
25122 	(((acp)->ac_local.ss_family == AF_INET) ?		\
25123 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
25124 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
25125 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
25126 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
25127 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
25128 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
25129 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
25130 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
25131 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25132 	(acp)->ac_end >= (tcp)->tcp_state) :		\
25133 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
25134 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
25135 	&(tcp)->tcp_ip_src_v6)) &&				\
25136 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
25137 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
25138 	&(tcp)->tcp_remote_v6)) &&				\
25139 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
25140 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
25141 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
25142 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
25143 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25144 	(acp)->ac_end >= (tcp)->tcp_state))
25145 
25146 #define	TCP_AC_MATCH(acp, tcp)					\
25147 	(((acp)->ac_zoneid == ALL_ZONES ||			\
25148 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
25149 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
25150 
25151 /*
25152  * Build a message containing a tcp_ioc_abort_conn_t structure
25153  * which is filled in with information from acp and tp.
25154  */
25155 static mblk_t *
25156 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
25157 {
25158 	mblk_t *mp;
25159 	tcp_ioc_abort_conn_t *tacp;
25160 
25161 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
25162 	if (mp == NULL)
25163 		return (NULL);
25164 
25165 	mp->b_datap->db_type = M_CTL;
25166 
25167 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
25168 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
25169 	    sizeof (uint32_t));
25170 
25171 	tacp->ac_start = acp->ac_start;
25172 	tacp->ac_end = acp->ac_end;
25173 	tacp->ac_zoneid = acp->ac_zoneid;
25174 
25175 	if (acp->ac_local.ss_family == AF_INET) {
25176 		tacp->ac_local.ss_family = AF_INET;
25177 		tacp->ac_remote.ss_family = AF_INET;
25178 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
25179 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
25180 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
25181 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
25182 	} else {
25183 		tacp->ac_local.ss_family = AF_INET6;
25184 		tacp->ac_remote.ss_family = AF_INET6;
25185 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
25186 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
25187 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
25188 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
25189 	}
25190 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
25191 	return (mp);
25192 }
25193 
25194 /*
25195  * Print a tcp_ioc_abort_conn_t structure.
25196  */
25197 static void
25198 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
25199 {
25200 	char lbuf[128];
25201 	char rbuf[128];
25202 	sa_family_t af;
25203 	in_port_t lport, rport;
25204 	ushort_t logflags;
25205 
25206 	af = acp->ac_local.ss_family;
25207 
25208 	if (af == AF_INET) {
25209 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
25210 		    lbuf, 128);
25211 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
25212 		    rbuf, 128);
25213 		lport = ntohs(TCP_AC_V4LPORT(acp));
25214 		rport = ntohs(TCP_AC_V4RPORT(acp));
25215 	} else {
25216 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
25217 		    lbuf, 128);
25218 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
25219 		    rbuf, 128);
25220 		lport = ntohs(TCP_AC_V6LPORT(acp));
25221 		rport = ntohs(TCP_AC_V6RPORT(acp));
25222 	}
25223 
25224 	logflags = SL_TRACE | SL_NOTE;
25225 	/*
25226 	 * Don't print this message to the console if the operation was done
25227 	 * to a non-global zone.
25228 	 */
25229 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25230 		logflags |= SL_CONSOLE;
25231 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
25232 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
25233 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
25234 	    acp->ac_start, acp->ac_end);
25235 }
25236 
25237 /*
25238  * Called inside tcp_rput when a message built using
25239  * tcp_ioctl_abort_build_msg is put into a queue.
25240  * Note that when we get here there is no wildcard in acp any more.
25241  */
25242 static void
25243 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
25244 {
25245 	tcp_ioc_abort_conn_t *acp;
25246 
25247 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
25248 	if (tcp->tcp_state <= acp->ac_end) {
25249 		/*
25250 		 * If we get here, we are already on the correct
25251 		 * squeue. This ioctl follows the following path
25252 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
25253 		 * ->tcp_ioctl_abort->squeue_enter (if on a
25254 		 * different squeue)
25255 		 */
25256 		int errcode;
25257 
25258 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
25259 		(void) tcp_clean_death(tcp, errcode, 26);
25260 	}
25261 	freemsg(mp);
25262 }
25263 
25264 /*
25265  * Abort all matching connections on a hash chain.
25266  */
25267 static int
25268 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
25269     boolean_t exact, tcp_stack_t *tcps)
25270 {
25271 	int nmatch, err = 0;
25272 	tcp_t *tcp;
25273 	MBLKP mp, last, listhead = NULL;
25274 	conn_t	*tconnp;
25275 	connf_t	*connfp;
25276 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25277 
25278 	connfp = &ipst->ips_ipcl_conn_fanout[index];
25279 
25280 startover:
25281 	nmatch = 0;
25282 
25283 	mutex_enter(&connfp->connf_lock);
25284 	for (tconnp = connfp->connf_head; tconnp != NULL;
25285 	    tconnp = tconnp->conn_next) {
25286 		tcp = tconnp->conn_tcp;
25287 		if (TCP_AC_MATCH(acp, tcp)) {
25288 			CONN_INC_REF(tcp->tcp_connp);
25289 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
25290 			if (mp == NULL) {
25291 				err = ENOMEM;
25292 				CONN_DEC_REF(tcp->tcp_connp);
25293 				break;
25294 			}
25295 			mp->b_prev = (mblk_t *)tcp;
25296 
25297 			if (listhead == NULL) {
25298 				listhead = mp;
25299 				last = mp;
25300 			} else {
25301 				last->b_next = mp;
25302 				last = mp;
25303 			}
25304 			nmatch++;
25305 			if (exact)
25306 				break;
25307 		}
25308 
25309 		/* Avoid holding lock for too long. */
25310 		if (nmatch >= 500)
25311 			break;
25312 	}
25313 	mutex_exit(&connfp->connf_lock);
25314 
25315 	/* Pass mp into the correct tcp */
25316 	while ((mp = listhead) != NULL) {
25317 		listhead = listhead->b_next;
25318 		tcp = (tcp_t *)mp->b_prev;
25319 		mp->b_next = mp->b_prev = NULL;
25320 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
25321 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
25322 	}
25323 
25324 	*count += nmatch;
25325 	if (nmatch >= 500 && err == 0)
25326 		goto startover;
25327 	return (err);
25328 }
25329 
25330 /*
25331  * Abort all connections that matches the attributes specified in acp.
25332  */
25333 static int
25334 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
25335 {
25336 	sa_family_t af;
25337 	uint32_t  ports;
25338 	uint16_t *pports;
25339 	int err = 0, count = 0;
25340 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25341 	int index = -1;
25342 	ushort_t logflags;
25343 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25344 
25345 	af = acp->ac_local.ss_family;
25346 
25347 	if (af == AF_INET) {
25348 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25349 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25350 			pports = (uint16_t *)&ports;
25351 			pports[1] = TCP_AC_V4LPORT(acp);
25352 			pports[0] = TCP_AC_V4RPORT(acp);
25353 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25354 		}
25355 	} else {
25356 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25357 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25358 			pports = (uint16_t *)&ports;
25359 			pports[1] = TCP_AC_V6LPORT(acp);
25360 			pports[0] = TCP_AC_V6RPORT(acp);
25361 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25362 		}
25363 	}
25364 
25365 	/*
25366 	 * For cases where remote addr, local port, and remote port are non-
25367 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25368 	 */
25369 	if (index != -1) {
25370 		err = tcp_ioctl_abort_bucket(acp, index,
25371 		    &count, exact, tcps);
25372 	} else {
25373 		/*
25374 		 * loop through all entries for wildcard case
25375 		 */
25376 		for (index = 0;
25377 		    index < ipst->ips_ipcl_conn_fanout_size;
25378 		    index++) {
25379 			err = tcp_ioctl_abort_bucket(acp, index,
25380 			    &count, exact, tcps);
25381 			if (err != 0)
25382 				break;
25383 		}
25384 	}
25385 
25386 	logflags = SL_TRACE | SL_NOTE;
25387 	/*
25388 	 * Don't print this message to the console if the operation was done
25389 	 * to a non-global zone.
25390 	 */
25391 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25392 		logflags |= SL_CONSOLE;
25393 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25394 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25395 	if (err == 0 && count == 0)
25396 		err = ENOENT;
25397 	return (err);
25398 }
25399 
25400 /*
25401  * Process the TCP_IOC_ABORT_CONN ioctl request.
25402  */
25403 static void
25404 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25405 {
25406 	int	err;
25407 	IOCP    iocp;
25408 	MBLKP   mp1;
25409 	sa_family_t laf, raf;
25410 	tcp_ioc_abort_conn_t *acp;
25411 	zone_t		*zptr;
25412 	conn_t		*connp = Q_TO_CONN(q);
25413 	zoneid_t	zoneid = connp->conn_zoneid;
25414 	tcp_t		*tcp = connp->conn_tcp;
25415 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25416 
25417 	iocp = (IOCP)mp->b_rptr;
25418 
25419 	if ((mp1 = mp->b_cont) == NULL ||
25420 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25421 		err = EINVAL;
25422 		goto out;
25423 	}
25424 
25425 	/* check permissions */
25426 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
25427 		err = EPERM;
25428 		goto out;
25429 	}
25430 
25431 	if (mp1->b_cont != NULL) {
25432 		freemsg(mp1->b_cont);
25433 		mp1->b_cont = NULL;
25434 	}
25435 
25436 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25437 	laf = acp->ac_local.ss_family;
25438 	raf = acp->ac_remote.ss_family;
25439 
25440 	/* check that a zone with the supplied zoneid exists */
25441 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25442 		zptr = zone_find_by_id(zoneid);
25443 		if (zptr != NULL) {
25444 			zone_rele(zptr);
25445 		} else {
25446 			err = EINVAL;
25447 			goto out;
25448 		}
25449 	}
25450 
25451 	/*
25452 	 * For exclusive stacks we set the zoneid to zero
25453 	 * to make TCP operate as if in the global zone.
25454 	 */
25455 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
25456 		acp->ac_zoneid = GLOBAL_ZONEID;
25457 
25458 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25459 	    acp->ac_start > acp->ac_end || laf != raf ||
25460 	    (laf != AF_INET && laf != AF_INET6)) {
25461 		err = EINVAL;
25462 		goto out;
25463 	}
25464 
25465 	tcp_ioctl_abort_dump(acp);
25466 	err = tcp_ioctl_abort(acp, tcps);
25467 
25468 out:
25469 	if (mp1 != NULL) {
25470 		freemsg(mp1);
25471 		mp->b_cont = NULL;
25472 	}
25473 
25474 	if (err != 0)
25475 		miocnak(q, mp, 0, err);
25476 	else
25477 		miocack(q, mp, 0, 0);
25478 }
25479 
25480 /*
25481  * tcp_time_wait_processing() handles processing of incoming packets when
25482  * the tcp is in the TIME_WAIT state.
25483  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25484  * on the time wait list.
25485  */
25486 void
25487 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25488     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25489 {
25490 	int32_t		bytes_acked;
25491 	int32_t		gap;
25492 	int32_t		rgap;
25493 	tcp_opt_t	tcpopt;
25494 	uint_t		flags;
25495 	uint32_t	new_swnd = 0;
25496 	conn_t		*connp;
25497 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25498 
25499 	BUMP_LOCAL(tcp->tcp_ibsegs);
25500 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
25501 
25502 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25503 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25504 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25505 	if (tcp->tcp_snd_ts_ok) {
25506 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25507 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25508 			    tcp->tcp_rnxt, TH_ACK);
25509 			goto done;
25510 		}
25511 	}
25512 	gap = seg_seq - tcp->tcp_rnxt;
25513 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25514 	if (gap < 0) {
25515 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25516 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25517 		    (seg_len > -gap ? -gap : seg_len));
25518 		seg_len += gap;
25519 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25520 			if (flags & TH_RST) {
25521 				goto done;
25522 			}
25523 			if ((flags & TH_FIN) && seg_len == -1) {
25524 				/*
25525 				 * When TCP receives a duplicate FIN in
25526 				 * TIME_WAIT state, restart the 2 MSL timer.
25527 				 * See page 73 in RFC 793. Make sure this TCP
25528 				 * is already on the TIME_WAIT list. If not,
25529 				 * just restart the timer.
25530 				 */
25531 				if (TCP_IS_DETACHED(tcp)) {
25532 					if (tcp_time_wait_remove(tcp, NULL) ==
25533 					    B_TRUE) {
25534 						tcp_time_wait_append(tcp);
25535 						TCP_DBGSTAT(tcps,
25536 						    tcp_rput_time_wait);
25537 					}
25538 				} else {
25539 					ASSERT(tcp != NULL);
25540 					TCP_TIMER_RESTART(tcp,
25541 					    tcps->tcps_time_wait_interval);
25542 				}
25543 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25544 				    tcp->tcp_rnxt, TH_ACK);
25545 				goto done;
25546 			}
25547 			flags |=  TH_ACK_NEEDED;
25548 			seg_len = 0;
25549 			goto process_ack;
25550 		}
25551 
25552 		/* Fix seg_seq, and chew the gap off the front. */
25553 		seg_seq = tcp->tcp_rnxt;
25554 	}
25555 
25556 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25557 		/*
25558 		 * Make sure that when we accept the connection, pick
25559 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25560 		 * old connection.
25561 		 *
25562 		 * The next ISS generated is equal to tcp_iss_incr_extra
25563 		 * + ISS_INCR/2 + other components depending on the
25564 		 * value of tcp_strong_iss.  We pre-calculate the new
25565 		 * ISS here and compare with tcp_snxt to determine if
25566 		 * we need to make adjustment to tcp_iss_incr_extra.
25567 		 *
25568 		 * The above calculation is ugly and is a
25569 		 * waste of CPU cycles...
25570 		 */
25571 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25572 		int32_t adj;
25573 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25574 
25575 		switch (tcps->tcps_strong_iss) {
25576 		case 2: {
25577 			/* Add time and MD5 components. */
25578 			uint32_t answer[4];
25579 			struct {
25580 				uint32_t ports;
25581 				in6_addr_t src;
25582 				in6_addr_t dst;
25583 			} arg;
25584 			MD5_CTX context;
25585 
25586 			mutex_enter(&tcps->tcps_iss_key_lock);
25587 			context = tcps->tcps_iss_key;
25588 			mutex_exit(&tcps->tcps_iss_key_lock);
25589 			arg.ports = tcp->tcp_ports;
25590 			/* We use MAPPED addresses in tcp_iss_init */
25591 			arg.src = tcp->tcp_ip_src_v6;
25592 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25593 				IN6_IPADDR_TO_V4MAPPED(
25594 				    tcp->tcp_ipha->ipha_dst,
25595 				    &arg.dst);
25596 			} else {
25597 				arg.dst =
25598 				    tcp->tcp_ip6h->ip6_dst;
25599 			}
25600 			MD5Update(&context, (uchar_t *)&arg,
25601 			    sizeof (arg));
25602 			MD5Final((uchar_t *)answer, &context);
25603 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25604 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25605 			break;
25606 		}
25607 		case 1:
25608 			/* Add time component and min random (i.e. 1). */
25609 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25610 			break;
25611 		default:
25612 			/* Add only time component. */
25613 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25614 			break;
25615 		}
25616 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25617 			/*
25618 			 * New ISS not guaranteed to be ISS_INCR/2
25619 			 * ahead of the current tcp_snxt, so add the
25620 			 * difference to tcp_iss_incr_extra.
25621 			 */
25622 			tcps->tcps_iss_incr_extra += adj;
25623 		}
25624 		/*
25625 		 * If tcp_clean_death() can not perform the task now,
25626 		 * drop the SYN packet and let the other side re-xmit.
25627 		 * Otherwise pass the SYN packet back in, since the
25628 		 * old tcp state has been cleaned up or freed.
25629 		 */
25630 		if (tcp_clean_death(tcp, 0, 27) == -1)
25631 			goto done;
25632 		/*
25633 		 * We will come back to tcp_rput_data
25634 		 * on the global queue. Packets destined
25635 		 * for the global queue will be checked
25636 		 * with global policy. But the policy for
25637 		 * this packet has already been checked as
25638 		 * this was destined for the detached
25639 		 * connection. We need to bypass policy
25640 		 * check this time by attaching a dummy
25641 		 * ipsec_in with ipsec_in_dont_check set.
25642 		 */
25643 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25644 		if (connp != NULL) {
25645 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25646 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25647 			return;
25648 		}
25649 		goto done;
25650 	}
25651 
25652 	/*
25653 	 * rgap is the amount of stuff received out of window.  A negative
25654 	 * value is the amount out of window.
25655 	 */
25656 	if (rgap < 0) {
25657 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25658 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
25659 		/* Fix seg_len and make sure there is something left. */
25660 		seg_len += rgap;
25661 		if (seg_len <= 0) {
25662 			if (flags & TH_RST) {
25663 				goto done;
25664 			}
25665 			flags |=  TH_ACK_NEEDED;
25666 			seg_len = 0;
25667 			goto process_ack;
25668 		}
25669 	}
25670 	/*
25671 	 * Check whether we can update tcp_ts_recent.  This test is
25672 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
25673 	 * Extensions for High Performance: An Update", Internet Draft.
25674 	 */
25675 	if (tcp->tcp_snd_ts_ok &&
25676 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
25677 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
25678 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
25679 		tcp->tcp_last_rcv_lbolt = lbolt64;
25680 	}
25681 
25682 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
25683 		/* Always ack out of order packets */
25684 		flags |= TH_ACK_NEEDED;
25685 		seg_len = 0;
25686 	} else if (seg_len > 0) {
25687 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
25688 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
25689 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
25690 	}
25691 	if (flags & TH_RST) {
25692 		(void) tcp_clean_death(tcp, 0, 28);
25693 		goto done;
25694 	}
25695 	if (flags & TH_SYN) {
25696 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
25697 		    TH_RST|TH_ACK);
25698 		/*
25699 		 * Do not delete the TCP structure if it is in
25700 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
25701 		 */
25702 		goto done;
25703 	}
25704 process_ack:
25705 	if (flags & TH_ACK) {
25706 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
25707 		if (bytes_acked <= 0) {
25708 			if (bytes_acked == 0 && seg_len == 0 &&
25709 			    new_swnd == tcp->tcp_swnd)
25710 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
25711 		} else {
25712 			/* Acks something not sent */
25713 			flags |= TH_ACK_NEEDED;
25714 		}
25715 	}
25716 	if (flags & TH_ACK_NEEDED) {
25717 		/*
25718 		 * Time to send an ack for some reason.
25719 		 */
25720 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25721 		    tcp->tcp_rnxt, TH_ACK);
25722 	}
25723 done:
25724 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25725 		DB_CKSUMSTART(mp) = 0;
25726 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
25727 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
25728 	}
25729 	freemsg(mp);
25730 }
25731 
25732 /*
25733  * TCP Timers Implementation.
25734  */
25735 timeout_id_t
25736 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25737 {
25738 	mblk_t *mp;
25739 	tcp_timer_t *tcpt;
25740 	tcp_t *tcp = connp->conn_tcp;
25741 
25742 	ASSERT(connp->conn_sqp != NULL);
25743 
25744 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
25745 
25746 	if (tcp->tcp_timercache == NULL) {
25747 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25748 	} else {
25749 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
25750 		mp = tcp->tcp_timercache;
25751 		tcp->tcp_timercache = mp->b_next;
25752 		mp->b_next = NULL;
25753 		ASSERT(mp->b_wptr == NULL);
25754 	}
25755 
25756 	CONN_INC_REF(connp);
25757 	tcpt = (tcp_timer_t *)mp->b_rptr;
25758 	tcpt->connp = connp;
25759 	tcpt->tcpt_proc = f;
25760 	/*
25761 	 * TCP timers are normal timeouts. Plus, they do not require more than
25762 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
25763 	 * rounding up the expiration to the next resolution boundary, we can
25764 	 * batch timers in the callout subsystem to make TCP timers more
25765 	 * efficient. The roundup also protects short timers from expiring too
25766 	 * early before they have a chance to be cancelled.
25767 	 */
25768 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
25769 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
25770 
25771 	return ((timeout_id_t)mp);
25772 }
25773 
25774 static void
25775 tcp_timer_callback(void *arg)
25776 {
25777 	mblk_t *mp = (mblk_t *)arg;
25778 	tcp_timer_t *tcpt;
25779 	conn_t	*connp;
25780 
25781 	tcpt = (tcp_timer_t *)mp->b_rptr;
25782 	connp = tcpt->connp;
25783 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
25784 	    SQ_FILL, SQTAG_TCP_TIMER);
25785 }
25786 
25787 static void
25788 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
25789 {
25790 	tcp_timer_t *tcpt;
25791 	conn_t *connp = (conn_t *)arg;
25792 	tcp_t *tcp = connp->conn_tcp;
25793 
25794 	tcpt = (tcp_timer_t *)mp->b_rptr;
25795 	ASSERT(connp == tcpt->connp);
25796 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
25797 
25798 	/*
25799 	 * If the TCP has reached the closed state, don't proceed any
25800 	 * further. This TCP logically does not exist on the system.
25801 	 * tcpt_proc could for example access queues, that have already
25802 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
25803 	 */
25804 	if (tcp->tcp_state != TCPS_CLOSED) {
25805 		(*tcpt->tcpt_proc)(connp);
25806 	} else {
25807 		tcp->tcp_timer_tid = 0;
25808 	}
25809 	tcp_timer_free(connp->conn_tcp, mp);
25810 }
25811 
25812 /*
25813  * There is potential race with untimeout and the handler firing at the same
25814  * time. The mblock may be freed by the handler while we are trying to use
25815  * it. But since both should execute on the same squeue, this race should not
25816  * occur.
25817  */
25818 clock_t
25819 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
25820 {
25821 	mblk_t	*mp = (mblk_t *)id;
25822 	tcp_timer_t *tcpt;
25823 	clock_t delta;
25824 
25825 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
25826 
25827 	if (mp == NULL)
25828 		return (-1);
25829 
25830 	tcpt = (tcp_timer_t *)mp->b_rptr;
25831 	ASSERT(tcpt->connp == connp);
25832 
25833 	delta = untimeout_default(tcpt->tcpt_tid, 0);
25834 
25835 	if (delta >= 0) {
25836 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
25837 		tcp_timer_free(connp->conn_tcp, mp);
25838 		CONN_DEC_REF(connp);
25839 	}
25840 
25841 	return (delta);
25842 }
25843 
25844 /*
25845  * Allocate space for the timer event. The allocation looks like mblk, but it is
25846  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25847  *
25848  * Dealing with failures: If we can't allocate from the timer cache we try
25849  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25850  * points to b_rptr.
25851  * If we can't allocate anything using allocb_tryhard(), we perform a last
25852  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25853  * save the actual allocation size in b_datap.
25854  */
25855 mblk_t *
25856 tcp_timermp_alloc(int kmflags)
25857 {
25858 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25859 	    kmflags & ~KM_PANIC);
25860 
25861 	if (mp != NULL) {
25862 		mp->b_next = mp->b_prev = NULL;
25863 		mp->b_rptr = (uchar_t *)(&mp[1]);
25864 		mp->b_wptr = NULL;
25865 		mp->b_datap = NULL;
25866 		mp->b_queue = NULL;
25867 		mp->b_cont = NULL;
25868 	} else if (kmflags & KM_PANIC) {
25869 		/*
25870 		 * Failed to allocate memory for the timer. Try allocating from
25871 		 * dblock caches.
25872 		 */
25873 		/* ipclassifier calls this from a constructor - hence no tcps */
25874 		TCP_G_STAT(tcp_timermp_allocfail);
25875 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25876 		if (mp == NULL) {
25877 			size_t size = 0;
25878 			/*
25879 			 * Memory is really low. Try tryhard allocation.
25880 			 *
25881 			 * ipclassifier calls this from a constructor -
25882 			 * hence no tcps
25883 			 */
25884 			TCP_G_STAT(tcp_timermp_allocdblfail);
25885 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25886 			    sizeof (tcp_timer_t), &size, kmflags);
25887 			mp->b_rptr = (uchar_t *)(&mp[1]);
25888 			mp->b_next = mp->b_prev = NULL;
25889 			mp->b_wptr = (uchar_t *)-1;
25890 			mp->b_datap = (dblk_t *)size;
25891 			mp->b_queue = NULL;
25892 			mp->b_cont = NULL;
25893 		}
25894 		ASSERT(mp->b_wptr != NULL);
25895 	}
25896 	/* ipclassifier calls this from a constructor - hence no tcps */
25897 	TCP_G_DBGSTAT(tcp_timermp_alloced);
25898 
25899 	return (mp);
25900 }
25901 
25902 /*
25903  * Free per-tcp timer cache.
25904  * It can only contain entries from tcp_timercache.
25905  */
25906 void
25907 tcp_timermp_free(tcp_t *tcp)
25908 {
25909 	mblk_t *mp;
25910 
25911 	while ((mp = tcp->tcp_timercache) != NULL) {
25912 		ASSERT(mp->b_wptr == NULL);
25913 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25914 		kmem_cache_free(tcp_timercache, mp);
25915 	}
25916 }
25917 
25918 /*
25919  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25920  * events there already (currently at most two events are cached).
25921  * If the event is not allocated from the timer cache, free it right away.
25922  */
25923 static void
25924 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25925 {
25926 	mblk_t *mp1 = tcp->tcp_timercache;
25927 
25928 	if (mp->b_wptr != NULL) {
25929 		/*
25930 		 * This allocation is not from a timer cache, free it right
25931 		 * away.
25932 		 */
25933 		if (mp->b_wptr != (uchar_t *)-1)
25934 			freeb(mp);
25935 		else
25936 			kmem_free(mp, (size_t)mp->b_datap);
25937 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25938 		/* Cache this timer block for future allocations */
25939 		mp->b_rptr = (uchar_t *)(&mp[1]);
25940 		mp->b_next = mp1;
25941 		tcp->tcp_timercache = mp;
25942 	} else {
25943 		kmem_cache_free(tcp_timercache, mp);
25944 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
25945 	}
25946 }
25947 
25948 /*
25949  * End of TCP Timers implementation.
25950  */
25951 
25952 /*
25953  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25954  * on the specified backing STREAMS q. Note, the caller may make the
25955  * decision to call based on the tcp_t.tcp_flow_stopped value which
25956  * when check outside the q's lock is only an advisory check ...
25957  */
25958 void
25959 tcp_setqfull(tcp_t *tcp)
25960 {
25961 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25962 	conn_t	*connp = tcp->tcp_connp;
25963 
25964 	if (tcp->tcp_closed)
25965 		return;
25966 
25967 	if (IPCL_IS_NONSTR(connp)) {
25968 		(*connp->conn_upcalls->su_txq_full)
25969 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
25970 		tcp->tcp_flow_stopped = B_TRUE;
25971 	} else {
25972 		queue_t *q = tcp->tcp_wq;
25973 
25974 		if (!(q->q_flag & QFULL)) {
25975 			mutex_enter(QLOCK(q));
25976 			if (!(q->q_flag & QFULL)) {
25977 				/* still need to set QFULL */
25978 				q->q_flag |= QFULL;
25979 				tcp->tcp_flow_stopped = B_TRUE;
25980 				mutex_exit(QLOCK(q));
25981 				TCP_STAT(tcps, tcp_flwctl_on);
25982 			} else {
25983 				mutex_exit(QLOCK(q));
25984 			}
25985 		}
25986 	}
25987 }
25988 
25989 void
25990 tcp_clrqfull(tcp_t *tcp)
25991 {
25992 	conn_t  *connp = tcp->tcp_connp;
25993 
25994 	if (tcp->tcp_closed)
25995 		return;
25996 
25997 	if (IPCL_IS_NONSTR(connp)) {
25998 		(*connp->conn_upcalls->su_txq_full)
25999 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
26000 		tcp->tcp_flow_stopped = B_FALSE;
26001 	} else {
26002 		queue_t *q = tcp->tcp_wq;
26003 
26004 		if (q->q_flag & QFULL) {
26005 			mutex_enter(QLOCK(q));
26006 			if (q->q_flag & QFULL) {
26007 				q->q_flag &= ~QFULL;
26008 				tcp->tcp_flow_stopped = B_FALSE;
26009 				mutex_exit(QLOCK(q));
26010 				if (q->q_flag & QWANTW)
26011 					qbackenable(q, 0);
26012 			} else {
26013 				mutex_exit(QLOCK(q));
26014 			}
26015 		}
26016 	}
26017 }
26018 
26019 /*
26020  * kstats related to squeues i.e. not per IP instance
26021  */
26022 static void *
26023 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26024 {
26025 	kstat_t *ksp;
26026 
26027 	tcp_g_stat_t template = {
26028 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26029 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
26030 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
26031 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
26032 	};
26033 
26034 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
26035 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26036 	    KSTAT_FLAG_VIRTUAL);
26037 
26038 	if (ksp == NULL)
26039 		return (NULL);
26040 
26041 	bcopy(&template, tcp_g_statp, sizeof (template));
26042 	ksp->ks_data = (void *)tcp_g_statp;
26043 
26044 	kstat_install(ksp);
26045 	return (ksp);
26046 }
26047 
26048 static void
26049 tcp_g_kstat_fini(kstat_t *ksp)
26050 {
26051 	if (ksp != NULL) {
26052 		kstat_delete(ksp);
26053 	}
26054 }
26055 
26056 
26057 static void *
26058 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
26059 {
26060 	kstat_t *ksp;
26061 
26062 	tcp_stat_t template = {
26063 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
26064 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
26065 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
26066 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
26067 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
26068 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
26069 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
26070 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
26071 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
26072 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
26073 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
26074 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
26075 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
26076 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
26077 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
26078 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
26079 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
26080 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
26081 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
26082 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
26083 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
26084 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
26085 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
26086 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
26087 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
26088 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
26089 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
26090 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
26091 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
26092 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
26093 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
26094 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
26095 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
26096 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
26097 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
26098 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
26099 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
26100 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
26101 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
26102 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
26103 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
26104 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
26105 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
26106 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
26107 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
26108 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
26109 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
26110 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
26111 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
26112 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
26113 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
26114 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
26115 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
26116 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
26117 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
26118 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
26119 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
26120 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
26121 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
26122 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
26123 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
26124 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
26125 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
26126 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
26127 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
26128 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
26129 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
26130 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
26131 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
26132 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
26133 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
26134 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
26135 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
26136 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
26137 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
26138 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
26139 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
26140 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
26141 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
26142 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
26143 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
26144 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
26145 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
26146 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
26147 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
26148 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
26149 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
26150 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
26151 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
26152 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
26153 	};
26154 
26155 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
26156 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26157 	    KSTAT_FLAG_VIRTUAL, stackid);
26158 
26159 	if (ksp == NULL)
26160 		return (NULL);
26161 
26162 	bcopy(&template, tcps_statisticsp, sizeof (template));
26163 	ksp->ks_data = (void *)tcps_statisticsp;
26164 	ksp->ks_private = (void *)(uintptr_t)stackid;
26165 
26166 	kstat_install(ksp);
26167 	return (ksp);
26168 }
26169 
26170 static void
26171 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
26172 {
26173 	if (ksp != NULL) {
26174 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26175 		kstat_delete_netstack(ksp, stackid);
26176 	}
26177 }
26178 
26179 /*
26180  * TCP Kstats implementation
26181  */
26182 static void *
26183 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
26184 {
26185 	kstat_t	*ksp;
26186 
26187 	tcp_named_kstat_t template = {
26188 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
26189 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
26190 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
26191 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
26192 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
26193 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
26194 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
26195 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
26196 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
26197 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
26198 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
26199 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
26200 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
26201 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
26202 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
26203 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
26204 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
26205 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
26206 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
26207 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
26208 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
26209 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
26210 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
26211 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
26212 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
26213 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
26214 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
26215 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
26216 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
26217 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
26218 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
26219 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
26220 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
26221 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
26222 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
26223 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
26224 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
26225 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
26226 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
26227 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
26228 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
26229 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
26230 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
26231 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
26232 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
26233 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
26234 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
26235 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
26236 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
26237 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
26238 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
26239 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
26240 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
26241 	};
26242 
26243 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
26244 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
26245 
26246 	if (ksp == NULL)
26247 		return (NULL);
26248 
26249 	template.rtoAlgorithm.value.ui32 = 4;
26250 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
26251 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
26252 	template.maxConn.value.i32 = -1;
26253 
26254 	bcopy(&template, ksp->ks_data, sizeof (template));
26255 	ksp->ks_update = tcp_kstat_update;
26256 	ksp->ks_private = (void *)(uintptr_t)stackid;
26257 
26258 	kstat_install(ksp);
26259 	return (ksp);
26260 }
26261 
26262 static void
26263 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
26264 {
26265 	if (ksp != NULL) {
26266 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26267 		kstat_delete_netstack(ksp, stackid);
26268 	}
26269 }
26270 
26271 static int
26272 tcp_kstat_update(kstat_t *kp, int rw)
26273 {
26274 	tcp_named_kstat_t *tcpkp;
26275 	tcp_t		*tcp;
26276 	connf_t		*connfp;
26277 	conn_t		*connp;
26278 	int 		i;
26279 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
26280 	netstack_t	*ns;
26281 	tcp_stack_t	*tcps;
26282 	ip_stack_t	*ipst;
26283 
26284 	if ((kp == NULL) || (kp->ks_data == NULL))
26285 		return (EIO);
26286 
26287 	if (rw == KSTAT_WRITE)
26288 		return (EACCES);
26289 
26290 	ns = netstack_find_by_stackid(stackid);
26291 	if (ns == NULL)
26292 		return (-1);
26293 	tcps = ns->netstack_tcp;
26294 	if (tcps == NULL) {
26295 		netstack_rele(ns);
26296 		return (-1);
26297 	}
26298 
26299 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
26300 
26301 	tcpkp->currEstab.value.ui32 = 0;
26302 
26303 	ipst = ns->netstack_ip;
26304 
26305 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
26306 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
26307 		connp = NULL;
26308 		while ((connp =
26309 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
26310 			tcp = connp->conn_tcp;
26311 			switch (tcp_snmp_state(tcp)) {
26312 			case MIB2_TCP_established:
26313 			case MIB2_TCP_closeWait:
26314 				tcpkp->currEstab.value.ui32++;
26315 				break;
26316 			}
26317 		}
26318 	}
26319 
26320 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
26321 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
26322 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
26323 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
26324 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
26325 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
26326 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
26327 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
26328 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
26329 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
26330 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
26331 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
26332 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
26333 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
26334 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
26335 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
26336 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
26337 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
26338 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
26339 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
26340 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
26341 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
26342 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
26343 	tcpkp->inDataInorderSegs.value.ui32 =
26344 	    tcps->tcps_mib.tcpInDataInorderSegs;
26345 	tcpkp->inDataInorderBytes.value.ui32 =
26346 	    tcps->tcps_mib.tcpInDataInorderBytes;
26347 	tcpkp->inDataUnorderSegs.value.ui32 =
26348 	    tcps->tcps_mib.tcpInDataUnorderSegs;
26349 	tcpkp->inDataUnorderBytes.value.ui32 =
26350 	    tcps->tcps_mib.tcpInDataUnorderBytes;
26351 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
26352 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
26353 	tcpkp->inDataPartDupSegs.value.ui32 =
26354 	    tcps->tcps_mib.tcpInDataPartDupSegs;
26355 	tcpkp->inDataPartDupBytes.value.ui32 =
26356 	    tcps->tcps_mib.tcpInDataPartDupBytes;
26357 	tcpkp->inDataPastWinSegs.value.ui32 =
26358 	    tcps->tcps_mib.tcpInDataPastWinSegs;
26359 	tcpkp->inDataPastWinBytes.value.ui32 =
26360 	    tcps->tcps_mib.tcpInDataPastWinBytes;
26361 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
26362 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
26363 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
26364 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
26365 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
26366 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
26367 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
26368 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
26369 	tcpkp->timKeepaliveProbe.value.ui32 =
26370 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
26371 	tcpkp->timKeepaliveDrop.value.ui32 =
26372 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
26373 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
26374 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
26375 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
26376 	tcpkp->outSackRetransSegs.value.ui32 =
26377 	    tcps->tcps_mib.tcpOutSackRetransSegs;
26378 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
26379 
26380 	netstack_rele(ns);
26381 	return (0);
26382 }
26383 
26384 void
26385 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
26386 {
26387 	uint16_t	hdr_len;
26388 	ipha_t		*ipha;
26389 	uint8_t		*nexthdrp;
26390 	tcph_t		*tcph;
26391 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26392 
26393 	/* Already has an eager */
26394 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26395 		TCP_STAT(tcps, tcp_reinput_syn);
26396 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26397 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
26398 		return;
26399 	}
26400 
26401 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
26402 	case IPV4_VERSION:
26403 		ipha = (ipha_t *)mp->b_rptr;
26404 		hdr_len = IPH_HDR_LENGTH(ipha);
26405 		break;
26406 	case IPV6_VERSION:
26407 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
26408 		    &hdr_len, &nexthdrp)) {
26409 			CONN_DEC_REF(connp);
26410 			freemsg(mp);
26411 			return;
26412 		}
26413 		break;
26414 	}
26415 
26416 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
26417 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
26418 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
26419 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
26420 	}
26421 
26422 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26423 	    SQ_FILL, SQTAG_TCP_REINPUT);
26424 }
26425 
26426 static int
26427 tcp_squeue_switch(int val)
26428 {
26429 	int rval = SQ_FILL;
26430 
26431 	switch (val) {
26432 	case 1:
26433 		rval = SQ_NODRAIN;
26434 		break;
26435 	case 2:
26436 		rval = SQ_PROCESS;
26437 		break;
26438 	default:
26439 		break;
26440 	}
26441 	return (rval);
26442 }
26443 
26444 /*
26445  * This is called once for each squeue - globally for all stack
26446  * instances.
26447  */
26448 static void
26449 tcp_squeue_add(squeue_t *sqp)
26450 {
26451 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
26452 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
26453 
26454 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
26455 	tcp_time_wait->tcp_time_wait_tid =
26456 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
26457 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
26458 	    CALLOUT_FLAG_ROUNDUP);
26459 	if (tcp_free_list_max_cnt == 0) {
26460 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
26461 		    max_ncpus : boot_max_ncpus);
26462 
26463 		/*
26464 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
26465 		 */
26466 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
26467 		    (tcp_ncpus * sizeof (tcp_t) * 100);
26468 	}
26469 	tcp_time_wait->tcp_free_list_cnt = 0;
26470 }
26471 
26472 static int
26473 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error, cred_t *cr, pid_t pid)
26474 {
26475 	mblk_t	*ire_mp = NULL;
26476 	mblk_t	*syn_mp;
26477 	mblk_t	*mdti;
26478 	mblk_t	*lsoi;
26479 	int	retval;
26480 	tcph_t	*tcph;
26481 	uint32_t	mss;
26482 	queue_t	*q = tcp->tcp_rq;
26483 	conn_t	*connp = tcp->tcp_connp;
26484 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26485 
26486 	if (error == 0) {
26487 		/*
26488 		 * Adapt Multidata information, if any.  The
26489 		 * following tcp_mdt_update routine will free
26490 		 * the message.
26491 		 */
26492 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
26493 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
26494 			    b_rptr)->mdt_capab, B_TRUE);
26495 			freemsg(mdti);
26496 		}
26497 
26498 		/*
26499 		 * Check to update LSO information with tcp, and
26500 		 * tcp_lso_update routine will free the message.
26501 		 */
26502 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
26503 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
26504 			    b_rptr)->lso_capab);
26505 			freemsg(lsoi);
26506 		}
26507 
26508 		/* Get the IRE, if we had requested for it */
26509 		if (mp != NULL)
26510 			ire_mp = tcp_ire_mp(&mp);
26511 
26512 		if (tcp->tcp_hard_binding) {
26513 			tcp->tcp_hard_binding = B_FALSE;
26514 			tcp->tcp_hard_bound = B_TRUE;
26515 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
26516 			if (retval != 0) {
26517 				error = EADDRINUSE;
26518 				goto bind_failed;
26519 			}
26520 		} else {
26521 			if (ire_mp != NULL)
26522 				freeb(ire_mp);
26523 			goto after_syn_sent;
26524 		}
26525 
26526 		retval = tcp_adapt_ire(tcp, ire_mp);
26527 		if (ire_mp != NULL)
26528 			freeb(ire_mp);
26529 		if (retval == 0) {
26530 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
26531 			    ENETUNREACH : EADDRNOTAVAIL);
26532 			goto ipcl_rm;
26533 		}
26534 		/*
26535 		 * Don't let an endpoint connect to itself.
26536 		 * Also checked in tcp_connect() but that
26537 		 * check can't handle the case when the
26538 		 * local IP address is INADDR_ANY.
26539 		 */
26540 		if (tcp->tcp_ipversion == IPV4_VERSION) {
26541 			if ((tcp->tcp_ipha->ipha_dst ==
26542 			    tcp->tcp_ipha->ipha_src) &&
26543 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26544 			    tcp->tcp_tcph->th_fport))) {
26545 				error = EADDRNOTAVAIL;
26546 				goto ipcl_rm;
26547 			}
26548 		} else {
26549 			if (IN6_ARE_ADDR_EQUAL(
26550 			    &tcp->tcp_ip6h->ip6_dst,
26551 			    &tcp->tcp_ip6h->ip6_src) &&
26552 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26553 			    tcp->tcp_tcph->th_fport))) {
26554 				error = EADDRNOTAVAIL;
26555 				goto ipcl_rm;
26556 			}
26557 		}
26558 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
26559 		/*
26560 		 * This should not be possible!  Just for
26561 		 * defensive coding...
26562 		 */
26563 		if (tcp->tcp_state != TCPS_SYN_SENT)
26564 			goto after_syn_sent;
26565 
26566 		if (is_system_labeled() &&
26567 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
26568 			error = EHOSTUNREACH;
26569 			goto ipcl_rm;
26570 		}
26571 
26572 		/*
26573 		 * tcp_adapt_ire() does not adjust
26574 		 * for TCP/IP header length.
26575 		 */
26576 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
26577 
26578 		/*
26579 		 * Just make sure our rwnd is at
26580 		 * least tcp_recv_hiwat_mss * MSS
26581 		 * large, and round up to the nearest
26582 		 * MSS.
26583 		 *
26584 		 * We do the round up here because
26585 		 * we need to get the interface
26586 		 * MTU first before we can do the
26587 		 * round up.
26588 		 */
26589 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
26590 		    tcps->tcps_recv_hiwat_minmss * mss);
26591 		if (!IPCL_IS_NONSTR(connp))
26592 			q->q_hiwat = tcp->tcp_rwnd;
26593 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
26594 		tcp_set_ws_value(tcp);
26595 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
26596 		    tcp->tcp_tcph->th_win);
26597 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
26598 			tcp->tcp_snd_ws_ok = B_TRUE;
26599 
26600 		/*
26601 		 * Set tcp_snd_ts_ok to true
26602 		 * so that tcp_xmit_mp will
26603 		 * include the timestamp
26604 		 * option in the SYN segment.
26605 		 */
26606 		if (tcps->tcps_tstamp_always ||
26607 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
26608 			tcp->tcp_snd_ts_ok = B_TRUE;
26609 		}
26610 
26611 		/*
26612 		 * tcp_snd_sack_ok can be set in
26613 		 * tcp_adapt_ire() if the sack metric
26614 		 * is set.  So check it here also.
26615 		 */
26616 		if (tcps->tcps_sack_permitted == 2 ||
26617 		    tcp->tcp_snd_sack_ok) {
26618 			if (tcp->tcp_sack_info == NULL) {
26619 				tcp->tcp_sack_info =
26620 				    kmem_cache_alloc(tcp_sack_info_cache,
26621 				    KM_SLEEP);
26622 			}
26623 			tcp->tcp_snd_sack_ok = B_TRUE;
26624 		}
26625 
26626 		/*
26627 		 * Should we use ECN?  Note that the current
26628 		 * default value (SunOS 5.9) of tcp_ecn_permitted
26629 		 * is 1.  The reason for doing this is that there
26630 		 * are equipments out there that will drop ECN
26631 		 * enabled IP packets.  Setting it to 1 avoids
26632 		 * compatibility problems.
26633 		 */
26634 		if (tcps->tcps_ecn_permitted == 2)
26635 			tcp->tcp_ecn_ok = B_TRUE;
26636 
26637 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
26638 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
26639 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
26640 		if (syn_mp) {
26641 			if (cr == NULL) {
26642 				cr = tcp->tcp_cred;
26643 				pid = tcp->tcp_cpid;
26644 			}
26645 			mblk_setcred(syn_mp, cr);
26646 			DB_CPID(syn_mp) = pid;
26647 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
26648 		}
26649 	after_syn_sent:
26650 		if (mp != NULL) {
26651 			ASSERT(mp->b_cont == NULL);
26652 			freeb(mp);
26653 		}
26654 		return (error);
26655 	} else {
26656 		/* error */
26657 		if (tcp->tcp_debug) {
26658 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
26659 			    "tcp_post_ip_bind: error == %d", error);
26660 		}
26661 		if (mp != NULL) {
26662 			freeb(mp);
26663 		}
26664 	}
26665 
26666 ipcl_rm:
26667 	/*
26668 	 * Need to unbind with classifier since we were just
26669 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
26670 	 */
26671 	tcp->tcp_hard_bound = B_FALSE;
26672 	tcp->tcp_hard_binding = B_FALSE;
26673 
26674 	ipcl_hash_remove(connp);
26675 
26676 bind_failed:
26677 	tcp->tcp_state = TCPS_IDLE;
26678 	if (tcp->tcp_ipversion == IPV4_VERSION)
26679 		tcp->tcp_ipha->ipha_src = 0;
26680 	else
26681 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
26682 	/*
26683 	 * Copy of the src addr. in tcp_t is needed since
26684 	 * the lookup funcs. can only look at tcp_t
26685 	 */
26686 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
26687 
26688 	tcph = tcp->tcp_tcph;
26689 	tcph->th_lport[0] = 0;
26690 	tcph->th_lport[1] = 0;
26691 	tcp_bind_hash_remove(tcp);
26692 	bzero(&connp->u_port, sizeof (connp->u_port));
26693 	/* blow away saved option results if any */
26694 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26695 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26696 
26697 	conn_delete_ire(tcp->tcp_connp, NULL);
26698 
26699 	return (error);
26700 }
26701 
26702 static int
26703 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
26704     boolean_t bind_to_req_port_only, cred_t *cr)
26705 {
26706 	in_port_t	mlp_port;
26707 	mlp_type_t 	addrtype, mlptype;
26708 	boolean_t	user_specified;
26709 	in_port_t	allocated_port;
26710 	in_port_t	requested_port = *requested_port_ptr;
26711 	conn_t		*connp;
26712 	zone_t		*zone;
26713 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26714 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
26715 
26716 	/*
26717 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
26718 	 */
26719 	if (cr == NULL)
26720 		cr = tcp->tcp_cred;
26721 	/*
26722 	 * Get a valid port (within the anonymous range and should not
26723 	 * be a privileged one) to use if the user has not given a port.
26724 	 * If multiple threads are here, they may all start with
26725 	 * with the same initial port. But, it should be fine as long as
26726 	 * tcp_bindi will ensure that no two threads will be assigned
26727 	 * the same port.
26728 	 *
26729 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
26730 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
26731 	 * unless TCP_ANONPRIVBIND option is set.
26732 	 */
26733 	mlptype = mlptSingle;
26734 	mlp_port = requested_port;
26735 	if (requested_port == 0) {
26736 		requested_port = tcp->tcp_anon_priv_bind ?
26737 		    tcp_get_next_priv_port(tcp) :
26738 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
26739 		    tcp, B_TRUE);
26740 		if (requested_port == 0) {
26741 			return (-TNOADDR);
26742 		}
26743 		user_specified = B_FALSE;
26744 
26745 		/*
26746 		 * If the user went through one of the RPC interfaces to create
26747 		 * this socket and RPC is MLP in this zone, then give him an
26748 		 * anonymous MLP.
26749 		 */
26750 		connp = tcp->tcp_connp;
26751 		if (connp->conn_anon_mlp && is_system_labeled()) {
26752 			zone = crgetzone(cr);
26753 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26754 			    IPV6_VERSION, &v6addr,
26755 			    tcps->tcps_netstack->netstack_ip);
26756 			if (addrtype == mlptSingle) {
26757 				return (-TNOADDR);
26758 			}
26759 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26760 			    PMAPPORT, addrtype);
26761 			mlp_port = PMAPPORT;
26762 		}
26763 	} else {
26764 		int i;
26765 		boolean_t priv = B_FALSE;
26766 
26767 		/*
26768 		 * If the requested_port is in the well-known privileged range,
26769 		 * verify that the stream was opened by a privileged user.
26770 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
26771 		 * but instead the code relies on:
26772 		 * - the fact that the address of the array and its size never
26773 		 *   changes
26774 		 * - the atomic assignment of the elements of the array
26775 		 */
26776 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
26777 			priv = B_TRUE;
26778 		} else {
26779 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
26780 				if (requested_port ==
26781 				    tcps->tcps_g_epriv_ports[i]) {
26782 					priv = B_TRUE;
26783 					break;
26784 				}
26785 			}
26786 		}
26787 		if (priv) {
26788 			if (secpolicy_net_privaddr(cr, requested_port,
26789 			    IPPROTO_TCP) != 0) {
26790 				if (tcp->tcp_debug) {
26791 					(void) strlog(TCP_MOD_ID, 0, 1,
26792 					    SL_ERROR|SL_TRACE,
26793 					    "tcp_bind: no priv for port %d",
26794 					    requested_port);
26795 				}
26796 				return (-TACCES);
26797 			}
26798 		}
26799 		user_specified = B_TRUE;
26800 
26801 		connp = tcp->tcp_connp;
26802 		if (is_system_labeled()) {
26803 			zone = crgetzone(cr);
26804 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26805 			    IPV6_VERSION, &v6addr,
26806 			    tcps->tcps_netstack->netstack_ip);
26807 			if (addrtype == mlptSingle) {
26808 				return (-TNOADDR);
26809 			}
26810 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26811 			    requested_port, addrtype);
26812 		}
26813 	}
26814 
26815 	if (mlptype != mlptSingle) {
26816 		if (secpolicy_net_bindmlp(cr) != 0) {
26817 			if (tcp->tcp_debug) {
26818 				(void) strlog(TCP_MOD_ID, 0, 1,
26819 				    SL_ERROR|SL_TRACE,
26820 				    "tcp_bind: no priv for multilevel port %d",
26821 				    requested_port);
26822 			}
26823 			return (-TACCES);
26824 		}
26825 
26826 		/*
26827 		 * If we're specifically binding a shared IP address and the
26828 		 * port is MLP on shared addresses, then check to see if this
26829 		 * zone actually owns the MLP.  Reject if not.
26830 		 */
26831 		if (mlptype == mlptShared && addrtype == mlptShared) {
26832 			/*
26833 			 * No need to handle exclusive-stack zones since
26834 			 * ALL_ZONES only applies to the shared stack.
26835 			 */
26836 			zoneid_t mlpzone;
26837 
26838 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26839 			    htons(mlp_port));
26840 			if (connp->conn_zoneid != mlpzone) {
26841 				if (tcp->tcp_debug) {
26842 					(void) strlog(TCP_MOD_ID, 0, 1,
26843 					    SL_ERROR|SL_TRACE,
26844 					    "tcp_bind: attempt to bind port "
26845 					    "%d on shared addr in zone %d "
26846 					    "(should be %d)",
26847 					    mlp_port, connp->conn_zoneid,
26848 					    mlpzone);
26849 				}
26850 				return (-TACCES);
26851 			}
26852 		}
26853 
26854 		if (!user_specified) {
26855 			int err;
26856 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26857 			    requested_port, B_TRUE);
26858 			if (err != 0) {
26859 				if (tcp->tcp_debug) {
26860 					(void) strlog(TCP_MOD_ID, 0, 1,
26861 					    SL_ERROR|SL_TRACE,
26862 					    "tcp_bind: cannot establish anon "
26863 					    "MLP for port %d",
26864 					    requested_port);
26865 				}
26866 				return (err);
26867 			}
26868 			connp->conn_anon_port = B_TRUE;
26869 		}
26870 		connp->conn_mlp_type = mlptype;
26871 	}
26872 
26873 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26874 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26875 
26876 	if (allocated_port == 0) {
26877 		connp->conn_mlp_type = mlptSingle;
26878 		if (connp->conn_anon_port) {
26879 			connp->conn_anon_port = B_FALSE;
26880 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26881 			    requested_port, B_FALSE);
26882 		}
26883 		if (bind_to_req_port_only) {
26884 			if (tcp->tcp_debug) {
26885 				(void) strlog(TCP_MOD_ID, 0, 1,
26886 				    SL_ERROR|SL_TRACE,
26887 				    "tcp_bind: requested addr busy");
26888 			}
26889 			return (-TADDRBUSY);
26890 		} else {
26891 			/* If we are out of ports, fail the bind. */
26892 			if (tcp->tcp_debug) {
26893 				(void) strlog(TCP_MOD_ID, 0, 1,
26894 				    SL_ERROR|SL_TRACE,
26895 				    "tcp_bind: out of ports?");
26896 			}
26897 			return (-TNOADDR);
26898 		}
26899 	}
26900 
26901 	/* Pass the allocated port back */
26902 	*requested_port_ptr = allocated_port;
26903 	return (0);
26904 }
26905 
26906 static int
26907 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26908     boolean_t bind_to_req_port_only)
26909 {
26910 	tcp_t	*tcp = connp->conn_tcp;
26911 
26912 	sin_t	*sin;
26913 	sin6_t  *sin6;
26914 	sin6_t		sin6addr;
26915 	in_port_t requested_port;
26916 	ipaddr_t	v4addr;
26917 	in6_addr_t	v6addr;
26918 	uint_t	origipversion;
26919 	int	error = 0;
26920 
26921 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
26922 
26923 	if (tcp->tcp_state == TCPS_BOUND) {
26924 		return (0);
26925 	} else if (tcp->tcp_state > TCPS_BOUND) {
26926 		if (tcp->tcp_debug) {
26927 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26928 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26929 		}
26930 		return (-TOUTSTATE);
26931 	}
26932 	origipversion = tcp->tcp_ipversion;
26933 
26934 	if (sa != NULL && !OK_32PTR((char *)sa)) {
26935 		if (tcp->tcp_debug) {
26936 			(void) strlog(TCP_MOD_ID, 0, 1,
26937 			    SL_ERROR|SL_TRACE,
26938 			    "tcp_bind: bad address parameter, "
26939 			    "address %p, len %d",
26940 			    (void *)sa, len);
26941 		}
26942 		return (-TPROTO);
26943 	}
26944 
26945 	switch (len) {
26946 	case 0:		/* request for a generic port */
26947 		if (tcp->tcp_family == AF_INET) {
26948 			sin = (sin_t *)&sin6addr;
26949 			*sin = sin_null;
26950 			sin->sin_family = AF_INET;
26951 			tcp->tcp_ipversion = IPV4_VERSION;
26952 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
26953 		} else {
26954 			ASSERT(tcp->tcp_family == AF_INET6);
26955 			sin6 = (sin6_t *)&sin6addr;
26956 			*sin6 = sin6_null;
26957 			sin6->sin6_family = AF_INET6;
26958 			tcp->tcp_ipversion = IPV6_VERSION;
26959 			V6_SET_ZERO(v6addr);
26960 		}
26961 		requested_port = 0;
26962 		break;
26963 
26964 	case sizeof (sin_t):	/* Complete IPv4 address */
26965 		sin = (sin_t *)sa;
26966 		/*
26967 		 * With sockets sockfs will accept bogus sin_family in
26968 		 * bind() and replace it with the family used in the socket
26969 		 * call.
26970 		 */
26971 		if (sin->sin_family != AF_INET ||
26972 		    tcp->tcp_family != AF_INET) {
26973 			return (EAFNOSUPPORT);
26974 		}
26975 		requested_port = ntohs(sin->sin_port);
26976 		tcp->tcp_ipversion = IPV4_VERSION;
26977 		v4addr = sin->sin_addr.s_addr;
26978 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
26979 		break;
26980 
26981 	case sizeof (sin6_t): /* Complete IPv6 address */
26982 		sin6 = (sin6_t *)sa;
26983 		if (sin6->sin6_family != AF_INET6 ||
26984 		    tcp->tcp_family != AF_INET6) {
26985 			return (EAFNOSUPPORT);
26986 		}
26987 		requested_port = ntohs(sin6->sin6_port);
26988 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
26989 		    IPV4_VERSION : IPV6_VERSION;
26990 		v6addr = sin6->sin6_addr;
26991 		break;
26992 
26993 	default:
26994 		if (tcp->tcp_debug) {
26995 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26996 			    "tcp_bind: bad address length, %d", len);
26997 		}
26998 		return (EAFNOSUPPORT);
26999 		/* return (-TBADADDR); */
27000 	}
27001 
27002 	tcp->tcp_bound_source_v6 = v6addr;
27003 
27004 	/* Check for change in ipversion */
27005 	if (origipversion != tcp->tcp_ipversion) {
27006 		ASSERT(tcp->tcp_family == AF_INET6);
27007 		error = tcp->tcp_ipversion == IPV6_VERSION ?
27008 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
27009 		if (error) {
27010 			return (ENOMEM);
27011 		}
27012 	}
27013 
27014 	/*
27015 	 * Initialize family specific fields. Copy of the src addr.
27016 	 * in tcp_t is needed for the lookup funcs.
27017 	 */
27018 	if (tcp->tcp_ipversion == IPV6_VERSION) {
27019 		tcp->tcp_ip6h->ip6_src = v6addr;
27020 	} else {
27021 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
27022 	}
27023 	tcp->tcp_ip_src_v6 = v6addr;
27024 
27025 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
27026 
27027 	error = tcp_bind_select_lport(tcp, &requested_port,
27028 	    bind_to_req_port_only, cr);
27029 
27030 	return (error);
27031 }
27032 
27033 /*
27034  * Return unix error is tli error is TSYSERR, otherwise return a negative
27035  * tli error.
27036  */
27037 int
27038 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
27039     boolean_t bind_to_req_port_only)
27040 {
27041 	int error;
27042 	tcp_t *tcp = connp->conn_tcp;
27043 
27044 	if (tcp->tcp_state >= TCPS_BOUND) {
27045 		if (tcp->tcp_debug) {
27046 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27047 			    "tcp_bind: bad state, %d", tcp->tcp_state);
27048 		}
27049 		return (-TOUTSTATE);
27050 	}
27051 
27052 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
27053 	if (error != 0)
27054 		return (error);
27055 
27056 	ASSERT(tcp->tcp_state == TCPS_BOUND);
27057 
27058 	tcp->tcp_conn_req_max = 0;
27059 
27060 	/*
27061 	 * We need to make sure that the conn_recv is set to a non-null
27062 	 * value before we insert the conn into the classifier table.
27063 	 * This is to avoid a race with an incoming packet which does an
27064 	 * ipcl_classify().
27065 	 */
27066 	connp->conn_recv = tcp_conn_request;
27067 
27068 	if (tcp->tcp_family == AF_INET6) {
27069 		ASSERT(tcp->tcp_connp->conn_af_isv6);
27070 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27071 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
27072 	} else {
27073 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
27074 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
27075 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
27076 	}
27077 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27078 }
27079 
27080 int
27081 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
27082     socklen_t len, cred_t *cr)
27083 {
27084 	int 		error;
27085 	conn_t		*connp = (conn_t *)proto_handle;
27086 	squeue_t	*sqp = connp->conn_sqp;
27087 
27088 	ASSERT(sqp != NULL);
27089 
27090 	error = squeue_synch_enter(sqp, connp, 0);
27091 	if (error != 0) {
27092 		/* failed to enter */
27093 		return (ENOSR);
27094 	}
27095 
27096 	/* binding to a NULL address really means unbind */
27097 	if (sa == NULL) {
27098 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
27099 			error = tcp_do_unbind(connp);
27100 		else
27101 			error = EINVAL;
27102 	} else {
27103 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
27104 	}
27105 
27106 	squeue_synch_exit(sqp, connp);
27107 
27108 	if (error < 0) {
27109 		if (error == -TOUTSTATE)
27110 			error = EINVAL;
27111 		else
27112 			error = proto_tlitosyserr(-error);
27113 	}
27114 
27115 	return (error);
27116 }
27117 
27118 /*
27119  * If the return value from this function is positive, it's a UNIX error.
27120  * Otherwise, if it's negative, then the absolute value is a TLI error.
27121  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
27122  */
27123 int
27124 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
27125     cred_t *cr, pid_t pid)
27126 {
27127 	tcp_t		*tcp = connp->conn_tcp;
27128 	sin_t		*sin = (sin_t *)sa;
27129 	sin6_t		*sin6 = (sin6_t *)sa;
27130 	ipaddr_t	*dstaddrp;
27131 	in_port_t	dstport;
27132 	uint_t		srcid;
27133 	int		error = 0;
27134 
27135 	switch (len) {
27136 	default:
27137 		/*
27138 		 * Should never happen
27139 		 */
27140 		return (EINVAL);
27141 
27142 	case sizeof (sin_t):
27143 		sin = (sin_t *)sa;
27144 		if (sin->sin_port == 0) {
27145 			return (-TBADADDR);
27146 		}
27147 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
27148 			return (EAFNOSUPPORT);
27149 		}
27150 		break;
27151 
27152 	case sizeof (sin6_t):
27153 		sin6 = (sin6_t *)sa;
27154 		if (sin6->sin6_port == 0) {
27155 			return (-TBADADDR);
27156 		}
27157 		break;
27158 	}
27159 	/*
27160 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
27161 	 * make sure that the template IP header in the tcp structure is an
27162 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
27163 	 * need to this before we call tcp_bindi() so that the port lookup
27164 	 * code will look for ports in the correct port space (IPv4 and
27165 	 * IPv6 have separate port spaces).
27166 	 */
27167 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
27168 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
27169 		int err = 0;
27170 
27171 		err = tcp_header_init_ipv4(tcp);
27172 			if (err != 0) {
27173 				error = ENOMEM;
27174 				goto connect_failed;
27175 			}
27176 		if (tcp->tcp_lport != 0)
27177 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
27178 	}
27179 
27180 	switch (tcp->tcp_state) {
27181 	case TCPS_LISTEN:
27182 		/*
27183 		 * Listening sockets are not allowed to issue connect().
27184 		 */
27185 		if (IPCL_IS_NONSTR(connp))
27186 			return (EOPNOTSUPP);
27187 		/* FALLTHRU */
27188 	case TCPS_IDLE:
27189 		/*
27190 		 * We support quick connect, refer to comments in
27191 		 * tcp_connect_*()
27192 		 */
27193 		/* FALLTHRU */
27194 	case TCPS_BOUND:
27195 		/*
27196 		 * We must bump the generation before the operation start.
27197 		 * This is done to ensure that any upcall made later on sends
27198 		 * up the right generation to the socket.
27199 		 */
27200 		SOCK_CONNID_BUMP(tcp->tcp_connid);
27201 
27202 		if (tcp->tcp_family == AF_INET6) {
27203 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
27204 				return (tcp_connect_ipv6(tcp,
27205 				    &sin6->sin6_addr,
27206 				    sin6->sin6_port, sin6->sin6_flowinfo,
27207 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
27208 				    cr, pid));
27209 			}
27210 			/*
27211 			 * Destination adress is mapped IPv6 address.
27212 			 * Source bound address should be unspecified or
27213 			 * IPv6 mapped address as well.
27214 			 */
27215 			if (!IN6_IS_ADDR_UNSPECIFIED(
27216 			    &tcp->tcp_bound_source_v6) &&
27217 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
27218 				return (EADDRNOTAVAIL);
27219 			}
27220 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
27221 			dstport = sin6->sin6_port;
27222 			srcid = sin6->__sin6_src_id;
27223 		} else {
27224 			dstaddrp = &sin->sin_addr.s_addr;
27225 			dstport = sin->sin_port;
27226 			srcid = 0;
27227 		}
27228 
27229 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
27230 		    pid);
27231 		break;
27232 	default:
27233 		return (-TOUTSTATE);
27234 	}
27235 	/*
27236 	 * Note: Code below is the "failure" case
27237 	 */
27238 connect_failed:
27239 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
27240 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
27241 	return (error);
27242 }
27243 
27244 int
27245 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
27246     socklen_t len, sock_connid_t *id, cred_t *cr)
27247 {
27248 	conn_t		*connp = (conn_t *)proto_handle;
27249 	tcp_t		*tcp = connp->conn_tcp;
27250 	squeue_t	*sqp = connp->conn_sqp;
27251 	int		error;
27252 
27253 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
27254 	if (error != 0) {
27255 		return (error);
27256 	}
27257 
27258 	error = squeue_synch_enter(sqp, connp, 0);
27259 	if (error != 0) {
27260 		/* failed to enter */
27261 		return (ENOSR);
27262 	}
27263 
27264 	/*
27265 	 * TCP supports quick connect, so no need to do an implicit bind
27266 	 */
27267 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
27268 	if (error == 0) {
27269 		*id = connp->conn_tcp->tcp_connid;
27270 	} else if (error < 0) {
27271 		if (error == -TOUTSTATE) {
27272 			switch (connp->conn_tcp->tcp_state) {
27273 			case TCPS_SYN_SENT:
27274 				error = EALREADY;
27275 				break;
27276 			case TCPS_ESTABLISHED:
27277 				error = EISCONN;
27278 				break;
27279 			case TCPS_LISTEN:
27280 				error = EOPNOTSUPP;
27281 				break;
27282 			default:
27283 				error = EINVAL;
27284 				break;
27285 			}
27286 		} else {
27287 			error = proto_tlitosyserr(-error);
27288 		}
27289 	}
27290 done:
27291 	squeue_synch_exit(sqp, connp);
27292 
27293 	return ((error == 0) ? EINPROGRESS : error);
27294 }
27295 
27296 /* ARGSUSED */
27297 sock_lower_handle_t
27298 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
27299     uint_t *smodep, int *errorp, int flags, cred_t *credp)
27300 {
27301 	conn_t		*connp;
27302 	boolean_t	isv6 = family == AF_INET6;
27303 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
27304 	    (proto != 0 && proto != IPPROTO_TCP)) {
27305 		*errorp = EPROTONOSUPPORT;
27306 		return (NULL);
27307 	}
27308 
27309 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
27310 	if (connp == NULL) {
27311 		return (NULL);
27312 	}
27313 
27314 	/*
27315 	 * Put the ref for TCP. Ref for IP was already put
27316 	 * by ipcl_conn_create. Also Make the conn_t globally
27317 	 * visible to walkers
27318 	 */
27319 	mutex_enter(&connp->conn_lock);
27320 	CONN_INC_REF_LOCKED(connp);
27321 	ASSERT(connp->conn_ref == 2);
27322 	connp->conn_state_flags &= ~CONN_INCIPIENT;
27323 
27324 	connp->conn_flags |= IPCL_NONSTR;
27325 	mutex_exit(&connp->conn_lock);
27326 
27327 	ASSERT(errorp != NULL);
27328 	*errorp = 0;
27329 	*sock_downcalls = &sock_tcp_downcalls;
27330 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
27331 	    SM_SENDFILESUPP;
27332 
27333 	return ((sock_lower_handle_t)connp);
27334 }
27335 
27336 /* ARGSUSED */
27337 void
27338 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
27339     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
27340 {
27341 	conn_t *connp = (conn_t *)proto_handle;
27342 	struct sock_proto_props sopp;
27343 
27344 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
27345 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
27346 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
27347 
27348 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
27349 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
27350 	sopp.sopp_maxpsz = INFPSZ;
27351 	sopp.sopp_maxblk = INFPSZ;
27352 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
27353 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
27354 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
27355 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
27356 	    tcp_rinfo.mi_minpsz;
27357 
27358 	connp->conn_upcalls = sock_upcalls;
27359 	connp->conn_upper_handle = sock_handle;
27360 
27361 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
27362 }
27363 
27364 /* ARGSUSED */
27365 int
27366 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
27367 {
27368 	conn_t *connp = (conn_t *)proto_handle;
27369 
27370 	tcp_close_common(connp, flags);
27371 
27372 	ip_close_helper_stream(connp);
27373 
27374 	/*
27375 	 * Drop IP's reference on the conn. This is the last reference
27376 	 * on the connp if the state was less than established. If the
27377 	 * connection has gone into timewait state, then we will have
27378 	 * one ref for the TCP and one more ref (total of two) for the
27379 	 * classifier connected hash list (a timewait connections stays
27380 	 * in connected hash till closed).
27381 	 *
27382 	 * We can't assert the references because there might be other
27383 	 * transient reference places because of some walkers or queued
27384 	 * packets in squeue for the timewait state.
27385 	 */
27386 	CONN_DEC_REF(connp);
27387 	return (0);
27388 }
27389 
27390 /* ARGSUSED */
27391 int
27392 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
27393     cred_t *cr)
27394 {
27395 	tcp_t		*tcp;
27396 	uint32_t	msize;
27397 	conn_t *connp = (conn_t *)proto_handle;
27398 	int32_t		tcpstate;
27399 
27400 	ASSERT(connp->conn_ref >= 2);
27401 
27402 	if (msg->msg_controllen != 0) {
27403 		return (EOPNOTSUPP);
27404 
27405 	}
27406 	switch (DB_TYPE(mp)) {
27407 	case M_DATA:
27408 		tcp = connp->conn_tcp;
27409 		ASSERT(tcp != NULL);
27410 
27411 		tcpstate = tcp->tcp_state;
27412 		if (tcpstate < TCPS_ESTABLISHED) {
27413 			freemsg(mp);
27414 			return (ENOTCONN);
27415 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
27416 			freemsg(mp);
27417 			return (EPIPE);
27418 		}
27419 
27420 		msize = msgdsize(mp);
27421 
27422 		mutex_enter(&tcp->tcp_non_sq_lock);
27423 		tcp->tcp_squeue_bytes += msize;
27424 		/*
27425 		 * Squeue Flow Control
27426 		 */
27427 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
27428 			tcp_setqfull(tcp);
27429 		}
27430 		mutex_exit(&tcp->tcp_non_sq_lock);
27431 
27432 		/*
27433 		 * The application may pass in an address in the msghdr, but
27434 		 * we ignore the address on connection-oriented sockets.
27435 		 * Just like BSD this code does not generate an error for
27436 		 * TCP (a CONNREQUIRED socket) when sending to an address
27437 		 * passed in with sendto/sendmsg. Instead the data is
27438 		 * delivered on the connection as if no address had been
27439 		 * supplied.
27440 		 */
27441 		CONN_INC_REF(connp);
27442 
27443 		if (msg != NULL && msg->msg_flags & MSG_OOB) {
27444 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
27445 			    tcp_output_urgent, connp, tcp_squeue_flag,
27446 			    SQTAG_TCP_OUTPUT);
27447 		} else {
27448 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
27449 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
27450 		}
27451 
27452 		return (0);
27453 
27454 	default:
27455 		ASSERT(0);
27456 	}
27457 
27458 	freemsg(mp);
27459 	return (0);
27460 }
27461 
27462 /* ARGSUSED */
27463 void
27464 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
27465 {
27466 	int len;
27467 	uint32_t msize;
27468 	conn_t *connp = (conn_t *)arg;
27469 	tcp_t *tcp = connp->conn_tcp;
27470 
27471 	msize = msgdsize(mp);
27472 
27473 	len = msize - 1;
27474 	if (len < 0) {
27475 		freemsg(mp);
27476 		return;
27477 	}
27478 
27479 	/*
27480 	 * Try to force urgent data out on the wire.
27481 	 * Even if we have unsent data this will
27482 	 * at least send the urgent flag.
27483 	 * XXX does not handle more flag correctly.
27484 	 */
27485 	len += tcp->tcp_unsent;
27486 	len += tcp->tcp_snxt;
27487 	tcp->tcp_urg = len;
27488 	tcp->tcp_valid_bits |= TCP_URG_VALID;
27489 
27490 	/* Bypass tcp protocol for fused tcp loopback */
27491 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
27492 		return;
27493 	tcp_wput_data(tcp, mp, B_TRUE);
27494 }
27495 
27496 /* ARGSUSED */
27497 int
27498 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27499     socklen_t *addrlen, cred_t *cr)
27500 {
27501 	sin_t   *sin;
27502 	sin6_t  *sin6;
27503 	conn_t	*connp = (conn_t *)proto_handle;
27504 	tcp_t	*tcp = connp->conn_tcp;
27505 
27506 	ASSERT(tcp != NULL);
27507 	if (tcp->tcp_state < TCPS_SYN_RCVD)
27508 		return (ENOTCONN);
27509 
27510 	addr->sa_family = tcp->tcp_family;
27511 	switch (tcp->tcp_family) {
27512 	case AF_INET:
27513 		if (*addrlen < sizeof (sin_t))
27514 			return (EINVAL);
27515 
27516 		sin = (sin_t *)addr;
27517 		*sin = sin_null;
27518 		sin->sin_family = AF_INET;
27519 		if (tcp->tcp_ipversion == IPV4_VERSION) {
27520 			IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
27521 			    sin->sin_addr.s_addr);
27522 		}
27523 		sin->sin_port = tcp->tcp_fport;
27524 		*addrlen = sizeof (struct sockaddr_in);
27525 		break;
27526 	case AF_INET6:
27527 		sin6 = (sin6_t *)addr;
27528 		*sin6 = sin6_null;
27529 		sin6->sin6_family = AF_INET6;
27530 
27531 		if (*addrlen < sizeof (struct sockaddr_in6))
27532 			return (EINVAL);
27533 
27534 		if (tcp->tcp_ipversion == IPV6_VERSION) {
27535 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
27536 			    ~IPV6_VERS_AND_FLOW_MASK;
27537 		}
27538 
27539 		sin6->sin6_addr = tcp->tcp_remote_v6;
27540 		sin6->sin6_port = tcp->tcp_fport;
27541 		*addrlen = sizeof (struct sockaddr_in6);
27542 		break;
27543 	}
27544 	return (0);
27545 }
27546 
27547 /* ARGSUSED */
27548 int
27549 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27550     socklen_t *addrlenp, cred_t *cr)
27551 {
27552 	sin_t   *sin;
27553 	sin6_t  *sin6;
27554 	conn_t	*connp = (conn_t *)proto_handle;
27555 	tcp_t	*tcp = connp->conn_tcp;
27556 
27557 	switch (tcp->tcp_family) {
27558 	case AF_INET:
27559 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
27560 		if (*addrlenp < sizeof (sin_t))
27561 			return (EINVAL);
27562 		sin = (sin_t *)addr;
27563 		*sin = sin_null;
27564 		sin->sin_family = AF_INET;
27565 		*addrlenp = sizeof (sin_t);
27566 		if (tcp->tcp_state >= TCPS_BOUND) {
27567 			sin->sin_addr.s_addr =  tcp->tcp_ipha->ipha_src;
27568 			sin->sin_port = tcp->tcp_lport;
27569 		}
27570 		break;
27571 
27572 	case AF_INET6:
27573 		if (*addrlenp < sizeof (sin6_t))
27574 			return (EINVAL);
27575 		sin6 = (sin6_t *)addr;
27576 		*sin6 = sin6_null;
27577 		sin6->sin6_family = AF_INET6;
27578 		*addrlenp = sizeof (sin6_t);
27579 		if (tcp->tcp_state >= TCPS_BOUND) {
27580 			sin6->sin6_port = tcp->tcp_lport;
27581 			if (tcp->tcp_ipversion == IPV4_VERSION) {
27582 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
27583 				    &sin6->sin6_addr);
27584 			} else {
27585 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
27586 			}
27587 		}
27588 		break;
27589 	}
27590 	return (0);
27591 }
27592 
27593 /*
27594  * tcp_fallback
27595  *
27596  * A direct socket is falling back to using STREAMS. Hanging
27597  * off of the queue is a temporary tcp_t, which was created using
27598  * tcp_open(). The tcp_open() was called as part of the regular
27599  * sockfs create path, i.e., the SO_SOCKSTR flag is passed down,
27600  * and therefore the temporary tcp_t is marked to be a socket
27601  * (i.e., IPCL_SOCKET, tcp_issocket). So the optimizations
27602  * introduced by FireEngine will be used.
27603  *
27604  * The tcp_t associated with the socket falling back will
27605  * still be marked as a socket, although the direct socket flag
27606  * (IPCL_NONSTR) is removed. A fall back to true TPI semantics
27607  * will not take place until a _SIOCSOCKFALLBACK ioctl is issued.
27608  *
27609  * If the above mentioned behavior, i.e., the tmp tcp_t is created
27610  * as a STREAMS/TPI endpoint, then we will need to do more work here.
27611  * Such as inserting the direct socket into the acceptor hash.
27612  */
27613 void
27614 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
27615     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
27616 {
27617 	tcp_t			*tcp, *eager;
27618 	conn_t 			*connp = (conn_t *)proto_handle;
27619 	int			error;
27620 	struct T_capability_ack tca;
27621 	struct sockaddr_in6	laddr, faddr;
27622 	socklen_t 		laddrlen, faddrlen;
27623 	short			opts;
27624 	struct stroptions	*stropt;
27625 	mblk_t			*stropt_mp;
27626 	mblk_t			*mp;
27627 	mblk_t			*conn_ind_head = NULL;
27628 	mblk_t			*conn_ind_tail = NULL;
27629 	mblk_t			*ordrel_mp;
27630 	mblk_t			*fused_sigurp_mp;
27631 
27632 	tcp = connp->conn_tcp;
27633 	/*
27634 	 * No support for acceptor fallback
27635 	 */
27636 	ASSERT(q->q_qinfo != &tcp_acceptor_rinit);
27637 
27638 	stropt_mp = allocb_wait(sizeof (*stropt), BPRI_HI, STR_NOSIG, NULL);
27639 
27640 	/* Pre-allocate the T_ordrel_ind mblk. */
27641 	ASSERT(tcp->tcp_ordrel_mp == NULL);
27642 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
27643 	    STR_NOSIG, NULL);
27644 	ordrel_mp->b_datap->db_type = M_PROTO;
27645 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
27646 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
27647 
27648 	/* Pre-allocate the M_PCSIG anyway */
27649 	fused_sigurp_mp = allocb_wait(1, BPRI_HI, STR_NOSIG, NULL);
27650 
27651 	/*
27652 	 * Enter the squeue so that no new packets can come in
27653 	 */
27654 	error = squeue_synch_enter(connp->conn_sqp, connp, 0);
27655 	if (error != 0) {
27656 		/* failed to enter, free all the pre-allocated messages. */
27657 		freeb(stropt_mp);
27658 		freeb(ordrel_mp);
27659 		freeb(fused_sigurp_mp);
27660 		return;
27661 	}
27662 
27663 	/* Disable I/OAT during fallback */
27664 	tcp->tcp_sodirect = NULL;
27665 
27666 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
27667 	connp->conn_minor_arena = WR(q)->q_ptr;
27668 
27669 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
27670 
27671 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
27672 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
27673 
27674 	WR(q)->q_qinfo = &tcp_sock_winit;
27675 
27676 	if (!direct_sockfs)
27677 		tcp_disable_direct_sockfs(tcp);
27678 
27679 	/*
27680 	 * free the helper stream
27681 	 */
27682 	ip_close_helper_stream(connp);
27683 
27684 	/*
27685 	 * Notify the STREAM head about options
27686 	 */
27687 	DB_TYPE(stropt_mp) = M_SETOPTS;
27688 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27689 	stropt_mp->b_wptr += sizeof (struct stroptions);
27690 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27691 	stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
27692 
27693 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
27694 	    tcp->tcp_tcps->tcps_wroff_xtra);
27695 	if (tcp->tcp_snd_sack_ok)
27696 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
27697 	stropt->so_hiwat = tcp->tcp_fused ?
27698 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
27699 	    MAX(tcp->tcp_recv_hiwater, tcp->tcp_tcps->tcps_sth_rcv_hiwat);
27700 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
27701 
27702 	putnext(RD(q), stropt_mp);
27703 
27704 	/*
27705 	 * Collect the information needed to sync with the sonode
27706 	 */
27707 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
27708 
27709 	laddrlen = faddrlen = sizeof (sin6_t);
27710 	(void) tcp_getsockname(proto_handle, (struct sockaddr *)&laddr,
27711 	    &laddrlen, CRED());
27712 	error = tcp_getpeername(proto_handle, (struct sockaddr *)&faddr,
27713 	    &faddrlen, CRED());
27714 	if (error != 0)
27715 		faddrlen = 0;
27716 
27717 	opts = 0;
27718 	if (tcp->tcp_oobinline)
27719 		opts |= SO_OOBINLINE;
27720 	if (tcp->tcp_dontroute)
27721 		opts |= SO_DONTROUTE;
27722 
27723 	/*
27724 	 * Notify the socket that the protocol is now quiescent,
27725 	 * and it's therefore safe move data from the socket
27726 	 * to the stream head.
27727 	 */
27728 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
27729 	    (struct sockaddr *)&laddr, laddrlen,
27730 	    (struct sockaddr *)&faddr, faddrlen, opts);
27731 
27732 	while ((mp = tcp->tcp_rcv_list) != NULL) {
27733 		tcp->tcp_rcv_list = mp->b_next;
27734 		mp->b_next = NULL;
27735 		putnext(q, mp);
27736 	}
27737 	tcp->tcp_rcv_last_head = NULL;
27738 	tcp->tcp_rcv_last_tail = NULL;
27739 	tcp->tcp_rcv_cnt = 0;
27740 
27741 	/*
27742 	 * No longer a direct socket
27743 	 */
27744 	connp->conn_flags &= ~IPCL_NONSTR;
27745 
27746 	tcp->tcp_ordrel_mp = ordrel_mp;
27747 
27748 	if (tcp->tcp_fused) {
27749 		ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
27750 		tcp->tcp_fused_sigurg_mp = fused_sigurp_mp;
27751 	} else {
27752 		freeb(fused_sigurp_mp);
27753 	}
27754 
27755 	/*
27756 	 * Send T_CONN_IND messages for all ESTABLISHED connections.
27757 	 */
27758 	mutex_enter(&tcp->tcp_eager_lock);
27759 	for (eager = tcp->tcp_eager_next_q; eager != NULL;
27760 	    eager = eager->tcp_eager_next_q) {
27761 		mp = eager->tcp_conn.tcp_eager_conn_ind;
27762 
27763 		eager->tcp_conn.tcp_eager_conn_ind = NULL;
27764 		ASSERT(mp != NULL);
27765 		/*
27766 		 * TLI/XTI applications will get confused by
27767 		 * sending eager as an option since it violates
27768 		 * the option semantics. So remove the eager as
27769 		 * option since TLI/XTI app doesn't need it anyway.
27770 		 */
27771 		if (!TCP_IS_SOCKET(tcp)) {
27772 			struct T_conn_ind *conn_ind;
27773 
27774 			conn_ind = (struct T_conn_ind *)mp->b_rptr;
27775 			conn_ind->OPT_length = 0;
27776 			conn_ind->OPT_offset = 0;
27777 		}
27778 		if (conn_ind_head == NULL) {
27779 			conn_ind_head = mp;
27780 		} else {
27781 			conn_ind_tail->b_next = mp;
27782 		}
27783 		conn_ind_tail = mp;
27784 	}
27785 	mutex_exit(&tcp->tcp_eager_lock);
27786 
27787 	mp = conn_ind_head;
27788 	while (mp != NULL) {
27789 		mblk_t *nmp = mp->b_next;
27790 		mp->b_next = NULL;
27791 
27792 		putnext(tcp->tcp_rq, mp);
27793 		mp = nmp;
27794 	}
27795 
27796 	/*
27797 	 * There should be atleast two ref's (IP + TCP)
27798 	 */
27799 	ASSERT(connp->conn_ref >= 2);
27800 	squeue_synch_exit(connp->conn_sqp, connp);
27801 }
27802 
27803 /* ARGSUSED */
27804 static void
27805 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
27806 {
27807 	conn_t 	*connp = (conn_t *)arg;
27808 	tcp_t	*tcp = connp->conn_tcp;
27809 
27810 	freemsg(mp);
27811 
27812 	if (tcp->tcp_fused)
27813 		tcp_unfuse(tcp);
27814 
27815 	if (tcp_xmit_end(tcp) != 0) {
27816 		/*
27817 		 * We were crossing FINs and got a reset from
27818 		 * the other side. Just ignore it.
27819 		 */
27820 		if (tcp->tcp_debug) {
27821 			(void) strlog(TCP_MOD_ID, 0, 1,
27822 			    SL_ERROR|SL_TRACE,
27823 			    "tcp_shutdown_output() out of state %s",
27824 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
27825 		}
27826 	}
27827 }
27828 
27829 /* ARGSUSED */
27830 int
27831 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
27832 {
27833 	conn_t  *connp = (conn_t *)proto_handle;
27834 	tcp_t   *tcp = connp->conn_tcp;
27835 
27836 	/*
27837 	 * X/Open requires that we check the connected state.
27838 	 */
27839 	if (tcp->tcp_state < TCPS_SYN_SENT)
27840 		return (ENOTCONN);
27841 
27842 	/* shutdown the send side */
27843 	if (how != SHUT_RD) {
27844 		mblk_t *bp;
27845 
27846 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
27847 		CONN_INC_REF(connp);
27848 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
27849 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
27850 
27851 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27852 		    SOCK_OPCTL_SHUT_SEND, 0);
27853 	}
27854 
27855 	/* shutdown the recv side */
27856 	if (how != SHUT_WR)
27857 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27858 		    SOCK_OPCTL_SHUT_RECV, 0);
27859 
27860 	return (0);
27861 }
27862 
27863 /*
27864  * SOP_LISTEN() calls into tcp_listen().
27865  */
27866 /* ARGSUSED */
27867 int
27868 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27869 {
27870 	conn_t	*connp = (conn_t *)proto_handle;
27871 	int 	error;
27872 	squeue_t *sqp = connp->conn_sqp;
27873 
27874 	error = squeue_synch_enter(sqp, connp, 0);
27875 	if (error != 0) {
27876 		/* failed to enter */
27877 		return (ENOBUFS);
27878 	}
27879 
27880 	error = tcp_do_listen(connp, backlog, cr);
27881 	if (error == 0) {
27882 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27883 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
27884 	} else if (error < 0) {
27885 		if (error == -TOUTSTATE)
27886 			error = EINVAL;
27887 		else
27888 			error = proto_tlitosyserr(-error);
27889 	}
27890 	squeue_synch_exit(sqp, connp);
27891 	return (error);
27892 }
27893 
27894 static int
27895 tcp_do_listen(conn_t *connp, int backlog, cred_t *cr)
27896 {
27897 	tcp_t		*tcp = connp->conn_tcp;
27898 	sin_t		*sin;
27899 	sin6_t  	*sin6;
27900 	int		error = 0;
27901 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27902 
27903 	if (tcp->tcp_state >= TCPS_BOUND) {
27904 		if ((tcp->tcp_state == TCPS_BOUND ||
27905 		    tcp->tcp_state == TCPS_LISTEN) &&
27906 		    backlog > 0) {
27907 			/*
27908 			 * Handle listen() increasing backlog.
27909 			 * This is more "liberal" then what the TPI spec
27910 			 * requires but is needed to avoid a t_unbind
27911 			 * when handling listen() since the port number
27912 			 * might be "stolen" between the unbind and bind.
27913 			 */
27914 			goto do_listen;
27915 		}
27916 		if (tcp->tcp_debug) {
27917 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27918 			    "tcp_bind: bad state, %d", tcp->tcp_state);
27919 		}
27920 		return (-TOUTSTATE);
27921 	} else {
27922 		int32_t len;
27923 		sin6_t	addr;
27924 
27925 		/* Do an implicit bind: Request for a generic port. */
27926 		if (tcp->tcp_family == AF_INET) {
27927 			len = sizeof (sin_t);
27928 			sin = (sin_t *)&addr;
27929 			*sin = sin_null;
27930 			sin->sin_family = AF_INET;
27931 			tcp->tcp_ipversion = IPV4_VERSION;
27932 		} else {
27933 			ASSERT(tcp->tcp_family == AF_INET6);
27934 			len = sizeof (sin6_t);
27935 			sin6 = (sin6_t *)&addr;
27936 			*sin6 = sin6_null;
27937 			sin6->sin6_family = AF_INET6;
27938 			tcp->tcp_ipversion = IPV6_VERSION;
27939 		}
27940 
27941 		error = tcp_bind_check(connp, (struct sockaddr *)&addr, len,
27942 		    cr, B_FALSE);
27943 		if (error)
27944 			return (error);
27945 		/* Fall through and do the fanout insertion */
27946 	}
27947 
27948 do_listen:
27949 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
27950 	tcp->tcp_conn_req_max = backlog;
27951 	if (tcp->tcp_conn_req_max) {
27952 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
27953 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
27954 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
27955 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
27956 		/*
27957 		 * If this is a listener, do not reset the eager list
27958 		 * and other stuffs.  Note that we don't check if the
27959 		 * existing eager list meets the new tcp_conn_req_max
27960 		 * requirement.
27961 		 */
27962 		if (tcp->tcp_state != TCPS_LISTEN) {
27963 			tcp->tcp_state = TCPS_LISTEN;
27964 			/* Initialize the chain. Don't need the eager_lock */
27965 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
27966 			tcp->tcp_eager_next_drop_q0 = tcp;
27967 			tcp->tcp_eager_prev_drop_q0 = tcp;
27968 			tcp->tcp_second_ctimer_threshold =
27969 			    tcps->tcps_ip_abort_linterval;
27970 		}
27971 	}
27972 
27973 	/*
27974 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
27975 	 * processing continues in tcp_rput_other().
27976 	 *
27977 	 * We need to make sure that the conn_recv is set to a non-null
27978 	 * value before we insert the conn into the classifier table.
27979 	 * This is to avoid a race with an incoming packet which does an
27980 	 * ipcl_classify().
27981 	 */
27982 	connp->conn_recv = tcp_conn_request;
27983 	if (tcp->tcp_family == AF_INET) {
27984 		error = ip_proto_bind_laddr_v4(connp, NULL,
27985 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
27986 	} else {
27987 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27988 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
27989 	}
27990 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27991 }
27992 
27993 void
27994 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
27995 {
27996 	conn_t  *connp = (conn_t *)proto_handle;
27997 	tcp_t	*tcp = connp->conn_tcp;
27998 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27999 	uint_t thwin;
28000 
28001 	(void) squeue_synch_enter(connp->conn_sqp, connp, 0);
28002 
28003 	/* Flow control condition has been removed. */
28004 	tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
28005 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
28006 	    << tcp->tcp_rcv_ws;
28007 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
28008 	/*
28009 	 * Send back a window update immediately if TCP is above
28010 	 * ESTABLISHED state and the increase of the rcv window
28011 	 * that the other side knows is at least 1 MSS after flow
28012 	 * control is lifted.
28013 	 */
28014 	if (tcp->tcp_state >= TCPS_ESTABLISHED &&
28015 	    (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss)) {
28016 		tcp_xmit_ctl(NULL, tcp,
28017 		    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
28018 		    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
28019 		BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
28020 	}
28021 
28022 	squeue_synch_exit(connp->conn_sqp, connp);
28023 }
28024 
28025 /* ARGSUSED */
28026 int
28027 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
28028     int mode, int32_t *rvalp, cred_t *cr)
28029 {
28030 	conn_t  	*connp = (conn_t *)proto_handle;
28031 	int		error;
28032 
28033 	switch (cmd) {
28034 		case ND_SET:
28035 		case ND_GET:
28036 		case TCP_IOC_DEFAULT_Q:
28037 		case _SIOCSOCKFALLBACK:
28038 		case TCP_IOC_ABORT_CONN:
28039 		case TI_GETPEERNAME:
28040 		case TI_GETMYNAME:
28041 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
28042 			    cmd));
28043 			error = EINVAL;
28044 			break;
28045 		default:
28046 			/*
28047 			 * Pass on to IP using helper stream
28048 			 */
28049 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
28050 			    cmd, arg, mode, cr, rvalp);
28051 			break;
28052 	}
28053 	return (error);
28054 }
28055 
28056 sock_downcalls_t sock_tcp_downcalls = {
28057 	tcp_activate,
28058 	tcp_accept,
28059 	tcp_bind,
28060 	tcp_listen,
28061 	tcp_connect,
28062 	tcp_getpeername,
28063 	tcp_getsockname,
28064 	tcp_getsockopt,
28065 	tcp_setsockopt,
28066 	tcp_sendmsg,
28067 	NULL,
28068 	NULL,
28069 	NULL,
28070 	tcp_shutdown,
28071 	tcp_clr_flowctrl,
28072 	tcp_ioctl,
28073 	tcp_close,
28074 };
28075