xref: /titanic_41/usr/src/uts/common/inet/tcp/tcp.c (revision 634e26ec75c89095090605284938356a3145f2b8)
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 2010 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/strsun.h>
31 #include <sys/strsubr.h>
32 #include <sys/stropts.h>
33 #include <sys/strlog.h>
34 #define	_SUN_TPI_VERSION 2
35 #include <sys/tihdr.h>
36 #include <sys/timod.h>
37 #include <sys/ddi.h>
38 #include <sys/sunddi.h>
39 #include <sys/suntpi.h>
40 #include <sys/xti_inet.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/sdt.h>
44 #include <sys/vtrace.h>
45 #include <sys/kmem.h>
46 #include <sys/ethernet.h>
47 #include <sys/cpuvar.h>
48 #include <sys/dlpi.h>
49 #include <sys/pattr.h>
50 #include <sys/policy.h>
51 #include <sys/priv.h>
52 #include <sys/zone.h>
53 #include <sys/sunldi.h>
54 
55 #include <sys/errno.h>
56 #include <sys/signal.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
59 #include <sys/sockio.h>
60 #include <sys/isa_defs.h>
61 #include <sys/md5.h>
62 #include <sys/random.h>
63 #include <sys/uio.h>
64 #include <sys/systm.h>
65 #include <netinet/in.h>
66 #include <netinet/tcp.h>
67 #include <netinet/ip6.h>
68 #include <netinet/icmp6.h>
69 #include <net/if.h>
70 #include <net/route.h>
71 #include <inet/ipsec_impl.h>
72 
73 #include <inet/common.h>
74 #include <inet/ip.h>
75 #include <inet/ip_impl.h>
76 #include <inet/ip6.h>
77 #include <inet/ip_ndp.h>
78 #include <inet/proto_set.h>
79 #include <inet/mib2.h>
80 #include <inet/nd.h>
81 #include <inet/optcom.h>
82 #include <inet/snmpcom.h>
83 #include <inet/kstatcom.h>
84 #include <inet/tcp.h>
85 #include <inet/tcp_impl.h>
86 #include <inet/udp_impl.h>
87 #include <net/pfkeyv2.h>
88 #include <inet/ipdrop.h>
89 
90 #include <inet/ipclassifier.h>
91 #include <inet/ip_ire.h>
92 #include <inet/ip_ftable.h>
93 #include <inet/ip_if.h>
94 #include <inet/ipp_common.h>
95 #include <inet/ip_rts.h>
96 #include <inet/ip_netinfo.h>
97 #include <sys/squeue_impl.h>
98 #include <sys/squeue.h>
99 #include <inet/kssl/ksslapi.h>
100 #include <sys/tsol/label.h>
101 #include <sys/tsol/tnet.h>
102 #include <rpc/pmap_prot.h>
103 #include <sys/callo.h>
104 
105 #include <sys/clock_impl.h>	/* For LBOLT_FASTPATH{,64} */
106 
107 /*
108  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
109  *
110  * (Read the detailed design doc in PSARC case directory)
111  *
112  * The entire tcp state is contained in tcp_t and conn_t structure
113  * which are allocated in tandem using ipcl_conn_create() and passing
114  * IPCL_TCPCONN as a flag. We use 'conn_ref' and 'conn_lock' to protect
115  * the references on the tcp_t. The tcp_t structure is never compressed
116  * and packets always land on the correct TCP perimeter from the time
117  * eager is created till the time tcp_t dies (as such the old mentat
118  * TCP global queue is not used for detached state and no IPSEC checking
119  * is required). The global queue is still allocated to send out resets
120  * for connection which have no listeners and IP directly calls
121  * tcp_xmit_listeners_reset() which does any policy check.
122  *
123  * Protection and Synchronisation mechanism:
124  *
125  * The tcp data structure does not use any kind of lock for protecting
126  * its state but instead uses 'squeues' for mutual exclusion from various
127  * read and write side threads. To access a tcp member, the thread should
128  * always be behind squeue (via squeue_enter with flags as SQ_FILL, SQ_PROCESS,
129  * or SQ_NODRAIN). Since the squeues allow a direct function call, caller
130  * can pass any tcp function having prototype of edesc_t as argument
131  * (different from traditional STREAMs model where packets come in only
132  * designated entry points). The list of functions that can be directly
133  * called via squeue are listed before the usual function prototype.
134  *
135  * Referencing:
136  *
137  * TCP is MT-Hot and we use a reference based scheme to make sure that the
138  * tcp structure doesn't disappear when its needed. When the application
139  * creates an outgoing connection or accepts an incoming connection, we
140  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
141  * The IP reference is just a symbolic reference since ip_tcpclose()
142  * looks at tcp structure after tcp_close_output() returns which could
143  * have dropped the last TCP reference. So as long as the connection is
144  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
145  * conn_t. The classifier puts its own reference when the connection is
146  * inserted in listen or connected hash. Anytime a thread needs to enter
147  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
148  * on write side or by doing a classify on read side and then puts a
149  * reference on the conn before doing squeue_enter/tryenter/fill. For
150  * read side, the classifier itself puts the reference under fanout lock
151  * to make sure that tcp can't disappear before it gets processed. The
152  * squeue will drop this reference automatically so the called function
153  * doesn't have to do a DEC_REF.
154  *
155  * Opening a new connection:
156  *
157  * The outgoing connection open is pretty simple. tcp_open() does the
158  * work in creating the conn/tcp structure and initializing it. The
159  * squeue assignment is done based on the CPU the application
160  * is running on. So for outbound connections, processing is always done
161  * on application CPU which might be different from the incoming CPU
162  * being interrupted by the NIC. An optimal way would be to figure out
163  * the NIC <-> CPU binding at listen time, and assign the outgoing
164  * connection to the squeue attached to the CPU that will be interrupted
165  * for incoming packets (we know the NIC based on the bind IP address).
166  * This might seem like a problem if more data is going out but the
167  * fact is that in most cases the transmit is ACK driven transmit where
168  * the outgoing data normally sits on TCP's xmit queue waiting to be
169  * transmitted.
170  *
171  * Accepting a connection:
172  *
173  * This is a more interesting case because of various races involved in
174  * establishing a eager in its own perimeter. Read the meta comment on
175  * top of tcp_input_listener(). But briefly, the squeue is picked by
176  * ip_fanout based on the ring or the sender (if loopback).
177  *
178  * Closing a connection:
179  *
180  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
181  * via squeue to do the close and mark the tcp as detached if the connection
182  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
183  * reference but tcp_close() drop IP's reference always. So if tcp was
184  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
185  * and 1 because it is in classifier's connected hash. This is the condition
186  * we use to determine that its OK to clean up the tcp outside of squeue
187  * when time wait expires (check the ref under fanout and conn_lock and
188  * if it is 2, remove it from fanout hash and kill it).
189  *
190  * Although close just drops the necessary references and marks the
191  * tcp_detached state, tcp_close needs to know the tcp_detached has been
192  * set (under squeue) before letting the STREAM go away (because a
193  * inbound packet might attempt to go up the STREAM while the close
194  * has happened and tcp_detached is not set). So a special lock and
195  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
196  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
197  * tcp_detached.
198  *
199  * Special provisions and fast paths:
200  *
201  * We make special provisions for sockfs by marking tcp_issocket
202  * whenever we have only sockfs on top of TCP. This allows us to skip
203  * putting the tcp in acceptor hash since a sockfs listener can never
204  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
205  * since eager has already been allocated and the accept now happens
206  * on acceptor STREAM. There is a big blob of comment on top of
207  * tcp_input_listener explaining the new accept. When socket is POP'd,
208  * sockfs sends us an ioctl to mark the fact and we go back to old
209  * behaviour. Once tcp_issocket is unset, its never set for the
210  * life of that connection.
211  *
212  * IPsec notes :
213  *
214  * Since a packet is always executed on the correct TCP perimeter
215  * all IPsec processing is defered to IP including checking new
216  * connections and setting IPSEC policies for new connection. The
217  * only exception is tcp_xmit_listeners_reset() which is called
218  * directly from IP and needs to policy check to see if TH_RST
219  * can be sent out.
220  */
221 
222 /*
223  * Values for squeue switch:
224  * 1: SQ_NODRAIN
225  * 2: SQ_PROCESS
226  * 3: SQ_FILL
227  */
228 int tcp_squeue_wput = 2;	/* /etc/systems */
229 int tcp_squeue_flag;
230 
231 /*
232  * This controls how tiny a write must be before we try to copy it
233  * into the mblk on the tail of the transmit queue.  Not much
234  * speedup is observed for values larger than sixteen.  Zero will
235  * disable the optimisation.
236  */
237 int tcp_tx_pull_len = 16;
238 
239 /*
240  * TCP Statistics.
241  *
242  * How TCP statistics work.
243  *
244  * There are two types of statistics invoked by two macros.
245  *
246  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
247  * supposed to be used in non MT-hot paths of the code.
248  *
249  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
250  * supposed to be used for DEBUG purposes and may be used on a hot path.
251  *
252  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
253  * (use "kstat tcp" to get them).
254  *
255  * There is also additional debugging facility that marks tcp_clean_death()
256  * instances and saves them in tcp_t structure. It is triggered by
257  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
258  * tcp_clean_death() calls that counts the number of times each tag was hit. It
259  * is triggered by TCP_CLD_COUNTERS define.
260  *
261  * How to add new counters.
262  *
263  * 1) Add a field in the tcp_stat structure describing your counter.
264  * 2) Add a line in the template in tcp_kstat2_init() with the name
265  *    of the counter.
266  *
267  *    IMPORTANT!! - make sure that both are in sync !!
268  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
269  *
270  * Please avoid using private counters which are not kstat-exported.
271  *
272  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
273  * in tcp_t structure.
274  *
275  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
276  */
277 
278 #ifndef TCP_DEBUG_COUNTER
279 #ifdef DEBUG
280 #define	TCP_DEBUG_COUNTER 1
281 #else
282 #define	TCP_DEBUG_COUNTER 0
283 #endif
284 #endif
285 
286 #define	TCP_CLD_COUNTERS 0
287 
288 #define	TCP_TAG_CLEAN_DEATH 1
289 #define	TCP_MAX_CLEAN_DEATH_TAG 32
290 
291 #ifdef lint
292 static int _lint_dummy_;
293 #endif
294 
295 #if TCP_CLD_COUNTERS
296 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
297 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
298 #elif defined(lint)
299 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
300 #else
301 #define	TCP_CLD_STAT(x)
302 #endif
303 
304 #if TCP_DEBUG_COUNTER
305 #define	TCP_DBGSTAT(tcps, x)	\
306 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
307 #define	TCP_G_DBGSTAT(x)	\
308 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
309 #elif defined(lint)
310 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
311 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
312 #else
313 #define	TCP_DBGSTAT(tcps, x)
314 #define	TCP_G_DBGSTAT(x)
315 #endif
316 
317 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
318 
319 tcp_g_stat_t	tcp_g_statistics;
320 kstat_t		*tcp_g_kstat;
321 
322 /* Macros for timestamp comparisons */
323 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
324 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
325 
326 /*
327  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
328  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
329  * by adding three components: a time component which grows by 1 every 4096
330  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
331  * a per-connection component which grows by 125000 for every new connection;
332  * and an "extra" component that grows by a random amount centered
333  * approximately on 64000.  This causes the ISS generator to cycle every
334  * 4.89 hours if no TCP connections are made, and faster if connections are
335  * made.
336  *
337  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
338  * components: a time component which grows by 250000 every second; and
339  * a per-connection component which grows by 125000 for every new connections.
340  *
341  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
342  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
343  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
344  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
345  * password.
346  */
347 #define	ISS_INCR	250000
348 #define	ISS_NSEC_SHT	12
349 
350 static sin_t	sin_null;	/* Zero address for quick clears */
351 static sin6_t	sin6_null;	/* Zero address for quick clears */
352 
353 /*
354  * This implementation follows the 4.3BSD interpretation of the urgent
355  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
356  * incompatible changes in protocols like telnet and rlogin.
357  */
358 #define	TCP_OLD_URP_INTERPRETATION	1
359 
360 /*
361  * Since tcp_listener is not cleared atomically with tcp_detached
362  * being cleared we need this extra bit to tell a detached connection
363  * apart from one that is in the process of being accepted.
364  */
365 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
366 	(TCP_IS_DETACHED(tcp) &&	\
367 	    (!(tcp)->tcp_hard_binding))
368 
369 /*
370  * TCP reassembly macros.  We hide starting and ending sequence numbers in
371  * b_next and b_prev of messages on the reassembly queue.  The messages are
372  * chained using b_cont.  These macros are used in tcp_reass() so we don't
373  * have to see the ugly casts and assignments.
374  */
375 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
376 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
377 					(mblk_t *)(uintptr_t)(u))
378 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
379 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
380 					(mblk_t *)(uintptr_t)(u))
381 
382 /*
383  * Implementation of TCP Timers.
384  * =============================
385  *
386  * INTERFACE:
387  *
388  * There are two basic functions dealing with tcp timers:
389  *
390  *	timeout_id_t	tcp_timeout(connp, func, time)
391  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
392  *	TCP_TIMER_RESTART(tcp, intvl)
393  *
394  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
395  * after 'time' ticks passed. The function called by timeout() must adhere to
396  * the same restrictions as a driver soft interrupt handler - it must not sleep
397  * or call other functions that might sleep. The value returned is the opaque
398  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
399  * cancel the request. The call to tcp_timeout() may fail in which case it
400  * returns zero. This is different from the timeout(9F) function which never
401  * fails.
402  *
403  * The call-back function 'func' always receives 'connp' as its single
404  * argument. It is always executed in the squeue corresponding to the tcp
405  * structure. The tcp structure is guaranteed to be present at the time the
406  * call-back is called.
407  *
408  * NOTE: The call-back function 'func' is never called if tcp is in
409  * 	the TCPS_CLOSED state.
410  *
411  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
412  * request. locks acquired by the call-back routine should not be held across
413  * the call to tcp_timeout_cancel() or a deadlock may result.
414  *
415  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
416  * Otherwise, it returns an integer value greater than or equal to 0. In
417  * particular, if the call-back function is already placed on the squeue, it can
418  * not be canceled.
419  *
420  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
421  * 	within squeue context corresponding to the tcp instance. Since the
422  *	call-back is also called via the same squeue, there are no race
423  *	conditions described in untimeout(9F) manual page since all calls are
424  *	strictly serialized.
425  *
426  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
427  *	stored in tcp_timer_tid and starts a new one using
428  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
429  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
430  *	field.
431  *
432  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
433  *	call-back may still be called, so it is possible tcp_timer() will be
434  *	called several times. This should not be a problem since tcp_timer()
435  *	should always check the tcp instance state.
436  *
437  *
438  * IMPLEMENTATION:
439  *
440  * TCP timers are implemented using three-stage process. The call to
441  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
442  * when the timer expires. The tcp_timer_callback() arranges the call of the
443  * tcp_timer_handler() function via squeue corresponding to the tcp
444  * instance. The tcp_timer_handler() calls actual requested timeout call-back
445  * and passes tcp instance as an argument to it. Information is passed between
446  * stages using the tcp_timer_t structure which contains the connp pointer, the
447  * tcp call-back to call and the timeout id returned by the timeout(9F).
448  *
449  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
450  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
451  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
452  * returns the pointer to this mblk.
453  *
454  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
455  * looks like a normal mblk without actual dblk attached to it.
456  *
457  * To optimize performance each tcp instance holds a small cache of timer
458  * mblocks. In the current implementation it caches up to two timer mblocks per
459  * tcp instance. The cache is preserved over tcp frees and is only freed when
460  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
461  * timer processing happens on a corresponding squeue, the cache manipulation
462  * does not require any locks. Experiments show that majority of timer mblocks
463  * allocations are satisfied from the tcp cache and do not involve kmem calls.
464  *
465  * The tcp_timeout() places a refhold on the connp instance which guarantees
466  * that it will be present at the time the call-back function fires. The
467  * tcp_timer_handler() drops the reference after calling the call-back, so the
468  * call-back function does not need to manipulate the references explicitly.
469  */
470 
471 typedef struct tcp_timer_s {
472 	conn_t	*connp;
473 	void 	(*tcpt_proc)(void *);
474 	callout_id_t   tcpt_tid;
475 } tcp_timer_t;
476 
477 static kmem_cache_t *tcp_timercache;
478 kmem_cache_t	*tcp_sack_info_cache;
479 
480 /*
481  * For scalability, we must not run a timer for every TCP connection
482  * in TIME_WAIT state.  To see why, consider (for time wait interval of
483  * 4 minutes):
484  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
485  *
486  * This list is ordered by time, so you need only delete from the head
487  * until you get to entries which aren't old enough to delete yet.
488  * The list consists of only the detached TIME_WAIT connections.
489  *
490  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
491  * becomes detached TIME_WAIT (either by changing the state and already
492  * being detached or the other way around). This means that the TIME_WAIT
493  * state can be extended (up to doubled) if the connection doesn't become
494  * detached for a long time.
495  *
496  * The list manipulations (including tcp_time_wait_next/prev)
497  * are protected by the tcp_time_wait_lock. The content of the
498  * detached TIME_WAIT connections is protected by the normal perimeters.
499  *
500  * This list is per squeue and squeues are shared across the tcp_stack_t's.
501  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
502  * and conn_netstack.
503  * The tcp_t's that are added to tcp_free_list are disassociated and
504  * have NULL tcp_tcps and conn_netstack pointers.
505  */
506 typedef struct tcp_squeue_priv_s {
507 	kmutex_t	tcp_time_wait_lock;
508 	callout_id_t	tcp_time_wait_tid;
509 	tcp_t		*tcp_time_wait_head;
510 	tcp_t		*tcp_time_wait_tail;
511 	tcp_t		*tcp_free_list;
512 	uint_t		tcp_free_list_cnt;
513 } tcp_squeue_priv_t;
514 
515 /*
516  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
517  * Running it every 5 seconds seems to give the best results.
518  */
519 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
520 
521 /*
522  * To prevent memory hog, limit the number of entries in tcp_free_list
523  * to 1% of available memory / number of cpus
524  */
525 uint_t tcp_free_list_max_cnt = 0;
526 
527 #define	TCP_XMIT_LOWATER	4096
528 #define	TCP_XMIT_HIWATER	49152
529 #define	TCP_RECV_LOWATER	2048
530 #define	TCP_RECV_HIWATER	128000
531 
532 /*
533  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
534  */
535 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
536 
537 #define	TIDUSZ	4096	/* transport interface data unit size */
538 
539 /*
540  * Bind hash list size and has function.  It has to be a power of 2 for
541  * hashing.
542  */
543 #define	TCP_BIND_FANOUT_SIZE	512
544 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
545 
546 /*
547  * Size of acceptor hash list.  It has to be a power of 2 for hashing.
548  */
549 #define	TCP_ACCEPTOR_FANOUT_SIZE		256
550 
551 #ifdef	_ILP32
552 #define	TCP_ACCEPTOR_HASH(accid)					\
553 		(((uint_t)(accid) >> 8) & (TCP_ACCEPTOR_FANOUT_SIZE - 1))
554 #else
555 #define	TCP_ACCEPTOR_HASH(accid)					\
556 		((uint_t)(accid) & (TCP_ACCEPTOR_FANOUT_SIZE - 1))
557 #endif	/* _ILP32 */
558 
559 #define	IP_ADDR_CACHE_SIZE	2048
560 #define	IP_ADDR_CACHE_HASH(faddr)					\
561 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
562 
563 /*
564  * If there is a limit set on the number of connections allowed per each
565  * listener, the following struct is used to store that counter.  This needs
566  * to be separated from the listener since the listener can go away before
567  * all the connections are gone.  When the struct is allocated, tlc_cnt is set
568  * to 1.  When the listener goes away, tlc_cnt is decremented  by one.  And
569  * the last connection (or the listener) which decrements tlc_cnt to zero
570  * frees the struct.
571  *
572  * tlc_max is the threshold value tcps_conn_listen_port.  It is set when the
573  * tcp_listen_cnt_t is allocated.
574  *
575  * tlc_report_time stores the time when cmn_err() is called to report that the
576  * max has been exceeeded.  Report is done at most once every
577  * TCP_TLC_REPORT_INTERVAL mins for a listener.
578  *
579  * tlc_drop stores the number of connection attempt dropped because the
580  * limit has reached.
581  */
582 typedef struct tcp_listen_cnt_s {
583 	uint32_t	tlc_max;
584 	uint32_t	tlc_cnt;
585 	int64_t		tlc_report_time;
586 	uint32_t	tlc_drop;
587 } tcp_listen_cnt_t;
588 
589 #define	TCP_TLC_REPORT_INTERVAL	(1 * MINUTES)
590 
591 #define	TCP_DECR_LISTEN_CNT(tcp)					\
592 {									\
593 	ASSERT((tcp)->tcp_listen_cnt->tlc_cnt > 0);			\
594 	if (atomic_add_32_nv(&(tcp)->tcp_listen_cnt->tlc_cnt, -1) == 0) \
595 		kmem_free((tcp)->tcp_listen_cnt, sizeof (tcp_listen_cnt_t)); \
596 	(tcp)->tcp_listen_cnt = NULL;					\
597 }
598 
599 /* Minimum number of connections per listener. */
600 uint32_t tcp_min_conn_listener = 2;
601 
602 /*
603  * Linked list struct to store listener connection limit configuration per
604  * IP stack.
605  */
606 typedef struct tcp_listener_s {
607 	in_port_t	tl_port;
608 	uint32_t	tl_ratio;
609 	list_node_t	tl_link;
610 } tcp_listener_t;
611 
612 /*
613  * The shift factor applied to tcp_mss to decide if the peer sends us a
614  * valid initial receive window.  By default, if the peer receive window
615  * is smaller than 1 MSS (shift factor is 0), it is considered as invalid.
616  */
617 uint32_t tcp_init_wnd_shft = 0;
618 
619 /*
620  * When the system is under memory pressure, stack variable tcps_reclaim is
621  * true, we shorten the connection timeout abort interval to tcp_early_abort
622  * seconds.
623  */
624 uint32_t tcp_early_abort = 30;
625 
626 /*
627  * TCP options struct returned from tcp_parse_options.
628  */
629 typedef struct tcp_opt_s {
630 	uint32_t	tcp_opt_mss;
631 	uint32_t	tcp_opt_wscale;
632 	uint32_t	tcp_opt_ts_val;
633 	uint32_t	tcp_opt_ts_ecr;
634 	tcp_t		*tcp;
635 } tcp_opt_t;
636 
637 /*
638  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
639  */
640 
641 #ifdef _BIG_ENDIAN
642 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
643 	(TCPOPT_TSTAMP << 8) | 10)
644 #else
645 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
646 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
647 #endif
648 
649 /*
650  * Flags returned from tcp_parse_options.
651  */
652 #define	TCP_OPT_MSS_PRESENT	1
653 #define	TCP_OPT_WSCALE_PRESENT	2
654 #define	TCP_OPT_TSTAMP_PRESENT	4
655 #define	TCP_OPT_SACK_OK_PRESENT	8
656 #define	TCP_OPT_SACK_PRESENT	16
657 
658 /* TCP option length */
659 #define	TCPOPT_NOP_LEN		1
660 #define	TCPOPT_MAXSEG_LEN	4
661 #define	TCPOPT_WS_LEN		3
662 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
663 #define	TCPOPT_TSTAMP_LEN	10
664 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
665 #define	TCPOPT_SACK_OK_LEN	2
666 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
667 #define	TCPOPT_REAL_SACK_LEN	4
668 #define	TCPOPT_MAX_SACK_LEN	36
669 #define	TCPOPT_HEADER_LEN	2
670 
671 /* TCP cwnd burst factor. */
672 #define	TCP_CWND_INFINITE	65535
673 #define	TCP_CWND_SS		3
674 #define	TCP_CWND_NORMAL		5
675 
676 /* Maximum TCP initial cwin (start/restart). */
677 #define	TCP_MAX_INIT_CWND	8
678 
679 /*
680  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
681  * either tcp_slow_start_initial or tcp_slow_start_after idle
682  * depending on the caller.  If the upper layer has not used the
683  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
684  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
685  * If the upper layer has changed set the tcp_init_cwnd, just use
686  * it to calculate the tcp_cwnd.
687  */
688 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
689 {									\
690 	if ((tcp)->tcp_init_cwnd == 0) {				\
691 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
692 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
693 	} else {							\
694 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
695 	}								\
696 	tcp->tcp_cwnd_cnt = 0;						\
697 }
698 
699 /* TCP Timer control structure */
700 typedef struct tcpt_s {
701 	pfv_t	tcpt_pfv;	/* The routine we are to call */
702 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
703 } tcpt_t;
704 
705 /*
706  * Functions called directly via squeue having a prototype of edesc_t.
707  */
708 void		tcp_input_listener(void *arg, mblk_t *mp, void *arg2,
709     ip_recv_attr_t *ira);
710 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2,
711     ip_recv_attr_t *dummy);
712 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2,
713     ip_recv_attr_t *dummy);
714 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2,
715     ip_recv_attr_t *dummy);
716 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2,
717     ip_recv_attr_t *dummy);
718 void		tcp_input_data(void *arg, mblk_t *mp, void *arg2,
719     ip_recv_attr_t *ira);
720 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2,
721     ip_recv_attr_t *dummy);
722 void		tcp_output(void *arg, mblk_t *mp, void *arg2,
723     ip_recv_attr_t *dummy);
724 void		tcp_output_urgent(void *arg, mblk_t *mp, void *arg2,
725     ip_recv_attr_t *dummy);
726 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2,
727     ip_recv_attr_t *dummy);
728 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2,
729     ip_recv_attr_t *dummy);
730 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2,
731     ip_recv_attr_t *dummy);
732 static void	tcp_send_synack(void *arg, mblk_t *mp, void *arg2,
733     ip_recv_attr_t *dummy);
734 
735 
736 /* Prototype for TCP functions */
737 static void	tcp_random_init(void);
738 int		tcp_random(void);
739 static void	tcp_tli_accept(tcp_t *tcp, mblk_t *mp);
740 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
741 		    tcp_t *eager);
742 static int	tcp_set_destination(tcp_t *tcp);
743 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
744     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
745     boolean_t user_specified);
746 static void	tcp_closei_local(tcp_t *tcp);
747 static void	tcp_close_detached(tcp_t *tcp);
748 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr,
749 		    mblk_t *idmp, mblk_t **defermp, ip_recv_attr_t *ira);
750 static void	tcp_tpi_connect(tcp_t *tcp, mblk_t *mp);
751 static int	tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
752 		    in_port_t dstport, uint_t srcid);
753 static int	tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
754 		    in_port_t dstport, uint32_t flowinfo,
755 		    uint_t srcid, uint32_t scope_id);
756 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
757 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
758 static char	*tcp_display(tcp_t *tcp, char *, char);
759 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
760 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
761 static void	tcp_eager_unlink(tcp_t *tcp);
762 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
763 		    int unixerr);
764 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
765 		    int tlierr, int unixerr);
766 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
767 		    cred_t *cr);
768 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
769 		    char *value, caddr_t cp, cred_t *cr);
770 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
771 		    char *value, caddr_t cp, cred_t *cr);
772 static int	tcp_tpistate(tcp_t *tcp);
773 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
774     int caller_holds_lock);
775 static void	tcp_bind_hash_remove(tcp_t *tcp);
776 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
777 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
778 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
779 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
780 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
781 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
782 static void	tcp_init_values(tcp_t *tcp);
783 static void	tcp_ip_notify(tcp_t *tcp);
784 static void	tcp_iss_init(tcp_t *tcp);
785 static void	tcp_keepalive_killer(void *arg);
786 static int	tcp_parse_options(tcpha_t *tcpha, tcp_opt_t *tcpopt);
787 static void	tcp_mss_set(tcp_t *tcp, uint32_t size);
788 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
789 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
790 static boolean_t tcp_allow_connopt_set(int level, int name);
791 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
792 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
793 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
794     tcp_stack_t *);
795 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
796 		    caddr_t cp, cred_t *cr);
797 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
798 		    caddr_t cp, cred_t *cr);
799 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
800 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
801 		    caddr_t cp, cred_t *cr);
802 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
803 static void	tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt);
804 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
805 static void	tcp_reass_timer(void *arg);
806 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
807 static void	tcp_reinit(tcp_t *tcp);
808 static void	tcp_reinit_values(tcp_t *tcp);
809 
810 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
811 static uint_t	tcp_rcv_drain(tcp_t *tcp);
812 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
813 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
814 static void	tcp_ss_rexmit(tcp_t *tcp);
815 static mblk_t	*tcp_input_add_ancillary(tcp_t *tcp, mblk_t *mp, ip_pkt_t *ipp,
816     ip_recv_attr_t *);
817 static void	tcp_process_options(tcp_t *, tcpha_t *);
818 static void	tcp_rsrv(queue_t *q);
819 static int	tcp_snmp_state(tcp_t *tcp);
820 static void	tcp_timer(void *arg);
821 static void	tcp_timer_callback(void *);
822 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
823     boolean_t random);
824 static in_port_t tcp_get_next_priv_port(const tcp_t *);
825 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
826 static void	tcp_wput_fallback(queue_t *q, mblk_t *mp);
827 void		tcp_tpi_accept(queue_t *q, mblk_t *mp);
828 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
829 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
830 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
831 static int	tcp_send(tcp_t *tcp, const int mss,
832 		    const int total_hdr_len, const int tcp_hdr_len,
833 		    const int num_sack_blk, int *usable, uint_t *snxt,
834 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time);
835 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
836 		    int num_sack_blk);
837 static void	tcp_wsrv(queue_t *q);
838 static int	tcp_xmit_end(tcp_t *tcp);
839 static void	tcp_ack_timer(void *arg);
840 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
841 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
842 		    uint32_t seq, uint32_t ack, int ctl, ip_recv_attr_t *,
843 		    ip_stack_t *, conn_t *);
844 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
845 		    uint32_t ack, int ctl);
846 static void	tcp_set_rto(tcp_t *, time_t);
847 static void	tcp_icmp_input(void *, mblk_t *, void *, ip_recv_attr_t *);
848 static void	tcp_icmp_error_ipv6(tcp_t *, mblk_t *, ip_recv_attr_t *);
849 static boolean_t tcp_verifyicmp(conn_t *, void *, icmph_t *, icmp6_t *,
850     ip_recv_attr_t *);
851 static int	tcp_build_hdrs(tcp_t *);
852 static void	tcp_time_wait_append(tcp_t *tcp);
853 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
854     uint32_t seg_seq, uint32_t seg_ack, int seg_len, tcpha_t *tcpha,
855     ip_recv_attr_t *ira);
856 boolean_t	tcp_paws_check(tcp_t *tcp, tcpha_t *tcpha, tcp_opt_t *tcpoptp);
857 static boolean_t tcp_zcopy_check(tcp_t *);
858 static void	tcp_zcopy_notify(tcp_t *);
859 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, boolean_t);
860 static void	tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa);
861 static void	tcp_update_pmtu(tcp_t *tcp, boolean_t decrease_only);
862 static void	tcp_update_zcopy(tcp_t *tcp);
863 static void	tcp_notify(void *, ip_xmit_attr_t *, ixa_notify_type_t,
864     ixa_notify_arg_t);
865 static void	tcp_rexmit_after_error(tcp_t *tcp);
866 static void	tcp_send_data(tcp_t *, mblk_t *);
867 extern mblk_t	*tcp_timermp_alloc(int);
868 extern void	tcp_timermp_free(tcp_t *);
869 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
870 static void	tcp_stop_lingering(tcp_t *tcp);
871 static void	tcp_close_linger_timeout(void *arg);
872 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
873 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
874 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
875 static void	tcp_g_kstat_fini(kstat_t *);
876 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
877 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
878 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
879 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
880 static int	tcp_kstat_update(kstat_t *kp, int rw);
881 static mblk_t	*tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
882     ip_recv_attr_t *ira);
883 static mblk_t	*tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, mblk_t *mp,
884     ip_recv_attr_t *ira);
885 static int	tcp_squeue_switch(int);
886 
887 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
888 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
889 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
890 static int	tcp_tpi_close(queue_t *, int);
891 static int	tcp_tpi_close_accept(queue_t *);
892 
893 static void	tcp_squeue_add(squeue_t *);
894 static void	tcp_setcred_data(mblk_t *, ip_recv_attr_t *);
895 
896 extern void	tcp_kssl_input(tcp_t *, mblk_t *, cred_t *);
897 
898 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy);
899 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2,
900     ip_recv_attr_t *dummy);
901 
902 static int tcp_accept(sock_lower_handle_t, sock_lower_handle_t,
903 	    sock_upper_handle_t, cred_t *);
904 static int tcp_listen(sock_lower_handle_t, int, cred_t *);
905 static int tcp_do_listen(conn_t *, struct sockaddr *, socklen_t, int, cred_t *,
906     boolean_t);
907 static int tcp_do_connect(conn_t *, const struct sockaddr *, socklen_t,
908     cred_t *, pid_t);
909 static int tcp_do_bind(conn_t *, struct sockaddr *, socklen_t, cred_t *,
910     boolean_t);
911 static int tcp_do_unbind(conn_t *);
912 static int tcp_bind_check(conn_t *, struct sockaddr *, socklen_t, cred_t *,
913     boolean_t);
914 
915 static void tcp_ulp_newconn(conn_t *, conn_t *, mblk_t *);
916 
917 static uint32_t tcp_find_listener_conf(tcp_stack_t *, in_port_t);
918 static int tcp_listener_conf_get(queue_t *, mblk_t *, caddr_t, cred_t *);
919 static int tcp_listener_conf_add(queue_t *, mblk_t *, char *, caddr_t,
920     cred_t *);
921 static int tcp_listener_conf_del(queue_t *, mblk_t *, char *, caddr_t,
922     cred_t *);
923 static void tcp_listener_conf_cleanup(tcp_stack_t *);
924 
925 /*
926  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
927  *
928  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
929  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
930  * (defined in tcp.h) needs to be filled in and passed into the kernel
931  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
932  * structure contains the four-tuple of a TCP connection and a range of TCP
933  * states (specified by ac_start and ac_end). The use of wildcard addresses
934  * and ports is allowed. Connections with a matching four tuple and a state
935  * within the specified range will be aborted. The valid states for the
936  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
937  * inclusive.
938  *
939  * An application which has its connection aborted by this ioctl will receive
940  * an error that is dependent on the connection state at the time of the abort.
941  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
942  * though a RST packet has been received.  If the connection state is equal to
943  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
944  * and all resources associated with the connection will be freed.
945  */
946 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
947 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
948 static void	tcp_ioctl_abort_handler(void *arg, mblk_t *mp, void *arg2,
949     ip_recv_attr_t *dummy);
950 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
951 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
952 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
953     boolean_t, tcp_stack_t *);
954 
955 static struct module_info tcp_rinfo =  {
956 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
957 };
958 
959 static struct module_info tcp_winfo =  {
960 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
961 };
962 
963 /*
964  * Entry points for TCP as a device. The normal case which supports
965  * the TCP functionality.
966  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
967  */
968 struct qinit tcp_rinitv4 = {
969 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, NULL, &tcp_rinfo
970 };
971 
972 struct qinit tcp_rinitv6 = {
973 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_tpi_close, NULL, &tcp_rinfo
974 };
975 
976 struct qinit tcp_winit = {
977 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
978 };
979 
980 /* Initial entry point for TCP in socket mode. */
981 struct qinit tcp_sock_winit = {
982 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
983 };
984 
985 /* TCP entry point during fallback */
986 struct qinit tcp_fallback_sock_winit = {
987 	(pfi_t)tcp_wput_fallback, NULL, NULL, NULL, NULL, &tcp_winfo
988 };
989 
990 /*
991  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
992  * an accept. Avoid allocating data structures since eager has already
993  * been created.
994  */
995 struct qinit tcp_acceptor_rinit = {
996 	NULL, (pfi_t)tcp_rsrv, NULL, tcp_tpi_close_accept, NULL, &tcp_winfo
997 };
998 
999 struct qinit tcp_acceptor_winit = {
1000 	(pfi_t)tcp_tpi_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1001 };
1002 
1003 /* For AF_INET aka /dev/tcp */
1004 struct streamtab tcpinfov4 = {
1005 	&tcp_rinitv4, &tcp_winit
1006 };
1007 
1008 /* For AF_INET6 aka /dev/tcp6 */
1009 struct streamtab tcpinfov6 = {
1010 	&tcp_rinitv6, &tcp_winit
1011 };
1012 
1013 sock_downcalls_t sock_tcp_downcalls;
1014 
1015 /* Setable only in /etc/system. Move to ndd? */
1016 boolean_t tcp_icmp_source_quench = B_FALSE;
1017 
1018 /*
1019  * Following assumes TPI alignment requirements stay along 32 bit
1020  * boundaries
1021  */
1022 #define	ROUNDUP32(x) \
1023 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1024 
1025 /* Template for response to info request. */
1026 static struct T_info_ack tcp_g_t_info_ack = {
1027 	T_INFO_ACK,		/* PRIM_type */
1028 	0,			/* TSDU_size */
1029 	T_INFINITE,		/* ETSDU_size */
1030 	T_INVALID,		/* CDATA_size */
1031 	T_INVALID,		/* DDATA_size */
1032 	sizeof (sin_t),		/* ADDR_size */
1033 	0,			/* OPT_size - not initialized here */
1034 	TIDUSZ,			/* TIDU_size */
1035 	T_COTS_ORD,		/* SERV_type */
1036 	TCPS_IDLE,		/* CURRENT_state */
1037 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1038 };
1039 
1040 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1041 	T_INFO_ACK,		/* PRIM_type */
1042 	0,			/* TSDU_size */
1043 	T_INFINITE,		/* ETSDU_size */
1044 	T_INVALID,		/* CDATA_size */
1045 	T_INVALID,		/* DDATA_size */
1046 	sizeof (sin6_t),	/* ADDR_size */
1047 	0,			/* OPT_size - not initialized here */
1048 	TIDUSZ,		/* TIDU_size */
1049 	T_COTS_ORD,		/* SERV_type */
1050 	TCPS_IDLE,		/* CURRENT_state */
1051 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1052 };
1053 
1054 #define	MS	1L
1055 #define	SECONDS	(1000 * MS)
1056 #define	MINUTES	(60 * SECONDS)
1057 #define	HOURS	(60 * MINUTES)
1058 #define	DAYS	(24 * HOURS)
1059 
1060 #define	PARAM_MAX (~(uint32_t)0)
1061 
1062 /* Max size IP datagram is 64k - 1 */
1063 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcpha_t)))
1064 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcpha_t)))
1065 /* Max of the above */
1066 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1067 
1068 /* Largest TCP port number */
1069 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1070 
1071 /*
1072  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1073  * layer header.  It has to be a multiple of 4.
1074  */
1075 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1076 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1077 
1078 #define	MB	(1024 * 1024)
1079 
1080 /*
1081  * All of these are alterable, within the min/max values given, at run time.
1082  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1083  * per the TCP spec.
1084  */
1085 /* BEGIN CSTYLED */
1086 static tcpparam_t	lcl_tcp_param_arr[] = {
1087  /*min		max		value		name */
1088  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1089  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1090  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1091  { 1,		1024,		1,		"tcp_conn_req_min" },
1092  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1093  { 128,		(1<<30),	1*MB,		"tcp_cwnd_max" },
1094  { 0,		10,		0,		"tcp_debug" },
1095  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1096  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1097  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1098  { 500*MS,	PARAM_MAX,	5*MINUTES,	"tcp_ip_abort_interval"},
1099  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1100  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1101  { 1,		255,		64,		"tcp_ipv4_ttl"},
1102  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1103  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1104  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1105  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1106  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1107  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1108  { 1*MS,	20*SECONDS,	1*SECONDS,	"tcp_rexmit_interval_initial"},
1109  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1110  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1111  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1112  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1113  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1114  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1115  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1116  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1117  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1118  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1119  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1120  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1121  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1122  { 8192,	(1<<30),	1*MB,		"tcp_max_buf"},
1123 /*
1124  * Question:  What default value should I set for tcp_strong_iss?
1125  */
1126  { 0,		2,		1,		"tcp_strong_iss"},
1127  { 0,		65536,		20,		"tcp_rtt_updates"},
1128  { 0,		1,		1,		"tcp_wscale_always"},
1129  { 0,		1,		0,		"tcp_tstamp_always"},
1130  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1131  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1132  { 0,		16,		2,		"tcp_deferred_acks_max"},
1133  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1134  { 1,		4,		4,		"tcp_slow_start_initial"},
1135  { 0,		2,		2,		"tcp_sack_permitted"},
1136  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1137  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1138  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1139  { 0,		1,		0,		"tcp_rev_src_routes"},
1140  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1141  { 0,		16,		8,		"tcp_local_dacks_max"},
1142  { 0,		2,		1,		"tcp_ecn_permitted"},
1143  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1144  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1145  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1146  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1147  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1148  { 0,		1,		0,		"tcp_dev_flow_ctl"},
1149  { 0,		PARAM_MAX,	100*SECONDS,	"tcp_reass_timeout"}
1150 };
1151 /* END CSTYLED */
1152 
1153 /* Round up the value to the nearest mss. */
1154 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1155 
1156 /*
1157  * Set ECN capable transport (ECT) code point in IP header.
1158  *
1159  * Note that there are 2 ECT code points '01' and '10', which are called
1160  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1161  * point ECT(0) for TCP as described in RFC 2481.
1162  */
1163 #define	SET_ECT(tcp, iph) \
1164 	if ((tcp)->tcp_connp->conn_ipversion == IPV4_VERSION) { \
1165 		/* We need to clear the code point first. */ \
1166 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1167 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1168 	} else { \
1169 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1170 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1171 	}
1172 
1173 /*
1174  * The format argument to pass to tcp_display().
1175  * DISP_PORT_ONLY means that the returned string has only port info.
1176  * DISP_ADDR_AND_PORT means that the returned string also contains the
1177  * remote and local IP address.
1178  */
1179 #define	DISP_PORT_ONLY		1
1180 #define	DISP_ADDR_AND_PORT	2
1181 
1182 #define	IS_VMLOANED_MBLK(mp) \
1183 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1184 
1185 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1186 
1187 /*
1188  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1189  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1190  * determined dynamically during tcp_set_destination(), which is the default.
1191  */
1192 boolean_t tcp_static_maxpsz = B_FALSE;
1193 
1194 /* Setable in /etc/system */
1195 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1196 uint32_t tcp_random_anon_port = 1;
1197 
1198 /*
1199  * To reach to an eager in Q0 which can be dropped due to an incoming
1200  * new SYN request when Q0 is full, a new doubly linked list is
1201  * introduced. This list allows to select an eager from Q0 in O(1) time.
1202  * This is needed to avoid spending too much time walking through the
1203  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1204  * this new list has to be a member of Q0.
1205  * This list is headed by listener's tcp_t. When the list is empty,
1206  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1207  * of listener's tcp_t point to listener's tcp_t itself.
1208  *
1209  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1210  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1211  * These macros do not affect the eager's membership to Q0.
1212  */
1213 
1214 
1215 #define	MAKE_DROPPABLE(listener, eager)					\
1216 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1217 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1218 		    = (eager);						\
1219 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1220 		(eager)->tcp_eager_next_drop_q0 =			\
1221 		    (listener)->tcp_eager_next_drop_q0;			\
1222 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1223 	}
1224 
1225 #define	MAKE_UNDROPPABLE(eager)						\
1226 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1227 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1228 		    = (eager)->tcp_eager_prev_drop_q0;			\
1229 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1230 		    = (eager)->tcp_eager_next_drop_q0;			\
1231 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1232 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1233 	}
1234 
1235 /*
1236  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1237  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1238  * data, TCP will not respond with an ACK.  RFC 793 requires that
1239  * TCP responds with an ACK for such a bogus ACK.  By not following
1240  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1241  * an attacker successfully spoofs an acceptable segment to our
1242  * peer; or when our peer is "confused."
1243  */
1244 uint32_t tcp_drop_ack_unsent_cnt = 10;
1245 
1246 /*
1247  * Hook functions to enable cluster networking
1248  * On non-clustered systems these vectors must always be NULL.
1249  */
1250 
1251 void (*cl_inet_listen)(netstackid_t stack_id, uint8_t protocol,
1252 			    sa_family_t addr_family, uint8_t *laddrp,
1253 			    in_port_t lport, void *args) = NULL;
1254 void (*cl_inet_unlisten)(netstackid_t stack_id, uint8_t protocol,
1255 			    sa_family_t addr_family, uint8_t *laddrp,
1256 			    in_port_t lport, void *args) = NULL;
1257 
1258 int (*cl_inet_connect2)(netstackid_t stack_id, uint8_t protocol,
1259 			    boolean_t is_outgoing,
1260 			    sa_family_t addr_family,
1261 			    uint8_t *laddrp, in_port_t lport,
1262 			    uint8_t *faddrp, in_port_t fport,
1263 			    void *args) = NULL;
1264 void (*cl_inet_disconnect)(netstackid_t stack_id, uint8_t protocol,
1265 			    sa_family_t addr_family, uint8_t *laddrp,
1266 			    in_port_t lport, uint8_t *faddrp,
1267 			    in_port_t fport, void *args) = NULL;
1268 
1269 
1270 /*
1271  * int CL_INET_CONNECT(conn_t *cp, tcp_t *tcp, boolean_t is_outgoing, int err)
1272  */
1273 #define	CL_INET_CONNECT(connp, is_outgoing, err) {		\
1274 	(err) = 0;						\
1275 	if (cl_inet_connect2 != NULL) {				\
1276 		/*						\
1277 		 * Running in cluster mode - register active connection	\
1278 		 * information						\
1279 		 */							\
1280 		if ((connp)->conn_ipversion == IPV4_VERSION) {		\
1281 			if ((connp)->conn_laddr_v4 != 0) {		\
1282 				(err) = (*cl_inet_connect2)(		\
1283 				    (connp)->conn_netstack->netstack_stackid,\
1284 				    IPPROTO_TCP, is_outgoing, AF_INET,	\
1285 				    (uint8_t *)(&((connp)->conn_laddr_v4)),\
1286 				    (in_port_t)(connp)->conn_lport,	\
1287 				    (uint8_t *)(&((connp)->conn_faddr_v4)),\
1288 				    (in_port_t)(connp)->conn_fport, NULL); \
1289 			}						\
1290 		} else {						\
1291 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1292 			    &(connp)->conn_laddr_v6)) {			\
1293 				(err) = (*cl_inet_connect2)(		\
1294 				    (connp)->conn_netstack->netstack_stackid,\
1295 				    IPPROTO_TCP, is_outgoing, AF_INET6,	\
1296 				    (uint8_t *)(&((connp)->conn_laddr_v6)),\
1297 				    (in_port_t)(connp)->conn_lport,	\
1298 				    (uint8_t *)(&((connp)->conn_faddr_v6)), \
1299 				    (in_port_t)(connp)->conn_fport, NULL); \
1300 			}						\
1301 		}							\
1302 	}								\
1303 }
1304 
1305 #define	CL_INET_DISCONNECT(connp)	{				\
1306 	if (cl_inet_disconnect != NULL) {				\
1307 		/*							\
1308 		 * Running in cluster mode - deregister active		\
1309 		 * connection information				\
1310 		 */							\
1311 		if ((connp)->conn_ipversion == IPV4_VERSION) {		\
1312 			if ((connp)->conn_laddr_v4 != 0) {		\
1313 				(*cl_inet_disconnect)(			\
1314 				    (connp)->conn_netstack->netstack_stackid,\
1315 				    IPPROTO_TCP, AF_INET,		\
1316 				    (uint8_t *)(&((connp)->conn_laddr_v4)),\
1317 				    (in_port_t)(connp)->conn_lport,	\
1318 				    (uint8_t *)(&((connp)->conn_faddr_v4)),\
1319 				    (in_port_t)(connp)->conn_fport, NULL); \
1320 			}						\
1321 		} else {						\
1322 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1323 			    &(connp)->conn_laddr_v6)) {			\
1324 				(*cl_inet_disconnect)(			\
1325 				    (connp)->conn_netstack->netstack_stackid,\
1326 				    IPPROTO_TCP, AF_INET6,		\
1327 				    (uint8_t *)(&((connp)->conn_laddr_v6)),\
1328 				    (in_port_t)(connp)->conn_lport,	\
1329 				    (uint8_t *)(&((connp)->conn_faddr_v6)), \
1330 				    (in_port_t)(connp)->conn_fport, NULL); \
1331 			}						\
1332 		}							\
1333 	}								\
1334 }
1335 
1336 /*
1337  * Steps to do when a tcp_t moves to TIME-WAIT state.
1338  *
1339  * This connection is done, we don't need to account for it.  Decrement
1340  * the listener connection counter if needed.
1341  *
1342  * Unconditionally clear the exclusive binding bit so this TIME-WAIT
1343  * connection won't interfere with new ones.
1344  *
1345  * Start the TIME-WAIT timer.  If upper layer has not closed the connection,
1346  * the timer is handled within the context of this tcp_t.  When the timer
1347  * fires, tcp_clean_death() is called.  If upper layer closes the connection
1348  * during this period, tcp_time_wait_append() will be called to add this
1349  * tcp_t to the global TIME-WAIT list.  Note that this means that the
1350  * actual wait time in TIME-WAIT state will be longer than the
1351  * tcps_time_wait_interval since the period before upper layer closes the
1352  * connection is not accounted for when tcp_time_wait_append() is called.
1353  *
1354  * If uppser layer has closed the connection, call tcp_time_wait_append()
1355  * directly.
1356  */
1357 #define	SET_TIME_WAIT(tcps, tcp, connp)				\
1358 {								\
1359 	(tcp)->tcp_state = TCPS_TIME_WAIT;			\
1360 	if ((tcp)->tcp_listen_cnt != NULL)			\
1361 		TCP_DECR_LISTEN_CNT(tcp);			\
1362 	(connp)->conn_exclbind = 0;				\
1363 	if (!TCP_IS_DETACHED(tcp)) {				\
1364 		TCP_TIMER_RESTART(tcp, (tcps)->tcps_time_wait_interval); \
1365 	} else {						\
1366 		tcp_time_wait_append(tcp);			\
1367 		TCP_DBGSTAT(tcps, tcp_rput_time_wait);		\
1368 	}							\
1369 }
1370 
1371 /*
1372  * Cluster networking hook for traversing current connection list.
1373  * This routine is used to extract the current list of live connections
1374  * which must continue to to be dispatched to this node.
1375  */
1376 int cl_tcp_walk_list(netstackid_t stack_id,
1377     int (*callback)(cl_tcp_info_t *, void *), void *arg);
1378 
1379 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1380     void *arg, tcp_stack_t *tcps);
1381 
1382 static void
1383 tcp_set_recv_threshold(tcp_t *tcp, uint32_t new_rcvthresh)
1384 {
1385 	uint32_t default_threshold = SOCKET_RECVHIWATER >> 3;
1386 
1387 	if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
1388 		conn_t *connp = tcp->tcp_connp;
1389 		struct sock_proto_props sopp;
1390 
1391 		/*
1392 		 * only increase rcvthresh upto default_threshold
1393 		 */
1394 		if (new_rcvthresh > default_threshold)
1395 			new_rcvthresh = default_threshold;
1396 
1397 		sopp.sopp_flags = SOCKOPT_RCVTHRESH;
1398 		sopp.sopp_rcvthresh = new_rcvthresh;
1399 
1400 		(*connp->conn_upcalls->su_set_proto_props)
1401 		    (connp->conn_upper_handle, &sopp);
1402 	}
1403 }
1404 /*
1405  * Figure out the value of window scale opton.  Note that the rwnd is
1406  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1407  * We cannot find the scale value and then do a round up of tcp_rwnd
1408  * because the scale value may not be correct after that.
1409  *
1410  * Set the compiler flag to make this function inline.
1411  */
1412 static void
1413 tcp_set_ws_value(tcp_t *tcp)
1414 {
1415 	int i;
1416 	uint32_t rwnd = tcp->tcp_rwnd;
1417 
1418 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1419 	    i++, rwnd >>= 1)
1420 		;
1421 	tcp->tcp_rcv_ws = i;
1422 }
1423 
1424 /*
1425  * Remove a connection from the list of detached TIME_WAIT connections.
1426  * It returns B_FALSE if it can't remove the connection from the list
1427  * as the connection has already been removed from the list due to an
1428  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1429  */
1430 static boolean_t
1431 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1432 {
1433 	boolean_t	locked = B_FALSE;
1434 
1435 	if (tcp_time_wait == NULL) {
1436 		tcp_time_wait = *((tcp_squeue_priv_t **)
1437 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1438 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1439 		locked = B_TRUE;
1440 	} else {
1441 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1442 	}
1443 
1444 	if (tcp->tcp_time_wait_expire == 0) {
1445 		ASSERT(tcp->tcp_time_wait_next == NULL);
1446 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1447 		if (locked)
1448 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1449 		return (B_FALSE);
1450 	}
1451 	ASSERT(TCP_IS_DETACHED(tcp));
1452 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1453 
1454 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1455 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1456 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1457 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1458 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1459 			    NULL;
1460 		} else {
1461 			tcp_time_wait->tcp_time_wait_tail = NULL;
1462 		}
1463 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1464 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1465 		ASSERT(tcp->tcp_time_wait_next == NULL);
1466 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1467 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1468 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1469 	} else {
1470 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1471 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1472 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1473 		    tcp->tcp_time_wait_next;
1474 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1475 		    tcp->tcp_time_wait_prev;
1476 	}
1477 	tcp->tcp_time_wait_next = NULL;
1478 	tcp->tcp_time_wait_prev = NULL;
1479 	tcp->tcp_time_wait_expire = 0;
1480 
1481 	if (locked)
1482 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1483 	return (B_TRUE);
1484 }
1485 
1486 /*
1487  * Add a connection to the list of detached TIME_WAIT connections
1488  * and set its time to expire.
1489  */
1490 static void
1491 tcp_time_wait_append(tcp_t *tcp)
1492 {
1493 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1494 	tcp_squeue_priv_t *tcp_time_wait =
1495 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1496 	    SQPRIVATE_TCP));
1497 
1498 	tcp_timers_stop(tcp);
1499 
1500 	/* Freed above */
1501 	ASSERT(tcp->tcp_timer_tid == 0);
1502 	ASSERT(tcp->tcp_ack_tid == 0);
1503 
1504 	/* must have happened at the time of detaching the tcp */
1505 	ASSERT(tcp->tcp_ptpahn == NULL);
1506 	ASSERT(tcp->tcp_flow_stopped == 0);
1507 	ASSERT(tcp->tcp_time_wait_next == NULL);
1508 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1509 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1510 	ASSERT(tcp->tcp_listener == NULL);
1511 
1512 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1513 	/*
1514 	 * The value computed below in tcp->tcp_time_wait_expire may
1515 	 * appear negative or wrap around. That is ok since our
1516 	 * interest is only in the difference between the current lbolt
1517 	 * value and tcp->tcp_time_wait_expire. But the value should not
1518 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1519 	 * The corresponding comparison in tcp_time_wait_collector() uses
1520 	 * modular arithmetic.
1521 	 */
1522 	tcp->tcp_time_wait_expire +=
1523 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1524 	if (tcp->tcp_time_wait_expire == 0)
1525 		tcp->tcp_time_wait_expire = 1;
1526 
1527 	ASSERT(TCP_IS_DETACHED(tcp));
1528 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1529 	ASSERT(tcp->tcp_time_wait_next == NULL);
1530 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1531 	TCP_DBGSTAT(tcps, tcp_time_wait);
1532 
1533 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1534 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1535 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1536 		tcp_time_wait->tcp_time_wait_head = tcp;
1537 	} else {
1538 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1539 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1540 		    TCPS_TIME_WAIT);
1541 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1542 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1543 	}
1544 	tcp_time_wait->tcp_time_wait_tail = tcp;
1545 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1546 }
1547 
1548 /* ARGSUSED */
1549 void
1550 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
1551 {
1552 	conn_t	*connp = (conn_t *)arg;
1553 	tcp_t	*tcp = connp->conn_tcp;
1554 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1555 
1556 	ASSERT(tcp != NULL);
1557 	if (tcp->tcp_state == TCPS_CLOSED) {
1558 		return;
1559 	}
1560 
1561 	ASSERT((connp->conn_family == AF_INET &&
1562 	    connp->conn_ipversion == IPV4_VERSION) ||
1563 	    (connp->conn_family == AF_INET6 &&
1564 	    (connp->conn_ipversion == IPV4_VERSION ||
1565 	    connp->conn_ipversion == IPV6_VERSION)));
1566 	ASSERT(!tcp->tcp_listener);
1567 
1568 	TCP_STAT(tcps, tcp_time_wait_reap);
1569 	ASSERT(TCP_IS_DETACHED(tcp));
1570 
1571 	/*
1572 	 * Because they have no upstream client to rebind or tcp_close()
1573 	 * them later, we axe the connection here and now.
1574 	 */
1575 	tcp_close_detached(tcp);
1576 }
1577 
1578 /*
1579  * Remove cached/latched IPsec references.
1580  */
1581 void
1582 tcp_ipsec_cleanup(tcp_t *tcp)
1583 {
1584 	conn_t		*connp = tcp->tcp_connp;
1585 
1586 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1587 
1588 	if (connp->conn_latch != NULL) {
1589 		IPLATCH_REFRELE(connp->conn_latch);
1590 		connp->conn_latch = NULL;
1591 	}
1592 	if (connp->conn_latch_in_policy != NULL) {
1593 		IPPOL_REFRELE(connp->conn_latch_in_policy);
1594 		connp->conn_latch_in_policy = NULL;
1595 	}
1596 	if (connp->conn_latch_in_action != NULL) {
1597 		IPACT_REFRELE(connp->conn_latch_in_action);
1598 		connp->conn_latch_in_action = NULL;
1599 	}
1600 	if (connp->conn_policy != NULL) {
1601 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1602 		connp->conn_policy = NULL;
1603 	}
1604 }
1605 
1606 /*
1607  * Cleaup before placing on free list.
1608  * Disassociate from the netstack/tcp_stack_t since the freelist
1609  * is per squeue and not per netstack.
1610  */
1611 void
1612 tcp_cleanup(tcp_t *tcp)
1613 {
1614 	mblk_t		*mp;
1615 	tcp_sack_info_t	*tcp_sack_info;
1616 	conn_t		*connp = tcp->tcp_connp;
1617 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1618 	netstack_t	*ns = tcps->tcps_netstack;
1619 	mblk_t		*tcp_rsrv_mp;
1620 
1621 	tcp_bind_hash_remove(tcp);
1622 
1623 	/* Cleanup that which needs the netstack first */
1624 	tcp_ipsec_cleanup(tcp);
1625 	ixa_cleanup(connp->conn_ixa);
1626 
1627 	if (connp->conn_ht_iphc != NULL) {
1628 		kmem_free(connp->conn_ht_iphc, connp->conn_ht_iphc_allocated);
1629 		connp->conn_ht_iphc = NULL;
1630 		connp->conn_ht_iphc_allocated = 0;
1631 		connp->conn_ht_iphc_len = 0;
1632 		connp->conn_ht_ulp = NULL;
1633 		connp->conn_ht_ulp_len = 0;
1634 		tcp->tcp_ipha = NULL;
1635 		tcp->tcp_ip6h = NULL;
1636 		tcp->tcp_tcpha = NULL;
1637 	}
1638 
1639 	/* We clear any IP_OPTIONS and extension headers */
1640 	ip_pkt_free(&connp->conn_xmit_ipp);
1641 
1642 	tcp_free(tcp);
1643 
1644 	/* Release any SSL context */
1645 	if (tcp->tcp_kssl_ent != NULL) {
1646 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1647 		tcp->tcp_kssl_ent = NULL;
1648 	}
1649 
1650 	if (tcp->tcp_kssl_ctx != NULL) {
1651 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1652 		tcp->tcp_kssl_ctx = NULL;
1653 	}
1654 	tcp->tcp_kssl_pending = B_FALSE;
1655 
1656 	/*
1657 	 * Since we will bzero the entire structure, we need to
1658 	 * remove it and reinsert it in global hash list. We
1659 	 * know the walkers can't get to this conn because we
1660 	 * had set CONDEMNED flag earlier and checked reference
1661 	 * under conn_lock so walker won't pick it and when we
1662 	 * go the ipcl_globalhash_remove() below, no walker
1663 	 * can get to it.
1664 	 */
1665 	ipcl_globalhash_remove(connp);
1666 
1667 	/* Save some state */
1668 	mp = tcp->tcp_timercache;
1669 
1670 	tcp_sack_info = tcp->tcp_sack_info;
1671 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1672 
1673 	if (connp->conn_cred != NULL) {
1674 		crfree(connp->conn_cred);
1675 		connp->conn_cred = NULL;
1676 	}
1677 	ipcl_conn_cleanup(connp);
1678 	connp->conn_flags = IPCL_TCPCONN;
1679 
1680 	/*
1681 	 * Now it is safe to decrement the reference counts.
1682 	 * This might be the last reference on the netstack
1683 	 * in which case it will cause the freeing of the IP Instance.
1684 	 */
1685 	connp->conn_netstack = NULL;
1686 	connp->conn_ixa->ixa_ipst = NULL;
1687 	netstack_rele(ns);
1688 	ASSERT(tcps != NULL);
1689 	tcp->tcp_tcps = NULL;
1690 
1691 	bzero(tcp, sizeof (tcp_t));
1692 
1693 	/* restore the state */
1694 	tcp->tcp_timercache = mp;
1695 
1696 	tcp->tcp_sack_info = tcp_sack_info;
1697 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1698 
1699 	tcp->tcp_connp = connp;
1700 
1701 	ASSERT(connp->conn_tcp == tcp);
1702 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1703 	connp->conn_state_flags = CONN_INCIPIENT;
1704 	ASSERT(connp->conn_proto == IPPROTO_TCP);
1705 	ASSERT(connp->conn_ref == 1);
1706 }
1707 
1708 /*
1709  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1710  * is done forwards from the head.
1711  * This walks all stack instances since
1712  * tcp_time_wait remains global across all stacks.
1713  */
1714 /* ARGSUSED */
1715 void
1716 tcp_time_wait_collector(void *arg)
1717 {
1718 	tcp_t *tcp;
1719 	clock_t now;
1720 	mblk_t *mp;
1721 	conn_t *connp;
1722 	kmutex_t *lock;
1723 	boolean_t removed;
1724 
1725 	squeue_t *sqp = (squeue_t *)arg;
1726 	tcp_squeue_priv_t *tcp_time_wait =
1727 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1728 
1729 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1730 	tcp_time_wait->tcp_time_wait_tid = 0;
1731 
1732 	if (tcp_time_wait->tcp_free_list != NULL &&
1733 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1734 		TCP_G_STAT(tcp_freelist_cleanup);
1735 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1736 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1737 			tcp->tcp_time_wait_next = NULL;
1738 			tcp_time_wait->tcp_free_list_cnt--;
1739 			ASSERT(tcp->tcp_tcps == NULL);
1740 			CONN_DEC_REF(tcp->tcp_connp);
1741 		}
1742 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1743 	}
1744 
1745 	/*
1746 	 * In order to reap time waits reliably, we should use a
1747 	 * source of time that is not adjustable by the user -- hence
1748 	 * the call to ddi_get_lbolt().
1749 	 */
1750 	now = ddi_get_lbolt();
1751 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1752 		/*
1753 		 * Compare times using modular arithmetic, since
1754 		 * lbolt can wrapover.
1755 		 */
1756 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1757 			break;
1758 		}
1759 
1760 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1761 		ASSERT(removed);
1762 
1763 		connp = tcp->tcp_connp;
1764 		ASSERT(connp->conn_fanout != NULL);
1765 		lock = &connp->conn_fanout->connf_lock;
1766 		/*
1767 		 * This is essentially a TW reclaim fast path optimization for
1768 		 * performance where the timewait collector checks under the
1769 		 * fanout lock (so that no one else can get access to the
1770 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1771 		 * the classifier hash list. If ref count is indeed 2, we can
1772 		 * just remove the conn under the fanout lock and avoid
1773 		 * cleaning up the conn under the squeue, provided that
1774 		 * clustering callbacks are not enabled. If clustering is
1775 		 * enabled, we need to make the clustering callback before
1776 		 * setting the CONDEMNED flag and after dropping all locks and
1777 		 * so we forego this optimization and fall back to the slow
1778 		 * path. Also please see the comments in tcp_closei_local
1779 		 * regarding the refcnt logic.
1780 		 *
1781 		 * Since we are holding the tcp_time_wait_lock, its better
1782 		 * not to block on the fanout_lock because other connections
1783 		 * can't add themselves to time_wait list. So we do a
1784 		 * tryenter instead of mutex_enter.
1785 		 */
1786 		if (mutex_tryenter(lock)) {
1787 			mutex_enter(&connp->conn_lock);
1788 			if ((connp->conn_ref == 2) &&
1789 			    (cl_inet_disconnect == NULL)) {
1790 				ipcl_hash_remove_locked(connp,
1791 				    connp->conn_fanout);
1792 				/*
1793 				 * Set the CONDEMNED flag now itself so that
1794 				 * the refcnt cannot increase due to any
1795 				 * walker.
1796 				 */
1797 				connp->conn_state_flags |= CONN_CONDEMNED;
1798 				mutex_exit(lock);
1799 				mutex_exit(&connp->conn_lock);
1800 				if (tcp_time_wait->tcp_free_list_cnt <
1801 				    tcp_free_list_max_cnt) {
1802 					/* Add to head of tcp_free_list */
1803 					mutex_exit(
1804 					    &tcp_time_wait->tcp_time_wait_lock);
1805 					tcp_cleanup(tcp);
1806 					ASSERT(connp->conn_latch == NULL);
1807 					ASSERT(connp->conn_policy == NULL);
1808 					ASSERT(tcp->tcp_tcps == NULL);
1809 					ASSERT(connp->conn_netstack == NULL);
1810 
1811 					mutex_enter(
1812 					    &tcp_time_wait->tcp_time_wait_lock);
1813 					tcp->tcp_time_wait_next =
1814 					    tcp_time_wait->tcp_free_list;
1815 					tcp_time_wait->tcp_free_list = tcp;
1816 					tcp_time_wait->tcp_free_list_cnt++;
1817 					continue;
1818 				} else {
1819 					/* Do not add to tcp_free_list */
1820 					mutex_exit(
1821 					    &tcp_time_wait->tcp_time_wait_lock);
1822 					tcp_bind_hash_remove(tcp);
1823 					ixa_cleanup(tcp->tcp_connp->conn_ixa);
1824 					tcp_ipsec_cleanup(tcp);
1825 					CONN_DEC_REF(tcp->tcp_connp);
1826 				}
1827 			} else {
1828 				CONN_INC_REF_LOCKED(connp);
1829 				mutex_exit(lock);
1830 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1831 				mutex_exit(&connp->conn_lock);
1832 				/*
1833 				 * We can reuse the closemp here since conn has
1834 				 * detached (otherwise we wouldn't even be in
1835 				 * time_wait list). tcp_closemp_used can safely
1836 				 * be changed without taking a lock as no other
1837 				 * thread can concurrently access it at this
1838 				 * point in the connection lifecycle.
1839 				 */
1840 
1841 				if (tcp->tcp_closemp.b_prev == NULL)
1842 					tcp->tcp_closemp_used = B_TRUE;
1843 				else
1844 					cmn_err(CE_PANIC,
1845 					    "tcp_timewait_collector: "
1846 					    "concurrent use of tcp_closemp: "
1847 					    "connp %p tcp %p\n", (void *)connp,
1848 					    (void *)tcp);
1849 
1850 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1851 				mp = &tcp->tcp_closemp;
1852 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1853 				    tcp_timewait_output, connp, NULL,
1854 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1855 			}
1856 		} else {
1857 			mutex_enter(&connp->conn_lock);
1858 			CONN_INC_REF_LOCKED(connp);
1859 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1860 			mutex_exit(&connp->conn_lock);
1861 			/*
1862 			 * We can reuse the closemp here since conn has
1863 			 * detached (otherwise we wouldn't even be in
1864 			 * time_wait list). tcp_closemp_used can safely
1865 			 * be changed without taking a lock as no other
1866 			 * thread can concurrently access it at this
1867 			 * point in the connection lifecycle.
1868 			 */
1869 
1870 			if (tcp->tcp_closemp.b_prev == NULL)
1871 				tcp->tcp_closemp_used = B_TRUE;
1872 			else
1873 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1874 				    "concurrent use of tcp_closemp: "
1875 				    "connp %p tcp %p\n", (void *)connp,
1876 				    (void *)tcp);
1877 
1878 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1879 			mp = &tcp->tcp_closemp;
1880 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1881 			    tcp_timewait_output, connp, NULL,
1882 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1883 		}
1884 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1885 	}
1886 
1887 	if (tcp_time_wait->tcp_free_list != NULL)
1888 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1889 
1890 	tcp_time_wait->tcp_time_wait_tid =
1891 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1892 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1893 	    CALLOUT_FLAG_ROUNDUP);
1894 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1895 }
1896 
1897 /*
1898  * Reply to a clients T_CONN_RES TPI message. This function
1899  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1900  * on the acceptor STREAM and processed in tcp_accept_common().
1901  * Read the block comment on top of tcp_input_listener().
1902  */
1903 static void
1904 tcp_tli_accept(tcp_t *listener, mblk_t *mp)
1905 {
1906 	tcp_t		*acceptor;
1907 	tcp_t		*eager;
1908 	tcp_t   	*tcp;
1909 	struct T_conn_res	*tcr;
1910 	t_uscalar_t	acceptor_id;
1911 	t_scalar_t	seqnum;
1912 	mblk_t		*discon_mp = NULL;
1913 	mblk_t		*ok_mp;
1914 	mblk_t		*mp1;
1915 	tcp_stack_t	*tcps = listener->tcp_tcps;
1916 	conn_t		*econnp;
1917 
1918 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1919 		tcp_err_ack(listener, mp, TPROTO, 0);
1920 		return;
1921 	}
1922 	tcr = (struct T_conn_res *)mp->b_rptr;
1923 
1924 	/*
1925 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1926 	 * read side queue of the streams device underneath us i.e. the
1927 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1928 	 * look it up in the queue_hash.  Under LP64 it sends down the
1929 	 * minor_t of the accepting endpoint.
1930 	 *
1931 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1932 	 * fanout hash lock is held.
1933 	 * This prevents any thread from entering the acceptor queue from
1934 	 * below (since it has not been hard bound yet i.e. any inbound
1935 	 * packets will arrive on the listener conn_t and
1936 	 * go through the classifier).
1937 	 * The CONN_INC_REF will prevent the acceptor from closing.
1938 	 *
1939 	 * XXX It is still possible for a tli application to send down data
1940 	 * on the accepting stream while another thread calls t_accept.
1941 	 * This should not be a problem for well-behaved applications since
1942 	 * the T_OK_ACK is sent after the queue swapping is completed.
1943 	 *
1944 	 * If the accepting fd is the same as the listening fd, avoid
1945 	 * queue hash lookup since that will return an eager listener in a
1946 	 * already established state.
1947 	 */
1948 	acceptor_id = tcr->ACCEPTOR_id;
1949 	mutex_enter(&listener->tcp_eager_lock);
1950 	if (listener->tcp_acceptor_id == acceptor_id) {
1951 		eager = listener->tcp_eager_next_q;
1952 		/* only count how many T_CONN_INDs so don't count q0 */
1953 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1954 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1955 			mutex_exit(&listener->tcp_eager_lock);
1956 			tcp_err_ack(listener, mp, TBADF, 0);
1957 			return;
1958 		}
1959 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1960 			/* Throw away all the eagers on q0. */
1961 			tcp_eager_cleanup(listener, 1);
1962 		}
1963 		if (listener->tcp_syn_defense) {
1964 			listener->tcp_syn_defense = B_FALSE;
1965 			if (listener->tcp_ip_addr_cache != NULL) {
1966 				kmem_free(listener->tcp_ip_addr_cache,
1967 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1968 				listener->tcp_ip_addr_cache = NULL;
1969 			}
1970 		}
1971 		/*
1972 		 * Transfer tcp_conn_req_max to the eager so that when
1973 		 * a disconnect occurs we can revert the endpoint to the
1974 		 * listen state.
1975 		 */
1976 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1977 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1978 		/*
1979 		 * Get a reference on the acceptor just like the
1980 		 * tcp_acceptor_hash_lookup below.
1981 		 */
1982 		acceptor = listener;
1983 		CONN_INC_REF(acceptor->tcp_connp);
1984 	} else {
1985 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
1986 		if (acceptor == NULL) {
1987 			if (listener->tcp_connp->conn_debug) {
1988 				(void) strlog(TCP_MOD_ID, 0, 1,
1989 				    SL_ERROR|SL_TRACE,
1990 				    "tcp_accept: did not find acceptor 0x%x\n",
1991 				    acceptor_id);
1992 			}
1993 			mutex_exit(&listener->tcp_eager_lock);
1994 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1995 			return;
1996 		}
1997 		/*
1998 		 * Verify acceptor state. The acceptable states for an acceptor
1999 		 * include TCPS_IDLE and TCPS_BOUND.
2000 		 */
2001 		switch (acceptor->tcp_state) {
2002 		case TCPS_IDLE:
2003 			/* FALLTHRU */
2004 		case TCPS_BOUND:
2005 			break;
2006 		default:
2007 			CONN_DEC_REF(acceptor->tcp_connp);
2008 			mutex_exit(&listener->tcp_eager_lock);
2009 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2010 			return;
2011 		}
2012 	}
2013 
2014 	/* The listener must be in TCPS_LISTEN */
2015 	if (listener->tcp_state != TCPS_LISTEN) {
2016 		CONN_DEC_REF(acceptor->tcp_connp);
2017 		mutex_exit(&listener->tcp_eager_lock);
2018 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2019 		return;
2020 	}
2021 
2022 	/*
2023 	 * Rendezvous with an eager connection request packet hanging off
2024 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2025 	 * tcp structure when the connection packet arrived in
2026 	 * tcp_input_listener().
2027 	 */
2028 	seqnum = tcr->SEQ_number;
2029 	eager = listener;
2030 	do {
2031 		eager = eager->tcp_eager_next_q;
2032 		if (eager == NULL) {
2033 			CONN_DEC_REF(acceptor->tcp_connp);
2034 			mutex_exit(&listener->tcp_eager_lock);
2035 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2036 			return;
2037 		}
2038 	} while (eager->tcp_conn_req_seqnum != seqnum);
2039 	mutex_exit(&listener->tcp_eager_lock);
2040 
2041 	/*
2042 	 * At this point, both acceptor and listener have 2 ref
2043 	 * that they begin with. Acceptor has one additional ref
2044 	 * we placed in lookup while listener has 3 additional
2045 	 * ref for being behind the squeue (tcp_accept() is
2046 	 * done on listener's squeue); being in classifier hash;
2047 	 * and eager's ref on listener.
2048 	 */
2049 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2050 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2051 
2052 	/*
2053 	 * The eager at this point is set in its own squeue and
2054 	 * could easily have been killed (tcp_accept_finish will
2055 	 * deal with that) because of a TH_RST so we can only
2056 	 * ASSERT for a single ref.
2057 	 */
2058 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2059 
2060 	/*
2061 	 * Pre allocate the discon_ind mblk also. tcp_accept_finish will
2062 	 * use it if something failed.
2063 	 */
2064 	discon_mp = allocb(MAX(sizeof (struct T_discon_ind),
2065 	    sizeof (struct stroptions)), BPRI_HI);
2066 	if (discon_mp == NULL) {
2067 		CONN_DEC_REF(acceptor->tcp_connp);
2068 		CONN_DEC_REF(eager->tcp_connp);
2069 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2070 		return;
2071 	}
2072 
2073 	econnp = eager->tcp_connp;
2074 
2075 	/* Hold a copy of mp, in case reallocb fails */
2076 	if ((mp1 = copymsg(mp)) == NULL) {
2077 		CONN_DEC_REF(acceptor->tcp_connp);
2078 		CONN_DEC_REF(eager->tcp_connp);
2079 		freemsg(discon_mp);
2080 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2081 		return;
2082 	}
2083 
2084 	tcr = (struct T_conn_res *)mp1->b_rptr;
2085 
2086 	/*
2087 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2088 	 * which allocates a larger mblk and appends the new
2089 	 * local address to the ok_ack.  The address is copied by
2090 	 * soaccept() for getsockname().
2091 	 */
2092 	{
2093 		int extra;
2094 
2095 		extra = (econnp->conn_family == AF_INET) ?
2096 		    sizeof (sin_t) : sizeof (sin6_t);
2097 
2098 		/*
2099 		 * Try to re-use mp, if possible.  Otherwise, allocate
2100 		 * an mblk and return it as ok_mp.  In any case, mp
2101 		 * is no longer usable upon return.
2102 		 */
2103 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2104 			CONN_DEC_REF(acceptor->tcp_connp);
2105 			CONN_DEC_REF(eager->tcp_connp);
2106 			freemsg(discon_mp);
2107 			/* Original mp has been freed by now, so use mp1 */
2108 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2109 			return;
2110 		}
2111 
2112 		mp = NULL;	/* We should never use mp after this point */
2113 
2114 		switch (extra) {
2115 		case sizeof (sin_t): {
2116 			sin_t *sin = (sin_t *)ok_mp->b_wptr;
2117 
2118 			ok_mp->b_wptr += extra;
2119 			sin->sin_family = AF_INET;
2120 			sin->sin_port = econnp->conn_lport;
2121 			sin->sin_addr.s_addr = econnp->conn_laddr_v4;
2122 			break;
2123 		}
2124 		case sizeof (sin6_t): {
2125 			sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2126 
2127 			ok_mp->b_wptr += extra;
2128 			sin6->sin6_family = AF_INET6;
2129 			sin6->sin6_port = econnp->conn_lport;
2130 			sin6->sin6_addr = econnp->conn_laddr_v6;
2131 			sin6->sin6_flowinfo = econnp->conn_flowinfo;
2132 			if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6) &&
2133 			    (econnp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)) {
2134 				sin6->sin6_scope_id =
2135 				    econnp->conn_ixa->ixa_scopeid;
2136 			} else {
2137 				sin6->sin6_scope_id = 0;
2138 			}
2139 			sin6->__sin6_src_id = 0;
2140 			break;
2141 		}
2142 		default:
2143 			break;
2144 		}
2145 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2146 	}
2147 
2148 	/*
2149 	 * If there are no options we know that the T_CONN_RES will
2150 	 * succeed. However, we can't send the T_OK_ACK upstream until
2151 	 * the tcp_accept_swap is done since it would be dangerous to
2152 	 * let the application start using the new fd prior to the swap.
2153 	 */
2154 	tcp_accept_swap(listener, acceptor, eager);
2155 
2156 	/*
2157 	 * tcp_accept_swap unlinks eager from listener but does not drop
2158 	 * the eager's reference on the listener.
2159 	 */
2160 	ASSERT(eager->tcp_listener == NULL);
2161 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2162 
2163 	/*
2164 	 * The eager is now associated with its own queue. Insert in
2165 	 * the hash so that the connection can be reused for a future
2166 	 * T_CONN_RES.
2167 	 */
2168 	tcp_acceptor_hash_insert(acceptor_id, eager);
2169 
2170 	/*
2171 	 * We now do the processing of options with T_CONN_RES.
2172 	 * We delay till now since we wanted to have queue to pass to
2173 	 * option processing routines that points back to the right
2174 	 * instance structure which does not happen until after
2175 	 * tcp_accept_swap().
2176 	 *
2177 	 * Note:
2178 	 * The sanity of the logic here assumes that whatever options
2179 	 * are appropriate to inherit from listner=>eager are done
2180 	 * before this point, and whatever were to be overridden (or not)
2181 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2182 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2183 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2184 	 * This may not be true at this point in time but can be fixed
2185 	 * independently. This option processing code starts with
2186 	 * the instantiated acceptor instance and the final queue at
2187 	 * this point.
2188 	 */
2189 
2190 	if (tcr->OPT_length != 0) {
2191 		/* Options to process */
2192 		int t_error = 0;
2193 		int sys_error = 0;
2194 		int do_disconnect = 0;
2195 
2196 		if (tcp_conprim_opt_process(eager, mp1,
2197 		    &do_disconnect, &t_error, &sys_error) < 0) {
2198 			eager->tcp_accept_error = 1;
2199 			if (do_disconnect) {
2200 				/*
2201 				 * An option failed which does not allow
2202 				 * connection to be accepted.
2203 				 *
2204 				 * We allow T_CONN_RES to succeed and
2205 				 * put a T_DISCON_IND on the eager queue.
2206 				 */
2207 				ASSERT(t_error == 0 && sys_error == 0);
2208 				eager->tcp_send_discon_ind = 1;
2209 			} else {
2210 				ASSERT(t_error != 0);
2211 				freemsg(ok_mp);
2212 				/*
2213 				 * Original mp was either freed or set
2214 				 * to ok_mp above, so use mp1 instead.
2215 				 */
2216 				tcp_err_ack(listener, mp1, t_error, sys_error);
2217 				goto finish;
2218 			}
2219 		}
2220 		/*
2221 		 * Most likely success in setting options (except if
2222 		 * eager->tcp_send_discon_ind set).
2223 		 * mp1 option buffer represented by OPT_length/offset
2224 		 * potentially modified and contains results of setting
2225 		 * options at this point
2226 		 */
2227 	}
2228 
2229 	/* We no longer need mp1, since all options processing has passed */
2230 	freemsg(mp1);
2231 
2232 	putnext(listener->tcp_connp->conn_rq, ok_mp);
2233 
2234 	mutex_enter(&listener->tcp_eager_lock);
2235 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2236 		tcp_t	*tail;
2237 		mblk_t	*conn_ind;
2238 
2239 		/*
2240 		 * This path should not be executed if listener and
2241 		 * acceptor streams are the same.
2242 		 */
2243 		ASSERT(listener != acceptor);
2244 
2245 		tcp = listener->tcp_eager_prev_q0;
2246 		/*
2247 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2248 		 * deferred T_conn_ind queue. We need to get to the head of
2249 		 * the queue in order to send up T_conn_ind the same order as
2250 		 * how the 3WHS is completed.
2251 		 */
2252 		while (tcp != listener) {
2253 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2254 				break;
2255 			else
2256 				tcp = tcp->tcp_eager_prev_q0;
2257 		}
2258 		ASSERT(tcp != listener);
2259 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2260 		ASSERT(conn_ind != NULL);
2261 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2262 
2263 		/* Move from q0 to q */
2264 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2265 		listener->tcp_conn_req_cnt_q0--;
2266 		listener->tcp_conn_req_cnt_q++;
2267 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2268 		    tcp->tcp_eager_prev_q0;
2269 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2270 		    tcp->tcp_eager_next_q0;
2271 		tcp->tcp_eager_prev_q0 = NULL;
2272 		tcp->tcp_eager_next_q0 = NULL;
2273 		tcp->tcp_conn_def_q0 = B_FALSE;
2274 
2275 		/* Make sure the tcp isn't in the list of droppables */
2276 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2277 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2278 
2279 		/*
2280 		 * Insert at end of the queue because sockfs sends
2281 		 * down T_CONN_RES in chronological order. Leaving
2282 		 * the older conn indications at front of the queue
2283 		 * helps reducing search time.
2284 		 */
2285 		tail = listener->tcp_eager_last_q;
2286 		if (tail != NULL)
2287 			tail->tcp_eager_next_q = tcp;
2288 		else
2289 			listener->tcp_eager_next_q = tcp;
2290 		listener->tcp_eager_last_q = tcp;
2291 		tcp->tcp_eager_next_q = NULL;
2292 		mutex_exit(&listener->tcp_eager_lock);
2293 		putnext(tcp->tcp_connp->conn_rq, conn_ind);
2294 	} else {
2295 		mutex_exit(&listener->tcp_eager_lock);
2296 	}
2297 
2298 	/*
2299 	 * Done with the acceptor - free it
2300 	 *
2301 	 * Note: from this point on, no access to listener should be made
2302 	 * as listener can be equal to acceptor.
2303 	 */
2304 finish:
2305 	ASSERT(acceptor->tcp_detached);
2306 	acceptor->tcp_connp->conn_rq = NULL;
2307 	ASSERT(!IPCL_IS_NONSTR(acceptor->tcp_connp));
2308 	acceptor->tcp_connp->conn_wq = NULL;
2309 	(void) tcp_clean_death(acceptor, 0, 2);
2310 	CONN_DEC_REF(acceptor->tcp_connp);
2311 
2312 	/*
2313 	 * We pass discon_mp to tcp_accept_finish to get on the right squeue.
2314 	 *
2315 	 * It will update the setting for sockfs/stream head and also take
2316 	 * care of any data that arrived before accept() wad called.
2317 	 * In case we already received a FIN then tcp_accept_finish will send up
2318 	 * the ordrel. It will also send up a window update if the window
2319 	 * has opened up.
2320 	 */
2321 
2322 	/*
2323 	 * XXX: we currently have a problem if XTI application closes the
2324 	 * acceptor stream in between. This problem exists in on10-gate also
2325 	 * and is well know but nothing can be done short of major rewrite
2326 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2327 	 * eager same squeue as listener (we can distinguish non socket
2328 	 * listeners at the time of handling a SYN in tcp_input_listener)
2329 	 * and do most of the work that tcp_accept_finish does here itself
2330 	 * and then get behind the acceptor squeue to access the acceptor
2331 	 * queue.
2332 	 */
2333 	/*
2334 	 * We already have a ref on tcp so no need to do one before squeue_enter
2335 	 */
2336 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, discon_mp,
2337 	    tcp_accept_finish, eager->tcp_connp, NULL, SQ_FILL,
2338 	    SQTAG_TCP_ACCEPT_FINISH);
2339 }
2340 
2341 /*
2342  * Swap information between the eager and acceptor for a TLI/XTI client.
2343  * The sockfs accept is done on the acceptor stream and control goes
2344  * through tcp_tli_accept() and tcp_accept()/tcp_accept_swap() is not
2345  * called. In either case, both the eager and listener are in their own
2346  * perimeter (squeue) and the code has to deal with potential race.
2347  *
2348  * See the block comment on top of tcp_accept() and tcp_tli_accept().
2349  */
2350 static void
2351 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2352 {
2353 	conn_t	*econnp, *aconnp;
2354 
2355 	ASSERT(eager->tcp_connp->conn_rq == listener->tcp_connp->conn_rq);
2356 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2357 	ASSERT(!TCP_IS_SOCKET(acceptor));
2358 	ASSERT(!TCP_IS_SOCKET(eager));
2359 	ASSERT(!TCP_IS_SOCKET(listener));
2360 
2361 	/*
2362 	 * Trusted Extensions may need to use a security label that is
2363 	 * different from the acceptor's label on MLP and MAC-Exempt
2364 	 * sockets. If this is the case, the required security label
2365 	 * already exists in econnp->conn_ixa->ixa_tsl. Since we make the
2366 	 * acceptor stream refer to econnp we atomatically get that label.
2367 	 */
2368 
2369 	acceptor->tcp_detached = B_TRUE;
2370 	/*
2371 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2372 	 * the acceptor id.
2373 	 */
2374 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2375 
2376 	/* remove eager from listen list... */
2377 	mutex_enter(&listener->tcp_eager_lock);
2378 	tcp_eager_unlink(eager);
2379 	ASSERT(eager->tcp_eager_next_q == NULL &&
2380 	    eager->tcp_eager_last_q == NULL);
2381 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2382 	    eager->tcp_eager_prev_q0 == NULL);
2383 	mutex_exit(&listener->tcp_eager_lock);
2384 
2385 	econnp = eager->tcp_connp;
2386 	aconnp = acceptor->tcp_connp;
2387 	econnp->conn_rq = aconnp->conn_rq;
2388 	econnp->conn_wq = aconnp->conn_wq;
2389 	econnp->conn_rq->q_ptr = econnp;
2390 	econnp->conn_wq->q_ptr = econnp;
2391 
2392 	/*
2393 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2394 	 * which might be a different squeue from our peer TCP instance.
2395 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2396 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2397 	 * membar_producer() to ensure that the assignments of conn_rq/conn_wq
2398 	 * above reach global visibility prior to the clearing of tcp_detached.
2399 	 */
2400 	membar_producer();
2401 	eager->tcp_detached = B_FALSE;
2402 
2403 	ASSERT(eager->tcp_ack_tid == 0);
2404 
2405 	econnp->conn_dev = aconnp->conn_dev;
2406 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2407 
2408 	ASSERT(econnp->conn_minor_arena != NULL);
2409 	if (econnp->conn_cred != NULL)
2410 		crfree(econnp->conn_cred);
2411 	econnp->conn_cred = aconnp->conn_cred;
2412 	aconnp->conn_cred = NULL;
2413 	econnp->conn_cpid = aconnp->conn_cpid;
2414 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2415 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2416 
2417 	econnp->conn_zoneid = aconnp->conn_zoneid;
2418 	econnp->conn_allzones = aconnp->conn_allzones;
2419 	econnp->conn_ixa->ixa_zoneid = aconnp->conn_ixa->ixa_zoneid;
2420 
2421 	econnp->conn_mac_mode = aconnp->conn_mac_mode;
2422 	econnp->conn_zone_is_global = aconnp->conn_zone_is_global;
2423 	aconnp->conn_mac_mode = CONN_MAC_DEFAULT;
2424 
2425 	/* Do the IPC initialization */
2426 	CONN_INC_REF(econnp);
2427 
2428 	/* Done with old IPC. Drop its ref on its connp */
2429 	CONN_DEC_REF(aconnp);
2430 }
2431 
2432 
2433 /*
2434  * Adapt to the information, such as rtt and rtt_sd, provided from the
2435  * DCE and IRE maintained by IP.
2436  *
2437  * Checks for multicast and broadcast destination address.
2438  * Returns zero if ok; an errno on failure.
2439  *
2440  * Note that the MSS calculation here is based on the info given in
2441  * the DCE and IRE.  We do not do any calculation based on TCP options.  They
2442  * will be handled in tcp_input_data() when TCP knows which options to use.
2443  *
2444  * Note on how TCP gets its parameters for a connection.
2445  *
2446  * When a tcp_t structure is allocated, it gets all the default parameters.
2447  * In tcp_set_destination(), it gets those metric parameters, like rtt, rtt_sd,
2448  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2449  * default.
2450  *
2451  * An incoming SYN with a multicast or broadcast destination address is dropped
2452  * in ip_fanout_v4/v6.
2453  *
2454  * An incoming SYN with a multicast or broadcast source address is always
2455  * dropped in tcp_set_destination, since IPDF_ALLOW_MCBC is not set in
2456  * conn_connect.
2457  * The same logic in tcp_set_destination also serves to
2458  * reject an attempt to connect to a broadcast or multicast (destination)
2459  * address.
2460  */
2461 static int
2462 tcp_set_destination(tcp_t *tcp)
2463 {
2464 	uint32_t	mss_max;
2465 	uint32_t	mss;
2466 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2467 	conn_t		*connp = tcp->tcp_connp;
2468 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2469 	iulp_t		uinfo;
2470 	int		error;
2471 	uint32_t	flags;
2472 
2473 	flags = IPDF_LSO | IPDF_ZCOPY;
2474 	/*
2475 	 * Make sure we have a dce for the destination to avoid dce_ident
2476 	 * contention for connected sockets.
2477 	 */
2478 	flags |= IPDF_UNIQUE_DCE;
2479 
2480 	if (!tcps->tcps_ignore_path_mtu)
2481 		connp->conn_ixa->ixa_flags |= IXAF_PMTU_DISCOVERY;
2482 
2483 	/* Use conn_lock to satify ASSERT; tcp is already serialized */
2484 	mutex_enter(&connp->conn_lock);
2485 	error = conn_connect(connp, &uinfo, flags);
2486 	mutex_exit(&connp->conn_lock);
2487 	if (error != 0)
2488 		return (error);
2489 
2490 	error = tcp_build_hdrs(tcp);
2491 	if (error != 0)
2492 		return (error);
2493 
2494 	tcp->tcp_localnet = uinfo.iulp_localnet;
2495 
2496 	if (uinfo.iulp_rtt != 0) {
2497 		clock_t	rto;
2498 
2499 		tcp->tcp_rtt_sa = uinfo.iulp_rtt;
2500 		tcp->tcp_rtt_sd = uinfo.iulp_rtt_sd;
2501 		rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2502 		    tcps->tcps_rexmit_interval_extra +
2503 		    (tcp->tcp_rtt_sa >> 5);
2504 
2505 		if (rto > tcps->tcps_rexmit_interval_max) {
2506 			tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2507 		} else if (rto < tcps->tcps_rexmit_interval_min) {
2508 			tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2509 		} else {
2510 			tcp->tcp_rto = rto;
2511 		}
2512 	}
2513 	if (uinfo.iulp_ssthresh != 0)
2514 		tcp->tcp_cwnd_ssthresh = uinfo.iulp_ssthresh;
2515 	else
2516 		tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2517 	if (uinfo.iulp_spipe > 0) {
2518 		connp->conn_sndbuf = MIN(uinfo.iulp_spipe,
2519 		    tcps->tcps_max_buf);
2520 		if (tcps->tcps_snd_lowat_fraction != 0) {
2521 			connp->conn_sndlowat = connp->conn_sndbuf /
2522 			    tcps->tcps_snd_lowat_fraction;
2523 		}
2524 		(void) tcp_maxpsz_set(tcp, B_TRUE);
2525 	}
2526 	/*
2527 	 * Note that up till now, acceptor always inherits receive
2528 	 * window from the listener.  But if there is a metrics
2529 	 * associated with a host, we should use that instead of
2530 	 * inheriting it from listener. Thus we need to pass this
2531 	 * info back to the caller.
2532 	 */
2533 	if (uinfo.iulp_rpipe > 0) {
2534 		tcp->tcp_rwnd = MIN(uinfo.iulp_rpipe,
2535 		    tcps->tcps_max_buf);
2536 	}
2537 
2538 	if (uinfo.iulp_rtomax > 0) {
2539 		tcp->tcp_second_timer_threshold =
2540 		    uinfo.iulp_rtomax;
2541 	}
2542 
2543 	/*
2544 	 * Use the metric option settings, iulp_tstamp_ok and
2545 	 * iulp_wscale_ok, only for active open. What this means
2546 	 * is that if the other side uses timestamp or window
2547 	 * scale option, TCP will also use those options. That
2548 	 * is for passive open.  If the application sets a
2549 	 * large window, window scale is enabled regardless of
2550 	 * the value in iulp_wscale_ok.  This is the behavior
2551 	 * since 2.6.  So we keep it.
2552 	 * The only case left in passive open processing is the
2553 	 * check for SACK.
2554 	 * For ECN, it should probably be like SACK.  But the
2555 	 * current value is binary, so we treat it like the other
2556 	 * cases.  The metric only controls active open.For passive
2557 	 * open, the ndd param, tcp_ecn_permitted, controls the
2558 	 * behavior.
2559 	 */
2560 	if (!tcp_detached) {
2561 		/*
2562 		 * The if check means that the following can only
2563 		 * be turned on by the metrics only IRE, but not off.
2564 		 */
2565 		if (uinfo.iulp_tstamp_ok)
2566 			tcp->tcp_snd_ts_ok = B_TRUE;
2567 		if (uinfo.iulp_wscale_ok)
2568 			tcp->tcp_snd_ws_ok = B_TRUE;
2569 		if (uinfo.iulp_sack == 2)
2570 			tcp->tcp_snd_sack_ok = B_TRUE;
2571 		if (uinfo.iulp_ecn_ok)
2572 			tcp->tcp_ecn_ok = B_TRUE;
2573 	} else {
2574 		/*
2575 		 * Passive open.
2576 		 *
2577 		 * As above, the if check means that SACK can only be
2578 		 * turned on by the metric only IRE.
2579 		 */
2580 		if (uinfo.iulp_sack > 0) {
2581 			tcp->tcp_snd_sack_ok = B_TRUE;
2582 		}
2583 	}
2584 
2585 	/*
2586 	 * XXX Note that currently, iulp_mtu can be as small as 68
2587 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2588 	 * length of all those options exceeds 28 bytes.  But because
2589 	 * of the tcp_mss_min check below, we may not have a problem if
2590 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2591 	 * the negative problem still exists.  And the check defeats PMTUd.
2592 	 * In fact, if PMTUd finds that the MSS should be smaller than
2593 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2594 	 * value.
2595 	 *
2596 	 * We do not deal with that now.  All those problems related to
2597 	 * PMTUd will be fixed later.
2598 	 */
2599 	ASSERT(uinfo.iulp_mtu != 0);
2600 	mss = tcp->tcp_initial_pmtu = uinfo.iulp_mtu;
2601 
2602 	/* Sanity check for MSS value. */
2603 	if (connp->conn_ipversion == IPV4_VERSION)
2604 		mss_max = tcps->tcps_mss_max_ipv4;
2605 	else
2606 		mss_max = tcps->tcps_mss_max_ipv6;
2607 
2608 	if (tcp->tcp_ipsec_overhead == 0)
2609 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2610 
2611 	mss -= tcp->tcp_ipsec_overhead;
2612 
2613 	if (mss < tcps->tcps_mss_min)
2614 		mss = tcps->tcps_mss_min;
2615 	if (mss > mss_max)
2616 		mss = mss_max;
2617 
2618 	/* Note that this is the maximum MSS, excluding all options. */
2619 	tcp->tcp_mss = mss;
2620 
2621 	/*
2622 	 * Update the tcp connection with LSO capability.
2623 	 */
2624 	tcp_update_lso(tcp, connp->conn_ixa);
2625 
2626 	/*
2627 	 * Initialize the ISS here now that we have the full connection ID.
2628 	 * The RFC 1948 method of initial sequence number generation requires
2629 	 * knowledge of the full connection ID before setting the ISS.
2630 	 */
2631 	tcp_iss_init(tcp);
2632 
2633 	tcp->tcp_loopback = (uinfo.iulp_loopback | uinfo.iulp_local);
2634 
2635 	/*
2636 	 * Make sure that conn is not marked incipient
2637 	 * for incoming connections. A blind
2638 	 * removal of incipient flag is cheaper than
2639 	 * check and removal.
2640 	 */
2641 	mutex_enter(&connp->conn_lock);
2642 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2643 	mutex_exit(&connp->conn_lock);
2644 	return (0);
2645 }
2646 
2647 static void
2648 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
2649 {
2650 	int	error;
2651 	conn_t	*connp = tcp->tcp_connp;
2652 	struct sockaddr	*sa;
2653 	mblk_t  *mp1;
2654 	struct T_bind_req *tbr;
2655 	int	backlog;
2656 	socklen_t	len;
2657 	sin_t	*sin;
2658 	sin6_t	*sin6;
2659 	cred_t		*cr;
2660 
2661 	/*
2662 	 * All Solaris components should pass a db_credp
2663 	 * for this TPI message, hence we ASSERT.
2664 	 * But in case there is some other M_PROTO that looks
2665 	 * like a TPI message sent by some other kernel
2666 	 * component, we check and return an error.
2667 	 */
2668 	cr = msg_getcred(mp, NULL);
2669 	ASSERT(cr != NULL);
2670 	if (cr == NULL) {
2671 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
2672 		return;
2673 	}
2674 
2675 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
2676 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
2677 		if (connp->conn_debug) {
2678 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2679 			    "tcp_tpi_bind: bad req, len %u",
2680 			    (uint_t)(mp->b_wptr - mp->b_rptr));
2681 		}
2682 		tcp_err_ack(tcp, mp, TPROTO, 0);
2683 		return;
2684 	}
2685 	/* Make sure the largest address fits */
2686 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t), 1);
2687 	if (mp1 == NULL) {
2688 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
2689 		return;
2690 	}
2691 	mp = mp1;
2692 	tbr = (struct T_bind_req *)mp->b_rptr;
2693 
2694 	backlog = tbr->CONIND_number;
2695 	len = tbr->ADDR_length;
2696 
2697 	switch (len) {
2698 	case 0:		/* request for a generic port */
2699 		tbr->ADDR_offset = sizeof (struct T_bind_req);
2700 		if (connp->conn_family == AF_INET) {
2701 			tbr->ADDR_length = sizeof (sin_t);
2702 			sin = (sin_t *)&tbr[1];
2703 			*sin = sin_null;
2704 			sin->sin_family = AF_INET;
2705 			sa = (struct sockaddr *)sin;
2706 			len = sizeof (sin_t);
2707 			mp->b_wptr = (uchar_t *)&sin[1];
2708 		} else {
2709 			ASSERT(connp->conn_family == AF_INET6);
2710 			tbr->ADDR_length = sizeof (sin6_t);
2711 			sin6 = (sin6_t *)&tbr[1];
2712 			*sin6 = sin6_null;
2713 			sin6->sin6_family = AF_INET6;
2714 			sa = (struct sockaddr *)sin6;
2715 			len = sizeof (sin6_t);
2716 			mp->b_wptr = (uchar_t *)&sin6[1];
2717 		}
2718 		break;
2719 
2720 	case sizeof (sin_t):    /* Complete IPv4 address */
2721 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
2722 		    sizeof (sin_t));
2723 		break;
2724 
2725 	case sizeof (sin6_t): /* Complete IPv6 address */
2726 		sa = (struct sockaddr *)mi_offset_param(mp,
2727 		    tbr->ADDR_offset, sizeof (sin6_t));
2728 		break;
2729 
2730 	default:
2731 		if (connp->conn_debug) {
2732 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2733 			    "tcp_tpi_bind: bad address length, %d",
2734 			    tbr->ADDR_length);
2735 		}
2736 		tcp_err_ack(tcp, mp, TBADADDR, 0);
2737 		return;
2738 	}
2739 
2740 	if (backlog > 0) {
2741 		error = tcp_do_listen(connp, sa, len, backlog, DB_CRED(mp),
2742 		    tbr->PRIM_type != O_T_BIND_REQ);
2743 	} else {
2744 		error = tcp_do_bind(connp, sa, len, DB_CRED(mp),
2745 		    tbr->PRIM_type != O_T_BIND_REQ);
2746 	}
2747 done:
2748 	if (error > 0) {
2749 		tcp_err_ack(tcp, mp, TSYSERR, error);
2750 	} else if (error < 0) {
2751 		tcp_err_ack(tcp, mp, -error, 0);
2752 	} else {
2753 		/*
2754 		 * Update port information as sockfs/tpi needs it for checking
2755 		 */
2756 		if (connp->conn_family == AF_INET) {
2757 			sin = (sin_t *)sa;
2758 			sin->sin_port = connp->conn_lport;
2759 		} else {
2760 			sin6 = (sin6_t *)sa;
2761 			sin6->sin6_port = connp->conn_lport;
2762 		}
2763 		mp->b_datap->db_type = M_PCPROTO;
2764 		tbr->PRIM_type = T_BIND_ACK;
2765 		putnext(connp->conn_rq, mp);
2766 	}
2767 }
2768 
2769 /*
2770  * If the "bind_to_req_port_only" parameter is set, if the requested port
2771  * number is available, return it, If not return 0
2772  *
2773  * If "bind_to_req_port_only" parameter is not set and
2774  * If the requested port number is available, return it.  If not, return
2775  * the first anonymous port we happen across.  If no anonymous ports are
2776  * available, return 0. addr is the requested local address, if any.
2777  *
2778  * In either case, when succeeding update the tcp_t to record the port number
2779  * and insert it in the bind hash table.
2780  *
2781  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
2782  * without setting SO_REUSEADDR. This is needed so that they
2783  * can be viewed as two independent transport protocols.
2784  */
2785 static in_port_t
2786 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
2787     int reuseaddr, boolean_t quick_connect,
2788     boolean_t bind_to_req_port_only, boolean_t user_specified)
2789 {
2790 	/* number of times we have run around the loop */
2791 	int count = 0;
2792 	/* maximum number of times to run around the loop */
2793 	int loopmax;
2794 	conn_t *connp = tcp->tcp_connp;
2795 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2796 
2797 	/*
2798 	 * Lookup for free addresses is done in a loop and "loopmax"
2799 	 * influences how long we spin in the loop
2800 	 */
2801 	if (bind_to_req_port_only) {
2802 		/*
2803 		 * If the requested port is busy, don't bother to look
2804 		 * for a new one. Setting loop maximum count to 1 has
2805 		 * that effect.
2806 		 */
2807 		loopmax = 1;
2808 	} else {
2809 		/*
2810 		 * If the requested port is busy, look for a free one
2811 		 * in the anonymous port range.
2812 		 * Set loopmax appropriately so that one does not look
2813 		 * forever in the case all of the anonymous ports are in use.
2814 		 */
2815 		if (connp->conn_anon_priv_bind) {
2816 			/*
2817 			 * loopmax =
2818 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
2819 			 */
2820 			loopmax = IPPORT_RESERVED -
2821 			    tcps->tcps_min_anonpriv_port;
2822 		} else {
2823 			loopmax = (tcps->tcps_largest_anon_port -
2824 			    tcps->tcps_smallest_anon_port + 1);
2825 		}
2826 	}
2827 	do {
2828 		uint16_t	lport;
2829 		tf_t		*tbf;
2830 		tcp_t		*ltcp;
2831 		conn_t		*lconnp;
2832 
2833 		lport = htons(port);
2834 
2835 		/*
2836 		 * Ensure that the tcp_t is not currently in the bind hash.
2837 		 * Hold the lock on the hash bucket to ensure that
2838 		 * the duplicate check plus the insertion is an atomic
2839 		 * operation.
2840 		 *
2841 		 * This function does an inline lookup on the bind hash list
2842 		 * Make sure that we access only members of tcp_t
2843 		 * and that we don't look at tcp_tcp, since we are not
2844 		 * doing a CONN_INC_REF.
2845 		 */
2846 		tcp_bind_hash_remove(tcp);
2847 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
2848 		mutex_enter(&tbf->tf_lock);
2849 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
2850 		    ltcp = ltcp->tcp_bind_hash) {
2851 			if (lport == ltcp->tcp_connp->conn_lport)
2852 				break;
2853 		}
2854 
2855 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
2856 			boolean_t not_socket;
2857 			boolean_t exclbind;
2858 
2859 			lconnp = ltcp->tcp_connp;
2860 
2861 			/*
2862 			 * On a labeled system, we must treat bindings to ports
2863 			 * on shared IP addresses by sockets with MAC exemption
2864 			 * privilege as being in all zones, as there's
2865 			 * otherwise no way to identify the right receiver.
2866 			 */
2867 			if (!IPCL_BIND_ZONE_MATCH(lconnp, connp))
2868 				continue;
2869 
2870 			/*
2871 			 * If TCP_EXCLBIND is set for either the bound or
2872 			 * binding endpoint, the semantics of bind
2873 			 * is changed according to the following.
2874 			 *
2875 			 * spec = specified address (v4 or v6)
2876 			 * unspec = unspecified address (v4 or v6)
2877 			 * A = specified addresses are different for endpoints
2878 			 *
2879 			 * bound	bind to		allowed
2880 			 * -------------------------------------
2881 			 * unspec	unspec		no
2882 			 * unspec	spec		no
2883 			 * spec		unspec		no
2884 			 * spec		spec		yes if A
2885 			 *
2886 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
2887 			 * as TCP_EXCLBIND, except that zoneid is ignored.
2888 			 *
2889 			 * Note:
2890 			 *
2891 			 * 1. Because of TLI semantics, an endpoint can go
2892 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
2893 			 * TCPS_BOUND, depending on whether it is originally
2894 			 * a listener or not.  That is why we need to check
2895 			 * for states greater than or equal to TCPS_BOUND
2896 			 * here.
2897 			 *
2898 			 * 2. Ideally, we should only check for state equals
2899 			 * to TCPS_LISTEN. And the following check should be
2900 			 * added.
2901 			 *
2902 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
2903 			 *	!reuseaddr || !lconnp->conn_reuseaddr) {
2904 			 *		...
2905 			 * }
2906 			 *
2907 			 * The semantics will be changed to this.  If the
2908 			 * endpoint on the list is in state not equal to
2909 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
2910 			 * set, let the bind succeed.
2911 			 *
2912 			 * Because of (1), we cannot do that for TLI
2913 			 * endpoints.  But we can do that for socket endpoints.
2914 			 * If in future, we can change this going back
2915 			 * semantics, we can use the above check for TLI also.
2916 			 */
2917 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
2918 			    TCP_IS_SOCKET(tcp));
2919 			exclbind = lconnp->conn_exclbind ||
2920 			    connp->conn_exclbind;
2921 
2922 			if ((lconnp->conn_mac_mode != CONN_MAC_DEFAULT) ||
2923 			    (connp->conn_mac_mode != CONN_MAC_DEFAULT) ||
2924 			    (exclbind && (not_socket ||
2925 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
2926 				if (V6_OR_V4_INADDR_ANY(
2927 				    lconnp->conn_bound_addr_v6) ||
2928 				    V6_OR_V4_INADDR_ANY(*laddr) ||
2929 				    IN6_ARE_ADDR_EQUAL(laddr,
2930 				    &lconnp->conn_bound_addr_v6)) {
2931 					break;
2932 				}
2933 				continue;
2934 			}
2935 
2936 			/*
2937 			 * Check ipversion to allow IPv4 and IPv6 sockets to
2938 			 * have disjoint port number spaces, if *_EXCLBIND
2939 			 * is not set and only if the application binds to a
2940 			 * specific port. We use the same autoassigned port
2941 			 * number space for IPv4 and IPv6 sockets.
2942 			 */
2943 			if (connp->conn_ipversion != lconnp->conn_ipversion &&
2944 			    bind_to_req_port_only)
2945 				continue;
2946 
2947 			/*
2948 			 * Ideally, we should make sure that the source
2949 			 * address, remote address, and remote port in the
2950 			 * four tuple for this tcp-connection is unique.
2951 			 * However, trying to find out the local source
2952 			 * address would require too much code duplication
2953 			 * with IP, since IP needs needs to have that code
2954 			 * to support userland TCP implementations.
2955 			 */
2956 			if (quick_connect &&
2957 			    (ltcp->tcp_state > TCPS_LISTEN) &&
2958 			    ((connp->conn_fport != lconnp->conn_fport) ||
2959 			    !IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6,
2960 			    &lconnp->conn_faddr_v6)))
2961 				continue;
2962 
2963 			if (!reuseaddr) {
2964 				/*
2965 				 * No socket option SO_REUSEADDR.
2966 				 * If existing port is bound to
2967 				 * a non-wildcard IP address
2968 				 * and the requesting stream is
2969 				 * bound to a distinct
2970 				 * different IP addresses
2971 				 * (non-wildcard, also), keep
2972 				 * going.
2973 				 */
2974 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
2975 				    !V6_OR_V4_INADDR_ANY(
2976 				    lconnp->conn_bound_addr_v6) &&
2977 				    !IN6_ARE_ADDR_EQUAL(laddr,
2978 				    &lconnp->conn_bound_addr_v6))
2979 					continue;
2980 				if (ltcp->tcp_state >= TCPS_BOUND) {
2981 					/*
2982 					 * This port is being used and
2983 					 * its state is >= TCPS_BOUND,
2984 					 * so we can't bind to it.
2985 					 */
2986 					break;
2987 				}
2988 			} else {
2989 				/*
2990 				 * socket option SO_REUSEADDR is set on the
2991 				 * binding tcp_t.
2992 				 *
2993 				 * If two streams are bound to
2994 				 * same IP address or both addr
2995 				 * and bound source are wildcards
2996 				 * (INADDR_ANY), we want to stop
2997 				 * searching.
2998 				 * We have found a match of IP source
2999 				 * address and source port, which is
3000 				 * refused regardless of the
3001 				 * SO_REUSEADDR setting, so we break.
3002 				 */
3003 				if (IN6_ARE_ADDR_EQUAL(laddr,
3004 				    &lconnp->conn_bound_addr_v6) &&
3005 				    (ltcp->tcp_state == TCPS_LISTEN ||
3006 				    ltcp->tcp_state == TCPS_BOUND))
3007 					break;
3008 			}
3009 		}
3010 		if (ltcp != NULL) {
3011 			/* The port number is busy */
3012 			mutex_exit(&tbf->tf_lock);
3013 		} else {
3014 			/*
3015 			 * This port is ours. Insert in fanout and mark as
3016 			 * bound to prevent others from getting the port
3017 			 * number.
3018 			 */
3019 			tcp->tcp_state = TCPS_BOUND;
3020 			connp->conn_lport = htons(port);
3021 
3022 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3023 			    connp->conn_lport)] == tbf);
3024 			tcp_bind_hash_insert(tbf, tcp, 1);
3025 
3026 			mutex_exit(&tbf->tf_lock);
3027 
3028 			/*
3029 			 * We don't want tcp_next_port_to_try to "inherit"
3030 			 * a port number supplied by the user in a bind.
3031 			 */
3032 			if (user_specified)
3033 				return (port);
3034 
3035 			/*
3036 			 * This is the only place where tcp_next_port_to_try
3037 			 * is updated. After the update, it may or may not
3038 			 * be in the valid range.
3039 			 */
3040 			if (!connp->conn_anon_priv_bind)
3041 				tcps->tcps_next_port_to_try = port + 1;
3042 			return (port);
3043 		}
3044 
3045 		if (connp->conn_anon_priv_bind) {
3046 			port = tcp_get_next_priv_port(tcp);
3047 		} else {
3048 			if (count == 0 && user_specified) {
3049 				/*
3050 				 * We may have to return an anonymous port. So
3051 				 * get one to start with.
3052 				 */
3053 				port =
3054 				    tcp_update_next_port(
3055 				    tcps->tcps_next_port_to_try,
3056 				    tcp, B_TRUE);
3057 				user_specified = B_FALSE;
3058 			} else {
3059 				port = tcp_update_next_port(port + 1, tcp,
3060 				    B_FALSE);
3061 			}
3062 		}
3063 		if (port == 0)
3064 			break;
3065 
3066 		/*
3067 		 * Don't let this loop run forever in the case where
3068 		 * all of the anonymous ports are in use.
3069 		 */
3070 	} while (++count < loopmax);
3071 	return (0);
3072 }
3073 
3074 /*
3075  * tcp_clean_death / tcp_close_detached must not be called more than once
3076  * on a tcp. Thus every function that potentially calls tcp_clean_death
3077  * must check for the tcp state before calling tcp_clean_death.
3078  * Eg. tcp_input_data, tcp_eager_kill, tcp_clean_death_wrapper,
3079  * tcp_timer_handler, all check for the tcp state.
3080  */
3081 /* ARGSUSED */
3082 void
3083 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2,
3084     ip_recv_attr_t *dummy)
3085 {
3086 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3087 
3088 	freemsg(mp);
3089 	if (tcp->tcp_state > TCPS_BOUND)
3090 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3091 		    ETIMEDOUT, 5);
3092 }
3093 
3094 /*
3095  * We are dying for some reason.  Try to do it gracefully.  (May be called
3096  * as writer.)
3097  *
3098  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3099  * done by a service procedure).
3100  * TBD - Should the return value distinguish between the tcp_t being
3101  * freed and it being reinitialized?
3102  */
3103 static int
3104 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3105 {
3106 	mblk_t	*mp;
3107 	queue_t	*q;
3108 	conn_t	*connp = tcp->tcp_connp;
3109 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3110 
3111 	TCP_CLD_STAT(tag);
3112 
3113 #if TCP_TAG_CLEAN_DEATH
3114 	tcp->tcp_cleandeathtag = tag;
3115 #endif
3116 
3117 	if (tcp->tcp_fused)
3118 		tcp_unfuse(tcp);
3119 
3120 	if (tcp->tcp_linger_tid != 0 &&
3121 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3122 		tcp_stop_lingering(tcp);
3123 	}
3124 
3125 	ASSERT(tcp != NULL);
3126 	ASSERT((connp->conn_family == AF_INET &&
3127 	    connp->conn_ipversion == IPV4_VERSION) ||
3128 	    (connp->conn_family == AF_INET6 &&
3129 	    (connp->conn_ipversion == IPV4_VERSION ||
3130 	    connp->conn_ipversion == IPV6_VERSION)));
3131 
3132 	if (TCP_IS_DETACHED(tcp)) {
3133 		if (tcp->tcp_hard_binding) {
3134 			/*
3135 			 * Its an eager that we are dealing with. We close the
3136 			 * eager but in case a conn_ind has already gone to the
3137 			 * listener, let tcp_accept_finish() send a discon_ind
3138 			 * to the listener and drop the last reference. If the
3139 			 * listener doesn't even know about the eager i.e. the
3140 			 * conn_ind hasn't gone up, blow away the eager and drop
3141 			 * the last reference as well. If the conn_ind has gone
3142 			 * up, state should be BOUND. tcp_accept_finish
3143 			 * will figure out that the connection has received a
3144 			 * RST and will send a DISCON_IND to the application.
3145 			 */
3146 			tcp_closei_local(tcp);
3147 			if (!tcp->tcp_tconnind_started) {
3148 				CONN_DEC_REF(connp);
3149 			} else {
3150 				tcp->tcp_state = TCPS_BOUND;
3151 			}
3152 		} else {
3153 			tcp_close_detached(tcp);
3154 		}
3155 		return (0);
3156 	}
3157 
3158 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3159 
3160 	/*
3161 	 * The connection is dead.  Decrement listener connection counter if
3162 	 * necessary.
3163 	 */
3164 	if (tcp->tcp_listen_cnt != NULL)
3165 		TCP_DECR_LISTEN_CNT(tcp);
3166 
3167 	q = connp->conn_rq;
3168 
3169 	/* Trash all inbound data */
3170 	if (!IPCL_IS_NONSTR(connp)) {
3171 		ASSERT(q != NULL);
3172 		flushq(q, FLUSHALL);
3173 	}
3174 
3175 	/*
3176 	 * If we are at least part way open and there is error
3177 	 * (err==0 implies no error)
3178 	 * notify our client by a T_DISCON_IND.
3179 	 */
3180 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3181 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3182 		    !TCP_IS_SOCKET(tcp)) {
3183 			/*
3184 			 * Send M_FLUSH according to TPI. Because sockets will
3185 			 * (and must) ignore FLUSHR we do that only for TPI
3186 			 * endpoints and sockets in STREAMS mode.
3187 			 */
3188 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3189 		}
3190 		if (connp->conn_debug) {
3191 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3192 			    "tcp_clean_death: discon err %d", err);
3193 		}
3194 		if (IPCL_IS_NONSTR(connp)) {
3195 			/* Direct socket, use upcall */
3196 			(*connp->conn_upcalls->su_disconnected)(
3197 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3198 		} else {
3199 			mp = mi_tpi_discon_ind(NULL, err, 0);
3200 			if (mp != NULL) {
3201 				putnext(q, mp);
3202 			} else {
3203 				if (connp->conn_debug) {
3204 					(void) strlog(TCP_MOD_ID, 0, 1,
3205 					    SL_ERROR|SL_TRACE,
3206 					    "tcp_clean_death, sending M_ERROR");
3207 				}
3208 				(void) putnextctl1(q, M_ERROR, EPROTO);
3209 			}
3210 		}
3211 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3212 			/* SYN_SENT or SYN_RCVD */
3213 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3214 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3215 			/* ESTABLISHED or CLOSE_WAIT */
3216 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3217 		}
3218 	}
3219 
3220 	tcp_reinit(tcp);
3221 	if (IPCL_IS_NONSTR(connp))
3222 		(void) tcp_do_unbind(connp);
3223 
3224 	return (-1);
3225 }
3226 
3227 /*
3228  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3229  * to expire, stop the wait and finish the close.
3230  */
3231 static void
3232 tcp_stop_lingering(tcp_t *tcp)
3233 {
3234 	clock_t	delta = 0;
3235 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3236 	conn_t		*connp = tcp->tcp_connp;
3237 
3238 	tcp->tcp_linger_tid = 0;
3239 	if (tcp->tcp_state > TCPS_LISTEN) {
3240 		tcp_acceptor_hash_remove(tcp);
3241 		mutex_enter(&tcp->tcp_non_sq_lock);
3242 		if (tcp->tcp_flow_stopped) {
3243 			tcp_clrqfull(tcp);
3244 		}
3245 		mutex_exit(&tcp->tcp_non_sq_lock);
3246 
3247 		if (tcp->tcp_timer_tid != 0) {
3248 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3249 			tcp->tcp_timer_tid = 0;
3250 		}
3251 		/*
3252 		 * Need to cancel those timers which will not be used when
3253 		 * TCP is detached.  This has to be done before the conn_wq
3254 		 * is cleared.
3255 		 */
3256 		tcp_timers_stop(tcp);
3257 
3258 		tcp->tcp_detached = B_TRUE;
3259 		connp->conn_rq = NULL;
3260 		connp->conn_wq = NULL;
3261 
3262 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3263 			tcp_time_wait_append(tcp);
3264 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3265 			goto finish;
3266 		}
3267 
3268 		/*
3269 		 * If delta is zero the timer event wasn't executed and was
3270 		 * successfully canceled. In this case we need to restart it
3271 		 * with the minimal delta possible.
3272 		 */
3273 		if (delta >= 0) {
3274 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3275 			    delta ? delta : 1);
3276 		}
3277 	} else {
3278 		tcp_closei_local(tcp);
3279 		CONN_DEC_REF(connp);
3280 	}
3281 finish:
3282 	/* Signal closing thread that it can complete close */
3283 	mutex_enter(&tcp->tcp_closelock);
3284 	tcp->tcp_detached = B_TRUE;
3285 	connp->conn_rq = NULL;
3286 	connp->conn_wq = NULL;
3287 
3288 	tcp->tcp_closed = 1;
3289 	cv_signal(&tcp->tcp_closecv);
3290 	mutex_exit(&tcp->tcp_closelock);
3291 }
3292 
3293 /*
3294  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3295  * expires.
3296  */
3297 static void
3298 tcp_close_linger_timeout(void *arg)
3299 {
3300 	conn_t	*connp = (conn_t *)arg;
3301 	tcp_t 	*tcp = connp->conn_tcp;
3302 
3303 	tcp->tcp_client_errno = ETIMEDOUT;
3304 	tcp_stop_lingering(tcp);
3305 }
3306 
3307 static void
3308 tcp_close_common(conn_t *connp, int flags)
3309 {
3310 	tcp_t		*tcp = connp->conn_tcp;
3311 	mblk_t 		*mp = &tcp->tcp_closemp;
3312 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3313 	mblk_t		*bp;
3314 
3315 	ASSERT(connp->conn_ref >= 2);
3316 
3317 	/*
3318 	 * Mark the conn as closing. ipsq_pending_mp_add will not
3319 	 * add any mp to the pending mp list, after this conn has
3320 	 * started closing.
3321 	 */
3322 	mutex_enter(&connp->conn_lock);
3323 	connp->conn_state_flags |= CONN_CLOSING;
3324 	if (connp->conn_oper_pending_ill != NULL)
3325 		conn_ioctl_cleanup_reqd = B_TRUE;
3326 	CONN_INC_REF_LOCKED(connp);
3327 	mutex_exit(&connp->conn_lock);
3328 	tcp->tcp_closeflags = (uint8_t)flags;
3329 	ASSERT(connp->conn_ref >= 3);
3330 
3331 	/*
3332 	 * tcp_closemp_used is used below without any protection of a lock
3333 	 * as we don't expect any one else to use it concurrently at this
3334 	 * point otherwise it would be a major defect.
3335 	 */
3336 
3337 	if (mp->b_prev == NULL)
3338 		tcp->tcp_closemp_used = B_TRUE;
3339 	else
3340 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3341 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3342 
3343 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3344 
3345 	/*
3346 	 * Cleanup any queued ioctls here. This must be done before the wq/rq
3347 	 * are re-written by tcp_close_output().
3348 	 */
3349 	if (conn_ioctl_cleanup_reqd)
3350 		conn_ioctl_cleanup(connp);
3351 
3352 	/*
3353 	 * As CONN_CLOSING is set, no further ioctls should be passed down to
3354 	 * IP for this conn (see the guards in tcp_ioctl, tcp_wput_ioctl and
3355 	 * tcp_wput_iocdata). If the ioctl was queued on an ipsq,
3356 	 * conn_ioctl_cleanup should have found it and removed it. If the ioctl
3357 	 * was still in flight at the time, we wait for it here. See comments
3358 	 * for CONN_INC_IOCTLREF in ip.h for details.
3359 	 */
3360 	mutex_enter(&connp->conn_lock);
3361 	while (connp->conn_ioctlref > 0)
3362 		cv_wait(&connp->conn_cv, &connp->conn_lock);
3363 	ASSERT(connp->conn_ioctlref == 0);
3364 	ASSERT(connp->conn_oper_pending_ill == NULL);
3365 	mutex_exit(&connp->conn_lock);
3366 
3367 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3368 	    NULL, tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3369 
3370 	mutex_enter(&tcp->tcp_closelock);
3371 	while (!tcp->tcp_closed) {
3372 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3373 			/*
3374 			 * The cv_wait_sig() was interrupted. We now do the
3375 			 * following:
3376 			 *
3377 			 * 1) If the endpoint was lingering, we allow this
3378 			 * to be interrupted by cancelling the linger timeout
3379 			 * and closing normally.
3380 			 *
3381 			 * 2) Revert to calling cv_wait()
3382 			 *
3383 			 * We revert to using cv_wait() to avoid an
3384 			 * infinite loop which can occur if the calling
3385 			 * thread is higher priority than the squeue worker
3386 			 * thread and is bound to the same cpu.
3387 			 */
3388 			if (connp->conn_linger && connp->conn_lingertime > 0) {
3389 				mutex_exit(&tcp->tcp_closelock);
3390 				/* Entering squeue, bump ref count. */
3391 				CONN_INC_REF(connp);
3392 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3393 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3394 				    tcp_linger_interrupted, connp, NULL,
3395 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3396 				mutex_enter(&tcp->tcp_closelock);
3397 			}
3398 			break;
3399 		}
3400 	}
3401 	while (!tcp->tcp_closed)
3402 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3403 	mutex_exit(&tcp->tcp_closelock);
3404 
3405 	/*
3406 	 * In the case of listener streams that have eagers in the q or q0
3407 	 * we wait for the eagers to drop their reference to us. conn_rq and
3408 	 * conn_wq of the eagers point to our queues. By waiting for the
3409 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3410 	 * up their queue pointers and also dropped their references to us.
3411 	 */
3412 	if (tcp->tcp_wait_for_eagers) {
3413 		mutex_enter(&connp->conn_lock);
3414 		while (connp->conn_ref != 1) {
3415 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3416 		}
3417 		mutex_exit(&connp->conn_lock);
3418 	}
3419 
3420 	connp->conn_cpid = NOPID;
3421 }
3422 
3423 static int
3424 tcp_tpi_close(queue_t *q, int flags)
3425 {
3426 	conn_t		*connp;
3427 
3428 	ASSERT(WR(q)->q_next == NULL);
3429 
3430 	if (flags & SO_FALLBACK) {
3431 		/*
3432 		 * stream is being closed while in fallback
3433 		 * simply free the resources that were allocated
3434 		 */
3435 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3436 		qprocsoff(q);
3437 		goto done;
3438 	}
3439 
3440 	connp = Q_TO_CONN(q);
3441 	/*
3442 	 * We are being closed as /dev/tcp or /dev/tcp6.
3443 	 */
3444 	tcp_close_common(connp, flags);
3445 
3446 	qprocsoff(q);
3447 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3448 
3449 	/*
3450 	 * Drop IP's reference on the conn. This is the last reference
3451 	 * on the connp if the state was less than established. If the
3452 	 * connection has gone into timewait state, then we will have
3453 	 * one ref for the TCP and one more ref (total of two) for the
3454 	 * classifier connected hash list (a timewait connections stays
3455 	 * in connected hash till closed).
3456 	 *
3457 	 * We can't assert the references because there might be other
3458 	 * transient reference places because of some walkers or queued
3459 	 * packets in squeue for the timewait state.
3460 	 */
3461 	CONN_DEC_REF(connp);
3462 done:
3463 	q->q_ptr = WR(q)->q_ptr = NULL;
3464 	return (0);
3465 }
3466 
3467 static int
3468 tcp_tpi_close_accept(queue_t *q)
3469 {
3470 	vmem_t	*minor_arena;
3471 	dev_t	conn_dev;
3472 
3473 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3474 
3475 	/*
3476 	 * We had opened an acceptor STREAM for sockfs which is
3477 	 * now being closed due to some error.
3478 	 */
3479 	qprocsoff(q);
3480 
3481 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3482 	conn_dev = (dev_t)RD(q)->q_ptr;
3483 	ASSERT(minor_arena != NULL);
3484 	ASSERT(conn_dev != 0);
3485 	inet_minor_free(minor_arena, conn_dev);
3486 	q->q_ptr = WR(q)->q_ptr = NULL;
3487 	return (0);
3488 }
3489 
3490 /*
3491  * Called by tcp_close() routine via squeue when lingering is
3492  * interrupted by a signal.
3493  */
3494 
3495 /* ARGSUSED */
3496 static void
3497 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
3498 {
3499 	conn_t	*connp = (conn_t *)arg;
3500 	tcp_t	*tcp = connp->conn_tcp;
3501 
3502 	freeb(mp);
3503 	if (tcp->tcp_linger_tid != 0 &&
3504 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3505 		tcp_stop_lingering(tcp);
3506 		tcp->tcp_client_errno = EINTR;
3507 	}
3508 }
3509 
3510 /*
3511  * Called by streams close routine via squeues when our client blows off her
3512  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3513  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3514  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3515  * acked.
3516  *
3517  * NOTE: tcp_close potentially returns error when lingering.
3518  * However, the stream head currently does not pass these errors
3519  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3520  * errors to the application (from tsleep()) and not errors
3521  * like ECONNRESET caused by receiving a reset packet.
3522  */
3523 
3524 /* ARGSUSED */
3525 static void
3526 tcp_close_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
3527 {
3528 	char	*msg;
3529 	conn_t	*connp = (conn_t *)arg;
3530 	tcp_t	*tcp = connp->conn_tcp;
3531 	clock_t	delta = 0;
3532 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3533 
3534 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3535 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3536 
3537 	mutex_enter(&tcp->tcp_eager_lock);
3538 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3539 		/* Cleanup for listener */
3540 		tcp_eager_cleanup(tcp, 0);
3541 		tcp->tcp_wait_for_eagers = 1;
3542 	}
3543 	mutex_exit(&tcp->tcp_eager_lock);
3544 
3545 	tcp->tcp_lso = B_FALSE;
3546 
3547 	msg = NULL;
3548 	switch (tcp->tcp_state) {
3549 	case TCPS_CLOSED:
3550 	case TCPS_IDLE:
3551 	case TCPS_BOUND:
3552 	case TCPS_LISTEN:
3553 		break;
3554 	case TCPS_SYN_SENT:
3555 		msg = "tcp_close, during connect";
3556 		break;
3557 	case TCPS_SYN_RCVD:
3558 		/*
3559 		 * Close during the connect 3-way handshake
3560 		 * but here there may or may not be pending data
3561 		 * already on queue. Process almost same as in
3562 		 * the ESTABLISHED state.
3563 		 */
3564 		/* FALLTHRU */
3565 	default:
3566 		if (tcp->tcp_fused)
3567 			tcp_unfuse(tcp);
3568 
3569 		/*
3570 		 * If SO_LINGER has set a zero linger time, abort the
3571 		 * connection with a reset.
3572 		 */
3573 		if (connp->conn_linger && connp->conn_lingertime == 0) {
3574 			msg = "tcp_close, zero lingertime";
3575 			break;
3576 		}
3577 
3578 		/*
3579 		 * Abort connection if there is unread data queued.
3580 		 */
3581 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3582 			msg = "tcp_close, unread data";
3583 			break;
3584 		}
3585 		/*
3586 		 * We have done a qwait() above which could have possibly
3587 		 * drained more messages in turn causing transition to a
3588 		 * different state. Check whether we have to do the rest
3589 		 * of the processing or not.
3590 		 */
3591 		if (tcp->tcp_state <= TCPS_LISTEN)
3592 			break;
3593 
3594 		/*
3595 		 * Transmit the FIN before detaching the tcp_t.
3596 		 * After tcp_detach returns this queue/perimeter
3597 		 * no longer owns the tcp_t thus others can modify it.
3598 		 */
3599 		(void) tcp_xmit_end(tcp);
3600 
3601 		/*
3602 		 * If lingering on close then wait until the fin is acked,
3603 		 * the SO_LINGER time passes, or a reset is sent/received.
3604 		 */
3605 		if (connp->conn_linger && connp->conn_lingertime > 0 &&
3606 		    !(tcp->tcp_fin_acked) &&
3607 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3608 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3609 				tcp->tcp_client_errno = EWOULDBLOCK;
3610 			} else if (tcp->tcp_client_errno == 0) {
3611 
3612 				ASSERT(tcp->tcp_linger_tid == 0);
3613 
3614 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3615 				    tcp_close_linger_timeout,
3616 				    connp->conn_lingertime * hz);
3617 
3618 				/* tcp_close_linger_timeout will finish close */
3619 				if (tcp->tcp_linger_tid == 0)
3620 					tcp->tcp_client_errno = ENOSR;
3621 				else
3622 					return;
3623 			}
3624 
3625 			/*
3626 			 * Check if we need to detach or just close
3627 			 * the instance.
3628 			 */
3629 			if (tcp->tcp_state <= TCPS_LISTEN)
3630 				break;
3631 		}
3632 
3633 		/*
3634 		 * Make sure that no other thread will access the conn_rq of
3635 		 * this instance (through lookups etc.) as conn_rq will go
3636 		 * away shortly.
3637 		 */
3638 		tcp_acceptor_hash_remove(tcp);
3639 
3640 		mutex_enter(&tcp->tcp_non_sq_lock);
3641 		if (tcp->tcp_flow_stopped) {
3642 			tcp_clrqfull(tcp);
3643 		}
3644 		mutex_exit(&tcp->tcp_non_sq_lock);
3645 
3646 		if (tcp->tcp_timer_tid != 0) {
3647 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3648 			tcp->tcp_timer_tid = 0;
3649 		}
3650 		/*
3651 		 * Need to cancel those timers which will not be used when
3652 		 * TCP is detached.  This has to be done before the conn_wq
3653 		 * is set to NULL.
3654 		 */
3655 		tcp_timers_stop(tcp);
3656 
3657 		tcp->tcp_detached = B_TRUE;
3658 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3659 			tcp_time_wait_append(tcp);
3660 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3661 			ASSERT(connp->conn_ref >= 3);
3662 			goto finish;
3663 		}
3664 
3665 		/*
3666 		 * If delta is zero the timer event wasn't executed and was
3667 		 * successfully canceled. In this case we need to restart it
3668 		 * with the minimal delta possible.
3669 		 */
3670 		if (delta >= 0)
3671 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3672 			    delta ? delta : 1);
3673 
3674 		ASSERT(connp->conn_ref >= 3);
3675 		goto finish;
3676 	}
3677 
3678 	/* Detach did not complete. Still need to remove q from stream. */
3679 	if (msg) {
3680 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
3681 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
3682 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3683 		if (tcp->tcp_state == TCPS_SYN_SENT ||
3684 		    tcp->tcp_state == TCPS_SYN_RCVD)
3685 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3686 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
3687 	}
3688 
3689 	tcp_closei_local(tcp);
3690 	CONN_DEC_REF(connp);
3691 	ASSERT(connp->conn_ref >= 2);
3692 
3693 finish:
3694 	mutex_enter(&tcp->tcp_closelock);
3695 	/*
3696 	 * Don't change the queues in the case of a listener that has
3697 	 * eagers in its q or q0. It could surprise the eagers.
3698 	 * Instead wait for the eagers outside the squeue.
3699 	 */
3700 	if (!tcp->tcp_wait_for_eagers) {
3701 		tcp->tcp_detached = B_TRUE;
3702 		connp->conn_rq = NULL;
3703 		connp->conn_wq = NULL;
3704 	}
3705 
3706 	/* Signal tcp_close() to finish closing. */
3707 	tcp->tcp_closed = 1;
3708 	cv_signal(&tcp->tcp_closecv);
3709 	mutex_exit(&tcp->tcp_closelock);
3710 }
3711 
3712 /*
3713  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
3714  * Some stream heads get upset if they see these later on as anything but NULL.
3715  */
3716 static void
3717 tcp_close_mpp(mblk_t **mpp)
3718 {
3719 	mblk_t	*mp;
3720 
3721 	if ((mp = *mpp) != NULL) {
3722 		do {
3723 			mp->b_next = NULL;
3724 			mp->b_prev = NULL;
3725 		} while ((mp = mp->b_cont) != NULL);
3726 
3727 		mp = *mpp;
3728 		*mpp = NULL;
3729 		freemsg(mp);
3730 	}
3731 }
3732 
3733 /* Do detached close. */
3734 static void
3735 tcp_close_detached(tcp_t *tcp)
3736 {
3737 	if (tcp->tcp_fused)
3738 		tcp_unfuse(tcp);
3739 
3740 	/*
3741 	 * Clustering code serializes TCP disconnect callbacks and
3742 	 * cluster tcp list walks by blocking a TCP disconnect callback
3743 	 * if a cluster tcp list walk is in progress. This ensures
3744 	 * accurate accounting of TCPs in the cluster code even though
3745 	 * the TCP list walk itself is not atomic.
3746 	 */
3747 	tcp_closei_local(tcp);
3748 	CONN_DEC_REF(tcp->tcp_connp);
3749 }
3750 
3751 /*
3752  * Stop all TCP timers, and free the timer mblks if requested.
3753  */
3754 void
3755 tcp_timers_stop(tcp_t *tcp)
3756 {
3757 	if (tcp->tcp_timer_tid != 0) {
3758 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3759 		tcp->tcp_timer_tid = 0;
3760 	}
3761 	if (tcp->tcp_ka_tid != 0) {
3762 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
3763 		tcp->tcp_ka_tid = 0;
3764 	}
3765 	if (tcp->tcp_ack_tid != 0) {
3766 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
3767 		tcp->tcp_ack_tid = 0;
3768 	}
3769 	if (tcp->tcp_push_tid != 0) {
3770 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
3771 		tcp->tcp_push_tid = 0;
3772 	}
3773 	if (tcp->tcp_reass_tid != 0) {
3774 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_reass_tid);
3775 		tcp->tcp_reass_tid = 0;
3776 	}
3777 }
3778 
3779 /*
3780  * The tcp_t is going away. Remove it from all lists and set it
3781  * to TCPS_CLOSED. The freeing up of memory is deferred until
3782  * tcp_inactive. This is needed since a thread in tcp_rput might have
3783  * done a CONN_INC_REF on this structure before it was removed from the
3784  * hashes.
3785  */
3786 static void
3787 tcp_closei_local(tcp_t *tcp)
3788 {
3789 	conn_t		*connp = tcp->tcp_connp;
3790 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3791 
3792 	if (!TCP_IS_SOCKET(tcp))
3793 		tcp_acceptor_hash_remove(tcp);
3794 
3795 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
3796 	tcp->tcp_ibsegs = 0;
3797 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
3798 	tcp->tcp_obsegs = 0;
3799 
3800 	/*
3801 	 * If we are an eager connection hanging off a listener that
3802 	 * hasn't formally accepted the connection yet, get off his
3803 	 * list and blow off any data that we have accumulated.
3804 	 */
3805 	if (tcp->tcp_listener != NULL) {
3806 		tcp_t	*listener = tcp->tcp_listener;
3807 		mutex_enter(&listener->tcp_eager_lock);
3808 		/*
3809 		 * tcp_tconnind_started == B_TRUE means that the
3810 		 * conn_ind has already gone to listener. At
3811 		 * this point, eager will be closed but we
3812 		 * leave it in listeners eager list so that
3813 		 * if listener decides to close without doing
3814 		 * accept, we can clean this up. In tcp_tli_accept
3815 		 * we take care of the case of accept on closed
3816 		 * eager.
3817 		 */
3818 		if (!tcp->tcp_tconnind_started) {
3819 			tcp_eager_unlink(tcp);
3820 			mutex_exit(&listener->tcp_eager_lock);
3821 			/*
3822 			 * We don't want to have any pointers to the
3823 			 * listener queue, after we have released our
3824 			 * reference on the listener
3825 			 */
3826 			ASSERT(tcp->tcp_detached);
3827 			connp->conn_rq = NULL;
3828 			connp->conn_wq = NULL;
3829 			CONN_DEC_REF(listener->tcp_connp);
3830 		} else {
3831 			mutex_exit(&listener->tcp_eager_lock);
3832 		}
3833 	}
3834 
3835 	/* Stop all the timers */
3836 	tcp_timers_stop(tcp);
3837 
3838 	if (tcp->tcp_state == TCPS_LISTEN) {
3839 		if (tcp->tcp_ip_addr_cache) {
3840 			kmem_free((void *)tcp->tcp_ip_addr_cache,
3841 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
3842 			tcp->tcp_ip_addr_cache = NULL;
3843 		}
3844 	}
3845 
3846 	/* Decrement listerner connection counter if necessary. */
3847 	if (tcp->tcp_listen_cnt != NULL)
3848 		TCP_DECR_LISTEN_CNT(tcp);
3849 
3850 	mutex_enter(&tcp->tcp_non_sq_lock);
3851 	if (tcp->tcp_flow_stopped)
3852 		tcp_clrqfull(tcp);
3853 	mutex_exit(&tcp->tcp_non_sq_lock);
3854 
3855 	tcp_bind_hash_remove(tcp);
3856 	/*
3857 	 * If the tcp_time_wait_collector (which runs outside the squeue)
3858 	 * is trying to remove this tcp from the time wait list, we will
3859 	 * block in tcp_time_wait_remove while trying to acquire the
3860 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
3861 	 * requires the ipcl_hash_remove to be ordered after the
3862 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
3863 	 */
3864 	if (tcp->tcp_state == TCPS_TIME_WAIT)
3865 		(void) tcp_time_wait_remove(tcp, NULL);
3866 	CL_INET_DISCONNECT(connp);
3867 	ipcl_hash_remove(connp);
3868 	ixa_cleanup(connp->conn_ixa);
3869 
3870 	/*
3871 	 * Mark the conn as CONDEMNED
3872 	 */
3873 	mutex_enter(&connp->conn_lock);
3874 	connp->conn_state_flags |= CONN_CONDEMNED;
3875 	mutex_exit(&connp->conn_lock);
3876 
3877 	ASSERT(tcp->tcp_time_wait_next == NULL);
3878 	ASSERT(tcp->tcp_time_wait_prev == NULL);
3879 	ASSERT(tcp->tcp_time_wait_expire == 0);
3880 	tcp->tcp_state = TCPS_CLOSED;
3881 
3882 	/* Release any SSL context */
3883 	if (tcp->tcp_kssl_ent != NULL) {
3884 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
3885 		tcp->tcp_kssl_ent = NULL;
3886 	}
3887 	if (tcp->tcp_kssl_ctx != NULL) {
3888 		kssl_release_ctx(tcp->tcp_kssl_ctx);
3889 		tcp->tcp_kssl_ctx = NULL;
3890 	}
3891 	tcp->tcp_kssl_pending = B_FALSE;
3892 
3893 	tcp_ipsec_cleanup(tcp);
3894 }
3895 
3896 /*
3897  * tcp is dying (called from ipcl_conn_destroy and error cases).
3898  * Free the tcp_t in either case.
3899  */
3900 void
3901 tcp_free(tcp_t *tcp)
3902 {
3903 	mblk_t		*mp;
3904 	conn_t		*connp = tcp->tcp_connp;
3905 
3906 	ASSERT(tcp != NULL);
3907 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
3908 
3909 	connp->conn_rq = NULL;
3910 	connp->conn_wq = NULL;
3911 
3912 	tcp_close_mpp(&tcp->tcp_xmit_head);
3913 	tcp_close_mpp(&tcp->tcp_reass_head);
3914 	if (tcp->tcp_rcv_list != NULL) {
3915 		/* Free b_next chain */
3916 		tcp_close_mpp(&tcp->tcp_rcv_list);
3917 	}
3918 	if ((mp = tcp->tcp_urp_mp) != NULL) {
3919 		freemsg(mp);
3920 	}
3921 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
3922 		freemsg(mp);
3923 	}
3924 
3925 	if (tcp->tcp_fused_sigurg_mp != NULL) {
3926 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
3927 		freeb(tcp->tcp_fused_sigurg_mp);
3928 		tcp->tcp_fused_sigurg_mp = NULL;
3929 	}
3930 
3931 	if (tcp->tcp_ordrel_mp != NULL) {
3932 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
3933 		freeb(tcp->tcp_ordrel_mp);
3934 		tcp->tcp_ordrel_mp = NULL;
3935 	}
3936 
3937 	if (tcp->tcp_sack_info != NULL) {
3938 		if (tcp->tcp_notsack_list != NULL) {
3939 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
3940 			    tcp);
3941 		}
3942 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
3943 	}
3944 
3945 	if (tcp->tcp_hopopts != NULL) {
3946 		mi_free(tcp->tcp_hopopts);
3947 		tcp->tcp_hopopts = NULL;
3948 		tcp->tcp_hopoptslen = 0;
3949 	}
3950 	ASSERT(tcp->tcp_hopoptslen == 0);
3951 	if (tcp->tcp_dstopts != NULL) {
3952 		mi_free(tcp->tcp_dstopts);
3953 		tcp->tcp_dstopts = NULL;
3954 		tcp->tcp_dstoptslen = 0;
3955 	}
3956 	ASSERT(tcp->tcp_dstoptslen == 0);
3957 	if (tcp->tcp_rthdrdstopts != NULL) {
3958 		mi_free(tcp->tcp_rthdrdstopts);
3959 		tcp->tcp_rthdrdstopts = NULL;
3960 		tcp->tcp_rthdrdstoptslen = 0;
3961 	}
3962 	ASSERT(tcp->tcp_rthdrdstoptslen == 0);
3963 	if (tcp->tcp_rthdr != NULL) {
3964 		mi_free(tcp->tcp_rthdr);
3965 		tcp->tcp_rthdr = NULL;
3966 		tcp->tcp_rthdrlen = 0;
3967 	}
3968 	ASSERT(tcp->tcp_rthdrlen == 0);
3969 
3970 	/*
3971 	 * Following is really a blowing away a union.
3972 	 * It happens to have exactly two members of identical size
3973 	 * the following code is enough.
3974 	 */
3975 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
3976 }
3977 
3978 
3979 /*
3980  * Put a connection confirmation message upstream built from the
3981  * address/flowid information with the conn and iph. Report our success or
3982  * failure.
3983  */
3984 static boolean_t
3985 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, mblk_t *idmp,
3986     mblk_t **defermp, ip_recv_attr_t *ira)
3987 {
3988 	sin_t	sin;
3989 	sin6_t	sin6;
3990 	mblk_t	*mp;
3991 	char	*optp = NULL;
3992 	int	optlen = 0;
3993 	conn_t	*connp = tcp->tcp_connp;
3994 
3995 	if (defermp != NULL)
3996 		*defermp = NULL;
3997 
3998 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
3999 		/*
4000 		 * Return in T_CONN_CON results of option negotiation through
4001 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4002 		 * negotiation, then what is received from remote end needs
4003 		 * to be taken into account but there is no such thing (yet?)
4004 		 * in our TCP/IP.
4005 		 * Note: We do not use mi_offset_param() here as
4006 		 * tcp_opts_conn_req contents do not directly come from
4007 		 * an application and are either generated in kernel or
4008 		 * from user input that was already verified.
4009 		 */
4010 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4011 		optp = (char *)(mp->b_rptr +
4012 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4013 		optlen = (int)
4014 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4015 	}
4016 
4017 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4018 
4019 		/* packet is IPv4 */
4020 		if (connp->conn_family == AF_INET) {
4021 			sin = sin_null;
4022 			sin.sin_addr.s_addr = connp->conn_faddr_v4;
4023 			sin.sin_port = connp->conn_fport;
4024 			sin.sin_family = AF_INET;
4025 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4026 			    (int)sizeof (sin_t), optp, optlen);
4027 		} else {
4028 			sin6 = sin6_null;
4029 			sin6.sin6_addr = connp->conn_faddr_v6;
4030 			sin6.sin6_port = connp->conn_fport;
4031 			sin6.sin6_family = AF_INET6;
4032 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4033 			    (int)sizeof (sin6_t), optp, optlen);
4034 
4035 		}
4036 	} else {
4037 		ip6_t	*ip6h = (ip6_t *)iphdr;
4038 
4039 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4040 		ASSERT(connp->conn_family == AF_INET6);
4041 		sin6 = sin6_null;
4042 		sin6.sin6_addr = connp->conn_faddr_v6;
4043 		sin6.sin6_port = connp->conn_fport;
4044 		sin6.sin6_family = AF_INET6;
4045 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4046 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4047 		    (int)sizeof (sin6_t), optp, optlen);
4048 	}
4049 
4050 	if (!mp)
4051 		return (B_FALSE);
4052 
4053 	mblk_copycred(mp, idmp);
4054 
4055 	if (defermp == NULL) {
4056 		conn_t *connp = tcp->tcp_connp;
4057 		if (IPCL_IS_NONSTR(connp)) {
4058 			(*connp->conn_upcalls->su_connected)
4059 			    (connp->conn_upper_handle, tcp->tcp_connid,
4060 			    ira->ira_cred, ira->ira_cpid);
4061 			freemsg(mp);
4062 		} else {
4063 			if (ira->ira_cred != NULL) {
4064 				/* So that getpeerucred works for TPI sockfs */
4065 				mblk_setcred(mp, ira->ira_cred, ira->ira_cpid);
4066 			}
4067 			putnext(connp->conn_rq, mp);
4068 		}
4069 	} else {
4070 		*defermp = mp;
4071 	}
4072 
4073 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4074 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4075 	return (B_TRUE);
4076 }
4077 
4078 /*
4079  * Defense for the SYN attack -
4080  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4081  *    one from the list of droppable eagers. This list is a subset of q0.
4082  *    see comments before the definition of MAKE_DROPPABLE().
4083  * 2. Don't drop a SYN request before its first timeout. This gives every
4084  *    request at least til the first timeout to complete its 3-way handshake.
4085  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4086  *    requests currently on the queue that has timed out. This will be used
4087  *    as an indicator of whether an attack is under way, so that appropriate
4088  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4089  *    either when eager goes into ESTABLISHED, or gets freed up.)
4090  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4091  *    # of timeout drops back to <= q0len/32 => SYN alert off
4092  */
4093 static boolean_t
4094 tcp_drop_q0(tcp_t *tcp)
4095 {
4096 	tcp_t	*eager;
4097 	mblk_t	*mp;
4098 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4099 
4100 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4101 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4102 
4103 	/* Pick oldest eager from the list of droppable eagers */
4104 	eager = tcp->tcp_eager_prev_drop_q0;
4105 
4106 	/* If list is empty. return B_FALSE */
4107 	if (eager == tcp) {
4108 		return (B_FALSE);
4109 	}
4110 
4111 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4112 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4113 		return (B_FALSE);
4114 
4115 	/*
4116 	 * Take this eager out from the list of droppable eagers since we are
4117 	 * going to drop it.
4118 	 */
4119 	MAKE_UNDROPPABLE(eager);
4120 
4121 	if (tcp->tcp_connp->conn_debug) {
4122 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4123 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4124 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4125 		    tcp->tcp_conn_req_cnt_q0,
4126 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4127 	}
4128 
4129 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4130 
4131 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4132 	CONN_INC_REF(eager->tcp_connp);
4133 
4134 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4135 	    tcp_clean_death_wrapper, eager->tcp_connp, NULL,
4136 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4137 
4138 	return (B_TRUE);
4139 }
4140 
4141 /*
4142  * Handle a SYN on an AF_INET6 socket; can be either IPv4 or IPv6
4143  */
4144 static mblk_t *
4145 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4146     ip_recv_attr_t *ira)
4147 {
4148 	tcp_t 		*ltcp = lconnp->conn_tcp;
4149 	tcp_t		*tcp = connp->conn_tcp;
4150 	mblk_t		*tpi_mp;
4151 	ipha_t		*ipha;
4152 	ip6_t		*ip6h;
4153 	sin6_t 		sin6;
4154 	uint_t		ifindex = ira->ira_ruifindex;
4155 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4156 
4157 	if (ira->ira_flags & IRAF_IS_IPV4) {
4158 		ipha = (ipha_t *)mp->b_rptr;
4159 
4160 		connp->conn_ipversion = IPV4_VERSION;
4161 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_laddr_v6);
4162 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_faddr_v6);
4163 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
4164 
4165 		sin6 = sin6_null;
4166 		sin6.sin6_addr = connp->conn_faddr_v6;
4167 		sin6.sin6_port = connp->conn_fport;
4168 		sin6.sin6_family = AF_INET6;
4169 		sin6.__sin6_src_id = ip_srcid_find_addr(&connp->conn_laddr_v6,
4170 		    IPCL_ZONEID(lconnp), tcps->tcps_netstack);
4171 
4172 		if (connp->conn_recv_ancillary.crb_recvdstaddr) {
4173 			sin6_t	sin6d;
4174 
4175 			sin6d = sin6_null;
4176 			sin6d.sin6_addr = connp->conn_laddr_v6;
4177 			sin6d.sin6_port = connp->conn_lport;
4178 			sin6d.sin6_family = AF_INET;
4179 			tpi_mp = mi_tpi_extconn_ind(NULL,
4180 			    (char *)&sin6d, sizeof (sin6_t),
4181 			    (char *)&tcp,
4182 			    (t_scalar_t)sizeof (intptr_t),
4183 			    (char *)&sin6d, sizeof (sin6_t),
4184 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4185 		} else {
4186 			tpi_mp = mi_tpi_conn_ind(NULL,
4187 			    (char *)&sin6, sizeof (sin6_t),
4188 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4189 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4190 		}
4191 	} else {
4192 		ip6h = (ip6_t *)mp->b_rptr;
4193 
4194 		connp->conn_ipversion = IPV6_VERSION;
4195 		connp->conn_laddr_v6 = ip6h->ip6_dst;
4196 		connp->conn_faddr_v6 = ip6h->ip6_src;
4197 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
4198 
4199 		sin6 = sin6_null;
4200 		sin6.sin6_addr = connp->conn_faddr_v6;
4201 		sin6.sin6_port = connp->conn_fport;
4202 		sin6.sin6_family = AF_INET6;
4203 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4204 		sin6.__sin6_src_id = ip_srcid_find_addr(&connp->conn_laddr_v6,
4205 		    IPCL_ZONEID(lconnp), tcps->tcps_netstack);
4206 
4207 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4208 			/* Pass up the scope_id of remote addr */
4209 			sin6.sin6_scope_id = ifindex;
4210 		} else {
4211 			sin6.sin6_scope_id = 0;
4212 		}
4213 		if (connp->conn_recv_ancillary.crb_recvdstaddr) {
4214 			sin6_t	sin6d;
4215 
4216 			sin6d = sin6_null;
4217 			sin6.sin6_addr = connp->conn_laddr_v6;
4218 			sin6d.sin6_port = connp->conn_lport;
4219 			sin6d.sin6_family = AF_INET6;
4220 			if (IN6_IS_ADDR_LINKSCOPE(&connp->conn_laddr_v6))
4221 				sin6d.sin6_scope_id = ifindex;
4222 
4223 			tpi_mp = mi_tpi_extconn_ind(NULL,
4224 			    (char *)&sin6d, sizeof (sin6_t),
4225 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4226 			    (char *)&sin6d, sizeof (sin6_t),
4227 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4228 		} else {
4229 			tpi_mp = mi_tpi_conn_ind(NULL,
4230 			    (char *)&sin6, sizeof (sin6_t),
4231 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4232 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4233 		}
4234 	}
4235 
4236 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4237 	return (tpi_mp);
4238 }
4239 
4240 /* Handle a SYN on an AF_INET socket */
4241 mblk_t *
4242 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4243     ip_recv_attr_t *ira)
4244 {
4245 	tcp_t 		*ltcp = lconnp->conn_tcp;
4246 	tcp_t		*tcp = connp->conn_tcp;
4247 	sin_t		sin;
4248 	mblk_t		*tpi_mp = NULL;
4249 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4250 	ipha_t		*ipha;
4251 
4252 	ASSERT(ira->ira_flags & IRAF_IS_IPV4);
4253 	ipha = (ipha_t *)mp->b_rptr;
4254 
4255 	connp->conn_ipversion = IPV4_VERSION;
4256 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_laddr_v6);
4257 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_faddr_v6);
4258 	connp->conn_saddr_v6 = connp->conn_laddr_v6;
4259 
4260 	sin = sin_null;
4261 	sin.sin_addr.s_addr = connp->conn_faddr_v4;
4262 	sin.sin_port = connp->conn_fport;
4263 	sin.sin_family = AF_INET;
4264 	if (lconnp->conn_recv_ancillary.crb_recvdstaddr) {
4265 		sin_t	sind;
4266 
4267 		sind = sin_null;
4268 		sind.sin_addr.s_addr = connp->conn_laddr_v4;
4269 		sind.sin_port = connp->conn_lport;
4270 		sind.sin_family = AF_INET;
4271 		tpi_mp = mi_tpi_extconn_ind(NULL,
4272 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4273 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4274 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4275 	} else {
4276 		tpi_mp = mi_tpi_conn_ind(NULL,
4277 		    (char *)&sin, sizeof (sin_t),
4278 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4279 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4280 	}
4281 
4282 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4283 	return (tpi_mp);
4284 }
4285 
4286 /*
4287  * tcp_get_conn/tcp_free_conn
4288  *
4289  * tcp_get_conn is used to get a clean tcp connection structure.
4290  * It tries to reuse the connections put on the freelist by the
4291  * time_wait_collector failing which it goes to kmem_cache. This
4292  * way has two benefits compared to just allocating from and
4293  * freeing to kmem_cache.
4294  * 1) The time_wait_collector can free (which includes the cleanup)
4295  * outside the squeue. So when the interrupt comes, we have a clean
4296  * connection sitting in the freelist. Obviously, this buys us
4297  * performance.
4298  *
4299  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_input_listener
4300  * has multiple disadvantages - tying up the squeue during alloc.
4301  * But allocating the conn/tcp in IP land is also not the best since
4302  * we can't check the 'q' and 'q0' which are protected by squeue and
4303  * blindly allocate memory which might have to be freed here if we are
4304  * not allowed to accept the connection. By using the freelist and
4305  * putting the conn/tcp back in freelist, we don't pay a penalty for
4306  * allocating memory without checking 'q/q0' and freeing it if we can't
4307  * accept the connection.
4308  *
4309  * Care should be taken to put the conn back in the same squeue's freelist
4310  * from which it was allocated. Best results are obtained if conn is
4311  * allocated from listener's squeue and freed to the same. Time wait
4312  * collector will free up the freelist is the connection ends up sitting
4313  * there for too long.
4314  */
4315 void *
4316 tcp_get_conn(void *arg, tcp_stack_t *tcps)
4317 {
4318 	tcp_t			*tcp = NULL;
4319 	conn_t			*connp = NULL;
4320 	squeue_t		*sqp = (squeue_t *)arg;
4321 	tcp_squeue_priv_t 	*tcp_time_wait;
4322 	netstack_t		*ns;
4323 	mblk_t			*tcp_rsrv_mp = NULL;
4324 
4325 	tcp_time_wait =
4326 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
4327 
4328 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
4329 	tcp = tcp_time_wait->tcp_free_list;
4330 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
4331 	if (tcp != NULL) {
4332 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
4333 		tcp_time_wait->tcp_free_list_cnt--;
4334 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4335 		tcp->tcp_time_wait_next = NULL;
4336 		connp = tcp->tcp_connp;
4337 		connp->conn_flags |= IPCL_REUSED;
4338 
4339 		ASSERT(tcp->tcp_tcps == NULL);
4340 		ASSERT(connp->conn_netstack == NULL);
4341 		ASSERT(tcp->tcp_rsrv_mp != NULL);
4342 		ns = tcps->tcps_netstack;
4343 		netstack_hold(ns);
4344 		connp->conn_netstack = ns;
4345 		connp->conn_ixa->ixa_ipst = ns->netstack_ip;
4346 		tcp->tcp_tcps = tcps;
4347 		ipcl_globalhash_insert(connp);
4348 
4349 		connp->conn_ixa->ixa_notify_cookie = tcp;
4350 		ASSERT(connp->conn_ixa->ixa_notify == tcp_notify);
4351 		connp->conn_recv = tcp_input_data;
4352 		ASSERT(connp->conn_recvicmp == tcp_icmp_input);
4353 		ASSERT(connp->conn_verifyicmp == tcp_verifyicmp);
4354 		return ((void *)connp);
4355 	}
4356 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4357 	/*
4358 	 * Pre-allocate the tcp_rsrv_mp. This mblk will not be freed until
4359 	 * this conn_t/tcp_t is freed at ipcl_conn_destroy().
4360 	 */
4361 	tcp_rsrv_mp = allocb(0, BPRI_HI);
4362 	if (tcp_rsrv_mp == NULL)
4363 		return (NULL);
4364 
4365 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
4366 	    tcps->tcps_netstack)) == NULL) {
4367 		freeb(tcp_rsrv_mp);
4368 		return (NULL);
4369 	}
4370 
4371 	tcp = connp->conn_tcp;
4372 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
4373 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
4374 
4375 	tcp->tcp_tcps = tcps;
4376 
4377 	connp->conn_recv = tcp_input_data;
4378 	connp->conn_recvicmp = tcp_icmp_input;
4379 	connp->conn_verifyicmp = tcp_verifyicmp;
4380 
4381 	/*
4382 	 * Register tcp_notify to listen to capability changes detected by IP.
4383 	 * This upcall is made in the context of the call to conn_ip_output
4384 	 * thus it is inside the squeue.
4385 	 */
4386 	connp->conn_ixa->ixa_notify = tcp_notify;
4387 	connp->conn_ixa->ixa_notify_cookie = tcp;
4388 
4389 	return ((void *)connp);
4390 }
4391 
4392 /* BEGIN CSTYLED */
4393 /*
4394  *
4395  * The sockfs ACCEPT path:
4396  * =======================
4397  *
4398  * The eager is now established in its own perimeter as soon as SYN is
4399  * received in tcp_input_listener(). When sockfs receives conn_ind, it
4400  * completes the accept processing on the acceptor STREAM. The sending
4401  * of conn_ind part is common for both sockfs listener and a TLI/XTI
4402  * listener but a TLI/XTI listener completes the accept processing
4403  * on the listener perimeter.
4404  *
4405  * Common control flow for 3 way handshake:
4406  * ----------------------------------------
4407  *
4408  * incoming SYN (listener perimeter)	-> tcp_input_listener()
4409  *
4410  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_input_data()
4411  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
4412  *
4413  * Sockfs ACCEPT Path:
4414  * -------------------
4415  *
4416  * open acceptor stream (tcp_open allocates tcp_tli_accept()
4417  * as STREAM entry point)
4418  *
4419  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_tli_accept()
4420  *
4421  * tcp_tli_accept() extracts the eager and makes the q->q_ptr <-> eager
4422  * association (we are not behind eager's squeue but sockfs is protecting us
4423  * and no one knows about this stream yet. The STREAMS entry point q->q_info
4424  * is changed to point at tcp_wput().
4425  *
4426  * tcp_accept_common() sends any deferred eagers via tcp_send_pending() to
4427  * listener (done on listener's perimeter).
4428  *
4429  * tcp_tli_accept() calls tcp_accept_finish() on eagers perimeter to finish
4430  * accept.
4431  *
4432  * TLI/XTI client ACCEPT path:
4433  * ---------------------------
4434  *
4435  * soaccept() sends T_CONN_RES on the listener STREAM.
4436  *
4437  * tcp_tli_accept() -> tcp_accept_swap() complete the processing and send
4438  * a M_SETOPS mblk to eager perimeter to finish accept (tcp_accept_finish()).
4439  *
4440  * Locks:
4441  * ======
4442  *
4443  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
4444  * and listeners->tcp_eager_next_q.
4445  *
4446  * Referencing:
4447  * ============
4448  *
4449  * 1) We start out in tcp_input_listener by eager placing a ref on
4450  * listener and listener adding eager to listeners->tcp_eager_next_q0.
4451  *
4452  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
4453  * doing so we place a ref on the eager. This ref is finally dropped at the
4454  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
4455  * reference is dropped by the squeue framework.
4456  *
4457  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
4458  *
4459  * The reference must be released by the same entity that added the reference
4460  * In the above scheme, the eager is the entity that adds and releases the
4461  * references. Note that tcp_accept_finish executes in the squeue of the eager
4462  * (albeit after it is attached to the acceptor stream). Though 1. executes
4463  * in the listener's squeue, the eager is nascent at this point and the
4464  * reference can be considered to have been added on behalf of the eager.
4465  *
4466  * Eager getting a Reset or listener closing:
4467  * ==========================================
4468  *
4469  * Once the listener and eager are linked, the listener never does the unlink.
4470  * If the listener needs to close, tcp_eager_cleanup() is called which queues
4471  * a message on all eager perimeter. The eager then does the unlink, clears
4472  * any pointers to the listener's queue and drops the reference to the
4473  * listener. The listener waits in tcp_close outside the squeue until its
4474  * refcount has dropped to 1. This ensures that the listener has waited for
4475  * all eagers to clear their association with the listener.
4476  *
4477  * Similarly, if eager decides to go away, it can unlink itself and close.
4478  * When the T_CONN_RES comes down, we check if eager has closed. Note that
4479  * the reference to eager is still valid because of the extra ref we put
4480  * in tcp_send_conn_ind.
4481  *
4482  * Listener can always locate the eager under the protection
4483  * of the listener->tcp_eager_lock, and then do a refhold
4484  * on the eager during the accept processing.
4485  *
4486  * The acceptor stream accesses the eager in the accept processing
4487  * based on the ref placed on eager before sending T_conn_ind.
4488  * The only entity that can negate this refhold is a listener close
4489  * which is mutually exclusive with an active acceptor stream.
4490  *
4491  * Eager's reference on the listener
4492  * ===================================
4493  *
4494  * If the accept happens (even on a closed eager) the eager drops its
4495  * reference on the listener at the start of tcp_accept_finish. If the
4496  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
4497  * the reference is dropped in tcp_closei_local. If the listener closes,
4498  * the reference is dropped in tcp_eager_kill. In all cases the reference
4499  * is dropped while executing in the eager's context (squeue).
4500  */
4501 /* END CSTYLED */
4502 
4503 /* Process the SYN packet, mp, directed at the listener 'tcp' */
4504 
4505 /*
4506  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
4507  * tcp_input_data will not see any packets for listeners since the listener
4508  * has conn_recv set to tcp_input_listener.
4509  */
4510 /* ARGSUSED */
4511 void
4512 tcp_input_listener(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4513 {
4514 	tcpha_t		*tcpha;
4515 	uint32_t	seg_seq;
4516 	tcp_t		*eager;
4517 	int		err;
4518 	conn_t		*econnp = NULL;
4519 	squeue_t	*new_sqp;
4520 	mblk_t		*mp1;
4521 	uint_t 		ip_hdr_len;
4522 	conn_t		*lconnp = (conn_t *)arg;
4523 	tcp_t		*listener = lconnp->conn_tcp;
4524 	tcp_stack_t	*tcps = listener->tcp_tcps;
4525 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
4526 	uint_t		flags;
4527 	mblk_t		*tpi_mp;
4528 	uint_t		ifindex = ira->ira_ruifindex;
4529 	boolean_t	tlc_set = B_FALSE;
4530 
4531 	ip_hdr_len = ira->ira_ip_hdr_length;
4532 	tcpha = (tcpha_t *)&mp->b_rptr[ip_hdr_len];
4533 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
4534 
4535 	if (!(flags & TH_SYN)) {
4536 		if ((flags & TH_RST) || (flags & TH_URG)) {
4537 			freemsg(mp);
4538 			return;
4539 		}
4540 		if (flags & TH_ACK) {
4541 			/* Note this executes in listener's squeue */
4542 			tcp_xmit_listeners_reset(mp, ira, ipst, lconnp);
4543 			return;
4544 		}
4545 
4546 		freemsg(mp);
4547 		return;
4548 	}
4549 
4550 	if (listener->tcp_state != TCPS_LISTEN)
4551 		goto error2;
4552 
4553 	ASSERT(IPCL_IS_BOUND(lconnp));
4554 
4555 	mutex_enter(&listener->tcp_eager_lock);
4556 
4557 	/*
4558 	 * The system is under memory pressure, so we need to do our part
4559 	 * to relieve the pressure.  So we only accept new request if there
4560 	 * is nothing waiting to be accepted or waiting to complete the 3-way
4561 	 * handshake.  This means that busy listener will not get too many
4562 	 * new requests which they cannot handle in time while non-busy
4563 	 * listener is still functioning properly.
4564 	 */
4565 	if (tcps->tcps_reclaim && (listener->tcp_conn_req_cnt_q > 0 ||
4566 	    listener->tcp_conn_req_cnt_q0 > 0)) {
4567 		mutex_exit(&listener->tcp_eager_lock);
4568 		TCP_STAT(tcps, tcp_listen_mem_drop);
4569 		goto error2;
4570 	}
4571 
4572 	if (listener->tcp_conn_req_cnt_q >= listener->tcp_conn_req_max) {
4573 		mutex_exit(&listener->tcp_eager_lock);
4574 		TCP_STAT(tcps, tcp_listendrop);
4575 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
4576 		if (lconnp->conn_debug) {
4577 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
4578 			    "tcp_input_listener: listen backlog (max=%d) "
4579 			    "overflow (%d pending) on %s",
4580 			    listener->tcp_conn_req_max,
4581 			    listener->tcp_conn_req_cnt_q,
4582 			    tcp_display(listener, NULL, DISP_PORT_ONLY));
4583 		}
4584 		goto error2;
4585 	}
4586 
4587 	if (listener->tcp_conn_req_cnt_q0 >=
4588 	    listener->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
4589 		/*
4590 		 * Q0 is full. Drop a pending half-open req from the queue
4591 		 * to make room for the new SYN req. Also mark the time we
4592 		 * drop a SYN.
4593 		 *
4594 		 * A more aggressive defense against SYN attack will
4595 		 * be to set the "tcp_syn_defense" flag now.
4596 		 */
4597 		TCP_STAT(tcps, tcp_listendropq0);
4598 		listener->tcp_last_rcv_lbolt = ddi_get_lbolt64();
4599 		if (!tcp_drop_q0(listener)) {
4600 			mutex_exit(&listener->tcp_eager_lock);
4601 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
4602 			if (lconnp->conn_debug) {
4603 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4604 				    "tcp_input_listener: listen half-open "
4605 				    "queue (max=%d) full (%d pending) on %s",
4606 				    tcps->tcps_conn_req_max_q0,
4607 				    listener->tcp_conn_req_cnt_q0,
4608 				    tcp_display(listener, NULL,
4609 				    DISP_PORT_ONLY));
4610 			}
4611 			goto error2;
4612 		}
4613 	}
4614 
4615 	/*
4616 	 * Enforce the limit set on the number of connections per listener.
4617 	 * Note that tlc_cnt starts with 1.  So need to add 1 to tlc_max
4618 	 * for comparison.
4619 	 */
4620 	if (listener->tcp_listen_cnt != NULL) {
4621 		tcp_listen_cnt_t *tlc = listener->tcp_listen_cnt;
4622 		int64_t now;
4623 
4624 		if (atomic_add_32_nv(&tlc->tlc_cnt, 1) > tlc->tlc_max + 1) {
4625 			mutex_exit(&listener->tcp_eager_lock);
4626 			now = ddi_get_lbolt64();
4627 			atomic_add_32(&tlc->tlc_cnt, -1);
4628 			TCP_STAT(tcps, tcp_listen_cnt_drop);
4629 			tlc->tlc_drop++;
4630 			if (now - tlc->tlc_report_time >
4631 			    MSEC_TO_TICK(TCP_TLC_REPORT_INTERVAL)) {
4632 				zcmn_err(lconnp->conn_zoneid, CE_WARN,
4633 				    "Listener (port %d) connection max (%u) "
4634 				    "reached: %u attempts dropped total\n",
4635 				    ntohs(listener->tcp_connp->conn_lport),
4636 				    tlc->tlc_max, tlc->tlc_drop);
4637 				tlc->tlc_report_time = now;
4638 			}
4639 			goto error2;
4640 		}
4641 		tlc_set = B_TRUE;
4642 	}
4643 
4644 	mutex_exit(&listener->tcp_eager_lock);
4645 
4646 	/*
4647 	 * IP sets ira_sqp to either the senders conn_sqp (for loopback)
4648 	 * or based on the ring (for packets from GLD). Otherwise it is
4649 	 * set based on lbolt i.e., a somewhat random number.
4650 	 */
4651 	ASSERT(ira->ira_sqp != NULL);
4652 	new_sqp = ira->ira_sqp;
4653 
4654 	econnp = (conn_t *)tcp_get_conn(arg2, tcps);
4655 	if (econnp == NULL)
4656 		goto error2;
4657 
4658 	ASSERT(econnp->conn_netstack == lconnp->conn_netstack);
4659 	econnp->conn_sqp = new_sqp;
4660 	econnp->conn_initial_sqp = new_sqp;
4661 	econnp->conn_ixa->ixa_sqp = new_sqp;
4662 
4663 	econnp->conn_fport = tcpha->tha_lport;
4664 	econnp->conn_lport = tcpha->tha_fport;
4665 
4666 	err = conn_inherit_parent(lconnp, econnp);
4667 	if (err != 0)
4668 		goto error3;
4669 
4670 	/* We already know the laddr of the new connection is ours */
4671 	econnp->conn_ixa->ixa_src_generation = ipst->ips_src_generation;
4672 
4673 	ASSERT(OK_32PTR(mp->b_rptr));
4674 	ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION ||
4675 	    IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
4676 
4677 	if (lconnp->conn_family == AF_INET) {
4678 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
4679 		tpi_mp = tcp_conn_create_v4(lconnp, econnp, mp, ira);
4680 	} else {
4681 		tpi_mp = tcp_conn_create_v6(lconnp, econnp, mp, ira);
4682 	}
4683 
4684 	if (tpi_mp == NULL)
4685 		goto error3;
4686 
4687 	eager = econnp->conn_tcp;
4688 	eager->tcp_detached = B_TRUE;
4689 	SOCK_CONNID_INIT(eager->tcp_connid);
4690 
4691 	tcp_init_values(eager);
4692 
4693 	ASSERT((econnp->conn_ixa->ixa_flags &
4694 	    (IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
4695 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO)) ==
4696 	    (IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
4697 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO));
4698 
4699 	if (!tcps->tcps_dev_flow_ctl)
4700 		econnp->conn_ixa->ixa_flags |= IXAF_NO_DEV_FLOW_CTL;
4701 
4702 	/* Prepare for diffing against previous packets */
4703 	eager->tcp_recvifindex = 0;
4704 	eager->tcp_recvhops = 0xffffffffU;
4705 
4706 	if (!(ira->ira_flags & IRAF_IS_IPV4) && econnp->conn_bound_if == 0) {
4707 		if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_faddr_v6) ||
4708 		    IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6)) {
4709 			econnp->conn_incoming_ifindex = ifindex;
4710 			econnp->conn_ixa->ixa_flags |= IXAF_SCOPEID_SET;
4711 			econnp->conn_ixa->ixa_scopeid = ifindex;
4712 		}
4713 	}
4714 
4715 	if ((ira->ira_flags & (IRAF_IS_IPV4|IRAF_IPV4_OPTIONS)) ==
4716 	    (IRAF_IS_IPV4|IRAF_IPV4_OPTIONS) &&
4717 	    tcps->tcps_rev_src_routes) {
4718 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
4719 		ip_pkt_t *ipp = &econnp->conn_xmit_ipp;
4720 
4721 		/* Source routing option copyover (reverse it) */
4722 		err = ip_find_hdr_v4(ipha, ipp, B_TRUE);
4723 		if (err != 0) {
4724 			freemsg(tpi_mp);
4725 			goto error3;
4726 		}
4727 		ip_pkt_source_route_reverse_v4(ipp);
4728 	}
4729 
4730 	ASSERT(eager->tcp_conn.tcp_eager_conn_ind == NULL);
4731 	ASSERT(!eager->tcp_tconnind_started);
4732 	/*
4733 	 * If the SYN came with a credential, it's a loopback packet or a
4734 	 * labeled packet; attach the credential to the TPI message.
4735 	 */
4736 	if (ira->ira_cred != NULL)
4737 		mblk_setcred(tpi_mp, ira->ira_cred, ira->ira_cpid);
4738 
4739 	eager->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4740 
4741 	/* Inherit the listener's SSL protection state */
4742 	if ((eager->tcp_kssl_ent = listener->tcp_kssl_ent) != NULL) {
4743 		kssl_hold_ent(eager->tcp_kssl_ent);
4744 		eager->tcp_kssl_pending = B_TRUE;
4745 	}
4746 
4747 	/* Inherit the listener's non-STREAMS flag */
4748 	if (IPCL_IS_NONSTR(lconnp)) {
4749 		econnp->conn_flags |= IPCL_NONSTR;
4750 	}
4751 
4752 	ASSERT(eager->tcp_ordrel_mp == NULL);
4753 
4754 	if (!IPCL_IS_NONSTR(econnp)) {
4755 		/*
4756 		 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that
4757 		 * at close time, we will always have that to send up.
4758 		 * Otherwise, we need to do special handling in case the
4759 		 * allocation fails at that time.
4760 		 */
4761 		if ((eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
4762 			goto error3;
4763 	}
4764 	/*
4765 	 * Now that the IP addresses and ports are setup in econnp we
4766 	 * can do the IPsec policy work.
4767 	 */
4768 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
4769 		if (lconnp->conn_policy != NULL) {
4770 			/*
4771 			 * Inherit the policy from the listener; use
4772 			 * actions from ira
4773 			 */
4774 			if (!ip_ipsec_policy_inherit(econnp, lconnp, ira)) {
4775 				CONN_DEC_REF(econnp);
4776 				freemsg(mp);
4777 				goto error3;
4778 			}
4779 		}
4780 	}
4781 
4782 	/* Inherit various TCP parameters from the listener */
4783 	eager->tcp_naglim = listener->tcp_naglim;
4784 	eager->tcp_first_timer_threshold = listener->tcp_first_timer_threshold;
4785 	eager->tcp_second_timer_threshold =
4786 	    listener->tcp_second_timer_threshold;
4787 	eager->tcp_first_ctimer_threshold =
4788 	    listener->tcp_first_ctimer_threshold;
4789 	eager->tcp_second_ctimer_threshold =
4790 	    listener->tcp_second_ctimer_threshold;
4791 
4792 	/*
4793 	 * tcp_set_destination() may set tcp_rwnd according to the route
4794 	 * metrics. If it does not, the eager's receive window will be set
4795 	 * to the listener's receive window later in this function.
4796 	 */
4797 	eager->tcp_rwnd = 0;
4798 
4799 	/*
4800 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
4801 	 * calling tcp_process_options() which set the initial cwnd.
4802 	 */
4803 	eager->tcp_init_cwnd = listener->tcp_init_cwnd;
4804 
4805 	if (is_system_labeled()) {
4806 		ip_xmit_attr_t *ixa = econnp->conn_ixa;
4807 
4808 		ASSERT(ira->ira_tsl != NULL);
4809 		/* Discard any old label */
4810 		if (ixa->ixa_free_flags & IXA_FREE_TSL) {
4811 			ASSERT(ixa->ixa_tsl != NULL);
4812 			label_rele(ixa->ixa_tsl);
4813 			ixa->ixa_free_flags &= ~IXA_FREE_TSL;
4814 			ixa->ixa_tsl = NULL;
4815 		}
4816 		if ((lconnp->conn_mlp_type != mlptSingle ||
4817 		    lconnp->conn_mac_mode != CONN_MAC_DEFAULT) &&
4818 		    ira->ira_tsl != NULL) {
4819 			/*
4820 			 * If this is an MLP connection or a MAC-Exempt
4821 			 * connection with an unlabeled node, packets are to be
4822 			 * exchanged using the security label of the received
4823 			 * SYN packet instead of the server application's label.
4824 			 * tsol_check_dest called from ip_set_destination
4825 			 * might later update TSF_UNLABELED by replacing
4826 			 * ixa_tsl with a new label.
4827 			 */
4828 			label_hold(ira->ira_tsl);
4829 			ip_xmit_attr_replace_tsl(ixa, ira->ira_tsl);
4830 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
4831 			    econnp, ts_label_t *, ixa->ixa_tsl)
4832 		} else {
4833 			ixa->ixa_tsl = crgetlabel(econnp->conn_cred);
4834 			DTRACE_PROBE2(syn_accept, conn_t *,
4835 			    econnp, ts_label_t *, ixa->ixa_tsl)
4836 		}
4837 		/*
4838 		 * conn_connect() called from tcp_set_destination will verify
4839 		 * the destination is allowed to receive packets at the
4840 		 * security label of the SYN-ACK we are generating. As part of
4841 		 * that, tsol_check_dest() may create a new effective label for
4842 		 * this connection.
4843 		 * Finally conn_connect() will call conn_update_label.
4844 		 * All that remains for TCP to do is to call
4845 		 * conn_build_hdr_template which is done as part of
4846 		 * tcp_set_destination.
4847 		 */
4848 	}
4849 
4850 	/*
4851 	 * Since we will clear tcp_listener before we clear tcp_detached
4852 	 * in the accept code we need tcp_hard_binding aka tcp_accept_inprogress
4853 	 * so we can tell a TCP_DETACHED_NONEAGER apart.
4854 	 */
4855 	eager->tcp_hard_binding = B_TRUE;
4856 
4857 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
4858 	    TCP_BIND_HASH(econnp->conn_lport)], eager, 0);
4859 
4860 	CL_INET_CONNECT(econnp, B_FALSE, err);
4861 	if (err != 0) {
4862 		tcp_bind_hash_remove(eager);
4863 		goto error3;
4864 	}
4865 
4866 	/*
4867 	 * No need to check for multicast destination since ip will only pass
4868 	 * up multicasts to those that have expressed interest
4869 	 * TODO: what about rejecting broadcasts?
4870 	 * Also check that source is not a multicast or broadcast address.
4871 	 */
4872 	eager->tcp_state = TCPS_SYN_RCVD;
4873 	SOCK_CONNID_BUMP(eager->tcp_connid);
4874 
4875 	/*
4876 	 * Adapt our mss, ttl, ... based on the remote address.
4877 	 */
4878 
4879 	if (tcp_set_destination(eager) != 0) {
4880 		BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4881 		/* Undo the bind_hash_insert */
4882 		tcp_bind_hash_remove(eager);
4883 		goto error3;
4884 	}
4885 
4886 	/* Process all TCP options. */
4887 	tcp_process_options(eager, tcpha);
4888 
4889 	/* Is the other end ECN capable? */
4890 	if (tcps->tcps_ecn_permitted >= 1 &&
4891 	    (tcpha->tha_flags & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
4892 		eager->tcp_ecn_ok = B_TRUE;
4893 	}
4894 
4895 	/*
4896 	 * The listener's conn_rcvbuf should be the default window size or a
4897 	 * window size changed via SO_RCVBUF option. First round up the
4898 	 * eager's tcp_rwnd to the nearest MSS. Then find out the window
4899 	 * scale option value if needed. Call tcp_rwnd_set() to finish the
4900 	 * setting.
4901 	 *
4902 	 * Note if there is a rpipe metric associated with the remote host,
4903 	 * we should not inherit receive window size from listener.
4904 	 */
4905 	eager->tcp_rwnd = MSS_ROUNDUP(
4906 	    (eager->tcp_rwnd == 0 ? econnp->conn_rcvbuf :
4907 	    eager->tcp_rwnd), eager->tcp_mss);
4908 	if (eager->tcp_snd_ws_ok)
4909 		tcp_set_ws_value(eager);
4910 	/*
4911 	 * Note that this is the only place tcp_rwnd_set() is called for
4912 	 * accepting a connection.  We need to call it here instead of
4913 	 * after the 3-way handshake because we need to tell the other
4914 	 * side our rwnd in the SYN-ACK segment.
4915 	 */
4916 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
4917 
4918 	ASSERT(eager->tcp_connp->conn_rcvbuf != 0 &&
4919 	    eager->tcp_connp->conn_rcvbuf == eager->tcp_rwnd);
4920 
4921 	ASSERT(econnp->conn_rcvbuf != 0 &&
4922 	    econnp->conn_rcvbuf == eager->tcp_rwnd);
4923 
4924 	/* Put a ref on the listener for the eager. */
4925 	CONN_INC_REF(lconnp);
4926 	mutex_enter(&listener->tcp_eager_lock);
4927 	listener->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
4928 	eager->tcp_eager_next_q0 = listener->tcp_eager_next_q0;
4929 	listener->tcp_eager_next_q0 = eager;
4930 	eager->tcp_eager_prev_q0 = listener;
4931 
4932 	/* Set tcp_listener before adding it to tcp_conn_fanout */
4933 	eager->tcp_listener = listener;
4934 	eager->tcp_saved_listener = listener;
4935 
4936 	/*
4937 	 * Set tcp_listen_cnt so that when the connection is done, the counter
4938 	 * is decremented.
4939 	 */
4940 	eager->tcp_listen_cnt = listener->tcp_listen_cnt;
4941 
4942 	/*
4943 	 * Tag this detached tcp vector for later retrieval
4944 	 * by our listener client in tcp_accept().
4945 	 */
4946 	eager->tcp_conn_req_seqnum = listener->tcp_conn_req_seqnum;
4947 	listener->tcp_conn_req_cnt_q0++;
4948 	if (++listener->tcp_conn_req_seqnum == -1) {
4949 		/*
4950 		 * -1 is "special" and defined in TPI as something
4951 		 * that should never be used in T_CONN_IND
4952 		 */
4953 		++listener->tcp_conn_req_seqnum;
4954 	}
4955 	mutex_exit(&listener->tcp_eager_lock);
4956 
4957 	if (listener->tcp_syn_defense) {
4958 		/* Don't drop the SYN that comes from a good IP source */
4959 		ipaddr_t *addr_cache;
4960 
4961 		addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
4962 		if (addr_cache != NULL && econnp->conn_faddr_v4 ==
4963 		    addr_cache[IP_ADDR_CACHE_HASH(econnp->conn_faddr_v4)]) {
4964 			eager->tcp_dontdrop = B_TRUE;
4965 		}
4966 	}
4967 
4968 	/*
4969 	 * We need to insert the eager in its own perimeter but as soon
4970 	 * as we do that, we expose the eager to the classifier and
4971 	 * should not touch any field outside the eager's perimeter.
4972 	 * So do all the work necessary before inserting the eager
4973 	 * in its own perimeter. Be optimistic that conn_connect()
4974 	 * will succeed but undo everything if it fails.
4975 	 */
4976 	seg_seq = ntohl(tcpha->tha_seq);
4977 	eager->tcp_irs = seg_seq;
4978 	eager->tcp_rack = seg_seq;
4979 	eager->tcp_rnxt = seg_seq + 1;
4980 	eager->tcp_tcpha->tha_ack = htonl(eager->tcp_rnxt);
4981 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
4982 	eager->tcp_state = TCPS_SYN_RCVD;
4983 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
4984 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
4985 	if (mp1 == NULL) {
4986 		/*
4987 		 * Increment the ref count as we are going to
4988 		 * enqueueing an mp in squeue
4989 		 */
4990 		CONN_INC_REF(econnp);
4991 		goto error;
4992 	}
4993 
4994 	/*
4995 	 * We need to start the rto timer. In normal case, we start
4996 	 * the timer after sending the packet on the wire (or at
4997 	 * least believing that packet was sent by waiting for
4998 	 * conn_ip_output() to return). Since this is the first packet
4999 	 * being sent on the wire for the eager, our initial tcp_rto
5000 	 * is at least tcp_rexmit_interval_min which is a fairly
5001 	 * large value to allow the algorithm to adjust slowly to large
5002 	 * fluctuations of RTT during first few transmissions.
5003 	 *
5004 	 * Starting the timer first and then sending the packet in this
5005 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5006 	 * is of the order of several 100ms and starting the timer
5007 	 * first and then sending the packet will result in difference
5008 	 * of few micro seconds.
5009 	 *
5010 	 * Without this optimization, we are forced to hold the fanout
5011 	 * lock across the ipcl_bind_insert() and sending the packet
5012 	 * so that we don't race against an incoming packet (maybe RST)
5013 	 * for this eager.
5014 	 *
5015 	 * It is necessary to acquire an extra reference on the eager
5016 	 * at this point and hold it until after tcp_send_data() to
5017 	 * ensure against an eager close race.
5018 	 */
5019 
5020 	CONN_INC_REF(econnp);
5021 
5022 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5023 
5024 	/*
5025 	 * Insert the eager in its own perimeter now. We are ready to deal
5026 	 * with any packets on eager.
5027 	 */
5028 	if (ipcl_conn_insert(econnp) != 0)
5029 		goto error;
5030 
5031 	ASSERT(econnp->conn_ixa->ixa_notify_cookie == econnp->conn_tcp);
5032 	freemsg(mp);
5033 	/*
5034 	 * Send the SYN-ACK. Use the right squeue so that conn_ixa is
5035 	 * only used by one thread at a time.
5036 	 */
5037 	if (econnp->conn_sqp == lconnp->conn_sqp) {
5038 		(void) conn_ip_output(mp1, econnp->conn_ixa);
5039 		CONN_DEC_REF(econnp);
5040 	} else {
5041 		SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_send_synack,
5042 		    econnp, NULL, SQ_PROCESS, SQTAG_TCP_SEND_SYNACK);
5043 	}
5044 	return;
5045 error:
5046 	freemsg(mp1);
5047 	eager->tcp_closemp_used = B_TRUE;
5048 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5049 	mp1 = &eager->tcp_closemp;
5050 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5051 	    econnp, NULL, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5052 
5053 	/*
5054 	 * If a connection already exists, send the mp to that connections so
5055 	 * that it can be appropriately dealt with.
5056 	 */
5057 	ipst = tcps->tcps_netstack->netstack_ip;
5058 
5059 	if ((econnp = ipcl_classify(mp, ira, ipst)) != NULL) {
5060 		if (!IPCL_IS_CONNECTED(econnp)) {
5061 			/*
5062 			 * Something bad happened. ipcl_conn_insert()
5063 			 * failed because a connection already existed
5064 			 * in connected hash but we can't find it
5065 			 * anymore (someone blew it away). Just
5066 			 * free this message and hopefully remote
5067 			 * will retransmit at which time the SYN can be
5068 			 * treated as a new connection or dealth with
5069 			 * a TH_RST if a connection already exists.
5070 			 */
5071 			CONN_DEC_REF(econnp);
5072 			freemsg(mp);
5073 		} else {
5074 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp, tcp_input_data,
5075 			    econnp, ira, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5076 		}
5077 	} else {
5078 		/* Nobody wants this packet */
5079 		freemsg(mp);
5080 	}
5081 	return;
5082 error3:
5083 	CONN_DEC_REF(econnp);
5084 error2:
5085 	freemsg(mp);
5086 	if (tlc_set)
5087 		atomic_add_32(&listener->tcp_listen_cnt->tlc_cnt, -1);
5088 }
5089 
5090 /* ARGSUSED2 */
5091 void
5092 tcp_send_synack(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
5093 {
5094 	conn_t	*econnp = (conn_t *)arg;
5095 	tcp_t	*tcp = econnp->conn_tcp;
5096 
5097 	/* Guard against a RST having blown it away while on the squeue */
5098 	if (tcp->tcp_state == TCPS_CLOSED) {
5099 		freemsg(mp);
5100 		return;
5101 	}
5102 
5103 	(void) conn_ip_output(mp, econnp->conn_ixa);
5104 }
5105 
5106 /*
5107  * In an ideal case of vertical partition in NUMA architecture, its
5108  * beneficial to have the listener and all the incoming connections
5109  * tied to the same squeue. The other constraint is that incoming
5110  * connections should be tied to the squeue attached to interrupted
5111  * CPU for obvious locality reason so this leaves the listener to
5112  * be tied to the same squeue. Our only problem is that when listener
5113  * is binding, the CPU that will get interrupted by the NIC whose
5114  * IP address the listener is binding to is not even known. So
5115  * the code below allows us to change that binding at the time the
5116  * CPU is interrupted by virtue of incoming connection's squeue.
5117  *
5118  * This is usefull only in case of a listener bound to a specific IP
5119  * address. For other kind of listeners, they get bound the
5120  * very first time and there is no attempt to rebind them.
5121  */
5122 void
5123 tcp_input_listener_unbound(void *arg, mblk_t *mp, void *arg2,
5124     ip_recv_attr_t *ira)
5125 {
5126 	conn_t		*connp = (conn_t *)arg;
5127 	squeue_t	*sqp = (squeue_t *)arg2;
5128 	squeue_t	*new_sqp;
5129 	uint32_t	conn_flags;
5130 
5131 	/*
5132 	 * IP sets ira_sqp to either the senders conn_sqp (for loopback)
5133 	 * or based on the ring (for packets from GLD). Otherwise it is
5134 	 * set based on lbolt i.e., a somewhat random number.
5135 	 */
5136 	ASSERT(ira->ira_sqp != NULL);
5137 	new_sqp = ira->ira_sqp;
5138 
5139 	if (connp->conn_fanout == NULL)
5140 		goto done;
5141 
5142 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5143 		mutex_enter(&connp->conn_fanout->connf_lock);
5144 		mutex_enter(&connp->conn_lock);
5145 		/*
5146 		 * No one from read or write side can access us now
5147 		 * except for already queued packets on this squeue.
5148 		 * But since we haven't changed the squeue yet, they
5149 		 * can't execute. If they are processed after we have
5150 		 * changed the squeue, they are sent back to the
5151 		 * correct squeue down below.
5152 		 * But a listner close can race with processing of
5153 		 * incoming SYN. If incoming SYN processing changes
5154 		 * the squeue then the listener close which is waiting
5155 		 * to enter the squeue would operate on the wrong
5156 		 * squeue. Hence we don't change the squeue here unless
5157 		 * the refcount is exactly the minimum refcount. The
5158 		 * minimum refcount of 4 is counted as - 1 each for
5159 		 * TCP and IP, 1 for being in the classifier hash, and
5160 		 * 1 for the mblk being processed.
5161 		 */
5162 
5163 		if (connp->conn_ref != 4 ||
5164 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5165 			mutex_exit(&connp->conn_lock);
5166 			mutex_exit(&connp->conn_fanout->connf_lock);
5167 			goto done;
5168 		}
5169 		if (connp->conn_sqp != new_sqp) {
5170 			while (connp->conn_sqp != new_sqp)
5171 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5172 			/* No special MT issues for outbound ixa_sqp hint */
5173 			connp->conn_ixa->ixa_sqp = new_sqp;
5174 		}
5175 
5176 		do {
5177 			conn_flags = connp->conn_flags;
5178 			conn_flags |= IPCL_FULLY_BOUND;
5179 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5180 			    conn_flags);
5181 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5182 
5183 		mutex_exit(&connp->conn_fanout->connf_lock);
5184 		mutex_exit(&connp->conn_lock);
5185 
5186 		/*
5187 		 * Assume we have picked a good squeue for the listener. Make
5188 		 * subsequent SYNs not try to change the squeue.
5189 		 */
5190 		connp->conn_recv = tcp_input_listener;
5191 	}
5192 
5193 done:
5194 	if (connp->conn_sqp != sqp) {
5195 		CONN_INC_REF(connp);
5196 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5197 		    ira, SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5198 	} else {
5199 		tcp_input_listener(connp, mp, sqp, ira);
5200 	}
5201 }
5202 
5203 /*
5204  * Successful connect request processing begins when our client passes
5205  * a T_CONN_REQ message into tcp_wput(), which performs function calls into
5206  * IP and the passes a T_OK_ACK (or T_ERROR_ACK upstream).
5207  *
5208  * After various error checks are completed, tcp_tpi_connect() lays
5209  * the target address and port into the composite header template.
5210  * Then we ask IP for information, including a source address if we didn't
5211  * already have one. Finally we prepare to send the SYN packet, and then
5212  * send up the T_OK_ACK reply message.
5213  */
5214 static void
5215 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5216 {
5217 	sin_t		*sin;
5218 	struct T_conn_req	*tcr;
5219 	struct sockaddr	*sa;
5220 	socklen_t	len;
5221 	int		error;
5222 	cred_t		*cr;
5223 	pid_t		cpid;
5224 	conn_t		*connp = tcp->tcp_connp;
5225 	queue_t		*q = connp->conn_wq;
5226 
5227 	/*
5228 	 * All Solaris components should pass a db_credp
5229 	 * for this TPI message, hence we ASSERT.
5230 	 * But in case there is some other M_PROTO that looks
5231 	 * like a TPI message sent by some other kernel
5232 	 * component, we check and return an error.
5233 	 */
5234 	cr = msg_getcred(mp, &cpid);
5235 	ASSERT(cr != NULL);
5236 	if (cr == NULL) {
5237 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5238 		return;
5239 	}
5240 
5241 	tcr = (struct T_conn_req *)mp->b_rptr;
5242 
5243 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5244 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5245 		tcp_err_ack(tcp, mp, TPROTO, 0);
5246 		return;
5247 	}
5248 
5249 	/*
5250 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5251 	 * will always have that to send up.  Otherwise, we need to do
5252 	 * special handling in case the allocation fails at that time.
5253 	 * If the end point is TPI, the tcp_t can be reused and the
5254 	 * tcp_ordrel_mp may be allocated already.
5255 	 */
5256 	if (tcp->tcp_ordrel_mp == NULL) {
5257 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5258 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5259 			return;
5260 		}
5261 	}
5262 
5263 	/*
5264 	 * Determine packet type based on type of address passed in
5265 	 * the request should contain an IPv4 or IPv6 address.
5266 	 * Make sure that address family matches the type of
5267 	 * family of the address passed down.
5268 	 */
5269 	switch (tcr->DEST_length) {
5270 	default:
5271 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5272 		return;
5273 
5274 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5275 		/*
5276 		 * XXX: The check for valid DEST_length was not there
5277 		 * in earlier releases and some buggy
5278 		 * TLI apps (e.g Sybase) got away with not feeding
5279 		 * in sin_zero part of address.
5280 		 * We allow that bug to keep those buggy apps humming.
5281 		 * Test suites require the check on DEST_length.
5282 		 * We construct a new mblk with valid DEST_length
5283 		 * free the original so the rest of the code does
5284 		 * not have to keep track of this special shorter
5285 		 * length address case.
5286 		 */
5287 		mblk_t *nmp;
5288 		struct T_conn_req *ntcr;
5289 		sin_t *nsin;
5290 
5291 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5292 		    tcr->OPT_length, BPRI_HI);
5293 		if (nmp == NULL) {
5294 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5295 			return;
5296 		}
5297 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5298 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5299 		ntcr->PRIM_type = T_CONN_REQ;
5300 		ntcr->DEST_length = sizeof (sin_t);
5301 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5302 
5303 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5304 		*nsin = sin_null;
5305 		/* Get pointer to shorter address to copy from original mp */
5306 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5307 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5308 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5309 			freemsg(nmp);
5310 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5311 			return;
5312 		}
5313 		nsin->sin_family = sin->sin_family;
5314 		nsin->sin_port = sin->sin_port;
5315 		nsin->sin_addr = sin->sin_addr;
5316 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5317 		nmp->b_wptr = (uchar_t *)&nsin[1];
5318 		if (tcr->OPT_length != 0) {
5319 			ntcr->OPT_length = tcr->OPT_length;
5320 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5321 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5322 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5323 			    tcr->OPT_length);
5324 			nmp->b_wptr += tcr->OPT_length;
5325 		}
5326 		freemsg(mp);	/* original mp freed */
5327 		mp = nmp;	/* re-initialize original variables */
5328 		tcr = ntcr;
5329 	}
5330 	/* FALLTHRU */
5331 
5332 	case sizeof (sin_t):
5333 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5334 		    sizeof (sin_t));
5335 		len = sizeof (sin_t);
5336 		break;
5337 
5338 	case sizeof (sin6_t):
5339 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5340 		    sizeof (sin6_t));
5341 		len = sizeof (sin6_t);
5342 		break;
5343 	}
5344 
5345 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
5346 	if (error != 0) {
5347 		tcp_err_ack(tcp, mp, TSYSERR, error);
5348 		return;
5349 	}
5350 
5351 	/*
5352 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
5353 	 * should key on their sequence number and cut them loose.
5354 	 */
5355 
5356 	/*
5357 	 * If options passed in, feed it for verification and handling
5358 	 */
5359 	if (tcr->OPT_length != 0) {
5360 		mblk_t	*ok_mp;
5361 		mblk_t	*discon_mp;
5362 		mblk_t  *conn_opts_mp;
5363 		int t_error, sys_error, do_disconnect;
5364 
5365 		conn_opts_mp = NULL;
5366 
5367 		if (tcp_conprim_opt_process(tcp, mp,
5368 		    &do_disconnect, &t_error, &sys_error) < 0) {
5369 			if (do_disconnect) {
5370 				ASSERT(t_error == 0 && sys_error == 0);
5371 				discon_mp = mi_tpi_discon_ind(NULL,
5372 				    ECONNREFUSED, 0);
5373 				if (!discon_mp) {
5374 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5375 					    TSYSERR, ENOMEM);
5376 					return;
5377 				}
5378 				ok_mp = mi_tpi_ok_ack_alloc(mp);
5379 				if (!ok_mp) {
5380 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5381 					    TSYSERR, ENOMEM);
5382 					return;
5383 				}
5384 				qreply(q, ok_mp);
5385 				qreply(q, discon_mp); /* no flush! */
5386 			} else {
5387 				ASSERT(t_error != 0);
5388 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
5389 				    sys_error);
5390 			}
5391 			return;
5392 		}
5393 		/*
5394 		 * Success in setting options, the mp option buffer represented
5395 		 * by OPT_length/offset has been potentially modified and
5396 		 * contains results of option processing. We copy it in
5397 		 * another mp to save it for potentially influencing returning
5398 		 * it in T_CONN_CONN.
5399 		 */
5400 		if (tcr->OPT_length != 0) { /* there are resulting options */
5401 			conn_opts_mp = copyb(mp);
5402 			if (!conn_opts_mp) {
5403 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5404 				    TSYSERR, ENOMEM);
5405 				return;
5406 			}
5407 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
5408 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
5409 			/*
5410 			 * Note:
5411 			 * These resulting option negotiation can include any
5412 			 * end-to-end negotiation options but there no such
5413 			 * thing (yet?) in our TCP/IP.
5414 			 */
5415 		}
5416 	}
5417 
5418 	/* call the non-TPI version */
5419 	error = tcp_do_connect(tcp->tcp_connp, sa, len, cr, cpid);
5420 	if (error < 0) {
5421 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
5422 	} else if (error > 0) {
5423 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
5424 	} else {
5425 		mp = mi_tpi_ok_ack_alloc(mp);
5426 	}
5427 
5428 	/*
5429 	 * Note: Code below is the "failure" case
5430 	 */
5431 	/* return error ack and blow away saved option results if any */
5432 connect_failed:
5433 	if (mp != NULL)
5434 		putnext(connp->conn_rq, mp);
5435 	else {
5436 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5437 		    TSYSERR, ENOMEM);
5438 	}
5439 }
5440 
5441 /*
5442  * Handle connect to IPv4 destinations, including connections for AF_INET6
5443  * sockets connecting to IPv4 mapped IPv6 destinations.
5444  * Returns zero if OK, a positive errno, or a negative TLI error.
5445  */
5446 static int
5447 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
5448     uint_t srcid)
5449 {
5450 	ipaddr_t 	dstaddr = *dstaddrp;
5451 	uint16_t 	lport;
5452 	conn_t		*connp = tcp->tcp_connp;
5453 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5454 	int		error;
5455 
5456 	ASSERT(connp->conn_ipversion == IPV4_VERSION);
5457 
5458 	/* Check for attempt to connect to INADDR_ANY */
5459 	if (dstaddr == INADDR_ANY)  {
5460 		/*
5461 		 * SunOS 4.x and 4.3 BSD allow an application
5462 		 * to connect a TCP socket to INADDR_ANY.
5463 		 * When they do this, the kernel picks the
5464 		 * address of one interface and uses it
5465 		 * instead.  The kernel usually ends up
5466 		 * picking the address of the loopback
5467 		 * interface.  This is an undocumented feature.
5468 		 * However, we provide the same thing here
5469 		 * in order to have source and binary
5470 		 * compatibility with SunOS 4.x.
5471 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
5472 		 * generate the T_CONN_CON.
5473 		 */
5474 		dstaddr = htonl(INADDR_LOOPBACK);
5475 		*dstaddrp = dstaddr;
5476 	}
5477 
5478 	/* Handle __sin6_src_id if socket not bound to an IP address */
5479 	if (srcid != 0 && connp->conn_laddr_v4 == INADDR_ANY) {
5480 		ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
5481 		    IPCL_ZONEID(connp), tcps->tcps_netstack);
5482 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
5483 	}
5484 
5485 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &connp->conn_faddr_v6);
5486 	connp->conn_fport = dstport;
5487 
5488 	/*
5489 	 * At this point the remote destination address and remote port fields
5490 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
5491 	 * have to see which state tcp was in so we can take appropriate action.
5492 	 */
5493 	if (tcp->tcp_state == TCPS_IDLE) {
5494 		/*
5495 		 * We support a quick connect capability here, allowing
5496 		 * clients to transition directly from IDLE to SYN_SENT
5497 		 * tcp_bindi will pick an unused port, insert the connection
5498 		 * in the bind hash and transition to BOUND state.
5499 		 */
5500 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
5501 		    tcp, B_TRUE);
5502 		lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
5503 		    B_FALSE, B_FALSE);
5504 		if (lport == 0)
5505 			return (-TNOADDR);
5506 	}
5507 
5508 	/*
5509 	 * Lookup the route to determine a source address and the uinfo.
5510 	 * Setup TCP parameters based on the metrics/DCE.
5511 	 */
5512 	error = tcp_set_destination(tcp);
5513 	if (error != 0)
5514 		return (error);
5515 
5516 	/*
5517 	 * Don't let an endpoint connect to itself.
5518 	 */
5519 	if (connp->conn_faddr_v4 == connp->conn_laddr_v4 &&
5520 	    connp->conn_fport == connp->conn_lport)
5521 		return (-TBADADDR);
5522 
5523 	tcp->tcp_state = TCPS_SYN_SENT;
5524 
5525 	return (ipcl_conn_insert_v4(connp));
5526 }
5527 
5528 /*
5529  * Handle connect to IPv6 destinations.
5530  * Returns zero if OK, a positive errno, or a negative TLI error.
5531  */
5532 static int
5533 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
5534     uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
5535 {
5536 	uint16_t 	lport;
5537 	conn_t		*connp = tcp->tcp_connp;
5538 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5539 	int		error;
5540 
5541 	ASSERT(connp->conn_family == AF_INET6);
5542 
5543 	/*
5544 	 * If we're here, it means that the destination address is a native
5545 	 * IPv6 address.  Return an error if conn_ipversion is not IPv6.  A
5546 	 * reason why it might not be IPv6 is if the socket was bound to an
5547 	 * IPv4-mapped IPv6 address.
5548 	 */
5549 	if (connp->conn_ipversion != IPV6_VERSION)
5550 		return (-TBADADDR);
5551 
5552 	/*
5553 	 * Interpret a zero destination to mean loopback.
5554 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
5555 	 * generate the T_CONN_CON.
5556 	 */
5557 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp))
5558 		*dstaddrp = ipv6_loopback;
5559 
5560 	/* Handle __sin6_src_id if socket not bound to an IP address */
5561 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&connp->conn_laddr_v6)) {
5562 		ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
5563 		    IPCL_ZONEID(connp), tcps->tcps_netstack);
5564 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
5565 	}
5566 
5567 	/*
5568 	 * Take care of the scope_id now.
5569 	 */
5570 	if (scope_id != 0 && IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
5571 		connp->conn_ixa->ixa_flags |= IXAF_SCOPEID_SET;
5572 		connp->conn_ixa->ixa_scopeid = scope_id;
5573 	} else {
5574 		connp->conn_ixa->ixa_flags &= ~IXAF_SCOPEID_SET;
5575 	}
5576 
5577 	connp->conn_flowinfo = flowinfo;
5578 	connp->conn_faddr_v6 = *dstaddrp;
5579 	connp->conn_fport = dstport;
5580 
5581 	/*
5582 	 * At this point the remote destination address and remote port fields
5583 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
5584 	 * have to see which state tcp was in so we can take appropriate action.
5585 	 */
5586 	if (tcp->tcp_state == TCPS_IDLE) {
5587 		/*
5588 		 * We support a quick connect capability here, allowing
5589 		 * clients to transition directly from IDLE to SYN_SENT
5590 		 * tcp_bindi will pick an unused port, insert the connection
5591 		 * in the bind hash and transition to BOUND state.
5592 		 */
5593 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
5594 		    tcp, B_TRUE);
5595 		lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
5596 		    B_FALSE, B_FALSE);
5597 		if (lport == 0)
5598 			return (-TNOADDR);
5599 	}
5600 
5601 	/*
5602 	 * Lookup the route to determine a source address and the uinfo.
5603 	 * Setup TCP parameters based on the metrics/DCE.
5604 	 */
5605 	error = tcp_set_destination(tcp);
5606 	if (error != 0)
5607 		return (error);
5608 
5609 	/*
5610 	 * Don't let an endpoint connect to itself.
5611 	 */
5612 	if (IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6, &connp->conn_laddr_v6) &&
5613 	    connp->conn_fport == connp->conn_lport)
5614 		return (-TBADADDR);
5615 
5616 	tcp->tcp_state = TCPS_SYN_SENT;
5617 
5618 	return (ipcl_conn_insert_v6(connp));
5619 }
5620 
5621 /*
5622  * Disconnect
5623  * Note that unlike other functions this returns a positive tli error
5624  * when it fails; it never returns an errno.
5625  */
5626 static int
5627 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
5628 {
5629 	conn_t		*lconnp;
5630 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5631 	conn_t		*connp = tcp->tcp_connp;
5632 
5633 	/*
5634 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
5635 	 * when the stream is in BOUND state. Do not send a reset,
5636 	 * since the destination IP address is not valid, and it can
5637 	 * be the initialized value of all zeros (broadcast address).
5638 	 */
5639 	if (tcp->tcp_state <= TCPS_BOUND) {
5640 		if (connp->conn_debug) {
5641 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
5642 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
5643 		}
5644 		return (TOUTSTATE);
5645 	}
5646 
5647 
5648 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
5649 
5650 		/*
5651 		 * According to TPI, for non-listeners, ignore seqnum
5652 		 * and disconnect.
5653 		 * Following interpretation of -1 seqnum is historical
5654 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
5655 		 * a valid seqnum should not be -1).
5656 		 *
5657 		 *	-1 means disconnect everything
5658 		 *	regardless even on a listener.
5659 		 */
5660 
5661 		int old_state = tcp->tcp_state;
5662 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
5663 
5664 		/*
5665 		 * The connection can't be on the tcp_time_wait_head list
5666 		 * since it is not detached.
5667 		 */
5668 		ASSERT(tcp->tcp_time_wait_next == NULL);
5669 		ASSERT(tcp->tcp_time_wait_prev == NULL);
5670 		ASSERT(tcp->tcp_time_wait_expire == 0);
5671 		/*
5672 		 * If it used to be a listener, check to make sure no one else
5673 		 * has taken the port before switching back to LISTEN state.
5674 		 */
5675 		if (connp->conn_ipversion == IPV4_VERSION) {
5676 			lconnp = ipcl_lookup_listener_v4(connp->conn_lport,
5677 			    connp->conn_laddr_v4, IPCL_ZONEID(connp), ipst);
5678 		} else {
5679 			uint_t ifindex = 0;
5680 
5681 			if (connp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)
5682 				ifindex = connp->conn_ixa->ixa_scopeid;
5683 
5684 			/* Allow conn_bound_if listeners? */
5685 			lconnp = ipcl_lookup_listener_v6(connp->conn_lport,
5686 			    &connp->conn_laddr_v6, ifindex, IPCL_ZONEID(connp),
5687 			    ipst);
5688 		}
5689 		if (tcp->tcp_conn_req_max && lconnp == NULL) {
5690 			tcp->tcp_state = TCPS_LISTEN;
5691 		} else if (old_state > TCPS_BOUND) {
5692 			tcp->tcp_conn_req_max = 0;
5693 			tcp->tcp_state = TCPS_BOUND;
5694 
5695 			/*
5696 			 * If this end point is not going to become a listener,
5697 			 * decrement the listener connection count if
5698 			 * necessary.  Note that we do not do this if it is
5699 			 * going to be a listner (the above if case) since
5700 			 * then it may remove the counter struct.
5701 			 */
5702 			if (tcp->tcp_listen_cnt != NULL)
5703 				TCP_DECR_LISTEN_CNT(tcp);
5704 		}
5705 		if (lconnp != NULL)
5706 			CONN_DEC_REF(lconnp);
5707 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
5708 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
5709 		} else if (old_state == TCPS_ESTABLISHED ||
5710 		    old_state == TCPS_CLOSE_WAIT) {
5711 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
5712 		}
5713 
5714 		if (tcp->tcp_fused)
5715 			tcp_unfuse(tcp);
5716 
5717 		mutex_enter(&tcp->tcp_eager_lock);
5718 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
5719 		    (tcp->tcp_conn_req_cnt_q != 0)) {
5720 			tcp_eager_cleanup(tcp, 0);
5721 		}
5722 		mutex_exit(&tcp->tcp_eager_lock);
5723 
5724 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
5725 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
5726 
5727 		tcp_reinit(tcp);
5728 
5729 		return (0);
5730 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
5731 		return (TBADSEQ);
5732 	}
5733 	return (0);
5734 }
5735 
5736 /*
5737  * Our client hereby directs us to reject the connection request
5738  * that tcp_input_listener() marked with 'seqnum'.  Rejection consists
5739  * of sending the appropriate RST, not an ICMP error.
5740  */
5741 static void
5742 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
5743 {
5744 	t_scalar_t seqnum;
5745 	int	error;
5746 	conn_t	*connp = tcp->tcp_connp;
5747 
5748 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5749 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
5750 		tcp_err_ack(tcp, mp, TPROTO, 0);
5751 		return;
5752 	}
5753 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
5754 	error = tcp_disconnect_common(tcp, seqnum);
5755 	if (error != 0)
5756 		tcp_err_ack(tcp, mp, error, 0);
5757 	else {
5758 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
5759 			/* Send M_FLUSH according to TPI */
5760 			(void) putnextctl1(connp->conn_rq, M_FLUSH, FLUSHRW);
5761 		}
5762 		mp = mi_tpi_ok_ack_alloc(mp);
5763 		if (mp != NULL)
5764 			putnext(connp->conn_rq, mp);
5765 	}
5766 }
5767 
5768 /*
5769  * Diagnostic routine used to return a string associated with the tcp state.
5770  * Note that if the caller does not supply a buffer, it will use an internal
5771  * static string.  This means that if multiple threads call this function at
5772  * the same time, output can be corrupted...  Note also that this function
5773  * does not check the size of the supplied buffer.  The caller has to make
5774  * sure that it is big enough.
5775  */
5776 static char *
5777 tcp_display(tcp_t *tcp, char *sup_buf, char format)
5778 {
5779 	char		buf1[30];
5780 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
5781 	char		*buf;
5782 	char		*cp;
5783 	in6_addr_t	local, remote;
5784 	char		local_addrbuf[INET6_ADDRSTRLEN];
5785 	char		remote_addrbuf[INET6_ADDRSTRLEN];
5786 	conn_t		*connp;
5787 
5788 	if (sup_buf != NULL)
5789 		buf = sup_buf;
5790 	else
5791 		buf = priv_buf;
5792 
5793 	if (tcp == NULL)
5794 		return ("NULL_TCP");
5795 
5796 	connp = tcp->tcp_connp;
5797 	switch (tcp->tcp_state) {
5798 	case TCPS_CLOSED:
5799 		cp = "TCP_CLOSED";
5800 		break;
5801 	case TCPS_IDLE:
5802 		cp = "TCP_IDLE";
5803 		break;
5804 	case TCPS_BOUND:
5805 		cp = "TCP_BOUND";
5806 		break;
5807 	case TCPS_LISTEN:
5808 		cp = "TCP_LISTEN";
5809 		break;
5810 	case TCPS_SYN_SENT:
5811 		cp = "TCP_SYN_SENT";
5812 		break;
5813 	case TCPS_SYN_RCVD:
5814 		cp = "TCP_SYN_RCVD";
5815 		break;
5816 	case TCPS_ESTABLISHED:
5817 		cp = "TCP_ESTABLISHED";
5818 		break;
5819 	case TCPS_CLOSE_WAIT:
5820 		cp = "TCP_CLOSE_WAIT";
5821 		break;
5822 	case TCPS_FIN_WAIT_1:
5823 		cp = "TCP_FIN_WAIT_1";
5824 		break;
5825 	case TCPS_CLOSING:
5826 		cp = "TCP_CLOSING";
5827 		break;
5828 	case TCPS_LAST_ACK:
5829 		cp = "TCP_LAST_ACK";
5830 		break;
5831 	case TCPS_FIN_WAIT_2:
5832 		cp = "TCP_FIN_WAIT_2";
5833 		break;
5834 	case TCPS_TIME_WAIT:
5835 		cp = "TCP_TIME_WAIT";
5836 		break;
5837 	default:
5838 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
5839 		cp = buf1;
5840 		break;
5841 	}
5842 	switch (format) {
5843 	case DISP_ADDR_AND_PORT:
5844 		if (connp->conn_ipversion == IPV4_VERSION) {
5845 			/*
5846 			 * Note that we use the remote address in the tcp_b
5847 			 * structure.  This means that it will print out
5848 			 * the real destination address, not the next hop's
5849 			 * address if source routing is used.
5850 			 */
5851 			IN6_IPADDR_TO_V4MAPPED(connp->conn_laddr_v4, &local);
5852 			IN6_IPADDR_TO_V4MAPPED(connp->conn_faddr_v4, &remote);
5853 
5854 		} else {
5855 			local = connp->conn_laddr_v6;
5856 			remote = connp->conn_faddr_v6;
5857 		}
5858 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
5859 		    sizeof (local_addrbuf));
5860 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
5861 		    sizeof (remote_addrbuf));
5862 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
5863 		    local_addrbuf, ntohs(connp->conn_lport), remote_addrbuf,
5864 		    ntohs(connp->conn_fport), cp);
5865 		break;
5866 	case DISP_PORT_ONLY:
5867 	default:
5868 		(void) mi_sprintf(buf, "[%u, %u] %s",
5869 		    ntohs(connp->conn_lport), ntohs(connp->conn_fport), cp);
5870 		break;
5871 	}
5872 
5873 	return (buf);
5874 }
5875 
5876 /*
5877  * Called via squeue to get on to eager's perimeter. It sends a
5878  * TH_RST if eager is in the fanout table. The listener wants the
5879  * eager to disappear either by means of tcp_eager_blowoff() or
5880  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
5881  * called (via squeue) if the eager cannot be inserted in the
5882  * fanout table in tcp_input_listener().
5883  */
5884 /* ARGSUSED */
5885 void
5886 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
5887 {
5888 	conn_t	*econnp = (conn_t *)arg;
5889 	tcp_t	*eager = econnp->conn_tcp;
5890 	tcp_t	*listener = eager->tcp_listener;
5891 
5892 	/*
5893 	 * We could be called because listener is closing. Since
5894 	 * the eager was using listener's queue's, we avoid
5895 	 * using the listeners queues from now on.
5896 	 */
5897 	ASSERT(eager->tcp_detached);
5898 	econnp->conn_rq = NULL;
5899 	econnp->conn_wq = NULL;
5900 
5901 	/*
5902 	 * An eager's conn_fanout will be NULL if it's a duplicate
5903 	 * for an existing 4-tuples in the conn fanout table.
5904 	 * We don't want to send an RST out in such case.
5905 	 */
5906 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
5907 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
5908 		    eager, eager->tcp_snxt, 0, TH_RST);
5909 	}
5910 
5911 	/* We are here because listener wants this eager gone */
5912 	if (listener != NULL) {
5913 		mutex_enter(&listener->tcp_eager_lock);
5914 		tcp_eager_unlink(eager);
5915 		if (eager->tcp_tconnind_started) {
5916 			/*
5917 			 * The eager has sent a conn_ind up to the
5918 			 * listener but listener decides to close
5919 			 * instead. We need to drop the extra ref
5920 			 * placed on eager in tcp_input_data() before
5921 			 * sending the conn_ind to listener.
5922 			 */
5923 			CONN_DEC_REF(econnp);
5924 		}
5925 		mutex_exit(&listener->tcp_eager_lock);
5926 		CONN_DEC_REF(listener->tcp_connp);
5927 	}
5928 
5929 	if (eager->tcp_state != TCPS_CLOSED)
5930 		tcp_close_detached(eager);
5931 }
5932 
5933 /*
5934  * Reset any eager connection hanging off this listener marked
5935  * with 'seqnum' and then reclaim it's resources.
5936  */
5937 static boolean_t
5938 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
5939 {
5940 	tcp_t	*eager;
5941 	mblk_t 	*mp;
5942 	tcp_stack_t	*tcps = listener->tcp_tcps;
5943 
5944 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
5945 	eager = listener;
5946 	mutex_enter(&listener->tcp_eager_lock);
5947 	do {
5948 		eager = eager->tcp_eager_next_q;
5949 		if (eager == NULL) {
5950 			mutex_exit(&listener->tcp_eager_lock);
5951 			return (B_FALSE);
5952 		}
5953 	} while (eager->tcp_conn_req_seqnum != seqnum);
5954 
5955 	if (eager->tcp_closemp_used) {
5956 		mutex_exit(&listener->tcp_eager_lock);
5957 		return (B_TRUE);
5958 	}
5959 	eager->tcp_closemp_used = B_TRUE;
5960 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5961 	CONN_INC_REF(eager->tcp_connp);
5962 	mutex_exit(&listener->tcp_eager_lock);
5963 	mp = &eager->tcp_closemp;
5964 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
5965 	    eager->tcp_connp, NULL, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
5966 	return (B_TRUE);
5967 }
5968 
5969 /*
5970  * Reset any eager connection hanging off this listener
5971  * and then reclaim it's resources.
5972  */
5973 static void
5974 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
5975 {
5976 	tcp_t	*eager;
5977 	mblk_t	*mp;
5978 	tcp_stack_t	*tcps = listener->tcp_tcps;
5979 
5980 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
5981 
5982 	if (!q0_only) {
5983 		/* First cleanup q */
5984 		TCP_STAT(tcps, tcp_eager_blowoff_q);
5985 		eager = listener->tcp_eager_next_q;
5986 		while (eager != NULL) {
5987 			if (!eager->tcp_closemp_used) {
5988 				eager->tcp_closemp_used = B_TRUE;
5989 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5990 				CONN_INC_REF(eager->tcp_connp);
5991 				mp = &eager->tcp_closemp;
5992 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
5993 				    tcp_eager_kill, eager->tcp_connp, NULL,
5994 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
5995 			}
5996 			eager = eager->tcp_eager_next_q;
5997 		}
5998 	}
5999 	/* Then cleanup q0 */
6000 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6001 	eager = listener->tcp_eager_next_q0;
6002 	while (eager != listener) {
6003 		if (!eager->tcp_closemp_used) {
6004 			eager->tcp_closemp_used = B_TRUE;
6005 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6006 			CONN_INC_REF(eager->tcp_connp);
6007 			mp = &eager->tcp_closemp;
6008 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6009 			    tcp_eager_kill, eager->tcp_connp, NULL, SQ_FILL,
6010 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6011 		}
6012 		eager = eager->tcp_eager_next_q0;
6013 	}
6014 }
6015 
6016 /*
6017  * If we are an eager connection hanging off a listener that hasn't
6018  * formally accepted the connection yet, get off his list and blow off
6019  * any data that we have accumulated.
6020  */
6021 static void
6022 tcp_eager_unlink(tcp_t *tcp)
6023 {
6024 	tcp_t	*listener = tcp->tcp_listener;
6025 
6026 	ASSERT(listener != NULL);
6027 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6028 	if (tcp->tcp_eager_next_q0 != NULL) {
6029 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6030 
6031 		/* Remove the eager tcp from q0 */
6032 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6033 		    tcp->tcp_eager_prev_q0;
6034 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6035 		    tcp->tcp_eager_next_q0;
6036 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6037 		listener->tcp_conn_req_cnt_q0--;
6038 
6039 		tcp->tcp_eager_next_q0 = NULL;
6040 		tcp->tcp_eager_prev_q0 = NULL;
6041 
6042 		/*
6043 		 * Take the eager out, if it is in the list of droppable
6044 		 * eagers.
6045 		 */
6046 		MAKE_UNDROPPABLE(tcp);
6047 
6048 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6049 			/* we have timed out before */
6050 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6051 			listener->tcp_syn_rcvd_timeout--;
6052 		}
6053 	} else {
6054 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6055 		tcp_t	*prev = NULL;
6056 
6057 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6058 			if (tcpp[0] == tcp) {
6059 				if (listener->tcp_eager_last_q == tcp) {
6060 					/*
6061 					 * If we are unlinking the last
6062 					 * element on the list, adjust
6063 					 * tail pointer. Set tail pointer
6064 					 * to nil when list is empty.
6065 					 */
6066 					ASSERT(tcp->tcp_eager_next_q == NULL);
6067 					if (listener->tcp_eager_last_q ==
6068 					    listener->tcp_eager_next_q) {
6069 						listener->tcp_eager_last_q =
6070 						    NULL;
6071 					} else {
6072 						/*
6073 						 * We won't get here if there
6074 						 * is only one eager in the
6075 						 * list.
6076 						 */
6077 						ASSERT(prev != NULL);
6078 						listener->tcp_eager_last_q =
6079 						    prev;
6080 					}
6081 				}
6082 				tcpp[0] = tcp->tcp_eager_next_q;
6083 				tcp->tcp_eager_next_q = NULL;
6084 				tcp->tcp_eager_last_q = NULL;
6085 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6086 				listener->tcp_conn_req_cnt_q--;
6087 				break;
6088 			}
6089 			prev = tcpp[0];
6090 		}
6091 	}
6092 	tcp->tcp_listener = NULL;
6093 }
6094 
6095 /* Shorthand to generate and send TPI error acks to our client */
6096 static void
6097 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6098 {
6099 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6100 		putnext(tcp->tcp_connp->conn_rq, mp);
6101 }
6102 
6103 /* Shorthand to generate and send TPI error acks to our client */
6104 static void
6105 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6106     int t_error, int sys_error)
6107 {
6108 	struct T_error_ack	*teackp;
6109 
6110 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
6111 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
6112 		teackp = (struct T_error_ack *)mp->b_rptr;
6113 		teackp->ERROR_prim = primitive;
6114 		teackp->TLI_error = t_error;
6115 		teackp->UNIX_error = sys_error;
6116 		putnext(tcp->tcp_connp->conn_rq, mp);
6117 	}
6118 }
6119 
6120 /*
6121  * Note: No locks are held when inspecting tcp_g_*epriv_ports
6122  * but instead the code relies on:
6123  * - the fact that the address of the array and its size never changes
6124  * - the atomic assignment of the elements of the array
6125  */
6126 /* ARGSUSED */
6127 static int
6128 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
6129 {
6130 	int i;
6131 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6132 
6133 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6134 		if (tcps->tcps_g_epriv_ports[i] != 0)
6135 			(void) mi_mpprintf(mp, "%d ",
6136 			    tcps->tcps_g_epriv_ports[i]);
6137 	}
6138 	return (0);
6139 }
6140 
6141 /*
6142  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6143  * threads from changing it at the same time.
6144  */
6145 /* ARGSUSED */
6146 static int
6147 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6148     cred_t *cr)
6149 {
6150 	long	new_value;
6151 	int	i;
6152 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6153 
6154 	/*
6155 	 * Fail the request if the new value does not lie within the
6156 	 * port number limits.
6157 	 */
6158 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6159 	    new_value <= 0 || new_value >= 65536) {
6160 		return (EINVAL);
6161 	}
6162 
6163 	mutex_enter(&tcps->tcps_epriv_port_lock);
6164 	/* Check if the value is already in the list */
6165 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6166 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
6167 			mutex_exit(&tcps->tcps_epriv_port_lock);
6168 			return (EEXIST);
6169 		}
6170 	}
6171 	/* Find an empty slot */
6172 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6173 		if (tcps->tcps_g_epriv_ports[i] == 0)
6174 			break;
6175 	}
6176 	if (i == tcps->tcps_g_num_epriv_ports) {
6177 		mutex_exit(&tcps->tcps_epriv_port_lock);
6178 		return (EOVERFLOW);
6179 	}
6180 	/* Set the new value */
6181 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
6182 	mutex_exit(&tcps->tcps_epriv_port_lock);
6183 	return (0);
6184 }
6185 
6186 /*
6187  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6188  * threads from changing it at the same time.
6189  */
6190 /* ARGSUSED */
6191 static int
6192 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6193     cred_t *cr)
6194 {
6195 	long	new_value;
6196 	int	i;
6197 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6198 
6199 	/*
6200 	 * Fail the request if the new value does not lie within the
6201 	 * port number limits.
6202 	 */
6203 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
6204 	    new_value >= 65536) {
6205 		return (EINVAL);
6206 	}
6207 
6208 	mutex_enter(&tcps->tcps_epriv_port_lock);
6209 	/* Check that the value is already in the list */
6210 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6211 		if (tcps->tcps_g_epriv_ports[i] == new_value)
6212 			break;
6213 	}
6214 	if (i == tcps->tcps_g_num_epriv_ports) {
6215 		mutex_exit(&tcps->tcps_epriv_port_lock);
6216 		return (ESRCH);
6217 	}
6218 	/* Clear the value */
6219 	tcps->tcps_g_epriv_ports[i] = 0;
6220 	mutex_exit(&tcps->tcps_epriv_port_lock);
6221 	return (0);
6222 }
6223 
6224 /* Return the TPI/TLI equivalent of our current tcp_state */
6225 static int
6226 tcp_tpistate(tcp_t *tcp)
6227 {
6228 	switch (tcp->tcp_state) {
6229 	case TCPS_IDLE:
6230 		return (TS_UNBND);
6231 	case TCPS_LISTEN:
6232 		/*
6233 		 * Return whether there are outstanding T_CONN_IND waiting
6234 		 * for the matching T_CONN_RES. Therefore don't count q0.
6235 		 */
6236 		if (tcp->tcp_conn_req_cnt_q > 0)
6237 			return (TS_WRES_CIND);
6238 		else
6239 			return (TS_IDLE);
6240 	case TCPS_BOUND:
6241 		return (TS_IDLE);
6242 	case TCPS_SYN_SENT:
6243 		return (TS_WCON_CREQ);
6244 	case TCPS_SYN_RCVD:
6245 		/*
6246 		 * Note: assumption: this has to the active open SYN_RCVD.
6247 		 * The passive instance is detached in SYN_RCVD stage of
6248 		 * incoming connection processing so we cannot get request
6249 		 * for T_info_ack on it.
6250 		 */
6251 		return (TS_WACK_CRES);
6252 	case TCPS_ESTABLISHED:
6253 		return (TS_DATA_XFER);
6254 	case TCPS_CLOSE_WAIT:
6255 		return (TS_WREQ_ORDREL);
6256 	case TCPS_FIN_WAIT_1:
6257 		return (TS_WIND_ORDREL);
6258 	case TCPS_FIN_WAIT_2:
6259 		return (TS_WIND_ORDREL);
6260 
6261 	case TCPS_CLOSING:
6262 	case TCPS_LAST_ACK:
6263 	case TCPS_TIME_WAIT:
6264 	case TCPS_CLOSED:
6265 		/*
6266 		 * Following TS_WACK_DREQ7 is a rendition of "not
6267 		 * yet TS_IDLE" TPI state. There is no best match to any
6268 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
6269 		 * choose a value chosen that will map to TLI/XTI level
6270 		 * state of TSTATECHNG (state is process of changing) which
6271 		 * captures what this dummy state represents.
6272 		 */
6273 		return (TS_WACK_DREQ7);
6274 	default:
6275 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
6276 		    tcp->tcp_state, tcp_display(tcp, NULL,
6277 		    DISP_PORT_ONLY));
6278 		return (TS_UNBND);
6279 	}
6280 }
6281 
6282 static void
6283 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
6284 {
6285 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6286 	conn_t		*connp = tcp->tcp_connp;
6287 
6288 	if (connp->conn_family == AF_INET6)
6289 		*tia = tcp_g_t_info_ack_v6;
6290 	else
6291 		*tia = tcp_g_t_info_ack;
6292 	tia->CURRENT_state = tcp_tpistate(tcp);
6293 	tia->OPT_size = tcp_max_optsize;
6294 	if (tcp->tcp_mss == 0) {
6295 		/* Not yet set - tcp_open does not set mss */
6296 		if (connp->conn_ipversion == IPV4_VERSION)
6297 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
6298 		else
6299 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
6300 	} else {
6301 		tia->TIDU_size = tcp->tcp_mss;
6302 	}
6303 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
6304 }
6305 
6306 static void
6307 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
6308     t_uscalar_t cap_bits1)
6309 {
6310 	tcap->CAP_bits1 = 0;
6311 
6312 	if (cap_bits1 & TC1_INFO) {
6313 		tcp_copy_info(&tcap->INFO_ack, tcp);
6314 		tcap->CAP_bits1 |= TC1_INFO;
6315 	}
6316 
6317 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
6318 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
6319 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
6320 	}
6321 
6322 }
6323 
6324 /*
6325  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
6326  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
6327  * tcp_g_t_info_ack.  The current state of the stream is copied from
6328  * tcp_state.
6329  */
6330 static void
6331 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
6332 {
6333 	t_uscalar_t		cap_bits1;
6334 	struct T_capability_ack	*tcap;
6335 
6336 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
6337 		freemsg(mp);
6338 		return;
6339 	}
6340 
6341 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
6342 
6343 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
6344 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
6345 	if (mp == NULL)
6346 		return;
6347 
6348 	tcap = (struct T_capability_ack *)mp->b_rptr;
6349 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
6350 
6351 	putnext(tcp->tcp_connp->conn_rq, mp);
6352 }
6353 
6354 /*
6355  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
6356  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
6357  * The current state of the stream is copied from tcp_state.
6358  */
6359 static void
6360 tcp_info_req(tcp_t *tcp, mblk_t *mp)
6361 {
6362 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
6363 	    T_INFO_ACK);
6364 	if (!mp) {
6365 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6366 		return;
6367 	}
6368 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
6369 	putnext(tcp->tcp_connp->conn_rq, mp);
6370 }
6371 
6372 /* Respond to the TPI addr request */
6373 static void
6374 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
6375 {
6376 	struct sockaddr *sa;
6377 	mblk_t	*ackmp;
6378 	struct T_addr_ack *taa;
6379 	conn_t	*connp = tcp->tcp_connp;
6380 	uint_t	addrlen;
6381 
6382 	/* Make it large enough for worst case */
6383 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
6384 	    2 * sizeof (sin6_t), 1);
6385 	if (ackmp == NULL) {
6386 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6387 		return;
6388 	}
6389 
6390 	taa = (struct T_addr_ack *)ackmp->b_rptr;
6391 
6392 	bzero(taa, sizeof (struct T_addr_ack));
6393 	ackmp->b_wptr = (uchar_t *)&taa[1];
6394 
6395 	taa->PRIM_type = T_ADDR_ACK;
6396 	ackmp->b_datap->db_type = M_PCPROTO;
6397 
6398 	if (connp->conn_family == AF_INET)
6399 		addrlen = sizeof (sin_t);
6400 	else
6401 		addrlen = sizeof (sin6_t);
6402 
6403 	/*
6404 	 * Note: Following code assumes 32 bit alignment of basic
6405 	 * data structures like sin_t and struct T_addr_ack.
6406 	 */
6407 	if (tcp->tcp_state >= TCPS_BOUND) {
6408 		/*
6409 		 * Fill in local address first
6410 		 */
6411 		taa->LOCADDR_offset = sizeof (*taa);
6412 		taa->LOCADDR_length = addrlen;
6413 		sa = (struct sockaddr *)&taa[1];
6414 		(void) conn_getsockname(connp, sa, &addrlen);
6415 		ackmp->b_wptr += addrlen;
6416 	}
6417 	if (tcp->tcp_state >= TCPS_SYN_RCVD) {
6418 		/*
6419 		 * Fill in Remote address
6420 		 */
6421 		taa->REMADDR_length = addrlen;
6422 		/* assumed 32-bit alignment */
6423 		taa->REMADDR_offset = taa->LOCADDR_offset + taa->LOCADDR_length;
6424 		sa = (struct sockaddr *)(ackmp->b_rptr + taa->REMADDR_offset);
6425 		(void) conn_getpeername(connp, sa, &addrlen);
6426 		ackmp->b_wptr += addrlen;
6427 	}
6428 	ASSERT(ackmp->b_wptr <= ackmp->b_datap->db_lim);
6429 	putnext(tcp->tcp_connp->conn_rq, ackmp);
6430 }
6431 
6432 /*
6433  * Handle reinitialization of a tcp structure.
6434  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
6435  */
6436 static void
6437 tcp_reinit(tcp_t *tcp)
6438 {
6439 	mblk_t		*mp;
6440 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6441 	conn_t		*connp  = tcp->tcp_connp;
6442 
6443 	TCP_STAT(tcps, tcp_reinit_calls);
6444 
6445 	/* tcp_reinit should never be called for detached tcp_t's */
6446 	ASSERT(tcp->tcp_listener == NULL);
6447 	ASSERT((connp->conn_family == AF_INET &&
6448 	    connp->conn_ipversion == IPV4_VERSION) ||
6449 	    (connp->conn_family == AF_INET6 &&
6450 	    (connp->conn_ipversion == IPV4_VERSION ||
6451 	    connp->conn_ipversion == IPV6_VERSION)));
6452 
6453 	/* Cancel outstanding timers */
6454 	tcp_timers_stop(tcp);
6455 
6456 	/*
6457 	 * Reset everything in the state vector, after updating global
6458 	 * MIB data from instance counters.
6459 	 */
6460 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
6461 	tcp->tcp_ibsegs = 0;
6462 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
6463 	tcp->tcp_obsegs = 0;
6464 
6465 	tcp_close_mpp(&tcp->tcp_xmit_head);
6466 	if (tcp->tcp_snd_zcopy_aware)
6467 		tcp_zcopy_notify(tcp);
6468 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
6469 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
6470 	mutex_enter(&tcp->tcp_non_sq_lock);
6471 	if (tcp->tcp_flow_stopped &&
6472 	    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
6473 		tcp_clrqfull(tcp);
6474 	}
6475 	mutex_exit(&tcp->tcp_non_sq_lock);
6476 	tcp_close_mpp(&tcp->tcp_reass_head);
6477 	tcp->tcp_reass_tail = NULL;
6478 	if (tcp->tcp_rcv_list != NULL) {
6479 		/* Free b_next chain */
6480 		tcp_close_mpp(&tcp->tcp_rcv_list);
6481 		tcp->tcp_rcv_last_head = NULL;
6482 		tcp->tcp_rcv_last_tail = NULL;
6483 		tcp->tcp_rcv_cnt = 0;
6484 	}
6485 	tcp->tcp_rcv_last_tail = NULL;
6486 
6487 	if ((mp = tcp->tcp_urp_mp) != NULL) {
6488 		freemsg(mp);
6489 		tcp->tcp_urp_mp = NULL;
6490 	}
6491 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
6492 		freemsg(mp);
6493 		tcp->tcp_urp_mark_mp = NULL;
6494 	}
6495 	if (tcp->tcp_fused_sigurg_mp != NULL) {
6496 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
6497 		freeb(tcp->tcp_fused_sigurg_mp);
6498 		tcp->tcp_fused_sigurg_mp = NULL;
6499 	}
6500 	if (tcp->tcp_ordrel_mp != NULL) {
6501 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
6502 		freeb(tcp->tcp_ordrel_mp);
6503 		tcp->tcp_ordrel_mp = NULL;
6504 	}
6505 
6506 	/*
6507 	 * Following is a union with two members which are
6508 	 * identical types and size so the following cleanup
6509 	 * is enough.
6510 	 */
6511 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
6512 
6513 	CL_INET_DISCONNECT(connp);
6514 
6515 	/*
6516 	 * The connection can't be on the tcp_time_wait_head list
6517 	 * since it is not detached.
6518 	 */
6519 	ASSERT(tcp->tcp_time_wait_next == NULL);
6520 	ASSERT(tcp->tcp_time_wait_prev == NULL);
6521 	ASSERT(tcp->tcp_time_wait_expire == 0);
6522 
6523 	if (tcp->tcp_kssl_pending) {
6524 		tcp->tcp_kssl_pending = B_FALSE;
6525 
6526 		/* Don't reset if the initialized by bind. */
6527 		if (tcp->tcp_kssl_ent != NULL) {
6528 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
6529 			    KSSL_NO_PROXY);
6530 		}
6531 	}
6532 	if (tcp->tcp_kssl_ctx != NULL) {
6533 		kssl_release_ctx(tcp->tcp_kssl_ctx);
6534 		tcp->tcp_kssl_ctx = NULL;
6535 	}
6536 
6537 	/*
6538 	 * Reset/preserve other values
6539 	 */
6540 	tcp_reinit_values(tcp);
6541 	ipcl_hash_remove(connp);
6542 	ixa_cleanup(connp->conn_ixa);
6543 	tcp_ipsec_cleanup(tcp);
6544 
6545 	connp->conn_laddr_v6 = connp->conn_bound_addr_v6;
6546 	connp->conn_saddr_v6 = connp->conn_bound_addr_v6;
6547 
6548 	if (tcp->tcp_conn_req_max != 0) {
6549 		/*
6550 		 * This is the case when a TLI program uses the same
6551 		 * transport end point to accept a connection.  This
6552 		 * makes the TCP both a listener and acceptor.  When
6553 		 * this connection is closed, we need to set the state
6554 		 * back to TCPS_LISTEN.  Make sure that the eager list
6555 		 * is reinitialized.
6556 		 *
6557 		 * Note that this stream is still bound to the four
6558 		 * tuples of the previous connection in IP.  If a new
6559 		 * SYN with different foreign address comes in, IP will
6560 		 * not find it and will send it to the global queue.  In
6561 		 * the global queue, TCP will do a tcp_lookup_listener()
6562 		 * to find this stream.  This works because this stream
6563 		 * is only removed from connected hash.
6564 		 *
6565 		 */
6566 		tcp->tcp_state = TCPS_LISTEN;
6567 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
6568 		tcp->tcp_eager_next_drop_q0 = tcp;
6569 		tcp->tcp_eager_prev_drop_q0 = tcp;
6570 		/*
6571 		 * Initially set conn_recv to tcp_input_listener_unbound to try
6572 		 * to pick a good squeue for the listener when the first SYN
6573 		 * arrives. tcp_input_listener_unbound sets it to
6574 		 * tcp_input_listener on that first SYN.
6575 		 */
6576 		connp->conn_recv = tcp_input_listener_unbound;
6577 
6578 		connp->conn_proto = IPPROTO_TCP;
6579 		connp->conn_faddr_v6 = ipv6_all_zeros;
6580 		connp->conn_fport = 0;
6581 
6582 		(void) ipcl_bind_insert(connp);
6583 	} else {
6584 		tcp->tcp_state = TCPS_BOUND;
6585 	}
6586 
6587 	/*
6588 	 * Initialize to default values
6589 	 */
6590 	tcp_init_values(tcp);
6591 
6592 	ASSERT(tcp->tcp_ptpbhn != NULL);
6593 	tcp->tcp_rwnd = connp->conn_rcvbuf;
6594 	tcp->tcp_mss = connp->conn_ipversion != IPV4_VERSION ?
6595 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
6596 }
6597 
6598 /*
6599  * Force values to zero that need be zero.
6600  * Do not touch values asociated with the BOUND or LISTEN state
6601  * since the connection will end up in that state after the reinit.
6602  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
6603  * structure!
6604  */
6605 static void
6606 tcp_reinit_values(tcp)
6607 	tcp_t *tcp;
6608 {
6609 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6610 	conn_t		*connp = tcp->tcp_connp;
6611 
6612 #ifndef	lint
6613 #define	DONTCARE(x)
6614 #define	PRESERVE(x)
6615 #else
6616 #define	DONTCARE(x)	((x) = (x))
6617 #define	PRESERVE(x)	((x) = (x))
6618 #endif	/* lint */
6619 
6620 	PRESERVE(tcp->tcp_bind_hash_port);
6621 	PRESERVE(tcp->tcp_bind_hash);
6622 	PRESERVE(tcp->tcp_ptpbhn);
6623 	PRESERVE(tcp->tcp_acceptor_hash);
6624 	PRESERVE(tcp->tcp_ptpahn);
6625 
6626 	/* Should be ASSERT NULL on these with new code! */
6627 	ASSERT(tcp->tcp_time_wait_next == NULL);
6628 	ASSERT(tcp->tcp_time_wait_prev == NULL);
6629 	ASSERT(tcp->tcp_time_wait_expire == 0);
6630 	PRESERVE(tcp->tcp_state);
6631 	PRESERVE(connp->conn_rq);
6632 	PRESERVE(connp->conn_wq);
6633 
6634 	ASSERT(tcp->tcp_xmit_head == NULL);
6635 	ASSERT(tcp->tcp_xmit_last == NULL);
6636 	ASSERT(tcp->tcp_unsent == 0);
6637 	ASSERT(tcp->tcp_xmit_tail == NULL);
6638 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
6639 
6640 	tcp->tcp_snxt = 0;			/* Displayed in mib */
6641 	tcp->tcp_suna = 0;			/* Displayed in mib */
6642 	tcp->tcp_swnd = 0;
6643 	DONTCARE(tcp->tcp_cwnd);	/* Init in tcp_process_options */
6644 
6645 	ASSERT(tcp->tcp_ibsegs == 0);
6646 	ASSERT(tcp->tcp_obsegs == 0);
6647 
6648 	if (connp->conn_ht_iphc != NULL) {
6649 		kmem_free(connp->conn_ht_iphc, connp->conn_ht_iphc_allocated);
6650 		connp->conn_ht_iphc = NULL;
6651 		connp->conn_ht_iphc_allocated = 0;
6652 		connp->conn_ht_iphc_len = 0;
6653 		connp->conn_ht_ulp = NULL;
6654 		connp->conn_ht_ulp_len = 0;
6655 		tcp->tcp_ipha = NULL;
6656 		tcp->tcp_ip6h = NULL;
6657 		tcp->tcp_tcpha = NULL;
6658 	}
6659 
6660 	/* We clear any IP_OPTIONS and extension headers */
6661 	ip_pkt_free(&connp->conn_xmit_ipp);
6662 
6663 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
6664 	DONTCARE(tcp->tcp_ipha);
6665 	DONTCARE(tcp->tcp_ip6h);
6666 	DONTCARE(tcp->tcp_tcpha);
6667 	tcp->tcp_valid_bits = 0;
6668 
6669 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
6670 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
6671 	tcp->tcp_last_rcv_lbolt = 0;
6672 
6673 	tcp->tcp_init_cwnd = 0;
6674 
6675 	tcp->tcp_urp_last_valid = 0;
6676 	tcp->tcp_hard_binding = 0;
6677 
6678 	tcp->tcp_fin_acked = 0;
6679 	tcp->tcp_fin_rcvd = 0;
6680 	tcp->tcp_fin_sent = 0;
6681 	tcp->tcp_ordrel_done = 0;
6682 
6683 	tcp->tcp_detached = 0;
6684 
6685 	tcp->tcp_snd_ws_ok = B_FALSE;
6686 	tcp->tcp_snd_ts_ok = B_FALSE;
6687 	tcp->tcp_zero_win_probe = 0;
6688 
6689 	tcp->tcp_loopback = 0;
6690 	tcp->tcp_localnet = 0;
6691 	tcp->tcp_syn_defense = 0;
6692 	tcp->tcp_set_timer = 0;
6693 
6694 	tcp->tcp_active_open = 0;
6695 	tcp->tcp_rexmit = B_FALSE;
6696 	tcp->tcp_xmit_zc_clean = B_FALSE;
6697 
6698 	tcp->tcp_snd_sack_ok = B_FALSE;
6699 	tcp->tcp_hwcksum = B_FALSE;
6700 
6701 	DONTCARE(tcp->tcp_maxpsz_multiplier);	/* Init in tcp_init_values */
6702 
6703 	tcp->tcp_conn_def_q0 = 0;
6704 	tcp->tcp_ip_forward_progress = B_FALSE;
6705 	tcp->tcp_ecn_ok = B_FALSE;
6706 
6707 	tcp->tcp_cwr = B_FALSE;
6708 	tcp->tcp_ecn_echo_on = B_FALSE;
6709 	tcp->tcp_is_wnd_shrnk = B_FALSE;
6710 
6711 	if (tcp->tcp_sack_info != NULL) {
6712 		if (tcp->tcp_notsack_list != NULL) {
6713 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
6714 			    tcp);
6715 		}
6716 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
6717 		tcp->tcp_sack_info = NULL;
6718 	}
6719 
6720 	tcp->tcp_rcv_ws = 0;
6721 	tcp->tcp_snd_ws = 0;
6722 	tcp->tcp_ts_recent = 0;
6723 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
6724 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
6725 	tcp->tcp_initial_pmtu = 0;
6726 
6727 	ASSERT(tcp->tcp_reass_head == NULL);
6728 	ASSERT(tcp->tcp_reass_tail == NULL);
6729 
6730 	tcp->tcp_cwnd_cnt = 0;
6731 
6732 	ASSERT(tcp->tcp_rcv_list == NULL);
6733 	ASSERT(tcp->tcp_rcv_last_head == NULL);
6734 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
6735 	ASSERT(tcp->tcp_rcv_cnt == 0);
6736 
6737 	DONTCARE(tcp->tcp_cwnd_ssthresh); /* Init in tcp_set_destination */
6738 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
6739 	tcp->tcp_csuna = 0;
6740 
6741 	tcp->tcp_rto = 0;			/* Displayed in MIB */
6742 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
6743 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
6744 	tcp->tcp_rtt_update = 0;
6745 
6746 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
6747 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
6748 
6749 	tcp->tcp_rack = 0;			/* Displayed in mib */
6750 	tcp->tcp_rack_cnt = 0;
6751 	tcp->tcp_rack_cur_max = 0;
6752 	tcp->tcp_rack_abs_max = 0;
6753 
6754 	tcp->tcp_max_swnd = 0;
6755 
6756 	ASSERT(tcp->tcp_listener == NULL);
6757 
6758 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
6759 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
6760 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
6761 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
6762 
6763 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
6764 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
6765 	PRESERVE(tcp->tcp_conn_req_max);
6766 	PRESERVE(tcp->tcp_conn_req_seqnum);
6767 
6768 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
6769 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
6770 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
6771 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
6772 
6773 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
6774 	ASSERT(tcp->tcp_urp_mp == NULL);
6775 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
6776 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
6777 
6778 	ASSERT(tcp->tcp_eager_next_q == NULL);
6779 	ASSERT(tcp->tcp_eager_last_q == NULL);
6780 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
6781 	    tcp->tcp_eager_prev_q0 == NULL) ||
6782 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
6783 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
6784 
6785 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
6786 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
6787 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
6788 
6789 	tcp->tcp_client_errno = 0;
6790 
6791 	DONTCARE(connp->conn_sum);		/* Init in tcp_init_values */
6792 
6793 	connp->conn_faddr_v6 = ipv6_all_zeros;	/* Displayed in MIB */
6794 
6795 	PRESERVE(connp->conn_bound_addr_v6);
6796 	tcp->tcp_last_sent_len = 0;
6797 	tcp->tcp_dupack_cnt = 0;
6798 
6799 	connp->conn_fport = 0;			/* Displayed in MIB */
6800 	PRESERVE(connp->conn_lport);
6801 
6802 	PRESERVE(tcp->tcp_acceptor_lockp);
6803 
6804 	ASSERT(tcp->tcp_ordrel_mp == NULL);
6805 	PRESERVE(tcp->tcp_acceptor_id);
6806 	DONTCARE(tcp->tcp_ipsec_overhead);
6807 
6808 	PRESERVE(connp->conn_family);
6809 	/* Remove any remnants of mapped address binding */
6810 	if (connp->conn_family == AF_INET6) {
6811 		connp->conn_ipversion = IPV6_VERSION;
6812 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
6813 	} else {
6814 		connp->conn_ipversion = IPV4_VERSION;
6815 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
6816 	}
6817 
6818 	connp->conn_bound_if = 0;
6819 	connp->conn_recv_ancillary.crb_all = 0;
6820 	tcp->tcp_recvifindex = 0;
6821 	tcp->tcp_recvhops = 0;
6822 	tcp->tcp_closed = 0;
6823 	tcp->tcp_cleandeathtag = 0;
6824 	if (tcp->tcp_hopopts != NULL) {
6825 		mi_free(tcp->tcp_hopopts);
6826 		tcp->tcp_hopopts = NULL;
6827 		tcp->tcp_hopoptslen = 0;
6828 	}
6829 	ASSERT(tcp->tcp_hopoptslen == 0);
6830 	if (tcp->tcp_dstopts != NULL) {
6831 		mi_free(tcp->tcp_dstopts);
6832 		tcp->tcp_dstopts = NULL;
6833 		tcp->tcp_dstoptslen = 0;
6834 	}
6835 	ASSERT(tcp->tcp_dstoptslen == 0);
6836 	if (tcp->tcp_rthdrdstopts != NULL) {
6837 		mi_free(tcp->tcp_rthdrdstopts);
6838 		tcp->tcp_rthdrdstopts = NULL;
6839 		tcp->tcp_rthdrdstoptslen = 0;
6840 	}
6841 	ASSERT(tcp->tcp_rthdrdstoptslen == 0);
6842 	if (tcp->tcp_rthdr != NULL) {
6843 		mi_free(tcp->tcp_rthdr);
6844 		tcp->tcp_rthdr = NULL;
6845 		tcp->tcp_rthdrlen = 0;
6846 	}
6847 	ASSERT(tcp->tcp_rthdrlen == 0);
6848 
6849 	/* Reset fusion-related fields */
6850 	tcp->tcp_fused = B_FALSE;
6851 	tcp->tcp_unfusable = B_FALSE;
6852 	tcp->tcp_fused_sigurg = B_FALSE;
6853 	tcp->tcp_loopback_peer = NULL;
6854 
6855 	tcp->tcp_lso = B_FALSE;
6856 
6857 	tcp->tcp_in_ack_unsent = 0;
6858 	tcp->tcp_cork = B_FALSE;
6859 	tcp->tcp_tconnind_started = B_FALSE;
6860 
6861 	PRESERVE(tcp->tcp_squeue_bytes);
6862 
6863 	ASSERT(tcp->tcp_kssl_ctx == NULL);
6864 	ASSERT(!tcp->tcp_kssl_pending);
6865 	PRESERVE(tcp->tcp_kssl_ent);
6866 
6867 	tcp->tcp_closemp_used = B_FALSE;
6868 
6869 	PRESERVE(tcp->tcp_rsrv_mp);
6870 	PRESERVE(tcp->tcp_rsrv_mp_lock);
6871 
6872 #ifdef DEBUG
6873 	DONTCARE(tcp->tcmp_stk[0]);
6874 #endif
6875 
6876 	PRESERVE(tcp->tcp_connid);
6877 
6878 	ASSERT(tcp->tcp_listen_cnt == NULL);
6879 	ASSERT(tcp->tcp_reass_tid == 0);
6880 
6881 #undef	DONTCARE
6882 #undef	PRESERVE
6883 }
6884 
6885 static void
6886 tcp_init_values(tcp_t *tcp)
6887 {
6888 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6889 	conn_t		*connp = tcp->tcp_connp;
6890 
6891 	ASSERT((connp->conn_family == AF_INET &&
6892 	    connp->conn_ipversion == IPV4_VERSION) ||
6893 	    (connp->conn_family == AF_INET6 &&
6894 	    (connp->conn_ipversion == IPV4_VERSION ||
6895 	    connp->conn_ipversion == IPV6_VERSION)));
6896 
6897 	/*
6898 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
6899 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
6900 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
6901 	 * during first few transmissions of a connection as seen in slow
6902 	 * links.
6903 	 */
6904 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
6905 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
6906 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
6907 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
6908 	    tcps->tcps_conn_grace_period;
6909 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
6910 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
6911 	tcp->tcp_timer_backoff = 0;
6912 	tcp->tcp_ms_we_have_waited = 0;
6913 	tcp->tcp_last_recv_time = ddi_get_lbolt();
6914 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
6915 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
6916 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
6917 
6918 	tcp->tcp_maxpsz_multiplier = tcps->tcps_maxpsz_multiplier;
6919 
6920 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
6921 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
6922 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
6923 	/*
6924 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
6925 	 * passive open.
6926 	 */
6927 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
6928 
6929 	tcp->tcp_naglim = tcps->tcps_naglim_def;
6930 
6931 	/* NOTE:  ISS is now set in tcp_set_destination(). */
6932 
6933 	/* Reset fusion-related fields */
6934 	tcp->tcp_fused = B_FALSE;
6935 	tcp->tcp_unfusable = B_FALSE;
6936 	tcp->tcp_fused_sigurg = B_FALSE;
6937 	tcp->tcp_loopback_peer = NULL;
6938 
6939 	/* We rebuild the header template on the next connect/conn_request */
6940 
6941 	connp->conn_mlp_type = mlptSingle;
6942 
6943 	/*
6944 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
6945 	 * down tcp_rwnd. tcp_set_destination() will set the right value later.
6946 	 */
6947 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
6948 	tcp->tcp_rwnd = connp->conn_rcvbuf;
6949 
6950 	tcp->tcp_cork = B_FALSE;
6951 	/*
6952 	 * Init the tcp_debug option if it wasn't already set.  This value
6953 	 * determines whether TCP
6954 	 * calls strlog() to print out debug messages.  Doing this
6955 	 * initialization here means that this value is not inherited thru
6956 	 * tcp_reinit().
6957 	 */
6958 	if (!connp->conn_debug)
6959 		connp->conn_debug = tcps->tcps_dbg;
6960 
6961 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
6962 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
6963 }
6964 
6965 /* At minimum we need 8 bytes in the TCP header for the lookup */
6966 #define	ICMP_MIN_TCP_HDR	8
6967 
6968 /*
6969  * tcp_icmp_input is called as conn_recvicmp to process ICMP error messages
6970  * passed up by IP. The message is always received on the correct tcp_t.
6971  * Assumes that IP has pulled up everything up to and including the ICMP header.
6972  */
6973 /* ARGSUSED2 */
6974 static void
6975 tcp_icmp_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
6976 {
6977 	conn_t		*connp = (conn_t *)arg1;
6978 	icmph_t		*icmph;
6979 	ipha_t		*ipha;
6980 	int		iph_hdr_length;
6981 	tcpha_t		*tcpha;
6982 	uint32_t	seg_seq;
6983 	tcp_t		*tcp = connp->conn_tcp;
6984 
6985 	/* Assume IP provides aligned packets */
6986 	ASSERT(OK_32PTR(mp->b_rptr));
6987 	ASSERT((MBLKL(mp) >= sizeof (ipha_t)));
6988 
6989 	/*
6990 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
6991 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
6992 	 */
6993 	if (!(ira->ira_flags & IRAF_IS_IPV4)) {
6994 		tcp_icmp_error_ipv6(tcp, mp, ira);
6995 		return;
6996 	}
6997 
6998 	/* Skip past the outer IP and ICMP headers */
6999 	iph_hdr_length = ira->ira_ip_hdr_length;
7000 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
7001 	/*
7002 	 * If we don't have the correct outer IP header length
7003 	 * or if we don't have a complete inner IP header
7004 	 * drop it.
7005 	 */
7006 	if (iph_hdr_length < sizeof (ipha_t) ||
7007 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
7008 noticmpv4:
7009 		freemsg(mp);
7010 		return;
7011 	}
7012 	ipha = (ipha_t *)&icmph[1];
7013 
7014 	/* Skip past the inner IP and find the ULP header */
7015 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
7016 	tcpha = (tcpha_t *)((char *)ipha + iph_hdr_length);
7017 	/*
7018 	 * If we don't have the correct inner IP header length or if the ULP
7019 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
7020 	 * bytes of TCP header, drop it.
7021 	 */
7022 	if (iph_hdr_length < sizeof (ipha_t) ||
7023 	    ipha->ipha_protocol != IPPROTO_TCP ||
7024 	    (uchar_t *)tcpha + ICMP_MIN_TCP_HDR > mp->b_wptr) {
7025 		goto noticmpv4;
7026 	}
7027 
7028 	seg_seq = ntohl(tcpha->tha_seq);
7029 	switch (icmph->icmph_type) {
7030 	case ICMP_DEST_UNREACHABLE:
7031 		switch (icmph->icmph_code) {
7032 		case ICMP_FRAGMENTATION_NEEDED:
7033 			/*
7034 			 * Update Path MTU, then try to send something out.
7035 			 */
7036 			tcp_update_pmtu(tcp, B_TRUE);
7037 			tcp_rexmit_after_error(tcp);
7038 			break;
7039 		case ICMP_PORT_UNREACHABLE:
7040 		case ICMP_PROTOCOL_UNREACHABLE:
7041 			switch (tcp->tcp_state) {
7042 			case TCPS_SYN_SENT:
7043 			case TCPS_SYN_RCVD:
7044 				/*
7045 				 * ICMP can snipe away incipient
7046 				 * TCP connections as long as
7047 				 * seq number is same as initial
7048 				 * send seq number.
7049 				 */
7050 				if (seg_seq == tcp->tcp_iss) {
7051 					(void) tcp_clean_death(tcp,
7052 					    ECONNREFUSED, 6);
7053 				}
7054 				break;
7055 			}
7056 			break;
7057 		case ICMP_HOST_UNREACHABLE:
7058 		case ICMP_NET_UNREACHABLE:
7059 			/* Record the error in case we finally time out. */
7060 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
7061 				tcp->tcp_client_errno = EHOSTUNREACH;
7062 			else
7063 				tcp->tcp_client_errno = ENETUNREACH;
7064 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
7065 				if (tcp->tcp_listener != NULL &&
7066 				    tcp->tcp_listener->tcp_syn_defense) {
7067 					/*
7068 					 * Ditch the half-open connection if we
7069 					 * suspect a SYN attack is under way.
7070 					 */
7071 					(void) tcp_clean_death(tcp,
7072 					    tcp->tcp_client_errno, 7);
7073 				}
7074 			}
7075 			break;
7076 		default:
7077 			break;
7078 		}
7079 		break;
7080 	case ICMP_SOURCE_QUENCH: {
7081 		/*
7082 		 * use a global boolean to control
7083 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
7084 		 * The default is false.
7085 		 */
7086 		if (tcp_icmp_source_quench) {
7087 			/*
7088 			 * Reduce the sending rate as if we got a
7089 			 * retransmit timeout
7090 			 */
7091 			uint32_t npkt;
7092 
7093 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
7094 			    tcp->tcp_mss;
7095 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
7096 			tcp->tcp_cwnd = tcp->tcp_mss;
7097 			tcp->tcp_cwnd_cnt = 0;
7098 		}
7099 		break;
7100 	}
7101 	}
7102 	freemsg(mp);
7103 }
7104 
7105 /*
7106  * CALLED OUTSIDE OF SQUEUE! It can not follow any pointers that tcp might
7107  * change. But it can refer to fields like tcp_suna and tcp_snxt.
7108  *
7109  * Function tcp_verifyicmp is called as conn_verifyicmp to verify the ICMP
7110  * error messages received by IP. The message is always received on the correct
7111  * tcp_t.
7112  */
7113 /* ARGSUSED */
7114 static boolean_t
7115 tcp_verifyicmp(conn_t *connp, void *arg2, icmph_t *icmph, icmp6_t *icmp6,
7116     ip_recv_attr_t *ira)
7117 {
7118 	tcpha_t		*tcpha = (tcpha_t *)arg2;
7119 	uint32_t	seq = ntohl(tcpha->tha_seq);
7120 	tcp_t		*tcp = connp->conn_tcp;
7121 
7122 	/*
7123 	 * TCP sequence number contained in payload of the ICMP error message
7124 	 * should be within the range SND.UNA <= SEG.SEQ < SND.NXT. Otherwise,
7125 	 * the message is either a stale ICMP error, or an attack from the
7126 	 * network. Fail the verification.
7127 	 */
7128 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
7129 		return (B_FALSE);
7130 
7131 	/* For "too big" we also check the ignore flag */
7132 	if (ira->ira_flags & IRAF_IS_IPV4) {
7133 		ASSERT(icmph != NULL);
7134 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
7135 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
7136 		    tcp->tcp_tcps->tcps_ignore_path_mtu)
7137 			return (B_FALSE);
7138 	} else {
7139 		ASSERT(icmp6 != NULL);
7140 		if (icmp6->icmp6_type == ICMP6_PACKET_TOO_BIG &&
7141 		    tcp->tcp_tcps->tcps_ignore_path_mtu)
7142 			return (B_FALSE);
7143 	}
7144 	return (B_TRUE);
7145 }
7146 
7147 /*
7148  * Update the TCP connection according to change of PMTU.
7149  *
7150  * Path MTU might have changed by either increase or decrease, so need to
7151  * adjust the MSS based on the value of ixa_pmtu. No need to handle tiny
7152  * or negative MSS, since tcp_mss_set() will do it.
7153  */
7154 static void
7155 tcp_update_pmtu(tcp_t *tcp, boolean_t decrease_only)
7156 {
7157 	uint32_t	pmtu;
7158 	int32_t		mss;
7159 	conn_t		*connp = tcp->tcp_connp;
7160 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
7161 	iaflags_t	ixaflags;
7162 
7163 	if (tcp->tcp_tcps->tcps_ignore_path_mtu)
7164 		return;
7165 
7166 	if (tcp->tcp_state < TCPS_ESTABLISHED)
7167 		return;
7168 
7169 	/*
7170 	 * Always call ip_get_pmtu() to make sure that IP has updated
7171 	 * ixa_flags properly.
7172 	 */
7173 	pmtu = ip_get_pmtu(ixa);
7174 	ixaflags = ixa->ixa_flags;
7175 
7176 	/*
7177 	 * Calculate the MSS by decreasing the PMTU by conn_ht_iphc_len and
7178 	 * IPsec overhead if applied. Make sure to use the most recent
7179 	 * IPsec information.
7180 	 */
7181 	mss = pmtu - connp->conn_ht_iphc_len - conn_ipsec_length(connp);
7182 
7183 	/*
7184 	 * Nothing to change, so just return.
7185 	 */
7186 	if (mss == tcp->tcp_mss)
7187 		return;
7188 
7189 	/*
7190 	 * Currently, for ICMP errors, only PMTU decrease is handled.
7191 	 */
7192 	if (mss > tcp->tcp_mss && decrease_only)
7193 		return;
7194 
7195 	DTRACE_PROBE2(tcp_update_pmtu, int32_t, tcp->tcp_mss, uint32_t, mss);
7196 
7197 	/*
7198 	 * Update ixa_fragsize and ixa_pmtu.
7199 	 */
7200 	ixa->ixa_fragsize = ixa->ixa_pmtu = pmtu;
7201 
7202 	/*
7203 	 * Adjust MSS and all relevant variables.
7204 	 */
7205 	tcp_mss_set(tcp, mss);
7206 
7207 	/*
7208 	 * If the PMTU is below the min size maintained by IP, then ip_get_pmtu
7209 	 * has set IXAF_PMTU_TOO_SMALL and cleared IXAF_PMTU_IPV4_DF. Since TCP
7210 	 * has a (potentially different) min size we do the same. Make sure to
7211 	 * clear IXAF_DONTFRAG, which is used by IP to decide whether to
7212 	 * fragment the packet.
7213 	 *
7214 	 * LSO over IPv6 can not be fragmented. So need to disable LSO
7215 	 * when IPv6 fragmentation is needed.
7216 	 */
7217 	if (mss < tcp->tcp_tcps->tcps_mss_min)
7218 		ixaflags |= IXAF_PMTU_TOO_SMALL;
7219 
7220 	if (ixaflags & IXAF_PMTU_TOO_SMALL)
7221 		ixaflags &= ~(IXAF_DONTFRAG | IXAF_PMTU_IPV4_DF);
7222 
7223 	if ((connp->conn_ipversion == IPV4_VERSION) &&
7224 	    !(ixaflags & IXAF_PMTU_IPV4_DF)) {
7225 		tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
7226 	}
7227 	ixa->ixa_flags = ixaflags;
7228 }
7229 
7230 /*
7231  * Do slow start retransmission after ICMP errors of PMTU changes.
7232  */
7233 static void
7234 tcp_rexmit_after_error(tcp_t *tcp)
7235 {
7236 	/*
7237 	 * All sent data has been acknowledged or no data left to send, just
7238 	 * to return.
7239 	 */
7240 	if (!SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) ||
7241 	    (tcp->tcp_xmit_head == NULL))
7242 		return;
7243 
7244 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) && (tcp->tcp_unsent == 0))
7245 		tcp->tcp_rexmit_max = tcp->tcp_fss;
7246 	else
7247 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
7248 
7249 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
7250 	tcp->tcp_rexmit = B_TRUE;
7251 	tcp->tcp_dupack_cnt = 0;
7252 	tcp->tcp_snd_burst = TCP_CWND_SS;
7253 	tcp_ss_rexmit(tcp);
7254 }
7255 
7256 /*
7257  * tcp_icmp_error_ipv6 is called from tcp_icmp_input to process ICMPv6
7258  * error messages passed up by IP.
7259  * Assumes that IP has pulled up all the extension headers as well
7260  * as the ICMPv6 header.
7261  */
7262 static void
7263 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, ip_recv_attr_t *ira)
7264 {
7265 	icmp6_t		*icmp6;
7266 	ip6_t		*ip6h;
7267 	uint16_t	iph_hdr_length = ira->ira_ip_hdr_length;
7268 	tcpha_t		*tcpha;
7269 	uint8_t		*nexthdrp;
7270 	uint32_t	seg_seq;
7271 
7272 	/*
7273 	 * Verify that we have a complete IP header.
7274 	 */
7275 	ASSERT((MBLKL(mp) >= sizeof (ip6_t)));
7276 
7277 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
7278 	ip6h = (ip6_t *)&icmp6[1];
7279 	/*
7280 	 * Verify if we have a complete ICMP and inner IP header.
7281 	 */
7282 	if ((uchar_t *)&ip6h[1] > mp->b_wptr) {
7283 noticmpv6:
7284 		freemsg(mp);
7285 		return;
7286 	}
7287 
7288 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
7289 		goto noticmpv6;
7290 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
7291 	/*
7292 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
7293 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
7294 	 * packet.
7295 	 */
7296 	if ((*nexthdrp != IPPROTO_TCP) ||
7297 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
7298 		goto noticmpv6;
7299 	}
7300 
7301 	seg_seq = ntohl(tcpha->tha_seq);
7302 	switch (icmp6->icmp6_type) {
7303 	case ICMP6_PACKET_TOO_BIG:
7304 		/*
7305 		 * Update Path MTU, then try to send something out.
7306 		 */
7307 		tcp_update_pmtu(tcp, B_TRUE);
7308 		tcp_rexmit_after_error(tcp);
7309 		break;
7310 	case ICMP6_DST_UNREACH:
7311 		switch (icmp6->icmp6_code) {
7312 		case ICMP6_DST_UNREACH_NOPORT:
7313 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
7314 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
7315 			    (seg_seq == tcp->tcp_iss)) {
7316 				(void) tcp_clean_death(tcp,
7317 				    ECONNREFUSED, 8);
7318 			}
7319 			break;
7320 		case ICMP6_DST_UNREACH_ADMIN:
7321 		case ICMP6_DST_UNREACH_NOROUTE:
7322 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
7323 		case ICMP6_DST_UNREACH_ADDR:
7324 			/* Record the error in case we finally time out. */
7325 			tcp->tcp_client_errno = EHOSTUNREACH;
7326 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
7327 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
7328 			    (seg_seq == tcp->tcp_iss)) {
7329 				if (tcp->tcp_listener != NULL &&
7330 				    tcp->tcp_listener->tcp_syn_defense) {
7331 					/*
7332 					 * Ditch the half-open connection if we
7333 					 * suspect a SYN attack is under way.
7334 					 */
7335 					(void) tcp_clean_death(tcp,
7336 					    tcp->tcp_client_errno, 9);
7337 				}
7338 			}
7339 
7340 
7341 			break;
7342 		default:
7343 			break;
7344 		}
7345 		break;
7346 	case ICMP6_PARAM_PROB:
7347 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
7348 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
7349 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
7350 		    (uchar_t *)nexthdrp) {
7351 			if (tcp->tcp_state == TCPS_SYN_SENT ||
7352 			    tcp->tcp_state == TCPS_SYN_RCVD) {
7353 				(void) tcp_clean_death(tcp,
7354 				    ECONNREFUSED, 10);
7355 			}
7356 			break;
7357 		}
7358 		break;
7359 
7360 	case ICMP6_TIME_EXCEEDED:
7361 	default:
7362 		break;
7363 	}
7364 	freemsg(mp);
7365 }
7366 
7367 /*
7368  * Notify IP that we are having trouble with this connection.  IP should
7369  * make note so it can potentially use a different IRE.
7370  */
7371 static void
7372 tcp_ip_notify(tcp_t *tcp)
7373 {
7374 	conn_t		*connp = tcp->tcp_connp;
7375 	ire_t		*ire;
7376 
7377 	/*
7378 	 * Note: in the case of source routing we want to blow away the
7379 	 * route to the first source route hop.
7380 	 */
7381 	ire = connp->conn_ixa->ixa_ire;
7382 	if (ire != NULL && !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
7383 		if (ire->ire_ipversion == IPV4_VERSION) {
7384 			/*
7385 			 * As per RFC 1122, we send an RTM_LOSING to inform
7386 			 * routing protocols.
7387 			 */
7388 			ip_rts_change(RTM_LOSING, ire->ire_addr,
7389 			    ire->ire_gateway_addr, ire->ire_mask,
7390 			    connp->conn_laddr_v4,  0, 0, 0,
7391 			    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_IFA),
7392 			    ire->ire_ipst);
7393 		}
7394 		(void) ire_no_good(ire);
7395 	}
7396 }
7397 
7398 #pragma inline(tcp_send_data)
7399 
7400 /*
7401  * Timer callback routine for keepalive probe.  We do a fake resend of
7402  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
7403  * check to see if we have heard anything from the other end for the last
7404  * RTO period.  If we have, set the timer to expire for another
7405  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
7406  * RTO << 1 and check again when it expires.  Keep exponentially increasing
7407  * the timeout if we have not heard from the other side.  If for more than
7408  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
7409  * kill the connection unless the keepalive abort threshold is 0.  In
7410  * that case, we will probe "forever."
7411  */
7412 static void
7413 tcp_keepalive_killer(void *arg)
7414 {
7415 	mblk_t	*mp;
7416 	conn_t	*connp = (conn_t *)arg;
7417 	tcp_t  	*tcp = connp->conn_tcp;
7418 	int32_t	firetime;
7419 	int32_t	idletime;
7420 	int32_t	ka_intrvl;
7421 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7422 
7423 	tcp->tcp_ka_tid = 0;
7424 
7425 	if (tcp->tcp_fused)
7426 		return;
7427 
7428 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
7429 	ka_intrvl = tcp->tcp_ka_interval;
7430 
7431 	/*
7432 	 * Keepalive probe should only be sent if the application has not
7433 	 * done a close on the connection.
7434 	 */
7435 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
7436 		return;
7437 	}
7438 	/* Timer fired too early, restart it. */
7439 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
7440 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
7441 		    MSEC_TO_TICK(ka_intrvl));
7442 		return;
7443 	}
7444 
7445 	idletime = TICK_TO_MSEC(ddi_get_lbolt() - tcp->tcp_last_recv_time);
7446 	/*
7447 	 * If we have not heard from the other side for a long
7448 	 * time, kill the connection unless the keepalive abort
7449 	 * threshold is 0.  In that case, we will probe "forever."
7450 	 */
7451 	if (tcp->tcp_ka_abort_thres != 0 &&
7452 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
7453 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
7454 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
7455 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
7456 		return;
7457 	}
7458 
7459 	if (tcp->tcp_snxt == tcp->tcp_suna &&
7460 	    idletime >= ka_intrvl) {
7461 		/* Fake resend of last ACKed byte. */
7462 		mblk_t	*mp1 = allocb(1, BPRI_LO);
7463 
7464 		if (mp1 != NULL) {
7465 			*mp1->b_wptr++ = '\0';
7466 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
7467 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
7468 			freeb(mp1);
7469 			/*
7470 			 * if allocation failed, fall through to start the
7471 			 * timer back.
7472 			 */
7473 			if (mp != NULL) {
7474 				tcp_send_data(tcp, mp);
7475 				BUMP_MIB(&tcps->tcps_mib,
7476 				    tcpTimKeepaliveProbe);
7477 				if (tcp->tcp_ka_last_intrvl != 0) {
7478 					int max;
7479 					/*
7480 					 * We should probe again at least
7481 					 * in ka_intrvl, but not more than
7482 					 * tcp_rexmit_interval_max.
7483 					 */
7484 					max = tcps->tcps_rexmit_interval_max;
7485 					firetime = MIN(ka_intrvl - 1,
7486 					    tcp->tcp_ka_last_intrvl << 1);
7487 					if (firetime > max)
7488 						firetime = max;
7489 				} else {
7490 					firetime = tcp->tcp_rto;
7491 				}
7492 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
7493 				    tcp_keepalive_killer,
7494 				    MSEC_TO_TICK(firetime));
7495 				tcp->tcp_ka_last_intrvl = firetime;
7496 				return;
7497 			}
7498 		}
7499 	} else {
7500 		tcp->tcp_ka_last_intrvl = 0;
7501 	}
7502 
7503 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
7504 	if ((firetime = ka_intrvl - idletime) < 0) {
7505 		firetime = ka_intrvl;
7506 	}
7507 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
7508 	    MSEC_TO_TICK(firetime));
7509 }
7510 
7511 int
7512 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
7513 {
7514 	conn_t	*connp = tcp->tcp_connp;
7515 	queue_t	*q = connp->conn_rq;
7516 	int32_t	mss = tcp->tcp_mss;
7517 	int	maxpsz;
7518 
7519 	if (TCP_IS_DETACHED(tcp))
7520 		return (mss);
7521 	if (tcp->tcp_fused) {
7522 		maxpsz = tcp_fuse_maxpsz(tcp);
7523 		mss = INFPSZ;
7524 	} else if (tcp->tcp_maxpsz_multiplier == 0) {
7525 		/*
7526 		 * Set the sd_qn_maxpsz according to the socket send buffer
7527 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
7528 		 * instruct the stream head to copyin user data into contiguous
7529 		 * kernel-allocated buffers without breaking it up into smaller
7530 		 * chunks.  We round up the buffer size to the nearest SMSS.
7531 		 */
7532 		maxpsz = MSS_ROUNDUP(connp->conn_sndbuf, mss);
7533 		if (tcp->tcp_kssl_ctx == NULL)
7534 			mss = INFPSZ;
7535 		else
7536 			mss = SSL3_MAX_RECORD_LEN;
7537 	} else {
7538 		/*
7539 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
7540 		 * (and a multiple of the mss).  This instructs the stream
7541 		 * head to break down larger than SMSS writes into SMSS-
7542 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
7543 		 */
7544 		maxpsz = tcp->tcp_maxpsz_multiplier * mss;
7545 		if (maxpsz > connp->conn_sndbuf / 2) {
7546 			maxpsz = connp->conn_sndbuf / 2;
7547 			/* Round up to nearest mss */
7548 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
7549 		}
7550 	}
7551 
7552 	(void) proto_set_maxpsz(q, connp, maxpsz);
7553 	if (!(IPCL_IS_NONSTR(connp)))
7554 		connp->conn_wq->q_maxpsz = maxpsz;
7555 	if (set_maxblk)
7556 		(void) proto_set_tx_maxblk(q, connp, mss);
7557 	return (mss);
7558 }
7559 
7560 /*
7561  * Extract option values from a tcp header.  We put any found values into the
7562  * tcpopt struct and return a bitmask saying which options were found.
7563  */
7564 static int
7565 tcp_parse_options(tcpha_t *tcpha, tcp_opt_t *tcpopt)
7566 {
7567 	uchar_t		*endp;
7568 	int		len;
7569 	uint32_t	mss;
7570 	uchar_t		*up = (uchar_t *)tcpha;
7571 	int		found = 0;
7572 	int32_t		sack_len;
7573 	tcp_seq		sack_begin, sack_end;
7574 	tcp_t		*tcp;
7575 
7576 	endp = up + TCP_HDR_LENGTH(tcpha);
7577 	up += TCP_MIN_HEADER_LENGTH;
7578 	while (up < endp) {
7579 		len = endp - up;
7580 		switch (*up) {
7581 		case TCPOPT_EOL:
7582 			break;
7583 
7584 		case TCPOPT_NOP:
7585 			up++;
7586 			continue;
7587 
7588 		case TCPOPT_MAXSEG:
7589 			if (len < TCPOPT_MAXSEG_LEN ||
7590 			    up[1] != TCPOPT_MAXSEG_LEN)
7591 				break;
7592 
7593 			mss = BE16_TO_U16(up+2);
7594 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
7595 			tcpopt->tcp_opt_mss = mss;
7596 			found |= TCP_OPT_MSS_PRESENT;
7597 
7598 			up += TCPOPT_MAXSEG_LEN;
7599 			continue;
7600 
7601 		case TCPOPT_WSCALE:
7602 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
7603 				break;
7604 
7605 			if (up[2] > TCP_MAX_WINSHIFT)
7606 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
7607 			else
7608 				tcpopt->tcp_opt_wscale = up[2];
7609 			found |= TCP_OPT_WSCALE_PRESENT;
7610 
7611 			up += TCPOPT_WS_LEN;
7612 			continue;
7613 
7614 		case TCPOPT_SACK_PERMITTED:
7615 			if (len < TCPOPT_SACK_OK_LEN ||
7616 			    up[1] != TCPOPT_SACK_OK_LEN)
7617 				break;
7618 			found |= TCP_OPT_SACK_OK_PRESENT;
7619 			up += TCPOPT_SACK_OK_LEN;
7620 			continue;
7621 
7622 		case TCPOPT_SACK:
7623 			if (len <= 2 || up[1] <= 2 || len < up[1])
7624 				break;
7625 
7626 			/* If TCP is not interested in SACK blks... */
7627 			if ((tcp = tcpopt->tcp) == NULL) {
7628 				up += up[1];
7629 				continue;
7630 			}
7631 			sack_len = up[1] - TCPOPT_HEADER_LEN;
7632 			up += TCPOPT_HEADER_LEN;
7633 
7634 			/*
7635 			 * If the list is empty, allocate one and assume
7636 			 * nothing is sack'ed.
7637 			 */
7638 			ASSERT(tcp->tcp_sack_info != NULL);
7639 			if (tcp->tcp_notsack_list == NULL) {
7640 				tcp_notsack_update(&(tcp->tcp_notsack_list),
7641 				    tcp->tcp_suna, tcp->tcp_snxt,
7642 				    &(tcp->tcp_num_notsack_blk),
7643 				    &(tcp->tcp_cnt_notsack_list));
7644 
7645 				/*
7646 				 * Make sure tcp_notsack_list is not NULL.
7647 				 * This happens when kmem_alloc(KM_NOSLEEP)
7648 				 * returns NULL.
7649 				 */
7650 				if (tcp->tcp_notsack_list == NULL) {
7651 					up += sack_len;
7652 					continue;
7653 				}
7654 				tcp->tcp_fack = tcp->tcp_suna;
7655 			}
7656 
7657 			while (sack_len > 0) {
7658 				if (up + 8 > endp) {
7659 					up = endp;
7660 					break;
7661 				}
7662 				sack_begin = BE32_TO_U32(up);
7663 				up += 4;
7664 				sack_end = BE32_TO_U32(up);
7665 				up += 4;
7666 				sack_len -= 8;
7667 				/*
7668 				 * Bounds checking.  Make sure the SACK
7669 				 * info is within tcp_suna and tcp_snxt.
7670 				 * If this SACK blk is out of bound, ignore
7671 				 * it but continue to parse the following
7672 				 * blks.
7673 				 */
7674 				if (SEQ_LEQ(sack_end, sack_begin) ||
7675 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
7676 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
7677 					continue;
7678 				}
7679 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
7680 				    sack_begin, sack_end,
7681 				    &(tcp->tcp_num_notsack_blk),
7682 				    &(tcp->tcp_cnt_notsack_list));
7683 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
7684 					tcp->tcp_fack = sack_end;
7685 				}
7686 			}
7687 			found |= TCP_OPT_SACK_PRESENT;
7688 			continue;
7689 
7690 		case TCPOPT_TSTAMP:
7691 			if (len < TCPOPT_TSTAMP_LEN ||
7692 			    up[1] != TCPOPT_TSTAMP_LEN)
7693 				break;
7694 
7695 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
7696 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
7697 
7698 			found |= TCP_OPT_TSTAMP_PRESENT;
7699 
7700 			up += TCPOPT_TSTAMP_LEN;
7701 			continue;
7702 
7703 		default:
7704 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
7705 				break;
7706 			up += up[1];
7707 			continue;
7708 		}
7709 		break;
7710 	}
7711 	return (found);
7712 }
7713 
7714 /*
7715  * Set the MSS associated with a particular tcp based on its current value,
7716  * and a new one passed in. Observe minimums and maximums, and reset other
7717  * state variables that we want to view as multiples of MSS.
7718  *
7719  * The value of MSS could be either increased or descreased.
7720  */
7721 static void
7722 tcp_mss_set(tcp_t *tcp, uint32_t mss)
7723 {
7724 	uint32_t	mss_max;
7725 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7726 	conn_t		*connp = tcp->tcp_connp;
7727 
7728 	if (connp->conn_ipversion == IPV4_VERSION)
7729 		mss_max = tcps->tcps_mss_max_ipv4;
7730 	else
7731 		mss_max = tcps->tcps_mss_max_ipv6;
7732 
7733 	if (mss < tcps->tcps_mss_min)
7734 		mss = tcps->tcps_mss_min;
7735 	if (mss > mss_max)
7736 		mss = mss_max;
7737 	/*
7738 	 * Unless naglim has been set by our client to
7739 	 * a non-mss value, force naglim to track mss.
7740 	 * This can help to aggregate small writes.
7741 	 */
7742 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
7743 		tcp->tcp_naglim = mss;
7744 	/*
7745 	 * TCP should be able to buffer at least 4 MSS data for obvious
7746 	 * performance reason.
7747 	 */
7748 	if ((mss << 2) > connp->conn_sndbuf)
7749 		connp->conn_sndbuf = mss << 2;
7750 
7751 	/*
7752 	 * Set the send lowater to at least twice of MSS.
7753 	 */
7754 	if ((mss << 1) > connp->conn_sndlowat)
7755 		connp->conn_sndlowat = mss << 1;
7756 
7757 	/*
7758 	 * Update tcp_cwnd according to the new value of MSS. Keep the
7759 	 * previous ratio to preserve the transmit rate.
7760 	 */
7761 	tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
7762 	tcp->tcp_cwnd_cnt = 0;
7763 
7764 	tcp->tcp_mss = mss;
7765 	(void) tcp_maxpsz_set(tcp, B_TRUE);
7766 }
7767 
7768 /* For /dev/tcp aka AF_INET open */
7769 static int
7770 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
7771 {
7772 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
7773 }
7774 
7775 /* For /dev/tcp6 aka AF_INET6 open */
7776 static int
7777 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
7778 {
7779 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
7780 }
7781 
7782 static conn_t *
7783 tcp_create_common(cred_t *credp, boolean_t isv6, boolean_t issocket,
7784     int *errorp)
7785 {
7786 	tcp_t		*tcp = NULL;
7787 	conn_t		*connp;
7788 	zoneid_t	zoneid;
7789 	tcp_stack_t	*tcps;
7790 	squeue_t	*sqp;
7791 
7792 	ASSERT(errorp != NULL);
7793 	/*
7794 	 * Find the proper zoneid and netstack.
7795 	 */
7796 	/*
7797 	 * Special case for install: miniroot needs to be able to
7798 	 * access files via NFS as though it were always in the
7799 	 * global zone.
7800 	 */
7801 	if (credp == kcred && nfs_global_client_only != 0) {
7802 		zoneid = GLOBAL_ZONEID;
7803 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
7804 		    netstack_tcp;
7805 		ASSERT(tcps != NULL);
7806 	} else {
7807 		netstack_t *ns;
7808 		int err;
7809 
7810 		if ((err = secpolicy_basic_net_access(credp)) != 0) {
7811 			*errorp = err;
7812 			return (NULL);
7813 		}
7814 
7815 		ns = netstack_find_by_cred(credp);
7816 		ASSERT(ns != NULL);
7817 		tcps = ns->netstack_tcp;
7818 		ASSERT(tcps != NULL);
7819 
7820 		/*
7821 		 * For exclusive stacks we set the zoneid to zero
7822 		 * to make TCP operate as if in the global zone.
7823 		 */
7824 		if (tcps->tcps_netstack->netstack_stackid !=
7825 		    GLOBAL_NETSTACKID)
7826 			zoneid = GLOBAL_ZONEID;
7827 		else
7828 			zoneid = crgetzoneid(credp);
7829 	}
7830 
7831 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
7832 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
7833 	/*
7834 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
7835 	 * so we drop it by one.
7836 	 */
7837 	netstack_rele(tcps->tcps_netstack);
7838 	if (connp == NULL) {
7839 		*errorp = ENOSR;
7840 		return (NULL);
7841 	}
7842 	ASSERT(connp->conn_ixa->ixa_protocol == connp->conn_proto);
7843 
7844 	connp->conn_sqp = sqp;
7845 	connp->conn_initial_sqp = connp->conn_sqp;
7846 	connp->conn_ixa->ixa_sqp = connp->conn_sqp;
7847 	tcp = connp->conn_tcp;
7848 
7849 	/*
7850 	 * Besides asking IP to set the checksum for us, have conn_ip_output
7851 	 * to do the following checks when necessary:
7852 	 *
7853 	 * IXAF_VERIFY_SOURCE: drop packets when our outer source goes invalid
7854 	 * IXAF_VERIFY_PMTU: verify PMTU changes
7855 	 * IXAF_VERIFY_LSO: verify LSO capability changes
7856 	 */
7857 	connp->conn_ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
7858 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO;
7859 
7860 	if (!tcps->tcps_dev_flow_ctl)
7861 		connp->conn_ixa->ixa_flags |= IXAF_NO_DEV_FLOW_CTL;
7862 
7863 	if (isv6) {
7864 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
7865 		connp->conn_ipversion = IPV6_VERSION;
7866 		connp->conn_family = AF_INET6;
7867 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7868 		connp->conn_default_ttl = tcps->tcps_ipv6_hoplimit;
7869 	} else {
7870 		connp->conn_ipversion = IPV4_VERSION;
7871 		connp->conn_family = AF_INET;
7872 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7873 		connp->conn_default_ttl = tcps->tcps_ipv4_ttl;
7874 	}
7875 	connp->conn_xmit_ipp.ipp_unicast_hops = connp->conn_default_ttl;
7876 
7877 	crhold(credp);
7878 	connp->conn_cred = credp;
7879 	connp->conn_cpid = curproc->p_pid;
7880 	connp->conn_open_time = ddi_get_lbolt64();
7881 
7882 	connp->conn_zoneid = zoneid;
7883 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
7884 	connp->conn_ixa->ixa_zoneid = zoneid;
7885 	connp->conn_mlp_type = mlptSingle;
7886 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
7887 	ASSERT(tcp->tcp_tcps == tcps);
7888 
7889 	/*
7890 	 * If the caller has the process-wide flag set, then default to MAC
7891 	 * exempt mode.  This allows read-down to unlabeled hosts.
7892 	 */
7893 	if (getpflags(NET_MAC_AWARE, credp) != 0)
7894 		connp->conn_mac_mode = CONN_MAC_AWARE;
7895 
7896 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
7897 
7898 	if (issocket) {
7899 		tcp->tcp_issocket = 1;
7900 	}
7901 
7902 	connp->conn_rcvbuf = tcps->tcps_recv_hiwat;
7903 	connp->conn_sndbuf = tcps->tcps_xmit_hiwat;
7904 	connp->conn_sndlowat = tcps->tcps_xmit_lowat;
7905 	connp->conn_so_type = SOCK_STREAM;
7906 	connp->conn_wroff = connp->conn_ht_iphc_allocated +
7907 	    tcps->tcps_wroff_xtra;
7908 
7909 	SOCK_CONNID_INIT(tcp->tcp_connid);
7910 	tcp->tcp_state = TCPS_IDLE;
7911 	tcp_init_values(tcp);
7912 	return (connp);
7913 }
7914 
7915 static int
7916 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
7917     boolean_t isv6)
7918 {
7919 	tcp_t		*tcp = NULL;
7920 	conn_t		*connp = NULL;
7921 	int		err;
7922 	vmem_t		*minor_arena = NULL;
7923 	dev_t		conn_dev;
7924 	boolean_t	issocket;
7925 
7926 	if (q->q_ptr != NULL)
7927 		return (0);
7928 
7929 	if (sflag == MODOPEN)
7930 		return (EINVAL);
7931 
7932 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
7933 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
7934 		minor_arena = ip_minor_arena_la;
7935 	} else {
7936 		/*
7937 		 * Either minor numbers in the large arena were exhausted
7938 		 * or a non socket application is doing the open.
7939 		 * Try to allocate from the small arena.
7940 		 */
7941 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
7942 			return (EBUSY);
7943 		}
7944 		minor_arena = ip_minor_arena_sa;
7945 	}
7946 
7947 	ASSERT(minor_arena != NULL);
7948 
7949 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
7950 
7951 	if (flag & SO_FALLBACK) {
7952 		/*
7953 		 * Non streams socket needs a stream to fallback to
7954 		 */
7955 		RD(q)->q_ptr = (void *)conn_dev;
7956 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
7957 		WR(q)->q_ptr = (void *)minor_arena;
7958 		qprocson(q);
7959 		return (0);
7960 	} else if (flag & SO_ACCEPTOR) {
7961 		q->q_qinfo = &tcp_acceptor_rinit;
7962 		/*
7963 		 * the conn_dev and minor_arena will be subsequently used by
7964 		 * tcp_tli_accept() and tcp_tpi_close_accept() to figure out
7965 		 * the minor device number for this connection from the q_ptr.
7966 		 */
7967 		RD(q)->q_ptr = (void *)conn_dev;
7968 		WR(q)->q_qinfo = &tcp_acceptor_winit;
7969 		WR(q)->q_ptr = (void *)minor_arena;
7970 		qprocson(q);
7971 		return (0);
7972 	}
7973 
7974 	issocket = flag & SO_SOCKSTR;
7975 	connp = tcp_create_common(credp, isv6, issocket, &err);
7976 
7977 	if (connp == NULL) {
7978 		inet_minor_free(minor_arena, conn_dev);
7979 		q->q_ptr = WR(q)->q_ptr = NULL;
7980 		return (err);
7981 	}
7982 
7983 	connp->conn_rq = q;
7984 	connp->conn_wq = WR(q);
7985 	q->q_ptr = WR(q)->q_ptr = connp;
7986 
7987 	connp->conn_dev = conn_dev;
7988 	connp->conn_minor_arena = minor_arena;
7989 
7990 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
7991 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
7992 
7993 	tcp = connp->conn_tcp;
7994 
7995 	if (issocket) {
7996 		WR(q)->q_qinfo = &tcp_sock_winit;
7997 	} else {
7998 #ifdef  _ILP32
7999 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
8000 #else
8001 		tcp->tcp_acceptor_id = conn_dev;
8002 #endif  /* _ILP32 */
8003 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
8004 	}
8005 
8006 	/*
8007 	 * Put the ref for TCP. Ref for IP was already put
8008 	 * by ipcl_conn_create. Also Make the conn_t globally
8009 	 * visible to walkers
8010 	 */
8011 	mutex_enter(&connp->conn_lock);
8012 	CONN_INC_REF_LOCKED(connp);
8013 	ASSERT(connp->conn_ref == 2);
8014 	connp->conn_state_flags &= ~CONN_INCIPIENT;
8015 	mutex_exit(&connp->conn_lock);
8016 
8017 	qprocson(q);
8018 	return (0);
8019 }
8020 
8021 /*
8022  * Some TCP options can be "set" by requesting them in the option
8023  * buffer. This is needed for XTI feature test though we do not
8024  * allow it in general. We interpret that this mechanism is more
8025  * applicable to OSI protocols and need not be allowed in general.
8026  * This routine filters out options for which it is not allowed (most)
8027  * and lets through those (few) for which it is. [ The XTI interface
8028  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
8029  * ever implemented will have to be allowed here ].
8030  */
8031 static boolean_t
8032 tcp_allow_connopt_set(int level, int name)
8033 {
8034 
8035 	switch (level) {
8036 	case IPPROTO_TCP:
8037 		switch (name) {
8038 		case TCP_NODELAY:
8039 			return (B_TRUE);
8040 		default:
8041 			return (B_FALSE);
8042 		}
8043 		/*NOTREACHED*/
8044 	default:
8045 		return (B_FALSE);
8046 	}
8047 	/*NOTREACHED*/
8048 }
8049 
8050 /*
8051  * This routine gets default values of certain options whose default
8052  * values are maintained by protocol specific code
8053  */
8054 /* ARGSUSED */
8055 int
8056 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
8057 {
8058 	int32_t	*i1 = (int32_t *)ptr;
8059 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
8060 
8061 	switch (level) {
8062 	case IPPROTO_TCP:
8063 		switch (name) {
8064 		case TCP_NOTIFY_THRESHOLD:
8065 			*i1 = tcps->tcps_ip_notify_interval;
8066 			break;
8067 		case TCP_ABORT_THRESHOLD:
8068 			*i1 = tcps->tcps_ip_abort_interval;
8069 			break;
8070 		case TCP_CONN_NOTIFY_THRESHOLD:
8071 			*i1 = tcps->tcps_ip_notify_cinterval;
8072 			break;
8073 		case TCP_CONN_ABORT_THRESHOLD:
8074 			*i1 = tcps->tcps_ip_abort_cinterval;
8075 			break;
8076 		default:
8077 			return (-1);
8078 		}
8079 		break;
8080 	case IPPROTO_IP:
8081 		switch (name) {
8082 		case IP_TTL:
8083 			*i1 = tcps->tcps_ipv4_ttl;
8084 			break;
8085 		default:
8086 			return (-1);
8087 		}
8088 		break;
8089 	case IPPROTO_IPV6:
8090 		switch (name) {
8091 		case IPV6_UNICAST_HOPS:
8092 			*i1 = tcps->tcps_ipv6_hoplimit;
8093 			break;
8094 		default:
8095 			return (-1);
8096 		}
8097 		break;
8098 	default:
8099 		return (-1);
8100 	}
8101 	return (sizeof (int));
8102 }
8103 
8104 /*
8105  * TCP routine to get the values of options.
8106  */
8107 static int
8108 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
8109 {
8110 	int		*i1 = (int *)ptr;
8111 	tcp_t		*tcp = connp->conn_tcp;
8112 	conn_opt_arg_t	coas;
8113 	int		retval;
8114 
8115 	coas.coa_connp = connp;
8116 	coas.coa_ixa = connp->conn_ixa;
8117 	coas.coa_ipp = &connp->conn_xmit_ipp;
8118 	coas.coa_ancillary = B_FALSE;
8119 	coas.coa_changed = 0;
8120 
8121 	switch (level) {
8122 	case SOL_SOCKET:
8123 		switch (name) {
8124 		case SO_SND_COPYAVOID:
8125 			*i1 = tcp->tcp_snd_zcopy_on ?
8126 			    SO_SND_COPYAVOID : 0;
8127 			return (sizeof (int));
8128 		case SO_ACCEPTCONN:
8129 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
8130 			return (sizeof (int));
8131 		}
8132 		break;
8133 	case IPPROTO_TCP:
8134 		switch (name) {
8135 		case TCP_NODELAY:
8136 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
8137 			return (sizeof (int));
8138 		case TCP_MAXSEG:
8139 			*i1 = tcp->tcp_mss;
8140 			return (sizeof (int));
8141 		case TCP_NOTIFY_THRESHOLD:
8142 			*i1 = (int)tcp->tcp_first_timer_threshold;
8143 			return (sizeof (int));
8144 		case TCP_ABORT_THRESHOLD:
8145 			*i1 = tcp->tcp_second_timer_threshold;
8146 			return (sizeof (int));
8147 		case TCP_CONN_NOTIFY_THRESHOLD:
8148 			*i1 = tcp->tcp_first_ctimer_threshold;
8149 			return (sizeof (int));
8150 		case TCP_CONN_ABORT_THRESHOLD:
8151 			*i1 = tcp->tcp_second_ctimer_threshold;
8152 			return (sizeof (int));
8153 		case TCP_INIT_CWND:
8154 			*i1 = tcp->tcp_init_cwnd;
8155 			return (sizeof (int));
8156 		case TCP_KEEPALIVE_THRESHOLD:
8157 			*i1 = tcp->tcp_ka_interval;
8158 			return (sizeof (int));
8159 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
8160 			*i1 = tcp->tcp_ka_abort_thres;
8161 			return (sizeof (int));
8162 		case TCP_CORK:
8163 			*i1 = tcp->tcp_cork;
8164 			return (sizeof (int));
8165 		}
8166 		break;
8167 	case IPPROTO_IP:
8168 		if (connp->conn_family != AF_INET)
8169 			return (-1);
8170 		switch (name) {
8171 		case IP_OPTIONS:
8172 		case T_IP_OPTIONS:
8173 			/* Caller ensures enough space */
8174 			return (ip_opt_get_user(connp, ptr));
8175 		default:
8176 			break;
8177 		}
8178 		break;
8179 
8180 	case IPPROTO_IPV6:
8181 		/*
8182 		 * IPPROTO_IPV6 options are only supported for sockets
8183 		 * that are using IPv6 on the wire.
8184 		 */
8185 		if (connp->conn_ipversion != IPV6_VERSION) {
8186 			return (-1);
8187 		}
8188 		switch (name) {
8189 		case IPV6_PATHMTU:
8190 			if (tcp->tcp_state < TCPS_ESTABLISHED)
8191 				return (-1);
8192 			break;
8193 		}
8194 		break;
8195 	}
8196 	mutex_enter(&connp->conn_lock);
8197 	retval = conn_opt_get(&coas, level, name, ptr);
8198 	mutex_exit(&connp->conn_lock);
8199 	return (retval);
8200 }
8201 
8202 /*
8203  * TCP routine to get the values of options.
8204  */
8205 int
8206 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
8207 {
8208 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
8209 }
8210 
8211 /* returns UNIX error, the optlen is a value-result arg */
8212 int
8213 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
8214     void *optvalp, socklen_t *optlen, cred_t *cr)
8215 {
8216 	conn_t		*connp = (conn_t *)proto_handle;
8217 	squeue_t	*sqp = connp->conn_sqp;
8218 	int		error;
8219 	t_uscalar_t	max_optbuf_len;
8220 	void		*optvalp_buf;
8221 	int		len;
8222 
8223 	ASSERT(connp->conn_upper_handle != NULL);
8224 
8225 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
8226 	    tcp_opt_obj.odb_opt_des_arr,
8227 	    tcp_opt_obj.odb_opt_arr_cnt,
8228 	    B_FALSE, B_TRUE, cr);
8229 	if (error != 0) {
8230 		if (error < 0) {
8231 			error = proto_tlitosyserr(-error);
8232 		}
8233 		return (error);
8234 	}
8235 
8236 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
8237 
8238 	error = squeue_synch_enter(sqp, connp, NULL);
8239 	if (error == ENOMEM) {
8240 		kmem_free(optvalp_buf, max_optbuf_len);
8241 		return (ENOMEM);
8242 	}
8243 
8244 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
8245 	squeue_synch_exit(sqp, connp);
8246 
8247 	if (len == -1) {
8248 		kmem_free(optvalp_buf, max_optbuf_len);
8249 		return (EINVAL);
8250 	}
8251 
8252 	/*
8253 	 * update optlen and copy option value
8254 	 */
8255 	t_uscalar_t size = MIN(len, *optlen);
8256 
8257 	bcopy(optvalp_buf, optvalp, size);
8258 	bcopy(&size, optlen, sizeof (size));
8259 
8260 	kmem_free(optvalp_buf, max_optbuf_len);
8261 	return (0);
8262 }
8263 
8264 /*
8265  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
8266  * Parameters are assumed to be verified by the caller.
8267  */
8268 /* ARGSUSED */
8269 int
8270 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
8271     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
8272     void *thisdg_attrs, cred_t *cr)
8273 {
8274 	tcp_t	*tcp = connp->conn_tcp;
8275 	int	*i1 = (int *)invalp;
8276 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
8277 	boolean_t checkonly;
8278 	int	reterr;
8279 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8280 	conn_opt_arg_t	coas;
8281 
8282 	coas.coa_connp = connp;
8283 	coas.coa_ixa = connp->conn_ixa;
8284 	coas.coa_ipp = &connp->conn_xmit_ipp;
8285 	coas.coa_ancillary = B_FALSE;
8286 	coas.coa_changed = 0;
8287 
8288 	switch (optset_context) {
8289 	case SETFN_OPTCOM_CHECKONLY:
8290 		checkonly = B_TRUE;
8291 		/*
8292 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
8293 		 * inlen != 0 implies value supplied and
8294 		 * 	we have to "pretend" to set it.
8295 		 * inlen == 0 implies that there is no
8296 		 * 	value part in T_CHECK request and just validation
8297 		 * done elsewhere should be enough, we just return here.
8298 		 */
8299 		if (inlen == 0) {
8300 			*outlenp = 0;
8301 			return (0);
8302 		}
8303 		break;
8304 	case SETFN_OPTCOM_NEGOTIATE:
8305 		checkonly = B_FALSE;
8306 		break;
8307 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
8308 	case SETFN_CONN_NEGOTIATE:
8309 		checkonly = B_FALSE;
8310 		/*
8311 		 * Negotiating local and "association-related" options
8312 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
8313 		 * primitives is allowed by XTI, but we choose
8314 		 * to not implement this style negotiation for Internet
8315 		 * protocols (We interpret it is a must for OSI world but
8316 		 * optional for Internet protocols) for all options.
8317 		 * [ Will do only for the few options that enable test
8318 		 * suites that our XTI implementation of this feature
8319 		 * works for transports that do allow it ]
8320 		 */
8321 		if (!tcp_allow_connopt_set(level, name)) {
8322 			*outlenp = 0;
8323 			return (EINVAL);
8324 		}
8325 		break;
8326 	default:
8327 		/*
8328 		 * We should never get here
8329 		 */
8330 		*outlenp = 0;
8331 		return (EINVAL);
8332 	}
8333 
8334 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
8335 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
8336 
8337 	/*
8338 	 * For TCP, we should have no ancillary data sent down
8339 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
8340 	 * has to be zero.
8341 	 */
8342 	ASSERT(thisdg_attrs == NULL);
8343 
8344 	/*
8345 	 * For fixed length options, no sanity check
8346 	 * of passed in length is done. It is assumed *_optcom_req()
8347 	 * routines do the right thing.
8348 	 */
8349 	switch (level) {
8350 	case SOL_SOCKET:
8351 		switch (name) {
8352 		case SO_KEEPALIVE:
8353 			if (checkonly) {
8354 				/* check only case */
8355 				break;
8356 			}
8357 
8358 			if (!onoff) {
8359 				if (connp->conn_keepalive) {
8360 					if (tcp->tcp_ka_tid != 0) {
8361 						(void) TCP_TIMER_CANCEL(tcp,
8362 						    tcp->tcp_ka_tid);
8363 						tcp->tcp_ka_tid = 0;
8364 					}
8365 					connp->conn_keepalive = 0;
8366 				}
8367 				break;
8368 			}
8369 			if (!connp->conn_keepalive) {
8370 				/* Crank up the keepalive timer */
8371 				tcp->tcp_ka_last_intrvl = 0;
8372 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8373 				    tcp_keepalive_killer,
8374 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
8375 				connp->conn_keepalive = 1;
8376 			}
8377 			break;
8378 		case SO_SNDBUF: {
8379 			if (*i1 > tcps->tcps_max_buf) {
8380 				*outlenp = 0;
8381 				return (ENOBUFS);
8382 			}
8383 			if (checkonly)
8384 				break;
8385 
8386 			connp->conn_sndbuf = *i1;
8387 			if (tcps->tcps_snd_lowat_fraction != 0) {
8388 				connp->conn_sndlowat = connp->conn_sndbuf /
8389 				    tcps->tcps_snd_lowat_fraction;
8390 			}
8391 			(void) tcp_maxpsz_set(tcp, B_TRUE);
8392 			/*
8393 			 * If we are flow-controlled, recheck the condition.
8394 			 * There are apps that increase SO_SNDBUF size when
8395 			 * flow-controlled (EWOULDBLOCK), and expect the flow
8396 			 * control condition to be lifted right away.
8397 			 */
8398 			mutex_enter(&tcp->tcp_non_sq_lock);
8399 			if (tcp->tcp_flow_stopped &&
8400 			    TCP_UNSENT_BYTES(tcp) < connp->conn_sndbuf) {
8401 				tcp_clrqfull(tcp);
8402 			}
8403 			mutex_exit(&tcp->tcp_non_sq_lock);
8404 			*outlenp = inlen;
8405 			return (0);
8406 		}
8407 		case SO_RCVBUF:
8408 			if (*i1 > tcps->tcps_max_buf) {
8409 				*outlenp = 0;
8410 				return (ENOBUFS);
8411 			}
8412 			/* Silently ignore zero */
8413 			if (!checkonly && *i1 != 0) {
8414 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
8415 				(void) tcp_rwnd_set(tcp, *i1);
8416 			}
8417 			/*
8418 			 * XXX should we return the rwnd here
8419 			 * and tcp_opt_get ?
8420 			 */
8421 			*outlenp = inlen;
8422 			return (0);
8423 		case SO_SND_COPYAVOID:
8424 			if (!checkonly) {
8425 				if (tcp->tcp_loopback ||
8426 				    (tcp->tcp_kssl_ctx != NULL) ||
8427 				    (onoff != 1) || !tcp_zcopy_check(tcp)) {
8428 					*outlenp = 0;
8429 					return (EOPNOTSUPP);
8430 				}
8431 				tcp->tcp_snd_zcopy_aware = 1;
8432 			}
8433 			*outlenp = inlen;
8434 			return (0);
8435 		}
8436 		break;
8437 	case IPPROTO_TCP:
8438 		switch (name) {
8439 		case TCP_NODELAY:
8440 			if (!checkonly)
8441 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
8442 			break;
8443 		case TCP_NOTIFY_THRESHOLD:
8444 			if (!checkonly)
8445 				tcp->tcp_first_timer_threshold = *i1;
8446 			break;
8447 		case TCP_ABORT_THRESHOLD:
8448 			if (!checkonly)
8449 				tcp->tcp_second_timer_threshold = *i1;
8450 			break;
8451 		case TCP_CONN_NOTIFY_THRESHOLD:
8452 			if (!checkonly)
8453 				tcp->tcp_first_ctimer_threshold = *i1;
8454 			break;
8455 		case TCP_CONN_ABORT_THRESHOLD:
8456 			if (!checkonly)
8457 				tcp->tcp_second_ctimer_threshold = *i1;
8458 			break;
8459 		case TCP_RECVDSTADDR:
8460 			if (tcp->tcp_state > TCPS_LISTEN) {
8461 				*outlenp = 0;
8462 				return (EOPNOTSUPP);
8463 			}
8464 			/* Setting done in conn_opt_set */
8465 			break;
8466 		case TCP_INIT_CWND: {
8467 			uint32_t init_cwnd = *((uint32_t *)invalp);
8468 
8469 			if (checkonly)
8470 				break;
8471 
8472 			/*
8473 			 * Only allow socket with network configuration
8474 			 * privilege to set the initial cwnd to be larger
8475 			 * than allowed by RFC 3390.
8476 			 */
8477 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
8478 				tcp->tcp_init_cwnd = init_cwnd;
8479 				break;
8480 			}
8481 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
8482 				*outlenp = 0;
8483 				return (reterr);
8484 			}
8485 			if (init_cwnd > TCP_MAX_INIT_CWND) {
8486 				*outlenp = 0;
8487 				return (EINVAL);
8488 			}
8489 			tcp->tcp_init_cwnd = init_cwnd;
8490 			break;
8491 		}
8492 		case TCP_KEEPALIVE_THRESHOLD:
8493 			if (checkonly)
8494 				break;
8495 
8496 			if (*i1 < tcps->tcps_keepalive_interval_low ||
8497 			    *i1 > tcps->tcps_keepalive_interval_high) {
8498 				*outlenp = 0;
8499 				return (EINVAL);
8500 			}
8501 			if (*i1 != tcp->tcp_ka_interval) {
8502 				tcp->tcp_ka_interval = *i1;
8503 				/*
8504 				 * Check if we need to restart the
8505 				 * keepalive timer.
8506 				 */
8507 				if (tcp->tcp_ka_tid != 0) {
8508 					ASSERT(connp->conn_keepalive);
8509 					(void) TCP_TIMER_CANCEL(tcp,
8510 					    tcp->tcp_ka_tid);
8511 					tcp->tcp_ka_last_intrvl = 0;
8512 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
8513 					    tcp_keepalive_killer,
8514 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
8515 				}
8516 			}
8517 			break;
8518 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
8519 			if (!checkonly) {
8520 				if (*i1 <
8521 				    tcps->tcps_keepalive_abort_interval_low ||
8522 				    *i1 >
8523 				    tcps->tcps_keepalive_abort_interval_high) {
8524 					*outlenp = 0;
8525 					return (EINVAL);
8526 				}
8527 				tcp->tcp_ka_abort_thres = *i1;
8528 			}
8529 			break;
8530 		case TCP_CORK:
8531 			if (!checkonly) {
8532 				/*
8533 				 * if tcp->tcp_cork was set and is now
8534 				 * being unset, we have to make sure that
8535 				 * the remaining data gets sent out. Also
8536 				 * unset tcp->tcp_cork so that tcp_wput_data()
8537 				 * can send data even if it is less than mss
8538 				 */
8539 				if (tcp->tcp_cork && onoff == 0 &&
8540 				    tcp->tcp_unsent > 0) {
8541 					tcp->tcp_cork = B_FALSE;
8542 					tcp_wput_data(tcp, NULL, B_FALSE);
8543 				}
8544 				tcp->tcp_cork = onoff;
8545 			}
8546 			break;
8547 		default:
8548 			break;
8549 		}
8550 		break;
8551 	case IPPROTO_IP:
8552 		if (connp->conn_family != AF_INET) {
8553 			*outlenp = 0;
8554 			return (EINVAL);
8555 		}
8556 		switch (name) {
8557 		case IP_SEC_OPT:
8558 			/*
8559 			 * We should not allow policy setting after
8560 			 * we start listening for connections.
8561 			 */
8562 			if (tcp->tcp_state == TCPS_LISTEN) {
8563 				return (EINVAL);
8564 			}
8565 			break;
8566 		}
8567 		break;
8568 	case IPPROTO_IPV6:
8569 		/*
8570 		 * IPPROTO_IPV6 options are only supported for sockets
8571 		 * that are using IPv6 on the wire.
8572 		 */
8573 		if (connp->conn_ipversion != IPV6_VERSION) {
8574 			*outlenp = 0;
8575 			return (EINVAL);
8576 		}
8577 
8578 		switch (name) {
8579 		case IPV6_RECVPKTINFO:
8580 			if (!checkonly) {
8581 				/* Force it to be sent up with the next msg */
8582 				tcp->tcp_recvifindex = 0;
8583 			}
8584 			break;
8585 		case IPV6_RECVTCLASS:
8586 			if (!checkonly) {
8587 				/* Force it to be sent up with the next msg */
8588 				tcp->tcp_recvtclass = 0xffffffffU;
8589 			}
8590 			break;
8591 		case IPV6_RECVHOPLIMIT:
8592 			if (!checkonly) {
8593 				/* Force it to be sent up with the next msg */
8594 				tcp->tcp_recvhops = 0xffffffffU;
8595 			}
8596 			break;
8597 		case IPV6_PKTINFO:
8598 			/* This is an extra check for TCP */
8599 			if (inlen == sizeof (struct in6_pktinfo)) {
8600 				struct in6_pktinfo *pkti;
8601 
8602 				pkti = (struct in6_pktinfo *)invalp;
8603 				/*
8604 				 * RFC 3542 states that ipi6_addr must be
8605 				 * the unspecified address when setting the
8606 				 * IPV6_PKTINFO sticky socket option on a
8607 				 * TCP socket.
8608 				 */
8609 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
8610 					return (EINVAL);
8611 			}
8612 			break;
8613 		case IPV6_SEC_OPT:
8614 			/*
8615 			 * We should not allow policy setting after
8616 			 * we start listening for connections.
8617 			 */
8618 			if (tcp->tcp_state == TCPS_LISTEN) {
8619 				return (EINVAL);
8620 			}
8621 			break;
8622 		}
8623 		break;
8624 	}
8625 	reterr = conn_opt_set(&coas, level, name, inlen, invalp,
8626 	    checkonly, cr);
8627 	if (reterr != 0) {
8628 		*outlenp = 0;
8629 		return (reterr);
8630 	}
8631 
8632 	/*
8633 	 * Common case of OK return with outval same as inval
8634 	 */
8635 	if (invalp != outvalp) {
8636 		/* don't trust bcopy for identical src/dst */
8637 		(void) bcopy(invalp, outvalp, inlen);
8638 	}
8639 	*outlenp = inlen;
8640 
8641 	if (coas.coa_changed & COA_HEADER_CHANGED) {
8642 		/* If we are connected we rebuilt the headers */
8643 		if (!IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6) &&
8644 		    !IN6_IS_ADDR_V4MAPPED_ANY(&connp->conn_faddr_v6)) {
8645 			reterr = tcp_build_hdrs(tcp);
8646 			if (reterr != 0)
8647 				return (reterr);
8648 		}
8649 	}
8650 	if (coas.coa_changed & COA_ROUTE_CHANGED) {
8651 		in6_addr_t nexthop;
8652 
8653 		/*
8654 		 * If we are connected we re-cache the information.
8655 		 * We ignore errors to preserve BSD behavior.
8656 		 * Note that we don't redo IPsec policy lookup here
8657 		 * since the final destination (or source) didn't change.
8658 		 */
8659 		ip_attr_nexthop(&connp->conn_xmit_ipp, connp->conn_ixa,
8660 		    &connp->conn_faddr_v6, &nexthop);
8661 
8662 		if (!IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6) &&
8663 		    !IN6_IS_ADDR_V4MAPPED_ANY(&connp->conn_faddr_v6)) {
8664 			(void) ip_attr_connect(connp, connp->conn_ixa,
8665 			    &connp->conn_laddr_v6, &connp->conn_faddr_v6,
8666 			    &nexthop, connp->conn_fport, NULL, NULL,
8667 			    IPDF_VERIFY_DST);
8668 		}
8669 	}
8670 	if ((coas.coa_changed & COA_SNDBUF_CHANGED) && !IPCL_IS_NONSTR(connp)) {
8671 		connp->conn_wq->q_hiwat = connp->conn_sndbuf;
8672 	}
8673 	if (coas.coa_changed & COA_WROFF_CHANGED) {
8674 		connp->conn_wroff = connp->conn_ht_iphc_allocated +
8675 		    tcps->tcps_wroff_xtra;
8676 		(void) proto_set_tx_wroff(connp->conn_rq, connp,
8677 		    connp->conn_wroff);
8678 	}
8679 	if (coas.coa_changed & COA_OOBINLINE_CHANGED) {
8680 		if (IPCL_IS_NONSTR(connp))
8681 			proto_set_rx_oob_opt(connp, onoff);
8682 	}
8683 	return (0);
8684 }
8685 
8686 /* ARGSUSED */
8687 int
8688 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
8689     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
8690     void *thisdg_attrs, cred_t *cr)
8691 {
8692 	conn_t	*connp =  Q_TO_CONN(q);
8693 
8694 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
8695 	    outlenp, outvalp, thisdg_attrs, cr));
8696 }
8697 
8698 int
8699 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
8700     const void *optvalp, socklen_t optlen, cred_t *cr)
8701 {
8702 	conn_t		*connp = (conn_t *)proto_handle;
8703 	squeue_t	*sqp = connp->conn_sqp;
8704 	int		error;
8705 
8706 	ASSERT(connp->conn_upper_handle != NULL);
8707 	/*
8708 	 * Entering the squeue synchronously can result in a context switch,
8709 	 * which can cause a rather sever performance degradation. So we try to
8710 	 * handle whatever options we can without entering the squeue.
8711 	 */
8712 	if (level == IPPROTO_TCP) {
8713 		switch (option_name) {
8714 		case TCP_NODELAY:
8715 			if (optlen != sizeof (int32_t))
8716 				return (EINVAL);
8717 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
8718 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
8719 			    connp->conn_tcp->tcp_mss;
8720 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
8721 			return (0);
8722 		default:
8723 			break;
8724 		}
8725 	}
8726 
8727 	error = squeue_synch_enter(sqp, connp, NULL);
8728 	if (error == ENOMEM) {
8729 		return (ENOMEM);
8730 	}
8731 
8732 	error = proto_opt_check(level, option_name, optlen, NULL,
8733 	    tcp_opt_obj.odb_opt_des_arr,
8734 	    tcp_opt_obj.odb_opt_arr_cnt,
8735 	    B_TRUE, B_FALSE, cr);
8736 
8737 	if (error != 0) {
8738 		if (error < 0) {
8739 			error = proto_tlitosyserr(-error);
8740 		}
8741 		squeue_synch_exit(sqp, connp);
8742 		return (error);
8743 	}
8744 
8745 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
8746 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
8747 	    NULL, cr);
8748 	squeue_synch_exit(sqp, connp);
8749 
8750 	ASSERT(error >= 0);
8751 
8752 	return (error);
8753 }
8754 
8755 /*
8756  * Build/update the tcp header template (in conn_ht_iphc) based on
8757  * conn_xmit_ipp. The headers include ip6_t, any extension
8758  * headers, and the maximum size tcp header (to avoid reallocation
8759  * on the fly for additional tcp options).
8760  *
8761  * Assumes the caller has already set conn_{faddr,laddr,fport,lport,flowinfo}.
8762  * Returns failure if can't allocate memory.
8763  */
8764 static int
8765 tcp_build_hdrs(tcp_t *tcp)
8766 {
8767 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8768 	conn_t		*connp = tcp->tcp_connp;
8769 	char		buf[TCP_MAX_HDR_LENGTH];
8770 	uint_t		buflen;
8771 	uint_t		ulplen = TCP_MIN_HEADER_LENGTH;
8772 	uint_t		extralen = TCP_MAX_TCP_OPTIONS_LENGTH;
8773 	tcpha_t		*tcpha;
8774 	uint32_t	cksum;
8775 	int		error;
8776 
8777 	/*
8778 	 * We might be called after the connection is set up, and we might
8779 	 * have TS options already in the TCP header. Thus we  save any
8780 	 * existing tcp header.
8781 	 */
8782 	buflen = connp->conn_ht_ulp_len;
8783 	if (buflen != 0) {
8784 		bcopy(connp->conn_ht_ulp, buf, buflen);
8785 		extralen -= buflen - ulplen;
8786 		ulplen = buflen;
8787 	}
8788 
8789 	/* Grab lock to satisfy ASSERT; TCP is serialized using squeue */
8790 	mutex_enter(&connp->conn_lock);
8791 	error = conn_build_hdr_template(connp, ulplen, extralen,
8792 	    &connp->conn_laddr_v6, &connp->conn_faddr_v6, connp->conn_flowinfo);
8793 	mutex_exit(&connp->conn_lock);
8794 	if (error != 0)
8795 		return (error);
8796 
8797 	/*
8798 	 * Any routing header/option has been massaged. The checksum difference
8799 	 * is stored in conn_sum for later use.
8800 	 */
8801 	tcpha = (tcpha_t *)connp->conn_ht_ulp;
8802 	tcp->tcp_tcpha = tcpha;
8803 
8804 	/* restore any old tcp header */
8805 	if (buflen != 0) {
8806 		bcopy(buf, connp->conn_ht_ulp, buflen);
8807 	} else {
8808 		tcpha->tha_sum = 0;
8809 		tcpha->tha_urp = 0;
8810 		tcpha->tha_ack = 0;
8811 		tcpha->tha_offset_and_reserved = (5 << 4);
8812 		tcpha->tha_lport = connp->conn_lport;
8813 		tcpha->tha_fport = connp->conn_fport;
8814 	}
8815 
8816 	/*
8817 	 * IP wants our header length in the checksum field to
8818 	 * allow it to perform a single pseudo-header+checksum
8819 	 * calculation on behalf of TCP.
8820 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8821 	 */
8822 	cksum = sizeof (tcpha_t) + connp->conn_sum;
8823 	cksum = (cksum >> 16) + (cksum & 0xFFFF);
8824 	ASSERT(cksum < 0x10000);
8825 	tcpha->tha_sum = htons(cksum);
8826 
8827 	if (connp->conn_ipversion == IPV4_VERSION)
8828 		tcp->tcp_ipha = (ipha_t *)connp->conn_ht_iphc;
8829 	else
8830 		tcp->tcp_ip6h = (ip6_t *)connp->conn_ht_iphc;
8831 
8832 	if (connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra >
8833 	    connp->conn_wroff) {
8834 		connp->conn_wroff = connp->conn_ht_iphc_allocated +
8835 		    tcps->tcps_wroff_xtra;
8836 		(void) proto_set_tx_wroff(connp->conn_rq, connp,
8837 		    connp->conn_wroff);
8838 	}
8839 	return (0);
8840 }
8841 
8842 /* Get callback routine passed to nd_load by tcp_param_register */
8843 /* ARGSUSED */
8844 static int
8845 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
8846 {
8847 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
8848 
8849 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
8850 	return (0);
8851 }
8852 
8853 /*
8854  * Walk through the param array specified registering each element with the
8855  * named dispatch handler.
8856  */
8857 static boolean_t
8858 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
8859 {
8860 	for (; cnt-- > 0; tcppa++) {
8861 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
8862 			if (!nd_load(ndp, tcppa->tcp_param_name,
8863 			    tcp_param_get, tcp_param_set,
8864 			    (caddr_t)tcppa)) {
8865 				nd_free(ndp);
8866 				return (B_FALSE);
8867 			}
8868 		}
8869 	}
8870 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
8871 	    KM_SLEEP);
8872 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
8873 	    sizeof (tcpparam_t));
8874 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
8875 	    tcp_param_get, tcp_param_set_aligned,
8876 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
8877 		nd_free(ndp);
8878 		return (B_FALSE);
8879 	}
8880 	if (!nd_load(ndp, "tcp_extra_priv_ports",
8881 	    tcp_extra_priv_ports_get, NULL, NULL)) {
8882 		nd_free(ndp);
8883 		return (B_FALSE);
8884 	}
8885 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
8886 	    NULL, tcp_extra_priv_ports_add, NULL)) {
8887 		nd_free(ndp);
8888 		return (B_FALSE);
8889 	}
8890 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
8891 	    NULL, tcp_extra_priv_ports_del, NULL)) {
8892 		nd_free(ndp);
8893 		return (B_FALSE);
8894 	}
8895 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
8896 	    tcp_1948_phrase_set, NULL)) {
8897 		nd_free(ndp);
8898 		return (B_FALSE);
8899 	}
8900 
8901 
8902 	if (!nd_load(ndp, "tcp_listener_limit_conf",
8903 	    tcp_listener_conf_get, NULL, NULL)) {
8904 		nd_free(ndp);
8905 		return (B_FALSE);
8906 	}
8907 	if (!nd_load(ndp, "tcp_listener_limit_conf_add",
8908 	    NULL, tcp_listener_conf_add, NULL)) {
8909 		nd_free(ndp);
8910 		return (B_FALSE);
8911 	}
8912 	if (!nd_load(ndp, "tcp_listener_limit_conf_del",
8913 	    NULL, tcp_listener_conf_del, NULL)) {
8914 		nd_free(ndp);
8915 		return (B_FALSE);
8916 	}
8917 
8918 	/*
8919 	 * Dummy ndd variables - only to convey obsolescence information
8920 	 * through printing of their name (no get or set routines)
8921 	 * XXX Remove in future releases ?
8922 	 */
8923 	if (!nd_load(ndp,
8924 	    "tcp_close_wait_interval(obsoleted - "
8925 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
8926 		nd_free(ndp);
8927 		return (B_FALSE);
8928 	}
8929 	return (B_TRUE);
8930 }
8931 
8932 /* ndd set routine for tcp_wroff_xtra. */
8933 /* ARGSUSED */
8934 static int
8935 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
8936     cred_t *cr)
8937 {
8938 	long new_value;
8939 	tcpparam_t *tcppa = (tcpparam_t *)cp;
8940 
8941 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
8942 	    new_value < tcppa->tcp_param_min ||
8943 	    new_value > tcppa->tcp_param_max) {
8944 		return (EINVAL);
8945 	}
8946 	/*
8947 	 * Need to make sure new_value is a multiple of 4.  If it is not,
8948 	 * round it up.  For future 64 bit requirement, we actually make it
8949 	 * a multiple of 8.
8950 	 */
8951 	if (new_value & 0x7) {
8952 		new_value = (new_value & ~0x7) + 0x8;
8953 	}
8954 	tcppa->tcp_param_val = new_value;
8955 	return (0);
8956 }
8957 
8958 /* Set callback routine passed to nd_load by tcp_param_register */
8959 /* ARGSUSED */
8960 static int
8961 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
8962 {
8963 	long	new_value;
8964 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
8965 
8966 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
8967 	    new_value < tcppa->tcp_param_min ||
8968 	    new_value > tcppa->tcp_param_max) {
8969 		return (EINVAL);
8970 	}
8971 	tcppa->tcp_param_val = new_value;
8972 	return (0);
8973 }
8974 
8975 static void
8976 tcp_reass_timer(void *arg)
8977 {
8978 	conn_t *connp = (conn_t *)arg;
8979 	tcp_t *tcp = connp->conn_tcp;
8980 
8981 	tcp->tcp_reass_tid = 0;
8982 	if (tcp->tcp_reass_head == NULL)
8983 		return;
8984 	ASSERT(tcp->tcp_reass_tail != NULL);
8985 	tcp_sack_remove(tcp->tcp_sack_list, TCP_REASS_END(tcp->tcp_reass_tail),
8986 	    &tcp->tcp_num_sack_blk);
8987 	tcp_close_mpp(&tcp->tcp_reass_head);
8988 	tcp->tcp_reass_tail = NULL;
8989 }
8990 
8991 /*
8992  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
8993  * is filled, return as much as we can.  The message passed in may be
8994  * multi-part, chained using b_cont.  "start" is the starting sequence
8995  * number for this piece.
8996  */
8997 static mblk_t *
8998 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
8999 {
9000 	uint32_t	end;
9001 	mblk_t		*mp1;
9002 	mblk_t		*mp2;
9003 	mblk_t		*next_mp;
9004 	uint32_t	u1;
9005 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9006 
9007 
9008 	/* Walk through all the new pieces. */
9009 	do {
9010 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
9011 		    (uintptr_t)INT_MAX);
9012 		end = start + (int)(mp->b_wptr - mp->b_rptr);
9013 		next_mp = mp->b_cont;
9014 		if (start == end) {
9015 			/* Empty.  Blast it. */
9016 			freeb(mp);
9017 			continue;
9018 		}
9019 		mp->b_cont = NULL;
9020 		TCP_REASS_SET_SEQ(mp, start);
9021 		TCP_REASS_SET_END(mp, end);
9022 		mp1 = tcp->tcp_reass_tail;
9023 		if (!mp1) {
9024 			tcp->tcp_reass_tail = mp;
9025 			tcp->tcp_reass_head = mp;
9026 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
9027 			UPDATE_MIB(&tcps->tcps_mib,
9028 			    tcpInDataUnorderBytes, end - start);
9029 			continue;
9030 		}
9031 		/* New stuff completely beyond tail? */
9032 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
9033 			/* Link it on end. */
9034 			mp1->b_cont = mp;
9035 			tcp->tcp_reass_tail = mp;
9036 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
9037 			UPDATE_MIB(&tcps->tcps_mib,
9038 			    tcpInDataUnorderBytes, end - start);
9039 			continue;
9040 		}
9041 		mp1 = tcp->tcp_reass_head;
9042 		u1 = TCP_REASS_SEQ(mp1);
9043 		/* New stuff at the front? */
9044 		if (SEQ_LT(start, u1)) {
9045 			/* Yes... Check for overlap. */
9046 			mp->b_cont = mp1;
9047 			tcp->tcp_reass_head = mp;
9048 			tcp_reass_elim_overlap(tcp, mp);
9049 			continue;
9050 		}
9051 		/*
9052 		 * The new piece fits somewhere between the head and tail.
9053 		 * We find our slot, where mp1 precedes us and mp2 trails.
9054 		 */
9055 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
9056 			u1 = TCP_REASS_SEQ(mp2);
9057 			if (SEQ_LEQ(start, u1))
9058 				break;
9059 		}
9060 		/* Link ourselves in */
9061 		mp->b_cont = mp2;
9062 		mp1->b_cont = mp;
9063 
9064 		/* Trim overlap with following mblk(s) first */
9065 		tcp_reass_elim_overlap(tcp, mp);
9066 
9067 		/* Trim overlap with preceding mblk */
9068 		tcp_reass_elim_overlap(tcp, mp1);
9069 
9070 	} while (start = end, mp = next_mp);
9071 	mp1 = tcp->tcp_reass_head;
9072 	/* Anything ready to go? */
9073 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
9074 		return (NULL);
9075 	/* Eat what we can off the queue */
9076 	for (;;) {
9077 		mp = mp1->b_cont;
9078 		end = TCP_REASS_END(mp1);
9079 		TCP_REASS_SET_SEQ(mp1, 0);
9080 		TCP_REASS_SET_END(mp1, 0);
9081 		if (!mp) {
9082 			tcp->tcp_reass_tail = NULL;
9083 			break;
9084 		}
9085 		if (end != TCP_REASS_SEQ(mp)) {
9086 			mp1->b_cont = NULL;
9087 			break;
9088 		}
9089 		mp1 = mp;
9090 	}
9091 	mp1 = tcp->tcp_reass_head;
9092 	tcp->tcp_reass_head = mp;
9093 	return (mp1);
9094 }
9095 
9096 /* Eliminate any overlap that mp may have over later mblks */
9097 static void
9098 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
9099 {
9100 	uint32_t	end;
9101 	mblk_t		*mp1;
9102 	uint32_t	u1;
9103 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9104 
9105 	end = TCP_REASS_END(mp);
9106 	while ((mp1 = mp->b_cont) != NULL) {
9107 		u1 = TCP_REASS_SEQ(mp1);
9108 		if (!SEQ_GT(end, u1))
9109 			break;
9110 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
9111 			mp->b_wptr -= end - u1;
9112 			TCP_REASS_SET_END(mp, u1);
9113 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
9114 			UPDATE_MIB(&tcps->tcps_mib,
9115 			    tcpInDataPartDupBytes, end - u1);
9116 			break;
9117 		}
9118 		mp->b_cont = mp1->b_cont;
9119 		TCP_REASS_SET_SEQ(mp1, 0);
9120 		TCP_REASS_SET_END(mp1, 0);
9121 		freeb(mp1);
9122 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
9123 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
9124 	}
9125 	if (!mp1)
9126 		tcp->tcp_reass_tail = mp;
9127 }
9128 
9129 static uint_t
9130 tcp_rwnd_reopen(tcp_t *tcp)
9131 {
9132 	uint_t ret = 0;
9133 	uint_t thwin;
9134 	conn_t *connp = tcp->tcp_connp;
9135 
9136 	/* Learn the latest rwnd information that we sent to the other side. */
9137 	thwin = ((uint_t)ntohs(tcp->tcp_tcpha->tha_win))
9138 	    << tcp->tcp_rcv_ws;
9139 	/* This is peer's calculated send window (our receive window). */
9140 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
9141 	/*
9142 	 * Increase the receive window to max.  But we need to do receiver
9143 	 * SWS avoidance.  This means that we need to check the increase of
9144 	 * of receive window is at least 1 MSS.
9145 	 */
9146 	if (connp->conn_rcvbuf - thwin >= tcp->tcp_mss) {
9147 		/*
9148 		 * If the window that the other side knows is less than max
9149 		 * deferred acks segments, send an update immediately.
9150 		 */
9151 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
9152 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
9153 			ret = TH_ACK_NEEDED;
9154 		}
9155 		tcp->tcp_rwnd = connp->conn_rcvbuf;
9156 	}
9157 	return (ret);
9158 }
9159 
9160 /*
9161  * Send up all messages queued on tcp_rcv_list.
9162  */
9163 static uint_t
9164 tcp_rcv_drain(tcp_t *tcp)
9165 {
9166 	mblk_t *mp;
9167 	uint_t ret = 0;
9168 #ifdef DEBUG
9169 	uint_t cnt = 0;
9170 #endif
9171 	queue_t	*q = tcp->tcp_connp->conn_rq;
9172 
9173 	/* Can't drain on an eager connection */
9174 	if (tcp->tcp_listener != NULL)
9175 		return (ret);
9176 
9177 	/* Can't be a non-STREAMS connection */
9178 	ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
9179 
9180 	/* No need for the push timer now. */
9181 	if (tcp->tcp_push_tid != 0) {
9182 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
9183 		tcp->tcp_push_tid = 0;
9184 	}
9185 
9186 	/*
9187 	 * Handle two cases here: we are currently fused or we were
9188 	 * previously fused and have some urgent data to be delivered
9189 	 * upstream.  The latter happens because we either ran out of
9190 	 * memory or were detached and therefore sending the SIGURG was
9191 	 * deferred until this point.  In either case we pass control
9192 	 * over to tcp_fuse_rcv_drain() since it may need to complete
9193 	 * some work.
9194 	 */
9195 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
9196 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
9197 		    tcp->tcp_fused_sigurg_mp != NULL);
9198 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
9199 		    &tcp->tcp_fused_sigurg_mp))
9200 			return (ret);
9201 	}
9202 
9203 	while ((mp = tcp->tcp_rcv_list) != NULL) {
9204 		tcp->tcp_rcv_list = mp->b_next;
9205 		mp->b_next = NULL;
9206 #ifdef DEBUG
9207 		cnt += msgdsize(mp);
9208 #endif
9209 		/* Does this need SSL processing first? */
9210 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
9211 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
9212 			    mblk_t *, mp);
9213 			tcp_kssl_input(tcp, mp, NULL);
9214 			continue;
9215 		}
9216 		putnext(q, mp);
9217 	}
9218 #ifdef DEBUG
9219 	ASSERT(cnt == tcp->tcp_rcv_cnt);
9220 #endif
9221 	tcp->tcp_rcv_last_head = NULL;
9222 	tcp->tcp_rcv_last_tail = NULL;
9223 	tcp->tcp_rcv_cnt = 0;
9224 
9225 	if (canputnext(q))
9226 		return (tcp_rwnd_reopen(tcp));
9227 
9228 	return (ret);
9229 }
9230 
9231 /*
9232  * Queue data on tcp_rcv_list which is a b_next chain.
9233  * tcp_rcv_last_head/tail is the last element of this chain.
9234  * Each element of the chain is a b_cont chain.
9235  *
9236  * M_DATA messages are added to the current element.
9237  * Other messages are added as new (b_next) elements.
9238  */
9239 void
9240 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len, cred_t *cr)
9241 {
9242 	ASSERT(seg_len == msgdsize(mp));
9243 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
9244 
9245 	if (is_system_labeled()) {
9246 		ASSERT(cr != NULL || msg_getcred(mp, NULL) != NULL);
9247 		/*
9248 		 * Provide for protocols above TCP such as RPC. NOPID leaves
9249 		 * db_cpid unchanged.
9250 		 * The cred could have already been set.
9251 		 */
9252 		if (cr != NULL)
9253 			mblk_setcred(mp, cr, NOPID);
9254 	}
9255 
9256 	if (tcp->tcp_rcv_list == NULL) {
9257 		ASSERT(tcp->tcp_rcv_last_head == NULL);
9258 		tcp->tcp_rcv_list = mp;
9259 		tcp->tcp_rcv_last_head = mp;
9260 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
9261 		tcp->tcp_rcv_last_tail->b_cont = mp;
9262 	} else {
9263 		tcp->tcp_rcv_last_head->b_next = mp;
9264 		tcp->tcp_rcv_last_head = mp;
9265 	}
9266 
9267 	while (mp->b_cont)
9268 		mp = mp->b_cont;
9269 
9270 	tcp->tcp_rcv_last_tail = mp;
9271 	tcp->tcp_rcv_cnt += seg_len;
9272 	tcp->tcp_rwnd -= seg_len;
9273 }
9274 
9275 /* The minimum of smoothed mean deviation in RTO calculation. */
9276 #define	TCP_SD_MIN	400
9277 
9278 /*
9279  * Set RTO for this connection.  The formula is from Jacobson and Karels'
9280  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
9281  * are the same as those in Appendix A.2 of that paper.
9282  *
9283  * m = new measurement
9284  * sa = smoothed RTT average (8 * average estimates).
9285  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
9286  */
9287 static void
9288 tcp_set_rto(tcp_t *tcp, clock_t rtt)
9289 {
9290 	long m = TICK_TO_MSEC(rtt);
9291 	clock_t sa = tcp->tcp_rtt_sa;
9292 	clock_t sv = tcp->tcp_rtt_sd;
9293 	clock_t rto;
9294 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9295 
9296 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
9297 	tcp->tcp_rtt_update++;
9298 
9299 	/* tcp_rtt_sa is not 0 means this is a new sample. */
9300 	if (sa != 0) {
9301 		/*
9302 		 * Update average estimator:
9303 		 *	new rtt = 7/8 old rtt + 1/8 Error
9304 		 */
9305 
9306 		/* m is now Error in estimate. */
9307 		m -= sa >> 3;
9308 		if ((sa += m) <= 0) {
9309 			/*
9310 			 * Don't allow the smoothed average to be negative.
9311 			 * We use 0 to denote reinitialization of the
9312 			 * variables.
9313 			 */
9314 			sa = 1;
9315 		}
9316 
9317 		/*
9318 		 * Update deviation estimator:
9319 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
9320 		 */
9321 		if (m < 0)
9322 			m = -m;
9323 		m -= sv >> 2;
9324 		sv += m;
9325 	} else {
9326 		/*
9327 		 * This follows BSD's implementation.  So the reinitialized
9328 		 * RTO is 3 * m.  We cannot go less than 2 because if the
9329 		 * link is bandwidth dominated, doubling the window size
9330 		 * during slow start means doubling the RTT.  We want to be
9331 		 * more conservative when we reinitialize our estimates.  3
9332 		 * is just a convenient number.
9333 		 */
9334 		sa = m << 3;
9335 		sv = m << 1;
9336 	}
9337 	if (sv < TCP_SD_MIN) {
9338 		/*
9339 		 * We do not know that if sa captures the delay ACK
9340 		 * effect as in a long train of segments, a receiver
9341 		 * does not delay its ACKs.  So set the minimum of sv
9342 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
9343 		 * of BSD DATO.  That means the minimum of mean
9344 		 * deviation is 100 ms.
9345 		 *
9346 		 */
9347 		sv = TCP_SD_MIN;
9348 	}
9349 	tcp->tcp_rtt_sa = sa;
9350 	tcp->tcp_rtt_sd = sv;
9351 	/*
9352 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
9353 	 *
9354 	 * Add tcp_rexmit_interval extra in case of extreme environment
9355 	 * where the algorithm fails to work.  The default value of
9356 	 * tcp_rexmit_interval_extra should be 0.
9357 	 *
9358 	 * As we use a finer grained clock than BSD and update
9359 	 * RTO for every ACKs, add in another .25 of RTT to the
9360 	 * deviation of RTO to accomodate burstiness of 1/4 of
9361 	 * window size.
9362 	 */
9363 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
9364 
9365 	if (rto > tcps->tcps_rexmit_interval_max) {
9366 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
9367 	} else if (rto < tcps->tcps_rexmit_interval_min) {
9368 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
9369 	} else {
9370 		tcp->tcp_rto = rto;
9371 	}
9372 
9373 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
9374 	tcp->tcp_timer_backoff = 0;
9375 }
9376 
9377 /*
9378  * tcp_get_seg_mp() is called to get the pointer to a segment in the
9379  * send queue which starts at the given sequence number. If the given
9380  * sequence number is equal to last valid sequence number (tcp_snxt), the
9381  * returned mblk is the last valid mblk, and off is set to the length of
9382  * that mblk.
9383  *
9384  * send queue which starts at the given seq. no.
9385  *
9386  * Parameters:
9387  *	tcp_t *tcp: the tcp instance pointer.
9388  *	uint32_t seq: the starting seq. no of the requested segment.
9389  *	int32_t *off: after the execution, *off will be the offset to
9390  *		the returned mblk which points to the requested seq no.
9391  *		It is the caller's responsibility to send in a non-null off.
9392  *
9393  * Return:
9394  *	A mblk_t pointer pointing to the requested segment in send queue.
9395  */
9396 static mblk_t *
9397 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
9398 {
9399 	int32_t	cnt;
9400 	mblk_t	*mp;
9401 
9402 	/* Defensive coding.  Make sure we don't send incorrect data. */
9403 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GT(seq, tcp->tcp_snxt))
9404 		return (NULL);
9405 
9406 	cnt = seq - tcp->tcp_suna;
9407 	mp = tcp->tcp_xmit_head;
9408 	while (cnt > 0 && mp != NULL) {
9409 		cnt -= mp->b_wptr - mp->b_rptr;
9410 		if (cnt <= 0) {
9411 			cnt += mp->b_wptr - mp->b_rptr;
9412 			break;
9413 		}
9414 		mp = mp->b_cont;
9415 	}
9416 	ASSERT(mp != NULL);
9417 	*off = cnt;
9418 	return (mp);
9419 }
9420 
9421 /*
9422  * This function handles all retransmissions if SACK is enabled for this
9423  * connection.  First it calculates how many segments can be retransmitted
9424  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
9425  * segments.  A segment is eligible if sack_cnt for that segment is greater
9426  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
9427  * all eligible segments, it checks to see if TCP can send some new segments
9428  * (fast recovery).  If it can, set the appropriate flag for tcp_input_data().
9429  *
9430  * Parameters:
9431  *	tcp_t *tcp: the tcp structure of the connection.
9432  *	uint_t *flags: in return, appropriate value will be set for
9433  *	tcp_input_data().
9434  */
9435 static void
9436 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
9437 {
9438 	notsack_blk_t	*notsack_blk;
9439 	int32_t		usable_swnd;
9440 	int32_t		mss;
9441 	uint32_t	seg_len;
9442 	mblk_t		*xmit_mp;
9443 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9444 
9445 	ASSERT(tcp->tcp_sack_info != NULL);
9446 	ASSERT(tcp->tcp_notsack_list != NULL);
9447 	ASSERT(tcp->tcp_rexmit == B_FALSE);
9448 
9449 	/* Defensive coding in case there is a bug... */
9450 	if (tcp->tcp_notsack_list == NULL) {
9451 		return;
9452 	}
9453 	notsack_blk = tcp->tcp_notsack_list;
9454 	mss = tcp->tcp_mss;
9455 
9456 	/*
9457 	 * Limit the num of outstanding data in the network to be
9458 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
9459 	 */
9460 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
9461 
9462 	/* At least retransmit 1 MSS of data. */
9463 	if (usable_swnd <= 0) {
9464 		usable_swnd = mss;
9465 	}
9466 
9467 	/* Make sure no new RTT samples will be taken. */
9468 	tcp->tcp_csuna = tcp->tcp_snxt;
9469 
9470 	notsack_blk = tcp->tcp_notsack_list;
9471 	while (usable_swnd > 0) {
9472 		mblk_t		*snxt_mp, *tmp_mp;
9473 		tcp_seq		begin = tcp->tcp_sack_snxt;
9474 		tcp_seq		end;
9475 		int32_t		off;
9476 
9477 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
9478 			if (SEQ_GT(notsack_blk->end, begin) &&
9479 			    (notsack_blk->sack_cnt >=
9480 			    tcps->tcps_dupack_fast_retransmit)) {
9481 				end = notsack_blk->end;
9482 				if (SEQ_LT(begin, notsack_blk->begin)) {
9483 					begin = notsack_blk->begin;
9484 				}
9485 				break;
9486 			}
9487 		}
9488 		/*
9489 		 * All holes are filled.  Manipulate tcp_cwnd to send more
9490 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
9491 		 * set to tcp_cwnd_ssthresh.
9492 		 */
9493 		if (notsack_blk == NULL) {
9494 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
9495 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
9496 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
9497 				ASSERT(tcp->tcp_cwnd > 0);
9498 				return;
9499 			} else {
9500 				usable_swnd = usable_swnd / mss;
9501 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
9502 				    MAX(usable_swnd * mss, mss);
9503 				*flags |= TH_XMIT_NEEDED;
9504 				return;
9505 			}
9506 		}
9507 
9508 		/*
9509 		 * Note that we may send more than usable_swnd allows here
9510 		 * because of round off, but no more than 1 MSS of data.
9511 		 */
9512 		seg_len = end - begin;
9513 		if (seg_len > mss)
9514 			seg_len = mss;
9515 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
9516 		ASSERT(snxt_mp != NULL);
9517 		/* This should not happen.  Defensive coding again... */
9518 		if (snxt_mp == NULL) {
9519 			return;
9520 		}
9521 
9522 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
9523 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
9524 		if (xmit_mp == NULL)
9525 			return;
9526 
9527 		usable_swnd -= seg_len;
9528 		tcp->tcp_pipe += seg_len;
9529 		tcp->tcp_sack_snxt = begin + seg_len;
9530 
9531 		tcp_send_data(tcp, xmit_mp);
9532 
9533 		/*
9534 		 * Update the send timestamp to avoid false retransmission.
9535 		 */
9536 		snxt_mp->b_prev = (mblk_t *)ddi_get_lbolt();
9537 
9538 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
9539 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
9540 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
9541 		/*
9542 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
9543 		 * This happens when new data sent during fast recovery is
9544 		 * also lost.  If TCP retransmits those new data, it needs
9545 		 * to extend SACK recover phase to avoid starting another
9546 		 * fast retransmit/recovery unnecessarily.
9547 		 */
9548 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
9549 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
9550 		}
9551 	}
9552 }
9553 
9554 /*
9555  * tcp_ss_rexmit() is called to do slow start retransmission after a timeout
9556  * or ICMP errors.
9557  *
9558  * To limit the number of duplicate segments, we limit the number of segment
9559  * to be sent in one time to tcp_snd_burst, the burst variable.
9560  */
9561 static void
9562 tcp_ss_rexmit(tcp_t *tcp)
9563 {
9564 	uint32_t	snxt;
9565 	uint32_t	smax;
9566 	int32_t		win;
9567 	int32_t		mss;
9568 	int32_t		off;
9569 	int32_t		burst = tcp->tcp_snd_burst;
9570 	mblk_t		*snxt_mp;
9571 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9572 
9573 	/*
9574 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
9575 	 * all unack'ed segments.
9576 	 */
9577 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
9578 		smax = tcp->tcp_rexmit_max;
9579 		snxt = tcp->tcp_rexmit_nxt;
9580 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
9581 			snxt = tcp->tcp_suna;
9582 		}
9583 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
9584 		win -= snxt - tcp->tcp_suna;
9585 		mss = tcp->tcp_mss;
9586 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
9587 
9588 		while (SEQ_LT(snxt, smax) && (win > 0) &&
9589 		    (burst > 0) && (snxt_mp != NULL)) {
9590 			mblk_t	*xmit_mp;
9591 			mblk_t	*old_snxt_mp = snxt_mp;
9592 			uint32_t cnt = mss;
9593 
9594 			if (win < cnt) {
9595 				cnt = win;
9596 			}
9597 			if (SEQ_GT(snxt + cnt, smax)) {
9598 				cnt = smax - snxt;
9599 			}
9600 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
9601 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
9602 			if (xmit_mp == NULL)
9603 				return;
9604 
9605 			tcp_send_data(tcp, xmit_mp);
9606 
9607 			snxt += cnt;
9608 			win -= cnt;
9609 			/*
9610 			 * Update the send timestamp to avoid false
9611 			 * retransmission.
9612 			 */
9613 			old_snxt_mp->b_prev = (mblk_t *)ddi_get_lbolt();
9614 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
9615 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
9616 
9617 			tcp->tcp_rexmit_nxt = snxt;
9618 			burst--;
9619 		}
9620 		/*
9621 		 * If we have transmitted all we have at the time
9622 		 * we started the retranmission, we can leave
9623 		 * the rest of the job to tcp_wput_data().  But we
9624 		 * need to check the send window first.  If the
9625 		 * win is not 0, go on with tcp_wput_data().
9626 		 */
9627 		if (SEQ_LT(snxt, smax) || win == 0) {
9628 			return;
9629 		}
9630 	}
9631 	/* Only call tcp_wput_data() if there is data to be sent. */
9632 	if (tcp->tcp_unsent) {
9633 		tcp_wput_data(tcp, NULL, B_FALSE);
9634 	}
9635 }
9636 
9637 /*
9638  * Process all TCP option in SYN segment.  Note that this function should
9639  * be called after tcp_set_destination() is called so that the necessary info
9640  * from IRE is already set in the tcp structure.
9641  *
9642  * This function sets up the correct tcp_mss value according to the
9643  * MSS option value and our header size.  It also sets up the window scale
9644  * and timestamp values, and initialize SACK info blocks.  But it does not
9645  * change receive window size after setting the tcp_mss value.  The caller
9646  * should do the appropriate change.
9647  */
9648 void
9649 tcp_process_options(tcp_t *tcp, tcpha_t *tcpha)
9650 {
9651 	int options;
9652 	tcp_opt_t tcpopt;
9653 	uint32_t mss_max;
9654 	char *tmp_tcph;
9655 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9656 	conn_t		*connp = tcp->tcp_connp;
9657 
9658 	tcpopt.tcp = NULL;
9659 	options = tcp_parse_options(tcpha, &tcpopt);
9660 
9661 	/*
9662 	 * Process MSS option.  Note that MSS option value does not account
9663 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
9664 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
9665 	 * IPv6.
9666 	 */
9667 	if (!(options & TCP_OPT_MSS_PRESENT)) {
9668 		if (connp->conn_ipversion == IPV4_VERSION)
9669 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
9670 		else
9671 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
9672 	} else {
9673 		if (connp->conn_ipversion == IPV4_VERSION)
9674 			mss_max = tcps->tcps_mss_max_ipv4;
9675 		else
9676 			mss_max = tcps->tcps_mss_max_ipv6;
9677 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
9678 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
9679 		else if (tcpopt.tcp_opt_mss > mss_max)
9680 			tcpopt.tcp_opt_mss = mss_max;
9681 	}
9682 
9683 	/* Process Window Scale option. */
9684 	if (options & TCP_OPT_WSCALE_PRESENT) {
9685 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
9686 		tcp->tcp_snd_ws_ok = B_TRUE;
9687 	} else {
9688 		tcp->tcp_snd_ws = B_FALSE;
9689 		tcp->tcp_snd_ws_ok = B_FALSE;
9690 		tcp->tcp_rcv_ws = B_FALSE;
9691 	}
9692 
9693 	/* Process Timestamp option. */
9694 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
9695 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
9696 		tmp_tcph = (char *)tcp->tcp_tcpha;
9697 
9698 		tcp->tcp_snd_ts_ok = B_TRUE;
9699 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
9700 		tcp->tcp_last_rcv_lbolt = ddi_get_lbolt64();
9701 		ASSERT(OK_32PTR(tmp_tcph));
9702 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
9703 
9704 		/* Fill in our template header with basic timestamp option. */
9705 		tmp_tcph += connp->conn_ht_ulp_len;
9706 		tmp_tcph[0] = TCPOPT_NOP;
9707 		tmp_tcph[1] = TCPOPT_NOP;
9708 		tmp_tcph[2] = TCPOPT_TSTAMP;
9709 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
9710 		connp->conn_ht_iphc_len += TCPOPT_REAL_TS_LEN;
9711 		connp->conn_ht_ulp_len += TCPOPT_REAL_TS_LEN;
9712 		tcp->tcp_tcpha->tha_offset_and_reserved += (3 << 4);
9713 	} else {
9714 		tcp->tcp_snd_ts_ok = B_FALSE;
9715 	}
9716 
9717 	/*
9718 	 * Process SACK options.  If SACK is enabled for this connection,
9719 	 * then allocate the SACK info structure.  Note the following ways
9720 	 * when tcp_snd_sack_ok is set to true.
9721 	 *
9722 	 * For active connection: in tcp_set_destination() called in
9723 	 * tcp_connect().
9724 	 *
9725 	 * For passive connection: in tcp_set_destination() called in
9726 	 * tcp_input_listener().
9727 	 *
9728 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
9729 	 * That check makes sure that if we did not send a SACK OK option,
9730 	 * we will not enable SACK for this connection even though the other
9731 	 * side sends us SACK OK option.  For active connection, the SACK
9732 	 * info structure has already been allocated.  So we need to free
9733 	 * it if SACK is disabled.
9734 	 */
9735 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
9736 	    (tcp->tcp_snd_sack_ok ||
9737 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
9738 		/* This should be true only in the passive case. */
9739 		if (tcp->tcp_sack_info == NULL) {
9740 			ASSERT(TCP_IS_DETACHED(tcp));
9741 			tcp->tcp_sack_info =
9742 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
9743 		}
9744 		if (tcp->tcp_sack_info == NULL) {
9745 			tcp->tcp_snd_sack_ok = B_FALSE;
9746 		} else {
9747 			tcp->tcp_snd_sack_ok = B_TRUE;
9748 			if (tcp->tcp_snd_ts_ok) {
9749 				tcp->tcp_max_sack_blk = 3;
9750 			} else {
9751 				tcp->tcp_max_sack_blk = 4;
9752 			}
9753 		}
9754 	} else {
9755 		/*
9756 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
9757 		 * no SACK info will be used for this
9758 		 * connection.  This assumes that SACK usage
9759 		 * permission is negotiated.  This may need
9760 		 * to be changed once this is clarified.
9761 		 */
9762 		if (tcp->tcp_sack_info != NULL) {
9763 			ASSERT(tcp->tcp_notsack_list == NULL);
9764 			kmem_cache_free(tcp_sack_info_cache,
9765 			    tcp->tcp_sack_info);
9766 			tcp->tcp_sack_info = NULL;
9767 		}
9768 		tcp->tcp_snd_sack_ok = B_FALSE;
9769 	}
9770 
9771 	/*
9772 	 * Now we know the exact TCP/IP header length, subtract
9773 	 * that from tcp_mss to get our side's MSS.
9774 	 */
9775 	tcp->tcp_mss -= connp->conn_ht_iphc_len;
9776 
9777 	/*
9778 	 * Here we assume that the other side's header size will be equal to
9779 	 * our header size.  We calculate the real MSS accordingly.  Need to
9780 	 * take into additional stuffs IPsec puts in.
9781 	 *
9782 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
9783 	 */
9784 	tcpopt.tcp_opt_mss -= connp->conn_ht_iphc_len +
9785 	    tcp->tcp_ipsec_overhead -
9786 	    ((connp->conn_ipversion == IPV4_VERSION ?
9787 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
9788 
9789 	/*
9790 	 * Set MSS to the smaller one of both ends of the connection.
9791 	 * We should not have called tcp_mss_set() before, but our
9792 	 * side of the MSS should have been set to a proper value
9793 	 * by tcp_set_destination().  tcp_mss_set() will also set up the
9794 	 * STREAM head parameters properly.
9795 	 *
9796 	 * If we have a larger-than-16-bit window but the other side
9797 	 * didn't want to do window scale, tcp_rwnd_set() will take
9798 	 * care of that.
9799 	 */
9800 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
9801 
9802 	/*
9803 	 * Initialize tcp_cwnd value. After tcp_mss_set(), tcp_mss has been
9804 	 * updated properly.
9805 	 */
9806 	SET_TCP_INIT_CWND(tcp, tcp->tcp_mss, tcps->tcps_slow_start_initial);
9807 }
9808 
9809 /*
9810  * Sends the T_CONN_IND to the listener. The caller calls this
9811  * functions via squeue to get inside the listener's perimeter
9812  * once the 3 way hand shake is done a T_CONN_IND needs to be
9813  * sent. As an optimization, the caller can call this directly
9814  * if listener's perimeter is same as eager's.
9815  */
9816 /* ARGSUSED */
9817 void
9818 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
9819 {
9820 	conn_t			*lconnp = (conn_t *)arg;
9821 	tcp_t			*listener = lconnp->conn_tcp;
9822 	tcp_t			*tcp;
9823 	struct T_conn_ind	*conn_ind;
9824 	ipaddr_t 		*addr_cache;
9825 	boolean_t		need_send_conn_ind = B_FALSE;
9826 	tcp_stack_t		*tcps = listener->tcp_tcps;
9827 
9828 	/* retrieve the eager */
9829 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
9830 	ASSERT(conn_ind->OPT_offset != 0 &&
9831 	    conn_ind->OPT_length == sizeof (intptr_t));
9832 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
9833 	    conn_ind->OPT_length);
9834 
9835 	/*
9836 	 * TLI/XTI applications will get confused by
9837 	 * sending eager as an option since it violates
9838 	 * the option semantics. So remove the eager as
9839 	 * option since TLI/XTI app doesn't need it anyway.
9840 	 */
9841 	if (!TCP_IS_SOCKET(listener)) {
9842 		conn_ind->OPT_length = 0;
9843 		conn_ind->OPT_offset = 0;
9844 	}
9845 	if (listener->tcp_state != TCPS_LISTEN) {
9846 		/*
9847 		 * If listener has closed, it would have caused a
9848 		 * a cleanup/blowoff to happen for the eager. We
9849 		 * just need to return.
9850 		 */
9851 		freemsg(mp);
9852 		return;
9853 	}
9854 
9855 
9856 	/*
9857 	 * if the conn_req_q is full defer passing up the
9858 	 * T_CONN_IND until space is availabe after t_accept()
9859 	 * processing
9860 	 */
9861 	mutex_enter(&listener->tcp_eager_lock);
9862 
9863 	/*
9864 	 * Take the eager out, if it is in the list of droppable eagers
9865 	 * as we are here because the 3W handshake is over.
9866 	 */
9867 	MAKE_UNDROPPABLE(tcp);
9868 
9869 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
9870 		tcp_t *tail;
9871 
9872 		/*
9873 		 * The eager already has an extra ref put in tcp_input_data
9874 		 * so that it stays till accept comes back even though it
9875 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
9876 		 */
9877 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
9878 		listener->tcp_conn_req_cnt_q0--;
9879 		listener->tcp_conn_req_cnt_q++;
9880 
9881 		/* Move from SYN_RCVD to ESTABLISHED list  */
9882 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
9883 		    tcp->tcp_eager_prev_q0;
9884 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
9885 		    tcp->tcp_eager_next_q0;
9886 		tcp->tcp_eager_prev_q0 = NULL;
9887 		tcp->tcp_eager_next_q0 = NULL;
9888 
9889 		/*
9890 		 * Insert at end of the queue because sockfs
9891 		 * sends down T_CONN_RES in chronological
9892 		 * order. Leaving the older conn indications
9893 		 * at front of the queue helps reducing search
9894 		 * time.
9895 		 */
9896 		tail = listener->tcp_eager_last_q;
9897 		if (tail != NULL)
9898 			tail->tcp_eager_next_q = tcp;
9899 		else
9900 			listener->tcp_eager_next_q = tcp;
9901 		listener->tcp_eager_last_q = tcp;
9902 		tcp->tcp_eager_next_q = NULL;
9903 		/*
9904 		 * Delay sending up the T_conn_ind until we are
9905 		 * done with the eager. Once we have have sent up
9906 		 * the T_conn_ind, the accept can potentially complete
9907 		 * any time and release the refhold we have on the eager.
9908 		 */
9909 		need_send_conn_ind = B_TRUE;
9910 	} else {
9911 		/*
9912 		 * Defer connection on q0 and set deferred
9913 		 * connection bit true
9914 		 */
9915 		tcp->tcp_conn_def_q0 = B_TRUE;
9916 
9917 		/* take tcp out of q0 ... */
9918 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
9919 		    tcp->tcp_eager_next_q0;
9920 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
9921 		    tcp->tcp_eager_prev_q0;
9922 
9923 		/* ... and place it at the end of q0 */
9924 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
9925 		tcp->tcp_eager_next_q0 = listener;
9926 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
9927 		listener->tcp_eager_prev_q0 = tcp;
9928 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
9929 	}
9930 
9931 	/* we have timed out before */
9932 	if (tcp->tcp_syn_rcvd_timeout != 0) {
9933 		tcp->tcp_syn_rcvd_timeout = 0;
9934 		listener->tcp_syn_rcvd_timeout--;
9935 		if (listener->tcp_syn_defense &&
9936 		    listener->tcp_syn_rcvd_timeout <=
9937 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
9938 		    10*MINUTES < TICK_TO_MSEC(ddi_get_lbolt64() -
9939 		    listener->tcp_last_rcv_lbolt)) {
9940 			/*
9941 			 * Turn off the defense mode if we
9942 			 * believe the SYN attack is over.
9943 			 */
9944 			listener->tcp_syn_defense = B_FALSE;
9945 			if (listener->tcp_ip_addr_cache) {
9946 				kmem_free((void *)listener->tcp_ip_addr_cache,
9947 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
9948 				listener->tcp_ip_addr_cache = NULL;
9949 			}
9950 		}
9951 	}
9952 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
9953 	if (addr_cache != NULL) {
9954 		/*
9955 		 * We have finished a 3-way handshake with this
9956 		 * remote host. This proves the IP addr is good.
9957 		 * Cache it!
9958 		 */
9959 		addr_cache[IP_ADDR_CACHE_HASH(tcp->tcp_connp->conn_faddr_v4)] =
9960 		    tcp->tcp_connp->conn_faddr_v4;
9961 	}
9962 	mutex_exit(&listener->tcp_eager_lock);
9963 	if (need_send_conn_ind)
9964 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
9965 }
9966 
9967 /*
9968  * Send the newconn notification to ulp. The eager is blown off if the
9969  * notification fails.
9970  */
9971 static void
9972 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
9973 {
9974 	if (IPCL_IS_NONSTR(lconnp)) {
9975 		cred_t	*cr;
9976 		pid_t	cpid = NOPID;
9977 
9978 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
9979 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
9980 		    lconnp->conn_tcp);
9981 
9982 		cr = msg_getcred(mp, &cpid);
9983 
9984 		/* Keep the message around in case of a fallback to TPI */
9985 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
9986 		/*
9987 		 * Notify the ULP about the newconn. It is guaranteed that no
9988 		 * tcp_accept() call will be made for the eager if the
9989 		 * notification fails, so it's safe to blow it off in that
9990 		 * case.
9991 		 *
9992 		 * The upper handle will be assigned when tcp_accept() is
9993 		 * called.
9994 		 */
9995 		if ((*lconnp->conn_upcalls->su_newconn)
9996 		    (lconnp->conn_upper_handle,
9997 		    (sock_lower_handle_t)econnp,
9998 		    &sock_tcp_downcalls, cr, cpid,
9999 		    &econnp->conn_upcalls) == NULL) {
10000 			/* Failed to allocate a socket */
10001 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
10002 			    tcpEstabResets);
10003 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
10004 			    econnp->conn_tcp->tcp_conn_req_seqnum);
10005 		}
10006 	} else {
10007 		putnext(lconnp->conn_rq, mp);
10008 	}
10009 }
10010 
10011 /*
10012  * Handle a packet that has been reclassified by TCP.
10013  * This function drops the ref on connp that the caller had.
10014  */
10015 static void
10016 tcp_reinput(conn_t *connp, mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst)
10017 {
10018 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
10019 
10020 	if (connp->conn_incoming_ifindex != 0 &&
10021 	    connp->conn_incoming_ifindex != ira->ira_ruifindex) {
10022 		freemsg(mp);
10023 		CONN_DEC_REF(connp);
10024 		return;
10025 	}
10026 
10027 	if (CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss) ||
10028 	    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
10029 		ip6_t *ip6h;
10030 		ipha_t *ipha;
10031 
10032 		if (ira->ira_flags & IRAF_IS_IPV4) {
10033 			ipha = (ipha_t *)mp->b_rptr;
10034 			ip6h = NULL;
10035 		} else {
10036 			ipha = NULL;
10037 			ip6h = (ip6_t *)mp->b_rptr;
10038 		}
10039 		mp = ipsec_check_inbound_policy(mp, connp, ipha, ip6h, ira);
10040 		if (mp == NULL) {
10041 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
10042 			/* Note that mp is NULL */
10043 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
10044 			CONN_DEC_REF(connp);
10045 			return;
10046 		}
10047 	}
10048 
10049 	if (IPCL_IS_TCP(connp)) {
10050 		/*
10051 		 * do not drain, certain use cases can blow
10052 		 * the stack
10053 		 */
10054 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
10055 		    connp->conn_recv, connp, ira,
10056 		    SQ_NODRAIN, SQTAG_IP_TCP_INPUT);
10057 	} else {
10058 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
10059 		(connp->conn_recv)(connp, mp, NULL,
10060 		    ira);
10061 		CONN_DEC_REF(connp);
10062 	}
10063 
10064 }
10065 
10066 boolean_t tcp_outbound_squeue_switch = B_FALSE;
10067 
10068 /*
10069  * Handle M_DATA messages from IP. Its called directly from IP via
10070  * squeue for received IP packets.
10071  *
10072  * The first argument is always the connp/tcp to which the mp belongs.
10073  * There are no exceptions to this rule. The caller has already put
10074  * a reference on this connp/tcp and once tcp_input_data() returns,
10075  * the squeue will do the refrele.
10076  *
10077  * The TH_SYN for the listener directly go to tcp_input_listener via
10078  * squeue. ICMP errors go directly to tcp_icmp_input().
10079  *
10080  * sqp: NULL = recursive, sqp != NULL means called from squeue
10081  */
10082 void
10083 tcp_input_data(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
10084 {
10085 	int32_t		bytes_acked;
10086 	int32_t		gap;
10087 	mblk_t		*mp1;
10088 	uint_t		flags;
10089 	uint32_t	new_swnd = 0;
10090 	uchar_t		*iphdr;
10091 	uchar_t		*rptr;
10092 	int32_t		rgap;
10093 	uint32_t	seg_ack;
10094 	int		seg_len;
10095 	uint_t		ip_hdr_len;
10096 	uint32_t	seg_seq;
10097 	tcpha_t		*tcpha;
10098 	int		urp;
10099 	tcp_opt_t	tcpopt;
10100 	ip_pkt_t	ipp;
10101 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
10102 	uint32_t	cwnd;
10103 	uint32_t	add;
10104 	int		npkt;
10105 	int		mss;
10106 	conn_t		*connp = (conn_t *)arg;
10107 	squeue_t	*sqp = (squeue_t *)arg2;
10108 	tcp_t		*tcp = connp->conn_tcp;
10109 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10110 
10111 	/*
10112 	 * RST from fused tcp loopback peer should trigger an unfuse.
10113 	 */
10114 	if (tcp->tcp_fused) {
10115 		TCP_STAT(tcps, tcp_fusion_aborted);
10116 		tcp_unfuse(tcp);
10117 	}
10118 
10119 	iphdr = mp->b_rptr;
10120 	rptr = mp->b_rptr;
10121 	ASSERT(OK_32PTR(rptr));
10122 
10123 	ip_hdr_len = ira->ira_ip_hdr_length;
10124 	if (connp->conn_recv_ancillary.crb_all != 0) {
10125 		/*
10126 		 * Record packet information in the ip_pkt_t
10127 		 */
10128 		ipp.ipp_fields = 0;
10129 		if (ira->ira_flags & IRAF_IS_IPV4) {
10130 			(void) ip_find_hdr_v4((ipha_t *)rptr, &ipp,
10131 			    B_FALSE);
10132 		} else {
10133 			uint8_t nexthdrp;
10134 
10135 			/*
10136 			 * IPv6 packets can only be received by applications
10137 			 * that are prepared to receive IPv6 addresses.
10138 			 * The IP fanout must ensure this.
10139 			 */
10140 			ASSERT(connp->conn_family == AF_INET6);
10141 
10142 			(void) ip_find_hdr_v6(mp, (ip6_t *)rptr, B_TRUE, &ipp,
10143 			    &nexthdrp);
10144 			ASSERT(nexthdrp == IPPROTO_TCP);
10145 
10146 			/* Could have caused a pullup? */
10147 			iphdr = mp->b_rptr;
10148 			rptr = mp->b_rptr;
10149 		}
10150 	}
10151 	ASSERT(DB_TYPE(mp) == M_DATA);
10152 	ASSERT(mp->b_next == NULL);
10153 
10154 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
10155 	seg_seq = ntohl(tcpha->tha_seq);
10156 	seg_ack = ntohl(tcpha->tha_ack);
10157 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
10158 	seg_len = (int)(mp->b_wptr - rptr) -
10159 	    (ip_hdr_len + TCP_HDR_LENGTH(tcpha));
10160 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
10161 		do {
10162 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
10163 			    (uintptr_t)INT_MAX);
10164 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
10165 		} while ((mp1 = mp1->b_cont) != NULL &&
10166 		    mp1->b_datap->db_type == M_DATA);
10167 	}
10168 
10169 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
10170 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
10171 		    seg_len, tcpha, ira);
10172 		return;
10173 	}
10174 
10175 	if (sqp != NULL) {
10176 		/*
10177 		 * This is the correct place to update tcp_last_recv_time. Note
10178 		 * that it is also updated for tcp structure that belongs to
10179 		 * global and listener queues which do not really need updating.
10180 		 * But that should not cause any harm.  And it is updated for
10181 		 * all kinds of incoming segments, not only for data segments.
10182 		 */
10183 		tcp->tcp_last_recv_time = LBOLT_FASTPATH;
10184 	}
10185 
10186 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
10187 
10188 	BUMP_LOCAL(tcp->tcp_ibsegs);
10189 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
10190 
10191 	if ((flags & TH_URG) && sqp != NULL) {
10192 		/*
10193 		 * TCP can't handle urgent pointers that arrive before
10194 		 * the connection has been accept()ed since it can't
10195 		 * buffer OOB data.  Discard segment if this happens.
10196 		 *
10197 		 * We can't just rely on a non-null tcp_listener to indicate
10198 		 * that the accept() has completed since unlinking of the
10199 		 * eager and completion of the accept are not atomic.
10200 		 * tcp_detached, when it is not set (B_FALSE) indicates
10201 		 * that the accept() has completed.
10202 		 *
10203 		 * Nor can it reassemble urgent pointers, so discard
10204 		 * if it's not the next segment expected.
10205 		 *
10206 		 * Otherwise, collapse chain into one mblk (discard if
10207 		 * that fails).  This makes sure the headers, retransmitted
10208 		 * data, and new data all are in the same mblk.
10209 		 */
10210 		ASSERT(mp != NULL);
10211 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
10212 			freemsg(mp);
10213 			return;
10214 		}
10215 		/* Update pointers into message */
10216 		iphdr = rptr = mp->b_rptr;
10217 		tcpha = (tcpha_t *)&rptr[ip_hdr_len];
10218 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
10219 			/*
10220 			 * Since we can't handle any data with this urgent
10221 			 * pointer that is out of sequence, we expunge
10222 			 * the data.  This allows us to still register
10223 			 * the urgent mark and generate the M_PCSIG,
10224 			 * which we can do.
10225 			 */
10226 			mp->b_wptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
10227 			seg_len = 0;
10228 		}
10229 	}
10230 
10231 	switch (tcp->tcp_state) {
10232 	case TCPS_SYN_SENT:
10233 		if (connp->conn_final_sqp == NULL &&
10234 		    tcp_outbound_squeue_switch && sqp != NULL) {
10235 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
10236 			connp->conn_final_sqp = sqp;
10237 			if (connp->conn_final_sqp != connp->conn_sqp) {
10238 				DTRACE_PROBE1(conn__final__sqp__switch,
10239 				    conn_t *, connp);
10240 				CONN_INC_REF(connp);
10241 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
10242 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
10243 				    tcp_input_data, connp, ira, ip_squeue_flag,
10244 				    SQTAG_CONNECT_FINISH);
10245 				return;
10246 			}
10247 			DTRACE_PROBE1(conn__final__sqp__same, conn_t *, connp);
10248 		}
10249 		if (flags & TH_ACK) {
10250 			/*
10251 			 * Note that our stack cannot send data before a
10252 			 * connection is established, therefore the
10253 			 * following check is valid.  Otherwise, it has
10254 			 * to be changed.
10255 			 */
10256 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
10257 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
10258 				freemsg(mp);
10259 				if (flags & TH_RST)
10260 					return;
10261 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
10262 				    tcp, seg_ack, 0, TH_RST);
10263 				return;
10264 			}
10265 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
10266 		}
10267 		if (flags & TH_RST) {
10268 			freemsg(mp);
10269 			if (flags & TH_ACK)
10270 				(void) tcp_clean_death(tcp,
10271 				    ECONNREFUSED, 13);
10272 			return;
10273 		}
10274 		if (!(flags & TH_SYN)) {
10275 			freemsg(mp);
10276 			return;
10277 		}
10278 
10279 		/* Process all TCP options. */
10280 		tcp_process_options(tcp, tcpha);
10281 		/*
10282 		 * The following changes our rwnd to be a multiple of the
10283 		 * MIN(peer MSS, our MSS) for performance reason.
10284 		 */
10285 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(connp->conn_rcvbuf,
10286 		    tcp->tcp_mss));
10287 
10288 		/* Is the other end ECN capable? */
10289 		if (tcp->tcp_ecn_ok) {
10290 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
10291 				tcp->tcp_ecn_ok = B_FALSE;
10292 			}
10293 		}
10294 		/*
10295 		 * Clear ECN flags because it may interfere with later
10296 		 * processing.
10297 		 */
10298 		flags &= ~(TH_ECE|TH_CWR);
10299 
10300 		tcp->tcp_irs = seg_seq;
10301 		tcp->tcp_rack = seg_seq;
10302 		tcp->tcp_rnxt = seg_seq + 1;
10303 		tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
10304 		if (!TCP_IS_DETACHED(tcp)) {
10305 			/* Allocate room for SACK options if needed. */
10306 			connp->conn_wroff = connp->conn_ht_iphc_len;
10307 			if (tcp->tcp_snd_sack_ok)
10308 				connp->conn_wroff += TCPOPT_MAX_SACK_LEN;
10309 			if (!tcp->tcp_loopback)
10310 				connp->conn_wroff += tcps->tcps_wroff_xtra;
10311 
10312 			(void) proto_set_tx_wroff(connp->conn_rq, connp,
10313 			    connp->conn_wroff);
10314 		}
10315 		if (flags & TH_ACK) {
10316 			/*
10317 			 * If we can't get the confirmation upstream, pretend
10318 			 * we didn't even see this one.
10319 			 *
10320 			 * XXX: how can we pretend we didn't see it if we
10321 			 * have updated rnxt et. al.
10322 			 *
10323 			 * For loopback we defer sending up the T_CONN_CON
10324 			 * until after some checks below.
10325 			 */
10326 			mp1 = NULL;
10327 			/*
10328 			 * tcp_sendmsg() checks tcp_state without entering
10329 			 * the squeue so tcp_state should be updated before
10330 			 * sending up connection confirmation
10331 			 */
10332 			tcp->tcp_state = TCPS_ESTABLISHED;
10333 			if (!tcp_conn_con(tcp, iphdr, mp,
10334 			    tcp->tcp_loopback ? &mp1 : NULL, ira)) {
10335 				tcp->tcp_state = TCPS_SYN_SENT;
10336 				freemsg(mp);
10337 				return;
10338 			}
10339 			/* SYN was acked - making progress */
10340 			tcp->tcp_ip_forward_progress = B_TRUE;
10341 
10342 			/* One for the SYN */
10343 			tcp->tcp_suna = tcp->tcp_iss + 1;
10344 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
10345 
10346 			/*
10347 			 * If SYN was retransmitted, need to reset all
10348 			 * retransmission info.  This is because this
10349 			 * segment will be treated as a dup ACK.
10350 			 */
10351 			if (tcp->tcp_rexmit) {
10352 				tcp->tcp_rexmit = B_FALSE;
10353 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
10354 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
10355 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
10356 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
10357 				tcp->tcp_ms_we_have_waited = 0;
10358 
10359 				/*
10360 				 * Set tcp_cwnd back to 1 MSS, per
10361 				 * recommendation from
10362 				 * draft-floyd-incr-init-win-01.txt,
10363 				 * Increasing TCP's Initial Window.
10364 				 */
10365 				tcp->tcp_cwnd = tcp->tcp_mss;
10366 			}
10367 
10368 			tcp->tcp_swl1 = seg_seq;
10369 			tcp->tcp_swl2 = seg_ack;
10370 
10371 			new_swnd = ntohs(tcpha->tha_win);
10372 			tcp->tcp_swnd = new_swnd;
10373 			if (new_swnd > tcp->tcp_max_swnd)
10374 				tcp->tcp_max_swnd = new_swnd;
10375 
10376 			/*
10377 			 * Always send the three-way handshake ack immediately
10378 			 * in order to make the connection complete as soon as
10379 			 * possible on the accepting host.
10380 			 */
10381 			flags |= TH_ACK_NEEDED;
10382 
10383 			/*
10384 			 * Special case for loopback.  At this point we have
10385 			 * received SYN-ACK from the remote endpoint.  In
10386 			 * order to ensure that both endpoints reach the
10387 			 * fused state prior to any data exchange, the final
10388 			 * ACK needs to be sent before we indicate T_CONN_CON
10389 			 * to the module upstream.
10390 			 */
10391 			if (tcp->tcp_loopback) {
10392 				mblk_t *ack_mp;
10393 
10394 				ASSERT(!tcp->tcp_unfusable);
10395 				ASSERT(mp1 != NULL);
10396 				/*
10397 				 * For loopback, we always get a pure SYN-ACK
10398 				 * and only need to send back the final ACK
10399 				 * with no data (this is because the other
10400 				 * tcp is ours and we don't do T/TCP).  This
10401 				 * final ACK triggers the passive side to
10402 				 * perform fusion in ESTABLISHED state.
10403 				 */
10404 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
10405 					if (tcp->tcp_ack_tid != 0) {
10406 						(void) TCP_TIMER_CANCEL(tcp,
10407 						    tcp->tcp_ack_tid);
10408 						tcp->tcp_ack_tid = 0;
10409 					}
10410 					tcp_send_data(tcp, ack_mp);
10411 					BUMP_LOCAL(tcp->tcp_obsegs);
10412 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
10413 
10414 					if (!IPCL_IS_NONSTR(connp)) {
10415 						/* Send up T_CONN_CON */
10416 						if (ira->ira_cred != NULL) {
10417 							mblk_setcred(mp1,
10418 							    ira->ira_cred,
10419 							    ira->ira_cpid);
10420 						}
10421 						putnext(connp->conn_rq, mp1);
10422 					} else {
10423 						(*connp->conn_upcalls->
10424 						    su_connected)
10425 						    (connp->conn_upper_handle,
10426 						    tcp->tcp_connid,
10427 						    ira->ira_cred,
10428 						    ira->ira_cpid);
10429 						freemsg(mp1);
10430 					}
10431 
10432 					freemsg(mp);
10433 					return;
10434 				}
10435 				/*
10436 				 * Forget fusion; we need to handle more
10437 				 * complex cases below.  Send the deferred
10438 				 * T_CONN_CON message upstream and proceed
10439 				 * as usual.  Mark this tcp as not capable
10440 				 * of fusion.
10441 				 */
10442 				TCP_STAT(tcps, tcp_fusion_unfusable);
10443 				tcp->tcp_unfusable = B_TRUE;
10444 				if (!IPCL_IS_NONSTR(connp)) {
10445 					if (ira->ira_cred != NULL) {
10446 						mblk_setcred(mp1, ira->ira_cred,
10447 						    ira->ira_cpid);
10448 					}
10449 					putnext(connp->conn_rq, mp1);
10450 				} else {
10451 					(*connp->conn_upcalls->su_connected)
10452 					    (connp->conn_upper_handle,
10453 					    tcp->tcp_connid, ira->ira_cred,
10454 					    ira->ira_cpid);
10455 					freemsg(mp1);
10456 				}
10457 			}
10458 
10459 			/*
10460 			 * Check to see if there is data to be sent.  If
10461 			 * yes, set the transmit flag.  Then check to see
10462 			 * if received data processing needs to be done.
10463 			 * If not, go straight to xmit_check.  This short
10464 			 * cut is OK as we don't support T/TCP.
10465 			 */
10466 			if (tcp->tcp_unsent)
10467 				flags |= TH_XMIT_NEEDED;
10468 
10469 			if (seg_len == 0 && !(flags & TH_URG)) {
10470 				freemsg(mp);
10471 				goto xmit_check;
10472 			}
10473 
10474 			flags &= ~TH_SYN;
10475 			seg_seq++;
10476 			break;
10477 		}
10478 		tcp->tcp_state = TCPS_SYN_RCVD;
10479 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
10480 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
10481 		if (mp1 != NULL) {
10482 			tcp_send_data(tcp, mp1);
10483 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
10484 		}
10485 		freemsg(mp);
10486 		return;
10487 	case TCPS_SYN_RCVD:
10488 		if (flags & TH_ACK) {
10489 			/*
10490 			 * In this state, a SYN|ACK packet is either bogus
10491 			 * because the other side must be ACKing our SYN which
10492 			 * indicates it has seen the ACK for their SYN and
10493 			 * shouldn't retransmit it or we're crossing SYNs
10494 			 * on active open.
10495 			 */
10496 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
10497 				freemsg(mp);
10498 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
10499 				    tcp, seg_ack, 0, TH_RST);
10500 				return;
10501 			}
10502 			/*
10503 			 * NOTE: RFC 793 pg. 72 says this should be
10504 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
10505 			 * but that would mean we have an ack that ignored
10506 			 * our SYN.
10507 			 */
10508 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
10509 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
10510 				freemsg(mp);
10511 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
10512 				    tcp, seg_ack, 0, TH_RST);
10513 				return;
10514 			}
10515 			/*
10516 			 * No sane TCP stack will send such a small window
10517 			 * without receiving any data.  Just drop this invalid
10518 			 * ACK.  We also shorten the abort timeout in case
10519 			 * this is an attack.
10520 			 */
10521 			if ((ntohs(tcpha->tha_win) << tcp->tcp_snd_ws) <
10522 			    (tcp->tcp_mss >> tcp_init_wnd_shft)) {
10523 				freemsg(mp);
10524 				TCP_STAT(tcps, tcp_zwin_ack_syn);
10525 				tcp->tcp_second_ctimer_threshold =
10526 				    tcp_early_abort * SECONDS;
10527 				return;
10528 			}
10529 		}
10530 		break;
10531 	case TCPS_LISTEN:
10532 		/*
10533 		 * Only a TLI listener can come through this path when a
10534 		 * acceptor is going back to be a listener and a packet
10535 		 * for the acceptor hits the classifier. For a socket
10536 		 * listener, this can never happen because a listener
10537 		 * can never accept connection on itself and hence a
10538 		 * socket acceptor can not go back to being a listener.
10539 		 */
10540 		ASSERT(!TCP_IS_SOCKET(tcp));
10541 		/*FALLTHRU*/
10542 	case TCPS_CLOSED:
10543 	case TCPS_BOUND: {
10544 		conn_t	*new_connp;
10545 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
10546 
10547 		/*
10548 		 * Don't accept any input on a closed tcp as this TCP logically
10549 		 * does not exist on the system. Don't proceed further with
10550 		 * this TCP. For instance, this packet could trigger another
10551 		 * close of this tcp which would be disastrous for tcp_refcnt.
10552 		 * tcp_close_detached / tcp_clean_death / tcp_closei_local must
10553 		 * be called at most once on a TCP. In this case we need to
10554 		 * refeed the packet into the classifier and figure out where
10555 		 * the packet should go.
10556 		 */
10557 		new_connp = ipcl_classify(mp, ira, ipst);
10558 		if (new_connp != NULL) {
10559 			/* Drops ref on new_connp */
10560 			tcp_reinput(new_connp, mp, ira, ipst);
10561 			return;
10562 		}
10563 		/* We failed to classify. For now just drop the packet */
10564 		freemsg(mp);
10565 		return;
10566 	}
10567 	case TCPS_IDLE:
10568 		/*
10569 		 * Handle the case where the tcp_clean_death() has happened
10570 		 * on a connection (application hasn't closed yet) but a packet
10571 		 * was already queued on squeue before tcp_clean_death()
10572 		 * was processed. Calling tcp_clean_death() twice on same
10573 		 * connection can result in weird behaviour.
10574 		 */
10575 		freemsg(mp);
10576 		return;
10577 	default:
10578 		break;
10579 	}
10580 
10581 	/*
10582 	 * Already on the correct queue/perimeter.
10583 	 * If this is a detached connection and not an eager
10584 	 * connection hanging off a listener then new data
10585 	 * (past the FIN) will cause a reset.
10586 	 * We do a special check here where it
10587 	 * is out of the main line, rather than check
10588 	 * if we are detached every time we see new
10589 	 * data down below.
10590 	 */
10591 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
10592 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
10593 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
10594 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
10595 
10596 		freemsg(mp);
10597 		/*
10598 		 * This could be an SSL closure alert. We're detached so just
10599 		 * acknowledge it this last time.
10600 		 */
10601 		if (tcp->tcp_kssl_ctx != NULL) {
10602 			kssl_release_ctx(tcp->tcp_kssl_ctx);
10603 			tcp->tcp_kssl_ctx = NULL;
10604 
10605 			tcp->tcp_rnxt += seg_len;
10606 			tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
10607 			flags |= TH_ACK_NEEDED;
10608 			goto ack_check;
10609 		}
10610 
10611 		tcp_xmit_ctl("new data when detached", tcp,
10612 		    tcp->tcp_snxt, 0, TH_RST);
10613 		(void) tcp_clean_death(tcp, EPROTO, 12);
10614 		return;
10615 	}
10616 
10617 	mp->b_rptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
10618 	urp = ntohs(tcpha->tha_urp) - TCP_OLD_URP_INTERPRETATION;
10619 	new_swnd = ntohs(tcpha->tha_win) <<
10620 	    ((tcpha->tha_flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
10621 
10622 	if (tcp->tcp_snd_ts_ok) {
10623 		if (!tcp_paws_check(tcp, tcpha, &tcpopt)) {
10624 			/*
10625 			 * This segment is not acceptable.
10626 			 * Drop it and send back an ACK.
10627 			 */
10628 			freemsg(mp);
10629 			flags |= TH_ACK_NEEDED;
10630 			goto ack_check;
10631 		}
10632 	} else if (tcp->tcp_snd_sack_ok) {
10633 		ASSERT(tcp->tcp_sack_info != NULL);
10634 		tcpopt.tcp = tcp;
10635 		/*
10636 		 * SACK info in already updated in tcp_parse_options.  Ignore
10637 		 * all other TCP options...
10638 		 */
10639 		(void) tcp_parse_options(tcpha, &tcpopt);
10640 	}
10641 try_again:;
10642 	mss = tcp->tcp_mss;
10643 	gap = seg_seq - tcp->tcp_rnxt;
10644 	rgap = tcp->tcp_rwnd - (gap + seg_len);
10645 	/*
10646 	 * gap is the amount of sequence space between what we expect to see
10647 	 * and what we got for seg_seq.  A positive value for gap means
10648 	 * something got lost.  A negative value means we got some old stuff.
10649 	 */
10650 	if (gap < 0) {
10651 		/* Old stuff present.  Is the SYN in there? */
10652 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
10653 		    (seg_len != 0)) {
10654 			flags &= ~TH_SYN;
10655 			seg_seq++;
10656 			urp--;
10657 			/* Recompute the gaps after noting the SYN. */
10658 			goto try_again;
10659 		}
10660 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
10661 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
10662 		    (seg_len > -gap ? -gap : seg_len));
10663 		/* Remove the old stuff from seg_len. */
10664 		seg_len += gap;
10665 		/*
10666 		 * Anything left?
10667 		 * Make sure to check for unack'd FIN when rest of data
10668 		 * has been previously ack'd.
10669 		 */
10670 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
10671 			/*
10672 			 * Resets are only valid if they lie within our offered
10673 			 * window.  If the RST bit is set, we just ignore this
10674 			 * segment.
10675 			 */
10676 			if (flags & TH_RST) {
10677 				freemsg(mp);
10678 				return;
10679 			}
10680 
10681 			/*
10682 			 * The arriving of dup data packets indicate that we
10683 			 * may have postponed an ack for too long, or the other
10684 			 * side's RTT estimate is out of shape. Start acking
10685 			 * more often.
10686 			 */
10687 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
10688 			    tcp->tcp_rack_cnt >= 1 &&
10689 			    tcp->tcp_rack_abs_max > 2) {
10690 				tcp->tcp_rack_abs_max--;
10691 			}
10692 			tcp->tcp_rack_cur_max = 1;
10693 
10694 			/*
10695 			 * This segment is "unacceptable".  None of its
10696 			 * sequence space lies within our advertized window.
10697 			 *
10698 			 * Adjust seg_len to the original value for tracing.
10699 			 */
10700 			seg_len -= gap;
10701 			if (connp->conn_debug) {
10702 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
10703 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
10704 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
10705 				    "seg_len %d, rnxt %u, snxt %u, %s",
10706 				    gap, rgap, flags, seg_seq, seg_ack,
10707 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
10708 				    tcp_display(tcp, NULL,
10709 				    DISP_ADDR_AND_PORT));
10710 			}
10711 
10712 			/*
10713 			 * Arrange to send an ACK in response to the
10714 			 * unacceptable segment per RFC 793 page 69. There
10715 			 * is only one small difference between ours and the
10716 			 * acceptability test in the RFC - we accept ACK-only
10717 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
10718 			 * will be generated.
10719 			 *
10720 			 * Note that we have to ACK an ACK-only packet at least
10721 			 * for stacks that send 0-length keep-alives with
10722 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
10723 			 * section 4.2.3.6. As long as we don't ever generate
10724 			 * an unacceptable packet in response to an incoming
10725 			 * packet that is unacceptable, it should not cause
10726 			 * "ACK wars".
10727 			 */
10728 			flags |=  TH_ACK_NEEDED;
10729 
10730 			/*
10731 			 * Continue processing this segment in order to use the
10732 			 * ACK information it contains, but skip all other
10733 			 * sequence-number processing.	Processing the ACK
10734 			 * information is necessary in order to
10735 			 * re-synchronize connections that may have lost
10736 			 * synchronization.
10737 			 *
10738 			 * We clear seg_len and flag fields related to
10739 			 * sequence number processing as they are not
10740 			 * to be trusted for an unacceptable segment.
10741 			 */
10742 			seg_len = 0;
10743 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
10744 			goto process_ack;
10745 		}
10746 
10747 		/* Fix seg_seq, and chew the gap off the front. */
10748 		seg_seq = tcp->tcp_rnxt;
10749 		urp += gap;
10750 		do {
10751 			mblk_t	*mp2;
10752 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10753 			    (uintptr_t)UINT_MAX);
10754 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
10755 			if (gap > 0) {
10756 				mp->b_rptr = mp->b_wptr - gap;
10757 				break;
10758 			}
10759 			mp2 = mp;
10760 			mp = mp->b_cont;
10761 			freeb(mp2);
10762 		} while (gap < 0);
10763 		/*
10764 		 * If the urgent data has already been acknowledged, we
10765 		 * should ignore TH_URG below
10766 		 */
10767 		if (urp < 0)
10768 			flags &= ~TH_URG;
10769 	}
10770 	/*
10771 	 * rgap is the amount of stuff received out of window.  A negative
10772 	 * value is the amount out of window.
10773 	 */
10774 	if (rgap < 0) {
10775 		mblk_t	*mp2;
10776 
10777 		if (tcp->tcp_rwnd == 0) {
10778 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
10779 		} else {
10780 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
10781 			UPDATE_MIB(&tcps->tcps_mib,
10782 			    tcpInDataPastWinBytes, -rgap);
10783 		}
10784 
10785 		/*
10786 		 * seg_len does not include the FIN, so if more than
10787 		 * just the FIN is out of window, we act like we don't
10788 		 * see it.  (If just the FIN is out of window, rgap
10789 		 * will be zero and we will go ahead and acknowledge
10790 		 * the FIN.)
10791 		 */
10792 		flags &= ~TH_FIN;
10793 
10794 		/* Fix seg_len and make sure there is something left. */
10795 		seg_len += rgap;
10796 		if (seg_len <= 0) {
10797 			/*
10798 			 * Resets are only valid if they lie within our offered
10799 			 * window.  If the RST bit is set, we just ignore this
10800 			 * segment.
10801 			 */
10802 			if (flags & TH_RST) {
10803 				freemsg(mp);
10804 				return;
10805 			}
10806 
10807 			/* Per RFC 793, we need to send back an ACK. */
10808 			flags |= TH_ACK_NEEDED;
10809 
10810 			/*
10811 			 * Send SIGURG as soon as possible i.e. even
10812 			 * if the TH_URG was delivered in a window probe
10813 			 * packet (which will be unacceptable).
10814 			 *
10815 			 * We generate a signal if none has been generated
10816 			 * for this connection or if this is a new urgent
10817 			 * byte. Also send a zero-length "unmarked" message
10818 			 * to inform SIOCATMARK that this is not the mark.
10819 			 *
10820 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
10821 			 * is sent up. This plus the check for old data
10822 			 * (gap >= 0) handles the wraparound of the sequence
10823 			 * number space without having to always track the
10824 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
10825 			 * this max in its rcv_up variable).
10826 			 *
10827 			 * This prevents duplicate SIGURGS due to a "late"
10828 			 * zero-window probe when the T_EXDATA_IND has already
10829 			 * been sent up.
10830 			 */
10831 			if ((flags & TH_URG) &&
10832 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
10833 			    tcp->tcp_urp_last))) {
10834 				if (IPCL_IS_NONSTR(connp)) {
10835 					if (!TCP_IS_DETACHED(tcp)) {
10836 						(*connp->conn_upcalls->
10837 						    su_signal_oob)
10838 						    (connp->conn_upper_handle,
10839 						    urp);
10840 					}
10841 				} else {
10842 					mp1 = allocb(0, BPRI_MED);
10843 					if (mp1 == NULL) {
10844 						freemsg(mp);
10845 						return;
10846 					}
10847 					if (!TCP_IS_DETACHED(tcp) &&
10848 					    !putnextctl1(connp->conn_rq,
10849 					    M_PCSIG, SIGURG)) {
10850 						/* Try again on the rexmit. */
10851 						freemsg(mp1);
10852 						freemsg(mp);
10853 						return;
10854 					}
10855 					/*
10856 					 * If the next byte would be the mark
10857 					 * then mark with MARKNEXT else mark
10858 					 * with NOTMARKNEXT.
10859 					 */
10860 					if (gap == 0 && urp == 0)
10861 						mp1->b_flag |= MSGMARKNEXT;
10862 					else
10863 						mp1->b_flag |= MSGNOTMARKNEXT;
10864 					freemsg(tcp->tcp_urp_mark_mp);
10865 					tcp->tcp_urp_mark_mp = mp1;
10866 					flags |= TH_SEND_URP_MARK;
10867 				}
10868 				tcp->tcp_urp_last_valid = B_TRUE;
10869 				tcp->tcp_urp_last = urp + seg_seq;
10870 			}
10871 			/*
10872 			 * If this is a zero window probe, continue to
10873 			 * process the ACK part.  But we need to set seg_len
10874 			 * to 0 to avoid data processing.  Otherwise just
10875 			 * drop the segment and send back an ACK.
10876 			 */
10877 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
10878 				flags &= ~(TH_SYN | TH_URG);
10879 				seg_len = 0;
10880 				goto process_ack;
10881 			} else {
10882 				freemsg(mp);
10883 				goto ack_check;
10884 			}
10885 		}
10886 		/* Pitch out of window stuff off the end. */
10887 		rgap = seg_len;
10888 		mp2 = mp;
10889 		do {
10890 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
10891 			    (uintptr_t)INT_MAX);
10892 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
10893 			if (rgap < 0) {
10894 				mp2->b_wptr += rgap;
10895 				if ((mp1 = mp2->b_cont) != NULL) {
10896 					mp2->b_cont = NULL;
10897 					freemsg(mp1);
10898 				}
10899 				break;
10900 			}
10901 		} while ((mp2 = mp2->b_cont) != NULL);
10902 	}
10903 ok:;
10904 	/*
10905 	 * TCP should check ECN info for segments inside the window only.
10906 	 * Therefore the check should be done here.
10907 	 */
10908 	if (tcp->tcp_ecn_ok) {
10909 		if (flags & TH_CWR) {
10910 			tcp->tcp_ecn_echo_on = B_FALSE;
10911 		}
10912 		/*
10913 		 * Note that both ECN_CE and CWR can be set in the
10914 		 * same segment.  In this case, we once again turn
10915 		 * on ECN_ECHO.
10916 		 */
10917 		if (connp->conn_ipversion == IPV4_VERSION) {
10918 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
10919 
10920 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
10921 				tcp->tcp_ecn_echo_on = B_TRUE;
10922 			}
10923 		} else {
10924 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
10925 
10926 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
10927 			    htonl(IPH_ECN_CE << 20)) {
10928 				tcp->tcp_ecn_echo_on = B_TRUE;
10929 			}
10930 		}
10931 	}
10932 
10933 	/*
10934 	 * Check whether we can update tcp_ts_recent.  This test is
10935 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
10936 	 * Extensions for High Performance: An Update", Internet Draft.
10937 	 */
10938 	if (tcp->tcp_snd_ts_ok &&
10939 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
10940 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
10941 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
10942 		tcp->tcp_last_rcv_lbolt = LBOLT_FASTPATH64;
10943 	}
10944 
10945 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
10946 		/*
10947 		 * FIN in an out of order segment.  We record this in
10948 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
10949 		 * Clear the FIN so that any check on FIN flag will fail.
10950 		 * Remember that FIN also counts in the sequence number
10951 		 * space.  So we need to ack out of order FIN only segments.
10952 		 */
10953 		if (flags & TH_FIN) {
10954 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
10955 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
10956 			flags &= ~TH_FIN;
10957 			flags |= TH_ACK_NEEDED;
10958 		}
10959 		if (seg_len > 0) {
10960 			/* Fill in the SACK blk list. */
10961 			if (tcp->tcp_snd_sack_ok) {
10962 				ASSERT(tcp->tcp_sack_info != NULL);
10963 				tcp_sack_insert(tcp->tcp_sack_list,
10964 				    seg_seq, seg_seq + seg_len,
10965 				    &(tcp->tcp_num_sack_blk));
10966 			}
10967 
10968 			/*
10969 			 * Attempt reassembly and see if we have something
10970 			 * ready to go.
10971 			 */
10972 			mp = tcp_reass(tcp, mp, seg_seq);
10973 			/* Always ack out of order packets */
10974 			flags |= TH_ACK_NEEDED | TH_PUSH;
10975 			if (mp) {
10976 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10977 				    (uintptr_t)INT_MAX);
10978 				seg_len = mp->b_cont ? msgdsize(mp) :
10979 				    (int)(mp->b_wptr - mp->b_rptr);
10980 				seg_seq = tcp->tcp_rnxt;
10981 				/*
10982 				 * A gap is filled and the seq num and len
10983 				 * of the gap match that of a previously
10984 				 * received FIN, put the FIN flag back in.
10985 				 */
10986 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
10987 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
10988 					flags |= TH_FIN;
10989 					tcp->tcp_valid_bits &=
10990 					    ~TCP_OFO_FIN_VALID;
10991 				}
10992 				if (tcp->tcp_reass_tid != 0) {
10993 					(void) TCP_TIMER_CANCEL(tcp,
10994 					    tcp->tcp_reass_tid);
10995 					/*
10996 					 * Restart the timer if there is still
10997 					 * data in the reassembly queue.
10998 					 */
10999 					if (tcp->tcp_reass_head != NULL) {
11000 						tcp->tcp_reass_tid = TCP_TIMER(
11001 						    tcp, tcp_reass_timer,
11002 						    MSEC_TO_TICK(
11003 						    tcps->tcps_reass_timeout));
11004 					} else {
11005 						tcp->tcp_reass_tid = 0;
11006 					}
11007 				}
11008 			} else {
11009 				/*
11010 				 * Keep going even with NULL mp.
11011 				 * There may be a useful ACK or something else
11012 				 * we don't want to miss.
11013 				 *
11014 				 * But TCP should not perform fast retransmit
11015 				 * because of the ack number.  TCP uses
11016 				 * seg_len == 0 to determine if it is a pure
11017 				 * ACK.  And this is not a pure ACK.
11018 				 */
11019 				seg_len = 0;
11020 				ofo_seg = B_TRUE;
11021 
11022 				if (tcps->tcps_reass_timeout != 0 &&
11023 				    tcp->tcp_reass_tid == 0) {
11024 					tcp->tcp_reass_tid = TCP_TIMER(tcp,
11025 					    tcp_reass_timer, MSEC_TO_TICK(
11026 					    tcps->tcps_reass_timeout));
11027 				}
11028 			}
11029 		}
11030 	} else if (seg_len > 0) {
11031 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
11032 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
11033 		/*
11034 		 * If an out of order FIN was received before, and the seq
11035 		 * num and len of the new segment match that of the FIN,
11036 		 * put the FIN flag back in.
11037 		 */
11038 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
11039 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
11040 			flags |= TH_FIN;
11041 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
11042 		}
11043 	}
11044 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
11045 	if (flags & TH_RST) {
11046 		freemsg(mp);
11047 		switch (tcp->tcp_state) {
11048 		case TCPS_SYN_RCVD:
11049 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
11050 			break;
11051 		case TCPS_ESTABLISHED:
11052 		case TCPS_FIN_WAIT_1:
11053 		case TCPS_FIN_WAIT_2:
11054 		case TCPS_CLOSE_WAIT:
11055 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
11056 			break;
11057 		case TCPS_CLOSING:
11058 		case TCPS_LAST_ACK:
11059 			(void) tcp_clean_death(tcp, 0, 16);
11060 			break;
11061 		default:
11062 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
11063 			(void) tcp_clean_death(tcp, ENXIO, 17);
11064 			break;
11065 		}
11066 		return;
11067 	}
11068 	if (flags & TH_SYN) {
11069 		/*
11070 		 * See RFC 793, Page 71
11071 		 *
11072 		 * The seq number must be in the window as it should
11073 		 * be "fixed" above.  If it is outside window, it should
11074 		 * be already rejected.  Note that we allow seg_seq to be
11075 		 * rnxt + rwnd because we want to accept 0 window probe.
11076 		 */
11077 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
11078 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
11079 		freemsg(mp);
11080 		/*
11081 		 * If the ACK flag is not set, just use our snxt as the
11082 		 * seq number of the RST segment.
11083 		 */
11084 		if (!(flags & TH_ACK)) {
11085 			seg_ack = tcp->tcp_snxt;
11086 		}
11087 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
11088 		    TH_RST|TH_ACK);
11089 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
11090 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
11091 		return;
11092 	}
11093 	/*
11094 	 * urp could be -1 when the urp field in the packet is 0
11095 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
11096 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
11097 	 */
11098 	if (flags & TH_URG && urp >= 0) {
11099 		if (!tcp->tcp_urp_last_valid ||
11100 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
11101 			/*
11102 			 * Non-STREAMS sockets handle the urgent data a litte
11103 			 * differently from STREAMS based sockets. There is no
11104 			 * need to mark any mblks with the MSG{NOT,}MARKNEXT
11105 			 * flags to keep SIOCATMARK happy. Instead a
11106 			 * su_signal_oob upcall is made to update the mark.
11107 			 * Neither is a T_EXDATA_IND mblk needed to be
11108 			 * prepended to the urgent data. The urgent data is
11109 			 * delivered using the su_recv upcall, where we set
11110 			 * the MSG_OOB flag to indicate that it is urg data.
11111 			 *
11112 			 * Neither TH_SEND_URP_MARK nor TH_MARKNEXT_NEEDED
11113 			 * are used by non-STREAMS sockets.
11114 			 */
11115 			if (IPCL_IS_NONSTR(connp)) {
11116 				if (!TCP_IS_DETACHED(tcp)) {
11117 					(*connp->conn_upcalls->su_signal_oob)
11118 					    (connp->conn_upper_handle, urp);
11119 				}
11120 			} else {
11121 				/*
11122 				 * If we haven't generated the signal yet for
11123 				 * this urgent pointer value, do it now.  Also,
11124 				 * send up a zero-length M_DATA indicating
11125 				 * whether or not this is the mark. The latter
11126 				 * is not needed when a T_EXDATA_IND is sent up.
11127 				 * However, if there are allocation failures
11128 				 * this code relies on the sender retransmitting
11129 				 * and the socket code for determining the mark
11130 				 * should not block waiting for the peer to
11131 				 * transmit. Thus, for simplicity we always
11132 				 * send up the mark indication.
11133 				 */
11134 				mp1 = allocb(0, BPRI_MED);
11135 				if (mp1 == NULL) {
11136 					freemsg(mp);
11137 					return;
11138 				}
11139 				if (!TCP_IS_DETACHED(tcp) &&
11140 				    !putnextctl1(connp->conn_rq, M_PCSIG,
11141 				    SIGURG)) {
11142 					/* Try again on the rexmit. */
11143 					freemsg(mp1);
11144 					freemsg(mp);
11145 					return;
11146 				}
11147 				/*
11148 				 * Mark with NOTMARKNEXT for now.
11149 				 * The code below will change this to MARKNEXT
11150 				 * if we are at the mark.
11151 				 *
11152 				 * If there are allocation failures (e.g. in
11153 				 * dupmsg below) the next time tcp_input_data
11154 				 * sees the urgent segment it will send up the
11155 				 * MSGMARKNEXT message.
11156 				 */
11157 				mp1->b_flag |= MSGNOTMARKNEXT;
11158 				freemsg(tcp->tcp_urp_mark_mp);
11159 				tcp->tcp_urp_mark_mp = mp1;
11160 				flags |= TH_SEND_URP_MARK;
11161 #ifdef DEBUG
11162 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11163 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
11164 				    "last %x, %s",
11165 				    seg_seq, urp, tcp->tcp_urp_last,
11166 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
11167 #endif /* DEBUG */
11168 			}
11169 			tcp->tcp_urp_last_valid = B_TRUE;
11170 			tcp->tcp_urp_last = urp + seg_seq;
11171 		} else if (tcp->tcp_urp_mark_mp != NULL) {
11172 			/*
11173 			 * An allocation failure prevented the previous
11174 			 * tcp_input_data from sending up the allocated
11175 			 * MSG*MARKNEXT message - send it up this time
11176 			 * around.
11177 			 */
11178 			flags |= TH_SEND_URP_MARK;
11179 		}
11180 
11181 		/*
11182 		 * If the urgent byte is in this segment, make sure that it is
11183 		 * all by itself.  This makes it much easier to deal with the
11184 		 * possibility of an allocation failure on the T_exdata_ind.
11185 		 * Note that seg_len is the number of bytes in the segment, and
11186 		 * urp is the offset into the segment of the urgent byte.
11187 		 * urp < seg_len means that the urgent byte is in this segment.
11188 		 */
11189 		if (urp < seg_len) {
11190 			if (seg_len != 1) {
11191 				uint32_t  tmp_rnxt;
11192 				/*
11193 				 * Break it up and feed it back in.
11194 				 * Re-attach the IP header.
11195 				 */
11196 				mp->b_rptr = iphdr;
11197 				if (urp > 0) {
11198 					/*
11199 					 * There is stuff before the urgent
11200 					 * byte.
11201 					 */
11202 					mp1 = dupmsg(mp);
11203 					if (!mp1) {
11204 						/*
11205 						 * Trim from urgent byte on.
11206 						 * The rest will come back.
11207 						 */
11208 						(void) adjmsg(mp,
11209 						    urp - seg_len);
11210 						tcp_input_data(connp,
11211 						    mp, NULL, ira);
11212 						return;
11213 					}
11214 					(void) adjmsg(mp1, urp - seg_len);
11215 					/* Feed this piece back in. */
11216 					tmp_rnxt = tcp->tcp_rnxt;
11217 					tcp_input_data(connp, mp1, NULL, ira);
11218 					/*
11219 					 * If the data passed back in was not
11220 					 * processed (ie: bad ACK) sending
11221 					 * the remainder back in will cause a
11222 					 * loop. In this case, drop the
11223 					 * packet and let the sender try
11224 					 * sending a good packet.
11225 					 */
11226 					if (tmp_rnxt == tcp->tcp_rnxt) {
11227 						freemsg(mp);
11228 						return;
11229 					}
11230 				}
11231 				if (urp != seg_len - 1) {
11232 					uint32_t  tmp_rnxt;
11233 					/*
11234 					 * There is stuff after the urgent
11235 					 * byte.
11236 					 */
11237 					mp1 = dupmsg(mp);
11238 					if (!mp1) {
11239 						/*
11240 						 * Trim everything beyond the
11241 						 * urgent byte.  The rest will
11242 						 * come back.
11243 						 */
11244 						(void) adjmsg(mp,
11245 						    urp + 1 - seg_len);
11246 						tcp_input_data(connp,
11247 						    mp, NULL, ira);
11248 						return;
11249 					}
11250 					(void) adjmsg(mp1, urp + 1 - seg_len);
11251 					tmp_rnxt = tcp->tcp_rnxt;
11252 					tcp_input_data(connp, mp1, NULL, ira);
11253 					/*
11254 					 * If the data passed back in was not
11255 					 * processed (ie: bad ACK) sending
11256 					 * the remainder back in will cause a
11257 					 * loop. In this case, drop the
11258 					 * packet and let the sender try
11259 					 * sending a good packet.
11260 					 */
11261 					if (tmp_rnxt == tcp->tcp_rnxt) {
11262 						freemsg(mp);
11263 						return;
11264 					}
11265 				}
11266 				tcp_input_data(connp, mp, NULL, ira);
11267 				return;
11268 			}
11269 			/*
11270 			 * This segment contains only the urgent byte.  We
11271 			 * have to allocate the T_exdata_ind, if we can.
11272 			 */
11273 			if (IPCL_IS_NONSTR(connp)) {
11274 				int error;
11275 
11276 				(*connp->conn_upcalls->su_recv)
11277 				    (connp->conn_upper_handle, mp, seg_len,
11278 				    MSG_OOB, &error, NULL);
11279 				/*
11280 				 * We should never be in middle of a
11281 				 * fallback, the squeue guarantees that.
11282 				 */
11283 				ASSERT(error != EOPNOTSUPP);
11284 				mp = NULL;
11285 				goto update_ack;
11286 			} else if (!tcp->tcp_urp_mp) {
11287 				struct T_exdata_ind *tei;
11288 				mp1 = allocb(sizeof (struct T_exdata_ind),
11289 				    BPRI_MED);
11290 				if (!mp1) {
11291 					/*
11292 					 * Sigh... It'll be back.
11293 					 * Generate any MSG*MARK message now.
11294 					 */
11295 					freemsg(mp);
11296 					seg_len = 0;
11297 					if (flags & TH_SEND_URP_MARK) {
11298 
11299 
11300 						ASSERT(tcp->tcp_urp_mark_mp);
11301 						tcp->tcp_urp_mark_mp->b_flag &=
11302 						    ~MSGNOTMARKNEXT;
11303 						tcp->tcp_urp_mark_mp->b_flag |=
11304 						    MSGMARKNEXT;
11305 					}
11306 					goto ack_check;
11307 				}
11308 				mp1->b_datap->db_type = M_PROTO;
11309 				tei = (struct T_exdata_ind *)mp1->b_rptr;
11310 				tei->PRIM_type = T_EXDATA_IND;
11311 				tei->MORE_flag = 0;
11312 				mp1->b_wptr = (uchar_t *)&tei[1];
11313 				tcp->tcp_urp_mp = mp1;
11314 #ifdef DEBUG
11315 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11316 				    "tcp_rput: allocated exdata_ind %s",
11317 				    tcp_display(tcp, NULL,
11318 				    DISP_PORT_ONLY));
11319 #endif /* DEBUG */
11320 				/*
11321 				 * There is no need to send a separate MSG*MARK
11322 				 * message since the T_EXDATA_IND will be sent
11323 				 * now.
11324 				 */
11325 				flags &= ~TH_SEND_URP_MARK;
11326 				freemsg(tcp->tcp_urp_mark_mp);
11327 				tcp->tcp_urp_mark_mp = NULL;
11328 			}
11329 			/*
11330 			 * Now we are all set.  On the next putnext upstream,
11331 			 * tcp_urp_mp will be non-NULL and will get prepended
11332 			 * to what has to be this piece containing the urgent
11333 			 * byte.  If for any reason we abort this segment below,
11334 			 * if it comes back, we will have this ready, or it
11335 			 * will get blown off in close.
11336 			 */
11337 		} else if (urp == seg_len) {
11338 			/*
11339 			 * The urgent byte is the next byte after this sequence
11340 			 * number. If this endpoint is non-STREAMS, then there
11341 			 * is nothing to do here since the socket has already
11342 			 * been notified about the urg pointer by the
11343 			 * su_signal_oob call above.
11344 			 *
11345 			 * In case of STREAMS, some more work might be needed.
11346 			 * If there is data it is marked with MSGMARKNEXT and
11347 			 * and any tcp_urp_mark_mp is discarded since it is not
11348 			 * needed. Otherwise, if the code above just allocated
11349 			 * a zero-length tcp_urp_mark_mp message, that message
11350 			 * is tagged with MSGMARKNEXT. Sending up these
11351 			 * MSGMARKNEXT messages makes SIOCATMARK work correctly
11352 			 * even though the T_EXDATA_IND will not be sent up
11353 			 * until the urgent byte arrives.
11354 			 */
11355 			if (!IPCL_IS_NONSTR(tcp->tcp_connp)) {
11356 				if (seg_len != 0) {
11357 					flags |= TH_MARKNEXT_NEEDED;
11358 					freemsg(tcp->tcp_urp_mark_mp);
11359 					tcp->tcp_urp_mark_mp = NULL;
11360 					flags &= ~TH_SEND_URP_MARK;
11361 				} else if (tcp->tcp_urp_mark_mp != NULL) {
11362 					flags |= TH_SEND_URP_MARK;
11363 					tcp->tcp_urp_mark_mp->b_flag &=
11364 					    ~MSGNOTMARKNEXT;
11365 					tcp->tcp_urp_mark_mp->b_flag |=
11366 					    MSGMARKNEXT;
11367 				}
11368 			}
11369 #ifdef DEBUG
11370 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11371 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
11372 			    seg_len, flags,
11373 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
11374 #endif /* DEBUG */
11375 		}
11376 #ifdef DEBUG
11377 		else {
11378 			/* Data left until we hit mark */
11379 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11380 			    "tcp_rput: URP %d bytes left, %s",
11381 			    urp - seg_len, tcp_display(tcp, NULL,
11382 			    DISP_PORT_ONLY));
11383 		}
11384 #endif /* DEBUG */
11385 	}
11386 
11387 process_ack:
11388 	if (!(flags & TH_ACK)) {
11389 		freemsg(mp);
11390 		goto xmit_check;
11391 	}
11392 	}
11393 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
11394 
11395 	if (bytes_acked > 0)
11396 		tcp->tcp_ip_forward_progress = B_TRUE;
11397 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
11398 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
11399 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
11400 			/* 3-way handshake complete - pass up the T_CONN_IND */
11401 			tcp_t	*listener = tcp->tcp_listener;
11402 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
11403 
11404 			tcp->tcp_tconnind_started = B_TRUE;
11405 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
11406 			/*
11407 			 * We are here means eager is fine but it can
11408 			 * get a TH_RST at any point between now and till
11409 			 * accept completes and disappear. We need to
11410 			 * ensure that reference to eager is valid after
11411 			 * we get out of eager's perimeter. So we do
11412 			 * an extra refhold.
11413 			 */
11414 			CONN_INC_REF(connp);
11415 
11416 			/*
11417 			 * The listener also exists because of the refhold
11418 			 * done in tcp_input_listener. Its possible that it
11419 			 * might have closed. We will check that once we
11420 			 * get inside listeners context.
11421 			 */
11422 			CONN_INC_REF(listener->tcp_connp);
11423 			if (listener->tcp_connp->conn_sqp ==
11424 			    connp->conn_sqp) {
11425 				/*
11426 				 * We optimize by not calling an SQUEUE_ENTER
11427 				 * on the listener since we know that the
11428 				 * listener and eager squeues are the same.
11429 				 * We are able to make this check safely only
11430 				 * because neither the eager nor the listener
11431 				 * can change its squeue. Only an active connect
11432 				 * can change its squeue
11433 				 */
11434 				tcp_send_conn_ind(listener->tcp_connp, mp,
11435 				    listener->tcp_connp->conn_sqp);
11436 				CONN_DEC_REF(listener->tcp_connp);
11437 			} else if (!tcp->tcp_loopback) {
11438 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
11439 				    mp, tcp_send_conn_ind,
11440 				    listener->tcp_connp, NULL, SQ_FILL,
11441 				    SQTAG_TCP_CONN_IND);
11442 			} else {
11443 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
11444 				    mp, tcp_send_conn_ind,
11445 				    listener->tcp_connp, NULL, SQ_PROCESS,
11446 				    SQTAG_TCP_CONN_IND);
11447 			}
11448 		}
11449 
11450 		/*
11451 		 * We are seeing the final ack in the three way
11452 		 * hand shake of a active open'ed connection
11453 		 * so we must send up a T_CONN_CON
11454 		 *
11455 		 * tcp_sendmsg() checks tcp_state without entering
11456 		 * the squeue so tcp_state should be updated before
11457 		 * sending up connection confirmation.
11458 		 */
11459 		tcp->tcp_state = TCPS_ESTABLISHED;
11460 		if (tcp->tcp_active_open) {
11461 			if (!tcp_conn_con(tcp, iphdr, mp, NULL, ira)) {
11462 				freemsg(mp);
11463 				tcp->tcp_state = TCPS_SYN_RCVD;
11464 				return;
11465 			}
11466 			/*
11467 			 * Don't fuse the loopback endpoints for
11468 			 * simultaneous active opens.
11469 			 */
11470 			if (tcp->tcp_loopback) {
11471 				TCP_STAT(tcps, tcp_fusion_unfusable);
11472 				tcp->tcp_unfusable = B_TRUE;
11473 			}
11474 		}
11475 
11476 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
11477 		bytes_acked--;
11478 		/* SYN was acked - making progress */
11479 		tcp->tcp_ip_forward_progress = B_TRUE;
11480 
11481 		/*
11482 		 * If SYN was retransmitted, need to reset all
11483 		 * retransmission info as this segment will be
11484 		 * treated as a dup ACK.
11485 		 */
11486 		if (tcp->tcp_rexmit) {
11487 			tcp->tcp_rexmit = B_FALSE;
11488 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
11489 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
11490 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
11491 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11492 			tcp->tcp_ms_we_have_waited = 0;
11493 			tcp->tcp_cwnd = mss;
11494 		}
11495 
11496 		/*
11497 		 * We set the send window to zero here.
11498 		 * This is needed if there is data to be
11499 		 * processed already on the queue.
11500 		 * Later (at swnd_update label), the
11501 		 * "new_swnd > tcp_swnd" condition is satisfied
11502 		 * the XMIT_NEEDED flag is set in the current
11503 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
11504 		 * called if there is already data on queue in
11505 		 * this state.
11506 		 */
11507 		tcp->tcp_swnd = 0;
11508 
11509 		if (new_swnd > tcp->tcp_max_swnd)
11510 			tcp->tcp_max_swnd = new_swnd;
11511 		tcp->tcp_swl1 = seg_seq;
11512 		tcp->tcp_swl2 = seg_ack;
11513 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
11514 
11515 		/* Fuse when both sides are in ESTABLISHED state */
11516 		if (tcp->tcp_loopback && do_tcp_fusion)
11517 			tcp_fuse(tcp, iphdr, tcpha);
11518 
11519 	}
11520 	/* This code follows 4.4BSD-Lite2 mostly. */
11521 	if (bytes_acked < 0)
11522 		goto est;
11523 
11524 	/*
11525 	 * If TCP is ECN capable and the congestion experience bit is
11526 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
11527 	 * done once per window (or more loosely, per RTT).
11528 	 */
11529 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
11530 		tcp->tcp_cwr = B_FALSE;
11531 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
11532 		if (!tcp->tcp_cwr) {
11533 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
11534 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
11535 			tcp->tcp_cwnd = npkt * mss;
11536 			/*
11537 			 * If the cwnd is 0, use the timer to clock out
11538 			 * new segments.  This is required by the ECN spec.
11539 			 */
11540 			if (npkt == 0) {
11541 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
11542 				/*
11543 				 * This makes sure that when the ACK comes
11544 				 * back, we will increase tcp_cwnd by 1 MSS.
11545 				 */
11546 				tcp->tcp_cwnd_cnt = 0;
11547 			}
11548 			tcp->tcp_cwr = B_TRUE;
11549 			/*
11550 			 * This marks the end of the current window of in
11551 			 * flight data.  That is why we don't use
11552 			 * tcp_suna + tcp_swnd.  Only data in flight can
11553 			 * provide ECN info.
11554 			 */
11555 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
11556 			tcp->tcp_ecn_cwr_sent = B_FALSE;
11557 		}
11558 	}
11559 
11560 	mp1 = tcp->tcp_xmit_head;
11561 	if (bytes_acked == 0) {
11562 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
11563 			int dupack_cnt;
11564 
11565 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
11566 			/*
11567 			 * Fast retransmit.  When we have seen exactly three
11568 			 * identical ACKs while we have unacked data
11569 			 * outstanding we take it as a hint that our peer
11570 			 * dropped something.
11571 			 *
11572 			 * If TCP is retransmitting, don't do fast retransmit.
11573 			 */
11574 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
11575 			    ! tcp->tcp_rexmit) {
11576 				/* Do Limited Transmit */
11577 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
11578 				    tcps->tcps_dupack_fast_retransmit) {
11579 					/*
11580 					 * RFC 3042
11581 					 *
11582 					 * What we need to do is temporarily
11583 					 * increase tcp_cwnd so that new
11584 					 * data can be sent if it is allowed
11585 					 * by the receive window (tcp_rwnd).
11586 					 * tcp_wput_data() will take care of
11587 					 * the rest.
11588 					 *
11589 					 * If the connection is SACK capable,
11590 					 * only do limited xmit when there
11591 					 * is SACK info.
11592 					 *
11593 					 * Note how tcp_cwnd is incremented.
11594 					 * The first dup ACK will increase
11595 					 * it by 1 MSS.  The second dup ACK
11596 					 * will increase it by 2 MSS.  This
11597 					 * means that only 1 new segment will
11598 					 * be sent for each dup ACK.
11599 					 */
11600 					if (tcp->tcp_unsent > 0 &&
11601 					    (!tcp->tcp_snd_sack_ok ||
11602 					    (tcp->tcp_snd_sack_ok &&
11603 					    tcp->tcp_notsack_list != NULL))) {
11604 						tcp->tcp_cwnd += mss <<
11605 						    (tcp->tcp_dupack_cnt - 1);
11606 						flags |= TH_LIMIT_XMIT;
11607 					}
11608 				} else if (dupack_cnt ==
11609 				    tcps->tcps_dupack_fast_retransmit) {
11610 
11611 				/*
11612 				 * If we have reduced tcp_ssthresh
11613 				 * because of ECN, do not reduce it again
11614 				 * unless it is already one window of data
11615 				 * away.  After one window of data, tcp_cwr
11616 				 * should then be cleared.  Note that
11617 				 * for non ECN capable connection, tcp_cwr
11618 				 * should always be false.
11619 				 *
11620 				 * Adjust cwnd since the duplicate
11621 				 * ack indicates that a packet was
11622 				 * dropped (due to congestion.)
11623 				 */
11624 				if (!tcp->tcp_cwr) {
11625 					npkt = ((tcp->tcp_snxt -
11626 					    tcp->tcp_suna) >> 1) / mss;
11627 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
11628 					    mss;
11629 					tcp->tcp_cwnd = (npkt +
11630 					    tcp->tcp_dupack_cnt) * mss;
11631 				}
11632 				if (tcp->tcp_ecn_ok) {
11633 					tcp->tcp_cwr = B_TRUE;
11634 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
11635 					tcp->tcp_ecn_cwr_sent = B_FALSE;
11636 				}
11637 
11638 				/*
11639 				 * We do Hoe's algorithm.  Refer to her
11640 				 * paper "Improving the Start-up Behavior
11641 				 * of a Congestion Control Scheme for TCP,"
11642 				 * appeared in SIGCOMM'96.
11643 				 *
11644 				 * Save highest seq no we have sent so far.
11645 				 * Be careful about the invisible FIN byte.
11646 				 */
11647 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
11648 				    (tcp->tcp_unsent == 0)) {
11649 					tcp->tcp_rexmit_max = tcp->tcp_fss;
11650 				} else {
11651 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
11652 				}
11653 
11654 				/*
11655 				 * Do not allow bursty traffic during.
11656 				 * fast recovery.  Refer to Fall and Floyd's
11657 				 * paper "Simulation-based Comparisons of
11658 				 * Tahoe, Reno and SACK TCP" (in CCR?)
11659 				 * This is a best current practise.
11660 				 */
11661 				tcp->tcp_snd_burst = TCP_CWND_SS;
11662 
11663 				/*
11664 				 * For SACK:
11665 				 * Calculate tcp_pipe, which is the
11666 				 * estimated number of bytes in
11667 				 * network.
11668 				 *
11669 				 * tcp_fack is the highest sack'ed seq num
11670 				 * TCP has received.
11671 				 *
11672 				 * tcp_pipe is explained in the above quoted
11673 				 * Fall and Floyd's paper.  tcp_fack is
11674 				 * explained in Mathis and Mahdavi's
11675 				 * "Forward Acknowledgment: Refining TCP
11676 				 * Congestion Control" in SIGCOMM '96.
11677 				 */
11678 				if (tcp->tcp_snd_sack_ok) {
11679 					ASSERT(tcp->tcp_sack_info != NULL);
11680 					if (tcp->tcp_notsack_list != NULL) {
11681 						tcp->tcp_pipe = tcp->tcp_snxt -
11682 						    tcp->tcp_fack;
11683 						tcp->tcp_sack_snxt = seg_ack;
11684 						flags |= TH_NEED_SACK_REXMIT;
11685 					} else {
11686 						/*
11687 						 * Always initialize tcp_pipe
11688 						 * even though we don't have
11689 						 * any SACK info.  If later
11690 						 * we get SACK info and
11691 						 * tcp_pipe is not initialized,
11692 						 * funny things will happen.
11693 						 */
11694 						tcp->tcp_pipe =
11695 						    tcp->tcp_cwnd_ssthresh;
11696 					}
11697 				} else {
11698 					flags |= TH_REXMIT_NEEDED;
11699 				} /* tcp_snd_sack_ok */
11700 
11701 				} else {
11702 					/*
11703 					 * Here we perform congestion
11704 					 * avoidance, but NOT slow start.
11705 					 * This is known as the Fast
11706 					 * Recovery Algorithm.
11707 					 */
11708 					if (tcp->tcp_snd_sack_ok &&
11709 					    tcp->tcp_notsack_list != NULL) {
11710 						flags |= TH_NEED_SACK_REXMIT;
11711 						tcp->tcp_pipe -= mss;
11712 						if (tcp->tcp_pipe < 0)
11713 							tcp->tcp_pipe = 0;
11714 					} else {
11715 					/*
11716 					 * We know that one more packet has
11717 					 * left the pipe thus we can update
11718 					 * cwnd.
11719 					 */
11720 					cwnd = tcp->tcp_cwnd + mss;
11721 					if (cwnd > tcp->tcp_cwnd_max)
11722 						cwnd = tcp->tcp_cwnd_max;
11723 					tcp->tcp_cwnd = cwnd;
11724 					if (tcp->tcp_unsent > 0)
11725 						flags |= TH_XMIT_NEEDED;
11726 					}
11727 				}
11728 			}
11729 		} else if (tcp->tcp_zero_win_probe) {
11730 			/*
11731 			 * If the window has opened, need to arrange
11732 			 * to send additional data.
11733 			 */
11734 			if (new_swnd != 0) {
11735 				/* tcp_suna != tcp_snxt */
11736 				/* Packet contains a window update */
11737 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
11738 				tcp->tcp_zero_win_probe = 0;
11739 				tcp->tcp_timer_backoff = 0;
11740 				tcp->tcp_ms_we_have_waited = 0;
11741 
11742 				/*
11743 				 * Transmit starting with tcp_suna since
11744 				 * the one byte probe is not ack'ed.
11745 				 * If TCP has sent more than one identical
11746 				 * probe, tcp_rexmit will be set.  That means
11747 				 * tcp_ss_rexmit() will send out the one
11748 				 * byte along with new data.  Otherwise,
11749 				 * fake the retransmission.
11750 				 */
11751 				flags |= TH_XMIT_NEEDED;
11752 				if (!tcp->tcp_rexmit) {
11753 					tcp->tcp_rexmit = B_TRUE;
11754 					tcp->tcp_dupack_cnt = 0;
11755 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
11756 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
11757 				}
11758 			}
11759 		}
11760 		goto swnd_update;
11761 	}
11762 
11763 	/*
11764 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
11765 	 * If the ACK value acks something that we have not yet sent, it might
11766 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
11767 	 * other side.
11768 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
11769 	 * state is handled above, so we can always just drop the segment and
11770 	 * send an ACK here.
11771 	 *
11772 	 * In the case where the peer shrinks the window, we see the new window
11773 	 * update, but all the data sent previously is queued up by the peer.
11774 	 * To account for this, in tcp_process_shrunk_swnd(), the sequence
11775 	 * number, which was already sent, and within window, is recorded.
11776 	 * tcp_snxt is then updated.
11777 	 *
11778 	 * If the window has previously shrunk, and an ACK for data not yet
11779 	 * sent, according to tcp_snxt is recieved, it may still be valid. If
11780 	 * the ACK is for data within the window at the time the window was
11781 	 * shrunk, then the ACK is acceptable. In this case tcp_snxt is set to
11782 	 * the sequence number ACK'ed.
11783 	 *
11784 	 * If the ACK covers all the data sent at the time the window was
11785 	 * shrunk, we can now set tcp_is_wnd_shrnk to B_FALSE.
11786 	 *
11787 	 * Should we send ACKs in response to ACK only segments?
11788 	 */
11789 
11790 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
11791 		if ((tcp->tcp_is_wnd_shrnk) &&
11792 		    (SEQ_LEQ(seg_ack, tcp->tcp_snxt_shrunk))) {
11793 			uint32_t data_acked_ahead_snxt;
11794 
11795 			data_acked_ahead_snxt = seg_ack - tcp->tcp_snxt;
11796 			tcp_update_xmit_tail(tcp, seg_ack);
11797 			tcp->tcp_unsent -= data_acked_ahead_snxt;
11798 		} else {
11799 			BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
11800 			/* drop the received segment */
11801 			freemsg(mp);
11802 
11803 			/*
11804 			 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
11805 			 * greater than 0, check if the number of such
11806 			 * bogus ACks is greater than that count.  If yes,
11807 			 * don't send back any ACK.  This prevents TCP from
11808 			 * getting into an ACK storm if somehow an attacker
11809 			 * successfully spoofs an acceptable segment to our
11810 			 * peer.  If this continues (count > 2 X threshold),
11811 			 * we should abort this connection.
11812 			 */
11813 			if (tcp_drop_ack_unsent_cnt > 0 &&
11814 			    ++tcp->tcp_in_ack_unsent >
11815 			    tcp_drop_ack_unsent_cnt) {
11816 				TCP_STAT(tcps, tcp_in_ack_unsent_drop);
11817 				if (tcp->tcp_in_ack_unsent > 2 *
11818 				    tcp_drop_ack_unsent_cnt) {
11819 					(void) tcp_clean_death(tcp, EPROTO, 20);
11820 				}
11821 				return;
11822 			}
11823 			mp = tcp_ack_mp(tcp);
11824 			if (mp != NULL) {
11825 				BUMP_LOCAL(tcp->tcp_obsegs);
11826 				BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
11827 				tcp_send_data(tcp, mp);
11828 			}
11829 			return;
11830 		}
11831 	} else if (tcp->tcp_is_wnd_shrnk && SEQ_GEQ(seg_ack,
11832 	    tcp->tcp_snxt_shrunk)) {
11833 			tcp->tcp_is_wnd_shrnk = B_FALSE;
11834 	}
11835 
11836 	/*
11837 	 * TCP gets a new ACK, update the notsack'ed list to delete those
11838 	 * blocks that are covered by this ACK.
11839 	 */
11840 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
11841 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
11842 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
11843 	}
11844 
11845 	/*
11846 	 * If we got an ACK after fast retransmit, check to see
11847 	 * if it is a partial ACK.  If it is not and the congestion
11848 	 * window was inflated to account for the other side's
11849 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
11850 	 */
11851 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
11852 		ASSERT(tcp->tcp_rexmit == B_FALSE);
11853 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
11854 			tcp->tcp_dupack_cnt = 0;
11855 			/*
11856 			 * Restore the orig tcp_cwnd_ssthresh after
11857 			 * fast retransmit phase.
11858 			 */
11859 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
11860 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
11861 			}
11862 			tcp->tcp_rexmit_max = seg_ack;
11863 			tcp->tcp_cwnd_cnt = 0;
11864 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
11865 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11866 
11867 			/*
11868 			 * Remove all notsack info to avoid confusion with
11869 			 * the next fast retrasnmit/recovery phase.
11870 			 */
11871 			if (tcp->tcp_snd_sack_ok &&
11872 			    tcp->tcp_notsack_list != NULL) {
11873 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
11874 				    tcp);
11875 			}
11876 		} else {
11877 			if (tcp->tcp_snd_sack_ok &&
11878 			    tcp->tcp_notsack_list != NULL) {
11879 				flags |= TH_NEED_SACK_REXMIT;
11880 				tcp->tcp_pipe -= mss;
11881 				if (tcp->tcp_pipe < 0)
11882 					tcp->tcp_pipe = 0;
11883 			} else {
11884 				/*
11885 				 * Hoe's algorithm:
11886 				 *
11887 				 * Retransmit the unack'ed segment and
11888 				 * restart fast recovery.  Note that we
11889 				 * need to scale back tcp_cwnd to the
11890 				 * original value when we started fast
11891 				 * recovery.  This is to prevent overly
11892 				 * aggressive behaviour in sending new
11893 				 * segments.
11894 				 */
11895 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
11896 				    tcps->tcps_dupack_fast_retransmit * mss;
11897 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
11898 				flags |= TH_REXMIT_NEEDED;
11899 			}
11900 		}
11901 	} else {
11902 		tcp->tcp_dupack_cnt = 0;
11903 		if (tcp->tcp_rexmit) {
11904 			/*
11905 			 * TCP is retranmitting.  If the ACK ack's all
11906 			 * outstanding data, update tcp_rexmit_max and
11907 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
11908 			 * to the correct value.
11909 			 *
11910 			 * Note that SEQ_LEQ() is used.  This is to avoid
11911 			 * unnecessary fast retransmit caused by dup ACKs
11912 			 * received when TCP does slow start retransmission
11913 			 * after a time out.  During this phase, TCP may
11914 			 * send out segments which are already received.
11915 			 * This causes dup ACKs to be sent back.
11916 			 */
11917 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
11918 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
11919 					tcp->tcp_rexmit_nxt = seg_ack;
11920 				}
11921 				if (seg_ack != tcp->tcp_rexmit_max) {
11922 					flags |= TH_XMIT_NEEDED;
11923 				}
11924 			} else {
11925 				tcp->tcp_rexmit = B_FALSE;
11926 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
11927 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
11928 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11929 			}
11930 			tcp->tcp_ms_we_have_waited = 0;
11931 		}
11932 	}
11933 
11934 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
11935 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
11936 	tcp->tcp_suna = seg_ack;
11937 	if (tcp->tcp_zero_win_probe != 0) {
11938 		tcp->tcp_zero_win_probe = 0;
11939 		tcp->tcp_timer_backoff = 0;
11940 	}
11941 
11942 	/*
11943 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
11944 	 * Note that it cannot be the SYN being ack'ed.  The code flow
11945 	 * will not reach here.
11946 	 */
11947 	if (mp1 == NULL) {
11948 		goto fin_acked;
11949 	}
11950 
11951 	/*
11952 	 * Update the congestion window.
11953 	 *
11954 	 * If TCP is not ECN capable or TCP is ECN capable but the
11955 	 * congestion experience bit is not set, increase the tcp_cwnd as
11956 	 * usual.
11957 	 */
11958 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
11959 		cwnd = tcp->tcp_cwnd;
11960 		add = mss;
11961 
11962 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
11963 			/*
11964 			 * This is to prevent an increase of less than 1 MSS of
11965 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
11966 			 * may send out tinygrams in order to preserve mblk
11967 			 * boundaries.
11968 			 *
11969 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
11970 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
11971 			 * increased by 1 MSS for every RTTs.
11972 			 */
11973 			if (tcp->tcp_cwnd_cnt <= 0) {
11974 				tcp->tcp_cwnd_cnt = cwnd + add;
11975 			} else {
11976 				tcp->tcp_cwnd_cnt -= add;
11977 				add = 0;
11978 			}
11979 		}
11980 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
11981 	}
11982 
11983 	/* See if the latest urgent data has been acknowledged */
11984 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
11985 	    SEQ_GT(seg_ack, tcp->tcp_urg))
11986 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
11987 
11988 	/* Can we update the RTT estimates? */
11989 	if (tcp->tcp_snd_ts_ok) {
11990 		/* Ignore zero timestamp echo-reply. */
11991 		if (tcpopt.tcp_opt_ts_ecr != 0) {
11992 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
11993 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
11994 		}
11995 
11996 		/* If needed, restart the timer. */
11997 		if (tcp->tcp_set_timer == 1) {
11998 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
11999 			tcp->tcp_set_timer = 0;
12000 		}
12001 		/*
12002 		 * Update tcp_csuna in case the other side stops sending
12003 		 * us timestamps.
12004 		 */
12005 		tcp->tcp_csuna = tcp->tcp_snxt;
12006 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
12007 		/*
12008 		 * An ACK sequence we haven't seen before, so get the RTT
12009 		 * and update the RTO. But first check if the timestamp is
12010 		 * valid to use.
12011 		 */
12012 		if ((mp1->b_next != NULL) &&
12013 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
12014 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
12015 			    (int32_t)(intptr_t)mp1->b_prev);
12016 		else
12017 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
12018 
12019 		/* Remeber the last sequence to be ACKed */
12020 		tcp->tcp_csuna = seg_ack;
12021 		if (tcp->tcp_set_timer == 1) {
12022 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
12023 			tcp->tcp_set_timer = 0;
12024 		}
12025 	} else {
12026 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
12027 	}
12028 
12029 	/* Eat acknowledged bytes off the xmit queue. */
12030 	for (;;) {
12031 		mblk_t	*mp2;
12032 		uchar_t	*wptr;
12033 
12034 		wptr = mp1->b_wptr;
12035 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
12036 		bytes_acked -= (int)(wptr - mp1->b_rptr);
12037 		if (bytes_acked < 0) {
12038 			mp1->b_rptr = wptr + bytes_acked;
12039 			/*
12040 			 * Set a new timestamp if all the bytes timed by the
12041 			 * old timestamp have been ack'ed.
12042 			 */
12043 			if (SEQ_GT(seg_ack,
12044 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
12045 				mp1->b_prev =
12046 				    (mblk_t *)(uintptr_t)LBOLT_FASTPATH;
12047 				mp1->b_next = NULL;
12048 			}
12049 			break;
12050 		}
12051 		mp1->b_next = NULL;
12052 		mp1->b_prev = NULL;
12053 		mp2 = mp1;
12054 		mp1 = mp1->b_cont;
12055 
12056 		/*
12057 		 * This notification is required for some zero-copy
12058 		 * clients to maintain a copy semantic. After the data
12059 		 * is ack'ed, client is safe to modify or reuse the buffer.
12060 		 */
12061 		if (tcp->tcp_snd_zcopy_aware &&
12062 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
12063 			tcp_zcopy_notify(tcp);
12064 		freeb(mp2);
12065 		if (bytes_acked == 0) {
12066 			if (mp1 == NULL) {
12067 				/* Everything is ack'ed, clear the tail. */
12068 				tcp->tcp_xmit_tail = NULL;
12069 				/*
12070 				 * Cancel the timer unless we are still
12071 				 * waiting for an ACK for the FIN packet.
12072 				 */
12073 				if (tcp->tcp_timer_tid != 0 &&
12074 				    tcp->tcp_snxt == tcp->tcp_suna) {
12075 					(void) TCP_TIMER_CANCEL(tcp,
12076 					    tcp->tcp_timer_tid);
12077 					tcp->tcp_timer_tid = 0;
12078 				}
12079 				goto pre_swnd_update;
12080 			}
12081 			if (mp2 != tcp->tcp_xmit_tail)
12082 				break;
12083 			tcp->tcp_xmit_tail = mp1;
12084 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12085 			    (uintptr_t)INT_MAX);
12086 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
12087 			    mp1->b_rptr);
12088 			break;
12089 		}
12090 		if (mp1 == NULL) {
12091 			/*
12092 			 * More was acked but there is nothing more
12093 			 * outstanding.  This means that the FIN was
12094 			 * just acked or that we're talking to a clown.
12095 			 */
12096 fin_acked:
12097 			ASSERT(tcp->tcp_fin_sent);
12098 			tcp->tcp_xmit_tail = NULL;
12099 			if (tcp->tcp_fin_sent) {
12100 				/* FIN was acked - making progress */
12101 				if (!tcp->tcp_fin_acked)
12102 					tcp->tcp_ip_forward_progress = B_TRUE;
12103 				tcp->tcp_fin_acked = B_TRUE;
12104 				if (tcp->tcp_linger_tid != 0 &&
12105 				    TCP_TIMER_CANCEL(tcp,
12106 				    tcp->tcp_linger_tid) >= 0) {
12107 					tcp_stop_lingering(tcp);
12108 					freemsg(mp);
12109 					mp = NULL;
12110 				}
12111 			} else {
12112 				/*
12113 				 * We should never get here because
12114 				 * we have already checked that the
12115 				 * number of bytes ack'ed should be
12116 				 * smaller than or equal to what we
12117 				 * have sent so far (it is the
12118 				 * acceptability check of the ACK).
12119 				 * We can only get here if the send
12120 				 * queue is corrupted.
12121 				 *
12122 				 * Terminate the connection and
12123 				 * panic the system.  It is better
12124 				 * for us to panic instead of
12125 				 * continuing to avoid other disaster.
12126 				 */
12127 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
12128 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
12129 				panic("Memory corruption "
12130 				    "detected for connection %s.",
12131 				    tcp_display(tcp, NULL,
12132 				    DISP_ADDR_AND_PORT));
12133 				/*NOTREACHED*/
12134 			}
12135 			goto pre_swnd_update;
12136 		}
12137 		ASSERT(mp2 != tcp->tcp_xmit_tail);
12138 	}
12139 	if (tcp->tcp_unsent) {
12140 		flags |= TH_XMIT_NEEDED;
12141 	}
12142 pre_swnd_update:
12143 	tcp->tcp_xmit_head = mp1;
12144 swnd_update:
12145 	/*
12146 	 * The following check is different from most other implementations.
12147 	 * For bi-directional transfer, when segments are dropped, the
12148 	 * "normal" check will not accept a window update in those
12149 	 * retransmitted segemnts.  Failing to do that, TCP may send out
12150 	 * segments which are outside receiver's window.  As TCP accepts
12151 	 * the ack in those retransmitted segments, if the window update in
12152 	 * the same segment is not accepted, TCP will incorrectly calculates
12153 	 * that it can send more segments.  This can create a deadlock
12154 	 * with the receiver if its window becomes zero.
12155 	 */
12156 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
12157 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
12158 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
12159 		/*
12160 		 * The criteria for update is:
12161 		 *
12162 		 * 1. the segment acknowledges some data.  Or
12163 		 * 2. the segment is new, i.e. it has a higher seq num. Or
12164 		 * 3. the segment is not old and the advertised window is
12165 		 * larger than the previous advertised window.
12166 		 */
12167 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
12168 			flags |= TH_XMIT_NEEDED;
12169 		tcp->tcp_swnd = new_swnd;
12170 		if (new_swnd > tcp->tcp_max_swnd)
12171 			tcp->tcp_max_swnd = new_swnd;
12172 		tcp->tcp_swl1 = seg_seq;
12173 		tcp->tcp_swl2 = seg_ack;
12174 	}
12175 est:
12176 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
12177 
12178 		switch (tcp->tcp_state) {
12179 		case TCPS_FIN_WAIT_1:
12180 			if (tcp->tcp_fin_acked) {
12181 				tcp->tcp_state = TCPS_FIN_WAIT_2;
12182 				/*
12183 				 * We implement the non-standard BSD/SunOS
12184 				 * FIN_WAIT_2 flushing algorithm.
12185 				 * If there is no user attached to this
12186 				 * TCP endpoint, then this TCP struct
12187 				 * could hang around forever in FIN_WAIT_2
12188 				 * state if the peer forgets to send us
12189 				 * a FIN.  To prevent this, we wait only
12190 				 * 2*MSL (a convenient time value) for
12191 				 * the FIN to arrive.  If it doesn't show up,
12192 				 * we flush the TCP endpoint.  This algorithm,
12193 				 * though a violation of RFC-793, has worked
12194 				 * for over 10 years in BSD systems.
12195 				 * Note: SunOS 4.x waits 675 seconds before
12196 				 * flushing the FIN_WAIT_2 connection.
12197 				 */
12198 				TCP_TIMER_RESTART(tcp,
12199 				    tcps->tcps_fin_wait_2_flush_interval);
12200 			}
12201 			break;
12202 		case TCPS_FIN_WAIT_2:
12203 			break;	/* Shutdown hook? */
12204 		case TCPS_LAST_ACK:
12205 			freemsg(mp);
12206 			if (tcp->tcp_fin_acked) {
12207 				(void) tcp_clean_death(tcp, 0, 19);
12208 				return;
12209 			}
12210 			goto xmit_check;
12211 		case TCPS_CLOSING:
12212 			if (tcp->tcp_fin_acked)
12213 				SET_TIME_WAIT(tcps, tcp, connp);
12214 			/*FALLTHRU*/
12215 		case TCPS_CLOSE_WAIT:
12216 			freemsg(mp);
12217 			goto xmit_check;
12218 		default:
12219 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
12220 			break;
12221 		}
12222 	}
12223 	if (flags & TH_FIN) {
12224 		/* Make sure we ack the fin */
12225 		flags |= TH_ACK_NEEDED;
12226 		if (!tcp->tcp_fin_rcvd) {
12227 			tcp->tcp_fin_rcvd = B_TRUE;
12228 			tcp->tcp_rnxt++;
12229 			tcpha = tcp->tcp_tcpha;
12230 			tcpha->tha_ack = htonl(tcp->tcp_rnxt);
12231 
12232 			/*
12233 			 * Generate the ordrel_ind at the end unless we
12234 			 * are an eager guy.
12235 			 * In the eager case tcp_rsrv will do this when run
12236 			 * after tcp_accept is done.
12237 			 */
12238 			if (tcp->tcp_listener == NULL &&
12239 			    !TCP_IS_DETACHED(tcp) && !tcp->tcp_hard_binding)
12240 				flags |= TH_ORDREL_NEEDED;
12241 			switch (tcp->tcp_state) {
12242 			case TCPS_SYN_RCVD:
12243 			case TCPS_ESTABLISHED:
12244 				tcp->tcp_state = TCPS_CLOSE_WAIT;
12245 				/* Keepalive? */
12246 				break;
12247 			case TCPS_FIN_WAIT_1:
12248 				if (!tcp->tcp_fin_acked) {
12249 					tcp->tcp_state = TCPS_CLOSING;
12250 					break;
12251 				}
12252 				/* FALLTHRU */
12253 			case TCPS_FIN_WAIT_2:
12254 				SET_TIME_WAIT(tcps, tcp, connp);
12255 				if (seg_len) {
12256 					/*
12257 					 * implies data piggybacked on FIN.
12258 					 * break to handle data.
12259 					 */
12260 					break;
12261 				}
12262 				freemsg(mp);
12263 				goto ack_check;
12264 			}
12265 		}
12266 	}
12267 	if (mp == NULL)
12268 		goto xmit_check;
12269 	if (seg_len == 0) {
12270 		freemsg(mp);
12271 		goto xmit_check;
12272 	}
12273 	if (mp->b_rptr == mp->b_wptr) {
12274 		/*
12275 		 * The header has been consumed, so we remove the
12276 		 * zero-length mblk here.
12277 		 */
12278 		mp1 = mp;
12279 		mp = mp->b_cont;
12280 		freeb(mp1);
12281 	}
12282 update_ack:
12283 	tcpha = tcp->tcp_tcpha;
12284 	tcp->tcp_rack_cnt++;
12285 	{
12286 		uint32_t cur_max;
12287 
12288 		cur_max = tcp->tcp_rack_cur_max;
12289 		if (tcp->tcp_rack_cnt >= cur_max) {
12290 			/*
12291 			 * We have more unacked data than we should - send
12292 			 * an ACK now.
12293 			 */
12294 			flags |= TH_ACK_NEEDED;
12295 			cur_max++;
12296 			if (cur_max > tcp->tcp_rack_abs_max)
12297 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
12298 			else
12299 				tcp->tcp_rack_cur_max = cur_max;
12300 		} else if (TCP_IS_DETACHED(tcp)) {
12301 			/* We don't have an ACK timer for detached TCP. */
12302 			flags |= TH_ACK_NEEDED;
12303 		} else if (seg_len < mss) {
12304 			/*
12305 			 * If we get a segment that is less than an mss, and we
12306 			 * already have unacknowledged data, and the amount
12307 			 * unacknowledged is not a multiple of mss, then we
12308 			 * better generate an ACK now.  Otherwise, this may be
12309 			 * the tail piece of a transaction, and we would rather
12310 			 * wait for the response.
12311 			 */
12312 			uint32_t udif;
12313 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
12314 			    (uintptr_t)INT_MAX);
12315 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
12316 			if (udif && (udif % mss))
12317 				flags |= TH_ACK_NEEDED;
12318 			else
12319 				flags |= TH_ACK_TIMER_NEEDED;
12320 		} else {
12321 			/* Start delayed ack timer */
12322 			flags |= TH_ACK_TIMER_NEEDED;
12323 		}
12324 	}
12325 	tcp->tcp_rnxt += seg_len;
12326 	tcpha->tha_ack = htonl(tcp->tcp_rnxt);
12327 
12328 	if (mp == NULL)
12329 		goto xmit_check;
12330 
12331 	/* Update SACK list */
12332 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
12333 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
12334 		    &(tcp->tcp_num_sack_blk));
12335 	}
12336 
12337 	if (tcp->tcp_urp_mp) {
12338 		tcp->tcp_urp_mp->b_cont = mp;
12339 		mp = tcp->tcp_urp_mp;
12340 		tcp->tcp_urp_mp = NULL;
12341 		/* Ready for a new signal. */
12342 		tcp->tcp_urp_last_valid = B_FALSE;
12343 #ifdef DEBUG
12344 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12345 		    "tcp_rput: sending exdata_ind %s",
12346 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
12347 #endif /* DEBUG */
12348 	}
12349 
12350 	/*
12351 	 * Check for ancillary data changes compared to last segment.
12352 	 */
12353 	if (connp->conn_recv_ancillary.crb_all != 0) {
12354 		mp = tcp_input_add_ancillary(tcp, mp, &ipp, ira);
12355 		if (mp == NULL)
12356 			return;
12357 	}
12358 
12359 	if (tcp->tcp_listener != NULL || tcp->tcp_hard_binding) {
12360 		/*
12361 		 * Side queue inbound data until the accept happens.
12362 		 * tcp_accept/tcp_rput drains this when the accept happens.
12363 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
12364 		 * T_EXDATA_IND) it is queued on b_next.
12365 		 * XXX Make urgent data use this. Requires:
12366 		 *	Removing tcp_listener check for TH_URG
12367 		 *	Making M_PCPROTO and MARK messages skip the eager case
12368 		 */
12369 
12370 		if (tcp->tcp_kssl_pending) {
12371 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
12372 			    mblk_t *, mp);
12373 			tcp_kssl_input(tcp, mp, ira->ira_cred);
12374 		} else {
12375 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
12376 		}
12377 	} else if (IPCL_IS_NONSTR(connp)) {
12378 		/*
12379 		 * Non-STREAMS socket
12380 		 *
12381 		 * Note that no KSSL processing is done here, because
12382 		 * KSSL is not supported for non-STREAMS sockets.
12383 		 */
12384 		boolean_t push = flags & (TH_PUSH|TH_FIN);
12385 		int error;
12386 
12387 		if ((*connp->conn_upcalls->su_recv)(
12388 		    connp->conn_upper_handle,
12389 		    mp, seg_len, 0, &error, &push) <= 0) {
12390 			/*
12391 			 * We should never be in middle of a
12392 			 * fallback, the squeue guarantees that.
12393 			 */
12394 			ASSERT(error != EOPNOTSUPP);
12395 			if (error == ENOSPC)
12396 				tcp->tcp_rwnd -= seg_len;
12397 		} else if (push) {
12398 			/* PUSH bit set and sockfs is not flow controlled */
12399 			flags |= tcp_rwnd_reopen(tcp);
12400 		}
12401 	} else {
12402 		/* STREAMS socket */
12403 		if (mp->b_datap->db_type != M_DATA ||
12404 		    (flags & TH_MARKNEXT_NEEDED)) {
12405 			if (tcp->tcp_rcv_list != NULL) {
12406 				flags |= tcp_rcv_drain(tcp);
12407 			}
12408 			ASSERT(tcp->tcp_rcv_list == NULL ||
12409 			    tcp->tcp_fused_sigurg);
12410 
12411 			if (flags & TH_MARKNEXT_NEEDED) {
12412 #ifdef DEBUG
12413 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12414 				    "tcp_rput: sending MSGMARKNEXT %s",
12415 				    tcp_display(tcp, NULL,
12416 				    DISP_PORT_ONLY));
12417 #endif /* DEBUG */
12418 				mp->b_flag |= MSGMARKNEXT;
12419 				flags &= ~TH_MARKNEXT_NEEDED;
12420 			}
12421 
12422 			/* Does this need SSL processing first? */
12423 			if ((tcp->tcp_kssl_ctx != NULL) &&
12424 			    (DB_TYPE(mp) == M_DATA)) {
12425 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
12426 				    mblk_t *, mp);
12427 				tcp_kssl_input(tcp, mp, ira->ira_cred);
12428 			} else {
12429 				if (is_system_labeled())
12430 					tcp_setcred_data(mp, ira);
12431 
12432 				putnext(connp->conn_rq, mp);
12433 				if (!canputnext(connp->conn_rq))
12434 					tcp->tcp_rwnd -= seg_len;
12435 			}
12436 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
12437 		    (DB_TYPE(mp) == M_DATA)) {
12438 			/* Does this need SSL processing first? */
12439 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
12440 			tcp_kssl_input(tcp, mp, ira->ira_cred);
12441 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
12442 		    tcp->tcp_rcv_cnt + seg_len >= connp->conn_rcvbuf >> 3) {
12443 			if (tcp->tcp_rcv_list != NULL) {
12444 				/*
12445 				 * Enqueue the new segment first and then
12446 				 * call tcp_rcv_drain() to send all data
12447 				 * up.  The other way to do this is to
12448 				 * send all queued data up and then call
12449 				 * putnext() to send the new segment up.
12450 				 * This way can remove the else part later
12451 				 * on.
12452 				 *
12453 				 * We don't do this to avoid one more call to
12454 				 * canputnext() as tcp_rcv_drain() needs to
12455 				 * call canputnext().
12456 				 */
12457 				tcp_rcv_enqueue(tcp, mp, seg_len,
12458 				    ira->ira_cred);
12459 				flags |= tcp_rcv_drain(tcp);
12460 			} else {
12461 				if (is_system_labeled())
12462 					tcp_setcred_data(mp, ira);
12463 
12464 				putnext(connp->conn_rq, mp);
12465 				if (!canputnext(connp->conn_rq))
12466 					tcp->tcp_rwnd -= seg_len;
12467 			}
12468 		} else {
12469 			/*
12470 			 * Enqueue all packets when processing an mblk
12471 			 * from the co queue and also enqueue normal packets.
12472 			 */
12473 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
12474 		}
12475 		/*
12476 		 * Make sure the timer is running if we have data waiting
12477 		 * for a push bit. This provides resiliency against
12478 		 * implementations that do not correctly generate push bits.
12479 		 */
12480 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
12481 			/*
12482 			 * The connection may be closed at this point, so don't
12483 			 * do anything for a detached tcp.
12484 			 */
12485 			if (!TCP_IS_DETACHED(tcp))
12486 				tcp->tcp_push_tid = TCP_TIMER(tcp,
12487 				    tcp_push_timer,
12488 				    MSEC_TO_TICK(
12489 				    tcps->tcps_push_timer_interval));
12490 		}
12491 	}
12492 
12493 xmit_check:
12494 	/* Is there anything left to do? */
12495 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
12496 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
12497 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
12498 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
12499 		goto done;
12500 
12501 	/* Any transmit work to do and a non-zero window? */
12502 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
12503 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
12504 		if (flags & TH_REXMIT_NEEDED) {
12505 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
12506 
12507 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
12508 			if (snd_size > mss)
12509 				snd_size = mss;
12510 			if (snd_size > tcp->tcp_swnd)
12511 				snd_size = tcp->tcp_swnd;
12512 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
12513 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
12514 			    B_TRUE);
12515 
12516 			if (mp1 != NULL) {
12517 				tcp->tcp_xmit_head->b_prev =
12518 				    (mblk_t *)LBOLT_FASTPATH;
12519 				tcp->tcp_csuna = tcp->tcp_snxt;
12520 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12521 				UPDATE_MIB(&tcps->tcps_mib,
12522 				    tcpRetransBytes, snd_size);
12523 				tcp_send_data(tcp, mp1);
12524 			}
12525 		}
12526 		if (flags & TH_NEED_SACK_REXMIT) {
12527 			tcp_sack_rxmit(tcp, &flags);
12528 		}
12529 		/*
12530 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
12531 		 * out new segment.  Note that tcp_rexmit should not be
12532 		 * set, otherwise TH_LIMIT_XMIT should not be set.
12533 		 */
12534 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
12535 			if (!tcp->tcp_rexmit) {
12536 				tcp_wput_data(tcp, NULL, B_FALSE);
12537 			} else {
12538 				tcp_ss_rexmit(tcp);
12539 			}
12540 		}
12541 		/*
12542 		 * Adjust tcp_cwnd back to normal value after sending
12543 		 * new data segments.
12544 		 */
12545 		if (flags & TH_LIMIT_XMIT) {
12546 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
12547 			/*
12548 			 * This will restart the timer.  Restarting the
12549 			 * timer is used to avoid a timeout before the
12550 			 * limited transmitted segment's ACK gets back.
12551 			 */
12552 			if (tcp->tcp_xmit_head != NULL)
12553 				tcp->tcp_xmit_head->b_prev =
12554 				    (mblk_t *)LBOLT_FASTPATH;
12555 		}
12556 
12557 		/* Anything more to do? */
12558 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
12559 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
12560 			goto done;
12561 	}
12562 ack_check:
12563 	if (flags & TH_SEND_URP_MARK) {
12564 		ASSERT(tcp->tcp_urp_mark_mp);
12565 		ASSERT(!IPCL_IS_NONSTR(connp));
12566 		/*
12567 		 * Send up any queued data and then send the mark message
12568 		 */
12569 		if (tcp->tcp_rcv_list != NULL) {
12570 			flags |= tcp_rcv_drain(tcp);
12571 
12572 		}
12573 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
12574 		mp1 = tcp->tcp_urp_mark_mp;
12575 		tcp->tcp_urp_mark_mp = NULL;
12576 		if (is_system_labeled())
12577 			tcp_setcred_data(mp1, ira);
12578 
12579 		putnext(connp->conn_rq, mp1);
12580 #ifdef DEBUG
12581 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12582 		    "tcp_rput: sending zero-length %s %s",
12583 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
12584 		    "MSGNOTMARKNEXT"),
12585 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
12586 #endif /* DEBUG */
12587 		flags &= ~TH_SEND_URP_MARK;
12588 	}
12589 	if (flags & TH_ACK_NEEDED) {
12590 		/*
12591 		 * Time to send an ack for some reason.
12592 		 */
12593 		mp1 = tcp_ack_mp(tcp);
12594 
12595 		if (mp1 != NULL) {
12596 			tcp_send_data(tcp, mp1);
12597 			BUMP_LOCAL(tcp->tcp_obsegs);
12598 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
12599 		}
12600 		if (tcp->tcp_ack_tid != 0) {
12601 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
12602 			tcp->tcp_ack_tid = 0;
12603 		}
12604 	}
12605 	if (flags & TH_ACK_TIMER_NEEDED) {
12606 		/*
12607 		 * Arrange for deferred ACK or push wait timeout.
12608 		 * Start timer if it is not already running.
12609 		 */
12610 		if (tcp->tcp_ack_tid == 0) {
12611 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
12612 			    MSEC_TO_TICK(tcp->tcp_localnet ?
12613 			    (clock_t)tcps->tcps_local_dack_interval :
12614 			    (clock_t)tcps->tcps_deferred_ack_interval));
12615 		}
12616 	}
12617 	if (flags & TH_ORDREL_NEEDED) {
12618 		/*
12619 		 * Send up the ordrel_ind unless we are an eager guy.
12620 		 * In the eager case tcp_rsrv will do this when run
12621 		 * after tcp_accept is done.
12622 		 */
12623 		ASSERT(tcp->tcp_listener == NULL);
12624 		ASSERT(!tcp->tcp_detached);
12625 
12626 		if (IPCL_IS_NONSTR(connp)) {
12627 			ASSERT(tcp->tcp_ordrel_mp == NULL);
12628 			tcp->tcp_ordrel_done = B_TRUE;
12629 			(*connp->conn_upcalls->su_opctl)
12630 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
12631 			goto done;
12632 		}
12633 
12634 		if (tcp->tcp_rcv_list != NULL) {
12635 			/*
12636 			 * Push any mblk(s) enqueued from co processing.
12637 			 */
12638 			flags |= tcp_rcv_drain(tcp);
12639 		}
12640 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
12641 
12642 		mp1 = tcp->tcp_ordrel_mp;
12643 		tcp->tcp_ordrel_mp = NULL;
12644 		tcp->tcp_ordrel_done = B_TRUE;
12645 		putnext(connp->conn_rq, mp1);
12646 	}
12647 done:
12648 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
12649 }
12650 
12651 /*
12652  * This routine adjusts next-to-send sequence number variables, in the
12653  * case where the reciever has shrunk it's window.
12654  */
12655 static void
12656 tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt)
12657 {
12658 	mblk_t *xmit_tail;
12659 	int32_t offset;
12660 
12661 	tcp->tcp_snxt = snxt;
12662 
12663 	/* Get the mblk, and the offset in it, as per the shrunk window */
12664 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
12665 	ASSERT(xmit_tail != NULL);
12666 	tcp->tcp_xmit_tail = xmit_tail;
12667 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr -
12668 	    xmit_tail->b_rptr - offset;
12669 }
12670 
12671 /*
12672  * This function does PAWS protection check. Returns B_TRUE if the
12673  * segment passes the PAWS test, else returns B_FALSE.
12674  */
12675 boolean_t
12676 tcp_paws_check(tcp_t *tcp, tcpha_t *tcpha, tcp_opt_t *tcpoptp)
12677 {
12678 	uint8_t	flags;
12679 	int	options;
12680 	uint8_t *up;
12681 	conn_t	*connp = tcp->tcp_connp;
12682 
12683 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
12684 	/*
12685 	 * If timestamp option is aligned nicely, get values inline,
12686 	 * otherwise call general routine to parse.  Only do that
12687 	 * if timestamp is the only option.
12688 	 */
12689 	if (TCP_HDR_LENGTH(tcpha) == (uint32_t)TCP_MIN_HEADER_LENGTH +
12690 	    TCPOPT_REAL_TS_LEN &&
12691 	    OK_32PTR((up = ((uint8_t *)tcpha) +
12692 	    TCP_MIN_HEADER_LENGTH)) &&
12693 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
12694 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
12695 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
12696 
12697 		options = TCP_OPT_TSTAMP_PRESENT;
12698 	} else {
12699 		if (tcp->tcp_snd_sack_ok) {
12700 			tcpoptp->tcp = tcp;
12701 		} else {
12702 			tcpoptp->tcp = NULL;
12703 		}
12704 		options = tcp_parse_options(tcpha, tcpoptp);
12705 	}
12706 
12707 	if (options & TCP_OPT_TSTAMP_PRESENT) {
12708 		/*
12709 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
12710 		 * regardless of the timestamp, page 18 RFC 1323.bis.
12711 		 */
12712 		if ((flags & TH_RST) == 0 &&
12713 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
12714 		    tcp->tcp_ts_recent)) {
12715 			if (TSTMP_LT(LBOLT_FASTPATH64,
12716 			    tcp->tcp_last_rcv_lbolt + PAWS_TIMEOUT)) {
12717 				/* This segment is not acceptable. */
12718 				return (B_FALSE);
12719 			} else {
12720 				/*
12721 				 * Connection has been idle for
12722 				 * too long.  Reset the timestamp
12723 				 * and assume the segment is valid.
12724 				 */
12725 				tcp->tcp_ts_recent =
12726 				    tcpoptp->tcp_opt_ts_val;
12727 			}
12728 		}
12729 	} else {
12730 		/*
12731 		 * If we don't get a timestamp on every packet, we
12732 		 * figure we can't really trust 'em, so we stop sending
12733 		 * and parsing them.
12734 		 */
12735 		tcp->tcp_snd_ts_ok = B_FALSE;
12736 
12737 		connp->conn_ht_iphc_len -= TCPOPT_REAL_TS_LEN;
12738 		connp->conn_ht_ulp_len -= TCPOPT_REAL_TS_LEN;
12739 		tcp->tcp_tcpha->tha_offset_and_reserved -= (3 << 4);
12740 		/*
12741 		 * Adjust the tcp_mss and tcp_cwnd accordingly. We avoid
12742 		 * doing a slow start here so as to not to lose on the
12743 		 * transfer rate built up so far.
12744 		 */
12745 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
12746 		if (tcp->tcp_snd_sack_ok) {
12747 			ASSERT(tcp->tcp_sack_info != NULL);
12748 			tcp->tcp_max_sack_blk = 4;
12749 		}
12750 	}
12751 	return (B_TRUE);
12752 }
12753 
12754 /*
12755  * Attach ancillary data to a received TCP segments for the
12756  * ancillary pieces requested by the application that are
12757  * different than they were in the previous data segment.
12758  *
12759  * Save the "current" values once memory allocation is ok so that
12760  * when memory allocation fails we can just wait for the next data segment.
12761  */
12762 static mblk_t *
12763 tcp_input_add_ancillary(tcp_t *tcp, mblk_t *mp, ip_pkt_t *ipp,
12764     ip_recv_attr_t *ira)
12765 {
12766 	struct T_optdata_ind *todi;
12767 	int optlen;
12768 	uchar_t *optptr;
12769 	struct T_opthdr *toh;
12770 	crb_t addflag;	/* Which pieces to add */
12771 	mblk_t *mp1;
12772 	conn_t	*connp = tcp->tcp_connp;
12773 
12774 	optlen = 0;
12775 	addflag.crb_all = 0;
12776 	/* If app asked for pktinfo and the index has changed ... */
12777 	if (connp->conn_recv_ancillary.crb_ip_recvpktinfo &&
12778 	    ira->ira_ruifindex != tcp->tcp_recvifindex) {
12779 		optlen += sizeof (struct T_opthdr) +
12780 		    sizeof (struct in6_pktinfo);
12781 		addflag.crb_ip_recvpktinfo = 1;
12782 	}
12783 	/* If app asked for hoplimit and it has changed ... */
12784 	if (connp->conn_recv_ancillary.crb_ipv6_recvhoplimit &&
12785 	    ipp->ipp_hoplimit != tcp->tcp_recvhops) {
12786 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
12787 		addflag.crb_ipv6_recvhoplimit = 1;
12788 	}
12789 	/* If app asked for tclass and it has changed ... */
12790 	if (connp->conn_recv_ancillary.crb_ipv6_recvtclass &&
12791 	    ipp->ipp_tclass != tcp->tcp_recvtclass) {
12792 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
12793 		addflag.crb_ipv6_recvtclass = 1;
12794 	}
12795 	/*
12796 	 * If app asked for hopbyhop headers and it has changed ...
12797 	 * For security labels, note that (1) security labels can't change on
12798 	 * a connected socket at all, (2) we're connected to at most one peer,
12799 	 * (3) if anything changes, then it must be some other extra option.
12800 	 */
12801 	if (connp->conn_recv_ancillary.crb_ipv6_recvhopopts &&
12802 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
12803 	    (ipp->ipp_fields & IPPF_HOPOPTS),
12804 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
12805 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
12806 		addflag.crb_ipv6_recvhopopts = 1;
12807 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
12808 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
12809 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
12810 			return (mp);
12811 	}
12812 	/* If app asked for dst headers before routing headers ... */
12813 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdrdstopts &&
12814 	    ip_cmpbuf(tcp->tcp_rthdrdstopts, tcp->tcp_rthdrdstoptslen,
12815 	    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12816 	    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen)) {
12817 		optlen += sizeof (struct T_opthdr) +
12818 		    ipp->ipp_rthdrdstoptslen;
12819 		addflag.crb_ipv6_recvrthdrdstopts = 1;
12820 		if (!ip_allocbuf((void **)&tcp->tcp_rthdrdstopts,
12821 		    &tcp->tcp_rthdrdstoptslen,
12822 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12823 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen))
12824 			return (mp);
12825 	}
12826 	/* If app asked for routing headers and it has changed ... */
12827 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdr &&
12828 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
12829 	    (ipp->ipp_fields & IPPF_RTHDR),
12830 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
12831 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
12832 		addflag.crb_ipv6_recvrthdr = 1;
12833 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
12834 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
12835 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
12836 			return (mp);
12837 	}
12838 	/* If app asked for dest headers and it has changed ... */
12839 	if ((connp->conn_recv_ancillary.crb_ipv6_recvdstopts ||
12840 	    connp->conn_recv_ancillary.crb_old_ipv6_recvdstopts) &&
12841 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
12842 	    (ipp->ipp_fields & IPPF_DSTOPTS),
12843 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
12844 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
12845 		addflag.crb_ipv6_recvdstopts = 1;
12846 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
12847 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
12848 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
12849 			return (mp);
12850 	}
12851 
12852 	if (optlen == 0) {
12853 		/* Nothing to add */
12854 		return (mp);
12855 	}
12856 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
12857 	if (mp1 == NULL) {
12858 		/*
12859 		 * Defer sending ancillary data until the next TCP segment
12860 		 * arrives.
12861 		 */
12862 		return (mp);
12863 	}
12864 	mp1->b_cont = mp;
12865 	mp = mp1;
12866 	mp->b_wptr += sizeof (*todi) + optlen;
12867 	mp->b_datap->db_type = M_PROTO;
12868 	todi = (struct T_optdata_ind *)mp->b_rptr;
12869 	todi->PRIM_type = T_OPTDATA_IND;
12870 	todi->DATA_flag = 1;	/* MORE data */
12871 	todi->OPT_length = optlen;
12872 	todi->OPT_offset = sizeof (*todi);
12873 	optptr = (uchar_t *)&todi[1];
12874 	/*
12875 	 * If app asked for pktinfo and the index has changed ...
12876 	 * Note that the local address never changes for the connection.
12877 	 */
12878 	if (addflag.crb_ip_recvpktinfo) {
12879 		struct in6_pktinfo *pkti;
12880 		uint_t ifindex;
12881 
12882 		ifindex = ira->ira_ruifindex;
12883 		toh = (struct T_opthdr *)optptr;
12884 		toh->level = IPPROTO_IPV6;
12885 		toh->name = IPV6_PKTINFO;
12886 		toh->len = sizeof (*toh) + sizeof (*pkti);
12887 		toh->status = 0;
12888 		optptr += sizeof (*toh);
12889 		pkti = (struct in6_pktinfo *)optptr;
12890 		pkti->ipi6_addr = connp->conn_laddr_v6;
12891 		pkti->ipi6_ifindex = ifindex;
12892 		optptr += sizeof (*pkti);
12893 		ASSERT(OK_32PTR(optptr));
12894 		/* Save as "last" value */
12895 		tcp->tcp_recvifindex = ifindex;
12896 	}
12897 	/* If app asked for hoplimit and it has changed ... */
12898 	if (addflag.crb_ipv6_recvhoplimit) {
12899 		toh = (struct T_opthdr *)optptr;
12900 		toh->level = IPPROTO_IPV6;
12901 		toh->name = IPV6_HOPLIMIT;
12902 		toh->len = sizeof (*toh) + sizeof (uint_t);
12903 		toh->status = 0;
12904 		optptr += sizeof (*toh);
12905 		*(uint_t *)optptr = ipp->ipp_hoplimit;
12906 		optptr += sizeof (uint_t);
12907 		ASSERT(OK_32PTR(optptr));
12908 		/* Save as "last" value */
12909 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
12910 	}
12911 	/* If app asked for tclass and it has changed ... */
12912 	if (addflag.crb_ipv6_recvtclass) {
12913 		toh = (struct T_opthdr *)optptr;
12914 		toh->level = IPPROTO_IPV6;
12915 		toh->name = IPV6_TCLASS;
12916 		toh->len = sizeof (*toh) + sizeof (uint_t);
12917 		toh->status = 0;
12918 		optptr += sizeof (*toh);
12919 		*(uint_t *)optptr = ipp->ipp_tclass;
12920 		optptr += sizeof (uint_t);
12921 		ASSERT(OK_32PTR(optptr));
12922 		/* Save as "last" value */
12923 		tcp->tcp_recvtclass = ipp->ipp_tclass;
12924 	}
12925 	if (addflag.crb_ipv6_recvhopopts) {
12926 		toh = (struct T_opthdr *)optptr;
12927 		toh->level = IPPROTO_IPV6;
12928 		toh->name = IPV6_HOPOPTS;
12929 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
12930 		toh->status = 0;
12931 		optptr += sizeof (*toh);
12932 		bcopy((uchar_t *)ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
12933 		optptr += ipp->ipp_hopoptslen;
12934 		ASSERT(OK_32PTR(optptr));
12935 		/* Save as last value */
12936 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
12937 		    (ipp->ipp_fields & IPPF_HOPOPTS),
12938 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
12939 	}
12940 	if (addflag.crb_ipv6_recvrthdrdstopts) {
12941 		toh = (struct T_opthdr *)optptr;
12942 		toh->level = IPPROTO_IPV6;
12943 		toh->name = IPV6_RTHDRDSTOPTS;
12944 		toh->len = sizeof (*toh) + ipp->ipp_rthdrdstoptslen;
12945 		toh->status = 0;
12946 		optptr += sizeof (*toh);
12947 		bcopy(ipp->ipp_rthdrdstopts, optptr, ipp->ipp_rthdrdstoptslen);
12948 		optptr += ipp->ipp_rthdrdstoptslen;
12949 		ASSERT(OK_32PTR(optptr));
12950 		/* Save as last value */
12951 		ip_savebuf((void **)&tcp->tcp_rthdrdstopts,
12952 		    &tcp->tcp_rthdrdstoptslen,
12953 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12954 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
12955 	}
12956 	if (addflag.crb_ipv6_recvrthdr) {
12957 		toh = (struct T_opthdr *)optptr;
12958 		toh->level = IPPROTO_IPV6;
12959 		toh->name = IPV6_RTHDR;
12960 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
12961 		toh->status = 0;
12962 		optptr += sizeof (*toh);
12963 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
12964 		optptr += ipp->ipp_rthdrlen;
12965 		ASSERT(OK_32PTR(optptr));
12966 		/* Save as last value */
12967 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
12968 		    (ipp->ipp_fields & IPPF_RTHDR),
12969 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
12970 	}
12971 	if (addflag.crb_ipv6_recvdstopts) {
12972 		toh = (struct T_opthdr *)optptr;
12973 		toh->level = IPPROTO_IPV6;
12974 		toh->name = IPV6_DSTOPTS;
12975 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
12976 		toh->status = 0;
12977 		optptr += sizeof (*toh);
12978 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
12979 		optptr += ipp->ipp_dstoptslen;
12980 		ASSERT(OK_32PTR(optptr));
12981 		/* Save as last value */
12982 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
12983 		    (ipp->ipp_fields & IPPF_DSTOPTS),
12984 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
12985 	}
12986 	ASSERT(optptr == mp->b_wptr);
12987 	return (mp);
12988 }
12989 
12990 /* ARGSUSED */
12991 static void
12992 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
12993 {
12994 	conn_t	*connp = (conn_t *)arg;
12995 	tcp_t	*tcp = connp->conn_tcp;
12996 	queue_t	*q = connp->conn_rq;
12997 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12998 
12999 	ASSERT(!IPCL_IS_NONSTR(connp));
13000 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
13001 	tcp->tcp_rsrv_mp = mp;
13002 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
13003 
13004 	TCP_STAT(tcps, tcp_rsrv_calls);
13005 
13006 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
13007 		return;
13008 	}
13009 
13010 	if (tcp->tcp_fused) {
13011 		tcp_fuse_backenable(tcp);
13012 		return;
13013 	}
13014 
13015 	if (canputnext(q)) {
13016 		/* Not flow-controlled, open rwnd */
13017 		tcp->tcp_rwnd = connp->conn_rcvbuf;
13018 
13019 		/*
13020 		 * Send back a window update immediately if TCP is above
13021 		 * ESTABLISHED state and the increase of the rcv window
13022 		 * that the other side knows is at least 1 MSS after flow
13023 		 * control is lifted.
13024 		 */
13025 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
13026 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
13027 			tcp_xmit_ctl(NULL, tcp,
13028 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
13029 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
13030 		}
13031 	}
13032 }
13033 
13034 /*
13035  * The read side service routine is called mostly when we get back-enabled as a
13036  * result of flow control relief.  Since we don't actually queue anything in
13037  * TCP, we have no data to send out of here.  What we do is clear the receive
13038  * window, and send out a window update.
13039  */
13040 static void
13041 tcp_rsrv(queue_t *q)
13042 {
13043 	conn_t		*connp = Q_TO_CONN(q);
13044 	tcp_t		*tcp = connp->conn_tcp;
13045 	mblk_t		*mp;
13046 
13047 	/* No code does a putq on the read side */
13048 	ASSERT(q->q_first == NULL);
13049 
13050 	/*
13051 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
13052 	 * been run.  So just return.
13053 	 */
13054 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
13055 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
13056 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
13057 		return;
13058 	}
13059 	tcp->tcp_rsrv_mp = NULL;
13060 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
13061 
13062 	CONN_INC_REF(connp);
13063 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
13064 	    NULL, SQ_PROCESS, SQTAG_TCP_RSRV);
13065 }
13066 
13067 /*
13068  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
13069  * We do not allow the receive window to shrink.  After setting rwnd,
13070  * set the flow control hiwat of the stream.
13071  *
13072  * This function is called in 2 cases:
13073  *
13074  * 1) Before data transfer begins, in tcp_input_listener() for accepting a
13075  *    connection (passive open) and in tcp_input_data() for active connect.
13076  *    This is called after tcp_mss_set() when the desired MSS value is known.
13077  *    This makes sure that our window size is a mutiple of the other side's
13078  *    MSS.
13079  * 2) Handling SO_RCVBUF option.
13080  *
13081  * It is ASSUMED that the requested size is a multiple of the current MSS.
13082  *
13083  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
13084  * user requests so.
13085  */
13086 int
13087 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
13088 {
13089 	uint32_t	mss = tcp->tcp_mss;
13090 	uint32_t	old_max_rwnd;
13091 	uint32_t	max_transmittable_rwnd;
13092 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
13093 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13094 	conn_t		*connp = tcp->tcp_connp;
13095 
13096 	/*
13097 	 * Insist on a receive window that is at least
13098 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
13099 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
13100 	 * and delayed acknowledgement.
13101 	 */
13102 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
13103 
13104 	if (tcp->tcp_fused) {
13105 		size_t sth_hiwat;
13106 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
13107 
13108 		ASSERT(peer_tcp != NULL);
13109 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
13110 		if (!tcp_detached) {
13111 			(void) proto_set_rx_hiwat(connp->conn_rq, connp,
13112 			    sth_hiwat);
13113 			tcp_set_recv_threshold(tcp, sth_hiwat >> 3);
13114 		}
13115 
13116 		/* Caller could have changed tcp_rwnd; update tha_win */
13117 		if (tcp->tcp_tcpha != NULL) {
13118 			tcp->tcp_tcpha->tha_win =
13119 			    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
13120 		}
13121 		if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
13122 			tcp->tcp_cwnd_max = rwnd;
13123 
13124 		/*
13125 		 * In the fusion case, the maxpsz stream head value of
13126 		 * our peer is set according to its send buffer size
13127 		 * and our receive buffer size; since the latter may
13128 		 * have changed we need to update the peer's maxpsz.
13129 		 */
13130 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
13131 		return (sth_hiwat);
13132 	}
13133 
13134 	if (tcp_detached)
13135 		old_max_rwnd = tcp->tcp_rwnd;
13136 	else
13137 		old_max_rwnd = connp->conn_rcvbuf;
13138 
13139 
13140 	/*
13141 	 * If window size info has already been exchanged, TCP should not
13142 	 * shrink the window.  Shrinking window is doable if done carefully.
13143 	 * We may add that support later.  But so far there is not a real
13144 	 * need to do that.
13145 	 */
13146 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
13147 		/* MSS may have changed, do a round up again. */
13148 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
13149 	}
13150 
13151 	/*
13152 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
13153 	 * can be applied even before the window scale option is decided.
13154 	 */
13155 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
13156 	if (rwnd > max_transmittable_rwnd) {
13157 		rwnd = max_transmittable_rwnd -
13158 		    (max_transmittable_rwnd % mss);
13159 		if (rwnd < mss)
13160 			rwnd = max_transmittable_rwnd;
13161 		/*
13162 		 * If we're over the limit we may have to back down tcp_rwnd.
13163 		 * The increment below won't work for us. So we set all three
13164 		 * here and the increment below will have no effect.
13165 		 */
13166 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
13167 	}
13168 	if (tcp->tcp_localnet) {
13169 		tcp->tcp_rack_abs_max =
13170 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
13171 	} else {
13172 		/*
13173 		 * For a remote host on a different subnet (through a router),
13174 		 * we ack every other packet to be conforming to RFC1122.
13175 		 * tcp_deferred_acks_max is default to 2.
13176 		 */
13177 		tcp->tcp_rack_abs_max =
13178 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
13179 	}
13180 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
13181 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
13182 	else
13183 		tcp->tcp_rack_cur_max = 0;
13184 	/*
13185 	 * Increment the current rwnd by the amount the maximum grew (we
13186 	 * can not overwrite it since we might be in the middle of a
13187 	 * connection.)
13188 	 */
13189 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
13190 	connp->conn_rcvbuf = rwnd;
13191 
13192 	/* Are we already connected? */
13193 	if (tcp->tcp_tcpha != NULL) {
13194 		tcp->tcp_tcpha->tha_win =
13195 		    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
13196 	}
13197 
13198 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
13199 		tcp->tcp_cwnd_max = rwnd;
13200 
13201 	if (tcp_detached)
13202 		return (rwnd);
13203 
13204 	tcp_set_recv_threshold(tcp, rwnd >> 3);
13205 
13206 	(void) proto_set_rx_hiwat(connp->conn_rq, connp, rwnd);
13207 	return (rwnd);
13208 }
13209 
13210 /*
13211  * Return SNMP stuff in buffer in mpdata.
13212  */
13213 mblk_t *
13214 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
13215 {
13216 	mblk_t			*mpdata;
13217 	mblk_t			*mp_conn_ctl = NULL;
13218 	mblk_t			*mp_conn_tail;
13219 	mblk_t			*mp_attr_ctl = NULL;
13220 	mblk_t			*mp_attr_tail;
13221 	mblk_t			*mp6_conn_ctl = NULL;
13222 	mblk_t			*mp6_conn_tail;
13223 	mblk_t			*mp6_attr_ctl = NULL;
13224 	mblk_t			*mp6_attr_tail;
13225 	struct opthdr		*optp;
13226 	mib2_tcpConnEntry_t	tce;
13227 	mib2_tcp6ConnEntry_t	tce6;
13228 	mib2_transportMLPEntry_t mlp;
13229 	connf_t			*connfp;
13230 	int			i;
13231 	boolean_t 		ispriv;
13232 	zoneid_t 		zoneid;
13233 	int			v4_conn_idx;
13234 	int			v6_conn_idx;
13235 	conn_t			*connp = Q_TO_CONN(q);
13236 	tcp_stack_t		*tcps;
13237 	ip_stack_t		*ipst;
13238 	mblk_t			*mp2ctl;
13239 
13240 	/*
13241 	 * make a copy of the original message
13242 	 */
13243 	mp2ctl = copymsg(mpctl);
13244 
13245 	if (mpctl == NULL ||
13246 	    (mpdata = mpctl->b_cont) == NULL ||
13247 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
13248 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
13249 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
13250 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
13251 		freemsg(mp_conn_ctl);
13252 		freemsg(mp_attr_ctl);
13253 		freemsg(mp6_conn_ctl);
13254 		freemsg(mp6_attr_ctl);
13255 		freemsg(mpctl);
13256 		freemsg(mp2ctl);
13257 		return (NULL);
13258 	}
13259 
13260 	ipst = connp->conn_netstack->netstack_ip;
13261 	tcps = connp->conn_netstack->netstack_tcp;
13262 
13263 	/* build table of connections -- need count in fixed part */
13264 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
13265 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
13266 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
13267 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
13268 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
13269 
13270 	ispriv =
13271 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
13272 	zoneid = Q_TO_CONN(q)->conn_zoneid;
13273 
13274 	v4_conn_idx = v6_conn_idx = 0;
13275 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
13276 
13277 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
13278 		ipst = tcps->tcps_netstack->netstack_ip;
13279 
13280 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
13281 
13282 		connp = NULL;
13283 
13284 		while ((connp =
13285 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
13286 			tcp_t *tcp;
13287 			boolean_t needattr;
13288 
13289 			if (connp->conn_zoneid != zoneid)
13290 				continue;	/* not in this zone */
13291 
13292 			tcp = connp->conn_tcp;
13293 			UPDATE_MIB(&tcps->tcps_mib,
13294 			    tcpHCInSegs, tcp->tcp_ibsegs);
13295 			tcp->tcp_ibsegs = 0;
13296 			UPDATE_MIB(&tcps->tcps_mib,
13297 			    tcpHCOutSegs, tcp->tcp_obsegs);
13298 			tcp->tcp_obsegs = 0;
13299 
13300 			tce6.tcp6ConnState = tce.tcpConnState =
13301 			    tcp_snmp_state(tcp);
13302 			if (tce.tcpConnState == MIB2_TCP_established ||
13303 			    tce.tcpConnState == MIB2_TCP_closeWait)
13304 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
13305 
13306 			needattr = B_FALSE;
13307 			bzero(&mlp, sizeof (mlp));
13308 			if (connp->conn_mlp_type != mlptSingle) {
13309 				if (connp->conn_mlp_type == mlptShared ||
13310 				    connp->conn_mlp_type == mlptBoth)
13311 					mlp.tme_flags |= MIB2_TMEF_SHARED;
13312 				if (connp->conn_mlp_type == mlptPrivate ||
13313 				    connp->conn_mlp_type == mlptBoth)
13314 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
13315 				needattr = B_TRUE;
13316 			}
13317 			if (connp->conn_anon_mlp) {
13318 				mlp.tme_flags |= MIB2_TMEF_ANONMLP;
13319 				needattr = B_TRUE;
13320 			}
13321 			switch (connp->conn_mac_mode) {
13322 			case CONN_MAC_DEFAULT:
13323 				break;
13324 			case CONN_MAC_AWARE:
13325 				mlp.tme_flags |= MIB2_TMEF_MACEXEMPT;
13326 				needattr = B_TRUE;
13327 				break;
13328 			case CONN_MAC_IMPLICIT:
13329 				mlp.tme_flags |= MIB2_TMEF_MACIMPLICIT;
13330 				needattr = B_TRUE;
13331 				break;
13332 			}
13333 			if (connp->conn_ixa->ixa_tsl != NULL) {
13334 				ts_label_t *tsl;
13335 
13336 				tsl = connp->conn_ixa->ixa_tsl;
13337 				mlp.tme_flags |= MIB2_TMEF_IS_LABELED;
13338 				mlp.tme_doi = label2doi(tsl);
13339 				mlp.tme_label = *label2bslabel(tsl);
13340 				needattr = B_TRUE;
13341 			}
13342 
13343 			/* Create a message to report on IPv6 entries */
13344 			if (connp->conn_ipversion == IPV6_VERSION) {
13345 			tce6.tcp6ConnLocalAddress = connp->conn_laddr_v6;
13346 			tce6.tcp6ConnRemAddress = connp->conn_faddr_v6;
13347 			tce6.tcp6ConnLocalPort = ntohs(connp->conn_lport);
13348 			tce6.tcp6ConnRemPort = ntohs(connp->conn_fport);
13349 			if (connp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET) {
13350 				tce6.tcp6ConnIfIndex =
13351 				    connp->conn_ixa->ixa_scopeid;
13352 			} else {
13353 				tce6.tcp6ConnIfIndex = connp->conn_bound_if;
13354 			}
13355 			/* Don't want just anybody seeing these... */
13356 			if (ispriv) {
13357 				tce6.tcp6ConnEntryInfo.ce_snxt =
13358 				    tcp->tcp_snxt;
13359 				tce6.tcp6ConnEntryInfo.ce_suna =
13360 				    tcp->tcp_suna;
13361 				tce6.tcp6ConnEntryInfo.ce_rnxt =
13362 				    tcp->tcp_rnxt;
13363 				tce6.tcp6ConnEntryInfo.ce_rack =
13364 				    tcp->tcp_rack;
13365 			} else {
13366 				/*
13367 				 * Netstat, unfortunately, uses this to
13368 				 * get send/receive queue sizes.  How to fix?
13369 				 * Why not compute the difference only?
13370 				 */
13371 				tce6.tcp6ConnEntryInfo.ce_snxt =
13372 				    tcp->tcp_snxt - tcp->tcp_suna;
13373 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
13374 				tce6.tcp6ConnEntryInfo.ce_rnxt =
13375 				    tcp->tcp_rnxt - tcp->tcp_rack;
13376 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
13377 			}
13378 
13379 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
13380 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
13381 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
13382 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
13383 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
13384 
13385 			tce6.tcp6ConnCreationProcess =
13386 			    (connp->conn_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
13387 			    connp->conn_cpid;
13388 			tce6.tcp6ConnCreationTime = connp->conn_open_time;
13389 
13390 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
13391 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
13392 
13393 			mlp.tme_connidx = v6_conn_idx++;
13394 			if (needattr)
13395 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
13396 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
13397 			}
13398 			/*
13399 			 * Create an IPv4 table entry for IPv4 entries and also
13400 			 * for IPv6 entries which are bound to in6addr_any
13401 			 * but don't have IPV6_V6ONLY set.
13402 			 * (i.e. anything an IPv4 peer could connect to)
13403 			 */
13404 			if (connp->conn_ipversion == IPV4_VERSION ||
13405 			    (tcp->tcp_state <= TCPS_LISTEN &&
13406 			    !connp->conn_ipv6_v6only &&
13407 			    IN6_IS_ADDR_UNSPECIFIED(&connp->conn_laddr_v6))) {
13408 				if (connp->conn_ipversion == IPV6_VERSION) {
13409 					tce.tcpConnRemAddress = INADDR_ANY;
13410 					tce.tcpConnLocalAddress = INADDR_ANY;
13411 				} else {
13412 					tce.tcpConnRemAddress =
13413 					    connp->conn_faddr_v4;
13414 					tce.tcpConnLocalAddress =
13415 					    connp->conn_laddr_v4;
13416 				}
13417 				tce.tcpConnLocalPort = ntohs(connp->conn_lport);
13418 				tce.tcpConnRemPort = ntohs(connp->conn_fport);
13419 				/* Don't want just anybody seeing these... */
13420 				if (ispriv) {
13421 					tce.tcpConnEntryInfo.ce_snxt =
13422 					    tcp->tcp_snxt;
13423 					tce.tcpConnEntryInfo.ce_suna =
13424 					    tcp->tcp_suna;
13425 					tce.tcpConnEntryInfo.ce_rnxt =
13426 					    tcp->tcp_rnxt;
13427 					tce.tcpConnEntryInfo.ce_rack =
13428 					    tcp->tcp_rack;
13429 				} else {
13430 					/*
13431 					 * Netstat, unfortunately, uses this to
13432 					 * get send/receive queue sizes.  How
13433 					 * to fix?
13434 					 * Why not compute the difference only?
13435 					 */
13436 					tce.tcpConnEntryInfo.ce_snxt =
13437 					    tcp->tcp_snxt - tcp->tcp_suna;
13438 					tce.tcpConnEntryInfo.ce_suna = 0;
13439 					tce.tcpConnEntryInfo.ce_rnxt =
13440 					    tcp->tcp_rnxt - tcp->tcp_rack;
13441 					tce.tcpConnEntryInfo.ce_rack = 0;
13442 				}
13443 
13444 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
13445 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
13446 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
13447 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
13448 				tce.tcpConnEntryInfo.ce_state =
13449 				    tcp->tcp_state;
13450 
13451 				tce.tcpConnCreationProcess =
13452 				    (connp->conn_cpid < 0) ?
13453 				    MIB2_UNKNOWN_PROCESS :
13454 				    connp->conn_cpid;
13455 				tce.tcpConnCreationTime = connp->conn_open_time;
13456 
13457 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
13458 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
13459 
13460 				mlp.tme_connidx = v4_conn_idx++;
13461 				if (needattr)
13462 					(void) snmp_append_data2(
13463 					    mp_attr_ctl->b_cont,
13464 					    &mp_attr_tail, (char *)&mlp,
13465 					    sizeof (mlp));
13466 			}
13467 		}
13468 	}
13469 
13470 	/* fixed length structure for IPv4 and IPv6 counters */
13471 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
13472 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
13473 	    sizeof (mib2_tcp6ConnEntry_t));
13474 	/* synchronize 32- and 64-bit counters */
13475 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
13476 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
13477 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
13478 	optp->level = MIB2_TCP;
13479 	optp->name = 0;
13480 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
13481 	    sizeof (tcps->tcps_mib));
13482 	optp->len = msgdsize(mpdata);
13483 	qreply(q, mpctl);
13484 
13485 	/* table of connections... */
13486 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
13487 	    sizeof (struct T_optmgmt_ack)];
13488 	optp->level = MIB2_TCP;
13489 	optp->name = MIB2_TCP_CONN;
13490 	optp->len = msgdsize(mp_conn_ctl->b_cont);
13491 	qreply(q, mp_conn_ctl);
13492 
13493 	/* table of MLP attributes... */
13494 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
13495 	    sizeof (struct T_optmgmt_ack)];
13496 	optp->level = MIB2_TCP;
13497 	optp->name = EXPER_XPORT_MLP;
13498 	optp->len = msgdsize(mp_attr_ctl->b_cont);
13499 	if (optp->len == 0)
13500 		freemsg(mp_attr_ctl);
13501 	else
13502 		qreply(q, mp_attr_ctl);
13503 
13504 	/* table of IPv6 connections... */
13505 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
13506 	    sizeof (struct T_optmgmt_ack)];
13507 	optp->level = MIB2_TCP6;
13508 	optp->name = MIB2_TCP6_CONN;
13509 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
13510 	qreply(q, mp6_conn_ctl);
13511 
13512 	/* table of IPv6 MLP attributes... */
13513 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
13514 	    sizeof (struct T_optmgmt_ack)];
13515 	optp->level = MIB2_TCP6;
13516 	optp->name = EXPER_XPORT_MLP;
13517 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
13518 	if (optp->len == 0)
13519 		freemsg(mp6_attr_ctl);
13520 	else
13521 		qreply(q, mp6_attr_ctl);
13522 	return (mp2ctl);
13523 }
13524 
13525 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
13526 /* ARGSUSED */
13527 int
13528 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
13529 {
13530 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
13531 
13532 	switch (level) {
13533 	case MIB2_TCP:
13534 		switch (name) {
13535 		case 13:
13536 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
13537 				return (0);
13538 			/* TODO: delete entry defined by tce */
13539 			return (1);
13540 		default:
13541 			return (0);
13542 		}
13543 	default:
13544 		return (1);
13545 	}
13546 }
13547 
13548 /* Translate TCP state to MIB2 TCP state. */
13549 static int
13550 tcp_snmp_state(tcp_t *tcp)
13551 {
13552 	if (tcp == NULL)
13553 		return (0);
13554 
13555 	switch (tcp->tcp_state) {
13556 	case TCPS_CLOSED:
13557 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
13558 	case TCPS_BOUND:
13559 		return (MIB2_TCP_closed);
13560 	case TCPS_LISTEN:
13561 		return (MIB2_TCP_listen);
13562 	case TCPS_SYN_SENT:
13563 		return (MIB2_TCP_synSent);
13564 	case TCPS_SYN_RCVD:
13565 		return (MIB2_TCP_synReceived);
13566 	case TCPS_ESTABLISHED:
13567 		return (MIB2_TCP_established);
13568 	case TCPS_CLOSE_WAIT:
13569 		return (MIB2_TCP_closeWait);
13570 	case TCPS_FIN_WAIT_1:
13571 		return (MIB2_TCP_finWait1);
13572 	case TCPS_CLOSING:
13573 		return (MIB2_TCP_closing);
13574 	case TCPS_LAST_ACK:
13575 		return (MIB2_TCP_lastAck);
13576 	case TCPS_FIN_WAIT_2:
13577 		return (MIB2_TCP_finWait2);
13578 	case TCPS_TIME_WAIT:
13579 		return (MIB2_TCP_timeWait);
13580 	default:
13581 		return (0);
13582 	}
13583 }
13584 
13585 /*
13586  * tcp_timer is the timer service routine.  It handles the retransmission,
13587  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
13588  * from the state of the tcp instance what kind of action needs to be done
13589  * at the time it is called.
13590  */
13591 static void
13592 tcp_timer(void *arg)
13593 {
13594 	mblk_t		*mp;
13595 	clock_t		first_threshold;
13596 	clock_t		second_threshold;
13597 	clock_t		ms;
13598 	uint32_t	mss;
13599 	conn_t		*connp = (conn_t *)arg;
13600 	tcp_t		*tcp = connp->conn_tcp;
13601 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13602 
13603 	tcp->tcp_timer_tid = 0;
13604 
13605 	if (tcp->tcp_fused)
13606 		return;
13607 
13608 	first_threshold =  tcp->tcp_first_timer_threshold;
13609 	second_threshold = tcp->tcp_second_timer_threshold;
13610 	switch (tcp->tcp_state) {
13611 	case TCPS_IDLE:
13612 	case TCPS_BOUND:
13613 	case TCPS_LISTEN:
13614 		return;
13615 	case TCPS_SYN_RCVD: {
13616 		tcp_t	*listener = tcp->tcp_listener;
13617 
13618 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
13619 			/* it's our first timeout */
13620 			tcp->tcp_syn_rcvd_timeout = 1;
13621 			mutex_enter(&listener->tcp_eager_lock);
13622 			listener->tcp_syn_rcvd_timeout++;
13623 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
13624 				/*
13625 				 * Make this eager available for drop if we
13626 				 * need to drop one to accomodate a new
13627 				 * incoming SYN request.
13628 				 */
13629 				MAKE_DROPPABLE(listener, tcp);
13630 			}
13631 			if (!listener->tcp_syn_defense &&
13632 			    (listener->tcp_syn_rcvd_timeout >
13633 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
13634 			    (tcps->tcps_conn_req_max_q0 > 200)) {
13635 				/* We may be under attack. Put on a defense. */
13636 				listener->tcp_syn_defense = B_TRUE;
13637 				cmn_err(CE_WARN, "High TCP connect timeout "
13638 				    "rate! System (port %d) may be under a "
13639 				    "SYN flood attack!",
13640 				    ntohs(listener->tcp_connp->conn_lport));
13641 
13642 				listener->tcp_ip_addr_cache = kmem_zalloc(
13643 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
13644 				    KM_NOSLEEP);
13645 			}
13646 			mutex_exit(&listener->tcp_eager_lock);
13647 		} else if (listener != NULL) {
13648 			mutex_enter(&listener->tcp_eager_lock);
13649 			tcp->tcp_syn_rcvd_timeout++;
13650 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
13651 			    !tcp->tcp_closemp_used) {
13652 				/*
13653 				 * This is our second timeout. Put the tcp in
13654 				 * the list of droppable eagers to allow it to
13655 				 * be dropped, if needed. We don't check
13656 				 * whether tcp_dontdrop is set or not to
13657 				 * protect ourselve from a SYN attack where a
13658 				 * remote host can spoof itself as one of the
13659 				 * good IP source and continue to hold
13660 				 * resources too long.
13661 				 */
13662 				MAKE_DROPPABLE(listener, tcp);
13663 			}
13664 			mutex_exit(&listener->tcp_eager_lock);
13665 		}
13666 	}
13667 		/* FALLTHRU */
13668 	case TCPS_SYN_SENT:
13669 		first_threshold =  tcp->tcp_first_ctimer_threshold;
13670 		second_threshold = tcp->tcp_second_ctimer_threshold;
13671 		break;
13672 	case TCPS_ESTABLISHED:
13673 	case TCPS_FIN_WAIT_1:
13674 	case TCPS_CLOSING:
13675 	case TCPS_CLOSE_WAIT:
13676 	case TCPS_LAST_ACK:
13677 		/* If we have data to rexmit */
13678 		if (tcp->tcp_suna != tcp->tcp_snxt) {
13679 			clock_t	time_to_wait;
13680 
13681 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
13682 			if (!tcp->tcp_xmit_head)
13683 				break;
13684 			time_to_wait = ddi_get_lbolt() -
13685 			    (clock_t)tcp->tcp_xmit_head->b_prev;
13686 			time_to_wait = tcp->tcp_rto -
13687 			    TICK_TO_MSEC(time_to_wait);
13688 			/*
13689 			 * If the timer fires too early, 1 clock tick earlier,
13690 			 * restart the timer.
13691 			 */
13692 			if (time_to_wait > msec_per_tick) {
13693 				TCP_STAT(tcps, tcp_timer_fire_early);
13694 				TCP_TIMER_RESTART(tcp, time_to_wait);
13695 				return;
13696 			}
13697 			/*
13698 			 * When we probe zero windows, we force the swnd open.
13699 			 * If our peer acks with a closed window swnd will be
13700 			 * set to zero by tcp_rput(). As long as we are
13701 			 * receiving acks tcp_rput will
13702 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
13703 			 * first and second interval actions.  NOTE: the timer
13704 			 * interval is allowed to continue its exponential
13705 			 * backoff.
13706 			 */
13707 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
13708 				if (connp->conn_debug) {
13709 					(void) strlog(TCP_MOD_ID, 0, 1,
13710 					    SL_TRACE, "tcp_timer: zero win");
13711 				}
13712 			} else {
13713 				/*
13714 				 * After retransmission, we need to do
13715 				 * slow start.  Set the ssthresh to one
13716 				 * half of current effective window and
13717 				 * cwnd to one MSS.  Also reset
13718 				 * tcp_cwnd_cnt.
13719 				 *
13720 				 * Note that if tcp_ssthresh is reduced because
13721 				 * of ECN, do not reduce it again unless it is
13722 				 * already one window of data away (tcp_cwr
13723 				 * should then be cleared) or this is a
13724 				 * timeout for a retransmitted segment.
13725 				 */
13726 				uint32_t npkt;
13727 
13728 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
13729 					npkt = ((tcp->tcp_timer_backoff ?
13730 					    tcp->tcp_cwnd_ssthresh :
13731 					    tcp->tcp_snxt -
13732 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
13733 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
13734 					    tcp->tcp_mss;
13735 				}
13736 				tcp->tcp_cwnd = tcp->tcp_mss;
13737 				tcp->tcp_cwnd_cnt = 0;
13738 				if (tcp->tcp_ecn_ok) {
13739 					tcp->tcp_cwr = B_TRUE;
13740 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13741 					tcp->tcp_ecn_cwr_sent = B_FALSE;
13742 				}
13743 			}
13744 			break;
13745 		}
13746 		/*
13747 		 * We have something to send yet we cannot send.  The
13748 		 * reason can be:
13749 		 *
13750 		 * 1. Zero send window: we need to do zero window probe.
13751 		 * 2. Zero cwnd: because of ECN, we need to "clock out
13752 		 * segments.
13753 		 * 3. SWS avoidance: receiver may have shrunk window,
13754 		 * reset our knowledge.
13755 		 *
13756 		 * Note that condition 2 can happen with either 1 or
13757 		 * 3.  But 1 and 3 are exclusive.
13758 		 */
13759 		if (tcp->tcp_unsent != 0) {
13760 			/*
13761 			 * Should not hold the zero-copy messages for too long.
13762 			 */
13763 			if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13764 				tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13765 				    tcp->tcp_xmit_head, B_TRUE);
13766 
13767 			if (tcp->tcp_cwnd == 0) {
13768 				/*
13769 				 * Set tcp_cwnd to 1 MSS so that a
13770 				 * new segment can be sent out.  We
13771 				 * are "clocking out" new data when
13772 				 * the network is really congested.
13773 				 */
13774 				ASSERT(tcp->tcp_ecn_ok);
13775 				tcp->tcp_cwnd = tcp->tcp_mss;
13776 			}
13777 			if (tcp->tcp_swnd == 0) {
13778 				/* Extend window for zero window probe */
13779 				tcp->tcp_swnd++;
13780 				tcp->tcp_zero_win_probe = B_TRUE;
13781 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
13782 			} else {
13783 				/*
13784 				 * Handle timeout from sender SWS avoidance.
13785 				 * Reset our knowledge of the max send window
13786 				 * since the receiver might have reduced its
13787 				 * receive buffer.  Avoid setting tcp_max_swnd
13788 				 * to one since that will essentially disable
13789 				 * the SWS checks.
13790 				 *
13791 				 * Note that since we don't have a SWS
13792 				 * state variable, if the timeout is set
13793 				 * for ECN but not for SWS, this
13794 				 * code will also be executed.  This is
13795 				 * fine as tcp_max_swnd is updated
13796 				 * constantly and it will not affect
13797 				 * anything.
13798 				 */
13799 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
13800 			}
13801 			tcp_wput_data(tcp, NULL, B_FALSE);
13802 			return;
13803 		}
13804 		/* Is there a FIN that needs to be to re retransmitted? */
13805 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13806 		    !tcp->tcp_fin_acked)
13807 			break;
13808 		/* Nothing to do, return without restarting timer. */
13809 		TCP_STAT(tcps, tcp_timer_fire_miss);
13810 		return;
13811 	case TCPS_FIN_WAIT_2:
13812 		/*
13813 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
13814 		 * We waited some time for for peer's FIN, but it hasn't
13815 		 * arrived.  We flush the connection now to avoid
13816 		 * case where the peer has rebooted.
13817 		 */
13818 		if (TCP_IS_DETACHED(tcp)) {
13819 			(void) tcp_clean_death(tcp, 0, 23);
13820 		} else {
13821 			TCP_TIMER_RESTART(tcp,
13822 			    tcps->tcps_fin_wait_2_flush_interval);
13823 		}
13824 		return;
13825 	case TCPS_TIME_WAIT:
13826 		(void) tcp_clean_death(tcp, 0, 24);
13827 		return;
13828 	default:
13829 		if (connp->conn_debug) {
13830 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
13831 			    "tcp_timer: strange state (%d) %s",
13832 			    tcp->tcp_state, tcp_display(tcp, NULL,
13833 			    DISP_PORT_ONLY));
13834 		}
13835 		return;
13836 	}
13837 
13838 	/*
13839 	 * If the system is under memory pressure or the max number of
13840 	 * connections have been established for the listener, be more
13841 	 * aggressive in aborting connections.
13842 	 */
13843 	if (tcps->tcps_reclaim || (tcp->tcp_listen_cnt != NULL &&
13844 	    tcp->tcp_listen_cnt->tlc_cnt > tcp->tcp_listen_cnt->tlc_max)) {
13845 		second_threshold = tcp_early_abort * SECONDS;
13846 	}
13847 
13848 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
13849 		/*
13850 		 * Should not hold the zero-copy messages for too long.
13851 		 */
13852 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13853 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13854 			    tcp->tcp_xmit_head, B_TRUE);
13855 
13856 		/*
13857 		 * For zero window probe, we need to send indefinitely,
13858 		 * unless we have not heard from the other side for some
13859 		 * time...
13860 		 */
13861 		if ((tcp->tcp_zero_win_probe == 0) ||
13862 		    (TICK_TO_MSEC(ddi_get_lbolt() - tcp->tcp_last_recv_time) >
13863 		    second_threshold)) {
13864 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
13865 			/*
13866 			 * If TCP is in SYN_RCVD state, send back a
13867 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
13868 			 * should be zero in TCPS_SYN_RCVD state.
13869 			 */
13870 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
13871 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
13872 				    "in SYN_RCVD",
13873 				    tcp, tcp->tcp_snxt,
13874 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
13875 			}
13876 			(void) tcp_clean_death(tcp,
13877 			    tcp->tcp_client_errno ?
13878 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
13879 			return;
13880 		} else {
13881 			/*
13882 			 * If the system is under memory pressure, we also
13883 			 * abort connection in zero window probing.
13884 			 */
13885 			if (tcps->tcps_reclaim) {
13886 				(void) tcp_clean_death(tcp,
13887 				    tcp->tcp_client_errno ?
13888 				    tcp->tcp_client_errno : ETIMEDOUT, 25);
13889 				return;
13890 			}
13891 			/*
13892 			 * Set tcp_ms_we_have_waited to second_threshold
13893 			 * so that in next timeout, we will do the above
13894 			 * check (ddi_get_lbolt() - tcp_last_recv_time).
13895 			 * This is also to avoid overflow.
13896 			 *
13897 			 * We don't need to decrement tcp_timer_backoff
13898 			 * to avoid overflow because it will be decremented
13899 			 * later if new timeout value is greater than
13900 			 * tcp_rexmit_interval_max.  In the case when
13901 			 * tcp_rexmit_interval_max is greater than
13902 			 * second_threshold, it means that we will wait
13903 			 * longer than second_threshold to send the next
13904 			 * window probe.
13905 			 */
13906 			tcp->tcp_ms_we_have_waited = second_threshold;
13907 		}
13908 	} else if (ms > first_threshold) {
13909 		/*
13910 		 * Should not hold the zero-copy messages for too long.
13911 		 */
13912 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13913 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13914 			    tcp->tcp_xmit_head, B_TRUE);
13915 
13916 		/*
13917 		 * We have been retransmitting for too long...  The RTT
13918 		 * we calculated is probably incorrect.  Reinitialize it.
13919 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
13920 		 * tcp_rtt_update so that we won't accidentally cache a
13921 		 * bad value.  But only do this if this is not a zero
13922 		 * window probe.
13923 		 */
13924 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
13925 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
13926 			    (tcp->tcp_rtt_sa >> 5);
13927 			tcp->tcp_rtt_sa = 0;
13928 			tcp_ip_notify(tcp);
13929 			tcp->tcp_rtt_update = 0;
13930 		}
13931 	}
13932 	tcp->tcp_timer_backoff++;
13933 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
13934 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
13935 	    tcps->tcps_rexmit_interval_min) {
13936 		/*
13937 		 * This means the original RTO is tcp_rexmit_interval_min.
13938 		 * So we will use tcp_rexmit_interval_min as the RTO value
13939 		 * and do the backoff.
13940 		 */
13941 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
13942 	} else {
13943 		ms <<= tcp->tcp_timer_backoff;
13944 	}
13945 	if (ms > tcps->tcps_rexmit_interval_max) {
13946 		ms = tcps->tcps_rexmit_interval_max;
13947 		/*
13948 		 * ms is at max, decrement tcp_timer_backoff to avoid
13949 		 * overflow.
13950 		 */
13951 		tcp->tcp_timer_backoff--;
13952 	}
13953 	tcp->tcp_ms_we_have_waited += ms;
13954 	if (tcp->tcp_zero_win_probe == 0) {
13955 		tcp->tcp_rto = ms;
13956 	}
13957 	TCP_TIMER_RESTART(tcp, ms);
13958 	/*
13959 	 * This is after a timeout and tcp_rto is backed off.  Set
13960 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
13961 	 * restart the timer with a correct value.
13962 	 */
13963 	tcp->tcp_set_timer = 1;
13964 	mss = tcp->tcp_snxt - tcp->tcp_suna;
13965 	if (mss > tcp->tcp_mss)
13966 		mss = tcp->tcp_mss;
13967 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
13968 		mss = tcp->tcp_swnd;
13969 
13970 	if ((mp = tcp->tcp_xmit_head) != NULL)
13971 		mp->b_prev = (mblk_t *)ddi_get_lbolt();
13972 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
13973 	    B_TRUE);
13974 
13975 	/*
13976 	 * When slow start after retransmission begins, start with
13977 	 * this seq no.  tcp_rexmit_max marks the end of special slow
13978 	 * start phase.  tcp_snd_burst controls how many segments
13979 	 * can be sent because of an ack.
13980 	 */
13981 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
13982 	tcp->tcp_snd_burst = TCP_CWND_SS;
13983 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13984 	    (tcp->tcp_unsent == 0)) {
13985 		tcp->tcp_rexmit_max = tcp->tcp_fss;
13986 	} else {
13987 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
13988 	}
13989 	tcp->tcp_rexmit = B_TRUE;
13990 	tcp->tcp_dupack_cnt = 0;
13991 
13992 	/*
13993 	 * Remove all rexmit SACK blk to start from fresh.
13994 	 */
13995 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL)
13996 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
13997 	if (mp == NULL) {
13998 		return;
13999 	}
14000 
14001 	tcp->tcp_csuna = tcp->tcp_snxt;
14002 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
14003 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
14004 	tcp_send_data(tcp, mp);
14005 
14006 }
14007 
14008 static int
14009 tcp_do_unbind(conn_t *connp)
14010 {
14011 	tcp_t *tcp = connp->conn_tcp;
14012 
14013 	switch (tcp->tcp_state) {
14014 	case TCPS_BOUND:
14015 	case TCPS_LISTEN:
14016 		break;
14017 	default:
14018 		return (-TOUTSTATE);
14019 	}
14020 
14021 	/*
14022 	 * Need to clean up all the eagers since after the unbind, segments
14023 	 * will no longer be delivered to this listener stream.
14024 	 */
14025 	mutex_enter(&tcp->tcp_eager_lock);
14026 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
14027 		tcp_eager_cleanup(tcp, 0);
14028 	}
14029 	mutex_exit(&tcp->tcp_eager_lock);
14030 
14031 	/* Clean up the listener connection counter if necessary. */
14032 	if (tcp->tcp_listen_cnt != NULL)
14033 		TCP_DECR_LISTEN_CNT(tcp);
14034 	connp->conn_laddr_v6 = ipv6_all_zeros;
14035 	connp->conn_saddr_v6 = ipv6_all_zeros;
14036 	tcp_bind_hash_remove(tcp);
14037 	tcp->tcp_state = TCPS_IDLE;
14038 
14039 	ip_unbind(connp);
14040 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
14041 
14042 	return (0);
14043 }
14044 
14045 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
14046 static void
14047 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
14048 {
14049 	conn_t *connp = tcp->tcp_connp;
14050 	int error;
14051 
14052 	error = tcp_do_unbind(connp);
14053 	if (error > 0) {
14054 		tcp_err_ack(tcp, mp, TSYSERR, error);
14055 	} else if (error < 0) {
14056 		tcp_err_ack(tcp, mp, -error, 0);
14057 	} else {
14058 		/* Send M_FLUSH according to TPI */
14059 		(void) putnextctl1(connp->conn_rq, M_FLUSH, FLUSHRW);
14060 
14061 		mp = mi_tpi_ok_ack_alloc(mp);
14062 		if (mp != NULL)
14063 			putnext(connp->conn_rq, mp);
14064 	}
14065 }
14066 
14067 /*
14068  * Don't let port fall into the privileged range.
14069  * Since the extra privileged ports can be arbitrary we also
14070  * ensure that we exclude those from consideration.
14071  * tcp_g_epriv_ports is not sorted thus we loop over it until
14072  * there are no changes.
14073  *
14074  * Note: No locks are held when inspecting tcp_g_*epriv_ports
14075  * but instead the code relies on:
14076  * - the fact that the address of the array and its size never changes
14077  * - the atomic assignment of the elements of the array
14078  *
14079  * Returns 0 if there are no more ports available.
14080  *
14081  * TS note: skip multilevel ports.
14082  */
14083 static in_port_t
14084 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
14085 {
14086 	int i;
14087 	boolean_t restart = B_FALSE;
14088 	tcp_stack_t *tcps = tcp->tcp_tcps;
14089 
14090 	if (random && tcp_random_anon_port != 0) {
14091 		(void) random_get_pseudo_bytes((uint8_t *)&port,
14092 		    sizeof (in_port_t));
14093 		/*
14094 		 * Unless changed by a sys admin, the smallest anon port
14095 		 * is 32768 and the largest anon port is 65535.  It is
14096 		 * very likely (50%) for the random port to be smaller
14097 		 * than the smallest anon port.  When that happens,
14098 		 * add port % (anon port range) to the smallest anon
14099 		 * port to get the random port.  It should fall into the
14100 		 * valid anon port range.
14101 		 */
14102 		if (port < tcps->tcps_smallest_anon_port) {
14103 			port = tcps->tcps_smallest_anon_port +
14104 			    port % (tcps->tcps_largest_anon_port -
14105 			    tcps->tcps_smallest_anon_port);
14106 		}
14107 	}
14108 
14109 retry:
14110 	if (port < tcps->tcps_smallest_anon_port)
14111 		port = (in_port_t)tcps->tcps_smallest_anon_port;
14112 
14113 	if (port > tcps->tcps_largest_anon_port) {
14114 		if (restart)
14115 			return (0);
14116 		restart = B_TRUE;
14117 		port = (in_port_t)tcps->tcps_smallest_anon_port;
14118 	}
14119 
14120 	if (port < tcps->tcps_smallest_nonpriv_port)
14121 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
14122 
14123 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
14124 		if (port == tcps->tcps_g_epriv_ports[i]) {
14125 			port++;
14126 			/*
14127 			 * Make sure whether the port is in the
14128 			 * valid range.
14129 			 */
14130 			goto retry;
14131 		}
14132 	}
14133 	if (is_system_labeled() &&
14134 	    (i = tsol_next_port(crgetzone(tcp->tcp_connp->conn_cred), port,
14135 	    IPPROTO_TCP, B_TRUE)) != 0) {
14136 		port = i;
14137 		goto retry;
14138 	}
14139 	return (port);
14140 }
14141 
14142 /*
14143  * Return the next anonymous port in the privileged port range for
14144  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
14145  * downwards.  This is the same behavior as documented in the userland
14146  * library call rresvport(3N).
14147  *
14148  * TS note: skip multilevel ports.
14149  */
14150 static in_port_t
14151 tcp_get_next_priv_port(const tcp_t *tcp)
14152 {
14153 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
14154 	in_port_t nextport;
14155 	boolean_t restart = B_FALSE;
14156 	tcp_stack_t *tcps = tcp->tcp_tcps;
14157 retry:
14158 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
14159 	    next_priv_port >= IPPORT_RESERVED) {
14160 		next_priv_port = IPPORT_RESERVED - 1;
14161 		if (restart)
14162 			return (0);
14163 		restart = B_TRUE;
14164 	}
14165 	if (is_system_labeled() &&
14166 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_connp->conn_cred),
14167 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
14168 		next_priv_port = nextport;
14169 		goto retry;
14170 	}
14171 	return (next_priv_port--);
14172 }
14173 
14174 /* The write side r/w procedure. */
14175 
14176 #if CCS_STATS
14177 struct {
14178 	struct {
14179 		int64_t count, bytes;
14180 	} tot, hit;
14181 } wrw_stats;
14182 #endif
14183 
14184 /*
14185  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
14186  * messages.
14187  */
14188 /* ARGSUSED */
14189 static void
14190 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14191 {
14192 	conn_t	*connp = (conn_t *)arg;
14193 	tcp_t	*tcp = connp->conn_tcp;
14194 
14195 	ASSERT(DB_TYPE(mp) != M_IOCTL);
14196 	/*
14197 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
14198 	 * Once the close starts, streamhead and sockfs will not let any data
14199 	 * packets come down (close ensures that there are no threads using the
14200 	 * queue and no new threads will come down) but since qprocsoff()
14201 	 * hasn't happened yet, a M_FLUSH or some non data message might
14202 	 * get reflected back (in response to our own FLUSHRW) and get
14203 	 * processed after tcp_close() is done. The conn would still be valid
14204 	 * because a ref would have added but we need to check the state
14205 	 * before actually processing the packet.
14206 	 */
14207 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
14208 		freemsg(mp);
14209 		return;
14210 	}
14211 
14212 	switch (DB_TYPE(mp)) {
14213 	case M_IOCDATA:
14214 		tcp_wput_iocdata(tcp, mp);
14215 		break;
14216 	case M_FLUSH:
14217 		tcp_wput_flush(tcp, mp);
14218 		break;
14219 	default:
14220 		ip_wput_nondata(connp->conn_wq, mp);
14221 		break;
14222 	}
14223 }
14224 
14225 /*
14226  * The TCP fast path write put procedure.
14227  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
14228  */
14229 /* ARGSUSED */
14230 void
14231 tcp_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14232 {
14233 	int		len;
14234 	int		hdrlen;
14235 	int		plen;
14236 	mblk_t		*mp1;
14237 	uchar_t		*rptr;
14238 	uint32_t	snxt;
14239 	tcpha_t		*tcpha;
14240 	struct datab	*db;
14241 	uint32_t	suna;
14242 	uint32_t	mss;
14243 	ipaddr_t	*dst;
14244 	ipaddr_t	*src;
14245 	uint32_t	sum;
14246 	int		usable;
14247 	conn_t		*connp = (conn_t *)arg;
14248 	tcp_t		*tcp = connp->conn_tcp;
14249 	uint32_t	msize;
14250 	tcp_stack_t	*tcps = tcp->tcp_tcps;
14251 	ip_xmit_attr_t	*ixa;
14252 	clock_t		now;
14253 
14254 	/*
14255 	 * Try and ASSERT the minimum possible references on the
14256 	 * conn early enough. Since we are executing on write side,
14257 	 * the connection is obviously not detached and that means
14258 	 * there is a ref each for TCP and IP. Since we are behind
14259 	 * the squeue, the minimum references needed are 3. If the
14260 	 * conn is in classifier hash list, there should be an
14261 	 * extra ref for that (we check both the possibilities).
14262 	 */
14263 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
14264 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
14265 
14266 	ASSERT(DB_TYPE(mp) == M_DATA);
14267 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
14268 
14269 	mutex_enter(&tcp->tcp_non_sq_lock);
14270 	tcp->tcp_squeue_bytes -= msize;
14271 	mutex_exit(&tcp->tcp_non_sq_lock);
14272 
14273 	/* Bypass tcp protocol for fused tcp loopback */
14274 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
14275 		return;
14276 
14277 	mss = tcp->tcp_mss;
14278 	/*
14279 	 * If ZEROCOPY has turned off, try not to send any zero-copy message
14280 	 * down. Do backoff, now.
14281 	 */
14282 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on)
14283 		mp = tcp_zcopy_backoff(tcp, mp, B_FALSE);
14284 
14285 
14286 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
14287 	len = (int)(mp->b_wptr - mp->b_rptr);
14288 
14289 	/*
14290 	 * Criteria for fast path:
14291 	 *
14292 	 *   1. no unsent data
14293 	 *   2. single mblk in request
14294 	 *   3. connection established
14295 	 *   4. data in mblk
14296 	 *   5. len <= mss
14297 	 *   6. no tcp_valid bits
14298 	 */
14299 	if ((tcp->tcp_unsent != 0) ||
14300 	    (tcp->tcp_cork) ||
14301 	    (mp->b_cont != NULL) ||
14302 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
14303 	    (len == 0) ||
14304 	    (len > mss) ||
14305 	    (tcp->tcp_valid_bits != 0)) {
14306 		tcp_wput_data(tcp, mp, B_FALSE);
14307 		return;
14308 	}
14309 
14310 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
14311 	ASSERT(tcp->tcp_fin_sent == 0);
14312 
14313 	/* queue new packet onto retransmission queue */
14314 	if (tcp->tcp_xmit_head == NULL) {
14315 		tcp->tcp_xmit_head = mp;
14316 	} else {
14317 		tcp->tcp_xmit_last->b_cont = mp;
14318 	}
14319 	tcp->tcp_xmit_last = mp;
14320 	tcp->tcp_xmit_tail = mp;
14321 
14322 	/* find out how much we can send */
14323 	/* BEGIN CSTYLED */
14324 	/*
14325 	 *    un-acked	   usable
14326 	 *  |--------------|-----------------|
14327 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
14328 	 */
14329 	/* END CSTYLED */
14330 
14331 	/* start sending from tcp_snxt */
14332 	snxt = tcp->tcp_snxt;
14333 
14334 	/*
14335 	 * Check to see if this connection has been idled for some
14336 	 * time and no ACK is expected.  If it is, we need to slow
14337 	 * start again to get back the connection's "self-clock" as
14338 	 * described in VJ's paper.
14339 	 *
14340 	 * Reinitialize tcp_cwnd after idle.
14341 	 */
14342 	now = LBOLT_FASTPATH;
14343 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
14344 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
14345 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
14346 	}
14347 
14348 	usable = tcp->tcp_swnd;		/* tcp window size */
14349 	if (usable > tcp->tcp_cwnd)
14350 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
14351 	usable -= snxt;		/* subtract stuff already sent */
14352 	suna = tcp->tcp_suna;
14353 	usable += suna;
14354 	/* usable can be < 0 if the congestion window is smaller */
14355 	if (len > usable) {
14356 		/* Can't send complete M_DATA in one shot */
14357 		goto slow;
14358 	}
14359 
14360 	mutex_enter(&tcp->tcp_non_sq_lock);
14361 	if (tcp->tcp_flow_stopped &&
14362 	    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
14363 		tcp_clrqfull(tcp);
14364 	}
14365 	mutex_exit(&tcp->tcp_non_sq_lock);
14366 
14367 	/*
14368 	 * determine if anything to send (Nagle).
14369 	 *
14370 	 *   1. len < tcp_mss (i.e. small)
14371 	 *   2. unacknowledged data present
14372 	 *   3. len < nagle limit
14373 	 *   4. last packet sent < nagle limit (previous packet sent)
14374 	 */
14375 	if ((len < mss) && (snxt != suna) &&
14376 	    (len < (int)tcp->tcp_naglim) &&
14377 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
14378 		/*
14379 		 * This was the first unsent packet and normally
14380 		 * mss < xmit_hiwater so there is no need to worry
14381 		 * about flow control. The next packet will go
14382 		 * through the flow control check in tcp_wput_data().
14383 		 */
14384 		/* leftover work from above */
14385 		tcp->tcp_unsent = len;
14386 		tcp->tcp_xmit_tail_unsent = len;
14387 
14388 		return;
14389 	}
14390 
14391 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
14392 
14393 	if (snxt == suna) {
14394 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14395 	}
14396 
14397 	/* we have always sent something */
14398 	tcp->tcp_rack_cnt = 0;
14399 
14400 	tcp->tcp_snxt = snxt + len;
14401 	tcp->tcp_rack = tcp->tcp_rnxt;
14402 
14403 	if ((mp1 = dupb(mp)) == 0)
14404 		goto no_memory;
14405 	mp->b_prev = (mblk_t *)(uintptr_t)now;
14406 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
14407 
14408 	/* adjust tcp header information */
14409 	tcpha = tcp->tcp_tcpha;
14410 	tcpha->tha_flags = (TH_ACK|TH_PUSH);
14411 
14412 	sum = len + connp->conn_ht_ulp_len + connp->conn_sum;
14413 	sum = (sum >> 16) + (sum & 0xFFFF);
14414 	tcpha->tha_sum = htons(sum);
14415 
14416 	tcpha->tha_seq = htonl(snxt);
14417 
14418 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
14419 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
14420 	BUMP_LOCAL(tcp->tcp_obsegs);
14421 
14422 	/* Update the latest receive window size in TCP header. */
14423 	tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
14424 
14425 	tcp->tcp_last_sent_len = (ushort_t)len;
14426 
14427 	plen = len + connp->conn_ht_iphc_len;
14428 
14429 	ixa = connp->conn_ixa;
14430 	ixa->ixa_pktlen = plen;
14431 
14432 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
14433 		tcp->tcp_ipha->ipha_length = htons(plen);
14434 	} else {
14435 		tcp->tcp_ip6h->ip6_plen = htons(plen - IPV6_HDR_LEN);
14436 	}
14437 
14438 	/* see if we need to allocate a mblk for the headers */
14439 	hdrlen = connp->conn_ht_iphc_len;
14440 	rptr = mp1->b_rptr - hdrlen;
14441 	db = mp1->b_datap;
14442 	if ((db->db_ref != 2) || rptr < db->db_base ||
14443 	    (!OK_32PTR(rptr))) {
14444 		/* NOTE: we assume allocb returns an OK_32PTR */
14445 		mp = allocb(hdrlen + tcps->tcps_wroff_xtra, BPRI_MED);
14446 		if (!mp) {
14447 			freemsg(mp1);
14448 			goto no_memory;
14449 		}
14450 		mp->b_cont = mp1;
14451 		mp1 = mp;
14452 		/* Leave room for Link Level header */
14453 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
14454 		mp1->b_wptr = &rptr[hdrlen];
14455 	}
14456 	mp1->b_rptr = rptr;
14457 
14458 	/* Fill in the timestamp option. */
14459 	if (tcp->tcp_snd_ts_ok) {
14460 		uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
14461 
14462 		U32_TO_BE32(llbolt,
14463 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
14464 		U32_TO_BE32(tcp->tcp_ts_recent,
14465 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
14466 	} else {
14467 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
14468 	}
14469 
14470 	/* copy header into outgoing packet */
14471 	dst = (ipaddr_t *)rptr;
14472 	src = (ipaddr_t *)connp->conn_ht_iphc;
14473 	dst[0] = src[0];
14474 	dst[1] = src[1];
14475 	dst[2] = src[2];
14476 	dst[3] = src[3];
14477 	dst[4] = src[4];
14478 	dst[5] = src[5];
14479 	dst[6] = src[6];
14480 	dst[7] = src[7];
14481 	dst[8] = src[8];
14482 	dst[9] = src[9];
14483 	if (hdrlen -= 40) {
14484 		hdrlen >>= 2;
14485 		dst += 10;
14486 		src += 10;
14487 		do {
14488 			*dst++ = *src++;
14489 		} while (--hdrlen);
14490 	}
14491 
14492 	/*
14493 	 * Set the ECN info in the TCP header.  Note that this
14494 	 * is not the template header.
14495 	 */
14496 	if (tcp->tcp_ecn_ok) {
14497 		SET_ECT(tcp, rptr);
14498 
14499 		tcpha = (tcpha_t *)(rptr + ixa->ixa_ip_hdr_length);
14500 		if (tcp->tcp_ecn_echo_on)
14501 			tcpha->tha_flags |= TH_ECE;
14502 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
14503 			tcpha->tha_flags |= TH_CWR;
14504 			tcp->tcp_ecn_cwr_sent = B_TRUE;
14505 		}
14506 	}
14507 
14508 	if (tcp->tcp_ip_forward_progress) {
14509 		tcp->tcp_ip_forward_progress = B_FALSE;
14510 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
14511 	} else {
14512 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
14513 	}
14514 	tcp_send_data(tcp, mp1);
14515 	return;
14516 
14517 	/*
14518 	 * If we ran out of memory, we pretend to have sent the packet
14519 	 * and that it was lost on the wire.
14520 	 */
14521 no_memory:
14522 	return;
14523 
14524 slow:
14525 	/* leftover work from above */
14526 	tcp->tcp_unsent = len;
14527 	tcp->tcp_xmit_tail_unsent = len;
14528 	tcp_wput_data(tcp, NULL, B_FALSE);
14529 }
14530 
14531 /*
14532  * This runs at the tail end of accept processing on the squeue of the
14533  * new connection.
14534  */
14535 /* ARGSUSED */
14536 void
14537 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14538 {
14539 	conn_t			*connp = (conn_t *)arg;
14540 	tcp_t			*tcp = connp->conn_tcp;
14541 	queue_t			*q = connp->conn_rq;
14542 	tcp_stack_t		*tcps = tcp->tcp_tcps;
14543 	/* socket options */
14544 	struct sock_proto_props	sopp;
14545 
14546 	/* We should just receive a single mblk that fits a T_discon_ind */
14547 	ASSERT(mp->b_cont == NULL);
14548 
14549 	/*
14550 	 * Drop the eager's ref on the listener, that was placed when
14551 	 * this eager began life in tcp_input_listener.
14552 	 */
14553 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
14554 	if (IPCL_IS_NONSTR(connp)) {
14555 		/* Safe to free conn_ind message */
14556 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
14557 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14558 	}
14559 
14560 	tcp->tcp_detached = B_FALSE;
14561 
14562 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
14563 		/*
14564 		 * Someone blewoff the eager before we could finish
14565 		 * the accept.
14566 		 *
14567 		 * The only reason eager exists it because we put in
14568 		 * a ref on it when conn ind went up. We need to send
14569 		 * a disconnect indication up while the last reference
14570 		 * on the eager will be dropped by the squeue when we
14571 		 * return.
14572 		 */
14573 		ASSERT(tcp->tcp_listener == NULL);
14574 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
14575 			if (IPCL_IS_NONSTR(connp)) {
14576 				ASSERT(tcp->tcp_issocket);
14577 				(*connp->conn_upcalls->su_disconnected)(
14578 				    connp->conn_upper_handle, tcp->tcp_connid,
14579 				    ECONNREFUSED);
14580 				freemsg(mp);
14581 			} else {
14582 				struct	T_discon_ind	*tdi;
14583 
14584 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
14585 				/*
14586 				 * Let us reuse the incoming mblk to avoid
14587 				 * memory allocation failure problems. We know
14588 				 * that the size of the incoming mblk i.e.
14589 				 * stroptions is greater than sizeof
14590 				 * T_discon_ind.
14591 				 */
14592 				ASSERT(DB_REF(mp) == 1);
14593 				ASSERT(MBLKSIZE(mp) >=
14594 				    sizeof (struct T_discon_ind));
14595 
14596 				DB_TYPE(mp) = M_PROTO;
14597 				((union T_primitives *)mp->b_rptr)->type =
14598 				    T_DISCON_IND;
14599 				tdi = (struct T_discon_ind *)mp->b_rptr;
14600 				if (tcp->tcp_issocket) {
14601 					tdi->DISCON_reason = ECONNREFUSED;
14602 					tdi->SEQ_number = 0;
14603 				} else {
14604 					tdi->DISCON_reason = ENOPROTOOPT;
14605 					tdi->SEQ_number =
14606 					    tcp->tcp_conn_req_seqnum;
14607 				}
14608 				mp->b_wptr = mp->b_rptr +
14609 				    sizeof (struct T_discon_ind);
14610 				putnext(q, mp);
14611 			}
14612 		}
14613 		tcp->tcp_hard_binding = B_FALSE;
14614 		return;
14615 	}
14616 
14617 	/*
14618 	 * This is the first time we run on the correct
14619 	 * queue after tcp_accept. So fix all the q parameters
14620 	 * here.
14621 	 */
14622 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
14623 	sopp.sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
14624 
14625 	sopp.sopp_rxhiwat = tcp->tcp_fused ?
14626 	    tcp_fuse_set_rcv_hiwat(tcp, connp->conn_rcvbuf) :
14627 	    connp->conn_rcvbuf;
14628 
14629 	/*
14630 	 * Determine what write offset value to use depending on SACK and
14631 	 * whether the endpoint is fused or not.
14632 	 */
14633 	if (tcp->tcp_fused) {
14634 		ASSERT(tcp->tcp_loopback);
14635 		ASSERT(tcp->tcp_loopback_peer != NULL);
14636 		/*
14637 		 * For fused tcp loopback, set the stream head's write
14638 		 * offset value to zero since we won't be needing any room
14639 		 * for TCP/IP headers.  This would also improve performance
14640 		 * since it would reduce the amount of work done by kmem.
14641 		 * Non-fused tcp loopback case is handled separately below.
14642 		 */
14643 		sopp.sopp_wroff = 0;
14644 		/*
14645 		 * Update the peer's transmit parameters according to
14646 		 * our recently calculated high water mark value.
14647 		 */
14648 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
14649 	} else if (tcp->tcp_snd_sack_ok) {
14650 		sopp.sopp_wroff = connp->conn_ht_iphc_allocated +
14651 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
14652 	} else {
14653 		sopp.sopp_wroff = connp->conn_ht_iphc_len +
14654 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
14655 	}
14656 
14657 	/*
14658 	 * If this is endpoint is handling SSL, then reserve extra
14659 	 * offset and space at the end.
14660 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
14661 	 * overriding the previous setting. The extra cost of signing and
14662 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
14663 	 * instead of a single contiguous one by the stream head
14664 	 * largely outweighs the statistical reduction of ACKs, when
14665 	 * applicable. The peer will also save on decryption and verification
14666 	 * costs.
14667 	 */
14668 	if (tcp->tcp_kssl_ctx != NULL) {
14669 		sopp.sopp_wroff += SSL3_WROFFSET;
14670 
14671 		sopp.sopp_flags |= SOCKOPT_TAIL;
14672 		sopp.sopp_tail = SSL3_MAX_TAIL_LEN;
14673 
14674 		sopp.sopp_flags |= SOCKOPT_ZCOPY;
14675 		sopp.sopp_zcopyflag = ZCVMUNSAFE;
14676 
14677 		sopp.sopp_maxblk = SSL3_MAX_RECORD_LEN;
14678 	}
14679 
14680 	/* Send the options up */
14681 	if (IPCL_IS_NONSTR(connp)) {
14682 		if (sopp.sopp_flags & SOCKOPT_TAIL) {
14683 			ASSERT(tcp->tcp_kssl_ctx != NULL);
14684 			ASSERT(sopp.sopp_flags & SOCKOPT_ZCOPY);
14685 		}
14686 		if (tcp->tcp_loopback) {
14687 			sopp.sopp_flags |= SOCKOPT_LOOPBACK;
14688 			sopp.sopp_loopback = B_TRUE;
14689 		}
14690 		(*connp->conn_upcalls->su_set_proto_props)
14691 		    (connp->conn_upper_handle, &sopp);
14692 		freemsg(mp);
14693 	} else {
14694 		/*
14695 		 * Let us reuse the incoming mblk to avoid
14696 		 * memory allocation failure problems. We know
14697 		 * that the size of the incoming mblk is at least
14698 		 * stroptions
14699 		 */
14700 		struct stroptions *stropt;
14701 
14702 		ASSERT(DB_REF(mp) == 1);
14703 		ASSERT(MBLKSIZE(mp) >= sizeof (struct stroptions));
14704 
14705 		DB_TYPE(mp) = M_SETOPTS;
14706 		stropt = (struct stroptions *)mp->b_rptr;
14707 		mp->b_wptr = mp->b_rptr + sizeof (struct stroptions);
14708 		stropt = (struct stroptions *)mp->b_rptr;
14709 		stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
14710 		stropt->so_hiwat = sopp.sopp_rxhiwat;
14711 		stropt->so_wroff = sopp.sopp_wroff;
14712 		stropt->so_maxblk = sopp.sopp_maxblk;
14713 
14714 		if (sopp.sopp_flags & SOCKOPT_TAIL) {
14715 			ASSERT(tcp->tcp_kssl_ctx != NULL);
14716 
14717 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
14718 			stropt->so_tail = sopp.sopp_tail;
14719 			stropt->so_copyopt = sopp.sopp_zcopyflag;
14720 		}
14721 
14722 		/* Send the options up */
14723 		putnext(q, mp);
14724 	}
14725 
14726 	/*
14727 	 * Pass up any data and/or a fin that has been received.
14728 	 *
14729 	 * Adjust receive window in case it had decreased
14730 	 * (because there is data <=> tcp_rcv_list != NULL)
14731 	 * while the connection was detached. Note that
14732 	 * in case the eager was flow-controlled, w/o this
14733 	 * code, the rwnd may never open up again!
14734 	 */
14735 	if (tcp->tcp_rcv_list != NULL) {
14736 		if (IPCL_IS_NONSTR(connp)) {
14737 			mblk_t *mp;
14738 			int space_left;
14739 			int error;
14740 			boolean_t push = B_TRUE;
14741 
14742 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
14743 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
14744 			    &push) >= 0) {
14745 				tcp->tcp_rwnd = connp->conn_rcvbuf;
14746 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
14747 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
14748 					tcp_xmit_ctl(NULL,
14749 					    tcp, (tcp->tcp_swnd == 0) ?
14750 					    tcp->tcp_suna : tcp->tcp_snxt,
14751 					    tcp->tcp_rnxt, TH_ACK);
14752 				}
14753 			}
14754 			while ((mp = tcp->tcp_rcv_list) != NULL) {
14755 				push = B_TRUE;
14756 				tcp->tcp_rcv_list = mp->b_next;
14757 				mp->b_next = NULL;
14758 				space_left = (*connp->conn_upcalls->su_recv)
14759 				    (connp->conn_upper_handle, mp, msgdsize(mp),
14760 				    0, &error, &push);
14761 				if (space_left < 0) {
14762 					/*
14763 					 * We should never be in middle of a
14764 					 * fallback, the squeue guarantees that.
14765 					 */
14766 					ASSERT(error != EOPNOTSUPP);
14767 				}
14768 			}
14769 			tcp->tcp_rcv_last_head = NULL;
14770 			tcp->tcp_rcv_last_tail = NULL;
14771 			tcp->tcp_rcv_cnt = 0;
14772 		} else {
14773 			/* We drain directly in case of fused tcp loopback */
14774 
14775 			if (!tcp->tcp_fused && canputnext(q)) {
14776 				tcp->tcp_rwnd = connp->conn_rcvbuf;
14777 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
14778 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
14779 					tcp_xmit_ctl(NULL,
14780 					    tcp, (tcp->tcp_swnd == 0) ?
14781 					    tcp->tcp_suna : tcp->tcp_snxt,
14782 					    tcp->tcp_rnxt, TH_ACK);
14783 				}
14784 			}
14785 
14786 			(void) tcp_rcv_drain(tcp);
14787 		}
14788 
14789 		/*
14790 		 * For fused tcp loopback, back-enable peer endpoint
14791 		 * if it's currently flow-controlled.
14792 		 */
14793 		if (tcp->tcp_fused) {
14794 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
14795 
14796 			ASSERT(peer_tcp != NULL);
14797 			ASSERT(peer_tcp->tcp_fused);
14798 
14799 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
14800 			if (peer_tcp->tcp_flow_stopped) {
14801 				tcp_clrqfull(peer_tcp);
14802 				TCP_STAT(tcps, tcp_fusion_backenabled);
14803 			}
14804 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
14805 		}
14806 	}
14807 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14808 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
14809 		tcp->tcp_ordrel_done = B_TRUE;
14810 		if (IPCL_IS_NONSTR(connp)) {
14811 			ASSERT(tcp->tcp_ordrel_mp == NULL);
14812 			(*connp->conn_upcalls->su_opctl)(
14813 			    connp->conn_upper_handle,
14814 			    SOCK_OPCTL_SHUT_RECV, 0);
14815 		} else {
14816 			mp = tcp->tcp_ordrel_mp;
14817 			tcp->tcp_ordrel_mp = NULL;
14818 			putnext(q, mp);
14819 		}
14820 	}
14821 	tcp->tcp_hard_binding = B_FALSE;
14822 
14823 	if (connp->conn_keepalive) {
14824 		tcp->tcp_ka_last_intrvl = 0;
14825 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
14826 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
14827 	}
14828 
14829 	/*
14830 	 * At this point, eager is fully established and will
14831 	 * have the following references -
14832 	 *
14833 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
14834 	 * 1 reference for the squeue which will be dropped by the squeue as
14835 	 *	soon as this function returns.
14836 	 * There will be 1 additonal reference for being in classifier
14837 	 *	hash list provided something bad hasn't happened.
14838 	 */
14839 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
14840 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
14841 }
14842 
14843 /*
14844  * The function called through squeue to get behind listener's perimeter to
14845  * send a deferred conn_ind.
14846  */
14847 /* ARGSUSED */
14848 void
14849 tcp_send_pending(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14850 {
14851 	conn_t	*lconnp = (conn_t *)arg;
14852 	tcp_t *listener = lconnp->conn_tcp;
14853 	struct T_conn_ind *conn_ind;
14854 	tcp_t *tcp;
14855 
14856 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
14857 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
14858 	    conn_ind->OPT_length);
14859 
14860 	if (listener->tcp_state != TCPS_LISTEN) {
14861 		/*
14862 		 * If listener has closed, it would have caused a
14863 		 * a cleanup/blowoff to happen for the eager, so
14864 		 * we don't need to do anything more.
14865 		 */
14866 		freemsg(mp);
14867 		return;
14868 	}
14869 
14870 	tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
14871 }
14872 
14873 /*
14874  * Common to TPI and sockfs accept code.
14875  */
14876 /* ARGSUSED2 */
14877 static int
14878 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
14879 {
14880 	tcp_t *listener, *eager;
14881 	mblk_t *discon_mp;
14882 
14883 	listener = lconnp->conn_tcp;
14884 	ASSERT(listener->tcp_state == TCPS_LISTEN);
14885 	eager = econnp->conn_tcp;
14886 	ASSERT(eager->tcp_listener != NULL);
14887 
14888 	/*
14889 	 * Pre allocate the discon_ind mblk also. tcp_accept_finish will
14890 	 * use it if something failed.
14891 	 */
14892 	discon_mp = allocb(MAX(sizeof (struct T_discon_ind),
14893 	    sizeof (struct stroptions)), BPRI_HI);
14894 
14895 	if (discon_mp == NULL) {
14896 		return (-TPROTO);
14897 	}
14898 	eager->tcp_issocket = B_TRUE;
14899 
14900 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
14901 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
14902 	ASSERT(econnp->conn_netstack ==
14903 	    listener->tcp_connp->conn_netstack);
14904 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
14905 
14906 	/* Put the ref for IP */
14907 	CONN_INC_REF(econnp);
14908 
14909 	/*
14910 	 * We should have minimum of 3 references on the conn
14911 	 * at this point. One each for TCP and IP and one for
14912 	 * the T_conn_ind that was sent up when the 3-way handshake
14913 	 * completed. In the normal case we would also have another
14914 	 * reference (making a total of 4) for the conn being in the
14915 	 * classifier hash list. However the eager could have received
14916 	 * an RST subsequently and tcp_closei_local could have removed
14917 	 * the eager from the classifier hash list, hence we can't
14918 	 * assert that reference.
14919 	 */
14920 	ASSERT(econnp->conn_ref >= 3);
14921 
14922 	mutex_enter(&listener->tcp_eager_lock);
14923 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
14924 
14925 		tcp_t *tail;
14926 		tcp_t *tcp;
14927 		mblk_t *mp1;
14928 
14929 		tcp = listener->tcp_eager_prev_q0;
14930 		/*
14931 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
14932 		 * deferred T_conn_ind queue. We need to get to the head
14933 		 * of the queue in order to send up T_conn_ind the same
14934 		 * order as how the 3WHS is completed.
14935 		 */
14936 		while (tcp != listener) {
14937 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
14938 			    !tcp->tcp_kssl_pending)
14939 				break;
14940 			else
14941 				tcp = tcp->tcp_eager_prev_q0;
14942 		}
14943 		/* None of the pending eagers can be sent up now */
14944 		if (tcp == listener)
14945 			goto no_more_eagers;
14946 
14947 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
14948 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14949 		/* Move from q0 to q */
14950 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
14951 		listener->tcp_conn_req_cnt_q0--;
14952 		listener->tcp_conn_req_cnt_q++;
14953 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
14954 		    tcp->tcp_eager_prev_q0;
14955 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
14956 		    tcp->tcp_eager_next_q0;
14957 		tcp->tcp_eager_prev_q0 = NULL;
14958 		tcp->tcp_eager_next_q0 = NULL;
14959 		tcp->tcp_conn_def_q0 = B_FALSE;
14960 
14961 		/* Make sure the tcp isn't in the list of droppables */
14962 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
14963 		    tcp->tcp_eager_prev_drop_q0 == NULL);
14964 
14965 		/*
14966 		 * Insert at end of the queue because sockfs sends
14967 		 * down T_CONN_RES in chronological order. Leaving
14968 		 * the older conn indications at front of the queue
14969 		 * helps reducing search time.
14970 		 */
14971 		tail = listener->tcp_eager_last_q;
14972 		if (tail != NULL) {
14973 			tail->tcp_eager_next_q = tcp;
14974 		} else {
14975 			listener->tcp_eager_next_q = tcp;
14976 		}
14977 		listener->tcp_eager_last_q = tcp;
14978 		tcp->tcp_eager_next_q = NULL;
14979 
14980 		/* Need to get inside the listener perimeter */
14981 		CONN_INC_REF(listener->tcp_connp);
14982 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
14983 		    tcp_send_pending, listener->tcp_connp, NULL, SQ_FILL,
14984 		    SQTAG_TCP_SEND_PENDING);
14985 	}
14986 no_more_eagers:
14987 	tcp_eager_unlink(eager);
14988 	mutex_exit(&listener->tcp_eager_lock);
14989 
14990 	/*
14991 	 * At this point, the eager is detached from the listener
14992 	 * but we still have an extra refs on eager (apart from the
14993 	 * usual tcp references). The ref was placed in tcp_input_data
14994 	 * before sending the conn_ind in tcp_send_conn_ind.
14995 	 * The ref will be dropped in tcp_accept_finish().
14996 	 */
14997 	SQUEUE_ENTER_ONE(econnp->conn_sqp, discon_mp, tcp_accept_finish,
14998 	    econnp, NULL, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
14999 	return (0);
15000 }
15001 
15002 int
15003 tcp_accept(sock_lower_handle_t lproto_handle,
15004     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
15005     cred_t *cr)
15006 {
15007 	conn_t *lconnp, *econnp;
15008 	tcp_t *listener, *eager;
15009 
15010 	lconnp = (conn_t *)lproto_handle;
15011 	listener = lconnp->conn_tcp;
15012 	ASSERT(listener->tcp_state == TCPS_LISTEN);
15013 	econnp = (conn_t *)eproto_handle;
15014 	eager = econnp->conn_tcp;
15015 	ASSERT(eager->tcp_listener != NULL);
15016 
15017 	/*
15018 	 * It is OK to manipulate these fields outside the eager's squeue
15019 	 * because they will not start being used until tcp_accept_finish
15020 	 * has been called.
15021 	 */
15022 	ASSERT(lconnp->conn_upper_handle != NULL);
15023 	ASSERT(econnp->conn_upper_handle == NULL);
15024 	econnp->conn_upper_handle = sock_handle;
15025 	econnp->conn_upcalls = lconnp->conn_upcalls;
15026 	ASSERT(IPCL_IS_NONSTR(econnp));
15027 	return (tcp_accept_common(lconnp, econnp, cr));
15028 }
15029 
15030 
15031 /*
15032  * This is the STREAMS entry point for T_CONN_RES coming down on
15033  * Acceptor STREAM when  sockfs listener does accept processing.
15034  * Read the block comment on top of tcp_input_listener().
15035  */
15036 void
15037 tcp_tpi_accept(queue_t *q, mblk_t *mp)
15038 {
15039 	queue_t *rq = RD(q);
15040 	struct T_conn_res *conn_res;
15041 	tcp_t *eager;
15042 	tcp_t *listener;
15043 	struct T_ok_ack *ok;
15044 	t_scalar_t PRIM_type;
15045 	conn_t *econnp;
15046 	cred_t *cr;
15047 
15048 	ASSERT(DB_TYPE(mp) == M_PROTO);
15049 
15050 	/*
15051 	 * All Solaris components should pass a db_credp
15052 	 * for this TPI message, hence we ASSERT.
15053 	 * But in case there is some other M_PROTO that looks
15054 	 * like a TPI message sent by some other kernel
15055 	 * component, we check and return an error.
15056 	 */
15057 	cr = msg_getcred(mp, NULL);
15058 	ASSERT(cr != NULL);
15059 	if (cr == NULL) {
15060 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
15061 		if (mp != NULL)
15062 			putnext(rq, mp);
15063 		return;
15064 	}
15065 	conn_res = (struct T_conn_res *)mp->b_rptr;
15066 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
15067 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
15068 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
15069 		if (mp != NULL)
15070 			putnext(rq, mp);
15071 		return;
15072 	}
15073 	switch (conn_res->PRIM_type) {
15074 	case O_T_CONN_RES:
15075 	case T_CONN_RES:
15076 		/*
15077 		 * We pass up an err ack if allocb fails. This will
15078 		 * cause sockfs to issue a T_DISCON_REQ which will cause
15079 		 * tcp_eager_blowoff to be called. sockfs will then call
15080 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
15081 		 * we need to do the allocb up here because we have to
15082 		 * make sure rq->q_qinfo->qi_qclose still points to the
15083 		 * correct function (tcp_tpi_close_accept) in case allocb
15084 		 * fails.
15085 		 */
15086 		bcopy(mp->b_rptr + conn_res->OPT_offset,
15087 		    &eager, conn_res->OPT_length);
15088 		PRIM_type = conn_res->PRIM_type;
15089 		mp->b_datap->db_type = M_PCPROTO;
15090 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
15091 		ok = (struct T_ok_ack *)mp->b_rptr;
15092 		ok->PRIM_type = T_OK_ACK;
15093 		ok->CORRECT_prim = PRIM_type;
15094 		econnp = eager->tcp_connp;
15095 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
15096 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
15097 		econnp->conn_rq = rq;
15098 		econnp->conn_wq = q;
15099 		rq->q_ptr = econnp;
15100 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
15101 		q->q_ptr = econnp;
15102 		q->q_qinfo = &tcp_winit;
15103 		listener = eager->tcp_listener;
15104 
15105 		if (tcp_accept_common(listener->tcp_connp,
15106 		    econnp, cr) < 0) {
15107 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
15108 			if (mp != NULL)
15109 				putnext(rq, mp);
15110 			return;
15111 		}
15112 
15113 		/*
15114 		 * Send the new local address also up to sockfs. There
15115 		 * should already be enough space in the mp that came
15116 		 * down from soaccept().
15117 		 */
15118 		if (econnp->conn_family == AF_INET) {
15119 			sin_t *sin;
15120 
15121 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
15122 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
15123 			sin = (sin_t *)mp->b_wptr;
15124 			mp->b_wptr += sizeof (sin_t);
15125 			sin->sin_family = AF_INET;
15126 			sin->sin_port = econnp->conn_lport;
15127 			sin->sin_addr.s_addr = econnp->conn_laddr_v4;
15128 		} else {
15129 			sin6_t *sin6;
15130 
15131 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
15132 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
15133 			sin6 = (sin6_t *)mp->b_wptr;
15134 			mp->b_wptr += sizeof (sin6_t);
15135 			sin6->sin6_family = AF_INET6;
15136 			sin6->sin6_port = econnp->conn_lport;
15137 			sin6->sin6_addr = econnp->conn_laddr_v6;
15138 			if (econnp->conn_ipversion == IPV4_VERSION)
15139 				sin6->sin6_flowinfo = 0;
15140 			else
15141 				sin6->sin6_flowinfo = econnp->conn_flowinfo;
15142 			if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6) &&
15143 			    (econnp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)) {
15144 				sin6->sin6_scope_id =
15145 				    econnp->conn_ixa->ixa_scopeid;
15146 			} else {
15147 				sin6->sin6_scope_id = 0;
15148 			}
15149 			sin6->__sin6_src_id = 0;
15150 		}
15151 
15152 		putnext(rq, mp);
15153 		return;
15154 	default:
15155 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
15156 		if (mp != NULL)
15157 			putnext(rq, mp);
15158 		return;
15159 	}
15160 }
15161 
15162 /*
15163  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
15164  */
15165 static void
15166 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
15167 {
15168 	void	*data;
15169 	mblk_t	*datamp = mp->b_cont;
15170 	conn_t	*connp = Q_TO_CONN(q);
15171 	tcp_t	*tcp = connp->conn_tcp;
15172 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
15173 
15174 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
15175 		cmdp->cb_error = EPROTO;
15176 		qreply(q, mp);
15177 		return;
15178 	}
15179 
15180 	data = datamp->b_rptr;
15181 
15182 	switch (cmdp->cb_cmd) {
15183 	case TI_GETPEERNAME:
15184 		if (tcp->tcp_state < TCPS_SYN_RCVD)
15185 			cmdp->cb_error = ENOTCONN;
15186 		else
15187 			cmdp->cb_error = conn_getpeername(connp, data,
15188 			    &cmdp->cb_len);
15189 		break;
15190 	case TI_GETMYNAME:
15191 		cmdp->cb_error = conn_getsockname(connp, data, &cmdp->cb_len);
15192 		break;
15193 	default:
15194 		cmdp->cb_error = EINVAL;
15195 		break;
15196 	}
15197 
15198 	qreply(q, mp);
15199 }
15200 
15201 void
15202 tcp_wput(queue_t *q, mblk_t *mp)
15203 {
15204 	conn_t	*connp = Q_TO_CONN(q);
15205 	tcp_t	*tcp;
15206 	void (*output_proc)();
15207 	t_scalar_t type;
15208 	uchar_t *rptr;
15209 	struct iocblk	*iocp;
15210 	size_t size;
15211 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
15212 
15213 	ASSERT(connp->conn_ref >= 2);
15214 
15215 	switch (DB_TYPE(mp)) {
15216 	case M_DATA:
15217 		tcp = connp->conn_tcp;
15218 		ASSERT(tcp != NULL);
15219 
15220 		size = msgdsize(mp);
15221 
15222 		mutex_enter(&tcp->tcp_non_sq_lock);
15223 		tcp->tcp_squeue_bytes += size;
15224 		if (TCP_UNSENT_BYTES(tcp) > connp->conn_sndbuf) {
15225 			tcp_setqfull(tcp);
15226 		}
15227 		mutex_exit(&tcp->tcp_non_sq_lock);
15228 
15229 		CONN_INC_REF(connp);
15230 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
15231 		    NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
15232 		return;
15233 
15234 	case M_CMD:
15235 		tcp_wput_cmdblk(q, mp);
15236 		return;
15237 
15238 	case M_PROTO:
15239 	case M_PCPROTO:
15240 		/*
15241 		 * if it is a snmp message, don't get behind the squeue
15242 		 */
15243 		tcp = connp->conn_tcp;
15244 		rptr = mp->b_rptr;
15245 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
15246 			type = ((union T_primitives *)rptr)->type;
15247 		} else {
15248 			if (connp->conn_debug) {
15249 				(void) strlog(TCP_MOD_ID, 0, 1,
15250 				    SL_ERROR|SL_TRACE,
15251 				    "tcp_wput_proto, dropping one...");
15252 			}
15253 			freemsg(mp);
15254 			return;
15255 		}
15256 		if (type == T_SVR4_OPTMGMT_REQ) {
15257 			/*
15258 			 * All Solaris components should pass a db_credp
15259 			 * for this TPI message, hence we ASSERT.
15260 			 * But in case there is some other M_PROTO that looks
15261 			 * like a TPI message sent by some other kernel
15262 			 * component, we check and return an error.
15263 			 */
15264 			cred_t	*cr = msg_getcred(mp, NULL);
15265 
15266 			ASSERT(cr != NULL);
15267 			if (cr == NULL) {
15268 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
15269 				return;
15270 			}
15271 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
15272 			    cr)) {
15273 				/*
15274 				 * This was a SNMP request
15275 				 */
15276 				return;
15277 			} else {
15278 				output_proc = tcp_wput_proto;
15279 			}
15280 		} else {
15281 			output_proc = tcp_wput_proto;
15282 		}
15283 		break;
15284 	case M_IOCTL:
15285 		/*
15286 		 * Most ioctls can be processed right away without going via
15287 		 * squeues - process them right here. Those that do require
15288 		 * squeue (currently _SIOCSOCKFALLBACK)
15289 		 * are processed by tcp_wput_ioctl().
15290 		 */
15291 		iocp = (struct iocblk *)mp->b_rptr;
15292 		tcp = connp->conn_tcp;
15293 
15294 		switch (iocp->ioc_cmd) {
15295 		case TCP_IOC_ABORT_CONN:
15296 			tcp_ioctl_abort_conn(q, mp);
15297 			return;
15298 		case TI_GETPEERNAME:
15299 		case TI_GETMYNAME:
15300 			mi_copyin(q, mp, NULL,
15301 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
15302 			return;
15303 		case ND_SET:
15304 			/* nd_getset does the necessary checks */
15305 		case ND_GET:
15306 			if (nd_getset(q, tcps->tcps_g_nd, mp)) {
15307 				qreply(q, mp);
15308 				return;
15309 			}
15310 			CONN_INC_IOCTLREF(connp);
15311 			ip_wput_nondata(q, mp);
15312 			CONN_DEC_IOCTLREF(connp);
15313 			return;
15314 
15315 		default:
15316 			output_proc = tcp_wput_ioctl;
15317 			break;
15318 		}
15319 		break;
15320 	default:
15321 		output_proc = tcp_wput_nondata;
15322 		break;
15323 	}
15324 
15325 	CONN_INC_REF(connp);
15326 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
15327 	    NULL, tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
15328 }
15329 
15330 /*
15331  * Initial STREAMS write side put() procedure for sockets. It tries to
15332  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
15333  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
15334  * are handled by tcp_wput() as usual.
15335  *
15336  * All further messages will also be handled by tcp_wput() because we cannot
15337  * be sure that the above short cut is safe later.
15338  */
15339 static void
15340 tcp_wput_sock(queue_t *wq, mblk_t *mp)
15341 {
15342 	conn_t			*connp = Q_TO_CONN(wq);
15343 	tcp_t			*tcp = connp->conn_tcp;
15344 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
15345 
15346 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
15347 	wq->q_qinfo = &tcp_winit;
15348 
15349 	ASSERT(IPCL_IS_TCP(connp));
15350 	ASSERT(TCP_IS_SOCKET(tcp));
15351 
15352 	if (DB_TYPE(mp) == M_PCPROTO &&
15353 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
15354 	    car->PRIM_type == T_CAPABILITY_REQ) {
15355 		tcp_capability_req(tcp, mp);
15356 		return;
15357 	}
15358 
15359 	tcp_wput(wq, mp);
15360 }
15361 
15362 /* ARGSUSED */
15363 static void
15364 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
15365 {
15366 #ifdef DEBUG
15367 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
15368 #endif
15369 	freemsg(mp);
15370 }
15371 
15372 /*
15373  * Check the usability of ZEROCOPY. It's instead checking the flag set by IP.
15374  */
15375 static boolean_t
15376 tcp_zcopy_check(tcp_t *tcp)
15377 {
15378 	conn_t		*connp = tcp->tcp_connp;
15379 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
15380 	boolean_t	zc_enabled = B_FALSE;
15381 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15382 
15383 	if (do_tcpzcopy == 2)
15384 		zc_enabled = B_TRUE;
15385 	else if ((do_tcpzcopy == 1) && (ixa->ixa_flags & IXAF_ZCOPY_CAPAB))
15386 		zc_enabled = B_TRUE;
15387 
15388 	tcp->tcp_snd_zcopy_on = zc_enabled;
15389 	if (!TCP_IS_DETACHED(tcp)) {
15390 		if (zc_enabled) {
15391 			ixa->ixa_flags |= IXAF_VERIFY_ZCOPY;
15392 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15393 			    ZCVMSAFE);
15394 			TCP_STAT(tcps, tcp_zcopy_on);
15395 		} else {
15396 			ixa->ixa_flags &= ~IXAF_VERIFY_ZCOPY;
15397 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15398 			    ZCVMUNSAFE);
15399 			TCP_STAT(tcps, tcp_zcopy_off);
15400 		}
15401 	}
15402 	return (zc_enabled);
15403 }
15404 
15405 /*
15406  * Backoff from a zero-copy message by copying data to a new allocated
15407  * message and freeing the original desballoca'ed segmapped message.
15408  *
15409  * This function is called by following two callers:
15410  * 1. tcp_timer: fix_xmitlist is set to B_TRUE, because it's safe to free
15411  *    the origial desballoca'ed message and notify sockfs. This is in re-
15412  *    transmit state.
15413  * 2. tcp_output: fix_xmitlist is set to B_FALSE. Flag STRUIO_ZCNOTIFY need
15414  *    to be copied to new message.
15415  */
15416 static mblk_t *
15417 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, boolean_t fix_xmitlist)
15418 {
15419 	mblk_t		*nbp;
15420 	mblk_t		*head = NULL;
15421 	mblk_t		*tail = NULL;
15422 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15423 
15424 	ASSERT(bp != NULL);
15425 	while (bp != NULL) {
15426 		if (IS_VMLOANED_MBLK(bp)) {
15427 			TCP_STAT(tcps, tcp_zcopy_backoff);
15428 			if ((nbp = copyb(bp)) == NULL) {
15429 				tcp->tcp_xmit_zc_clean = B_FALSE;
15430 				if (tail != NULL)
15431 					tail->b_cont = bp;
15432 				return ((head == NULL) ? bp : head);
15433 			}
15434 
15435 			if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
15436 				if (fix_xmitlist)
15437 					tcp_zcopy_notify(tcp);
15438 				else
15439 					nbp->b_datap->db_struioflag |=
15440 					    STRUIO_ZCNOTIFY;
15441 			}
15442 			nbp->b_cont = bp->b_cont;
15443 
15444 			/*
15445 			 * Copy saved information and adjust tcp_xmit_tail
15446 			 * if needed.
15447 			 */
15448 			if (fix_xmitlist) {
15449 				nbp->b_prev = bp->b_prev;
15450 				nbp->b_next = bp->b_next;
15451 
15452 				if (tcp->tcp_xmit_tail == bp)
15453 					tcp->tcp_xmit_tail = nbp;
15454 			}
15455 
15456 			/* Free the original message. */
15457 			bp->b_prev = NULL;
15458 			bp->b_next = NULL;
15459 			freeb(bp);
15460 
15461 			bp = nbp;
15462 		}
15463 
15464 		if (head == NULL) {
15465 			head = bp;
15466 		}
15467 		if (tail == NULL) {
15468 			tail = bp;
15469 		} else {
15470 			tail->b_cont = bp;
15471 			tail = bp;
15472 		}
15473 
15474 		/* Move forward. */
15475 		bp = bp->b_cont;
15476 	}
15477 
15478 	if (fix_xmitlist) {
15479 		tcp->tcp_xmit_last = tail;
15480 		tcp->tcp_xmit_zc_clean = B_TRUE;
15481 	}
15482 
15483 	return (head);
15484 }
15485 
15486 static void
15487 tcp_zcopy_notify(tcp_t *tcp)
15488 {
15489 	struct stdata	*stp;
15490 	conn_t		*connp;
15491 
15492 	if (tcp->tcp_detached)
15493 		return;
15494 	connp = tcp->tcp_connp;
15495 	if (IPCL_IS_NONSTR(connp)) {
15496 		(*connp->conn_upcalls->su_zcopy_notify)
15497 		    (connp->conn_upper_handle);
15498 		return;
15499 	}
15500 	stp = STREAM(connp->conn_rq);
15501 	mutex_enter(&stp->sd_lock);
15502 	stp->sd_flag |= STZCNOTIFY;
15503 	cv_broadcast(&stp->sd_zcopy_wait);
15504 	mutex_exit(&stp->sd_lock);
15505 }
15506 
15507 /*
15508  * Update the TCP connection according to change of LSO capability.
15509  */
15510 static void
15511 tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa)
15512 {
15513 	/*
15514 	 * We check against IPv4 header length to preserve the old behavior
15515 	 * of only enabling LSO when there are no IP options.
15516 	 * But this restriction might not be necessary at all. Before removing
15517 	 * it, need to verify how LSO is handled for source routing case, with
15518 	 * which IP does software checksum.
15519 	 *
15520 	 * For IPv6, whenever any extension header is needed, LSO is supressed.
15521 	 */
15522 	if (ixa->ixa_ip_hdr_length != ((ixa->ixa_flags & IXAF_IS_IPV4) ?
15523 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN))
15524 		return;
15525 
15526 	/*
15527 	 * Either the LSO capability newly became usable, or it has changed.
15528 	 */
15529 	if (ixa->ixa_flags & IXAF_LSO_CAPAB) {
15530 		ill_lso_capab_t	*lsoc = &ixa->ixa_lso_capab;
15531 
15532 		ASSERT(lsoc->ill_lso_max > 0);
15533 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH, lsoc->ill_lso_max);
15534 
15535 		DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
15536 		    boolean_t, B_TRUE, uint32_t, tcp->tcp_lso_max);
15537 
15538 		/*
15539 		 * If LSO to be enabled, notify the STREAM header with larger
15540 		 * data block.
15541 		 */
15542 		if (!tcp->tcp_lso)
15543 			tcp->tcp_maxpsz_multiplier = 0;
15544 
15545 		tcp->tcp_lso = B_TRUE;
15546 		TCP_STAT(tcp->tcp_tcps, tcp_lso_enabled);
15547 	} else { /* LSO capability is not usable any more. */
15548 		DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
15549 		    boolean_t, B_FALSE, uint32_t, tcp->tcp_lso_max);
15550 
15551 		/*
15552 		 * If LSO to be disabled, notify the STREAM header with smaller
15553 		 * data block. And need to restore fragsize to PMTU.
15554 		 */
15555 		if (tcp->tcp_lso) {
15556 			tcp->tcp_maxpsz_multiplier =
15557 			    tcp->tcp_tcps->tcps_maxpsz_multiplier;
15558 			ixa->ixa_fragsize = ixa->ixa_pmtu;
15559 			tcp->tcp_lso = B_FALSE;
15560 			TCP_STAT(tcp->tcp_tcps, tcp_lso_disabled);
15561 		}
15562 	}
15563 
15564 	(void) tcp_maxpsz_set(tcp, B_TRUE);
15565 }
15566 
15567 /*
15568  * Update the TCP connection according to change of ZEROCOPY capability.
15569  */
15570 static void
15571 tcp_update_zcopy(tcp_t *tcp)
15572 {
15573 	conn_t		*connp = tcp->tcp_connp;
15574 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15575 
15576 	if (tcp->tcp_snd_zcopy_on) {
15577 		tcp->tcp_snd_zcopy_on = B_FALSE;
15578 		if (!TCP_IS_DETACHED(tcp)) {
15579 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15580 			    ZCVMUNSAFE);
15581 			TCP_STAT(tcps, tcp_zcopy_off);
15582 		}
15583 	} else {
15584 		tcp->tcp_snd_zcopy_on = B_TRUE;
15585 		if (!TCP_IS_DETACHED(tcp)) {
15586 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15587 			    ZCVMSAFE);
15588 			TCP_STAT(tcps, tcp_zcopy_on);
15589 		}
15590 	}
15591 }
15592 
15593 /*
15594  * Notify function registered with ip_xmit_attr_t. It's called in the squeue
15595  * so it's safe to update the TCP connection.
15596  */
15597 /* ARGSUSED1 */
15598 static void
15599 tcp_notify(void *arg, ip_xmit_attr_t *ixa, ixa_notify_type_t ntype,
15600     ixa_notify_arg_t narg)
15601 {
15602 	tcp_t		*tcp = (tcp_t *)arg;
15603 	conn_t		*connp = tcp->tcp_connp;
15604 
15605 	switch (ntype) {
15606 	case IXAN_LSO:
15607 		tcp_update_lso(tcp, connp->conn_ixa);
15608 		break;
15609 	case IXAN_PMTU:
15610 		tcp_update_pmtu(tcp, B_FALSE);
15611 		break;
15612 	case IXAN_ZCOPY:
15613 		tcp_update_zcopy(tcp);
15614 		break;
15615 	default:
15616 		break;
15617 	}
15618 }
15619 
15620 static void
15621 tcp_send_data(tcp_t *tcp, mblk_t *mp)
15622 {
15623 	conn_t		*connp = tcp->tcp_connp;
15624 
15625 	/*
15626 	 * Check here to avoid sending zero-copy message down to IP when
15627 	 * ZEROCOPY capability has turned off. We only need to deal with
15628 	 * the race condition between sockfs and the notification here.
15629 	 * Since we have tried to backoff the tcp_xmit_head when turning
15630 	 * zero-copy off and new messages in tcp_output(), we simply drop
15631 	 * the dup'ed packet here and let tcp retransmit, if tcp_xmit_zc_clean
15632 	 * is not true.
15633 	 */
15634 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on &&
15635 	    !tcp->tcp_xmit_zc_clean) {
15636 		ip_drop_output("TCP ZC was disabled but not clean", mp, NULL);
15637 		freemsg(mp);
15638 		return;
15639 	}
15640 
15641 	ASSERT(connp->conn_ixa->ixa_notify_cookie == connp->conn_tcp);
15642 	(void) conn_ip_output(mp, connp->conn_ixa);
15643 }
15644 
15645 /*
15646  * This handles the case when the receiver has shrunk its win. Per RFC 1122
15647  * if the receiver shrinks the window, i.e. moves the right window to the
15648  * left, the we should not send new data, but should retransmit normally the
15649  * old unacked data between suna and suna + swnd. We might has sent data
15650  * that is now outside the new window, pretend that we didn't send  it.
15651  */
15652 static void
15653 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
15654 {
15655 	uint32_t	snxt = tcp->tcp_snxt;
15656 
15657 	ASSERT(shrunk_count > 0);
15658 
15659 	if (!tcp->tcp_is_wnd_shrnk) {
15660 		tcp->tcp_snxt_shrunk = snxt;
15661 		tcp->tcp_is_wnd_shrnk = B_TRUE;
15662 	} else if (SEQ_GT(snxt, tcp->tcp_snxt_shrunk)) {
15663 		tcp->tcp_snxt_shrunk = snxt;
15664 	}
15665 
15666 	/* Pretend we didn't send the data outside the window */
15667 	snxt -= shrunk_count;
15668 
15669 	/* Reset all the values per the now shrunk window */
15670 	tcp_update_xmit_tail(tcp, snxt);
15671 	tcp->tcp_unsent += shrunk_count;
15672 
15673 	/*
15674 	 * If the SACK option is set, delete the entire list of
15675 	 * notsack'ed blocks.
15676 	 */
15677 	if (tcp->tcp_sack_info != NULL) {
15678 		if (tcp->tcp_notsack_list != NULL)
15679 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
15680 	}
15681 
15682 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
15683 		/*
15684 		 * Make sure the timer is running so that we will probe a zero
15685 		 * window.
15686 		 */
15687 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15688 }
15689 
15690 
15691 /*
15692  * The TCP normal data output path.
15693  * NOTE: the logic of the fast path is duplicated from this function.
15694  */
15695 static void
15696 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
15697 {
15698 	int		len;
15699 	mblk_t		*local_time;
15700 	mblk_t		*mp1;
15701 	uint32_t	snxt;
15702 	int		tail_unsent;
15703 	int		tcpstate;
15704 	int		usable = 0;
15705 	mblk_t		*xmit_tail;
15706 	int32_t		mss;
15707 	int32_t		num_sack_blk = 0;
15708 	int32_t		total_hdr_len;
15709 	int32_t		tcp_hdr_len;
15710 	int		rc;
15711 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15712 	conn_t		*connp = tcp->tcp_connp;
15713 	clock_t		now = LBOLT_FASTPATH;
15714 
15715 	tcpstate = tcp->tcp_state;
15716 	if (mp == NULL) {
15717 		/*
15718 		 * tcp_wput_data() with NULL mp should only be called when
15719 		 * there is unsent data.
15720 		 */
15721 		ASSERT(tcp->tcp_unsent > 0);
15722 		/* Really tacky... but we need this for detached closes. */
15723 		len = tcp->tcp_unsent;
15724 		goto data_null;
15725 	}
15726 
15727 #if CCS_STATS
15728 	wrw_stats.tot.count++;
15729 	wrw_stats.tot.bytes += msgdsize(mp);
15730 #endif
15731 	ASSERT(mp->b_datap->db_type == M_DATA);
15732 	/*
15733 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
15734 	 * or before a connection attempt has begun.
15735 	 */
15736 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
15737 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
15738 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
15739 #ifdef DEBUG
15740 			cmn_err(CE_WARN,
15741 			    "tcp_wput_data: data after ordrel, %s",
15742 			    tcp_display(tcp, NULL,
15743 			    DISP_ADDR_AND_PORT));
15744 #else
15745 			if (connp->conn_debug) {
15746 				(void) strlog(TCP_MOD_ID, 0, 1,
15747 				    SL_TRACE|SL_ERROR,
15748 				    "tcp_wput_data: data after ordrel, %s\n",
15749 				    tcp_display(tcp, NULL,
15750 				    DISP_ADDR_AND_PORT));
15751 			}
15752 #endif /* DEBUG */
15753 		}
15754 		if (tcp->tcp_snd_zcopy_aware &&
15755 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
15756 			tcp_zcopy_notify(tcp);
15757 		freemsg(mp);
15758 		mutex_enter(&tcp->tcp_non_sq_lock);
15759 		if (tcp->tcp_flow_stopped &&
15760 		    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
15761 			tcp_clrqfull(tcp);
15762 		}
15763 		mutex_exit(&tcp->tcp_non_sq_lock);
15764 		return;
15765 	}
15766 
15767 	/* Strip empties */
15768 	for (;;) {
15769 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
15770 		    (uintptr_t)INT_MAX);
15771 		len = (int)(mp->b_wptr - mp->b_rptr);
15772 		if (len > 0)
15773 			break;
15774 		mp1 = mp;
15775 		mp = mp->b_cont;
15776 		freeb(mp1);
15777 		if (!mp) {
15778 			return;
15779 		}
15780 	}
15781 
15782 	/* If we are the first on the list ... */
15783 	if (tcp->tcp_xmit_head == NULL) {
15784 		tcp->tcp_xmit_head = mp;
15785 		tcp->tcp_xmit_tail = mp;
15786 		tcp->tcp_xmit_tail_unsent = len;
15787 	} else {
15788 		/* If tiny tx and room in txq tail, pullup to save mblks. */
15789 		struct datab *dp;
15790 
15791 		mp1 = tcp->tcp_xmit_last;
15792 		if (len < tcp_tx_pull_len &&
15793 		    (dp = mp1->b_datap)->db_ref == 1 &&
15794 		    dp->db_lim - mp1->b_wptr >= len) {
15795 			ASSERT(len > 0);
15796 			ASSERT(!mp1->b_cont);
15797 			if (len == 1) {
15798 				*mp1->b_wptr++ = *mp->b_rptr;
15799 			} else {
15800 				bcopy(mp->b_rptr, mp1->b_wptr, len);
15801 				mp1->b_wptr += len;
15802 			}
15803 			if (mp1 == tcp->tcp_xmit_tail)
15804 				tcp->tcp_xmit_tail_unsent += len;
15805 			mp1->b_cont = mp->b_cont;
15806 			if (tcp->tcp_snd_zcopy_aware &&
15807 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
15808 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
15809 			freeb(mp);
15810 			mp = mp1;
15811 		} else {
15812 			tcp->tcp_xmit_last->b_cont = mp;
15813 		}
15814 		len += tcp->tcp_unsent;
15815 	}
15816 
15817 	/* Tack on however many more positive length mblks we have */
15818 	if ((mp1 = mp->b_cont) != NULL) {
15819 		do {
15820 			int tlen;
15821 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
15822 			    (uintptr_t)INT_MAX);
15823 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
15824 			if (tlen <= 0) {
15825 				mp->b_cont = mp1->b_cont;
15826 				freeb(mp1);
15827 			} else {
15828 				len += tlen;
15829 				mp = mp1;
15830 			}
15831 		} while ((mp1 = mp->b_cont) != NULL);
15832 	}
15833 	tcp->tcp_xmit_last = mp;
15834 	tcp->tcp_unsent = len;
15835 
15836 	if (urgent)
15837 		usable = 1;
15838 
15839 data_null:
15840 	snxt = tcp->tcp_snxt;
15841 	xmit_tail = tcp->tcp_xmit_tail;
15842 	tail_unsent = tcp->tcp_xmit_tail_unsent;
15843 
15844 	/*
15845 	 * Note that tcp_mss has been adjusted to take into account the
15846 	 * timestamp option if applicable.  Because SACK options do not
15847 	 * appear in every TCP segments and they are of variable lengths,
15848 	 * they cannot be included in tcp_mss.  Thus we need to calculate
15849 	 * the actual segment length when we need to send a segment which
15850 	 * includes SACK options.
15851 	 */
15852 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15853 		int32_t	opt_len;
15854 
15855 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
15856 		    tcp->tcp_num_sack_blk);
15857 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
15858 		    2 + TCPOPT_HEADER_LEN;
15859 		mss = tcp->tcp_mss - opt_len;
15860 		total_hdr_len = connp->conn_ht_iphc_len + opt_len;
15861 		tcp_hdr_len = connp->conn_ht_ulp_len + opt_len;
15862 	} else {
15863 		mss = tcp->tcp_mss;
15864 		total_hdr_len = connp->conn_ht_iphc_len;
15865 		tcp_hdr_len = connp->conn_ht_ulp_len;
15866 	}
15867 
15868 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
15869 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
15870 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
15871 	}
15872 	if (tcpstate == TCPS_SYN_RCVD) {
15873 		/*
15874 		 * The three-way connection establishment handshake is not
15875 		 * complete yet. We want to queue the data for transmission
15876 		 * after entering ESTABLISHED state (RFC793). A jump to
15877 		 * "done" label effectively leaves data on the queue.
15878 		 */
15879 		goto done;
15880 	} else {
15881 		int usable_r;
15882 
15883 		/*
15884 		 * In the special case when cwnd is zero, which can only
15885 		 * happen if the connection is ECN capable, return now.
15886 		 * New segments is sent using tcp_timer().  The timer
15887 		 * is set in tcp_input_data().
15888 		 */
15889 		if (tcp->tcp_cwnd == 0) {
15890 			/*
15891 			 * Note that tcp_cwnd is 0 before 3-way handshake is
15892 			 * finished.
15893 			 */
15894 			ASSERT(tcp->tcp_ecn_ok ||
15895 			    tcp->tcp_state < TCPS_ESTABLISHED);
15896 			return;
15897 		}
15898 
15899 		/* NOTE: trouble if xmitting while SYN not acked? */
15900 		usable_r = snxt - tcp->tcp_suna;
15901 		usable_r = tcp->tcp_swnd - usable_r;
15902 
15903 		/*
15904 		 * Check if the receiver has shrunk the window.  If
15905 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
15906 		 * cannot be set as there is unsent data, so FIN cannot
15907 		 * be sent out.  Otherwise, we need to take into account
15908 		 * of FIN as it consumes an "invisible" sequence number.
15909 		 */
15910 		ASSERT(tcp->tcp_fin_sent == 0);
15911 		if (usable_r < 0) {
15912 			/*
15913 			 * The receiver has shrunk the window and we have sent
15914 			 * -usable_r date beyond the window, re-adjust.
15915 			 *
15916 			 * If TCP window scaling is enabled, there can be
15917 			 * round down error as the advertised receive window
15918 			 * is actually right shifted n bits.  This means that
15919 			 * the lower n bits info is wiped out.  It will look
15920 			 * like the window is shrunk.  Do a check here to
15921 			 * see if the shrunk amount is actually within the
15922 			 * error in window calculation.  If it is, just
15923 			 * return.  Note that this check is inside the
15924 			 * shrunk window check.  This makes sure that even
15925 			 * though tcp_process_shrunk_swnd() is not called,
15926 			 * we will stop further processing.
15927 			 */
15928 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
15929 				tcp_process_shrunk_swnd(tcp, -usable_r);
15930 			}
15931 			return;
15932 		}
15933 
15934 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
15935 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
15936 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
15937 
15938 		/* usable = MIN(usable, unsent) */
15939 		if (usable_r > len)
15940 			usable_r = len;
15941 
15942 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
15943 		if (usable_r > 0) {
15944 			usable = usable_r;
15945 		} else {
15946 			/* Bypass all other unnecessary processing. */
15947 			goto done;
15948 		}
15949 	}
15950 
15951 	local_time = (mblk_t *)now;
15952 
15953 	/*
15954 	 * "Our" Nagle Algorithm.  This is not the same as in the old
15955 	 * BSD.  This is more in line with the true intent of Nagle.
15956 	 *
15957 	 * The conditions are:
15958 	 * 1. The amount of unsent data (or amount of data which can be
15959 	 *    sent, whichever is smaller) is less than Nagle limit.
15960 	 * 2. The last sent size is also less than Nagle limit.
15961 	 * 3. There is unack'ed data.
15962 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
15963 	 *    Nagle algorithm.  This reduces the probability that urgent
15964 	 *    bytes get "merged" together.
15965 	 * 5. The app has not closed the connection.  This eliminates the
15966 	 *    wait time of the receiving side waiting for the last piece of
15967 	 *    (small) data.
15968 	 *
15969 	 * If all are satisified, exit without sending anything.  Note
15970 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
15971 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
15972 	 * 4095).
15973 	 */
15974 	if (usable < (int)tcp->tcp_naglim &&
15975 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
15976 	    snxt != tcp->tcp_suna &&
15977 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
15978 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
15979 		goto done;
15980 	}
15981 
15982 	/*
15983 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
15984 	 * is set, then we have to force TCP not to send partial segment
15985 	 * (smaller than MSS bytes). We are calculating the usable now
15986 	 * based on full mss and will save the rest of remaining data for
15987 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
15988 	 * something to do zero window probe.
15989 	 */
15990 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
15991 		if (usable < mss)
15992 			goto done;
15993 		usable = (usable / mss) * mss;
15994 	}
15995 
15996 	/* Update the latest receive window size in TCP header. */
15997 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
15998 
15999 	/* Send the packet. */
16000 	rc = tcp_send(tcp, mss, total_hdr_len, tcp_hdr_len,
16001 	    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
16002 	    local_time);
16003 
16004 	/* Pretend that all we were trying to send really got sent */
16005 	if (rc < 0 && tail_unsent < 0) {
16006 		do {
16007 			xmit_tail = xmit_tail->b_cont;
16008 			xmit_tail->b_prev = local_time;
16009 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
16010 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
16011 			tail_unsent += (int)(xmit_tail->b_wptr -
16012 			    xmit_tail->b_rptr);
16013 		} while (tail_unsent < 0);
16014 	}
16015 done:;
16016 	tcp->tcp_xmit_tail = xmit_tail;
16017 	tcp->tcp_xmit_tail_unsent = tail_unsent;
16018 	len = tcp->tcp_snxt - snxt;
16019 	if (len) {
16020 		/*
16021 		 * If new data was sent, need to update the notsack
16022 		 * list, which is, afterall, data blocks that have
16023 		 * not been sack'ed by the receiver.  New data is
16024 		 * not sack'ed.
16025 		 */
16026 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16027 			/* len is a negative value. */
16028 			tcp->tcp_pipe -= len;
16029 			tcp_notsack_update(&(tcp->tcp_notsack_list),
16030 			    tcp->tcp_snxt, snxt,
16031 			    &(tcp->tcp_num_notsack_blk),
16032 			    &(tcp->tcp_cnt_notsack_list));
16033 		}
16034 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
16035 		tcp->tcp_rack = tcp->tcp_rnxt;
16036 		tcp->tcp_rack_cnt = 0;
16037 		if ((snxt + len) == tcp->tcp_suna) {
16038 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16039 		}
16040 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
16041 		/*
16042 		 * Didn't send anything. Make sure the timer is running
16043 		 * so that we will probe a zero window.
16044 		 */
16045 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16046 	}
16047 	/* Note that len is the amount we just sent but with a negative sign */
16048 	tcp->tcp_unsent += len;
16049 	mutex_enter(&tcp->tcp_non_sq_lock);
16050 	if (tcp->tcp_flow_stopped) {
16051 		if (TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
16052 			tcp_clrqfull(tcp);
16053 		}
16054 	} else if (TCP_UNSENT_BYTES(tcp) >= connp->conn_sndbuf) {
16055 		if (!(tcp->tcp_detached))
16056 			tcp_setqfull(tcp);
16057 	}
16058 	mutex_exit(&tcp->tcp_non_sq_lock);
16059 }
16060 
16061 /*
16062  * tcp_fill_header is called by tcp_send() to fill the outgoing TCP header
16063  * with the template header, as well as other options such as time-stamp,
16064  * ECN and/or SACK.
16065  */
16066 static void
16067 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
16068 {
16069 	tcpha_t *tcp_tmpl, *tcpha;
16070 	uint32_t *dst, *src;
16071 	int hdrlen;
16072 	conn_t *connp = tcp->tcp_connp;
16073 
16074 	ASSERT(OK_32PTR(rptr));
16075 
16076 	/* Template header */
16077 	tcp_tmpl = tcp->tcp_tcpha;
16078 
16079 	/* Header of outgoing packet */
16080 	tcpha = (tcpha_t *)(rptr + connp->conn_ixa->ixa_ip_hdr_length);
16081 
16082 	/* dst and src are opaque 32-bit fields, used for copying */
16083 	dst = (uint32_t *)rptr;
16084 	src = (uint32_t *)connp->conn_ht_iphc;
16085 	hdrlen = connp->conn_ht_iphc_len;
16086 
16087 	/* Fill time-stamp option if needed */
16088 	if (tcp->tcp_snd_ts_ok) {
16089 		U32_TO_BE32((uint32_t)now,
16090 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
16091 		U32_TO_BE32(tcp->tcp_ts_recent,
16092 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
16093 	} else {
16094 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
16095 	}
16096 
16097 	/*
16098 	 * Copy the template header; is this really more efficient than
16099 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
16100 	 * but perhaps not for other scenarios.
16101 	 */
16102 	dst[0] = src[0];
16103 	dst[1] = src[1];
16104 	dst[2] = src[2];
16105 	dst[3] = src[3];
16106 	dst[4] = src[4];
16107 	dst[5] = src[5];
16108 	dst[6] = src[6];
16109 	dst[7] = src[7];
16110 	dst[8] = src[8];
16111 	dst[9] = src[9];
16112 	if (hdrlen -= 40) {
16113 		hdrlen >>= 2;
16114 		dst += 10;
16115 		src += 10;
16116 		do {
16117 			*dst++ = *src++;
16118 		} while (--hdrlen);
16119 	}
16120 
16121 	/*
16122 	 * Set the ECN info in the TCP header if it is not a zero
16123 	 * window probe.  Zero window probe is only sent in
16124 	 * tcp_wput_data() and tcp_timer().
16125 	 */
16126 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
16127 		SET_ECT(tcp, rptr);
16128 
16129 		if (tcp->tcp_ecn_echo_on)
16130 			tcpha->tha_flags |= TH_ECE;
16131 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
16132 			tcpha->tha_flags |= TH_CWR;
16133 			tcp->tcp_ecn_cwr_sent = B_TRUE;
16134 		}
16135 	}
16136 
16137 	/* Fill in SACK options */
16138 	if (num_sack_blk > 0) {
16139 		uchar_t *wptr = rptr + connp->conn_ht_iphc_len;
16140 		sack_blk_t *tmp;
16141 		int32_t	i;
16142 
16143 		wptr[0] = TCPOPT_NOP;
16144 		wptr[1] = TCPOPT_NOP;
16145 		wptr[2] = TCPOPT_SACK;
16146 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
16147 		    sizeof (sack_blk_t);
16148 		wptr += TCPOPT_REAL_SACK_LEN;
16149 
16150 		tmp = tcp->tcp_sack_list;
16151 		for (i = 0; i < num_sack_blk; i++) {
16152 			U32_TO_BE32(tmp[i].begin, wptr);
16153 			wptr += sizeof (tcp_seq);
16154 			U32_TO_BE32(tmp[i].end, wptr);
16155 			wptr += sizeof (tcp_seq);
16156 		}
16157 		tcpha->tha_offset_and_reserved +=
16158 		    ((num_sack_blk * 2 + 1) << 4);
16159 	}
16160 }
16161 
16162 /*
16163  * tcp_send() is called by tcp_wput_data() and returns one of the following:
16164  *
16165  * -1 = failed allocation.
16166  *  0 = success; burst count reached, or usable send window is too small,
16167  *      and that we'd rather wait until later before sending again.
16168  */
16169 static int
16170 tcp_send(tcp_t *tcp, const int mss, const int total_hdr_len,
16171     const int tcp_hdr_len, const int num_sack_blk, int *usable,
16172     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time)
16173 {
16174 	int		num_burst_seg = tcp->tcp_snd_burst;
16175 	int		num_lso_seg = 1;
16176 	uint_t		lso_usable;
16177 	boolean_t	do_lso_send = B_FALSE;
16178 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16179 	conn_t		*connp = tcp->tcp_connp;
16180 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
16181 
16182 	/*
16183 	 * Check LSO possibility. The value of tcp->tcp_lso indicates whether
16184 	 * the underlying connection is LSO capable. Will check whether having
16185 	 * enough available data to initiate LSO transmission in the for(){}
16186 	 * loops.
16187 	 */
16188 	if (tcp->tcp_lso && (tcp->tcp_valid_bits & ~TCP_FSS_VALID) == 0)
16189 		do_lso_send = B_TRUE;
16190 
16191 	for (;;) {
16192 		struct datab	*db;
16193 		tcpha_t		*tcpha;
16194 		uint32_t	sum;
16195 		mblk_t		*mp, *mp1;
16196 		uchar_t		*rptr;
16197 		int		len;
16198 
16199 		/*
16200 		 * Burst count reached, return successfully.
16201 		 */
16202 		if (num_burst_seg == 0)
16203 			break;
16204 
16205 		/*
16206 		 * Calculate the maximum payload length we can send at one
16207 		 * time.
16208 		 */
16209 		if (do_lso_send) {
16210 			/*
16211 			 * Check whether be able to to do LSO for the current
16212 			 * available data.
16213 			 */
16214 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
16215 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
16216 				lso_usable = MIN(lso_usable,
16217 				    num_burst_seg * mss);
16218 
16219 				num_lso_seg = lso_usable / mss;
16220 				if (lso_usable % mss) {
16221 					num_lso_seg++;
16222 					tcp->tcp_last_sent_len = (ushort_t)
16223 					    (lso_usable % mss);
16224 				} else {
16225 					tcp->tcp_last_sent_len = (ushort_t)mss;
16226 				}
16227 			} else {
16228 				do_lso_send = B_FALSE;
16229 				num_lso_seg = 1;
16230 				lso_usable = mss;
16231 			}
16232 		}
16233 
16234 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
16235 #ifdef DEBUG
16236 		DTRACE_PROBE2(tcp_send_lso, int, num_lso_seg, boolean_t,
16237 		    do_lso_send);
16238 #endif
16239 		/*
16240 		 * Adjust num_burst_seg here.
16241 		 */
16242 		num_burst_seg -= num_lso_seg;
16243 
16244 		len = mss;
16245 		if (len > *usable) {
16246 			ASSERT(do_lso_send == B_FALSE);
16247 
16248 			len = *usable;
16249 			if (len <= 0) {
16250 				/* Terminate the loop */
16251 				break;	/* success; too small */
16252 			}
16253 			/*
16254 			 * Sender silly-window avoidance.
16255 			 * Ignore this if we are going to send a
16256 			 * zero window probe out.
16257 			 *
16258 			 * TODO: force data into microscopic window?
16259 			 *	==> (!pushed || (unsent > usable))
16260 			 */
16261 			if (len < (tcp->tcp_max_swnd >> 1) &&
16262 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
16263 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
16264 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
16265 				/*
16266 				 * If the retransmit timer is not running
16267 				 * we start it so that we will retransmit
16268 				 * in the case when the receiver has
16269 				 * decremented the window.
16270 				 */
16271 				if (*snxt == tcp->tcp_snxt &&
16272 				    *snxt == tcp->tcp_suna) {
16273 					/*
16274 					 * We are not supposed to send
16275 					 * anything.  So let's wait a little
16276 					 * bit longer before breaking SWS
16277 					 * avoidance.
16278 					 *
16279 					 * What should the value be?
16280 					 * Suggestion: MAX(init rexmit time,
16281 					 * tcp->tcp_rto)
16282 					 */
16283 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16284 				}
16285 				break;	/* success; too small */
16286 			}
16287 		}
16288 
16289 		tcpha = tcp->tcp_tcpha;
16290 
16291 		/*
16292 		 * The reason to adjust len here is that we need to set flags
16293 		 * and calculate checksum.
16294 		 */
16295 		if (do_lso_send)
16296 			len = lso_usable;
16297 
16298 		*usable -= len; /* Approximate - can be adjusted later */
16299 		if (*usable > 0)
16300 			tcpha->tha_flags = TH_ACK;
16301 		else
16302 			tcpha->tha_flags = (TH_ACK | TH_PUSH);
16303 
16304 		/*
16305 		 * Prime pump for IP's checksumming on our behalf.
16306 		 * Include the adjustment for a source route if any.
16307 		 * In case of LSO, the partial pseudo-header checksum should
16308 		 * exclusive TCP length, so zero tha_sum before IP calculate
16309 		 * pseudo-header checksum for partial checksum offload.
16310 		 */
16311 		if (do_lso_send) {
16312 			sum = 0;
16313 		} else {
16314 			sum = len + tcp_hdr_len + connp->conn_sum;
16315 			sum = (sum >> 16) + (sum & 0xFFFF);
16316 		}
16317 		tcpha->tha_sum = htons(sum);
16318 		tcpha->tha_seq = htonl(*snxt);
16319 
16320 		/*
16321 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
16322 		 * set.  For the case when TCP_FSS_VALID is the only valid
16323 		 * bit (normal active close), branch off only when we think
16324 		 * that the FIN flag needs to be set.  Note for this case,
16325 		 * that (snxt + len) may not reflect the actual seg_len,
16326 		 * as len may be further reduced in tcp_xmit_mp().  If len
16327 		 * gets modified, we will end up here again.
16328 		 */
16329 		if (tcp->tcp_valid_bits != 0 &&
16330 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
16331 		    ((*snxt + len) == tcp->tcp_fss))) {
16332 			uchar_t		*prev_rptr;
16333 			uint32_t	prev_snxt = tcp->tcp_snxt;
16334 
16335 			if (*tail_unsent == 0) {
16336 				ASSERT((*xmit_tail)->b_cont != NULL);
16337 				*xmit_tail = (*xmit_tail)->b_cont;
16338 				prev_rptr = (*xmit_tail)->b_rptr;
16339 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
16340 				    (*xmit_tail)->b_rptr);
16341 			} else {
16342 				prev_rptr = (*xmit_tail)->b_rptr;
16343 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
16344 				    *tail_unsent;
16345 			}
16346 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
16347 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
16348 			/* Restore tcp_snxt so we get amount sent right. */
16349 			tcp->tcp_snxt = prev_snxt;
16350 			if (prev_rptr == (*xmit_tail)->b_rptr) {
16351 				/*
16352 				 * If the previous timestamp is still in use,
16353 				 * don't stomp on it.
16354 				 */
16355 				if ((*xmit_tail)->b_next == NULL) {
16356 					(*xmit_tail)->b_prev = local_time;
16357 					(*xmit_tail)->b_next =
16358 					    (mblk_t *)(uintptr_t)(*snxt);
16359 				}
16360 			} else
16361 				(*xmit_tail)->b_rptr = prev_rptr;
16362 
16363 			if (mp == NULL) {
16364 				return (-1);
16365 			}
16366 			mp1 = mp->b_cont;
16367 
16368 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
16369 				tcp->tcp_last_sent_len = (ushort_t)len;
16370 			while (mp1->b_cont) {
16371 				*xmit_tail = (*xmit_tail)->b_cont;
16372 				(*xmit_tail)->b_prev = local_time;
16373 				(*xmit_tail)->b_next =
16374 				    (mblk_t *)(uintptr_t)(*snxt);
16375 				mp1 = mp1->b_cont;
16376 			}
16377 			*snxt += len;
16378 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
16379 			BUMP_LOCAL(tcp->tcp_obsegs);
16380 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16381 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16382 			tcp_send_data(tcp, mp);
16383 			continue;
16384 		}
16385 
16386 		*snxt += len;	/* Adjust later if we don't send all of len */
16387 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16388 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16389 
16390 		if (*tail_unsent) {
16391 			/* Are the bytes above us in flight? */
16392 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
16393 			if (rptr != (*xmit_tail)->b_rptr) {
16394 				*tail_unsent -= len;
16395 				if (len <= mss) /* LSO is unusable */
16396 					tcp->tcp_last_sent_len = (ushort_t)len;
16397 				len += total_hdr_len;
16398 				ixa->ixa_pktlen = len;
16399 
16400 				if (ixa->ixa_flags & IXAF_IS_IPV4) {
16401 					tcp->tcp_ipha->ipha_length = htons(len);
16402 				} else {
16403 					tcp->tcp_ip6h->ip6_plen =
16404 					    htons(len - IPV6_HDR_LEN);
16405 				}
16406 
16407 				mp = dupb(*xmit_tail);
16408 				if (mp == NULL) {
16409 					return (-1);	/* out_of_mem */
16410 				}
16411 				mp->b_rptr = rptr;
16412 				/*
16413 				 * If the old timestamp is no longer in use,
16414 				 * sample a new timestamp now.
16415 				 */
16416 				if ((*xmit_tail)->b_next == NULL) {
16417 					(*xmit_tail)->b_prev = local_time;
16418 					(*xmit_tail)->b_next =
16419 					    (mblk_t *)(uintptr_t)(*snxt-len);
16420 				}
16421 				goto must_alloc;
16422 			}
16423 		} else {
16424 			*xmit_tail = (*xmit_tail)->b_cont;
16425 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
16426 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
16427 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
16428 			    (*xmit_tail)->b_rptr);
16429 		}
16430 
16431 		(*xmit_tail)->b_prev = local_time;
16432 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
16433 
16434 		*tail_unsent -= len;
16435 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
16436 			tcp->tcp_last_sent_len = (ushort_t)len;
16437 
16438 		len += total_hdr_len;
16439 		ixa->ixa_pktlen = len;
16440 
16441 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
16442 			tcp->tcp_ipha->ipha_length = htons(len);
16443 		} else {
16444 			tcp->tcp_ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
16445 		}
16446 
16447 		mp = dupb(*xmit_tail);
16448 		if (mp == NULL) {
16449 			return (-1);	/* out_of_mem */
16450 		}
16451 
16452 		len = total_hdr_len;
16453 		/*
16454 		 * There are four reasons to allocate a new hdr mblk:
16455 		 *  1) The bytes above us are in use by another packet
16456 		 *  2) We don't have good alignment
16457 		 *  3) The mblk is being shared
16458 		 *  4) We don't have enough room for a header
16459 		 */
16460 		rptr = mp->b_rptr - len;
16461 		if (!OK_32PTR(rptr) ||
16462 		    ((db = mp->b_datap), db->db_ref != 2) ||
16463 		    rptr < db->db_base) {
16464 			/* NOTE: we assume allocb returns an OK_32PTR */
16465 
16466 		must_alloc:;
16467 			mp1 = allocb(connp->conn_ht_iphc_allocated +
16468 			    tcps->tcps_wroff_xtra, BPRI_MED);
16469 			if (mp1 == NULL) {
16470 				freemsg(mp);
16471 				return (-1);	/* out_of_mem */
16472 			}
16473 			mp1->b_cont = mp;
16474 			mp = mp1;
16475 			/* Leave room for Link Level header */
16476 			len = total_hdr_len;
16477 			rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
16478 			mp->b_wptr = &rptr[len];
16479 		}
16480 
16481 		/*
16482 		 * Fill in the header using the template header, and add
16483 		 * options such as time-stamp, ECN and/or SACK, as needed.
16484 		 */
16485 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
16486 
16487 		mp->b_rptr = rptr;
16488 
16489 		if (*tail_unsent) {
16490 			int spill = *tail_unsent;
16491 
16492 			mp1 = mp->b_cont;
16493 			if (mp1 == NULL)
16494 				mp1 = mp;
16495 
16496 			/*
16497 			 * If we're a little short, tack on more mblks until
16498 			 * there is no more spillover.
16499 			 */
16500 			while (spill < 0) {
16501 				mblk_t *nmp;
16502 				int nmpsz;
16503 
16504 				nmp = (*xmit_tail)->b_cont;
16505 				nmpsz = MBLKL(nmp);
16506 
16507 				/*
16508 				 * Excess data in mblk; can we split it?
16509 				 * If LSO is enabled for the connection,
16510 				 * keep on splitting as this is a transient
16511 				 * send path.
16512 				 */
16513 				if (!do_lso_send && (spill + nmpsz > 0)) {
16514 					/*
16515 					 * Don't split if stream head was
16516 					 * told to break up larger writes
16517 					 * into smaller ones.
16518 					 */
16519 					if (tcp->tcp_maxpsz_multiplier > 0)
16520 						break;
16521 
16522 					/*
16523 					 * Next mblk is less than SMSS/2
16524 					 * rounded up to nearest 64-byte;
16525 					 * let it get sent as part of the
16526 					 * next segment.
16527 					 */
16528 					if (tcp->tcp_localnet &&
16529 					    !tcp->tcp_cork &&
16530 					    (nmpsz < roundup((mss >> 1), 64)))
16531 						break;
16532 				}
16533 
16534 				*xmit_tail = nmp;
16535 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
16536 				/* Stash for rtt use later */
16537 				(*xmit_tail)->b_prev = local_time;
16538 				(*xmit_tail)->b_next =
16539 				    (mblk_t *)(uintptr_t)(*snxt - len);
16540 				mp1->b_cont = dupb(*xmit_tail);
16541 				mp1 = mp1->b_cont;
16542 
16543 				spill += nmpsz;
16544 				if (mp1 == NULL) {
16545 					*tail_unsent = spill;
16546 					freemsg(mp);
16547 					return (-1);	/* out_of_mem */
16548 				}
16549 			}
16550 
16551 			/* Trim back any surplus on the last mblk */
16552 			if (spill >= 0) {
16553 				mp1->b_wptr -= spill;
16554 				*tail_unsent = spill;
16555 			} else {
16556 				/*
16557 				 * We did not send everything we could in
16558 				 * order to remain within the b_cont limit.
16559 				 */
16560 				*usable -= spill;
16561 				*snxt += spill;
16562 				tcp->tcp_last_sent_len += spill;
16563 				UPDATE_MIB(&tcps->tcps_mib,
16564 				    tcpOutDataBytes, spill);
16565 				/*
16566 				 * Adjust the checksum
16567 				 */
16568 				tcpha = (tcpha_t *)(rptr +
16569 				    ixa->ixa_ip_hdr_length);
16570 				sum += spill;
16571 				sum = (sum >> 16) + (sum & 0xFFFF);
16572 				tcpha->tha_sum = htons(sum);
16573 				if (connp->conn_ipversion == IPV4_VERSION) {
16574 					sum = ntohs(
16575 					    ((ipha_t *)rptr)->ipha_length) +
16576 					    spill;
16577 					((ipha_t *)rptr)->ipha_length =
16578 					    htons(sum);
16579 				} else {
16580 					sum = ntohs(
16581 					    ((ip6_t *)rptr)->ip6_plen) +
16582 					    spill;
16583 					((ip6_t *)rptr)->ip6_plen =
16584 					    htons(sum);
16585 				}
16586 				ixa->ixa_pktlen += spill;
16587 				*tail_unsent = 0;
16588 			}
16589 		}
16590 		if (tcp->tcp_ip_forward_progress) {
16591 			tcp->tcp_ip_forward_progress = B_FALSE;
16592 			ixa->ixa_flags |= IXAF_REACH_CONF;
16593 		} else {
16594 			ixa->ixa_flags &= ~IXAF_REACH_CONF;
16595 		}
16596 
16597 		if (do_lso_send) {
16598 			/* Append LSO information to the mp. */
16599 			lso_info_set(mp, mss, HW_LSO);
16600 			ixa->ixa_fragsize = IP_MAXPACKET;
16601 			ixa->ixa_extra_ident = num_lso_seg - 1;
16602 
16603 			DTRACE_PROBE2(tcp_send_lso, int, num_lso_seg,
16604 			    boolean_t, B_TRUE);
16605 
16606 			tcp_send_data(tcp, mp);
16607 
16608 			/*
16609 			 * Restore values of ixa_fragsize and ixa_extra_ident.
16610 			 */
16611 			ixa->ixa_fragsize = ixa->ixa_pmtu;
16612 			ixa->ixa_extra_ident = 0;
16613 			tcp->tcp_obsegs += num_lso_seg;
16614 			TCP_STAT(tcps, tcp_lso_times);
16615 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
16616 		} else {
16617 			/*
16618 			 * Make sure to clean up LSO information. Wherever a
16619 			 * new mp uses the prepended header room after dupb(),
16620 			 * lso_info_cleanup() should be called.
16621 			 */
16622 			lso_info_cleanup(mp);
16623 			tcp_send_data(tcp, mp);
16624 			BUMP_LOCAL(tcp->tcp_obsegs);
16625 		}
16626 	}
16627 
16628 	return (0);
16629 }
16630 
16631 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
16632 static void
16633 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
16634 {
16635 	uchar_t	fval = *mp->b_rptr;
16636 	mblk_t	*tail;
16637 	conn_t	*connp = tcp->tcp_connp;
16638 	queue_t	*q = connp->conn_wq;
16639 
16640 	/* TODO: How should flush interact with urgent data? */
16641 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
16642 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
16643 		/*
16644 		 * Flush only data that has not yet been put on the wire.  If
16645 		 * we flush data that we have already transmitted, life, as we
16646 		 * know it, may come to an end.
16647 		 */
16648 		tail = tcp->tcp_xmit_tail;
16649 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
16650 		tcp->tcp_xmit_tail_unsent = 0;
16651 		tcp->tcp_unsent = 0;
16652 		if (tail->b_wptr != tail->b_rptr)
16653 			tail = tail->b_cont;
16654 		if (tail) {
16655 			mblk_t **excess = &tcp->tcp_xmit_head;
16656 			for (;;) {
16657 				mblk_t *mp1 = *excess;
16658 				if (mp1 == tail)
16659 					break;
16660 				tcp->tcp_xmit_tail = mp1;
16661 				tcp->tcp_xmit_last = mp1;
16662 				excess = &mp1->b_cont;
16663 			}
16664 			*excess = NULL;
16665 			tcp_close_mpp(&tail);
16666 			if (tcp->tcp_snd_zcopy_aware)
16667 				tcp_zcopy_notify(tcp);
16668 		}
16669 		/*
16670 		 * We have no unsent data, so unsent must be less than
16671 		 * conn_sndlowat, so re-enable flow.
16672 		 */
16673 		mutex_enter(&tcp->tcp_non_sq_lock);
16674 		if (tcp->tcp_flow_stopped) {
16675 			tcp_clrqfull(tcp);
16676 		}
16677 		mutex_exit(&tcp->tcp_non_sq_lock);
16678 	}
16679 	/*
16680 	 * TODO: you can't just flush these, you have to increase rwnd for one
16681 	 * thing.  For another, how should urgent data interact?
16682 	 */
16683 	if (fval & FLUSHR) {
16684 		*mp->b_rptr = fval & ~FLUSHW;
16685 		/* XXX */
16686 		qreply(q, mp);
16687 		return;
16688 	}
16689 	freemsg(mp);
16690 }
16691 
16692 /*
16693  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
16694  * messages.
16695  */
16696 static void
16697 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
16698 {
16699 	mblk_t		*mp1;
16700 	struct iocblk	*iocp = (struct iocblk *)mp->b_rptr;
16701 	STRUCT_HANDLE(strbuf, sb);
16702 	uint_t		addrlen;
16703 	conn_t		*connp = tcp->tcp_connp;
16704 	queue_t 	*q = connp->conn_wq;
16705 
16706 	/* Make sure it is one of ours. */
16707 	switch (iocp->ioc_cmd) {
16708 	case TI_GETMYNAME:
16709 	case TI_GETPEERNAME:
16710 		break;
16711 	default:
16712 		/*
16713 		 * If the conn is closing, then error the ioctl here. Otherwise
16714 		 * use the CONN_IOCTLREF_* macros to hold off tcp_close until
16715 		 * we're done here. We also need to decrement the ioctlref which
16716 		 * was bumped in either tcp_ioctl or tcp_wput_ioctl.
16717 		 */
16718 		mutex_enter(&connp->conn_lock);
16719 		if (connp->conn_state_flags & CONN_CLOSING) {
16720 			mutex_exit(&connp->conn_lock);
16721 			iocp = (struct iocblk *)mp->b_rptr;
16722 			iocp->ioc_error = EINVAL;
16723 			mp->b_datap->db_type = M_IOCNAK;
16724 			iocp->ioc_count = 0;
16725 			qreply(q, mp);
16726 			return;
16727 		}
16728 
16729 		CONN_INC_IOCTLREF_LOCKED(connp);
16730 		ip_wput_nondata(q, mp);
16731 		CONN_DEC_IOCTLREF(connp);
16732 		return;
16733 	}
16734 	switch (mi_copy_state(q, mp, &mp1)) {
16735 	case -1:
16736 		return;
16737 	case MI_COPY_CASE(MI_COPY_IN, 1):
16738 		break;
16739 	case MI_COPY_CASE(MI_COPY_OUT, 1):
16740 		/* Copy out the strbuf. */
16741 		mi_copyout(q, mp);
16742 		return;
16743 	case MI_COPY_CASE(MI_COPY_OUT, 2):
16744 		/* All done. */
16745 		mi_copy_done(q, mp, 0);
16746 		return;
16747 	default:
16748 		mi_copy_done(q, mp, EPROTO);
16749 		return;
16750 	}
16751 	/* Check alignment of the strbuf */
16752 	if (!OK_32PTR(mp1->b_rptr)) {
16753 		mi_copy_done(q, mp, EINVAL);
16754 		return;
16755 	}
16756 
16757 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
16758 
16759 	if (connp->conn_family == AF_INET)
16760 		addrlen = sizeof (sin_t);
16761 	else
16762 		addrlen = sizeof (sin6_t);
16763 
16764 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
16765 		mi_copy_done(q, mp, EINVAL);
16766 		return;
16767 	}
16768 
16769 	switch (iocp->ioc_cmd) {
16770 	case TI_GETMYNAME:
16771 		break;
16772 	case TI_GETPEERNAME:
16773 		if (tcp->tcp_state < TCPS_SYN_RCVD) {
16774 			mi_copy_done(q, mp, ENOTCONN);
16775 			return;
16776 		}
16777 		break;
16778 	}
16779 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
16780 	if (!mp1)
16781 		return;
16782 
16783 	STRUCT_FSET(sb, len, addrlen);
16784 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
16785 	case TI_GETMYNAME:
16786 		(void) conn_getsockname(connp, (struct sockaddr *)mp1->b_wptr,
16787 		    &addrlen);
16788 		break;
16789 	case TI_GETPEERNAME:
16790 		(void) conn_getpeername(connp, (struct sockaddr *)mp1->b_wptr,
16791 		    &addrlen);
16792 		break;
16793 	}
16794 	mp1->b_wptr += addrlen;
16795 	/* Copy out the address */
16796 	mi_copyout(q, mp);
16797 }
16798 
16799 static void
16800 tcp_use_pure_tpi(tcp_t *tcp)
16801 {
16802 	conn_t		*connp = tcp->tcp_connp;
16803 
16804 #ifdef	_ILP32
16805 	tcp->tcp_acceptor_id = (t_uscalar_t)connp->conn_rq;
16806 #else
16807 	tcp->tcp_acceptor_id = connp->conn_dev;
16808 #endif
16809 	/*
16810 	 * Insert this socket into the acceptor hash.
16811 	 * We might need it for T_CONN_RES message
16812 	 */
16813 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
16814 
16815 	tcp->tcp_issocket = B_FALSE;
16816 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
16817 }
16818 
16819 /*
16820  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
16821  * messages.
16822  */
16823 /* ARGSUSED */
16824 static void
16825 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
16826 {
16827 	conn_t 		*connp = (conn_t *)arg;
16828 	tcp_t		*tcp = connp->conn_tcp;
16829 	queue_t		*q = connp->conn_wq;
16830 	struct iocblk	*iocp;
16831 
16832 	ASSERT(DB_TYPE(mp) == M_IOCTL);
16833 	/*
16834 	 * Try and ASSERT the minimum possible references on the
16835 	 * conn early enough. Since we are executing on write side,
16836 	 * the connection is obviously not detached and that means
16837 	 * there is a ref each for TCP and IP. Since we are behind
16838 	 * the squeue, the minimum references needed are 3. If the
16839 	 * conn is in classifier hash list, there should be an
16840 	 * extra ref for that (we check both the possibilities).
16841 	 */
16842 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16843 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16844 
16845 	iocp = (struct iocblk *)mp->b_rptr;
16846 	switch (iocp->ioc_cmd) {
16847 	case _SIOCSOCKFALLBACK:
16848 		/*
16849 		 * Either sockmod is about to be popped and the socket
16850 		 * would now be treated as a plain stream, or a module
16851 		 * is about to be pushed so we could no longer use read-
16852 		 * side synchronous streams for fused loopback tcp.
16853 		 * Drain any queued data and disable direct sockfs
16854 		 * interface from now on.
16855 		 */
16856 		if (!tcp->tcp_issocket) {
16857 			DB_TYPE(mp) = M_IOCNAK;
16858 			iocp->ioc_error = EINVAL;
16859 		} else {
16860 			tcp_use_pure_tpi(tcp);
16861 			DB_TYPE(mp) = M_IOCACK;
16862 			iocp->ioc_error = 0;
16863 		}
16864 		iocp->ioc_count = 0;
16865 		iocp->ioc_rval = 0;
16866 		qreply(q, mp);
16867 		return;
16868 	}
16869 
16870 	/*
16871 	 * If the conn is closing, then error the ioctl here. Otherwise bump the
16872 	 * conn_ioctlref to hold off tcp_close until we're done here.
16873 	 */
16874 	mutex_enter(&(connp)->conn_lock);
16875 	if ((connp)->conn_state_flags & CONN_CLOSING) {
16876 		mutex_exit(&(connp)->conn_lock);
16877 		iocp->ioc_error = EINVAL;
16878 		mp->b_datap->db_type = M_IOCNAK;
16879 		iocp->ioc_count = 0;
16880 		qreply(q, mp);
16881 		return;
16882 	}
16883 
16884 	CONN_INC_IOCTLREF_LOCKED(connp);
16885 	ip_wput_nondata(q, mp);
16886 	CONN_DEC_IOCTLREF(connp);
16887 }
16888 
16889 /*
16890  * This routine is called by tcp_wput() to handle all TPI requests.
16891  */
16892 /* ARGSUSED */
16893 static void
16894 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
16895 {
16896 	conn_t		*connp = (conn_t *)arg;
16897 	tcp_t		*tcp = connp->conn_tcp;
16898 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
16899 	uchar_t		*rptr;
16900 	t_scalar_t	type;
16901 	cred_t		*cr;
16902 
16903 	/*
16904 	 * Try and ASSERT the minimum possible references on the
16905 	 * conn early enough. Since we are executing on write side,
16906 	 * the connection is obviously not detached and that means
16907 	 * there is a ref each for TCP and IP. Since we are behind
16908 	 * the squeue, the minimum references needed are 3. If the
16909 	 * conn is in classifier hash list, there should be an
16910 	 * extra ref for that (we check both the possibilities).
16911 	 */
16912 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16913 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16914 
16915 	rptr = mp->b_rptr;
16916 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
16917 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
16918 		type = ((union T_primitives *)rptr)->type;
16919 		if (type == T_EXDATA_REQ) {
16920 			tcp_output_urgent(connp, mp, arg2, NULL);
16921 		} else if (type != T_DATA_REQ) {
16922 			goto non_urgent_data;
16923 		} else {
16924 			/* TODO: options, flags, ... from user */
16925 			/* Set length to zero for reclamation below */
16926 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
16927 			freeb(mp);
16928 		}
16929 		return;
16930 	} else {
16931 		if (connp->conn_debug) {
16932 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
16933 			    "tcp_wput_proto, dropping one...");
16934 		}
16935 		freemsg(mp);
16936 		return;
16937 	}
16938 
16939 non_urgent_data:
16940 
16941 	switch ((int)tprim->type) {
16942 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
16943 		/*
16944 		 * save the kssl_ent_t from the next block, and convert this
16945 		 * back to a normal bind_req.
16946 		 */
16947 		if (mp->b_cont != NULL) {
16948 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
16949 
16950 			if (tcp->tcp_kssl_ent != NULL) {
16951 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
16952 				    KSSL_NO_PROXY);
16953 				tcp->tcp_kssl_ent = NULL;
16954 			}
16955 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
16956 			    sizeof (kssl_ent_t));
16957 			kssl_hold_ent(tcp->tcp_kssl_ent);
16958 			freemsg(mp->b_cont);
16959 			mp->b_cont = NULL;
16960 		}
16961 		tprim->type = T_BIND_REQ;
16962 
16963 	/* FALLTHROUGH */
16964 	case O_T_BIND_REQ:	/* bind request */
16965 	case T_BIND_REQ:	/* new semantics bind request */
16966 		tcp_tpi_bind(tcp, mp);
16967 		break;
16968 	case T_UNBIND_REQ:	/* unbind request */
16969 		tcp_tpi_unbind(tcp, mp);
16970 		break;
16971 	case O_T_CONN_RES:	/* old connection response XXX */
16972 	case T_CONN_RES:	/* connection response */
16973 		tcp_tli_accept(tcp, mp);
16974 		break;
16975 	case T_CONN_REQ:	/* connection request */
16976 		tcp_tpi_connect(tcp, mp);
16977 		break;
16978 	case T_DISCON_REQ:	/* disconnect request */
16979 		tcp_disconnect(tcp, mp);
16980 		break;
16981 	case T_CAPABILITY_REQ:
16982 		tcp_capability_req(tcp, mp);	/* capability request */
16983 		break;
16984 	case T_INFO_REQ:	/* information request */
16985 		tcp_info_req(tcp, mp);
16986 		break;
16987 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
16988 	case T_OPTMGMT_REQ:
16989 		/*
16990 		 * Note:  no support for snmpcom_req() through new
16991 		 * T_OPTMGMT_REQ. See comments in ip.c
16992 		 */
16993 
16994 		/*
16995 		 * All Solaris components should pass a db_credp
16996 		 * for this TPI message, hence we ASSERT.
16997 		 * But in case there is some other M_PROTO that looks
16998 		 * like a TPI message sent by some other kernel
16999 		 * component, we check and return an error.
17000 		 */
17001 		cr = msg_getcred(mp, NULL);
17002 		ASSERT(cr != NULL);
17003 		if (cr == NULL) {
17004 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
17005 			return;
17006 		}
17007 		/*
17008 		 * If EINPROGRESS is returned, the request has been queued
17009 		 * for subsequent processing by ip_restart_optmgmt(), which
17010 		 * will do the CONN_DEC_REF().
17011 		 */
17012 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
17013 			svr4_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
17014 		} else {
17015 			tpi_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
17016 		}
17017 		break;
17018 
17019 	case T_UNITDATA_REQ:	/* unitdata request */
17020 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
17021 		break;
17022 	case T_ORDREL_REQ:	/* orderly release req */
17023 		freemsg(mp);
17024 
17025 		if (tcp->tcp_fused)
17026 			tcp_unfuse(tcp);
17027 
17028 		if (tcp_xmit_end(tcp) != 0) {
17029 			/*
17030 			 * We were crossing FINs and got a reset from
17031 			 * the other side. Just ignore it.
17032 			 */
17033 			if (connp->conn_debug) {
17034 				(void) strlog(TCP_MOD_ID, 0, 1,
17035 				    SL_ERROR|SL_TRACE,
17036 				    "tcp_wput_proto, T_ORDREL_REQ out of "
17037 				    "state %s",
17038 				    tcp_display(tcp, NULL,
17039 				    DISP_ADDR_AND_PORT));
17040 			}
17041 		}
17042 		break;
17043 	case T_ADDR_REQ:
17044 		tcp_addr_req(tcp, mp);
17045 		break;
17046 	default:
17047 		if (connp->conn_debug) {
17048 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
17049 			    "tcp_wput_proto, bogus TPI msg, type %d",
17050 			    tprim->type);
17051 		}
17052 		/*
17053 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
17054 		 * to recover.
17055 		 */
17056 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
17057 		break;
17058 	}
17059 }
17060 
17061 /*
17062  * The TCP write service routine should never be called...
17063  */
17064 /* ARGSUSED */
17065 static void
17066 tcp_wsrv(queue_t *q)
17067 {
17068 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
17069 
17070 	TCP_STAT(tcps, tcp_wsrv_called);
17071 }
17072 
17073 /*
17074  * Send out a control packet on the tcp connection specified.  This routine
17075  * is typically called where we need a simple ACK or RST generated.
17076  */
17077 static void
17078 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
17079 {
17080 	uchar_t		*rptr;
17081 	tcpha_t		*tcpha;
17082 	ipha_t		*ipha = NULL;
17083 	ip6_t		*ip6h = NULL;
17084 	uint32_t	sum;
17085 	int		total_hdr_len;
17086 	int		ip_hdr_len;
17087 	mblk_t		*mp;
17088 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17089 	conn_t		*connp = tcp->tcp_connp;
17090 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
17091 
17092 	/*
17093 	 * Save sum for use in source route later.
17094 	 */
17095 	sum = connp->conn_ht_ulp_len + connp->conn_sum;
17096 	total_hdr_len = connp->conn_ht_iphc_len;
17097 	ip_hdr_len = ixa->ixa_ip_hdr_length;
17098 
17099 	/* If a text string is passed in with the request, pass it to strlog. */
17100 	if (str != NULL && connp->conn_debug) {
17101 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
17102 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
17103 		    str, seq, ack, ctl);
17104 	}
17105 	mp = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
17106 	    BPRI_MED);
17107 	if (mp == NULL) {
17108 		return;
17109 	}
17110 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
17111 	mp->b_rptr = rptr;
17112 	mp->b_wptr = &rptr[total_hdr_len];
17113 	bcopy(connp->conn_ht_iphc, rptr, total_hdr_len);
17114 
17115 	ixa->ixa_pktlen = total_hdr_len;
17116 
17117 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
17118 		ipha = (ipha_t *)rptr;
17119 		ipha->ipha_length = htons(total_hdr_len);
17120 	} else {
17121 		ip6h = (ip6_t *)rptr;
17122 		ip6h->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
17123 	}
17124 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
17125 	tcpha->tha_flags = (uint8_t)ctl;
17126 	if (ctl & TH_RST) {
17127 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
17128 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17129 		/*
17130 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
17131 		 */
17132 		if (tcp->tcp_snd_ts_ok &&
17133 		    tcp->tcp_state > TCPS_SYN_SENT) {
17134 			mp->b_wptr = &rptr[total_hdr_len - TCPOPT_REAL_TS_LEN];
17135 			*(mp->b_wptr) = TCPOPT_EOL;
17136 
17137 			ixa->ixa_pktlen = total_hdr_len - TCPOPT_REAL_TS_LEN;
17138 
17139 			if (connp->conn_ipversion == IPV4_VERSION) {
17140 				ipha->ipha_length = htons(total_hdr_len -
17141 				    TCPOPT_REAL_TS_LEN);
17142 			} else {
17143 				ip6h->ip6_plen = htons(total_hdr_len -
17144 				    IPV6_HDR_LEN - TCPOPT_REAL_TS_LEN);
17145 			}
17146 			tcpha->tha_offset_and_reserved -= (3 << 4);
17147 			sum -= TCPOPT_REAL_TS_LEN;
17148 		}
17149 	}
17150 	if (ctl & TH_ACK) {
17151 		if (tcp->tcp_snd_ts_ok) {
17152 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
17153 
17154 			U32_TO_BE32(llbolt,
17155 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
17156 			U32_TO_BE32(tcp->tcp_ts_recent,
17157 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
17158 		}
17159 
17160 		/* Update the latest receive window size in TCP header. */
17161 		tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
17162 		/* Track what we sent to the peer */
17163 		tcp->tcp_tcpha->tha_win = tcpha->tha_win;
17164 		tcp->tcp_rack = ack;
17165 		tcp->tcp_rack_cnt = 0;
17166 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
17167 	}
17168 	BUMP_LOCAL(tcp->tcp_obsegs);
17169 	tcpha->tha_seq = htonl(seq);
17170 	tcpha->tha_ack = htonl(ack);
17171 	/*
17172 	 * Include the adjustment for a source route if any.
17173 	 */
17174 	sum = (sum >> 16) + (sum & 0xFFFF);
17175 	tcpha->tha_sum = htons(sum);
17176 	tcp_send_data(tcp, mp);
17177 }
17178 
17179 /*
17180  * If this routine returns B_TRUE, TCP can generate a RST in response
17181  * to a segment.  If it returns B_FALSE, TCP should not respond.
17182  */
17183 static boolean_t
17184 tcp_send_rst_chk(tcp_stack_t *tcps)
17185 {
17186 	int64_t	now;
17187 
17188 	/*
17189 	 * TCP needs to protect itself from generating too many RSTs.
17190 	 * This can be a DoS attack by sending us random segments
17191 	 * soliciting RSTs.
17192 	 *
17193 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
17194 	 * in each 1 second interval.  In this way, TCP still generate
17195 	 * RSTs in normal cases but when under attack, the impact is
17196 	 * limited.
17197 	 */
17198 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
17199 		now = ddi_get_lbolt64();
17200 		if (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
17201 		    1*SECONDS) {
17202 			tcps->tcps_last_rst_intrvl = now;
17203 			tcps->tcps_rst_cnt = 1;
17204 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
17205 			return (B_FALSE);
17206 		}
17207 	}
17208 	return (B_TRUE);
17209 }
17210 
17211 /*
17212  * Generate a reset based on an inbound packet, connp is set by caller
17213  * when RST is in response to an unexpected inbound packet for which
17214  * there is active tcp state in the system.
17215  *
17216  * IPSEC NOTE : Try to send the reply with the same protection as it came
17217  * in.  We have the ip_recv_attr_t which is reversed to form the ip_xmit_attr_t.
17218  * That way the packet will go out at the same level of protection as it
17219  * came in with.
17220  */
17221 static void
17222 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq, uint32_t ack, int ctl,
17223     ip_recv_attr_t *ira, ip_stack_t *ipst, conn_t *connp)
17224 {
17225 	ipha_t		*ipha = NULL;
17226 	ip6_t		*ip6h = NULL;
17227 	ushort_t	len;
17228 	tcpha_t		*tcpha;
17229 	int		i;
17230 	ipaddr_t	v4addr;
17231 	in6_addr_t	v6addr;
17232 	netstack_t	*ns = ipst->ips_netstack;
17233 	tcp_stack_t	*tcps = ns->netstack_tcp;
17234 	ip_xmit_attr_t	ixas, *ixa;
17235 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
17236 	boolean_t	need_refrele = B_FALSE;		/* ixa_refrele(ixa) */
17237 	ushort_t	port;
17238 
17239 	if (!tcp_send_rst_chk(tcps)) {
17240 		TCP_STAT(tcps, tcp_rst_unsent);
17241 		freemsg(mp);
17242 		return;
17243 	}
17244 
17245 	/*
17246 	 * If connp != NULL we use conn_ixa to keep IP_NEXTHOP and other
17247 	 * options from the listener. In that case the caller must ensure that
17248 	 * we are running on the listener = connp squeue.
17249 	 *
17250 	 * We get a safe copy of conn_ixa so we don't need to restore anything
17251 	 * we or ip_output_simple might change in the ixa.
17252 	 */
17253 	if (connp != NULL) {
17254 		ASSERT(connp->conn_on_sqp);
17255 
17256 		ixa = conn_get_ixa_exclusive(connp);
17257 		if (ixa == NULL) {
17258 			TCP_STAT(tcps, tcp_rst_unsent);
17259 			freemsg(mp);
17260 			return;
17261 		}
17262 		need_refrele = B_TRUE;
17263 	} else {
17264 		bzero(&ixas, sizeof (ixas));
17265 		ixa = &ixas;
17266 		/*
17267 		 * IXAF_VERIFY_SOURCE is overkill since we know the
17268 		 * packet was for us.
17269 		 */
17270 		ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE;
17271 		ixa->ixa_protocol = IPPROTO_TCP;
17272 		ixa->ixa_zoneid = ira->ira_zoneid;
17273 		ixa->ixa_ifindex = 0;
17274 		ixa->ixa_ipst = ipst;
17275 		ixa->ixa_cred = kcred;
17276 		ixa->ixa_cpid = NOPID;
17277 	}
17278 
17279 	if (str && tcps->tcps_dbg) {
17280 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
17281 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
17282 		    "flags 0x%x",
17283 		    str, seq, ack, ctl);
17284 	}
17285 	if (mp->b_datap->db_ref != 1) {
17286 		mblk_t *mp1 = copyb(mp);
17287 		freemsg(mp);
17288 		mp = mp1;
17289 		if (mp == NULL)
17290 			goto done;
17291 	} else if (mp->b_cont) {
17292 		freemsg(mp->b_cont);
17293 		mp->b_cont = NULL;
17294 		DB_CKSUMFLAGS(mp) = 0;
17295 	}
17296 	/*
17297 	 * We skip reversing source route here.
17298 	 * (for now we replace all IP options with EOL)
17299 	 */
17300 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17301 		ipha = (ipha_t *)mp->b_rptr;
17302 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
17303 			mp->b_rptr[i] = IPOPT_EOL;
17304 		/*
17305 		 * Make sure that src address isn't flagrantly invalid.
17306 		 * Not all broadcast address checking for the src address
17307 		 * is possible, since we don't know the netmask of the src
17308 		 * addr.  No check for destination address is done, since
17309 		 * IP will not pass up a packet with a broadcast dest
17310 		 * address to TCP.  Similar checks are done below for IPv6.
17311 		 */
17312 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
17313 		    CLASSD(ipha->ipha_src)) {
17314 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
17315 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
17316 			freemsg(mp);
17317 			goto done;
17318 		}
17319 	} else {
17320 		ip6h = (ip6_t *)mp->b_rptr;
17321 
17322 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
17323 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
17324 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
17325 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
17326 			freemsg(mp);
17327 			goto done;
17328 		}
17329 
17330 		/* Remove any extension headers assuming partial overlay */
17331 		if (ip_hdr_len > IPV6_HDR_LEN) {
17332 			uint8_t *to;
17333 
17334 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
17335 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
17336 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
17337 			ip_hdr_len = IPV6_HDR_LEN;
17338 			ip6h = (ip6_t *)mp->b_rptr;
17339 			ip6h->ip6_nxt = IPPROTO_TCP;
17340 		}
17341 	}
17342 	tcpha = (tcpha_t *)&mp->b_rptr[ip_hdr_len];
17343 	if (tcpha->tha_flags & TH_RST) {
17344 		freemsg(mp);
17345 		goto done;
17346 	}
17347 	tcpha->tha_offset_and_reserved = (5 << 4);
17348 	len = ip_hdr_len + sizeof (tcpha_t);
17349 	mp->b_wptr = &mp->b_rptr[len];
17350 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17351 		ipha->ipha_length = htons(len);
17352 		/* Swap addresses */
17353 		v4addr = ipha->ipha_src;
17354 		ipha->ipha_src = ipha->ipha_dst;
17355 		ipha->ipha_dst = v4addr;
17356 		ipha->ipha_ident = 0;
17357 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
17358 		ixa->ixa_flags |= IXAF_IS_IPV4;
17359 		ixa->ixa_ip_hdr_length = ip_hdr_len;
17360 	} else {
17361 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
17362 		/* Swap addresses */
17363 		v6addr = ip6h->ip6_src;
17364 		ip6h->ip6_src = ip6h->ip6_dst;
17365 		ip6h->ip6_dst = v6addr;
17366 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
17367 		ixa->ixa_flags &= ~IXAF_IS_IPV4;
17368 
17369 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_dst)) {
17370 			ixa->ixa_flags |= IXAF_SCOPEID_SET;
17371 			ixa->ixa_scopeid = ira->ira_ruifindex;
17372 		}
17373 		ixa->ixa_ip_hdr_length = IPV6_HDR_LEN;
17374 	}
17375 	ixa->ixa_pktlen = len;
17376 
17377 	/* Swap the ports */
17378 	port = tcpha->tha_fport;
17379 	tcpha->tha_fport = tcpha->tha_lport;
17380 	tcpha->tha_lport = port;
17381 
17382 	tcpha->tha_ack = htonl(ack);
17383 	tcpha->tha_seq = htonl(seq);
17384 	tcpha->tha_win = 0;
17385 	tcpha->tha_sum = htons(sizeof (tcpha_t));
17386 	tcpha->tha_flags = (uint8_t)ctl;
17387 	if (ctl & TH_RST) {
17388 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
17389 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17390 	}
17391 
17392 	/* Discard any old label */
17393 	if (ixa->ixa_free_flags & IXA_FREE_TSL) {
17394 		ASSERT(ixa->ixa_tsl != NULL);
17395 		label_rele(ixa->ixa_tsl);
17396 		ixa->ixa_free_flags &= ~IXA_FREE_TSL;
17397 	}
17398 	ixa->ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
17399 
17400 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
17401 		/*
17402 		 * Apply IPsec based on how IPsec was applied to
17403 		 * the packet that caused the RST.
17404 		 */
17405 		if (!ipsec_in_to_out(ira, ixa, mp, ipha, ip6h)) {
17406 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
17407 			/* Note: mp already consumed and ip_drop_packet done */
17408 			goto done;
17409 		}
17410 	} else {
17411 		/*
17412 		 * This is in clear. The RST message we are building
17413 		 * here should go out in clear, independent of our policy.
17414 		 */
17415 		ixa->ixa_flags |= IXAF_NO_IPSEC;
17416 	}
17417 
17418 	/*
17419 	 * NOTE:  one might consider tracing a TCP packet here, but
17420 	 * this function has no active TCP state and no tcp structure
17421 	 * that has a trace buffer.  If we traced here, we would have
17422 	 * to keep a local trace buffer in tcp_record_trace().
17423 	 */
17424 
17425 	(void) ip_output_simple(mp, ixa);
17426 done:
17427 	ixa_cleanup(ixa);
17428 	if (need_refrele) {
17429 		ASSERT(ixa != &ixas);
17430 		ixa_refrele(ixa);
17431 	}
17432 }
17433 
17434 /*
17435  * Initiate closedown sequence on an active connection.  (May be called as
17436  * writer.)  Return value zero for OK return, non-zero for error return.
17437  */
17438 static int
17439 tcp_xmit_end(tcp_t *tcp)
17440 {
17441 	mblk_t		*mp;
17442 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17443 	iulp_t		uinfo;
17444 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17445 	conn_t		*connp = tcp->tcp_connp;
17446 
17447 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
17448 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
17449 		/*
17450 		 * Invalid state, only states TCPS_SYN_RCVD,
17451 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
17452 		 */
17453 		return (-1);
17454 	}
17455 
17456 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
17457 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
17458 	/*
17459 	 * If there is nothing more unsent, send the FIN now.
17460 	 * Otherwise, it will go out with the last segment.
17461 	 */
17462 	if (tcp->tcp_unsent == 0) {
17463 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
17464 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
17465 
17466 		if (mp) {
17467 			tcp_send_data(tcp, mp);
17468 		} else {
17469 			/*
17470 			 * Couldn't allocate msg.  Pretend we got it out.
17471 			 * Wait for rexmit timeout.
17472 			 */
17473 			tcp->tcp_snxt = tcp->tcp_fss + 1;
17474 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17475 		}
17476 
17477 		/*
17478 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
17479 		 * changed.
17480 		 */
17481 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
17482 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
17483 		}
17484 	} else {
17485 		/*
17486 		 * If tcp->tcp_cork is set, then the data will not get sent,
17487 		 * so we have to check that and unset it first.
17488 		 */
17489 		if (tcp->tcp_cork)
17490 			tcp->tcp_cork = B_FALSE;
17491 		tcp_wput_data(tcp, NULL, B_FALSE);
17492 	}
17493 
17494 	/*
17495 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
17496 	 * is 0, don't update the cache.
17497 	 */
17498 	if (tcps->tcps_rtt_updates == 0 ||
17499 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
17500 		return (0);
17501 
17502 	/*
17503 	 * We do not have a good algorithm to update ssthresh at this time.
17504 	 * So don't do any update.
17505 	 */
17506 	bzero(&uinfo, sizeof (uinfo));
17507 	uinfo.iulp_rtt = tcp->tcp_rtt_sa;
17508 	uinfo.iulp_rtt_sd = tcp->tcp_rtt_sd;
17509 
17510 	/*
17511 	 * Note that uinfo is kept for conn_faddr in the DCE. Could update even
17512 	 * if source routed but we don't.
17513 	 */
17514 	if (connp->conn_ipversion == IPV4_VERSION) {
17515 		if (connp->conn_faddr_v4 !=  tcp->tcp_ipha->ipha_dst) {
17516 			return (0);
17517 		}
17518 		(void) dce_update_uinfo_v4(connp->conn_faddr_v4, &uinfo, ipst);
17519 	} else {
17520 		uint_t ifindex;
17521 
17522 		if (!(IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6,
17523 		    &tcp->tcp_ip6h->ip6_dst))) {
17524 			return (0);
17525 		}
17526 		ifindex = 0;
17527 		if (IN6_IS_ADDR_LINKSCOPE(&connp->conn_faddr_v6)) {
17528 			ip_xmit_attr_t *ixa = connp->conn_ixa;
17529 
17530 			/*
17531 			 * If we are going to create a DCE we'd better have
17532 			 * an ifindex
17533 			 */
17534 			if (ixa->ixa_nce != NULL) {
17535 				ifindex = ixa->ixa_nce->nce_common->ncec_ill->
17536 				    ill_phyint->phyint_ifindex;
17537 			} else {
17538 				return (0);
17539 			}
17540 		}
17541 
17542 		(void) dce_update_uinfo(&connp->conn_faddr_v6, ifindex, &uinfo,
17543 		    ipst);
17544 	}
17545 	return (0);
17546 }
17547 
17548 /*
17549  * Generate a "no listener here" RST in response to an "unknown" segment.
17550  * connp is set by caller when RST is in response to an unexpected
17551  * inbound packet for which there is active tcp state in the system.
17552  * Note that we are reusing the incoming mp to construct the outgoing RST.
17553  */
17554 void
17555 tcp_xmit_listeners_reset(mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst,
17556     conn_t *connp)
17557 {
17558 	uchar_t		*rptr;
17559 	uint32_t	seg_len;
17560 	tcpha_t		*tcpha;
17561 	uint32_t	seg_seq;
17562 	uint32_t	seg_ack;
17563 	uint_t		flags;
17564 	ipha_t 		*ipha;
17565 	ip6_t 		*ip6h;
17566 	boolean_t	policy_present;
17567 	netstack_t	*ns = ipst->ips_netstack;
17568 	tcp_stack_t	*tcps = ns->netstack_tcp;
17569 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
17570 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
17571 
17572 	TCP_STAT(tcps, tcp_no_listener);
17573 
17574 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17575 		policy_present = ipss->ipsec_inbound_v4_policy_present;
17576 		ipha = (ipha_t *)mp->b_rptr;
17577 		ip6h = NULL;
17578 	} else {
17579 		policy_present = ipss->ipsec_inbound_v6_policy_present;
17580 		ipha = NULL;
17581 		ip6h = (ip6_t *)mp->b_rptr;
17582 	}
17583 
17584 	if (policy_present) {
17585 		/*
17586 		 * The conn_t parameter is NULL because we already know
17587 		 * nobody's home.
17588 		 */
17589 		mp = ipsec_check_global_policy(mp, (conn_t *)NULL, ipha, ip6h,
17590 		    ira, ns);
17591 		if (mp == NULL)
17592 			return;
17593 	}
17594 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
17595 		DTRACE_PROBE2(
17596 		    tx__ip__log__error__nolistener__tcp,
17597 		    char *, "Could not reply with RST to mp(1)",
17598 		    mblk_t *, mp);
17599 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
17600 		freemsg(mp);
17601 		return;
17602 	}
17603 
17604 	rptr = mp->b_rptr;
17605 
17606 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
17607 	seg_seq = ntohl(tcpha->tha_seq);
17608 	seg_ack = ntohl(tcpha->tha_ack);
17609 	flags = tcpha->tha_flags;
17610 
17611 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcpha) + ip_hdr_len);
17612 	if (flags & TH_RST) {
17613 		freemsg(mp);
17614 	} else if (flags & TH_ACK) {
17615 		tcp_xmit_early_reset("no tcp, reset", mp, seg_ack, 0, TH_RST,
17616 		    ira, ipst, connp);
17617 	} else {
17618 		if (flags & TH_SYN) {
17619 			seg_len++;
17620 		} else {
17621 			/*
17622 			 * Here we violate the RFC.  Note that a normal
17623 			 * TCP will never send a segment without the ACK
17624 			 * flag, except for RST or SYN segment.  This
17625 			 * segment is neither.  Just drop it on the
17626 			 * floor.
17627 			 */
17628 			freemsg(mp);
17629 			TCP_STAT(tcps, tcp_rst_unsent);
17630 			return;
17631 		}
17632 
17633 		tcp_xmit_early_reset("no tcp, reset/ack", mp, 0,
17634 		    seg_seq + seg_len, TH_RST | TH_ACK, ira, ipst, connp);
17635 	}
17636 }
17637 
17638 /*
17639  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
17640  * ip and tcp header ready to pass down to IP.  If the mp passed in is
17641  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
17642  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
17643  * otherwise it will dup partial mblks.)
17644  * Otherwise, an appropriate ACK packet will be generated.  This
17645  * routine is not usually called to send new data for the first time.  It
17646  * is mostly called out of the timer for retransmits, and to generate ACKs.
17647  *
17648  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
17649  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
17650  * of the original mblk chain will be returned in *offset and *end_mp.
17651  */
17652 mblk_t *
17653 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
17654     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
17655     boolean_t rexmit)
17656 {
17657 	int	data_length;
17658 	int32_t	off = 0;
17659 	uint_t	flags;
17660 	mblk_t	*mp1;
17661 	mblk_t	*mp2;
17662 	uchar_t	*rptr;
17663 	tcpha_t	*tcpha;
17664 	int32_t	num_sack_blk = 0;
17665 	int32_t	sack_opt_len = 0;
17666 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17667 	conn_t		*connp = tcp->tcp_connp;
17668 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
17669 
17670 	/* Allocate for our maximum TCP header + link-level */
17671 	mp1 = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
17672 	    BPRI_MED);
17673 	if (!mp1)
17674 		return (NULL);
17675 	data_length = 0;
17676 
17677 	/*
17678 	 * Note that tcp_mss has been adjusted to take into account the
17679 	 * timestamp option if applicable.  Because SACK options do not
17680 	 * appear in every TCP segments and they are of variable lengths,
17681 	 * they cannot be included in tcp_mss.  Thus we need to calculate
17682 	 * the actual segment length when we need to send a segment which
17683 	 * includes SACK options.
17684 	 */
17685 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
17686 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
17687 		    tcp->tcp_num_sack_blk);
17688 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
17689 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
17690 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
17691 			max_to_send -= sack_opt_len;
17692 	}
17693 
17694 	if (offset != NULL) {
17695 		off = *offset;
17696 		/* We use offset as an indicator that end_mp is not NULL. */
17697 		*end_mp = NULL;
17698 	}
17699 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
17700 		/* This could be faster with cooperation from downstream */
17701 		if (mp2 != mp1 && !sendall &&
17702 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
17703 		    max_to_send)
17704 			/*
17705 			 * Don't send the next mblk since the whole mblk
17706 			 * does not fit.
17707 			 */
17708 			break;
17709 		mp2->b_cont = dupb(mp);
17710 		mp2 = mp2->b_cont;
17711 		if (!mp2) {
17712 			freemsg(mp1);
17713 			return (NULL);
17714 		}
17715 		mp2->b_rptr += off;
17716 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
17717 		    (uintptr_t)INT_MAX);
17718 
17719 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
17720 		if (data_length > max_to_send) {
17721 			mp2->b_wptr -= data_length - max_to_send;
17722 			data_length = max_to_send;
17723 			off = mp2->b_wptr - mp->b_rptr;
17724 			break;
17725 		} else {
17726 			off = 0;
17727 		}
17728 	}
17729 	if (offset != NULL) {
17730 		*offset = off;
17731 		*end_mp = mp;
17732 	}
17733 	if (seg_len != NULL) {
17734 		*seg_len = data_length;
17735 	}
17736 
17737 	/* Update the latest receive window size in TCP header. */
17738 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
17739 
17740 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
17741 	mp1->b_rptr = rptr;
17742 	mp1->b_wptr = rptr + connp->conn_ht_iphc_len + sack_opt_len;
17743 	bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
17744 	tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
17745 	tcpha->tha_seq = htonl(seq);
17746 
17747 	/*
17748 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
17749 	 * that this function was called from tcp_wput_data. Thus, when called
17750 	 * to retransmit data the setting of the PUSH bit may appear some
17751 	 * what random in that it might get set when it should not. This
17752 	 * should not pose any performance issues.
17753 	 */
17754 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
17755 	    tcp->tcp_unsent == data_length)) {
17756 		flags = TH_ACK | TH_PUSH;
17757 	} else {
17758 		flags = TH_ACK;
17759 	}
17760 
17761 	if (tcp->tcp_ecn_ok) {
17762 		if (tcp->tcp_ecn_echo_on)
17763 			flags |= TH_ECE;
17764 
17765 		/*
17766 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
17767 		 * There is no TCP flow control for non-data segments, and
17768 		 * only data segment is transmitted reliably.
17769 		 */
17770 		if (data_length > 0 && !rexmit) {
17771 			SET_ECT(tcp, rptr);
17772 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17773 				flags |= TH_CWR;
17774 				tcp->tcp_ecn_cwr_sent = B_TRUE;
17775 			}
17776 		}
17777 	}
17778 
17779 	if (tcp->tcp_valid_bits) {
17780 		uint32_t u1;
17781 
17782 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
17783 		    seq == tcp->tcp_iss) {
17784 			uchar_t	*wptr;
17785 
17786 			/*
17787 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
17788 			 * TCP can only be in SYN-SENT, SYN-RCVD or
17789 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
17790 			 * our SYN is not ack'ed but the app closes this
17791 			 * TCP connection.
17792 			 */
17793 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
17794 			    tcp->tcp_state == TCPS_SYN_RCVD ||
17795 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
17796 
17797 			/*
17798 			 * Tack on the MSS option.  It is always needed
17799 			 * for both active and passive open.
17800 			 *
17801 			 * MSS option value should be interface MTU - MIN
17802 			 * TCP/IP header according to RFC 793 as it means
17803 			 * the maximum segment size TCP can receive.  But
17804 			 * to get around some broken middle boxes/end hosts
17805 			 * out there, we allow the option value to be the
17806 			 * same as the MSS option size on the peer side.
17807 			 * In this way, the other side will not send
17808 			 * anything larger than they can receive.
17809 			 *
17810 			 * Note that for SYN_SENT state, the ndd param
17811 			 * tcp_use_smss_as_mss_opt has no effect as we
17812 			 * don't know the peer's MSS option value. So
17813 			 * the only case we need to take care of is in
17814 			 * SYN_RCVD state, which is done later.
17815 			 */
17816 			wptr = mp1->b_wptr;
17817 			wptr[0] = TCPOPT_MAXSEG;
17818 			wptr[1] = TCPOPT_MAXSEG_LEN;
17819 			wptr += 2;
17820 			u1 = tcp->tcp_initial_pmtu -
17821 			    (connp->conn_ipversion == IPV4_VERSION ?
17822 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
17823 			    TCP_MIN_HEADER_LENGTH;
17824 			U16_TO_BE16(u1, wptr);
17825 			mp1->b_wptr = wptr + 2;
17826 			/* Update the offset to cover the additional word */
17827 			tcpha->tha_offset_and_reserved += (1 << 4);
17828 
17829 			/*
17830 			 * Note that the following way of filling in
17831 			 * TCP options are not optimal.  Some NOPs can
17832 			 * be saved.  But there is no need at this time
17833 			 * to optimize it.  When it is needed, we will
17834 			 * do it.
17835 			 */
17836 			switch (tcp->tcp_state) {
17837 			case TCPS_SYN_SENT:
17838 				flags = TH_SYN;
17839 
17840 				if (tcp->tcp_snd_ts_ok) {
17841 					uint32_t llbolt =
17842 					    (uint32_t)LBOLT_FASTPATH;
17843 
17844 					wptr = mp1->b_wptr;
17845 					wptr[0] = TCPOPT_NOP;
17846 					wptr[1] = TCPOPT_NOP;
17847 					wptr[2] = TCPOPT_TSTAMP;
17848 					wptr[3] = TCPOPT_TSTAMP_LEN;
17849 					wptr += 4;
17850 					U32_TO_BE32(llbolt, wptr);
17851 					wptr += 4;
17852 					ASSERT(tcp->tcp_ts_recent == 0);
17853 					U32_TO_BE32(0L, wptr);
17854 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
17855 					tcpha->tha_offset_and_reserved +=
17856 					    (3 << 4);
17857 				}
17858 
17859 				/*
17860 				 * Set up all the bits to tell other side
17861 				 * we are ECN capable.
17862 				 */
17863 				if (tcp->tcp_ecn_ok) {
17864 					flags |= (TH_ECE | TH_CWR);
17865 				}
17866 				break;
17867 			case TCPS_SYN_RCVD:
17868 				flags |= TH_SYN;
17869 
17870 				/*
17871 				 * Reset the MSS option value to be SMSS
17872 				 * We should probably add back the bytes
17873 				 * for timestamp option and IPsec.  We
17874 				 * don't do that as this is a workaround
17875 				 * for broken middle boxes/end hosts, it
17876 				 * is better for us to be more cautious.
17877 				 * They may not take these things into
17878 				 * account in their SMSS calculation.  Thus
17879 				 * the peer's calculated SMSS may be smaller
17880 				 * than what it can be.  This should be OK.
17881 				 */
17882 				if (tcps->tcps_use_smss_as_mss_opt) {
17883 					u1 = tcp->tcp_mss;
17884 					U16_TO_BE16(u1, wptr);
17885 				}
17886 
17887 				/*
17888 				 * If the other side is ECN capable, reply
17889 				 * that we are also ECN capable.
17890 				 */
17891 				if (tcp->tcp_ecn_ok)
17892 					flags |= TH_ECE;
17893 				break;
17894 			default:
17895 				/*
17896 				 * The above ASSERT() makes sure that this
17897 				 * must be FIN-WAIT-1 state.  Our SYN has
17898 				 * not been ack'ed so retransmit it.
17899 				 */
17900 				flags |= TH_SYN;
17901 				break;
17902 			}
17903 
17904 			if (tcp->tcp_snd_ws_ok) {
17905 				wptr = mp1->b_wptr;
17906 				wptr[0] =  TCPOPT_NOP;
17907 				wptr[1] =  TCPOPT_WSCALE;
17908 				wptr[2] =  TCPOPT_WS_LEN;
17909 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
17910 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
17911 				tcpha->tha_offset_and_reserved += (1 << 4);
17912 			}
17913 
17914 			if (tcp->tcp_snd_sack_ok) {
17915 				wptr = mp1->b_wptr;
17916 				wptr[0] = TCPOPT_NOP;
17917 				wptr[1] = TCPOPT_NOP;
17918 				wptr[2] = TCPOPT_SACK_PERMITTED;
17919 				wptr[3] = TCPOPT_SACK_OK_LEN;
17920 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
17921 				tcpha->tha_offset_and_reserved += (1 << 4);
17922 			}
17923 
17924 			/* allocb() of adequate mblk assures space */
17925 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
17926 			    (uintptr_t)INT_MAX);
17927 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
17928 			/*
17929 			 * Get IP set to checksum on our behalf
17930 			 * Include the adjustment for a source route if any.
17931 			 */
17932 			u1 += connp->conn_sum;
17933 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
17934 			tcpha->tha_sum = htons(u1);
17935 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17936 		}
17937 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17938 		    (seq + data_length) == tcp->tcp_fss) {
17939 			if (!tcp->tcp_fin_acked) {
17940 				flags |= TH_FIN;
17941 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17942 			}
17943 			if (!tcp->tcp_fin_sent) {
17944 				tcp->tcp_fin_sent = B_TRUE;
17945 				switch (tcp->tcp_state) {
17946 				case TCPS_SYN_RCVD:
17947 				case TCPS_ESTABLISHED:
17948 					tcp->tcp_state = TCPS_FIN_WAIT_1;
17949 					break;
17950 				case TCPS_CLOSE_WAIT:
17951 					tcp->tcp_state = TCPS_LAST_ACK;
17952 					break;
17953 				}
17954 				if (tcp->tcp_suna == tcp->tcp_snxt)
17955 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17956 				tcp->tcp_snxt = tcp->tcp_fss + 1;
17957 			}
17958 		}
17959 		/*
17960 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
17961 		 * is smaller than seq, u1 will become a very huge value.
17962 		 * So the comparison will fail.  Also note that tcp_urp
17963 		 * should be positive, see RFC 793 page 17.
17964 		 */
17965 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
17966 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
17967 		    u1 < (uint32_t)(64 * 1024)) {
17968 			flags |= TH_URG;
17969 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
17970 			tcpha->tha_urp = htons(u1);
17971 		}
17972 	}
17973 	tcpha->tha_flags = (uchar_t)flags;
17974 	tcp->tcp_rack = tcp->tcp_rnxt;
17975 	tcp->tcp_rack_cnt = 0;
17976 
17977 	if (tcp->tcp_snd_ts_ok) {
17978 		if (tcp->tcp_state != TCPS_SYN_SENT) {
17979 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
17980 
17981 			U32_TO_BE32(llbolt,
17982 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
17983 			U32_TO_BE32(tcp->tcp_ts_recent,
17984 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
17985 		}
17986 	}
17987 
17988 	if (num_sack_blk > 0) {
17989 		uchar_t *wptr = (uchar_t *)tcpha + connp->conn_ht_ulp_len;
17990 		sack_blk_t *tmp;
17991 		int32_t	i;
17992 
17993 		wptr[0] = TCPOPT_NOP;
17994 		wptr[1] = TCPOPT_NOP;
17995 		wptr[2] = TCPOPT_SACK;
17996 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
17997 		    sizeof (sack_blk_t);
17998 		wptr += TCPOPT_REAL_SACK_LEN;
17999 
18000 		tmp = tcp->tcp_sack_list;
18001 		for (i = 0; i < num_sack_blk; i++) {
18002 			U32_TO_BE32(tmp[i].begin, wptr);
18003 			wptr += sizeof (tcp_seq);
18004 			U32_TO_BE32(tmp[i].end, wptr);
18005 			wptr += sizeof (tcp_seq);
18006 		}
18007 		tcpha->tha_offset_and_reserved += ((num_sack_blk * 2 + 1) << 4);
18008 	}
18009 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
18010 	data_length += (int)(mp1->b_wptr - rptr);
18011 
18012 	ixa->ixa_pktlen = data_length;
18013 
18014 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
18015 		((ipha_t *)rptr)->ipha_length = htons(data_length);
18016 	} else {
18017 		ip6_t *ip6 = (ip6_t *)rptr;
18018 
18019 		ip6->ip6_plen = htons(data_length - IPV6_HDR_LEN);
18020 	}
18021 
18022 	/*
18023 	 * Prime pump for IP
18024 	 * Include the adjustment for a source route if any.
18025 	 */
18026 	data_length -= ixa->ixa_ip_hdr_length;
18027 	data_length += connp->conn_sum;
18028 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
18029 	tcpha->tha_sum = htons(data_length);
18030 	if (tcp->tcp_ip_forward_progress) {
18031 		tcp->tcp_ip_forward_progress = B_FALSE;
18032 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
18033 	} else {
18034 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
18035 	}
18036 	return (mp1);
18037 }
18038 
18039 /* This function handles the push timeout. */
18040 void
18041 tcp_push_timer(void *arg)
18042 {
18043 	conn_t	*connp = (conn_t *)arg;
18044 	tcp_t *tcp = connp->conn_tcp;
18045 
18046 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
18047 
18048 	ASSERT(tcp->tcp_listener == NULL);
18049 
18050 	ASSERT(!IPCL_IS_NONSTR(connp));
18051 
18052 	tcp->tcp_push_tid = 0;
18053 
18054 	if (tcp->tcp_rcv_list != NULL &&
18055 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
18056 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
18057 }
18058 
18059 /*
18060  * This function handles delayed ACK timeout.
18061  */
18062 static void
18063 tcp_ack_timer(void *arg)
18064 {
18065 	conn_t	*connp = (conn_t *)arg;
18066 	tcp_t *tcp = connp->conn_tcp;
18067 	mblk_t *mp;
18068 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18069 
18070 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
18071 
18072 	tcp->tcp_ack_tid = 0;
18073 
18074 	if (tcp->tcp_fused)
18075 		return;
18076 
18077 	/*
18078 	 * Do not send ACK if there is no outstanding unack'ed data.
18079 	 */
18080 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
18081 		return;
18082 	}
18083 
18084 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
18085 		/*
18086 		 * Make sure we don't allow deferred ACKs to result in
18087 		 * timer-based ACKing.  If we have held off an ACK
18088 		 * when there was more than an mss here, and the timer
18089 		 * goes off, we have to worry about the possibility
18090 		 * that the sender isn't doing slow-start, or is out
18091 		 * of step with us for some other reason.  We fall
18092 		 * permanently back in the direction of
18093 		 * ACK-every-other-packet as suggested in RFC 1122.
18094 		 */
18095 		if (tcp->tcp_rack_abs_max > 2)
18096 			tcp->tcp_rack_abs_max--;
18097 		tcp->tcp_rack_cur_max = 2;
18098 	}
18099 	mp = tcp_ack_mp(tcp);
18100 
18101 	if (mp != NULL) {
18102 		BUMP_LOCAL(tcp->tcp_obsegs);
18103 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
18104 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
18105 		tcp_send_data(tcp, mp);
18106 	}
18107 }
18108 
18109 
18110 /* Generate an ACK-only (no data) segment for a TCP endpoint */
18111 static mblk_t *
18112 tcp_ack_mp(tcp_t *tcp)
18113 {
18114 	uint32_t	seq_no;
18115 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18116 	conn_t		*connp = tcp->tcp_connp;
18117 
18118 	/*
18119 	 * There are a few cases to be considered while setting the sequence no.
18120 	 * Essentially, we can come here while processing an unacceptable pkt
18121 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
18122 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
18123 	 * If we are here for a zero window probe, stick with suna. In all
18124 	 * other cases, we check if suna + swnd encompasses snxt and set
18125 	 * the sequence number to snxt, if so. If snxt falls outside the
18126 	 * window (the receiver probably shrunk its window), we will go with
18127 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
18128 	 * receiver.
18129 	 */
18130 	if (tcp->tcp_zero_win_probe) {
18131 		seq_no = tcp->tcp_suna;
18132 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
18133 		ASSERT(tcp->tcp_swnd == 0);
18134 		seq_no = tcp->tcp_snxt;
18135 	} else {
18136 		seq_no = SEQ_GT(tcp->tcp_snxt,
18137 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
18138 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
18139 	}
18140 
18141 	if (tcp->tcp_valid_bits) {
18142 		/*
18143 		 * For the complex case where we have to send some
18144 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
18145 		 */
18146 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
18147 		    NULL, B_FALSE));
18148 	} else {
18149 		/* Generate a simple ACK */
18150 		int	data_length;
18151 		uchar_t	*rptr;
18152 		tcpha_t	*tcpha;
18153 		mblk_t	*mp1;
18154 		int32_t	total_hdr_len;
18155 		int32_t	tcp_hdr_len;
18156 		int32_t	num_sack_blk = 0;
18157 		int32_t sack_opt_len;
18158 		ip_xmit_attr_t *ixa = connp->conn_ixa;
18159 
18160 		/*
18161 		 * Allocate space for TCP + IP headers
18162 		 * and link-level header
18163 		 */
18164 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18165 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18166 			    tcp->tcp_num_sack_blk);
18167 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
18168 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
18169 			total_hdr_len = connp->conn_ht_iphc_len + sack_opt_len;
18170 			tcp_hdr_len = connp->conn_ht_ulp_len + sack_opt_len;
18171 		} else {
18172 			total_hdr_len = connp->conn_ht_iphc_len;
18173 			tcp_hdr_len = connp->conn_ht_ulp_len;
18174 		}
18175 		mp1 = allocb(total_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
18176 		if (!mp1)
18177 			return (NULL);
18178 
18179 		/* Update the latest receive window size in TCP header. */
18180 		tcp->tcp_tcpha->tha_win =
18181 		    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
18182 		/* copy in prototype TCP + IP header */
18183 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
18184 		mp1->b_rptr = rptr;
18185 		mp1->b_wptr = rptr + total_hdr_len;
18186 		bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
18187 
18188 		tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
18189 
18190 		/* Set the TCP sequence number. */
18191 		tcpha->tha_seq = htonl(seq_no);
18192 
18193 		/* Set up the TCP flag field. */
18194 		tcpha->tha_flags = (uchar_t)TH_ACK;
18195 		if (tcp->tcp_ecn_echo_on)
18196 			tcpha->tha_flags |= TH_ECE;
18197 
18198 		tcp->tcp_rack = tcp->tcp_rnxt;
18199 		tcp->tcp_rack_cnt = 0;
18200 
18201 		/* fill in timestamp option if in use */
18202 		if (tcp->tcp_snd_ts_ok) {
18203 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
18204 
18205 			U32_TO_BE32(llbolt,
18206 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
18207 			U32_TO_BE32(tcp->tcp_ts_recent,
18208 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
18209 		}
18210 
18211 		/* Fill in SACK options */
18212 		if (num_sack_blk > 0) {
18213 			uchar_t *wptr = (uchar_t *)tcpha +
18214 			    connp->conn_ht_ulp_len;
18215 			sack_blk_t *tmp;
18216 			int32_t	i;
18217 
18218 			wptr[0] = TCPOPT_NOP;
18219 			wptr[1] = TCPOPT_NOP;
18220 			wptr[2] = TCPOPT_SACK;
18221 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
18222 			    sizeof (sack_blk_t);
18223 			wptr += TCPOPT_REAL_SACK_LEN;
18224 
18225 			tmp = tcp->tcp_sack_list;
18226 			for (i = 0; i < num_sack_blk; i++) {
18227 				U32_TO_BE32(tmp[i].begin, wptr);
18228 				wptr += sizeof (tcp_seq);
18229 				U32_TO_BE32(tmp[i].end, wptr);
18230 				wptr += sizeof (tcp_seq);
18231 			}
18232 			tcpha->tha_offset_and_reserved +=
18233 			    ((num_sack_blk * 2 + 1) << 4);
18234 		}
18235 
18236 		ixa->ixa_pktlen = total_hdr_len;
18237 
18238 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
18239 			((ipha_t *)rptr)->ipha_length = htons(total_hdr_len);
18240 		} else {
18241 			ip6_t *ip6 = (ip6_t *)rptr;
18242 
18243 			ip6->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
18244 		}
18245 
18246 		/*
18247 		 * Prime pump for checksum calculation in IP.  Include the
18248 		 * adjustment for a source route if any.
18249 		 */
18250 		data_length = tcp_hdr_len + connp->conn_sum;
18251 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
18252 		tcpha->tha_sum = htons(data_length);
18253 
18254 		if (tcp->tcp_ip_forward_progress) {
18255 			tcp->tcp_ip_forward_progress = B_FALSE;
18256 			connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
18257 		} else {
18258 			connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
18259 		}
18260 		return (mp1);
18261 	}
18262 }
18263 
18264 /*
18265  * Hash list insertion routine for tcp_t structures. Each hash bucket
18266  * contains a list of tcp_t entries, and each entry is bound to a unique
18267  * port. If there are multiple tcp_t's that are bound to the same port, then
18268  * one of them will be linked into the hash bucket list, and the rest will
18269  * hang off of that one entry. For each port, entries bound to a specific IP
18270  * address will be inserted before those those bound to INADDR_ANY.
18271  */
18272 static void
18273 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
18274 {
18275 	tcp_t	**tcpp;
18276 	tcp_t	*tcpnext;
18277 	tcp_t	*tcphash;
18278 	conn_t	*connp = tcp->tcp_connp;
18279 	conn_t	*connext;
18280 
18281 	if (tcp->tcp_ptpbhn != NULL) {
18282 		ASSERT(!caller_holds_lock);
18283 		tcp_bind_hash_remove(tcp);
18284 	}
18285 	tcpp = &tbf->tf_tcp;
18286 	if (!caller_holds_lock) {
18287 		mutex_enter(&tbf->tf_lock);
18288 	} else {
18289 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
18290 	}
18291 	tcphash = tcpp[0];
18292 	tcpnext = NULL;
18293 	if (tcphash != NULL) {
18294 		/* Look for an entry using the same port */
18295 		while ((tcphash = tcpp[0]) != NULL &&
18296 		    connp->conn_lport != tcphash->tcp_connp->conn_lport)
18297 			tcpp = &(tcphash->tcp_bind_hash);
18298 
18299 		/* The port was not found, just add to the end */
18300 		if (tcphash == NULL)
18301 			goto insert;
18302 
18303 		/*
18304 		 * OK, there already exists an entry bound to the
18305 		 * same port.
18306 		 *
18307 		 * If the new tcp bound to the INADDR_ANY address
18308 		 * and the first one in the list is not bound to
18309 		 * INADDR_ANY we skip all entries until we find the
18310 		 * first one bound to INADDR_ANY.
18311 		 * This makes sure that applications binding to a
18312 		 * specific address get preference over those binding to
18313 		 * INADDR_ANY.
18314 		 */
18315 		tcpnext = tcphash;
18316 		connext = tcpnext->tcp_connp;
18317 		tcphash = NULL;
18318 		if (V6_OR_V4_INADDR_ANY(connp->conn_bound_addr_v6) &&
18319 		    !V6_OR_V4_INADDR_ANY(connext->conn_bound_addr_v6)) {
18320 			while ((tcpnext = tcpp[0]) != NULL) {
18321 				connext = tcpnext->tcp_connp;
18322 				if (!V6_OR_V4_INADDR_ANY(
18323 				    connext->conn_bound_addr_v6))
18324 					tcpp = &(tcpnext->tcp_bind_hash_port);
18325 				else
18326 					break;
18327 			}
18328 			if (tcpnext != NULL) {
18329 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
18330 				tcphash = tcpnext->tcp_bind_hash;
18331 				if (tcphash != NULL) {
18332 					tcphash->tcp_ptpbhn =
18333 					    &(tcp->tcp_bind_hash);
18334 					tcpnext->tcp_bind_hash = NULL;
18335 				}
18336 			}
18337 		} else {
18338 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
18339 			tcphash = tcpnext->tcp_bind_hash;
18340 			if (tcphash != NULL) {
18341 				tcphash->tcp_ptpbhn =
18342 				    &(tcp->tcp_bind_hash);
18343 				tcpnext->tcp_bind_hash = NULL;
18344 			}
18345 		}
18346 	}
18347 insert:
18348 	tcp->tcp_bind_hash_port = tcpnext;
18349 	tcp->tcp_bind_hash = tcphash;
18350 	tcp->tcp_ptpbhn = tcpp;
18351 	tcpp[0] = tcp;
18352 	if (!caller_holds_lock)
18353 		mutex_exit(&tbf->tf_lock);
18354 }
18355 
18356 /*
18357  * Hash list removal routine for tcp_t structures.
18358  */
18359 static void
18360 tcp_bind_hash_remove(tcp_t *tcp)
18361 {
18362 	tcp_t	*tcpnext;
18363 	kmutex_t *lockp;
18364 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18365 	conn_t		*connp = tcp->tcp_connp;
18366 
18367 	if (tcp->tcp_ptpbhn == NULL)
18368 		return;
18369 
18370 	/*
18371 	 * Extract the lock pointer in case there are concurrent
18372 	 * hash_remove's for this instance.
18373 	 */
18374 	ASSERT(connp->conn_lport != 0);
18375 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(
18376 	    connp->conn_lport)].tf_lock;
18377 
18378 	ASSERT(lockp != NULL);
18379 	mutex_enter(lockp);
18380 	if (tcp->tcp_ptpbhn) {
18381 		tcpnext = tcp->tcp_bind_hash_port;
18382 		if (tcpnext != NULL) {
18383 			tcp->tcp_bind_hash_port = NULL;
18384 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
18385 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
18386 			if (tcpnext->tcp_bind_hash != NULL) {
18387 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
18388 				    &(tcpnext->tcp_bind_hash);
18389 				tcp->tcp_bind_hash = NULL;
18390 			}
18391 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
18392 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
18393 			tcp->tcp_bind_hash = NULL;
18394 		}
18395 		*tcp->tcp_ptpbhn = tcpnext;
18396 		tcp->tcp_ptpbhn = NULL;
18397 	}
18398 	mutex_exit(lockp);
18399 }
18400 
18401 
18402 /*
18403  * Hash list lookup routine for tcp_t structures.
18404  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
18405  */
18406 static tcp_t *
18407 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
18408 {
18409 	tf_t	*tf;
18410 	tcp_t	*tcp;
18411 
18412 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
18413 	mutex_enter(&tf->tf_lock);
18414 	for (tcp = tf->tf_tcp; tcp != NULL;
18415 	    tcp = tcp->tcp_acceptor_hash) {
18416 		if (tcp->tcp_acceptor_id == id) {
18417 			CONN_INC_REF(tcp->tcp_connp);
18418 			mutex_exit(&tf->tf_lock);
18419 			return (tcp);
18420 		}
18421 	}
18422 	mutex_exit(&tf->tf_lock);
18423 	return (NULL);
18424 }
18425 
18426 
18427 /*
18428  * Hash list insertion routine for tcp_t structures.
18429  */
18430 void
18431 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
18432 {
18433 	tf_t	*tf;
18434 	tcp_t	**tcpp;
18435 	tcp_t	*tcpnext;
18436 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18437 
18438 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
18439 
18440 	if (tcp->tcp_ptpahn != NULL)
18441 		tcp_acceptor_hash_remove(tcp);
18442 	tcpp = &tf->tf_tcp;
18443 	mutex_enter(&tf->tf_lock);
18444 	tcpnext = tcpp[0];
18445 	if (tcpnext)
18446 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
18447 	tcp->tcp_acceptor_hash = tcpnext;
18448 	tcp->tcp_ptpahn = tcpp;
18449 	tcpp[0] = tcp;
18450 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
18451 	mutex_exit(&tf->tf_lock);
18452 }
18453 
18454 /*
18455  * Hash list removal routine for tcp_t structures.
18456  */
18457 static void
18458 tcp_acceptor_hash_remove(tcp_t *tcp)
18459 {
18460 	tcp_t	*tcpnext;
18461 	kmutex_t *lockp;
18462 
18463 	/*
18464 	 * Extract the lock pointer in case there are concurrent
18465 	 * hash_remove's for this instance.
18466 	 */
18467 	lockp = tcp->tcp_acceptor_lockp;
18468 
18469 	if (tcp->tcp_ptpahn == NULL)
18470 		return;
18471 
18472 	ASSERT(lockp != NULL);
18473 	mutex_enter(lockp);
18474 	if (tcp->tcp_ptpahn) {
18475 		tcpnext = tcp->tcp_acceptor_hash;
18476 		if (tcpnext) {
18477 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
18478 			tcp->tcp_acceptor_hash = NULL;
18479 		}
18480 		*tcp->tcp_ptpahn = tcpnext;
18481 		tcp->tcp_ptpahn = NULL;
18482 	}
18483 	mutex_exit(lockp);
18484 	tcp->tcp_acceptor_lockp = NULL;
18485 }
18486 
18487 /*
18488  * Type three generator adapted from the random() function in 4.4 BSD:
18489  */
18490 
18491 /*
18492  * Copyright (c) 1983, 1993
18493  *	The Regents of the University of California.  All rights reserved.
18494  *
18495  * Redistribution and use in source and binary forms, with or without
18496  * modification, are permitted provided that the following conditions
18497  * are met:
18498  * 1. Redistributions of source code must retain the above copyright
18499  *    notice, this list of conditions and the following disclaimer.
18500  * 2. Redistributions in binary form must reproduce the above copyright
18501  *    notice, this list of conditions and the following disclaimer in the
18502  *    documentation and/or other materials provided with the distribution.
18503  * 3. All advertising materials mentioning features or use of this software
18504  *    must display the following acknowledgement:
18505  *	This product includes software developed by the University of
18506  *	California, Berkeley and its contributors.
18507  * 4. Neither the name of the University nor the names of its contributors
18508  *    may be used to endorse or promote products derived from this software
18509  *    without specific prior written permission.
18510  *
18511  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18512  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18513  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18514  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18515  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18516  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
18517  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
18518  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
18519  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
18520  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
18521  * SUCH DAMAGE.
18522  */
18523 
18524 /* Type 3 -- x**31 + x**3 + 1 */
18525 #define	DEG_3		31
18526 #define	SEP_3		3
18527 
18528 
18529 /* Protected by tcp_random_lock */
18530 static int tcp_randtbl[DEG_3 + 1];
18531 
18532 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
18533 static int *tcp_random_rptr = &tcp_randtbl[1];
18534 
18535 static int *tcp_random_state = &tcp_randtbl[1];
18536 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
18537 
18538 kmutex_t tcp_random_lock;
18539 
18540 void
18541 tcp_random_init(void)
18542 {
18543 	int i;
18544 	hrtime_t hrt;
18545 	time_t wallclock;
18546 	uint64_t result;
18547 
18548 	/*
18549 	 * Use high-res timer and current time for seed.  Gethrtime() returns
18550 	 * a longlong, which may contain resolution down to nanoseconds.
18551 	 * The current time will either be a 32-bit or a 64-bit quantity.
18552 	 * XOR the two together in a 64-bit result variable.
18553 	 * Convert the result to a 32-bit value by multiplying the high-order
18554 	 * 32-bits by the low-order 32-bits.
18555 	 */
18556 
18557 	hrt = gethrtime();
18558 	(void) drv_getparm(TIME, &wallclock);
18559 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
18560 	mutex_enter(&tcp_random_lock);
18561 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
18562 	    (result & 0xffffffff);
18563 
18564 	for (i = 1; i < DEG_3; i++)
18565 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
18566 		    + 12345;
18567 	tcp_random_fptr = &tcp_random_state[SEP_3];
18568 	tcp_random_rptr = &tcp_random_state[0];
18569 	mutex_exit(&tcp_random_lock);
18570 	for (i = 0; i < 10 * DEG_3; i++)
18571 		(void) tcp_random();
18572 }
18573 
18574 /*
18575  * tcp_random: Return a random number in the range [1 - (128K + 1)].
18576  * This range is selected to be approximately centered on TCP_ISS / 2,
18577  * and easy to compute. We get this value by generating a 32-bit random
18578  * number, selecting out the high-order 17 bits, and then adding one so
18579  * that we never return zero.
18580  */
18581 int
18582 tcp_random(void)
18583 {
18584 	int i;
18585 
18586 	mutex_enter(&tcp_random_lock);
18587 	*tcp_random_fptr += *tcp_random_rptr;
18588 
18589 	/*
18590 	 * The high-order bits are more random than the low-order bits,
18591 	 * so we select out the high-order 17 bits and add one so that
18592 	 * we never return zero.
18593 	 */
18594 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
18595 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
18596 		tcp_random_fptr = tcp_random_state;
18597 		++tcp_random_rptr;
18598 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
18599 		tcp_random_rptr = tcp_random_state;
18600 
18601 	mutex_exit(&tcp_random_lock);
18602 	return (i);
18603 }
18604 
18605 static int
18606 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
18607     int *t_errorp, int *sys_errorp)
18608 {
18609 	int error;
18610 	int is_absreq_failure;
18611 	t_scalar_t *opt_lenp;
18612 	t_scalar_t opt_offset;
18613 	int prim_type;
18614 	struct T_conn_req *tcreqp;
18615 	struct T_conn_res *tcresp;
18616 	cred_t *cr;
18617 
18618 	/*
18619 	 * All Solaris components should pass a db_credp
18620 	 * for this TPI message, hence we ASSERT.
18621 	 * But in case there is some other M_PROTO that looks
18622 	 * like a TPI message sent by some other kernel
18623 	 * component, we check and return an error.
18624 	 */
18625 	cr = msg_getcred(mp, NULL);
18626 	ASSERT(cr != NULL);
18627 	if (cr == NULL)
18628 		return (-1);
18629 
18630 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
18631 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
18632 	    prim_type == T_CONN_RES);
18633 
18634 	switch (prim_type) {
18635 	case T_CONN_REQ:
18636 		tcreqp = (struct T_conn_req *)mp->b_rptr;
18637 		opt_offset = tcreqp->OPT_offset;
18638 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
18639 		break;
18640 	case O_T_CONN_RES:
18641 	case T_CONN_RES:
18642 		tcresp = (struct T_conn_res *)mp->b_rptr;
18643 		opt_offset = tcresp->OPT_offset;
18644 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
18645 		break;
18646 	}
18647 
18648 	*t_errorp = 0;
18649 	*sys_errorp = 0;
18650 	*do_disconnectp = 0;
18651 
18652 	error = tpi_optcom_buf(tcp->tcp_connp->conn_wq, mp, opt_lenp,
18653 	    opt_offset, cr, &tcp_opt_obj,
18654 	    NULL, &is_absreq_failure);
18655 
18656 	switch (error) {
18657 	case  0:		/* no error */
18658 		ASSERT(is_absreq_failure == 0);
18659 		return (0);
18660 	case ENOPROTOOPT:
18661 		*t_errorp = TBADOPT;
18662 		break;
18663 	case EACCES:
18664 		*t_errorp = TACCES;
18665 		break;
18666 	default:
18667 		*t_errorp = TSYSERR; *sys_errorp = error;
18668 		break;
18669 	}
18670 	if (is_absreq_failure != 0) {
18671 		/*
18672 		 * The connection request should get the local ack
18673 		 * T_OK_ACK and then a T_DISCON_IND.
18674 		 */
18675 		*do_disconnectp = 1;
18676 	}
18677 	return (-1);
18678 }
18679 
18680 /*
18681  * Split this function out so that if the secret changes, I'm okay.
18682  *
18683  * Initialize the tcp_iss_cookie and tcp_iss_key.
18684  */
18685 
18686 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
18687 
18688 static void
18689 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
18690 {
18691 	struct {
18692 		int32_t current_time;
18693 		uint32_t randnum;
18694 		uint16_t pad;
18695 		uint8_t ether[6];
18696 		uint8_t passwd[PASSWD_SIZE];
18697 	} tcp_iss_cookie;
18698 	time_t t;
18699 
18700 	/*
18701 	 * Start with the current absolute time.
18702 	 */
18703 	(void) drv_getparm(TIME, &t);
18704 	tcp_iss_cookie.current_time = t;
18705 
18706 	/*
18707 	 * XXX - Need a more random number per RFC 1750, not this crap.
18708 	 * OTOH, if what follows is pretty random, then I'm in better shape.
18709 	 */
18710 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
18711 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
18712 
18713 	/*
18714 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
18715 	 * as a good template.
18716 	 */
18717 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
18718 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
18719 
18720 	/*
18721 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
18722 	 */
18723 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
18724 
18725 	/*
18726 	 * See 4010593 if this section becomes a problem again,
18727 	 * but the local ethernet address is useful here.
18728 	 */
18729 	(void) localetheraddr(NULL,
18730 	    (struct ether_addr *)&tcp_iss_cookie.ether);
18731 
18732 	/*
18733 	 * Hash 'em all together.  The MD5Final is called per-connection.
18734 	 */
18735 	mutex_enter(&tcps->tcps_iss_key_lock);
18736 	MD5Init(&tcps->tcps_iss_key);
18737 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
18738 	    sizeof (tcp_iss_cookie));
18739 	mutex_exit(&tcps->tcps_iss_key_lock);
18740 }
18741 
18742 /*
18743  * Set the RFC 1948 pass phrase
18744  */
18745 /* ARGSUSED */
18746 static int
18747 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
18748     cred_t *cr)
18749 {
18750 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18751 
18752 	/*
18753 	 * Basically, value contains a new pass phrase.  Pass it along!
18754 	 */
18755 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
18756 	return (0);
18757 }
18758 
18759 /* ARGSUSED */
18760 static int
18761 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
18762 {
18763 	bzero(buf, sizeof (tcp_sack_info_t));
18764 	return (0);
18765 }
18766 
18767 /*
18768  * Called by IP when IP is loaded into the kernel
18769  */
18770 void
18771 tcp_ddi_g_init(void)
18772 {
18773 	tcp_timercache = kmem_cache_create("tcp_timercache",
18774 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
18775 	    NULL, NULL, NULL, NULL, NULL, 0);
18776 
18777 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
18778 	    sizeof (tcp_sack_info_t), 0,
18779 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
18780 
18781 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
18782 
18783 	/* Initialize the random number generator */
18784 	tcp_random_init();
18785 
18786 	/* A single callback independently of how many netstacks we have */
18787 	ip_squeue_init(tcp_squeue_add);
18788 
18789 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
18790 
18791 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
18792 
18793 	/*
18794 	 * We want to be informed each time a stack is created or
18795 	 * destroyed in the kernel, so we can maintain the
18796 	 * set of tcp_stack_t's.
18797 	 */
18798 	netstack_register(NS_TCP, tcp_stack_init, NULL, tcp_stack_fini);
18799 }
18800 
18801 
18802 #define	INET_NAME	"ip"
18803 
18804 /*
18805  * Initialize the TCP stack instance.
18806  */
18807 static void *
18808 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
18809 {
18810 	tcp_stack_t	*tcps;
18811 	tcpparam_t	*pa;
18812 	int		i;
18813 	int		error = 0;
18814 	major_t		major;
18815 
18816 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
18817 	tcps->tcps_netstack = ns;
18818 
18819 	/* Initialize locks */
18820 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
18821 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
18822 
18823 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
18824 	tcps->tcps_g_epriv_ports[0] = 2049;
18825 	tcps->tcps_g_epriv_ports[1] = 4045;
18826 	tcps->tcps_min_anonpriv_port = 512;
18827 
18828 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
18829 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
18830 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
18831 	    TCP_ACCEPTOR_FANOUT_SIZE, KM_SLEEP);
18832 
18833 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
18834 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
18835 		    MUTEX_DEFAULT, NULL);
18836 	}
18837 
18838 	for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
18839 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
18840 		    MUTEX_DEFAULT, NULL);
18841 	}
18842 
18843 	/* TCP's IPsec code calls the packet dropper. */
18844 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
18845 
18846 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
18847 	tcps->tcps_params = pa;
18848 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
18849 
18850 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
18851 	    A_CNT(lcl_tcp_param_arr), tcps);
18852 
18853 	/*
18854 	 * Note: To really walk the device tree you need the devinfo
18855 	 * pointer to your device which is only available after probe/attach.
18856 	 * The following is safe only because it uses ddi_root_node()
18857 	 */
18858 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
18859 	    tcp_opt_obj.odb_opt_arr_cnt);
18860 
18861 	/*
18862 	 * Initialize RFC 1948 secret values.  This will probably be reset once
18863 	 * by the boot scripts.
18864 	 *
18865 	 * Use NULL name, as the name is caught by the new lockstats.
18866 	 *
18867 	 * Initialize with some random, non-guessable string, like the global
18868 	 * T_INFO_ACK.
18869 	 */
18870 
18871 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
18872 	    sizeof (tcp_g_t_info_ack), tcps);
18873 
18874 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
18875 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
18876 
18877 	major = mod_name_to_major(INET_NAME);
18878 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
18879 	ASSERT(error == 0);
18880 	tcps->tcps_ixa_cleanup_mp = allocb_wait(0, BPRI_MED, STR_NOSIG, NULL);
18881 	ASSERT(tcps->tcps_ixa_cleanup_mp != NULL);
18882 	cv_init(&tcps->tcps_ixa_cleanup_cv, NULL, CV_DEFAULT, NULL);
18883 	mutex_init(&tcps->tcps_ixa_cleanup_lock, NULL, MUTEX_DEFAULT, NULL);
18884 
18885 	mutex_init(&tcps->tcps_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
18886 	tcps->tcps_reclaim = B_FALSE;
18887 	tcps->tcps_reclaim_tid = 0;
18888 	tcps->tcps_reclaim_period = tcps->tcps_rexmit_interval_max * 3;
18889 
18890 	mutex_init(&tcps->tcps_listener_conf_lock, NULL, MUTEX_DEFAULT, NULL);
18891 	list_create(&tcps->tcps_listener_conf, sizeof (tcp_listener_t),
18892 	    offsetof(tcp_listener_t, tl_link));
18893 
18894 	return (tcps);
18895 }
18896 
18897 /*
18898  * Called when the IP module is about to be unloaded.
18899  */
18900 void
18901 tcp_ddi_g_destroy(void)
18902 {
18903 	tcp_g_kstat_fini(tcp_g_kstat);
18904 	tcp_g_kstat = NULL;
18905 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
18906 
18907 	mutex_destroy(&tcp_random_lock);
18908 
18909 	kmem_cache_destroy(tcp_timercache);
18910 	kmem_cache_destroy(tcp_sack_info_cache);
18911 
18912 	netstack_unregister(NS_TCP);
18913 }
18914 
18915 /*
18916  * Free the TCP stack instance.
18917  */
18918 static void
18919 tcp_stack_fini(netstackid_t stackid, void *arg)
18920 {
18921 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
18922 	int i;
18923 
18924 	freeb(tcps->tcps_ixa_cleanup_mp);
18925 	tcps->tcps_ixa_cleanup_mp = NULL;
18926 	cv_destroy(&tcps->tcps_ixa_cleanup_cv);
18927 	mutex_destroy(&tcps->tcps_ixa_cleanup_lock);
18928 
18929 	if (tcps->tcps_reclaim_tid != 0)
18930 		(void) untimeout(tcps->tcps_reclaim_tid);
18931 	mutex_destroy(&tcps->tcps_reclaim_lock);
18932 
18933 	tcp_listener_conf_cleanup(tcps);
18934 
18935 	nd_free(&tcps->tcps_g_nd);
18936 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
18937 	tcps->tcps_params = NULL;
18938 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
18939 	tcps->tcps_wroff_xtra_param = NULL;
18940 
18941 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
18942 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
18943 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
18944 	}
18945 
18946 	for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
18947 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
18948 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
18949 	}
18950 
18951 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
18952 	tcps->tcps_bind_fanout = NULL;
18953 
18954 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) *
18955 	    TCP_ACCEPTOR_FANOUT_SIZE);
18956 	tcps->tcps_acceptor_fanout = NULL;
18957 
18958 	mutex_destroy(&tcps->tcps_iss_key_lock);
18959 	mutex_destroy(&tcps->tcps_epriv_port_lock);
18960 
18961 	ip_drop_unregister(&tcps->tcps_dropper);
18962 
18963 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
18964 	tcps->tcps_kstat = NULL;
18965 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
18966 
18967 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
18968 	tcps->tcps_mibkp = NULL;
18969 
18970 	ldi_ident_release(tcps->tcps_ldi_ident);
18971 	kmem_free(tcps, sizeof (*tcps));
18972 }
18973 
18974 /*
18975  * Generate ISS, taking into account NDD changes may happen halfway through.
18976  * (If the iss is not zero, set it.)
18977  */
18978 
18979 static void
18980 tcp_iss_init(tcp_t *tcp)
18981 {
18982 	MD5_CTX context;
18983 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
18984 	uint32_t answer[4];
18985 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18986 	conn_t		*connp = tcp->tcp_connp;
18987 
18988 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
18989 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
18990 	switch (tcps->tcps_strong_iss) {
18991 	case 2:
18992 		mutex_enter(&tcps->tcps_iss_key_lock);
18993 		context = tcps->tcps_iss_key;
18994 		mutex_exit(&tcps->tcps_iss_key_lock);
18995 		arg.ports = connp->conn_ports;
18996 		arg.src = connp->conn_laddr_v6;
18997 		arg.dst = connp->conn_faddr_v6;
18998 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
18999 		MD5Final((uchar_t *)answer, &context);
19000 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
19001 		/*
19002 		 * Now that we've hashed into a unique per-connection sequence
19003 		 * space, add a random increment per strong_iss == 1.  So I
19004 		 * guess we'll have to...
19005 		 */
19006 		/* FALLTHRU */
19007 	case 1:
19008 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
19009 		break;
19010 	default:
19011 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
19012 		break;
19013 	}
19014 	tcp->tcp_valid_bits = TCP_ISS_VALID;
19015 	tcp->tcp_fss = tcp->tcp_iss - 1;
19016 	tcp->tcp_suna = tcp->tcp_iss;
19017 	tcp->tcp_snxt = tcp->tcp_iss + 1;
19018 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
19019 	tcp->tcp_csuna = tcp->tcp_snxt;
19020 }
19021 
19022 /*
19023  * Exported routine for extracting active tcp connection status.
19024  *
19025  * This is used by the Solaris Cluster Networking software to
19026  * gather a list of connections that need to be forwarded to
19027  * specific nodes in the cluster when configuration changes occur.
19028  *
19029  * The callback is invoked for each tcp_t structure from all netstacks,
19030  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
19031  * from the netstack with the specified stack_id. Returning
19032  * non-zero from the callback routine terminates the search.
19033  */
19034 int
19035 cl_tcp_walk_list(netstackid_t stack_id,
19036     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
19037 {
19038 	netstack_handle_t nh;
19039 	netstack_t *ns;
19040 	int ret = 0;
19041 
19042 	if (stack_id >= 0) {
19043 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
19044 			return (EINVAL);
19045 
19046 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
19047 		    ns->netstack_tcp);
19048 		netstack_rele(ns);
19049 		return (ret);
19050 	}
19051 
19052 	netstack_next_init(&nh);
19053 	while ((ns = netstack_next(&nh)) != NULL) {
19054 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
19055 		    ns->netstack_tcp);
19056 		netstack_rele(ns);
19057 	}
19058 	netstack_next_fini(&nh);
19059 	return (ret);
19060 }
19061 
19062 static int
19063 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
19064     tcp_stack_t *tcps)
19065 {
19066 	tcp_t *tcp;
19067 	cl_tcp_info_t	cl_tcpi;
19068 	connf_t	*connfp;
19069 	conn_t	*connp;
19070 	int	i;
19071 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19072 
19073 	ASSERT(callback != NULL);
19074 
19075 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
19076 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
19077 		connp = NULL;
19078 
19079 		while ((connp =
19080 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
19081 
19082 			tcp = connp->conn_tcp;
19083 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
19084 			cl_tcpi.cl_tcpi_ipversion = connp->conn_ipversion;
19085 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
19086 			cl_tcpi.cl_tcpi_lport = connp->conn_lport;
19087 			cl_tcpi.cl_tcpi_fport = connp->conn_fport;
19088 			cl_tcpi.cl_tcpi_laddr_v6 = connp->conn_laddr_v6;
19089 			cl_tcpi.cl_tcpi_faddr_v6 = connp->conn_faddr_v6;
19090 
19091 			/*
19092 			 * If the callback returns non-zero
19093 			 * we terminate the traversal.
19094 			 */
19095 			if ((*callback)(&cl_tcpi, arg) != 0) {
19096 				CONN_DEC_REF(tcp->tcp_connp);
19097 				return (1);
19098 			}
19099 		}
19100 	}
19101 
19102 	return (0);
19103 }
19104 
19105 /*
19106  * Macros used for accessing the different types of sockaddr
19107  * structures inside a tcp_ioc_abort_conn_t.
19108  */
19109 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
19110 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
19111 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
19112 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
19113 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
19114 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
19115 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
19116 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
19117 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
19118 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
19119 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
19120 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
19121 
19122 /*
19123  * Return the correct error code to mimic the behavior
19124  * of a connection reset.
19125  */
19126 #define	TCP_AC_GET_ERRCODE(state, err) {	\
19127 		switch ((state)) {		\
19128 		case TCPS_SYN_SENT:		\
19129 		case TCPS_SYN_RCVD:		\
19130 			(err) = ECONNREFUSED;	\
19131 			break;			\
19132 		case TCPS_ESTABLISHED:		\
19133 		case TCPS_FIN_WAIT_1:		\
19134 		case TCPS_FIN_WAIT_2:		\
19135 		case TCPS_CLOSE_WAIT:		\
19136 			(err) = ECONNRESET;	\
19137 			break;			\
19138 		case TCPS_CLOSING:		\
19139 		case TCPS_LAST_ACK:		\
19140 		case TCPS_TIME_WAIT:		\
19141 			(err) = 0;		\
19142 			break;			\
19143 		default:			\
19144 			(err) = ENXIO;		\
19145 		}				\
19146 	}
19147 
19148 /*
19149  * Check if a tcp structure matches the info in acp.
19150  */
19151 #define	TCP_AC_ADDR_MATCH(acp, connp, tcp)			\
19152 	(((acp)->ac_local.ss_family == AF_INET) ?		\
19153 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
19154 	TCP_AC_V4LOCAL((acp)) == (connp)->conn_laddr_v4) &&	\
19155 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
19156 	TCP_AC_V4REMOTE((acp)) == (connp)->conn_faddr_v4) &&	\
19157 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
19158 	TCP_AC_V4LPORT((acp)) == (connp)->conn_lport) &&	\
19159 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
19160 	TCP_AC_V4RPORT((acp)) == (connp)->conn_fport) &&	\
19161 	(acp)->ac_start <= (tcp)->tcp_state &&			\
19162 	(acp)->ac_end >= (tcp)->tcp_state) :			\
19163 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
19164 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
19165 	&(connp)->conn_laddr_v6)) &&				\
19166 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
19167 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
19168 	&(connp)->conn_faddr_v6)) &&				\
19169 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
19170 	TCP_AC_V6LPORT((acp)) == (connp)->conn_lport) &&	\
19171 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
19172 	TCP_AC_V6RPORT((acp)) == (connp)->conn_fport) &&	\
19173 	(acp)->ac_start <= (tcp)->tcp_state &&			\
19174 	(acp)->ac_end >= (tcp)->tcp_state))
19175 
19176 #define	TCP_AC_MATCH(acp, connp, tcp)				\
19177 	(((acp)->ac_zoneid == ALL_ZONES ||			\
19178 	(acp)->ac_zoneid == (connp)->conn_zoneid) ?		\
19179 	TCP_AC_ADDR_MATCH(acp, connp, tcp) : 0)
19180 
19181 /*
19182  * Build a message containing a tcp_ioc_abort_conn_t structure
19183  * which is filled in with information from acp and tp.
19184  */
19185 static mblk_t *
19186 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
19187 {
19188 	mblk_t *mp;
19189 	tcp_ioc_abort_conn_t *tacp;
19190 
19191 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
19192 	if (mp == NULL)
19193 		return (NULL);
19194 
19195 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
19196 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
19197 	    sizeof (uint32_t));
19198 
19199 	tacp->ac_start = acp->ac_start;
19200 	tacp->ac_end = acp->ac_end;
19201 	tacp->ac_zoneid = acp->ac_zoneid;
19202 
19203 	if (acp->ac_local.ss_family == AF_INET) {
19204 		tacp->ac_local.ss_family = AF_INET;
19205 		tacp->ac_remote.ss_family = AF_INET;
19206 		TCP_AC_V4LOCAL(tacp) = tp->tcp_connp->conn_laddr_v4;
19207 		TCP_AC_V4REMOTE(tacp) = tp->tcp_connp->conn_faddr_v4;
19208 		TCP_AC_V4LPORT(tacp) = tp->tcp_connp->conn_lport;
19209 		TCP_AC_V4RPORT(tacp) = tp->tcp_connp->conn_fport;
19210 	} else {
19211 		tacp->ac_local.ss_family = AF_INET6;
19212 		tacp->ac_remote.ss_family = AF_INET6;
19213 		TCP_AC_V6LOCAL(tacp) = tp->tcp_connp->conn_laddr_v6;
19214 		TCP_AC_V6REMOTE(tacp) = tp->tcp_connp->conn_faddr_v6;
19215 		TCP_AC_V6LPORT(tacp) = tp->tcp_connp->conn_lport;
19216 		TCP_AC_V6RPORT(tacp) = tp->tcp_connp->conn_fport;
19217 	}
19218 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
19219 	return (mp);
19220 }
19221 
19222 /*
19223  * Print a tcp_ioc_abort_conn_t structure.
19224  */
19225 static void
19226 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
19227 {
19228 	char lbuf[128];
19229 	char rbuf[128];
19230 	sa_family_t af;
19231 	in_port_t lport, rport;
19232 	ushort_t logflags;
19233 
19234 	af = acp->ac_local.ss_family;
19235 
19236 	if (af == AF_INET) {
19237 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
19238 		    lbuf, 128);
19239 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
19240 		    rbuf, 128);
19241 		lport = ntohs(TCP_AC_V4LPORT(acp));
19242 		rport = ntohs(TCP_AC_V4RPORT(acp));
19243 	} else {
19244 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
19245 		    lbuf, 128);
19246 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
19247 		    rbuf, 128);
19248 		lport = ntohs(TCP_AC_V6LPORT(acp));
19249 		rport = ntohs(TCP_AC_V6RPORT(acp));
19250 	}
19251 
19252 	logflags = SL_TRACE | SL_NOTE;
19253 	/*
19254 	 * Don't print this message to the console if the operation was done
19255 	 * to a non-global zone.
19256 	 */
19257 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
19258 		logflags |= SL_CONSOLE;
19259 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
19260 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
19261 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
19262 	    acp->ac_start, acp->ac_end);
19263 }
19264 
19265 /*
19266  * Called using SQ_FILL when a message built using
19267  * tcp_ioctl_abort_build_msg is put into a queue.
19268  * Note that when we get here there is no wildcard in acp any more.
19269  */
19270 /* ARGSUSED2 */
19271 static void
19272 tcp_ioctl_abort_handler(void *arg, mblk_t *mp, void *arg2,
19273     ip_recv_attr_t *dummy)
19274 {
19275 	conn_t			*connp = (conn_t *)arg;
19276 	tcp_t			*tcp = connp->conn_tcp;
19277 	tcp_ioc_abort_conn_t	*acp;
19278 
19279 	/*
19280 	 * Don't accept any input on a closed tcp as this TCP logically does
19281 	 * not exist on the system. Don't proceed further with this TCP.
19282 	 * For eg. this packet could trigger another close of this tcp
19283 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
19284 	 * tcp_clean_death / tcp_closei_local must be called at most once
19285 	 * on a TCP.
19286 	 */
19287 	if (tcp->tcp_state == TCPS_CLOSED ||
19288 	    tcp->tcp_state == TCPS_BOUND) {
19289 		freemsg(mp);
19290 		return;
19291 	}
19292 
19293 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
19294 	if (tcp->tcp_state <= acp->ac_end) {
19295 		/*
19296 		 * If we get here, we are already on the correct
19297 		 * squeue. This ioctl follows the following path
19298 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
19299 		 * ->tcp_ioctl_abort->squeue_enter (if on a
19300 		 * different squeue)
19301 		 */
19302 		int errcode;
19303 
19304 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
19305 		(void) tcp_clean_death(tcp, errcode, 26);
19306 	}
19307 	freemsg(mp);
19308 }
19309 
19310 /*
19311  * Abort all matching connections on a hash chain.
19312  */
19313 static int
19314 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
19315     boolean_t exact, tcp_stack_t *tcps)
19316 {
19317 	int nmatch, err = 0;
19318 	tcp_t *tcp;
19319 	MBLKP mp, last, listhead = NULL;
19320 	conn_t	*tconnp;
19321 	connf_t	*connfp;
19322 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
19323 
19324 	connfp = &ipst->ips_ipcl_conn_fanout[index];
19325 
19326 startover:
19327 	nmatch = 0;
19328 
19329 	mutex_enter(&connfp->connf_lock);
19330 	for (tconnp = connfp->connf_head; tconnp != NULL;
19331 	    tconnp = tconnp->conn_next) {
19332 		tcp = tconnp->conn_tcp;
19333 		/*
19334 		 * We are missing a check on sin6_scope_id for linklocals here,
19335 		 * but current usage is just for aborting based on zoneid
19336 		 * for shared-IP zones.
19337 		 */
19338 		if (TCP_AC_MATCH(acp, tconnp, tcp)) {
19339 			CONN_INC_REF(tconnp);
19340 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
19341 			if (mp == NULL) {
19342 				err = ENOMEM;
19343 				CONN_DEC_REF(tconnp);
19344 				break;
19345 			}
19346 			mp->b_prev = (mblk_t *)tcp;
19347 
19348 			if (listhead == NULL) {
19349 				listhead = mp;
19350 				last = mp;
19351 			} else {
19352 				last->b_next = mp;
19353 				last = mp;
19354 			}
19355 			nmatch++;
19356 			if (exact)
19357 				break;
19358 		}
19359 
19360 		/* Avoid holding lock for too long. */
19361 		if (nmatch >= 500)
19362 			break;
19363 	}
19364 	mutex_exit(&connfp->connf_lock);
19365 
19366 	/* Pass mp into the correct tcp */
19367 	while ((mp = listhead) != NULL) {
19368 		listhead = listhead->b_next;
19369 		tcp = (tcp_t *)mp->b_prev;
19370 		mp->b_next = mp->b_prev = NULL;
19371 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp,
19372 		    tcp_ioctl_abort_handler, tcp->tcp_connp, NULL,
19373 		    SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
19374 	}
19375 
19376 	*count += nmatch;
19377 	if (nmatch >= 500 && err == 0)
19378 		goto startover;
19379 	return (err);
19380 }
19381 
19382 /*
19383  * Abort all connections that matches the attributes specified in acp.
19384  */
19385 static int
19386 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
19387 {
19388 	sa_family_t af;
19389 	uint32_t  ports;
19390 	uint16_t *pports;
19391 	int err = 0, count = 0;
19392 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
19393 	int index = -1;
19394 	ushort_t logflags;
19395 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19396 
19397 	af = acp->ac_local.ss_family;
19398 
19399 	if (af == AF_INET) {
19400 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
19401 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
19402 			pports = (uint16_t *)&ports;
19403 			pports[1] = TCP_AC_V4LPORT(acp);
19404 			pports[0] = TCP_AC_V4RPORT(acp);
19405 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
19406 		}
19407 	} else {
19408 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
19409 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
19410 			pports = (uint16_t *)&ports;
19411 			pports[1] = TCP_AC_V6LPORT(acp);
19412 			pports[0] = TCP_AC_V6RPORT(acp);
19413 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
19414 		}
19415 	}
19416 
19417 	/*
19418 	 * For cases where remote addr, local port, and remote port are non-
19419 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
19420 	 */
19421 	if (index != -1) {
19422 		err = tcp_ioctl_abort_bucket(acp, index,
19423 		    &count, exact, tcps);
19424 	} else {
19425 		/*
19426 		 * loop through all entries for wildcard case
19427 		 */
19428 		for (index = 0;
19429 		    index < ipst->ips_ipcl_conn_fanout_size;
19430 		    index++) {
19431 			err = tcp_ioctl_abort_bucket(acp, index,
19432 			    &count, exact, tcps);
19433 			if (err != 0)
19434 				break;
19435 		}
19436 	}
19437 
19438 	logflags = SL_TRACE | SL_NOTE;
19439 	/*
19440 	 * Don't print this message to the console if the operation was done
19441 	 * to a non-global zone.
19442 	 */
19443 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
19444 		logflags |= SL_CONSOLE;
19445 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
19446 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
19447 	if (err == 0 && count == 0)
19448 		err = ENOENT;
19449 	return (err);
19450 }
19451 
19452 /*
19453  * Process the TCP_IOC_ABORT_CONN ioctl request.
19454  */
19455 static void
19456 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
19457 {
19458 	int	err;
19459 	IOCP    iocp;
19460 	MBLKP   mp1;
19461 	sa_family_t laf, raf;
19462 	tcp_ioc_abort_conn_t *acp;
19463 	zone_t		*zptr;
19464 	conn_t		*connp = Q_TO_CONN(q);
19465 	zoneid_t	zoneid = connp->conn_zoneid;
19466 	tcp_t		*tcp = connp->conn_tcp;
19467 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19468 
19469 	iocp = (IOCP)mp->b_rptr;
19470 
19471 	if ((mp1 = mp->b_cont) == NULL ||
19472 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
19473 		err = EINVAL;
19474 		goto out;
19475 	}
19476 
19477 	/* check permissions */
19478 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
19479 		err = EPERM;
19480 		goto out;
19481 	}
19482 
19483 	if (mp1->b_cont != NULL) {
19484 		freemsg(mp1->b_cont);
19485 		mp1->b_cont = NULL;
19486 	}
19487 
19488 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
19489 	laf = acp->ac_local.ss_family;
19490 	raf = acp->ac_remote.ss_family;
19491 
19492 	/* check that a zone with the supplied zoneid exists */
19493 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
19494 		zptr = zone_find_by_id(zoneid);
19495 		if (zptr != NULL) {
19496 			zone_rele(zptr);
19497 		} else {
19498 			err = EINVAL;
19499 			goto out;
19500 		}
19501 	}
19502 
19503 	/*
19504 	 * For exclusive stacks we set the zoneid to zero
19505 	 * to make TCP operate as if in the global zone.
19506 	 */
19507 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
19508 		acp->ac_zoneid = GLOBAL_ZONEID;
19509 
19510 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
19511 	    acp->ac_start > acp->ac_end || laf != raf ||
19512 	    (laf != AF_INET && laf != AF_INET6)) {
19513 		err = EINVAL;
19514 		goto out;
19515 	}
19516 
19517 	tcp_ioctl_abort_dump(acp);
19518 	err = tcp_ioctl_abort(acp, tcps);
19519 
19520 out:
19521 	if (mp1 != NULL) {
19522 		freemsg(mp1);
19523 		mp->b_cont = NULL;
19524 	}
19525 
19526 	if (err != 0)
19527 		miocnak(q, mp, 0, err);
19528 	else
19529 		miocack(q, mp, 0, 0);
19530 }
19531 
19532 /*
19533  * tcp_time_wait_processing() handles processing of incoming packets when
19534  * the tcp is in the TIME_WAIT state.
19535  * A TIME_WAIT tcp that has an associated open TCP stream is never put
19536  * on the time wait list.
19537  */
19538 void
19539 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
19540     uint32_t seg_ack, int seg_len, tcpha_t *tcpha, ip_recv_attr_t *ira)
19541 {
19542 	int32_t		bytes_acked;
19543 	int32_t		gap;
19544 	int32_t		rgap;
19545 	tcp_opt_t	tcpopt;
19546 	uint_t		flags;
19547 	uint32_t	new_swnd = 0;
19548 	conn_t		*nconnp;
19549 	conn_t		*connp = tcp->tcp_connp;
19550 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19551 
19552 	BUMP_LOCAL(tcp->tcp_ibsegs);
19553 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
19554 
19555 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
19556 	new_swnd = ntohs(tcpha->tha_win) <<
19557 	    ((tcpha->tha_flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
19558 	if (tcp->tcp_snd_ts_ok) {
19559 		if (!tcp_paws_check(tcp, tcpha, &tcpopt)) {
19560 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19561 			    tcp->tcp_rnxt, TH_ACK);
19562 			goto done;
19563 		}
19564 	}
19565 	gap = seg_seq - tcp->tcp_rnxt;
19566 	rgap = tcp->tcp_rwnd - (gap + seg_len);
19567 	if (gap < 0) {
19568 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
19569 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
19570 		    (seg_len > -gap ? -gap : seg_len));
19571 		seg_len += gap;
19572 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
19573 			if (flags & TH_RST) {
19574 				goto done;
19575 			}
19576 			if ((flags & TH_FIN) && seg_len == -1) {
19577 				/*
19578 				 * When TCP receives a duplicate FIN in
19579 				 * TIME_WAIT state, restart the 2 MSL timer.
19580 				 * See page 73 in RFC 793. Make sure this TCP
19581 				 * is already on the TIME_WAIT list. If not,
19582 				 * just restart the timer.
19583 				 */
19584 				if (TCP_IS_DETACHED(tcp)) {
19585 					if (tcp_time_wait_remove(tcp, NULL) ==
19586 					    B_TRUE) {
19587 						tcp_time_wait_append(tcp);
19588 						TCP_DBGSTAT(tcps,
19589 						    tcp_rput_time_wait);
19590 					}
19591 				} else {
19592 					ASSERT(tcp != NULL);
19593 					TCP_TIMER_RESTART(tcp,
19594 					    tcps->tcps_time_wait_interval);
19595 				}
19596 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19597 				    tcp->tcp_rnxt, TH_ACK);
19598 				goto done;
19599 			}
19600 			flags |=  TH_ACK_NEEDED;
19601 			seg_len = 0;
19602 			goto process_ack;
19603 		}
19604 
19605 		/* Fix seg_seq, and chew the gap off the front. */
19606 		seg_seq = tcp->tcp_rnxt;
19607 	}
19608 
19609 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
19610 		/*
19611 		 * Make sure that when we accept the connection, pick
19612 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
19613 		 * old connection.
19614 		 *
19615 		 * The next ISS generated is equal to tcp_iss_incr_extra
19616 		 * + ISS_INCR/2 + other components depending on the
19617 		 * value of tcp_strong_iss.  We pre-calculate the new
19618 		 * ISS here and compare with tcp_snxt to determine if
19619 		 * we need to make adjustment to tcp_iss_incr_extra.
19620 		 *
19621 		 * The above calculation is ugly and is a
19622 		 * waste of CPU cycles...
19623 		 */
19624 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
19625 		int32_t adj;
19626 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
19627 
19628 		switch (tcps->tcps_strong_iss) {
19629 		case 2: {
19630 			/* Add time and MD5 components. */
19631 			uint32_t answer[4];
19632 			struct {
19633 				uint32_t ports;
19634 				in6_addr_t src;
19635 				in6_addr_t dst;
19636 			} arg;
19637 			MD5_CTX context;
19638 
19639 			mutex_enter(&tcps->tcps_iss_key_lock);
19640 			context = tcps->tcps_iss_key;
19641 			mutex_exit(&tcps->tcps_iss_key_lock);
19642 			arg.ports = connp->conn_ports;
19643 			/* We use MAPPED addresses in tcp_iss_init */
19644 			arg.src = connp->conn_laddr_v6;
19645 			arg.dst = connp->conn_faddr_v6;
19646 			MD5Update(&context, (uchar_t *)&arg,
19647 			    sizeof (arg));
19648 			MD5Final((uchar_t *)answer, &context);
19649 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
19650 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
19651 			break;
19652 		}
19653 		case 1:
19654 			/* Add time component and min random (i.e. 1). */
19655 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
19656 			break;
19657 		default:
19658 			/* Add only time component. */
19659 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
19660 			break;
19661 		}
19662 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
19663 			/*
19664 			 * New ISS not guaranteed to be ISS_INCR/2
19665 			 * ahead of the current tcp_snxt, so add the
19666 			 * difference to tcp_iss_incr_extra.
19667 			 */
19668 			tcps->tcps_iss_incr_extra += adj;
19669 		}
19670 		/*
19671 		 * If tcp_clean_death() can not perform the task now,
19672 		 * drop the SYN packet and let the other side re-xmit.
19673 		 * Otherwise pass the SYN packet back in, since the
19674 		 * old tcp state has been cleaned up or freed.
19675 		 */
19676 		if (tcp_clean_death(tcp, 0, 27) == -1)
19677 			goto done;
19678 		nconnp = ipcl_classify(mp, ira, ipst);
19679 		if (nconnp != NULL) {
19680 			TCP_STAT(tcps, tcp_time_wait_syn_success);
19681 			/* Drops ref on nconnp */
19682 			tcp_reinput(nconnp, mp, ira, ipst);
19683 			return;
19684 		}
19685 		goto done;
19686 	}
19687 
19688 	/*
19689 	 * rgap is the amount of stuff received out of window.  A negative
19690 	 * value is the amount out of window.
19691 	 */
19692 	if (rgap < 0) {
19693 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
19694 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
19695 		/* Fix seg_len and make sure there is something left. */
19696 		seg_len += rgap;
19697 		if (seg_len <= 0) {
19698 			if (flags & TH_RST) {
19699 				goto done;
19700 			}
19701 			flags |=  TH_ACK_NEEDED;
19702 			seg_len = 0;
19703 			goto process_ack;
19704 		}
19705 	}
19706 	/*
19707 	 * Check whether we can update tcp_ts_recent.  This test is
19708 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
19709 	 * Extensions for High Performance: An Update", Internet Draft.
19710 	 */
19711 	if (tcp->tcp_snd_ts_ok &&
19712 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
19713 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
19714 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
19715 		tcp->tcp_last_rcv_lbolt = ddi_get_lbolt64();
19716 	}
19717 
19718 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
19719 		/* Always ack out of order packets */
19720 		flags |= TH_ACK_NEEDED;
19721 		seg_len = 0;
19722 	} else if (seg_len > 0) {
19723 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
19724 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
19725 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
19726 	}
19727 	if (flags & TH_RST) {
19728 		(void) tcp_clean_death(tcp, 0, 28);
19729 		goto done;
19730 	}
19731 	if (flags & TH_SYN) {
19732 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
19733 		    TH_RST|TH_ACK);
19734 		/*
19735 		 * Do not delete the TCP structure if it is in
19736 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
19737 		 */
19738 		goto done;
19739 	}
19740 process_ack:
19741 	if (flags & TH_ACK) {
19742 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
19743 		if (bytes_acked <= 0) {
19744 			if (bytes_acked == 0 && seg_len == 0 &&
19745 			    new_swnd == tcp->tcp_swnd)
19746 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
19747 		} else {
19748 			/* Acks something not sent */
19749 			flags |= TH_ACK_NEEDED;
19750 		}
19751 	}
19752 	if (flags & TH_ACK_NEEDED) {
19753 		/*
19754 		 * Time to send an ack for some reason.
19755 		 */
19756 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19757 		    tcp->tcp_rnxt, TH_ACK);
19758 	}
19759 done:
19760 	freemsg(mp);
19761 }
19762 
19763 /*
19764  * TCP Timers Implementation.
19765  */
19766 timeout_id_t
19767 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
19768 {
19769 	mblk_t *mp;
19770 	tcp_timer_t *tcpt;
19771 	tcp_t *tcp = connp->conn_tcp;
19772 
19773 	ASSERT(connp->conn_sqp != NULL);
19774 
19775 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
19776 
19777 	if (tcp->tcp_timercache == NULL) {
19778 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
19779 	} else {
19780 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
19781 		mp = tcp->tcp_timercache;
19782 		tcp->tcp_timercache = mp->b_next;
19783 		mp->b_next = NULL;
19784 		ASSERT(mp->b_wptr == NULL);
19785 	}
19786 
19787 	CONN_INC_REF(connp);
19788 	tcpt = (tcp_timer_t *)mp->b_rptr;
19789 	tcpt->connp = connp;
19790 	tcpt->tcpt_proc = f;
19791 	/*
19792 	 * TCP timers are normal timeouts. Plus, they do not require more than
19793 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
19794 	 * rounding up the expiration to the next resolution boundary, we can
19795 	 * batch timers in the callout subsystem to make TCP timers more
19796 	 * efficient. The roundup also protects short timers from expiring too
19797 	 * early before they have a chance to be cancelled.
19798 	 */
19799 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
19800 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
19801 
19802 	return ((timeout_id_t)mp);
19803 }
19804 
19805 static void
19806 tcp_timer_callback(void *arg)
19807 {
19808 	mblk_t *mp = (mblk_t *)arg;
19809 	tcp_timer_t *tcpt;
19810 	conn_t	*connp;
19811 
19812 	tcpt = (tcp_timer_t *)mp->b_rptr;
19813 	connp = tcpt->connp;
19814 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
19815 	    NULL, SQ_FILL, SQTAG_TCP_TIMER);
19816 }
19817 
19818 /* ARGSUSED */
19819 static void
19820 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
19821 {
19822 	tcp_timer_t *tcpt;
19823 	conn_t *connp = (conn_t *)arg;
19824 	tcp_t *tcp = connp->conn_tcp;
19825 
19826 	tcpt = (tcp_timer_t *)mp->b_rptr;
19827 	ASSERT(connp == tcpt->connp);
19828 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
19829 
19830 	/*
19831 	 * If the TCP has reached the closed state, don't proceed any
19832 	 * further. This TCP logically does not exist on the system.
19833 	 * tcpt_proc could for example access queues, that have already
19834 	 * been qprocoff'ed off.
19835 	 */
19836 	if (tcp->tcp_state != TCPS_CLOSED) {
19837 		(*tcpt->tcpt_proc)(connp);
19838 	} else {
19839 		tcp->tcp_timer_tid = 0;
19840 	}
19841 	tcp_timer_free(connp->conn_tcp, mp);
19842 }
19843 
19844 /*
19845  * There is potential race with untimeout and the handler firing at the same
19846  * time. The mblock may be freed by the handler while we are trying to use
19847  * it. But since both should execute on the same squeue, this race should not
19848  * occur.
19849  */
19850 clock_t
19851 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
19852 {
19853 	mblk_t	*mp = (mblk_t *)id;
19854 	tcp_timer_t *tcpt;
19855 	clock_t delta;
19856 
19857 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
19858 
19859 	if (mp == NULL)
19860 		return (-1);
19861 
19862 	tcpt = (tcp_timer_t *)mp->b_rptr;
19863 	ASSERT(tcpt->connp == connp);
19864 
19865 	delta = untimeout_default(tcpt->tcpt_tid, 0);
19866 
19867 	if (delta >= 0) {
19868 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
19869 		tcp_timer_free(connp->conn_tcp, mp);
19870 		CONN_DEC_REF(connp);
19871 	}
19872 
19873 	return (delta);
19874 }
19875 
19876 /*
19877  * Allocate space for the timer event. The allocation looks like mblk, but it is
19878  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
19879  *
19880  * Dealing with failures: If we can't allocate from the timer cache we try
19881  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
19882  * points to b_rptr.
19883  * If we can't allocate anything using allocb_tryhard(), we perform a last
19884  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
19885  * save the actual allocation size in b_datap.
19886  */
19887 mblk_t *
19888 tcp_timermp_alloc(int kmflags)
19889 {
19890 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
19891 	    kmflags & ~KM_PANIC);
19892 
19893 	if (mp != NULL) {
19894 		mp->b_next = mp->b_prev = NULL;
19895 		mp->b_rptr = (uchar_t *)(&mp[1]);
19896 		mp->b_wptr = NULL;
19897 		mp->b_datap = NULL;
19898 		mp->b_queue = NULL;
19899 		mp->b_cont = NULL;
19900 	} else if (kmflags & KM_PANIC) {
19901 		/*
19902 		 * Failed to allocate memory for the timer. Try allocating from
19903 		 * dblock caches.
19904 		 */
19905 		/* ipclassifier calls this from a constructor - hence no tcps */
19906 		TCP_G_STAT(tcp_timermp_allocfail);
19907 		mp = allocb_tryhard(sizeof (tcp_timer_t));
19908 		if (mp == NULL) {
19909 			size_t size = 0;
19910 			/*
19911 			 * Memory is really low. Try tryhard allocation.
19912 			 *
19913 			 * ipclassifier calls this from a constructor -
19914 			 * hence no tcps
19915 			 */
19916 			TCP_G_STAT(tcp_timermp_allocdblfail);
19917 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
19918 			    sizeof (tcp_timer_t), &size, kmflags);
19919 			mp->b_rptr = (uchar_t *)(&mp[1]);
19920 			mp->b_next = mp->b_prev = NULL;
19921 			mp->b_wptr = (uchar_t *)-1;
19922 			mp->b_datap = (dblk_t *)size;
19923 			mp->b_queue = NULL;
19924 			mp->b_cont = NULL;
19925 		}
19926 		ASSERT(mp->b_wptr != NULL);
19927 	}
19928 	/* ipclassifier calls this from a constructor - hence no tcps */
19929 	TCP_G_DBGSTAT(tcp_timermp_alloced);
19930 
19931 	return (mp);
19932 }
19933 
19934 /*
19935  * Free per-tcp timer cache.
19936  * It can only contain entries from tcp_timercache.
19937  */
19938 void
19939 tcp_timermp_free(tcp_t *tcp)
19940 {
19941 	mblk_t *mp;
19942 
19943 	while ((mp = tcp->tcp_timercache) != NULL) {
19944 		ASSERT(mp->b_wptr == NULL);
19945 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
19946 		kmem_cache_free(tcp_timercache, mp);
19947 	}
19948 }
19949 
19950 /*
19951  * Free timer event. Put it on the per-tcp timer cache if there is not too many
19952  * events there already (currently at most two events are cached).
19953  * If the event is not allocated from the timer cache, free it right away.
19954  */
19955 static void
19956 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
19957 {
19958 	mblk_t *mp1 = tcp->tcp_timercache;
19959 
19960 	if (mp->b_wptr != NULL) {
19961 		/*
19962 		 * This allocation is not from a timer cache, free it right
19963 		 * away.
19964 		 */
19965 		if (mp->b_wptr != (uchar_t *)-1)
19966 			freeb(mp);
19967 		else
19968 			kmem_free(mp, (size_t)mp->b_datap);
19969 	} else if (mp1 == NULL || mp1->b_next == NULL) {
19970 		/* Cache this timer block for future allocations */
19971 		mp->b_rptr = (uchar_t *)(&mp[1]);
19972 		mp->b_next = mp1;
19973 		tcp->tcp_timercache = mp;
19974 	} else {
19975 		kmem_cache_free(tcp_timercache, mp);
19976 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
19977 	}
19978 }
19979 
19980 /*
19981  * End of TCP Timers implementation.
19982  */
19983 
19984 /*
19985  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
19986  * on the specified backing STREAMS q. Note, the caller may make the
19987  * decision to call based on the tcp_t.tcp_flow_stopped value which
19988  * when check outside the q's lock is only an advisory check ...
19989  */
19990 void
19991 tcp_setqfull(tcp_t *tcp)
19992 {
19993 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19994 	conn_t	*connp = tcp->tcp_connp;
19995 
19996 	if (tcp->tcp_closed)
19997 		return;
19998 
19999 	conn_setqfull(connp, &tcp->tcp_flow_stopped);
20000 	if (tcp->tcp_flow_stopped)
20001 		TCP_STAT(tcps, tcp_flwctl_on);
20002 }
20003 
20004 void
20005 tcp_clrqfull(tcp_t *tcp)
20006 {
20007 	conn_t  *connp = tcp->tcp_connp;
20008 
20009 	if (tcp->tcp_closed)
20010 		return;
20011 	conn_clrqfull(connp, &tcp->tcp_flow_stopped);
20012 }
20013 
20014 /*
20015  * kstats related to squeues i.e. not per IP instance
20016  */
20017 static void *
20018 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
20019 {
20020 	kstat_t *ksp;
20021 
20022 	tcp_g_stat_t template = {
20023 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
20024 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
20025 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
20026 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
20027 	};
20028 
20029 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
20030 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
20031 	    KSTAT_FLAG_VIRTUAL);
20032 
20033 	if (ksp == NULL)
20034 		return (NULL);
20035 
20036 	bcopy(&template, tcp_g_statp, sizeof (template));
20037 	ksp->ks_data = (void *)tcp_g_statp;
20038 
20039 	kstat_install(ksp);
20040 	return (ksp);
20041 }
20042 
20043 static void
20044 tcp_g_kstat_fini(kstat_t *ksp)
20045 {
20046 	if (ksp != NULL) {
20047 		kstat_delete(ksp);
20048 	}
20049 }
20050 
20051 
20052 static void *
20053 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
20054 {
20055 	kstat_t *ksp;
20056 
20057 	tcp_stat_t template = {
20058 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
20059 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
20060 		{ "tcp_time_wait_syn_success",	KSTAT_DATA_UINT64 },
20061 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
20062 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
20063 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
20064 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
20065 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
20066 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
20067 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
20068 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
20069 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
20070 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
20071 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
20072 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
20073 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
20074 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
20075 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
20076 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
20077 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
20078 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
20079 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
20080 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
20081 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
20082 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
20083 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
20084 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
20085 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
20086 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
20087 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
20088 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
20089 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
20090 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
20091 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
20092 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
20093 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
20094 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
20095 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
20096 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
20097 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
20098 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
20099 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
20100 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
20101 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
20102 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
20103 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
20104 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
20105 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
20106 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
20107 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
20108 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
20109 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
20110 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
20111 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
20112 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
20113 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
20114 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
20115 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
20116 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
20117 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
20118 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
20119 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
20120 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
20121 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
20122 		{ "tcp_listen_cnt_drop",	KSTAT_DATA_UINT64 },
20123 		{ "tcp_listen_mem_drop",	KSTAT_DATA_UINT64 },
20124 		{ "tcp_zwin_ack_syn",		KSTAT_DATA_UINT64 },
20125 		{ "tcp_rst_unsent",		KSTAT_DATA_UINT64 }
20126 	};
20127 
20128 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
20129 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
20130 	    KSTAT_FLAG_VIRTUAL, stackid);
20131 
20132 	if (ksp == NULL)
20133 		return (NULL);
20134 
20135 	bcopy(&template, tcps_statisticsp, sizeof (template));
20136 	ksp->ks_data = (void *)tcps_statisticsp;
20137 	ksp->ks_private = (void *)(uintptr_t)stackid;
20138 
20139 	kstat_install(ksp);
20140 	return (ksp);
20141 }
20142 
20143 static void
20144 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
20145 {
20146 	if (ksp != NULL) {
20147 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
20148 		kstat_delete_netstack(ksp, stackid);
20149 	}
20150 }
20151 
20152 /*
20153  * TCP Kstats implementation
20154  */
20155 static void *
20156 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
20157 {
20158 	kstat_t	*ksp;
20159 
20160 	tcp_named_kstat_t template = {
20161 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
20162 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
20163 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
20164 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
20165 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
20166 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
20167 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
20168 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
20169 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
20170 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
20171 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
20172 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
20173 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
20174 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
20175 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
20176 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
20177 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
20178 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
20179 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
20180 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
20181 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
20182 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
20183 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
20184 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
20185 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
20186 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
20187 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
20188 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
20189 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
20190 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
20191 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
20192 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
20193 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
20194 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
20195 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
20196 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
20197 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
20198 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
20199 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
20200 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
20201 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
20202 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
20203 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
20204 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
20205 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
20206 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
20207 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
20208 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
20209 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
20210 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
20211 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
20212 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
20213 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
20214 	};
20215 
20216 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
20217 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
20218 
20219 	if (ksp == NULL)
20220 		return (NULL);
20221 
20222 	template.rtoAlgorithm.value.ui32 = 4;
20223 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
20224 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
20225 	template.maxConn.value.i32 = -1;
20226 
20227 	bcopy(&template, ksp->ks_data, sizeof (template));
20228 	ksp->ks_update = tcp_kstat_update;
20229 	ksp->ks_private = (void *)(uintptr_t)stackid;
20230 
20231 	kstat_install(ksp);
20232 	return (ksp);
20233 }
20234 
20235 static void
20236 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
20237 {
20238 	if (ksp != NULL) {
20239 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
20240 		kstat_delete_netstack(ksp, stackid);
20241 	}
20242 }
20243 
20244 static int
20245 tcp_kstat_update(kstat_t *kp, int rw)
20246 {
20247 	tcp_named_kstat_t *tcpkp;
20248 	tcp_t		*tcp;
20249 	connf_t		*connfp;
20250 	conn_t		*connp;
20251 	int 		i;
20252 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
20253 	netstack_t	*ns;
20254 	tcp_stack_t	*tcps;
20255 	ip_stack_t	*ipst;
20256 
20257 	if ((kp == NULL) || (kp->ks_data == NULL))
20258 		return (EIO);
20259 
20260 	if (rw == KSTAT_WRITE)
20261 		return (EACCES);
20262 
20263 	ns = netstack_find_by_stackid(stackid);
20264 	if (ns == NULL)
20265 		return (-1);
20266 	tcps = ns->netstack_tcp;
20267 	if (tcps == NULL) {
20268 		netstack_rele(ns);
20269 		return (-1);
20270 	}
20271 
20272 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
20273 
20274 	tcpkp->currEstab.value.ui32 = 0;
20275 
20276 	ipst = ns->netstack_ip;
20277 
20278 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
20279 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
20280 		connp = NULL;
20281 		while ((connp =
20282 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
20283 			tcp = connp->conn_tcp;
20284 			switch (tcp_snmp_state(tcp)) {
20285 			case MIB2_TCP_established:
20286 			case MIB2_TCP_closeWait:
20287 				tcpkp->currEstab.value.ui32++;
20288 				break;
20289 			}
20290 		}
20291 	}
20292 
20293 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
20294 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
20295 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
20296 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
20297 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
20298 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
20299 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
20300 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
20301 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
20302 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
20303 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
20304 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
20305 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
20306 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
20307 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
20308 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
20309 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
20310 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
20311 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
20312 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
20313 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
20314 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
20315 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
20316 	tcpkp->inDataInorderSegs.value.ui32 =
20317 	    tcps->tcps_mib.tcpInDataInorderSegs;
20318 	tcpkp->inDataInorderBytes.value.ui32 =
20319 	    tcps->tcps_mib.tcpInDataInorderBytes;
20320 	tcpkp->inDataUnorderSegs.value.ui32 =
20321 	    tcps->tcps_mib.tcpInDataUnorderSegs;
20322 	tcpkp->inDataUnorderBytes.value.ui32 =
20323 	    tcps->tcps_mib.tcpInDataUnorderBytes;
20324 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
20325 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
20326 	tcpkp->inDataPartDupSegs.value.ui32 =
20327 	    tcps->tcps_mib.tcpInDataPartDupSegs;
20328 	tcpkp->inDataPartDupBytes.value.ui32 =
20329 	    tcps->tcps_mib.tcpInDataPartDupBytes;
20330 	tcpkp->inDataPastWinSegs.value.ui32 =
20331 	    tcps->tcps_mib.tcpInDataPastWinSegs;
20332 	tcpkp->inDataPastWinBytes.value.ui32 =
20333 	    tcps->tcps_mib.tcpInDataPastWinBytes;
20334 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
20335 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
20336 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
20337 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
20338 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
20339 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
20340 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
20341 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
20342 	tcpkp->timKeepaliveProbe.value.ui32 =
20343 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
20344 	tcpkp->timKeepaliveDrop.value.ui32 =
20345 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
20346 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
20347 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
20348 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
20349 	tcpkp->outSackRetransSegs.value.ui32 =
20350 	    tcps->tcps_mib.tcpOutSackRetransSegs;
20351 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
20352 
20353 	netstack_rele(ns);
20354 	return (0);
20355 }
20356 
20357 static int
20358 tcp_squeue_switch(int val)
20359 {
20360 	int rval = SQ_FILL;
20361 
20362 	switch (val) {
20363 	case 1:
20364 		rval = SQ_NODRAIN;
20365 		break;
20366 	case 2:
20367 		rval = SQ_PROCESS;
20368 		break;
20369 	default:
20370 		break;
20371 	}
20372 	return (rval);
20373 }
20374 
20375 /*
20376  * This is called once for each squeue - globally for all stack
20377  * instances.
20378  */
20379 static void
20380 tcp_squeue_add(squeue_t *sqp)
20381 {
20382 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
20383 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
20384 
20385 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
20386 	tcp_time_wait->tcp_time_wait_tid =
20387 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
20388 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
20389 	    CALLOUT_FLAG_ROUNDUP);
20390 	if (tcp_free_list_max_cnt == 0) {
20391 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
20392 		    max_ncpus : boot_max_ncpus);
20393 
20394 		/*
20395 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
20396 		 */
20397 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
20398 		    (tcp_ncpus * sizeof (tcp_t) * 100);
20399 	}
20400 	tcp_time_wait->tcp_free_list_cnt = 0;
20401 }
20402 
20403 /*
20404  * On a labeled system we have some protocols above TCP, such as RPC, which
20405  * appear to assume that every mblk in a chain has a db_credp.
20406  */
20407 static void
20408 tcp_setcred_data(mblk_t *mp, ip_recv_attr_t *ira)
20409 {
20410 	ASSERT(is_system_labeled());
20411 	ASSERT(ira->ira_cred != NULL);
20412 
20413 	while (mp != NULL) {
20414 		mblk_setcred(mp, ira->ira_cred, NOPID);
20415 		mp = mp->b_cont;
20416 	}
20417 }
20418 
20419 static int
20420 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
20421     boolean_t bind_to_req_port_only, cred_t *cr)
20422 {
20423 	in_port_t	mlp_port;
20424 	mlp_type_t 	addrtype, mlptype;
20425 	boolean_t	user_specified;
20426 	in_port_t	allocated_port;
20427 	in_port_t	requested_port = *requested_port_ptr;
20428 	conn_t		*connp = tcp->tcp_connp;
20429 	zone_t		*zone;
20430 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20431 	in6_addr_t	v6addr = connp->conn_laddr_v6;
20432 
20433 	/*
20434 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
20435 	 */
20436 	ASSERT(cr != NULL);
20437 
20438 	/*
20439 	 * Get a valid port (within the anonymous range and should not
20440 	 * be a privileged one) to use if the user has not given a port.
20441 	 * If multiple threads are here, they may all start with
20442 	 * with the same initial port. But, it should be fine as long as
20443 	 * tcp_bindi will ensure that no two threads will be assigned
20444 	 * the same port.
20445 	 *
20446 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
20447 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
20448 	 * unless TCP_ANONPRIVBIND option is set.
20449 	 */
20450 	mlptype = mlptSingle;
20451 	mlp_port = requested_port;
20452 	if (requested_port == 0) {
20453 		requested_port = connp->conn_anon_priv_bind ?
20454 		    tcp_get_next_priv_port(tcp) :
20455 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
20456 		    tcp, B_TRUE);
20457 		if (requested_port == 0) {
20458 			return (-TNOADDR);
20459 		}
20460 		user_specified = B_FALSE;
20461 
20462 		/*
20463 		 * If the user went through one of the RPC interfaces to create
20464 		 * this socket and RPC is MLP in this zone, then give him an
20465 		 * anonymous MLP.
20466 		 */
20467 		if (connp->conn_anon_mlp && is_system_labeled()) {
20468 			zone = crgetzone(cr);
20469 			addrtype = tsol_mlp_addr_type(
20470 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
20471 			    IPV6_VERSION, &v6addr,
20472 			    tcps->tcps_netstack->netstack_ip);
20473 			if (addrtype == mlptSingle) {
20474 				return (-TNOADDR);
20475 			}
20476 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
20477 			    PMAPPORT, addrtype);
20478 			mlp_port = PMAPPORT;
20479 		}
20480 	} else {
20481 		int i;
20482 		boolean_t priv = B_FALSE;
20483 
20484 		/*
20485 		 * If the requested_port is in the well-known privileged range,
20486 		 * verify that the stream was opened by a privileged user.
20487 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
20488 		 * but instead the code relies on:
20489 		 * - the fact that the address of the array and its size never
20490 		 *   changes
20491 		 * - the atomic assignment of the elements of the array
20492 		 */
20493 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
20494 			priv = B_TRUE;
20495 		} else {
20496 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
20497 				if (requested_port ==
20498 				    tcps->tcps_g_epriv_ports[i]) {
20499 					priv = B_TRUE;
20500 					break;
20501 				}
20502 			}
20503 		}
20504 		if (priv) {
20505 			if (secpolicy_net_privaddr(cr, requested_port,
20506 			    IPPROTO_TCP) != 0) {
20507 				if (connp->conn_debug) {
20508 					(void) strlog(TCP_MOD_ID, 0, 1,
20509 					    SL_ERROR|SL_TRACE,
20510 					    "tcp_bind: no priv for port %d",
20511 					    requested_port);
20512 				}
20513 				return (-TACCES);
20514 			}
20515 		}
20516 		user_specified = B_TRUE;
20517 
20518 		connp = tcp->tcp_connp;
20519 		if (is_system_labeled()) {
20520 			zone = crgetzone(cr);
20521 			addrtype = tsol_mlp_addr_type(
20522 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
20523 			    IPV6_VERSION, &v6addr,
20524 			    tcps->tcps_netstack->netstack_ip);
20525 			if (addrtype == mlptSingle) {
20526 				return (-TNOADDR);
20527 			}
20528 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
20529 			    requested_port, addrtype);
20530 		}
20531 	}
20532 
20533 	if (mlptype != mlptSingle) {
20534 		if (secpolicy_net_bindmlp(cr) != 0) {
20535 			if (connp->conn_debug) {
20536 				(void) strlog(TCP_MOD_ID, 0, 1,
20537 				    SL_ERROR|SL_TRACE,
20538 				    "tcp_bind: no priv for multilevel port %d",
20539 				    requested_port);
20540 			}
20541 			return (-TACCES);
20542 		}
20543 
20544 		/*
20545 		 * If we're specifically binding a shared IP address and the
20546 		 * port is MLP on shared addresses, then check to see if this
20547 		 * zone actually owns the MLP.  Reject if not.
20548 		 */
20549 		if (mlptype == mlptShared && addrtype == mlptShared) {
20550 			/*
20551 			 * No need to handle exclusive-stack zones since
20552 			 * ALL_ZONES only applies to the shared stack.
20553 			 */
20554 			zoneid_t mlpzone;
20555 
20556 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
20557 			    htons(mlp_port));
20558 			if (connp->conn_zoneid != mlpzone) {
20559 				if (connp->conn_debug) {
20560 					(void) strlog(TCP_MOD_ID, 0, 1,
20561 					    SL_ERROR|SL_TRACE,
20562 					    "tcp_bind: attempt to bind port "
20563 					    "%d on shared addr in zone %d "
20564 					    "(should be %d)",
20565 					    mlp_port, connp->conn_zoneid,
20566 					    mlpzone);
20567 				}
20568 				return (-TACCES);
20569 			}
20570 		}
20571 
20572 		if (!user_specified) {
20573 			int err;
20574 			err = tsol_mlp_anon(zone, mlptype, connp->conn_proto,
20575 			    requested_port, B_TRUE);
20576 			if (err != 0) {
20577 				if (connp->conn_debug) {
20578 					(void) strlog(TCP_MOD_ID, 0, 1,
20579 					    SL_ERROR|SL_TRACE,
20580 					    "tcp_bind: cannot establish anon "
20581 					    "MLP for port %d",
20582 					    requested_port);
20583 				}
20584 				return (err);
20585 			}
20586 			connp->conn_anon_port = B_TRUE;
20587 		}
20588 		connp->conn_mlp_type = mlptype;
20589 	}
20590 
20591 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
20592 	    connp->conn_reuseaddr, B_FALSE, bind_to_req_port_only,
20593 	    user_specified);
20594 
20595 	if (allocated_port == 0) {
20596 		connp->conn_mlp_type = mlptSingle;
20597 		if (connp->conn_anon_port) {
20598 			connp->conn_anon_port = B_FALSE;
20599 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_proto,
20600 			    requested_port, B_FALSE);
20601 		}
20602 		if (bind_to_req_port_only) {
20603 			if (connp->conn_debug) {
20604 				(void) strlog(TCP_MOD_ID, 0, 1,
20605 				    SL_ERROR|SL_TRACE,
20606 				    "tcp_bind: requested addr busy");
20607 			}
20608 			return (-TADDRBUSY);
20609 		} else {
20610 			/* If we are out of ports, fail the bind. */
20611 			if (connp->conn_debug) {
20612 				(void) strlog(TCP_MOD_ID, 0, 1,
20613 				    SL_ERROR|SL_TRACE,
20614 				    "tcp_bind: out of ports?");
20615 			}
20616 			return (-TNOADDR);
20617 		}
20618 	}
20619 
20620 	/* Pass the allocated port back */
20621 	*requested_port_ptr = allocated_port;
20622 	return (0);
20623 }
20624 
20625 /*
20626  * Check the address and check/pick a local port number.
20627  */
20628 static int
20629 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
20630     boolean_t bind_to_req_port_only)
20631 {
20632 	tcp_t	*tcp = connp->conn_tcp;
20633 	sin_t	*sin;
20634 	sin6_t  *sin6;
20635 	in_port_t	requested_port;
20636 	ipaddr_t	v4addr;
20637 	in6_addr_t	v6addr;
20638 	ip_laddr_t	laddr_type = IPVL_UNICAST_UP;	/* INADDR_ANY */
20639 	zoneid_t	zoneid = IPCL_ZONEID(connp);
20640 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
20641 	uint_t		scopeid = 0;
20642 	int		error = 0;
20643 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
20644 
20645 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
20646 
20647 	if (tcp->tcp_state == TCPS_BOUND) {
20648 		return (0);
20649 	} else if (tcp->tcp_state > TCPS_BOUND) {
20650 		if (connp->conn_debug) {
20651 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20652 			    "tcp_bind: bad state, %d", tcp->tcp_state);
20653 		}
20654 		return (-TOUTSTATE);
20655 	}
20656 
20657 	ASSERT(sa != NULL && len != 0);
20658 
20659 	if (!OK_32PTR((char *)sa)) {
20660 		if (connp->conn_debug) {
20661 			(void) strlog(TCP_MOD_ID, 0, 1,
20662 			    SL_ERROR|SL_TRACE,
20663 			    "tcp_bind: bad address parameter, "
20664 			    "address %p, len %d",
20665 			    (void *)sa, len);
20666 		}
20667 		return (-TPROTO);
20668 	}
20669 
20670 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
20671 	if (error != 0) {
20672 		return (error);
20673 	}
20674 
20675 	switch (len) {
20676 	case sizeof (sin_t):	/* Complete IPv4 address */
20677 		sin = (sin_t *)sa;
20678 		requested_port = ntohs(sin->sin_port);
20679 		v4addr = sin->sin_addr.s_addr;
20680 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
20681 		if (v4addr != INADDR_ANY) {
20682 			laddr_type = ip_laddr_verify_v4(v4addr, zoneid, ipst,
20683 			    B_FALSE);
20684 		}
20685 		break;
20686 
20687 	case sizeof (sin6_t): /* Complete IPv6 address */
20688 		sin6 = (sin6_t *)sa;
20689 		v6addr = sin6->sin6_addr;
20690 		requested_port = ntohs(sin6->sin6_port);
20691 		if (IN6_IS_ADDR_V4MAPPED(&v6addr)) {
20692 			if (connp->conn_ipv6_v6only)
20693 				return (EADDRNOTAVAIL);
20694 
20695 			IN6_V4MAPPED_TO_IPADDR(&v6addr, v4addr);
20696 			if (v4addr != INADDR_ANY) {
20697 				laddr_type = ip_laddr_verify_v4(v4addr,
20698 				    zoneid, ipst, B_FALSE);
20699 			}
20700 		} else {
20701 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6addr)) {
20702 				if (IN6_IS_ADDR_LINKSCOPE(&v6addr))
20703 					scopeid = sin6->sin6_scope_id;
20704 				laddr_type = ip_laddr_verify_v6(&v6addr,
20705 				    zoneid, ipst, B_FALSE, scopeid);
20706 			}
20707 		}
20708 		break;
20709 
20710 	default:
20711 		if (connp->conn_debug) {
20712 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20713 			    "tcp_bind: bad address length, %d", len);
20714 		}
20715 		return (EAFNOSUPPORT);
20716 		/* return (-TBADADDR); */
20717 	}
20718 
20719 	/* Is the local address a valid unicast address? */
20720 	if (laddr_type == IPVL_BAD)
20721 		return (EADDRNOTAVAIL);
20722 
20723 	connp->conn_bound_addr_v6 = v6addr;
20724 	if (scopeid != 0) {
20725 		ixa->ixa_flags |= IXAF_SCOPEID_SET;
20726 		ixa->ixa_scopeid = scopeid;
20727 		connp->conn_incoming_ifindex = scopeid;
20728 	} else {
20729 		ixa->ixa_flags &= ~IXAF_SCOPEID_SET;
20730 		connp->conn_incoming_ifindex = connp->conn_bound_if;
20731 	}
20732 
20733 	connp->conn_laddr_v6 = v6addr;
20734 	connp->conn_saddr_v6 = v6addr;
20735 
20736 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
20737 
20738 	error = tcp_bind_select_lport(tcp, &requested_port,
20739 	    bind_to_req_port_only, cr);
20740 	if (error != 0) {
20741 		connp->conn_laddr_v6 = ipv6_all_zeros;
20742 		connp->conn_saddr_v6 = ipv6_all_zeros;
20743 		connp->conn_bound_addr_v6 = ipv6_all_zeros;
20744 	}
20745 	return (error);
20746 }
20747 
20748 /*
20749  * Return unix error is tli error is TSYSERR, otherwise return a negative
20750  * tli error.
20751  */
20752 int
20753 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
20754     boolean_t bind_to_req_port_only)
20755 {
20756 	int error;
20757 	tcp_t *tcp = connp->conn_tcp;
20758 
20759 	if (tcp->tcp_state >= TCPS_BOUND) {
20760 		if (connp->conn_debug) {
20761 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20762 			    "tcp_bind: bad state, %d", tcp->tcp_state);
20763 		}
20764 		return (-TOUTSTATE);
20765 	}
20766 
20767 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
20768 	if (error != 0)
20769 		return (error);
20770 
20771 	ASSERT(tcp->tcp_state == TCPS_BOUND);
20772 	tcp->tcp_conn_req_max = 0;
20773 	return (0);
20774 }
20775 
20776 int
20777 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
20778     socklen_t len, cred_t *cr)
20779 {
20780 	int 		error;
20781 	conn_t		*connp = (conn_t *)proto_handle;
20782 	squeue_t	*sqp = connp->conn_sqp;
20783 
20784 	/* All Solaris components should pass a cred for this operation. */
20785 	ASSERT(cr != NULL);
20786 
20787 	ASSERT(sqp != NULL);
20788 	ASSERT(connp->conn_upper_handle != NULL);
20789 
20790 	error = squeue_synch_enter(sqp, connp, NULL);
20791 	if (error != 0) {
20792 		/* failed to enter */
20793 		return (ENOSR);
20794 	}
20795 
20796 	/* binding to a NULL address really means unbind */
20797 	if (sa == NULL) {
20798 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
20799 			error = tcp_do_unbind(connp);
20800 		else
20801 			error = EINVAL;
20802 	} else {
20803 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
20804 	}
20805 
20806 	squeue_synch_exit(sqp, connp);
20807 
20808 	if (error < 0) {
20809 		if (error == -TOUTSTATE)
20810 			error = EINVAL;
20811 		else
20812 			error = proto_tlitosyserr(-error);
20813 	}
20814 
20815 	return (error);
20816 }
20817 
20818 /*
20819  * If the return value from this function is positive, it's a UNIX error.
20820  * Otherwise, if it's negative, then the absolute value is a TLI error.
20821  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
20822  */
20823 int
20824 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
20825     cred_t *cr, pid_t pid)
20826 {
20827 	tcp_t		*tcp = connp->conn_tcp;
20828 	sin_t		*sin = (sin_t *)sa;
20829 	sin6_t		*sin6 = (sin6_t *)sa;
20830 	ipaddr_t	*dstaddrp;
20831 	in_port_t	dstport;
20832 	uint_t		srcid;
20833 	int		error;
20834 	uint32_t	mss;
20835 	mblk_t		*syn_mp;
20836 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20837 	int32_t		oldstate;
20838 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
20839 
20840 	oldstate = tcp->tcp_state;
20841 
20842 	switch (len) {
20843 	default:
20844 		/*
20845 		 * Should never happen
20846 		 */
20847 		return (EINVAL);
20848 
20849 	case sizeof (sin_t):
20850 		sin = (sin_t *)sa;
20851 		if (sin->sin_port == 0) {
20852 			return (-TBADADDR);
20853 		}
20854 		if (connp->conn_ipv6_v6only) {
20855 			return (EAFNOSUPPORT);
20856 		}
20857 		break;
20858 
20859 	case sizeof (sin6_t):
20860 		sin6 = (sin6_t *)sa;
20861 		if (sin6->sin6_port == 0) {
20862 			return (-TBADADDR);
20863 		}
20864 		break;
20865 	}
20866 	/*
20867 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
20868 	 * make sure that the conn_ipversion is IPV4_VERSION.  We
20869 	 * need to this before we call tcp_bindi() so that the port lookup
20870 	 * code will look for ports in the correct port space (IPv4 and
20871 	 * IPv6 have separate port spaces).
20872 	 */
20873 	if (connp->conn_family == AF_INET6 &&
20874 	    connp->conn_ipversion == IPV6_VERSION &&
20875 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
20876 		if (connp->conn_ipv6_v6only)
20877 			return (EADDRNOTAVAIL);
20878 
20879 		connp->conn_ipversion = IPV4_VERSION;
20880 	}
20881 
20882 	switch (tcp->tcp_state) {
20883 	case TCPS_LISTEN:
20884 		/*
20885 		 * Listening sockets are not allowed to issue connect().
20886 		 */
20887 		if (IPCL_IS_NONSTR(connp))
20888 			return (EOPNOTSUPP);
20889 		/* FALLTHRU */
20890 	case TCPS_IDLE:
20891 		/*
20892 		 * We support quick connect, refer to comments in
20893 		 * tcp_connect_*()
20894 		 */
20895 		/* FALLTHRU */
20896 	case TCPS_BOUND:
20897 		break;
20898 	default:
20899 		return (-TOUTSTATE);
20900 	}
20901 
20902 	/*
20903 	 * We update our cred/cpid based on the caller of connect
20904 	 */
20905 	if (connp->conn_cred != cr) {
20906 		crhold(cr);
20907 		crfree(connp->conn_cred);
20908 		connp->conn_cred = cr;
20909 	}
20910 	connp->conn_cpid = pid;
20911 
20912 	/* Cache things in the ixa without any refhold */
20913 	ixa->ixa_cred = cr;
20914 	ixa->ixa_cpid = pid;
20915 	if (is_system_labeled()) {
20916 		/* We need to restart with a label based on the cred */
20917 		ip_xmit_attr_restore_tsl(ixa, ixa->ixa_cred);
20918 	}
20919 
20920 	if (connp->conn_family == AF_INET6) {
20921 		if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
20922 			error = tcp_connect_ipv6(tcp, &sin6->sin6_addr,
20923 			    sin6->sin6_port, sin6->sin6_flowinfo,
20924 			    sin6->__sin6_src_id, sin6->sin6_scope_id);
20925 		} else {
20926 			/*
20927 			 * Destination adress is mapped IPv6 address.
20928 			 * Source bound address should be unspecified or
20929 			 * IPv6 mapped address as well.
20930 			 */
20931 			if (!IN6_IS_ADDR_UNSPECIFIED(
20932 			    &connp->conn_bound_addr_v6) &&
20933 			    !IN6_IS_ADDR_V4MAPPED(&connp->conn_bound_addr_v6)) {
20934 				return (EADDRNOTAVAIL);
20935 			}
20936 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
20937 			dstport = sin6->sin6_port;
20938 			srcid = sin6->__sin6_src_id;
20939 			error = tcp_connect_ipv4(tcp, dstaddrp, dstport,
20940 			    srcid);
20941 		}
20942 	} else {
20943 		dstaddrp = &sin->sin_addr.s_addr;
20944 		dstport = sin->sin_port;
20945 		srcid = 0;
20946 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid);
20947 	}
20948 
20949 	if (error != 0)
20950 		goto connect_failed;
20951 
20952 	CL_INET_CONNECT(connp, B_TRUE, error);
20953 	if (error != 0)
20954 		goto connect_failed;
20955 
20956 	/* connect succeeded */
20957 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
20958 	tcp->tcp_active_open = 1;
20959 
20960 	/*
20961 	 * tcp_set_destination() does not adjust for TCP/IP header length.
20962 	 */
20963 	mss = tcp->tcp_mss - connp->conn_ht_iphc_len;
20964 
20965 	/*
20966 	 * Just make sure our rwnd is at least rcvbuf * MSS large, and round up
20967 	 * to the nearest MSS.
20968 	 *
20969 	 * We do the round up here because we need to get the interface MTU
20970 	 * first before we can do the round up.
20971 	 */
20972 	tcp->tcp_rwnd = connp->conn_rcvbuf;
20973 	tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
20974 	    tcps->tcps_recv_hiwat_minmss * mss);
20975 	connp->conn_rcvbuf = tcp->tcp_rwnd;
20976 	tcp_set_ws_value(tcp);
20977 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
20978 	if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
20979 		tcp->tcp_snd_ws_ok = B_TRUE;
20980 
20981 	/*
20982 	 * Set tcp_snd_ts_ok to true
20983 	 * so that tcp_xmit_mp will
20984 	 * include the timestamp
20985 	 * option in the SYN segment.
20986 	 */
20987 	if (tcps->tcps_tstamp_always ||
20988 	    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
20989 		tcp->tcp_snd_ts_ok = B_TRUE;
20990 	}
20991 
20992 	/*
20993 	 * tcp_snd_sack_ok can be set in
20994 	 * tcp_set_destination() if the sack metric
20995 	 * is set.  So check it here also.
20996 	 */
20997 	if (tcps->tcps_sack_permitted == 2 ||
20998 	    tcp->tcp_snd_sack_ok) {
20999 		if (tcp->tcp_sack_info == NULL) {
21000 			tcp->tcp_sack_info = kmem_cache_alloc(
21001 			    tcp_sack_info_cache, KM_SLEEP);
21002 		}
21003 		tcp->tcp_snd_sack_ok = B_TRUE;
21004 	}
21005 
21006 	/*
21007 	 * Should we use ECN?  Note that the current
21008 	 * default value (SunOS 5.9) of tcp_ecn_permitted
21009 	 * is 1.  The reason for doing this is that there
21010 	 * are equipments out there that will drop ECN
21011 	 * enabled IP packets.  Setting it to 1 avoids
21012 	 * compatibility problems.
21013 	 */
21014 	if (tcps->tcps_ecn_permitted == 2)
21015 		tcp->tcp_ecn_ok = B_TRUE;
21016 
21017 	TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21018 	syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21019 	    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
21020 	if (syn_mp != NULL) {
21021 		/*
21022 		 * We must bump the generation before sending the syn
21023 		 * to ensure that we use the right generation in case
21024 		 * this thread issues a "connected" up call.
21025 		 */
21026 		SOCK_CONNID_BUMP(tcp->tcp_connid);
21027 		tcp_send_data(tcp, syn_mp);
21028 	}
21029 
21030 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
21031 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
21032 	return (0);
21033 
21034 connect_failed:
21035 	connp->conn_faddr_v6 = ipv6_all_zeros;
21036 	connp->conn_fport = 0;
21037 	tcp->tcp_state = oldstate;
21038 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
21039 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
21040 	return (error);
21041 }
21042 
21043 int
21044 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
21045     socklen_t len, sock_connid_t *id, cred_t *cr)
21046 {
21047 	conn_t		*connp = (conn_t *)proto_handle;
21048 	squeue_t	*sqp = connp->conn_sqp;
21049 	int		error;
21050 
21051 	ASSERT(connp->conn_upper_handle != NULL);
21052 
21053 	/* All Solaris components should pass a cred for this operation. */
21054 	ASSERT(cr != NULL);
21055 
21056 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
21057 	if (error != 0) {
21058 		return (error);
21059 	}
21060 
21061 	error = squeue_synch_enter(sqp, connp, NULL);
21062 	if (error != 0) {
21063 		/* failed to enter */
21064 		return (ENOSR);
21065 	}
21066 
21067 	/*
21068 	 * TCP supports quick connect, so no need to do an implicit bind
21069 	 */
21070 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
21071 	if (error == 0) {
21072 		*id = connp->conn_tcp->tcp_connid;
21073 	} else if (error < 0) {
21074 		if (error == -TOUTSTATE) {
21075 			switch (connp->conn_tcp->tcp_state) {
21076 			case TCPS_SYN_SENT:
21077 				error = EALREADY;
21078 				break;
21079 			case TCPS_ESTABLISHED:
21080 				error = EISCONN;
21081 				break;
21082 			case TCPS_LISTEN:
21083 				error = EOPNOTSUPP;
21084 				break;
21085 			default:
21086 				error = EINVAL;
21087 				break;
21088 			}
21089 		} else {
21090 			error = proto_tlitosyserr(-error);
21091 		}
21092 	}
21093 
21094 	if (connp->conn_tcp->tcp_loopback) {
21095 		struct sock_proto_props sopp;
21096 
21097 		sopp.sopp_flags = SOCKOPT_LOOPBACK;
21098 		sopp.sopp_loopback = B_TRUE;
21099 
21100 		(*connp->conn_upcalls->su_set_proto_props)(
21101 		    connp->conn_upper_handle, &sopp);
21102 	}
21103 done:
21104 	squeue_synch_exit(sqp, connp);
21105 
21106 	return ((error == 0) ? EINPROGRESS : error);
21107 }
21108 
21109 /* ARGSUSED */
21110 sock_lower_handle_t
21111 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
21112     uint_t *smodep, int *errorp, int flags, cred_t *credp)
21113 {
21114 	conn_t		*connp;
21115 	boolean_t	isv6 = family == AF_INET6;
21116 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
21117 	    (proto != 0 && proto != IPPROTO_TCP)) {
21118 		*errorp = EPROTONOSUPPORT;
21119 		return (NULL);
21120 	}
21121 
21122 	connp = tcp_create_common(credp, isv6, B_TRUE, errorp);
21123 	if (connp == NULL) {
21124 		return (NULL);
21125 	}
21126 
21127 	/*
21128 	 * Put the ref for TCP. Ref for IP was already put
21129 	 * by ipcl_conn_create. Also Make the conn_t globally
21130 	 * visible to walkers
21131 	 */
21132 	mutex_enter(&connp->conn_lock);
21133 	CONN_INC_REF_LOCKED(connp);
21134 	ASSERT(connp->conn_ref == 2);
21135 	connp->conn_state_flags &= ~CONN_INCIPIENT;
21136 
21137 	connp->conn_flags |= IPCL_NONSTR;
21138 	mutex_exit(&connp->conn_lock);
21139 
21140 	ASSERT(errorp != NULL);
21141 	*errorp = 0;
21142 	*sock_downcalls = &sock_tcp_downcalls;
21143 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
21144 	    SM_SENDFILESUPP;
21145 
21146 	return ((sock_lower_handle_t)connp);
21147 }
21148 
21149 /* ARGSUSED */
21150 void
21151 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
21152     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
21153 {
21154 	conn_t *connp = (conn_t *)proto_handle;
21155 	struct sock_proto_props sopp;
21156 
21157 	ASSERT(connp->conn_upper_handle == NULL);
21158 
21159 	/* All Solaris components should pass a cred for this operation. */
21160 	ASSERT(cr != NULL);
21161 
21162 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
21163 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
21164 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
21165 
21166 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
21167 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
21168 	sopp.sopp_maxpsz = INFPSZ;
21169 	sopp.sopp_maxblk = INFPSZ;
21170 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
21171 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
21172 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
21173 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
21174 	    tcp_rinfo.mi_minpsz;
21175 
21176 	connp->conn_upcalls = sock_upcalls;
21177 	connp->conn_upper_handle = sock_handle;
21178 
21179 	ASSERT(connp->conn_rcvbuf != 0 &&
21180 	    connp->conn_rcvbuf == connp->conn_tcp->tcp_rwnd);
21181 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
21182 }
21183 
21184 /* ARGSUSED */
21185 int
21186 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
21187 {
21188 	conn_t *connp = (conn_t *)proto_handle;
21189 
21190 	ASSERT(connp->conn_upper_handle != NULL);
21191 
21192 	/* All Solaris components should pass a cred for this operation. */
21193 	ASSERT(cr != NULL);
21194 
21195 	tcp_close_common(connp, flags);
21196 
21197 	ip_free_helper_stream(connp);
21198 
21199 	/*
21200 	 * Drop IP's reference on the conn. This is the last reference
21201 	 * on the connp if the state was less than established. If the
21202 	 * connection has gone into timewait state, then we will have
21203 	 * one ref for the TCP and one more ref (total of two) for the
21204 	 * classifier connected hash list (a timewait connections stays
21205 	 * in connected hash till closed).
21206 	 *
21207 	 * We can't assert the references because there might be other
21208 	 * transient reference places because of some walkers or queued
21209 	 * packets in squeue for the timewait state.
21210 	 */
21211 	CONN_DEC_REF(connp);
21212 	return (0);
21213 }
21214 
21215 /* ARGSUSED */
21216 int
21217 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
21218     cred_t *cr)
21219 {
21220 	tcp_t		*tcp;
21221 	uint32_t	msize;
21222 	conn_t *connp = (conn_t *)proto_handle;
21223 	int32_t		tcpstate;
21224 
21225 	/* All Solaris components should pass a cred for this operation. */
21226 	ASSERT(cr != NULL);
21227 
21228 	ASSERT(connp->conn_ref >= 2);
21229 	ASSERT(connp->conn_upper_handle != NULL);
21230 
21231 	if (msg->msg_controllen != 0) {
21232 		freemsg(mp);
21233 		return (EOPNOTSUPP);
21234 	}
21235 
21236 	switch (DB_TYPE(mp)) {
21237 	case M_DATA:
21238 		tcp = connp->conn_tcp;
21239 		ASSERT(tcp != NULL);
21240 
21241 		tcpstate = tcp->tcp_state;
21242 		if (tcpstate < TCPS_ESTABLISHED) {
21243 			freemsg(mp);
21244 			/*
21245 			 * We return ENOTCONN if the endpoint is trying to
21246 			 * connect or has never been connected, and EPIPE if it
21247 			 * has been disconnected. The connection id helps us
21248 			 * distinguish between the last two cases.
21249 			 */
21250 			return ((tcpstate == TCPS_SYN_SENT) ? ENOTCONN :
21251 			    ((tcp->tcp_connid > 0) ? EPIPE : ENOTCONN));
21252 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
21253 			freemsg(mp);
21254 			return (EPIPE);
21255 		}
21256 
21257 		msize = msgdsize(mp);
21258 
21259 		mutex_enter(&tcp->tcp_non_sq_lock);
21260 		tcp->tcp_squeue_bytes += msize;
21261 		/*
21262 		 * Squeue Flow Control
21263 		 */
21264 		if (TCP_UNSENT_BYTES(tcp) > connp->conn_sndbuf) {
21265 			tcp_setqfull(tcp);
21266 		}
21267 		mutex_exit(&tcp->tcp_non_sq_lock);
21268 
21269 		/*
21270 		 * The application may pass in an address in the msghdr, but
21271 		 * we ignore the address on connection-oriented sockets.
21272 		 * Just like BSD this code does not generate an error for
21273 		 * TCP (a CONNREQUIRED socket) when sending to an address
21274 		 * passed in with sendto/sendmsg. Instead the data is
21275 		 * delivered on the connection as if no address had been
21276 		 * supplied.
21277 		 */
21278 		CONN_INC_REF(connp);
21279 
21280 		if (msg->msg_flags & MSG_OOB) {
21281 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output_urgent,
21282 			    connp, NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
21283 		} else {
21284 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
21285 			    connp, NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
21286 		}
21287 
21288 		return (0);
21289 
21290 	default:
21291 		ASSERT(0);
21292 	}
21293 
21294 	freemsg(mp);
21295 	return (0);
21296 }
21297 
21298 /* ARGSUSED2 */
21299 void
21300 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
21301 {
21302 	int len;
21303 	uint32_t msize;
21304 	conn_t *connp = (conn_t *)arg;
21305 	tcp_t *tcp = connp->conn_tcp;
21306 
21307 	msize = msgdsize(mp);
21308 
21309 	len = msize - 1;
21310 	if (len < 0) {
21311 		freemsg(mp);
21312 		return;
21313 	}
21314 
21315 	/*
21316 	 * Try to force urgent data out on the wire. Even if we have unsent
21317 	 * data this will at least send the urgent flag.
21318 	 * XXX does not handle more flag correctly.
21319 	 */
21320 	len += tcp->tcp_unsent;
21321 	len += tcp->tcp_snxt;
21322 	tcp->tcp_urg = len;
21323 	tcp->tcp_valid_bits |= TCP_URG_VALID;
21324 
21325 	/* Bypass tcp protocol for fused tcp loopback */
21326 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
21327 		return;
21328 
21329 	/* Strip off the T_EXDATA_REQ if the data is from TPI */
21330 	if (DB_TYPE(mp) != M_DATA) {
21331 		mblk_t *mp1 = mp;
21332 		ASSERT(!IPCL_IS_NONSTR(connp));
21333 		mp = mp->b_cont;
21334 		freeb(mp1);
21335 	}
21336 	tcp_wput_data(tcp, mp, B_TRUE);
21337 }
21338 
21339 /* ARGSUSED3 */
21340 int
21341 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
21342     socklen_t *addrlenp, cred_t *cr)
21343 {
21344 	conn_t	*connp = (conn_t *)proto_handle;
21345 	tcp_t	*tcp = connp->conn_tcp;
21346 
21347 	ASSERT(connp->conn_upper_handle != NULL);
21348 	/* All Solaris components should pass a cred for this operation. */
21349 	ASSERT(cr != NULL);
21350 
21351 	ASSERT(tcp != NULL);
21352 	if (tcp->tcp_state < TCPS_SYN_RCVD)
21353 		return (ENOTCONN);
21354 
21355 	return (conn_getpeername(connp, addr, addrlenp));
21356 }
21357 
21358 /* ARGSUSED3 */
21359 int
21360 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
21361     socklen_t *addrlenp, cred_t *cr)
21362 {
21363 	conn_t	*connp = (conn_t *)proto_handle;
21364 
21365 	/* All Solaris components should pass a cred for this operation. */
21366 	ASSERT(cr != NULL);
21367 
21368 	ASSERT(connp->conn_upper_handle != NULL);
21369 	return (conn_getsockname(connp, addr, addrlenp));
21370 }
21371 
21372 /*
21373  * tcp_fallback
21374  *
21375  * A direct socket is falling back to using STREAMS. The queue
21376  * that is being passed down was created using tcp_open() with
21377  * the SO_FALLBACK flag set. As a result, the queue is not
21378  * associated with a conn, and the q_ptrs instead contain the
21379  * dev and minor area that should be used.
21380  *
21381  * The 'issocket' flag indicates whether the FireEngine
21382  * optimizations should be used. The common case would be that
21383  * optimizations are enabled, and they might be subsequently
21384  * disabled using the _SIOCSOCKFALLBACK ioctl.
21385  */
21386 
21387 /*
21388  * An active connection is falling back to TPI. Gather all the information
21389  * required by the STREAM head and TPI sonode and send it up.
21390  */
21391 void
21392 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
21393     boolean_t issocket, so_proto_quiesced_cb_t quiesced_cb)
21394 {
21395 	conn_t			*connp = tcp->tcp_connp;
21396 	struct stroptions	*stropt;
21397 	struct T_capability_ack tca;
21398 	struct sockaddr_in6	laddr, faddr;
21399 	socklen_t 		laddrlen, faddrlen;
21400 	short			opts;
21401 	int			error;
21402 	mblk_t			*mp;
21403 
21404 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
21405 	connp->conn_minor_arena = WR(q)->q_ptr;
21406 
21407 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
21408 
21409 	connp->conn_rq = RD(q);
21410 	connp->conn_wq = WR(q);
21411 
21412 	WR(q)->q_qinfo = &tcp_sock_winit;
21413 
21414 	if (!issocket)
21415 		tcp_use_pure_tpi(tcp);
21416 
21417 	/*
21418 	 * free the helper stream
21419 	 */
21420 	ip_free_helper_stream(connp);
21421 
21422 	/*
21423 	 * Notify the STREAM head about options
21424 	 */
21425 	DB_TYPE(stropt_mp) = M_SETOPTS;
21426 	stropt = (struct stroptions *)stropt_mp->b_rptr;
21427 	stropt_mp->b_wptr += sizeof (struct stroptions);
21428 	stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
21429 
21430 	stropt->so_wroff = connp->conn_ht_iphc_len + (tcp->tcp_loopback ? 0 :
21431 	    tcp->tcp_tcps->tcps_wroff_xtra);
21432 	if (tcp->tcp_snd_sack_ok)
21433 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
21434 	stropt->so_hiwat = connp->conn_rcvbuf;
21435 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
21436 
21437 	putnext(RD(q), stropt_mp);
21438 
21439 	/*
21440 	 * Collect the information needed to sync with the sonode
21441 	 */
21442 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
21443 
21444 	laddrlen = faddrlen = sizeof (sin6_t);
21445 	(void) tcp_getsockname((sock_lower_handle_t)connp,
21446 	    (struct sockaddr *)&laddr, &laddrlen, CRED());
21447 	error = tcp_getpeername((sock_lower_handle_t)connp,
21448 	    (struct sockaddr *)&faddr, &faddrlen, CRED());
21449 	if (error != 0)
21450 		faddrlen = 0;
21451 
21452 	opts = 0;
21453 	if (connp->conn_oobinline)
21454 		opts |= SO_OOBINLINE;
21455 	if (connp->conn_ixa->ixa_flags & IXAF_DONTROUTE)
21456 		opts |= SO_DONTROUTE;
21457 
21458 	/*
21459 	 * Notify the socket that the protocol is now quiescent,
21460 	 * and it's therefore safe move data from the socket
21461 	 * to the stream head.
21462 	 */
21463 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
21464 	    (struct sockaddr *)&laddr, laddrlen,
21465 	    (struct sockaddr *)&faddr, faddrlen, opts);
21466 
21467 	while ((mp = tcp->tcp_rcv_list) != NULL) {
21468 		tcp->tcp_rcv_list = mp->b_next;
21469 		mp->b_next = NULL;
21470 		/* We never do fallback for kernel RPC */
21471 		putnext(q, mp);
21472 	}
21473 	tcp->tcp_rcv_last_head = NULL;
21474 	tcp->tcp_rcv_last_tail = NULL;
21475 	tcp->tcp_rcv_cnt = 0;
21476 }
21477 
21478 /*
21479  * An eager is falling back to TPI. All we have to do is send
21480  * up a T_CONN_IND.
21481  */
21482 void
21483 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
21484 {
21485 	tcp_t *listener = eager->tcp_listener;
21486 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
21487 
21488 	ASSERT(listener != NULL);
21489 	ASSERT(mp != NULL);
21490 
21491 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
21492 
21493 	/*
21494 	 * TLI/XTI applications will get confused by
21495 	 * sending eager as an option since it violates
21496 	 * the option semantics. So remove the eager as
21497 	 * option since TLI/XTI app doesn't need it anyway.
21498 	 */
21499 	if (!direct_sockfs) {
21500 		struct T_conn_ind *conn_ind;
21501 
21502 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
21503 		conn_ind->OPT_length = 0;
21504 		conn_ind->OPT_offset = 0;
21505 	}
21506 
21507 	/*
21508 	 * Sockfs guarantees that the listener will not be closed
21509 	 * during fallback. So we can safely use the listener's queue.
21510 	 */
21511 	putnext(listener->tcp_connp->conn_rq, mp);
21512 }
21513 
21514 int
21515 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
21516     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
21517 {
21518 	tcp_t			*tcp;
21519 	conn_t 			*connp = (conn_t *)proto_handle;
21520 	int			error;
21521 	mblk_t			*stropt_mp;
21522 	mblk_t			*ordrel_mp;
21523 
21524 	tcp = connp->conn_tcp;
21525 
21526 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
21527 	    NULL);
21528 
21529 	/* Pre-allocate the T_ordrel_ind mblk. */
21530 	ASSERT(tcp->tcp_ordrel_mp == NULL);
21531 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
21532 	    STR_NOSIG, NULL);
21533 	ordrel_mp->b_datap->db_type = M_PROTO;
21534 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
21535 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
21536 
21537 	/*
21538 	 * Enter the squeue so that no new packets can come in
21539 	 */
21540 	error = squeue_synch_enter(connp->conn_sqp, connp, NULL);
21541 	if (error != 0) {
21542 		/* failed to enter, free all the pre-allocated messages. */
21543 		freeb(stropt_mp);
21544 		freeb(ordrel_mp);
21545 		/*
21546 		 * We cannot process the eager, so at least send out a
21547 		 * RST so the peer can reconnect.
21548 		 */
21549 		if (tcp->tcp_listener != NULL) {
21550 			(void) tcp_eager_blowoff(tcp->tcp_listener,
21551 			    tcp->tcp_conn_req_seqnum);
21552 		}
21553 		return (ENOMEM);
21554 	}
21555 
21556 	/*
21557 	 * Both endpoints must be of the same type (either STREAMS or
21558 	 * non-STREAMS) for fusion to be enabled. So if we are fused,
21559 	 * we have to unfuse.
21560 	 */
21561 	if (tcp->tcp_fused)
21562 		tcp_unfuse(tcp);
21563 
21564 	/*
21565 	 * No longer a direct socket
21566 	 */
21567 	connp->conn_flags &= ~IPCL_NONSTR;
21568 	tcp->tcp_ordrel_mp = ordrel_mp;
21569 
21570 	if (tcp->tcp_listener != NULL) {
21571 		/* The eager will deal with opts when accept() is called */
21572 		freeb(stropt_mp);
21573 		tcp_fallback_eager(tcp, direct_sockfs);
21574 	} else {
21575 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
21576 		    quiesced_cb);
21577 	}
21578 
21579 	/*
21580 	 * There should be atleast two ref's (IP + TCP)
21581 	 */
21582 	ASSERT(connp->conn_ref >= 2);
21583 	squeue_synch_exit(connp->conn_sqp, connp);
21584 
21585 	return (0);
21586 }
21587 
21588 /* ARGSUSED */
21589 static void
21590 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
21591 {
21592 	conn_t 	*connp = (conn_t *)arg;
21593 	tcp_t	*tcp = connp->conn_tcp;
21594 
21595 	freemsg(mp);
21596 
21597 	if (tcp->tcp_fused)
21598 		tcp_unfuse(tcp);
21599 
21600 	if (tcp_xmit_end(tcp) != 0) {
21601 		/*
21602 		 * We were crossing FINs and got a reset from
21603 		 * the other side. Just ignore it.
21604 		 */
21605 		if (connp->conn_debug) {
21606 			(void) strlog(TCP_MOD_ID, 0, 1,
21607 			    SL_ERROR|SL_TRACE,
21608 			    "tcp_shutdown_output() out of state %s",
21609 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
21610 		}
21611 	}
21612 }
21613 
21614 /* ARGSUSED */
21615 int
21616 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
21617 {
21618 	conn_t  *connp = (conn_t *)proto_handle;
21619 	tcp_t   *tcp = connp->conn_tcp;
21620 
21621 	ASSERT(connp->conn_upper_handle != NULL);
21622 
21623 	/* All Solaris components should pass a cred for this operation. */
21624 	ASSERT(cr != NULL);
21625 
21626 	/*
21627 	 * X/Open requires that we check the connected state.
21628 	 */
21629 	if (tcp->tcp_state < TCPS_SYN_SENT)
21630 		return (ENOTCONN);
21631 
21632 	/* shutdown the send side */
21633 	if (how != SHUT_RD) {
21634 		mblk_t *bp;
21635 
21636 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
21637 		CONN_INC_REF(connp);
21638 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
21639 		    connp, NULL, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
21640 
21641 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21642 		    SOCK_OPCTL_SHUT_SEND, 0);
21643 	}
21644 
21645 	/* shutdown the recv side */
21646 	if (how != SHUT_WR)
21647 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21648 		    SOCK_OPCTL_SHUT_RECV, 0);
21649 
21650 	return (0);
21651 }
21652 
21653 /*
21654  * SOP_LISTEN() calls into tcp_listen().
21655  */
21656 /* ARGSUSED */
21657 int
21658 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
21659 {
21660 	conn_t	*connp = (conn_t *)proto_handle;
21661 	int 	error;
21662 	squeue_t *sqp = connp->conn_sqp;
21663 
21664 	ASSERT(connp->conn_upper_handle != NULL);
21665 
21666 	/* All Solaris components should pass a cred for this operation. */
21667 	ASSERT(cr != NULL);
21668 
21669 	error = squeue_synch_enter(sqp, connp, NULL);
21670 	if (error != 0) {
21671 		/* failed to enter */
21672 		return (ENOBUFS);
21673 	}
21674 
21675 	error = tcp_do_listen(connp, NULL, 0, backlog, cr, FALSE);
21676 	if (error == 0) {
21677 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21678 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
21679 	} else if (error < 0) {
21680 		if (error == -TOUTSTATE)
21681 			error = EINVAL;
21682 		else
21683 			error = proto_tlitosyserr(-error);
21684 	}
21685 	squeue_synch_exit(sqp, connp);
21686 	return (error);
21687 }
21688 
21689 static int
21690 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
21691     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
21692 {
21693 	tcp_t		*tcp = connp->conn_tcp;
21694 	int		error = 0;
21695 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21696 
21697 	/* All Solaris components should pass a cred for this operation. */
21698 	ASSERT(cr != NULL);
21699 
21700 	if (tcp->tcp_state >= TCPS_BOUND) {
21701 		if ((tcp->tcp_state == TCPS_BOUND ||
21702 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
21703 			/*
21704 			 * Handle listen() increasing backlog.
21705 			 * This is more "liberal" then what the TPI spec
21706 			 * requires but is needed to avoid a t_unbind
21707 			 * when handling listen() since the port number
21708 			 * might be "stolen" between the unbind and bind.
21709 			 */
21710 			goto do_listen;
21711 		}
21712 		if (connp->conn_debug) {
21713 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21714 			    "tcp_listen: bad state, %d", tcp->tcp_state);
21715 		}
21716 		return (-TOUTSTATE);
21717 	} else {
21718 		if (sa == NULL) {
21719 			sin6_t	addr;
21720 			sin_t *sin;
21721 			sin6_t *sin6;
21722 
21723 			ASSERT(IPCL_IS_NONSTR(connp));
21724 			/* Do an implicit bind: Request for a generic port. */
21725 			if (connp->conn_family == AF_INET) {
21726 				len = sizeof (sin_t);
21727 				sin = (sin_t *)&addr;
21728 				*sin = sin_null;
21729 				sin->sin_family = AF_INET;
21730 			} else {
21731 				ASSERT(connp->conn_family == AF_INET6);
21732 				len = sizeof (sin6_t);
21733 				sin6 = (sin6_t *)&addr;
21734 				*sin6 = sin6_null;
21735 				sin6->sin6_family = AF_INET6;
21736 			}
21737 			sa = (struct sockaddr *)&addr;
21738 		}
21739 
21740 		error = tcp_bind_check(connp, sa, len, cr,
21741 		    bind_to_req_port_only);
21742 		if (error)
21743 			return (error);
21744 		/* Fall through and do the fanout insertion */
21745 	}
21746 
21747 do_listen:
21748 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
21749 	tcp->tcp_conn_req_max = backlog;
21750 	if (tcp->tcp_conn_req_max) {
21751 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
21752 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
21753 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
21754 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
21755 		/*
21756 		 * If this is a listener, do not reset the eager list
21757 		 * and other stuffs.  Note that we don't check if the
21758 		 * existing eager list meets the new tcp_conn_req_max
21759 		 * requirement.
21760 		 */
21761 		if (tcp->tcp_state != TCPS_LISTEN) {
21762 			tcp->tcp_state = TCPS_LISTEN;
21763 			/* Initialize the chain. Don't need the eager_lock */
21764 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
21765 			tcp->tcp_eager_next_drop_q0 = tcp;
21766 			tcp->tcp_eager_prev_drop_q0 = tcp;
21767 			tcp->tcp_second_ctimer_threshold =
21768 			    tcps->tcps_ip_abort_linterval;
21769 		}
21770 	}
21771 
21772 	/*
21773 	 * We need to make sure that the conn_recv is set to a non-null
21774 	 * value before we insert the conn into the classifier table.
21775 	 * This is to avoid a race with an incoming packet which does an
21776 	 * ipcl_classify().
21777 	 * We initially set it to tcp_input_listener_unbound to try to
21778 	 * pick a good squeue for the listener when the first SYN arrives.
21779 	 * tcp_input_listener_unbound sets it to tcp_input_listener on that
21780 	 * first SYN.
21781 	 */
21782 	connp->conn_recv = tcp_input_listener_unbound;
21783 
21784 	/* Insert the listener in the classifier table */
21785 	error = ip_laddr_fanout_insert(connp);
21786 	if (error != 0) {
21787 		/* Undo the bind - release the port number */
21788 		tcp->tcp_state = TCPS_IDLE;
21789 		connp->conn_bound_addr_v6 = ipv6_all_zeros;
21790 
21791 		connp->conn_laddr_v6 = ipv6_all_zeros;
21792 		connp->conn_saddr_v6 = ipv6_all_zeros;
21793 		connp->conn_ports = 0;
21794 
21795 		if (connp->conn_anon_port) {
21796 			zone_t		*zone;
21797 
21798 			zone = crgetzone(cr);
21799 			connp->conn_anon_port = B_FALSE;
21800 			(void) tsol_mlp_anon(zone, connp->conn_mlp_type,
21801 			    connp->conn_proto, connp->conn_lport, B_FALSE);
21802 		}
21803 		connp->conn_mlp_type = mlptSingle;
21804 
21805 		tcp_bind_hash_remove(tcp);
21806 		return (error);
21807 	} else {
21808 		/*
21809 		 * If there is a connection limit, allocate and initialize
21810 		 * the counter struct.  Note that since listen can be called
21811 		 * multiple times, the struct may have been allready allocated.
21812 		 */
21813 		if (!list_is_empty(&tcps->tcps_listener_conf) &&
21814 		    tcp->tcp_listen_cnt == NULL) {
21815 			tcp_listen_cnt_t *tlc;
21816 			uint32_t ratio;
21817 
21818 			ratio = tcp_find_listener_conf(tcps,
21819 			    ntohs(connp->conn_lport));
21820 			if (ratio != 0) {
21821 				uint32_t mem_ratio, tot_buf;
21822 
21823 				tlc = kmem_alloc(sizeof (tcp_listen_cnt_t),
21824 				    KM_SLEEP);
21825 				/*
21826 				 * Calculate the connection limit based on
21827 				 * the configured ratio and maxusers.  Maxusers
21828 				 * are calculated based on memory size,
21829 				 * ~ 1 user per MB.  Note that the conn_rcvbuf
21830 				 * and conn_sndbuf may change after a
21831 				 * connection is accepted.  So what we have
21832 				 * is only an approximation.
21833 				 */
21834 				if ((tot_buf = connp->conn_rcvbuf +
21835 				    connp->conn_sndbuf) < MB) {
21836 					mem_ratio = MB / tot_buf;
21837 					tlc->tlc_max = maxusers / ratio *
21838 					    mem_ratio;
21839 				} else {
21840 					mem_ratio = tot_buf / MB;
21841 					tlc->tlc_max = maxusers / ratio /
21842 					    mem_ratio;
21843 				}
21844 				/* At least we should allow two connections! */
21845 				if (tlc->tlc_max <= tcp_min_conn_listener)
21846 					tlc->tlc_max = tcp_min_conn_listener;
21847 				tlc->tlc_cnt = 1;
21848 				tlc->tlc_drop = 0;
21849 				tcp->tcp_listen_cnt = tlc;
21850 			}
21851 		}
21852 	}
21853 	return (error);
21854 }
21855 
21856 void
21857 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
21858 {
21859 	conn_t  *connp = (conn_t *)proto_handle;
21860 	tcp_t	*tcp = connp->conn_tcp;
21861 	mblk_t *mp;
21862 	int error;
21863 
21864 	ASSERT(connp->conn_upper_handle != NULL);
21865 
21866 	/*
21867 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_clr_flowctrl()
21868 	 * is currently running.
21869 	 */
21870 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
21871 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
21872 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
21873 		return;
21874 	}
21875 	tcp->tcp_rsrv_mp = NULL;
21876 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
21877 
21878 	error = squeue_synch_enter(connp->conn_sqp, connp, mp);
21879 	ASSERT(error == 0);
21880 
21881 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
21882 	tcp->tcp_rsrv_mp = mp;
21883 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
21884 
21885 	if (tcp->tcp_fused) {
21886 		tcp_fuse_backenable(tcp);
21887 	} else {
21888 		tcp->tcp_rwnd = connp->conn_rcvbuf;
21889 		/*
21890 		 * Send back a window update immediately if TCP is above
21891 		 * ESTABLISHED state and the increase of the rcv window
21892 		 * that the other side knows is at least 1 MSS after flow
21893 		 * control is lifted.
21894 		 */
21895 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
21896 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
21897 			tcp_xmit_ctl(NULL, tcp,
21898 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
21899 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
21900 		}
21901 	}
21902 
21903 	squeue_synch_exit(connp->conn_sqp, connp);
21904 }
21905 
21906 /* ARGSUSED */
21907 int
21908 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
21909     int mode, int32_t *rvalp, cred_t *cr)
21910 {
21911 	conn_t  	*connp = (conn_t *)proto_handle;
21912 	int		error;
21913 
21914 	ASSERT(connp->conn_upper_handle != NULL);
21915 
21916 	/* All Solaris components should pass a cred for this operation. */
21917 	ASSERT(cr != NULL);
21918 
21919 	/*
21920 	 * If we don't have a helper stream then create one.
21921 	 * ip_create_helper_stream takes care of locking the conn_t,
21922 	 * so this check for NULL is just a performance optimization.
21923 	 */
21924 	if (connp->conn_helper_info == NULL) {
21925 		tcp_stack_t *tcps = connp->conn_tcp->tcp_tcps;
21926 
21927 		/*
21928 		 * Create a helper stream for non-STREAMS socket.
21929 		 */
21930 		error = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
21931 		if (error != 0) {
21932 			ip0dbg(("tcp_ioctl: create of IP helper stream "
21933 			    "failed %d\n", error));
21934 			return (error);
21935 		}
21936 	}
21937 
21938 	switch (cmd) {
21939 		case ND_SET:
21940 		case ND_GET:
21941 		case _SIOCSOCKFALLBACK:
21942 		case TCP_IOC_ABORT_CONN:
21943 		case TI_GETPEERNAME:
21944 		case TI_GETMYNAME:
21945 			ip1dbg(("tcp_ioctl: cmd 0x%x on non streams socket",
21946 			    cmd));
21947 			error = EINVAL;
21948 			break;
21949 		default:
21950 			/*
21951 			 * If the conn is not closing, pass on to IP using
21952 			 * helper stream. Bump the ioctlref to prevent tcp_close
21953 			 * from closing the rq/wq out from underneath the ioctl
21954 			 * if it ends up queued or aborted/interrupted.
21955 			 */
21956 			mutex_enter(&connp->conn_lock);
21957 			if (connp->conn_state_flags & (CONN_CLOSING)) {
21958 				mutex_exit(&connp->conn_lock);
21959 				error = EINVAL;
21960 				break;
21961 			}
21962 			CONN_INC_IOCTLREF_LOCKED(connp);
21963 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
21964 			    cmd, arg, mode, cr, rvalp);
21965 			CONN_DEC_IOCTLREF(connp);
21966 			break;
21967 	}
21968 	return (error);
21969 }
21970 
21971 sock_downcalls_t sock_tcp_downcalls = {
21972 	tcp_activate,
21973 	tcp_accept,
21974 	tcp_bind,
21975 	tcp_listen,
21976 	tcp_connect,
21977 	tcp_getpeername,
21978 	tcp_getsockname,
21979 	tcp_getsockopt,
21980 	tcp_setsockopt,
21981 	tcp_sendmsg,
21982 	NULL,
21983 	NULL,
21984 	NULL,
21985 	tcp_shutdown,
21986 	tcp_clr_flowctrl,
21987 	tcp_ioctl,
21988 	tcp_close,
21989 };
21990 
21991 /*
21992  * Timeout function to reset the TCP stack variable tcps_reclaim to false.
21993  */
21994 static void
21995 tcp_reclaim_timer(void *arg)
21996 {
21997 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
21998 
21999 	mutex_enter(&tcps->tcps_reclaim_lock);
22000 	tcps->tcps_reclaim = B_FALSE;
22001 	tcps->tcps_reclaim_tid = 0;
22002 	mutex_exit(&tcps->tcps_reclaim_lock);
22003 	/* Only need to print this once. */
22004 	if (tcps->tcps_netstack->netstack_stackid == GLOBAL_ZONEID)
22005 		cmn_err(CE_WARN, "TCP defensive mode off\n");
22006 }
22007 
22008 /*
22009  * Kmem reclaim call back function.  When the system is under memory
22010  * pressure, we set the TCP stack variable tcps_reclaim to true.  This
22011  * variable is reset to false after tcps_reclaim_period msecs.  During this
22012  * period, TCP will be more aggressive in aborting connections not making
22013  * progress, meaning retransmitting for some time (tcp_early_abort seconds).
22014  * TCP will also not accept new connection request for those listeners whose
22015  * q or q0 is not empty.
22016  */
22017 /* ARGSUSED */
22018 void
22019 tcp_conn_reclaim(void *arg)
22020 {
22021 	netstack_handle_t nh;
22022 	netstack_t *ns;
22023 	tcp_stack_t *tcps;
22024 	boolean_t new = B_FALSE;
22025 
22026 	netstack_next_init(&nh);
22027 	while ((ns = netstack_next(&nh)) != NULL) {
22028 		tcps = ns->netstack_tcp;
22029 		mutex_enter(&tcps->tcps_reclaim_lock);
22030 		if (!tcps->tcps_reclaim) {
22031 			tcps->tcps_reclaim = B_TRUE;
22032 			tcps->tcps_reclaim_tid = timeout(tcp_reclaim_timer,
22033 			    tcps, MSEC_TO_TICK(tcps->tcps_reclaim_period));
22034 			new = B_TRUE;
22035 		}
22036 		mutex_exit(&tcps->tcps_reclaim_lock);
22037 		netstack_rele(ns);
22038 	}
22039 	netstack_next_fini(&nh);
22040 	if (new)
22041 		cmn_err(CE_WARN, "Memory pressure: TCP defensive mode on\n");
22042 }
22043 
22044 /*
22045  * Given a tcp_stack_t and a port (in host byte order), find a listener
22046  * configuration for that port and return the ratio.
22047  */
22048 static uint32_t
22049 tcp_find_listener_conf(tcp_stack_t *tcps, in_port_t port)
22050 {
22051 	tcp_listener_t	*tl;
22052 	uint32_t ratio = 0;
22053 
22054 	mutex_enter(&tcps->tcps_listener_conf_lock);
22055 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22056 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22057 		if (tl->tl_port == port) {
22058 			ratio = tl->tl_ratio;
22059 			break;
22060 		}
22061 	}
22062 	mutex_exit(&tcps->tcps_listener_conf_lock);
22063 	return (ratio);
22064 }
22065 
22066 /*
22067  * Ndd param helper routine to return the current list of listener limit
22068  * configuration.
22069  */
22070 /* ARGSUSED */
22071 static int
22072 tcp_listener_conf_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22073 {
22074 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22075 	tcp_listener_t	*tl;
22076 
22077 	mutex_enter(&tcps->tcps_listener_conf_lock);
22078 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22079 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22080 		(void) mi_mpprintf(mp, "%d:%d ", tl->tl_port, tl->tl_ratio);
22081 	}
22082 	mutex_exit(&tcps->tcps_listener_conf_lock);
22083 	return (0);
22084 }
22085 
22086 /*
22087  * Ndd param helper routine to add a new listener limit configuration.
22088  */
22089 /* ARGSUSED */
22090 static int
22091 tcp_listener_conf_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22092     cred_t *cr)
22093 {
22094 	tcp_listener_t	*new_tl;
22095 	tcp_listener_t	*tl;
22096 	long		lport;
22097 	long		ratio;
22098 	char		*colon;
22099 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22100 
22101 	if (ddi_strtol(value, &colon, 10, &lport) != 0 || lport <= 0 ||
22102 	    lport > USHRT_MAX || *colon != ':') {
22103 		return (EINVAL);
22104 	}
22105 	if (ddi_strtol(colon + 1, NULL, 10, &ratio) != 0 || ratio <= 0)
22106 		return (EINVAL);
22107 
22108 	mutex_enter(&tcps->tcps_listener_conf_lock);
22109 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22110 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22111 		/* There is an existing entry, so update its ratio value. */
22112 		if (tl->tl_port == lport) {
22113 			tl->tl_ratio = ratio;
22114 			mutex_exit(&tcps->tcps_listener_conf_lock);
22115 			return (0);
22116 		}
22117 	}
22118 
22119 	if ((new_tl = kmem_alloc(sizeof (tcp_listener_t), KM_NOSLEEP)) ==
22120 	    NULL) {
22121 		mutex_exit(&tcps->tcps_listener_conf_lock);
22122 		return (ENOMEM);
22123 	}
22124 
22125 	new_tl->tl_port = lport;
22126 	new_tl->tl_ratio = ratio;
22127 	list_insert_tail(&tcps->tcps_listener_conf, new_tl);
22128 	mutex_exit(&tcps->tcps_listener_conf_lock);
22129 	return (0);
22130 }
22131 
22132 /*
22133  * Ndd param helper routine to remove a listener limit configuration.
22134  */
22135 /* ARGSUSED */
22136 static int
22137 tcp_listener_conf_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22138     cred_t *cr)
22139 {
22140 	tcp_listener_t	*tl;
22141 	long		lport;
22142 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22143 
22144 	if (ddi_strtol(value, NULL, 10, &lport) != 0 || lport <= 0 ||
22145 	    lport > USHRT_MAX) {
22146 		return (EINVAL);
22147 	}
22148 	mutex_enter(&tcps->tcps_listener_conf_lock);
22149 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22150 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22151 		if (tl->tl_port == lport) {
22152 			list_remove(&tcps->tcps_listener_conf, tl);
22153 			mutex_exit(&tcps->tcps_listener_conf_lock);
22154 			kmem_free(tl, sizeof (tcp_listener_t));
22155 			return (0);
22156 		}
22157 	}
22158 	mutex_exit(&tcps->tcps_listener_conf_lock);
22159 	return (ESRCH);
22160 }
22161 
22162 /*
22163  * To remove all listener limit configuration in a tcp_stack_t.
22164  */
22165 static void
22166 tcp_listener_conf_cleanup(tcp_stack_t *tcps)
22167 {
22168 	tcp_listener_t	*tl;
22169 
22170 	mutex_enter(&tcps->tcps_listener_conf_lock);
22171 	while ((tl = list_head(&tcps->tcps_listener_conf)) != NULL) {
22172 		list_remove(&tcps->tcps_listener_conf, tl);
22173 		kmem_free(tl, sizeof (tcp_listener_t));
22174 	}
22175 	mutex_destroy(&tcps->tcps_listener_conf_lock);
22176 	list_destroy(&tcps->tcps_listener_conf);
22177 }
22178