xref: /titanic_41/usr/src/uts/common/inet/tcp/tcp.c (revision 1f0f5e3e328e41529296f756090856aa7f239b1c)
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 /* Control whether TCP can enter defensive mode when under memory pressure. */
620 boolean_t tcp_do_reclaim = B_TRUE;
621 
622 /*
623  * When the system is under memory pressure, stack variable tcps_reclaim is
624  * true, we shorten the connection timeout abort interval to tcp_early_abort
625  * seconds.
626  */
627 uint32_t tcp_early_abort = 30;
628 
629 /*
630  * TCP options struct returned from tcp_parse_options.
631  */
632 typedef struct tcp_opt_s {
633 	uint32_t	tcp_opt_mss;
634 	uint32_t	tcp_opt_wscale;
635 	uint32_t	tcp_opt_ts_val;
636 	uint32_t	tcp_opt_ts_ecr;
637 	tcp_t		*tcp;
638 } tcp_opt_t;
639 
640 /*
641  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
642  */
643 
644 #ifdef _BIG_ENDIAN
645 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
646 	(TCPOPT_TSTAMP << 8) | 10)
647 #else
648 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
649 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
650 #endif
651 
652 /*
653  * Flags returned from tcp_parse_options.
654  */
655 #define	TCP_OPT_MSS_PRESENT	1
656 #define	TCP_OPT_WSCALE_PRESENT	2
657 #define	TCP_OPT_TSTAMP_PRESENT	4
658 #define	TCP_OPT_SACK_OK_PRESENT	8
659 #define	TCP_OPT_SACK_PRESENT	16
660 
661 /* TCP option length */
662 #define	TCPOPT_NOP_LEN		1
663 #define	TCPOPT_MAXSEG_LEN	4
664 #define	TCPOPT_WS_LEN		3
665 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
666 #define	TCPOPT_TSTAMP_LEN	10
667 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
668 #define	TCPOPT_SACK_OK_LEN	2
669 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
670 #define	TCPOPT_REAL_SACK_LEN	4
671 #define	TCPOPT_MAX_SACK_LEN	36
672 #define	TCPOPT_HEADER_LEN	2
673 
674 /* TCP cwnd burst factor. */
675 #define	TCP_CWND_INFINITE	65535
676 #define	TCP_CWND_SS		3
677 #define	TCP_CWND_NORMAL		5
678 
679 /* Maximum TCP initial cwin (start/restart). */
680 #define	TCP_MAX_INIT_CWND	8
681 
682 /*
683  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
684  * either tcp_slow_start_initial or tcp_slow_start_after idle
685  * depending on the caller.  If the upper layer has not used the
686  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
687  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
688  * If the upper layer has changed set the tcp_init_cwnd, just use
689  * it to calculate the tcp_cwnd.
690  */
691 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
692 {									\
693 	if ((tcp)->tcp_init_cwnd == 0) {				\
694 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
695 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
696 	} else {							\
697 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
698 	}								\
699 	tcp->tcp_cwnd_cnt = 0;						\
700 }
701 
702 /* TCP Timer control structure */
703 typedef struct tcpt_s {
704 	pfv_t	tcpt_pfv;	/* The routine we are to call */
705 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
706 } tcpt_t;
707 
708 /*
709  * Functions called directly via squeue having a prototype of edesc_t.
710  */
711 void		tcp_input_listener(void *arg, mblk_t *mp, void *arg2,
712     ip_recv_attr_t *ira);
713 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2,
714     ip_recv_attr_t *dummy);
715 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2,
716     ip_recv_attr_t *dummy);
717 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2,
718     ip_recv_attr_t *dummy);
719 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2,
720     ip_recv_attr_t *dummy);
721 void		tcp_input_data(void *arg, mblk_t *mp, void *arg2,
722     ip_recv_attr_t *ira);
723 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2,
724     ip_recv_attr_t *dummy);
725 void		tcp_output(void *arg, mblk_t *mp, void *arg2,
726     ip_recv_attr_t *dummy);
727 void		tcp_output_urgent(void *arg, mblk_t *mp, void *arg2,
728     ip_recv_attr_t *dummy);
729 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2,
730     ip_recv_attr_t *dummy);
731 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2,
732     ip_recv_attr_t *dummy);
733 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2,
734     ip_recv_attr_t *dummy);
735 static void	tcp_send_synack(void *arg, mblk_t *mp, void *arg2,
736     ip_recv_attr_t *dummy);
737 
738 
739 /* Prototype for TCP functions */
740 static void	tcp_random_init(void);
741 int		tcp_random(void);
742 static void	tcp_tli_accept(tcp_t *tcp, mblk_t *mp);
743 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
744 		    tcp_t *eager);
745 static int	tcp_set_destination(tcp_t *tcp);
746 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
747     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
748     boolean_t user_specified);
749 static void	tcp_closei_local(tcp_t *tcp);
750 static void	tcp_close_detached(tcp_t *tcp);
751 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr,
752 		    mblk_t *idmp, mblk_t **defermp, ip_recv_attr_t *ira);
753 static void	tcp_tpi_connect(tcp_t *tcp, mblk_t *mp);
754 static int	tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
755 		    in_port_t dstport, uint_t srcid);
756 static int	tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
757 		    in_port_t dstport, uint32_t flowinfo,
758 		    uint_t srcid, uint32_t scope_id);
759 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
760 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
761 static char	*tcp_display(tcp_t *tcp, char *, char);
762 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
763 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
764 static void	tcp_eager_unlink(tcp_t *tcp);
765 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
766 		    int unixerr);
767 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
768 		    int tlierr, int unixerr);
769 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
770 		    cred_t *cr);
771 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
772 		    char *value, caddr_t cp, cred_t *cr);
773 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
774 		    char *value, caddr_t cp, cred_t *cr);
775 static int	tcp_tpistate(tcp_t *tcp);
776 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
777     int caller_holds_lock);
778 static void	tcp_bind_hash_remove(tcp_t *tcp);
779 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
780 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
781 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
782 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
783 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
784 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
785 static void	tcp_init_values(tcp_t *tcp);
786 static void	tcp_ip_notify(tcp_t *tcp);
787 static void	tcp_iss_init(tcp_t *tcp);
788 static void	tcp_keepalive_killer(void *arg);
789 static int	tcp_parse_options(tcpha_t *tcpha, tcp_opt_t *tcpopt);
790 static void	tcp_mss_set(tcp_t *tcp, uint32_t size);
791 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
792 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
793 static boolean_t tcp_allow_connopt_set(int level, int name);
794 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
795 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
796 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
797     tcp_stack_t *);
798 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
799 		    caddr_t cp, cred_t *cr);
800 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
801 		    caddr_t cp, cred_t *cr);
802 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
803 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
804 		    caddr_t cp, cred_t *cr);
805 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
806 static void	tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt);
807 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
808 static void	tcp_reass_timer(void *arg);
809 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
810 static void	tcp_reinit(tcp_t *tcp);
811 static void	tcp_reinit_values(tcp_t *tcp);
812 
813 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
814 static uint_t	tcp_rcv_drain(tcp_t *tcp);
815 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
816 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
817 static void	tcp_ss_rexmit(tcp_t *tcp);
818 static mblk_t	*tcp_input_add_ancillary(tcp_t *tcp, mblk_t *mp, ip_pkt_t *ipp,
819     ip_recv_attr_t *);
820 static void	tcp_process_options(tcp_t *, tcpha_t *);
821 static void	tcp_rsrv(queue_t *q);
822 static int	tcp_snmp_state(tcp_t *tcp);
823 static void	tcp_timer(void *arg);
824 static void	tcp_timer_callback(void *);
825 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
826     boolean_t random);
827 static in_port_t tcp_get_next_priv_port(const tcp_t *);
828 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
829 static void	tcp_wput_fallback(queue_t *q, mblk_t *mp);
830 void		tcp_tpi_accept(queue_t *q, mblk_t *mp);
831 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
832 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
833 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
834 static int	tcp_send(tcp_t *tcp, const int mss,
835 		    const int total_hdr_len, const int tcp_hdr_len,
836 		    const int num_sack_blk, int *usable, uint_t *snxt,
837 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time);
838 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
839 		    int num_sack_blk);
840 static void	tcp_wsrv(queue_t *q);
841 static int	tcp_xmit_end(tcp_t *tcp);
842 static void	tcp_ack_timer(void *arg);
843 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
844 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
845 		    uint32_t seq, uint32_t ack, int ctl, ip_recv_attr_t *,
846 		    ip_stack_t *, conn_t *);
847 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
848 		    uint32_t ack, int ctl);
849 static void	tcp_set_rto(tcp_t *, time_t);
850 static void	tcp_icmp_input(void *, mblk_t *, void *, ip_recv_attr_t *);
851 static void	tcp_icmp_error_ipv6(tcp_t *, mblk_t *, ip_recv_attr_t *);
852 static boolean_t tcp_verifyicmp(conn_t *, void *, icmph_t *, icmp6_t *,
853     ip_recv_attr_t *);
854 static int	tcp_build_hdrs(tcp_t *);
855 static void	tcp_time_wait_append(tcp_t *tcp);
856 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
857     uint32_t seg_seq, uint32_t seg_ack, int seg_len, tcpha_t *tcpha,
858     ip_recv_attr_t *ira);
859 boolean_t	tcp_paws_check(tcp_t *tcp, tcpha_t *tcpha, tcp_opt_t *tcpoptp);
860 static boolean_t tcp_zcopy_check(tcp_t *);
861 static void	tcp_zcopy_notify(tcp_t *);
862 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, boolean_t);
863 static void	tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa);
864 static void	tcp_update_pmtu(tcp_t *tcp, boolean_t decrease_only);
865 static void	tcp_update_zcopy(tcp_t *tcp);
866 static void	tcp_notify(void *, ip_xmit_attr_t *, ixa_notify_type_t,
867     ixa_notify_arg_t);
868 static void	tcp_rexmit_after_error(tcp_t *tcp);
869 static void	tcp_send_data(tcp_t *, mblk_t *);
870 extern mblk_t	*tcp_timermp_alloc(int);
871 extern void	tcp_timermp_free(tcp_t *);
872 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
873 static void	tcp_stop_lingering(tcp_t *tcp);
874 static void	tcp_close_linger_timeout(void *arg);
875 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
876 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
877 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
878 static void	tcp_g_kstat_fini(kstat_t *);
879 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
880 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
881 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
882 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
883 static int	tcp_kstat_update(kstat_t *kp, int rw);
884 static mblk_t	*tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
885     ip_recv_attr_t *ira);
886 static mblk_t	*tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, mblk_t *mp,
887     ip_recv_attr_t *ira);
888 static int	tcp_squeue_switch(int);
889 
890 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
891 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
892 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
893 static int	tcp_tpi_close(queue_t *, int);
894 static int	tcp_tpi_close_accept(queue_t *);
895 
896 static void	tcp_squeue_add(squeue_t *);
897 static void	tcp_setcred_data(mblk_t *, ip_recv_attr_t *);
898 
899 extern void	tcp_kssl_input(tcp_t *, mblk_t *, cred_t *);
900 
901 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy);
902 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2,
903     ip_recv_attr_t *dummy);
904 
905 static int tcp_accept(sock_lower_handle_t, sock_lower_handle_t,
906 	    sock_upper_handle_t, cred_t *);
907 static int tcp_listen(sock_lower_handle_t, int, cred_t *);
908 static int tcp_do_listen(conn_t *, struct sockaddr *, socklen_t, int, cred_t *,
909     boolean_t);
910 static int tcp_do_connect(conn_t *, const struct sockaddr *, socklen_t,
911     cred_t *, pid_t);
912 static int tcp_do_bind(conn_t *, struct sockaddr *, socklen_t, cred_t *,
913     boolean_t);
914 static int tcp_do_unbind(conn_t *);
915 static int tcp_bind_check(conn_t *, struct sockaddr *, socklen_t, cred_t *,
916     boolean_t);
917 
918 static void tcp_ulp_newconn(conn_t *, conn_t *, mblk_t *);
919 
920 static uint32_t tcp_find_listener_conf(tcp_stack_t *, in_port_t);
921 static int tcp_listener_conf_get(queue_t *, mblk_t *, caddr_t, cred_t *);
922 static int tcp_listener_conf_add(queue_t *, mblk_t *, char *, caddr_t,
923     cred_t *);
924 static int tcp_listener_conf_del(queue_t *, mblk_t *, char *, caddr_t,
925     cred_t *);
926 static void tcp_listener_conf_cleanup(tcp_stack_t *);
927 
928 /*
929  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
930  *
931  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
932  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
933  * (defined in tcp.h) needs to be filled in and passed into the kernel
934  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
935  * structure contains the four-tuple of a TCP connection and a range of TCP
936  * states (specified by ac_start and ac_end). The use of wildcard addresses
937  * and ports is allowed. Connections with a matching four tuple and a state
938  * within the specified range will be aborted. The valid states for the
939  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
940  * inclusive.
941  *
942  * An application which has its connection aborted by this ioctl will receive
943  * an error that is dependent on the connection state at the time of the abort.
944  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
945  * though a RST packet has been received.  If the connection state is equal to
946  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
947  * and all resources associated with the connection will be freed.
948  */
949 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
950 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
951 static void	tcp_ioctl_abort_handler(void *arg, mblk_t *mp, void *arg2,
952     ip_recv_attr_t *dummy);
953 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
954 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
955 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
956     boolean_t, tcp_stack_t *);
957 
958 static struct module_info tcp_rinfo =  {
959 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
960 };
961 
962 static struct module_info tcp_winfo =  {
963 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
964 };
965 
966 /*
967  * Entry points for TCP as a device. The normal case which supports
968  * the TCP functionality.
969  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
970  */
971 struct qinit tcp_rinitv4 = {
972 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, NULL, &tcp_rinfo
973 };
974 
975 struct qinit tcp_rinitv6 = {
976 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_tpi_close, NULL, &tcp_rinfo
977 };
978 
979 struct qinit tcp_winit = {
980 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
981 };
982 
983 /* Initial entry point for TCP in socket mode. */
984 struct qinit tcp_sock_winit = {
985 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
986 };
987 
988 /* TCP entry point during fallback */
989 struct qinit tcp_fallback_sock_winit = {
990 	(pfi_t)tcp_wput_fallback, NULL, NULL, NULL, NULL, &tcp_winfo
991 };
992 
993 /*
994  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
995  * an accept. Avoid allocating data structures since eager has already
996  * been created.
997  */
998 struct qinit tcp_acceptor_rinit = {
999 	NULL, (pfi_t)tcp_rsrv, NULL, tcp_tpi_close_accept, NULL, &tcp_winfo
1000 };
1001 
1002 struct qinit tcp_acceptor_winit = {
1003 	(pfi_t)tcp_tpi_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1004 };
1005 
1006 /* For AF_INET aka /dev/tcp */
1007 struct streamtab tcpinfov4 = {
1008 	&tcp_rinitv4, &tcp_winit
1009 };
1010 
1011 /* For AF_INET6 aka /dev/tcp6 */
1012 struct streamtab tcpinfov6 = {
1013 	&tcp_rinitv6, &tcp_winit
1014 };
1015 
1016 sock_downcalls_t sock_tcp_downcalls;
1017 
1018 /* Setable only in /etc/system. Move to ndd? */
1019 boolean_t tcp_icmp_source_quench = B_FALSE;
1020 
1021 /*
1022  * Following assumes TPI alignment requirements stay along 32 bit
1023  * boundaries
1024  */
1025 #define	ROUNDUP32(x) \
1026 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1027 
1028 /* Template for response to info request. */
1029 static struct T_info_ack tcp_g_t_info_ack = {
1030 	T_INFO_ACK,		/* PRIM_type */
1031 	0,			/* TSDU_size */
1032 	T_INFINITE,		/* ETSDU_size */
1033 	T_INVALID,		/* CDATA_size */
1034 	T_INVALID,		/* DDATA_size */
1035 	sizeof (sin_t),		/* ADDR_size */
1036 	0,			/* OPT_size - not initialized here */
1037 	TIDUSZ,			/* TIDU_size */
1038 	T_COTS_ORD,		/* SERV_type */
1039 	TCPS_IDLE,		/* CURRENT_state */
1040 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1041 };
1042 
1043 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1044 	T_INFO_ACK,		/* PRIM_type */
1045 	0,			/* TSDU_size */
1046 	T_INFINITE,		/* ETSDU_size */
1047 	T_INVALID,		/* CDATA_size */
1048 	T_INVALID,		/* DDATA_size */
1049 	sizeof (sin6_t),	/* ADDR_size */
1050 	0,			/* OPT_size - not initialized here */
1051 	TIDUSZ,		/* TIDU_size */
1052 	T_COTS_ORD,		/* SERV_type */
1053 	TCPS_IDLE,		/* CURRENT_state */
1054 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1055 };
1056 
1057 #define	MS	1L
1058 #define	SECONDS	(1000 * MS)
1059 #define	MINUTES	(60 * SECONDS)
1060 #define	HOURS	(60 * MINUTES)
1061 #define	DAYS	(24 * HOURS)
1062 
1063 #define	PARAM_MAX (~(uint32_t)0)
1064 
1065 /* Max size IP datagram is 64k - 1 */
1066 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcpha_t)))
1067 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcpha_t)))
1068 /* Max of the above */
1069 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1070 
1071 /* Largest TCP port number */
1072 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1073 
1074 /*
1075  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1076  * layer header.  It has to be a multiple of 4.
1077  */
1078 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1079 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1080 
1081 #define	MB	(1024 * 1024)
1082 
1083 /*
1084  * All of these are alterable, within the min/max values given, at run time.
1085  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1086  * per the TCP spec.
1087  */
1088 /* BEGIN CSTYLED */
1089 static tcpparam_t	lcl_tcp_param_arr[] = {
1090  /*min		max		value		name */
1091  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1092  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1093  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1094  { 1,		1024,		1,		"tcp_conn_req_min" },
1095  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1096  { 128,		(1<<30),	1*MB,		"tcp_cwnd_max" },
1097  { 0,		10,		0,		"tcp_debug" },
1098  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1099  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1100  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1101  { 500*MS,	PARAM_MAX,	5*MINUTES,	"tcp_ip_abort_interval"},
1102  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1103  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1104  { 1,		255,		64,		"tcp_ipv4_ttl"},
1105  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1106  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1107  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1108  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1109  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1110  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1111  { 1*MS,	20*SECONDS,	1*SECONDS,	"tcp_rexmit_interval_initial"},
1112  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1113  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1114  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1115  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1116  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1117  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1118  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1119  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1120  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1121  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1122  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1123  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1124  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1125  { 8192,	(1<<30),	1*MB,		"tcp_max_buf"},
1126 /*
1127  * Question:  What default value should I set for tcp_strong_iss?
1128  */
1129  { 0,		2,		1,		"tcp_strong_iss"},
1130  { 0,		65536,		20,		"tcp_rtt_updates"},
1131  { 0,		1,		1,		"tcp_wscale_always"},
1132  { 0,		1,		0,		"tcp_tstamp_always"},
1133  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1134  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1135  { 0,		16,		2,		"tcp_deferred_acks_max"},
1136  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1137  { 1,		4,		4,		"tcp_slow_start_initial"},
1138  { 0,		2,		2,		"tcp_sack_permitted"},
1139  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1140  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1141  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1142  { 0,		1,		0,		"tcp_rev_src_routes"},
1143  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1144  { 0,		16,		8,		"tcp_local_dacks_max"},
1145  { 0,		2,		1,		"tcp_ecn_permitted"},
1146  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1147  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1148  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1149  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1150  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1151  { 0,		1,		0,		"tcp_dev_flow_ctl"},
1152  { 0,		PARAM_MAX,	100*SECONDS,	"tcp_reass_timeout"}
1153 };
1154 /* END CSTYLED */
1155 
1156 /* Round up the value to the nearest mss. */
1157 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1158 
1159 /*
1160  * Set ECN capable transport (ECT) code point in IP header.
1161  *
1162  * Note that there are 2 ECT code points '01' and '10', which are called
1163  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1164  * point ECT(0) for TCP as described in RFC 2481.
1165  */
1166 #define	SET_ECT(tcp, iph) \
1167 	if ((tcp)->tcp_connp->conn_ipversion == IPV4_VERSION) { \
1168 		/* We need to clear the code point first. */ \
1169 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1170 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1171 	} else { \
1172 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1173 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1174 	}
1175 
1176 /*
1177  * The format argument to pass to tcp_display().
1178  * DISP_PORT_ONLY means that the returned string has only port info.
1179  * DISP_ADDR_AND_PORT means that the returned string also contains the
1180  * remote and local IP address.
1181  */
1182 #define	DISP_PORT_ONLY		1
1183 #define	DISP_ADDR_AND_PORT	2
1184 
1185 #define	IS_VMLOANED_MBLK(mp) \
1186 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1187 
1188 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1189 
1190 /*
1191  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1192  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1193  * determined dynamically during tcp_set_destination(), which is the default.
1194  */
1195 boolean_t tcp_static_maxpsz = B_FALSE;
1196 
1197 /* Setable in /etc/system */
1198 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1199 uint32_t tcp_random_anon_port = 1;
1200 
1201 /*
1202  * To reach to an eager in Q0 which can be dropped due to an incoming
1203  * new SYN request when Q0 is full, a new doubly linked list is
1204  * introduced. This list allows to select an eager from Q0 in O(1) time.
1205  * This is needed to avoid spending too much time walking through the
1206  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1207  * this new list has to be a member of Q0.
1208  * This list is headed by listener's tcp_t. When the list is empty,
1209  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1210  * of listener's tcp_t point to listener's tcp_t itself.
1211  *
1212  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1213  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1214  * These macros do not affect the eager's membership to Q0.
1215  */
1216 
1217 
1218 #define	MAKE_DROPPABLE(listener, eager)					\
1219 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1220 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1221 		    = (eager);						\
1222 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1223 		(eager)->tcp_eager_next_drop_q0 =			\
1224 		    (listener)->tcp_eager_next_drop_q0;			\
1225 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1226 	}
1227 
1228 #define	MAKE_UNDROPPABLE(eager)						\
1229 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1230 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1231 		    = (eager)->tcp_eager_prev_drop_q0;			\
1232 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1233 		    = (eager)->tcp_eager_next_drop_q0;			\
1234 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1235 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1236 	}
1237 
1238 /*
1239  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1240  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1241  * data, TCP will not respond with an ACK.  RFC 793 requires that
1242  * TCP responds with an ACK for such a bogus ACK.  By not following
1243  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1244  * an attacker successfully spoofs an acceptable segment to our
1245  * peer; or when our peer is "confused."
1246  */
1247 uint32_t tcp_drop_ack_unsent_cnt = 10;
1248 
1249 /*
1250  * Hook functions to enable cluster networking
1251  * On non-clustered systems these vectors must always be NULL.
1252  */
1253 
1254 void (*cl_inet_listen)(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 void (*cl_inet_unlisten)(netstackid_t stack_id, uint8_t protocol,
1258 			    sa_family_t addr_family, uint8_t *laddrp,
1259 			    in_port_t lport, void *args) = NULL;
1260 
1261 int (*cl_inet_connect2)(netstackid_t stack_id, uint8_t protocol,
1262 			    boolean_t is_outgoing,
1263 			    sa_family_t addr_family,
1264 			    uint8_t *laddrp, in_port_t lport,
1265 			    uint8_t *faddrp, in_port_t fport,
1266 			    void *args) = NULL;
1267 void (*cl_inet_disconnect)(netstackid_t stack_id, uint8_t protocol,
1268 			    sa_family_t addr_family, uint8_t *laddrp,
1269 			    in_port_t lport, uint8_t *faddrp,
1270 			    in_port_t fport, void *args) = NULL;
1271 
1272 
1273 /*
1274  * int CL_INET_CONNECT(conn_t *cp, tcp_t *tcp, boolean_t is_outgoing, int err)
1275  */
1276 #define	CL_INET_CONNECT(connp, is_outgoing, err) {		\
1277 	(err) = 0;						\
1278 	if (cl_inet_connect2 != NULL) {				\
1279 		/*						\
1280 		 * Running in cluster mode - register active connection	\
1281 		 * information						\
1282 		 */							\
1283 		if ((connp)->conn_ipversion == IPV4_VERSION) {		\
1284 			if ((connp)->conn_laddr_v4 != 0) {		\
1285 				(err) = (*cl_inet_connect2)(		\
1286 				    (connp)->conn_netstack->netstack_stackid,\
1287 				    IPPROTO_TCP, is_outgoing, AF_INET,	\
1288 				    (uint8_t *)(&((connp)->conn_laddr_v4)),\
1289 				    (in_port_t)(connp)->conn_lport,	\
1290 				    (uint8_t *)(&((connp)->conn_faddr_v4)),\
1291 				    (in_port_t)(connp)->conn_fport, NULL); \
1292 			}						\
1293 		} else {						\
1294 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1295 			    &(connp)->conn_laddr_v6)) {			\
1296 				(err) = (*cl_inet_connect2)(		\
1297 				    (connp)->conn_netstack->netstack_stackid,\
1298 				    IPPROTO_TCP, is_outgoing, AF_INET6,	\
1299 				    (uint8_t *)(&((connp)->conn_laddr_v6)),\
1300 				    (in_port_t)(connp)->conn_lport,	\
1301 				    (uint8_t *)(&((connp)->conn_faddr_v6)), \
1302 				    (in_port_t)(connp)->conn_fport, NULL); \
1303 			}						\
1304 		}							\
1305 	}								\
1306 }
1307 
1308 #define	CL_INET_DISCONNECT(connp)	{				\
1309 	if (cl_inet_disconnect != NULL) {				\
1310 		/*							\
1311 		 * Running in cluster mode - deregister active		\
1312 		 * connection information				\
1313 		 */							\
1314 		if ((connp)->conn_ipversion == IPV4_VERSION) {		\
1315 			if ((connp)->conn_laddr_v4 != 0) {		\
1316 				(*cl_inet_disconnect)(			\
1317 				    (connp)->conn_netstack->netstack_stackid,\
1318 				    IPPROTO_TCP, AF_INET,		\
1319 				    (uint8_t *)(&((connp)->conn_laddr_v4)),\
1320 				    (in_port_t)(connp)->conn_lport,	\
1321 				    (uint8_t *)(&((connp)->conn_faddr_v4)),\
1322 				    (in_port_t)(connp)->conn_fport, NULL); \
1323 			}						\
1324 		} else {						\
1325 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1326 			    &(connp)->conn_laddr_v6)) {			\
1327 				(*cl_inet_disconnect)(			\
1328 				    (connp)->conn_netstack->netstack_stackid,\
1329 				    IPPROTO_TCP, AF_INET6,		\
1330 				    (uint8_t *)(&((connp)->conn_laddr_v6)),\
1331 				    (in_port_t)(connp)->conn_lport,	\
1332 				    (uint8_t *)(&((connp)->conn_faddr_v6)), \
1333 				    (in_port_t)(connp)->conn_fport, NULL); \
1334 			}						\
1335 		}							\
1336 	}								\
1337 }
1338 
1339 /*
1340  * Steps to do when a tcp_t moves to TIME-WAIT state.
1341  *
1342  * This connection is done, we don't need to account for it.  Decrement
1343  * the listener connection counter if needed.
1344  *
1345  * Unconditionally clear the exclusive binding bit so this TIME-WAIT
1346  * connection won't interfere with new ones.
1347  *
1348  * Start the TIME-WAIT timer.  If upper layer has not closed the connection,
1349  * the timer is handled within the context of this tcp_t.  When the timer
1350  * fires, tcp_clean_death() is called.  If upper layer closes the connection
1351  * during this period, tcp_time_wait_append() will be called to add this
1352  * tcp_t to the global TIME-WAIT list.  Note that this means that the
1353  * actual wait time in TIME-WAIT state will be longer than the
1354  * tcps_time_wait_interval since the period before upper layer closes the
1355  * connection is not accounted for when tcp_time_wait_append() is called.
1356  *
1357  * If uppser layer has closed the connection, call tcp_time_wait_append()
1358  * directly.
1359  */
1360 #define	SET_TIME_WAIT(tcps, tcp, connp)				\
1361 {								\
1362 	(tcp)->tcp_state = TCPS_TIME_WAIT;			\
1363 	if ((tcp)->tcp_listen_cnt != NULL)			\
1364 		TCP_DECR_LISTEN_CNT(tcp);			\
1365 	(connp)->conn_exclbind = 0;				\
1366 	if (!TCP_IS_DETACHED(tcp)) {				\
1367 		TCP_TIMER_RESTART(tcp, (tcps)->tcps_time_wait_interval); \
1368 	} else {						\
1369 		tcp_time_wait_append(tcp);			\
1370 		TCP_DBGSTAT(tcps, tcp_rput_time_wait);		\
1371 	}							\
1372 }
1373 
1374 /*
1375  * Cluster networking hook for traversing current connection list.
1376  * This routine is used to extract the current list of live connections
1377  * which must continue to to be dispatched to this node.
1378  */
1379 int cl_tcp_walk_list(netstackid_t stack_id,
1380     int (*callback)(cl_tcp_info_t *, void *), void *arg);
1381 
1382 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1383     void *arg, tcp_stack_t *tcps);
1384 
1385 static void
1386 tcp_set_recv_threshold(tcp_t *tcp, uint32_t new_rcvthresh)
1387 {
1388 	uint32_t default_threshold = SOCKET_RECVHIWATER >> 3;
1389 
1390 	if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
1391 		conn_t *connp = tcp->tcp_connp;
1392 		struct sock_proto_props sopp;
1393 
1394 		/*
1395 		 * only increase rcvthresh upto default_threshold
1396 		 */
1397 		if (new_rcvthresh > default_threshold)
1398 			new_rcvthresh = default_threshold;
1399 
1400 		sopp.sopp_flags = SOCKOPT_RCVTHRESH;
1401 		sopp.sopp_rcvthresh = new_rcvthresh;
1402 
1403 		(*connp->conn_upcalls->su_set_proto_props)
1404 		    (connp->conn_upper_handle, &sopp);
1405 	}
1406 }
1407 /*
1408  * Figure out the value of window scale opton.  Note that the rwnd is
1409  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1410  * We cannot find the scale value and then do a round up of tcp_rwnd
1411  * because the scale value may not be correct after that.
1412  *
1413  * Set the compiler flag to make this function inline.
1414  */
1415 static void
1416 tcp_set_ws_value(tcp_t *tcp)
1417 {
1418 	int i;
1419 	uint32_t rwnd = tcp->tcp_rwnd;
1420 
1421 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1422 	    i++, rwnd >>= 1)
1423 		;
1424 	tcp->tcp_rcv_ws = i;
1425 }
1426 
1427 /*
1428  * Remove a connection from the list of detached TIME_WAIT connections.
1429  * It returns B_FALSE if it can't remove the connection from the list
1430  * as the connection has already been removed from the list due to an
1431  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1432  */
1433 static boolean_t
1434 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1435 {
1436 	boolean_t	locked = B_FALSE;
1437 
1438 	if (tcp_time_wait == NULL) {
1439 		tcp_time_wait = *((tcp_squeue_priv_t **)
1440 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1441 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1442 		locked = B_TRUE;
1443 	} else {
1444 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1445 	}
1446 
1447 	if (tcp->tcp_time_wait_expire == 0) {
1448 		ASSERT(tcp->tcp_time_wait_next == NULL);
1449 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1450 		if (locked)
1451 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1452 		return (B_FALSE);
1453 	}
1454 	ASSERT(TCP_IS_DETACHED(tcp));
1455 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1456 
1457 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1458 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1459 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1460 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1461 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1462 			    NULL;
1463 		} else {
1464 			tcp_time_wait->tcp_time_wait_tail = NULL;
1465 		}
1466 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1467 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1468 		ASSERT(tcp->tcp_time_wait_next == NULL);
1469 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1470 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1471 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1472 	} else {
1473 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1474 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1475 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1476 		    tcp->tcp_time_wait_next;
1477 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1478 		    tcp->tcp_time_wait_prev;
1479 	}
1480 	tcp->tcp_time_wait_next = NULL;
1481 	tcp->tcp_time_wait_prev = NULL;
1482 	tcp->tcp_time_wait_expire = 0;
1483 
1484 	if (locked)
1485 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1486 	return (B_TRUE);
1487 }
1488 
1489 /*
1490  * Add a connection to the list of detached TIME_WAIT connections
1491  * and set its time to expire.
1492  */
1493 static void
1494 tcp_time_wait_append(tcp_t *tcp)
1495 {
1496 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1497 	tcp_squeue_priv_t *tcp_time_wait =
1498 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1499 	    SQPRIVATE_TCP));
1500 
1501 	tcp_timers_stop(tcp);
1502 
1503 	/* Freed above */
1504 	ASSERT(tcp->tcp_timer_tid == 0);
1505 	ASSERT(tcp->tcp_ack_tid == 0);
1506 
1507 	/* must have happened at the time of detaching the tcp */
1508 	ASSERT(tcp->tcp_ptpahn == NULL);
1509 	ASSERT(tcp->tcp_flow_stopped == 0);
1510 	ASSERT(tcp->tcp_time_wait_next == NULL);
1511 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1512 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1513 	ASSERT(tcp->tcp_listener == NULL);
1514 
1515 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1516 	/*
1517 	 * The value computed below in tcp->tcp_time_wait_expire may
1518 	 * appear negative or wrap around. That is ok since our
1519 	 * interest is only in the difference between the current lbolt
1520 	 * value and tcp->tcp_time_wait_expire. But the value should not
1521 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1522 	 * The corresponding comparison in tcp_time_wait_collector() uses
1523 	 * modular arithmetic.
1524 	 */
1525 	tcp->tcp_time_wait_expire +=
1526 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1527 	if (tcp->tcp_time_wait_expire == 0)
1528 		tcp->tcp_time_wait_expire = 1;
1529 
1530 	ASSERT(TCP_IS_DETACHED(tcp));
1531 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1532 	ASSERT(tcp->tcp_time_wait_next == NULL);
1533 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1534 	TCP_DBGSTAT(tcps, tcp_time_wait);
1535 
1536 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1537 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1538 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1539 		tcp_time_wait->tcp_time_wait_head = tcp;
1540 	} else {
1541 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1542 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1543 		    TCPS_TIME_WAIT);
1544 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1545 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1546 	}
1547 	tcp_time_wait->tcp_time_wait_tail = tcp;
1548 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1549 }
1550 
1551 /* ARGSUSED */
1552 void
1553 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
1554 {
1555 	conn_t	*connp = (conn_t *)arg;
1556 	tcp_t	*tcp = connp->conn_tcp;
1557 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1558 
1559 	ASSERT(tcp != NULL);
1560 	if (tcp->tcp_state == TCPS_CLOSED) {
1561 		return;
1562 	}
1563 
1564 	ASSERT((connp->conn_family == AF_INET &&
1565 	    connp->conn_ipversion == IPV4_VERSION) ||
1566 	    (connp->conn_family == AF_INET6 &&
1567 	    (connp->conn_ipversion == IPV4_VERSION ||
1568 	    connp->conn_ipversion == IPV6_VERSION)));
1569 	ASSERT(!tcp->tcp_listener);
1570 
1571 	TCP_STAT(tcps, tcp_time_wait_reap);
1572 	ASSERT(TCP_IS_DETACHED(tcp));
1573 
1574 	/*
1575 	 * Because they have no upstream client to rebind or tcp_close()
1576 	 * them later, we axe the connection here and now.
1577 	 */
1578 	tcp_close_detached(tcp);
1579 }
1580 
1581 /*
1582  * Remove cached/latched IPsec references.
1583  */
1584 void
1585 tcp_ipsec_cleanup(tcp_t *tcp)
1586 {
1587 	conn_t		*connp = tcp->tcp_connp;
1588 
1589 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1590 
1591 	if (connp->conn_latch != NULL) {
1592 		IPLATCH_REFRELE(connp->conn_latch);
1593 		connp->conn_latch = NULL;
1594 	}
1595 	if (connp->conn_latch_in_policy != NULL) {
1596 		IPPOL_REFRELE(connp->conn_latch_in_policy);
1597 		connp->conn_latch_in_policy = NULL;
1598 	}
1599 	if (connp->conn_latch_in_action != NULL) {
1600 		IPACT_REFRELE(connp->conn_latch_in_action);
1601 		connp->conn_latch_in_action = NULL;
1602 	}
1603 	if (connp->conn_policy != NULL) {
1604 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1605 		connp->conn_policy = NULL;
1606 	}
1607 }
1608 
1609 /*
1610  * Cleaup before placing on free list.
1611  * Disassociate from the netstack/tcp_stack_t since the freelist
1612  * is per squeue and not per netstack.
1613  */
1614 void
1615 tcp_cleanup(tcp_t *tcp)
1616 {
1617 	mblk_t		*mp;
1618 	tcp_sack_info_t	*tcp_sack_info;
1619 	conn_t		*connp = tcp->tcp_connp;
1620 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1621 	netstack_t	*ns = tcps->tcps_netstack;
1622 	mblk_t		*tcp_rsrv_mp;
1623 
1624 	tcp_bind_hash_remove(tcp);
1625 
1626 	/* Cleanup that which needs the netstack first */
1627 	tcp_ipsec_cleanup(tcp);
1628 	ixa_cleanup(connp->conn_ixa);
1629 
1630 	if (connp->conn_ht_iphc != NULL) {
1631 		kmem_free(connp->conn_ht_iphc, connp->conn_ht_iphc_allocated);
1632 		connp->conn_ht_iphc = NULL;
1633 		connp->conn_ht_iphc_allocated = 0;
1634 		connp->conn_ht_iphc_len = 0;
1635 		connp->conn_ht_ulp = NULL;
1636 		connp->conn_ht_ulp_len = 0;
1637 		tcp->tcp_ipha = NULL;
1638 		tcp->tcp_ip6h = NULL;
1639 		tcp->tcp_tcpha = NULL;
1640 	}
1641 
1642 	/* We clear any IP_OPTIONS and extension headers */
1643 	ip_pkt_free(&connp->conn_xmit_ipp);
1644 
1645 	tcp_free(tcp);
1646 
1647 	/* Release any SSL context */
1648 	if (tcp->tcp_kssl_ent != NULL) {
1649 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1650 		tcp->tcp_kssl_ent = NULL;
1651 	}
1652 
1653 	if (tcp->tcp_kssl_ctx != NULL) {
1654 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1655 		tcp->tcp_kssl_ctx = NULL;
1656 	}
1657 	tcp->tcp_kssl_pending = B_FALSE;
1658 
1659 	/*
1660 	 * Since we will bzero the entire structure, we need to
1661 	 * remove it and reinsert it in global hash list. We
1662 	 * know the walkers can't get to this conn because we
1663 	 * had set CONDEMNED flag earlier and checked reference
1664 	 * under conn_lock so walker won't pick it and when we
1665 	 * go the ipcl_globalhash_remove() below, no walker
1666 	 * can get to it.
1667 	 */
1668 	ipcl_globalhash_remove(connp);
1669 
1670 	/* Save some state */
1671 	mp = tcp->tcp_timercache;
1672 
1673 	tcp_sack_info = tcp->tcp_sack_info;
1674 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1675 
1676 	if (connp->conn_cred != NULL) {
1677 		crfree(connp->conn_cred);
1678 		connp->conn_cred = NULL;
1679 	}
1680 	ipcl_conn_cleanup(connp);
1681 	connp->conn_flags = IPCL_TCPCONN;
1682 
1683 	/*
1684 	 * Now it is safe to decrement the reference counts.
1685 	 * This might be the last reference on the netstack
1686 	 * in which case it will cause the freeing of the IP Instance.
1687 	 */
1688 	connp->conn_netstack = NULL;
1689 	connp->conn_ixa->ixa_ipst = NULL;
1690 	netstack_rele(ns);
1691 	ASSERT(tcps != NULL);
1692 	tcp->tcp_tcps = NULL;
1693 
1694 	bzero(tcp, sizeof (tcp_t));
1695 
1696 	/* restore the state */
1697 	tcp->tcp_timercache = mp;
1698 
1699 	tcp->tcp_sack_info = tcp_sack_info;
1700 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1701 
1702 	tcp->tcp_connp = connp;
1703 
1704 	ASSERT(connp->conn_tcp == tcp);
1705 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1706 	connp->conn_state_flags = CONN_INCIPIENT;
1707 	ASSERT(connp->conn_proto == IPPROTO_TCP);
1708 	ASSERT(connp->conn_ref == 1);
1709 }
1710 
1711 /*
1712  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1713  * is done forwards from the head.
1714  * This walks all stack instances since
1715  * tcp_time_wait remains global across all stacks.
1716  */
1717 /* ARGSUSED */
1718 void
1719 tcp_time_wait_collector(void *arg)
1720 {
1721 	tcp_t *tcp;
1722 	clock_t now;
1723 	mblk_t *mp;
1724 	conn_t *connp;
1725 	kmutex_t *lock;
1726 	boolean_t removed;
1727 
1728 	squeue_t *sqp = (squeue_t *)arg;
1729 	tcp_squeue_priv_t *tcp_time_wait =
1730 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1731 
1732 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1733 	tcp_time_wait->tcp_time_wait_tid = 0;
1734 
1735 	if (tcp_time_wait->tcp_free_list != NULL &&
1736 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1737 		TCP_G_STAT(tcp_freelist_cleanup);
1738 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1739 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1740 			tcp->tcp_time_wait_next = NULL;
1741 			tcp_time_wait->tcp_free_list_cnt--;
1742 			ASSERT(tcp->tcp_tcps == NULL);
1743 			CONN_DEC_REF(tcp->tcp_connp);
1744 		}
1745 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1746 	}
1747 
1748 	/*
1749 	 * In order to reap time waits reliably, we should use a
1750 	 * source of time that is not adjustable by the user -- hence
1751 	 * the call to ddi_get_lbolt().
1752 	 */
1753 	now = ddi_get_lbolt();
1754 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1755 		/*
1756 		 * Compare times using modular arithmetic, since
1757 		 * lbolt can wrapover.
1758 		 */
1759 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1760 			break;
1761 		}
1762 
1763 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1764 		ASSERT(removed);
1765 
1766 		connp = tcp->tcp_connp;
1767 		ASSERT(connp->conn_fanout != NULL);
1768 		lock = &connp->conn_fanout->connf_lock;
1769 		/*
1770 		 * This is essentially a TW reclaim fast path optimization for
1771 		 * performance where the timewait collector checks under the
1772 		 * fanout lock (so that no one else can get access to the
1773 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1774 		 * the classifier hash list. If ref count is indeed 2, we can
1775 		 * just remove the conn under the fanout lock and avoid
1776 		 * cleaning up the conn under the squeue, provided that
1777 		 * clustering callbacks are not enabled. If clustering is
1778 		 * enabled, we need to make the clustering callback before
1779 		 * setting the CONDEMNED flag and after dropping all locks and
1780 		 * so we forego this optimization and fall back to the slow
1781 		 * path. Also please see the comments in tcp_closei_local
1782 		 * regarding the refcnt logic.
1783 		 *
1784 		 * Since we are holding the tcp_time_wait_lock, its better
1785 		 * not to block on the fanout_lock because other connections
1786 		 * can't add themselves to time_wait list. So we do a
1787 		 * tryenter instead of mutex_enter.
1788 		 */
1789 		if (mutex_tryenter(lock)) {
1790 			mutex_enter(&connp->conn_lock);
1791 			if ((connp->conn_ref == 2) &&
1792 			    (cl_inet_disconnect == NULL)) {
1793 				ipcl_hash_remove_locked(connp,
1794 				    connp->conn_fanout);
1795 				/*
1796 				 * Set the CONDEMNED flag now itself so that
1797 				 * the refcnt cannot increase due to any
1798 				 * walker.
1799 				 */
1800 				connp->conn_state_flags |= CONN_CONDEMNED;
1801 				mutex_exit(lock);
1802 				mutex_exit(&connp->conn_lock);
1803 				if (tcp_time_wait->tcp_free_list_cnt <
1804 				    tcp_free_list_max_cnt) {
1805 					/* Add to head of tcp_free_list */
1806 					mutex_exit(
1807 					    &tcp_time_wait->tcp_time_wait_lock);
1808 					tcp_cleanup(tcp);
1809 					ASSERT(connp->conn_latch == NULL);
1810 					ASSERT(connp->conn_policy == NULL);
1811 					ASSERT(tcp->tcp_tcps == NULL);
1812 					ASSERT(connp->conn_netstack == NULL);
1813 
1814 					mutex_enter(
1815 					    &tcp_time_wait->tcp_time_wait_lock);
1816 					tcp->tcp_time_wait_next =
1817 					    tcp_time_wait->tcp_free_list;
1818 					tcp_time_wait->tcp_free_list = tcp;
1819 					tcp_time_wait->tcp_free_list_cnt++;
1820 					continue;
1821 				} else {
1822 					/* Do not add to tcp_free_list */
1823 					mutex_exit(
1824 					    &tcp_time_wait->tcp_time_wait_lock);
1825 					tcp_bind_hash_remove(tcp);
1826 					ixa_cleanup(tcp->tcp_connp->conn_ixa);
1827 					tcp_ipsec_cleanup(tcp);
1828 					CONN_DEC_REF(tcp->tcp_connp);
1829 				}
1830 			} else {
1831 				CONN_INC_REF_LOCKED(connp);
1832 				mutex_exit(lock);
1833 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1834 				mutex_exit(&connp->conn_lock);
1835 				/*
1836 				 * We can reuse the closemp here since conn has
1837 				 * detached (otherwise we wouldn't even be in
1838 				 * time_wait list). tcp_closemp_used can safely
1839 				 * be changed without taking a lock as no other
1840 				 * thread can concurrently access it at this
1841 				 * point in the connection lifecycle.
1842 				 */
1843 
1844 				if (tcp->tcp_closemp.b_prev == NULL)
1845 					tcp->tcp_closemp_used = B_TRUE;
1846 				else
1847 					cmn_err(CE_PANIC,
1848 					    "tcp_timewait_collector: "
1849 					    "concurrent use of tcp_closemp: "
1850 					    "connp %p tcp %p\n", (void *)connp,
1851 					    (void *)tcp);
1852 
1853 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1854 				mp = &tcp->tcp_closemp;
1855 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1856 				    tcp_timewait_output, connp, NULL,
1857 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1858 			}
1859 		} else {
1860 			mutex_enter(&connp->conn_lock);
1861 			CONN_INC_REF_LOCKED(connp);
1862 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1863 			mutex_exit(&connp->conn_lock);
1864 			/*
1865 			 * We can reuse the closemp here since conn has
1866 			 * detached (otherwise we wouldn't even be in
1867 			 * time_wait list). tcp_closemp_used can safely
1868 			 * be changed without taking a lock as no other
1869 			 * thread can concurrently access it at this
1870 			 * point in the connection lifecycle.
1871 			 */
1872 
1873 			if (tcp->tcp_closemp.b_prev == NULL)
1874 				tcp->tcp_closemp_used = B_TRUE;
1875 			else
1876 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1877 				    "concurrent use of tcp_closemp: "
1878 				    "connp %p tcp %p\n", (void *)connp,
1879 				    (void *)tcp);
1880 
1881 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1882 			mp = &tcp->tcp_closemp;
1883 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1884 			    tcp_timewait_output, connp, NULL,
1885 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1886 		}
1887 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1888 	}
1889 
1890 	if (tcp_time_wait->tcp_free_list != NULL)
1891 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1892 
1893 	tcp_time_wait->tcp_time_wait_tid =
1894 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1895 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1896 	    CALLOUT_FLAG_ROUNDUP);
1897 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1898 }
1899 
1900 /*
1901  * Reply to a clients T_CONN_RES TPI message. This function
1902  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1903  * on the acceptor STREAM and processed in tcp_accept_common().
1904  * Read the block comment on top of tcp_input_listener().
1905  */
1906 static void
1907 tcp_tli_accept(tcp_t *listener, mblk_t *mp)
1908 {
1909 	tcp_t		*acceptor;
1910 	tcp_t		*eager;
1911 	tcp_t   	*tcp;
1912 	struct T_conn_res	*tcr;
1913 	t_uscalar_t	acceptor_id;
1914 	t_scalar_t	seqnum;
1915 	mblk_t		*discon_mp = NULL;
1916 	mblk_t		*ok_mp;
1917 	mblk_t		*mp1;
1918 	tcp_stack_t	*tcps = listener->tcp_tcps;
1919 	conn_t		*econnp;
1920 
1921 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1922 		tcp_err_ack(listener, mp, TPROTO, 0);
1923 		return;
1924 	}
1925 	tcr = (struct T_conn_res *)mp->b_rptr;
1926 
1927 	/*
1928 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1929 	 * read side queue of the streams device underneath us i.e. the
1930 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1931 	 * look it up in the queue_hash.  Under LP64 it sends down the
1932 	 * minor_t of the accepting endpoint.
1933 	 *
1934 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1935 	 * fanout hash lock is held.
1936 	 * This prevents any thread from entering the acceptor queue from
1937 	 * below (since it has not been hard bound yet i.e. any inbound
1938 	 * packets will arrive on the listener conn_t and
1939 	 * go through the classifier).
1940 	 * The CONN_INC_REF will prevent the acceptor from closing.
1941 	 *
1942 	 * XXX It is still possible for a tli application to send down data
1943 	 * on the accepting stream while another thread calls t_accept.
1944 	 * This should not be a problem for well-behaved applications since
1945 	 * the T_OK_ACK is sent after the queue swapping is completed.
1946 	 *
1947 	 * If the accepting fd is the same as the listening fd, avoid
1948 	 * queue hash lookup since that will return an eager listener in a
1949 	 * already established state.
1950 	 */
1951 	acceptor_id = tcr->ACCEPTOR_id;
1952 	mutex_enter(&listener->tcp_eager_lock);
1953 	if (listener->tcp_acceptor_id == acceptor_id) {
1954 		eager = listener->tcp_eager_next_q;
1955 		/* only count how many T_CONN_INDs so don't count q0 */
1956 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1957 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1958 			mutex_exit(&listener->tcp_eager_lock);
1959 			tcp_err_ack(listener, mp, TBADF, 0);
1960 			return;
1961 		}
1962 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1963 			/* Throw away all the eagers on q0. */
1964 			tcp_eager_cleanup(listener, 1);
1965 		}
1966 		if (listener->tcp_syn_defense) {
1967 			listener->tcp_syn_defense = B_FALSE;
1968 			if (listener->tcp_ip_addr_cache != NULL) {
1969 				kmem_free(listener->tcp_ip_addr_cache,
1970 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1971 				listener->tcp_ip_addr_cache = NULL;
1972 			}
1973 		}
1974 		/*
1975 		 * Transfer tcp_conn_req_max to the eager so that when
1976 		 * a disconnect occurs we can revert the endpoint to the
1977 		 * listen state.
1978 		 */
1979 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1980 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1981 		/*
1982 		 * Get a reference on the acceptor just like the
1983 		 * tcp_acceptor_hash_lookup below.
1984 		 */
1985 		acceptor = listener;
1986 		CONN_INC_REF(acceptor->tcp_connp);
1987 	} else {
1988 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
1989 		if (acceptor == NULL) {
1990 			if (listener->tcp_connp->conn_debug) {
1991 				(void) strlog(TCP_MOD_ID, 0, 1,
1992 				    SL_ERROR|SL_TRACE,
1993 				    "tcp_accept: did not find acceptor 0x%x\n",
1994 				    acceptor_id);
1995 			}
1996 			mutex_exit(&listener->tcp_eager_lock);
1997 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1998 			return;
1999 		}
2000 		/*
2001 		 * Verify acceptor state. The acceptable states for an acceptor
2002 		 * include TCPS_IDLE and TCPS_BOUND.
2003 		 */
2004 		switch (acceptor->tcp_state) {
2005 		case TCPS_IDLE:
2006 			/* FALLTHRU */
2007 		case TCPS_BOUND:
2008 			break;
2009 		default:
2010 			CONN_DEC_REF(acceptor->tcp_connp);
2011 			mutex_exit(&listener->tcp_eager_lock);
2012 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2013 			return;
2014 		}
2015 	}
2016 
2017 	/* The listener must be in TCPS_LISTEN */
2018 	if (listener->tcp_state != TCPS_LISTEN) {
2019 		CONN_DEC_REF(acceptor->tcp_connp);
2020 		mutex_exit(&listener->tcp_eager_lock);
2021 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2022 		return;
2023 	}
2024 
2025 	/*
2026 	 * Rendezvous with an eager connection request packet hanging off
2027 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2028 	 * tcp structure when the connection packet arrived in
2029 	 * tcp_input_listener().
2030 	 */
2031 	seqnum = tcr->SEQ_number;
2032 	eager = listener;
2033 	do {
2034 		eager = eager->tcp_eager_next_q;
2035 		if (eager == NULL) {
2036 			CONN_DEC_REF(acceptor->tcp_connp);
2037 			mutex_exit(&listener->tcp_eager_lock);
2038 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2039 			return;
2040 		}
2041 	} while (eager->tcp_conn_req_seqnum != seqnum);
2042 	mutex_exit(&listener->tcp_eager_lock);
2043 
2044 	/*
2045 	 * At this point, both acceptor and listener have 2 ref
2046 	 * that they begin with. Acceptor has one additional ref
2047 	 * we placed in lookup while listener has 3 additional
2048 	 * ref for being behind the squeue (tcp_accept() is
2049 	 * done on listener's squeue); being in classifier hash;
2050 	 * and eager's ref on listener.
2051 	 */
2052 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2053 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2054 
2055 	/*
2056 	 * The eager at this point is set in its own squeue and
2057 	 * could easily have been killed (tcp_accept_finish will
2058 	 * deal with that) because of a TH_RST so we can only
2059 	 * ASSERT for a single ref.
2060 	 */
2061 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2062 
2063 	/*
2064 	 * Pre allocate the discon_ind mblk also. tcp_accept_finish will
2065 	 * use it if something failed.
2066 	 */
2067 	discon_mp = allocb(MAX(sizeof (struct T_discon_ind),
2068 	    sizeof (struct stroptions)), BPRI_HI);
2069 	if (discon_mp == NULL) {
2070 		CONN_DEC_REF(acceptor->tcp_connp);
2071 		CONN_DEC_REF(eager->tcp_connp);
2072 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2073 		return;
2074 	}
2075 
2076 	econnp = eager->tcp_connp;
2077 
2078 	/* Hold a copy of mp, in case reallocb fails */
2079 	if ((mp1 = copymsg(mp)) == NULL) {
2080 		CONN_DEC_REF(acceptor->tcp_connp);
2081 		CONN_DEC_REF(eager->tcp_connp);
2082 		freemsg(discon_mp);
2083 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2084 		return;
2085 	}
2086 
2087 	tcr = (struct T_conn_res *)mp1->b_rptr;
2088 
2089 	/*
2090 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2091 	 * which allocates a larger mblk and appends the new
2092 	 * local address to the ok_ack.  The address is copied by
2093 	 * soaccept() for getsockname().
2094 	 */
2095 	{
2096 		int extra;
2097 
2098 		extra = (econnp->conn_family == AF_INET) ?
2099 		    sizeof (sin_t) : sizeof (sin6_t);
2100 
2101 		/*
2102 		 * Try to re-use mp, if possible.  Otherwise, allocate
2103 		 * an mblk and return it as ok_mp.  In any case, mp
2104 		 * is no longer usable upon return.
2105 		 */
2106 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2107 			CONN_DEC_REF(acceptor->tcp_connp);
2108 			CONN_DEC_REF(eager->tcp_connp);
2109 			freemsg(discon_mp);
2110 			/* Original mp has been freed by now, so use mp1 */
2111 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2112 			return;
2113 		}
2114 
2115 		mp = NULL;	/* We should never use mp after this point */
2116 
2117 		switch (extra) {
2118 		case sizeof (sin_t): {
2119 			sin_t *sin = (sin_t *)ok_mp->b_wptr;
2120 
2121 			ok_mp->b_wptr += extra;
2122 			sin->sin_family = AF_INET;
2123 			sin->sin_port = econnp->conn_lport;
2124 			sin->sin_addr.s_addr = econnp->conn_laddr_v4;
2125 			break;
2126 		}
2127 		case sizeof (sin6_t): {
2128 			sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2129 
2130 			ok_mp->b_wptr += extra;
2131 			sin6->sin6_family = AF_INET6;
2132 			sin6->sin6_port = econnp->conn_lport;
2133 			sin6->sin6_addr = econnp->conn_laddr_v6;
2134 			sin6->sin6_flowinfo = econnp->conn_flowinfo;
2135 			if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6) &&
2136 			    (econnp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)) {
2137 				sin6->sin6_scope_id =
2138 				    econnp->conn_ixa->ixa_scopeid;
2139 			} else {
2140 				sin6->sin6_scope_id = 0;
2141 			}
2142 			sin6->__sin6_src_id = 0;
2143 			break;
2144 		}
2145 		default:
2146 			break;
2147 		}
2148 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2149 	}
2150 
2151 	/*
2152 	 * If there are no options we know that the T_CONN_RES will
2153 	 * succeed. However, we can't send the T_OK_ACK upstream until
2154 	 * the tcp_accept_swap is done since it would be dangerous to
2155 	 * let the application start using the new fd prior to the swap.
2156 	 */
2157 	tcp_accept_swap(listener, acceptor, eager);
2158 
2159 	/*
2160 	 * tcp_accept_swap unlinks eager from listener but does not drop
2161 	 * the eager's reference on the listener.
2162 	 */
2163 	ASSERT(eager->tcp_listener == NULL);
2164 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2165 
2166 	/*
2167 	 * The eager is now associated with its own queue. Insert in
2168 	 * the hash so that the connection can be reused for a future
2169 	 * T_CONN_RES.
2170 	 */
2171 	tcp_acceptor_hash_insert(acceptor_id, eager);
2172 
2173 	/*
2174 	 * We now do the processing of options with T_CONN_RES.
2175 	 * We delay till now since we wanted to have queue to pass to
2176 	 * option processing routines that points back to the right
2177 	 * instance structure which does not happen until after
2178 	 * tcp_accept_swap().
2179 	 *
2180 	 * Note:
2181 	 * The sanity of the logic here assumes that whatever options
2182 	 * are appropriate to inherit from listner=>eager are done
2183 	 * before this point, and whatever were to be overridden (or not)
2184 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2185 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2186 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2187 	 * This may not be true at this point in time but can be fixed
2188 	 * independently. This option processing code starts with
2189 	 * the instantiated acceptor instance and the final queue at
2190 	 * this point.
2191 	 */
2192 
2193 	if (tcr->OPT_length != 0) {
2194 		/* Options to process */
2195 		int t_error = 0;
2196 		int sys_error = 0;
2197 		int do_disconnect = 0;
2198 
2199 		if (tcp_conprim_opt_process(eager, mp1,
2200 		    &do_disconnect, &t_error, &sys_error) < 0) {
2201 			eager->tcp_accept_error = 1;
2202 			if (do_disconnect) {
2203 				/*
2204 				 * An option failed which does not allow
2205 				 * connection to be accepted.
2206 				 *
2207 				 * We allow T_CONN_RES to succeed and
2208 				 * put a T_DISCON_IND on the eager queue.
2209 				 */
2210 				ASSERT(t_error == 0 && sys_error == 0);
2211 				eager->tcp_send_discon_ind = 1;
2212 			} else {
2213 				ASSERT(t_error != 0);
2214 				freemsg(ok_mp);
2215 				/*
2216 				 * Original mp was either freed or set
2217 				 * to ok_mp above, so use mp1 instead.
2218 				 */
2219 				tcp_err_ack(listener, mp1, t_error, sys_error);
2220 				goto finish;
2221 			}
2222 		}
2223 		/*
2224 		 * Most likely success in setting options (except if
2225 		 * eager->tcp_send_discon_ind set).
2226 		 * mp1 option buffer represented by OPT_length/offset
2227 		 * potentially modified and contains results of setting
2228 		 * options at this point
2229 		 */
2230 	}
2231 
2232 	/* We no longer need mp1, since all options processing has passed */
2233 	freemsg(mp1);
2234 
2235 	putnext(listener->tcp_connp->conn_rq, ok_mp);
2236 
2237 	mutex_enter(&listener->tcp_eager_lock);
2238 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2239 		tcp_t	*tail;
2240 		mblk_t	*conn_ind;
2241 
2242 		/*
2243 		 * This path should not be executed if listener and
2244 		 * acceptor streams are the same.
2245 		 */
2246 		ASSERT(listener != acceptor);
2247 
2248 		tcp = listener->tcp_eager_prev_q0;
2249 		/*
2250 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2251 		 * deferred T_conn_ind queue. We need to get to the head of
2252 		 * the queue in order to send up T_conn_ind the same order as
2253 		 * how the 3WHS is completed.
2254 		 */
2255 		while (tcp != listener) {
2256 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2257 				break;
2258 			else
2259 				tcp = tcp->tcp_eager_prev_q0;
2260 		}
2261 		ASSERT(tcp != listener);
2262 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2263 		ASSERT(conn_ind != NULL);
2264 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2265 
2266 		/* Move from q0 to q */
2267 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2268 		listener->tcp_conn_req_cnt_q0--;
2269 		listener->tcp_conn_req_cnt_q++;
2270 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2271 		    tcp->tcp_eager_prev_q0;
2272 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2273 		    tcp->tcp_eager_next_q0;
2274 		tcp->tcp_eager_prev_q0 = NULL;
2275 		tcp->tcp_eager_next_q0 = NULL;
2276 		tcp->tcp_conn_def_q0 = B_FALSE;
2277 
2278 		/* Make sure the tcp isn't in the list of droppables */
2279 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2280 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2281 
2282 		/*
2283 		 * Insert at end of the queue because sockfs sends
2284 		 * down T_CONN_RES in chronological order. Leaving
2285 		 * the older conn indications at front of the queue
2286 		 * helps reducing search time.
2287 		 */
2288 		tail = listener->tcp_eager_last_q;
2289 		if (tail != NULL)
2290 			tail->tcp_eager_next_q = tcp;
2291 		else
2292 			listener->tcp_eager_next_q = tcp;
2293 		listener->tcp_eager_last_q = tcp;
2294 		tcp->tcp_eager_next_q = NULL;
2295 		mutex_exit(&listener->tcp_eager_lock);
2296 		putnext(tcp->tcp_connp->conn_rq, conn_ind);
2297 	} else {
2298 		mutex_exit(&listener->tcp_eager_lock);
2299 	}
2300 
2301 	/*
2302 	 * Done with the acceptor - free it
2303 	 *
2304 	 * Note: from this point on, no access to listener should be made
2305 	 * as listener can be equal to acceptor.
2306 	 */
2307 finish:
2308 	ASSERT(acceptor->tcp_detached);
2309 	acceptor->tcp_connp->conn_rq = NULL;
2310 	ASSERT(!IPCL_IS_NONSTR(acceptor->tcp_connp));
2311 	acceptor->tcp_connp->conn_wq = NULL;
2312 	(void) tcp_clean_death(acceptor, 0, 2);
2313 	CONN_DEC_REF(acceptor->tcp_connp);
2314 
2315 	/*
2316 	 * We pass discon_mp to tcp_accept_finish to get on the right squeue.
2317 	 *
2318 	 * It will update the setting for sockfs/stream head and also take
2319 	 * care of any data that arrived before accept() wad called.
2320 	 * In case we already received a FIN then tcp_accept_finish will send up
2321 	 * the ordrel. It will also send up a window update if the window
2322 	 * has opened up.
2323 	 */
2324 
2325 	/*
2326 	 * XXX: we currently have a problem if XTI application closes the
2327 	 * acceptor stream in between. This problem exists in on10-gate also
2328 	 * and is well know but nothing can be done short of major rewrite
2329 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2330 	 * eager same squeue as listener (we can distinguish non socket
2331 	 * listeners at the time of handling a SYN in tcp_input_listener)
2332 	 * and do most of the work that tcp_accept_finish does here itself
2333 	 * and then get behind the acceptor squeue to access the acceptor
2334 	 * queue.
2335 	 */
2336 	/*
2337 	 * We already have a ref on tcp so no need to do one before squeue_enter
2338 	 */
2339 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, discon_mp,
2340 	    tcp_accept_finish, eager->tcp_connp, NULL, SQ_FILL,
2341 	    SQTAG_TCP_ACCEPT_FINISH);
2342 }
2343 
2344 /*
2345  * Swap information between the eager and acceptor for a TLI/XTI client.
2346  * The sockfs accept is done on the acceptor stream and control goes
2347  * through tcp_tli_accept() and tcp_accept()/tcp_accept_swap() is not
2348  * called. In either case, both the eager and listener are in their own
2349  * perimeter (squeue) and the code has to deal with potential race.
2350  *
2351  * See the block comment on top of tcp_accept() and tcp_tli_accept().
2352  */
2353 static void
2354 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2355 {
2356 	conn_t	*econnp, *aconnp;
2357 
2358 	ASSERT(eager->tcp_connp->conn_rq == listener->tcp_connp->conn_rq);
2359 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2360 	ASSERT(!TCP_IS_SOCKET(acceptor));
2361 	ASSERT(!TCP_IS_SOCKET(eager));
2362 	ASSERT(!TCP_IS_SOCKET(listener));
2363 
2364 	/*
2365 	 * Trusted Extensions may need to use a security label that is
2366 	 * different from the acceptor's label on MLP and MAC-Exempt
2367 	 * sockets. If this is the case, the required security label
2368 	 * already exists in econnp->conn_ixa->ixa_tsl. Since we make the
2369 	 * acceptor stream refer to econnp we atomatically get that label.
2370 	 */
2371 
2372 	acceptor->tcp_detached = B_TRUE;
2373 	/*
2374 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2375 	 * the acceptor id.
2376 	 */
2377 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2378 
2379 	/* remove eager from listen list... */
2380 	mutex_enter(&listener->tcp_eager_lock);
2381 	tcp_eager_unlink(eager);
2382 	ASSERT(eager->tcp_eager_next_q == NULL &&
2383 	    eager->tcp_eager_last_q == NULL);
2384 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2385 	    eager->tcp_eager_prev_q0 == NULL);
2386 	mutex_exit(&listener->tcp_eager_lock);
2387 
2388 	econnp = eager->tcp_connp;
2389 	aconnp = acceptor->tcp_connp;
2390 	econnp->conn_rq = aconnp->conn_rq;
2391 	econnp->conn_wq = aconnp->conn_wq;
2392 	econnp->conn_rq->q_ptr = econnp;
2393 	econnp->conn_wq->q_ptr = econnp;
2394 
2395 	/*
2396 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2397 	 * which might be a different squeue from our peer TCP instance.
2398 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2399 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2400 	 * membar_producer() to ensure that the assignments of conn_rq/conn_wq
2401 	 * above reach global visibility prior to the clearing of tcp_detached.
2402 	 */
2403 	membar_producer();
2404 	eager->tcp_detached = B_FALSE;
2405 
2406 	ASSERT(eager->tcp_ack_tid == 0);
2407 
2408 	econnp->conn_dev = aconnp->conn_dev;
2409 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2410 
2411 	ASSERT(econnp->conn_minor_arena != NULL);
2412 	if (econnp->conn_cred != NULL)
2413 		crfree(econnp->conn_cred);
2414 	econnp->conn_cred = aconnp->conn_cred;
2415 	aconnp->conn_cred = NULL;
2416 	econnp->conn_cpid = aconnp->conn_cpid;
2417 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2418 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2419 
2420 	econnp->conn_zoneid = aconnp->conn_zoneid;
2421 	econnp->conn_allzones = aconnp->conn_allzones;
2422 	econnp->conn_ixa->ixa_zoneid = aconnp->conn_ixa->ixa_zoneid;
2423 
2424 	econnp->conn_mac_mode = aconnp->conn_mac_mode;
2425 	econnp->conn_zone_is_global = aconnp->conn_zone_is_global;
2426 	aconnp->conn_mac_mode = CONN_MAC_DEFAULT;
2427 
2428 	/* Do the IPC initialization */
2429 	CONN_INC_REF(econnp);
2430 
2431 	/* Done with old IPC. Drop its ref on its connp */
2432 	CONN_DEC_REF(aconnp);
2433 }
2434 
2435 
2436 /*
2437  * Adapt to the information, such as rtt and rtt_sd, provided from the
2438  * DCE and IRE maintained by IP.
2439  *
2440  * Checks for multicast and broadcast destination address.
2441  * Returns zero if ok; an errno on failure.
2442  *
2443  * Note that the MSS calculation here is based on the info given in
2444  * the DCE and IRE.  We do not do any calculation based on TCP options.  They
2445  * will be handled in tcp_input_data() when TCP knows which options to use.
2446  *
2447  * Note on how TCP gets its parameters for a connection.
2448  *
2449  * When a tcp_t structure is allocated, it gets all the default parameters.
2450  * In tcp_set_destination(), it gets those metric parameters, like rtt, rtt_sd,
2451  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2452  * default.
2453  *
2454  * An incoming SYN with a multicast or broadcast destination address is dropped
2455  * in ip_fanout_v4/v6.
2456  *
2457  * An incoming SYN with a multicast or broadcast source address is always
2458  * dropped in tcp_set_destination, since IPDF_ALLOW_MCBC is not set in
2459  * conn_connect.
2460  * The same logic in tcp_set_destination also serves to
2461  * reject an attempt to connect to a broadcast or multicast (destination)
2462  * address.
2463  */
2464 static int
2465 tcp_set_destination(tcp_t *tcp)
2466 {
2467 	uint32_t	mss_max;
2468 	uint32_t	mss;
2469 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2470 	conn_t		*connp = tcp->tcp_connp;
2471 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2472 	iulp_t		uinfo;
2473 	int		error;
2474 	uint32_t	flags;
2475 
2476 	flags = IPDF_LSO | IPDF_ZCOPY;
2477 	/*
2478 	 * Make sure we have a dce for the destination to avoid dce_ident
2479 	 * contention for connected sockets.
2480 	 */
2481 	flags |= IPDF_UNIQUE_DCE;
2482 
2483 	if (!tcps->tcps_ignore_path_mtu)
2484 		connp->conn_ixa->ixa_flags |= IXAF_PMTU_DISCOVERY;
2485 
2486 	/* Use conn_lock to satify ASSERT; tcp is already serialized */
2487 	mutex_enter(&connp->conn_lock);
2488 	error = conn_connect(connp, &uinfo, flags);
2489 	mutex_exit(&connp->conn_lock);
2490 	if (error != 0)
2491 		return (error);
2492 
2493 	error = tcp_build_hdrs(tcp);
2494 	if (error != 0)
2495 		return (error);
2496 
2497 	tcp->tcp_localnet = uinfo.iulp_localnet;
2498 
2499 	if (uinfo.iulp_rtt != 0) {
2500 		clock_t	rto;
2501 
2502 		tcp->tcp_rtt_sa = uinfo.iulp_rtt;
2503 		tcp->tcp_rtt_sd = uinfo.iulp_rtt_sd;
2504 		rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2505 		    tcps->tcps_rexmit_interval_extra +
2506 		    (tcp->tcp_rtt_sa >> 5);
2507 
2508 		if (rto > tcps->tcps_rexmit_interval_max) {
2509 			tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2510 		} else if (rto < tcps->tcps_rexmit_interval_min) {
2511 			tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2512 		} else {
2513 			tcp->tcp_rto = rto;
2514 		}
2515 	}
2516 	if (uinfo.iulp_ssthresh != 0)
2517 		tcp->tcp_cwnd_ssthresh = uinfo.iulp_ssthresh;
2518 	else
2519 		tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2520 	if (uinfo.iulp_spipe > 0) {
2521 		connp->conn_sndbuf = MIN(uinfo.iulp_spipe,
2522 		    tcps->tcps_max_buf);
2523 		if (tcps->tcps_snd_lowat_fraction != 0) {
2524 			connp->conn_sndlowat = connp->conn_sndbuf /
2525 			    tcps->tcps_snd_lowat_fraction;
2526 		}
2527 		(void) tcp_maxpsz_set(tcp, B_TRUE);
2528 	}
2529 	/*
2530 	 * Note that up till now, acceptor always inherits receive
2531 	 * window from the listener.  But if there is a metrics
2532 	 * associated with a host, we should use that instead of
2533 	 * inheriting it from listener. Thus we need to pass this
2534 	 * info back to the caller.
2535 	 */
2536 	if (uinfo.iulp_rpipe > 0) {
2537 		tcp->tcp_rwnd = MIN(uinfo.iulp_rpipe,
2538 		    tcps->tcps_max_buf);
2539 	}
2540 
2541 	if (uinfo.iulp_rtomax > 0) {
2542 		tcp->tcp_second_timer_threshold =
2543 		    uinfo.iulp_rtomax;
2544 	}
2545 
2546 	/*
2547 	 * Use the metric option settings, iulp_tstamp_ok and
2548 	 * iulp_wscale_ok, only for active open. What this means
2549 	 * is that if the other side uses timestamp or window
2550 	 * scale option, TCP will also use those options. That
2551 	 * is for passive open.  If the application sets a
2552 	 * large window, window scale is enabled regardless of
2553 	 * the value in iulp_wscale_ok.  This is the behavior
2554 	 * since 2.6.  So we keep it.
2555 	 * The only case left in passive open processing is the
2556 	 * check for SACK.
2557 	 * For ECN, it should probably be like SACK.  But the
2558 	 * current value is binary, so we treat it like the other
2559 	 * cases.  The metric only controls active open.For passive
2560 	 * open, the ndd param, tcp_ecn_permitted, controls the
2561 	 * behavior.
2562 	 */
2563 	if (!tcp_detached) {
2564 		/*
2565 		 * The if check means that the following can only
2566 		 * be turned on by the metrics only IRE, but not off.
2567 		 */
2568 		if (uinfo.iulp_tstamp_ok)
2569 			tcp->tcp_snd_ts_ok = B_TRUE;
2570 		if (uinfo.iulp_wscale_ok)
2571 			tcp->tcp_snd_ws_ok = B_TRUE;
2572 		if (uinfo.iulp_sack == 2)
2573 			tcp->tcp_snd_sack_ok = B_TRUE;
2574 		if (uinfo.iulp_ecn_ok)
2575 			tcp->tcp_ecn_ok = B_TRUE;
2576 	} else {
2577 		/*
2578 		 * Passive open.
2579 		 *
2580 		 * As above, the if check means that SACK can only be
2581 		 * turned on by the metric only IRE.
2582 		 */
2583 		if (uinfo.iulp_sack > 0) {
2584 			tcp->tcp_snd_sack_ok = B_TRUE;
2585 		}
2586 	}
2587 
2588 	/*
2589 	 * XXX Note that currently, iulp_mtu can be as small as 68
2590 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2591 	 * length of all those options exceeds 28 bytes.  But because
2592 	 * of the tcp_mss_min check below, we may not have a problem if
2593 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2594 	 * the negative problem still exists.  And the check defeats PMTUd.
2595 	 * In fact, if PMTUd finds that the MSS should be smaller than
2596 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2597 	 * value.
2598 	 *
2599 	 * We do not deal with that now.  All those problems related to
2600 	 * PMTUd will be fixed later.
2601 	 */
2602 	ASSERT(uinfo.iulp_mtu != 0);
2603 	mss = tcp->tcp_initial_pmtu = uinfo.iulp_mtu;
2604 
2605 	/* Sanity check for MSS value. */
2606 	if (connp->conn_ipversion == IPV4_VERSION)
2607 		mss_max = tcps->tcps_mss_max_ipv4;
2608 	else
2609 		mss_max = tcps->tcps_mss_max_ipv6;
2610 
2611 	if (tcp->tcp_ipsec_overhead == 0)
2612 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2613 
2614 	mss -= tcp->tcp_ipsec_overhead;
2615 
2616 	if (mss < tcps->tcps_mss_min)
2617 		mss = tcps->tcps_mss_min;
2618 	if (mss > mss_max)
2619 		mss = mss_max;
2620 
2621 	/* Note that this is the maximum MSS, excluding all options. */
2622 	tcp->tcp_mss = mss;
2623 
2624 	/*
2625 	 * Update the tcp connection with LSO capability.
2626 	 */
2627 	tcp_update_lso(tcp, connp->conn_ixa);
2628 
2629 	/*
2630 	 * Initialize the ISS here now that we have the full connection ID.
2631 	 * The RFC 1948 method of initial sequence number generation requires
2632 	 * knowledge of the full connection ID before setting the ISS.
2633 	 */
2634 	tcp_iss_init(tcp);
2635 
2636 	tcp->tcp_loopback = (uinfo.iulp_loopback | uinfo.iulp_local);
2637 
2638 	/*
2639 	 * Make sure that conn is not marked incipient
2640 	 * for incoming connections. A blind
2641 	 * removal of incipient flag is cheaper than
2642 	 * check and removal.
2643 	 */
2644 	mutex_enter(&connp->conn_lock);
2645 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2646 	mutex_exit(&connp->conn_lock);
2647 	return (0);
2648 }
2649 
2650 static void
2651 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
2652 {
2653 	int	error;
2654 	conn_t	*connp = tcp->tcp_connp;
2655 	struct sockaddr	*sa;
2656 	mblk_t  *mp1;
2657 	struct T_bind_req *tbr;
2658 	int	backlog;
2659 	socklen_t	len;
2660 	sin_t	*sin;
2661 	sin6_t	*sin6;
2662 	cred_t		*cr;
2663 
2664 	/*
2665 	 * All Solaris components should pass a db_credp
2666 	 * for this TPI message, hence we ASSERT.
2667 	 * But in case there is some other M_PROTO that looks
2668 	 * like a TPI message sent by some other kernel
2669 	 * component, we check and return an error.
2670 	 */
2671 	cr = msg_getcred(mp, NULL);
2672 	ASSERT(cr != NULL);
2673 	if (cr == NULL) {
2674 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
2675 		return;
2676 	}
2677 
2678 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
2679 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
2680 		if (connp->conn_debug) {
2681 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2682 			    "tcp_tpi_bind: bad req, len %u",
2683 			    (uint_t)(mp->b_wptr - mp->b_rptr));
2684 		}
2685 		tcp_err_ack(tcp, mp, TPROTO, 0);
2686 		return;
2687 	}
2688 	/* Make sure the largest address fits */
2689 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t), 1);
2690 	if (mp1 == NULL) {
2691 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
2692 		return;
2693 	}
2694 	mp = mp1;
2695 	tbr = (struct T_bind_req *)mp->b_rptr;
2696 
2697 	backlog = tbr->CONIND_number;
2698 	len = tbr->ADDR_length;
2699 
2700 	switch (len) {
2701 	case 0:		/* request for a generic port */
2702 		tbr->ADDR_offset = sizeof (struct T_bind_req);
2703 		if (connp->conn_family == AF_INET) {
2704 			tbr->ADDR_length = sizeof (sin_t);
2705 			sin = (sin_t *)&tbr[1];
2706 			*sin = sin_null;
2707 			sin->sin_family = AF_INET;
2708 			sa = (struct sockaddr *)sin;
2709 			len = sizeof (sin_t);
2710 			mp->b_wptr = (uchar_t *)&sin[1];
2711 		} else {
2712 			ASSERT(connp->conn_family == AF_INET6);
2713 			tbr->ADDR_length = sizeof (sin6_t);
2714 			sin6 = (sin6_t *)&tbr[1];
2715 			*sin6 = sin6_null;
2716 			sin6->sin6_family = AF_INET6;
2717 			sa = (struct sockaddr *)sin6;
2718 			len = sizeof (sin6_t);
2719 			mp->b_wptr = (uchar_t *)&sin6[1];
2720 		}
2721 		break;
2722 
2723 	case sizeof (sin_t):    /* Complete IPv4 address */
2724 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
2725 		    sizeof (sin_t));
2726 		break;
2727 
2728 	case sizeof (sin6_t): /* Complete IPv6 address */
2729 		sa = (struct sockaddr *)mi_offset_param(mp,
2730 		    tbr->ADDR_offset, sizeof (sin6_t));
2731 		break;
2732 
2733 	default:
2734 		if (connp->conn_debug) {
2735 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2736 			    "tcp_tpi_bind: bad address length, %d",
2737 			    tbr->ADDR_length);
2738 		}
2739 		tcp_err_ack(tcp, mp, TBADADDR, 0);
2740 		return;
2741 	}
2742 
2743 	if (backlog > 0) {
2744 		error = tcp_do_listen(connp, sa, len, backlog, DB_CRED(mp),
2745 		    tbr->PRIM_type != O_T_BIND_REQ);
2746 	} else {
2747 		error = tcp_do_bind(connp, sa, len, DB_CRED(mp),
2748 		    tbr->PRIM_type != O_T_BIND_REQ);
2749 	}
2750 done:
2751 	if (error > 0) {
2752 		tcp_err_ack(tcp, mp, TSYSERR, error);
2753 	} else if (error < 0) {
2754 		tcp_err_ack(tcp, mp, -error, 0);
2755 	} else {
2756 		/*
2757 		 * Update port information as sockfs/tpi needs it for checking
2758 		 */
2759 		if (connp->conn_family == AF_INET) {
2760 			sin = (sin_t *)sa;
2761 			sin->sin_port = connp->conn_lport;
2762 		} else {
2763 			sin6 = (sin6_t *)sa;
2764 			sin6->sin6_port = connp->conn_lport;
2765 		}
2766 		mp->b_datap->db_type = M_PCPROTO;
2767 		tbr->PRIM_type = T_BIND_ACK;
2768 		putnext(connp->conn_rq, mp);
2769 	}
2770 }
2771 
2772 /*
2773  * If the "bind_to_req_port_only" parameter is set, if the requested port
2774  * number is available, return it, If not return 0
2775  *
2776  * If "bind_to_req_port_only" parameter is not set and
2777  * If the requested port number is available, return it.  If not, return
2778  * the first anonymous port we happen across.  If no anonymous ports are
2779  * available, return 0. addr is the requested local address, if any.
2780  *
2781  * In either case, when succeeding update the tcp_t to record the port number
2782  * and insert it in the bind hash table.
2783  *
2784  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
2785  * without setting SO_REUSEADDR. This is needed so that they
2786  * can be viewed as two independent transport protocols.
2787  */
2788 static in_port_t
2789 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
2790     int reuseaddr, boolean_t quick_connect,
2791     boolean_t bind_to_req_port_only, boolean_t user_specified)
2792 {
2793 	/* number of times we have run around the loop */
2794 	int count = 0;
2795 	/* maximum number of times to run around the loop */
2796 	int loopmax;
2797 	conn_t *connp = tcp->tcp_connp;
2798 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2799 
2800 	/*
2801 	 * Lookup for free addresses is done in a loop and "loopmax"
2802 	 * influences how long we spin in the loop
2803 	 */
2804 	if (bind_to_req_port_only) {
2805 		/*
2806 		 * If the requested port is busy, don't bother to look
2807 		 * for a new one. Setting loop maximum count to 1 has
2808 		 * that effect.
2809 		 */
2810 		loopmax = 1;
2811 	} else {
2812 		/*
2813 		 * If the requested port is busy, look for a free one
2814 		 * in the anonymous port range.
2815 		 * Set loopmax appropriately so that one does not look
2816 		 * forever in the case all of the anonymous ports are in use.
2817 		 */
2818 		if (connp->conn_anon_priv_bind) {
2819 			/*
2820 			 * loopmax =
2821 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
2822 			 */
2823 			loopmax = IPPORT_RESERVED -
2824 			    tcps->tcps_min_anonpriv_port;
2825 		} else {
2826 			loopmax = (tcps->tcps_largest_anon_port -
2827 			    tcps->tcps_smallest_anon_port + 1);
2828 		}
2829 	}
2830 	do {
2831 		uint16_t	lport;
2832 		tf_t		*tbf;
2833 		tcp_t		*ltcp;
2834 		conn_t		*lconnp;
2835 
2836 		lport = htons(port);
2837 
2838 		/*
2839 		 * Ensure that the tcp_t is not currently in the bind hash.
2840 		 * Hold the lock on the hash bucket to ensure that
2841 		 * the duplicate check plus the insertion is an atomic
2842 		 * operation.
2843 		 *
2844 		 * This function does an inline lookup on the bind hash list
2845 		 * Make sure that we access only members of tcp_t
2846 		 * and that we don't look at tcp_tcp, since we are not
2847 		 * doing a CONN_INC_REF.
2848 		 */
2849 		tcp_bind_hash_remove(tcp);
2850 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
2851 		mutex_enter(&tbf->tf_lock);
2852 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
2853 		    ltcp = ltcp->tcp_bind_hash) {
2854 			if (lport == ltcp->tcp_connp->conn_lport)
2855 				break;
2856 		}
2857 
2858 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
2859 			boolean_t not_socket;
2860 			boolean_t exclbind;
2861 
2862 			lconnp = ltcp->tcp_connp;
2863 
2864 			/*
2865 			 * On a labeled system, we must treat bindings to ports
2866 			 * on shared IP addresses by sockets with MAC exemption
2867 			 * privilege as being in all zones, as there's
2868 			 * otherwise no way to identify the right receiver.
2869 			 */
2870 			if (!IPCL_BIND_ZONE_MATCH(lconnp, connp))
2871 				continue;
2872 
2873 			/*
2874 			 * If TCP_EXCLBIND is set for either the bound or
2875 			 * binding endpoint, the semantics of bind
2876 			 * is changed according to the following.
2877 			 *
2878 			 * spec = specified address (v4 or v6)
2879 			 * unspec = unspecified address (v4 or v6)
2880 			 * A = specified addresses are different for endpoints
2881 			 *
2882 			 * bound	bind to		allowed
2883 			 * -------------------------------------
2884 			 * unspec	unspec		no
2885 			 * unspec	spec		no
2886 			 * spec		unspec		no
2887 			 * spec		spec		yes if A
2888 			 *
2889 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
2890 			 * as TCP_EXCLBIND, except that zoneid is ignored.
2891 			 *
2892 			 * Note:
2893 			 *
2894 			 * 1. Because of TLI semantics, an endpoint can go
2895 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
2896 			 * TCPS_BOUND, depending on whether it is originally
2897 			 * a listener or not.  That is why we need to check
2898 			 * for states greater than or equal to TCPS_BOUND
2899 			 * here.
2900 			 *
2901 			 * 2. Ideally, we should only check for state equals
2902 			 * to TCPS_LISTEN. And the following check should be
2903 			 * added.
2904 			 *
2905 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
2906 			 *	!reuseaddr || !lconnp->conn_reuseaddr) {
2907 			 *		...
2908 			 * }
2909 			 *
2910 			 * The semantics will be changed to this.  If the
2911 			 * endpoint on the list is in state not equal to
2912 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
2913 			 * set, let the bind succeed.
2914 			 *
2915 			 * Because of (1), we cannot do that for TLI
2916 			 * endpoints.  But we can do that for socket endpoints.
2917 			 * If in future, we can change this going back
2918 			 * semantics, we can use the above check for TLI also.
2919 			 */
2920 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
2921 			    TCP_IS_SOCKET(tcp));
2922 			exclbind = lconnp->conn_exclbind ||
2923 			    connp->conn_exclbind;
2924 
2925 			if ((lconnp->conn_mac_mode != CONN_MAC_DEFAULT) ||
2926 			    (connp->conn_mac_mode != CONN_MAC_DEFAULT) ||
2927 			    (exclbind && (not_socket ||
2928 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
2929 				if (V6_OR_V4_INADDR_ANY(
2930 				    lconnp->conn_bound_addr_v6) ||
2931 				    V6_OR_V4_INADDR_ANY(*laddr) ||
2932 				    IN6_ARE_ADDR_EQUAL(laddr,
2933 				    &lconnp->conn_bound_addr_v6)) {
2934 					break;
2935 				}
2936 				continue;
2937 			}
2938 
2939 			/*
2940 			 * Check ipversion to allow IPv4 and IPv6 sockets to
2941 			 * have disjoint port number spaces, if *_EXCLBIND
2942 			 * is not set and only if the application binds to a
2943 			 * specific port. We use the same autoassigned port
2944 			 * number space for IPv4 and IPv6 sockets.
2945 			 */
2946 			if (connp->conn_ipversion != lconnp->conn_ipversion &&
2947 			    bind_to_req_port_only)
2948 				continue;
2949 
2950 			/*
2951 			 * Ideally, we should make sure that the source
2952 			 * address, remote address, and remote port in the
2953 			 * four tuple for this tcp-connection is unique.
2954 			 * However, trying to find out the local source
2955 			 * address would require too much code duplication
2956 			 * with IP, since IP needs needs to have that code
2957 			 * to support userland TCP implementations.
2958 			 */
2959 			if (quick_connect &&
2960 			    (ltcp->tcp_state > TCPS_LISTEN) &&
2961 			    ((connp->conn_fport != lconnp->conn_fport) ||
2962 			    !IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6,
2963 			    &lconnp->conn_faddr_v6)))
2964 				continue;
2965 
2966 			if (!reuseaddr) {
2967 				/*
2968 				 * No socket option SO_REUSEADDR.
2969 				 * If existing port is bound to
2970 				 * a non-wildcard IP address
2971 				 * and the requesting stream is
2972 				 * bound to a distinct
2973 				 * different IP addresses
2974 				 * (non-wildcard, also), keep
2975 				 * going.
2976 				 */
2977 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
2978 				    !V6_OR_V4_INADDR_ANY(
2979 				    lconnp->conn_bound_addr_v6) &&
2980 				    !IN6_ARE_ADDR_EQUAL(laddr,
2981 				    &lconnp->conn_bound_addr_v6))
2982 					continue;
2983 				if (ltcp->tcp_state >= TCPS_BOUND) {
2984 					/*
2985 					 * This port is being used and
2986 					 * its state is >= TCPS_BOUND,
2987 					 * so we can't bind to it.
2988 					 */
2989 					break;
2990 				}
2991 			} else {
2992 				/*
2993 				 * socket option SO_REUSEADDR is set on the
2994 				 * binding tcp_t.
2995 				 *
2996 				 * If two streams are bound to
2997 				 * same IP address or both addr
2998 				 * and bound source are wildcards
2999 				 * (INADDR_ANY), we want to stop
3000 				 * searching.
3001 				 * We have found a match of IP source
3002 				 * address and source port, which is
3003 				 * refused regardless of the
3004 				 * SO_REUSEADDR setting, so we break.
3005 				 */
3006 				if (IN6_ARE_ADDR_EQUAL(laddr,
3007 				    &lconnp->conn_bound_addr_v6) &&
3008 				    (ltcp->tcp_state == TCPS_LISTEN ||
3009 				    ltcp->tcp_state == TCPS_BOUND))
3010 					break;
3011 			}
3012 		}
3013 		if (ltcp != NULL) {
3014 			/* The port number is busy */
3015 			mutex_exit(&tbf->tf_lock);
3016 		} else {
3017 			/*
3018 			 * This port is ours. Insert in fanout and mark as
3019 			 * bound to prevent others from getting the port
3020 			 * number.
3021 			 */
3022 			tcp->tcp_state = TCPS_BOUND;
3023 			connp->conn_lport = htons(port);
3024 
3025 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3026 			    connp->conn_lport)] == tbf);
3027 			tcp_bind_hash_insert(tbf, tcp, 1);
3028 
3029 			mutex_exit(&tbf->tf_lock);
3030 
3031 			/*
3032 			 * We don't want tcp_next_port_to_try to "inherit"
3033 			 * a port number supplied by the user in a bind.
3034 			 */
3035 			if (user_specified)
3036 				return (port);
3037 
3038 			/*
3039 			 * This is the only place where tcp_next_port_to_try
3040 			 * is updated. After the update, it may or may not
3041 			 * be in the valid range.
3042 			 */
3043 			if (!connp->conn_anon_priv_bind)
3044 				tcps->tcps_next_port_to_try = port + 1;
3045 			return (port);
3046 		}
3047 
3048 		if (connp->conn_anon_priv_bind) {
3049 			port = tcp_get_next_priv_port(tcp);
3050 		} else {
3051 			if (count == 0 && user_specified) {
3052 				/*
3053 				 * We may have to return an anonymous port. So
3054 				 * get one to start with.
3055 				 */
3056 				port =
3057 				    tcp_update_next_port(
3058 				    tcps->tcps_next_port_to_try,
3059 				    tcp, B_TRUE);
3060 				user_specified = B_FALSE;
3061 			} else {
3062 				port = tcp_update_next_port(port + 1, tcp,
3063 				    B_FALSE);
3064 			}
3065 		}
3066 		if (port == 0)
3067 			break;
3068 
3069 		/*
3070 		 * Don't let this loop run forever in the case where
3071 		 * all of the anonymous ports are in use.
3072 		 */
3073 	} while (++count < loopmax);
3074 	return (0);
3075 }
3076 
3077 /*
3078  * tcp_clean_death / tcp_close_detached must not be called more than once
3079  * on a tcp. Thus every function that potentially calls tcp_clean_death
3080  * must check for the tcp state before calling tcp_clean_death.
3081  * Eg. tcp_input_data, tcp_eager_kill, tcp_clean_death_wrapper,
3082  * tcp_timer_handler, all check for the tcp state.
3083  */
3084 /* ARGSUSED */
3085 void
3086 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2,
3087     ip_recv_attr_t *dummy)
3088 {
3089 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3090 
3091 	freemsg(mp);
3092 	if (tcp->tcp_state > TCPS_BOUND)
3093 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3094 		    ETIMEDOUT, 5);
3095 }
3096 
3097 /*
3098  * We are dying for some reason.  Try to do it gracefully.  (May be called
3099  * as writer.)
3100  *
3101  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3102  * done by a service procedure).
3103  * TBD - Should the return value distinguish between the tcp_t being
3104  * freed and it being reinitialized?
3105  */
3106 static int
3107 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3108 {
3109 	mblk_t	*mp;
3110 	queue_t	*q;
3111 	conn_t	*connp = tcp->tcp_connp;
3112 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3113 
3114 	TCP_CLD_STAT(tag);
3115 
3116 #if TCP_TAG_CLEAN_DEATH
3117 	tcp->tcp_cleandeathtag = tag;
3118 #endif
3119 
3120 	if (tcp->tcp_fused)
3121 		tcp_unfuse(tcp);
3122 
3123 	if (tcp->tcp_linger_tid != 0 &&
3124 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3125 		tcp_stop_lingering(tcp);
3126 	}
3127 
3128 	ASSERT(tcp != NULL);
3129 	ASSERT((connp->conn_family == AF_INET &&
3130 	    connp->conn_ipversion == IPV4_VERSION) ||
3131 	    (connp->conn_family == AF_INET6 &&
3132 	    (connp->conn_ipversion == IPV4_VERSION ||
3133 	    connp->conn_ipversion == IPV6_VERSION)));
3134 
3135 	if (TCP_IS_DETACHED(tcp)) {
3136 		if (tcp->tcp_hard_binding) {
3137 			/*
3138 			 * Its an eager that we are dealing with. We close the
3139 			 * eager but in case a conn_ind has already gone to the
3140 			 * listener, let tcp_accept_finish() send a discon_ind
3141 			 * to the listener and drop the last reference. If the
3142 			 * listener doesn't even know about the eager i.e. the
3143 			 * conn_ind hasn't gone up, blow away the eager and drop
3144 			 * the last reference as well. If the conn_ind has gone
3145 			 * up, state should be BOUND. tcp_accept_finish
3146 			 * will figure out that the connection has received a
3147 			 * RST and will send a DISCON_IND to the application.
3148 			 */
3149 			tcp_closei_local(tcp);
3150 			if (!tcp->tcp_tconnind_started) {
3151 				CONN_DEC_REF(connp);
3152 			} else {
3153 				tcp->tcp_state = TCPS_BOUND;
3154 			}
3155 		} else {
3156 			tcp_close_detached(tcp);
3157 		}
3158 		return (0);
3159 	}
3160 
3161 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3162 
3163 	/*
3164 	 * The connection is dead.  Decrement listener connection counter if
3165 	 * necessary.
3166 	 */
3167 	if (tcp->tcp_listen_cnt != NULL)
3168 		TCP_DECR_LISTEN_CNT(tcp);
3169 
3170 	q = connp->conn_rq;
3171 
3172 	/* Trash all inbound data */
3173 	if (!IPCL_IS_NONSTR(connp)) {
3174 		ASSERT(q != NULL);
3175 		flushq(q, FLUSHALL);
3176 	}
3177 
3178 	/*
3179 	 * If we are at least part way open and there is error
3180 	 * (err==0 implies no error)
3181 	 * notify our client by a T_DISCON_IND.
3182 	 */
3183 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3184 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3185 		    !TCP_IS_SOCKET(tcp)) {
3186 			/*
3187 			 * Send M_FLUSH according to TPI. Because sockets will
3188 			 * (and must) ignore FLUSHR we do that only for TPI
3189 			 * endpoints and sockets in STREAMS mode.
3190 			 */
3191 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3192 		}
3193 		if (connp->conn_debug) {
3194 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3195 			    "tcp_clean_death: discon err %d", err);
3196 		}
3197 		if (IPCL_IS_NONSTR(connp)) {
3198 			/* Direct socket, use upcall */
3199 			(*connp->conn_upcalls->su_disconnected)(
3200 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3201 		} else {
3202 			mp = mi_tpi_discon_ind(NULL, err, 0);
3203 			if (mp != NULL) {
3204 				putnext(q, mp);
3205 			} else {
3206 				if (connp->conn_debug) {
3207 					(void) strlog(TCP_MOD_ID, 0, 1,
3208 					    SL_ERROR|SL_TRACE,
3209 					    "tcp_clean_death, sending M_ERROR");
3210 				}
3211 				(void) putnextctl1(q, M_ERROR, EPROTO);
3212 			}
3213 		}
3214 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3215 			/* SYN_SENT or SYN_RCVD */
3216 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3217 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3218 			/* ESTABLISHED or CLOSE_WAIT */
3219 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3220 		}
3221 	}
3222 
3223 	tcp_reinit(tcp);
3224 	if (IPCL_IS_NONSTR(connp))
3225 		(void) tcp_do_unbind(connp);
3226 
3227 	return (-1);
3228 }
3229 
3230 /*
3231  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3232  * to expire, stop the wait and finish the close.
3233  */
3234 static void
3235 tcp_stop_lingering(tcp_t *tcp)
3236 {
3237 	clock_t	delta = 0;
3238 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3239 	conn_t		*connp = tcp->tcp_connp;
3240 
3241 	tcp->tcp_linger_tid = 0;
3242 	if (tcp->tcp_state > TCPS_LISTEN) {
3243 		tcp_acceptor_hash_remove(tcp);
3244 		mutex_enter(&tcp->tcp_non_sq_lock);
3245 		if (tcp->tcp_flow_stopped) {
3246 			tcp_clrqfull(tcp);
3247 		}
3248 		mutex_exit(&tcp->tcp_non_sq_lock);
3249 
3250 		if (tcp->tcp_timer_tid != 0) {
3251 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3252 			tcp->tcp_timer_tid = 0;
3253 		}
3254 		/*
3255 		 * Need to cancel those timers which will not be used when
3256 		 * TCP is detached.  This has to be done before the conn_wq
3257 		 * is cleared.
3258 		 */
3259 		tcp_timers_stop(tcp);
3260 
3261 		tcp->tcp_detached = B_TRUE;
3262 		connp->conn_rq = NULL;
3263 		connp->conn_wq = NULL;
3264 
3265 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3266 			tcp_time_wait_append(tcp);
3267 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3268 			goto finish;
3269 		}
3270 
3271 		/*
3272 		 * If delta is zero the timer event wasn't executed and was
3273 		 * successfully canceled. In this case we need to restart it
3274 		 * with the minimal delta possible.
3275 		 */
3276 		if (delta >= 0) {
3277 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3278 			    delta ? delta : 1);
3279 		}
3280 	} else {
3281 		tcp_closei_local(tcp);
3282 		CONN_DEC_REF(connp);
3283 	}
3284 finish:
3285 	/* Signal closing thread that it can complete close */
3286 	mutex_enter(&tcp->tcp_closelock);
3287 	tcp->tcp_detached = B_TRUE;
3288 	connp->conn_rq = NULL;
3289 	connp->conn_wq = NULL;
3290 
3291 	tcp->tcp_closed = 1;
3292 	cv_signal(&tcp->tcp_closecv);
3293 	mutex_exit(&tcp->tcp_closelock);
3294 }
3295 
3296 /*
3297  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3298  * expires.
3299  */
3300 static void
3301 tcp_close_linger_timeout(void *arg)
3302 {
3303 	conn_t	*connp = (conn_t *)arg;
3304 	tcp_t 	*tcp = connp->conn_tcp;
3305 
3306 	tcp->tcp_client_errno = ETIMEDOUT;
3307 	tcp_stop_lingering(tcp);
3308 }
3309 
3310 static void
3311 tcp_close_common(conn_t *connp, int flags)
3312 {
3313 	tcp_t		*tcp = connp->conn_tcp;
3314 	mblk_t 		*mp = &tcp->tcp_closemp;
3315 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3316 	mblk_t		*bp;
3317 
3318 	ASSERT(connp->conn_ref >= 2);
3319 
3320 	/*
3321 	 * Mark the conn as closing. ipsq_pending_mp_add will not
3322 	 * add any mp to the pending mp list, after this conn has
3323 	 * started closing.
3324 	 */
3325 	mutex_enter(&connp->conn_lock);
3326 	connp->conn_state_flags |= CONN_CLOSING;
3327 	if (connp->conn_oper_pending_ill != NULL)
3328 		conn_ioctl_cleanup_reqd = B_TRUE;
3329 	CONN_INC_REF_LOCKED(connp);
3330 	mutex_exit(&connp->conn_lock);
3331 	tcp->tcp_closeflags = (uint8_t)flags;
3332 	ASSERT(connp->conn_ref >= 3);
3333 
3334 	/*
3335 	 * tcp_closemp_used is used below without any protection of a lock
3336 	 * as we don't expect any one else to use it concurrently at this
3337 	 * point otherwise it would be a major defect.
3338 	 */
3339 
3340 	if (mp->b_prev == NULL)
3341 		tcp->tcp_closemp_used = B_TRUE;
3342 	else
3343 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3344 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3345 
3346 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3347 
3348 	/*
3349 	 * Cleanup any queued ioctls here. This must be done before the wq/rq
3350 	 * are re-written by tcp_close_output().
3351 	 */
3352 	if (conn_ioctl_cleanup_reqd)
3353 		conn_ioctl_cleanup(connp);
3354 
3355 	/*
3356 	 * As CONN_CLOSING is set, no further ioctls should be passed down to
3357 	 * IP for this conn (see the guards in tcp_ioctl, tcp_wput_ioctl and
3358 	 * tcp_wput_iocdata). If the ioctl was queued on an ipsq,
3359 	 * conn_ioctl_cleanup should have found it and removed it. If the ioctl
3360 	 * was still in flight at the time, we wait for it here. See comments
3361 	 * for CONN_INC_IOCTLREF in ip.h for details.
3362 	 */
3363 	mutex_enter(&connp->conn_lock);
3364 	while (connp->conn_ioctlref > 0)
3365 		cv_wait(&connp->conn_cv, &connp->conn_lock);
3366 	ASSERT(connp->conn_ioctlref == 0);
3367 	ASSERT(connp->conn_oper_pending_ill == NULL);
3368 	mutex_exit(&connp->conn_lock);
3369 
3370 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3371 	    NULL, tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3372 
3373 	mutex_enter(&tcp->tcp_closelock);
3374 	while (!tcp->tcp_closed) {
3375 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3376 			/*
3377 			 * The cv_wait_sig() was interrupted. We now do the
3378 			 * following:
3379 			 *
3380 			 * 1) If the endpoint was lingering, we allow this
3381 			 * to be interrupted by cancelling the linger timeout
3382 			 * and closing normally.
3383 			 *
3384 			 * 2) Revert to calling cv_wait()
3385 			 *
3386 			 * We revert to using cv_wait() to avoid an
3387 			 * infinite loop which can occur if the calling
3388 			 * thread is higher priority than the squeue worker
3389 			 * thread and is bound to the same cpu.
3390 			 */
3391 			if (connp->conn_linger && connp->conn_lingertime > 0) {
3392 				mutex_exit(&tcp->tcp_closelock);
3393 				/* Entering squeue, bump ref count. */
3394 				CONN_INC_REF(connp);
3395 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3396 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3397 				    tcp_linger_interrupted, connp, NULL,
3398 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3399 				mutex_enter(&tcp->tcp_closelock);
3400 			}
3401 			break;
3402 		}
3403 	}
3404 	while (!tcp->tcp_closed)
3405 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3406 	mutex_exit(&tcp->tcp_closelock);
3407 
3408 	/*
3409 	 * In the case of listener streams that have eagers in the q or q0
3410 	 * we wait for the eagers to drop their reference to us. conn_rq and
3411 	 * conn_wq of the eagers point to our queues. By waiting for the
3412 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3413 	 * up their queue pointers and also dropped their references to us.
3414 	 */
3415 	if (tcp->tcp_wait_for_eagers) {
3416 		mutex_enter(&connp->conn_lock);
3417 		while (connp->conn_ref != 1) {
3418 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3419 		}
3420 		mutex_exit(&connp->conn_lock);
3421 	}
3422 
3423 	connp->conn_cpid = NOPID;
3424 }
3425 
3426 static int
3427 tcp_tpi_close(queue_t *q, int flags)
3428 {
3429 	conn_t		*connp;
3430 
3431 	ASSERT(WR(q)->q_next == NULL);
3432 
3433 	if (flags & SO_FALLBACK) {
3434 		/*
3435 		 * stream is being closed while in fallback
3436 		 * simply free the resources that were allocated
3437 		 */
3438 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3439 		qprocsoff(q);
3440 		goto done;
3441 	}
3442 
3443 	connp = Q_TO_CONN(q);
3444 	/*
3445 	 * We are being closed as /dev/tcp or /dev/tcp6.
3446 	 */
3447 	tcp_close_common(connp, flags);
3448 
3449 	qprocsoff(q);
3450 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3451 
3452 	/*
3453 	 * Drop IP's reference on the conn. This is the last reference
3454 	 * on the connp if the state was less than established. If the
3455 	 * connection has gone into timewait state, then we will have
3456 	 * one ref for the TCP and one more ref (total of two) for the
3457 	 * classifier connected hash list (a timewait connections stays
3458 	 * in connected hash till closed).
3459 	 *
3460 	 * We can't assert the references because there might be other
3461 	 * transient reference places because of some walkers or queued
3462 	 * packets in squeue for the timewait state.
3463 	 */
3464 	CONN_DEC_REF(connp);
3465 done:
3466 	q->q_ptr = WR(q)->q_ptr = NULL;
3467 	return (0);
3468 }
3469 
3470 static int
3471 tcp_tpi_close_accept(queue_t *q)
3472 {
3473 	vmem_t	*minor_arena;
3474 	dev_t	conn_dev;
3475 
3476 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3477 
3478 	/*
3479 	 * We had opened an acceptor STREAM for sockfs which is
3480 	 * now being closed due to some error.
3481 	 */
3482 	qprocsoff(q);
3483 
3484 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3485 	conn_dev = (dev_t)RD(q)->q_ptr;
3486 	ASSERT(minor_arena != NULL);
3487 	ASSERT(conn_dev != 0);
3488 	inet_minor_free(minor_arena, conn_dev);
3489 	q->q_ptr = WR(q)->q_ptr = NULL;
3490 	return (0);
3491 }
3492 
3493 /*
3494  * Called by tcp_close() routine via squeue when lingering is
3495  * interrupted by a signal.
3496  */
3497 
3498 /* ARGSUSED */
3499 static void
3500 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
3501 {
3502 	conn_t	*connp = (conn_t *)arg;
3503 	tcp_t	*tcp = connp->conn_tcp;
3504 
3505 	freeb(mp);
3506 	if (tcp->tcp_linger_tid != 0 &&
3507 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3508 		tcp_stop_lingering(tcp);
3509 		tcp->tcp_client_errno = EINTR;
3510 	}
3511 }
3512 
3513 /*
3514  * Called by streams close routine via squeues when our client blows off her
3515  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3516  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3517  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3518  * acked.
3519  *
3520  * NOTE: tcp_close potentially returns error when lingering.
3521  * However, the stream head currently does not pass these errors
3522  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3523  * errors to the application (from tsleep()) and not errors
3524  * like ECONNRESET caused by receiving a reset packet.
3525  */
3526 
3527 /* ARGSUSED */
3528 static void
3529 tcp_close_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
3530 {
3531 	char	*msg;
3532 	conn_t	*connp = (conn_t *)arg;
3533 	tcp_t	*tcp = connp->conn_tcp;
3534 	clock_t	delta = 0;
3535 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3536 
3537 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3538 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3539 
3540 	mutex_enter(&tcp->tcp_eager_lock);
3541 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3542 		/* Cleanup for listener */
3543 		tcp_eager_cleanup(tcp, 0);
3544 		tcp->tcp_wait_for_eagers = 1;
3545 	}
3546 	mutex_exit(&tcp->tcp_eager_lock);
3547 
3548 	tcp->tcp_lso = B_FALSE;
3549 
3550 	msg = NULL;
3551 	switch (tcp->tcp_state) {
3552 	case TCPS_CLOSED:
3553 	case TCPS_IDLE:
3554 	case TCPS_BOUND:
3555 	case TCPS_LISTEN:
3556 		break;
3557 	case TCPS_SYN_SENT:
3558 		msg = "tcp_close, during connect";
3559 		break;
3560 	case TCPS_SYN_RCVD:
3561 		/*
3562 		 * Close during the connect 3-way handshake
3563 		 * but here there may or may not be pending data
3564 		 * already on queue. Process almost same as in
3565 		 * the ESTABLISHED state.
3566 		 */
3567 		/* FALLTHRU */
3568 	default:
3569 		if (tcp->tcp_fused)
3570 			tcp_unfuse(tcp);
3571 
3572 		/*
3573 		 * If SO_LINGER has set a zero linger time, abort the
3574 		 * connection with a reset.
3575 		 */
3576 		if (connp->conn_linger && connp->conn_lingertime == 0) {
3577 			msg = "tcp_close, zero lingertime";
3578 			break;
3579 		}
3580 
3581 		/*
3582 		 * Abort connection if there is unread data queued.
3583 		 */
3584 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3585 			msg = "tcp_close, unread data";
3586 			break;
3587 		}
3588 		/*
3589 		 * We have done a qwait() above which could have possibly
3590 		 * drained more messages in turn causing transition to a
3591 		 * different state. Check whether we have to do the rest
3592 		 * of the processing or not.
3593 		 */
3594 		if (tcp->tcp_state <= TCPS_LISTEN)
3595 			break;
3596 
3597 		/*
3598 		 * Transmit the FIN before detaching the tcp_t.
3599 		 * After tcp_detach returns this queue/perimeter
3600 		 * no longer owns the tcp_t thus others can modify it.
3601 		 */
3602 		(void) tcp_xmit_end(tcp);
3603 
3604 		/*
3605 		 * If lingering on close then wait until the fin is acked,
3606 		 * the SO_LINGER time passes, or a reset is sent/received.
3607 		 */
3608 		if (connp->conn_linger && connp->conn_lingertime > 0 &&
3609 		    !(tcp->tcp_fin_acked) &&
3610 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3611 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3612 				tcp->tcp_client_errno = EWOULDBLOCK;
3613 			} else if (tcp->tcp_client_errno == 0) {
3614 
3615 				ASSERT(tcp->tcp_linger_tid == 0);
3616 
3617 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3618 				    tcp_close_linger_timeout,
3619 				    connp->conn_lingertime * hz);
3620 
3621 				/* tcp_close_linger_timeout will finish close */
3622 				if (tcp->tcp_linger_tid == 0)
3623 					tcp->tcp_client_errno = ENOSR;
3624 				else
3625 					return;
3626 			}
3627 
3628 			/*
3629 			 * Check if we need to detach or just close
3630 			 * the instance.
3631 			 */
3632 			if (tcp->tcp_state <= TCPS_LISTEN)
3633 				break;
3634 		}
3635 
3636 		/*
3637 		 * Make sure that no other thread will access the conn_rq of
3638 		 * this instance (through lookups etc.) as conn_rq will go
3639 		 * away shortly.
3640 		 */
3641 		tcp_acceptor_hash_remove(tcp);
3642 
3643 		mutex_enter(&tcp->tcp_non_sq_lock);
3644 		if (tcp->tcp_flow_stopped) {
3645 			tcp_clrqfull(tcp);
3646 		}
3647 		mutex_exit(&tcp->tcp_non_sq_lock);
3648 
3649 		if (tcp->tcp_timer_tid != 0) {
3650 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3651 			tcp->tcp_timer_tid = 0;
3652 		}
3653 		/*
3654 		 * Need to cancel those timers which will not be used when
3655 		 * TCP is detached.  This has to be done before the conn_wq
3656 		 * is set to NULL.
3657 		 */
3658 		tcp_timers_stop(tcp);
3659 
3660 		tcp->tcp_detached = B_TRUE;
3661 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3662 			tcp_time_wait_append(tcp);
3663 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3664 			ASSERT(connp->conn_ref >= 3);
3665 			goto finish;
3666 		}
3667 
3668 		/*
3669 		 * If delta is zero the timer event wasn't executed and was
3670 		 * successfully canceled. In this case we need to restart it
3671 		 * with the minimal delta possible.
3672 		 */
3673 		if (delta >= 0)
3674 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3675 			    delta ? delta : 1);
3676 
3677 		ASSERT(connp->conn_ref >= 3);
3678 		goto finish;
3679 	}
3680 
3681 	/* Detach did not complete. Still need to remove q from stream. */
3682 	if (msg) {
3683 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
3684 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
3685 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3686 		if (tcp->tcp_state == TCPS_SYN_SENT ||
3687 		    tcp->tcp_state == TCPS_SYN_RCVD)
3688 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3689 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
3690 	}
3691 
3692 	tcp_closei_local(tcp);
3693 	CONN_DEC_REF(connp);
3694 	ASSERT(connp->conn_ref >= 2);
3695 
3696 finish:
3697 	mutex_enter(&tcp->tcp_closelock);
3698 	/*
3699 	 * Don't change the queues in the case of a listener that has
3700 	 * eagers in its q or q0. It could surprise the eagers.
3701 	 * Instead wait for the eagers outside the squeue.
3702 	 */
3703 	if (!tcp->tcp_wait_for_eagers) {
3704 		tcp->tcp_detached = B_TRUE;
3705 		connp->conn_rq = NULL;
3706 		connp->conn_wq = NULL;
3707 	}
3708 
3709 	/* Signal tcp_close() to finish closing. */
3710 	tcp->tcp_closed = 1;
3711 	cv_signal(&tcp->tcp_closecv);
3712 	mutex_exit(&tcp->tcp_closelock);
3713 }
3714 
3715 /*
3716  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
3717  * Some stream heads get upset if they see these later on as anything but NULL.
3718  */
3719 static void
3720 tcp_close_mpp(mblk_t **mpp)
3721 {
3722 	mblk_t	*mp;
3723 
3724 	if ((mp = *mpp) != NULL) {
3725 		do {
3726 			mp->b_next = NULL;
3727 			mp->b_prev = NULL;
3728 		} while ((mp = mp->b_cont) != NULL);
3729 
3730 		mp = *mpp;
3731 		*mpp = NULL;
3732 		freemsg(mp);
3733 	}
3734 }
3735 
3736 /* Do detached close. */
3737 static void
3738 tcp_close_detached(tcp_t *tcp)
3739 {
3740 	if (tcp->tcp_fused)
3741 		tcp_unfuse(tcp);
3742 
3743 	/*
3744 	 * Clustering code serializes TCP disconnect callbacks and
3745 	 * cluster tcp list walks by blocking a TCP disconnect callback
3746 	 * if a cluster tcp list walk is in progress. This ensures
3747 	 * accurate accounting of TCPs in the cluster code even though
3748 	 * the TCP list walk itself is not atomic.
3749 	 */
3750 	tcp_closei_local(tcp);
3751 	CONN_DEC_REF(tcp->tcp_connp);
3752 }
3753 
3754 /*
3755  * Stop all TCP timers, and free the timer mblks if requested.
3756  */
3757 void
3758 tcp_timers_stop(tcp_t *tcp)
3759 {
3760 	if (tcp->tcp_timer_tid != 0) {
3761 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3762 		tcp->tcp_timer_tid = 0;
3763 	}
3764 	if (tcp->tcp_ka_tid != 0) {
3765 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
3766 		tcp->tcp_ka_tid = 0;
3767 	}
3768 	if (tcp->tcp_ack_tid != 0) {
3769 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
3770 		tcp->tcp_ack_tid = 0;
3771 	}
3772 	if (tcp->tcp_push_tid != 0) {
3773 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
3774 		tcp->tcp_push_tid = 0;
3775 	}
3776 	if (tcp->tcp_reass_tid != 0) {
3777 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_reass_tid);
3778 		tcp->tcp_reass_tid = 0;
3779 	}
3780 }
3781 
3782 /*
3783  * The tcp_t is going away. Remove it from all lists and set it
3784  * to TCPS_CLOSED. The freeing up of memory is deferred until
3785  * tcp_inactive. This is needed since a thread in tcp_rput might have
3786  * done a CONN_INC_REF on this structure before it was removed from the
3787  * hashes.
3788  */
3789 static void
3790 tcp_closei_local(tcp_t *tcp)
3791 {
3792 	conn_t		*connp = tcp->tcp_connp;
3793 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3794 
3795 	if (!TCP_IS_SOCKET(tcp))
3796 		tcp_acceptor_hash_remove(tcp);
3797 
3798 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
3799 	tcp->tcp_ibsegs = 0;
3800 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
3801 	tcp->tcp_obsegs = 0;
3802 
3803 	/*
3804 	 * If we are an eager connection hanging off a listener that
3805 	 * hasn't formally accepted the connection yet, get off his
3806 	 * list and blow off any data that we have accumulated.
3807 	 */
3808 	if (tcp->tcp_listener != NULL) {
3809 		tcp_t	*listener = tcp->tcp_listener;
3810 		mutex_enter(&listener->tcp_eager_lock);
3811 		/*
3812 		 * tcp_tconnind_started == B_TRUE means that the
3813 		 * conn_ind has already gone to listener. At
3814 		 * this point, eager will be closed but we
3815 		 * leave it in listeners eager list so that
3816 		 * if listener decides to close without doing
3817 		 * accept, we can clean this up. In tcp_tli_accept
3818 		 * we take care of the case of accept on closed
3819 		 * eager.
3820 		 */
3821 		if (!tcp->tcp_tconnind_started) {
3822 			tcp_eager_unlink(tcp);
3823 			mutex_exit(&listener->tcp_eager_lock);
3824 			/*
3825 			 * We don't want to have any pointers to the
3826 			 * listener queue, after we have released our
3827 			 * reference on the listener
3828 			 */
3829 			ASSERT(tcp->tcp_detached);
3830 			connp->conn_rq = NULL;
3831 			connp->conn_wq = NULL;
3832 			CONN_DEC_REF(listener->tcp_connp);
3833 		} else {
3834 			mutex_exit(&listener->tcp_eager_lock);
3835 		}
3836 	}
3837 
3838 	/* Stop all the timers */
3839 	tcp_timers_stop(tcp);
3840 
3841 	if (tcp->tcp_state == TCPS_LISTEN) {
3842 		if (tcp->tcp_ip_addr_cache) {
3843 			kmem_free((void *)tcp->tcp_ip_addr_cache,
3844 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
3845 			tcp->tcp_ip_addr_cache = NULL;
3846 		}
3847 	}
3848 
3849 	/* Decrement listerner connection counter if necessary. */
3850 	if (tcp->tcp_listen_cnt != NULL)
3851 		TCP_DECR_LISTEN_CNT(tcp);
3852 
3853 	mutex_enter(&tcp->tcp_non_sq_lock);
3854 	if (tcp->tcp_flow_stopped)
3855 		tcp_clrqfull(tcp);
3856 	mutex_exit(&tcp->tcp_non_sq_lock);
3857 
3858 	tcp_bind_hash_remove(tcp);
3859 	/*
3860 	 * If the tcp_time_wait_collector (which runs outside the squeue)
3861 	 * is trying to remove this tcp from the time wait list, we will
3862 	 * block in tcp_time_wait_remove while trying to acquire the
3863 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
3864 	 * requires the ipcl_hash_remove to be ordered after the
3865 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
3866 	 */
3867 	if (tcp->tcp_state == TCPS_TIME_WAIT)
3868 		(void) tcp_time_wait_remove(tcp, NULL);
3869 	CL_INET_DISCONNECT(connp);
3870 	ipcl_hash_remove(connp);
3871 	ixa_cleanup(connp->conn_ixa);
3872 
3873 	/*
3874 	 * Mark the conn as CONDEMNED
3875 	 */
3876 	mutex_enter(&connp->conn_lock);
3877 	connp->conn_state_flags |= CONN_CONDEMNED;
3878 	mutex_exit(&connp->conn_lock);
3879 
3880 	ASSERT(tcp->tcp_time_wait_next == NULL);
3881 	ASSERT(tcp->tcp_time_wait_prev == NULL);
3882 	ASSERT(tcp->tcp_time_wait_expire == 0);
3883 	tcp->tcp_state = TCPS_CLOSED;
3884 
3885 	/* Release any SSL context */
3886 	if (tcp->tcp_kssl_ent != NULL) {
3887 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
3888 		tcp->tcp_kssl_ent = NULL;
3889 	}
3890 	if (tcp->tcp_kssl_ctx != NULL) {
3891 		kssl_release_ctx(tcp->tcp_kssl_ctx);
3892 		tcp->tcp_kssl_ctx = NULL;
3893 	}
3894 	tcp->tcp_kssl_pending = B_FALSE;
3895 
3896 	tcp_ipsec_cleanup(tcp);
3897 }
3898 
3899 /*
3900  * tcp is dying (called from ipcl_conn_destroy and error cases).
3901  * Free the tcp_t in either case.
3902  */
3903 void
3904 tcp_free(tcp_t *tcp)
3905 {
3906 	mblk_t		*mp;
3907 	conn_t		*connp = tcp->tcp_connp;
3908 
3909 	ASSERT(tcp != NULL);
3910 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
3911 
3912 	connp->conn_rq = NULL;
3913 	connp->conn_wq = NULL;
3914 
3915 	tcp_close_mpp(&tcp->tcp_xmit_head);
3916 	tcp_close_mpp(&tcp->tcp_reass_head);
3917 	if (tcp->tcp_rcv_list != NULL) {
3918 		/* Free b_next chain */
3919 		tcp_close_mpp(&tcp->tcp_rcv_list);
3920 	}
3921 	if ((mp = tcp->tcp_urp_mp) != NULL) {
3922 		freemsg(mp);
3923 	}
3924 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
3925 		freemsg(mp);
3926 	}
3927 
3928 	if (tcp->tcp_fused_sigurg_mp != NULL) {
3929 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
3930 		freeb(tcp->tcp_fused_sigurg_mp);
3931 		tcp->tcp_fused_sigurg_mp = NULL;
3932 	}
3933 
3934 	if (tcp->tcp_ordrel_mp != NULL) {
3935 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
3936 		freeb(tcp->tcp_ordrel_mp);
3937 		tcp->tcp_ordrel_mp = NULL;
3938 	}
3939 
3940 	if (tcp->tcp_sack_info != NULL) {
3941 		if (tcp->tcp_notsack_list != NULL) {
3942 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
3943 			    tcp);
3944 		}
3945 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
3946 	}
3947 
3948 	if (tcp->tcp_hopopts != NULL) {
3949 		mi_free(tcp->tcp_hopopts);
3950 		tcp->tcp_hopopts = NULL;
3951 		tcp->tcp_hopoptslen = 0;
3952 	}
3953 	ASSERT(tcp->tcp_hopoptslen == 0);
3954 	if (tcp->tcp_dstopts != NULL) {
3955 		mi_free(tcp->tcp_dstopts);
3956 		tcp->tcp_dstopts = NULL;
3957 		tcp->tcp_dstoptslen = 0;
3958 	}
3959 	ASSERT(tcp->tcp_dstoptslen == 0);
3960 	if (tcp->tcp_rthdrdstopts != NULL) {
3961 		mi_free(tcp->tcp_rthdrdstopts);
3962 		tcp->tcp_rthdrdstopts = NULL;
3963 		tcp->tcp_rthdrdstoptslen = 0;
3964 	}
3965 	ASSERT(tcp->tcp_rthdrdstoptslen == 0);
3966 	if (tcp->tcp_rthdr != NULL) {
3967 		mi_free(tcp->tcp_rthdr);
3968 		tcp->tcp_rthdr = NULL;
3969 		tcp->tcp_rthdrlen = 0;
3970 	}
3971 	ASSERT(tcp->tcp_rthdrlen == 0);
3972 
3973 	/*
3974 	 * Following is really a blowing away a union.
3975 	 * It happens to have exactly two members of identical size
3976 	 * the following code is enough.
3977 	 */
3978 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
3979 }
3980 
3981 
3982 /*
3983  * Put a connection confirmation message upstream built from the
3984  * address/flowid information with the conn and iph. Report our success or
3985  * failure.
3986  */
3987 static boolean_t
3988 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, mblk_t *idmp,
3989     mblk_t **defermp, ip_recv_attr_t *ira)
3990 {
3991 	sin_t	sin;
3992 	sin6_t	sin6;
3993 	mblk_t	*mp;
3994 	char	*optp = NULL;
3995 	int	optlen = 0;
3996 	conn_t	*connp = tcp->tcp_connp;
3997 
3998 	if (defermp != NULL)
3999 		*defermp = NULL;
4000 
4001 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4002 		/*
4003 		 * Return in T_CONN_CON results of option negotiation through
4004 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4005 		 * negotiation, then what is received from remote end needs
4006 		 * to be taken into account but there is no such thing (yet?)
4007 		 * in our TCP/IP.
4008 		 * Note: We do not use mi_offset_param() here as
4009 		 * tcp_opts_conn_req contents do not directly come from
4010 		 * an application and are either generated in kernel or
4011 		 * from user input that was already verified.
4012 		 */
4013 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4014 		optp = (char *)(mp->b_rptr +
4015 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4016 		optlen = (int)
4017 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4018 	}
4019 
4020 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4021 
4022 		/* packet is IPv4 */
4023 		if (connp->conn_family == AF_INET) {
4024 			sin = sin_null;
4025 			sin.sin_addr.s_addr = connp->conn_faddr_v4;
4026 			sin.sin_port = connp->conn_fport;
4027 			sin.sin_family = AF_INET;
4028 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4029 			    (int)sizeof (sin_t), optp, optlen);
4030 		} else {
4031 			sin6 = sin6_null;
4032 			sin6.sin6_addr = connp->conn_faddr_v6;
4033 			sin6.sin6_port = connp->conn_fport;
4034 			sin6.sin6_family = AF_INET6;
4035 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4036 			    (int)sizeof (sin6_t), optp, optlen);
4037 
4038 		}
4039 	} else {
4040 		ip6_t	*ip6h = (ip6_t *)iphdr;
4041 
4042 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4043 		ASSERT(connp->conn_family == AF_INET6);
4044 		sin6 = sin6_null;
4045 		sin6.sin6_addr = connp->conn_faddr_v6;
4046 		sin6.sin6_port = connp->conn_fport;
4047 		sin6.sin6_family = AF_INET6;
4048 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4049 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4050 		    (int)sizeof (sin6_t), optp, optlen);
4051 	}
4052 
4053 	if (!mp)
4054 		return (B_FALSE);
4055 
4056 	mblk_copycred(mp, idmp);
4057 
4058 	if (defermp == NULL) {
4059 		conn_t *connp = tcp->tcp_connp;
4060 		if (IPCL_IS_NONSTR(connp)) {
4061 			(*connp->conn_upcalls->su_connected)
4062 			    (connp->conn_upper_handle, tcp->tcp_connid,
4063 			    ira->ira_cred, ira->ira_cpid);
4064 			freemsg(mp);
4065 		} else {
4066 			if (ira->ira_cred != NULL) {
4067 				/* So that getpeerucred works for TPI sockfs */
4068 				mblk_setcred(mp, ira->ira_cred, ira->ira_cpid);
4069 			}
4070 			putnext(connp->conn_rq, mp);
4071 		}
4072 	} else {
4073 		*defermp = mp;
4074 	}
4075 
4076 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4077 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4078 	return (B_TRUE);
4079 }
4080 
4081 /*
4082  * Defense for the SYN attack -
4083  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4084  *    one from the list of droppable eagers. This list is a subset of q0.
4085  *    see comments before the definition of MAKE_DROPPABLE().
4086  * 2. Don't drop a SYN request before its first timeout. This gives every
4087  *    request at least til the first timeout to complete its 3-way handshake.
4088  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4089  *    requests currently on the queue that has timed out. This will be used
4090  *    as an indicator of whether an attack is under way, so that appropriate
4091  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4092  *    either when eager goes into ESTABLISHED, or gets freed up.)
4093  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4094  *    # of timeout drops back to <= q0len/32 => SYN alert off
4095  */
4096 static boolean_t
4097 tcp_drop_q0(tcp_t *tcp)
4098 {
4099 	tcp_t	*eager;
4100 	mblk_t	*mp;
4101 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4102 
4103 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4104 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4105 
4106 	/* Pick oldest eager from the list of droppable eagers */
4107 	eager = tcp->tcp_eager_prev_drop_q0;
4108 
4109 	/* If list is empty. return B_FALSE */
4110 	if (eager == tcp) {
4111 		return (B_FALSE);
4112 	}
4113 
4114 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4115 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4116 		return (B_FALSE);
4117 
4118 	/*
4119 	 * Take this eager out from the list of droppable eagers since we are
4120 	 * going to drop it.
4121 	 */
4122 	MAKE_UNDROPPABLE(eager);
4123 
4124 	if (tcp->tcp_connp->conn_debug) {
4125 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4126 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4127 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4128 		    tcp->tcp_conn_req_cnt_q0,
4129 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4130 	}
4131 
4132 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4133 
4134 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4135 	CONN_INC_REF(eager->tcp_connp);
4136 
4137 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4138 	    tcp_clean_death_wrapper, eager->tcp_connp, NULL,
4139 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4140 
4141 	return (B_TRUE);
4142 }
4143 
4144 /*
4145  * Handle a SYN on an AF_INET6 socket; can be either IPv4 or IPv6
4146  */
4147 static mblk_t *
4148 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4149     ip_recv_attr_t *ira)
4150 {
4151 	tcp_t 		*ltcp = lconnp->conn_tcp;
4152 	tcp_t		*tcp = connp->conn_tcp;
4153 	mblk_t		*tpi_mp;
4154 	ipha_t		*ipha;
4155 	ip6_t		*ip6h;
4156 	sin6_t 		sin6;
4157 	uint_t		ifindex = ira->ira_ruifindex;
4158 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4159 
4160 	if (ira->ira_flags & IRAF_IS_IPV4) {
4161 		ipha = (ipha_t *)mp->b_rptr;
4162 
4163 		connp->conn_ipversion = IPV4_VERSION;
4164 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_laddr_v6);
4165 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_faddr_v6);
4166 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
4167 
4168 		sin6 = sin6_null;
4169 		sin6.sin6_addr = connp->conn_faddr_v6;
4170 		sin6.sin6_port = connp->conn_fport;
4171 		sin6.sin6_family = AF_INET6;
4172 		sin6.__sin6_src_id = ip_srcid_find_addr(&connp->conn_laddr_v6,
4173 		    IPCL_ZONEID(lconnp), tcps->tcps_netstack);
4174 
4175 		if (connp->conn_recv_ancillary.crb_recvdstaddr) {
4176 			sin6_t	sin6d;
4177 
4178 			sin6d = sin6_null;
4179 			sin6d.sin6_addr = connp->conn_laddr_v6;
4180 			sin6d.sin6_port = connp->conn_lport;
4181 			sin6d.sin6_family = AF_INET;
4182 			tpi_mp = mi_tpi_extconn_ind(NULL,
4183 			    (char *)&sin6d, sizeof (sin6_t),
4184 			    (char *)&tcp,
4185 			    (t_scalar_t)sizeof (intptr_t),
4186 			    (char *)&sin6d, sizeof (sin6_t),
4187 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4188 		} else {
4189 			tpi_mp = mi_tpi_conn_ind(NULL,
4190 			    (char *)&sin6, sizeof (sin6_t),
4191 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4192 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4193 		}
4194 	} else {
4195 		ip6h = (ip6_t *)mp->b_rptr;
4196 
4197 		connp->conn_ipversion = IPV6_VERSION;
4198 		connp->conn_laddr_v6 = ip6h->ip6_dst;
4199 		connp->conn_faddr_v6 = ip6h->ip6_src;
4200 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
4201 
4202 		sin6 = sin6_null;
4203 		sin6.sin6_addr = connp->conn_faddr_v6;
4204 		sin6.sin6_port = connp->conn_fport;
4205 		sin6.sin6_family = AF_INET6;
4206 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4207 		sin6.__sin6_src_id = ip_srcid_find_addr(&connp->conn_laddr_v6,
4208 		    IPCL_ZONEID(lconnp), tcps->tcps_netstack);
4209 
4210 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4211 			/* Pass up the scope_id of remote addr */
4212 			sin6.sin6_scope_id = ifindex;
4213 		} else {
4214 			sin6.sin6_scope_id = 0;
4215 		}
4216 		if (connp->conn_recv_ancillary.crb_recvdstaddr) {
4217 			sin6_t	sin6d;
4218 
4219 			sin6d = sin6_null;
4220 			sin6.sin6_addr = connp->conn_laddr_v6;
4221 			sin6d.sin6_port = connp->conn_lport;
4222 			sin6d.sin6_family = AF_INET6;
4223 			if (IN6_IS_ADDR_LINKSCOPE(&connp->conn_laddr_v6))
4224 				sin6d.sin6_scope_id = ifindex;
4225 
4226 			tpi_mp = mi_tpi_extconn_ind(NULL,
4227 			    (char *)&sin6d, sizeof (sin6_t),
4228 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4229 			    (char *)&sin6d, sizeof (sin6_t),
4230 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4231 		} else {
4232 			tpi_mp = mi_tpi_conn_ind(NULL,
4233 			    (char *)&sin6, sizeof (sin6_t),
4234 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4235 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4236 		}
4237 	}
4238 
4239 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4240 	return (tpi_mp);
4241 }
4242 
4243 /* Handle a SYN on an AF_INET socket */
4244 mblk_t *
4245 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4246     ip_recv_attr_t *ira)
4247 {
4248 	tcp_t 		*ltcp = lconnp->conn_tcp;
4249 	tcp_t		*tcp = connp->conn_tcp;
4250 	sin_t		sin;
4251 	mblk_t		*tpi_mp = NULL;
4252 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4253 	ipha_t		*ipha;
4254 
4255 	ASSERT(ira->ira_flags & IRAF_IS_IPV4);
4256 	ipha = (ipha_t *)mp->b_rptr;
4257 
4258 	connp->conn_ipversion = IPV4_VERSION;
4259 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_laddr_v6);
4260 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_faddr_v6);
4261 	connp->conn_saddr_v6 = connp->conn_laddr_v6;
4262 
4263 	sin = sin_null;
4264 	sin.sin_addr.s_addr = connp->conn_faddr_v4;
4265 	sin.sin_port = connp->conn_fport;
4266 	sin.sin_family = AF_INET;
4267 	if (lconnp->conn_recv_ancillary.crb_recvdstaddr) {
4268 		sin_t	sind;
4269 
4270 		sind = sin_null;
4271 		sind.sin_addr.s_addr = connp->conn_laddr_v4;
4272 		sind.sin_port = connp->conn_lport;
4273 		sind.sin_family = AF_INET;
4274 		tpi_mp = mi_tpi_extconn_ind(NULL,
4275 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4276 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4277 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4278 	} else {
4279 		tpi_mp = mi_tpi_conn_ind(NULL,
4280 		    (char *)&sin, sizeof (sin_t),
4281 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4282 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4283 	}
4284 
4285 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4286 	return (tpi_mp);
4287 }
4288 
4289 /*
4290  * tcp_get_conn/tcp_free_conn
4291  *
4292  * tcp_get_conn is used to get a clean tcp connection structure.
4293  * It tries to reuse the connections put on the freelist by the
4294  * time_wait_collector failing which it goes to kmem_cache. This
4295  * way has two benefits compared to just allocating from and
4296  * freeing to kmem_cache.
4297  * 1) The time_wait_collector can free (which includes the cleanup)
4298  * outside the squeue. So when the interrupt comes, we have a clean
4299  * connection sitting in the freelist. Obviously, this buys us
4300  * performance.
4301  *
4302  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_input_listener
4303  * has multiple disadvantages - tying up the squeue during alloc.
4304  * But allocating the conn/tcp in IP land is also not the best since
4305  * we can't check the 'q' and 'q0' which are protected by squeue and
4306  * blindly allocate memory which might have to be freed here if we are
4307  * not allowed to accept the connection. By using the freelist and
4308  * putting the conn/tcp back in freelist, we don't pay a penalty for
4309  * allocating memory without checking 'q/q0' and freeing it if we can't
4310  * accept the connection.
4311  *
4312  * Care should be taken to put the conn back in the same squeue's freelist
4313  * from which it was allocated. Best results are obtained if conn is
4314  * allocated from listener's squeue and freed to the same. Time wait
4315  * collector will free up the freelist is the connection ends up sitting
4316  * there for too long.
4317  */
4318 void *
4319 tcp_get_conn(void *arg, tcp_stack_t *tcps)
4320 {
4321 	tcp_t			*tcp = NULL;
4322 	conn_t			*connp = NULL;
4323 	squeue_t		*sqp = (squeue_t *)arg;
4324 	tcp_squeue_priv_t 	*tcp_time_wait;
4325 	netstack_t		*ns;
4326 	mblk_t			*tcp_rsrv_mp = NULL;
4327 
4328 	tcp_time_wait =
4329 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
4330 
4331 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
4332 	tcp = tcp_time_wait->tcp_free_list;
4333 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
4334 	if (tcp != NULL) {
4335 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
4336 		tcp_time_wait->tcp_free_list_cnt--;
4337 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4338 		tcp->tcp_time_wait_next = NULL;
4339 		connp = tcp->tcp_connp;
4340 		connp->conn_flags |= IPCL_REUSED;
4341 
4342 		ASSERT(tcp->tcp_tcps == NULL);
4343 		ASSERT(connp->conn_netstack == NULL);
4344 		ASSERT(tcp->tcp_rsrv_mp != NULL);
4345 		ns = tcps->tcps_netstack;
4346 		netstack_hold(ns);
4347 		connp->conn_netstack = ns;
4348 		connp->conn_ixa->ixa_ipst = ns->netstack_ip;
4349 		tcp->tcp_tcps = tcps;
4350 		ipcl_globalhash_insert(connp);
4351 
4352 		connp->conn_ixa->ixa_notify_cookie = tcp;
4353 		ASSERT(connp->conn_ixa->ixa_notify == tcp_notify);
4354 		connp->conn_recv = tcp_input_data;
4355 		ASSERT(connp->conn_recvicmp == tcp_icmp_input);
4356 		ASSERT(connp->conn_verifyicmp == tcp_verifyicmp);
4357 		return ((void *)connp);
4358 	}
4359 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4360 	/*
4361 	 * Pre-allocate the tcp_rsrv_mp. This mblk will not be freed until
4362 	 * this conn_t/tcp_t is freed at ipcl_conn_destroy().
4363 	 */
4364 	tcp_rsrv_mp = allocb(0, BPRI_HI);
4365 	if (tcp_rsrv_mp == NULL)
4366 		return (NULL);
4367 
4368 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
4369 	    tcps->tcps_netstack)) == NULL) {
4370 		freeb(tcp_rsrv_mp);
4371 		return (NULL);
4372 	}
4373 
4374 	tcp = connp->conn_tcp;
4375 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
4376 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
4377 
4378 	tcp->tcp_tcps = tcps;
4379 
4380 	connp->conn_recv = tcp_input_data;
4381 	connp->conn_recvicmp = tcp_icmp_input;
4382 	connp->conn_verifyicmp = tcp_verifyicmp;
4383 
4384 	/*
4385 	 * Register tcp_notify to listen to capability changes detected by IP.
4386 	 * This upcall is made in the context of the call to conn_ip_output
4387 	 * thus it is inside the squeue.
4388 	 */
4389 	connp->conn_ixa->ixa_notify = tcp_notify;
4390 	connp->conn_ixa->ixa_notify_cookie = tcp;
4391 
4392 	return ((void *)connp);
4393 }
4394 
4395 /* BEGIN CSTYLED */
4396 /*
4397  *
4398  * The sockfs ACCEPT path:
4399  * =======================
4400  *
4401  * The eager is now established in its own perimeter as soon as SYN is
4402  * received in tcp_input_listener(). When sockfs receives conn_ind, it
4403  * completes the accept processing on the acceptor STREAM. The sending
4404  * of conn_ind part is common for both sockfs listener and a TLI/XTI
4405  * listener but a TLI/XTI listener completes the accept processing
4406  * on the listener perimeter.
4407  *
4408  * Common control flow for 3 way handshake:
4409  * ----------------------------------------
4410  *
4411  * incoming SYN (listener perimeter)	-> tcp_input_listener()
4412  *
4413  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_input_data()
4414  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
4415  *
4416  * Sockfs ACCEPT Path:
4417  * -------------------
4418  *
4419  * open acceptor stream (tcp_open allocates tcp_tli_accept()
4420  * as STREAM entry point)
4421  *
4422  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_tli_accept()
4423  *
4424  * tcp_tli_accept() extracts the eager and makes the q->q_ptr <-> eager
4425  * association (we are not behind eager's squeue but sockfs is protecting us
4426  * and no one knows about this stream yet. The STREAMS entry point q->q_info
4427  * is changed to point at tcp_wput().
4428  *
4429  * tcp_accept_common() sends any deferred eagers via tcp_send_pending() to
4430  * listener (done on listener's perimeter).
4431  *
4432  * tcp_tli_accept() calls tcp_accept_finish() on eagers perimeter to finish
4433  * accept.
4434  *
4435  * TLI/XTI client ACCEPT path:
4436  * ---------------------------
4437  *
4438  * soaccept() sends T_CONN_RES on the listener STREAM.
4439  *
4440  * tcp_tli_accept() -> tcp_accept_swap() complete the processing and send
4441  * a M_SETOPS mblk to eager perimeter to finish accept (tcp_accept_finish()).
4442  *
4443  * Locks:
4444  * ======
4445  *
4446  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
4447  * and listeners->tcp_eager_next_q.
4448  *
4449  * Referencing:
4450  * ============
4451  *
4452  * 1) We start out in tcp_input_listener by eager placing a ref on
4453  * listener and listener adding eager to listeners->tcp_eager_next_q0.
4454  *
4455  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
4456  * doing so we place a ref on the eager. This ref is finally dropped at the
4457  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
4458  * reference is dropped by the squeue framework.
4459  *
4460  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
4461  *
4462  * The reference must be released by the same entity that added the reference
4463  * In the above scheme, the eager is the entity that adds and releases the
4464  * references. Note that tcp_accept_finish executes in the squeue of the eager
4465  * (albeit after it is attached to the acceptor stream). Though 1. executes
4466  * in the listener's squeue, the eager is nascent at this point and the
4467  * reference can be considered to have been added on behalf of the eager.
4468  *
4469  * Eager getting a Reset or listener closing:
4470  * ==========================================
4471  *
4472  * Once the listener and eager are linked, the listener never does the unlink.
4473  * If the listener needs to close, tcp_eager_cleanup() is called which queues
4474  * a message on all eager perimeter. The eager then does the unlink, clears
4475  * any pointers to the listener's queue and drops the reference to the
4476  * listener. The listener waits in tcp_close outside the squeue until its
4477  * refcount has dropped to 1. This ensures that the listener has waited for
4478  * all eagers to clear their association with the listener.
4479  *
4480  * Similarly, if eager decides to go away, it can unlink itself and close.
4481  * When the T_CONN_RES comes down, we check if eager has closed. Note that
4482  * the reference to eager is still valid because of the extra ref we put
4483  * in tcp_send_conn_ind.
4484  *
4485  * Listener can always locate the eager under the protection
4486  * of the listener->tcp_eager_lock, and then do a refhold
4487  * on the eager during the accept processing.
4488  *
4489  * The acceptor stream accesses the eager in the accept processing
4490  * based on the ref placed on eager before sending T_conn_ind.
4491  * The only entity that can negate this refhold is a listener close
4492  * which is mutually exclusive with an active acceptor stream.
4493  *
4494  * Eager's reference on the listener
4495  * ===================================
4496  *
4497  * If the accept happens (even on a closed eager) the eager drops its
4498  * reference on the listener at the start of tcp_accept_finish. If the
4499  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
4500  * the reference is dropped in tcp_closei_local. If the listener closes,
4501  * the reference is dropped in tcp_eager_kill. In all cases the reference
4502  * is dropped while executing in the eager's context (squeue).
4503  */
4504 /* END CSTYLED */
4505 
4506 /* Process the SYN packet, mp, directed at the listener 'tcp' */
4507 
4508 /*
4509  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
4510  * tcp_input_data will not see any packets for listeners since the listener
4511  * has conn_recv set to tcp_input_listener.
4512  */
4513 /* ARGSUSED */
4514 void
4515 tcp_input_listener(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4516 {
4517 	tcpha_t		*tcpha;
4518 	uint32_t	seg_seq;
4519 	tcp_t		*eager;
4520 	int		err;
4521 	conn_t		*econnp = NULL;
4522 	squeue_t	*new_sqp;
4523 	mblk_t		*mp1;
4524 	uint_t 		ip_hdr_len;
4525 	conn_t		*lconnp = (conn_t *)arg;
4526 	tcp_t		*listener = lconnp->conn_tcp;
4527 	tcp_stack_t	*tcps = listener->tcp_tcps;
4528 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
4529 	uint_t		flags;
4530 	mblk_t		*tpi_mp;
4531 	uint_t		ifindex = ira->ira_ruifindex;
4532 	boolean_t	tlc_set = B_FALSE;
4533 
4534 	ip_hdr_len = ira->ira_ip_hdr_length;
4535 	tcpha = (tcpha_t *)&mp->b_rptr[ip_hdr_len];
4536 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
4537 
4538 	if (!(flags & TH_SYN)) {
4539 		if ((flags & TH_RST) || (flags & TH_URG)) {
4540 			freemsg(mp);
4541 			return;
4542 		}
4543 		if (flags & TH_ACK) {
4544 			/* Note this executes in listener's squeue */
4545 			tcp_xmit_listeners_reset(mp, ira, ipst, lconnp);
4546 			return;
4547 		}
4548 
4549 		freemsg(mp);
4550 		return;
4551 	}
4552 
4553 	if (listener->tcp_state != TCPS_LISTEN)
4554 		goto error2;
4555 
4556 	ASSERT(IPCL_IS_BOUND(lconnp));
4557 
4558 	mutex_enter(&listener->tcp_eager_lock);
4559 
4560 	/*
4561 	 * The system is under memory pressure, so we need to do our part
4562 	 * to relieve the pressure.  So we only accept new request if there
4563 	 * is nothing waiting to be accepted or waiting to complete the 3-way
4564 	 * handshake.  This means that busy listener will not get too many
4565 	 * new requests which they cannot handle in time while non-busy
4566 	 * listener is still functioning properly.
4567 	 */
4568 	if (tcps->tcps_reclaim && (listener->tcp_conn_req_cnt_q > 0 ||
4569 	    listener->tcp_conn_req_cnt_q0 > 0)) {
4570 		mutex_exit(&listener->tcp_eager_lock);
4571 		TCP_STAT(tcps, tcp_listen_mem_drop);
4572 		goto error2;
4573 	}
4574 
4575 	if (listener->tcp_conn_req_cnt_q >= listener->tcp_conn_req_max) {
4576 		mutex_exit(&listener->tcp_eager_lock);
4577 		TCP_STAT(tcps, tcp_listendrop);
4578 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
4579 		if (lconnp->conn_debug) {
4580 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
4581 			    "tcp_input_listener: listen backlog (max=%d) "
4582 			    "overflow (%d pending) on %s",
4583 			    listener->tcp_conn_req_max,
4584 			    listener->tcp_conn_req_cnt_q,
4585 			    tcp_display(listener, NULL, DISP_PORT_ONLY));
4586 		}
4587 		goto error2;
4588 	}
4589 
4590 	if (listener->tcp_conn_req_cnt_q0 >=
4591 	    listener->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
4592 		/*
4593 		 * Q0 is full. Drop a pending half-open req from the queue
4594 		 * to make room for the new SYN req. Also mark the time we
4595 		 * drop a SYN.
4596 		 *
4597 		 * A more aggressive defense against SYN attack will
4598 		 * be to set the "tcp_syn_defense" flag now.
4599 		 */
4600 		TCP_STAT(tcps, tcp_listendropq0);
4601 		listener->tcp_last_rcv_lbolt = ddi_get_lbolt64();
4602 		if (!tcp_drop_q0(listener)) {
4603 			mutex_exit(&listener->tcp_eager_lock);
4604 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
4605 			if (lconnp->conn_debug) {
4606 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4607 				    "tcp_input_listener: listen half-open "
4608 				    "queue (max=%d) full (%d pending) on %s",
4609 				    tcps->tcps_conn_req_max_q0,
4610 				    listener->tcp_conn_req_cnt_q0,
4611 				    tcp_display(listener, NULL,
4612 				    DISP_PORT_ONLY));
4613 			}
4614 			goto error2;
4615 		}
4616 	}
4617 
4618 	/*
4619 	 * Enforce the limit set on the number of connections per listener.
4620 	 * Note that tlc_cnt starts with 1.  So need to add 1 to tlc_max
4621 	 * for comparison.
4622 	 */
4623 	if (listener->tcp_listen_cnt != NULL) {
4624 		tcp_listen_cnt_t *tlc = listener->tcp_listen_cnt;
4625 		int64_t now;
4626 
4627 		if (atomic_add_32_nv(&tlc->tlc_cnt, 1) > tlc->tlc_max + 1) {
4628 			mutex_exit(&listener->tcp_eager_lock);
4629 			now = ddi_get_lbolt64();
4630 			atomic_add_32(&tlc->tlc_cnt, -1);
4631 			TCP_STAT(tcps, tcp_listen_cnt_drop);
4632 			tlc->tlc_drop++;
4633 			if (now - tlc->tlc_report_time >
4634 			    MSEC_TO_TICK(TCP_TLC_REPORT_INTERVAL)) {
4635 				zcmn_err(lconnp->conn_zoneid, CE_WARN,
4636 				    "Listener (port %d) connection max (%u) "
4637 				    "reached: %u attempts dropped total\n",
4638 				    ntohs(listener->tcp_connp->conn_lport),
4639 				    tlc->tlc_max, tlc->tlc_drop);
4640 				tlc->tlc_report_time = now;
4641 			}
4642 			goto error2;
4643 		}
4644 		tlc_set = B_TRUE;
4645 	}
4646 
4647 	mutex_exit(&listener->tcp_eager_lock);
4648 
4649 	/*
4650 	 * IP sets ira_sqp to either the senders conn_sqp (for loopback)
4651 	 * or based on the ring (for packets from GLD). Otherwise it is
4652 	 * set based on lbolt i.e., a somewhat random number.
4653 	 */
4654 	ASSERT(ira->ira_sqp != NULL);
4655 	new_sqp = ira->ira_sqp;
4656 
4657 	econnp = (conn_t *)tcp_get_conn(arg2, tcps);
4658 	if (econnp == NULL)
4659 		goto error2;
4660 
4661 	ASSERT(econnp->conn_netstack == lconnp->conn_netstack);
4662 	econnp->conn_sqp = new_sqp;
4663 	econnp->conn_initial_sqp = new_sqp;
4664 	econnp->conn_ixa->ixa_sqp = new_sqp;
4665 
4666 	econnp->conn_fport = tcpha->tha_lport;
4667 	econnp->conn_lport = tcpha->tha_fport;
4668 
4669 	err = conn_inherit_parent(lconnp, econnp);
4670 	if (err != 0)
4671 		goto error3;
4672 
4673 	/* We already know the laddr of the new connection is ours */
4674 	econnp->conn_ixa->ixa_src_generation = ipst->ips_src_generation;
4675 
4676 	ASSERT(OK_32PTR(mp->b_rptr));
4677 	ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION ||
4678 	    IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
4679 
4680 	if (lconnp->conn_family == AF_INET) {
4681 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
4682 		tpi_mp = tcp_conn_create_v4(lconnp, econnp, mp, ira);
4683 	} else {
4684 		tpi_mp = tcp_conn_create_v6(lconnp, econnp, mp, ira);
4685 	}
4686 
4687 	if (tpi_mp == NULL)
4688 		goto error3;
4689 
4690 	eager = econnp->conn_tcp;
4691 	eager->tcp_detached = B_TRUE;
4692 	SOCK_CONNID_INIT(eager->tcp_connid);
4693 
4694 	tcp_init_values(eager);
4695 
4696 	ASSERT((econnp->conn_ixa->ixa_flags &
4697 	    (IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
4698 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO)) ==
4699 	    (IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
4700 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO));
4701 
4702 	if (!tcps->tcps_dev_flow_ctl)
4703 		econnp->conn_ixa->ixa_flags |= IXAF_NO_DEV_FLOW_CTL;
4704 
4705 	/* Prepare for diffing against previous packets */
4706 	eager->tcp_recvifindex = 0;
4707 	eager->tcp_recvhops = 0xffffffffU;
4708 
4709 	if (!(ira->ira_flags & IRAF_IS_IPV4) && econnp->conn_bound_if == 0) {
4710 		if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_faddr_v6) ||
4711 		    IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6)) {
4712 			econnp->conn_incoming_ifindex = ifindex;
4713 			econnp->conn_ixa->ixa_flags |= IXAF_SCOPEID_SET;
4714 			econnp->conn_ixa->ixa_scopeid = ifindex;
4715 		}
4716 	}
4717 
4718 	if ((ira->ira_flags & (IRAF_IS_IPV4|IRAF_IPV4_OPTIONS)) ==
4719 	    (IRAF_IS_IPV4|IRAF_IPV4_OPTIONS) &&
4720 	    tcps->tcps_rev_src_routes) {
4721 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
4722 		ip_pkt_t *ipp = &econnp->conn_xmit_ipp;
4723 
4724 		/* Source routing option copyover (reverse it) */
4725 		err = ip_find_hdr_v4(ipha, ipp, B_TRUE);
4726 		if (err != 0) {
4727 			freemsg(tpi_mp);
4728 			goto error3;
4729 		}
4730 		ip_pkt_source_route_reverse_v4(ipp);
4731 	}
4732 
4733 	ASSERT(eager->tcp_conn.tcp_eager_conn_ind == NULL);
4734 	ASSERT(!eager->tcp_tconnind_started);
4735 	/*
4736 	 * If the SYN came with a credential, it's a loopback packet or a
4737 	 * labeled packet; attach the credential to the TPI message.
4738 	 */
4739 	if (ira->ira_cred != NULL)
4740 		mblk_setcred(tpi_mp, ira->ira_cred, ira->ira_cpid);
4741 
4742 	eager->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4743 
4744 	/* Inherit the listener's SSL protection state */
4745 	if ((eager->tcp_kssl_ent = listener->tcp_kssl_ent) != NULL) {
4746 		kssl_hold_ent(eager->tcp_kssl_ent);
4747 		eager->tcp_kssl_pending = B_TRUE;
4748 	}
4749 
4750 	/* Inherit the listener's non-STREAMS flag */
4751 	if (IPCL_IS_NONSTR(lconnp)) {
4752 		econnp->conn_flags |= IPCL_NONSTR;
4753 	}
4754 
4755 	ASSERT(eager->tcp_ordrel_mp == NULL);
4756 
4757 	if (!IPCL_IS_NONSTR(econnp)) {
4758 		/*
4759 		 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that
4760 		 * at close time, we will always have that to send up.
4761 		 * Otherwise, we need to do special handling in case the
4762 		 * allocation fails at that time.
4763 		 */
4764 		if ((eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
4765 			goto error3;
4766 	}
4767 	/*
4768 	 * Now that the IP addresses and ports are setup in econnp we
4769 	 * can do the IPsec policy work.
4770 	 */
4771 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
4772 		if (lconnp->conn_policy != NULL) {
4773 			/*
4774 			 * Inherit the policy from the listener; use
4775 			 * actions from ira
4776 			 */
4777 			if (!ip_ipsec_policy_inherit(econnp, lconnp, ira)) {
4778 				CONN_DEC_REF(econnp);
4779 				freemsg(mp);
4780 				goto error3;
4781 			}
4782 		}
4783 	}
4784 
4785 	/* Inherit various TCP parameters from the listener */
4786 	eager->tcp_naglim = listener->tcp_naglim;
4787 	eager->tcp_first_timer_threshold = listener->tcp_first_timer_threshold;
4788 	eager->tcp_second_timer_threshold =
4789 	    listener->tcp_second_timer_threshold;
4790 	eager->tcp_first_ctimer_threshold =
4791 	    listener->tcp_first_ctimer_threshold;
4792 	eager->tcp_second_ctimer_threshold =
4793 	    listener->tcp_second_ctimer_threshold;
4794 
4795 	/*
4796 	 * tcp_set_destination() may set tcp_rwnd according to the route
4797 	 * metrics. If it does not, the eager's receive window will be set
4798 	 * to the listener's receive window later in this function.
4799 	 */
4800 	eager->tcp_rwnd = 0;
4801 
4802 	/*
4803 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
4804 	 * calling tcp_process_options() which set the initial cwnd.
4805 	 */
4806 	eager->tcp_init_cwnd = listener->tcp_init_cwnd;
4807 
4808 	if (is_system_labeled()) {
4809 		ip_xmit_attr_t *ixa = econnp->conn_ixa;
4810 
4811 		ASSERT(ira->ira_tsl != NULL);
4812 		/* Discard any old label */
4813 		if (ixa->ixa_free_flags & IXA_FREE_TSL) {
4814 			ASSERT(ixa->ixa_tsl != NULL);
4815 			label_rele(ixa->ixa_tsl);
4816 			ixa->ixa_free_flags &= ~IXA_FREE_TSL;
4817 			ixa->ixa_tsl = NULL;
4818 		}
4819 		if ((lconnp->conn_mlp_type != mlptSingle ||
4820 		    lconnp->conn_mac_mode != CONN_MAC_DEFAULT) &&
4821 		    ira->ira_tsl != NULL) {
4822 			/*
4823 			 * If this is an MLP connection or a MAC-Exempt
4824 			 * connection with an unlabeled node, packets are to be
4825 			 * exchanged using the security label of the received
4826 			 * SYN packet instead of the server application's label.
4827 			 * tsol_check_dest called from ip_set_destination
4828 			 * might later update TSF_UNLABELED by replacing
4829 			 * ixa_tsl with a new label.
4830 			 */
4831 			label_hold(ira->ira_tsl);
4832 			ip_xmit_attr_replace_tsl(ixa, ira->ira_tsl);
4833 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
4834 			    econnp, ts_label_t *, ixa->ixa_tsl)
4835 		} else {
4836 			ixa->ixa_tsl = crgetlabel(econnp->conn_cred);
4837 			DTRACE_PROBE2(syn_accept, conn_t *,
4838 			    econnp, ts_label_t *, ixa->ixa_tsl)
4839 		}
4840 		/*
4841 		 * conn_connect() called from tcp_set_destination will verify
4842 		 * the destination is allowed to receive packets at the
4843 		 * security label of the SYN-ACK we are generating. As part of
4844 		 * that, tsol_check_dest() may create a new effective label for
4845 		 * this connection.
4846 		 * Finally conn_connect() will call conn_update_label.
4847 		 * All that remains for TCP to do is to call
4848 		 * conn_build_hdr_template which is done as part of
4849 		 * tcp_set_destination.
4850 		 */
4851 	}
4852 
4853 	/*
4854 	 * Since we will clear tcp_listener before we clear tcp_detached
4855 	 * in the accept code we need tcp_hard_binding aka tcp_accept_inprogress
4856 	 * so we can tell a TCP_DETACHED_NONEAGER apart.
4857 	 */
4858 	eager->tcp_hard_binding = B_TRUE;
4859 
4860 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
4861 	    TCP_BIND_HASH(econnp->conn_lport)], eager, 0);
4862 
4863 	CL_INET_CONNECT(econnp, B_FALSE, err);
4864 	if (err != 0) {
4865 		tcp_bind_hash_remove(eager);
4866 		goto error3;
4867 	}
4868 
4869 	/*
4870 	 * No need to check for multicast destination since ip will only pass
4871 	 * up multicasts to those that have expressed interest
4872 	 * TODO: what about rejecting broadcasts?
4873 	 * Also check that source is not a multicast or broadcast address.
4874 	 */
4875 	eager->tcp_state = TCPS_SYN_RCVD;
4876 	SOCK_CONNID_BUMP(eager->tcp_connid);
4877 
4878 	/*
4879 	 * Adapt our mss, ttl, ... based on the remote address.
4880 	 */
4881 
4882 	if (tcp_set_destination(eager) != 0) {
4883 		BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4884 		/* Undo the bind_hash_insert */
4885 		tcp_bind_hash_remove(eager);
4886 		goto error3;
4887 	}
4888 
4889 	/* Process all TCP options. */
4890 	tcp_process_options(eager, tcpha);
4891 
4892 	/* Is the other end ECN capable? */
4893 	if (tcps->tcps_ecn_permitted >= 1 &&
4894 	    (tcpha->tha_flags & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
4895 		eager->tcp_ecn_ok = B_TRUE;
4896 	}
4897 
4898 	/*
4899 	 * The listener's conn_rcvbuf should be the default window size or a
4900 	 * window size changed via SO_RCVBUF option. First round up the
4901 	 * eager's tcp_rwnd to the nearest MSS. Then find out the window
4902 	 * scale option value if needed. Call tcp_rwnd_set() to finish the
4903 	 * setting.
4904 	 *
4905 	 * Note if there is a rpipe metric associated with the remote host,
4906 	 * we should not inherit receive window size from listener.
4907 	 */
4908 	eager->tcp_rwnd = MSS_ROUNDUP(
4909 	    (eager->tcp_rwnd == 0 ? econnp->conn_rcvbuf :
4910 	    eager->tcp_rwnd), eager->tcp_mss);
4911 	if (eager->tcp_snd_ws_ok)
4912 		tcp_set_ws_value(eager);
4913 	/*
4914 	 * Note that this is the only place tcp_rwnd_set() is called for
4915 	 * accepting a connection.  We need to call it here instead of
4916 	 * after the 3-way handshake because we need to tell the other
4917 	 * side our rwnd in the SYN-ACK segment.
4918 	 */
4919 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
4920 
4921 	ASSERT(eager->tcp_connp->conn_rcvbuf != 0 &&
4922 	    eager->tcp_connp->conn_rcvbuf == eager->tcp_rwnd);
4923 
4924 	ASSERT(econnp->conn_rcvbuf != 0 &&
4925 	    econnp->conn_rcvbuf == eager->tcp_rwnd);
4926 
4927 	/* Put a ref on the listener for the eager. */
4928 	CONN_INC_REF(lconnp);
4929 	mutex_enter(&listener->tcp_eager_lock);
4930 	listener->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
4931 	eager->tcp_eager_next_q0 = listener->tcp_eager_next_q0;
4932 	listener->tcp_eager_next_q0 = eager;
4933 	eager->tcp_eager_prev_q0 = listener;
4934 
4935 	/* Set tcp_listener before adding it to tcp_conn_fanout */
4936 	eager->tcp_listener = listener;
4937 	eager->tcp_saved_listener = listener;
4938 
4939 	/*
4940 	 * Set tcp_listen_cnt so that when the connection is done, the counter
4941 	 * is decremented.
4942 	 */
4943 	eager->tcp_listen_cnt = listener->tcp_listen_cnt;
4944 
4945 	/*
4946 	 * Tag this detached tcp vector for later retrieval
4947 	 * by our listener client in tcp_accept().
4948 	 */
4949 	eager->tcp_conn_req_seqnum = listener->tcp_conn_req_seqnum;
4950 	listener->tcp_conn_req_cnt_q0++;
4951 	if (++listener->tcp_conn_req_seqnum == -1) {
4952 		/*
4953 		 * -1 is "special" and defined in TPI as something
4954 		 * that should never be used in T_CONN_IND
4955 		 */
4956 		++listener->tcp_conn_req_seqnum;
4957 	}
4958 	mutex_exit(&listener->tcp_eager_lock);
4959 
4960 	if (listener->tcp_syn_defense) {
4961 		/* Don't drop the SYN that comes from a good IP source */
4962 		ipaddr_t *addr_cache;
4963 
4964 		addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
4965 		if (addr_cache != NULL && econnp->conn_faddr_v4 ==
4966 		    addr_cache[IP_ADDR_CACHE_HASH(econnp->conn_faddr_v4)]) {
4967 			eager->tcp_dontdrop = B_TRUE;
4968 		}
4969 	}
4970 
4971 	/*
4972 	 * We need to insert the eager in its own perimeter but as soon
4973 	 * as we do that, we expose the eager to the classifier and
4974 	 * should not touch any field outside the eager's perimeter.
4975 	 * So do all the work necessary before inserting the eager
4976 	 * in its own perimeter. Be optimistic that conn_connect()
4977 	 * will succeed but undo everything if it fails.
4978 	 */
4979 	seg_seq = ntohl(tcpha->tha_seq);
4980 	eager->tcp_irs = seg_seq;
4981 	eager->tcp_rack = seg_seq;
4982 	eager->tcp_rnxt = seg_seq + 1;
4983 	eager->tcp_tcpha->tha_ack = htonl(eager->tcp_rnxt);
4984 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
4985 	eager->tcp_state = TCPS_SYN_RCVD;
4986 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
4987 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
4988 	if (mp1 == NULL) {
4989 		/*
4990 		 * Increment the ref count as we are going to
4991 		 * enqueueing an mp in squeue
4992 		 */
4993 		CONN_INC_REF(econnp);
4994 		goto error;
4995 	}
4996 
4997 	/*
4998 	 * We need to start the rto timer. In normal case, we start
4999 	 * the timer after sending the packet on the wire (or at
5000 	 * least believing that packet was sent by waiting for
5001 	 * conn_ip_output() to return). Since this is the first packet
5002 	 * being sent on the wire for the eager, our initial tcp_rto
5003 	 * is at least tcp_rexmit_interval_min which is a fairly
5004 	 * large value to allow the algorithm to adjust slowly to large
5005 	 * fluctuations of RTT during first few transmissions.
5006 	 *
5007 	 * Starting the timer first and then sending the packet in this
5008 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5009 	 * is of the order of several 100ms and starting the timer
5010 	 * first and then sending the packet will result in difference
5011 	 * of few micro seconds.
5012 	 *
5013 	 * Without this optimization, we are forced to hold the fanout
5014 	 * lock across the ipcl_bind_insert() and sending the packet
5015 	 * so that we don't race against an incoming packet (maybe RST)
5016 	 * for this eager.
5017 	 *
5018 	 * It is necessary to acquire an extra reference on the eager
5019 	 * at this point and hold it until after tcp_send_data() to
5020 	 * ensure against an eager close race.
5021 	 */
5022 
5023 	CONN_INC_REF(econnp);
5024 
5025 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5026 
5027 	/*
5028 	 * Insert the eager in its own perimeter now. We are ready to deal
5029 	 * with any packets on eager.
5030 	 */
5031 	if (ipcl_conn_insert(econnp) != 0)
5032 		goto error;
5033 
5034 	ASSERT(econnp->conn_ixa->ixa_notify_cookie == econnp->conn_tcp);
5035 	freemsg(mp);
5036 	/*
5037 	 * Send the SYN-ACK. Use the right squeue so that conn_ixa is
5038 	 * only used by one thread at a time.
5039 	 */
5040 	if (econnp->conn_sqp == lconnp->conn_sqp) {
5041 		(void) conn_ip_output(mp1, econnp->conn_ixa);
5042 		CONN_DEC_REF(econnp);
5043 	} else {
5044 		SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_send_synack,
5045 		    econnp, NULL, SQ_PROCESS, SQTAG_TCP_SEND_SYNACK);
5046 	}
5047 	return;
5048 error:
5049 	freemsg(mp1);
5050 	eager->tcp_closemp_used = B_TRUE;
5051 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5052 	mp1 = &eager->tcp_closemp;
5053 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5054 	    econnp, NULL, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5055 
5056 	/*
5057 	 * If a connection already exists, send the mp to that connections so
5058 	 * that it can be appropriately dealt with.
5059 	 */
5060 	ipst = tcps->tcps_netstack->netstack_ip;
5061 
5062 	if ((econnp = ipcl_classify(mp, ira, ipst)) != NULL) {
5063 		if (!IPCL_IS_CONNECTED(econnp)) {
5064 			/*
5065 			 * Something bad happened. ipcl_conn_insert()
5066 			 * failed because a connection already existed
5067 			 * in connected hash but we can't find it
5068 			 * anymore (someone blew it away). Just
5069 			 * free this message and hopefully remote
5070 			 * will retransmit at which time the SYN can be
5071 			 * treated as a new connection or dealth with
5072 			 * a TH_RST if a connection already exists.
5073 			 */
5074 			CONN_DEC_REF(econnp);
5075 			freemsg(mp);
5076 		} else {
5077 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp, tcp_input_data,
5078 			    econnp, ira, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5079 		}
5080 	} else {
5081 		/* Nobody wants this packet */
5082 		freemsg(mp);
5083 	}
5084 	return;
5085 error3:
5086 	CONN_DEC_REF(econnp);
5087 error2:
5088 	freemsg(mp);
5089 	if (tlc_set)
5090 		atomic_add_32(&listener->tcp_listen_cnt->tlc_cnt, -1);
5091 }
5092 
5093 /* ARGSUSED2 */
5094 void
5095 tcp_send_synack(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
5096 {
5097 	conn_t	*econnp = (conn_t *)arg;
5098 	tcp_t	*tcp = econnp->conn_tcp;
5099 
5100 	/* Guard against a RST having blown it away while on the squeue */
5101 	if (tcp->tcp_state == TCPS_CLOSED) {
5102 		freemsg(mp);
5103 		return;
5104 	}
5105 
5106 	(void) conn_ip_output(mp, econnp->conn_ixa);
5107 }
5108 
5109 /*
5110  * In an ideal case of vertical partition in NUMA architecture, its
5111  * beneficial to have the listener and all the incoming connections
5112  * tied to the same squeue. The other constraint is that incoming
5113  * connections should be tied to the squeue attached to interrupted
5114  * CPU for obvious locality reason so this leaves the listener to
5115  * be tied to the same squeue. Our only problem is that when listener
5116  * is binding, the CPU that will get interrupted by the NIC whose
5117  * IP address the listener is binding to is not even known. So
5118  * the code below allows us to change that binding at the time the
5119  * CPU is interrupted by virtue of incoming connection's squeue.
5120  *
5121  * This is usefull only in case of a listener bound to a specific IP
5122  * address. For other kind of listeners, they get bound the
5123  * very first time and there is no attempt to rebind them.
5124  */
5125 void
5126 tcp_input_listener_unbound(void *arg, mblk_t *mp, void *arg2,
5127     ip_recv_attr_t *ira)
5128 {
5129 	conn_t		*connp = (conn_t *)arg;
5130 	squeue_t	*sqp = (squeue_t *)arg2;
5131 	squeue_t	*new_sqp;
5132 	uint32_t	conn_flags;
5133 
5134 	/*
5135 	 * IP sets ira_sqp to either the senders conn_sqp (for loopback)
5136 	 * or based on the ring (for packets from GLD). Otherwise it is
5137 	 * set based on lbolt i.e., a somewhat random number.
5138 	 */
5139 	ASSERT(ira->ira_sqp != NULL);
5140 	new_sqp = ira->ira_sqp;
5141 
5142 	if (connp->conn_fanout == NULL)
5143 		goto done;
5144 
5145 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5146 		mutex_enter(&connp->conn_fanout->connf_lock);
5147 		mutex_enter(&connp->conn_lock);
5148 		/*
5149 		 * No one from read or write side can access us now
5150 		 * except for already queued packets on this squeue.
5151 		 * But since we haven't changed the squeue yet, they
5152 		 * can't execute. If they are processed after we have
5153 		 * changed the squeue, they are sent back to the
5154 		 * correct squeue down below.
5155 		 * But a listner close can race with processing of
5156 		 * incoming SYN. If incoming SYN processing changes
5157 		 * the squeue then the listener close which is waiting
5158 		 * to enter the squeue would operate on the wrong
5159 		 * squeue. Hence we don't change the squeue here unless
5160 		 * the refcount is exactly the minimum refcount. The
5161 		 * minimum refcount of 4 is counted as - 1 each for
5162 		 * TCP and IP, 1 for being in the classifier hash, and
5163 		 * 1 for the mblk being processed.
5164 		 */
5165 
5166 		if (connp->conn_ref != 4 ||
5167 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5168 			mutex_exit(&connp->conn_lock);
5169 			mutex_exit(&connp->conn_fanout->connf_lock);
5170 			goto done;
5171 		}
5172 		if (connp->conn_sqp != new_sqp) {
5173 			while (connp->conn_sqp != new_sqp)
5174 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5175 			/* No special MT issues for outbound ixa_sqp hint */
5176 			connp->conn_ixa->ixa_sqp = new_sqp;
5177 		}
5178 
5179 		do {
5180 			conn_flags = connp->conn_flags;
5181 			conn_flags |= IPCL_FULLY_BOUND;
5182 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5183 			    conn_flags);
5184 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5185 
5186 		mutex_exit(&connp->conn_fanout->connf_lock);
5187 		mutex_exit(&connp->conn_lock);
5188 
5189 		/*
5190 		 * Assume we have picked a good squeue for the listener. Make
5191 		 * subsequent SYNs not try to change the squeue.
5192 		 */
5193 		connp->conn_recv = tcp_input_listener;
5194 	}
5195 
5196 done:
5197 	if (connp->conn_sqp != sqp) {
5198 		CONN_INC_REF(connp);
5199 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5200 		    ira, SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5201 	} else {
5202 		tcp_input_listener(connp, mp, sqp, ira);
5203 	}
5204 }
5205 
5206 /*
5207  * Successful connect request processing begins when our client passes
5208  * a T_CONN_REQ message into tcp_wput(), which performs function calls into
5209  * IP and the passes a T_OK_ACK (or T_ERROR_ACK upstream).
5210  *
5211  * After various error checks are completed, tcp_tpi_connect() lays
5212  * the target address and port into the composite header template.
5213  * Then we ask IP for information, including a source address if we didn't
5214  * already have one. Finally we prepare to send the SYN packet, and then
5215  * send up the T_OK_ACK reply message.
5216  */
5217 static void
5218 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5219 {
5220 	sin_t		*sin;
5221 	struct T_conn_req	*tcr;
5222 	struct sockaddr	*sa;
5223 	socklen_t	len;
5224 	int		error;
5225 	cred_t		*cr;
5226 	pid_t		cpid;
5227 	conn_t		*connp = tcp->tcp_connp;
5228 	queue_t		*q = connp->conn_wq;
5229 
5230 	/*
5231 	 * All Solaris components should pass a db_credp
5232 	 * for this TPI message, hence we ASSERT.
5233 	 * But in case there is some other M_PROTO that looks
5234 	 * like a TPI message sent by some other kernel
5235 	 * component, we check and return an error.
5236 	 */
5237 	cr = msg_getcred(mp, &cpid);
5238 	ASSERT(cr != NULL);
5239 	if (cr == NULL) {
5240 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5241 		return;
5242 	}
5243 
5244 	tcr = (struct T_conn_req *)mp->b_rptr;
5245 
5246 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5247 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5248 		tcp_err_ack(tcp, mp, TPROTO, 0);
5249 		return;
5250 	}
5251 
5252 	/*
5253 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5254 	 * will always have that to send up.  Otherwise, we need to do
5255 	 * special handling in case the allocation fails at that time.
5256 	 * If the end point is TPI, the tcp_t can be reused and the
5257 	 * tcp_ordrel_mp may be allocated already.
5258 	 */
5259 	if (tcp->tcp_ordrel_mp == NULL) {
5260 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5261 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5262 			return;
5263 		}
5264 	}
5265 
5266 	/*
5267 	 * Determine packet type based on type of address passed in
5268 	 * the request should contain an IPv4 or IPv6 address.
5269 	 * Make sure that address family matches the type of
5270 	 * family of the address passed down.
5271 	 */
5272 	switch (tcr->DEST_length) {
5273 	default:
5274 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5275 		return;
5276 
5277 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5278 		/*
5279 		 * XXX: The check for valid DEST_length was not there
5280 		 * in earlier releases and some buggy
5281 		 * TLI apps (e.g Sybase) got away with not feeding
5282 		 * in sin_zero part of address.
5283 		 * We allow that bug to keep those buggy apps humming.
5284 		 * Test suites require the check on DEST_length.
5285 		 * We construct a new mblk with valid DEST_length
5286 		 * free the original so the rest of the code does
5287 		 * not have to keep track of this special shorter
5288 		 * length address case.
5289 		 */
5290 		mblk_t *nmp;
5291 		struct T_conn_req *ntcr;
5292 		sin_t *nsin;
5293 
5294 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5295 		    tcr->OPT_length, BPRI_HI);
5296 		if (nmp == NULL) {
5297 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5298 			return;
5299 		}
5300 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5301 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5302 		ntcr->PRIM_type = T_CONN_REQ;
5303 		ntcr->DEST_length = sizeof (sin_t);
5304 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5305 
5306 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5307 		*nsin = sin_null;
5308 		/* Get pointer to shorter address to copy from original mp */
5309 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5310 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5311 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5312 			freemsg(nmp);
5313 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5314 			return;
5315 		}
5316 		nsin->sin_family = sin->sin_family;
5317 		nsin->sin_port = sin->sin_port;
5318 		nsin->sin_addr = sin->sin_addr;
5319 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5320 		nmp->b_wptr = (uchar_t *)&nsin[1];
5321 		if (tcr->OPT_length != 0) {
5322 			ntcr->OPT_length = tcr->OPT_length;
5323 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5324 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5325 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5326 			    tcr->OPT_length);
5327 			nmp->b_wptr += tcr->OPT_length;
5328 		}
5329 		freemsg(mp);	/* original mp freed */
5330 		mp = nmp;	/* re-initialize original variables */
5331 		tcr = ntcr;
5332 	}
5333 	/* FALLTHRU */
5334 
5335 	case sizeof (sin_t):
5336 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5337 		    sizeof (sin_t));
5338 		len = sizeof (sin_t);
5339 		break;
5340 
5341 	case sizeof (sin6_t):
5342 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5343 		    sizeof (sin6_t));
5344 		len = sizeof (sin6_t);
5345 		break;
5346 	}
5347 
5348 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
5349 	if (error != 0) {
5350 		tcp_err_ack(tcp, mp, TSYSERR, error);
5351 		return;
5352 	}
5353 
5354 	/*
5355 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
5356 	 * should key on their sequence number and cut them loose.
5357 	 */
5358 
5359 	/*
5360 	 * If options passed in, feed it for verification and handling
5361 	 */
5362 	if (tcr->OPT_length != 0) {
5363 		mblk_t	*ok_mp;
5364 		mblk_t	*discon_mp;
5365 		mblk_t  *conn_opts_mp;
5366 		int t_error, sys_error, do_disconnect;
5367 
5368 		conn_opts_mp = NULL;
5369 
5370 		if (tcp_conprim_opt_process(tcp, mp,
5371 		    &do_disconnect, &t_error, &sys_error) < 0) {
5372 			if (do_disconnect) {
5373 				ASSERT(t_error == 0 && sys_error == 0);
5374 				discon_mp = mi_tpi_discon_ind(NULL,
5375 				    ECONNREFUSED, 0);
5376 				if (!discon_mp) {
5377 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5378 					    TSYSERR, ENOMEM);
5379 					return;
5380 				}
5381 				ok_mp = mi_tpi_ok_ack_alloc(mp);
5382 				if (!ok_mp) {
5383 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5384 					    TSYSERR, ENOMEM);
5385 					return;
5386 				}
5387 				qreply(q, ok_mp);
5388 				qreply(q, discon_mp); /* no flush! */
5389 			} else {
5390 				ASSERT(t_error != 0);
5391 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
5392 				    sys_error);
5393 			}
5394 			return;
5395 		}
5396 		/*
5397 		 * Success in setting options, the mp option buffer represented
5398 		 * by OPT_length/offset has been potentially modified and
5399 		 * contains results of option processing. We copy it in
5400 		 * another mp to save it for potentially influencing returning
5401 		 * it in T_CONN_CONN.
5402 		 */
5403 		if (tcr->OPT_length != 0) { /* there are resulting options */
5404 			conn_opts_mp = copyb(mp);
5405 			if (!conn_opts_mp) {
5406 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5407 				    TSYSERR, ENOMEM);
5408 				return;
5409 			}
5410 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
5411 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
5412 			/*
5413 			 * Note:
5414 			 * These resulting option negotiation can include any
5415 			 * end-to-end negotiation options but there no such
5416 			 * thing (yet?) in our TCP/IP.
5417 			 */
5418 		}
5419 	}
5420 
5421 	/* call the non-TPI version */
5422 	error = tcp_do_connect(tcp->tcp_connp, sa, len, cr, cpid);
5423 	if (error < 0) {
5424 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
5425 	} else if (error > 0) {
5426 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
5427 	} else {
5428 		mp = mi_tpi_ok_ack_alloc(mp);
5429 	}
5430 
5431 	/*
5432 	 * Note: Code below is the "failure" case
5433 	 */
5434 	/* return error ack and blow away saved option results if any */
5435 connect_failed:
5436 	if (mp != NULL)
5437 		putnext(connp->conn_rq, mp);
5438 	else {
5439 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5440 		    TSYSERR, ENOMEM);
5441 	}
5442 }
5443 
5444 /*
5445  * Handle connect to IPv4 destinations, including connections for AF_INET6
5446  * sockets connecting to IPv4 mapped IPv6 destinations.
5447  * Returns zero if OK, a positive errno, or a negative TLI error.
5448  */
5449 static int
5450 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
5451     uint_t srcid)
5452 {
5453 	ipaddr_t 	dstaddr = *dstaddrp;
5454 	uint16_t 	lport;
5455 	conn_t		*connp = tcp->tcp_connp;
5456 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5457 	int		error;
5458 
5459 	ASSERT(connp->conn_ipversion == IPV4_VERSION);
5460 
5461 	/* Check for attempt to connect to INADDR_ANY */
5462 	if (dstaddr == INADDR_ANY)  {
5463 		/*
5464 		 * SunOS 4.x and 4.3 BSD allow an application
5465 		 * to connect a TCP socket to INADDR_ANY.
5466 		 * When they do this, the kernel picks the
5467 		 * address of one interface and uses it
5468 		 * instead.  The kernel usually ends up
5469 		 * picking the address of the loopback
5470 		 * interface.  This is an undocumented feature.
5471 		 * However, we provide the same thing here
5472 		 * in order to have source and binary
5473 		 * compatibility with SunOS 4.x.
5474 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
5475 		 * generate the T_CONN_CON.
5476 		 */
5477 		dstaddr = htonl(INADDR_LOOPBACK);
5478 		*dstaddrp = dstaddr;
5479 	}
5480 
5481 	/* Handle __sin6_src_id if socket not bound to an IP address */
5482 	if (srcid != 0 && connp->conn_laddr_v4 == INADDR_ANY) {
5483 		ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
5484 		    IPCL_ZONEID(connp), tcps->tcps_netstack);
5485 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
5486 	}
5487 
5488 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &connp->conn_faddr_v6);
5489 	connp->conn_fport = dstport;
5490 
5491 	/*
5492 	 * At this point the remote destination address and remote port fields
5493 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
5494 	 * have to see which state tcp was in so we can take appropriate action.
5495 	 */
5496 	if (tcp->tcp_state == TCPS_IDLE) {
5497 		/*
5498 		 * We support a quick connect capability here, allowing
5499 		 * clients to transition directly from IDLE to SYN_SENT
5500 		 * tcp_bindi will pick an unused port, insert the connection
5501 		 * in the bind hash and transition to BOUND state.
5502 		 */
5503 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
5504 		    tcp, B_TRUE);
5505 		lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
5506 		    B_FALSE, B_FALSE);
5507 		if (lport == 0)
5508 			return (-TNOADDR);
5509 	}
5510 
5511 	/*
5512 	 * Lookup the route to determine a source address and the uinfo.
5513 	 * Setup TCP parameters based on the metrics/DCE.
5514 	 */
5515 	error = tcp_set_destination(tcp);
5516 	if (error != 0)
5517 		return (error);
5518 
5519 	/*
5520 	 * Don't let an endpoint connect to itself.
5521 	 */
5522 	if (connp->conn_faddr_v4 == connp->conn_laddr_v4 &&
5523 	    connp->conn_fport == connp->conn_lport)
5524 		return (-TBADADDR);
5525 
5526 	tcp->tcp_state = TCPS_SYN_SENT;
5527 
5528 	return (ipcl_conn_insert_v4(connp));
5529 }
5530 
5531 /*
5532  * Handle connect to IPv6 destinations.
5533  * Returns zero if OK, a positive errno, or a negative TLI error.
5534  */
5535 static int
5536 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
5537     uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
5538 {
5539 	uint16_t 	lport;
5540 	conn_t		*connp = tcp->tcp_connp;
5541 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5542 	int		error;
5543 
5544 	ASSERT(connp->conn_family == AF_INET6);
5545 
5546 	/*
5547 	 * If we're here, it means that the destination address is a native
5548 	 * IPv6 address.  Return an error if conn_ipversion is not IPv6.  A
5549 	 * reason why it might not be IPv6 is if the socket was bound to an
5550 	 * IPv4-mapped IPv6 address.
5551 	 */
5552 	if (connp->conn_ipversion != IPV6_VERSION)
5553 		return (-TBADADDR);
5554 
5555 	/*
5556 	 * Interpret a zero destination to mean loopback.
5557 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
5558 	 * generate the T_CONN_CON.
5559 	 */
5560 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp))
5561 		*dstaddrp = ipv6_loopback;
5562 
5563 	/* Handle __sin6_src_id if socket not bound to an IP address */
5564 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&connp->conn_laddr_v6)) {
5565 		ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
5566 		    IPCL_ZONEID(connp), tcps->tcps_netstack);
5567 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
5568 	}
5569 
5570 	/*
5571 	 * Take care of the scope_id now.
5572 	 */
5573 	if (scope_id != 0 && IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
5574 		connp->conn_ixa->ixa_flags |= IXAF_SCOPEID_SET;
5575 		connp->conn_ixa->ixa_scopeid = scope_id;
5576 	} else {
5577 		connp->conn_ixa->ixa_flags &= ~IXAF_SCOPEID_SET;
5578 	}
5579 
5580 	connp->conn_flowinfo = flowinfo;
5581 	connp->conn_faddr_v6 = *dstaddrp;
5582 	connp->conn_fport = dstport;
5583 
5584 	/*
5585 	 * At this point the remote destination address and remote port fields
5586 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
5587 	 * have to see which state tcp was in so we can take appropriate action.
5588 	 */
5589 	if (tcp->tcp_state == TCPS_IDLE) {
5590 		/*
5591 		 * We support a quick connect capability here, allowing
5592 		 * clients to transition directly from IDLE to SYN_SENT
5593 		 * tcp_bindi will pick an unused port, insert the connection
5594 		 * in the bind hash and transition to BOUND state.
5595 		 */
5596 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
5597 		    tcp, B_TRUE);
5598 		lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
5599 		    B_FALSE, B_FALSE);
5600 		if (lport == 0)
5601 			return (-TNOADDR);
5602 	}
5603 
5604 	/*
5605 	 * Lookup the route to determine a source address and the uinfo.
5606 	 * Setup TCP parameters based on the metrics/DCE.
5607 	 */
5608 	error = tcp_set_destination(tcp);
5609 	if (error != 0)
5610 		return (error);
5611 
5612 	/*
5613 	 * Don't let an endpoint connect to itself.
5614 	 */
5615 	if (IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6, &connp->conn_laddr_v6) &&
5616 	    connp->conn_fport == connp->conn_lport)
5617 		return (-TBADADDR);
5618 
5619 	tcp->tcp_state = TCPS_SYN_SENT;
5620 
5621 	return (ipcl_conn_insert_v6(connp));
5622 }
5623 
5624 /*
5625  * Disconnect
5626  * Note that unlike other functions this returns a positive tli error
5627  * when it fails; it never returns an errno.
5628  */
5629 static int
5630 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
5631 {
5632 	conn_t		*lconnp;
5633 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5634 	conn_t		*connp = tcp->tcp_connp;
5635 
5636 	/*
5637 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
5638 	 * when the stream is in BOUND state. Do not send a reset,
5639 	 * since the destination IP address is not valid, and it can
5640 	 * be the initialized value of all zeros (broadcast address).
5641 	 */
5642 	if (tcp->tcp_state <= TCPS_BOUND) {
5643 		if (connp->conn_debug) {
5644 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
5645 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
5646 		}
5647 		return (TOUTSTATE);
5648 	}
5649 
5650 
5651 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
5652 
5653 		/*
5654 		 * According to TPI, for non-listeners, ignore seqnum
5655 		 * and disconnect.
5656 		 * Following interpretation of -1 seqnum is historical
5657 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
5658 		 * a valid seqnum should not be -1).
5659 		 *
5660 		 *	-1 means disconnect everything
5661 		 *	regardless even on a listener.
5662 		 */
5663 
5664 		int old_state = tcp->tcp_state;
5665 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
5666 
5667 		/*
5668 		 * The connection can't be on the tcp_time_wait_head list
5669 		 * since it is not detached.
5670 		 */
5671 		ASSERT(tcp->tcp_time_wait_next == NULL);
5672 		ASSERT(tcp->tcp_time_wait_prev == NULL);
5673 		ASSERT(tcp->tcp_time_wait_expire == 0);
5674 		/*
5675 		 * If it used to be a listener, check to make sure no one else
5676 		 * has taken the port before switching back to LISTEN state.
5677 		 */
5678 		if (connp->conn_ipversion == IPV4_VERSION) {
5679 			lconnp = ipcl_lookup_listener_v4(connp->conn_lport,
5680 			    connp->conn_laddr_v4, IPCL_ZONEID(connp), ipst);
5681 		} else {
5682 			uint_t ifindex = 0;
5683 
5684 			if (connp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)
5685 				ifindex = connp->conn_ixa->ixa_scopeid;
5686 
5687 			/* Allow conn_bound_if listeners? */
5688 			lconnp = ipcl_lookup_listener_v6(connp->conn_lport,
5689 			    &connp->conn_laddr_v6, ifindex, IPCL_ZONEID(connp),
5690 			    ipst);
5691 		}
5692 		if (tcp->tcp_conn_req_max && lconnp == NULL) {
5693 			tcp->tcp_state = TCPS_LISTEN;
5694 		} else if (old_state > TCPS_BOUND) {
5695 			tcp->tcp_conn_req_max = 0;
5696 			tcp->tcp_state = TCPS_BOUND;
5697 
5698 			/*
5699 			 * If this end point is not going to become a listener,
5700 			 * decrement the listener connection count if
5701 			 * necessary.  Note that we do not do this if it is
5702 			 * going to be a listner (the above if case) since
5703 			 * then it may remove the counter struct.
5704 			 */
5705 			if (tcp->tcp_listen_cnt != NULL)
5706 				TCP_DECR_LISTEN_CNT(tcp);
5707 		}
5708 		if (lconnp != NULL)
5709 			CONN_DEC_REF(lconnp);
5710 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
5711 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
5712 		} else if (old_state == TCPS_ESTABLISHED ||
5713 		    old_state == TCPS_CLOSE_WAIT) {
5714 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
5715 		}
5716 
5717 		if (tcp->tcp_fused)
5718 			tcp_unfuse(tcp);
5719 
5720 		mutex_enter(&tcp->tcp_eager_lock);
5721 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
5722 		    (tcp->tcp_conn_req_cnt_q != 0)) {
5723 			tcp_eager_cleanup(tcp, 0);
5724 		}
5725 		mutex_exit(&tcp->tcp_eager_lock);
5726 
5727 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
5728 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
5729 
5730 		tcp_reinit(tcp);
5731 
5732 		return (0);
5733 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
5734 		return (TBADSEQ);
5735 	}
5736 	return (0);
5737 }
5738 
5739 /*
5740  * Our client hereby directs us to reject the connection request
5741  * that tcp_input_listener() marked with 'seqnum'.  Rejection consists
5742  * of sending the appropriate RST, not an ICMP error.
5743  */
5744 static void
5745 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
5746 {
5747 	t_scalar_t seqnum;
5748 	int	error;
5749 	conn_t	*connp = tcp->tcp_connp;
5750 
5751 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5752 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
5753 		tcp_err_ack(tcp, mp, TPROTO, 0);
5754 		return;
5755 	}
5756 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
5757 	error = tcp_disconnect_common(tcp, seqnum);
5758 	if (error != 0)
5759 		tcp_err_ack(tcp, mp, error, 0);
5760 	else {
5761 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
5762 			/* Send M_FLUSH according to TPI */
5763 			(void) putnextctl1(connp->conn_rq, M_FLUSH, FLUSHRW);
5764 		}
5765 		mp = mi_tpi_ok_ack_alloc(mp);
5766 		if (mp != NULL)
5767 			putnext(connp->conn_rq, mp);
5768 	}
5769 }
5770 
5771 /*
5772  * Diagnostic routine used to return a string associated with the tcp state.
5773  * Note that if the caller does not supply a buffer, it will use an internal
5774  * static string.  This means that if multiple threads call this function at
5775  * the same time, output can be corrupted...  Note also that this function
5776  * does not check the size of the supplied buffer.  The caller has to make
5777  * sure that it is big enough.
5778  */
5779 static char *
5780 tcp_display(tcp_t *tcp, char *sup_buf, char format)
5781 {
5782 	char		buf1[30];
5783 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
5784 	char		*buf;
5785 	char		*cp;
5786 	in6_addr_t	local, remote;
5787 	char		local_addrbuf[INET6_ADDRSTRLEN];
5788 	char		remote_addrbuf[INET6_ADDRSTRLEN];
5789 	conn_t		*connp;
5790 
5791 	if (sup_buf != NULL)
5792 		buf = sup_buf;
5793 	else
5794 		buf = priv_buf;
5795 
5796 	if (tcp == NULL)
5797 		return ("NULL_TCP");
5798 
5799 	connp = tcp->tcp_connp;
5800 	switch (tcp->tcp_state) {
5801 	case TCPS_CLOSED:
5802 		cp = "TCP_CLOSED";
5803 		break;
5804 	case TCPS_IDLE:
5805 		cp = "TCP_IDLE";
5806 		break;
5807 	case TCPS_BOUND:
5808 		cp = "TCP_BOUND";
5809 		break;
5810 	case TCPS_LISTEN:
5811 		cp = "TCP_LISTEN";
5812 		break;
5813 	case TCPS_SYN_SENT:
5814 		cp = "TCP_SYN_SENT";
5815 		break;
5816 	case TCPS_SYN_RCVD:
5817 		cp = "TCP_SYN_RCVD";
5818 		break;
5819 	case TCPS_ESTABLISHED:
5820 		cp = "TCP_ESTABLISHED";
5821 		break;
5822 	case TCPS_CLOSE_WAIT:
5823 		cp = "TCP_CLOSE_WAIT";
5824 		break;
5825 	case TCPS_FIN_WAIT_1:
5826 		cp = "TCP_FIN_WAIT_1";
5827 		break;
5828 	case TCPS_CLOSING:
5829 		cp = "TCP_CLOSING";
5830 		break;
5831 	case TCPS_LAST_ACK:
5832 		cp = "TCP_LAST_ACK";
5833 		break;
5834 	case TCPS_FIN_WAIT_2:
5835 		cp = "TCP_FIN_WAIT_2";
5836 		break;
5837 	case TCPS_TIME_WAIT:
5838 		cp = "TCP_TIME_WAIT";
5839 		break;
5840 	default:
5841 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
5842 		cp = buf1;
5843 		break;
5844 	}
5845 	switch (format) {
5846 	case DISP_ADDR_AND_PORT:
5847 		if (connp->conn_ipversion == IPV4_VERSION) {
5848 			/*
5849 			 * Note that we use the remote address in the tcp_b
5850 			 * structure.  This means that it will print out
5851 			 * the real destination address, not the next hop's
5852 			 * address if source routing is used.
5853 			 */
5854 			IN6_IPADDR_TO_V4MAPPED(connp->conn_laddr_v4, &local);
5855 			IN6_IPADDR_TO_V4MAPPED(connp->conn_faddr_v4, &remote);
5856 
5857 		} else {
5858 			local = connp->conn_laddr_v6;
5859 			remote = connp->conn_faddr_v6;
5860 		}
5861 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
5862 		    sizeof (local_addrbuf));
5863 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
5864 		    sizeof (remote_addrbuf));
5865 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
5866 		    local_addrbuf, ntohs(connp->conn_lport), remote_addrbuf,
5867 		    ntohs(connp->conn_fport), cp);
5868 		break;
5869 	case DISP_PORT_ONLY:
5870 	default:
5871 		(void) mi_sprintf(buf, "[%u, %u] %s",
5872 		    ntohs(connp->conn_lport), ntohs(connp->conn_fport), cp);
5873 		break;
5874 	}
5875 
5876 	return (buf);
5877 }
5878 
5879 /*
5880  * Called via squeue to get on to eager's perimeter. It sends a
5881  * TH_RST if eager is in the fanout table. The listener wants the
5882  * eager to disappear either by means of tcp_eager_blowoff() or
5883  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
5884  * called (via squeue) if the eager cannot be inserted in the
5885  * fanout table in tcp_input_listener().
5886  */
5887 /* ARGSUSED */
5888 void
5889 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
5890 {
5891 	conn_t	*econnp = (conn_t *)arg;
5892 	tcp_t	*eager = econnp->conn_tcp;
5893 	tcp_t	*listener = eager->tcp_listener;
5894 
5895 	/*
5896 	 * We could be called because listener is closing. Since
5897 	 * the eager was using listener's queue's, we avoid
5898 	 * using the listeners queues from now on.
5899 	 */
5900 	ASSERT(eager->tcp_detached);
5901 	econnp->conn_rq = NULL;
5902 	econnp->conn_wq = NULL;
5903 
5904 	/*
5905 	 * An eager's conn_fanout will be NULL if it's a duplicate
5906 	 * for an existing 4-tuples in the conn fanout table.
5907 	 * We don't want to send an RST out in such case.
5908 	 */
5909 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
5910 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
5911 		    eager, eager->tcp_snxt, 0, TH_RST);
5912 	}
5913 
5914 	/* We are here because listener wants this eager gone */
5915 	if (listener != NULL) {
5916 		mutex_enter(&listener->tcp_eager_lock);
5917 		tcp_eager_unlink(eager);
5918 		if (eager->tcp_tconnind_started) {
5919 			/*
5920 			 * The eager has sent a conn_ind up to the
5921 			 * listener but listener decides to close
5922 			 * instead. We need to drop the extra ref
5923 			 * placed on eager in tcp_input_data() before
5924 			 * sending the conn_ind to listener.
5925 			 */
5926 			CONN_DEC_REF(econnp);
5927 		}
5928 		mutex_exit(&listener->tcp_eager_lock);
5929 		CONN_DEC_REF(listener->tcp_connp);
5930 	}
5931 
5932 	if (eager->tcp_state != TCPS_CLOSED)
5933 		tcp_close_detached(eager);
5934 }
5935 
5936 /*
5937  * Reset any eager connection hanging off this listener marked
5938  * with 'seqnum' and then reclaim it's resources.
5939  */
5940 static boolean_t
5941 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
5942 {
5943 	tcp_t	*eager;
5944 	mblk_t 	*mp;
5945 	tcp_stack_t	*tcps = listener->tcp_tcps;
5946 
5947 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
5948 	eager = listener;
5949 	mutex_enter(&listener->tcp_eager_lock);
5950 	do {
5951 		eager = eager->tcp_eager_next_q;
5952 		if (eager == NULL) {
5953 			mutex_exit(&listener->tcp_eager_lock);
5954 			return (B_FALSE);
5955 		}
5956 	} while (eager->tcp_conn_req_seqnum != seqnum);
5957 
5958 	if (eager->tcp_closemp_used) {
5959 		mutex_exit(&listener->tcp_eager_lock);
5960 		return (B_TRUE);
5961 	}
5962 	eager->tcp_closemp_used = B_TRUE;
5963 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5964 	CONN_INC_REF(eager->tcp_connp);
5965 	mutex_exit(&listener->tcp_eager_lock);
5966 	mp = &eager->tcp_closemp;
5967 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
5968 	    eager->tcp_connp, NULL, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
5969 	return (B_TRUE);
5970 }
5971 
5972 /*
5973  * Reset any eager connection hanging off this listener
5974  * and then reclaim it's resources.
5975  */
5976 static void
5977 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
5978 {
5979 	tcp_t	*eager;
5980 	mblk_t	*mp;
5981 	tcp_stack_t	*tcps = listener->tcp_tcps;
5982 
5983 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
5984 
5985 	if (!q0_only) {
5986 		/* First cleanup q */
5987 		TCP_STAT(tcps, tcp_eager_blowoff_q);
5988 		eager = listener->tcp_eager_next_q;
5989 		while (eager != NULL) {
5990 			if (!eager->tcp_closemp_used) {
5991 				eager->tcp_closemp_used = B_TRUE;
5992 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5993 				CONN_INC_REF(eager->tcp_connp);
5994 				mp = &eager->tcp_closemp;
5995 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
5996 				    tcp_eager_kill, eager->tcp_connp, NULL,
5997 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
5998 			}
5999 			eager = eager->tcp_eager_next_q;
6000 		}
6001 	}
6002 	/* Then cleanup q0 */
6003 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6004 	eager = listener->tcp_eager_next_q0;
6005 	while (eager != listener) {
6006 		if (!eager->tcp_closemp_used) {
6007 			eager->tcp_closemp_used = B_TRUE;
6008 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6009 			CONN_INC_REF(eager->tcp_connp);
6010 			mp = &eager->tcp_closemp;
6011 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6012 			    tcp_eager_kill, eager->tcp_connp, NULL, SQ_FILL,
6013 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6014 		}
6015 		eager = eager->tcp_eager_next_q0;
6016 	}
6017 }
6018 
6019 /*
6020  * If we are an eager connection hanging off a listener that hasn't
6021  * formally accepted the connection yet, get off his list and blow off
6022  * any data that we have accumulated.
6023  */
6024 static void
6025 tcp_eager_unlink(tcp_t *tcp)
6026 {
6027 	tcp_t	*listener = tcp->tcp_listener;
6028 
6029 	ASSERT(listener != NULL);
6030 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6031 	if (tcp->tcp_eager_next_q0 != NULL) {
6032 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6033 
6034 		/* Remove the eager tcp from q0 */
6035 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6036 		    tcp->tcp_eager_prev_q0;
6037 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6038 		    tcp->tcp_eager_next_q0;
6039 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6040 		listener->tcp_conn_req_cnt_q0--;
6041 
6042 		tcp->tcp_eager_next_q0 = NULL;
6043 		tcp->tcp_eager_prev_q0 = NULL;
6044 
6045 		/*
6046 		 * Take the eager out, if it is in the list of droppable
6047 		 * eagers.
6048 		 */
6049 		MAKE_UNDROPPABLE(tcp);
6050 
6051 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6052 			/* we have timed out before */
6053 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6054 			listener->tcp_syn_rcvd_timeout--;
6055 		}
6056 	} else {
6057 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6058 		tcp_t	*prev = NULL;
6059 
6060 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6061 			if (tcpp[0] == tcp) {
6062 				if (listener->tcp_eager_last_q == tcp) {
6063 					/*
6064 					 * If we are unlinking the last
6065 					 * element on the list, adjust
6066 					 * tail pointer. Set tail pointer
6067 					 * to nil when list is empty.
6068 					 */
6069 					ASSERT(tcp->tcp_eager_next_q == NULL);
6070 					if (listener->tcp_eager_last_q ==
6071 					    listener->tcp_eager_next_q) {
6072 						listener->tcp_eager_last_q =
6073 						    NULL;
6074 					} else {
6075 						/*
6076 						 * We won't get here if there
6077 						 * is only one eager in the
6078 						 * list.
6079 						 */
6080 						ASSERT(prev != NULL);
6081 						listener->tcp_eager_last_q =
6082 						    prev;
6083 					}
6084 				}
6085 				tcpp[0] = tcp->tcp_eager_next_q;
6086 				tcp->tcp_eager_next_q = NULL;
6087 				tcp->tcp_eager_last_q = NULL;
6088 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6089 				listener->tcp_conn_req_cnt_q--;
6090 				break;
6091 			}
6092 			prev = tcpp[0];
6093 		}
6094 	}
6095 	tcp->tcp_listener = NULL;
6096 }
6097 
6098 /* Shorthand to generate and send TPI error acks to our client */
6099 static void
6100 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6101 {
6102 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6103 		putnext(tcp->tcp_connp->conn_rq, mp);
6104 }
6105 
6106 /* Shorthand to generate and send TPI error acks to our client */
6107 static void
6108 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6109     int t_error, int sys_error)
6110 {
6111 	struct T_error_ack	*teackp;
6112 
6113 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
6114 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
6115 		teackp = (struct T_error_ack *)mp->b_rptr;
6116 		teackp->ERROR_prim = primitive;
6117 		teackp->TLI_error = t_error;
6118 		teackp->UNIX_error = sys_error;
6119 		putnext(tcp->tcp_connp->conn_rq, mp);
6120 	}
6121 }
6122 
6123 /*
6124  * Note: No locks are held when inspecting tcp_g_*epriv_ports
6125  * but instead the code relies on:
6126  * - the fact that the address of the array and its size never changes
6127  * - the atomic assignment of the elements of the array
6128  */
6129 /* ARGSUSED */
6130 static int
6131 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
6132 {
6133 	int i;
6134 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6135 
6136 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6137 		if (tcps->tcps_g_epriv_ports[i] != 0)
6138 			(void) mi_mpprintf(mp, "%d ",
6139 			    tcps->tcps_g_epriv_ports[i]);
6140 	}
6141 	return (0);
6142 }
6143 
6144 /*
6145  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6146  * threads from changing it at the same time.
6147  */
6148 /* ARGSUSED */
6149 static int
6150 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6151     cred_t *cr)
6152 {
6153 	long	new_value;
6154 	int	i;
6155 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6156 
6157 	/*
6158 	 * Fail the request if the new value does not lie within the
6159 	 * port number limits.
6160 	 */
6161 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6162 	    new_value <= 0 || new_value >= 65536) {
6163 		return (EINVAL);
6164 	}
6165 
6166 	mutex_enter(&tcps->tcps_epriv_port_lock);
6167 	/* Check if the value is already in the list */
6168 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6169 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
6170 			mutex_exit(&tcps->tcps_epriv_port_lock);
6171 			return (EEXIST);
6172 		}
6173 	}
6174 	/* Find an empty slot */
6175 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6176 		if (tcps->tcps_g_epriv_ports[i] == 0)
6177 			break;
6178 	}
6179 	if (i == tcps->tcps_g_num_epriv_ports) {
6180 		mutex_exit(&tcps->tcps_epriv_port_lock);
6181 		return (EOVERFLOW);
6182 	}
6183 	/* Set the new value */
6184 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
6185 	mutex_exit(&tcps->tcps_epriv_port_lock);
6186 	return (0);
6187 }
6188 
6189 /*
6190  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6191  * threads from changing it at the same time.
6192  */
6193 /* ARGSUSED */
6194 static int
6195 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6196     cred_t *cr)
6197 {
6198 	long	new_value;
6199 	int	i;
6200 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6201 
6202 	/*
6203 	 * Fail the request if the new value does not lie within the
6204 	 * port number limits.
6205 	 */
6206 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
6207 	    new_value >= 65536) {
6208 		return (EINVAL);
6209 	}
6210 
6211 	mutex_enter(&tcps->tcps_epriv_port_lock);
6212 	/* Check that the value is already in the list */
6213 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6214 		if (tcps->tcps_g_epriv_ports[i] == new_value)
6215 			break;
6216 	}
6217 	if (i == tcps->tcps_g_num_epriv_ports) {
6218 		mutex_exit(&tcps->tcps_epriv_port_lock);
6219 		return (ESRCH);
6220 	}
6221 	/* Clear the value */
6222 	tcps->tcps_g_epriv_ports[i] = 0;
6223 	mutex_exit(&tcps->tcps_epriv_port_lock);
6224 	return (0);
6225 }
6226 
6227 /* Return the TPI/TLI equivalent of our current tcp_state */
6228 static int
6229 tcp_tpistate(tcp_t *tcp)
6230 {
6231 	switch (tcp->tcp_state) {
6232 	case TCPS_IDLE:
6233 		return (TS_UNBND);
6234 	case TCPS_LISTEN:
6235 		/*
6236 		 * Return whether there are outstanding T_CONN_IND waiting
6237 		 * for the matching T_CONN_RES. Therefore don't count q0.
6238 		 */
6239 		if (tcp->tcp_conn_req_cnt_q > 0)
6240 			return (TS_WRES_CIND);
6241 		else
6242 			return (TS_IDLE);
6243 	case TCPS_BOUND:
6244 		return (TS_IDLE);
6245 	case TCPS_SYN_SENT:
6246 		return (TS_WCON_CREQ);
6247 	case TCPS_SYN_RCVD:
6248 		/*
6249 		 * Note: assumption: this has to the active open SYN_RCVD.
6250 		 * The passive instance is detached in SYN_RCVD stage of
6251 		 * incoming connection processing so we cannot get request
6252 		 * for T_info_ack on it.
6253 		 */
6254 		return (TS_WACK_CRES);
6255 	case TCPS_ESTABLISHED:
6256 		return (TS_DATA_XFER);
6257 	case TCPS_CLOSE_WAIT:
6258 		return (TS_WREQ_ORDREL);
6259 	case TCPS_FIN_WAIT_1:
6260 		return (TS_WIND_ORDREL);
6261 	case TCPS_FIN_WAIT_2:
6262 		return (TS_WIND_ORDREL);
6263 
6264 	case TCPS_CLOSING:
6265 	case TCPS_LAST_ACK:
6266 	case TCPS_TIME_WAIT:
6267 	case TCPS_CLOSED:
6268 		/*
6269 		 * Following TS_WACK_DREQ7 is a rendition of "not
6270 		 * yet TS_IDLE" TPI state. There is no best match to any
6271 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
6272 		 * choose a value chosen that will map to TLI/XTI level
6273 		 * state of TSTATECHNG (state is process of changing) which
6274 		 * captures what this dummy state represents.
6275 		 */
6276 		return (TS_WACK_DREQ7);
6277 	default:
6278 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
6279 		    tcp->tcp_state, tcp_display(tcp, NULL,
6280 		    DISP_PORT_ONLY));
6281 		return (TS_UNBND);
6282 	}
6283 }
6284 
6285 static void
6286 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
6287 {
6288 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6289 	conn_t		*connp = tcp->tcp_connp;
6290 
6291 	if (connp->conn_family == AF_INET6)
6292 		*tia = tcp_g_t_info_ack_v6;
6293 	else
6294 		*tia = tcp_g_t_info_ack;
6295 	tia->CURRENT_state = tcp_tpistate(tcp);
6296 	tia->OPT_size = tcp_max_optsize;
6297 	if (tcp->tcp_mss == 0) {
6298 		/* Not yet set - tcp_open does not set mss */
6299 		if (connp->conn_ipversion == IPV4_VERSION)
6300 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
6301 		else
6302 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
6303 	} else {
6304 		tia->TIDU_size = tcp->tcp_mss;
6305 	}
6306 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
6307 }
6308 
6309 static void
6310 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
6311     t_uscalar_t cap_bits1)
6312 {
6313 	tcap->CAP_bits1 = 0;
6314 
6315 	if (cap_bits1 & TC1_INFO) {
6316 		tcp_copy_info(&tcap->INFO_ack, tcp);
6317 		tcap->CAP_bits1 |= TC1_INFO;
6318 	}
6319 
6320 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
6321 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
6322 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
6323 	}
6324 
6325 }
6326 
6327 /*
6328  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
6329  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
6330  * tcp_g_t_info_ack.  The current state of the stream is copied from
6331  * tcp_state.
6332  */
6333 static void
6334 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
6335 {
6336 	t_uscalar_t		cap_bits1;
6337 	struct T_capability_ack	*tcap;
6338 
6339 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
6340 		freemsg(mp);
6341 		return;
6342 	}
6343 
6344 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
6345 
6346 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
6347 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
6348 	if (mp == NULL)
6349 		return;
6350 
6351 	tcap = (struct T_capability_ack *)mp->b_rptr;
6352 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
6353 
6354 	putnext(tcp->tcp_connp->conn_rq, mp);
6355 }
6356 
6357 /*
6358  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
6359  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
6360  * The current state of the stream is copied from tcp_state.
6361  */
6362 static void
6363 tcp_info_req(tcp_t *tcp, mblk_t *mp)
6364 {
6365 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
6366 	    T_INFO_ACK);
6367 	if (!mp) {
6368 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6369 		return;
6370 	}
6371 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
6372 	putnext(tcp->tcp_connp->conn_rq, mp);
6373 }
6374 
6375 /* Respond to the TPI addr request */
6376 static void
6377 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
6378 {
6379 	struct sockaddr *sa;
6380 	mblk_t	*ackmp;
6381 	struct T_addr_ack *taa;
6382 	conn_t	*connp = tcp->tcp_connp;
6383 	uint_t	addrlen;
6384 
6385 	/* Make it large enough for worst case */
6386 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
6387 	    2 * sizeof (sin6_t), 1);
6388 	if (ackmp == NULL) {
6389 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6390 		return;
6391 	}
6392 
6393 	taa = (struct T_addr_ack *)ackmp->b_rptr;
6394 
6395 	bzero(taa, sizeof (struct T_addr_ack));
6396 	ackmp->b_wptr = (uchar_t *)&taa[1];
6397 
6398 	taa->PRIM_type = T_ADDR_ACK;
6399 	ackmp->b_datap->db_type = M_PCPROTO;
6400 
6401 	if (connp->conn_family == AF_INET)
6402 		addrlen = sizeof (sin_t);
6403 	else
6404 		addrlen = sizeof (sin6_t);
6405 
6406 	/*
6407 	 * Note: Following code assumes 32 bit alignment of basic
6408 	 * data structures like sin_t and struct T_addr_ack.
6409 	 */
6410 	if (tcp->tcp_state >= TCPS_BOUND) {
6411 		/*
6412 		 * Fill in local address first
6413 		 */
6414 		taa->LOCADDR_offset = sizeof (*taa);
6415 		taa->LOCADDR_length = addrlen;
6416 		sa = (struct sockaddr *)&taa[1];
6417 		(void) conn_getsockname(connp, sa, &addrlen);
6418 		ackmp->b_wptr += addrlen;
6419 	}
6420 	if (tcp->tcp_state >= TCPS_SYN_RCVD) {
6421 		/*
6422 		 * Fill in Remote address
6423 		 */
6424 		taa->REMADDR_length = addrlen;
6425 		/* assumed 32-bit alignment */
6426 		taa->REMADDR_offset = taa->LOCADDR_offset + taa->LOCADDR_length;
6427 		sa = (struct sockaddr *)(ackmp->b_rptr + taa->REMADDR_offset);
6428 		(void) conn_getpeername(connp, sa, &addrlen);
6429 		ackmp->b_wptr += addrlen;
6430 	}
6431 	ASSERT(ackmp->b_wptr <= ackmp->b_datap->db_lim);
6432 	putnext(tcp->tcp_connp->conn_rq, ackmp);
6433 }
6434 
6435 /*
6436  * Handle reinitialization of a tcp structure.
6437  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
6438  */
6439 static void
6440 tcp_reinit(tcp_t *tcp)
6441 {
6442 	mblk_t		*mp;
6443 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6444 	conn_t		*connp  = tcp->tcp_connp;
6445 
6446 	TCP_STAT(tcps, tcp_reinit_calls);
6447 
6448 	/* tcp_reinit should never be called for detached tcp_t's */
6449 	ASSERT(tcp->tcp_listener == NULL);
6450 	ASSERT((connp->conn_family == AF_INET &&
6451 	    connp->conn_ipversion == IPV4_VERSION) ||
6452 	    (connp->conn_family == AF_INET6 &&
6453 	    (connp->conn_ipversion == IPV4_VERSION ||
6454 	    connp->conn_ipversion == IPV6_VERSION)));
6455 
6456 	/* Cancel outstanding timers */
6457 	tcp_timers_stop(tcp);
6458 
6459 	/*
6460 	 * Reset everything in the state vector, after updating global
6461 	 * MIB data from instance counters.
6462 	 */
6463 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
6464 	tcp->tcp_ibsegs = 0;
6465 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
6466 	tcp->tcp_obsegs = 0;
6467 
6468 	tcp_close_mpp(&tcp->tcp_xmit_head);
6469 	if (tcp->tcp_snd_zcopy_aware)
6470 		tcp_zcopy_notify(tcp);
6471 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
6472 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
6473 	mutex_enter(&tcp->tcp_non_sq_lock);
6474 	if (tcp->tcp_flow_stopped &&
6475 	    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
6476 		tcp_clrqfull(tcp);
6477 	}
6478 	mutex_exit(&tcp->tcp_non_sq_lock);
6479 	tcp_close_mpp(&tcp->tcp_reass_head);
6480 	tcp->tcp_reass_tail = NULL;
6481 	if (tcp->tcp_rcv_list != NULL) {
6482 		/* Free b_next chain */
6483 		tcp_close_mpp(&tcp->tcp_rcv_list);
6484 		tcp->tcp_rcv_last_head = NULL;
6485 		tcp->tcp_rcv_last_tail = NULL;
6486 		tcp->tcp_rcv_cnt = 0;
6487 	}
6488 	tcp->tcp_rcv_last_tail = NULL;
6489 
6490 	if ((mp = tcp->tcp_urp_mp) != NULL) {
6491 		freemsg(mp);
6492 		tcp->tcp_urp_mp = NULL;
6493 	}
6494 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
6495 		freemsg(mp);
6496 		tcp->tcp_urp_mark_mp = NULL;
6497 	}
6498 	if (tcp->tcp_fused_sigurg_mp != NULL) {
6499 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
6500 		freeb(tcp->tcp_fused_sigurg_mp);
6501 		tcp->tcp_fused_sigurg_mp = NULL;
6502 	}
6503 	if (tcp->tcp_ordrel_mp != NULL) {
6504 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
6505 		freeb(tcp->tcp_ordrel_mp);
6506 		tcp->tcp_ordrel_mp = NULL;
6507 	}
6508 
6509 	/*
6510 	 * Following is a union with two members which are
6511 	 * identical types and size so the following cleanup
6512 	 * is enough.
6513 	 */
6514 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
6515 
6516 	CL_INET_DISCONNECT(connp);
6517 
6518 	/*
6519 	 * The connection can't be on the tcp_time_wait_head list
6520 	 * since it is not detached.
6521 	 */
6522 	ASSERT(tcp->tcp_time_wait_next == NULL);
6523 	ASSERT(tcp->tcp_time_wait_prev == NULL);
6524 	ASSERT(tcp->tcp_time_wait_expire == 0);
6525 
6526 	if (tcp->tcp_kssl_pending) {
6527 		tcp->tcp_kssl_pending = B_FALSE;
6528 
6529 		/* Don't reset if the initialized by bind. */
6530 		if (tcp->tcp_kssl_ent != NULL) {
6531 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
6532 			    KSSL_NO_PROXY);
6533 		}
6534 	}
6535 	if (tcp->tcp_kssl_ctx != NULL) {
6536 		kssl_release_ctx(tcp->tcp_kssl_ctx);
6537 		tcp->tcp_kssl_ctx = NULL;
6538 	}
6539 
6540 	/*
6541 	 * Reset/preserve other values
6542 	 */
6543 	tcp_reinit_values(tcp);
6544 	ipcl_hash_remove(connp);
6545 	ixa_cleanup(connp->conn_ixa);
6546 	tcp_ipsec_cleanup(tcp);
6547 
6548 	connp->conn_laddr_v6 = connp->conn_bound_addr_v6;
6549 	connp->conn_saddr_v6 = connp->conn_bound_addr_v6;
6550 
6551 	if (tcp->tcp_conn_req_max != 0) {
6552 		/*
6553 		 * This is the case when a TLI program uses the same
6554 		 * transport end point to accept a connection.  This
6555 		 * makes the TCP both a listener and acceptor.  When
6556 		 * this connection is closed, we need to set the state
6557 		 * back to TCPS_LISTEN.  Make sure that the eager list
6558 		 * is reinitialized.
6559 		 *
6560 		 * Note that this stream is still bound to the four
6561 		 * tuples of the previous connection in IP.  If a new
6562 		 * SYN with different foreign address comes in, IP will
6563 		 * not find it and will send it to the global queue.  In
6564 		 * the global queue, TCP will do a tcp_lookup_listener()
6565 		 * to find this stream.  This works because this stream
6566 		 * is only removed from connected hash.
6567 		 *
6568 		 */
6569 		tcp->tcp_state = TCPS_LISTEN;
6570 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
6571 		tcp->tcp_eager_next_drop_q0 = tcp;
6572 		tcp->tcp_eager_prev_drop_q0 = tcp;
6573 		/*
6574 		 * Initially set conn_recv to tcp_input_listener_unbound to try
6575 		 * to pick a good squeue for the listener when the first SYN
6576 		 * arrives. tcp_input_listener_unbound sets it to
6577 		 * tcp_input_listener on that first SYN.
6578 		 */
6579 		connp->conn_recv = tcp_input_listener_unbound;
6580 
6581 		connp->conn_proto = IPPROTO_TCP;
6582 		connp->conn_faddr_v6 = ipv6_all_zeros;
6583 		connp->conn_fport = 0;
6584 
6585 		(void) ipcl_bind_insert(connp);
6586 	} else {
6587 		tcp->tcp_state = TCPS_BOUND;
6588 	}
6589 
6590 	/*
6591 	 * Initialize to default values
6592 	 */
6593 	tcp_init_values(tcp);
6594 
6595 	ASSERT(tcp->tcp_ptpbhn != NULL);
6596 	tcp->tcp_rwnd = connp->conn_rcvbuf;
6597 	tcp->tcp_mss = connp->conn_ipversion != IPV4_VERSION ?
6598 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
6599 }
6600 
6601 /*
6602  * Force values to zero that need be zero.
6603  * Do not touch values asociated with the BOUND or LISTEN state
6604  * since the connection will end up in that state after the reinit.
6605  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
6606  * structure!
6607  */
6608 static void
6609 tcp_reinit_values(tcp)
6610 	tcp_t *tcp;
6611 {
6612 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6613 	conn_t		*connp = tcp->tcp_connp;
6614 
6615 #ifndef	lint
6616 #define	DONTCARE(x)
6617 #define	PRESERVE(x)
6618 #else
6619 #define	DONTCARE(x)	((x) = (x))
6620 #define	PRESERVE(x)	((x) = (x))
6621 #endif	/* lint */
6622 
6623 	PRESERVE(tcp->tcp_bind_hash_port);
6624 	PRESERVE(tcp->tcp_bind_hash);
6625 	PRESERVE(tcp->tcp_ptpbhn);
6626 	PRESERVE(tcp->tcp_acceptor_hash);
6627 	PRESERVE(tcp->tcp_ptpahn);
6628 
6629 	/* Should be ASSERT NULL on these with new code! */
6630 	ASSERT(tcp->tcp_time_wait_next == NULL);
6631 	ASSERT(tcp->tcp_time_wait_prev == NULL);
6632 	ASSERT(tcp->tcp_time_wait_expire == 0);
6633 	PRESERVE(tcp->tcp_state);
6634 	PRESERVE(connp->conn_rq);
6635 	PRESERVE(connp->conn_wq);
6636 
6637 	ASSERT(tcp->tcp_xmit_head == NULL);
6638 	ASSERT(tcp->tcp_xmit_last == NULL);
6639 	ASSERT(tcp->tcp_unsent == 0);
6640 	ASSERT(tcp->tcp_xmit_tail == NULL);
6641 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
6642 
6643 	tcp->tcp_snxt = 0;			/* Displayed in mib */
6644 	tcp->tcp_suna = 0;			/* Displayed in mib */
6645 	tcp->tcp_swnd = 0;
6646 	DONTCARE(tcp->tcp_cwnd);	/* Init in tcp_process_options */
6647 
6648 	ASSERT(tcp->tcp_ibsegs == 0);
6649 	ASSERT(tcp->tcp_obsegs == 0);
6650 
6651 	if (connp->conn_ht_iphc != NULL) {
6652 		kmem_free(connp->conn_ht_iphc, connp->conn_ht_iphc_allocated);
6653 		connp->conn_ht_iphc = NULL;
6654 		connp->conn_ht_iphc_allocated = 0;
6655 		connp->conn_ht_iphc_len = 0;
6656 		connp->conn_ht_ulp = NULL;
6657 		connp->conn_ht_ulp_len = 0;
6658 		tcp->tcp_ipha = NULL;
6659 		tcp->tcp_ip6h = NULL;
6660 		tcp->tcp_tcpha = NULL;
6661 	}
6662 
6663 	/* We clear any IP_OPTIONS and extension headers */
6664 	ip_pkt_free(&connp->conn_xmit_ipp);
6665 
6666 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
6667 	DONTCARE(tcp->tcp_ipha);
6668 	DONTCARE(tcp->tcp_ip6h);
6669 	DONTCARE(tcp->tcp_tcpha);
6670 	tcp->tcp_valid_bits = 0;
6671 
6672 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
6673 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
6674 	tcp->tcp_last_rcv_lbolt = 0;
6675 
6676 	tcp->tcp_init_cwnd = 0;
6677 
6678 	tcp->tcp_urp_last_valid = 0;
6679 	tcp->tcp_hard_binding = 0;
6680 
6681 	tcp->tcp_fin_acked = 0;
6682 	tcp->tcp_fin_rcvd = 0;
6683 	tcp->tcp_fin_sent = 0;
6684 	tcp->tcp_ordrel_done = 0;
6685 
6686 	tcp->tcp_detached = 0;
6687 
6688 	tcp->tcp_snd_ws_ok = B_FALSE;
6689 	tcp->tcp_snd_ts_ok = B_FALSE;
6690 	tcp->tcp_zero_win_probe = 0;
6691 
6692 	tcp->tcp_loopback = 0;
6693 	tcp->tcp_localnet = 0;
6694 	tcp->tcp_syn_defense = 0;
6695 	tcp->tcp_set_timer = 0;
6696 
6697 	tcp->tcp_active_open = 0;
6698 	tcp->tcp_rexmit = B_FALSE;
6699 	tcp->tcp_xmit_zc_clean = B_FALSE;
6700 
6701 	tcp->tcp_snd_sack_ok = B_FALSE;
6702 	tcp->tcp_hwcksum = B_FALSE;
6703 
6704 	DONTCARE(tcp->tcp_maxpsz_multiplier);	/* Init in tcp_init_values */
6705 
6706 	tcp->tcp_conn_def_q0 = 0;
6707 	tcp->tcp_ip_forward_progress = B_FALSE;
6708 	tcp->tcp_ecn_ok = B_FALSE;
6709 
6710 	tcp->tcp_cwr = B_FALSE;
6711 	tcp->tcp_ecn_echo_on = B_FALSE;
6712 	tcp->tcp_is_wnd_shrnk = B_FALSE;
6713 
6714 	if (tcp->tcp_sack_info != NULL) {
6715 		if (tcp->tcp_notsack_list != NULL) {
6716 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
6717 			    tcp);
6718 		}
6719 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
6720 		tcp->tcp_sack_info = NULL;
6721 	}
6722 
6723 	tcp->tcp_rcv_ws = 0;
6724 	tcp->tcp_snd_ws = 0;
6725 	tcp->tcp_ts_recent = 0;
6726 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
6727 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
6728 	tcp->tcp_initial_pmtu = 0;
6729 
6730 	ASSERT(tcp->tcp_reass_head == NULL);
6731 	ASSERT(tcp->tcp_reass_tail == NULL);
6732 
6733 	tcp->tcp_cwnd_cnt = 0;
6734 
6735 	ASSERT(tcp->tcp_rcv_list == NULL);
6736 	ASSERT(tcp->tcp_rcv_last_head == NULL);
6737 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
6738 	ASSERT(tcp->tcp_rcv_cnt == 0);
6739 
6740 	DONTCARE(tcp->tcp_cwnd_ssthresh); /* Init in tcp_set_destination */
6741 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
6742 	tcp->tcp_csuna = 0;
6743 
6744 	tcp->tcp_rto = 0;			/* Displayed in MIB */
6745 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
6746 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
6747 	tcp->tcp_rtt_update = 0;
6748 
6749 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
6750 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
6751 
6752 	tcp->tcp_rack = 0;			/* Displayed in mib */
6753 	tcp->tcp_rack_cnt = 0;
6754 	tcp->tcp_rack_cur_max = 0;
6755 	tcp->tcp_rack_abs_max = 0;
6756 
6757 	tcp->tcp_max_swnd = 0;
6758 
6759 	ASSERT(tcp->tcp_listener == NULL);
6760 
6761 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
6762 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
6763 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
6764 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
6765 
6766 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
6767 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
6768 	PRESERVE(tcp->tcp_conn_req_max);
6769 	PRESERVE(tcp->tcp_conn_req_seqnum);
6770 
6771 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
6772 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
6773 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
6774 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
6775 
6776 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
6777 	ASSERT(tcp->tcp_urp_mp == NULL);
6778 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
6779 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
6780 
6781 	ASSERT(tcp->tcp_eager_next_q == NULL);
6782 	ASSERT(tcp->tcp_eager_last_q == NULL);
6783 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
6784 	    tcp->tcp_eager_prev_q0 == NULL) ||
6785 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
6786 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
6787 
6788 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
6789 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
6790 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
6791 
6792 	tcp->tcp_client_errno = 0;
6793 
6794 	DONTCARE(connp->conn_sum);		/* Init in tcp_init_values */
6795 
6796 	connp->conn_faddr_v6 = ipv6_all_zeros;	/* Displayed in MIB */
6797 
6798 	PRESERVE(connp->conn_bound_addr_v6);
6799 	tcp->tcp_last_sent_len = 0;
6800 	tcp->tcp_dupack_cnt = 0;
6801 
6802 	connp->conn_fport = 0;			/* Displayed in MIB */
6803 	PRESERVE(connp->conn_lport);
6804 
6805 	PRESERVE(tcp->tcp_acceptor_lockp);
6806 
6807 	ASSERT(tcp->tcp_ordrel_mp == NULL);
6808 	PRESERVE(tcp->tcp_acceptor_id);
6809 	DONTCARE(tcp->tcp_ipsec_overhead);
6810 
6811 	PRESERVE(connp->conn_family);
6812 	/* Remove any remnants of mapped address binding */
6813 	if (connp->conn_family == AF_INET6) {
6814 		connp->conn_ipversion = IPV6_VERSION;
6815 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
6816 	} else {
6817 		connp->conn_ipversion = IPV4_VERSION;
6818 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
6819 	}
6820 
6821 	connp->conn_bound_if = 0;
6822 	connp->conn_recv_ancillary.crb_all = 0;
6823 	tcp->tcp_recvifindex = 0;
6824 	tcp->tcp_recvhops = 0;
6825 	tcp->tcp_closed = 0;
6826 	tcp->tcp_cleandeathtag = 0;
6827 	if (tcp->tcp_hopopts != NULL) {
6828 		mi_free(tcp->tcp_hopopts);
6829 		tcp->tcp_hopopts = NULL;
6830 		tcp->tcp_hopoptslen = 0;
6831 	}
6832 	ASSERT(tcp->tcp_hopoptslen == 0);
6833 	if (tcp->tcp_dstopts != NULL) {
6834 		mi_free(tcp->tcp_dstopts);
6835 		tcp->tcp_dstopts = NULL;
6836 		tcp->tcp_dstoptslen = 0;
6837 	}
6838 	ASSERT(tcp->tcp_dstoptslen == 0);
6839 	if (tcp->tcp_rthdrdstopts != NULL) {
6840 		mi_free(tcp->tcp_rthdrdstopts);
6841 		tcp->tcp_rthdrdstopts = NULL;
6842 		tcp->tcp_rthdrdstoptslen = 0;
6843 	}
6844 	ASSERT(tcp->tcp_rthdrdstoptslen == 0);
6845 	if (tcp->tcp_rthdr != NULL) {
6846 		mi_free(tcp->tcp_rthdr);
6847 		tcp->tcp_rthdr = NULL;
6848 		tcp->tcp_rthdrlen = 0;
6849 	}
6850 	ASSERT(tcp->tcp_rthdrlen == 0);
6851 
6852 	/* Reset fusion-related fields */
6853 	tcp->tcp_fused = B_FALSE;
6854 	tcp->tcp_unfusable = B_FALSE;
6855 	tcp->tcp_fused_sigurg = B_FALSE;
6856 	tcp->tcp_loopback_peer = NULL;
6857 
6858 	tcp->tcp_lso = B_FALSE;
6859 
6860 	tcp->tcp_in_ack_unsent = 0;
6861 	tcp->tcp_cork = B_FALSE;
6862 	tcp->tcp_tconnind_started = B_FALSE;
6863 
6864 	PRESERVE(tcp->tcp_squeue_bytes);
6865 
6866 	ASSERT(tcp->tcp_kssl_ctx == NULL);
6867 	ASSERT(!tcp->tcp_kssl_pending);
6868 	PRESERVE(tcp->tcp_kssl_ent);
6869 
6870 	tcp->tcp_closemp_used = B_FALSE;
6871 
6872 	PRESERVE(tcp->tcp_rsrv_mp);
6873 	PRESERVE(tcp->tcp_rsrv_mp_lock);
6874 
6875 #ifdef DEBUG
6876 	DONTCARE(tcp->tcmp_stk[0]);
6877 #endif
6878 
6879 	PRESERVE(tcp->tcp_connid);
6880 
6881 	ASSERT(tcp->tcp_listen_cnt == NULL);
6882 	ASSERT(tcp->tcp_reass_tid == 0);
6883 
6884 #undef	DONTCARE
6885 #undef	PRESERVE
6886 }
6887 
6888 static void
6889 tcp_init_values(tcp_t *tcp)
6890 {
6891 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6892 	conn_t		*connp = tcp->tcp_connp;
6893 
6894 	ASSERT((connp->conn_family == AF_INET &&
6895 	    connp->conn_ipversion == IPV4_VERSION) ||
6896 	    (connp->conn_family == AF_INET6 &&
6897 	    (connp->conn_ipversion == IPV4_VERSION ||
6898 	    connp->conn_ipversion == IPV6_VERSION)));
6899 
6900 	/*
6901 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
6902 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
6903 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
6904 	 * during first few transmissions of a connection as seen in slow
6905 	 * links.
6906 	 */
6907 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
6908 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
6909 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
6910 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
6911 	    tcps->tcps_conn_grace_period;
6912 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
6913 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
6914 	tcp->tcp_timer_backoff = 0;
6915 	tcp->tcp_ms_we_have_waited = 0;
6916 	tcp->tcp_last_recv_time = ddi_get_lbolt();
6917 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
6918 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
6919 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
6920 
6921 	tcp->tcp_maxpsz_multiplier = tcps->tcps_maxpsz_multiplier;
6922 
6923 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
6924 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
6925 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
6926 	/*
6927 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
6928 	 * passive open.
6929 	 */
6930 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
6931 
6932 	tcp->tcp_naglim = tcps->tcps_naglim_def;
6933 
6934 	/* NOTE:  ISS is now set in tcp_set_destination(). */
6935 
6936 	/* Reset fusion-related fields */
6937 	tcp->tcp_fused = B_FALSE;
6938 	tcp->tcp_unfusable = B_FALSE;
6939 	tcp->tcp_fused_sigurg = B_FALSE;
6940 	tcp->tcp_loopback_peer = NULL;
6941 
6942 	/* We rebuild the header template on the next connect/conn_request */
6943 
6944 	connp->conn_mlp_type = mlptSingle;
6945 
6946 	/*
6947 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
6948 	 * down tcp_rwnd. tcp_set_destination() will set the right value later.
6949 	 */
6950 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
6951 	tcp->tcp_rwnd = connp->conn_rcvbuf;
6952 
6953 	tcp->tcp_cork = B_FALSE;
6954 	/*
6955 	 * Init the tcp_debug option if it wasn't already set.  This value
6956 	 * determines whether TCP
6957 	 * calls strlog() to print out debug messages.  Doing this
6958 	 * initialization here means that this value is not inherited thru
6959 	 * tcp_reinit().
6960 	 */
6961 	if (!connp->conn_debug)
6962 		connp->conn_debug = tcps->tcps_dbg;
6963 
6964 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
6965 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
6966 }
6967 
6968 /* At minimum we need 8 bytes in the TCP header for the lookup */
6969 #define	ICMP_MIN_TCP_HDR	8
6970 
6971 /*
6972  * tcp_icmp_input is called as conn_recvicmp to process ICMP error messages
6973  * passed up by IP. The message is always received on the correct tcp_t.
6974  * Assumes that IP has pulled up everything up to and including the ICMP header.
6975  */
6976 /* ARGSUSED2 */
6977 static void
6978 tcp_icmp_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
6979 {
6980 	conn_t		*connp = (conn_t *)arg1;
6981 	icmph_t		*icmph;
6982 	ipha_t		*ipha;
6983 	int		iph_hdr_length;
6984 	tcpha_t		*tcpha;
6985 	uint32_t	seg_seq;
6986 	tcp_t		*tcp = connp->conn_tcp;
6987 
6988 	/* Assume IP provides aligned packets */
6989 	ASSERT(OK_32PTR(mp->b_rptr));
6990 	ASSERT((MBLKL(mp) >= sizeof (ipha_t)));
6991 
6992 	/*
6993 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
6994 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
6995 	 */
6996 	if (!(ira->ira_flags & IRAF_IS_IPV4)) {
6997 		tcp_icmp_error_ipv6(tcp, mp, ira);
6998 		return;
6999 	}
7000 
7001 	/* Skip past the outer IP and ICMP headers */
7002 	iph_hdr_length = ira->ira_ip_hdr_length;
7003 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
7004 	/*
7005 	 * If we don't have the correct outer IP header length
7006 	 * or if we don't have a complete inner IP header
7007 	 * drop it.
7008 	 */
7009 	if (iph_hdr_length < sizeof (ipha_t) ||
7010 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
7011 noticmpv4:
7012 		freemsg(mp);
7013 		return;
7014 	}
7015 	ipha = (ipha_t *)&icmph[1];
7016 
7017 	/* Skip past the inner IP and find the ULP header */
7018 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
7019 	tcpha = (tcpha_t *)((char *)ipha + iph_hdr_length);
7020 	/*
7021 	 * If we don't have the correct inner IP header length or if the ULP
7022 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
7023 	 * bytes of TCP header, drop it.
7024 	 */
7025 	if (iph_hdr_length < sizeof (ipha_t) ||
7026 	    ipha->ipha_protocol != IPPROTO_TCP ||
7027 	    (uchar_t *)tcpha + ICMP_MIN_TCP_HDR > mp->b_wptr) {
7028 		goto noticmpv4;
7029 	}
7030 
7031 	seg_seq = ntohl(tcpha->tha_seq);
7032 	switch (icmph->icmph_type) {
7033 	case ICMP_DEST_UNREACHABLE:
7034 		switch (icmph->icmph_code) {
7035 		case ICMP_FRAGMENTATION_NEEDED:
7036 			/*
7037 			 * Update Path MTU, then try to send something out.
7038 			 */
7039 			tcp_update_pmtu(tcp, B_TRUE);
7040 			tcp_rexmit_after_error(tcp);
7041 			break;
7042 		case ICMP_PORT_UNREACHABLE:
7043 		case ICMP_PROTOCOL_UNREACHABLE:
7044 			switch (tcp->tcp_state) {
7045 			case TCPS_SYN_SENT:
7046 			case TCPS_SYN_RCVD:
7047 				/*
7048 				 * ICMP can snipe away incipient
7049 				 * TCP connections as long as
7050 				 * seq number is same as initial
7051 				 * send seq number.
7052 				 */
7053 				if (seg_seq == tcp->tcp_iss) {
7054 					(void) tcp_clean_death(tcp,
7055 					    ECONNREFUSED, 6);
7056 				}
7057 				break;
7058 			}
7059 			break;
7060 		case ICMP_HOST_UNREACHABLE:
7061 		case ICMP_NET_UNREACHABLE:
7062 			/* Record the error in case we finally time out. */
7063 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
7064 				tcp->tcp_client_errno = EHOSTUNREACH;
7065 			else
7066 				tcp->tcp_client_errno = ENETUNREACH;
7067 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
7068 				if (tcp->tcp_listener != NULL &&
7069 				    tcp->tcp_listener->tcp_syn_defense) {
7070 					/*
7071 					 * Ditch the half-open connection if we
7072 					 * suspect a SYN attack is under way.
7073 					 */
7074 					(void) tcp_clean_death(tcp,
7075 					    tcp->tcp_client_errno, 7);
7076 				}
7077 			}
7078 			break;
7079 		default:
7080 			break;
7081 		}
7082 		break;
7083 	case ICMP_SOURCE_QUENCH: {
7084 		/*
7085 		 * use a global boolean to control
7086 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
7087 		 * The default is false.
7088 		 */
7089 		if (tcp_icmp_source_quench) {
7090 			/*
7091 			 * Reduce the sending rate as if we got a
7092 			 * retransmit timeout
7093 			 */
7094 			uint32_t npkt;
7095 
7096 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
7097 			    tcp->tcp_mss;
7098 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
7099 			tcp->tcp_cwnd = tcp->tcp_mss;
7100 			tcp->tcp_cwnd_cnt = 0;
7101 		}
7102 		break;
7103 	}
7104 	}
7105 	freemsg(mp);
7106 }
7107 
7108 /*
7109  * CALLED OUTSIDE OF SQUEUE! It can not follow any pointers that tcp might
7110  * change. But it can refer to fields like tcp_suna and tcp_snxt.
7111  *
7112  * Function tcp_verifyicmp is called as conn_verifyicmp to verify the ICMP
7113  * error messages received by IP. The message is always received on the correct
7114  * tcp_t.
7115  */
7116 /* ARGSUSED */
7117 static boolean_t
7118 tcp_verifyicmp(conn_t *connp, void *arg2, icmph_t *icmph, icmp6_t *icmp6,
7119     ip_recv_attr_t *ira)
7120 {
7121 	tcpha_t		*tcpha = (tcpha_t *)arg2;
7122 	uint32_t	seq = ntohl(tcpha->tha_seq);
7123 	tcp_t		*tcp = connp->conn_tcp;
7124 
7125 	/*
7126 	 * TCP sequence number contained in payload of the ICMP error message
7127 	 * should be within the range SND.UNA <= SEG.SEQ < SND.NXT. Otherwise,
7128 	 * the message is either a stale ICMP error, or an attack from the
7129 	 * network. Fail the verification.
7130 	 */
7131 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
7132 		return (B_FALSE);
7133 
7134 	/* For "too big" we also check the ignore flag */
7135 	if (ira->ira_flags & IRAF_IS_IPV4) {
7136 		ASSERT(icmph != NULL);
7137 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
7138 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
7139 		    tcp->tcp_tcps->tcps_ignore_path_mtu)
7140 			return (B_FALSE);
7141 	} else {
7142 		ASSERT(icmp6 != NULL);
7143 		if (icmp6->icmp6_type == ICMP6_PACKET_TOO_BIG &&
7144 		    tcp->tcp_tcps->tcps_ignore_path_mtu)
7145 			return (B_FALSE);
7146 	}
7147 	return (B_TRUE);
7148 }
7149 
7150 /*
7151  * Update the TCP connection according to change of PMTU.
7152  *
7153  * Path MTU might have changed by either increase or decrease, so need to
7154  * adjust the MSS based on the value of ixa_pmtu. No need to handle tiny
7155  * or negative MSS, since tcp_mss_set() will do it.
7156  */
7157 static void
7158 tcp_update_pmtu(tcp_t *tcp, boolean_t decrease_only)
7159 {
7160 	uint32_t	pmtu;
7161 	int32_t		mss;
7162 	conn_t		*connp = tcp->tcp_connp;
7163 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
7164 	iaflags_t	ixaflags;
7165 
7166 	if (tcp->tcp_tcps->tcps_ignore_path_mtu)
7167 		return;
7168 
7169 	if (tcp->tcp_state < TCPS_ESTABLISHED)
7170 		return;
7171 
7172 	/*
7173 	 * Always call ip_get_pmtu() to make sure that IP has updated
7174 	 * ixa_flags properly.
7175 	 */
7176 	pmtu = ip_get_pmtu(ixa);
7177 	ixaflags = ixa->ixa_flags;
7178 
7179 	/*
7180 	 * Calculate the MSS by decreasing the PMTU by conn_ht_iphc_len and
7181 	 * IPsec overhead if applied. Make sure to use the most recent
7182 	 * IPsec information.
7183 	 */
7184 	mss = pmtu - connp->conn_ht_iphc_len - conn_ipsec_length(connp);
7185 
7186 	/*
7187 	 * Nothing to change, so just return.
7188 	 */
7189 	if (mss == tcp->tcp_mss)
7190 		return;
7191 
7192 	/*
7193 	 * Currently, for ICMP errors, only PMTU decrease is handled.
7194 	 */
7195 	if (mss > tcp->tcp_mss && decrease_only)
7196 		return;
7197 
7198 	DTRACE_PROBE2(tcp_update_pmtu, int32_t, tcp->tcp_mss, uint32_t, mss);
7199 
7200 	/*
7201 	 * Update ixa_fragsize and ixa_pmtu.
7202 	 */
7203 	ixa->ixa_fragsize = ixa->ixa_pmtu = pmtu;
7204 
7205 	/*
7206 	 * Adjust MSS and all relevant variables.
7207 	 */
7208 	tcp_mss_set(tcp, mss);
7209 
7210 	/*
7211 	 * If the PMTU is below the min size maintained by IP, then ip_get_pmtu
7212 	 * has set IXAF_PMTU_TOO_SMALL and cleared IXAF_PMTU_IPV4_DF. Since TCP
7213 	 * has a (potentially different) min size we do the same. Make sure to
7214 	 * clear IXAF_DONTFRAG, which is used by IP to decide whether to
7215 	 * fragment the packet.
7216 	 *
7217 	 * LSO over IPv6 can not be fragmented. So need to disable LSO
7218 	 * when IPv6 fragmentation is needed.
7219 	 */
7220 	if (mss < tcp->tcp_tcps->tcps_mss_min)
7221 		ixaflags |= IXAF_PMTU_TOO_SMALL;
7222 
7223 	if (ixaflags & IXAF_PMTU_TOO_SMALL)
7224 		ixaflags &= ~(IXAF_DONTFRAG | IXAF_PMTU_IPV4_DF);
7225 
7226 	if ((connp->conn_ipversion == IPV4_VERSION) &&
7227 	    !(ixaflags & IXAF_PMTU_IPV4_DF)) {
7228 		tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
7229 	}
7230 	ixa->ixa_flags = ixaflags;
7231 }
7232 
7233 /*
7234  * Do slow start retransmission after ICMP errors of PMTU changes.
7235  */
7236 static void
7237 tcp_rexmit_after_error(tcp_t *tcp)
7238 {
7239 	/*
7240 	 * All sent data has been acknowledged or no data left to send, just
7241 	 * to return.
7242 	 */
7243 	if (!SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) ||
7244 	    (tcp->tcp_xmit_head == NULL))
7245 		return;
7246 
7247 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) && (tcp->tcp_unsent == 0))
7248 		tcp->tcp_rexmit_max = tcp->tcp_fss;
7249 	else
7250 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
7251 
7252 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
7253 	tcp->tcp_rexmit = B_TRUE;
7254 	tcp->tcp_dupack_cnt = 0;
7255 	tcp->tcp_snd_burst = TCP_CWND_SS;
7256 	tcp_ss_rexmit(tcp);
7257 }
7258 
7259 /*
7260  * tcp_icmp_error_ipv6 is called from tcp_icmp_input to process ICMPv6
7261  * error messages passed up by IP.
7262  * Assumes that IP has pulled up all the extension headers as well
7263  * as the ICMPv6 header.
7264  */
7265 static void
7266 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, ip_recv_attr_t *ira)
7267 {
7268 	icmp6_t		*icmp6;
7269 	ip6_t		*ip6h;
7270 	uint16_t	iph_hdr_length = ira->ira_ip_hdr_length;
7271 	tcpha_t		*tcpha;
7272 	uint8_t		*nexthdrp;
7273 	uint32_t	seg_seq;
7274 
7275 	/*
7276 	 * Verify that we have a complete IP header.
7277 	 */
7278 	ASSERT((MBLKL(mp) >= sizeof (ip6_t)));
7279 
7280 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
7281 	ip6h = (ip6_t *)&icmp6[1];
7282 	/*
7283 	 * Verify if we have a complete ICMP and inner IP header.
7284 	 */
7285 	if ((uchar_t *)&ip6h[1] > mp->b_wptr) {
7286 noticmpv6:
7287 		freemsg(mp);
7288 		return;
7289 	}
7290 
7291 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
7292 		goto noticmpv6;
7293 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
7294 	/*
7295 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
7296 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
7297 	 * packet.
7298 	 */
7299 	if ((*nexthdrp != IPPROTO_TCP) ||
7300 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
7301 		goto noticmpv6;
7302 	}
7303 
7304 	seg_seq = ntohl(tcpha->tha_seq);
7305 	switch (icmp6->icmp6_type) {
7306 	case ICMP6_PACKET_TOO_BIG:
7307 		/*
7308 		 * Update Path MTU, then try to send something out.
7309 		 */
7310 		tcp_update_pmtu(tcp, B_TRUE);
7311 		tcp_rexmit_after_error(tcp);
7312 		break;
7313 	case ICMP6_DST_UNREACH:
7314 		switch (icmp6->icmp6_code) {
7315 		case ICMP6_DST_UNREACH_NOPORT:
7316 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
7317 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
7318 			    (seg_seq == tcp->tcp_iss)) {
7319 				(void) tcp_clean_death(tcp,
7320 				    ECONNREFUSED, 8);
7321 			}
7322 			break;
7323 		case ICMP6_DST_UNREACH_ADMIN:
7324 		case ICMP6_DST_UNREACH_NOROUTE:
7325 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
7326 		case ICMP6_DST_UNREACH_ADDR:
7327 			/* Record the error in case we finally time out. */
7328 			tcp->tcp_client_errno = EHOSTUNREACH;
7329 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
7330 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
7331 			    (seg_seq == tcp->tcp_iss)) {
7332 				if (tcp->tcp_listener != NULL &&
7333 				    tcp->tcp_listener->tcp_syn_defense) {
7334 					/*
7335 					 * Ditch the half-open connection if we
7336 					 * suspect a SYN attack is under way.
7337 					 */
7338 					(void) tcp_clean_death(tcp,
7339 					    tcp->tcp_client_errno, 9);
7340 				}
7341 			}
7342 
7343 
7344 			break;
7345 		default:
7346 			break;
7347 		}
7348 		break;
7349 	case ICMP6_PARAM_PROB:
7350 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
7351 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
7352 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
7353 		    (uchar_t *)nexthdrp) {
7354 			if (tcp->tcp_state == TCPS_SYN_SENT ||
7355 			    tcp->tcp_state == TCPS_SYN_RCVD) {
7356 				(void) tcp_clean_death(tcp,
7357 				    ECONNREFUSED, 10);
7358 			}
7359 			break;
7360 		}
7361 		break;
7362 
7363 	case ICMP6_TIME_EXCEEDED:
7364 	default:
7365 		break;
7366 	}
7367 	freemsg(mp);
7368 }
7369 
7370 /*
7371  * Notify IP that we are having trouble with this connection.  IP should
7372  * make note so it can potentially use a different IRE.
7373  */
7374 static void
7375 tcp_ip_notify(tcp_t *tcp)
7376 {
7377 	conn_t		*connp = tcp->tcp_connp;
7378 	ire_t		*ire;
7379 
7380 	/*
7381 	 * Note: in the case of source routing we want to blow away the
7382 	 * route to the first source route hop.
7383 	 */
7384 	ire = connp->conn_ixa->ixa_ire;
7385 	if (ire != NULL && !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
7386 		if (ire->ire_ipversion == IPV4_VERSION) {
7387 			/*
7388 			 * As per RFC 1122, we send an RTM_LOSING to inform
7389 			 * routing protocols.
7390 			 */
7391 			ip_rts_change(RTM_LOSING, ire->ire_addr,
7392 			    ire->ire_gateway_addr, ire->ire_mask,
7393 			    connp->conn_laddr_v4,  0, 0, 0,
7394 			    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_IFA),
7395 			    ire->ire_ipst);
7396 		}
7397 		(void) ire_no_good(ire);
7398 	}
7399 }
7400 
7401 #pragma inline(tcp_send_data)
7402 
7403 /*
7404  * Timer callback routine for keepalive probe.  We do a fake resend of
7405  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
7406  * check to see if we have heard anything from the other end for the last
7407  * RTO period.  If we have, set the timer to expire for another
7408  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
7409  * RTO << 1 and check again when it expires.  Keep exponentially increasing
7410  * the timeout if we have not heard from the other side.  If for more than
7411  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
7412  * kill the connection unless the keepalive abort threshold is 0.  In
7413  * that case, we will probe "forever."
7414  */
7415 static void
7416 tcp_keepalive_killer(void *arg)
7417 {
7418 	mblk_t	*mp;
7419 	conn_t	*connp = (conn_t *)arg;
7420 	tcp_t  	*tcp = connp->conn_tcp;
7421 	int32_t	firetime;
7422 	int32_t	idletime;
7423 	int32_t	ka_intrvl;
7424 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7425 
7426 	tcp->tcp_ka_tid = 0;
7427 
7428 	if (tcp->tcp_fused)
7429 		return;
7430 
7431 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
7432 	ka_intrvl = tcp->tcp_ka_interval;
7433 
7434 	/*
7435 	 * Keepalive probe should only be sent if the application has not
7436 	 * done a close on the connection.
7437 	 */
7438 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
7439 		return;
7440 	}
7441 	/* Timer fired too early, restart it. */
7442 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
7443 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
7444 		    MSEC_TO_TICK(ka_intrvl));
7445 		return;
7446 	}
7447 
7448 	idletime = TICK_TO_MSEC(ddi_get_lbolt() - tcp->tcp_last_recv_time);
7449 	/*
7450 	 * If we have not heard from the other side for a long
7451 	 * time, kill the connection unless the keepalive abort
7452 	 * threshold is 0.  In that case, we will probe "forever."
7453 	 */
7454 	if (tcp->tcp_ka_abort_thres != 0 &&
7455 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
7456 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
7457 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
7458 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
7459 		return;
7460 	}
7461 
7462 	if (tcp->tcp_snxt == tcp->tcp_suna &&
7463 	    idletime >= ka_intrvl) {
7464 		/* Fake resend of last ACKed byte. */
7465 		mblk_t	*mp1 = allocb(1, BPRI_LO);
7466 
7467 		if (mp1 != NULL) {
7468 			*mp1->b_wptr++ = '\0';
7469 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
7470 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
7471 			freeb(mp1);
7472 			/*
7473 			 * if allocation failed, fall through to start the
7474 			 * timer back.
7475 			 */
7476 			if (mp != NULL) {
7477 				tcp_send_data(tcp, mp);
7478 				BUMP_MIB(&tcps->tcps_mib,
7479 				    tcpTimKeepaliveProbe);
7480 				if (tcp->tcp_ka_last_intrvl != 0) {
7481 					int max;
7482 					/*
7483 					 * We should probe again at least
7484 					 * in ka_intrvl, but not more than
7485 					 * tcp_rexmit_interval_max.
7486 					 */
7487 					max = tcps->tcps_rexmit_interval_max;
7488 					firetime = MIN(ka_intrvl - 1,
7489 					    tcp->tcp_ka_last_intrvl << 1);
7490 					if (firetime > max)
7491 						firetime = max;
7492 				} else {
7493 					firetime = tcp->tcp_rto;
7494 				}
7495 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
7496 				    tcp_keepalive_killer,
7497 				    MSEC_TO_TICK(firetime));
7498 				tcp->tcp_ka_last_intrvl = firetime;
7499 				return;
7500 			}
7501 		}
7502 	} else {
7503 		tcp->tcp_ka_last_intrvl = 0;
7504 	}
7505 
7506 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
7507 	if ((firetime = ka_intrvl - idletime) < 0) {
7508 		firetime = ka_intrvl;
7509 	}
7510 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
7511 	    MSEC_TO_TICK(firetime));
7512 }
7513 
7514 int
7515 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
7516 {
7517 	conn_t	*connp = tcp->tcp_connp;
7518 	queue_t	*q = connp->conn_rq;
7519 	int32_t	mss = tcp->tcp_mss;
7520 	int	maxpsz;
7521 
7522 	if (TCP_IS_DETACHED(tcp))
7523 		return (mss);
7524 	if (tcp->tcp_fused) {
7525 		maxpsz = tcp_fuse_maxpsz(tcp);
7526 		mss = INFPSZ;
7527 	} else if (tcp->tcp_maxpsz_multiplier == 0) {
7528 		/*
7529 		 * Set the sd_qn_maxpsz according to the socket send buffer
7530 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
7531 		 * instruct the stream head to copyin user data into contiguous
7532 		 * kernel-allocated buffers without breaking it up into smaller
7533 		 * chunks.  We round up the buffer size to the nearest SMSS.
7534 		 */
7535 		maxpsz = MSS_ROUNDUP(connp->conn_sndbuf, mss);
7536 		if (tcp->tcp_kssl_ctx == NULL)
7537 			mss = INFPSZ;
7538 		else
7539 			mss = SSL3_MAX_RECORD_LEN;
7540 	} else {
7541 		/*
7542 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
7543 		 * (and a multiple of the mss).  This instructs the stream
7544 		 * head to break down larger than SMSS writes into SMSS-
7545 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
7546 		 */
7547 		maxpsz = tcp->tcp_maxpsz_multiplier * mss;
7548 		if (maxpsz > connp->conn_sndbuf / 2) {
7549 			maxpsz = connp->conn_sndbuf / 2;
7550 			/* Round up to nearest mss */
7551 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
7552 		}
7553 	}
7554 
7555 	(void) proto_set_maxpsz(q, connp, maxpsz);
7556 	if (!(IPCL_IS_NONSTR(connp)))
7557 		connp->conn_wq->q_maxpsz = maxpsz;
7558 	if (set_maxblk)
7559 		(void) proto_set_tx_maxblk(q, connp, mss);
7560 	return (mss);
7561 }
7562 
7563 /*
7564  * Extract option values from a tcp header.  We put any found values into the
7565  * tcpopt struct and return a bitmask saying which options were found.
7566  */
7567 static int
7568 tcp_parse_options(tcpha_t *tcpha, tcp_opt_t *tcpopt)
7569 {
7570 	uchar_t		*endp;
7571 	int		len;
7572 	uint32_t	mss;
7573 	uchar_t		*up = (uchar_t *)tcpha;
7574 	int		found = 0;
7575 	int32_t		sack_len;
7576 	tcp_seq		sack_begin, sack_end;
7577 	tcp_t		*tcp;
7578 
7579 	endp = up + TCP_HDR_LENGTH(tcpha);
7580 	up += TCP_MIN_HEADER_LENGTH;
7581 	while (up < endp) {
7582 		len = endp - up;
7583 		switch (*up) {
7584 		case TCPOPT_EOL:
7585 			break;
7586 
7587 		case TCPOPT_NOP:
7588 			up++;
7589 			continue;
7590 
7591 		case TCPOPT_MAXSEG:
7592 			if (len < TCPOPT_MAXSEG_LEN ||
7593 			    up[1] != TCPOPT_MAXSEG_LEN)
7594 				break;
7595 
7596 			mss = BE16_TO_U16(up+2);
7597 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
7598 			tcpopt->tcp_opt_mss = mss;
7599 			found |= TCP_OPT_MSS_PRESENT;
7600 
7601 			up += TCPOPT_MAXSEG_LEN;
7602 			continue;
7603 
7604 		case TCPOPT_WSCALE:
7605 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
7606 				break;
7607 
7608 			if (up[2] > TCP_MAX_WINSHIFT)
7609 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
7610 			else
7611 				tcpopt->tcp_opt_wscale = up[2];
7612 			found |= TCP_OPT_WSCALE_PRESENT;
7613 
7614 			up += TCPOPT_WS_LEN;
7615 			continue;
7616 
7617 		case TCPOPT_SACK_PERMITTED:
7618 			if (len < TCPOPT_SACK_OK_LEN ||
7619 			    up[1] != TCPOPT_SACK_OK_LEN)
7620 				break;
7621 			found |= TCP_OPT_SACK_OK_PRESENT;
7622 			up += TCPOPT_SACK_OK_LEN;
7623 			continue;
7624 
7625 		case TCPOPT_SACK:
7626 			if (len <= 2 || up[1] <= 2 || len < up[1])
7627 				break;
7628 
7629 			/* If TCP is not interested in SACK blks... */
7630 			if ((tcp = tcpopt->tcp) == NULL) {
7631 				up += up[1];
7632 				continue;
7633 			}
7634 			sack_len = up[1] - TCPOPT_HEADER_LEN;
7635 			up += TCPOPT_HEADER_LEN;
7636 
7637 			/*
7638 			 * If the list is empty, allocate one and assume
7639 			 * nothing is sack'ed.
7640 			 */
7641 			ASSERT(tcp->tcp_sack_info != NULL);
7642 			if (tcp->tcp_notsack_list == NULL) {
7643 				tcp_notsack_update(&(tcp->tcp_notsack_list),
7644 				    tcp->tcp_suna, tcp->tcp_snxt,
7645 				    &(tcp->tcp_num_notsack_blk),
7646 				    &(tcp->tcp_cnt_notsack_list));
7647 
7648 				/*
7649 				 * Make sure tcp_notsack_list is not NULL.
7650 				 * This happens when kmem_alloc(KM_NOSLEEP)
7651 				 * returns NULL.
7652 				 */
7653 				if (tcp->tcp_notsack_list == NULL) {
7654 					up += sack_len;
7655 					continue;
7656 				}
7657 				tcp->tcp_fack = tcp->tcp_suna;
7658 			}
7659 
7660 			while (sack_len > 0) {
7661 				if (up + 8 > endp) {
7662 					up = endp;
7663 					break;
7664 				}
7665 				sack_begin = BE32_TO_U32(up);
7666 				up += 4;
7667 				sack_end = BE32_TO_U32(up);
7668 				up += 4;
7669 				sack_len -= 8;
7670 				/*
7671 				 * Bounds checking.  Make sure the SACK
7672 				 * info is within tcp_suna and tcp_snxt.
7673 				 * If this SACK blk is out of bound, ignore
7674 				 * it but continue to parse the following
7675 				 * blks.
7676 				 */
7677 				if (SEQ_LEQ(sack_end, sack_begin) ||
7678 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
7679 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
7680 					continue;
7681 				}
7682 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
7683 				    sack_begin, sack_end,
7684 				    &(tcp->tcp_num_notsack_blk),
7685 				    &(tcp->tcp_cnt_notsack_list));
7686 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
7687 					tcp->tcp_fack = sack_end;
7688 				}
7689 			}
7690 			found |= TCP_OPT_SACK_PRESENT;
7691 			continue;
7692 
7693 		case TCPOPT_TSTAMP:
7694 			if (len < TCPOPT_TSTAMP_LEN ||
7695 			    up[1] != TCPOPT_TSTAMP_LEN)
7696 				break;
7697 
7698 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
7699 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
7700 
7701 			found |= TCP_OPT_TSTAMP_PRESENT;
7702 
7703 			up += TCPOPT_TSTAMP_LEN;
7704 			continue;
7705 
7706 		default:
7707 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
7708 				break;
7709 			up += up[1];
7710 			continue;
7711 		}
7712 		break;
7713 	}
7714 	return (found);
7715 }
7716 
7717 /*
7718  * Set the MSS associated with a particular tcp based on its current value,
7719  * and a new one passed in. Observe minimums and maximums, and reset other
7720  * state variables that we want to view as multiples of MSS.
7721  *
7722  * The value of MSS could be either increased or descreased.
7723  */
7724 static void
7725 tcp_mss_set(tcp_t *tcp, uint32_t mss)
7726 {
7727 	uint32_t	mss_max;
7728 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7729 	conn_t		*connp = tcp->tcp_connp;
7730 
7731 	if (connp->conn_ipversion == IPV4_VERSION)
7732 		mss_max = tcps->tcps_mss_max_ipv4;
7733 	else
7734 		mss_max = tcps->tcps_mss_max_ipv6;
7735 
7736 	if (mss < tcps->tcps_mss_min)
7737 		mss = tcps->tcps_mss_min;
7738 	if (mss > mss_max)
7739 		mss = mss_max;
7740 	/*
7741 	 * Unless naglim has been set by our client to
7742 	 * a non-mss value, force naglim to track mss.
7743 	 * This can help to aggregate small writes.
7744 	 */
7745 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
7746 		tcp->tcp_naglim = mss;
7747 	/*
7748 	 * TCP should be able to buffer at least 4 MSS data for obvious
7749 	 * performance reason.
7750 	 */
7751 	if ((mss << 2) > connp->conn_sndbuf)
7752 		connp->conn_sndbuf = mss << 2;
7753 
7754 	/*
7755 	 * Set the send lowater to at least twice of MSS.
7756 	 */
7757 	if ((mss << 1) > connp->conn_sndlowat)
7758 		connp->conn_sndlowat = mss << 1;
7759 
7760 	/*
7761 	 * Update tcp_cwnd according to the new value of MSS. Keep the
7762 	 * previous ratio to preserve the transmit rate.
7763 	 */
7764 	tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
7765 	tcp->tcp_cwnd_cnt = 0;
7766 
7767 	tcp->tcp_mss = mss;
7768 	(void) tcp_maxpsz_set(tcp, B_TRUE);
7769 }
7770 
7771 /* For /dev/tcp aka AF_INET open */
7772 static int
7773 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
7774 {
7775 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
7776 }
7777 
7778 /* For /dev/tcp6 aka AF_INET6 open */
7779 static int
7780 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
7781 {
7782 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
7783 }
7784 
7785 static conn_t *
7786 tcp_create_common(cred_t *credp, boolean_t isv6, boolean_t issocket,
7787     int *errorp)
7788 {
7789 	tcp_t		*tcp = NULL;
7790 	conn_t		*connp;
7791 	zoneid_t	zoneid;
7792 	tcp_stack_t	*tcps;
7793 	squeue_t	*sqp;
7794 
7795 	ASSERT(errorp != NULL);
7796 	/*
7797 	 * Find the proper zoneid and netstack.
7798 	 */
7799 	/*
7800 	 * Special case for install: miniroot needs to be able to
7801 	 * access files via NFS as though it were always in the
7802 	 * global zone.
7803 	 */
7804 	if (credp == kcred && nfs_global_client_only != 0) {
7805 		zoneid = GLOBAL_ZONEID;
7806 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
7807 		    netstack_tcp;
7808 		ASSERT(tcps != NULL);
7809 	} else {
7810 		netstack_t *ns;
7811 		int err;
7812 
7813 		if ((err = secpolicy_basic_net_access(credp)) != 0) {
7814 			*errorp = err;
7815 			return (NULL);
7816 		}
7817 
7818 		ns = netstack_find_by_cred(credp);
7819 		ASSERT(ns != NULL);
7820 		tcps = ns->netstack_tcp;
7821 		ASSERT(tcps != NULL);
7822 
7823 		/*
7824 		 * For exclusive stacks we set the zoneid to zero
7825 		 * to make TCP operate as if in the global zone.
7826 		 */
7827 		if (tcps->tcps_netstack->netstack_stackid !=
7828 		    GLOBAL_NETSTACKID)
7829 			zoneid = GLOBAL_ZONEID;
7830 		else
7831 			zoneid = crgetzoneid(credp);
7832 	}
7833 
7834 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
7835 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
7836 	/*
7837 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
7838 	 * so we drop it by one.
7839 	 */
7840 	netstack_rele(tcps->tcps_netstack);
7841 	if (connp == NULL) {
7842 		*errorp = ENOSR;
7843 		return (NULL);
7844 	}
7845 	ASSERT(connp->conn_ixa->ixa_protocol == connp->conn_proto);
7846 
7847 	connp->conn_sqp = sqp;
7848 	connp->conn_initial_sqp = connp->conn_sqp;
7849 	connp->conn_ixa->ixa_sqp = connp->conn_sqp;
7850 	tcp = connp->conn_tcp;
7851 
7852 	/*
7853 	 * Besides asking IP to set the checksum for us, have conn_ip_output
7854 	 * to do the following checks when necessary:
7855 	 *
7856 	 * IXAF_VERIFY_SOURCE: drop packets when our outer source goes invalid
7857 	 * IXAF_VERIFY_PMTU: verify PMTU changes
7858 	 * IXAF_VERIFY_LSO: verify LSO capability changes
7859 	 */
7860 	connp->conn_ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
7861 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO;
7862 
7863 	if (!tcps->tcps_dev_flow_ctl)
7864 		connp->conn_ixa->ixa_flags |= IXAF_NO_DEV_FLOW_CTL;
7865 
7866 	if (isv6) {
7867 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
7868 		connp->conn_ipversion = IPV6_VERSION;
7869 		connp->conn_family = AF_INET6;
7870 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7871 		connp->conn_default_ttl = tcps->tcps_ipv6_hoplimit;
7872 	} else {
7873 		connp->conn_ipversion = IPV4_VERSION;
7874 		connp->conn_family = AF_INET;
7875 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7876 		connp->conn_default_ttl = tcps->tcps_ipv4_ttl;
7877 	}
7878 	connp->conn_xmit_ipp.ipp_unicast_hops = connp->conn_default_ttl;
7879 
7880 	crhold(credp);
7881 	connp->conn_cred = credp;
7882 	connp->conn_cpid = curproc->p_pid;
7883 	connp->conn_open_time = ddi_get_lbolt64();
7884 
7885 	connp->conn_zoneid = zoneid;
7886 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
7887 	connp->conn_ixa->ixa_zoneid = zoneid;
7888 	connp->conn_mlp_type = mlptSingle;
7889 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
7890 	ASSERT(tcp->tcp_tcps == tcps);
7891 
7892 	/*
7893 	 * If the caller has the process-wide flag set, then default to MAC
7894 	 * exempt mode.  This allows read-down to unlabeled hosts.
7895 	 */
7896 	if (getpflags(NET_MAC_AWARE, credp) != 0)
7897 		connp->conn_mac_mode = CONN_MAC_AWARE;
7898 
7899 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
7900 
7901 	if (issocket) {
7902 		tcp->tcp_issocket = 1;
7903 	}
7904 
7905 	connp->conn_rcvbuf = tcps->tcps_recv_hiwat;
7906 	connp->conn_sndbuf = tcps->tcps_xmit_hiwat;
7907 	connp->conn_sndlowat = tcps->tcps_xmit_lowat;
7908 	connp->conn_so_type = SOCK_STREAM;
7909 	connp->conn_wroff = connp->conn_ht_iphc_allocated +
7910 	    tcps->tcps_wroff_xtra;
7911 
7912 	SOCK_CONNID_INIT(tcp->tcp_connid);
7913 	tcp->tcp_state = TCPS_IDLE;
7914 	tcp_init_values(tcp);
7915 	return (connp);
7916 }
7917 
7918 static int
7919 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
7920     boolean_t isv6)
7921 {
7922 	tcp_t		*tcp = NULL;
7923 	conn_t		*connp = NULL;
7924 	int		err;
7925 	vmem_t		*minor_arena = NULL;
7926 	dev_t		conn_dev;
7927 	boolean_t	issocket;
7928 
7929 	if (q->q_ptr != NULL)
7930 		return (0);
7931 
7932 	if (sflag == MODOPEN)
7933 		return (EINVAL);
7934 
7935 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
7936 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
7937 		minor_arena = ip_minor_arena_la;
7938 	} else {
7939 		/*
7940 		 * Either minor numbers in the large arena were exhausted
7941 		 * or a non socket application is doing the open.
7942 		 * Try to allocate from the small arena.
7943 		 */
7944 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
7945 			return (EBUSY);
7946 		}
7947 		minor_arena = ip_minor_arena_sa;
7948 	}
7949 
7950 	ASSERT(minor_arena != NULL);
7951 
7952 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
7953 
7954 	if (flag & SO_FALLBACK) {
7955 		/*
7956 		 * Non streams socket needs a stream to fallback to
7957 		 */
7958 		RD(q)->q_ptr = (void *)conn_dev;
7959 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
7960 		WR(q)->q_ptr = (void *)minor_arena;
7961 		qprocson(q);
7962 		return (0);
7963 	} else if (flag & SO_ACCEPTOR) {
7964 		q->q_qinfo = &tcp_acceptor_rinit;
7965 		/*
7966 		 * the conn_dev and minor_arena will be subsequently used by
7967 		 * tcp_tli_accept() and tcp_tpi_close_accept() to figure out
7968 		 * the minor device number for this connection from the q_ptr.
7969 		 */
7970 		RD(q)->q_ptr = (void *)conn_dev;
7971 		WR(q)->q_qinfo = &tcp_acceptor_winit;
7972 		WR(q)->q_ptr = (void *)minor_arena;
7973 		qprocson(q);
7974 		return (0);
7975 	}
7976 
7977 	issocket = flag & SO_SOCKSTR;
7978 	connp = tcp_create_common(credp, isv6, issocket, &err);
7979 
7980 	if (connp == NULL) {
7981 		inet_minor_free(minor_arena, conn_dev);
7982 		q->q_ptr = WR(q)->q_ptr = NULL;
7983 		return (err);
7984 	}
7985 
7986 	connp->conn_rq = q;
7987 	connp->conn_wq = WR(q);
7988 	q->q_ptr = WR(q)->q_ptr = connp;
7989 
7990 	connp->conn_dev = conn_dev;
7991 	connp->conn_minor_arena = minor_arena;
7992 
7993 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
7994 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
7995 
7996 	tcp = connp->conn_tcp;
7997 
7998 	if (issocket) {
7999 		WR(q)->q_qinfo = &tcp_sock_winit;
8000 	} else {
8001 #ifdef  _ILP32
8002 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
8003 #else
8004 		tcp->tcp_acceptor_id = conn_dev;
8005 #endif  /* _ILP32 */
8006 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
8007 	}
8008 
8009 	/*
8010 	 * Put the ref for TCP. Ref for IP was already put
8011 	 * by ipcl_conn_create. Also Make the conn_t globally
8012 	 * visible to walkers
8013 	 */
8014 	mutex_enter(&connp->conn_lock);
8015 	CONN_INC_REF_LOCKED(connp);
8016 	ASSERT(connp->conn_ref == 2);
8017 	connp->conn_state_flags &= ~CONN_INCIPIENT;
8018 	mutex_exit(&connp->conn_lock);
8019 
8020 	qprocson(q);
8021 	return (0);
8022 }
8023 
8024 /*
8025  * Some TCP options can be "set" by requesting them in the option
8026  * buffer. This is needed for XTI feature test though we do not
8027  * allow it in general. We interpret that this mechanism is more
8028  * applicable to OSI protocols and need not be allowed in general.
8029  * This routine filters out options for which it is not allowed (most)
8030  * and lets through those (few) for which it is. [ The XTI interface
8031  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
8032  * ever implemented will have to be allowed here ].
8033  */
8034 static boolean_t
8035 tcp_allow_connopt_set(int level, int name)
8036 {
8037 
8038 	switch (level) {
8039 	case IPPROTO_TCP:
8040 		switch (name) {
8041 		case TCP_NODELAY:
8042 			return (B_TRUE);
8043 		default:
8044 			return (B_FALSE);
8045 		}
8046 		/*NOTREACHED*/
8047 	default:
8048 		return (B_FALSE);
8049 	}
8050 	/*NOTREACHED*/
8051 }
8052 
8053 /*
8054  * This routine gets default values of certain options whose default
8055  * values are maintained by protocol specific code
8056  */
8057 /* ARGSUSED */
8058 int
8059 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
8060 {
8061 	int32_t	*i1 = (int32_t *)ptr;
8062 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
8063 
8064 	switch (level) {
8065 	case IPPROTO_TCP:
8066 		switch (name) {
8067 		case TCP_NOTIFY_THRESHOLD:
8068 			*i1 = tcps->tcps_ip_notify_interval;
8069 			break;
8070 		case TCP_ABORT_THRESHOLD:
8071 			*i1 = tcps->tcps_ip_abort_interval;
8072 			break;
8073 		case TCP_CONN_NOTIFY_THRESHOLD:
8074 			*i1 = tcps->tcps_ip_notify_cinterval;
8075 			break;
8076 		case TCP_CONN_ABORT_THRESHOLD:
8077 			*i1 = tcps->tcps_ip_abort_cinterval;
8078 			break;
8079 		default:
8080 			return (-1);
8081 		}
8082 		break;
8083 	case IPPROTO_IP:
8084 		switch (name) {
8085 		case IP_TTL:
8086 			*i1 = tcps->tcps_ipv4_ttl;
8087 			break;
8088 		default:
8089 			return (-1);
8090 		}
8091 		break;
8092 	case IPPROTO_IPV6:
8093 		switch (name) {
8094 		case IPV6_UNICAST_HOPS:
8095 			*i1 = tcps->tcps_ipv6_hoplimit;
8096 			break;
8097 		default:
8098 			return (-1);
8099 		}
8100 		break;
8101 	default:
8102 		return (-1);
8103 	}
8104 	return (sizeof (int));
8105 }
8106 
8107 /*
8108  * TCP routine to get the values of options.
8109  */
8110 static int
8111 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
8112 {
8113 	int		*i1 = (int *)ptr;
8114 	tcp_t		*tcp = connp->conn_tcp;
8115 	conn_opt_arg_t	coas;
8116 	int		retval;
8117 
8118 	coas.coa_connp = connp;
8119 	coas.coa_ixa = connp->conn_ixa;
8120 	coas.coa_ipp = &connp->conn_xmit_ipp;
8121 	coas.coa_ancillary = B_FALSE;
8122 	coas.coa_changed = 0;
8123 
8124 	switch (level) {
8125 	case SOL_SOCKET:
8126 		switch (name) {
8127 		case SO_SND_COPYAVOID:
8128 			*i1 = tcp->tcp_snd_zcopy_on ?
8129 			    SO_SND_COPYAVOID : 0;
8130 			return (sizeof (int));
8131 		case SO_ACCEPTCONN:
8132 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
8133 			return (sizeof (int));
8134 		}
8135 		break;
8136 	case IPPROTO_TCP:
8137 		switch (name) {
8138 		case TCP_NODELAY:
8139 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
8140 			return (sizeof (int));
8141 		case TCP_MAXSEG:
8142 			*i1 = tcp->tcp_mss;
8143 			return (sizeof (int));
8144 		case TCP_NOTIFY_THRESHOLD:
8145 			*i1 = (int)tcp->tcp_first_timer_threshold;
8146 			return (sizeof (int));
8147 		case TCP_ABORT_THRESHOLD:
8148 			*i1 = tcp->tcp_second_timer_threshold;
8149 			return (sizeof (int));
8150 		case TCP_CONN_NOTIFY_THRESHOLD:
8151 			*i1 = tcp->tcp_first_ctimer_threshold;
8152 			return (sizeof (int));
8153 		case TCP_CONN_ABORT_THRESHOLD:
8154 			*i1 = tcp->tcp_second_ctimer_threshold;
8155 			return (sizeof (int));
8156 		case TCP_INIT_CWND:
8157 			*i1 = tcp->tcp_init_cwnd;
8158 			return (sizeof (int));
8159 		case TCP_KEEPALIVE_THRESHOLD:
8160 			*i1 = tcp->tcp_ka_interval;
8161 			return (sizeof (int));
8162 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
8163 			*i1 = tcp->tcp_ka_abort_thres;
8164 			return (sizeof (int));
8165 		case TCP_CORK:
8166 			*i1 = tcp->tcp_cork;
8167 			return (sizeof (int));
8168 		}
8169 		break;
8170 	case IPPROTO_IP:
8171 		if (connp->conn_family != AF_INET)
8172 			return (-1);
8173 		switch (name) {
8174 		case IP_OPTIONS:
8175 		case T_IP_OPTIONS:
8176 			/* Caller ensures enough space */
8177 			return (ip_opt_get_user(connp, ptr));
8178 		default:
8179 			break;
8180 		}
8181 		break;
8182 
8183 	case IPPROTO_IPV6:
8184 		/*
8185 		 * IPPROTO_IPV6 options are only supported for sockets
8186 		 * that are using IPv6 on the wire.
8187 		 */
8188 		if (connp->conn_ipversion != IPV6_VERSION) {
8189 			return (-1);
8190 		}
8191 		switch (name) {
8192 		case IPV6_PATHMTU:
8193 			if (tcp->tcp_state < TCPS_ESTABLISHED)
8194 				return (-1);
8195 			break;
8196 		}
8197 		break;
8198 	}
8199 	mutex_enter(&connp->conn_lock);
8200 	retval = conn_opt_get(&coas, level, name, ptr);
8201 	mutex_exit(&connp->conn_lock);
8202 	return (retval);
8203 }
8204 
8205 /*
8206  * TCP routine to get the values of options.
8207  */
8208 int
8209 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
8210 {
8211 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
8212 }
8213 
8214 /* returns UNIX error, the optlen is a value-result arg */
8215 int
8216 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
8217     void *optvalp, socklen_t *optlen, cred_t *cr)
8218 {
8219 	conn_t		*connp = (conn_t *)proto_handle;
8220 	squeue_t	*sqp = connp->conn_sqp;
8221 	int		error;
8222 	t_uscalar_t	max_optbuf_len;
8223 	void		*optvalp_buf;
8224 	int		len;
8225 
8226 	ASSERT(connp->conn_upper_handle != NULL);
8227 
8228 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
8229 	    tcp_opt_obj.odb_opt_des_arr,
8230 	    tcp_opt_obj.odb_opt_arr_cnt,
8231 	    B_FALSE, B_TRUE, cr);
8232 	if (error != 0) {
8233 		if (error < 0) {
8234 			error = proto_tlitosyserr(-error);
8235 		}
8236 		return (error);
8237 	}
8238 
8239 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
8240 
8241 	error = squeue_synch_enter(sqp, connp, NULL);
8242 	if (error == ENOMEM) {
8243 		kmem_free(optvalp_buf, max_optbuf_len);
8244 		return (ENOMEM);
8245 	}
8246 
8247 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
8248 	squeue_synch_exit(sqp, connp);
8249 
8250 	if (len == -1) {
8251 		kmem_free(optvalp_buf, max_optbuf_len);
8252 		return (EINVAL);
8253 	}
8254 
8255 	/*
8256 	 * update optlen and copy option value
8257 	 */
8258 	t_uscalar_t size = MIN(len, *optlen);
8259 
8260 	bcopy(optvalp_buf, optvalp, size);
8261 	bcopy(&size, optlen, sizeof (size));
8262 
8263 	kmem_free(optvalp_buf, max_optbuf_len);
8264 	return (0);
8265 }
8266 
8267 /*
8268  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
8269  * Parameters are assumed to be verified by the caller.
8270  */
8271 /* ARGSUSED */
8272 int
8273 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
8274     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
8275     void *thisdg_attrs, cred_t *cr)
8276 {
8277 	tcp_t	*tcp = connp->conn_tcp;
8278 	int	*i1 = (int *)invalp;
8279 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
8280 	boolean_t checkonly;
8281 	int	reterr;
8282 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8283 	conn_opt_arg_t	coas;
8284 
8285 	coas.coa_connp = connp;
8286 	coas.coa_ixa = connp->conn_ixa;
8287 	coas.coa_ipp = &connp->conn_xmit_ipp;
8288 	coas.coa_ancillary = B_FALSE;
8289 	coas.coa_changed = 0;
8290 
8291 	switch (optset_context) {
8292 	case SETFN_OPTCOM_CHECKONLY:
8293 		checkonly = B_TRUE;
8294 		/*
8295 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
8296 		 * inlen != 0 implies value supplied and
8297 		 * 	we have to "pretend" to set it.
8298 		 * inlen == 0 implies that there is no
8299 		 * 	value part in T_CHECK request and just validation
8300 		 * done elsewhere should be enough, we just return here.
8301 		 */
8302 		if (inlen == 0) {
8303 			*outlenp = 0;
8304 			return (0);
8305 		}
8306 		break;
8307 	case SETFN_OPTCOM_NEGOTIATE:
8308 		checkonly = B_FALSE;
8309 		break;
8310 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
8311 	case SETFN_CONN_NEGOTIATE:
8312 		checkonly = B_FALSE;
8313 		/*
8314 		 * Negotiating local and "association-related" options
8315 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
8316 		 * primitives is allowed by XTI, but we choose
8317 		 * to not implement this style negotiation for Internet
8318 		 * protocols (We interpret it is a must for OSI world but
8319 		 * optional for Internet protocols) for all options.
8320 		 * [ Will do only for the few options that enable test
8321 		 * suites that our XTI implementation of this feature
8322 		 * works for transports that do allow it ]
8323 		 */
8324 		if (!tcp_allow_connopt_set(level, name)) {
8325 			*outlenp = 0;
8326 			return (EINVAL);
8327 		}
8328 		break;
8329 	default:
8330 		/*
8331 		 * We should never get here
8332 		 */
8333 		*outlenp = 0;
8334 		return (EINVAL);
8335 	}
8336 
8337 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
8338 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
8339 
8340 	/*
8341 	 * For TCP, we should have no ancillary data sent down
8342 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
8343 	 * has to be zero.
8344 	 */
8345 	ASSERT(thisdg_attrs == NULL);
8346 
8347 	/*
8348 	 * For fixed length options, no sanity check
8349 	 * of passed in length is done. It is assumed *_optcom_req()
8350 	 * routines do the right thing.
8351 	 */
8352 	switch (level) {
8353 	case SOL_SOCKET:
8354 		switch (name) {
8355 		case SO_KEEPALIVE:
8356 			if (checkonly) {
8357 				/* check only case */
8358 				break;
8359 			}
8360 
8361 			if (!onoff) {
8362 				if (connp->conn_keepalive) {
8363 					if (tcp->tcp_ka_tid != 0) {
8364 						(void) TCP_TIMER_CANCEL(tcp,
8365 						    tcp->tcp_ka_tid);
8366 						tcp->tcp_ka_tid = 0;
8367 					}
8368 					connp->conn_keepalive = 0;
8369 				}
8370 				break;
8371 			}
8372 			if (!connp->conn_keepalive) {
8373 				/* Crank up the keepalive timer */
8374 				tcp->tcp_ka_last_intrvl = 0;
8375 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8376 				    tcp_keepalive_killer,
8377 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
8378 				connp->conn_keepalive = 1;
8379 			}
8380 			break;
8381 		case SO_SNDBUF: {
8382 			if (*i1 > tcps->tcps_max_buf) {
8383 				*outlenp = 0;
8384 				return (ENOBUFS);
8385 			}
8386 			if (checkonly)
8387 				break;
8388 
8389 			connp->conn_sndbuf = *i1;
8390 			if (tcps->tcps_snd_lowat_fraction != 0) {
8391 				connp->conn_sndlowat = connp->conn_sndbuf /
8392 				    tcps->tcps_snd_lowat_fraction;
8393 			}
8394 			(void) tcp_maxpsz_set(tcp, B_TRUE);
8395 			/*
8396 			 * If we are flow-controlled, recheck the condition.
8397 			 * There are apps that increase SO_SNDBUF size when
8398 			 * flow-controlled (EWOULDBLOCK), and expect the flow
8399 			 * control condition to be lifted right away.
8400 			 */
8401 			mutex_enter(&tcp->tcp_non_sq_lock);
8402 			if (tcp->tcp_flow_stopped &&
8403 			    TCP_UNSENT_BYTES(tcp) < connp->conn_sndbuf) {
8404 				tcp_clrqfull(tcp);
8405 			}
8406 			mutex_exit(&tcp->tcp_non_sq_lock);
8407 			*outlenp = inlen;
8408 			return (0);
8409 		}
8410 		case SO_RCVBUF:
8411 			if (*i1 > tcps->tcps_max_buf) {
8412 				*outlenp = 0;
8413 				return (ENOBUFS);
8414 			}
8415 			/* Silently ignore zero */
8416 			if (!checkonly && *i1 != 0) {
8417 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
8418 				(void) tcp_rwnd_set(tcp, *i1);
8419 			}
8420 			/*
8421 			 * XXX should we return the rwnd here
8422 			 * and tcp_opt_get ?
8423 			 */
8424 			*outlenp = inlen;
8425 			return (0);
8426 		case SO_SND_COPYAVOID:
8427 			if (!checkonly) {
8428 				if (tcp->tcp_loopback ||
8429 				    (tcp->tcp_kssl_ctx != NULL) ||
8430 				    (onoff != 1) || !tcp_zcopy_check(tcp)) {
8431 					*outlenp = 0;
8432 					return (EOPNOTSUPP);
8433 				}
8434 				tcp->tcp_snd_zcopy_aware = 1;
8435 			}
8436 			*outlenp = inlen;
8437 			return (0);
8438 		}
8439 		break;
8440 	case IPPROTO_TCP:
8441 		switch (name) {
8442 		case TCP_NODELAY:
8443 			if (!checkonly)
8444 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
8445 			break;
8446 		case TCP_NOTIFY_THRESHOLD:
8447 			if (!checkonly)
8448 				tcp->tcp_first_timer_threshold = *i1;
8449 			break;
8450 		case TCP_ABORT_THRESHOLD:
8451 			if (!checkonly)
8452 				tcp->tcp_second_timer_threshold = *i1;
8453 			break;
8454 		case TCP_CONN_NOTIFY_THRESHOLD:
8455 			if (!checkonly)
8456 				tcp->tcp_first_ctimer_threshold = *i1;
8457 			break;
8458 		case TCP_CONN_ABORT_THRESHOLD:
8459 			if (!checkonly)
8460 				tcp->tcp_second_ctimer_threshold = *i1;
8461 			break;
8462 		case TCP_RECVDSTADDR:
8463 			if (tcp->tcp_state > TCPS_LISTEN) {
8464 				*outlenp = 0;
8465 				return (EOPNOTSUPP);
8466 			}
8467 			/* Setting done in conn_opt_set */
8468 			break;
8469 		case TCP_INIT_CWND: {
8470 			uint32_t init_cwnd = *((uint32_t *)invalp);
8471 
8472 			if (checkonly)
8473 				break;
8474 
8475 			/*
8476 			 * Only allow socket with network configuration
8477 			 * privilege to set the initial cwnd to be larger
8478 			 * than allowed by RFC 3390.
8479 			 */
8480 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
8481 				tcp->tcp_init_cwnd = init_cwnd;
8482 				break;
8483 			}
8484 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
8485 				*outlenp = 0;
8486 				return (reterr);
8487 			}
8488 			if (init_cwnd > TCP_MAX_INIT_CWND) {
8489 				*outlenp = 0;
8490 				return (EINVAL);
8491 			}
8492 			tcp->tcp_init_cwnd = init_cwnd;
8493 			break;
8494 		}
8495 		case TCP_KEEPALIVE_THRESHOLD:
8496 			if (checkonly)
8497 				break;
8498 
8499 			if (*i1 < tcps->tcps_keepalive_interval_low ||
8500 			    *i1 > tcps->tcps_keepalive_interval_high) {
8501 				*outlenp = 0;
8502 				return (EINVAL);
8503 			}
8504 			if (*i1 != tcp->tcp_ka_interval) {
8505 				tcp->tcp_ka_interval = *i1;
8506 				/*
8507 				 * Check if we need to restart the
8508 				 * keepalive timer.
8509 				 */
8510 				if (tcp->tcp_ka_tid != 0) {
8511 					ASSERT(connp->conn_keepalive);
8512 					(void) TCP_TIMER_CANCEL(tcp,
8513 					    tcp->tcp_ka_tid);
8514 					tcp->tcp_ka_last_intrvl = 0;
8515 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
8516 					    tcp_keepalive_killer,
8517 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
8518 				}
8519 			}
8520 			break;
8521 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
8522 			if (!checkonly) {
8523 				if (*i1 <
8524 				    tcps->tcps_keepalive_abort_interval_low ||
8525 				    *i1 >
8526 				    tcps->tcps_keepalive_abort_interval_high) {
8527 					*outlenp = 0;
8528 					return (EINVAL);
8529 				}
8530 				tcp->tcp_ka_abort_thres = *i1;
8531 			}
8532 			break;
8533 		case TCP_CORK:
8534 			if (!checkonly) {
8535 				/*
8536 				 * if tcp->tcp_cork was set and is now
8537 				 * being unset, we have to make sure that
8538 				 * the remaining data gets sent out. Also
8539 				 * unset tcp->tcp_cork so that tcp_wput_data()
8540 				 * can send data even if it is less than mss
8541 				 */
8542 				if (tcp->tcp_cork && onoff == 0 &&
8543 				    tcp->tcp_unsent > 0) {
8544 					tcp->tcp_cork = B_FALSE;
8545 					tcp_wput_data(tcp, NULL, B_FALSE);
8546 				}
8547 				tcp->tcp_cork = onoff;
8548 			}
8549 			break;
8550 		default:
8551 			break;
8552 		}
8553 		break;
8554 	case IPPROTO_IP:
8555 		if (connp->conn_family != AF_INET) {
8556 			*outlenp = 0;
8557 			return (EINVAL);
8558 		}
8559 		switch (name) {
8560 		case IP_SEC_OPT:
8561 			/*
8562 			 * We should not allow policy setting after
8563 			 * we start listening for connections.
8564 			 */
8565 			if (tcp->tcp_state == TCPS_LISTEN) {
8566 				return (EINVAL);
8567 			}
8568 			break;
8569 		}
8570 		break;
8571 	case IPPROTO_IPV6:
8572 		/*
8573 		 * IPPROTO_IPV6 options are only supported for sockets
8574 		 * that are using IPv6 on the wire.
8575 		 */
8576 		if (connp->conn_ipversion != IPV6_VERSION) {
8577 			*outlenp = 0;
8578 			return (EINVAL);
8579 		}
8580 
8581 		switch (name) {
8582 		case IPV6_RECVPKTINFO:
8583 			if (!checkonly) {
8584 				/* Force it to be sent up with the next msg */
8585 				tcp->tcp_recvifindex = 0;
8586 			}
8587 			break;
8588 		case IPV6_RECVTCLASS:
8589 			if (!checkonly) {
8590 				/* Force it to be sent up with the next msg */
8591 				tcp->tcp_recvtclass = 0xffffffffU;
8592 			}
8593 			break;
8594 		case IPV6_RECVHOPLIMIT:
8595 			if (!checkonly) {
8596 				/* Force it to be sent up with the next msg */
8597 				tcp->tcp_recvhops = 0xffffffffU;
8598 			}
8599 			break;
8600 		case IPV6_PKTINFO:
8601 			/* This is an extra check for TCP */
8602 			if (inlen == sizeof (struct in6_pktinfo)) {
8603 				struct in6_pktinfo *pkti;
8604 
8605 				pkti = (struct in6_pktinfo *)invalp;
8606 				/*
8607 				 * RFC 3542 states that ipi6_addr must be
8608 				 * the unspecified address when setting the
8609 				 * IPV6_PKTINFO sticky socket option on a
8610 				 * TCP socket.
8611 				 */
8612 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
8613 					return (EINVAL);
8614 			}
8615 			break;
8616 		case IPV6_SEC_OPT:
8617 			/*
8618 			 * We should not allow policy setting after
8619 			 * we start listening for connections.
8620 			 */
8621 			if (tcp->tcp_state == TCPS_LISTEN) {
8622 				return (EINVAL);
8623 			}
8624 			break;
8625 		}
8626 		break;
8627 	}
8628 	reterr = conn_opt_set(&coas, level, name, inlen, invalp,
8629 	    checkonly, cr);
8630 	if (reterr != 0) {
8631 		*outlenp = 0;
8632 		return (reterr);
8633 	}
8634 
8635 	/*
8636 	 * Common case of OK return with outval same as inval
8637 	 */
8638 	if (invalp != outvalp) {
8639 		/* don't trust bcopy for identical src/dst */
8640 		(void) bcopy(invalp, outvalp, inlen);
8641 	}
8642 	*outlenp = inlen;
8643 
8644 	if (coas.coa_changed & COA_HEADER_CHANGED) {
8645 		/* If we are connected we rebuilt the headers */
8646 		if (!IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6) &&
8647 		    !IN6_IS_ADDR_V4MAPPED_ANY(&connp->conn_faddr_v6)) {
8648 			reterr = tcp_build_hdrs(tcp);
8649 			if (reterr != 0)
8650 				return (reterr);
8651 		}
8652 	}
8653 	if (coas.coa_changed & COA_ROUTE_CHANGED) {
8654 		in6_addr_t nexthop;
8655 
8656 		/*
8657 		 * If we are connected we re-cache the information.
8658 		 * We ignore errors to preserve BSD behavior.
8659 		 * Note that we don't redo IPsec policy lookup here
8660 		 * since the final destination (or source) didn't change.
8661 		 */
8662 		ip_attr_nexthop(&connp->conn_xmit_ipp, connp->conn_ixa,
8663 		    &connp->conn_faddr_v6, &nexthop);
8664 
8665 		if (!IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6) &&
8666 		    !IN6_IS_ADDR_V4MAPPED_ANY(&connp->conn_faddr_v6)) {
8667 			(void) ip_attr_connect(connp, connp->conn_ixa,
8668 			    &connp->conn_laddr_v6, &connp->conn_faddr_v6,
8669 			    &nexthop, connp->conn_fport, NULL, NULL,
8670 			    IPDF_VERIFY_DST);
8671 		}
8672 	}
8673 	if ((coas.coa_changed & COA_SNDBUF_CHANGED) && !IPCL_IS_NONSTR(connp)) {
8674 		connp->conn_wq->q_hiwat = connp->conn_sndbuf;
8675 	}
8676 	if (coas.coa_changed & COA_WROFF_CHANGED) {
8677 		connp->conn_wroff = connp->conn_ht_iphc_allocated +
8678 		    tcps->tcps_wroff_xtra;
8679 		(void) proto_set_tx_wroff(connp->conn_rq, connp,
8680 		    connp->conn_wroff);
8681 	}
8682 	if (coas.coa_changed & COA_OOBINLINE_CHANGED) {
8683 		if (IPCL_IS_NONSTR(connp))
8684 			proto_set_rx_oob_opt(connp, onoff);
8685 	}
8686 	return (0);
8687 }
8688 
8689 /* ARGSUSED */
8690 int
8691 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
8692     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
8693     void *thisdg_attrs, cred_t *cr)
8694 {
8695 	conn_t	*connp =  Q_TO_CONN(q);
8696 
8697 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
8698 	    outlenp, outvalp, thisdg_attrs, cr));
8699 }
8700 
8701 int
8702 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
8703     const void *optvalp, socklen_t optlen, cred_t *cr)
8704 {
8705 	conn_t		*connp = (conn_t *)proto_handle;
8706 	squeue_t	*sqp = connp->conn_sqp;
8707 	int		error;
8708 
8709 	ASSERT(connp->conn_upper_handle != NULL);
8710 	/*
8711 	 * Entering the squeue synchronously can result in a context switch,
8712 	 * which can cause a rather sever performance degradation. So we try to
8713 	 * handle whatever options we can without entering the squeue.
8714 	 */
8715 	if (level == IPPROTO_TCP) {
8716 		switch (option_name) {
8717 		case TCP_NODELAY:
8718 			if (optlen != sizeof (int32_t))
8719 				return (EINVAL);
8720 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
8721 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
8722 			    connp->conn_tcp->tcp_mss;
8723 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
8724 			return (0);
8725 		default:
8726 			break;
8727 		}
8728 	}
8729 
8730 	error = squeue_synch_enter(sqp, connp, NULL);
8731 	if (error == ENOMEM) {
8732 		return (ENOMEM);
8733 	}
8734 
8735 	error = proto_opt_check(level, option_name, optlen, NULL,
8736 	    tcp_opt_obj.odb_opt_des_arr,
8737 	    tcp_opt_obj.odb_opt_arr_cnt,
8738 	    B_TRUE, B_FALSE, cr);
8739 
8740 	if (error != 0) {
8741 		if (error < 0) {
8742 			error = proto_tlitosyserr(-error);
8743 		}
8744 		squeue_synch_exit(sqp, connp);
8745 		return (error);
8746 	}
8747 
8748 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
8749 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
8750 	    NULL, cr);
8751 	squeue_synch_exit(sqp, connp);
8752 
8753 	ASSERT(error >= 0);
8754 
8755 	return (error);
8756 }
8757 
8758 /*
8759  * Build/update the tcp header template (in conn_ht_iphc) based on
8760  * conn_xmit_ipp. The headers include ip6_t, any extension
8761  * headers, and the maximum size tcp header (to avoid reallocation
8762  * on the fly for additional tcp options).
8763  *
8764  * Assumes the caller has already set conn_{faddr,laddr,fport,lport,flowinfo}.
8765  * Returns failure if can't allocate memory.
8766  */
8767 static int
8768 tcp_build_hdrs(tcp_t *tcp)
8769 {
8770 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8771 	conn_t		*connp = tcp->tcp_connp;
8772 	char		buf[TCP_MAX_HDR_LENGTH];
8773 	uint_t		buflen;
8774 	uint_t		ulplen = TCP_MIN_HEADER_LENGTH;
8775 	uint_t		extralen = TCP_MAX_TCP_OPTIONS_LENGTH;
8776 	tcpha_t		*tcpha;
8777 	uint32_t	cksum;
8778 	int		error;
8779 
8780 	/*
8781 	 * We might be called after the connection is set up, and we might
8782 	 * have TS options already in the TCP header. Thus we  save any
8783 	 * existing tcp header.
8784 	 */
8785 	buflen = connp->conn_ht_ulp_len;
8786 	if (buflen != 0) {
8787 		bcopy(connp->conn_ht_ulp, buf, buflen);
8788 		extralen -= buflen - ulplen;
8789 		ulplen = buflen;
8790 	}
8791 
8792 	/* Grab lock to satisfy ASSERT; TCP is serialized using squeue */
8793 	mutex_enter(&connp->conn_lock);
8794 	error = conn_build_hdr_template(connp, ulplen, extralen,
8795 	    &connp->conn_laddr_v6, &connp->conn_faddr_v6, connp->conn_flowinfo);
8796 	mutex_exit(&connp->conn_lock);
8797 	if (error != 0)
8798 		return (error);
8799 
8800 	/*
8801 	 * Any routing header/option has been massaged. The checksum difference
8802 	 * is stored in conn_sum for later use.
8803 	 */
8804 	tcpha = (tcpha_t *)connp->conn_ht_ulp;
8805 	tcp->tcp_tcpha = tcpha;
8806 
8807 	/* restore any old tcp header */
8808 	if (buflen != 0) {
8809 		bcopy(buf, connp->conn_ht_ulp, buflen);
8810 	} else {
8811 		tcpha->tha_sum = 0;
8812 		tcpha->tha_urp = 0;
8813 		tcpha->tha_ack = 0;
8814 		tcpha->tha_offset_and_reserved = (5 << 4);
8815 		tcpha->tha_lport = connp->conn_lport;
8816 		tcpha->tha_fport = connp->conn_fport;
8817 	}
8818 
8819 	/*
8820 	 * IP wants our header length in the checksum field to
8821 	 * allow it to perform a single pseudo-header+checksum
8822 	 * calculation on behalf of TCP.
8823 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8824 	 */
8825 	cksum = sizeof (tcpha_t) + connp->conn_sum;
8826 	cksum = (cksum >> 16) + (cksum & 0xFFFF);
8827 	ASSERT(cksum < 0x10000);
8828 	tcpha->tha_sum = htons(cksum);
8829 
8830 	if (connp->conn_ipversion == IPV4_VERSION)
8831 		tcp->tcp_ipha = (ipha_t *)connp->conn_ht_iphc;
8832 	else
8833 		tcp->tcp_ip6h = (ip6_t *)connp->conn_ht_iphc;
8834 
8835 	if (connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra >
8836 	    connp->conn_wroff) {
8837 		connp->conn_wroff = connp->conn_ht_iphc_allocated +
8838 		    tcps->tcps_wroff_xtra;
8839 		(void) proto_set_tx_wroff(connp->conn_rq, connp,
8840 		    connp->conn_wroff);
8841 	}
8842 	return (0);
8843 }
8844 
8845 /* Get callback routine passed to nd_load by tcp_param_register */
8846 /* ARGSUSED */
8847 static int
8848 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
8849 {
8850 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
8851 
8852 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
8853 	return (0);
8854 }
8855 
8856 /*
8857  * Walk through the param array specified registering each element with the
8858  * named dispatch handler.
8859  */
8860 static boolean_t
8861 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
8862 {
8863 	for (; cnt-- > 0; tcppa++) {
8864 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
8865 			if (!nd_load(ndp, tcppa->tcp_param_name,
8866 			    tcp_param_get, tcp_param_set,
8867 			    (caddr_t)tcppa)) {
8868 				nd_free(ndp);
8869 				return (B_FALSE);
8870 			}
8871 		}
8872 	}
8873 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
8874 	    KM_SLEEP);
8875 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
8876 	    sizeof (tcpparam_t));
8877 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
8878 	    tcp_param_get, tcp_param_set_aligned,
8879 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
8880 		nd_free(ndp);
8881 		return (B_FALSE);
8882 	}
8883 	if (!nd_load(ndp, "tcp_extra_priv_ports",
8884 	    tcp_extra_priv_ports_get, NULL, NULL)) {
8885 		nd_free(ndp);
8886 		return (B_FALSE);
8887 	}
8888 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
8889 	    NULL, tcp_extra_priv_ports_add, NULL)) {
8890 		nd_free(ndp);
8891 		return (B_FALSE);
8892 	}
8893 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
8894 	    NULL, tcp_extra_priv_ports_del, NULL)) {
8895 		nd_free(ndp);
8896 		return (B_FALSE);
8897 	}
8898 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
8899 	    tcp_1948_phrase_set, NULL)) {
8900 		nd_free(ndp);
8901 		return (B_FALSE);
8902 	}
8903 
8904 
8905 	if (!nd_load(ndp, "tcp_listener_limit_conf",
8906 	    tcp_listener_conf_get, NULL, NULL)) {
8907 		nd_free(ndp);
8908 		return (B_FALSE);
8909 	}
8910 	if (!nd_load(ndp, "tcp_listener_limit_conf_add",
8911 	    NULL, tcp_listener_conf_add, NULL)) {
8912 		nd_free(ndp);
8913 		return (B_FALSE);
8914 	}
8915 	if (!nd_load(ndp, "tcp_listener_limit_conf_del",
8916 	    NULL, tcp_listener_conf_del, NULL)) {
8917 		nd_free(ndp);
8918 		return (B_FALSE);
8919 	}
8920 
8921 	/*
8922 	 * Dummy ndd variables - only to convey obsolescence information
8923 	 * through printing of their name (no get or set routines)
8924 	 * XXX Remove in future releases ?
8925 	 */
8926 	if (!nd_load(ndp,
8927 	    "tcp_close_wait_interval(obsoleted - "
8928 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
8929 		nd_free(ndp);
8930 		return (B_FALSE);
8931 	}
8932 	return (B_TRUE);
8933 }
8934 
8935 /* ndd set routine for tcp_wroff_xtra. */
8936 /* ARGSUSED */
8937 static int
8938 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
8939     cred_t *cr)
8940 {
8941 	long new_value;
8942 	tcpparam_t *tcppa = (tcpparam_t *)cp;
8943 
8944 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
8945 	    new_value < tcppa->tcp_param_min ||
8946 	    new_value > tcppa->tcp_param_max) {
8947 		return (EINVAL);
8948 	}
8949 	/*
8950 	 * Need to make sure new_value is a multiple of 4.  If it is not,
8951 	 * round it up.  For future 64 bit requirement, we actually make it
8952 	 * a multiple of 8.
8953 	 */
8954 	if (new_value & 0x7) {
8955 		new_value = (new_value & ~0x7) + 0x8;
8956 	}
8957 	tcppa->tcp_param_val = new_value;
8958 	return (0);
8959 }
8960 
8961 /* Set callback routine passed to nd_load by tcp_param_register */
8962 /* ARGSUSED */
8963 static int
8964 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
8965 {
8966 	long	new_value;
8967 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
8968 
8969 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
8970 	    new_value < tcppa->tcp_param_min ||
8971 	    new_value > tcppa->tcp_param_max) {
8972 		return (EINVAL);
8973 	}
8974 	tcppa->tcp_param_val = new_value;
8975 	return (0);
8976 }
8977 
8978 static void
8979 tcp_reass_timer(void *arg)
8980 {
8981 	conn_t *connp = (conn_t *)arg;
8982 	tcp_t *tcp = connp->conn_tcp;
8983 
8984 	tcp->tcp_reass_tid = 0;
8985 	if (tcp->tcp_reass_head == NULL)
8986 		return;
8987 	ASSERT(tcp->tcp_reass_tail != NULL);
8988 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
8989 		tcp_sack_remove(tcp->tcp_sack_list,
8990 		    TCP_REASS_END(tcp->tcp_reass_tail), &tcp->tcp_num_sack_blk);
8991 	}
8992 	tcp_close_mpp(&tcp->tcp_reass_head);
8993 	tcp->tcp_reass_tail = NULL;
8994 }
8995 
8996 /*
8997  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
8998  * is filled, return as much as we can.  The message passed in may be
8999  * multi-part, chained using b_cont.  "start" is the starting sequence
9000  * number for this piece.
9001  */
9002 static mblk_t *
9003 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
9004 {
9005 	uint32_t	end;
9006 	mblk_t		*mp1;
9007 	mblk_t		*mp2;
9008 	mblk_t		*next_mp;
9009 	uint32_t	u1;
9010 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9011 
9012 
9013 	/* Walk through all the new pieces. */
9014 	do {
9015 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
9016 		    (uintptr_t)INT_MAX);
9017 		end = start + (int)(mp->b_wptr - mp->b_rptr);
9018 		next_mp = mp->b_cont;
9019 		if (start == end) {
9020 			/* Empty.  Blast it. */
9021 			freeb(mp);
9022 			continue;
9023 		}
9024 		mp->b_cont = NULL;
9025 		TCP_REASS_SET_SEQ(mp, start);
9026 		TCP_REASS_SET_END(mp, end);
9027 		mp1 = tcp->tcp_reass_tail;
9028 		if (!mp1) {
9029 			tcp->tcp_reass_tail = mp;
9030 			tcp->tcp_reass_head = mp;
9031 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
9032 			UPDATE_MIB(&tcps->tcps_mib,
9033 			    tcpInDataUnorderBytes, end - start);
9034 			continue;
9035 		}
9036 		/* New stuff completely beyond tail? */
9037 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
9038 			/* Link it on end. */
9039 			mp1->b_cont = mp;
9040 			tcp->tcp_reass_tail = mp;
9041 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
9042 			UPDATE_MIB(&tcps->tcps_mib,
9043 			    tcpInDataUnorderBytes, end - start);
9044 			continue;
9045 		}
9046 		mp1 = tcp->tcp_reass_head;
9047 		u1 = TCP_REASS_SEQ(mp1);
9048 		/* New stuff at the front? */
9049 		if (SEQ_LT(start, u1)) {
9050 			/* Yes... Check for overlap. */
9051 			mp->b_cont = mp1;
9052 			tcp->tcp_reass_head = mp;
9053 			tcp_reass_elim_overlap(tcp, mp);
9054 			continue;
9055 		}
9056 		/*
9057 		 * The new piece fits somewhere between the head and tail.
9058 		 * We find our slot, where mp1 precedes us and mp2 trails.
9059 		 */
9060 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
9061 			u1 = TCP_REASS_SEQ(mp2);
9062 			if (SEQ_LEQ(start, u1))
9063 				break;
9064 		}
9065 		/* Link ourselves in */
9066 		mp->b_cont = mp2;
9067 		mp1->b_cont = mp;
9068 
9069 		/* Trim overlap with following mblk(s) first */
9070 		tcp_reass_elim_overlap(tcp, mp);
9071 
9072 		/* Trim overlap with preceding mblk */
9073 		tcp_reass_elim_overlap(tcp, mp1);
9074 
9075 	} while (start = end, mp = next_mp);
9076 	mp1 = tcp->tcp_reass_head;
9077 	/* Anything ready to go? */
9078 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
9079 		return (NULL);
9080 	/* Eat what we can off the queue */
9081 	for (;;) {
9082 		mp = mp1->b_cont;
9083 		end = TCP_REASS_END(mp1);
9084 		TCP_REASS_SET_SEQ(mp1, 0);
9085 		TCP_REASS_SET_END(mp1, 0);
9086 		if (!mp) {
9087 			tcp->tcp_reass_tail = NULL;
9088 			break;
9089 		}
9090 		if (end != TCP_REASS_SEQ(mp)) {
9091 			mp1->b_cont = NULL;
9092 			break;
9093 		}
9094 		mp1 = mp;
9095 	}
9096 	mp1 = tcp->tcp_reass_head;
9097 	tcp->tcp_reass_head = mp;
9098 	return (mp1);
9099 }
9100 
9101 /* Eliminate any overlap that mp may have over later mblks */
9102 static void
9103 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
9104 {
9105 	uint32_t	end;
9106 	mblk_t		*mp1;
9107 	uint32_t	u1;
9108 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9109 
9110 	end = TCP_REASS_END(mp);
9111 	while ((mp1 = mp->b_cont) != NULL) {
9112 		u1 = TCP_REASS_SEQ(mp1);
9113 		if (!SEQ_GT(end, u1))
9114 			break;
9115 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
9116 			mp->b_wptr -= end - u1;
9117 			TCP_REASS_SET_END(mp, u1);
9118 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
9119 			UPDATE_MIB(&tcps->tcps_mib,
9120 			    tcpInDataPartDupBytes, end - u1);
9121 			break;
9122 		}
9123 		mp->b_cont = mp1->b_cont;
9124 		TCP_REASS_SET_SEQ(mp1, 0);
9125 		TCP_REASS_SET_END(mp1, 0);
9126 		freeb(mp1);
9127 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
9128 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
9129 	}
9130 	if (!mp1)
9131 		tcp->tcp_reass_tail = mp;
9132 }
9133 
9134 static uint_t
9135 tcp_rwnd_reopen(tcp_t *tcp)
9136 {
9137 	uint_t ret = 0;
9138 	uint_t thwin;
9139 	conn_t *connp = tcp->tcp_connp;
9140 
9141 	/* Learn the latest rwnd information that we sent to the other side. */
9142 	thwin = ((uint_t)ntohs(tcp->tcp_tcpha->tha_win))
9143 	    << tcp->tcp_rcv_ws;
9144 	/* This is peer's calculated send window (our receive window). */
9145 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
9146 	/*
9147 	 * Increase the receive window to max.  But we need to do receiver
9148 	 * SWS avoidance.  This means that we need to check the increase of
9149 	 * of receive window is at least 1 MSS.
9150 	 */
9151 	if (connp->conn_rcvbuf - thwin >= tcp->tcp_mss) {
9152 		/*
9153 		 * If the window that the other side knows is less than max
9154 		 * deferred acks segments, send an update immediately.
9155 		 */
9156 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
9157 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
9158 			ret = TH_ACK_NEEDED;
9159 		}
9160 		tcp->tcp_rwnd = connp->conn_rcvbuf;
9161 	}
9162 	return (ret);
9163 }
9164 
9165 /*
9166  * Send up all messages queued on tcp_rcv_list.
9167  */
9168 static uint_t
9169 tcp_rcv_drain(tcp_t *tcp)
9170 {
9171 	mblk_t *mp;
9172 	uint_t ret = 0;
9173 #ifdef DEBUG
9174 	uint_t cnt = 0;
9175 #endif
9176 	queue_t	*q = tcp->tcp_connp->conn_rq;
9177 
9178 	/* Can't drain on an eager connection */
9179 	if (tcp->tcp_listener != NULL)
9180 		return (ret);
9181 
9182 	/* Can't be a non-STREAMS connection */
9183 	ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
9184 
9185 	/* No need for the push timer now. */
9186 	if (tcp->tcp_push_tid != 0) {
9187 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
9188 		tcp->tcp_push_tid = 0;
9189 	}
9190 
9191 	/*
9192 	 * Handle two cases here: we are currently fused or we were
9193 	 * previously fused and have some urgent data to be delivered
9194 	 * upstream.  The latter happens because we either ran out of
9195 	 * memory or were detached and therefore sending the SIGURG was
9196 	 * deferred until this point.  In either case we pass control
9197 	 * over to tcp_fuse_rcv_drain() since it may need to complete
9198 	 * some work.
9199 	 */
9200 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
9201 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
9202 		    tcp->tcp_fused_sigurg_mp != NULL);
9203 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
9204 		    &tcp->tcp_fused_sigurg_mp))
9205 			return (ret);
9206 	}
9207 
9208 	while ((mp = tcp->tcp_rcv_list) != NULL) {
9209 		tcp->tcp_rcv_list = mp->b_next;
9210 		mp->b_next = NULL;
9211 #ifdef DEBUG
9212 		cnt += msgdsize(mp);
9213 #endif
9214 		/* Does this need SSL processing first? */
9215 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
9216 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
9217 			    mblk_t *, mp);
9218 			tcp_kssl_input(tcp, mp, NULL);
9219 			continue;
9220 		}
9221 		putnext(q, mp);
9222 	}
9223 #ifdef DEBUG
9224 	ASSERT(cnt == tcp->tcp_rcv_cnt);
9225 #endif
9226 	tcp->tcp_rcv_last_head = NULL;
9227 	tcp->tcp_rcv_last_tail = NULL;
9228 	tcp->tcp_rcv_cnt = 0;
9229 
9230 	if (canputnext(q))
9231 		return (tcp_rwnd_reopen(tcp));
9232 
9233 	return (ret);
9234 }
9235 
9236 /*
9237  * Queue data on tcp_rcv_list which is a b_next chain.
9238  * tcp_rcv_last_head/tail is the last element of this chain.
9239  * Each element of the chain is a b_cont chain.
9240  *
9241  * M_DATA messages are added to the current element.
9242  * Other messages are added as new (b_next) elements.
9243  */
9244 void
9245 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len, cred_t *cr)
9246 {
9247 	ASSERT(seg_len == msgdsize(mp));
9248 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
9249 
9250 	if (is_system_labeled()) {
9251 		ASSERT(cr != NULL || msg_getcred(mp, NULL) != NULL);
9252 		/*
9253 		 * Provide for protocols above TCP such as RPC. NOPID leaves
9254 		 * db_cpid unchanged.
9255 		 * The cred could have already been set.
9256 		 */
9257 		if (cr != NULL)
9258 			mblk_setcred(mp, cr, NOPID);
9259 	}
9260 
9261 	if (tcp->tcp_rcv_list == NULL) {
9262 		ASSERT(tcp->tcp_rcv_last_head == NULL);
9263 		tcp->tcp_rcv_list = mp;
9264 		tcp->tcp_rcv_last_head = mp;
9265 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
9266 		tcp->tcp_rcv_last_tail->b_cont = mp;
9267 	} else {
9268 		tcp->tcp_rcv_last_head->b_next = mp;
9269 		tcp->tcp_rcv_last_head = mp;
9270 	}
9271 
9272 	while (mp->b_cont)
9273 		mp = mp->b_cont;
9274 
9275 	tcp->tcp_rcv_last_tail = mp;
9276 	tcp->tcp_rcv_cnt += seg_len;
9277 	tcp->tcp_rwnd -= seg_len;
9278 }
9279 
9280 /* The minimum of smoothed mean deviation in RTO calculation. */
9281 #define	TCP_SD_MIN	400
9282 
9283 /*
9284  * Set RTO for this connection.  The formula is from Jacobson and Karels'
9285  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
9286  * are the same as those in Appendix A.2 of that paper.
9287  *
9288  * m = new measurement
9289  * sa = smoothed RTT average (8 * average estimates).
9290  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
9291  */
9292 static void
9293 tcp_set_rto(tcp_t *tcp, clock_t rtt)
9294 {
9295 	long m = TICK_TO_MSEC(rtt);
9296 	clock_t sa = tcp->tcp_rtt_sa;
9297 	clock_t sv = tcp->tcp_rtt_sd;
9298 	clock_t rto;
9299 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9300 
9301 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
9302 	tcp->tcp_rtt_update++;
9303 
9304 	/* tcp_rtt_sa is not 0 means this is a new sample. */
9305 	if (sa != 0) {
9306 		/*
9307 		 * Update average estimator:
9308 		 *	new rtt = 7/8 old rtt + 1/8 Error
9309 		 */
9310 
9311 		/* m is now Error in estimate. */
9312 		m -= sa >> 3;
9313 		if ((sa += m) <= 0) {
9314 			/*
9315 			 * Don't allow the smoothed average to be negative.
9316 			 * We use 0 to denote reinitialization of the
9317 			 * variables.
9318 			 */
9319 			sa = 1;
9320 		}
9321 
9322 		/*
9323 		 * Update deviation estimator:
9324 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
9325 		 */
9326 		if (m < 0)
9327 			m = -m;
9328 		m -= sv >> 2;
9329 		sv += m;
9330 	} else {
9331 		/*
9332 		 * This follows BSD's implementation.  So the reinitialized
9333 		 * RTO is 3 * m.  We cannot go less than 2 because if the
9334 		 * link is bandwidth dominated, doubling the window size
9335 		 * during slow start means doubling the RTT.  We want to be
9336 		 * more conservative when we reinitialize our estimates.  3
9337 		 * is just a convenient number.
9338 		 */
9339 		sa = m << 3;
9340 		sv = m << 1;
9341 	}
9342 	if (sv < TCP_SD_MIN) {
9343 		/*
9344 		 * We do not know that if sa captures the delay ACK
9345 		 * effect as in a long train of segments, a receiver
9346 		 * does not delay its ACKs.  So set the minimum of sv
9347 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
9348 		 * of BSD DATO.  That means the minimum of mean
9349 		 * deviation is 100 ms.
9350 		 *
9351 		 */
9352 		sv = TCP_SD_MIN;
9353 	}
9354 	tcp->tcp_rtt_sa = sa;
9355 	tcp->tcp_rtt_sd = sv;
9356 	/*
9357 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
9358 	 *
9359 	 * Add tcp_rexmit_interval extra in case of extreme environment
9360 	 * where the algorithm fails to work.  The default value of
9361 	 * tcp_rexmit_interval_extra should be 0.
9362 	 *
9363 	 * As we use a finer grained clock than BSD and update
9364 	 * RTO for every ACKs, add in another .25 of RTT to the
9365 	 * deviation of RTO to accomodate burstiness of 1/4 of
9366 	 * window size.
9367 	 */
9368 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
9369 
9370 	if (rto > tcps->tcps_rexmit_interval_max) {
9371 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
9372 	} else if (rto < tcps->tcps_rexmit_interval_min) {
9373 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
9374 	} else {
9375 		tcp->tcp_rto = rto;
9376 	}
9377 
9378 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
9379 	tcp->tcp_timer_backoff = 0;
9380 }
9381 
9382 /*
9383  * tcp_get_seg_mp() is called to get the pointer to a segment in the
9384  * send queue which starts at the given sequence number. If the given
9385  * sequence number is equal to last valid sequence number (tcp_snxt), the
9386  * returned mblk is the last valid mblk, and off is set to the length of
9387  * that mblk.
9388  *
9389  * send queue which starts at the given seq. no.
9390  *
9391  * Parameters:
9392  *	tcp_t *tcp: the tcp instance pointer.
9393  *	uint32_t seq: the starting seq. no of the requested segment.
9394  *	int32_t *off: after the execution, *off will be the offset to
9395  *		the returned mblk which points to the requested seq no.
9396  *		It is the caller's responsibility to send in a non-null off.
9397  *
9398  * Return:
9399  *	A mblk_t pointer pointing to the requested segment in send queue.
9400  */
9401 static mblk_t *
9402 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
9403 {
9404 	int32_t	cnt;
9405 	mblk_t	*mp;
9406 
9407 	/* Defensive coding.  Make sure we don't send incorrect data. */
9408 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GT(seq, tcp->tcp_snxt))
9409 		return (NULL);
9410 
9411 	cnt = seq - tcp->tcp_suna;
9412 	mp = tcp->tcp_xmit_head;
9413 	while (cnt > 0 && mp != NULL) {
9414 		cnt -= mp->b_wptr - mp->b_rptr;
9415 		if (cnt <= 0) {
9416 			cnt += mp->b_wptr - mp->b_rptr;
9417 			break;
9418 		}
9419 		mp = mp->b_cont;
9420 	}
9421 	ASSERT(mp != NULL);
9422 	*off = cnt;
9423 	return (mp);
9424 }
9425 
9426 /*
9427  * This function handles all retransmissions if SACK is enabled for this
9428  * connection.  First it calculates how many segments can be retransmitted
9429  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
9430  * segments.  A segment is eligible if sack_cnt for that segment is greater
9431  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
9432  * all eligible segments, it checks to see if TCP can send some new segments
9433  * (fast recovery).  If it can, set the appropriate flag for tcp_input_data().
9434  *
9435  * Parameters:
9436  *	tcp_t *tcp: the tcp structure of the connection.
9437  *	uint_t *flags: in return, appropriate value will be set for
9438  *	tcp_input_data().
9439  */
9440 static void
9441 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
9442 {
9443 	notsack_blk_t	*notsack_blk;
9444 	int32_t		usable_swnd;
9445 	int32_t		mss;
9446 	uint32_t	seg_len;
9447 	mblk_t		*xmit_mp;
9448 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9449 
9450 	ASSERT(tcp->tcp_sack_info != NULL);
9451 	ASSERT(tcp->tcp_notsack_list != NULL);
9452 	ASSERT(tcp->tcp_rexmit == B_FALSE);
9453 
9454 	/* Defensive coding in case there is a bug... */
9455 	if (tcp->tcp_notsack_list == NULL) {
9456 		return;
9457 	}
9458 	notsack_blk = tcp->tcp_notsack_list;
9459 	mss = tcp->tcp_mss;
9460 
9461 	/*
9462 	 * Limit the num of outstanding data in the network to be
9463 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
9464 	 */
9465 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
9466 
9467 	/* At least retransmit 1 MSS of data. */
9468 	if (usable_swnd <= 0) {
9469 		usable_swnd = mss;
9470 	}
9471 
9472 	/* Make sure no new RTT samples will be taken. */
9473 	tcp->tcp_csuna = tcp->tcp_snxt;
9474 
9475 	notsack_blk = tcp->tcp_notsack_list;
9476 	while (usable_swnd > 0) {
9477 		mblk_t		*snxt_mp, *tmp_mp;
9478 		tcp_seq		begin = tcp->tcp_sack_snxt;
9479 		tcp_seq		end;
9480 		int32_t		off;
9481 
9482 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
9483 			if (SEQ_GT(notsack_blk->end, begin) &&
9484 			    (notsack_blk->sack_cnt >=
9485 			    tcps->tcps_dupack_fast_retransmit)) {
9486 				end = notsack_blk->end;
9487 				if (SEQ_LT(begin, notsack_blk->begin)) {
9488 					begin = notsack_blk->begin;
9489 				}
9490 				break;
9491 			}
9492 		}
9493 		/*
9494 		 * All holes are filled.  Manipulate tcp_cwnd to send more
9495 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
9496 		 * set to tcp_cwnd_ssthresh.
9497 		 */
9498 		if (notsack_blk == NULL) {
9499 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
9500 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
9501 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
9502 				ASSERT(tcp->tcp_cwnd > 0);
9503 				return;
9504 			} else {
9505 				usable_swnd = usable_swnd / mss;
9506 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
9507 				    MAX(usable_swnd * mss, mss);
9508 				*flags |= TH_XMIT_NEEDED;
9509 				return;
9510 			}
9511 		}
9512 
9513 		/*
9514 		 * Note that we may send more than usable_swnd allows here
9515 		 * because of round off, but no more than 1 MSS of data.
9516 		 */
9517 		seg_len = end - begin;
9518 		if (seg_len > mss)
9519 			seg_len = mss;
9520 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
9521 		ASSERT(snxt_mp != NULL);
9522 		/* This should not happen.  Defensive coding again... */
9523 		if (snxt_mp == NULL) {
9524 			return;
9525 		}
9526 
9527 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
9528 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
9529 		if (xmit_mp == NULL)
9530 			return;
9531 
9532 		usable_swnd -= seg_len;
9533 		tcp->tcp_pipe += seg_len;
9534 		tcp->tcp_sack_snxt = begin + seg_len;
9535 
9536 		tcp_send_data(tcp, xmit_mp);
9537 
9538 		/*
9539 		 * Update the send timestamp to avoid false retransmission.
9540 		 */
9541 		snxt_mp->b_prev = (mblk_t *)ddi_get_lbolt();
9542 
9543 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
9544 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
9545 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
9546 		/*
9547 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
9548 		 * This happens when new data sent during fast recovery is
9549 		 * also lost.  If TCP retransmits those new data, it needs
9550 		 * to extend SACK recover phase to avoid starting another
9551 		 * fast retransmit/recovery unnecessarily.
9552 		 */
9553 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
9554 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
9555 		}
9556 	}
9557 }
9558 
9559 /*
9560  * tcp_ss_rexmit() is called to do slow start retransmission after a timeout
9561  * or ICMP errors.
9562  *
9563  * To limit the number of duplicate segments, we limit the number of segment
9564  * to be sent in one time to tcp_snd_burst, the burst variable.
9565  */
9566 static void
9567 tcp_ss_rexmit(tcp_t *tcp)
9568 {
9569 	uint32_t	snxt;
9570 	uint32_t	smax;
9571 	int32_t		win;
9572 	int32_t		mss;
9573 	int32_t		off;
9574 	int32_t		burst = tcp->tcp_snd_burst;
9575 	mblk_t		*snxt_mp;
9576 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9577 
9578 	/*
9579 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
9580 	 * all unack'ed segments.
9581 	 */
9582 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
9583 		smax = tcp->tcp_rexmit_max;
9584 		snxt = tcp->tcp_rexmit_nxt;
9585 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
9586 			snxt = tcp->tcp_suna;
9587 		}
9588 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
9589 		win -= snxt - tcp->tcp_suna;
9590 		mss = tcp->tcp_mss;
9591 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
9592 
9593 		while (SEQ_LT(snxt, smax) && (win > 0) &&
9594 		    (burst > 0) && (snxt_mp != NULL)) {
9595 			mblk_t	*xmit_mp;
9596 			mblk_t	*old_snxt_mp = snxt_mp;
9597 			uint32_t cnt = mss;
9598 
9599 			if (win < cnt) {
9600 				cnt = win;
9601 			}
9602 			if (SEQ_GT(snxt + cnt, smax)) {
9603 				cnt = smax - snxt;
9604 			}
9605 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
9606 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
9607 			if (xmit_mp == NULL)
9608 				return;
9609 
9610 			tcp_send_data(tcp, xmit_mp);
9611 
9612 			snxt += cnt;
9613 			win -= cnt;
9614 			/*
9615 			 * Update the send timestamp to avoid false
9616 			 * retransmission.
9617 			 */
9618 			old_snxt_mp->b_prev = (mblk_t *)ddi_get_lbolt();
9619 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
9620 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
9621 
9622 			tcp->tcp_rexmit_nxt = snxt;
9623 			burst--;
9624 		}
9625 		/*
9626 		 * If we have transmitted all we have at the time
9627 		 * we started the retranmission, we can leave
9628 		 * the rest of the job to tcp_wput_data().  But we
9629 		 * need to check the send window first.  If the
9630 		 * win is not 0, go on with tcp_wput_data().
9631 		 */
9632 		if (SEQ_LT(snxt, smax) || win == 0) {
9633 			return;
9634 		}
9635 	}
9636 	/* Only call tcp_wput_data() if there is data to be sent. */
9637 	if (tcp->tcp_unsent) {
9638 		tcp_wput_data(tcp, NULL, B_FALSE);
9639 	}
9640 }
9641 
9642 /*
9643  * Process all TCP option in SYN segment.  Note that this function should
9644  * be called after tcp_set_destination() is called so that the necessary info
9645  * from IRE is already set in the tcp structure.
9646  *
9647  * This function sets up the correct tcp_mss value according to the
9648  * MSS option value and our header size.  It also sets up the window scale
9649  * and timestamp values, and initialize SACK info blocks.  But it does not
9650  * change receive window size after setting the tcp_mss value.  The caller
9651  * should do the appropriate change.
9652  */
9653 void
9654 tcp_process_options(tcp_t *tcp, tcpha_t *tcpha)
9655 {
9656 	int options;
9657 	tcp_opt_t tcpopt;
9658 	uint32_t mss_max;
9659 	char *tmp_tcph;
9660 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9661 	conn_t		*connp = tcp->tcp_connp;
9662 
9663 	tcpopt.tcp = NULL;
9664 	options = tcp_parse_options(tcpha, &tcpopt);
9665 
9666 	/*
9667 	 * Process MSS option.  Note that MSS option value does not account
9668 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
9669 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
9670 	 * IPv6.
9671 	 */
9672 	if (!(options & TCP_OPT_MSS_PRESENT)) {
9673 		if (connp->conn_ipversion == IPV4_VERSION)
9674 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
9675 		else
9676 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
9677 	} else {
9678 		if (connp->conn_ipversion == IPV4_VERSION)
9679 			mss_max = tcps->tcps_mss_max_ipv4;
9680 		else
9681 			mss_max = tcps->tcps_mss_max_ipv6;
9682 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
9683 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
9684 		else if (tcpopt.tcp_opt_mss > mss_max)
9685 			tcpopt.tcp_opt_mss = mss_max;
9686 	}
9687 
9688 	/* Process Window Scale option. */
9689 	if (options & TCP_OPT_WSCALE_PRESENT) {
9690 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
9691 		tcp->tcp_snd_ws_ok = B_TRUE;
9692 	} else {
9693 		tcp->tcp_snd_ws = B_FALSE;
9694 		tcp->tcp_snd_ws_ok = B_FALSE;
9695 		tcp->tcp_rcv_ws = B_FALSE;
9696 	}
9697 
9698 	/* Process Timestamp option. */
9699 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
9700 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
9701 		tmp_tcph = (char *)tcp->tcp_tcpha;
9702 
9703 		tcp->tcp_snd_ts_ok = B_TRUE;
9704 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
9705 		tcp->tcp_last_rcv_lbolt = ddi_get_lbolt64();
9706 		ASSERT(OK_32PTR(tmp_tcph));
9707 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
9708 
9709 		/* Fill in our template header with basic timestamp option. */
9710 		tmp_tcph += connp->conn_ht_ulp_len;
9711 		tmp_tcph[0] = TCPOPT_NOP;
9712 		tmp_tcph[1] = TCPOPT_NOP;
9713 		tmp_tcph[2] = TCPOPT_TSTAMP;
9714 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
9715 		connp->conn_ht_iphc_len += TCPOPT_REAL_TS_LEN;
9716 		connp->conn_ht_ulp_len += TCPOPT_REAL_TS_LEN;
9717 		tcp->tcp_tcpha->tha_offset_and_reserved += (3 << 4);
9718 	} else {
9719 		tcp->tcp_snd_ts_ok = B_FALSE;
9720 	}
9721 
9722 	/*
9723 	 * Process SACK options.  If SACK is enabled for this connection,
9724 	 * then allocate the SACK info structure.  Note the following ways
9725 	 * when tcp_snd_sack_ok is set to true.
9726 	 *
9727 	 * For active connection: in tcp_set_destination() called in
9728 	 * tcp_connect().
9729 	 *
9730 	 * For passive connection: in tcp_set_destination() called in
9731 	 * tcp_input_listener().
9732 	 *
9733 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
9734 	 * That check makes sure that if we did not send a SACK OK option,
9735 	 * we will not enable SACK for this connection even though the other
9736 	 * side sends us SACK OK option.  For active connection, the SACK
9737 	 * info structure has already been allocated.  So we need to free
9738 	 * it if SACK is disabled.
9739 	 */
9740 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
9741 	    (tcp->tcp_snd_sack_ok ||
9742 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
9743 		/* This should be true only in the passive case. */
9744 		if (tcp->tcp_sack_info == NULL) {
9745 			ASSERT(TCP_IS_DETACHED(tcp));
9746 			tcp->tcp_sack_info =
9747 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
9748 		}
9749 		if (tcp->tcp_sack_info == NULL) {
9750 			tcp->tcp_snd_sack_ok = B_FALSE;
9751 		} else {
9752 			tcp->tcp_snd_sack_ok = B_TRUE;
9753 			if (tcp->tcp_snd_ts_ok) {
9754 				tcp->tcp_max_sack_blk = 3;
9755 			} else {
9756 				tcp->tcp_max_sack_blk = 4;
9757 			}
9758 		}
9759 	} else {
9760 		/*
9761 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
9762 		 * no SACK info will be used for this
9763 		 * connection.  This assumes that SACK usage
9764 		 * permission is negotiated.  This may need
9765 		 * to be changed once this is clarified.
9766 		 */
9767 		if (tcp->tcp_sack_info != NULL) {
9768 			ASSERT(tcp->tcp_notsack_list == NULL);
9769 			kmem_cache_free(tcp_sack_info_cache,
9770 			    tcp->tcp_sack_info);
9771 			tcp->tcp_sack_info = NULL;
9772 		}
9773 		tcp->tcp_snd_sack_ok = B_FALSE;
9774 	}
9775 
9776 	/*
9777 	 * Now we know the exact TCP/IP header length, subtract
9778 	 * that from tcp_mss to get our side's MSS.
9779 	 */
9780 	tcp->tcp_mss -= connp->conn_ht_iphc_len;
9781 
9782 	/*
9783 	 * Here we assume that the other side's header size will be equal to
9784 	 * our header size.  We calculate the real MSS accordingly.  Need to
9785 	 * take into additional stuffs IPsec puts in.
9786 	 *
9787 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
9788 	 */
9789 	tcpopt.tcp_opt_mss -= connp->conn_ht_iphc_len +
9790 	    tcp->tcp_ipsec_overhead -
9791 	    ((connp->conn_ipversion == IPV4_VERSION ?
9792 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
9793 
9794 	/*
9795 	 * Set MSS to the smaller one of both ends of the connection.
9796 	 * We should not have called tcp_mss_set() before, but our
9797 	 * side of the MSS should have been set to a proper value
9798 	 * by tcp_set_destination().  tcp_mss_set() will also set up the
9799 	 * STREAM head parameters properly.
9800 	 *
9801 	 * If we have a larger-than-16-bit window but the other side
9802 	 * didn't want to do window scale, tcp_rwnd_set() will take
9803 	 * care of that.
9804 	 */
9805 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
9806 
9807 	/*
9808 	 * Initialize tcp_cwnd value. After tcp_mss_set(), tcp_mss has been
9809 	 * updated properly.
9810 	 */
9811 	SET_TCP_INIT_CWND(tcp, tcp->tcp_mss, tcps->tcps_slow_start_initial);
9812 }
9813 
9814 /*
9815  * Sends the T_CONN_IND to the listener. The caller calls this
9816  * functions via squeue to get inside the listener's perimeter
9817  * once the 3 way hand shake is done a T_CONN_IND needs to be
9818  * sent. As an optimization, the caller can call this directly
9819  * if listener's perimeter is same as eager's.
9820  */
9821 /* ARGSUSED */
9822 void
9823 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
9824 {
9825 	conn_t			*lconnp = (conn_t *)arg;
9826 	tcp_t			*listener = lconnp->conn_tcp;
9827 	tcp_t			*tcp;
9828 	struct T_conn_ind	*conn_ind;
9829 	ipaddr_t 		*addr_cache;
9830 	boolean_t		need_send_conn_ind = B_FALSE;
9831 	tcp_stack_t		*tcps = listener->tcp_tcps;
9832 
9833 	/* retrieve the eager */
9834 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
9835 	ASSERT(conn_ind->OPT_offset != 0 &&
9836 	    conn_ind->OPT_length == sizeof (intptr_t));
9837 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
9838 	    conn_ind->OPT_length);
9839 
9840 	/*
9841 	 * TLI/XTI applications will get confused by
9842 	 * sending eager as an option since it violates
9843 	 * the option semantics. So remove the eager as
9844 	 * option since TLI/XTI app doesn't need it anyway.
9845 	 */
9846 	if (!TCP_IS_SOCKET(listener)) {
9847 		conn_ind->OPT_length = 0;
9848 		conn_ind->OPT_offset = 0;
9849 	}
9850 	if (listener->tcp_state != TCPS_LISTEN) {
9851 		/*
9852 		 * If listener has closed, it would have caused a
9853 		 * a cleanup/blowoff to happen for the eager. We
9854 		 * just need to return.
9855 		 */
9856 		freemsg(mp);
9857 		return;
9858 	}
9859 
9860 
9861 	/*
9862 	 * if the conn_req_q is full defer passing up the
9863 	 * T_CONN_IND until space is availabe after t_accept()
9864 	 * processing
9865 	 */
9866 	mutex_enter(&listener->tcp_eager_lock);
9867 
9868 	/*
9869 	 * Take the eager out, if it is in the list of droppable eagers
9870 	 * as we are here because the 3W handshake is over.
9871 	 */
9872 	MAKE_UNDROPPABLE(tcp);
9873 
9874 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
9875 		tcp_t *tail;
9876 
9877 		/*
9878 		 * The eager already has an extra ref put in tcp_input_data
9879 		 * so that it stays till accept comes back even though it
9880 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
9881 		 */
9882 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
9883 		listener->tcp_conn_req_cnt_q0--;
9884 		listener->tcp_conn_req_cnt_q++;
9885 
9886 		/* Move from SYN_RCVD to ESTABLISHED list  */
9887 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
9888 		    tcp->tcp_eager_prev_q0;
9889 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
9890 		    tcp->tcp_eager_next_q0;
9891 		tcp->tcp_eager_prev_q0 = NULL;
9892 		tcp->tcp_eager_next_q0 = NULL;
9893 
9894 		/*
9895 		 * Insert at end of the queue because sockfs
9896 		 * sends down T_CONN_RES in chronological
9897 		 * order. Leaving the older conn indications
9898 		 * at front of the queue helps reducing search
9899 		 * time.
9900 		 */
9901 		tail = listener->tcp_eager_last_q;
9902 		if (tail != NULL)
9903 			tail->tcp_eager_next_q = tcp;
9904 		else
9905 			listener->tcp_eager_next_q = tcp;
9906 		listener->tcp_eager_last_q = tcp;
9907 		tcp->tcp_eager_next_q = NULL;
9908 		/*
9909 		 * Delay sending up the T_conn_ind until we are
9910 		 * done with the eager. Once we have have sent up
9911 		 * the T_conn_ind, the accept can potentially complete
9912 		 * any time and release the refhold we have on the eager.
9913 		 */
9914 		need_send_conn_ind = B_TRUE;
9915 	} else {
9916 		/*
9917 		 * Defer connection on q0 and set deferred
9918 		 * connection bit true
9919 		 */
9920 		tcp->tcp_conn_def_q0 = B_TRUE;
9921 
9922 		/* take tcp out of q0 ... */
9923 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
9924 		    tcp->tcp_eager_next_q0;
9925 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
9926 		    tcp->tcp_eager_prev_q0;
9927 
9928 		/* ... and place it at the end of q0 */
9929 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
9930 		tcp->tcp_eager_next_q0 = listener;
9931 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
9932 		listener->tcp_eager_prev_q0 = tcp;
9933 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
9934 	}
9935 
9936 	/* we have timed out before */
9937 	if (tcp->tcp_syn_rcvd_timeout != 0) {
9938 		tcp->tcp_syn_rcvd_timeout = 0;
9939 		listener->tcp_syn_rcvd_timeout--;
9940 		if (listener->tcp_syn_defense &&
9941 		    listener->tcp_syn_rcvd_timeout <=
9942 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
9943 		    10*MINUTES < TICK_TO_MSEC(ddi_get_lbolt64() -
9944 		    listener->tcp_last_rcv_lbolt)) {
9945 			/*
9946 			 * Turn off the defense mode if we
9947 			 * believe the SYN attack is over.
9948 			 */
9949 			listener->tcp_syn_defense = B_FALSE;
9950 			if (listener->tcp_ip_addr_cache) {
9951 				kmem_free((void *)listener->tcp_ip_addr_cache,
9952 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
9953 				listener->tcp_ip_addr_cache = NULL;
9954 			}
9955 		}
9956 	}
9957 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
9958 	if (addr_cache != NULL) {
9959 		/*
9960 		 * We have finished a 3-way handshake with this
9961 		 * remote host. This proves the IP addr is good.
9962 		 * Cache it!
9963 		 */
9964 		addr_cache[IP_ADDR_CACHE_HASH(tcp->tcp_connp->conn_faddr_v4)] =
9965 		    tcp->tcp_connp->conn_faddr_v4;
9966 	}
9967 	mutex_exit(&listener->tcp_eager_lock);
9968 	if (need_send_conn_ind)
9969 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
9970 }
9971 
9972 /*
9973  * Send the newconn notification to ulp. The eager is blown off if the
9974  * notification fails.
9975  */
9976 static void
9977 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
9978 {
9979 	if (IPCL_IS_NONSTR(lconnp)) {
9980 		cred_t	*cr;
9981 		pid_t	cpid = NOPID;
9982 
9983 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
9984 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
9985 		    lconnp->conn_tcp);
9986 
9987 		cr = msg_getcred(mp, &cpid);
9988 
9989 		/* Keep the message around in case of a fallback to TPI */
9990 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
9991 		/*
9992 		 * Notify the ULP about the newconn. It is guaranteed that no
9993 		 * tcp_accept() call will be made for the eager if the
9994 		 * notification fails, so it's safe to blow it off in that
9995 		 * case.
9996 		 *
9997 		 * The upper handle will be assigned when tcp_accept() is
9998 		 * called.
9999 		 */
10000 		if ((*lconnp->conn_upcalls->su_newconn)
10001 		    (lconnp->conn_upper_handle,
10002 		    (sock_lower_handle_t)econnp,
10003 		    &sock_tcp_downcalls, cr, cpid,
10004 		    &econnp->conn_upcalls) == NULL) {
10005 			/* Failed to allocate a socket */
10006 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
10007 			    tcpEstabResets);
10008 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
10009 			    econnp->conn_tcp->tcp_conn_req_seqnum);
10010 		}
10011 	} else {
10012 		putnext(lconnp->conn_rq, mp);
10013 	}
10014 }
10015 
10016 /*
10017  * Handle a packet that has been reclassified by TCP.
10018  * This function drops the ref on connp that the caller had.
10019  */
10020 static void
10021 tcp_reinput(conn_t *connp, mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst)
10022 {
10023 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
10024 
10025 	if (connp->conn_incoming_ifindex != 0 &&
10026 	    connp->conn_incoming_ifindex != ira->ira_ruifindex) {
10027 		freemsg(mp);
10028 		CONN_DEC_REF(connp);
10029 		return;
10030 	}
10031 
10032 	if (CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss) ||
10033 	    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
10034 		ip6_t *ip6h;
10035 		ipha_t *ipha;
10036 
10037 		if (ira->ira_flags & IRAF_IS_IPV4) {
10038 			ipha = (ipha_t *)mp->b_rptr;
10039 			ip6h = NULL;
10040 		} else {
10041 			ipha = NULL;
10042 			ip6h = (ip6_t *)mp->b_rptr;
10043 		}
10044 		mp = ipsec_check_inbound_policy(mp, connp, ipha, ip6h, ira);
10045 		if (mp == NULL) {
10046 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
10047 			/* Note that mp is NULL */
10048 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
10049 			CONN_DEC_REF(connp);
10050 			return;
10051 		}
10052 	}
10053 
10054 	if (IPCL_IS_TCP(connp)) {
10055 		/*
10056 		 * do not drain, certain use cases can blow
10057 		 * the stack
10058 		 */
10059 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
10060 		    connp->conn_recv, connp, ira,
10061 		    SQ_NODRAIN, SQTAG_IP_TCP_INPUT);
10062 	} else {
10063 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
10064 		(connp->conn_recv)(connp, mp, NULL,
10065 		    ira);
10066 		CONN_DEC_REF(connp);
10067 	}
10068 
10069 }
10070 
10071 boolean_t tcp_outbound_squeue_switch = B_FALSE;
10072 
10073 /*
10074  * Handle M_DATA messages from IP. Its called directly from IP via
10075  * squeue for received IP packets.
10076  *
10077  * The first argument is always the connp/tcp to which the mp belongs.
10078  * There are no exceptions to this rule. The caller has already put
10079  * a reference on this connp/tcp and once tcp_input_data() returns,
10080  * the squeue will do the refrele.
10081  *
10082  * The TH_SYN for the listener directly go to tcp_input_listener via
10083  * squeue. ICMP errors go directly to tcp_icmp_input().
10084  *
10085  * sqp: NULL = recursive, sqp != NULL means called from squeue
10086  */
10087 void
10088 tcp_input_data(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
10089 {
10090 	int32_t		bytes_acked;
10091 	int32_t		gap;
10092 	mblk_t		*mp1;
10093 	uint_t		flags;
10094 	uint32_t	new_swnd = 0;
10095 	uchar_t		*iphdr;
10096 	uchar_t		*rptr;
10097 	int32_t		rgap;
10098 	uint32_t	seg_ack;
10099 	int		seg_len;
10100 	uint_t		ip_hdr_len;
10101 	uint32_t	seg_seq;
10102 	tcpha_t		*tcpha;
10103 	int		urp;
10104 	tcp_opt_t	tcpopt;
10105 	ip_pkt_t	ipp;
10106 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
10107 	uint32_t	cwnd;
10108 	uint32_t	add;
10109 	int		npkt;
10110 	int		mss;
10111 	conn_t		*connp = (conn_t *)arg;
10112 	squeue_t	*sqp = (squeue_t *)arg2;
10113 	tcp_t		*tcp = connp->conn_tcp;
10114 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10115 
10116 	/*
10117 	 * RST from fused tcp loopback peer should trigger an unfuse.
10118 	 */
10119 	if (tcp->tcp_fused) {
10120 		TCP_STAT(tcps, tcp_fusion_aborted);
10121 		tcp_unfuse(tcp);
10122 	}
10123 
10124 	iphdr = mp->b_rptr;
10125 	rptr = mp->b_rptr;
10126 	ASSERT(OK_32PTR(rptr));
10127 
10128 	ip_hdr_len = ira->ira_ip_hdr_length;
10129 	if (connp->conn_recv_ancillary.crb_all != 0) {
10130 		/*
10131 		 * Record packet information in the ip_pkt_t
10132 		 */
10133 		ipp.ipp_fields = 0;
10134 		if (ira->ira_flags & IRAF_IS_IPV4) {
10135 			(void) ip_find_hdr_v4((ipha_t *)rptr, &ipp,
10136 			    B_FALSE);
10137 		} else {
10138 			uint8_t nexthdrp;
10139 
10140 			/*
10141 			 * IPv6 packets can only be received by applications
10142 			 * that are prepared to receive IPv6 addresses.
10143 			 * The IP fanout must ensure this.
10144 			 */
10145 			ASSERT(connp->conn_family == AF_INET6);
10146 
10147 			(void) ip_find_hdr_v6(mp, (ip6_t *)rptr, B_TRUE, &ipp,
10148 			    &nexthdrp);
10149 			ASSERT(nexthdrp == IPPROTO_TCP);
10150 
10151 			/* Could have caused a pullup? */
10152 			iphdr = mp->b_rptr;
10153 			rptr = mp->b_rptr;
10154 		}
10155 	}
10156 	ASSERT(DB_TYPE(mp) == M_DATA);
10157 	ASSERT(mp->b_next == NULL);
10158 
10159 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
10160 	seg_seq = ntohl(tcpha->tha_seq);
10161 	seg_ack = ntohl(tcpha->tha_ack);
10162 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
10163 	seg_len = (int)(mp->b_wptr - rptr) -
10164 	    (ip_hdr_len + TCP_HDR_LENGTH(tcpha));
10165 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
10166 		do {
10167 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
10168 			    (uintptr_t)INT_MAX);
10169 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
10170 		} while ((mp1 = mp1->b_cont) != NULL &&
10171 		    mp1->b_datap->db_type == M_DATA);
10172 	}
10173 
10174 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
10175 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
10176 		    seg_len, tcpha, ira);
10177 		return;
10178 	}
10179 
10180 	if (sqp != NULL) {
10181 		/*
10182 		 * This is the correct place to update tcp_last_recv_time. Note
10183 		 * that it is also updated for tcp structure that belongs to
10184 		 * global and listener queues which do not really need updating.
10185 		 * But that should not cause any harm.  And it is updated for
10186 		 * all kinds of incoming segments, not only for data segments.
10187 		 */
10188 		tcp->tcp_last_recv_time = LBOLT_FASTPATH;
10189 	}
10190 
10191 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
10192 
10193 	BUMP_LOCAL(tcp->tcp_ibsegs);
10194 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
10195 
10196 	if ((flags & TH_URG) && sqp != NULL) {
10197 		/*
10198 		 * TCP can't handle urgent pointers that arrive before
10199 		 * the connection has been accept()ed since it can't
10200 		 * buffer OOB data.  Discard segment if this happens.
10201 		 *
10202 		 * We can't just rely on a non-null tcp_listener to indicate
10203 		 * that the accept() has completed since unlinking of the
10204 		 * eager and completion of the accept are not atomic.
10205 		 * tcp_detached, when it is not set (B_FALSE) indicates
10206 		 * that the accept() has completed.
10207 		 *
10208 		 * Nor can it reassemble urgent pointers, so discard
10209 		 * if it's not the next segment expected.
10210 		 *
10211 		 * Otherwise, collapse chain into one mblk (discard if
10212 		 * that fails).  This makes sure the headers, retransmitted
10213 		 * data, and new data all are in the same mblk.
10214 		 */
10215 		ASSERT(mp != NULL);
10216 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
10217 			freemsg(mp);
10218 			return;
10219 		}
10220 		/* Update pointers into message */
10221 		iphdr = rptr = mp->b_rptr;
10222 		tcpha = (tcpha_t *)&rptr[ip_hdr_len];
10223 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
10224 			/*
10225 			 * Since we can't handle any data with this urgent
10226 			 * pointer that is out of sequence, we expunge
10227 			 * the data.  This allows us to still register
10228 			 * the urgent mark and generate the M_PCSIG,
10229 			 * which we can do.
10230 			 */
10231 			mp->b_wptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
10232 			seg_len = 0;
10233 		}
10234 	}
10235 
10236 	switch (tcp->tcp_state) {
10237 	case TCPS_SYN_SENT:
10238 		if (connp->conn_final_sqp == NULL &&
10239 		    tcp_outbound_squeue_switch && sqp != NULL) {
10240 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
10241 			connp->conn_final_sqp = sqp;
10242 			if (connp->conn_final_sqp != connp->conn_sqp) {
10243 				DTRACE_PROBE1(conn__final__sqp__switch,
10244 				    conn_t *, connp);
10245 				CONN_INC_REF(connp);
10246 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
10247 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
10248 				    tcp_input_data, connp, ira, ip_squeue_flag,
10249 				    SQTAG_CONNECT_FINISH);
10250 				return;
10251 			}
10252 			DTRACE_PROBE1(conn__final__sqp__same, conn_t *, connp);
10253 		}
10254 		if (flags & TH_ACK) {
10255 			/*
10256 			 * Note that our stack cannot send data before a
10257 			 * connection is established, therefore the
10258 			 * following check is valid.  Otherwise, it has
10259 			 * to be changed.
10260 			 */
10261 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
10262 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
10263 				freemsg(mp);
10264 				if (flags & TH_RST)
10265 					return;
10266 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
10267 				    tcp, seg_ack, 0, TH_RST);
10268 				return;
10269 			}
10270 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
10271 		}
10272 		if (flags & TH_RST) {
10273 			freemsg(mp);
10274 			if (flags & TH_ACK)
10275 				(void) tcp_clean_death(tcp,
10276 				    ECONNREFUSED, 13);
10277 			return;
10278 		}
10279 		if (!(flags & TH_SYN)) {
10280 			freemsg(mp);
10281 			return;
10282 		}
10283 
10284 		/* Process all TCP options. */
10285 		tcp_process_options(tcp, tcpha);
10286 		/*
10287 		 * The following changes our rwnd to be a multiple of the
10288 		 * MIN(peer MSS, our MSS) for performance reason.
10289 		 */
10290 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(connp->conn_rcvbuf,
10291 		    tcp->tcp_mss));
10292 
10293 		/* Is the other end ECN capable? */
10294 		if (tcp->tcp_ecn_ok) {
10295 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
10296 				tcp->tcp_ecn_ok = B_FALSE;
10297 			}
10298 		}
10299 		/*
10300 		 * Clear ECN flags because it may interfere with later
10301 		 * processing.
10302 		 */
10303 		flags &= ~(TH_ECE|TH_CWR);
10304 
10305 		tcp->tcp_irs = seg_seq;
10306 		tcp->tcp_rack = seg_seq;
10307 		tcp->tcp_rnxt = seg_seq + 1;
10308 		tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
10309 		if (!TCP_IS_DETACHED(tcp)) {
10310 			/* Allocate room for SACK options if needed. */
10311 			connp->conn_wroff = connp->conn_ht_iphc_len;
10312 			if (tcp->tcp_snd_sack_ok)
10313 				connp->conn_wroff += TCPOPT_MAX_SACK_LEN;
10314 			if (!tcp->tcp_loopback)
10315 				connp->conn_wroff += tcps->tcps_wroff_xtra;
10316 
10317 			(void) proto_set_tx_wroff(connp->conn_rq, connp,
10318 			    connp->conn_wroff);
10319 		}
10320 		if (flags & TH_ACK) {
10321 			/*
10322 			 * If we can't get the confirmation upstream, pretend
10323 			 * we didn't even see this one.
10324 			 *
10325 			 * XXX: how can we pretend we didn't see it if we
10326 			 * have updated rnxt et. al.
10327 			 *
10328 			 * For loopback we defer sending up the T_CONN_CON
10329 			 * until after some checks below.
10330 			 */
10331 			mp1 = NULL;
10332 			/*
10333 			 * tcp_sendmsg() checks tcp_state without entering
10334 			 * the squeue so tcp_state should be updated before
10335 			 * sending up connection confirmation
10336 			 */
10337 			tcp->tcp_state = TCPS_ESTABLISHED;
10338 			if (!tcp_conn_con(tcp, iphdr, mp,
10339 			    tcp->tcp_loopback ? &mp1 : NULL, ira)) {
10340 				tcp->tcp_state = TCPS_SYN_SENT;
10341 				freemsg(mp);
10342 				return;
10343 			}
10344 			/* SYN was acked - making progress */
10345 			tcp->tcp_ip_forward_progress = B_TRUE;
10346 
10347 			/* One for the SYN */
10348 			tcp->tcp_suna = tcp->tcp_iss + 1;
10349 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
10350 
10351 			/*
10352 			 * If SYN was retransmitted, need to reset all
10353 			 * retransmission info.  This is because this
10354 			 * segment will be treated as a dup ACK.
10355 			 */
10356 			if (tcp->tcp_rexmit) {
10357 				tcp->tcp_rexmit = B_FALSE;
10358 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
10359 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
10360 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
10361 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
10362 				tcp->tcp_ms_we_have_waited = 0;
10363 
10364 				/*
10365 				 * Set tcp_cwnd back to 1 MSS, per
10366 				 * recommendation from
10367 				 * draft-floyd-incr-init-win-01.txt,
10368 				 * Increasing TCP's Initial Window.
10369 				 */
10370 				tcp->tcp_cwnd = tcp->tcp_mss;
10371 			}
10372 
10373 			tcp->tcp_swl1 = seg_seq;
10374 			tcp->tcp_swl2 = seg_ack;
10375 
10376 			new_swnd = ntohs(tcpha->tha_win);
10377 			tcp->tcp_swnd = new_swnd;
10378 			if (new_swnd > tcp->tcp_max_swnd)
10379 				tcp->tcp_max_swnd = new_swnd;
10380 
10381 			/*
10382 			 * Always send the three-way handshake ack immediately
10383 			 * in order to make the connection complete as soon as
10384 			 * possible on the accepting host.
10385 			 */
10386 			flags |= TH_ACK_NEEDED;
10387 
10388 			/*
10389 			 * Special case for loopback.  At this point we have
10390 			 * received SYN-ACK from the remote endpoint.  In
10391 			 * order to ensure that both endpoints reach the
10392 			 * fused state prior to any data exchange, the final
10393 			 * ACK needs to be sent before we indicate T_CONN_CON
10394 			 * to the module upstream.
10395 			 */
10396 			if (tcp->tcp_loopback) {
10397 				mblk_t *ack_mp;
10398 
10399 				ASSERT(!tcp->tcp_unfusable);
10400 				ASSERT(mp1 != NULL);
10401 				/*
10402 				 * For loopback, we always get a pure SYN-ACK
10403 				 * and only need to send back the final ACK
10404 				 * with no data (this is because the other
10405 				 * tcp is ours and we don't do T/TCP).  This
10406 				 * final ACK triggers the passive side to
10407 				 * perform fusion in ESTABLISHED state.
10408 				 */
10409 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
10410 					if (tcp->tcp_ack_tid != 0) {
10411 						(void) TCP_TIMER_CANCEL(tcp,
10412 						    tcp->tcp_ack_tid);
10413 						tcp->tcp_ack_tid = 0;
10414 					}
10415 					tcp_send_data(tcp, ack_mp);
10416 					BUMP_LOCAL(tcp->tcp_obsegs);
10417 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
10418 
10419 					if (!IPCL_IS_NONSTR(connp)) {
10420 						/* Send up T_CONN_CON */
10421 						if (ira->ira_cred != NULL) {
10422 							mblk_setcred(mp1,
10423 							    ira->ira_cred,
10424 							    ira->ira_cpid);
10425 						}
10426 						putnext(connp->conn_rq, mp1);
10427 					} else {
10428 						(*connp->conn_upcalls->
10429 						    su_connected)
10430 						    (connp->conn_upper_handle,
10431 						    tcp->tcp_connid,
10432 						    ira->ira_cred,
10433 						    ira->ira_cpid);
10434 						freemsg(mp1);
10435 					}
10436 
10437 					freemsg(mp);
10438 					return;
10439 				}
10440 				/*
10441 				 * Forget fusion; we need to handle more
10442 				 * complex cases below.  Send the deferred
10443 				 * T_CONN_CON message upstream and proceed
10444 				 * as usual.  Mark this tcp as not capable
10445 				 * of fusion.
10446 				 */
10447 				TCP_STAT(tcps, tcp_fusion_unfusable);
10448 				tcp->tcp_unfusable = B_TRUE;
10449 				if (!IPCL_IS_NONSTR(connp)) {
10450 					if (ira->ira_cred != NULL) {
10451 						mblk_setcred(mp1, ira->ira_cred,
10452 						    ira->ira_cpid);
10453 					}
10454 					putnext(connp->conn_rq, mp1);
10455 				} else {
10456 					(*connp->conn_upcalls->su_connected)
10457 					    (connp->conn_upper_handle,
10458 					    tcp->tcp_connid, ira->ira_cred,
10459 					    ira->ira_cpid);
10460 					freemsg(mp1);
10461 				}
10462 			}
10463 
10464 			/*
10465 			 * Check to see if there is data to be sent.  If
10466 			 * yes, set the transmit flag.  Then check to see
10467 			 * if received data processing needs to be done.
10468 			 * If not, go straight to xmit_check.  This short
10469 			 * cut is OK as we don't support T/TCP.
10470 			 */
10471 			if (tcp->tcp_unsent)
10472 				flags |= TH_XMIT_NEEDED;
10473 
10474 			if (seg_len == 0 && !(flags & TH_URG)) {
10475 				freemsg(mp);
10476 				goto xmit_check;
10477 			}
10478 
10479 			flags &= ~TH_SYN;
10480 			seg_seq++;
10481 			break;
10482 		}
10483 		tcp->tcp_state = TCPS_SYN_RCVD;
10484 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
10485 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
10486 		if (mp1 != NULL) {
10487 			tcp_send_data(tcp, mp1);
10488 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
10489 		}
10490 		freemsg(mp);
10491 		return;
10492 	case TCPS_SYN_RCVD:
10493 		if (flags & TH_ACK) {
10494 			/*
10495 			 * In this state, a SYN|ACK packet is either bogus
10496 			 * because the other side must be ACKing our SYN which
10497 			 * indicates it has seen the ACK for their SYN and
10498 			 * shouldn't retransmit it or we're crossing SYNs
10499 			 * on active open.
10500 			 */
10501 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
10502 				freemsg(mp);
10503 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
10504 				    tcp, seg_ack, 0, TH_RST);
10505 				return;
10506 			}
10507 			/*
10508 			 * NOTE: RFC 793 pg. 72 says this should be
10509 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
10510 			 * but that would mean we have an ack that ignored
10511 			 * our SYN.
10512 			 */
10513 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
10514 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
10515 				freemsg(mp);
10516 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
10517 				    tcp, seg_ack, 0, TH_RST);
10518 				return;
10519 			}
10520 			/*
10521 			 * No sane TCP stack will send such a small window
10522 			 * without receiving any data.  Just drop this invalid
10523 			 * ACK.  We also shorten the abort timeout in case
10524 			 * this is an attack.
10525 			 */
10526 			if ((ntohs(tcpha->tha_win) << tcp->tcp_snd_ws) <
10527 			    (tcp->tcp_mss >> tcp_init_wnd_shft)) {
10528 				freemsg(mp);
10529 				TCP_STAT(tcps, tcp_zwin_ack_syn);
10530 				tcp->tcp_second_ctimer_threshold =
10531 				    tcp_early_abort * SECONDS;
10532 				return;
10533 			}
10534 		}
10535 		break;
10536 	case TCPS_LISTEN:
10537 		/*
10538 		 * Only a TLI listener can come through this path when a
10539 		 * acceptor is going back to be a listener and a packet
10540 		 * for the acceptor hits the classifier. For a socket
10541 		 * listener, this can never happen because a listener
10542 		 * can never accept connection on itself and hence a
10543 		 * socket acceptor can not go back to being a listener.
10544 		 */
10545 		ASSERT(!TCP_IS_SOCKET(tcp));
10546 		/*FALLTHRU*/
10547 	case TCPS_CLOSED:
10548 	case TCPS_BOUND: {
10549 		conn_t	*new_connp;
10550 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
10551 
10552 		/*
10553 		 * Don't accept any input on a closed tcp as this TCP logically
10554 		 * does not exist on the system. Don't proceed further with
10555 		 * this TCP. For instance, this packet could trigger another
10556 		 * close of this tcp which would be disastrous for tcp_refcnt.
10557 		 * tcp_close_detached / tcp_clean_death / tcp_closei_local must
10558 		 * be called at most once on a TCP. In this case we need to
10559 		 * refeed the packet into the classifier and figure out where
10560 		 * the packet should go.
10561 		 */
10562 		new_connp = ipcl_classify(mp, ira, ipst);
10563 		if (new_connp != NULL) {
10564 			/* Drops ref on new_connp */
10565 			tcp_reinput(new_connp, mp, ira, ipst);
10566 			return;
10567 		}
10568 		/* We failed to classify. For now just drop the packet */
10569 		freemsg(mp);
10570 		return;
10571 	}
10572 	case TCPS_IDLE:
10573 		/*
10574 		 * Handle the case where the tcp_clean_death() has happened
10575 		 * on a connection (application hasn't closed yet) but a packet
10576 		 * was already queued on squeue before tcp_clean_death()
10577 		 * was processed. Calling tcp_clean_death() twice on same
10578 		 * connection can result in weird behaviour.
10579 		 */
10580 		freemsg(mp);
10581 		return;
10582 	default:
10583 		break;
10584 	}
10585 
10586 	/*
10587 	 * Already on the correct queue/perimeter.
10588 	 * If this is a detached connection and not an eager
10589 	 * connection hanging off a listener then new data
10590 	 * (past the FIN) will cause a reset.
10591 	 * We do a special check here where it
10592 	 * is out of the main line, rather than check
10593 	 * if we are detached every time we see new
10594 	 * data down below.
10595 	 */
10596 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
10597 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
10598 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
10599 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
10600 
10601 		freemsg(mp);
10602 		/*
10603 		 * This could be an SSL closure alert. We're detached so just
10604 		 * acknowledge it this last time.
10605 		 */
10606 		if (tcp->tcp_kssl_ctx != NULL) {
10607 			kssl_release_ctx(tcp->tcp_kssl_ctx);
10608 			tcp->tcp_kssl_ctx = NULL;
10609 
10610 			tcp->tcp_rnxt += seg_len;
10611 			tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
10612 			flags |= TH_ACK_NEEDED;
10613 			goto ack_check;
10614 		}
10615 
10616 		tcp_xmit_ctl("new data when detached", tcp,
10617 		    tcp->tcp_snxt, 0, TH_RST);
10618 		(void) tcp_clean_death(tcp, EPROTO, 12);
10619 		return;
10620 	}
10621 
10622 	mp->b_rptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
10623 	urp = ntohs(tcpha->tha_urp) - TCP_OLD_URP_INTERPRETATION;
10624 	new_swnd = ntohs(tcpha->tha_win) <<
10625 	    ((tcpha->tha_flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
10626 
10627 	if (tcp->tcp_snd_ts_ok) {
10628 		if (!tcp_paws_check(tcp, tcpha, &tcpopt)) {
10629 			/*
10630 			 * This segment is not acceptable.
10631 			 * Drop it and send back an ACK.
10632 			 */
10633 			freemsg(mp);
10634 			flags |= TH_ACK_NEEDED;
10635 			goto ack_check;
10636 		}
10637 	} else if (tcp->tcp_snd_sack_ok) {
10638 		ASSERT(tcp->tcp_sack_info != NULL);
10639 		tcpopt.tcp = tcp;
10640 		/*
10641 		 * SACK info in already updated in tcp_parse_options.  Ignore
10642 		 * all other TCP options...
10643 		 */
10644 		(void) tcp_parse_options(tcpha, &tcpopt);
10645 	}
10646 try_again:;
10647 	mss = tcp->tcp_mss;
10648 	gap = seg_seq - tcp->tcp_rnxt;
10649 	rgap = tcp->tcp_rwnd - (gap + seg_len);
10650 	/*
10651 	 * gap is the amount of sequence space between what we expect to see
10652 	 * and what we got for seg_seq.  A positive value for gap means
10653 	 * something got lost.  A negative value means we got some old stuff.
10654 	 */
10655 	if (gap < 0) {
10656 		/* Old stuff present.  Is the SYN in there? */
10657 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
10658 		    (seg_len != 0)) {
10659 			flags &= ~TH_SYN;
10660 			seg_seq++;
10661 			urp--;
10662 			/* Recompute the gaps after noting the SYN. */
10663 			goto try_again;
10664 		}
10665 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
10666 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
10667 		    (seg_len > -gap ? -gap : seg_len));
10668 		/* Remove the old stuff from seg_len. */
10669 		seg_len += gap;
10670 		/*
10671 		 * Anything left?
10672 		 * Make sure to check for unack'd FIN when rest of data
10673 		 * has been previously ack'd.
10674 		 */
10675 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
10676 			/*
10677 			 * Resets are only valid if they lie within our offered
10678 			 * window.  If the RST bit is set, we just ignore this
10679 			 * segment.
10680 			 */
10681 			if (flags & TH_RST) {
10682 				freemsg(mp);
10683 				return;
10684 			}
10685 
10686 			/*
10687 			 * The arriving of dup data packets indicate that we
10688 			 * may have postponed an ack for too long, or the other
10689 			 * side's RTT estimate is out of shape. Start acking
10690 			 * more often.
10691 			 */
10692 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
10693 			    tcp->tcp_rack_cnt >= 1 &&
10694 			    tcp->tcp_rack_abs_max > 2) {
10695 				tcp->tcp_rack_abs_max--;
10696 			}
10697 			tcp->tcp_rack_cur_max = 1;
10698 
10699 			/*
10700 			 * This segment is "unacceptable".  None of its
10701 			 * sequence space lies within our advertized window.
10702 			 *
10703 			 * Adjust seg_len to the original value for tracing.
10704 			 */
10705 			seg_len -= gap;
10706 			if (connp->conn_debug) {
10707 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
10708 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
10709 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
10710 				    "seg_len %d, rnxt %u, snxt %u, %s",
10711 				    gap, rgap, flags, seg_seq, seg_ack,
10712 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
10713 				    tcp_display(tcp, NULL,
10714 				    DISP_ADDR_AND_PORT));
10715 			}
10716 
10717 			/*
10718 			 * Arrange to send an ACK in response to the
10719 			 * unacceptable segment per RFC 793 page 69. There
10720 			 * is only one small difference between ours and the
10721 			 * acceptability test in the RFC - we accept ACK-only
10722 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
10723 			 * will be generated.
10724 			 *
10725 			 * Note that we have to ACK an ACK-only packet at least
10726 			 * for stacks that send 0-length keep-alives with
10727 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
10728 			 * section 4.2.3.6. As long as we don't ever generate
10729 			 * an unacceptable packet in response to an incoming
10730 			 * packet that is unacceptable, it should not cause
10731 			 * "ACK wars".
10732 			 */
10733 			flags |=  TH_ACK_NEEDED;
10734 
10735 			/*
10736 			 * Continue processing this segment in order to use the
10737 			 * ACK information it contains, but skip all other
10738 			 * sequence-number processing.	Processing the ACK
10739 			 * information is necessary in order to
10740 			 * re-synchronize connections that may have lost
10741 			 * synchronization.
10742 			 *
10743 			 * We clear seg_len and flag fields related to
10744 			 * sequence number processing as they are not
10745 			 * to be trusted for an unacceptable segment.
10746 			 */
10747 			seg_len = 0;
10748 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
10749 			goto process_ack;
10750 		}
10751 
10752 		/* Fix seg_seq, and chew the gap off the front. */
10753 		seg_seq = tcp->tcp_rnxt;
10754 		urp += gap;
10755 		do {
10756 			mblk_t	*mp2;
10757 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10758 			    (uintptr_t)UINT_MAX);
10759 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
10760 			if (gap > 0) {
10761 				mp->b_rptr = mp->b_wptr - gap;
10762 				break;
10763 			}
10764 			mp2 = mp;
10765 			mp = mp->b_cont;
10766 			freeb(mp2);
10767 		} while (gap < 0);
10768 		/*
10769 		 * If the urgent data has already been acknowledged, we
10770 		 * should ignore TH_URG below
10771 		 */
10772 		if (urp < 0)
10773 			flags &= ~TH_URG;
10774 	}
10775 	/*
10776 	 * rgap is the amount of stuff received out of window.  A negative
10777 	 * value is the amount out of window.
10778 	 */
10779 	if (rgap < 0) {
10780 		mblk_t	*mp2;
10781 
10782 		if (tcp->tcp_rwnd == 0) {
10783 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
10784 		} else {
10785 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
10786 			UPDATE_MIB(&tcps->tcps_mib,
10787 			    tcpInDataPastWinBytes, -rgap);
10788 		}
10789 
10790 		/*
10791 		 * seg_len does not include the FIN, so if more than
10792 		 * just the FIN is out of window, we act like we don't
10793 		 * see it.  (If just the FIN is out of window, rgap
10794 		 * will be zero and we will go ahead and acknowledge
10795 		 * the FIN.)
10796 		 */
10797 		flags &= ~TH_FIN;
10798 
10799 		/* Fix seg_len and make sure there is something left. */
10800 		seg_len += rgap;
10801 		if (seg_len <= 0) {
10802 			/*
10803 			 * Resets are only valid if they lie within our offered
10804 			 * window.  If the RST bit is set, we just ignore this
10805 			 * segment.
10806 			 */
10807 			if (flags & TH_RST) {
10808 				freemsg(mp);
10809 				return;
10810 			}
10811 
10812 			/* Per RFC 793, we need to send back an ACK. */
10813 			flags |= TH_ACK_NEEDED;
10814 
10815 			/*
10816 			 * Send SIGURG as soon as possible i.e. even
10817 			 * if the TH_URG was delivered in a window probe
10818 			 * packet (which will be unacceptable).
10819 			 *
10820 			 * We generate a signal if none has been generated
10821 			 * for this connection or if this is a new urgent
10822 			 * byte. Also send a zero-length "unmarked" message
10823 			 * to inform SIOCATMARK that this is not the mark.
10824 			 *
10825 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
10826 			 * is sent up. This plus the check for old data
10827 			 * (gap >= 0) handles the wraparound of the sequence
10828 			 * number space without having to always track the
10829 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
10830 			 * this max in its rcv_up variable).
10831 			 *
10832 			 * This prevents duplicate SIGURGS due to a "late"
10833 			 * zero-window probe when the T_EXDATA_IND has already
10834 			 * been sent up.
10835 			 */
10836 			if ((flags & TH_URG) &&
10837 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
10838 			    tcp->tcp_urp_last))) {
10839 				if (IPCL_IS_NONSTR(connp)) {
10840 					if (!TCP_IS_DETACHED(tcp)) {
10841 						(*connp->conn_upcalls->
10842 						    su_signal_oob)
10843 						    (connp->conn_upper_handle,
10844 						    urp);
10845 					}
10846 				} else {
10847 					mp1 = allocb(0, BPRI_MED);
10848 					if (mp1 == NULL) {
10849 						freemsg(mp);
10850 						return;
10851 					}
10852 					if (!TCP_IS_DETACHED(tcp) &&
10853 					    !putnextctl1(connp->conn_rq,
10854 					    M_PCSIG, SIGURG)) {
10855 						/* Try again on the rexmit. */
10856 						freemsg(mp1);
10857 						freemsg(mp);
10858 						return;
10859 					}
10860 					/*
10861 					 * If the next byte would be the mark
10862 					 * then mark with MARKNEXT else mark
10863 					 * with NOTMARKNEXT.
10864 					 */
10865 					if (gap == 0 && urp == 0)
10866 						mp1->b_flag |= MSGMARKNEXT;
10867 					else
10868 						mp1->b_flag |= MSGNOTMARKNEXT;
10869 					freemsg(tcp->tcp_urp_mark_mp);
10870 					tcp->tcp_urp_mark_mp = mp1;
10871 					flags |= TH_SEND_URP_MARK;
10872 				}
10873 				tcp->tcp_urp_last_valid = B_TRUE;
10874 				tcp->tcp_urp_last = urp + seg_seq;
10875 			}
10876 			/*
10877 			 * If this is a zero window probe, continue to
10878 			 * process the ACK part.  But we need to set seg_len
10879 			 * to 0 to avoid data processing.  Otherwise just
10880 			 * drop the segment and send back an ACK.
10881 			 */
10882 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
10883 				flags &= ~(TH_SYN | TH_URG);
10884 				seg_len = 0;
10885 				goto process_ack;
10886 			} else {
10887 				freemsg(mp);
10888 				goto ack_check;
10889 			}
10890 		}
10891 		/* Pitch out of window stuff off the end. */
10892 		rgap = seg_len;
10893 		mp2 = mp;
10894 		do {
10895 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
10896 			    (uintptr_t)INT_MAX);
10897 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
10898 			if (rgap < 0) {
10899 				mp2->b_wptr += rgap;
10900 				if ((mp1 = mp2->b_cont) != NULL) {
10901 					mp2->b_cont = NULL;
10902 					freemsg(mp1);
10903 				}
10904 				break;
10905 			}
10906 		} while ((mp2 = mp2->b_cont) != NULL);
10907 	}
10908 ok:;
10909 	/*
10910 	 * TCP should check ECN info for segments inside the window only.
10911 	 * Therefore the check should be done here.
10912 	 */
10913 	if (tcp->tcp_ecn_ok) {
10914 		if (flags & TH_CWR) {
10915 			tcp->tcp_ecn_echo_on = B_FALSE;
10916 		}
10917 		/*
10918 		 * Note that both ECN_CE and CWR can be set in the
10919 		 * same segment.  In this case, we once again turn
10920 		 * on ECN_ECHO.
10921 		 */
10922 		if (connp->conn_ipversion == IPV4_VERSION) {
10923 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
10924 
10925 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
10926 				tcp->tcp_ecn_echo_on = B_TRUE;
10927 			}
10928 		} else {
10929 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
10930 
10931 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
10932 			    htonl(IPH_ECN_CE << 20)) {
10933 				tcp->tcp_ecn_echo_on = B_TRUE;
10934 			}
10935 		}
10936 	}
10937 
10938 	/*
10939 	 * Check whether we can update tcp_ts_recent.  This test is
10940 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
10941 	 * Extensions for High Performance: An Update", Internet Draft.
10942 	 */
10943 	if (tcp->tcp_snd_ts_ok &&
10944 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
10945 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
10946 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
10947 		tcp->tcp_last_rcv_lbolt = LBOLT_FASTPATH64;
10948 	}
10949 
10950 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
10951 		/*
10952 		 * FIN in an out of order segment.  We record this in
10953 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
10954 		 * Clear the FIN so that any check on FIN flag will fail.
10955 		 * Remember that FIN also counts in the sequence number
10956 		 * space.  So we need to ack out of order FIN only segments.
10957 		 */
10958 		if (flags & TH_FIN) {
10959 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
10960 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
10961 			flags &= ~TH_FIN;
10962 			flags |= TH_ACK_NEEDED;
10963 		}
10964 		if (seg_len > 0) {
10965 			/* Fill in the SACK blk list. */
10966 			if (tcp->tcp_snd_sack_ok) {
10967 				ASSERT(tcp->tcp_sack_info != NULL);
10968 				tcp_sack_insert(tcp->tcp_sack_list,
10969 				    seg_seq, seg_seq + seg_len,
10970 				    &(tcp->tcp_num_sack_blk));
10971 			}
10972 
10973 			/*
10974 			 * Attempt reassembly and see if we have something
10975 			 * ready to go.
10976 			 */
10977 			mp = tcp_reass(tcp, mp, seg_seq);
10978 			/* Always ack out of order packets */
10979 			flags |= TH_ACK_NEEDED | TH_PUSH;
10980 			if (mp) {
10981 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10982 				    (uintptr_t)INT_MAX);
10983 				seg_len = mp->b_cont ? msgdsize(mp) :
10984 				    (int)(mp->b_wptr - mp->b_rptr);
10985 				seg_seq = tcp->tcp_rnxt;
10986 				/*
10987 				 * A gap is filled and the seq num and len
10988 				 * of the gap match that of a previously
10989 				 * received FIN, put the FIN flag back in.
10990 				 */
10991 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
10992 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
10993 					flags |= TH_FIN;
10994 					tcp->tcp_valid_bits &=
10995 					    ~TCP_OFO_FIN_VALID;
10996 				}
10997 				if (tcp->tcp_reass_tid != 0) {
10998 					(void) TCP_TIMER_CANCEL(tcp,
10999 					    tcp->tcp_reass_tid);
11000 					/*
11001 					 * Restart the timer if there is still
11002 					 * data in the reassembly queue.
11003 					 */
11004 					if (tcp->tcp_reass_head != NULL) {
11005 						tcp->tcp_reass_tid = TCP_TIMER(
11006 						    tcp, tcp_reass_timer,
11007 						    MSEC_TO_TICK(
11008 						    tcps->tcps_reass_timeout));
11009 					} else {
11010 						tcp->tcp_reass_tid = 0;
11011 					}
11012 				}
11013 			} else {
11014 				/*
11015 				 * Keep going even with NULL mp.
11016 				 * There may be a useful ACK or something else
11017 				 * we don't want to miss.
11018 				 *
11019 				 * But TCP should not perform fast retransmit
11020 				 * because of the ack number.  TCP uses
11021 				 * seg_len == 0 to determine if it is a pure
11022 				 * ACK.  And this is not a pure ACK.
11023 				 */
11024 				seg_len = 0;
11025 				ofo_seg = B_TRUE;
11026 
11027 				if (tcps->tcps_reass_timeout != 0 &&
11028 				    tcp->tcp_reass_tid == 0) {
11029 					tcp->tcp_reass_tid = TCP_TIMER(tcp,
11030 					    tcp_reass_timer, MSEC_TO_TICK(
11031 					    tcps->tcps_reass_timeout));
11032 				}
11033 			}
11034 		}
11035 	} else if (seg_len > 0) {
11036 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
11037 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
11038 		/*
11039 		 * If an out of order FIN was received before, and the seq
11040 		 * num and len of the new segment match that of the FIN,
11041 		 * put the FIN flag back in.
11042 		 */
11043 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
11044 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
11045 			flags |= TH_FIN;
11046 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
11047 		}
11048 	}
11049 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
11050 	if (flags & TH_RST) {
11051 		freemsg(mp);
11052 		switch (tcp->tcp_state) {
11053 		case TCPS_SYN_RCVD:
11054 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
11055 			break;
11056 		case TCPS_ESTABLISHED:
11057 		case TCPS_FIN_WAIT_1:
11058 		case TCPS_FIN_WAIT_2:
11059 		case TCPS_CLOSE_WAIT:
11060 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
11061 			break;
11062 		case TCPS_CLOSING:
11063 		case TCPS_LAST_ACK:
11064 			(void) tcp_clean_death(tcp, 0, 16);
11065 			break;
11066 		default:
11067 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
11068 			(void) tcp_clean_death(tcp, ENXIO, 17);
11069 			break;
11070 		}
11071 		return;
11072 	}
11073 	if (flags & TH_SYN) {
11074 		/*
11075 		 * See RFC 793, Page 71
11076 		 *
11077 		 * The seq number must be in the window as it should
11078 		 * be "fixed" above.  If it is outside window, it should
11079 		 * be already rejected.  Note that we allow seg_seq to be
11080 		 * rnxt + rwnd because we want to accept 0 window probe.
11081 		 */
11082 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
11083 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
11084 		freemsg(mp);
11085 		/*
11086 		 * If the ACK flag is not set, just use our snxt as the
11087 		 * seq number of the RST segment.
11088 		 */
11089 		if (!(flags & TH_ACK)) {
11090 			seg_ack = tcp->tcp_snxt;
11091 		}
11092 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
11093 		    TH_RST|TH_ACK);
11094 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
11095 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
11096 		return;
11097 	}
11098 	/*
11099 	 * urp could be -1 when the urp field in the packet is 0
11100 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
11101 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
11102 	 */
11103 	if (flags & TH_URG && urp >= 0) {
11104 		if (!tcp->tcp_urp_last_valid ||
11105 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
11106 			/*
11107 			 * Non-STREAMS sockets handle the urgent data a litte
11108 			 * differently from STREAMS based sockets. There is no
11109 			 * need to mark any mblks with the MSG{NOT,}MARKNEXT
11110 			 * flags to keep SIOCATMARK happy. Instead a
11111 			 * su_signal_oob upcall is made to update the mark.
11112 			 * Neither is a T_EXDATA_IND mblk needed to be
11113 			 * prepended to the urgent data. The urgent data is
11114 			 * delivered using the su_recv upcall, where we set
11115 			 * the MSG_OOB flag to indicate that it is urg data.
11116 			 *
11117 			 * Neither TH_SEND_URP_MARK nor TH_MARKNEXT_NEEDED
11118 			 * are used by non-STREAMS sockets.
11119 			 */
11120 			if (IPCL_IS_NONSTR(connp)) {
11121 				if (!TCP_IS_DETACHED(tcp)) {
11122 					(*connp->conn_upcalls->su_signal_oob)
11123 					    (connp->conn_upper_handle, urp);
11124 				}
11125 			} else {
11126 				/*
11127 				 * If we haven't generated the signal yet for
11128 				 * this urgent pointer value, do it now.  Also,
11129 				 * send up a zero-length M_DATA indicating
11130 				 * whether or not this is the mark. The latter
11131 				 * is not needed when a T_EXDATA_IND is sent up.
11132 				 * However, if there are allocation failures
11133 				 * this code relies on the sender retransmitting
11134 				 * and the socket code for determining the mark
11135 				 * should not block waiting for the peer to
11136 				 * transmit. Thus, for simplicity we always
11137 				 * send up the mark indication.
11138 				 */
11139 				mp1 = allocb(0, BPRI_MED);
11140 				if (mp1 == NULL) {
11141 					freemsg(mp);
11142 					return;
11143 				}
11144 				if (!TCP_IS_DETACHED(tcp) &&
11145 				    !putnextctl1(connp->conn_rq, M_PCSIG,
11146 				    SIGURG)) {
11147 					/* Try again on the rexmit. */
11148 					freemsg(mp1);
11149 					freemsg(mp);
11150 					return;
11151 				}
11152 				/*
11153 				 * Mark with NOTMARKNEXT for now.
11154 				 * The code below will change this to MARKNEXT
11155 				 * if we are at the mark.
11156 				 *
11157 				 * If there are allocation failures (e.g. in
11158 				 * dupmsg below) the next time tcp_input_data
11159 				 * sees the urgent segment it will send up the
11160 				 * MSGMARKNEXT message.
11161 				 */
11162 				mp1->b_flag |= MSGNOTMARKNEXT;
11163 				freemsg(tcp->tcp_urp_mark_mp);
11164 				tcp->tcp_urp_mark_mp = mp1;
11165 				flags |= TH_SEND_URP_MARK;
11166 #ifdef DEBUG
11167 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11168 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
11169 				    "last %x, %s",
11170 				    seg_seq, urp, tcp->tcp_urp_last,
11171 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
11172 #endif /* DEBUG */
11173 			}
11174 			tcp->tcp_urp_last_valid = B_TRUE;
11175 			tcp->tcp_urp_last = urp + seg_seq;
11176 		} else if (tcp->tcp_urp_mark_mp != NULL) {
11177 			/*
11178 			 * An allocation failure prevented the previous
11179 			 * tcp_input_data from sending up the allocated
11180 			 * MSG*MARKNEXT message - send it up this time
11181 			 * around.
11182 			 */
11183 			flags |= TH_SEND_URP_MARK;
11184 		}
11185 
11186 		/*
11187 		 * If the urgent byte is in this segment, make sure that it is
11188 		 * all by itself.  This makes it much easier to deal with the
11189 		 * possibility of an allocation failure on the T_exdata_ind.
11190 		 * Note that seg_len is the number of bytes in the segment, and
11191 		 * urp is the offset into the segment of the urgent byte.
11192 		 * urp < seg_len means that the urgent byte is in this segment.
11193 		 */
11194 		if (urp < seg_len) {
11195 			if (seg_len != 1) {
11196 				uint32_t  tmp_rnxt;
11197 				/*
11198 				 * Break it up and feed it back in.
11199 				 * Re-attach the IP header.
11200 				 */
11201 				mp->b_rptr = iphdr;
11202 				if (urp > 0) {
11203 					/*
11204 					 * There is stuff before the urgent
11205 					 * byte.
11206 					 */
11207 					mp1 = dupmsg(mp);
11208 					if (!mp1) {
11209 						/*
11210 						 * Trim from urgent byte on.
11211 						 * The rest will come back.
11212 						 */
11213 						(void) adjmsg(mp,
11214 						    urp - seg_len);
11215 						tcp_input_data(connp,
11216 						    mp, NULL, ira);
11217 						return;
11218 					}
11219 					(void) adjmsg(mp1, urp - seg_len);
11220 					/* Feed this piece back in. */
11221 					tmp_rnxt = tcp->tcp_rnxt;
11222 					tcp_input_data(connp, mp1, NULL, ira);
11223 					/*
11224 					 * If the data passed back in was not
11225 					 * processed (ie: bad ACK) sending
11226 					 * the remainder back in will cause a
11227 					 * loop. In this case, drop the
11228 					 * packet and let the sender try
11229 					 * sending a good packet.
11230 					 */
11231 					if (tmp_rnxt == tcp->tcp_rnxt) {
11232 						freemsg(mp);
11233 						return;
11234 					}
11235 				}
11236 				if (urp != seg_len - 1) {
11237 					uint32_t  tmp_rnxt;
11238 					/*
11239 					 * There is stuff after the urgent
11240 					 * byte.
11241 					 */
11242 					mp1 = dupmsg(mp);
11243 					if (!mp1) {
11244 						/*
11245 						 * Trim everything beyond the
11246 						 * urgent byte.  The rest will
11247 						 * come back.
11248 						 */
11249 						(void) adjmsg(mp,
11250 						    urp + 1 - seg_len);
11251 						tcp_input_data(connp,
11252 						    mp, NULL, ira);
11253 						return;
11254 					}
11255 					(void) adjmsg(mp1, urp + 1 - seg_len);
11256 					tmp_rnxt = tcp->tcp_rnxt;
11257 					tcp_input_data(connp, mp1, NULL, ira);
11258 					/*
11259 					 * If the data passed back in was not
11260 					 * processed (ie: bad ACK) sending
11261 					 * the remainder back in will cause a
11262 					 * loop. In this case, drop the
11263 					 * packet and let the sender try
11264 					 * sending a good packet.
11265 					 */
11266 					if (tmp_rnxt == tcp->tcp_rnxt) {
11267 						freemsg(mp);
11268 						return;
11269 					}
11270 				}
11271 				tcp_input_data(connp, mp, NULL, ira);
11272 				return;
11273 			}
11274 			/*
11275 			 * This segment contains only the urgent byte.  We
11276 			 * have to allocate the T_exdata_ind, if we can.
11277 			 */
11278 			if (IPCL_IS_NONSTR(connp)) {
11279 				int error;
11280 
11281 				(*connp->conn_upcalls->su_recv)
11282 				    (connp->conn_upper_handle, mp, seg_len,
11283 				    MSG_OOB, &error, NULL);
11284 				/*
11285 				 * We should never be in middle of a
11286 				 * fallback, the squeue guarantees that.
11287 				 */
11288 				ASSERT(error != EOPNOTSUPP);
11289 				mp = NULL;
11290 				goto update_ack;
11291 			} else if (!tcp->tcp_urp_mp) {
11292 				struct T_exdata_ind *tei;
11293 				mp1 = allocb(sizeof (struct T_exdata_ind),
11294 				    BPRI_MED);
11295 				if (!mp1) {
11296 					/*
11297 					 * Sigh... It'll be back.
11298 					 * Generate any MSG*MARK message now.
11299 					 */
11300 					freemsg(mp);
11301 					seg_len = 0;
11302 					if (flags & TH_SEND_URP_MARK) {
11303 
11304 
11305 						ASSERT(tcp->tcp_urp_mark_mp);
11306 						tcp->tcp_urp_mark_mp->b_flag &=
11307 						    ~MSGNOTMARKNEXT;
11308 						tcp->tcp_urp_mark_mp->b_flag |=
11309 						    MSGMARKNEXT;
11310 					}
11311 					goto ack_check;
11312 				}
11313 				mp1->b_datap->db_type = M_PROTO;
11314 				tei = (struct T_exdata_ind *)mp1->b_rptr;
11315 				tei->PRIM_type = T_EXDATA_IND;
11316 				tei->MORE_flag = 0;
11317 				mp1->b_wptr = (uchar_t *)&tei[1];
11318 				tcp->tcp_urp_mp = mp1;
11319 #ifdef DEBUG
11320 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11321 				    "tcp_rput: allocated exdata_ind %s",
11322 				    tcp_display(tcp, NULL,
11323 				    DISP_PORT_ONLY));
11324 #endif /* DEBUG */
11325 				/*
11326 				 * There is no need to send a separate MSG*MARK
11327 				 * message since the T_EXDATA_IND will be sent
11328 				 * now.
11329 				 */
11330 				flags &= ~TH_SEND_URP_MARK;
11331 				freemsg(tcp->tcp_urp_mark_mp);
11332 				tcp->tcp_urp_mark_mp = NULL;
11333 			}
11334 			/*
11335 			 * Now we are all set.  On the next putnext upstream,
11336 			 * tcp_urp_mp will be non-NULL and will get prepended
11337 			 * to what has to be this piece containing the urgent
11338 			 * byte.  If for any reason we abort this segment below,
11339 			 * if it comes back, we will have this ready, or it
11340 			 * will get blown off in close.
11341 			 */
11342 		} else if (urp == seg_len) {
11343 			/*
11344 			 * The urgent byte is the next byte after this sequence
11345 			 * number. If this endpoint is non-STREAMS, then there
11346 			 * is nothing to do here since the socket has already
11347 			 * been notified about the urg pointer by the
11348 			 * su_signal_oob call above.
11349 			 *
11350 			 * In case of STREAMS, some more work might be needed.
11351 			 * If there is data it is marked with MSGMARKNEXT and
11352 			 * and any tcp_urp_mark_mp is discarded since it is not
11353 			 * needed. Otherwise, if the code above just allocated
11354 			 * a zero-length tcp_urp_mark_mp message, that message
11355 			 * is tagged with MSGMARKNEXT. Sending up these
11356 			 * MSGMARKNEXT messages makes SIOCATMARK work correctly
11357 			 * even though the T_EXDATA_IND will not be sent up
11358 			 * until the urgent byte arrives.
11359 			 */
11360 			if (!IPCL_IS_NONSTR(tcp->tcp_connp)) {
11361 				if (seg_len != 0) {
11362 					flags |= TH_MARKNEXT_NEEDED;
11363 					freemsg(tcp->tcp_urp_mark_mp);
11364 					tcp->tcp_urp_mark_mp = NULL;
11365 					flags &= ~TH_SEND_URP_MARK;
11366 				} else if (tcp->tcp_urp_mark_mp != NULL) {
11367 					flags |= TH_SEND_URP_MARK;
11368 					tcp->tcp_urp_mark_mp->b_flag &=
11369 					    ~MSGNOTMARKNEXT;
11370 					tcp->tcp_urp_mark_mp->b_flag |=
11371 					    MSGMARKNEXT;
11372 				}
11373 			}
11374 #ifdef DEBUG
11375 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11376 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
11377 			    seg_len, flags,
11378 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
11379 #endif /* DEBUG */
11380 		}
11381 #ifdef DEBUG
11382 		else {
11383 			/* Data left until we hit mark */
11384 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11385 			    "tcp_rput: URP %d bytes left, %s",
11386 			    urp - seg_len, tcp_display(tcp, NULL,
11387 			    DISP_PORT_ONLY));
11388 		}
11389 #endif /* DEBUG */
11390 	}
11391 
11392 process_ack:
11393 	if (!(flags & TH_ACK)) {
11394 		freemsg(mp);
11395 		goto xmit_check;
11396 	}
11397 	}
11398 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
11399 
11400 	if (bytes_acked > 0)
11401 		tcp->tcp_ip_forward_progress = B_TRUE;
11402 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
11403 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
11404 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
11405 			/* 3-way handshake complete - pass up the T_CONN_IND */
11406 			tcp_t	*listener = tcp->tcp_listener;
11407 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
11408 
11409 			tcp->tcp_tconnind_started = B_TRUE;
11410 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
11411 			/*
11412 			 * We are here means eager is fine but it can
11413 			 * get a TH_RST at any point between now and till
11414 			 * accept completes and disappear. We need to
11415 			 * ensure that reference to eager is valid after
11416 			 * we get out of eager's perimeter. So we do
11417 			 * an extra refhold.
11418 			 */
11419 			CONN_INC_REF(connp);
11420 
11421 			/*
11422 			 * The listener also exists because of the refhold
11423 			 * done in tcp_input_listener. Its possible that it
11424 			 * might have closed. We will check that once we
11425 			 * get inside listeners context.
11426 			 */
11427 			CONN_INC_REF(listener->tcp_connp);
11428 			if (listener->tcp_connp->conn_sqp ==
11429 			    connp->conn_sqp) {
11430 				/*
11431 				 * We optimize by not calling an SQUEUE_ENTER
11432 				 * on the listener since we know that the
11433 				 * listener and eager squeues are the same.
11434 				 * We are able to make this check safely only
11435 				 * because neither the eager nor the listener
11436 				 * can change its squeue. Only an active connect
11437 				 * can change its squeue
11438 				 */
11439 				tcp_send_conn_ind(listener->tcp_connp, mp,
11440 				    listener->tcp_connp->conn_sqp);
11441 				CONN_DEC_REF(listener->tcp_connp);
11442 			} else if (!tcp->tcp_loopback) {
11443 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
11444 				    mp, tcp_send_conn_ind,
11445 				    listener->tcp_connp, NULL, SQ_FILL,
11446 				    SQTAG_TCP_CONN_IND);
11447 			} else {
11448 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
11449 				    mp, tcp_send_conn_ind,
11450 				    listener->tcp_connp, NULL, SQ_PROCESS,
11451 				    SQTAG_TCP_CONN_IND);
11452 			}
11453 		}
11454 
11455 		/*
11456 		 * We are seeing the final ack in the three way
11457 		 * hand shake of a active open'ed connection
11458 		 * so we must send up a T_CONN_CON
11459 		 *
11460 		 * tcp_sendmsg() checks tcp_state without entering
11461 		 * the squeue so tcp_state should be updated before
11462 		 * sending up connection confirmation.
11463 		 */
11464 		tcp->tcp_state = TCPS_ESTABLISHED;
11465 		if (tcp->tcp_active_open) {
11466 			if (!tcp_conn_con(tcp, iphdr, mp, NULL, ira)) {
11467 				freemsg(mp);
11468 				tcp->tcp_state = TCPS_SYN_RCVD;
11469 				return;
11470 			}
11471 			/*
11472 			 * Don't fuse the loopback endpoints for
11473 			 * simultaneous active opens.
11474 			 */
11475 			if (tcp->tcp_loopback) {
11476 				TCP_STAT(tcps, tcp_fusion_unfusable);
11477 				tcp->tcp_unfusable = B_TRUE;
11478 			}
11479 		}
11480 
11481 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
11482 		bytes_acked--;
11483 		/* SYN was acked - making progress */
11484 		tcp->tcp_ip_forward_progress = B_TRUE;
11485 
11486 		/*
11487 		 * If SYN was retransmitted, need to reset all
11488 		 * retransmission info as this segment will be
11489 		 * treated as a dup ACK.
11490 		 */
11491 		if (tcp->tcp_rexmit) {
11492 			tcp->tcp_rexmit = B_FALSE;
11493 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
11494 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
11495 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
11496 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11497 			tcp->tcp_ms_we_have_waited = 0;
11498 			tcp->tcp_cwnd = mss;
11499 		}
11500 
11501 		/*
11502 		 * We set the send window to zero here.
11503 		 * This is needed if there is data to be
11504 		 * processed already on the queue.
11505 		 * Later (at swnd_update label), the
11506 		 * "new_swnd > tcp_swnd" condition is satisfied
11507 		 * the XMIT_NEEDED flag is set in the current
11508 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
11509 		 * called if there is already data on queue in
11510 		 * this state.
11511 		 */
11512 		tcp->tcp_swnd = 0;
11513 
11514 		if (new_swnd > tcp->tcp_max_swnd)
11515 			tcp->tcp_max_swnd = new_swnd;
11516 		tcp->tcp_swl1 = seg_seq;
11517 		tcp->tcp_swl2 = seg_ack;
11518 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
11519 
11520 		/* Fuse when both sides are in ESTABLISHED state */
11521 		if (tcp->tcp_loopback && do_tcp_fusion)
11522 			tcp_fuse(tcp, iphdr, tcpha);
11523 
11524 	}
11525 	/* This code follows 4.4BSD-Lite2 mostly. */
11526 	if (bytes_acked < 0)
11527 		goto est;
11528 
11529 	/*
11530 	 * If TCP is ECN capable and the congestion experience bit is
11531 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
11532 	 * done once per window (or more loosely, per RTT).
11533 	 */
11534 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
11535 		tcp->tcp_cwr = B_FALSE;
11536 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
11537 		if (!tcp->tcp_cwr) {
11538 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
11539 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
11540 			tcp->tcp_cwnd = npkt * mss;
11541 			/*
11542 			 * If the cwnd is 0, use the timer to clock out
11543 			 * new segments.  This is required by the ECN spec.
11544 			 */
11545 			if (npkt == 0) {
11546 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
11547 				/*
11548 				 * This makes sure that when the ACK comes
11549 				 * back, we will increase tcp_cwnd by 1 MSS.
11550 				 */
11551 				tcp->tcp_cwnd_cnt = 0;
11552 			}
11553 			tcp->tcp_cwr = B_TRUE;
11554 			/*
11555 			 * This marks the end of the current window of in
11556 			 * flight data.  That is why we don't use
11557 			 * tcp_suna + tcp_swnd.  Only data in flight can
11558 			 * provide ECN info.
11559 			 */
11560 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
11561 			tcp->tcp_ecn_cwr_sent = B_FALSE;
11562 		}
11563 	}
11564 
11565 	mp1 = tcp->tcp_xmit_head;
11566 	if (bytes_acked == 0) {
11567 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
11568 			int dupack_cnt;
11569 
11570 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
11571 			/*
11572 			 * Fast retransmit.  When we have seen exactly three
11573 			 * identical ACKs while we have unacked data
11574 			 * outstanding we take it as a hint that our peer
11575 			 * dropped something.
11576 			 *
11577 			 * If TCP is retransmitting, don't do fast retransmit.
11578 			 */
11579 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
11580 			    ! tcp->tcp_rexmit) {
11581 				/* Do Limited Transmit */
11582 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
11583 				    tcps->tcps_dupack_fast_retransmit) {
11584 					/*
11585 					 * RFC 3042
11586 					 *
11587 					 * What we need to do is temporarily
11588 					 * increase tcp_cwnd so that new
11589 					 * data can be sent if it is allowed
11590 					 * by the receive window (tcp_rwnd).
11591 					 * tcp_wput_data() will take care of
11592 					 * the rest.
11593 					 *
11594 					 * If the connection is SACK capable,
11595 					 * only do limited xmit when there
11596 					 * is SACK info.
11597 					 *
11598 					 * Note how tcp_cwnd is incremented.
11599 					 * The first dup ACK will increase
11600 					 * it by 1 MSS.  The second dup ACK
11601 					 * will increase it by 2 MSS.  This
11602 					 * means that only 1 new segment will
11603 					 * be sent for each dup ACK.
11604 					 */
11605 					if (tcp->tcp_unsent > 0 &&
11606 					    (!tcp->tcp_snd_sack_ok ||
11607 					    (tcp->tcp_snd_sack_ok &&
11608 					    tcp->tcp_notsack_list != NULL))) {
11609 						tcp->tcp_cwnd += mss <<
11610 						    (tcp->tcp_dupack_cnt - 1);
11611 						flags |= TH_LIMIT_XMIT;
11612 					}
11613 				} else if (dupack_cnt ==
11614 				    tcps->tcps_dupack_fast_retransmit) {
11615 
11616 				/*
11617 				 * If we have reduced tcp_ssthresh
11618 				 * because of ECN, do not reduce it again
11619 				 * unless it is already one window of data
11620 				 * away.  After one window of data, tcp_cwr
11621 				 * should then be cleared.  Note that
11622 				 * for non ECN capable connection, tcp_cwr
11623 				 * should always be false.
11624 				 *
11625 				 * Adjust cwnd since the duplicate
11626 				 * ack indicates that a packet was
11627 				 * dropped (due to congestion.)
11628 				 */
11629 				if (!tcp->tcp_cwr) {
11630 					npkt = ((tcp->tcp_snxt -
11631 					    tcp->tcp_suna) >> 1) / mss;
11632 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
11633 					    mss;
11634 					tcp->tcp_cwnd = (npkt +
11635 					    tcp->tcp_dupack_cnt) * mss;
11636 				}
11637 				if (tcp->tcp_ecn_ok) {
11638 					tcp->tcp_cwr = B_TRUE;
11639 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
11640 					tcp->tcp_ecn_cwr_sent = B_FALSE;
11641 				}
11642 
11643 				/*
11644 				 * We do Hoe's algorithm.  Refer to her
11645 				 * paper "Improving the Start-up Behavior
11646 				 * of a Congestion Control Scheme for TCP,"
11647 				 * appeared in SIGCOMM'96.
11648 				 *
11649 				 * Save highest seq no we have sent so far.
11650 				 * Be careful about the invisible FIN byte.
11651 				 */
11652 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
11653 				    (tcp->tcp_unsent == 0)) {
11654 					tcp->tcp_rexmit_max = tcp->tcp_fss;
11655 				} else {
11656 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
11657 				}
11658 
11659 				/*
11660 				 * Do not allow bursty traffic during.
11661 				 * fast recovery.  Refer to Fall and Floyd's
11662 				 * paper "Simulation-based Comparisons of
11663 				 * Tahoe, Reno and SACK TCP" (in CCR?)
11664 				 * This is a best current practise.
11665 				 */
11666 				tcp->tcp_snd_burst = TCP_CWND_SS;
11667 
11668 				/*
11669 				 * For SACK:
11670 				 * Calculate tcp_pipe, which is the
11671 				 * estimated number of bytes in
11672 				 * network.
11673 				 *
11674 				 * tcp_fack is the highest sack'ed seq num
11675 				 * TCP has received.
11676 				 *
11677 				 * tcp_pipe is explained in the above quoted
11678 				 * Fall and Floyd's paper.  tcp_fack is
11679 				 * explained in Mathis and Mahdavi's
11680 				 * "Forward Acknowledgment: Refining TCP
11681 				 * Congestion Control" in SIGCOMM '96.
11682 				 */
11683 				if (tcp->tcp_snd_sack_ok) {
11684 					ASSERT(tcp->tcp_sack_info != NULL);
11685 					if (tcp->tcp_notsack_list != NULL) {
11686 						tcp->tcp_pipe = tcp->tcp_snxt -
11687 						    tcp->tcp_fack;
11688 						tcp->tcp_sack_snxt = seg_ack;
11689 						flags |= TH_NEED_SACK_REXMIT;
11690 					} else {
11691 						/*
11692 						 * Always initialize tcp_pipe
11693 						 * even though we don't have
11694 						 * any SACK info.  If later
11695 						 * we get SACK info and
11696 						 * tcp_pipe is not initialized,
11697 						 * funny things will happen.
11698 						 */
11699 						tcp->tcp_pipe =
11700 						    tcp->tcp_cwnd_ssthresh;
11701 					}
11702 				} else {
11703 					flags |= TH_REXMIT_NEEDED;
11704 				} /* tcp_snd_sack_ok */
11705 
11706 				} else {
11707 					/*
11708 					 * Here we perform congestion
11709 					 * avoidance, but NOT slow start.
11710 					 * This is known as the Fast
11711 					 * Recovery Algorithm.
11712 					 */
11713 					if (tcp->tcp_snd_sack_ok &&
11714 					    tcp->tcp_notsack_list != NULL) {
11715 						flags |= TH_NEED_SACK_REXMIT;
11716 						tcp->tcp_pipe -= mss;
11717 						if (tcp->tcp_pipe < 0)
11718 							tcp->tcp_pipe = 0;
11719 					} else {
11720 					/*
11721 					 * We know that one more packet has
11722 					 * left the pipe thus we can update
11723 					 * cwnd.
11724 					 */
11725 					cwnd = tcp->tcp_cwnd + mss;
11726 					if (cwnd > tcp->tcp_cwnd_max)
11727 						cwnd = tcp->tcp_cwnd_max;
11728 					tcp->tcp_cwnd = cwnd;
11729 					if (tcp->tcp_unsent > 0)
11730 						flags |= TH_XMIT_NEEDED;
11731 					}
11732 				}
11733 			}
11734 		} else if (tcp->tcp_zero_win_probe) {
11735 			/*
11736 			 * If the window has opened, need to arrange
11737 			 * to send additional data.
11738 			 */
11739 			if (new_swnd != 0) {
11740 				/* tcp_suna != tcp_snxt */
11741 				/* Packet contains a window update */
11742 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
11743 				tcp->tcp_zero_win_probe = 0;
11744 				tcp->tcp_timer_backoff = 0;
11745 				tcp->tcp_ms_we_have_waited = 0;
11746 
11747 				/*
11748 				 * Transmit starting with tcp_suna since
11749 				 * the one byte probe is not ack'ed.
11750 				 * If TCP has sent more than one identical
11751 				 * probe, tcp_rexmit will be set.  That means
11752 				 * tcp_ss_rexmit() will send out the one
11753 				 * byte along with new data.  Otherwise,
11754 				 * fake the retransmission.
11755 				 */
11756 				flags |= TH_XMIT_NEEDED;
11757 				if (!tcp->tcp_rexmit) {
11758 					tcp->tcp_rexmit = B_TRUE;
11759 					tcp->tcp_dupack_cnt = 0;
11760 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
11761 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
11762 				}
11763 			}
11764 		}
11765 		goto swnd_update;
11766 	}
11767 
11768 	/*
11769 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
11770 	 * If the ACK value acks something that we have not yet sent, it might
11771 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
11772 	 * other side.
11773 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
11774 	 * state is handled above, so we can always just drop the segment and
11775 	 * send an ACK here.
11776 	 *
11777 	 * In the case where the peer shrinks the window, we see the new window
11778 	 * update, but all the data sent previously is queued up by the peer.
11779 	 * To account for this, in tcp_process_shrunk_swnd(), the sequence
11780 	 * number, which was already sent, and within window, is recorded.
11781 	 * tcp_snxt is then updated.
11782 	 *
11783 	 * If the window has previously shrunk, and an ACK for data not yet
11784 	 * sent, according to tcp_snxt is recieved, it may still be valid. If
11785 	 * the ACK is for data within the window at the time the window was
11786 	 * shrunk, then the ACK is acceptable. In this case tcp_snxt is set to
11787 	 * the sequence number ACK'ed.
11788 	 *
11789 	 * If the ACK covers all the data sent at the time the window was
11790 	 * shrunk, we can now set tcp_is_wnd_shrnk to B_FALSE.
11791 	 *
11792 	 * Should we send ACKs in response to ACK only segments?
11793 	 */
11794 
11795 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
11796 		if ((tcp->tcp_is_wnd_shrnk) &&
11797 		    (SEQ_LEQ(seg_ack, tcp->tcp_snxt_shrunk))) {
11798 			uint32_t data_acked_ahead_snxt;
11799 
11800 			data_acked_ahead_snxt = seg_ack - tcp->tcp_snxt;
11801 			tcp_update_xmit_tail(tcp, seg_ack);
11802 			tcp->tcp_unsent -= data_acked_ahead_snxt;
11803 		} else {
11804 			BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
11805 			/* drop the received segment */
11806 			freemsg(mp);
11807 
11808 			/*
11809 			 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
11810 			 * greater than 0, check if the number of such
11811 			 * bogus ACks is greater than that count.  If yes,
11812 			 * don't send back any ACK.  This prevents TCP from
11813 			 * getting into an ACK storm if somehow an attacker
11814 			 * successfully spoofs an acceptable segment to our
11815 			 * peer.  If this continues (count > 2 X threshold),
11816 			 * we should abort this connection.
11817 			 */
11818 			if (tcp_drop_ack_unsent_cnt > 0 &&
11819 			    ++tcp->tcp_in_ack_unsent >
11820 			    tcp_drop_ack_unsent_cnt) {
11821 				TCP_STAT(tcps, tcp_in_ack_unsent_drop);
11822 				if (tcp->tcp_in_ack_unsent > 2 *
11823 				    tcp_drop_ack_unsent_cnt) {
11824 					(void) tcp_clean_death(tcp, EPROTO, 20);
11825 				}
11826 				return;
11827 			}
11828 			mp = tcp_ack_mp(tcp);
11829 			if (mp != NULL) {
11830 				BUMP_LOCAL(tcp->tcp_obsegs);
11831 				BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
11832 				tcp_send_data(tcp, mp);
11833 			}
11834 			return;
11835 		}
11836 	} else if (tcp->tcp_is_wnd_shrnk && SEQ_GEQ(seg_ack,
11837 	    tcp->tcp_snxt_shrunk)) {
11838 			tcp->tcp_is_wnd_shrnk = B_FALSE;
11839 	}
11840 
11841 	/*
11842 	 * TCP gets a new ACK, update the notsack'ed list to delete those
11843 	 * blocks that are covered by this ACK.
11844 	 */
11845 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
11846 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
11847 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
11848 	}
11849 
11850 	/*
11851 	 * If we got an ACK after fast retransmit, check to see
11852 	 * if it is a partial ACK.  If it is not and the congestion
11853 	 * window was inflated to account for the other side's
11854 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
11855 	 */
11856 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
11857 		ASSERT(tcp->tcp_rexmit == B_FALSE);
11858 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
11859 			tcp->tcp_dupack_cnt = 0;
11860 			/*
11861 			 * Restore the orig tcp_cwnd_ssthresh after
11862 			 * fast retransmit phase.
11863 			 */
11864 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
11865 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
11866 			}
11867 			tcp->tcp_rexmit_max = seg_ack;
11868 			tcp->tcp_cwnd_cnt = 0;
11869 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
11870 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11871 
11872 			/*
11873 			 * Remove all notsack info to avoid confusion with
11874 			 * the next fast retrasnmit/recovery phase.
11875 			 */
11876 			if (tcp->tcp_snd_sack_ok &&
11877 			    tcp->tcp_notsack_list != NULL) {
11878 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
11879 				    tcp);
11880 			}
11881 		} else {
11882 			if (tcp->tcp_snd_sack_ok &&
11883 			    tcp->tcp_notsack_list != NULL) {
11884 				flags |= TH_NEED_SACK_REXMIT;
11885 				tcp->tcp_pipe -= mss;
11886 				if (tcp->tcp_pipe < 0)
11887 					tcp->tcp_pipe = 0;
11888 			} else {
11889 				/*
11890 				 * Hoe's algorithm:
11891 				 *
11892 				 * Retransmit the unack'ed segment and
11893 				 * restart fast recovery.  Note that we
11894 				 * need to scale back tcp_cwnd to the
11895 				 * original value when we started fast
11896 				 * recovery.  This is to prevent overly
11897 				 * aggressive behaviour in sending new
11898 				 * segments.
11899 				 */
11900 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
11901 				    tcps->tcps_dupack_fast_retransmit * mss;
11902 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
11903 				flags |= TH_REXMIT_NEEDED;
11904 			}
11905 		}
11906 	} else {
11907 		tcp->tcp_dupack_cnt = 0;
11908 		if (tcp->tcp_rexmit) {
11909 			/*
11910 			 * TCP is retranmitting.  If the ACK ack's all
11911 			 * outstanding data, update tcp_rexmit_max and
11912 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
11913 			 * to the correct value.
11914 			 *
11915 			 * Note that SEQ_LEQ() is used.  This is to avoid
11916 			 * unnecessary fast retransmit caused by dup ACKs
11917 			 * received when TCP does slow start retransmission
11918 			 * after a time out.  During this phase, TCP may
11919 			 * send out segments which are already received.
11920 			 * This causes dup ACKs to be sent back.
11921 			 */
11922 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
11923 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
11924 					tcp->tcp_rexmit_nxt = seg_ack;
11925 				}
11926 				if (seg_ack != tcp->tcp_rexmit_max) {
11927 					flags |= TH_XMIT_NEEDED;
11928 				}
11929 			} else {
11930 				tcp->tcp_rexmit = B_FALSE;
11931 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
11932 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
11933 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11934 			}
11935 			tcp->tcp_ms_we_have_waited = 0;
11936 		}
11937 	}
11938 
11939 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
11940 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
11941 	tcp->tcp_suna = seg_ack;
11942 	if (tcp->tcp_zero_win_probe != 0) {
11943 		tcp->tcp_zero_win_probe = 0;
11944 		tcp->tcp_timer_backoff = 0;
11945 	}
11946 
11947 	/*
11948 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
11949 	 * Note that it cannot be the SYN being ack'ed.  The code flow
11950 	 * will not reach here.
11951 	 */
11952 	if (mp1 == NULL) {
11953 		goto fin_acked;
11954 	}
11955 
11956 	/*
11957 	 * Update the congestion window.
11958 	 *
11959 	 * If TCP is not ECN capable or TCP is ECN capable but the
11960 	 * congestion experience bit is not set, increase the tcp_cwnd as
11961 	 * usual.
11962 	 */
11963 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
11964 		cwnd = tcp->tcp_cwnd;
11965 		add = mss;
11966 
11967 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
11968 			/*
11969 			 * This is to prevent an increase of less than 1 MSS of
11970 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
11971 			 * may send out tinygrams in order to preserve mblk
11972 			 * boundaries.
11973 			 *
11974 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
11975 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
11976 			 * increased by 1 MSS for every RTTs.
11977 			 */
11978 			if (tcp->tcp_cwnd_cnt <= 0) {
11979 				tcp->tcp_cwnd_cnt = cwnd + add;
11980 			} else {
11981 				tcp->tcp_cwnd_cnt -= add;
11982 				add = 0;
11983 			}
11984 		}
11985 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
11986 	}
11987 
11988 	/* See if the latest urgent data has been acknowledged */
11989 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
11990 	    SEQ_GT(seg_ack, tcp->tcp_urg))
11991 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
11992 
11993 	/* Can we update the RTT estimates? */
11994 	if (tcp->tcp_snd_ts_ok) {
11995 		/* Ignore zero timestamp echo-reply. */
11996 		if (tcpopt.tcp_opt_ts_ecr != 0) {
11997 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
11998 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
11999 		}
12000 
12001 		/* If needed, restart the timer. */
12002 		if (tcp->tcp_set_timer == 1) {
12003 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
12004 			tcp->tcp_set_timer = 0;
12005 		}
12006 		/*
12007 		 * Update tcp_csuna in case the other side stops sending
12008 		 * us timestamps.
12009 		 */
12010 		tcp->tcp_csuna = tcp->tcp_snxt;
12011 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
12012 		/*
12013 		 * An ACK sequence we haven't seen before, so get the RTT
12014 		 * and update the RTO. But first check if the timestamp is
12015 		 * valid to use.
12016 		 */
12017 		if ((mp1->b_next != NULL) &&
12018 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
12019 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
12020 			    (int32_t)(intptr_t)mp1->b_prev);
12021 		else
12022 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
12023 
12024 		/* Remeber the last sequence to be ACKed */
12025 		tcp->tcp_csuna = seg_ack;
12026 		if (tcp->tcp_set_timer == 1) {
12027 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
12028 			tcp->tcp_set_timer = 0;
12029 		}
12030 	} else {
12031 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
12032 	}
12033 
12034 	/* Eat acknowledged bytes off the xmit queue. */
12035 	for (;;) {
12036 		mblk_t	*mp2;
12037 		uchar_t	*wptr;
12038 
12039 		wptr = mp1->b_wptr;
12040 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
12041 		bytes_acked -= (int)(wptr - mp1->b_rptr);
12042 		if (bytes_acked < 0) {
12043 			mp1->b_rptr = wptr + bytes_acked;
12044 			/*
12045 			 * Set a new timestamp if all the bytes timed by the
12046 			 * old timestamp have been ack'ed.
12047 			 */
12048 			if (SEQ_GT(seg_ack,
12049 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
12050 				mp1->b_prev =
12051 				    (mblk_t *)(uintptr_t)LBOLT_FASTPATH;
12052 				mp1->b_next = NULL;
12053 			}
12054 			break;
12055 		}
12056 		mp1->b_next = NULL;
12057 		mp1->b_prev = NULL;
12058 		mp2 = mp1;
12059 		mp1 = mp1->b_cont;
12060 
12061 		/*
12062 		 * This notification is required for some zero-copy
12063 		 * clients to maintain a copy semantic. After the data
12064 		 * is ack'ed, client is safe to modify or reuse the buffer.
12065 		 */
12066 		if (tcp->tcp_snd_zcopy_aware &&
12067 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
12068 			tcp_zcopy_notify(tcp);
12069 		freeb(mp2);
12070 		if (bytes_acked == 0) {
12071 			if (mp1 == NULL) {
12072 				/* Everything is ack'ed, clear the tail. */
12073 				tcp->tcp_xmit_tail = NULL;
12074 				/*
12075 				 * Cancel the timer unless we are still
12076 				 * waiting for an ACK for the FIN packet.
12077 				 */
12078 				if (tcp->tcp_timer_tid != 0 &&
12079 				    tcp->tcp_snxt == tcp->tcp_suna) {
12080 					(void) TCP_TIMER_CANCEL(tcp,
12081 					    tcp->tcp_timer_tid);
12082 					tcp->tcp_timer_tid = 0;
12083 				}
12084 				goto pre_swnd_update;
12085 			}
12086 			if (mp2 != tcp->tcp_xmit_tail)
12087 				break;
12088 			tcp->tcp_xmit_tail = mp1;
12089 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12090 			    (uintptr_t)INT_MAX);
12091 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
12092 			    mp1->b_rptr);
12093 			break;
12094 		}
12095 		if (mp1 == NULL) {
12096 			/*
12097 			 * More was acked but there is nothing more
12098 			 * outstanding.  This means that the FIN was
12099 			 * just acked or that we're talking to a clown.
12100 			 */
12101 fin_acked:
12102 			ASSERT(tcp->tcp_fin_sent);
12103 			tcp->tcp_xmit_tail = NULL;
12104 			if (tcp->tcp_fin_sent) {
12105 				/* FIN was acked - making progress */
12106 				if (!tcp->tcp_fin_acked)
12107 					tcp->tcp_ip_forward_progress = B_TRUE;
12108 				tcp->tcp_fin_acked = B_TRUE;
12109 				if (tcp->tcp_linger_tid != 0 &&
12110 				    TCP_TIMER_CANCEL(tcp,
12111 				    tcp->tcp_linger_tid) >= 0) {
12112 					tcp_stop_lingering(tcp);
12113 					freemsg(mp);
12114 					mp = NULL;
12115 				}
12116 			} else {
12117 				/*
12118 				 * We should never get here because
12119 				 * we have already checked that the
12120 				 * number of bytes ack'ed should be
12121 				 * smaller than or equal to what we
12122 				 * have sent so far (it is the
12123 				 * acceptability check of the ACK).
12124 				 * We can only get here if the send
12125 				 * queue is corrupted.
12126 				 *
12127 				 * Terminate the connection and
12128 				 * panic the system.  It is better
12129 				 * for us to panic instead of
12130 				 * continuing to avoid other disaster.
12131 				 */
12132 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
12133 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
12134 				panic("Memory corruption "
12135 				    "detected for connection %s.",
12136 				    tcp_display(tcp, NULL,
12137 				    DISP_ADDR_AND_PORT));
12138 				/*NOTREACHED*/
12139 			}
12140 			goto pre_swnd_update;
12141 		}
12142 		ASSERT(mp2 != tcp->tcp_xmit_tail);
12143 	}
12144 	if (tcp->tcp_unsent) {
12145 		flags |= TH_XMIT_NEEDED;
12146 	}
12147 pre_swnd_update:
12148 	tcp->tcp_xmit_head = mp1;
12149 swnd_update:
12150 	/*
12151 	 * The following check is different from most other implementations.
12152 	 * For bi-directional transfer, when segments are dropped, the
12153 	 * "normal" check will not accept a window update in those
12154 	 * retransmitted segemnts.  Failing to do that, TCP may send out
12155 	 * segments which are outside receiver's window.  As TCP accepts
12156 	 * the ack in those retransmitted segments, if the window update in
12157 	 * the same segment is not accepted, TCP will incorrectly calculates
12158 	 * that it can send more segments.  This can create a deadlock
12159 	 * with the receiver if its window becomes zero.
12160 	 */
12161 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
12162 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
12163 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
12164 		/*
12165 		 * The criteria for update is:
12166 		 *
12167 		 * 1. the segment acknowledges some data.  Or
12168 		 * 2. the segment is new, i.e. it has a higher seq num. Or
12169 		 * 3. the segment is not old and the advertised window is
12170 		 * larger than the previous advertised window.
12171 		 */
12172 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
12173 			flags |= TH_XMIT_NEEDED;
12174 		tcp->tcp_swnd = new_swnd;
12175 		if (new_swnd > tcp->tcp_max_swnd)
12176 			tcp->tcp_max_swnd = new_swnd;
12177 		tcp->tcp_swl1 = seg_seq;
12178 		tcp->tcp_swl2 = seg_ack;
12179 	}
12180 est:
12181 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
12182 
12183 		switch (tcp->tcp_state) {
12184 		case TCPS_FIN_WAIT_1:
12185 			if (tcp->tcp_fin_acked) {
12186 				tcp->tcp_state = TCPS_FIN_WAIT_2;
12187 				/*
12188 				 * We implement the non-standard BSD/SunOS
12189 				 * FIN_WAIT_2 flushing algorithm.
12190 				 * If there is no user attached to this
12191 				 * TCP endpoint, then this TCP struct
12192 				 * could hang around forever in FIN_WAIT_2
12193 				 * state if the peer forgets to send us
12194 				 * a FIN.  To prevent this, we wait only
12195 				 * 2*MSL (a convenient time value) for
12196 				 * the FIN to arrive.  If it doesn't show up,
12197 				 * we flush the TCP endpoint.  This algorithm,
12198 				 * though a violation of RFC-793, has worked
12199 				 * for over 10 years in BSD systems.
12200 				 * Note: SunOS 4.x waits 675 seconds before
12201 				 * flushing the FIN_WAIT_2 connection.
12202 				 */
12203 				TCP_TIMER_RESTART(tcp,
12204 				    tcps->tcps_fin_wait_2_flush_interval);
12205 			}
12206 			break;
12207 		case TCPS_FIN_WAIT_2:
12208 			break;	/* Shutdown hook? */
12209 		case TCPS_LAST_ACK:
12210 			freemsg(mp);
12211 			if (tcp->tcp_fin_acked) {
12212 				(void) tcp_clean_death(tcp, 0, 19);
12213 				return;
12214 			}
12215 			goto xmit_check;
12216 		case TCPS_CLOSING:
12217 			if (tcp->tcp_fin_acked)
12218 				SET_TIME_WAIT(tcps, tcp, connp);
12219 			/*FALLTHRU*/
12220 		case TCPS_CLOSE_WAIT:
12221 			freemsg(mp);
12222 			goto xmit_check;
12223 		default:
12224 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
12225 			break;
12226 		}
12227 	}
12228 	if (flags & TH_FIN) {
12229 		/* Make sure we ack the fin */
12230 		flags |= TH_ACK_NEEDED;
12231 		if (!tcp->tcp_fin_rcvd) {
12232 			tcp->tcp_fin_rcvd = B_TRUE;
12233 			tcp->tcp_rnxt++;
12234 			tcpha = tcp->tcp_tcpha;
12235 			tcpha->tha_ack = htonl(tcp->tcp_rnxt);
12236 
12237 			/*
12238 			 * Generate the ordrel_ind at the end unless we
12239 			 * are an eager guy.
12240 			 * In the eager case tcp_rsrv will do this when run
12241 			 * after tcp_accept is done.
12242 			 */
12243 			if (tcp->tcp_listener == NULL &&
12244 			    !TCP_IS_DETACHED(tcp) && !tcp->tcp_hard_binding)
12245 				flags |= TH_ORDREL_NEEDED;
12246 			switch (tcp->tcp_state) {
12247 			case TCPS_SYN_RCVD:
12248 			case TCPS_ESTABLISHED:
12249 				tcp->tcp_state = TCPS_CLOSE_WAIT;
12250 				/* Keepalive? */
12251 				break;
12252 			case TCPS_FIN_WAIT_1:
12253 				if (!tcp->tcp_fin_acked) {
12254 					tcp->tcp_state = TCPS_CLOSING;
12255 					break;
12256 				}
12257 				/* FALLTHRU */
12258 			case TCPS_FIN_WAIT_2:
12259 				SET_TIME_WAIT(tcps, tcp, connp);
12260 				if (seg_len) {
12261 					/*
12262 					 * implies data piggybacked on FIN.
12263 					 * break to handle data.
12264 					 */
12265 					break;
12266 				}
12267 				freemsg(mp);
12268 				goto ack_check;
12269 			}
12270 		}
12271 	}
12272 	if (mp == NULL)
12273 		goto xmit_check;
12274 	if (seg_len == 0) {
12275 		freemsg(mp);
12276 		goto xmit_check;
12277 	}
12278 	if (mp->b_rptr == mp->b_wptr) {
12279 		/*
12280 		 * The header has been consumed, so we remove the
12281 		 * zero-length mblk here.
12282 		 */
12283 		mp1 = mp;
12284 		mp = mp->b_cont;
12285 		freeb(mp1);
12286 	}
12287 update_ack:
12288 	tcpha = tcp->tcp_tcpha;
12289 	tcp->tcp_rack_cnt++;
12290 	{
12291 		uint32_t cur_max;
12292 
12293 		cur_max = tcp->tcp_rack_cur_max;
12294 		if (tcp->tcp_rack_cnt >= cur_max) {
12295 			/*
12296 			 * We have more unacked data than we should - send
12297 			 * an ACK now.
12298 			 */
12299 			flags |= TH_ACK_NEEDED;
12300 			cur_max++;
12301 			if (cur_max > tcp->tcp_rack_abs_max)
12302 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
12303 			else
12304 				tcp->tcp_rack_cur_max = cur_max;
12305 		} else if (TCP_IS_DETACHED(tcp)) {
12306 			/* We don't have an ACK timer for detached TCP. */
12307 			flags |= TH_ACK_NEEDED;
12308 		} else if (seg_len < mss) {
12309 			/*
12310 			 * If we get a segment that is less than an mss, and we
12311 			 * already have unacknowledged data, and the amount
12312 			 * unacknowledged is not a multiple of mss, then we
12313 			 * better generate an ACK now.  Otherwise, this may be
12314 			 * the tail piece of a transaction, and we would rather
12315 			 * wait for the response.
12316 			 */
12317 			uint32_t udif;
12318 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
12319 			    (uintptr_t)INT_MAX);
12320 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
12321 			if (udif && (udif % mss))
12322 				flags |= TH_ACK_NEEDED;
12323 			else
12324 				flags |= TH_ACK_TIMER_NEEDED;
12325 		} else {
12326 			/* Start delayed ack timer */
12327 			flags |= TH_ACK_TIMER_NEEDED;
12328 		}
12329 	}
12330 	tcp->tcp_rnxt += seg_len;
12331 	tcpha->tha_ack = htonl(tcp->tcp_rnxt);
12332 
12333 	if (mp == NULL)
12334 		goto xmit_check;
12335 
12336 	/* Update SACK list */
12337 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
12338 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
12339 		    &(tcp->tcp_num_sack_blk));
12340 	}
12341 
12342 	if (tcp->tcp_urp_mp) {
12343 		tcp->tcp_urp_mp->b_cont = mp;
12344 		mp = tcp->tcp_urp_mp;
12345 		tcp->tcp_urp_mp = NULL;
12346 		/* Ready for a new signal. */
12347 		tcp->tcp_urp_last_valid = B_FALSE;
12348 #ifdef DEBUG
12349 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12350 		    "tcp_rput: sending exdata_ind %s",
12351 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
12352 #endif /* DEBUG */
12353 	}
12354 
12355 	/*
12356 	 * Check for ancillary data changes compared to last segment.
12357 	 */
12358 	if (connp->conn_recv_ancillary.crb_all != 0) {
12359 		mp = tcp_input_add_ancillary(tcp, mp, &ipp, ira);
12360 		if (mp == NULL)
12361 			return;
12362 	}
12363 
12364 	if (tcp->tcp_listener != NULL || tcp->tcp_hard_binding) {
12365 		/*
12366 		 * Side queue inbound data until the accept happens.
12367 		 * tcp_accept/tcp_rput drains this when the accept happens.
12368 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
12369 		 * T_EXDATA_IND) it is queued on b_next.
12370 		 * XXX Make urgent data use this. Requires:
12371 		 *	Removing tcp_listener check for TH_URG
12372 		 *	Making M_PCPROTO and MARK messages skip the eager case
12373 		 */
12374 
12375 		if (tcp->tcp_kssl_pending) {
12376 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
12377 			    mblk_t *, mp);
12378 			tcp_kssl_input(tcp, mp, ira->ira_cred);
12379 		} else {
12380 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
12381 		}
12382 	} else if (IPCL_IS_NONSTR(connp)) {
12383 		/*
12384 		 * Non-STREAMS socket
12385 		 *
12386 		 * Note that no KSSL processing is done here, because
12387 		 * KSSL is not supported for non-STREAMS sockets.
12388 		 */
12389 		boolean_t push = flags & (TH_PUSH|TH_FIN);
12390 		int error;
12391 
12392 		if ((*connp->conn_upcalls->su_recv)(
12393 		    connp->conn_upper_handle,
12394 		    mp, seg_len, 0, &error, &push) <= 0) {
12395 			/*
12396 			 * We should never be in middle of a
12397 			 * fallback, the squeue guarantees that.
12398 			 */
12399 			ASSERT(error != EOPNOTSUPP);
12400 			if (error == ENOSPC)
12401 				tcp->tcp_rwnd -= seg_len;
12402 		} else if (push) {
12403 			/* PUSH bit set and sockfs is not flow controlled */
12404 			flags |= tcp_rwnd_reopen(tcp);
12405 		}
12406 	} else {
12407 		/* STREAMS socket */
12408 		if (mp->b_datap->db_type != M_DATA ||
12409 		    (flags & TH_MARKNEXT_NEEDED)) {
12410 			if (tcp->tcp_rcv_list != NULL) {
12411 				flags |= tcp_rcv_drain(tcp);
12412 			}
12413 			ASSERT(tcp->tcp_rcv_list == NULL ||
12414 			    tcp->tcp_fused_sigurg);
12415 
12416 			if (flags & TH_MARKNEXT_NEEDED) {
12417 #ifdef DEBUG
12418 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12419 				    "tcp_rput: sending MSGMARKNEXT %s",
12420 				    tcp_display(tcp, NULL,
12421 				    DISP_PORT_ONLY));
12422 #endif /* DEBUG */
12423 				mp->b_flag |= MSGMARKNEXT;
12424 				flags &= ~TH_MARKNEXT_NEEDED;
12425 			}
12426 
12427 			/* Does this need SSL processing first? */
12428 			if ((tcp->tcp_kssl_ctx != NULL) &&
12429 			    (DB_TYPE(mp) == M_DATA)) {
12430 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
12431 				    mblk_t *, mp);
12432 				tcp_kssl_input(tcp, mp, ira->ira_cred);
12433 			} else {
12434 				if (is_system_labeled())
12435 					tcp_setcred_data(mp, ira);
12436 
12437 				putnext(connp->conn_rq, mp);
12438 				if (!canputnext(connp->conn_rq))
12439 					tcp->tcp_rwnd -= seg_len;
12440 			}
12441 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
12442 		    (DB_TYPE(mp) == M_DATA)) {
12443 			/* Does this need SSL processing first? */
12444 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
12445 			tcp_kssl_input(tcp, mp, ira->ira_cred);
12446 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
12447 		    tcp->tcp_rcv_cnt + seg_len >= connp->conn_rcvbuf >> 3) {
12448 			if (tcp->tcp_rcv_list != NULL) {
12449 				/*
12450 				 * Enqueue the new segment first and then
12451 				 * call tcp_rcv_drain() to send all data
12452 				 * up.  The other way to do this is to
12453 				 * send all queued data up and then call
12454 				 * putnext() to send the new segment up.
12455 				 * This way can remove the else part later
12456 				 * on.
12457 				 *
12458 				 * We don't do this to avoid one more call to
12459 				 * canputnext() as tcp_rcv_drain() needs to
12460 				 * call canputnext().
12461 				 */
12462 				tcp_rcv_enqueue(tcp, mp, seg_len,
12463 				    ira->ira_cred);
12464 				flags |= tcp_rcv_drain(tcp);
12465 			} else {
12466 				if (is_system_labeled())
12467 					tcp_setcred_data(mp, ira);
12468 
12469 				putnext(connp->conn_rq, mp);
12470 				if (!canputnext(connp->conn_rq))
12471 					tcp->tcp_rwnd -= seg_len;
12472 			}
12473 		} else {
12474 			/*
12475 			 * Enqueue all packets when processing an mblk
12476 			 * from the co queue and also enqueue normal packets.
12477 			 */
12478 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
12479 		}
12480 		/*
12481 		 * Make sure the timer is running if we have data waiting
12482 		 * for a push bit. This provides resiliency against
12483 		 * implementations that do not correctly generate push bits.
12484 		 */
12485 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
12486 			/*
12487 			 * The connection may be closed at this point, so don't
12488 			 * do anything for a detached tcp.
12489 			 */
12490 			if (!TCP_IS_DETACHED(tcp))
12491 				tcp->tcp_push_tid = TCP_TIMER(tcp,
12492 				    tcp_push_timer,
12493 				    MSEC_TO_TICK(
12494 				    tcps->tcps_push_timer_interval));
12495 		}
12496 	}
12497 
12498 xmit_check:
12499 	/* Is there anything left to do? */
12500 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
12501 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
12502 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
12503 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
12504 		goto done;
12505 
12506 	/* Any transmit work to do and a non-zero window? */
12507 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
12508 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
12509 		if (flags & TH_REXMIT_NEEDED) {
12510 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
12511 
12512 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
12513 			if (snd_size > mss)
12514 				snd_size = mss;
12515 			if (snd_size > tcp->tcp_swnd)
12516 				snd_size = tcp->tcp_swnd;
12517 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
12518 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
12519 			    B_TRUE);
12520 
12521 			if (mp1 != NULL) {
12522 				tcp->tcp_xmit_head->b_prev =
12523 				    (mblk_t *)LBOLT_FASTPATH;
12524 				tcp->tcp_csuna = tcp->tcp_snxt;
12525 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12526 				UPDATE_MIB(&tcps->tcps_mib,
12527 				    tcpRetransBytes, snd_size);
12528 				tcp_send_data(tcp, mp1);
12529 			}
12530 		}
12531 		if (flags & TH_NEED_SACK_REXMIT) {
12532 			tcp_sack_rxmit(tcp, &flags);
12533 		}
12534 		/*
12535 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
12536 		 * out new segment.  Note that tcp_rexmit should not be
12537 		 * set, otherwise TH_LIMIT_XMIT should not be set.
12538 		 */
12539 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
12540 			if (!tcp->tcp_rexmit) {
12541 				tcp_wput_data(tcp, NULL, B_FALSE);
12542 			} else {
12543 				tcp_ss_rexmit(tcp);
12544 			}
12545 		}
12546 		/*
12547 		 * Adjust tcp_cwnd back to normal value after sending
12548 		 * new data segments.
12549 		 */
12550 		if (flags & TH_LIMIT_XMIT) {
12551 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
12552 			/*
12553 			 * This will restart the timer.  Restarting the
12554 			 * timer is used to avoid a timeout before the
12555 			 * limited transmitted segment's ACK gets back.
12556 			 */
12557 			if (tcp->tcp_xmit_head != NULL)
12558 				tcp->tcp_xmit_head->b_prev =
12559 				    (mblk_t *)LBOLT_FASTPATH;
12560 		}
12561 
12562 		/* Anything more to do? */
12563 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
12564 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
12565 			goto done;
12566 	}
12567 ack_check:
12568 	if (flags & TH_SEND_URP_MARK) {
12569 		ASSERT(tcp->tcp_urp_mark_mp);
12570 		ASSERT(!IPCL_IS_NONSTR(connp));
12571 		/*
12572 		 * Send up any queued data and then send the mark message
12573 		 */
12574 		if (tcp->tcp_rcv_list != NULL) {
12575 			flags |= tcp_rcv_drain(tcp);
12576 
12577 		}
12578 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
12579 		mp1 = tcp->tcp_urp_mark_mp;
12580 		tcp->tcp_urp_mark_mp = NULL;
12581 		if (is_system_labeled())
12582 			tcp_setcred_data(mp1, ira);
12583 
12584 		putnext(connp->conn_rq, mp1);
12585 #ifdef DEBUG
12586 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12587 		    "tcp_rput: sending zero-length %s %s",
12588 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
12589 		    "MSGNOTMARKNEXT"),
12590 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
12591 #endif /* DEBUG */
12592 		flags &= ~TH_SEND_URP_MARK;
12593 	}
12594 	if (flags & TH_ACK_NEEDED) {
12595 		/*
12596 		 * Time to send an ack for some reason.
12597 		 */
12598 		mp1 = tcp_ack_mp(tcp);
12599 
12600 		if (mp1 != NULL) {
12601 			tcp_send_data(tcp, mp1);
12602 			BUMP_LOCAL(tcp->tcp_obsegs);
12603 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
12604 		}
12605 		if (tcp->tcp_ack_tid != 0) {
12606 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
12607 			tcp->tcp_ack_tid = 0;
12608 		}
12609 	}
12610 	if (flags & TH_ACK_TIMER_NEEDED) {
12611 		/*
12612 		 * Arrange for deferred ACK or push wait timeout.
12613 		 * Start timer if it is not already running.
12614 		 */
12615 		if (tcp->tcp_ack_tid == 0) {
12616 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
12617 			    MSEC_TO_TICK(tcp->tcp_localnet ?
12618 			    (clock_t)tcps->tcps_local_dack_interval :
12619 			    (clock_t)tcps->tcps_deferred_ack_interval));
12620 		}
12621 	}
12622 	if (flags & TH_ORDREL_NEEDED) {
12623 		/*
12624 		 * Send up the ordrel_ind unless we are an eager guy.
12625 		 * In the eager case tcp_rsrv will do this when run
12626 		 * after tcp_accept is done.
12627 		 */
12628 		ASSERT(tcp->tcp_listener == NULL);
12629 		ASSERT(!tcp->tcp_detached);
12630 
12631 		if (IPCL_IS_NONSTR(connp)) {
12632 			ASSERT(tcp->tcp_ordrel_mp == NULL);
12633 			tcp->tcp_ordrel_done = B_TRUE;
12634 			(*connp->conn_upcalls->su_opctl)
12635 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
12636 			goto done;
12637 		}
12638 
12639 		if (tcp->tcp_rcv_list != NULL) {
12640 			/*
12641 			 * Push any mblk(s) enqueued from co processing.
12642 			 */
12643 			flags |= tcp_rcv_drain(tcp);
12644 		}
12645 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
12646 
12647 		mp1 = tcp->tcp_ordrel_mp;
12648 		tcp->tcp_ordrel_mp = NULL;
12649 		tcp->tcp_ordrel_done = B_TRUE;
12650 		putnext(connp->conn_rq, mp1);
12651 	}
12652 done:
12653 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
12654 }
12655 
12656 /*
12657  * This routine adjusts next-to-send sequence number variables, in the
12658  * case where the reciever has shrunk it's window.
12659  */
12660 static void
12661 tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt)
12662 {
12663 	mblk_t *xmit_tail;
12664 	int32_t offset;
12665 
12666 	tcp->tcp_snxt = snxt;
12667 
12668 	/* Get the mblk, and the offset in it, as per the shrunk window */
12669 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
12670 	ASSERT(xmit_tail != NULL);
12671 	tcp->tcp_xmit_tail = xmit_tail;
12672 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr -
12673 	    xmit_tail->b_rptr - offset;
12674 }
12675 
12676 /*
12677  * This function does PAWS protection check. Returns B_TRUE if the
12678  * segment passes the PAWS test, else returns B_FALSE.
12679  */
12680 boolean_t
12681 tcp_paws_check(tcp_t *tcp, tcpha_t *tcpha, tcp_opt_t *tcpoptp)
12682 {
12683 	uint8_t	flags;
12684 	int	options;
12685 	uint8_t *up;
12686 	conn_t	*connp = tcp->tcp_connp;
12687 
12688 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
12689 	/*
12690 	 * If timestamp option is aligned nicely, get values inline,
12691 	 * otherwise call general routine to parse.  Only do that
12692 	 * if timestamp is the only option.
12693 	 */
12694 	if (TCP_HDR_LENGTH(tcpha) == (uint32_t)TCP_MIN_HEADER_LENGTH +
12695 	    TCPOPT_REAL_TS_LEN &&
12696 	    OK_32PTR((up = ((uint8_t *)tcpha) +
12697 	    TCP_MIN_HEADER_LENGTH)) &&
12698 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
12699 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
12700 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
12701 
12702 		options = TCP_OPT_TSTAMP_PRESENT;
12703 	} else {
12704 		if (tcp->tcp_snd_sack_ok) {
12705 			tcpoptp->tcp = tcp;
12706 		} else {
12707 			tcpoptp->tcp = NULL;
12708 		}
12709 		options = tcp_parse_options(tcpha, tcpoptp);
12710 	}
12711 
12712 	if (options & TCP_OPT_TSTAMP_PRESENT) {
12713 		/*
12714 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
12715 		 * regardless of the timestamp, page 18 RFC 1323.bis.
12716 		 */
12717 		if ((flags & TH_RST) == 0 &&
12718 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
12719 		    tcp->tcp_ts_recent)) {
12720 			if (TSTMP_LT(LBOLT_FASTPATH64,
12721 			    tcp->tcp_last_rcv_lbolt + PAWS_TIMEOUT)) {
12722 				/* This segment is not acceptable. */
12723 				return (B_FALSE);
12724 			} else {
12725 				/*
12726 				 * Connection has been idle for
12727 				 * too long.  Reset the timestamp
12728 				 * and assume the segment is valid.
12729 				 */
12730 				tcp->tcp_ts_recent =
12731 				    tcpoptp->tcp_opt_ts_val;
12732 			}
12733 		}
12734 	} else {
12735 		/*
12736 		 * If we don't get a timestamp on every packet, we
12737 		 * figure we can't really trust 'em, so we stop sending
12738 		 * and parsing them.
12739 		 */
12740 		tcp->tcp_snd_ts_ok = B_FALSE;
12741 
12742 		connp->conn_ht_iphc_len -= TCPOPT_REAL_TS_LEN;
12743 		connp->conn_ht_ulp_len -= TCPOPT_REAL_TS_LEN;
12744 		tcp->tcp_tcpha->tha_offset_and_reserved -= (3 << 4);
12745 		/*
12746 		 * Adjust the tcp_mss and tcp_cwnd accordingly. We avoid
12747 		 * doing a slow start here so as to not to lose on the
12748 		 * transfer rate built up so far.
12749 		 */
12750 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
12751 		if (tcp->tcp_snd_sack_ok) {
12752 			ASSERT(tcp->tcp_sack_info != NULL);
12753 			tcp->tcp_max_sack_blk = 4;
12754 		}
12755 	}
12756 	return (B_TRUE);
12757 }
12758 
12759 /*
12760  * Attach ancillary data to a received TCP segments for the
12761  * ancillary pieces requested by the application that are
12762  * different than they were in the previous data segment.
12763  *
12764  * Save the "current" values once memory allocation is ok so that
12765  * when memory allocation fails we can just wait for the next data segment.
12766  */
12767 static mblk_t *
12768 tcp_input_add_ancillary(tcp_t *tcp, mblk_t *mp, ip_pkt_t *ipp,
12769     ip_recv_attr_t *ira)
12770 {
12771 	struct T_optdata_ind *todi;
12772 	int optlen;
12773 	uchar_t *optptr;
12774 	struct T_opthdr *toh;
12775 	crb_t addflag;	/* Which pieces to add */
12776 	mblk_t *mp1;
12777 	conn_t	*connp = tcp->tcp_connp;
12778 
12779 	optlen = 0;
12780 	addflag.crb_all = 0;
12781 	/* If app asked for pktinfo and the index has changed ... */
12782 	if (connp->conn_recv_ancillary.crb_ip_recvpktinfo &&
12783 	    ira->ira_ruifindex != tcp->tcp_recvifindex) {
12784 		optlen += sizeof (struct T_opthdr) +
12785 		    sizeof (struct in6_pktinfo);
12786 		addflag.crb_ip_recvpktinfo = 1;
12787 	}
12788 	/* If app asked for hoplimit and it has changed ... */
12789 	if (connp->conn_recv_ancillary.crb_ipv6_recvhoplimit &&
12790 	    ipp->ipp_hoplimit != tcp->tcp_recvhops) {
12791 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
12792 		addflag.crb_ipv6_recvhoplimit = 1;
12793 	}
12794 	/* If app asked for tclass and it has changed ... */
12795 	if (connp->conn_recv_ancillary.crb_ipv6_recvtclass &&
12796 	    ipp->ipp_tclass != tcp->tcp_recvtclass) {
12797 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
12798 		addflag.crb_ipv6_recvtclass = 1;
12799 	}
12800 	/*
12801 	 * If app asked for hopbyhop headers and it has changed ...
12802 	 * For security labels, note that (1) security labels can't change on
12803 	 * a connected socket at all, (2) we're connected to at most one peer,
12804 	 * (3) if anything changes, then it must be some other extra option.
12805 	 */
12806 	if (connp->conn_recv_ancillary.crb_ipv6_recvhopopts &&
12807 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
12808 	    (ipp->ipp_fields & IPPF_HOPOPTS),
12809 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
12810 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
12811 		addflag.crb_ipv6_recvhopopts = 1;
12812 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
12813 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
12814 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
12815 			return (mp);
12816 	}
12817 	/* If app asked for dst headers before routing headers ... */
12818 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdrdstopts &&
12819 	    ip_cmpbuf(tcp->tcp_rthdrdstopts, tcp->tcp_rthdrdstoptslen,
12820 	    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12821 	    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen)) {
12822 		optlen += sizeof (struct T_opthdr) +
12823 		    ipp->ipp_rthdrdstoptslen;
12824 		addflag.crb_ipv6_recvrthdrdstopts = 1;
12825 		if (!ip_allocbuf((void **)&tcp->tcp_rthdrdstopts,
12826 		    &tcp->tcp_rthdrdstoptslen,
12827 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12828 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen))
12829 			return (mp);
12830 	}
12831 	/* If app asked for routing headers and it has changed ... */
12832 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdr &&
12833 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
12834 	    (ipp->ipp_fields & IPPF_RTHDR),
12835 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
12836 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
12837 		addflag.crb_ipv6_recvrthdr = 1;
12838 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
12839 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
12840 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
12841 			return (mp);
12842 	}
12843 	/* If app asked for dest headers and it has changed ... */
12844 	if ((connp->conn_recv_ancillary.crb_ipv6_recvdstopts ||
12845 	    connp->conn_recv_ancillary.crb_old_ipv6_recvdstopts) &&
12846 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
12847 	    (ipp->ipp_fields & IPPF_DSTOPTS),
12848 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
12849 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
12850 		addflag.crb_ipv6_recvdstopts = 1;
12851 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
12852 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
12853 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
12854 			return (mp);
12855 	}
12856 
12857 	if (optlen == 0) {
12858 		/* Nothing to add */
12859 		return (mp);
12860 	}
12861 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
12862 	if (mp1 == NULL) {
12863 		/*
12864 		 * Defer sending ancillary data until the next TCP segment
12865 		 * arrives.
12866 		 */
12867 		return (mp);
12868 	}
12869 	mp1->b_cont = mp;
12870 	mp = mp1;
12871 	mp->b_wptr += sizeof (*todi) + optlen;
12872 	mp->b_datap->db_type = M_PROTO;
12873 	todi = (struct T_optdata_ind *)mp->b_rptr;
12874 	todi->PRIM_type = T_OPTDATA_IND;
12875 	todi->DATA_flag = 1;	/* MORE data */
12876 	todi->OPT_length = optlen;
12877 	todi->OPT_offset = sizeof (*todi);
12878 	optptr = (uchar_t *)&todi[1];
12879 	/*
12880 	 * If app asked for pktinfo and the index has changed ...
12881 	 * Note that the local address never changes for the connection.
12882 	 */
12883 	if (addflag.crb_ip_recvpktinfo) {
12884 		struct in6_pktinfo *pkti;
12885 		uint_t ifindex;
12886 
12887 		ifindex = ira->ira_ruifindex;
12888 		toh = (struct T_opthdr *)optptr;
12889 		toh->level = IPPROTO_IPV6;
12890 		toh->name = IPV6_PKTINFO;
12891 		toh->len = sizeof (*toh) + sizeof (*pkti);
12892 		toh->status = 0;
12893 		optptr += sizeof (*toh);
12894 		pkti = (struct in6_pktinfo *)optptr;
12895 		pkti->ipi6_addr = connp->conn_laddr_v6;
12896 		pkti->ipi6_ifindex = ifindex;
12897 		optptr += sizeof (*pkti);
12898 		ASSERT(OK_32PTR(optptr));
12899 		/* Save as "last" value */
12900 		tcp->tcp_recvifindex = ifindex;
12901 	}
12902 	/* If app asked for hoplimit and it has changed ... */
12903 	if (addflag.crb_ipv6_recvhoplimit) {
12904 		toh = (struct T_opthdr *)optptr;
12905 		toh->level = IPPROTO_IPV6;
12906 		toh->name = IPV6_HOPLIMIT;
12907 		toh->len = sizeof (*toh) + sizeof (uint_t);
12908 		toh->status = 0;
12909 		optptr += sizeof (*toh);
12910 		*(uint_t *)optptr = ipp->ipp_hoplimit;
12911 		optptr += sizeof (uint_t);
12912 		ASSERT(OK_32PTR(optptr));
12913 		/* Save as "last" value */
12914 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
12915 	}
12916 	/* If app asked for tclass and it has changed ... */
12917 	if (addflag.crb_ipv6_recvtclass) {
12918 		toh = (struct T_opthdr *)optptr;
12919 		toh->level = IPPROTO_IPV6;
12920 		toh->name = IPV6_TCLASS;
12921 		toh->len = sizeof (*toh) + sizeof (uint_t);
12922 		toh->status = 0;
12923 		optptr += sizeof (*toh);
12924 		*(uint_t *)optptr = ipp->ipp_tclass;
12925 		optptr += sizeof (uint_t);
12926 		ASSERT(OK_32PTR(optptr));
12927 		/* Save as "last" value */
12928 		tcp->tcp_recvtclass = ipp->ipp_tclass;
12929 	}
12930 	if (addflag.crb_ipv6_recvhopopts) {
12931 		toh = (struct T_opthdr *)optptr;
12932 		toh->level = IPPROTO_IPV6;
12933 		toh->name = IPV6_HOPOPTS;
12934 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
12935 		toh->status = 0;
12936 		optptr += sizeof (*toh);
12937 		bcopy((uchar_t *)ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
12938 		optptr += ipp->ipp_hopoptslen;
12939 		ASSERT(OK_32PTR(optptr));
12940 		/* Save as last value */
12941 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
12942 		    (ipp->ipp_fields & IPPF_HOPOPTS),
12943 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
12944 	}
12945 	if (addflag.crb_ipv6_recvrthdrdstopts) {
12946 		toh = (struct T_opthdr *)optptr;
12947 		toh->level = IPPROTO_IPV6;
12948 		toh->name = IPV6_RTHDRDSTOPTS;
12949 		toh->len = sizeof (*toh) + ipp->ipp_rthdrdstoptslen;
12950 		toh->status = 0;
12951 		optptr += sizeof (*toh);
12952 		bcopy(ipp->ipp_rthdrdstopts, optptr, ipp->ipp_rthdrdstoptslen);
12953 		optptr += ipp->ipp_rthdrdstoptslen;
12954 		ASSERT(OK_32PTR(optptr));
12955 		/* Save as last value */
12956 		ip_savebuf((void **)&tcp->tcp_rthdrdstopts,
12957 		    &tcp->tcp_rthdrdstoptslen,
12958 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12959 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
12960 	}
12961 	if (addflag.crb_ipv6_recvrthdr) {
12962 		toh = (struct T_opthdr *)optptr;
12963 		toh->level = IPPROTO_IPV6;
12964 		toh->name = IPV6_RTHDR;
12965 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
12966 		toh->status = 0;
12967 		optptr += sizeof (*toh);
12968 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
12969 		optptr += ipp->ipp_rthdrlen;
12970 		ASSERT(OK_32PTR(optptr));
12971 		/* Save as last value */
12972 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
12973 		    (ipp->ipp_fields & IPPF_RTHDR),
12974 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
12975 	}
12976 	if (addflag.crb_ipv6_recvdstopts) {
12977 		toh = (struct T_opthdr *)optptr;
12978 		toh->level = IPPROTO_IPV6;
12979 		toh->name = IPV6_DSTOPTS;
12980 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
12981 		toh->status = 0;
12982 		optptr += sizeof (*toh);
12983 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
12984 		optptr += ipp->ipp_dstoptslen;
12985 		ASSERT(OK_32PTR(optptr));
12986 		/* Save as last value */
12987 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
12988 		    (ipp->ipp_fields & IPPF_DSTOPTS),
12989 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
12990 	}
12991 	ASSERT(optptr == mp->b_wptr);
12992 	return (mp);
12993 }
12994 
12995 /* ARGSUSED */
12996 static void
12997 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
12998 {
12999 	conn_t	*connp = (conn_t *)arg;
13000 	tcp_t	*tcp = connp->conn_tcp;
13001 	queue_t	*q = connp->conn_rq;
13002 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13003 
13004 	ASSERT(!IPCL_IS_NONSTR(connp));
13005 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
13006 	tcp->tcp_rsrv_mp = mp;
13007 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
13008 
13009 	TCP_STAT(tcps, tcp_rsrv_calls);
13010 
13011 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
13012 		return;
13013 	}
13014 
13015 	if (tcp->tcp_fused) {
13016 		tcp_fuse_backenable(tcp);
13017 		return;
13018 	}
13019 
13020 	if (canputnext(q)) {
13021 		/* Not flow-controlled, open rwnd */
13022 		tcp->tcp_rwnd = connp->conn_rcvbuf;
13023 
13024 		/*
13025 		 * Send back a window update immediately if TCP is above
13026 		 * ESTABLISHED state and the increase of the rcv window
13027 		 * that the other side knows is at least 1 MSS after flow
13028 		 * control is lifted.
13029 		 */
13030 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
13031 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
13032 			tcp_xmit_ctl(NULL, tcp,
13033 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
13034 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
13035 		}
13036 	}
13037 }
13038 
13039 /*
13040  * The read side service routine is called mostly when we get back-enabled as a
13041  * result of flow control relief.  Since we don't actually queue anything in
13042  * TCP, we have no data to send out of here.  What we do is clear the receive
13043  * window, and send out a window update.
13044  */
13045 static void
13046 tcp_rsrv(queue_t *q)
13047 {
13048 	conn_t		*connp = Q_TO_CONN(q);
13049 	tcp_t		*tcp = connp->conn_tcp;
13050 	mblk_t		*mp;
13051 
13052 	/* No code does a putq on the read side */
13053 	ASSERT(q->q_first == NULL);
13054 
13055 	/*
13056 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
13057 	 * been run.  So just return.
13058 	 */
13059 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
13060 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
13061 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
13062 		return;
13063 	}
13064 	tcp->tcp_rsrv_mp = NULL;
13065 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
13066 
13067 	CONN_INC_REF(connp);
13068 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
13069 	    NULL, SQ_PROCESS, SQTAG_TCP_RSRV);
13070 }
13071 
13072 /*
13073  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
13074  * We do not allow the receive window to shrink.  After setting rwnd,
13075  * set the flow control hiwat of the stream.
13076  *
13077  * This function is called in 2 cases:
13078  *
13079  * 1) Before data transfer begins, in tcp_input_listener() for accepting a
13080  *    connection (passive open) and in tcp_input_data() for active connect.
13081  *    This is called after tcp_mss_set() when the desired MSS value is known.
13082  *    This makes sure that our window size is a mutiple of the other side's
13083  *    MSS.
13084  * 2) Handling SO_RCVBUF option.
13085  *
13086  * It is ASSUMED that the requested size is a multiple of the current MSS.
13087  *
13088  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
13089  * user requests so.
13090  */
13091 int
13092 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
13093 {
13094 	uint32_t	mss = tcp->tcp_mss;
13095 	uint32_t	old_max_rwnd;
13096 	uint32_t	max_transmittable_rwnd;
13097 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
13098 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13099 	conn_t		*connp = tcp->tcp_connp;
13100 
13101 	/*
13102 	 * Insist on a receive window that is at least
13103 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
13104 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
13105 	 * and delayed acknowledgement.
13106 	 */
13107 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
13108 
13109 	if (tcp->tcp_fused) {
13110 		size_t sth_hiwat;
13111 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
13112 
13113 		ASSERT(peer_tcp != NULL);
13114 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
13115 		if (!tcp_detached) {
13116 			(void) proto_set_rx_hiwat(connp->conn_rq, connp,
13117 			    sth_hiwat);
13118 			tcp_set_recv_threshold(tcp, sth_hiwat >> 3);
13119 		}
13120 
13121 		/* Caller could have changed tcp_rwnd; update tha_win */
13122 		if (tcp->tcp_tcpha != NULL) {
13123 			tcp->tcp_tcpha->tha_win =
13124 			    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
13125 		}
13126 		if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
13127 			tcp->tcp_cwnd_max = rwnd;
13128 
13129 		/*
13130 		 * In the fusion case, the maxpsz stream head value of
13131 		 * our peer is set according to its send buffer size
13132 		 * and our receive buffer size; since the latter may
13133 		 * have changed we need to update the peer's maxpsz.
13134 		 */
13135 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
13136 		return (sth_hiwat);
13137 	}
13138 
13139 	if (tcp_detached)
13140 		old_max_rwnd = tcp->tcp_rwnd;
13141 	else
13142 		old_max_rwnd = connp->conn_rcvbuf;
13143 
13144 
13145 	/*
13146 	 * If window size info has already been exchanged, TCP should not
13147 	 * shrink the window.  Shrinking window is doable if done carefully.
13148 	 * We may add that support later.  But so far there is not a real
13149 	 * need to do that.
13150 	 */
13151 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
13152 		/* MSS may have changed, do a round up again. */
13153 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
13154 	}
13155 
13156 	/*
13157 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
13158 	 * can be applied even before the window scale option is decided.
13159 	 */
13160 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
13161 	if (rwnd > max_transmittable_rwnd) {
13162 		rwnd = max_transmittable_rwnd -
13163 		    (max_transmittable_rwnd % mss);
13164 		if (rwnd < mss)
13165 			rwnd = max_transmittable_rwnd;
13166 		/*
13167 		 * If we're over the limit we may have to back down tcp_rwnd.
13168 		 * The increment below won't work for us. So we set all three
13169 		 * here and the increment below will have no effect.
13170 		 */
13171 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
13172 	}
13173 	if (tcp->tcp_localnet) {
13174 		tcp->tcp_rack_abs_max =
13175 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
13176 	} else {
13177 		/*
13178 		 * For a remote host on a different subnet (through a router),
13179 		 * we ack every other packet to be conforming to RFC1122.
13180 		 * tcp_deferred_acks_max is default to 2.
13181 		 */
13182 		tcp->tcp_rack_abs_max =
13183 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
13184 	}
13185 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
13186 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
13187 	else
13188 		tcp->tcp_rack_cur_max = 0;
13189 	/*
13190 	 * Increment the current rwnd by the amount the maximum grew (we
13191 	 * can not overwrite it since we might be in the middle of a
13192 	 * connection.)
13193 	 */
13194 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
13195 	connp->conn_rcvbuf = rwnd;
13196 
13197 	/* Are we already connected? */
13198 	if (tcp->tcp_tcpha != NULL) {
13199 		tcp->tcp_tcpha->tha_win =
13200 		    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
13201 	}
13202 
13203 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
13204 		tcp->tcp_cwnd_max = rwnd;
13205 
13206 	if (tcp_detached)
13207 		return (rwnd);
13208 
13209 	tcp_set_recv_threshold(tcp, rwnd >> 3);
13210 
13211 	(void) proto_set_rx_hiwat(connp->conn_rq, connp, rwnd);
13212 	return (rwnd);
13213 }
13214 
13215 /*
13216  * Return SNMP stuff in buffer in mpdata.
13217  */
13218 mblk_t *
13219 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
13220 {
13221 	mblk_t			*mpdata;
13222 	mblk_t			*mp_conn_ctl = NULL;
13223 	mblk_t			*mp_conn_tail;
13224 	mblk_t			*mp_attr_ctl = NULL;
13225 	mblk_t			*mp_attr_tail;
13226 	mblk_t			*mp6_conn_ctl = NULL;
13227 	mblk_t			*mp6_conn_tail;
13228 	mblk_t			*mp6_attr_ctl = NULL;
13229 	mblk_t			*mp6_attr_tail;
13230 	struct opthdr		*optp;
13231 	mib2_tcpConnEntry_t	tce;
13232 	mib2_tcp6ConnEntry_t	tce6;
13233 	mib2_transportMLPEntry_t mlp;
13234 	connf_t			*connfp;
13235 	int			i;
13236 	boolean_t 		ispriv;
13237 	zoneid_t 		zoneid;
13238 	int			v4_conn_idx;
13239 	int			v6_conn_idx;
13240 	conn_t			*connp = Q_TO_CONN(q);
13241 	tcp_stack_t		*tcps;
13242 	ip_stack_t		*ipst;
13243 	mblk_t			*mp2ctl;
13244 
13245 	/*
13246 	 * make a copy of the original message
13247 	 */
13248 	mp2ctl = copymsg(mpctl);
13249 
13250 	if (mpctl == NULL ||
13251 	    (mpdata = mpctl->b_cont) == NULL ||
13252 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
13253 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
13254 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
13255 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
13256 		freemsg(mp_conn_ctl);
13257 		freemsg(mp_attr_ctl);
13258 		freemsg(mp6_conn_ctl);
13259 		freemsg(mp6_attr_ctl);
13260 		freemsg(mpctl);
13261 		freemsg(mp2ctl);
13262 		return (NULL);
13263 	}
13264 
13265 	ipst = connp->conn_netstack->netstack_ip;
13266 	tcps = connp->conn_netstack->netstack_tcp;
13267 
13268 	/* build table of connections -- need count in fixed part */
13269 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
13270 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
13271 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
13272 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
13273 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
13274 
13275 	ispriv =
13276 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
13277 	zoneid = Q_TO_CONN(q)->conn_zoneid;
13278 
13279 	v4_conn_idx = v6_conn_idx = 0;
13280 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
13281 
13282 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
13283 		ipst = tcps->tcps_netstack->netstack_ip;
13284 
13285 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
13286 
13287 		connp = NULL;
13288 
13289 		while ((connp =
13290 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
13291 			tcp_t *tcp;
13292 			boolean_t needattr;
13293 
13294 			if (connp->conn_zoneid != zoneid)
13295 				continue;	/* not in this zone */
13296 
13297 			tcp = connp->conn_tcp;
13298 			UPDATE_MIB(&tcps->tcps_mib,
13299 			    tcpHCInSegs, tcp->tcp_ibsegs);
13300 			tcp->tcp_ibsegs = 0;
13301 			UPDATE_MIB(&tcps->tcps_mib,
13302 			    tcpHCOutSegs, tcp->tcp_obsegs);
13303 			tcp->tcp_obsegs = 0;
13304 
13305 			tce6.tcp6ConnState = tce.tcpConnState =
13306 			    tcp_snmp_state(tcp);
13307 			if (tce.tcpConnState == MIB2_TCP_established ||
13308 			    tce.tcpConnState == MIB2_TCP_closeWait)
13309 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
13310 
13311 			needattr = B_FALSE;
13312 			bzero(&mlp, sizeof (mlp));
13313 			if (connp->conn_mlp_type != mlptSingle) {
13314 				if (connp->conn_mlp_type == mlptShared ||
13315 				    connp->conn_mlp_type == mlptBoth)
13316 					mlp.tme_flags |= MIB2_TMEF_SHARED;
13317 				if (connp->conn_mlp_type == mlptPrivate ||
13318 				    connp->conn_mlp_type == mlptBoth)
13319 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
13320 				needattr = B_TRUE;
13321 			}
13322 			if (connp->conn_anon_mlp) {
13323 				mlp.tme_flags |= MIB2_TMEF_ANONMLP;
13324 				needattr = B_TRUE;
13325 			}
13326 			switch (connp->conn_mac_mode) {
13327 			case CONN_MAC_DEFAULT:
13328 				break;
13329 			case CONN_MAC_AWARE:
13330 				mlp.tme_flags |= MIB2_TMEF_MACEXEMPT;
13331 				needattr = B_TRUE;
13332 				break;
13333 			case CONN_MAC_IMPLICIT:
13334 				mlp.tme_flags |= MIB2_TMEF_MACIMPLICIT;
13335 				needattr = B_TRUE;
13336 				break;
13337 			}
13338 			if (connp->conn_ixa->ixa_tsl != NULL) {
13339 				ts_label_t *tsl;
13340 
13341 				tsl = connp->conn_ixa->ixa_tsl;
13342 				mlp.tme_flags |= MIB2_TMEF_IS_LABELED;
13343 				mlp.tme_doi = label2doi(tsl);
13344 				mlp.tme_label = *label2bslabel(tsl);
13345 				needattr = B_TRUE;
13346 			}
13347 
13348 			/* Create a message to report on IPv6 entries */
13349 			if (connp->conn_ipversion == IPV6_VERSION) {
13350 			tce6.tcp6ConnLocalAddress = connp->conn_laddr_v6;
13351 			tce6.tcp6ConnRemAddress = connp->conn_faddr_v6;
13352 			tce6.tcp6ConnLocalPort = ntohs(connp->conn_lport);
13353 			tce6.tcp6ConnRemPort = ntohs(connp->conn_fport);
13354 			if (connp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET) {
13355 				tce6.tcp6ConnIfIndex =
13356 				    connp->conn_ixa->ixa_scopeid;
13357 			} else {
13358 				tce6.tcp6ConnIfIndex = connp->conn_bound_if;
13359 			}
13360 			/* Don't want just anybody seeing these... */
13361 			if (ispriv) {
13362 				tce6.tcp6ConnEntryInfo.ce_snxt =
13363 				    tcp->tcp_snxt;
13364 				tce6.tcp6ConnEntryInfo.ce_suna =
13365 				    tcp->tcp_suna;
13366 				tce6.tcp6ConnEntryInfo.ce_rnxt =
13367 				    tcp->tcp_rnxt;
13368 				tce6.tcp6ConnEntryInfo.ce_rack =
13369 				    tcp->tcp_rack;
13370 			} else {
13371 				/*
13372 				 * Netstat, unfortunately, uses this to
13373 				 * get send/receive queue sizes.  How to fix?
13374 				 * Why not compute the difference only?
13375 				 */
13376 				tce6.tcp6ConnEntryInfo.ce_snxt =
13377 				    tcp->tcp_snxt - tcp->tcp_suna;
13378 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
13379 				tce6.tcp6ConnEntryInfo.ce_rnxt =
13380 				    tcp->tcp_rnxt - tcp->tcp_rack;
13381 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
13382 			}
13383 
13384 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
13385 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
13386 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
13387 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
13388 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
13389 
13390 			tce6.tcp6ConnCreationProcess =
13391 			    (connp->conn_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
13392 			    connp->conn_cpid;
13393 			tce6.tcp6ConnCreationTime = connp->conn_open_time;
13394 
13395 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
13396 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
13397 
13398 			mlp.tme_connidx = v6_conn_idx++;
13399 			if (needattr)
13400 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
13401 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
13402 			}
13403 			/*
13404 			 * Create an IPv4 table entry for IPv4 entries and also
13405 			 * for IPv6 entries which are bound to in6addr_any
13406 			 * but don't have IPV6_V6ONLY set.
13407 			 * (i.e. anything an IPv4 peer could connect to)
13408 			 */
13409 			if (connp->conn_ipversion == IPV4_VERSION ||
13410 			    (tcp->tcp_state <= TCPS_LISTEN &&
13411 			    !connp->conn_ipv6_v6only &&
13412 			    IN6_IS_ADDR_UNSPECIFIED(&connp->conn_laddr_v6))) {
13413 				if (connp->conn_ipversion == IPV6_VERSION) {
13414 					tce.tcpConnRemAddress = INADDR_ANY;
13415 					tce.tcpConnLocalAddress = INADDR_ANY;
13416 				} else {
13417 					tce.tcpConnRemAddress =
13418 					    connp->conn_faddr_v4;
13419 					tce.tcpConnLocalAddress =
13420 					    connp->conn_laddr_v4;
13421 				}
13422 				tce.tcpConnLocalPort = ntohs(connp->conn_lport);
13423 				tce.tcpConnRemPort = ntohs(connp->conn_fport);
13424 				/* Don't want just anybody seeing these... */
13425 				if (ispriv) {
13426 					tce.tcpConnEntryInfo.ce_snxt =
13427 					    tcp->tcp_snxt;
13428 					tce.tcpConnEntryInfo.ce_suna =
13429 					    tcp->tcp_suna;
13430 					tce.tcpConnEntryInfo.ce_rnxt =
13431 					    tcp->tcp_rnxt;
13432 					tce.tcpConnEntryInfo.ce_rack =
13433 					    tcp->tcp_rack;
13434 				} else {
13435 					/*
13436 					 * Netstat, unfortunately, uses this to
13437 					 * get send/receive queue sizes.  How
13438 					 * to fix?
13439 					 * Why not compute the difference only?
13440 					 */
13441 					tce.tcpConnEntryInfo.ce_snxt =
13442 					    tcp->tcp_snxt - tcp->tcp_suna;
13443 					tce.tcpConnEntryInfo.ce_suna = 0;
13444 					tce.tcpConnEntryInfo.ce_rnxt =
13445 					    tcp->tcp_rnxt - tcp->tcp_rack;
13446 					tce.tcpConnEntryInfo.ce_rack = 0;
13447 				}
13448 
13449 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
13450 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
13451 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
13452 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
13453 				tce.tcpConnEntryInfo.ce_state =
13454 				    tcp->tcp_state;
13455 
13456 				tce.tcpConnCreationProcess =
13457 				    (connp->conn_cpid < 0) ?
13458 				    MIB2_UNKNOWN_PROCESS :
13459 				    connp->conn_cpid;
13460 				tce.tcpConnCreationTime = connp->conn_open_time;
13461 
13462 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
13463 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
13464 
13465 				mlp.tme_connidx = v4_conn_idx++;
13466 				if (needattr)
13467 					(void) snmp_append_data2(
13468 					    mp_attr_ctl->b_cont,
13469 					    &mp_attr_tail, (char *)&mlp,
13470 					    sizeof (mlp));
13471 			}
13472 		}
13473 	}
13474 
13475 	/* fixed length structure for IPv4 and IPv6 counters */
13476 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
13477 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
13478 	    sizeof (mib2_tcp6ConnEntry_t));
13479 	/* synchronize 32- and 64-bit counters */
13480 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
13481 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
13482 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
13483 	optp->level = MIB2_TCP;
13484 	optp->name = 0;
13485 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
13486 	    sizeof (tcps->tcps_mib));
13487 	optp->len = msgdsize(mpdata);
13488 	qreply(q, mpctl);
13489 
13490 	/* table of connections... */
13491 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
13492 	    sizeof (struct T_optmgmt_ack)];
13493 	optp->level = MIB2_TCP;
13494 	optp->name = MIB2_TCP_CONN;
13495 	optp->len = msgdsize(mp_conn_ctl->b_cont);
13496 	qreply(q, mp_conn_ctl);
13497 
13498 	/* table of MLP attributes... */
13499 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
13500 	    sizeof (struct T_optmgmt_ack)];
13501 	optp->level = MIB2_TCP;
13502 	optp->name = EXPER_XPORT_MLP;
13503 	optp->len = msgdsize(mp_attr_ctl->b_cont);
13504 	if (optp->len == 0)
13505 		freemsg(mp_attr_ctl);
13506 	else
13507 		qreply(q, mp_attr_ctl);
13508 
13509 	/* table of IPv6 connections... */
13510 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
13511 	    sizeof (struct T_optmgmt_ack)];
13512 	optp->level = MIB2_TCP6;
13513 	optp->name = MIB2_TCP6_CONN;
13514 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
13515 	qreply(q, mp6_conn_ctl);
13516 
13517 	/* table of IPv6 MLP attributes... */
13518 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
13519 	    sizeof (struct T_optmgmt_ack)];
13520 	optp->level = MIB2_TCP6;
13521 	optp->name = EXPER_XPORT_MLP;
13522 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
13523 	if (optp->len == 0)
13524 		freemsg(mp6_attr_ctl);
13525 	else
13526 		qreply(q, mp6_attr_ctl);
13527 	return (mp2ctl);
13528 }
13529 
13530 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
13531 /* ARGSUSED */
13532 int
13533 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
13534 {
13535 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
13536 
13537 	switch (level) {
13538 	case MIB2_TCP:
13539 		switch (name) {
13540 		case 13:
13541 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
13542 				return (0);
13543 			/* TODO: delete entry defined by tce */
13544 			return (1);
13545 		default:
13546 			return (0);
13547 		}
13548 	default:
13549 		return (1);
13550 	}
13551 }
13552 
13553 /* Translate TCP state to MIB2 TCP state. */
13554 static int
13555 tcp_snmp_state(tcp_t *tcp)
13556 {
13557 	if (tcp == NULL)
13558 		return (0);
13559 
13560 	switch (tcp->tcp_state) {
13561 	case TCPS_CLOSED:
13562 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
13563 	case TCPS_BOUND:
13564 		return (MIB2_TCP_closed);
13565 	case TCPS_LISTEN:
13566 		return (MIB2_TCP_listen);
13567 	case TCPS_SYN_SENT:
13568 		return (MIB2_TCP_synSent);
13569 	case TCPS_SYN_RCVD:
13570 		return (MIB2_TCP_synReceived);
13571 	case TCPS_ESTABLISHED:
13572 		return (MIB2_TCP_established);
13573 	case TCPS_CLOSE_WAIT:
13574 		return (MIB2_TCP_closeWait);
13575 	case TCPS_FIN_WAIT_1:
13576 		return (MIB2_TCP_finWait1);
13577 	case TCPS_CLOSING:
13578 		return (MIB2_TCP_closing);
13579 	case TCPS_LAST_ACK:
13580 		return (MIB2_TCP_lastAck);
13581 	case TCPS_FIN_WAIT_2:
13582 		return (MIB2_TCP_finWait2);
13583 	case TCPS_TIME_WAIT:
13584 		return (MIB2_TCP_timeWait);
13585 	default:
13586 		return (0);
13587 	}
13588 }
13589 
13590 /*
13591  * tcp_timer is the timer service routine.  It handles the retransmission,
13592  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
13593  * from the state of the tcp instance what kind of action needs to be done
13594  * at the time it is called.
13595  */
13596 static void
13597 tcp_timer(void *arg)
13598 {
13599 	mblk_t		*mp;
13600 	clock_t		first_threshold;
13601 	clock_t		second_threshold;
13602 	clock_t		ms;
13603 	uint32_t	mss;
13604 	conn_t		*connp = (conn_t *)arg;
13605 	tcp_t		*tcp = connp->conn_tcp;
13606 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13607 
13608 	tcp->tcp_timer_tid = 0;
13609 
13610 	if (tcp->tcp_fused)
13611 		return;
13612 
13613 	first_threshold =  tcp->tcp_first_timer_threshold;
13614 	second_threshold = tcp->tcp_second_timer_threshold;
13615 	switch (tcp->tcp_state) {
13616 	case TCPS_IDLE:
13617 	case TCPS_BOUND:
13618 	case TCPS_LISTEN:
13619 		return;
13620 	case TCPS_SYN_RCVD: {
13621 		tcp_t	*listener = tcp->tcp_listener;
13622 
13623 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
13624 			/* it's our first timeout */
13625 			tcp->tcp_syn_rcvd_timeout = 1;
13626 			mutex_enter(&listener->tcp_eager_lock);
13627 			listener->tcp_syn_rcvd_timeout++;
13628 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
13629 				/*
13630 				 * Make this eager available for drop if we
13631 				 * need to drop one to accomodate a new
13632 				 * incoming SYN request.
13633 				 */
13634 				MAKE_DROPPABLE(listener, tcp);
13635 			}
13636 			if (!listener->tcp_syn_defense &&
13637 			    (listener->tcp_syn_rcvd_timeout >
13638 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
13639 			    (tcps->tcps_conn_req_max_q0 > 200)) {
13640 				/* We may be under attack. Put on a defense. */
13641 				listener->tcp_syn_defense = B_TRUE;
13642 				cmn_err(CE_WARN, "High TCP connect timeout "
13643 				    "rate! System (port %d) may be under a "
13644 				    "SYN flood attack!",
13645 				    ntohs(listener->tcp_connp->conn_lport));
13646 
13647 				listener->tcp_ip_addr_cache = kmem_zalloc(
13648 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
13649 				    KM_NOSLEEP);
13650 			}
13651 			mutex_exit(&listener->tcp_eager_lock);
13652 		} else if (listener != NULL) {
13653 			mutex_enter(&listener->tcp_eager_lock);
13654 			tcp->tcp_syn_rcvd_timeout++;
13655 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
13656 			    !tcp->tcp_closemp_used) {
13657 				/*
13658 				 * This is our second timeout. Put the tcp in
13659 				 * the list of droppable eagers to allow it to
13660 				 * be dropped, if needed. We don't check
13661 				 * whether tcp_dontdrop is set or not to
13662 				 * protect ourselve from a SYN attack where a
13663 				 * remote host can spoof itself as one of the
13664 				 * good IP source and continue to hold
13665 				 * resources too long.
13666 				 */
13667 				MAKE_DROPPABLE(listener, tcp);
13668 			}
13669 			mutex_exit(&listener->tcp_eager_lock);
13670 		}
13671 	}
13672 		/* FALLTHRU */
13673 	case TCPS_SYN_SENT:
13674 		first_threshold =  tcp->tcp_first_ctimer_threshold;
13675 		second_threshold = tcp->tcp_second_ctimer_threshold;
13676 		break;
13677 	case TCPS_ESTABLISHED:
13678 	case TCPS_FIN_WAIT_1:
13679 	case TCPS_CLOSING:
13680 	case TCPS_CLOSE_WAIT:
13681 	case TCPS_LAST_ACK:
13682 		/* If we have data to rexmit */
13683 		if (tcp->tcp_suna != tcp->tcp_snxt) {
13684 			clock_t	time_to_wait;
13685 
13686 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
13687 			if (!tcp->tcp_xmit_head)
13688 				break;
13689 			time_to_wait = ddi_get_lbolt() -
13690 			    (clock_t)tcp->tcp_xmit_head->b_prev;
13691 			time_to_wait = tcp->tcp_rto -
13692 			    TICK_TO_MSEC(time_to_wait);
13693 			/*
13694 			 * If the timer fires too early, 1 clock tick earlier,
13695 			 * restart the timer.
13696 			 */
13697 			if (time_to_wait > msec_per_tick) {
13698 				TCP_STAT(tcps, tcp_timer_fire_early);
13699 				TCP_TIMER_RESTART(tcp, time_to_wait);
13700 				return;
13701 			}
13702 			/*
13703 			 * When we probe zero windows, we force the swnd open.
13704 			 * If our peer acks with a closed window swnd will be
13705 			 * set to zero by tcp_rput(). As long as we are
13706 			 * receiving acks tcp_rput will
13707 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
13708 			 * first and second interval actions.  NOTE: the timer
13709 			 * interval is allowed to continue its exponential
13710 			 * backoff.
13711 			 */
13712 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
13713 				if (connp->conn_debug) {
13714 					(void) strlog(TCP_MOD_ID, 0, 1,
13715 					    SL_TRACE, "tcp_timer: zero win");
13716 				}
13717 			} else {
13718 				/*
13719 				 * After retransmission, we need to do
13720 				 * slow start.  Set the ssthresh to one
13721 				 * half of current effective window and
13722 				 * cwnd to one MSS.  Also reset
13723 				 * tcp_cwnd_cnt.
13724 				 *
13725 				 * Note that if tcp_ssthresh is reduced because
13726 				 * of ECN, do not reduce it again unless it is
13727 				 * already one window of data away (tcp_cwr
13728 				 * should then be cleared) or this is a
13729 				 * timeout for a retransmitted segment.
13730 				 */
13731 				uint32_t npkt;
13732 
13733 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
13734 					npkt = ((tcp->tcp_timer_backoff ?
13735 					    tcp->tcp_cwnd_ssthresh :
13736 					    tcp->tcp_snxt -
13737 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
13738 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
13739 					    tcp->tcp_mss;
13740 				}
13741 				tcp->tcp_cwnd = tcp->tcp_mss;
13742 				tcp->tcp_cwnd_cnt = 0;
13743 				if (tcp->tcp_ecn_ok) {
13744 					tcp->tcp_cwr = B_TRUE;
13745 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13746 					tcp->tcp_ecn_cwr_sent = B_FALSE;
13747 				}
13748 			}
13749 			break;
13750 		}
13751 		/*
13752 		 * We have something to send yet we cannot send.  The
13753 		 * reason can be:
13754 		 *
13755 		 * 1. Zero send window: we need to do zero window probe.
13756 		 * 2. Zero cwnd: because of ECN, we need to "clock out
13757 		 * segments.
13758 		 * 3. SWS avoidance: receiver may have shrunk window,
13759 		 * reset our knowledge.
13760 		 *
13761 		 * Note that condition 2 can happen with either 1 or
13762 		 * 3.  But 1 and 3 are exclusive.
13763 		 */
13764 		if (tcp->tcp_unsent != 0) {
13765 			/*
13766 			 * Should not hold the zero-copy messages for too long.
13767 			 */
13768 			if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13769 				tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13770 				    tcp->tcp_xmit_head, B_TRUE);
13771 
13772 			if (tcp->tcp_cwnd == 0) {
13773 				/*
13774 				 * Set tcp_cwnd to 1 MSS so that a
13775 				 * new segment can be sent out.  We
13776 				 * are "clocking out" new data when
13777 				 * the network is really congested.
13778 				 */
13779 				ASSERT(tcp->tcp_ecn_ok);
13780 				tcp->tcp_cwnd = tcp->tcp_mss;
13781 			}
13782 			if (tcp->tcp_swnd == 0) {
13783 				/* Extend window for zero window probe */
13784 				tcp->tcp_swnd++;
13785 				tcp->tcp_zero_win_probe = B_TRUE;
13786 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
13787 			} else {
13788 				/*
13789 				 * Handle timeout from sender SWS avoidance.
13790 				 * Reset our knowledge of the max send window
13791 				 * since the receiver might have reduced its
13792 				 * receive buffer.  Avoid setting tcp_max_swnd
13793 				 * to one since that will essentially disable
13794 				 * the SWS checks.
13795 				 *
13796 				 * Note that since we don't have a SWS
13797 				 * state variable, if the timeout is set
13798 				 * for ECN but not for SWS, this
13799 				 * code will also be executed.  This is
13800 				 * fine as tcp_max_swnd is updated
13801 				 * constantly and it will not affect
13802 				 * anything.
13803 				 */
13804 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
13805 			}
13806 			tcp_wput_data(tcp, NULL, B_FALSE);
13807 			return;
13808 		}
13809 		/* Is there a FIN that needs to be to re retransmitted? */
13810 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13811 		    !tcp->tcp_fin_acked)
13812 			break;
13813 		/* Nothing to do, return without restarting timer. */
13814 		TCP_STAT(tcps, tcp_timer_fire_miss);
13815 		return;
13816 	case TCPS_FIN_WAIT_2:
13817 		/*
13818 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
13819 		 * We waited some time for for peer's FIN, but it hasn't
13820 		 * arrived.  We flush the connection now to avoid
13821 		 * case where the peer has rebooted.
13822 		 */
13823 		if (TCP_IS_DETACHED(tcp)) {
13824 			(void) tcp_clean_death(tcp, 0, 23);
13825 		} else {
13826 			TCP_TIMER_RESTART(tcp,
13827 			    tcps->tcps_fin_wait_2_flush_interval);
13828 		}
13829 		return;
13830 	case TCPS_TIME_WAIT:
13831 		(void) tcp_clean_death(tcp, 0, 24);
13832 		return;
13833 	default:
13834 		if (connp->conn_debug) {
13835 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
13836 			    "tcp_timer: strange state (%d) %s",
13837 			    tcp->tcp_state, tcp_display(tcp, NULL,
13838 			    DISP_PORT_ONLY));
13839 		}
13840 		return;
13841 	}
13842 
13843 	/*
13844 	 * If the system is under memory pressure or the max number of
13845 	 * connections have been established for the listener, be more
13846 	 * aggressive in aborting connections.
13847 	 */
13848 	if (tcps->tcps_reclaim || (tcp->tcp_listen_cnt != NULL &&
13849 	    tcp->tcp_listen_cnt->tlc_cnt > tcp->tcp_listen_cnt->tlc_max)) {
13850 		second_threshold = tcp_early_abort * SECONDS;
13851 	}
13852 
13853 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
13854 		/*
13855 		 * Should not hold the zero-copy messages for too long.
13856 		 */
13857 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13858 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13859 			    tcp->tcp_xmit_head, B_TRUE);
13860 
13861 		/*
13862 		 * For zero window probe, we need to send indefinitely,
13863 		 * unless we have not heard from the other side for some
13864 		 * time...
13865 		 */
13866 		if ((tcp->tcp_zero_win_probe == 0) ||
13867 		    (TICK_TO_MSEC(ddi_get_lbolt() - tcp->tcp_last_recv_time) >
13868 		    second_threshold)) {
13869 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
13870 			/*
13871 			 * If TCP is in SYN_RCVD state, send back a
13872 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
13873 			 * should be zero in TCPS_SYN_RCVD state.
13874 			 */
13875 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
13876 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
13877 				    "in SYN_RCVD",
13878 				    tcp, tcp->tcp_snxt,
13879 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
13880 			}
13881 			(void) tcp_clean_death(tcp,
13882 			    tcp->tcp_client_errno ?
13883 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
13884 			return;
13885 		} else {
13886 			/*
13887 			 * If the system is under memory pressure, we also
13888 			 * abort connection in zero window probing.
13889 			 */
13890 			if (tcps->tcps_reclaim) {
13891 				(void) tcp_clean_death(tcp,
13892 				    tcp->tcp_client_errno ?
13893 				    tcp->tcp_client_errno : ETIMEDOUT, 25);
13894 				return;
13895 			}
13896 			/*
13897 			 * Set tcp_ms_we_have_waited to second_threshold
13898 			 * so that in next timeout, we will do the above
13899 			 * check (ddi_get_lbolt() - tcp_last_recv_time).
13900 			 * This is also to avoid overflow.
13901 			 *
13902 			 * We don't need to decrement tcp_timer_backoff
13903 			 * to avoid overflow because it will be decremented
13904 			 * later if new timeout value is greater than
13905 			 * tcp_rexmit_interval_max.  In the case when
13906 			 * tcp_rexmit_interval_max is greater than
13907 			 * second_threshold, it means that we will wait
13908 			 * longer than second_threshold to send the next
13909 			 * window probe.
13910 			 */
13911 			tcp->tcp_ms_we_have_waited = second_threshold;
13912 		}
13913 	} else if (ms > first_threshold) {
13914 		/*
13915 		 * Should not hold the zero-copy messages for too long.
13916 		 */
13917 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13918 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13919 			    tcp->tcp_xmit_head, B_TRUE);
13920 
13921 		/*
13922 		 * We have been retransmitting for too long...  The RTT
13923 		 * we calculated is probably incorrect.  Reinitialize it.
13924 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
13925 		 * tcp_rtt_update so that we won't accidentally cache a
13926 		 * bad value.  But only do this if this is not a zero
13927 		 * window probe.
13928 		 */
13929 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
13930 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
13931 			    (tcp->tcp_rtt_sa >> 5);
13932 			tcp->tcp_rtt_sa = 0;
13933 			tcp_ip_notify(tcp);
13934 			tcp->tcp_rtt_update = 0;
13935 		}
13936 	}
13937 	tcp->tcp_timer_backoff++;
13938 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
13939 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
13940 	    tcps->tcps_rexmit_interval_min) {
13941 		/*
13942 		 * This means the original RTO is tcp_rexmit_interval_min.
13943 		 * So we will use tcp_rexmit_interval_min as the RTO value
13944 		 * and do the backoff.
13945 		 */
13946 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
13947 	} else {
13948 		ms <<= tcp->tcp_timer_backoff;
13949 	}
13950 	if (ms > tcps->tcps_rexmit_interval_max) {
13951 		ms = tcps->tcps_rexmit_interval_max;
13952 		/*
13953 		 * ms is at max, decrement tcp_timer_backoff to avoid
13954 		 * overflow.
13955 		 */
13956 		tcp->tcp_timer_backoff--;
13957 	}
13958 	tcp->tcp_ms_we_have_waited += ms;
13959 	if (tcp->tcp_zero_win_probe == 0) {
13960 		tcp->tcp_rto = ms;
13961 	}
13962 	TCP_TIMER_RESTART(tcp, ms);
13963 	/*
13964 	 * This is after a timeout and tcp_rto is backed off.  Set
13965 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
13966 	 * restart the timer with a correct value.
13967 	 */
13968 	tcp->tcp_set_timer = 1;
13969 	mss = tcp->tcp_snxt - tcp->tcp_suna;
13970 	if (mss > tcp->tcp_mss)
13971 		mss = tcp->tcp_mss;
13972 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
13973 		mss = tcp->tcp_swnd;
13974 
13975 	if ((mp = tcp->tcp_xmit_head) != NULL)
13976 		mp->b_prev = (mblk_t *)ddi_get_lbolt();
13977 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
13978 	    B_TRUE);
13979 
13980 	/*
13981 	 * When slow start after retransmission begins, start with
13982 	 * this seq no.  tcp_rexmit_max marks the end of special slow
13983 	 * start phase.  tcp_snd_burst controls how many segments
13984 	 * can be sent because of an ack.
13985 	 */
13986 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
13987 	tcp->tcp_snd_burst = TCP_CWND_SS;
13988 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13989 	    (tcp->tcp_unsent == 0)) {
13990 		tcp->tcp_rexmit_max = tcp->tcp_fss;
13991 	} else {
13992 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
13993 	}
13994 	tcp->tcp_rexmit = B_TRUE;
13995 	tcp->tcp_dupack_cnt = 0;
13996 
13997 	/*
13998 	 * Remove all rexmit SACK blk to start from fresh.
13999 	 */
14000 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL)
14001 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
14002 	if (mp == NULL) {
14003 		return;
14004 	}
14005 
14006 	tcp->tcp_csuna = tcp->tcp_snxt;
14007 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
14008 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
14009 	tcp_send_data(tcp, mp);
14010 
14011 }
14012 
14013 static int
14014 tcp_do_unbind(conn_t *connp)
14015 {
14016 	tcp_t *tcp = connp->conn_tcp;
14017 
14018 	switch (tcp->tcp_state) {
14019 	case TCPS_BOUND:
14020 	case TCPS_LISTEN:
14021 		break;
14022 	default:
14023 		return (-TOUTSTATE);
14024 	}
14025 
14026 	/*
14027 	 * Need to clean up all the eagers since after the unbind, segments
14028 	 * will no longer be delivered to this listener stream.
14029 	 */
14030 	mutex_enter(&tcp->tcp_eager_lock);
14031 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
14032 		tcp_eager_cleanup(tcp, 0);
14033 	}
14034 	mutex_exit(&tcp->tcp_eager_lock);
14035 
14036 	/* Clean up the listener connection counter if necessary. */
14037 	if (tcp->tcp_listen_cnt != NULL)
14038 		TCP_DECR_LISTEN_CNT(tcp);
14039 	connp->conn_laddr_v6 = ipv6_all_zeros;
14040 	connp->conn_saddr_v6 = ipv6_all_zeros;
14041 	tcp_bind_hash_remove(tcp);
14042 	tcp->tcp_state = TCPS_IDLE;
14043 
14044 	ip_unbind(connp);
14045 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
14046 
14047 	return (0);
14048 }
14049 
14050 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
14051 static void
14052 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
14053 {
14054 	conn_t *connp = tcp->tcp_connp;
14055 	int error;
14056 
14057 	error = tcp_do_unbind(connp);
14058 	if (error > 0) {
14059 		tcp_err_ack(tcp, mp, TSYSERR, error);
14060 	} else if (error < 0) {
14061 		tcp_err_ack(tcp, mp, -error, 0);
14062 	} else {
14063 		/* Send M_FLUSH according to TPI */
14064 		(void) putnextctl1(connp->conn_rq, M_FLUSH, FLUSHRW);
14065 
14066 		mp = mi_tpi_ok_ack_alloc(mp);
14067 		if (mp != NULL)
14068 			putnext(connp->conn_rq, mp);
14069 	}
14070 }
14071 
14072 /*
14073  * Don't let port fall into the privileged range.
14074  * Since the extra privileged ports can be arbitrary we also
14075  * ensure that we exclude those from consideration.
14076  * tcp_g_epriv_ports is not sorted thus we loop over it until
14077  * there are no changes.
14078  *
14079  * Note: No locks are held when inspecting tcp_g_*epriv_ports
14080  * but instead the code relies on:
14081  * - the fact that the address of the array and its size never changes
14082  * - the atomic assignment of the elements of the array
14083  *
14084  * Returns 0 if there are no more ports available.
14085  *
14086  * TS note: skip multilevel ports.
14087  */
14088 static in_port_t
14089 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
14090 {
14091 	int i;
14092 	boolean_t restart = B_FALSE;
14093 	tcp_stack_t *tcps = tcp->tcp_tcps;
14094 
14095 	if (random && tcp_random_anon_port != 0) {
14096 		(void) random_get_pseudo_bytes((uint8_t *)&port,
14097 		    sizeof (in_port_t));
14098 		/*
14099 		 * Unless changed by a sys admin, the smallest anon port
14100 		 * is 32768 and the largest anon port is 65535.  It is
14101 		 * very likely (50%) for the random port to be smaller
14102 		 * than the smallest anon port.  When that happens,
14103 		 * add port % (anon port range) to the smallest anon
14104 		 * port to get the random port.  It should fall into the
14105 		 * valid anon port range.
14106 		 */
14107 		if (port < tcps->tcps_smallest_anon_port) {
14108 			port = tcps->tcps_smallest_anon_port +
14109 			    port % (tcps->tcps_largest_anon_port -
14110 			    tcps->tcps_smallest_anon_port);
14111 		}
14112 	}
14113 
14114 retry:
14115 	if (port < tcps->tcps_smallest_anon_port)
14116 		port = (in_port_t)tcps->tcps_smallest_anon_port;
14117 
14118 	if (port > tcps->tcps_largest_anon_port) {
14119 		if (restart)
14120 			return (0);
14121 		restart = B_TRUE;
14122 		port = (in_port_t)tcps->tcps_smallest_anon_port;
14123 	}
14124 
14125 	if (port < tcps->tcps_smallest_nonpriv_port)
14126 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
14127 
14128 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
14129 		if (port == tcps->tcps_g_epriv_ports[i]) {
14130 			port++;
14131 			/*
14132 			 * Make sure whether the port is in the
14133 			 * valid range.
14134 			 */
14135 			goto retry;
14136 		}
14137 	}
14138 	if (is_system_labeled() &&
14139 	    (i = tsol_next_port(crgetzone(tcp->tcp_connp->conn_cred), port,
14140 	    IPPROTO_TCP, B_TRUE)) != 0) {
14141 		port = i;
14142 		goto retry;
14143 	}
14144 	return (port);
14145 }
14146 
14147 /*
14148  * Return the next anonymous port in the privileged port range for
14149  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
14150  * downwards.  This is the same behavior as documented in the userland
14151  * library call rresvport(3N).
14152  *
14153  * TS note: skip multilevel ports.
14154  */
14155 static in_port_t
14156 tcp_get_next_priv_port(const tcp_t *tcp)
14157 {
14158 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
14159 	in_port_t nextport;
14160 	boolean_t restart = B_FALSE;
14161 	tcp_stack_t *tcps = tcp->tcp_tcps;
14162 retry:
14163 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
14164 	    next_priv_port >= IPPORT_RESERVED) {
14165 		next_priv_port = IPPORT_RESERVED - 1;
14166 		if (restart)
14167 			return (0);
14168 		restart = B_TRUE;
14169 	}
14170 	if (is_system_labeled() &&
14171 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_connp->conn_cred),
14172 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
14173 		next_priv_port = nextport;
14174 		goto retry;
14175 	}
14176 	return (next_priv_port--);
14177 }
14178 
14179 /* The write side r/w procedure. */
14180 
14181 #if CCS_STATS
14182 struct {
14183 	struct {
14184 		int64_t count, bytes;
14185 	} tot, hit;
14186 } wrw_stats;
14187 #endif
14188 
14189 /*
14190  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
14191  * messages.
14192  */
14193 /* ARGSUSED */
14194 static void
14195 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14196 {
14197 	conn_t	*connp = (conn_t *)arg;
14198 	tcp_t	*tcp = connp->conn_tcp;
14199 
14200 	ASSERT(DB_TYPE(mp) != M_IOCTL);
14201 	/*
14202 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
14203 	 * Once the close starts, streamhead and sockfs will not let any data
14204 	 * packets come down (close ensures that there are no threads using the
14205 	 * queue and no new threads will come down) but since qprocsoff()
14206 	 * hasn't happened yet, a M_FLUSH or some non data message might
14207 	 * get reflected back (in response to our own FLUSHRW) and get
14208 	 * processed after tcp_close() is done. The conn would still be valid
14209 	 * because a ref would have added but we need to check the state
14210 	 * before actually processing the packet.
14211 	 */
14212 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
14213 		freemsg(mp);
14214 		return;
14215 	}
14216 
14217 	switch (DB_TYPE(mp)) {
14218 	case M_IOCDATA:
14219 		tcp_wput_iocdata(tcp, mp);
14220 		break;
14221 	case M_FLUSH:
14222 		tcp_wput_flush(tcp, mp);
14223 		break;
14224 	default:
14225 		ip_wput_nondata(connp->conn_wq, mp);
14226 		break;
14227 	}
14228 }
14229 
14230 /*
14231  * The TCP fast path write put procedure.
14232  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
14233  */
14234 /* ARGSUSED */
14235 void
14236 tcp_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14237 {
14238 	int		len;
14239 	int		hdrlen;
14240 	int		plen;
14241 	mblk_t		*mp1;
14242 	uchar_t		*rptr;
14243 	uint32_t	snxt;
14244 	tcpha_t		*tcpha;
14245 	struct datab	*db;
14246 	uint32_t	suna;
14247 	uint32_t	mss;
14248 	ipaddr_t	*dst;
14249 	ipaddr_t	*src;
14250 	uint32_t	sum;
14251 	int		usable;
14252 	conn_t		*connp = (conn_t *)arg;
14253 	tcp_t		*tcp = connp->conn_tcp;
14254 	uint32_t	msize;
14255 	tcp_stack_t	*tcps = tcp->tcp_tcps;
14256 	ip_xmit_attr_t	*ixa;
14257 	clock_t		now;
14258 
14259 	/*
14260 	 * Try and ASSERT the minimum possible references on the
14261 	 * conn early enough. Since we are executing on write side,
14262 	 * the connection is obviously not detached and that means
14263 	 * there is a ref each for TCP and IP. Since we are behind
14264 	 * the squeue, the minimum references needed are 3. If the
14265 	 * conn is in classifier hash list, there should be an
14266 	 * extra ref for that (we check both the possibilities).
14267 	 */
14268 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
14269 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
14270 
14271 	ASSERT(DB_TYPE(mp) == M_DATA);
14272 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
14273 
14274 	mutex_enter(&tcp->tcp_non_sq_lock);
14275 	tcp->tcp_squeue_bytes -= msize;
14276 	mutex_exit(&tcp->tcp_non_sq_lock);
14277 
14278 	/* Bypass tcp protocol for fused tcp loopback */
14279 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
14280 		return;
14281 
14282 	mss = tcp->tcp_mss;
14283 	/*
14284 	 * If ZEROCOPY has turned off, try not to send any zero-copy message
14285 	 * down. Do backoff, now.
14286 	 */
14287 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on)
14288 		mp = tcp_zcopy_backoff(tcp, mp, B_FALSE);
14289 
14290 
14291 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
14292 	len = (int)(mp->b_wptr - mp->b_rptr);
14293 
14294 	/*
14295 	 * Criteria for fast path:
14296 	 *
14297 	 *   1. no unsent data
14298 	 *   2. single mblk in request
14299 	 *   3. connection established
14300 	 *   4. data in mblk
14301 	 *   5. len <= mss
14302 	 *   6. no tcp_valid bits
14303 	 */
14304 	if ((tcp->tcp_unsent != 0) ||
14305 	    (tcp->tcp_cork) ||
14306 	    (mp->b_cont != NULL) ||
14307 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
14308 	    (len == 0) ||
14309 	    (len > mss) ||
14310 	    (tcp->tcp_valid_bits != 0)) {
14311 		tcp_wput_data(tcp, mp, B_FALSE);
14312 		return;
14313 	}
14314 
14315 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
14316 	ASSERT(tcp->tcp_fin_sent == 0);
14317 
14318 	/* queue new packet onto retransmission queue */
14319 	if (tcp->tcp_xmit_head == NULL) {
14320 		tcp->tcp_xmit_head = mp;
14321 	} else {
14322 		tcp->tcp_xmit_last->b_cont = mp;
14323 	}
14324 	tcp->tcp_xmit_last = mp;
14325 	tcp->tcp_xmit_tail = mp;
14326 
14327 	/* find out how much we can send */
14328 	/* BEGIN CSTYLED */
14329 	/*
14330 	 *    un-acked	   usable
14331 	 *  |--------------|-----------------|
14332 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
14333 	 */
14334 	/* END CSTYLED */
14335 
14336 	/* start sending from tcp_snxt */
14337 	snxt = tcp->tcp_snxt;
14338 
14339 	/*
14340 	 * Check to see if this connection has been idled for some
14341 	 * time and no ACK is expected.  If it is, we need to slow
14342 	 * start again to get back the connection's "self-clock" as
14343 	 * described in VJ's paper.
14344 	 *
14345 	 * Reinitialize tcp_cwnd after idle.
14346 	 */
14347 	now = LBOLT_FASTPATH;
14348 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
14349 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
14350 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
14351 	}
14352 
14353 	usable = tcp->tcp_swnd;		/* tcp window size */
14354 	if (usable > tcp->tcp_cwnd)
14355 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
14356 	usable -= snxt;		/* subtract stuff already sent */
14357 	suna = tcp->tcp_suna;
14358 	usable += suna;
14359 	/* usable can be < 0 if the congestion window is smaller */
14360 	if (len > usable) {
14361 		/* Can't send complete M_DATA in one shot */
14362 		goto slow;
14363 	}
14364 
14365 	mutex_enter(&tcp->tcp_non_sq_lock);
14366 	if (tcp->tcp_flow_stopped &&
14367 	    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
14368 		tcp_clrqfull(tcp);
14369 	}
14370 	mutex_exit(&tcp->tcp_non_sq_lock);
14371 
14372 	/*
14373 	 * determine if anything to send (Nagle).
14374 	 *
14375 	 *   1. len < tcp_mss (i.e. small)
14376 	 *   2. unacknowledged data present
14377 	 *   3. len < nagle limit
14378 	 *   4. last packet sent < nagle limit (previous packet sent)
14379 	 */
14380 	if ((len < mss) && (snxt != suna) &&
14381 	    (len < (int)tcp->tcp_naglim) &&
14382 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
14383 		/*
14384 		 * This was the first unsent packet and normally
14385 		 * mss < xmit_hiwater so there is no need to worry
14386 		 * about flow control. The next packet will go
14387 		 * through the flow control check in tcp_wput_data().
14388 		 */
14389 		/* leftover work from above */
14390 		tcp->tcp_unsent = len;
14391 		tcp->tcp_xmit_tail_unsent = len;
14392 
14393 		return;
14394 	}
14395 
14396 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
14397 
14398 	if (snxt == suna) {
14399 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14400 	}
14401 
14402 	/* we have always sent something */
14403 	tcp->tcp_rack_cnt = 0;
14404 
14405 	tcp->tcp_snxt = snxt + len;
14406 	tcp->tcp_rack = tcp->tcp_rnxt;
14407 
14408 	if ((mp1 = dupb(mp)) == 0)
14409 		goto no_memory;
14410 	mp->b_prev = (mblk_t *)(uintptr_t)now;
14411 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
14412 
14413 	/* adjust tcp header information */
14414 	tcpha = tcp->tcp_tcpha;
14415 	tcpha->tha_flags = (TH_ACK|TH_PUSH);
14416 
14417 	sum = len + connp->conn_ht_ulp_len + connp->conn_sum;
14418 	sum = (sum >> 16) + (sum & 0xFFFF);
14419 	tcpha->tha_sum = htons(sum);
14420 
14421 	tcpha->tha_seq = htonl(snxt);
14422 
14423 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
14424 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
14425 	BUMP_LOCAL(tcp->tcp_obsegs);
14426 
14427 	/* Update the latest receive window size in TCP header. */
14428 	tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
14429 
14430 	tcp->tcp_last_sent_len = (ushort_t)len;
14431 
14432 	plen = len + connp->conn_ht_iphc_len;
14433 
14434 	ixa = connp->conn_ixa;
14435 	ixa->ixa_pktlen = plen;
14436 
14437 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
14438 		tcp->tcp_ipha->ipha_length = htons(plen);
14439 	} else {
14440 		tcp->tcp_ip6h->ip6_plen = htons(plen - IPV6_HDR_LEN);
14441 	}
14442 
14443 	/* see if we need to allocate a mblk for the headers */
14444 	hdrlen = connp->conn_ht_iphc_len;
14445 	rptr = mp1->b_rptr - hdrlen;
14446 	db = mp1->b_datap;
14447 	if ((db->db_ref != 2) || rptr < db->db_base ||
14448 	    (!OK_32PTR(rptr))) {
14449 		/* NOTE: we assume allocb returns an OK_32PTR */
14450 		mp = allocb(hdrlen + tcps->tcps_wroff_xtra, BPRI_MED);
14451 		if (!mp) {
14452 			freemsg(mp1);
14453 			goto no_memory;
14454 		}
14455 		mp->b_cont = mp1;
14456 		mp1 = mp;
14457 		/* Leave room for Link Level header */
14458 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
14459 		mp1->b_wptr = &rptr[hdrlen];
14460 	}
14461 	mp1->b_rptr = rptr;
14462 
14463 	/* Fill in the timestamp option. */
14464 	if (tcp->tcp_snd_ts_ok) {
14465 		uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
14466 
14467 		U32_TO_BE32(llbolt,
14468 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
14469 		U32_TO_BE32(tcp->tcp_ts_recent,
14470 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
14471 	} else {
14472 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
14473 	}
14474 
14475 	/* copy header into outgoing packet */
14476 	dst = (ipaddr_t *)rptr;
14477 	src = (ipaddr_t *)connp->conn_ht_iphc;
14478 	dst[0] = src[0];
14479 	dst[1] = src[1];
14480 	dst[2] = src[2];
14481 	dst[3] = src[3];
14482 	dst[4] = src[4];
14483 	dst[5] = src[5];
14484 	dst[6] = src[6];
14485 	dst[7] = src[7];
14486 	dst[8] = src[8];
14487 	dst[9] = src[9];
14488 	if (hdrlen -= 40) {
14489 		hdrlen >>= 2;
14490 		dst += 10;
14491 		src += 10;
14492 		do {
14493 			*dst++ = *src++;
14494 		} while (--hdrlen);
14495 	}
14496 
14497 	/*
14498 	 * Set the ECN info in the TCP header.  Note that this
14499 	 * is not the template header.
14500 	 */
14501 	if (tcp->tcp_ecn_ok) {
14502 		SET_ECT(tcp, rptr);
14503 
14504 		tcpha = (tcpha_t *)(rptr + ixa->ixa_ip_hdr_length);
14505 		if (tcp->tcp_ecn_echo_on)
14506 			tcpha->tha_flags |= TH_ECE;
14507 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
14508 			tcpha->tha_flags |= TH_CWR;
14509 			tcp->tcp_ecn_cwr_sent = B_TRUE;
14510 		}
14511 	}
14512 
14513 	if (tcp->tcp_ip_forward_progress) {
14514 		tcp->tcp_ip_forward_progress = B_FALSE;
14515 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
14516 	} else {
14517 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
14518 	}
14519 	tcp_send_data(tcp, mp1);
14520 	return;
14521 
14522 	/*
14523 	 * If we ran out of memory, we pretend to have sent the packet
14524 	 * and that it was lost on the wire.
14525 	 */
14526 no_memory:
14527 	return;
14528 
14529 slow:
14530 	/* leftover work from above */
14531 	tcp->tcp_unsent = len;
14532 	tcp->tcp_xmit_tail_unsent = len;
14533 	tcp_wput_data(tcp, NULL, B_FALSE);
14534 }
14535 
14536 /*
14537  * This runs at the tail end of accept processing on the squeue of the
14538  * new connection.
14539  */
14540 /* ARGSUSED */
14541 void
14542 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14543 {
14544 	conn_t			*connp = (conn_t *)arg;
14545 	tcp_t			*tcp = connp->conn_tcp;
14546 	queue_t			*q = connp->conn_rq;
14547 	tcp_stack_t		*tcps = tcp->tcp_tcps;
14548 	/* socket options */
14549 	struct sock_proto_props	sopp;
14550 
14551 	/* We should just receive a single mblk that fits a T_discon_ind */
14552 	ASSERT(mp->b_cont == NULL);
14553 
14554 	/*
14555 	 * Drop the eager's ref on the listener, that was placed when
14556 	 * this eager began life in tcp_input_listener.
14557 	 */
14558 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
14559 	if (IPCL_IS_NONSTR(connp)) {
14560 		/* Safe to free conn_ind message */
14561 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
14562 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14563 	}
14564 
14565 	tcp->tcp_detached = B_FALSE;
14566 
14567 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
14568 		/*
14569 		 * Someone blewoff the eager before we could finish
14570 		 * the accept.
14571 		 *
14572 		 * The only reason eager exists it because we put in
14573 		 * a ref on it when conn ind went up. We need to send
14574 		 * a disconnect indication up while the last reference
14575 		 * on the eager will be dropped by the squeue when we
14576 		 * return.
14577 		 */
14578 		ASSERT(tcp->tcp_listener == NULL);
14579 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
14580 			if (IPCL_IS_NONSTR(connp)) {
14581 				ASSERT(tcp->tcp_issocket);
14582 				(*connp->conn_upcalls->su_disconnected)(
14583 				    connp->conn_upper_handle, tcp->tcp_connid,
14584 				    ECONNREFUSED);
14585 				freemsg(mp);
14586 			} else {
14587 				struct	T_discon_ind	*tdi;
14588 
14589 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
14590 				/*
14591 				 * Let us reuse the incoming mblk to avoid
14592 				 * memory allocation failure problems. We know
14593 				 * that the size of the incoming mblk i.e.
14594 				 * stroptions is greater than sizeof
14595 				 * T_discon_ind.
14596 				 */
14597 				ASSERT(DB_REF(mp) == 1);
14598 				ASSERT(MBLKSIZE(mp) >=
14599 				    sizeof (struct T_discon_ind));
14600 
14601 				DB_TYPE(mp) = M_PROTO;
14602 				((union T_primitives *)mp->b_rptr)->type =
14603 				    T_DISCON_IND;
14604 				tdi = (struct T_discon_ind *)mp->b_rptr;
14605 				if (tcp->tcp_issocket) {
14606 					tdi->DISCON_reason = ECONNREFUSED;
14607 					tdi->SEQ_number = 0;
14608 				} else {
14609 					tdi->DISCON_reason = ENOPROTOOPT;
14610 					tdi->SEQ_number =
14611 					    tcp->tcp_conn_req_seqnum;
14612 				}
14613 				mp->b_wptr = mp->b_rptr +
14614 				    sizeof (struct T_discon_ind);
14615 				putnext(q, mp);
14616 			}
14617 		}
14618 		tcp->tcp_hard_binding = B_FALSE;
14619 		return;
14620 	}
14621 
14622 	/*
14623 	 * This is the first time we run on the correct
14624 	 * queue after tcp_accept. So fix all the q parameters
14625 	 * here.
14626 	 */
14627 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
14628 	sopp.sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
14629 
14630 	sopp.sopp_rxhiwat = tcp->tcp_fused ?
14631 	    tcp_fuse_set_rcv_hiwat(tcp, connp->conn_rcvbuf) :
14632 	    connp->conn_rcvbuf;
14633 
14634 	/*
14635 	 * Determine what write offset value to use depending on SACK and
14636 	 * whether the endpoint is fused or not.
14637 	 */
14638 	if (tcp->tcp_fused) {
14639 		ASSERT(tcp->tcp_loopback);
14640 		ASSERT(tcp->tcp_loopback_peer != NULL);
14641 		/*
14642 		 * For fused tcp loopback, set the stream head's write
14643 		 * offset value to zero since we won't be needing any room
14644 		 * for TCP/IP headers.  This would also improve performance
14645 		 * since it would reduce the amount of work done by kmem.
14646 		 * Non-fused tcp loopback case is handled separately below.
14647 		 */
14648 		sopp.sopp_wroff = 0;
14649 		/*
14650 		 * Update the peer's transmit parameters according to
14651 		 * our recently calculated high water mark value.
14652 		 */
14653 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
14654 	} else if (tcp->tcp_snd_sack_ok) {
14655 		sopp.sopp_wroff = connp->conn_ht_iphc_allocated +
14656 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
14657 	} else {
14658 		sopp.sopp_wroff = connp->conn_ht_iphc_len +
14659 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
14660 	}
14661 
14662 	/*
14663 	 * If this is endpoint is handling SSL, then reserve extra
14664 	 * offset and space at the end.
14665 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
14666 	 * overriding the previous setting. The extra cost of signing and
14667 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
14668 	 * instead of a single contiguous one by the stream head
14669 	 * largely outweighs the statistical reduction of ACKs, when
14670 	 * applicable. The peer will also save on decryption and verification
14671 	 * costs.
14672 	 */
14673 	if (tcp->tcp_kssl_ctx != NULL) {
14674 		sopp.sopp_wroff += SSL3_WROFFSET;
14675 
14676 		sopp.sopp_flags |= SOCKOPT_TAIL;
14677 		sopp.sopp_tail = SSL3_MAX_TAIL_LEN;
14678 
14679 		sopp.sopp_flags |= SOCKOPT_ZCOPY;
14680 		sopp.sopp_zcopyflag = ZCVMUNSAFE;
14681 
14682 		sopp.sopp_maxblk = SSL3_MAX_RECORD_LEN;
14683 	}
14684 
14685 	/* Send the options up */
14686 	if (IPCL_IS_NONSTR(connp)) {
14687 		if (sopp.sopp_flags & SOCKOPT_TAIL) {
14688 			ASSERT(tcp->tcp_kssl_ctx != NULL);
14689 			ASSERT(sopp.sopp_flags & SOCKOPT_ZCOPY);
14690 		}
14691 		if (tcp->tcp_loopback) {
14692 			sopp.sopp_flags |= SOCKOPT_LOOPBACK;
14693 			sopp.sopp_loopback = B_TRUE;
14694 		}
14695 		(*connp->conn_upcalls->su_set_proto_props)
14696 		    (connp->conn_upper_handle, &sopp);
14697 		freemsg(mp);
14698 	} else {
14699 		/*
14700 		 * Let us reuse the incoming mblk to avoid
14701 		 * memory allocation failure problems. We know
14702 		 * that the size of the incoming mblk is at least
14703 		 * stroptions
14704 		 */
14705 		struct stroptions *stropt;
14706 
14707 		ASSERT(DB_REF(mp) == 1);
14708 		ASSERT(MBLKSIZE(mp) >= sizeof (struct stroptions));
14709 
14710 		DB_TYPE(mp) = M_SETOPTS;
14711 		stropt = (struct stroptions *)mp->b_rptr;
14712 		mp->b_wptr = mp->b_rptr + sizeof (struct stroptions);
14713 		stropt = (struct stroptions *)mp->b_rptr;
14714 		stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
14715 		stropt->so_hiwat = sopp.sopp_rxhiwat;
14716 		stropt->so_wroff = sopp.sopp_wroff;
14717 		stropt->so_maxblk = sopp.sopp_maxblk;
14718 
14719 		if (sopp.sopp_flags & SOCKOPT_TAIL) {
14720 			ASSERT(tcp->tcp_kssl_ctx != NULL);
14721 
14722 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
14723 			stropt->so_tail = sopp.sopp_tail;
14724 			stropt->so_copyopt = sopp.sopp_zcopyflag;
14725 		}
14726 
14727 		/* Send the options up */
14728 		putnext(q, mp);
14729 	}
14730 
14731 	/*
14732 	 * Pass up any data and/or a fin that has been received.
14733 	 *
14734 	 * Adjust receive window in case it had decreased
14735 	 * (because there is data <=> tcp_rcv_list != NULL)
14736 	 * while the connection was detached. Note that
14737 	 * in case the eager was flow-controlled, w/o this
14738 	 * code, the rwnd may never open up again!
14739 	 */
14740 	if (tcp->tcp_rcv_list != NULL) {
14741 		if (IPCL_IS_NONSTR(connp)) {
14742 			mblk_t *mp;
14743 			int space_left;
14744 			int error;
14745 			boolean_t push = B_TRUE;
14746 
14747 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
14748 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
14749 			    &push) >= 0) {
14750 				tcp->tcp_rwnd = connp->conn_rcvbuf;
14751 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
14752 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
14753 					tcp_xmit_ctl(NULL,
14754 					    tcp, (tcp->tcp_swnd == 0) ?
14755 					    tcp->tcp_suna : tcp->tcp_snxt,
14756 					    tcp->tcp_rnxt, TH_ACK);
14757 				}
14758 			}
14759 			while ((mp = tcp->tcp_rcv_list) != NULL) {
14760 				push = B_TRUE;
14761 				tcp->tcp_rcv_list = mp->b_next;
14762 				mp->b_next = NULL;
14763 				space_left = (*connp->conn_upcalls->su_recv)
14764 				    (connp->conn_upper_handle, mp, msgdsize(mp),
14765 				    0, &error, &push);
14766 				if (space_left < 0) {
14767 					/*
14768 					 * We should never be in middle of a
14769 					 * fallback, the squeue guarantees that.
14770 					 */
14771 					ASSERT(error != EOPNOTSUPP);
14772 				}
14773 			}
14774 			tcp->tcp_rcv_last_head = NULL;
14775 			tcp->tcp_rcv_last_tail = NULL;
14776 			tcp->tcp_rcv_cnt = 0;
14777 		} else {
14778 			/* We drain directly in case of fused tcp loopback */
14779 
14780 			if (!tcp->tcp_fused && canputnext(q)) {
14781 				tcp->tcp_rwnd = connp->conn_rcvbuf;
14782 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
14783 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
14784 					tcp_xmit_ctl(NULL,
14785 					    tcp, (tcp->tcp_swnd == 0) ?
14786 					    tcp->tcp_suna : tcp->tcp_snxt,
14787 					    tcp->tcp_rnxt, TH_ACK);
14788 				}
14789 			}
14790 
14791 			(void) tcp_rcv_drain(tcp);
14792 		}
14793 
14794 		/*
14795 		 * For fused tcp loopback, back-enable peer endpoint
14796 		 * if it's currently flow-controlled.
14797 		 */
14798 		if (tcp->tcp_fused) {
14799 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
14800 
14801 			ASSERT(peer_tcp != NULL);
14802 			ASSERT(peer_tcp->tcp_fused);
14803 
14804 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
14805 			if (peer_tcp->tcp_flow_stopped) {
14806 				tcp_clrqfull(peer_tcp);
14807 				TCP_STAT(tcps, tcp_fusion_backenabled);
14808 			}
14809 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
14810 		}
14811 	}
14812 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14813 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
14814 		tcp->tcp_ordrel_done = B_TRUE;
14815 		if (IPCL_IS_NONSTR(connp)) {
14816 			ASSERT(tcp->tcp_ordrel_mp == NULL);
14817 			(*connp->conn_upcalls->su_opctl)(
14818 			    connp->conn_upper_handle,
14819 			    SOCK_OPCTL_SHUT_RECV, 0);
14820 		} else {
14821 			mp = tcp->tcp_ordrel_mp;
14822 			tcp->tcp_ordrel_mp = NULL;
14823 			putnext(q, mp);
14824 		}
14825 	}
14826 	tcp->tcp_hard_binding = B_FALSE;
14827 
14828 	if (connp->conn_keepalive) {
14829 		tcp->tcp_ka_last_intrvl = 0;
14830 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
14831 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
14832 	}
14833 
14834 	/*
14835 	 * At this point, eager is fully established and will
14836 	 * have the following references -
14837 	 *
14838 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
14839 	 * 1 reference for the squeue which will be dropped by the squeue as
14840 	 *	soon as this function returns.
14841 	 * There will be 1 additonal reference for being in classifier
14842 	 *	hash list provided something bad hasn't happened.
14843 	 */
14844 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
14845 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
14846 }
14847 
14848 /*
14849  * The function called through squeue to get behind listener's perimeter to
14850  * send a deferred conn_ind.
14851  */
14852 /* ARGSUSED */
14853 void
14854 tcp_send_pending(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14855 {
14856 	conn_t	*lconnp = (conn_t *)arg;
14857 	tcp_t *listener = lconnp->conn_tcp;
14858 	struct T_conn_ind *conn_ind;
14859 	tcp_t *tcp;
14860 
14861 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
14862 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
14863 	    conn_ind->OPT_length);
14864 
14865 	if (listener->tcp_state != TCPS_LISTEN) {
14866 		/*
14867 		 * If listener has closed, it would have caused a
14868 		 * a cleanup/blowoff to happen for the eager, so
14869 		 * we don't need to do anything more.
14870 		 */
14871 		freemsg(mp);
14872 		return;
14873 	}
14874 
14875 	tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
14876 }
14877 
14878 /*
14879  * Common to TPI and sockfs accept code.
14880  */
14881 /* ARGSUSED2 */
14882 static int
14883 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
14884 {
14885 	tcp_t *listener, *eager;
14886 	mblk_t *discon_mp;
14887 
14888 	listener = lconnp->conn_tcp;
14889 	ASSERT(listener->tcp_state == TCPS_LISTEN);
14890 	eager = econnp->conn_tcp;
14891 	ASSERT(eager->tcp_listener != NULL);
14892 
14893 	/*
14894 	 * Pre allocate the discon_ind mblk also. tcp_accept_finish will
14895 	 * use it if something failed.
14896 	 */
14897 	discon_mp = allocb(MAX(sizeof (struct T_discon_ind),
14898 	    sizeof (struct stroptions)), BPRI_HI);
14899 
14900 	if (discon_mp == NULL) {
14901 		return (-TPROTO);
14902 	}
14903 	eager->tcp_issocket = B_TRUE;
14904 
14905 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
14906 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
14907 	ASSERT(econnp->conn_netstack ==
14908 	    listener->tcp_connp->conn_netstack);
14909 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
14910 
14911 	/* Put the ref for IP */
14912 	CONN_INC_REF(econnp);
14913 
14914 	/*
14915 	 * We should have minimum of 3 references on the conn
14916 	 * at this point. One each for TCP and IP and one for
14917 	 * the T_conn_ind that was sent up when the 3-way handshake
14918 	 * completed. In the normal case we would also have another
14919 	 * reference (making a total of 4) for the conn being in the
14920 	 * classifier hash list. However the eager could have received
14921 	 * an RST subsequently and tcp_closei_local could have removed
14922 	 * the eager from the classifier hash list, hence we can't
14923 	 * assert that reference.
14924 	 */
14925 	ASSERT(econnp->conn_ref >= 3);
14926 
14927 	mutex_enter(&listener->tcp_eager_lock);
14928 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
14929 
14930 		tcp_t *tail;
14931 		tcp_t *tcp;
14932 		mblk_t *mp1;
14933 
14934 		tcp = listener->tcp_eager_prev_q0;
14935 		/*
14936 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
14937 		 * deferred T_conn_ind queue. We need to get to the head
14938 		 * of the queue in order to send up T_conn_ind the same
14939 		 * order as how the 3WHS is completed.
14940 		 */
14941 		while (tcp != listener) {
14942 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
14943 			    !tcp->tcp_kssl_pending)
14944 				break;
14945 			else
14946 				tcp = tcp->tcp_eager_prev_q0;
14947 		}
14948 		/* None of the pending eagers can be sent up now */
14949 		if (tcp == listener)
14950 			goto no_more_eagers;
14951 
14952 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
14953 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14954 		/* Move from q0 to q */
14955 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
14956 		listener->tcp_conn_req_cnt_q0--;
14957 		listener->tcp_conn_req_cnt_q++;
14958 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
14959 		    tcp->tcp_eager_prev_q0;
14960 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
14961 		    tcp->tcp_eager_next_q0;
14962 		tcp->tcp_eager_prev_q0 = NULL;
14963 		tcp->tcp_eager_next_q0 = NULL;
14964 		tcp->tcp_conn_def_q0 = B_FALSE;
14965 
14966 		/* Make sure the tcp isn't in the list of droppables */
14967 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
14968 		    tcp->tcp_eager_prev_drop_q0 == NULL);
14969 
14970 		/*
14971 		 * Insert at end of the queue because sockfs sends
14972 		 * down T_CONN_RES in chronological order. Leaving
14973 		 * the older conn indications at front of the queue
14974 		 * helps reducing search time.
14975 		 */
14976 		tail = listener->tcp_eager_last_q;
14977 		if (tail != NULL) {
14978 			tail->tcp_eager_next_q = tcp;
14979 		} else {
14980 			listener->tcp_eager_next_q = tcp;
14981 		}
14982 		listener->tcp_eager_last_q = tcp;
14983 		tcp->tcp_eager_next_q = NULL;
14984 
14985 		/* Need to get inside the listener perimeter */
14986 		CONN_INC_REF(listener->tcp_connp);
14987 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
14988 		    tcp_send_pending, listener->tcp_connp, NULL, SQ_FILL,
14989 		    SQTAG_TCP_SEND_PENDING);
14990 	}
14991 no_more_eagers:
14992 	tcp_eager_unlink(eager);
14993 	mutex_exit(&listener->tcp_eager_lock);
14994 
14995 	/*
14996 	 * At this point, the eager is detached from the listener
14997 	 * but we still have an extra refs on eager (apart from the
14998 	 * usual tcp references). The ref was placed in tcp_input_data
14999 	 * before sending the conn_ind in tcp_send_conn_ind.
15000 	 * The ref will be dropped in tcp_accept_finish().
15001 	 */
15002 	SQUEUE_ENTER_ONE(econnp->conn_sqp, discon_mp, tcp_accept_finish,
15003 	    econnp, NULL, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
15004 	return (0);
15005 }
15006 
15007 int
15008 tcp_accept(sock_lower_handle_t lproto_handle,
15009     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
15010     cred_t *cr)
15011 {
15012 	conn_t *lconnp, *econnp;
15013 	tcp_t *listener, *eager;
15014 
15015 	lconnp = (conn_t *)lproto_handle;
15016 	listener = lconnp->conn_tcp;
15017 	ASSERT(listener->tcp_state == TCPS_LISTEN);
15018 	econnp = (conn_t *)eproto_handle;
15019 	eager = econnp->conn_tcp;
15020 	ASSERT(eager->tcp_listener != NULL);
15021 
15022 	/*
15023 	 * It is OK to manipulate these fields outside the eager's squeue
15024 	 * because they will not start being used until tcp_accept_finish
15025 	 * has been called.
15026 	 */
15027 	ASSERT(lconnp->conn_upper_handle != NULL);
15028 	ASSERT(econnp->conn_upper_handle == NULL);
15029 	econnp->conn_upper_handle = sock_handle;
15030 	econnp->conn_upcalls = lconnp->conn_upcalls;
15031 	ASSERT(IPCL_IS_NONSTR(econnp));
15032 	return (tcp_accept_common(lconnp, econnp, cr));
15033 }
15034 
15035 
15036 /*
15037  * This is the STREAMS entry point for T_CONN_RES coming down on
15038  * Acceptor STREAM when  sockfs listener does accept processing.
15039  * Read the block comment on top of tcp_input_listener().
15040  */
15041 void
15042 tcp_tpi_accept(queue_t *q, mblk_t *mp)
15043 {
15044 	queue_t *rq = RD(q);
15045 	struct T_conn_res *conn_res;
15046 	tcp_t *eager;
15047 	tcp_t *listener;
15048 	struct T_ok_ack *ok;
15049 	t_scalar_t PRIM_type;
15050 	conn_t *econnp;
15051 	cred_t *cr;
15052 
15053 	ASSERT(DB_TYPE(mp) == M_PROTO);
15054 
15055 	/*
15056 	 * All Solaris components should pass a db_credp
15057 	 * for this TPI message, hence we ASSERT.
15058 	 * But in case there is some other M_PROTO that looks
15059 	 * like a TPI message sent by some other kernel
15060 	 * component, we check and return an error.
15061 	 */
15062 	cr = msg_getcred(mp, NULL);
15063 	ASSERT(cr != NULL);
15064 	if (cr == NULL) {
15065 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
15066 		if (mp != NULL)
15067 			putnext(rq, mp);
15068 		return;
15069 	}
15070 	conn_res = (struct T_conn_res *)mp->b_rptr;
15071 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
15072 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
15073 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
15074 		if (mp != NULL)
15075 			putnext(rq, mp);
15076 		return;
15077 	}
15078 	switch (conn_res->PRIM_type) {
15079 	case O_T_CONN_RES:
15080 	case T_CONN_RES:
15081 		/*
15082 		 * We pass up an err ack if allocb fails. This will
15083 		 * cause sockfs to issue a T_DISCON_REQ which will cause
15084 		 * tcp_eager_blowoff to be called. sockfs will then call
15085 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
15086 		 * we need to do the allocb up here because we have to
15087 		 * make sure rq->q_qinfo->qi_qclose still points to the
15088 		 * correct function (tcp_tpi_close_accept) in case allocb
15089 		 * fails.
15090 		 */
15091 		bcopy(mp->b_rptr + conn_res->OPT_offset,
15092 		    &eager, conn_res->OPT_length);
15093 		PRIM_type = conn_res->PRIM_type;
15094 		mp->b_datap->db_type = M_PCPROTO;
15095 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
15096 		ok = (struct T_ok_ack *)mp->b_rptr;
15097 		ok->PRIM_type = T_OK_ACK;
15098 		ok->CORRECT_prim = PRIM_type;
15099 		econnp = eager->tcp_connp;
15100 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
15101 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
15102 		econnp->conn_rq = rq;
15103 		econnp->conn_wq = q;
15104 		rq->q_ptr = econnp;
15105 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
15106 		q->q_ptr = econnp;
15107 		q->q_qinfo = &tcp_winit;
15108 		listener = eager->tcp_listener;
15109 
15110 		if (tcp_accept_common(listener->tcp_connp,
15111 		    econnp, cr) < 0) {
15112 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
15113 			if (mp != NULL)
15114 				putnext(rq, mp);
15115 			return;
15116 		}
15117 
15118 		/*
15119 		 * Send the new local address also up to sockfs. There
15120 		 * should already be enough space in the mp that came
15121 		 * down from soaccept().
15122 		 */
15123 		if (econnp->conn_family == AF_INET) {
15124 			sin_t *sin;
15125 
15126 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
15127 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
15128 			sin = (sin_t *)mp->b_wptr;
15129 			mp->b_wptr += sizeof (sin_t);
15130 			sin->sin_family = AF_INET;
15131 			sin->sin_port = econnp->conn_lport;
15132 			sin->sin_addr.s_addr = econnp->conn_laddr_v4;
15133 		} else {
15134 			sin6_t *sin6;
15135 
15136 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
15137 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
15138 			sin6 = (sin6_t *)mp->b_wptr;
15139 			mp->b_wptr += sizeof (sin6_t);
15140 			sin6->sin6_family = AF_INET6;
15141 			sin6->sin6_port = econnp->conn_lport;
15142 			sin6->sin6_addr = econnp->conn_laddr_v6;
15143 			if (econnp->conn_ipversion == IPV4_VERSION)
15144 				sin6->sin6_flowinfo = 0;
15145 			else
15146 				sin6->sin6_flowinfo = econnp->conn_flowinfo;
15147 			if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6) &&
15148 			    (econnp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)) {
15149 				sin6->sin6_scope_id =
15150 				    econnp->conn_ixa->ixa_scopeid;
15151 			} else {
15152 				sin6->sin6_scope_id = 0;
15153 			}
15154 			sin6->__sin6_src_id = 0;
15155 		}
15156 
15157 		putnext(rq, mp);
15158 		return;
15159 	default:
15160 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
15161 		if (mp != NULL)
15162 			putnext(rq, mp);
15163 		return;
15164 	}
15165 }
15166 
15167 /*
15168  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
15169  */
15170 static void
15171 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
15172 {
15173 	void	*data;
15174 	mblk_t	*datamp = mp->b_cont;
15175 	conn_t	*connp = Q_TO_CONN(q);
15176 	tcp_t	*tcp = connp->conn_tcp;
15177 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
15178 
15179 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
15180 		cmdp->cb_error = EPROTO;
15181 		qreply(q, mp);
15182 		return;
15183 	}
15184 
15185 	data = datamp->b_rptr;
15186 
15187 	switch (cmdp->cb_cmd) {
15188 	case TI_GETPEERNAME:
15189 		if (tcp->tcp_state < TCPS_SYN_RCVD)
15190 			cmdp->cb_error = ENOTCONN;
15191 		else
15192 			cmdp->cb_error = conn_getpeername(connp, data,
15193 			    &cmdp->cb_len);
15194 		break;
15195 	case TI_GETMYNAME:
15196 		cmdp->cb_error = conn_getsockname(connp, data, &cmdp->cb_len);
15197 		break;
15198 	default:
15199 		cmdp->cb_error = EINVAL;
15200 		break;
15201 	}
15202 
15203 	qreply(q, mp);
15204 }
15205 
15206 void
15207 tcp_wput(queue_t *q, mblk_t *mp)
15208 {
15209 	conn_t	*connp = Q_TO_CONN(q);
15210 	tcp_t	*tcp;
15211 	void (*output_proc)();
15212 	t_scalar_t type;
15213 	uchar_t *rptr;
15214 	struct iocblk	*iocp;
15215 	size_t size;
15216 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
15217 
15218 	ASSERT(connp->conn_ref >= 2);
15219 
15220 	switch (DB_TYPE(mp)) {
15221 	case M_DATA:
15222 		tcp = connp->conn_tcp;
15223 		ASSERT(tcp != NULL);
15224 
15225 		size = msgdsize(mp);
15226 
15227 		mutex_enter(&tcp->tcp_non_sq_lock);
15228 		tcp->tcp_squeue_bytes += size;
15229 		if (TCP_UNSENT_BYTES(tcp) > connp->conn_sndbuf) {
15230 			tcp_setqfull(tcp);
15231 		}
15232 		mutex_exit(&tcp->tcp_non_sq_lock);
15233 
15234 		CONN_INC_REF(connp);
15235 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
15236 		    NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
15237 		return;
15238 
15239 	case M_CMD:
15240 		tcp_wput_cmdblk(q, mp);
15241 		return;
15242 
15243 	case M_PROTO:
15244 	case M_PCPROTO:
15245 		/*
15246 		 * if it is a snmp message, don't get behind the squeue
15247 		 */
15248 		tcp = connp->conn_tcp;
15249 		rptr = mp->b_rptr;
15250 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
15251 			type = ((union T_primitives *)rptr)->type;
15252 		} else {
15253 			if (connp->conn_debug) {
15254 				(void) strlog(TCP_MOD_ID, 0, 1,
15255 				    SL_ERROR|SL_TRACE,
15256 				    "tcp_wput_proto, dropping one...");
15257 			}
15258 			freemsg(mp);
15259 			return;
15260 		}
15261 		if (type == T_SVR4_OPTMGMT_REQ) {
15262 			/*
15263 			 * All Solaris components should pass a db_credp
15264 			 * for this TPI message, hence we ASSERT.
15265 			 * But in case there is some other M_PROTO that looks
15266 			 * like a TPI message sent by some other kernel
15267 			 * component, we check and return an error.
15268 			 */
15269 			cred_t	*cr = msg_getcred(mp, NULL);
15270 
15271 			ASSERT(cr != NULL);
15272 			if (cr == NULL) {
15273 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
15274 				return;
15275 			}
15276 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
15277 			    cr)) {
15278 				/*
15279 				 * This was a SNMP request
15280 				 */
15281 				return;
15282 			} else {
15283 				output_proc = tcp_wput_proto;
15284 			}
15285 		} else {
15286 			output_proc = tcp_wput_proto;
15287 		}
15288 		break;
15289 	case M_IOCTL:
15290 		/*
15291 		 * Most ioctls can be processed right away without going via
15292 		 * squeues - process them right here. Those that do require
15293 		 * squeue (currently _SIOCSOCKFALLBACK)
15294 		 * are processed by tcp_wput_ioctl().
15295 		 */
15296 		iocp = (struct iocblk *)mp->b_rptr;
15297 		tcp = connp->conn_tcp;
15298 
15299 		switch (iocp->ioc_cmd) {
15300 		case TCP_IOC_ABORT_CONN:
15301 			tcp_ioctl_abort_conn(q, mp);
15302 			return;
15303 		case TI_GETPEERNAME:
15304 		case TI_GETMYNAME:
15305 			mi_copyin(q, mp, NULL,
15306 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
15307 			return;
15308 		case ND_SET:
15309 			/* nd_getset does the necessary checks */
15310 		case ND_GET:
15311 			if (nd_getset(q, tcps->tcps_g_nd, mp)) {
15312 				qreply(q, mp);
15313 				return;
15314 			}
15315 			CONN_INC_IOCTLREF(connp);
15316 			ip_wput_nondata(q, mp);
15317 			CONN_DEC_IOCTLREF(connp);
15318 			return;
15319 
15320 		default:
15321 			output_proc = tcp_wput_ioctl;
15322 			break;
15323 		}
15324 		break;
15325 	default:
15326 		output_proc = tcp_wput_nondata;
15327 		break;
15328 	}
15329 
15330 	CONN_INC_REF(connp);
15331 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
15332 	    NULL, tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
15333 }
15334 
15335 /*
15336  * Initial STREAMS write side put() procedure for sockets. It tries to
15337  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
15338  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
15339  * are handled by tcp_wput() as usual.
15340  *
15341  * All further messages will also be handled by tcp_wput() because we cannot
15342  * be sure that the above short cut is safe later.
15343  */
15344 static void
15345 tcp_wput_sock(queue_t *wq, mblk_t *mp)
15346 {
15347 	conn_t			*connp = Q_TO_CONN(wq);
15348 	tcp_t			*tcp = connp->conn_tcp;
15349 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
15350 
15351 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
15352 	wq->q_qinfo = &tcp_winit;
15353 
15354 	ASSERT(IPCL_IS_TCP(connp));
15355 	ASSERT(TCP_IS_SOCKET(tcp));
15356 
15357 	if (DB_TYPE(mp) == M_PCPROTO &&
15358 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
15359 	    car->PRIM_type == T_CAPABILITY_REQ) {
15360 		tcp_capability_req(tcp, mp);
15361 		return;
15362 	}
15363 
15364 	tcp_wput(wq, mp);
15365 }
15366 
15367 /* ARGSUSED */
15368 static void
15369 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
15370 {
15371 #ifdef DEBUG
15372 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
15373 #endif
15374 	freemsg(mp);
15375 }
15376 
15377 /*
15378  * Check the usability of ZEROCOPY. It's instead checking the flag set by IP.
15379  */
15380 static boolean_t
15381 tcp_zcopy_check(tcp_t *tcp)
15382 {
15383 	conn_t		*connp = tcp->tcp_connp;
15384 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
15385 	boolean_t	zc_enabled = B_FALSE;
15386 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15387 
15388 	if (do_tcpzcopy == 2)
15389 		zc_enabled = B_TRUE;
15390 	else if ((do_tcpzcopy == 1) && (ixa->ixa_flags & IXAF_ZCOPY_CAPAB))
15391 		zc_enabled = B_TRUE;
15392 
15393 	tcp->tcp_snd_zcopy_on = zc_enabled;
15394 	if (!TCP_IS_DETACHED(tcp)) {
15395 		if (zc_enabled) {
15396 			ixa->ixa_flags |= IXAF_VERIFY_ZCOPY;
15397 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15398 			    ZCVMSAFE);
15399 			TCP_STAT(tcps, tcp_zcopy_on);
15400 		} else {
15401 			ixa->ixa_flags &= ~IXAF_VERIFY_ZCOPY;
15402 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15403 			    ZCVMUNSAFE);
15404 			TCP_STAT(tcps, tcp_zcopy_off);
15405 		}
15406 	}
15407 	return (zc_enabled);
15408 }
15409 
15410 /*
15411  * Backoff from a zero-copy message by copying data to a new allocated
15412  * message and freeing the original desballoca'ed segmapped message.
15413  *
15414  * This function is called by following two callers:
15415  * 1. tcp_timer: fix_xmitlist is set to B_TRUE, because it's safe to free
15416  *    the origial desballoca'ed message and notify sockfs. This is in re-
15417  *    transmit state.
15418  * 2. tcp_output: fix_xmitlist is set to B_FALSE. Flag STRUIO_ZCNOTIFY need
15419  *    to be copied to new message.
15420  */
15421 static mblk_t *
15422 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, boolean_t fix_xmitlist)
15423 {
15424 	mblk_t		*nbp;
15425 	mblk_t		*head = NULL;
15426 	mblk_t		*tail = NULL;
15427 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15428 
15429 	ASSERT(bp != NULL);
15430 	while (bp != NULL) {
15431 		if (IS_VMLOANED_MBLK(bp)) {
15432 			TCP_STAT(tcps, tcp_zcopy_backoff);
15433 			if ((nbp = copyb(bp)) == NULL) {
15434 				tcp->tcp_xmit_zc_clean = B_FALSE;
15435 				if (tail != NULL)
15436 					tail->b_cont = bp;
15437 				return ((head == NULL) ? bp : head);
15438 			}
15439 
15440 			if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
15441 				if (fix_xmitlist)
15442 					tcp_zcopy_notify(tcp);
15443 				else
15444 					nbp->b_datap->db_struioflag |=
15445 					    STRUIO_ZCNOTIFY;
15446 			}
15447 			nbp->b_cont = bp->b_cont;
15448 
15449 			/*
15450 			 * Copy saved information and adjust tcp_xmit_tail
15451 			 * if needed.
15452 			 */
15453 			if (fix_xmitlist) {
15454 				nbp->b_prev = bp->b_prev;
15455 				nbp->b_next = bp->b_next;
15456 
15457 				if (tcp->tcp_xmit_tail == bp)
15458 					tcp->tcp_xmit_tail = nbp;
15459 			}
15460 
15461 			/* Free the original message. */
15462 			bp->b_prev = NULL;
15463 			bp->b_next = NULL;
15464 			freeb(bp);
15465 
15466 			bp = nbp;
15467 		}
15468 
15469 		if (head == NULL) {
15470 			head = bp;
15471 		}
15472 		if (tail == NULL) {
15473 			tail = bp;
15474 		} else {
15475 			tail->b_cont = bp;
15476 			tail = bp;
15477 		}
15478 
15479 		/* Move forward. */
15480 		bp = bp->b_cont;
15481 	}
15482 
15483 	if (fix_xmitlist) {
15484 		tcp->tcp_xmit_last = tail;
15485 		tcp->tcp_xmit_zc_clean = B_TRUE;
15486 	}
15487 
15488 	return (head);
15489 }
15490 
15491 static void
15492 tcp_zcopy_notify(tcp_t *tcp)
15493 {
15494 	struct stdata	*stp;
15495 	conn_t		*connp;
15496 
15497 	if (tcp->tcp_detached)
15498 		return;
15499 	connp = tcp->tcp_connp;
15500 	if (IPCL_IS_NONSTR(connp)) {
15501 		(*connp->conn_upcalls->su_zcopy_notify)
15502 		    (connp->conn_upper_handle);
15503 		return;
15504 	}
15505 	stp = STREAM(connp->conn_rq);
15506 	mutex_enter(&stp->sd_lock);
15507 	stp->sd_flag |= STZCNOTIFY;
15508 	cv_broadcast(&stp->sd_zcopy_wait);
15509 	mutex_exit(&stp->sd_lock);
15510 }
15511 
15512 /*
15513  * Update the TCP connection according to change of LSO capability.
15514  */
15515 static void
15516 tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa)
15517 {
15518 	/*
15519 	 * We check against IPv4 header length to preserve the old behavior
15520 	 * of only enabling LSO when there are no IP options.
15521 	 * But this restriction might not be necessary at all. Before removing
15522 	 * it, need to verify how LSO is handled for source routing case, with
15523 	 * which IP does software checksum.
15524 	 *
15525 	 * For IPv6, whenever any extension header is needed, LSO is supressed.
15526 	 */
15527 	if (ixa->ixa_ip_hdr_length != ((ixa->ixa_flags & IXAF_IS_IPV4) ?
15528 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN))
15529 		return;
15530 
15531 	/*
15532 	 * Either the LSO capability newly became usable, or it has changed.
15533 	 */
15534 	if (ixa->ixa_flags & IXAF_LSO_CAPAB) {
15535 		ill_lso_capab_t	*lsoc = &ixa->ixa_lso_capab;
15536 
15537 		ASSERT(lsoc->ill_lso_max > 0);
15538 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH, lsoc->ill_lso_max);
15539 
15540 		DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
15541 		    boolean_t, B_TRUE, uint32_t, tcp->tcp_lso_max);
15542 
15543 		/*
15544 		 * If LSO to be enabled, notify the STREAM header with larger
15545 		 * data block.
15546 		 */
15547 		if (!tcp->tcp_lso)
15548 			tcp->tcp_maxpsz_multiplier = 0;
15549 
15550 		tcp->tcp_lso = B_TRUE;
15551 		TCP_STAT(tcp->tcp_tcps, tcp_lso_enabled);
15552 	} else { /* LSO capability is not usable any more. */
15553 		DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
15554 		    boolean_t, B_FALSE, uint32_t, tcp->tcp_lso_max);
15555 
15556 		/*
15557 		 * If LSO to be disabled, notify the STREAM header with smaller
15558 		 * data block. And need to restore fragsize to PMTU.
15559 		 */
15560 		if (tcp->tcp_lso) {
15561 			tcp->tcp_maxpsz_multiplier =
15562 			    tcp->tcp_tcps->tcps_maxpsz_multiplier;
15563 			ixa->ixa_fragsize = ixa->ixa_pmtu;
15564 			tcp->tcp_lso = B_FALSE;
15565 			TCP_STAT(tcp->tcp_tcps, tcp_lso_disabled);
15566 		}
15567 	}
15568 
15569 	(void) tcp_maxpsz_set(tcp, B_TRUE);
15570 }
15571 
15572 /*
15573  * Update the TCP connection according to change of ZEROCOPY capability.
15574  */
15575 static void
15576 tcp_update_zcopy(tcp_t *tcp)
15577 {
15578 	conn_t		*connp = tcp->tcp_connp;
15579 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15580 
15581 	if (tcp->tcp_snd_zcopy_on) {
15582 		tcp->tcp_snd_zcopy_on = B_FALSE;
15583 		if (!TCP_IS_DETACHED(tcp)) {
15584 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15585 			    ZCVMUNSAFE);
15586 			TCP_STAT(tcps, tcp_zcopy_off);
15587 		}
15588 	} else {
15589 		tcp->tcp_snd_zcopy_on = B_TRUE;
15590 		if (!TCP_IS_DETACHED(tcp)) {
15591 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15592 			    ZCVMSAFE);
15593 			TCP_STAT(tcps, tcp_zcopy_on);
15594 		}
15595 	}
15596 }
15597 
15598 /*
15599  * Notify function registered with ip_xmit_attr_t. It's called in the squeue
15600  * so it's safe to update the TCP connection.
15601  */
15602 /* ARGSUSED1 */
15603 static void
15604 tcp_notify(void *arg, ip_xmit_attr_t *ixa, ixa_notify_type_t ntype,
15605     ixa_notify_arg_t narg)
15606 {
15607 	tcp_t		*tcp = (tcp_t *)arg;
15608 	conn_t		*connp = tcp->tcp_connp;
15609 
15610 	switch (ntype) {
15611 	case IXAN_LSO:
15612 		tcp_update_lso(tcp, connp->conn_ixa);
15613 		break;
15614 	case IXAN_PMTU:
15615 		tcp_update_pmtu(tcp, B_FALSE);
15616 		break;
15617 	case IXAN_ZCOPY:
15618 		tcp_update_zcopy(tcp);
15619 		break;
15620 	default:
15621 		break;
15622 	}
15623 }
15624 
15625 static void
15626 tcp_send_data(tcp_t *tcp, mblk_t *mp)
15627 {
15628 	conn_t		*connp = tcp->tcp_connp;
15629 
15630 	/*
15631 	 * Check here to avoid sending zero-copy message down to IP when
15632 	 * ZEROCOPY capability has turned off. We only need to deal with
15633 	 * the race condition between sockfs and the notification here.
15634 	 * Since we have tried to backoff the tcp_xmit_head when turning
15635 	 * zero-copy off and new messages in tcp_output(), we simply drop
15636 	 * the dup'ed packet here and let tcp retransmit, if tcp_xmit_zc_clean
15637 	 * is not true.
15638 	 */
15639 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on &&
15640 	    !tcp->tcp_xmit_zc_clean) {
15641 		ip_drop_output("TCP ZC was disabled but not clean", mp, NULL);
15642 		freemsg(mp);
15643 		return;
15644 	}
15645 
15646 	ASSERT(connp->conn_ixa->ixa_notify_cookie == connp->conn_tcp);
15647 	(void) conn_ip_output(mp, connp->conn_ixa);
15648 }
15649 
15650 /*
15651  * This handles the case when the receiver has shrunk its win. Per RFC 1122
15652  * if the receiver shrinks the window, i.e. moves the right window to the
15653  * left, the we should not send new data, but should retransmit normally the
15654  * old unacked data between suna and suna + swnd. We might has sent data
15655  * that is now outside the new window, pretend that we didn't send  it.
15656  */
15657 static void
15658 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
15659 {
15660 	uint32_t	snxt = tcp->tcp_snxt;
15661 
15662 	ASSERT(shrunk_count > 0);
15663 
15664 	if (!tcp->tcp_is_wnd_shrnk) {
15665 		tcp->tcp_snxt_shrunk = snxt;
15666 		tcp->tcp_is_wnd_shrnk = B_TRUE;
15667 	} else if (SEQ_GT(snxt, tcp->tcp_snxt_shrunk)) {
15668 		tcp->tcp_snxt_shrunk = snxt;
15669 	}
15670 
15671 	/* Pretend we didn't send the data outside the window */
15672 	snxt -= shrunk_count;
15673 
15674 	/* Reset all the values per the now shrunk window */
15675 	tcp_update_xmit_tail(tcp, snxt);
15676 	tcp->tcp_unsent += shrunk_count;
15677 
15678 	/*
15679 	 * If the SACK option is set, delete the entire list of
15680 	 * notsack'ed blocks.
15681 	 */
15682 	if (tcp->tcp_sack_info != NULL) {
15683 		if (tcp->tcp_notsack_list != NULL)
15684 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
15685 	}
15686 
15687 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
15688 		/*
15689 		 * Make sure the timer is running so that we will probe a zero
15690 		 * window.
15691 		 */
15692 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15693 }
15694 
15695 
15696 /*
15697  * The TCP normal data output path.
15698  * NOTE: the logic of the fast path is duplicated from this function.
15699  */
15700 static void
15701 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
15702 {
15703 	int		len;
15704 	mblk_t		*local_time;
15705 	mblk_t		*mp1;
15706 	uint32_t	snxt;
15707 	int		tail_unsent;
15708 	int		tcpstate;
15709 	int		usable = 0;
15710 	mblk_t		*xmit_tail;
15711 	int32_t		mss;
15712 	int32_t		num_sack_blk = 0;
15713 	int32_t		total_hdr_len;
15714 	int32_t		tcp_hdr_len;
15715 	int		rc;
15716 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15717 	conn_t		*connp = tcp->tcp_connp;
15718 	clock_t		now = LBOLT_FASTPATH;
15719 
15720 	tcpstate = tcp->tcp_state;
15721 	if (mp == NULL) {
15722 		/*
15723 		 * tcp_wput_data() with NULL mp should only be called when
15724 		 * there is unsent data.
15725 		 */
15726 		ASSERT(tcp->tcp_unsent > 0);
15727 		/* Really tacky... but we need this for detached closes. */
15728 		len = tcp->tcp_unsent;
15729 		goto data_null;
15730 	}
15731 
15732 #if CCS_STATS
15733 	wrw_stats.tot.count++;
15734 	wrw_stats.tot.bytes += msgdsize(mp);
15735 #endif
15736 	ASSERT(mp->b_datap->db_type == M_DATA);
15737 	/*
15738 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
15739 	 * or before a connection attempt has begun.
15740 	 */
15741 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
15742 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
15743 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
15744 #ifdef DEBUG
15745 			cmn_err(CE_WARN,
15746 			    "tcp_wput_data: data after ordrel, %s",
15747 			    tcp_display(tcp, NULL,
15748 			    DISP_ADDR_AND_PORT));
15749 #else
15750 			if (connp->conn_debug) {
15751 				(void) strlog(TCP_MOD_ID, 0, 1,
15752 				    SL_TRACE|SL_ERROR,
15753 				    "tcp_wput_data: data after ordrel, %s\n",
15754 				    tcp_display(tcp, NULL,
15755 				    DISP_ADDR_AND_PORT));
15756 			}
15757 #endif /* DEBUG */
15758 		}
15759 		if (tcp->tcp_snd_zcopy_aware &&
15760 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
15761 			tcp_zcopy_notify(tcp);
15762 		freemsg(mp);
15763 		mutex_enter(&tcp->tcp_non_sq_lock);
15764 		if (tcp->tcp_flow_stopped &&
15765 		    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
15766 			tcp_clrqfull(tcp);
15767 		}
15768 		mutex_exit(&tcp->tcp_non_sq_lock);
15769 		return;
15770 	}
15771 
15772 	/* Strip empties */
15773 	for (;;) {
15774 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
15775 		    (uintptr_t)INT_MAX);
15776 		len = (int)(mp->b_wptr - mp->b_rptr);
15777 		if (len > 0)
15778 			break;
15779 		mp1 = mp;
15780 		mp = mp->b_cont;
15781 		freeb(mp1);
15782 		if (!mp) {
15783 			return;
15784 		}
15785 	}
15786 
15787 	/* If we are the first on the list ... */
15788 	if (tcp->tcp_xmit_head == NULL) {
15789 		tcp->tcp_xmit_head = mp;
15790 		tcp->tcp_xmit_tail = mp;
15791 		tcp->tcp_xmit_tail_unsent = len;
15792 	} else {
15793 		/* If tiny tx and room in txq tail, pullup to save mblks. */
15794 		struct datab *dp;
15795 
15796 		mp1 = tcp->tcp_xmit_last;
15797 		if (len < tcp_tx_pull_len &&
15798 		    (dp = mp1->b_datap)->db_ref == 1 &&
15799 		    dp->db_lim - mp1->b_wptr >= len) {
15800 			ASSERT(len > 0);
15801 			ASSERT(!mp1->b_cont);
15802 			if (len == 1) {
15803 				*mp1->b_wptr++ = *mp->b_rptr;
15804 			} else {
15805 				bcopy(mp->b_rptr, mp1->b_wptr, len);
15806 				mp1->b_wptr += len;
15807 			}
15808 			if (mp1 == tcp->tcp_xmit_tail)
15809 				tcp->tcp_xmit_tail_unsent += len;
15810 			mp1->b_cont = mp->b_cont;
15811 			if (tcp->tcp_snd_zcopy_aware &&
15812 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
15813 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
15814 			freeb(mp);
15815 			mp = mp1;
15816 		} else {
15817 			tcp->tcp_xmit_last->b_cont = mp;
15818 		}
15819 		len += tcp->tcp_unsent;
15820 	}
15821 
15822 	/* Tack on however many more positive length mblks we have */
15823 	if ((mp1 = mp->b_cont) != NULL) {
15824 		do {
15825 			int tlen;
15826 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
15827 			    (uintptr_t)INT_MAX);
15828 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
15829 			if (tlen <= 0) {
15830 				mp->b_cont = mp1->b_cont;
15831 				freeb(mp1);
15832 			} else {
15833 				len += tlen;
15834 				mp = mp1;
15835 			}
15836 		} while ((mp1 = mp->b_cont) != NULL);
15837 	}
15838 	tcp->tcp_xmit_last = mp;
15839 	tcp->tcp_unsent = len;
15840 
15841 	if (urgent)
15842 		usable = 1;
15843 
15844 data_null:
15845 	snxt = tcp->tcp_snxt;
15846 	xmit_tail = tcp->tcp_xmit_tail;
15847 	tail_unsent = tcp->tcp_xmit_tail_unsent;
15848 
15849 	/*
15850 	 * Note that tcp_mss has been adjusted to take into account the
15851 	 * timestamp option if applicable.  Because SACK options do not
15852 	 * appear in every TCP segments and they are of variable lengths,
15853 	 * they cannot be included in tcp_mss.  Thus we need to calculate
15854 	 * the actual segment length when we need to send a segment which
15855 	 * includes SACK options.
15856 	 */
15857 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15858 		int32_t	opt_len;
15859 
15860 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
15861 		    tcp->tcp_num_sack_blk);
15862 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
15863 		    2 + TCPOPT_HEADER_LEN;
15864 		mss = tcp->tcp_mss - opt_len;
15865 		total_hdr_len = connp->conn_ht_iphc_len + opt_len;
15866 		tcp_hdr_len = connp->conn_ht_ulp_len + opt_len;
15867 	} else {
15868 		mss = tcp->tcp_mss;
15869 		total_hdr_len = connp->conn_ht_iphc_len;
15870 		tcp_hdr_len = connp->conn_ht_ulp_len;
15871 	}
15872 
15873 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
15874 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
15875 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
15876 	}
15877 	if (tcpstate == TCPS_SYN_RCVD) {
15878 		/*
15879 		 * The three-way connection establishment handshake is not
15880 		 * complete yet. We want to queue the data for transmission
15881 		 * after entering ESTABLISHED state (RFC793). A jump to
15882 		 * "done" label effectively leaves data on the queue.
15883 		 */
15884 		goto done;
15885 	} else {
15886 		int usable_r;
15887 
15888 		/*
15889 		 * In the special case when cwnd is zero, which can only
15890 		 * happen if the connection is ECN capable, return now.
15891 		 * New segments is sent using tcp_timer().  The timer
15892 		 * is set in tcp_input_data().
15893 		 */
15894 		if (tcp->tcp_cwnd == 0) {
15895 			/*
15896 			 * Note that tcp_cwnd is 0 before 3-way handshake is
15897 			 * finished.
15898 			 */
15899 			ASSERT(tcp->tcp_ecn_ok ||
15900 			    tcp->tcp_state < TCPS_ESTABLISHED);
15901 			return;
15902 		}
15903 
15904 		/* NOTE: trouble if xmitting while SYN not acked? */
15905 		usable_r = snxt - tcp->tcp_suna;
15906 		usable_r = tcp->tcp_swnd - usable_r;
15907 
15908 		/*
15909 		 * Check if the receiver has shrunk the window.  If
15910 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
15911 		 * cannot be set as there is unsent data, so FIN cannot
15912 		 * be sent out.  Otherwise, we need to take into account
15913 		 * of FIN as it consumes an "invisible" sequence number.
15914 		 */
15915 		ASSERT(tcp->tcp_fin_sent == 0);
15916 		if (usable_r < 0) {
15917 			/*
15918 			 * The receiver has shrunk the window and we have sent
15919 			 * -usable_r date beyond the window, re-adjust.
15920 			 *
15921 			 * If TCP window scaling is enabled, there can be
15922 			 * round down error as the advertised receive window
15923 			 * is actually right shifted n bits.  This means that
15924 			 * the lower n bits info is wiped out.  It will look
15925 			 * like the window is shrunk.  Do a check here to
15926 			 * see if the shrunk amount is actually within the
15927 			 * error in window calculation.  If it is, just
15928 			 * return.  Note that this check is inside the
15929 			 * shrunk window check.  This makes sure that even
15930 			 * though tcp_process_shrunk_swnd() is not called,
15931 			 * we will stop further processing.
15932 			 */
15933 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
15934 				tcp_process_shrunk_swnd(tcp, -usable_r);
15935 			}
15936 			return;
15937 		}
15938 
15939 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
15940 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
15941 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
15942 
15943 		/* usable = MIN(usable, unsent) */
15944 		if (usable_r > len)
15945 			usable_r = len;
15946 
15947 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
15948 		if (usable_r > 0) {
15949 			usable = usable_r;
15950 		} else {
15951 			/* Bypass all other unnecessary processing. */
15952 			goto done;
15953 		}
15954 	}
15955 
15956 	local_time = (mblk_t *)now;
15957 
15958 	/*
15959 	 * "Our" Nagle Algorithm.  This is not the same as in the old
15960 	 * BSD.  This is more in line with the true intent of Nagle.
15961 	 *
15962 	 * The conditions are:
15963 	 * 1. The amount of unsent data (or amount of data which can be
15964 	 *    sent, whichever is smaller) is less than Nagle limit.
15965 	 * 2. The last sent size is also less than Nagle limit.
15966 	 * 3. There is unack'ed data.
15967 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
15968 	 *    Nagle algorithm.  This reduces the probability that urgent
15969 	 *    bytes get "merged" together.
15970 	 * 5. The app has not closed the connection.  This eliminates the
15971 	 *    wait time of the receiving side waiting for the last piece of
15972 	 *    (small) data.
15973 	 *
15974 	 * If all are satisified, exit without sending anything.  Note
15975 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
15976 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
15977 	 * 4095).
15978 	 */
15979 	if (usable < (int)tcp->tcp_naglim &&
15980 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
15981 	    snxt != tcp->tcp_suna &&
15982 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
15983 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
15984 		goto done;
15985 	}
15986 
15987 	/*
15988 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
15989 	 * is set, then we have to force TCP not to send partial segment
15990 	 * (smaller than MSS bytes). We are calculating the usable now
15991 	 * based on full mss and will save the rest of remaining data for
15992 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
15993 	 * something to do zero window probe.
15994 	 */
15995 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
15996 		if (usable < mss)
15997 			goto done;
15998 		usable = (usable / mss) * mss;
15999 	}
16000 
16001 	/* Update the latest receive window size in TCP header. */
16002 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
16003 
16004 	/* Send the packet. */
16005 	rc = tcp_send(tcp, mss, total_hdr_len, tcp_hdr_len,
16006 	    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
16007 	    local_time);
16008 
16009 	/* Pretend that all we were trying to send really got sent */
16010 	if (rc < 0 && tail_unsent < 0) {
16011 		do {
16012 			xmit_tail = xmit_tail->b_cont;
16013 			xmit_tail->b_prev = local_time;
16014 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
16015 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
16016 			tail_unsent += (int)(xmit_tail->b_wptr -
16017 			    xmit_tail->b_rptr);
16018 		} while (tail_unsent < 0);
16019 	}
16020 done:;
16021 	tcp->tcp_xmit_tail = xmit_tail;
16022 	tcp->tcp_xmit_tail_unsent = tail_unsent;
16023 	len = tcp->tcp_snxt - snxt;
16024 	if (len) {
16025 		/*
16026 		 * If new data was sent, need to update the notsack
16027 		 * list, which is, afterall, data blocks that have
16028 		 * not been sack'ed by the receiver.  New data is
16029 		 * not sack'ed.
16030 		 */
16031 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16032 			/* len is a negative value. */
16033 			tcp->tcp_pipe -= len;
16034 			tcp_notsack_update(&(tcp->tcp_notsack_list),
16035 			    tcp->tcp_snxt, snxt,
16036 			    &(tcp->tcp_num_notsack_blk),
16037 			    &(tcp->tcp_cnt_notsack_list));
16038 		}
16039 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
16040 		tcp->tcp_rack = tcp->tcp_rnxt;
16041 		tcp->tcp_rack_cnt = 0;
16042 		if ((snxt + len) == tcp->tcp_suna) {
16043 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16044 		}
16045 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
16046 		/*
16047 		 * Didn't send anything. Make sure the timer is running
16048 		 * so that we will probe a zero window.
16049 		 */
16050 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16051 	}
16052 	/* Note that len is the amount we just sent but with a negative sign */
16053 	tcp->tcp_unsent += len;
16054 	mutex_enter(&tcp->tcp_non_sq_lock);
16055 	if (tcp->tcp_flow_stopped) {
16056 		if (TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
16057 			tcp_clrqfull(tcp);
16058 		}
16059 	} else if (TCP_UNSENT_BYTES(tcp) >= connp->conn_sndbuf) {
16060 		if (!(tcp->tcp_detached))
16061 			tcp_setqfull(tcp);
16062 	}
16063 	mutex_exit(&tcp->tcp_non_sq_lock);
16064 }
16065 
16066 /*
16067  * tcp_fill_header is called by tcp_send() to fill the outgoing TCP header
16068  * with the template header, as well as other options such as time-stamp,
16069  * ECN and/or SACK.
16070  */
16071 static void
16072 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
16073 {
16074 	tcpha_t *tcp_tmpl, *tcpha;
16075 	uint32_t *dst, *src;
16076 	int hdrlen;
16077 	conn_t *connp = tcp->tcp_connp;
16078 
16079 	ASSERT(OK_32PTR(rptr));
16080 
16081 	/* Template header */
16082 	tcp_tmpl = tcp->tcp_tcpha;
16083 
16084 	/* Header of outgoing packet */
16085 	tcpha = (tcpha_t *)(rptr + connp->conn_ixa->ixa_ip_hdr_length);
16086 
16087 	/* dst and src are opaque 32-bit fields, used for copying */
16088 	dst = (uint32_t *)rptr;
16089 	src = (uint32_t *)connp->conn_ht_iphc;
16090 	hdrlen = connp->conn_ht_iphc_len;
16091 
16092 	/* Fill time-stamp option if needed */
16093 	if (tcp->tcp_snd_ts_ok) {
16094 		U32_TO_BE32((uint32_t)now,
16095 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
16096 		U32_TO_BE32(tcp->tcp_ts_recent,
16097 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
16098 	} else {
16099 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
16100 	}
16101 
16102 	/*
16103 	 * Copy the template header; is this really more efficient than
16104 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
16105 	 * but perhaps not for other scenarios.
16106 	 */
16107 	dst[0] = src[0];
16108 	dst[1] = src[1];
16109 	dst[2] = src[2];
16110 	dst[3] = src[3];
16111 	dst[4] = src[4];
16112 	dst[5] = src[5];
16113 	dst[6] = src[6];
16114 	dst[7] = src[7];
16115 	dst[8] = src[8];
16116 	dst[9] = src[9];
16117 	if (hdrlen -= 40) {
16118 		hdrlen >>= 2;
16119 		dst += 10;
16120 		src += 10;
16121 		do {
16122 			*dst++ = *src++;
16123 		} while (--hdrlen);
16124 	}
16125 
16126 	/*
16127 	 * Set the ECN info in the TCP header if it is not a zero
16128 	 * window probe.  Zero window probe is only sent in
16129 	 * tcp_wput_data() and tcp_timer().
16130 	 */
16131 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
16132 		SET_ECT(tcp, rptr);
16133 
16134 		if (tcp->tcp_ecn_echo_on)
16135 			tcpha->tha_flags |= TH_ECE;
16136 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
16137 			tcpha->tha_flags |= TH_CWR;
16138 			tcp->tcp_ecn_cwr_sent = B_TRUE;
16139 		}
16140 	}
16141 
16142 	/* Fill in SACK options */
16143 	if (num_sack_blk > 0) {
16144 		uchar_t *wptr = rptr + connp->conn_ht_iphc_len;
16145 		sack_blk_t *tmp;
16146 		int32_t	i;
16147 
16148 		wptr[0] = TCPOPT_NOP;
16149 		wptr[1] = TCPOPT_NOP;
16150 		wptr[2] = TCPOPT_SACK;
16151 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
16152 		    sizeof (sack_blk_t);
16153 		wptr += TCPOPT_REAL_SACK_LEN;
16154 
16155 		tmp = tcp->tcp_sack_list;
16156 		for (i = 0; i < num_sack_blk; i++) {
16157 			U32_TO_BE32(tmp[i].begin, wptr);
16158 			wptr += sizeof (tcp_seq);
16159 			U32_TO_BE32(tmp[i].end, wptr);
16160 			wptr += sizeof (tcp_seq);
16161 		}
16162 		tcpha->tha_offset_and_reserved +=
16163 		    ((num_sack_blk * 2 + 1) << 4);
16164 	}
16165 }
16166 
16167 /*
16168  * tcp_send() is called by tcp_wput_data() and returns one of the following:
16169  *
16170  * -1 = failed allocation.
16171  *  0 = success; burst count reached, or usable send window is too small,
16172  *      and that we'd rather wait until later before sending again.
16173  */
16174 static int
16175 tcp_send(tcp_t *tcp, const int mss, const int total_hdr_len,
16176     const int tcp_hdr_len, const int num_sack_blk, int *usable,
16177     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time)
16178 {
16179 	int		num_burst_seg = tcp->tcp_snd_burst;
16180 	int		num_lso_seg = 1;
16181 	uint_t		lso_usable;
16182 	boolean_t	do_lso_send = B_FALSE;
16183 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16184 	conn_t		*connp = tcp->tcp_connp;
16185 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
16186 
16187 	/*
16188 	 * Check LSO possibility. The value of tcp->tcp_lso indicates whether
16189 	 * the underlying connection is LSO capable. Will check whether having
16190 	 * enough available data to initiate LSO transmission in the for(){}
16191 	 * loops.
16192 	 */
16193 	if (tcp->tcp_lso && (tcp->tcp_valid_bits & ~TCP_FSS_VALID) == 0)
16194 		do_lso_send = B_TRUE;
16195 
16196 	for (;;) {
16197 		struct datab	*db;
16198 		tcpha_t		*tcpha;
16199 		uint32_t	sum;
16200 		mblk_t		*mp, *mp1;
16201 		uchar_t		*rptr;
16202 		int		len;
16203 
16204 		/*
16205 		 * Burst count reached, return successfully.
16206 		 */
16207 		if (num_burst_seg == 0)
16208 			break;
16209 
16210 		/*
16211 		 * Calculate the maximum payload length we can send at one
16212 		 * time.
16213 		 */
16214 		if (do_lso_send) {
16215 			/*
16216 			 * Check whether be able to to do LSO for the current
16217 			 * available data.
16218 			 */
16219 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
16220 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
16221 				lso_usable = MIN(lso_usable,
16222 				    num_burst_seg * mss);
16223 
16224 				num_lso_seg = lso_usable / mss;
16225 				if (lso_usable % mss) {
16226 					num_lso_seg++;
16227 					tcp->tcp_last_sent_len = (ushort_t)
16228 					    (lso_usable % mss);
16229 				} else {
16230 					tcp->tcp_last_sent_len = (ushort_t)mss;
16231 				}
16232 			} else {
16233 				do_lso_send = B_FALSE;
16234 				num_lso_seg = 1;
16235 				lso_usable = mss;
16236 			}
16237 		}
16238 
16239 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
16240 #ifdef DEBUG
16241 		DTRACE_PROBE2(tcp_send_lso, int, num_lso_seg, boolean_t,
16242 		    do_lso_send);
16243 #endif
16244 		/*
16245 		 * Adjust num_burst_seg here.
16246 		 */
16247 		num_burst_seg -= num_lso_seg;
16248 
16249 		len = mss;
16250 		if (len > *usable) {
16251 			ASSERT(do_lso_send == B_FALSE);
16252 
16253 			len = *usable;
16254 			if (len <= 0) {
16255 				/* Terminate the loop */
16256 				break;	/* success; too small */
16257 			}
16258 			/*
16259 			 * Sender silly-window avoidance.
16260 			 * Ignore this if we are going to send a
16261 			 * zero window probe out.
16262 			 *
16263 			 * TODO: force data into microscopic window?
16264 			 *	==> (!pushed || (unsent > usable))
16265 			 */
16266 			if (len < (tcp->tcp_max_swnd >> 1) &&
16267 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
16268 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
16269 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
16270 				/*
16271 				 * If the retransmit timer is not running
16272 				 * we start it so that we will retransmit
16273 				 * in the case when the receiver has
16274 				 * decremented the window.
16275 				 */
16276 				if (*snxt == tcp->tcp_snxt &&
16277 				    *snxt == tcp->tcp_suna) {
16278 					/*
16279 					 * We are not supposed to send
16280 					 * anything.  So let's wait a little
16281 					 * bit longer before breaking SWS
16282 					 * avoidance.
16283 					 *
16284 					 * What should the value be?
16285 					 * Suggestion: MAX(init rexmit time,
16286 					 * tcp->tcp_rto)
16287 					 */
16288 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16289 				}
16290 				break;	/* success; too small */
16291 			}
16292 		}
16293 
16294 		tcpha = tcp->tcp_tcpha;
16295 
16296 		/*
16297 		 * The reason to adjust len here is that we need to set flags
16298 		 * and calculate checksum.
16299 		 */
16300 		if (do_lso_send)
16301 			len = lso_usable;
16302 
16303 		*usable -= len; /* Approximate - can be adjusted later */
16304 		if (*usable > 0)
16305 			tcpha->tha_flags = TH_ACK;
16306 		else
16307 			tcpha->tha_flags = (TH_ACK | TH_PUSH);
16308 
16309 		/*
16310 		 * Prime pump for IP's checksumming on our behalf.
16311 		 * Include the adjustment for a source route if any.
16312 		 * In case of LSO, the partial pseudo-header checksum should
16313 		 * exclusive TCP length, so zero tha_sum before IP calculate
16314 		 * pseudo-header checksum for partial checksum offload.
16315 		 */
16316 		if (do_lso_send) {
16317 			sum = 0;
16318 		} else {
16319 			sum = len + tcp_hdr_len + connp->conn_sum;
16320 			sum = (sum >> 16) + (sum & 0xFFFF);
16321 		}
16322 		tcpha->tha_sum = htons(sum);
16323 		tcpha->tha_seq = htonl(*snxt);
16324 
16325 		/*
16326 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
16327 		 * set.  For the case when TCP_FSS_VALID is the only valid
16328 		 * bit (normal active close), branch off only when we think
16329 		 * that the FIN flag needs to be set.  Note for this case,
16330 		 * that (snxt + len) may not reflect the actual seg_len,
16331 		 * as len may be further reduced in tcp_xmit_mp().  If len
16332 		 * gets modified, we will end up here again.
16333 		 */
16334 		if (tcp->tcp_valid_bits != 0 &&
16335 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
16336 		    ((*snxt + len) == tcp->tcp_fss))) {
16337 			uchar_t		*prev_rptr;
16338 			uint32_t	prev_snxt = tcp->tcp_snxt;
16339 
16340 			if (*tail_unsent == 0) {
16341 				ASSERT((*xmit_tail)->b_cont != NULL);
16342 				*xmit_tail = (*xmit_tail)->b_cont;
16343 				prev_rptr = (*xmit_tail)->b_rptr;
16344 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
16345 				    (*xmit_tail)->b_rptr);
16346 			} else {
16347 				prev_rptr = (*xmit_tail)->b_rptr;
16348 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
16349 				    *tail_unsent;
16350 			}
16351 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
16352 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
16353 			/* Restore tcp_snxt so we get amount sent right. */
16354 			tcp->tcp_snxt = prev_snxt;
16355 			if (prev_rptr == (*xmit_tail)->b_rptr) {
16356 				/*
16357 				 * If the previous timestamp is still in use,
16358 				 * don't stomp on it.
16359 				 */
16360 				if ((*xmit_tail)->b_next == NULL) {
16361 					(*xmit_tail)->b_prev = local_time;
16362 					(*xmit_tail)->b_next =
16363 					    (mblk_t *)(uintptr_t)(*snxt);
16364 				}
16365 			} else
16366 				(*xmit_tail)->b_rptr = prev_rptr;
16367 
16368 			if (mp == NULL) {
16369 				return (-1);
16370 			}
16371 			mp1 = mp->b_cont;
16372 
16373 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
16374 				tcp->tcp_last_sent_len = (ushort_t)len;
16375 			while (mp1->b_cont) {
16376 				*xmit_tail = (*xmit_tail)->b_cont;
16377 				(*xmit_tail)->b_prev = local_time;
16378 				(*xmit_tail)->b_next =
16379 				    (mblk_t *)(uintptr_t)(*snxt);
16380 				mp1 = mp1->b_cont;
16381 			}
16382 			*snxt += len;
16383 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
16384 			BUMP_LOCAL(tcp->tcp_obsegs);
16385 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16386 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16387 			tcp_send_data(tcp, mp);
16388 			continue;
16389 		}
16390 
16391 		*snxt += len;	/* Adjust later if we don't send all of len */
16392 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16393 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16394 
16395 		if (*tail_unsent) {
16396 			/* Are the bytes above us in flight? */
16397 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
16398 			if (rptr != (*xmit_tail)->b_rptr) {
16399 				*tail_unsent -= len;
16400 				if (len <= mss) /* LSO is unusable */
16401 					tcp->tcp_last_sent_len = (ushort_t)len;
16402 				len += total_hdr_len;
16403 				ixa->ixa_pktlen = len;
16404 
16405 				if (ixa->ixa_flags & IXAF_IS_IPV4) {
16406 					tcp->tcp_ipha->ipha_length = htons(len);
16407 				} else {
16408 					tcp->tcp_ip6h->ip6_plen =
16409 					    htons(len - IPV6_HDR_LEN);
16410 				}
16411 
16412 				mp = dupb(*xmit_tail);
16413 				if (mp == NULL) {
16414 					return (-1);	/* out_of_mem */
16415 				}
16416 				mp->b_rptr = rptr;
16417 				/*
16418 				 * If the old timestamp is no longer in use,
16419 				 * sample a new timestamp now.
16420 				 */
16421 				if ((*xmit_tail)->b_next == NULL) {
16422 					(*xmit_tail)->b_prev = local_time;
16423 					(*xmit_tail)->b_next =
16424 					    (mblk_t *)(uintptr_t)(*snxt-len);
16425 				}
16426 				goto must_alloc;
16427 			}
16428 		} else {
16429 			*xmit_tail = (*xmit_tail)->b_cont;
16430 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
16431 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
16432 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
16433 			    (*xmit_tail)->b_rptr);
16434 		}
16435 
16436 		(*xmit_tail)->b_prev = local_time;
16437 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
16438 
16439 		*tail_unsent -= len;
16440 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
16441 			tcp->tcp_last_sent_len = (ushort_t)len;
16442 
16443 		len += total_hdr_len;
16444 		ixa->ixa_pktlen = len;
16445 
16446 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
16447 			tcp->tcp_ipha->ipha_length = htons(len);
16448 		} else {
16449 			tcp->tcp_ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
16450 		}
16451 
16452 		mp = dupb(*xmit_tail);
16453 		if (mp == NULL) {
16454 			return (-1);	/* out_of_mem */
16455 		}
16456 
16457 		len = total_hdr_len;
16458 		/*
16459 		 * There are four reasons to allocate a new hdr mblk:
16460 		 *  1) The bytes above us are in use by another packet
16461 		 *  2) We don't have good alignment
16462 		 *  3) The mblk is being shared
16463 		 *  4) We don't have enough room for a header
16464 		 */
16465 		rptr = mp->b_rptr - len;
16466 		if (!OK_32PTR(rptr) ||
16467 		    ((db = mp->b_datap), db->db_ref != 2) ||
16468 		    rptr < db->db_base) {
16469 			/* NOTE: we assume allocb returns an OK_32PTR */
16470 
16471 		must_alloc:;
16472 			mp1 = allocb(connp->conn_ht_iphc_allocated +
16473 			    tcps->tcps_wroff_xtra, BPRI_MED);
16474 			if (mp1 == NULL) {
16475 				freemsg(mp);
16476 				return (-1);	/* out_of_mem */
16477 			}
16478 			mp1->b_cont = mp;
16479 			mp = mp1;
16480 			/* Leave room for Link Level header */
16481 			len = total_hdr_len;
16482 			rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
16483 			mp->b_wptr = &rptr[len];
16484 		}
16485 
16486 		/*
16487 		 * Fill in the header using the template header, and add
16488 		 * options such as time-stamp, ECN and/or SACK, as needed.
16489 		 */
16490 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
16491 
16492 		mp->b_rptr = rptr;
16493 
16494 		if (*tail_unsent) {
16495 			int spill = *tail_unsent;
16496 
16497 			mp1 = mp->b_cont;
16498 			if (mp1 == NULL)
16499 				mp1 = mp;
16500 
16501 			/*
16502 			 * If we're a little short, tack on more mblks until
16503 			 * there is no more spillover.
16504 			 */
16505 			while (spill < 0) {
16506 				mblk_t *nmp;
16507 				int nmpsz;
16508 
16509 				nmp = (*xmit_tail)->b_cont;
16510 				nmpsz = MBLKL(nmp);
16511 
16512 				/*
16513 				 * Excess data in mblk; can we split it?
16514 				 * If LSO is enabled for the connection,
16515 				 * keep on splitting as this is a transient
16516 				 * send path.
16517 				 */
16518 				if (!do_lso_send && (spill + nmpsz > 0)) {
16519 					/*
16520 					 * Don't split if stream head was
16521 					 * told to break up larger writes
16522 					 * into smaller ones.
16523 					 */
16524 					if (tcp->tcp_maxpsz_multiplier > 0)
16525 						break;
16526 
16527 					/*
16528 					 * Next mblk is less than SMSS/2
16529 					 * rounded up to nearest 64-byte;
16530 					 * let it get sent as part of the
16531 					 * next segment.
16532 					 */
16533 					if (tcp->tcp_localnet &&
16534 					    !tcp->tcp_cork &&
16535 					    (nmpsz < roundup((mss >> 1), 64)))
16536 						break;
16537 				}
16538 
16539 				*xmit_tail = nmp;
16540 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
16541 				/* Stash for rtt use later */
16542 				(*xmit_tail)->b_prev = local_time;
16543 				(*xmit_tail)->b_next =
16544 				    (mblk_t *)(uintptr_t)(*snxt - len);
16545 				mp1->b_cont = dupb(*xmit_tail);
16546 				mp1 = mp1->b_cont;
16547 
16548 				spill += nmpsz;
16549 				if (mp1 == NULL) {
16550 					*tail_unsent = spill;
16551 					freemsg(mp);
16552 					return (-1);	/* out_of_mem */
16553 				}
16554 			}
16555 
16556 			/* Trim back any surplus on the last mblk */
16557 			if (spill >= 0) {
16558 				mp1->b_wptr -= spill;
16559 				*tail_unsent = spill;
16560 			} else {
16561 				/*
16562 				 * We did not send everything we could in
16563 				 * order to remain within the b_cont limit.
16564 				 */
16565 				*usable -= spill;
16566 				*snxt += spill;
16567 				tcp->tcp_last_sent_len += spill;
16568 				UPDATE_MIB(&tcps->tcps_mib,
16569 				    tcpOutDataBytes, spill);
16570 				/*
16571 				 * Adjust the checksum
16572 				 */
16573 				tcpha = (tcpha_t *)(rptr +
16574 				    ixa->ixa_ip_hdr_length);
16575 				sum += spill;
16576 				sum = (sum >> 16) + (sum & 0xFFFF);
16577 				tcpha->tha_sum = htons(sum);
16578 				if (connp->conn_ipversion == IPV4_VERSION) {
16579 					sum = ntohs(
16580 					    ((ipha_t *)rptr)->ipha_length) +
16581 					    spill;
16582 					((ipha_t *)rptr)->ipha_length =
16583 					    htons(sum);
16584 				} else {
16585 					sum = ntohs(
16586 					    ((ip6_t *)rptr)->ip6_plen) +
16587 					    spill;
16588 					((ip6_t *)rptr)->ip6_plen =
16589 					    htons(sum);
16590 				}
16591 				ixa->ixa_pktlen += spill;
16592 				*tail_unsent = 0;
16593 			}
16594 		}
16595 		if (tcp->tcp_ip_forward_progress) {
16596 			tcp->tcp_ip_forward_progress = B_FALSE;
16597 			ixa->ixa_flags |= IXAF_REACH_CONF;
16598 		} else {
16599 			ixa->ixa_flags &= ~IXAF_REACH_CONF;
16600 		}
16601 
16602 		if (do_lso_send) {
16603 			/* Append LSO information to the mp. */
16604 			lso_info_set(mp, mss, HW_LSO);
16605 			ixa->ixa_fragsize = IP_MAXPACKET;
16606 			ixa->ixa_extra_ident = num_lso_seg - 1;
16607 
16608 			DTRACE_PROBE2(tcp_send_lso, int, num_lso_seg,
16609 			    boolean_t, B_TRUE);
16610 
16611 			tcp_send_data(tcp, mp);
16612 
16613 			/*
16614 			 * Restore values of ixa_fragsize and ixa_extra_ident.
16615 			 */
16616 			ixa->ixa_fragsize = ixa->ixa_pmtu;
16617 			ixa->ixa_extra_ident = 0;
16618 			tcp->tcp_obsegs += num_lso_seg;
16619 			TCP_STAT(tcps, tcp_lso_times);
16620 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
16621 		} else {
16622 			/*
16623 			 * Make sure to clean up LSO information. Wherever a
16624 			 * new mp uses the prepended header room after dupb(),
16625 			 * lso_info_cleanup() should be called.
16626 			 */
16627 			lso_info_cleanup(mp);
16628 			tcp_send_data(tcp, mp);
16629 			BUMP_LOCAL(tcp->tcp_obsegs);
16630 		}
16631 	}
16632 
16633 	return (0);
16634 }
16635 
16636 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
16637 static void
16638 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
16639 {
16640 	uchar_t	fval = *mp->b_rptr;
16641 	mblk_t	*tail;
16642 	conn_t	*connp = tcp->tcp_connp;
16643 	queue_t	*q = connp->conn_wq;
16644 
16645 	/* TODO: How should flush interact with urgent data? */
16646 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
16647 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
16648 		/*
16649 		 * Flush only data that has not yet been put on the wire.  If
16650 		 * we flush data that we have already transmitted, life, as we
16651 		 * know it, may come to an end.
16652 		 */
16653 		tail = tcp->tcp_xmit_tail;
16654 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
16655 		tcp->tcp_xmit_tail_unsent = 0;
16656 		tcp->tcp_unsent = 0;
16657 		if (tail->b_wptr != tail->b_rptr)
16658 			tail = tail->b_cont;
16659 		if (tail) {
16660 			mblk_t **excess = &tcp->tcp_xmit_head;
16661 			for (;;) {
16662 				mblk_t *mp1 = *excess;
16663 				if (mp1 == tail)
16664 					break;
16665 				tcp->tcp_xmit_tail = mp1;
16666 				tcp->tcp_xmit_last = mp1;
16667 				excess = &mp1->b_cont;
16668 			}
16669 			*excess = NULL;
16670 			tcp_close_mpp(&tail);
16671 			if (tcp->tcp_snd_zcopy_aware)
16672 				tcp_zcopy_notify(tcp);
16673 		}
16674 		/*
16675 		 * We have no unsent data, so unsent must be less than
16676 		 * conn_sndlowat, so re-enable flow.
16677 		 */
16678 		mutex_enter(&tcp->tcp_non_sq_lock);
16679 		if (tcp->tcp_flow_stopped) {
16680 			tcp_clrqfull(tcp);
16681 		}
16682 		mutex_exit(&tcp->tcp_non_sq_lock);
16683 	}
16684 	/*
16685 	 * TODO: you can't just flush these, you have to increase rwnd for one
16686 	 * thing.  For another, how should urgent data interact?
16687 	 */
16688 	if (fval & FLUSHR) {
16689 		*mp->b_rptr = fval & ~FLUSHW;
16690 		/* XXX */
16691 		qreply(q, mp);
16692 		return;
16693 	}
16694 	freemsg(mp);
16695 }
16696 
16697 /*
16698  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
16699  * messages.
16700  */
16701 static void
16702 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
16703 {
16704 	mblk_t		*mp1;
16705 	struct iocblk	*iocp = (struct iocblk *)mp->b_rptr;
16706 	STRUCT_HANDLE(strbuf, sb);
16707 	uint_t		addrlen;
16708 	conn_t		*connp = tcp->tcp_connp;
16709 	queue_t 	*q = connp->conn_wq;
16710 
16711 	/* Make sure it is one of ours. */
16712 	switch (iocp->ioc_cmd) {
16713 	case TI_GETMYNAME:
16714 	case TI_GETPEERNAME:
16715 		break;
16716 	default:
16717 		/*
16718 		 * If the conn is closing, then error the ioctl here. Otherwise
16719 		 * use the CONN_IOCTLREF_* macros to hold off tcp_close until
16720 		 * we're done here.
16721 		 */
16722 		mutex_enter(&connp->conn_lock);
16723 		if (connp->conn_state_flags & CONN_CLOSING) {
16724 			mutex_exit(&connp->conn_lock);
16725 			iocp->ioc_error = EINVAL;
16726 			mp->b_datap->db_type = M_IOCNAK;
16727 			iocp->ioc_count = 0;
16728 			qreply(q, mp);
16729 			return;
16730 		}
16731 
16732 		CONN_INC_IOCTLREF_LOCKED(connp);
16733 		ip_wput_nondata(q, mp);
16734 		CONN_DEC_IOCTLREF(connp);
16735 		return;
16736 	}
16737 	switch (mi_copy_state(q, mp, &mp1)) {
16738 	case -1:
16739 		return;
16740 	case MI_COPY_CASE(MI_COPY_IN, 1):
16741 		break;
16742 	case MI_COPY_CASE(MI_COPY_OUT, 1):
16743 		/* Copy out the strbuf. */
16744 		mi_copyout(q, mp);
16745 		return;
16746 	case MI_COPY_CASE(MI_COPY_OUT, 2):
16747 		/* All done. */
16748 		mi_copy_done(q, mp, 0);
16749 		return;
16750 	default:
16751 		mi_copy_done(q, mp, EPROTO);
16752 		return;
16753 	}
16754 	/* Check alignment of the strbuf */
16755 	if (!OK_32PTR(mp1->b_rptr)) {
16756 		mi_copy_done(q, mp, EINVAL);
16757 		return;
16758 	}
16759 
16760 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
16761 
16762 	if (connp->conn_family == AF_INET)
16763 		addrlen = sizeof (sin_t);
16764 	else
16765 		addrlen = sizeof (sin6_t);
16766 
16767 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
16768 		mi_copy_done(q, mp, EINVAL);
16769 		return;
16770 	}
16771 
16772 	switch (iocp->ioc_cmd) {
16773 	case TI_GETMYNAME:
16774 		break;
16775 	case TI_GETPEERNAME:
16776 		if (tcp->tcp_state < TCPS_SYN_RCVD) {
16777 			mi_copy_done(q, mp, ENOTCONN);
16778 			return;
16779 		}
16780 		break;
16781 	}
16782 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
16783 	if (!mp1)
16784 		return;
16785 
16786 	STRUCT_FSET(sb, len, addrlen);
16787 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
16788 	case TI_GETMYNAME:
16789 		(void) conn_getsockname(connp, (struct sockaddr *)mp1->b_wptr,
16790 		    &addrlen);
16791 		break;
16792 	case TI_GETPEERNAME:
16793 		(void) conn_getpeername(connp, (struct sockaddr *)mp1->b_wptr,
16794 		    &addrlen);
16795 		break;
16796 	}
16797 	mp1->b_wptr += addrlen;
16798 	/* Copy out the address */
16799 	mi_copyout(q, mp);
16800 }
16801 
16802 static void
16803 tcp_use_pure_tpi(tcp_t *tcp)
16804 {
16805 	conn_t		*connp = tcp->tcp_connp;
16806 
16807 #ifdef	_ILP32
16808 	tcp->tcp_acceptor_id = (t_uscalar_t)connp->conn_rq;
16809 #else
16810 	tcp->tcp_acceptor_id = connp->conn_dev;
16811 #endif
16812 	/*
16813 	 * Insert this socket into the acceptor hash.
16814 	 * We might need it for T_CONN_RES message
16815 	 */
16816 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
16817 
16818 	tcp->tcp_issocket = B_FALSE;
16819 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
16820 }
16821 
16822 /*
16823  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
16824  * messages.
16825  */
16826 /* ARGSUSED */
16827 static void
16828 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
16829 {
16830 	conn_t 		*connp = (conn_t *)arg;
16831 	tcp_t		*tcp = connp->conn_tcp;
16832 	queue_t		*q = connp->conn_wq;
16833 	struct iocblk	*iocp;
16834 
16835 	ASSERT(DB_TYPE(mp) == M_IOCTL);
16836 	/*
16837 	 * Try and ASSERT the minimum possible references on the
16838 	 * conn early enough. Since we are executing on write side,
16839 	 * the connection is obviously not detached and that means
16840 	 * there is a ref each for TCP and IP. Since we are behind
16841 	 * the squeue, the minimum references needed are 3. If the
16842 	 * conn is in classifier hash list, there should be an
16843 	 * extra ref for that (we check both the possibilities).
16844 	 */
16845 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16846 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16847 
16848 	iocp = (struct iocblk *)mp->b_rptr;
16849 	switch (iocp->ioc_cmd) {
16850 	case _SIOCSOCKFALLBACK:
16851 		/*
16852 		 * Either sockmod is about to be popped and the socket
16853 		 * would now be treated as a plain stream, or a module
16854 		 * is about to be pushed so we could no longer use read-
16855 		 * side synchronous streams for fused loopback tcp.
16856 		 * Drain any queued data and disable direct sockfs
16857 		 * interface from now on.
16858 		 */
16859 		if (!tcp->tcp_issocket) {
16860 			DB_TYPE(mp) = M_IOCNAK;
16861 			iocp->ioc_error = EINVAL;
16862 		} else {
16863 			tcp_use_pure_tpi(tcp);
16864 			DB_TYPE(mp) = M_IOCACK;
16865 			iocp->ioc_error = 0;
16866 		}
16867 		iocp->ioc_count = 0;
16868 		iocp->ioc_rval = 0;
16869 		qreply(q, mp);
16870 		return;
16871 	}
16872 
16873 	/*
16874 	 * If the conn is closing, then error the ioctl here. Otherwise bump the
16875 	 * conn_ioctlref to hold off tcp_close until we're done here.
16876 	 */
16877 	mutex_enter(&(connp)->conn_lock);
16878 	if ((connp)->conn_state_flags & CONN_CLOSING) {
16879 		mutex_exit(&(connp)->conn_lock);
16880 		iocp->ioc_error = EINVAL;
16881 		mp->b_datap->db_type = M_IOCNAK;
16882 		iocp->ioc_count = 0;
16883 		qreply(q, mp);
16884 		return;
16885 	}
16886 
16887 	CONN_INC_IOCTLREF_LOCKED(connp);
16888 	ip_wput_nondata(q, mp);
16889 	CONN_DEC_IOCTLREF(connp);
16890 }
16891 
16892 /*
16893  * This routine is called by tcp_wput() to handle all TPI requests.
16894  */
16895 /* ARGSUSED */
16896 static void
16897 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
16898 {
16899 	conn_t		*connp = (conn_t *)arg;
16900 	tcp_t		*tcp = connp->conn_tcp;
16901 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
16902 	uchar_t		*rptr;
16903 	t_scalar_t	type;
16904 	cred_t		*cr;
16905 
16906 	/*
16907 	 * Try and ASSERT the minimum possible references on the
16908 	 * conn early enough. Since we are executing on write side,
16909 	 * the connection is obviously not detached and that means
16910 	 * there is a ref each for TCP and IP. Since we are behind
16911 	 * the squeue, the minimum references needed are 3. If the
16912 	 * conn is in classifier hash list, there should be an
16913 	 * extra ref for that (we check both the possibilities).
16914 	 */
16915 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16916 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16917 
16918 	rptr = mp->b_rptr;
16919 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
16920 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
16921 		type = ((union T_primitives *)rptr)->type;
16922 		if (type == T_EXDATA_REQ) {
16923 			tcp_output_urgent(connp, mp, arg2, NULL);
16924 		} else if (type != T_DATA_REQ) {
16925 			goto non_urgent_data;
16926 		} else {
16927 			/* TODO: options, flags, ... from user */
16928 			/* Set length to zero for reclamation below */
16929 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
16930 			freeb(mp);
16931 		}
16932 		return;
16933 	} else {
16934 		if (connp->conn_debug) {
16935 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
16936 			    "tcp_wput_proto, dropping one...");
16937 		}
16938 		freemsg(mp);
16939 		return;
16940 	}
16941 
16942 non_urgent_data:
16943 
16944 	switch ((int)tprim->type) {
16945 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
16946 		/*
16947 		 * save the kssl_ent_t from the next block, and convert this
16948 		 * back to a normal bind_req.
16949 		 */
16950 		if (mp->b_cont != NULL) {
16951 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
16952 
16953 			if (tcp->tcp_kssl_ent != NULL) {
16954 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
16955 				    KSSL_NO_PROXY);
16956 				tcp->tcp_kssl_ent = NULL;
16957 			}
16958 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
16959 			    sizeof (kssl_ent_t));
16960 			kssl_hold_ent(tcp->tcp_kssl_ent);
16961 			freemsg(mp->b_cont);
16962 			mp->b_cont = NULL;
16963 		}
16964 		tprim->type = T_BIND_REQ;
16965 
16966 	/* FALLTHROUGH */
16967 	case O_T_BIND_REQ:	/* bind request */
16968 	case T_BIND_REQ:	/* new semantics bind request */
16969 		tcp_tpi_bind(tcp, mp);
16970 		break;
16971 	case T_UNBIND_REQ:	/* unbind request */
16972 		tcp_tpi_unbind(tcp, mp);
16973 		break;
16974 	case O_T_CONN_RES:	/* old connection response XXX */
16975 	case T_CONN_RES:	/* connection response */
16976 		tcp_tli_accept(tcp, mp);
16977 		break;
16978 	case T_CONN_REQ:	/* connection request */
16979 		tcp_tpi_connect(tcp, mp);
16980 		break;
16981 	case T_DISCON_REQ:	/* disconnect request */
16982 		tcp_disconnect(tcp, mp);
16983 		break;
16984 	case T_CAPABILITY_REQ:
16985 		tcp_capability_req(tcp, mp);	/* capability request */
16986 		break;
16987 	case T_INFO_REQ:	/* information request */
16988 		tcp_info_req(tcp, mp);
16989 		break;
16990 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
16991 	case T_OPTMGMT_REQ:
16992 		/*
16993 		 * Note:  no support for snmpcom_req() through new
16994 		 * T_OPTMGMT_REQ. See comments in ip.c
16995 		 */
16996 
16997 		/*
16998 		 * All Solaris components should pass a db_credp
16999 		 * for this TPI message, hence we ASSERT.
17000 		 * But in case there is some other M_PROTO that looks
17001 		 * like a TPI message sent by some other kernel
17002 		 * component, we check and return an error.
17003 		 */
17004 		cr = msg_getcred(mp, NULL);
17005 		ASSERT(cr != NULL);
17006 		if (cr == NULL) {
17007 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
17008 			return;
17009 		}
17010 		/*
17011 		 * If EINPROGRESS is returned, the request has been queued
17012 		 * for subsequent processing by ip_restart_optmgmt(), which
17013 		 * will do the CONN_DEC_REF().
17014 		 */
17015 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
17016 			svr4_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
17017 		} else {
17018 			tpi_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
17019 		}
17020 		break;
17021 
17022 	case T_UNITDATA_REQ:	/* unitdata request */
17023 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
17024 		break;
17025 	case T_ORDREL_REQ:	/* orderly release req */
17026 		freemsg(mp);
17027 
17028 		if (tcp->tcp_fused)
17029 			tcp_unfuse(tcp);
17030 
17031 		if (tcp_xmit_end(tcp) != 0) {
17032 			/*
17033 			 * We were crossing FINs and got a reset from
17034 			 * the other side. Just ignore it.
17035 			 */
17036 			if (connp->conn_debug) {
17037 				(void) strlog(TCP_MOD_ID, 0, 1,
17038 				    SL_ERROR|SL_TRACE,
17039 				    "tcp_wput_proto, T_ORDREL_REQ out of "
17040 				    "state %s",
17041 				    tcp_display(tcp, NULL,
17042 				    DISP_ADDR_AND_PORT));
17043 			}
17044 		}
17045 		break;
17046 	case T_ADDR_REQ:
17047 		tcp_addr_req(tcp, mp);
17048 		break;
17049 	default:
17050 		if (connp->conn_debug) {
17051 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
17052 			    "tcp_wput_proto, bogus TPI msg, type %d",
17053 			    tprim->type);
17054 		}
17055 		/*
17056 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
17057 		 * to recover.
17058 		 */
17059 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
17060 		break;
17061 	}
17062 }
17063 
17064 /*
17065  * The TCP write service routine should never be called...
17066  */
17067 /* ARGSUSED */
17068 static void
17069 tcp_wsrv(queue_t *q)
17070 {
17071 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
17072 
17073 	TCP_STAT(tcps, tcp_wsrv_called);
17074 }
17075 
17076 /*
17077  * Send out a control packet on the tcp connection specified.  This routine
17078  * is typically called where we need a simple ACK or RST generated.
17079  */
17080 static void
17081 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
17082 {
17083 	uchar_t		*rptr;
17084 	tcpha_t		*tcpha;
17085 	ipha_t		*ipha = NULL;
17086 	ip6_t		*ip6h = NULL;
17087 	uint32_t	sum;
17088 	int		total_hdr_len;
17089 	int		ip_hdr_len;
17090 	mblk_t		*mp;
17091 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17092 	conn_t		*connp = tcp->tcp_connp;
17093 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
17094 
17095 	/*
17096 	 * Save sum for use in source route later.
17097 	 */
17098 	sum = connp->conn_ht_ulp_len + connp->conn_sum;
17099 	total_hdr_len = connp->conn_ht_iphc_len;
17100 	ip_hdr_len = ixa->ixa_ip_hdr_length;
17101 
17102 	/* If a text string is passed in with the request, pass it to strlog. */
17103 	if (str != NULL && connp->conn_debug) {
17104 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
17105 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
17106 		    str, seq, ack, ctl);
17107 	}
17108 	mp = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
17109 	    BPRI_MED);
17110 	if (mp == NULL) {
17111 		return;
17112 	}
17113 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
17114 	mp->b_rptr = rptr;
17115 	mp->b_wptr = &rptr[total_hdr_len];
17116 	bcopy(connp->conn_ht_iphc, rptr, total_hdr_len);
17117 
17118 	ixa->ixa_pktlen = total_hdr_len;
17119 
17120 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
17121 		ipha = (ipha_t *)rptr;
17122 		ipha->ipha_length = htons(total_hdr_len);
17123 	} else {
17124 		ip6h = (ip6_t *)rptr;
17125 		ip6h->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
17126 	}
17127 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
17128 	tcpha->tha_flags = (uint8_t)ctl;
17129 	if (ctl & TH_RST) {
17130 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
17131 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17132 		/*
17133 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
17134 		 */
17135 		if (tcp->tcp_snd_ts_ok &&
17136 		    tcp->tcp_state > TCPS_SYN_SENT) {
17137 			mp->b_wptr = &rptr[total_hdr_len - TCPOPT_REAL_TS_LEN];
17138 			*(mp->b_wptr) = TCPOPT_EOL;
17139 
17140 			ixa->ixa_pktlen = total_hdr_len - TCPOPT_REAL_TS_LEN;
17141 
17142 			if (connp->conn_ipversion == IPV4_VERSION) {
17143 				ipha->ipha_length = htons(total_hdr_len -
17144 				    TCPOPT_REAL_TS_LEN);
17145 			} else {
17146 				ip6h->ip6_plen = htons(total_hdr_len -
17147 				    IPV6_HDR_LEN - TCPOPT_REAL_TS_LEN);
17148 			}
17149 			tcpha->tha_offset_and_reserved -= (3 << 4);
17150 			sum -= TCPOPT_REAL_TS_LEN;
17151 		}
17152 	}
17153 	if (ctl & TH_ACK) {
17154 		if (tcp->tcp_snd_ts_ok) {
17155 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
17156 
17157 			U32_TO_BE32(llbolt,
17158 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
17159 			U32_TO_BE32(tcp->tcp_ts_recent,
17160 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
17161 		}
17162 
17163 		/* Update the latest receive window size in TCP header. */
17164 		tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
17165 		/* Track what we sent to the peer */
17166 		tcp->tcp_tcpha->tha_win = tcpha->tha_win;
17167 		tcp->tcp_rack = ack;
17168 		tcp->tcp_rack_cnt = 0;
17169 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
17170 	}
17171 	BUMP_LOCAL(tcp->tcp_obsegs);
17172 	tcpha->tha_seq = htonl(seq);
17173 	tcpha->tha_ack = htonl(ack);
17174 	/*
17175 	 * Include the adjustment for a source route if any.
17176 	 */
17177 	sum = (sum >> 16) + (sum & 0xFFFF);
17178 	tcpha->tha_sum = htons(sum);
17179 	tcp_send_data(tcp, mp);
17180 }
17181 
17182 /*
17183  * If this routine returns B_TRUE, TCP can generate a RST in response
17184  * to a segment.  If it returns B_FALSE, TCP should not respond.
17185  */
17186 static boolean_t
17187 tcp_send_rst_chk(tcp_stack_t *tcps)
17188 {
17189 	int64_t	now;
17190 
17191 	/*
17192 	 * TCP needs to protect itself from generating too many RSTs.
17193 	 * This can be a DoS attack by sending us random segments
17194 	 * soliciting RSTs.
17195 	 *
17196 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
17197 	 * in each 1 second interval.  In this way, TCP still generate
17198 	 * RSTs in normal cases but when under attack, the impact is
17199 	 * limited.
17200 	 */
17201 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
17202 		now = ddi_get_lbolt64();
17203 		if (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
17204 		    1*SECONDS) {
17205 			tcps->tcps_last_rst_intrvl = now;
17206 			tcps->tcps_rst_cnt = 1;
17207 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
17208 			return (B_FALSE);
17209 		}
17210 	}
17211 	return (B_TRUE);
17212 }
17213 
17214 /*
17215  * Generate a reset based on an inbound packet, connp is set by caller
17216  * when RST is in response to an unexpected inbound packet for which
17217  * there is active tcp state in the system.
17218  *
17219  * IPSEC NOTE : Try to send the reply with the same protection as it came
17220  * in.  We have the ip_recv_attr_t which is reversed to form the ip_xmit_attr_t.
17221  * That way the packet will go out at the same level of protection as it
17222  * came in with.
17223  */
17224 static void
17225 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq, uint32_t ack, int ctl,
17226     ip_recv_attr_t *ira, ip_stack_t *ipst, conn_t *connp)
17227 {
17228 	ipha_t		*ipha = NULL;
17229 	ip6_t		*ip6h = NULL;
17230 	ushort_t	len;
17231 	tcpha_t		*tcpha;
17232 	int		i;
17233 	ipaddr_t	v4addr;
17234 	in6_addr_t	v6addr;
17235 	netstack_t	*ns = ipst->ips_netstack;
17236 	tcp_stack_t	*tcps = ns->netstack_tcp;
17237 	ip_xmit_attr_t	ixas, *ixa;
17238 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
17239 	boolean_t	need_refrele = B_FALSE;		/* ixa_refrele(ixa) */
17240 	ushort_t	port;
17241 
17242 	if (!tcp_send_rst_chk(tcps)) {
17243 		TCP_STAT(tcps, tcp_rst_unsent);
17244 		freemsg(mp);
17245 		return;
17246 	}
17247 
17248 	/*
17249 	 * If connp != NULL we use conn_ixa to keep IP_NEXTHOP and other
17250 	 * options from the listener. In that case the caller must ensure that
17251 	 * we are running on the listener = connp squeue.
17252 	 *
17253 	 * We get a safe copy of conn_ixa so we don't need to restore anything
17254 	 * we or ip_output_simple might change in the ixa.
17255 	 */
17256 	if (connp != NULL) {
17257 		ASSERT(connp->conn_on_sqp);
17258 
17259 		ixa = conn_get_ixa_exclusive(connp);
17260 		if (ixa == NULL) {
17261 			TCP_STAT(tcps, tcp_rst_unsent);
17262 			freemsg(mp);
17263 			return;
17264 		}
17265 		need_refrele = B_TRUE;
17266 	} else {
17267 		bzero(&ixas, sizeof (ixas));
17268 		ixa = &ixas;
17269 		/*
17270 		 * IXAF_VERIFY_SOURCE is overkill since we know the
17271 		 * packet was for us.
17272 		 */
17273 		ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE;
17274 		ixa->ixa_protocol = IPPROTO_TCP;
17275 		ixa->ixa_zoneid = ira->ira_zoneid;
17276 		ixa->ixa_ifindex = 0;
17277 		ixa->ixa_ipst = ipst;
17278 		ixa->ixa_cred = kcred;
17279 		ixa->ixa_cpid = NOPID;
17280 	}
17281 
17282 	if (str && tcps->tcps_dbg) {
17283 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
17284 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
17285 		    "flags 0x%x",
17286 		    str, seq, ack, ctl);
17287 	}
17288 	if (mp->b_datap->db_ref != 1) {
17289 		mblk_t *mp1 = copyb(mp);
17290 		freemsg(mp);
17291 		mp = mp1;
17292 		if (mp == NULL)
17293 			goto done;
17294 	} else if (mp->b_cont) {
17295 		freemsg(mp->b_cont);
17296 		mp->b_cont = NULL;
17297 		DB_CKSUMFLAGS(mp) = 0;
17298 	}
17299 	/*
17300 	 * We skip reversing source route here.
17301 	 * (for now we replace all IP options with EOL)
17302 	 */
17303 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17304 		ipha = (ipha_t *)mp->b_rptr;
17305 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
17306 			mp->b_rptr[i] = IPOPT_EOL;
17307 		/*
17308 		 * Make sure that src address isn't flagrantly invalid.
17309 		 * Not all broadcast address checking for the src address
17310 		 * is possible, since we don't know the netmask of the src
17311 		 * addr.  No check for destination address is done, since
17312 		 * IP will not pass up a packet with a broadcast dest
17313 		 * address to TCP.  Similar checks are done below for IPv6.
17314 		 */
17315 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
17316 		    CLASSD(ipha->ipha_src)) {
17317 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
17318 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
17319 			freemsg(mp);
17320 			goto done;
17321 		}
17322 	} else {
17323 		ip6h = (ip6_t *)mp->b_rptr;
17324 
17325 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
17326 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
17327 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
17328 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
17329 			freemsg(mp);
17330 			goto done;
17331 		}
17332 
17333 		/* Remove any extension headers assuming partial overlay */
17334 		if (ip_hdr_len > IPV6_HDR_LEN) {
17335 			uint8_t *to;
17336 
17337 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
17338 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
17339 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
17340 			ip_hdr_len = IPV6_HDR_LEN;
17341 			ip6h = (ip6_t *)mp->b_rptr;
17342 			ip6h->ip6_nxt = IPPROTO_TCP;
17343 		}
17344 	}
17345 	tcpha = (tcpha_t *)&mp->b_rptr[ip_hdr_len];
17346 	if (tcpha->tha_flags & TH_RST) {
17347 		freemsg(mp);
17348 		goto done;
17349 	}
17350 	tcpha->tha_offset_and_reserved = (5 << 4);
17351 	len = ip_hdr_len + sizeof (tcpha_t);
17352 	mp->b_wptr = &mp->b_rptr[len];
17353 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17354 		ipha->ipha_length = htons(len);
17355 		/* Swap addresses */
17356 		v4addr = ipha->ipha_src;
17357 		ipha->ipha_src = ipha->ipha_dst;
17358 		ipha->ipha_dst = v4addr;
17359 		ipha->ipha_ident = 0;
17360 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
17361 		ixa->ixa_flags |= IXAF_IS_IPV4;
17362 		ixa->ixa_ip_hdr_length = ip_hdr_len;
17363 	} else {
17364 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
17365 		/* Swap addresses */
17366 		v6addr = ip6h->ip6_src;
17367 		ip6h->ip6_src = ip6h->ip6_dst;
17368 		ip6h->ip6_dst = v6addr;
17369 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
17370 		ixa->ixa_flags &= ~IXAF_IS_IPV4;
17371 
17372 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_dst)) {
17373 			ixa->ixa_flags |= IXAF_SCOPEID_SET;
17374 			ixa->ixa_scopeid = ira->ira_ruifindex;
17375 		}
17376 		ixa->ixa_ip_hdr_length = IPV6_HDR_LEN;
17377 	}
17378 	ixa->ixa_pktlen = len;
17379 
17380 	/* Swap the ports */
17381 	port = tcpha->tha_fport;
17382 	tcpha->tha_fport = tcpha->tha_lport;
17383 	tcpha->tha_lport = port;
17384 
17385 	tcpha->tha_ack = htonl(ack);
17386 	tcpha->tha_seq = htonl(seq);
17387 	tcpha->tha_win = 0;
17388 	tcpha->tha_sum = htons(sizeof (tcpha_t));
17389 	tcpha->tha_flags = (uint8_t)ctl;
17390 	if (ctl & TH_RST) {
17391 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
17392 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17393 	}
17394 
17395 	/* Discard any old label */
17396 	if (ixa->ixa_free_flags & IXA_FREE_TSL) {
17397 		ASSERT(ixa->ixa_tsl != NULL);
17398 		label_rele(ixa->ixa_tsl);
17399 		ixa->ixa_free_flags &= ~IXA_FREE_TSL;
17400 	}
17401 	ixa->ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
17402 
17403 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
17404 		/*
17405 		 * Apply IPsec based on how IPsec was applied to
17406 		 * the packet that caused the RST.
17407 		 */
17408 		if (!ipsec_in_to_out(ira, ixa, mp, ipha, ip6h)) {
17409 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
17410 			/* Note: mp already consumed and ip_drop_packet done */
17411 			goto done;
17412 		}
17413 	} else {
17414 		/*
17415 		 * This is in clear. The RST message we are building
17416 		 * here should go out in clear, independent of our policy.
17417 		 */
17418 		ixa->ixa_flags |= IXAF_NO_IPSEC;
17419 	}
17420 
17421 	/*
17422 	 * NOTE:  one might consider tracing a TCP packet here, but
17423 	 * this function has no active TCP state and no tcp structure
17424 	 * that has a trace buffer.  If we traced here, we would have
17425 	 * to keep a local trace buffer in tcp_record_trace().
17426 	 */
17427 
17428 	(void) ip_output_simple(mp, ixa);
17429 done:
17430 	ixa_cleanup(ixa);
17431 	if (need_refrele) {
17432 		ASSERT(ixa != &ixas);
17433 		ixa_refrele(ixa);
17434 	}
17435 }
17436 
17437 /*
17438  * Initiate closedown sequence on an active connection.  (May be called as
17439  * writer.)  Return value zero for OK return, non-zero for error return.
17440  */
17441 static int
17442 tcp_xmit_end(tcp_t *tcp)
17443 {
17444 	mblk_t		*mp;
17445 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17446 	iulp_t		uinfo;
17447 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17448 	conn_t		*connp = tcp->tcp_connp;
17449 
17450 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
17451 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
17452 		/*
17453 		 * Invalid state, only states TCPS_SYN_RCVD,
17454 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
17455 		 */
17456 		return (-1);
17457 	}
17458 
17459 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
17460 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
17461 	/*
17462 	 * If there is nothing more unsent, send the FIN now.
17463 	 * Otherwise, it will go out with the last segment.
17464 	 */
17465 	if (tcp->tcp_unsent == 0) {
17466 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
17467 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
17468 
17469 		if (mp) {
17470 			tcp_send_data(tcp, mp);
17471 		} else {
17472 			/*
17473 			 * Couldn't allocate msg.  Pretend we got it out.
17474 			 * Wait for rexmit timeout.
17475 			 */
17476 			tcp->tcp_snxt = tcp->tcp_fss + 1;
17477 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17478 		}
17479 
17480 		/*
17481 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
17482 		 * changed.
17483 		 */
17484 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
17485 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
17486 		}
17487 	} else {
17488 		/*
17489 		 * If tcp->tcp_cork is set, then the data will not get sent,
17490 		 * so we have to check that and unset it first.
17491 		 */
17492 		if (tcp->tcp_cork)
17493 			tcp->tcp_cork = B_FALSE;
17494 		tcp_wput_data(tcp, NULL, B_FALSE);
17495 	}
17496 
17497 	/*
17498 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
17499 	 * is 0, don't update the cache.
17500 	 */
17501 	if (tcps->tcps_rtt_updates == 0 ||
17502 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
17503 		return (0);
17504 
17505 	/*
17506 	 * We do not have a good algorithm to update ssthresh at this time.
17507 	 * So don't do any update.
17508 	 */
17509 	bzero(&uinfo, sizeof (uinfo));
17510 	uinfo.iulp_rtt = tcp->tcp_rtt_sa;
17511 	uinfo.iulp_rtt_sd = tcp->tcp_rtt_sd;
17512 
17513 	/*
17514 	 * Note that uinfo is kept for conn_faddr in the DCE. Could update even
17515 	 * if source routed but we don't.
17516 	 */
17517 	if (connp->conn_ipversion == IPV4_VERSION) {
17518 		if (connp->conn_faddr_v4 !=  tcp->tcp_ipha->ipha_dst) {
17519 			return (0);
17520 		}
17521 		(void) dce_update_uinfo_v4(connp->conn_faddr_v4, &uinfo, ipst);
17522 	} else {
17523 		uint_t ifindex;
17524 
17525 		if (!(IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6,
17526 		    &tcp->tcp_ip6h->ip6_dst))) {
17527 			return (0);
17528 		}
17529 		ifindex = 0;
17530 		if (IN6_IS_ADDR_LINKSCOPE(&connp->conn_faddr_v6)) {
17531 			ip_xmit_attr_t *ixa = connp->conn_ixa;
17532 
17533 			/*
17534 			 * If we are going to create a DCE we'd better have
17535 			 * an ifindex
17536 			 */
17537 			if (ixa->ixa_nce != NULL) {
17538 				ifindex = ixa->ixa_nce->nce_common->ncec_ill->
17539 				    ill_phyint->phyint_ifindex;
17540 			} else {
17541 				return (0);
17542 			}
17543 		}
17544 
17545 		(void) dce_update_uinfo(&connp->conn_faddr_v6, ifindex, &uinfo,
17546 		    ipst);
17547 	}
17548 	return (0);
17549 }
17550 
17551 /*
17552  * Generate a "no listener here" RST in response to an "unknown" segment.
17553  * connp is set by caller when RST is in response to an unexpected
17554  * inbound packet for which there is active tcp state in the system.
17555  * Note that we are reusing the incoming mp to construct the outgoing RST.
17556  */
17557 void
17558 tcp_xmit_listeners_reset(mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst,
17559     conn_t *connp)
17560 {
17561 	uchar_t		*rptr;
17562 	uint32_t	seg_len;
17563 	tcpha_t		*tcpha;
17564 	uint32_t	seg_seq;
17565 	uint32_t	seg_ack;
17566 	uint_t		flags;
17567 	ipha_t 		*ipha;
17568 	ip6_t 		*ip6h;
17569 	boolean_t	policy_present;
17570 	netstack_t	*ns = ipst->ips_netstack;
17571 	tcp_stack_t	*tcps = ns->netstack_tcp;
17572 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
17573 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
17574 
17575 	TCP_STAT(tcps, tcp_no_listener);
17576 
17577 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17578 		policy_present = ipss->ipsec_inbound_v4_policy_present;
17579 		ipha = (ipha_t *)mp->b_rptr;
17580 		ip6h = NULL;
17581 	} else {
17582 		policy_present = ipss->ipsec_inbound_v6_policy_present;
17583 		ipha = NULL;
17584 		ip6h = (ip6_t *)mp->b_rptr;
17585 	}
17586 
17587 	if (policy_present) {
17588 		/*
17589 		 * The conn_t parameter is NULL because we already know
17590 		 * nobody's home.
17591 		 */
17592 		mp = ipsec_check_global_policy(mp, (conn_t *)NULL, ipha, ip6h,
17593 		    ira, ns);
17594 		if (mp == NULL)
17595 			return;
17596 	}
17597 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
17598 		DTRACE_PROBE2(
17599 		    tx__ip__log__error__nolistener__tcp,
17600 		    char *, "Could not reply with RST to mp(1)",
17601 		    mblk_t *, mp);
17602 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
17603 		freemsg(mp);
17604 		return;
17605 	}
17606 
17607 	rptr = mp->b_rptr;
17608 
17609 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
17610 	seg_seq = ntohl(tcpha->tha_seq);
17611 	seg_ack = ntohl(tcpha->tha_ack);
17612 	flags = tcpha->tha_flags;
17613 
17614 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcpha) + ip_hdr_len);
17615 	if (flags & TH_RST) {
17616 		freemsg(mp);
17617 	} else if (flags & TH_ACK) {
17618 		tcp_xmit_early_reset("no tcp, reset", mp, seg_ack, 0, TH_RST,
17619 		    ira, ipst, connp);
17620 	} else {
17621 		if (flags & TH_SYN) {
17622 			seg_len++;
17623 		} else {
17624 			/*
17625 			 * Here we violate the RFC.  Note that a normal
17626 			 * TCP will never send a segment without the ACK
17627 			 * flag, except for RST or SYN segment.  This
17628 			 * segment is neither.  Just drop it on the
17629 			 * floor.
17630 			 */
17631 			freemsg(mp);
17632 			TCP_STAT(tcps, tcp_rst_unsent);
17633 			return;
17634 		}
17635 
17636 		tcp_xmit_early_reset("no tcp, reset/ack", mp, 0,
17637 		    seg_seq + seg_len, TH_RST | TH_ACK, ira, ipst, connp);
17638 	}
17639 }
17640 
17641 /*
17642  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
17643  * ip and tcp header ready to pass down to IP.  If the mp passed in is
17644  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
17645  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
17646  * otherwise it will dup partial mblks.)
17647  * Otherwise, an appropriate ACK packet will be generated.  This
17648  * routine is not usually called to send new data for the first time.  It
17649  * is mostly called out of the timer for retransmits, and to generate ACKs.
17650  *
17651  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
17652  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
17653  * of the original mblk chain will be returned in *offset and *end_mp.
17654  */
17655 mblk_t *
17656 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
17657     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
17658     boolean_t rexmit)
17659 {
17660 	int	data_length;
17661 	int32_t	off = 0;
17662 	uint_t	flags;
17663 	mblk_t	*mp1;
17664 	mblk_t	*mp2;
17665 	uchar_t	*rptr;
17666 	tcpha_t	*tcpha;
17667 	int32_t	num_sack_blk = 0;
17668 	int32_t	sack_opt_len = 0;
17669 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17670 	conn_t		*connp = tcp->tcp_connp;
17671 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
17672 
17673 	/* Allocate for our maximum TCP header + link-level */
17674 	mp1 = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
17675 	    BPRI_MED);
17676 	if (!mp1)
17677 		return (NULL);
17678 	data_length = 0;
17679 
17680 	/*
17681 	 * Note that tcp_mss has been adjusted to take into account the
17682 	 * timestamp option if applicable.  Because SACK options do not
17683 	 * appear in every TCP segments and they are of variable lengths,
17684 	 * they cannot be included in tcp_mss.  Thus we need to calculate
17685 	 * the actual segment length when we need to send a segment which
17686 	 * includes SACK options.
17687 	 */
17688 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
17689 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
17690 		    tcp->tcp_num_sack_blk);
17691 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
17692 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
17693 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
17694 			max_to_send -= sack_opt_len;
17695 	}
17696 
17697 	if (offset != NULL) {
17698 		off = *offset;
17699 		/* We use offset as an indicator that end_mp is not NULL. */
17700 		*end_mp = NULL;
17701 	}
17702 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
17703 		/* This could be faster with cooperation from downstream */
17704 		if (mp2 != mp1 && !sendall &&
17705 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
17706 		    max_to_send)
17707 			/*
17708 			 * Don't send the next mblk since the whole mblk
17709 			 * does not fit.
17710 			 */
17711 			break;
17712 		mp2->b_cont = dupb(mp);
17713 		mp2 = mp2->b_cont;
17714 		if (!mp2) {
17715 			freemsg(mp1);
17716 			return (NULL);
17717 		}
17718 		mp2->b_rptr += off;
17719 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
17720 		    (uintptr_t)INT_MAX);
17721 
17722 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
17723 		if (data_length > max_to_send) {
17724 			mp2->b_wptr -= data_length - max_to_send;
17725 			data_length = max_to_send;
17726 			off = mp2->b_wptr - mp->b_rptr;
17727 			break;
17728 		} else {
17729 			off = 0;
17730 		}
17731 	}
17732 	if (offset != NULL) {
17733 		*offset = off;
17734 		*end_mp = mp;
17735 	}
17736 	if (seg_len != NULL) {
17737 		*seg_len = data_length;
17738 	}
17739 
17740 	/* Update the latest receive window size in TCP header. */
17741 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
17742 
17743 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
17744 	mp1->b_rptr = rptr;
17745 	mp1->b_wptr = rptr + connp->conn_ht_iphc_len + sack_opt_len;
17746 	bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
17747 	tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
17748 	tcpha->tha_seq = htonl(seq);
17749 
17750 	/*
17751 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
17752 	 * that this function was called from tcp_wput_data. Thus, when called
17753 	 * to retransmit data the setting of the PUSH bit may appear some
17754 	 * what random in that it might get set when it should not. This
17755 	 * should not pose any performance issues.
17756 	 */
17757 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
17758 	    tcp->tcp_unsent == data_length)) {
17759 		flags = TH_ACK | TH_PUSH;
17760 	} else {
17761 		flags = TH_ACK;
17762 	}
17763 
17764 	if (tcp->tcp_ecn_ok) {
17765 		if (tcp->tcp_ecn_echo_on)
17766 			flags |= TH_ECE;
17767 
17768 		/*
17769 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
17770 		 * There is no TCP flow control for non-data segments, and
17771 		 * only data segment is transmitted reliably.
17772 		 */
17773 		if (data_length > 0 && !rexmit) {
17774 			SET_ECT(tcp, rptr);
17775 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17776 				flags |= TH_CWR;
17777 				tcp->tcp_ecn_cwr_sent = B_TRUE;
17778 			}
17779 		}
17780 	}
17781 
17782 	if (tcp->tcp_valid_bits) {
17783 		uint32_t u1;
17784 
17785 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
17786 		    seq == tcp->tcp_iss) {
17787 			uchar_t	*wptr;
17788 
17789 			/*
17790 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
17791 			 * TCP can only be in SYN-SENT, SYN-RCVD or
17792 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
17793 			 * our SYN is not ack'ed but the app closes this
17794 			 * TCP connection.
17795 			 */
17796 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
17797 			    tcp->tcp_state == TCPS_SYN_RCVD ||
17798 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
17799 
17800 			/*
17801 			 * Tack on the MSS option.  It is always needed
17802 			 * for both active and passive open.
17803 			 *
17804 			 * MSS option value should be interface MTU - MIN
17805 			 * TCP/IP header according to RFC 793 as it means
17806 			 * the maximum segment size TCP can receive.  But
17807 			 * to get around some broken middle boxes/end hosts
17808 			 * out there, we allow the option value to be the
17809 			 * same as the MSS option size on the peer side.
17810 			 * In this way, the other side will not send
17811 			 * anything larger than they can receive.
17812 			 *
17813 			 * Note that for SYN_SENT state, the ndd param
17814 			 * tcp_use_smss_as_mss_opt has no effect as we
17815 			 * don't know the peer's MSS option value. So
17816 			 * the only case we need to take care of is in
17817 			 * SYN_RCVD state, which is done later.
17818 			 */
17819 			wptr = mp1->b_wptr;
17820 			wptr[0] = TCPOPT_MAXSEG;
17821 			wptr[1] = TCPOPT_MAXSEG_LEN;
17822 			wptr += 2;
17823 			u1 = tcp->tcp_initial_pmtu -
17824 			    (connp->conn_ipversion == IPV4_VERSION ?
17825 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
17826 			    TCP_MIN_HEADER_LENGTH;
17827 			U16_TO_BE16(u1, wptr);
17828 			mp1->b_wptr = wptr + 2;
17829 			/* Update the offset to cover the additional word */
17830 			tcpha->tha_offset_and_reserved += (1 << 4);
17831 
17832 			/*
17833 			 * Note that the following way of filling in
17834 			 * TCP options are not optimal.  Some NOPs can
17835 			 * be saved.  But there is no need at this time
17836 			 * to optimize it.  When it is needed, we will
17837 			 * do it.
17838 			 */
17839 			switch (tcp->tcp_state) {
17840 			case TCPS_SYN_SENT:
17841 				flags = TH_SYN;
17842 
17843 				if (tcp->tcp_snd_ts_ok) {
17844 					uint32_t llbolt =
17845 					    (uint32_t)LBOLT_FASTPATH;
17846 
17847 					wptr = mp1->b_wptr;
17848 					wptr[0] = TCPOPT_NOP;
17849 					wptr[1] = TCPOPT_NOP;
17850 					wptr[2] = TCPOPT_TSTAMP;
17851 					wptr[3] = TCPOPT_TSTAMP_LEN;
17852 					wptr += 4;
17853 					U32_TO_BE32(llbolt, wptr);
17854 					wptr += 4;
17855 					ASSERT(tcp->tcp_ts_recent == 0);
17856 					U32_TO_BE32(0L, wptr);
17857 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
17858 					tcpha->tha_offset_and_reserved +=
17859 					    (3 << 4);
17860 				}
17861 
17862 				/*
17863 				 * Set up all the bits to tell other side
17864 				 * we are ECN capable.
17865 				 */
17866 				if (tcp->tcp_ecn_ok) {
17867 					flags |= (TH_ECE | TH_CWR);
17868 				}
17869 				break;
17870 			case TCPS_SYN_RCVD:
17871 				flags |= TH_SYN;
17872 
17873 				/*
17874 				 * Reset the MSS option value to be SMSS
17875 				 * We should probably add back the bytes
17876 				 * for timestamp option and IPsec.  We
17877 				 * don't do that as this is a workaround
17878 				 * for broken middle boxes/end hosts, it
17879 				 * is better for us to be more cautious.
17880 				 * They may not take these things into
17881 				 * account in their SMSS calculation.  Thus
17882 				 * the peer's calculated SMSS may be smaller
17883 				 * than what it can be.  This should be OK.
17884 				 */
17885 				if (tcps->tcps_use_smss_as_mss_opt) {
17886 					u1 = tcp->tcp_mss;
17887 					U16_TO_BE16(u1, wptr);
17888 				}
17889 
17890 				/*
17891 				 * If the other side is ECN capable, reply
17892 				 * that we are also ECN capable.
17893 				 */
17894 				if (tcp->tcp_ecn_ok)
17895 					flags |= TH_ECE;
17896 				break;
17897 			default:
17898 				/*
17899 				 * The above ASSERT() makes sure that this
17900 				 * must be FIN-WAIT-1 state.  Our SYN has
17901 				 * not been ack'ed so retransmit it.
17902 				 */
17903 				flags |= TH_SYN;
17904 				break;
17905 			}
17906 
17907 			if (tcp->tcp_snd_ws_ok) {
17908 				wptr = mp1->b_wptr;
17909 				wptr[0] =  TCPOPT_NOP;
17910 				wptr[1] =  TCPOPT_WSCALE;
17911 				wptr[2] =  TCPOPT_WS_LEN;
17912 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
17913 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
17914 				tcpha->tha_offset_and_reserved += (1 << 4);
17915 			}
17916 
17917 			if (tcp->tcp_snd_sack_ok) {
17918 				wptr = mp1->b_wptr;
17919 				wptr[0] = TCPOPT_NOP;
17920 				wptr[1] = TCPOPT_NOP;
17921 				wptr[2] = TCPOPT_SACK_PERMITTED;
17922 				wptr[3] = TCPOPT_SACK_OK_LEN;
17923 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
17924 				tcpha->tha_offset_and_reserved += (1 << 4);
17925 			}
17926 
17927 			/* allocb() of adequate mblk assures space */
17928 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
17929 			    (uintptr_t)INT_MAX);
17930 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
17931 			/*
17932 			 * Get IP set to checksum on our behalf
17933 			 * Include the adjustment for a source route if any.
17934 			 */
17935 			u1 += connp->conn_sum;
17936 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
17937 			tcpha->tha_sum = htons(u1);
17938 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17939 		}
17940 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17941 		    (seq + data_length) == tcp->tcp_fss) {
17942 			if (!tcp->tcp_fin_acked) {
17943 				flags |= TH_FIN;
17944 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17945 			}
17946 			if (!tcp->tcp_fin_sent) {
17947 				tcp->tcp_fin_sent = B_TRUE;
17948 				switch (tcp->tcp_state) {
17949 				case TCPS_SYN_RCVD:
17950 				case TCPS_ESTABLISHED:
17951 					tcp->tcp_state = TCPS_FIN_WAIT_1;
17952 					break;
17953 				case TCPS_CLOSE_WAIT:
17954 					tcp->tcp_state = TCPS_LAST_ACK;
17955 					break;
17956 				}
17957 				if (tcp->tcp_suna == tcp->tcp_snxt)
17958 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17959 				tcp->tcp_snxt = tcp->tcp_fss + 1;
17960 			}
17961 		}
17962 		/*
17963 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
17964 		 * is smaller than seq, u1 will become a very huge value.
17965 		 * So the comparison will fail.  Also note that tcp_urp
17966 		 * should be positive, see RFC 793 page 17.
17967 		 */
17968 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
17969 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
17970 		    u1 < (uint32_t)(64 * 1024)) {
17971 			flags |= TH_URG;
17972 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
17973 			tcpha->tha_urp = htons(u1);
17974 		}
17975 	}
17976 	tcpha->tha_flags = (uchar_t)flags;
17977 	tcp->tcp_rack = tcp->tcp_rnxt;
17978 	tcp->tcp_rack_cnt = 0;
17979 
17980 	if (tcp->tcp_snd_ts_ok) {
17981 		if (tcp->tcp_state != TCPS_SYN_SENT) {
17982 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
17983 
17984 			U32_TO_BE32(llbolt,
17985 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
17986 			U32_TO_BE32(tcp->tcp_ts_recent,
17987 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
17988 		}
17989 	}
17990 
17991 	if (num_sack_blk > 0) {
17992 		uchar_t *wptr = (uchar_t *)tcpha + connp->conn_ht_ulp_len;
17993 		sack_blk_t *tmp;
17994 		int32_t	i;
17995 
17996 		wptr[0] = TCPOPT_NOP;
17997 		wptr[1] = TCPOPT_NOP;
17998 		wptr[2] = TCPOPT_SACK;
17999 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
18000 		    sizeof (sack_blk_t);
18001 		wptr += TCPOPT_REAL_SACK_LEN;
18002 
18003 		tmp = tcp->tcp_sack_list;
18004 		for (i = 0; i < num_sack_blk; i++) {
18005 			U32_TO_BE32(tmp[i].begin, wptr);
18006 			wptr += sizeof (tcp_seq);
18007 			U32_TO_BE32(tmp[i].end, wptr);
18008 			wptr += sizeof (tcp_seq);
18009 		}
18010 		tcpha->tha_offset_and_reserved += ((num_sack_blk * 2 + 1) << 4);
18011 	}
18012 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
18013 	data_length += (int)(mp1->b_wptr - rptr);
18014 
18015 	ixa->ixa_pktlen = data_length;
18016 
18017 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
18018 		((ipha_t *)rptr)->ipha_length = htons(data_length);
18019 	} else {
18020 		ip6_t *ip6 = (ip6_t *)rptr;
18021 
18022 		ip6->ip6_plen = htons(data_length - IPV6_HDR_LEN);
18023 	}
18024 
18025 	/*
18026 	 * Prime pump for IP
18027 	 * Include the adjustment for a source route if any.
18028 	 */
18029 	data_length -= ixa->ixa_ip_hdr_length;
18030 	data_length += connp->conn_sum;
18031 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
18032 	tcpha->tha_sum = htons(data_length);
18033 	if (tcp->tcp_ip_forward_progress) {
18034 		tcp->tcp_ip_forward_progress = B_FALSE;
18035 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
18036 	} else {
18037 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
18038 	}
18039 	return (mp1);
18040 }
18041 
18042 /* This function handles the push timeout. */
18043 void
18044 tcp_push_timer(void *arg)
18045 {
18046 	conn_t	*connp = (conn_t *)arg;
18047 	tcp_t *tcp = connp->conn_tcp;
18048 
18049 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
18050 
18051 	ASSERT(tcp->tcp_listener == NULL);
18052 
18053 	ASSERT(!IPCL_IS_NONSTR(connp));
18054 
18055 	tcp->tcp_push_tid = 0;
18056 
18057 	if (tcp->tcp_rcv_list != NULL &&
18058 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
18059 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
18060 }
18061 
18062 /*
18063  * This function handles delayed ACK timeout.
18064  */
18065 static void
18066 tcp_ack_timer(void *arg)
18067 {
18068 	conn_t	*connp = (conn_t *)arg;
18069 	tcp_t *tcp = connp->conn_tcp;
18070 	mblk_t *mp;
18071 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18072 
18073 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
18074 
18075 	tcp->tcp_ack_tid = 0;
18076 
18077 	if (tcp->tcp_fused)
18078 		return;
18079 
18080 	/*
18081 	 * Do not send ACK if there is no outstanding unack'ed data.
18082 	 */
18083 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
18084 		return;
18085 	}
18086 
18087 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
18088 		/*
18089 		 * Make sure we don't allow deferred ACKs to result in
18090 		 * timer-based ACKing.  If we have held off an ACK
18091 		 * when there was more than an mss here, and the timer
18092 		 * goes off, we have to worry about the possibility
18093 		 * that the sender isn't doing slow-start, or is out
18094 		 * of step with us for some other reason.  We fall
18095 		 * permanently back in the direction of
18096 		 * ACK-every-other-packet as suggested in RFC 1122.
18097 		 */
18098 		if (tcp->tcp_rack_abs_max > 2)
18099 			tcp->tcp_rack_abs_max--;
18100 		tcp->tcp_rack_cur_max = 2;
18101 	}
18102 	mp = tcp_ack_mp(tcp);
18103 
18104 	if (mp != NULL) {
18105 		BUMP_LOCAL(tcp->tcp_obsegs);
18106 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
18107 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
18108 		tcp_send_data(tcp, mp);
18109 	}
18110 }
18111 
18112 
18113 /* Generate an ACK-only (no data) segment for a TCP endpoint */
18114 static mblk_t *
18115 tcp_ack_mp(tcp_t *tcp)
18116 {
18117 	uint32_t	seq_no;
18118 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18119 	conn_t		*connp = tcp->tcp_connp;
18120 
18121 	/*
18122 	 * There are a few cases to be considered while setting the sequence no.
18123 	 * Essentially, we can come here while processing an unacceptable pkt
18124 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
18125 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
18126 	 * If we are here for a zero window probe, stick with suna. In all
18127 	 * other cases, we check if suna + swnd encompasses snxt and set
18128 	 * the sequence number to snxt, if so. If snxt falls outside the
18129 	 * window (the receiver probably shrunk its window), we will go with
18130 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
18131 	 * receiver.
18132 	 */
18133 	if (tcp->tcp_zero_win_probe) {
18134 		seq_no = tcp->tcp_suna;
18135 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
18136 		ASSERT(tcp->tcp_swnd == 0);
18137 		seq_no = tcp->tcp_snxt;
18138 	} else {
18139 		seq_no = SEQ_GT(tcp->tcp_snxt,
18140 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
18141 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
18142 	}
18143 
18144 	if (tcp->tcp_valid_bits) {
18145 		/*
18146 		 * For the complex case where we have to send some
18147 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
18148 		 */
18149 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
18150 		    NULL, B_FALSE));
18151 	} else {
18152 		/* Generate a simple ACK */
18153 		int	data_length;
18154 		uchar_t	*rptr;
18155 		tcpha_t	*tcpha;
18156 		mblk_t	*mp1;
18157 		int32_t	total_hdr_len;
18158 		int32_t	tcp_hdr_len;
18159 		int32_t	num_sack_blk = 0;
18160 		int32_t sack_opt_len;
18161 		ip_xmit_attr_t *ixa = connp->conn_ixa;
18162 
18163 		/*
18164 		 * Allocate space for TCP + IP headers
18165 		 * and link-level header
18166 		 */
18167 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18168 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18169 			    tcp->tcp_num_sack_blk);
18170 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
18171 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
18172 			total_hdr_len = connp->conn_ht_iphc_len + sack_opt_len;
18173 			tcp_hdr_len = connp->conn_ht_ulp_len + sack_opt_len;
18174 		} else {
18175 			total_hdr_len = connp->conn_ht_iphc_len;
18176 			tcp_hdr_len = connp->conn_ht_ulp_len;
18177 		}
18178 		mp1 = allocb(total_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
18179 		if (!mp1)
18180 			return (NULL);
18181 
18182 		/* Update the latest receive window size in TCP header. */
18183 		tcp->tcp_tcpha->tha_win =
18184 		    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
18185 		/* copy in prototype TCP + IP header */
18186 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
18187 		mp1->b_rptr = rptr;
18188 		mp1->b_wptr = rptr + total_hdr_len;
18189 		bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
18190 
18191 		tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
18192 
18193 		/* Set the TCP sequence number. */
18194 		tcpha->tha_seq = htonl(seq_no);
18195 
18196 		/* Set up the TCP flag field. */
18197 		tcpha->tha_flags = (uchar_t)TH_ACK;
18198 		if (tcp->tcp_ecn_echo_on)
18199 			tcpha->tha_flags |= TH_ECE;
18200 
18201 		tcp->tcp_rack = tcp->tcp_rnxt;
18202 		tcp->tcp_rack_cnt = 0;
18203 
18204 		/* fill in timestamp option if in use */
18205 		if (tcp->tcp_snd_ts_ok) {
18206 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
18207 
18208 			U32_TO_BE32(llbolt,
18209 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
18210 			U32_TO_BE32(tcp->tcp_ts_recent,
18211 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
18212 		}
18213 
18214 		/* Fill in SACK options */
18215 		if (num_sack_blk > 0) {
18216 			uchar_t *wptr = (uchar_t *)tcpha +
18217 			    connp->conn_ht_ulp_len;
18218 			sack_blk_t *tmp;
18219 			int32_t	i;
18220 
18221 			wptr[0] = TCPOPT_NOP;
18222 			wptr[1] = TCPOPT_NOP;
18223 			wptr[2] = TCPOPT_SACK;
18224 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
18225 			    sizeof (sack_blk_t);
18226 			wptr += TCPOPT_REAL_SACK_LEN;
18227 
18228 			tmp = tcp->tcp_sack_list;
18229 			for (i = 0; i < num_sack_blk; i++) {
18230 				U32_TO_BE32(tmp[i].begin, wptr);
18231 				wptr += sizeof (tcp_seq);
18232 				U32_TO_BE32(tmp[i].end, wptr);
18233 				wptr += sizeof (tcp_seq);
18234 			}
18235 			tcpha->tha_offset_and_reserved +=
18236 			    ((num_sack_blk * 2 + 1) << 4);
18237 		}
18238 
18239 		ixa->ixa_pktlen = total_hdr_len;
18240 
18241 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
18242 			((ipha_t *)rptr)->ipha_length = htons(total_hdr_len);
18243 		} else {
18244 			ip6_t *ip6 = (ip6_t *)rptr;
18245 
18246 			ip6->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
18247 		}
18248 
18249 		/*
18250 		 * Prime pump for checksum calculation in IP.  Include the
18251 		 * adjustment for a source route if any.
18252 		 */
18253 		data_length = tcp_hdr_len + connp->conn_sum;
18254 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
18255 		tcpha->tha_sum = htons(data_length);
18256 
18257 		if (tcp->tcp_ip_forward_progress) {
18258 			tcp->tcp_ip_forward_progress = B_FALSE;
18259 			connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
18260 		} else {
18261 			connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
18262 		}
18263 		return (mp1);
18264 	}
18265 }
18266 
18267 /*
18268  * Hash list insertion routine for tcp_t structures. Each hash bucket
18269  * contains a list of tcp_t entries, and each entry is bound to a unique
18270  * port. If there are multiple tcp_t's that are bound to the same port, then
18271  * one of them will be linked into the hash bucket list, and the rest will
18272  * hang off of that one entry. For each port, entries bound to a specific IP
18273  * address will be inserted before those those bound to INADDR_ANY.
18274  */
18275 static void
18276 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
18277 {
18278 	tcp_t	**tcpp;
18279 	tcp_t	*tcpnext;
18280 	tcp_t	*tcphash;
18281 	conn_t	*connp = tcp->tcp_connp;
18282 	conn_t	*connext;
18283 
18284 	if (tcp->tcp_ptpbhn != NULL) {
18285 		ASSERT(!caller_holds_lock);
18286 		tcp_bind_hash_remove(tcp);
18287 	}
18288 	tcpp = &tbf->tf_tcp;
18289 	if (!caller_holds_lock) {
18290 		mutex_enter(&tbf->tf_lock);
18291 	} else {
18292 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
18293 	}
18294 	tcphash = tcpp[0];
18295 	tcpnext = NULL;
18296 	if (tcphash != NULL) {
18297 		/* Look for an entry using the same port */
18298 		while ((tcphash = tcpp[0]) != NULL &&
18299 		    connp->conn_lport != tcphash->tcp_connp->conn_lport)
18300 			tcpp = &(tcphash->tcp_bind_hash);
18301 
18302 		/* The port was not found, just add to the end */
18303 		if (tcphash == NULL)
18304 			goto insert;
18305 
18306 		/*
18307 		 * OK, there already exists an entry bound to the
18308 		 * same port.
18309 		 *
18310 		 * If the new tcp bound to the INADDR_ANY address
18311 		 * and the first one in the list is not bound to
18312 		 * INADDR_ANY we skip all entries until we find the
18313 		 * first one bound to INADDR_ANY.
18314 		 * This makes sure that applications binding to a
18315 		 * specific address get preference over those binding to
18316 		 * INADDR_ANY.
18317 		 */
18318 		tcpnext = tcphash;
18319 		connext = tcpnext->tcp_connp;
18320 		tcphash = NULL;
18321 		if (V6_OR_V4_INADDR_ANY(connp->conn_bound_addr_v6) &&
18322 		    !V6_OR_V4_INADDR_ANY(connext->conn_bound_addr_v6)) {
18323 			while ((tcpnext = tcpp[0]) != NULL) {
18324 				connext = tcpnext->tcp_connp;
18325 				if (!V6_OR_V4_INADDR_ANY(
18326 				    connext->conn_bound_addr_v6))
18327 					tcpp = &(tcpnext->tcp_bind_hash_port);
18328 				else
18329 					break;
18330 			}
18331 			if (tcpnext != NULL) {
18332 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
18333 				tcphash = tcpnext->tcp_bind_hash;
18334 				if (tcphash != NULL) {
18335 					tcphash->tcp_ptpbhn =
18336 					    &(tcp->tcp_bind_hash);
18337 					tcpnext->tcp_bind_hash = NULL;
18338 				}
18339 			}
18340 		} else {
18341 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
18342 			tcphash = tcpnext->tcp_bind_hash;
18343 			if (tcphash != NULL) {
18344 				tcphash->tcp_ptpbhn =
18345 				    &(tcp->tcp_bind_hash);
18346 				tcpnext->tcp_bind_hash = NULL;
18347 			}
18348 		}
18349 	}
18350 insert:
18351 	tcp->tcp_bind_hash_port = tcpnext;
18352 	tcp->tcp_bind_hash = tcphash;
18353 	tcp->tcp_ptpbhn = tcpp;
18354 	tcpp[0] = tcp;
18355 	if (!caller_holds_lock)
18356 		mutex_exit(&tbf->tf_lock);
18357 }
18358 
18359 /*
18360  * Hash list removal routine for tcp_t structures.
18361  */
18362 static void
18363 tcp_bind_hash_remove(tcp_t *tcp)
18364 {
18365 	tcp_t	*tcpnext;
18366 	kmutex_t *lockp;
18367 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18368 	conn_t		*connp = tcp->tcp_connp;
18369 
18370 	if (tcp->tcp_ptpbhn == NULL)
18371 		return;
18372 
18373 	/*
18374 	 * Extract the lock pointer in case there are concurrent
18375 	 * hash_remove's for this instance.
18376 	 */
18377 	ASSERT(connp->conn_lport != 0);
18378 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(
18379 	    connp->conn_lport)].tf_lock;
18380 
18381 	ASSERT(lockp != NULL);
18382 	mutex_enter(lockp);
18383 	if (tcp->tcp_ptpbhn) {
18384 		tcpnext = tcp->tcp_bind_hash_port;
18385 		if (tcpnext != NULL) {
18386 			tcp->tcp_bind_hash_port = NULL;
18387 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
18388 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
18389 			if (tcpnext->tcp_bind_hash != NULL) {
18390 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
18391 				    &(tcpnext->tcp_bind_hash);
18392 				tcp->tcp_bind_hash = NULL;
18393 			}
18394 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
18395 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
18396 			tcp->tcp_bind_hash = NULL;
18397 		}
18398 		*tcp->tcp_ptpbhn = tcpnext;
18399 		tcp->tcp_ptpbhn = NULL;
18400 	}
18401 	mutex_exit(lockp);
18402 }
18403 
18404 
18405 /*
18406  * Hash list lookup routine for tcp_t structures.
18407  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
18408  */
18409 static tcp_t *
18410 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
18411 {
18412 	tf_t	*tf;
18413 	tcp_t	*tcp;
18414 
18415 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
18416 	mutex_enter(&tf->tf_lock);
18417 	for (tcp = tf->tf_tcp; tcp != NULL;
18418 	    tcp = tcp->tcp_acceptor_hash) {
18419 		if (tcp->tcp_acceptor_id == id) {
18420 			CONN_INC_REF(tcp->tcp_connp);
18421 			mutex_exit(&tf->tf_lock);
18422 			return (tcp);
18423 		}
18424 	}
18425 	mutex_exit(&tf->tf_lock);
18426 	return (NULL);
18427 }
18428 
18429 
18430 /*
18431  * Hash list insertion routine for tcp_t structures.
18432  */
18433 void
18434 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
18435 {
18436 	tf_t	*tf;
18437 	tcp_t	**tcpp;
18438 	tcp_t	*tcpnext;
18439 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18440 
18441 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
18442 
18443 	if (tcp->tcp_ptpahn != NULL)
18444 		tcp_acceptor_hash_remove(tcp);
18445 	tcpp = &tf->tf_tcp;
18446 	mutex_enter(&tf->tf_lock);
18447 	tcpnext = tcpp[0];
18448 	if (tcpnext)
18449 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
18450 	tcp->tcp_acceptor_hash = tcpnext;
18451 	tcp->tcp_ptpahn = tcpp;
18452 	tcpp[0] = tcp;
18453 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
18454 	mutex_exit(&tf->tf_lock);
18455 }
18456 
18457 /*
18458  * Hash list removal routine for tcp_t structures.
18459  */
18460 static void
18461 tcp_acceptor_hash_remove(tcp_t *tcp)
18462 {
18463 	tcp_t	*tcpnext;
18464 	kmutex_t *lockp;
18465 
18466 	/*
18467 	 * Extract the lock pointer in case there are concurrent
18468 	 * hash_remove's for this instance.
18469 	 */
18470 	lockp = tcp->tcp_acceptor_lockp;
18471 
18472 	if (tcp->tcp_ptpahn == NULL)
18473 		return;
18474 
18475 	ASSERT(lockp != NULL);
18476 	mutex_enter(lockp);
18477 	if (tcp->tcp_ptpahn) {
18478 		tcpnext = tcp->tcp_acceptor_hash;
18479 		if (tcpnext) {
18480 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
18481 			tcp->tcp_acceptor_hash = NULL;
18482 		}
18483 		*tcp->tcp_ptpahn = tcpnext;
18484 		tcp->tcp_ptpahn = NULL;
18485 	}
18486 	mutex_exit(lockp);
18487 	tcp->tcp_acceptor_lockp = NULL;
18488 }
18489 
18490 /*
18491  * Type three generator adapted from the random() function in 4.4 BSD:
18492  */
18493 
18494 /*
18495  * Copyright (c) 1983, 1993
18496  *	The Regents of the University of California.  All rights reserved.
18497  *
18498  * Redistribution and use in source and binary forms, with or without
18499  * modification, are permitted provided that the following conditions
18500  * are met:
18501  * 1. Redistributions of source code must retain the above copyright
18502  *    notice, this list of conditions and the following disclaimer.
18503  * 2. Redistributions in binary form must reproduce the above copyright
18504  *    notice, this list of conditions and the following disclaimer in the
18505  *    documentation and/or other materials provided with the distribution.
18506  * 3. All advertising materials mentioning features or use of this software
18507  *    must display the following acknowledgement:
18508  *	This product includes software developed by the University of
18509  *	California, Berkeley and its contributors.
18510  * 4. Neither the name of the University nor the names of its contributors
18511  *    may be used to endorse or promote products derived from this software
18512  *    without specific prior written permission.
18513  *
18514  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18515  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18516  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18517  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18518  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18519  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
18520  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
18521  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
18522  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
18523  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
18524  * SUCH DAMAGE.
18525  */
18526 
18527 /* Type 3 -- x**31 + x**3 + 1 */
18528 #define	DEG_3		31
18529 #define	SEP_3		3
18530 
18531 
18532 /* Protected by tcp_random_lock */
18533 static int tcp_randtbl[DEG_3 + 1];
18534 
18535 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
18536 static int *tcp_random_rptr = &tcp_randtbl[1];
18537 
18538 static int *tcp_random_state = &tcp_randtbl[1];
18539 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
18540 
18541 kmutex_t tcp_random_lock;
18542 
18543 void
18544 tcp_random_init(void)
18545 {
18546 	int i;
18547 	hrtime_t hrt;
18548 	time_t wallclock;
18549 	uint64_t result;
18550 
18551 	/*
18552 	 * Use high-res timer and current time for seed.  Gethrtime() returns
18553 	 * a longlong, which may contain resolution down to nanoseconds.
18554 	 * The current time will either be a 32-bit or a 64-bit quantity.
18555 	 * XOR the two together in a 64-bit result variable.
18556 	 * Convert the result to a 32-bit value by multiplying the high-order
18557 	 * 32-bits by the low-order 32-bits.
18558 	 */
18559 
18560 	hrt = gethrtime();
18561 	(void) drv_getparm(TIME, &wallclock);
18562 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
18563 	mutex_enter(&tcp_random_lock);
18564 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
18565 	    (result & 0xffffffff);
18566 
18567 	for (i = 1; i < DEG_3; i++)
18568 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
18569 		    + 12345;
18570 	tcp_random_fptr = &tcp_random_state[SEP_3];
18571 	tcp_random_rptr = &tcp_random_state[0];
18572 	mutex_exit(&tcp_random_lock);
18573 	for (i = 0; i < 10 * DEG_3; i++)
18574 		(void) tcp_random();
18575 }
18576 
18577 /*
18578  * tcp_random: Return a random number in the range [1 - (128K + 1)].
18579  * This range is selected to be approximately centered on TCP_ISS / 2,
18580  * and easy to compute. We get this value by generating a 32-bit random
18581  * number, selecting out the high-order 17 bits, and then adding one so
18582  * that we never return zero.
18583  */
18584 int
18585 tcp_random(void)
18586 {
18587 	int i;
18588 
18589 	mutex_enter(&tcp_random_lock);
18590 	*tcp_random_fptr += *tcp_random_rptr;
18591 
18592 	/*
18593 	 * The high-order bits are more random than the low-order bits,
18594 	 * so we select out the high-order 17 bits and add one so that
18595 	 * we never return zero.
18596 	 */
18597 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
18598 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
18599 		tcp_random_fptr = tcp_random_state;
18600 		++tcp_random_rptr;
18601 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
18602 		tcp_random_rptr = tcp_random_state;
18603 
18604 	mutex_exit(&tcp_random_lock);
18605 	return (i);
18606 }
18607 
18608 static int
18609 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
18610     int *t_errorp, int *sys_errorp)
18611 {
18612 	int error;
18613 	int is_absreq_failure;
18614 	t_scalar_t *opt_lenp;
18615 	t_scalar_t opt_offset;
18616 	int prim_type;
18617 	struct T_conn_req *tcreqp;
18618 	struct T_conn_res *tcresp;
18619 	cred_t *cr;
18620 
18621 	/*
18622 	 * All Solaris components should pass a db_credp
18623 	 * for this TPI message, hence we ASSERT.
18624 	 * But in case there is some other M_PROTO that looks
18625 	 * like a TPI message sent by some other kernel
18626 	 * component, we check and return an error.
18627 	 */
18628 	cr = msg_getcred(mp, NULL);
18629 	ASSERT(cr != NULL);
18630 	if (cr == NULL)
18631 		return (-1);
18632 
18633 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
18634 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
18635 	    prim_type == T_CONN_RES);
18636 
18637 	switch (prim_type) {
18638 	case T_CONN_REQ:
18639 		tcreqp = (struct T_conn_req *)mp->b_rptr;
18640 		opt_offset = tcreqp->OPT_offset;
18641 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
18642 		break;
18643 	case O_T_CONN_RES:
18644 	case T_CONN_RES:
18645 		tcresp = (struct T_conn_res *)mp->b_rptr;
18646 		opt_offset = tcresp->OPT_offset;
18647 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
18648 		break;
18649 	}
18650 
18651 	*t_errorp = 0;
18652 	*sys_errorp = 0;
18653 	*do_disconnectp = 0;
18654 
18655 	error = tpi_optcom_buf(tcp->tcp_connp->conn_wq, mp, opt_lenp,
18656 	    opt_offset, cr, &tcp_opt_obj,
18657 	    NULL, &is_absreq_failure);
18658 
18659 	switch (error) {
18660 	case  0:		/* no error */
18661 		ASSERT(is_absreq_failure == 0);
18662 		return (0);
18663 	case ENOPROTOOPT:
18664 		*t_errorp = TBADOPT;
18665 		break;
18666 	case EACCES:
18667 		*t_errorp = TACCES;
18668 		break;
18669 	default:
18670 		*t_errorp = TSYSERR; *sys_errorp = error;
18671 		break;
18672 	}
18673 	if (is_absreq_failure != 0) {
18674 		/*
18675 		 * The connection request should get the local ack
18676 		 * T_OK_ACK and then a T_DISCON_IND.
18677 		 */
18678 		*do_disconnectp = 1;
18679 	}
18680 	return (-1);
18681 }
18682 
18683 /*
18684  * Split this function out so that if the secret changes, I'm okay.
18685  *
18686  * Initialize the tcp_iss_cookie and tcp_iss_key.
18687  */
18688 
18689 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
18690 
18691 static void
18692 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
18693 {
18694 	struct {
18695 		int32_t current_time;
18696 		uint32_t randnum;
18697 		uint16_t pad;
18698 		uint8_t ether[6];
18699 		uint8_t passwd[PASSWD_SIZE];
18700 	} tcp_iss_cookie;
18701 	time_t t;
18702 
18703 	/*
18704 	 * Start with the current absolute time.
18705 	 */
18706 	(void) drv_getparm(TIME, &t);
18707 	tcp_iss_cookie.current_time = t;
18708 
18709 	/*
18710 	 * XXX - Need a more random number per RFC 1750, not this crap.
18711 	 * OTOH, if what follows is pretty random, then I'm in better shape.
18712 	 */
18713 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
18714 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
18715 
18716 	/*
18717 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
18718 	 * as a good template.
18719 	 */
18720 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
18721 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
18722 
18723 	/*
18724 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
18725 	 */
18726 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
18727 
18728 	/*
18729 	 * See 4010593 if this section becomes a problem again,
18730 	 * but the local ethernet address is useful here.
18731 	 */
18732 	(void) localetheraddr(NULL,
18733 	    (struct ether_addr *)&tcp_iss_cookie.ether);
18734 
18735 	/*
18736 	 * Hash 'em all together.  The MD5Final is called per-connection.
18737 	 */
18738 	mutex_enter(&tcps->tcps_iss_key_lock);
18739 	MD5Init(&tcps->tcps_iss_key);
18740 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
18741 	    sizeof (tcp_iss_cookie));
18742 	mutex_exit(&tcps->tcps_iss_key_lock);
18743 }
18744 
18745 /*
18746  * Set the RFC 1948 pass phrase
18747  */
18748 /* ARGSUSED */
18749 static int
18750 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
18751     cred_t *cr)
18752 {
18753 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18754 
18755 	/*
18756 	 * Basically, value contains a new pass phrase.  Pass it along!
18757 	 */
18758 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
18759 	return (0);
18760 }
18761 
18762 /* ARGSUSED */
18763 static int
18764 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
18765 {
18766 	bzero(buf, sizeof (tcp_sack_info_t));
18767 	return (0);
18768 }
18769 
18770 /*
18771  * Called by IP when IP is loaded into the kernel
18772  */
18773 void
18774 tcp_ddi_g_init(void)
18775 {
18776 	tcp_timercache = kmem_cache_create("tcp_timercache",
18777 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
18778 	    NULL, NULL, NULL, NULL, NULL, 0);
18779 
18780 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
18781 	    sizeof (tcp_sack_info_t), 0,
18782 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
18783 
18784 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
18785 
18786 	/* Initialize the random number generator */
18787 	tcp_random_init();
18788 
18789 	/* A single callback independently of how many netstacks we have */
18790 	ip_squeue_init(tcp_squeue_add);
18791 
18792 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
18793 
18794 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
18795 
18796 	/*
18797 	 * We want to be informed each time a stack is created or
18798 	 * destroyed in the kernel, so we can maintain the
18799 	 * set of tcp_stack_t's.
18800 	 */
18801 	netstack_register(NS_TCP, tcp_stack_init, NULL, tcp_stack_fini);
18802 }
18803 
18804 
18805 #define	INET_NAME	"ip"
18806 
18807 /*
18808  * Initialize the TCP stack instance.
18809  */
18810 static void *
18811 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
18812 {
18813 	tcp_stack_t	*tcps;
18814 	tcpparam_t	*pa;
18815 	int		i;
18816 	int		error = 0;
18817 	major_t		major;
18818 
18819 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
18820 	tcps->tcps_netstack = ns;
18821 
18822 	/* Initialize locks */
18823 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
18824 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
18825 
18826 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
18827 	tcps->tcps_g_epriv_ports[0] = 2049;
18828 	tcps->tcps_g_epriv_ports[1] = 4045;
18829 	tcps->tcps_min_anonpriv_port = 512;
18830 
18831 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
18832 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
18833 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
18834 	    TCP_ACCEPTOR_FANOUT_SIZE, KM_SLEEP);
18835 
18836 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
18837 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
18838 		    MUTEX_DEFAULT, NULL);
18839 	}
18840 
18841 	for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
18842 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
18843 		    MUTEX_DEFAULT, NULL);
18844 	}
18845 
18846 	/* TCP's IPsec code calls the packet dropper. */
18847 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
18848 
18849 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
18850 	tcps->tcps_params = pa;
18851 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
18852 
18853 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
18854 	    A_CNT(lcl_tcp_param_arr), tcps);
18855 
18856 	/*
18857 	 * Note: To really walk the device tree you need the devinfo
18858 	 * pointer to your device which is only available after probe/attach.
18859 	 * The following is safe only because it uses ddi_root_node()
18860 	 */
18861 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
18862 	    tcp_opt_obj.odb_opt_arr_cnt);
18863 
18864 	/*
18865 	 * Initialize RFC 1948 secret values.  This will probably be reset once
18866 	 * by the boot scripts.
18867 	 *
18868 	 * Use NULL name, as the name is caught by the new lockstats.
18869 	 *
18870 	 * Initialize with some random, non-guessable string, like the global
18871 	 * T_INFO_ACK.
18872 	 */
18873 
18874 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
18875 	    sizeof (tcp_g_t_info_ack), tcps);
18876 
18877 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
18878 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
18879 
18880 	major = mod_name_to_major(INET_NAME);
18881 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
18882 	ASSERT(error == 0);
18883 	tcps->tcps_ixa_cleanup_mp = allocb_wait(0, BPRI_MED, STR_NOSIG, NULL);
18884 	ASSERT(tcps->tcps_ixa_cleanup_mp != NULL);
18885 	cv_init(&tcps->tcps_ixa_cleanup_cv, NULL, CV_DEFAULT, NULL);
18886 	mutex_init(&tcps->tcps_ixa_cleanup_lock, NULL, MUTEX_DEFAULT, NULL);
18887 
18888 	mutex_init(&tcps->tcps_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
18889 	tcps->tcps_reclaim = B_FALSE;
18890 	tcps->tcps_reclaim_tid = 0;
18891 	tcps->tcps_reclaim_period = tcps->tcps_rexmit_interval_max * 3;
18892 
18893 	mutex_init(&tcps->tcps_listener_conf_lock, NULL, MUTEX_DEFAULT, NULL);
18894 	list_create(&tcps->tcps_listener_conf, sizeof (tcp_listener_t),
18895 	    offsetof(tcp_listener_t, tl_link));
18896 
18897 	return (tcps);
18898 }
18899 
18900 /*
18901  * Called when the IP module is about to be unloaded.
18902  */
18903 void
18904 tcp_ddi_g_destroy(void)
18905 {
18906 	tcp_g_kstat_fini(tcp_g_kstat);
18907 	tcp_g_kstat = NULL;
18908 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
18909 
18910 	mutex_destroy(&tcp_random_lock);
18911 
18912 	kmem_cache_destroy(tcp_timercache);
18913 	kmem_cache_destroy(tcp_sack_info_cache);
18914 
18915 	netstack_unregister(NS_TCP);
18916 }
18917 
18918 /*
18919  * Free the TCP stack instance.
18920  */
18921 static void
18922 tcp_stack_fini(netstackid_t stackid, void *arg)
18923 {
18924 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
18925 	int i;
18926 
18927 	freeb(tcps->tcps_ixa_cleanup_mp);
18928 	tcps->tcps_ixa_cleanup_mp = NULL;
18929 	cv_destroy(&tcps->tcps_ixa_cleanup_cv);
18930 	mutex_destroy(&tcps->tcps_ixa_cleanup_lock);
18931 
18932 	if (tcps->tcps_reclaim_tid != 0)
18933 		(void) untimeout(tcps->tcps_reclaim_tid);
18934 	mutex_destroy(&tcps->tcps_reclaim_lock);
18935 
18936 	tcp_listener_conf_cleanup(tcps);
18937 
18938 	nd_free(&tcps->tcps_g_nd);
18939 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
18940 	tcps->tcps_params = NULL;
18941 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
18942 	tcps->tcps_wroff_xtra_param = NULL;
18943 
18944 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
18945 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
18946 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
18947 	}
18948 
18949 	for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
18950 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
18951 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
18952 	}
18953 
18954 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
18955 	tcps->tcps_bind_fanout = NULL;
18956 
18957 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) *
18958 	    TCP_ACCEPTOR_FANOUT_SIZE);
18959 	tcps->tcps_acceptor_fanout = NULL;
18960 
18961 	mutex_destroy(&tcps->tcps_iss_key_lock);
18962 	mutex_destroy(&tcps->tcps_epriv_port_lock);
18963 
18964 	ip_drop_unregister(&tcps->tcps_dropper);
18965 
18966 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
18967 	tcps->tcps_kstat = NULL;
18968 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
18969 
18970 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
18971 	tcps->tcps_mibkp = NULL;
18972 
18973 	ldi_ident_release(tcps->tcps_ldi_ident);
18974 	kmem_free(tcps, sizeof (*tcps));
18975 }
18976 
18977 /*
18978  * Generate ISS, taking into account NDD changes may happen halfway through.
18979  * (If the iss is not zero, set it.)
18980  */
18981 
18982 static void
18983 tcp_iss_init(tcp_t *tcp)
18984 {
18985 	MD5_CTX context;
18986 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
18987 	uint32_t answer[4];
18988 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18989 	conn_t		*connp = tcp->tcp_connp;
18990 
18991 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
18992 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
18993 	switch (tcps->tcps_strong_iss) {
18994 	case 2:
18995 		mutex_enter(&tcps->tcps_iss_key_lock);
18996 		context = tcps->tcps_iss_key;
18997 		mutex_exit(&tcps->tcps_iss_key_lock);
18998 		arg.ports = connp->conn_ports;
18999 		arg.src = connp->conn_laddr_v6;
19000 		arg.dst = connp->conn_faddr_v6;
19001 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
19002 		MD5Final((uchar_t *)answer, &context);
19003 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
19004 		/*
19005 		 * Now that we've hashed into a unique per-connection sequence
19006 		 * space, add a random increment per strong_iss == 1.  So I
19007 		 * guess we'll have to...
19008 		 */
19009 		/* FALLTHRU */
19010 	case 1:
19011 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
19012 		break;
19013 	default:
19014 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
19015 		break;
19016 	}
19017 	tcp->tcp_valid_bits = TCP_ISS_VALID;
19018 	tcp->tcp_fss = tcp->tcp_iss - 1;
19019 	tcp->tcp_suna = tcp->tcp_iss;
19020 	tcp->tcp_snxt = tcp->tcp_iss + 1;
19021 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
19022 	tcp->tcp_csuna = tcp->tcp_snxt;
19023 }
19024 
19025 /*
19026  * Exported routine for extracting active tcp connection status.
19027  *
19028  * This is used by the Solaris Cluster Networking software to
19029  * gather a list of connections that need to be forwarded to
19030  * specific nodes in the cluster when configuration changes occur.
19031  *
19032  * The callback is invoked for each tcp_t structure from all netstacks,
19033  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
19034  * from the netstack with the specified stack_id. Returning
19035  * non-zero from the callback routine terminates the search.
19036  */
19037 int
19038 cl_tcp_walk_list(netstackid_t stack_id,
19039     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
19040 {
19041 	netstack_handle_t nh;
19042 	netstack_t *ns;
19043 	int ret = 0;
19044 
19045 	if (stack_id >= 0) {
19046 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
19047 			return (EINVAL);
19048 
19049 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
19050 		    ns->netstack_tcp);
19051 		netstack_rele(ns);
19052 		return (ret);
19053 	}
19054 
19055 	netstack_next_init(&nh);
19056 	while ((ns = netstack_next(&nh)) != NULL) {
19057 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
19058 		    ns->netstack_tcp);
19059 		netstack_rele(ns);
19060 	}
19061 	netstack_next_fini(&nh);
19062 	return (ret);
19063 }
19064 
19065 static int
19066 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
19067     tcp_stack_t *tcps)
19068 {
19069 	tcp_t *tcp;
19070 	cl_tcp_info_t	cl_tcpi;
19071 	connf_t	*connfp;
19072 	conn_t	*connp;
19073 	int	i;
19074 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19075 
19076 	ASSERT(callback != NULL);
19077 
19078 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
19079 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
19080 		connp = NULL;
19081 
19082 		while ((connp =
19083 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
19084 
19085 			tcp = connp->conn_tcp;
19086 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
19087 			cl_tcpi.cl_tcpi_ipversion = connp->conn_ipversion;
19088 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
19089 			cl_tcpi.cl_tcpi_lport = connp->conn_lport;
19090 			cl_tcpi.cl_tcpi_fport = connp->conn_fport;
19091 			cl_tcpi.cl_tcpi_laddr_v6 = connp->conn_laddr_v6;
19092 			cl_tcpi.cl_tcpi_faddr_v6 = connp->conn_faddr_v6;
19093 
19094 			/*
19095 			 * If the callback returns non-zero
19096 			 * we terminate the traversal.
19097 			 */
19098 			if ((*callback)(&cl_tcpi, arg) != 0) {
19099 				CONN_DEC_REF(tcp->tcp_connp);
19100 				return (1);
19101 			}
19102 		}
19103 	}
19104 
19105 	return (0);
19106 }
19107 
19108 /*
19109  * Macros used for accessing the different types of sockaddr
19110  * structures inside a tcp_ioc_abort_conn_t.
19111  */
19112 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
19113 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
19114 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
19115 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
19116 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
19117 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
19118 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
19119 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
19120 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
19121 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
19122 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
19123 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
19124 
19125 /*
19126  * Return the correct error code to mimic the behavior
19127  * of a connection reset.
19128  */
19129 #define	TCP_AC_GET_ERRCODE(state, err) {	\
19130 		switch ((state)) {		\
19131 		case TCPS_SYN_SENT:		\
19132 		case TCPS_SYN_RCVD:		\
19133 			(err) = ECONNREFUSED;	\
19134 			break;			\
19135 		case TCPS_ESTABLISHED:		\
19136 		case TCPS_FIN_WAIT_1:		\
19137 		case TCPS_FIN_WAIT_2:		\
19138 		case TCPS_CLOSE_WAIT:		\
19139 			(err) = ECONNRESET;	\
19140 			break;			\
19141 		case TCPS_CLOSING:		\
19142 		case TCPS_LAST_ACK:		\
19143 		case TCPS_TIME_WAIT:		\
19144 			(err) = 0;		\
19145 			break;			\
19146 		default:			\
19147 			(err) = ENXIO;		\
19148 		}				\
19149 	}
19150 
19151 /*
19152  * Check if a tcp structure matches the info in acp.
19153  */
19154 #define	TCP_AC_ADDR_MATCH(acp, connp, tcp)			\
19155 	(((acp)->ac_local.ss_family == AF_INET) ?		\
19156 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
19157 	TCP_AC_V4LOCAL((acp)) == (connp)->conn_laddr_v4) &&	\
19158 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
19159 	TCP_AC_V4REMOTE((acp)) == (connp)->conn_faddr_v4) &&	\
19160 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
19161 	TCP_AC_V4LPORT((acp)) == (connp)->conn_lport) &&	\
19162 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
19163 	TCP_AC_V4RPORT((acp)) == (connp)->conn_fport) &&	\
19164 	(acp)->ac_start <= (tcp)->tcp_state &&			\
19165 	(acp)->ac_end >= (tcp)->tcp_state) :			\
19166 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
19167 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
19168 	&(connp)->conn_laddr_v6)) &&				\
19169 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
19170 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
19171 	&(connp)->conn_faddr_v6)) &&				\
19172 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
19173 	TCP_AC_V6LPORT((acp)) == (connp)->conn_lport) &&	\
19174 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
19175 	TCP_AC_V6RPORT((acp)) == (connp)->conn_fport) &&	\
19176 	(acp)->ac_start <= (tcp)->tcp_state &&			\
19177 	(acp)->ac_end >= (tcp)->tcp_state))
19178 
19179 #define	TCP_AC_MATCH(acp, connp, tcp)				\
19180 	(((acp)->ac_zoneid == ALL_ZONES ||			\
19181 	(acp)->ac_zoneid == (connp)->conn_zoneid) ?		\
19182 	TCP_AC_ADDR_MATCH(acp, connp, tcp) : 0)
19183 
19184 /*
19185  * Build a message containing a tcp_ioc_abort_conn_t structure
19186  * which is filled in with information from acp and tp.
19187  */
19188 static mblk_t *
19189 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
19190 {
19191 	mblk_t *mp;
19192 	tcp_ioc_abort_conn_t *tacp;
19193 
19194 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
19195 	if (mp == NULL)
19196 		return (NULL);
19197 
19198 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
19199 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
19200 	    sizeof (uint32_t));
19201 
19202 	tacp->ac_start = acp->ac_start;
19203 	tacp->ac_end = acp->ac_end;
19204 	tacp->ac_zoneid = acp->ac_zoneid;
19205 
19206 	if (acp->ac_local.ss_family == AF_INET) {
19207 		tacp->ac_local.ss_family = AF_INET;
19208 		tacp->ac_remote.ss_family = AF_INET;
19209 		TCP_AC_V4LOCAL(tacp) = tp->tcp_connp->conn_laddr_v4;
19210 		TCP_AC_V4REMOTE(tacp) = tp->tcp_connp->conn_faddr_v4;
19211 		TCP_AC_V4LPORT(tacp) = tp->tcp_connp->conn_lport;
19212 		TCP_AC_V4RPORT(tacp) = tp->tcp_connp->conn_fport;
19213 	} else {
19214 		tacp->ac_local.ss_family = AF_INET6;
19215 		tacp->ac_remote.ss_family = AF_INET6;
19216 		TCP_AC_V6LOCAL(tacp) = tp->tcp_connp->conn_laddr_v6;
19217 		TCP_AC_V6REMOTE(tacp) = tp->tcp_connp->conn_faddr_v6;
19218 		TCP_AC_V6LPORT(tacp) = tp->tcp_connp->conn_lport;
19219 		TCP_AC_V6RPORT(tacp) = tp->tcp_connp->conn_fport;
19220 	}
19221 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
19222 	return (mp);
19223 }
19224 
19225 /*
19226  * Print a tcp_ioc_abort_conn_t structure.
19227  */
19228 static void
19229 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
19230 {
19231 	char lbuf[128];
19232 	char rbuf[128];
19233 	sa_family_t af;
19234 	in_port_t lport, rport;
19235 	ushort_t logflags;
19236 
19237 	af = acp->ac_local.ss_family;
19238 
19239 	if (af == AF_INET) {
19240 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
19241 		    lbuf, 128);
19242 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
19243 		    rbuf, 128);
19244 		lport = ntohs(TCP_AC_V4LPORT(acp));
19245 		rport = ntohs(TCP_AC_V4RPORT(acp));
19246 	} else {
19247 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
19248 		    lbuf, 128);
19249 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
19250 		    rbuf, 128);
19251 		lport = ntohs(TCP_AC_V6LPORT(acp));
19252 		rport = ntohs(TCP_AC_V6RPORT(acp));
19253 	}
19254 
19255 	logflags = SL_TRACE | SL_NOTE;
19256 	/*
19257 	 * Don't print this message to the console if the operation was done
19258 	 * to a non-global zone.
19259 	 */
19260 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
19261 		logflags |= SL_CONSOLE;
19262 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
19263 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
19264 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
19265 	    acp->ac_start, acp->ac_end);
19266 }
19267 
19268 /*
19269  * Called using SQ_FILL when a message built using
19270  * tcp_ioctl_abort_build_msg is put into a queue.
19271  * Note that when we get here there is no wildcard in acp any more.
19272  */
19273 /* ARGSUSED2 */
19274 static void
19275 tcp_ioctl_abort_handler(void *arg, mblk_t *mp, void *arg2,
19276     ip_recv_attr_t *dummy)
19277 {
19278 	conn_t			*connp = (conn_t *)arg;
19279 	tcp_t			*tcp = connp->conn_tcp;
19280 	tcp_ioc_abort_conn_t	*acp;
19281 
19282 	/*
19283 	 * Don't accept any input on a closed tcp as this TCP logically does
19284 	 * not exist on the system. Don't proceed further with this TCP.
19285 	 * For eg. this packet could trigger another close of this tcp
19286 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
19287 	 * tcp_clean_death / tcp_closei_local must be called at most once
19288 	 * on a TCP.
19289 	 */
19290 	if (tcp->tcp_state == TCPS_CLOSED ||
19291 	    tcp->tcp_state == TCPS_BOUND) {
19292 		freemsg(mp);
19293 		return;
19294 	}
19295 
19296 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
19297 	if (tcp->tcp_state <= acp->ac_end) {
19298 		/*
19299 		 * If we get here, we are already on the correct
19300 		 * squeue. This ioctl follows the following path
19301 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
19302 		 * ->tcp_ioctl_abort->squeue_enter (if on a
19303 		 * different squeue)
19304 		 */
19305 		int errcode;
19306 
19307 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
19308 		(void) tcp_clean_death(tcp, errcode, 26);
19309 	}
19310 	freemsg(mp);
19311 }
19312 
19313 /*
19314  * Abort all matching connections on a hash chain.
19315  */
19316 static int
19317 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
19318     boolean_t exact, tcp_stack_t *tcps)
19319 {
19320 	int nmatch, err = 0;
19321 	tcp_t *tcp;
19322 	MBLKP mp, last, listhead = NULL;
19323 	conn_t	*tconnp;
19324 	connf_t	*connfp;
19325 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
19326 
19327 	connfp = &ipst->ips_ipcl_conn_fanout[index];
19328 
19329 startover:
19330 	nmatch = 0;
19331 
19332 	mutex_enter(&connfp->connf_lock);
19333 	for (tconnp = connfp->connf_head; tconnp != NULL;
19334 	    tconnp = tconnp->conn_next) {
19335 		tcp = tconnp->conn_tcp;
19336 		/*
19337 		 * We are missing a check on sin6_scope_id for linklocals here,
19338 		 * but current usage is just for aborting based on zoneid
19339 		 * for shared-IP zones.
19340 		 */
19341 		if (TCP_AC_MATCH(acp, tconnp, tcp)) {
19342 			CONN_INC_REF(tconnp);
19343 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
19344 			if (mp == NULL) {
19345 				err = ENOMEM;
19346 				CONN_DEC_REF(tconnp);
19347 				break;
19348 			}
19349 			mp->b_prev = (mblk_t *)tcp;
19350 
19351 			if (listhead == NULL) {
19352 				listhead = mp;
19353 				last = mp;
19354 			} else {
19355 				last->b_next = mp;
19356 				last = mp;
19357 			}
19358 			nmatch++;
19359 			if (exact)
19360 				break;
19361 		}
19362 
19363 		/* Avoid holding lock for too long. */
19364 		if (nmatch >= 500)
19365 			break;
19366 	}
19367 	mutex_exit(&connfp->connf_lock);
19368 
19369 	/* Pass mp into the correct tcp */
19370 	while ((mp = listhead) != NULL) {
19371 		listhead = listhead->b_next;
19372 		tcp = (tcp_t *)mp->b_prev;
19373 		mp->b_next = mp->b_prev = NULL;
19374 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp,
19375 		    tcp_ioctl_abort_handler, tcp->tcp_connp, NULL,
19376 		    SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
19377 	}
19378 
19379 	*count += nmatch;
19380 	if (nmatch >= 500 && err == 0)
19381 		goto startover;
19382 	return (err);
19383 }
19384 
19385 /*
19386  * Abort all connections that matches the attributes specified in acp.
19387  */
19388 static int
19389 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
19390 {
19391 	sa_family_t af;
19392 	uint32_t  ports;
19393 	uint16_t *pports;
19394 	int err = 0, count = 0;
19395 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
19396 	int index = -1;
19397 	ushort_t logflags;
19398 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19399 
19400 	af = acp->ac_local.ss_family;
19401 
19402 	if (af == AF_INET) {
19403 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
19404 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
19405 			pports = (uint16_t *)&ports;
19406 			pports[1] = TCP_AC_V4LPORT(acp);
19407 			pports[0] = TCP_AC_V4RPORT(acp);
19408 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
19409 		}
19410 	} else {
19411 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
19412 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
19413 			pports = (uint16_t *)&ports;
19414 			pports[1] = TCP_AC_V6LPORT(acp);
19415 			pports[0] = TCP_AC_V6RPORT(acp);
19416 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
19417 		}
19418 	}
19419 
19420 	/*
19421 	 * For cases where remote addr, local port, and remote port are non-
19422 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
19423 	 */
19424 	if (index != -1) {
19425 		err = tcp_ioctl_abort_bucket(acp, index,
19426 		    &count, exact, tcps);
19427 	} else {
19428 		/*
19429 		 * loop through all entries for wildcard case
19430 		 */
19431 		for (index = 0;
19432 		    index < ipst->ips_ipcl_conn_fanout_size;
19433 		    index++) {
19434 			err = tcp_ioctl_abort_bucket(acp, index,
19435 			    &count, exact, tcps);
19436 			if (err != 0)
19437 				break;
19438 		}
19439 	}
19440 
19441 	logflags = SL_TRACE | SL_NOTE;
19442 	/*
19443 	 * Don't print this message to the console if the operation was done
19444 	 * to a non-global zone.
19445 	 */
19446 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
19447 		logflags |= SL_CONSOLE;
19448 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
19449 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
19450 	if (err == 0 && count == 0)
19451 		err = ENOENT;
19452 	return (err);
19453 }
19454 
19455 /*
19456  * Process the TCP_IOC_ABORT_CONN ioctl request.
19457  */
19458 static void
19459 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
19460 {
19461 	int	err;
19462 	IOCP    iocp;
19463 	MBLKP   mp1;
19464 	sa_family_t laf, raf;
19465 	tcp_ioc_abort_conn_t *acp;
19466 	zone_t		*zptr;
19467 	conn_t		*connp = Q_TO_CONN(q);
19468 	zoneid_t	zoneid = connp->conn_zoneid;
19469 	tcp_t		*tcp = connp->conn_tcp;
19470 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19471 
19472 	iocp = (IOCP)mp->b_rptr;
19473 
19474 	if ((mp1 = mp->b_cont) == NULL ||
19475 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
19476 		err = EINVAL;
19477 		goto out;
19478 	}
19479 
19480 	/* check permissions */
19481 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
19482 		err = EPERM;
19483 		goto out;
19484 	}
19485 
19486 	if (mp1->b_cont != NULL) {
19487 		freemsg(mp1->b_cont);
19488 		mp1->b_cont = NULL;
19489 	}
19490 
19491 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
19492 	laf = acp->ac_local.ss_family;
19493 	raf = acp->ac_remote.ss_family;
19494 
19495 	/* check that a zone with the supplied zoneid exists */
19496 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
19497 		zptr = zone_find_by_id(zoneid);
19498 		if (zptr != NULL) {
19499 			zone_rele(zptr);
19500 		} else {
19501 			err = EINVAL;
19502 			goto out;
19503 		}
19504 	}
19505 
19506 	/*
19507 	 * For exclusive stacks we set the zoneid to zero
19508 	 * to make TCP operate as if in the global zone.
19509 	 */
19510 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
19511 		acp->ac_zoneid = GLOBAL_ZONEID;
19512 
19513 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
19514 	    acp->ac_start > acp->ac_end || laf != raf ||
19515 	    (laf != AF_INET && laf != AF_INET6)) {
19516 		err = EINVAL;
19517 		goto out;
19518 	}
19519 
19520 	tcp_ioctl_abort_dump(acp);
19521 	err = tcp_ioctl_abort(acp, tcps);
19522 
19523 out:
19524 	if (mp1 != NULL) {
19525 		freemsg(mp1);
19526 		mp->b_cont = NULL;
19527 	}
19528 
19529 	if (err != 0)
19530 		miocnak(q, mp, 0, err);
19531 	else
19532 		miocack(q, mp, 0, 0);
19533 }
19534 
19535 /*
19536  * tcp_time_wait_processing() handles processing of incoming packets when
19537  * the tcp is in the TIME_WAIT state.
19538  * A TIME_WAIT tcp that has an associated open TCP stream is never put
19539  * on the time wait list.
19540  */
19541 void
19542 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
19543     uint32_t seg_ack, int seg_len, tcpha_t *tcpha, ip_recv_attr_t *ira)
19544 {
19545 	int32_t		bytes_acked;
19546 	int32_t		gap;
19547 	int32_t		rgap;
19548 	tcp_opt_t	tcpopt;
19549 	uint_t		flags;
19550 	uint32_t	new_swnd = 0;
19551 	conn_t		*nconnp;
19552 	conn_t		*connp = tcp->tcp_connp;
19553 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19554 
19555 	BUMP_LOCAL(tcp->tcp_ibsegs);
19556 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
19557 
19558 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
19559 	new_swnd = ntohs(tcpha->tha_win) <<
19560 	    ((tcpha->tha_flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
19561 	if (tcp->tcp_snd_ts_ok) {
19562 		if (!tcp_paws_check(tcp, tcpha, &tcpopt)) {
19563 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19564 			    tcp->tcp_rnxt, TH_ACK);
19565 			goto done;
19566 		}
19567 	}
19568 	gap = seg_seq - tcp->tcp_rnxt;
19569 	rgap = tcp->tcp_rwnd - (gap + seg_len);
19570 	if (gap < 0) {
19571 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
19572 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
19573 		    (seg_len > -gap ? -gap : seg_len));
19574 		seg_len += gap;
19575 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
19576 			if (flags & TH_RST) {
19577 				goto done;
19578 			}
19579 			if ((flags & TH_FIN) && seg_len == -1) {
19580 				/*
19581 				 * When TCP receives a duplicate FIN in
19582 				 * TIME_WAIT state, restart the 2 MSL timer.
19583 				 * See page 73 in RFC 793. Make sure this TCP
19584 				 * is already on the TIME_WAIT list. If not,
19585 				 * just restart the timer.
19586 				 */
19587 				if (TCP_IS_DETACHED(tcp)) {
19588 					if (tcp_time_wait_remove(tcp, NULL) ==
19589 					    B_TRUE) {
19590 						tcp_time_wait_append(tcp);
19591 						TCP_DBGSTAT(tcps,
19592 						    tcp_rput_time_wait);
19593 					}
19594 				} else {
19595 					ASSERT(tcp != NULL);
19596 					TCP_TIMER_RESTART(tcp,
19597 					    tcps->tcps_time_wait_interval);
19598 				}
19599 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19600 				    tcp->tcp_rnxt, TH_ACK);
19601 				goto done;
19602 			}
19603 			flags |=  TH_ACK_NEEDED;
19604 			seg_len = 0;
19605 			goto process_ack;
19606 		}
19607 
19608 		/* Fix seg_seq, and chew the gap off the front. */
19609 		seg_seq = tcp->tcp_rnxt;
19610 	}
19611 
19612 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
19613 		/*
19614 		 * Make sure that when we accept the connection, pick
19615 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
19616 		 * old connection.
19617 		 *
19618 		 * The next ISS generated is equal to tcp_iss_incr_extra
19619 		 * + ISS_INCR/2 + other components depending on the
19620 		 * value of tcp_strong_iss.  We pre-calculate the new
19621 		 * ISS here and compare with tcp_snxt to determine if
19622 		 * we need to make adjustment to tcp_iss_incr_extra.
19623 		 *
19624 		 * The above calculation is ugly and is a
19625 		 * waste of CPU cycles...
19626 		 */
19627 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
19628 		int32_t adj;
19629 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
19630 
19631 		switch (tcps->tcps_strong_iss) {
19632 		case 2: {
19633 			/* Add time and MD5 components. */
19634 			uint32_t answer[4];
19635 			struct {
19636 				uint32_t ports;
19637 				in6_addr_t src;
19638 				in6_addr_t dst;
19639 			} arg;
19640 			MD5_CTX context;
19641 
19642 			mutex_enter(&tcps->tcps_iss_key_lock);
19643 			context = tcps->tcps_iss_key;
19644 			mutex_exit(&tcps->tcps_iss_key_lock);
19645 			arg.ports = connp->conn_ports;
19646 			/* We use MAPPED addresses in tcp_iss_init */
19647 			arg.src = connp->conn_laddr_v6;
19648 			arg.dst = connp->conn_faddr_v6;
19649 			MD5Update(&context, (uchar_t *)&arg,
19650 			    sizeof (arg));
19651 			MD5Final((uchar_t *)answer, &context);
19652 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
19653 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
19654 			break;
19655 		}
19656 		case 1:
19657 			/* Add time component and min random (i.e. 1). */
19658 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
19659 			break;
19660 		default:
19661 			/* Add only time component. */
19662 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
19663 			break;
19664 		}
19665 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
19666 			/*
19667 			 * New ISS not guaranteed to be ISS_INCR/2
19668 			 * ahead of the current tcp_snxt, so add the
19669 			 * difference to tcp_iss_incr_extra.
19670 			 */
19671 			tcps->tcps_iss_incr_extra += adj;
19672 		}
19673 		/*
19674 		 * If tcp_clean_death() can not perform the task now,
19675 		 * drop the SYN packet and let the other side re-xmit.
19676 		 * Otherwise pass the SYN packet back in, since the
19677 		 * old tcp state has been cleaned up or freed.
19678 		 */
19679 		if (tcp_clean_death(tcp, 0, 27) == -1)
19680 			goto done;
19681 		nconnp = ipcl_classify(mp, ira, ipst);
19682 		if (nconnp != NULL) {
19683 			TCP_STAT(tcps, tcp_time_wait_syn_success);
19684 			/* Drops ref on nconnp */
19685 			tcp_reinput(nconnp, mp, ira, ipst);
19686 			return;
19687 		}
19688 		goto done;
19689 	}
19690 
19691 	/*
19692 	 * rgap is the amount of stuff received out of window.  A negative
19693 	 * value is the amount out of window.
19694 	 */
19695 	if (rgap < 0) {
19696 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
19697 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
19698 		/* Fix seg_len and make sure there is something left. */
19699 		seg_len += rgap;
19700 		if (seg_len <= 0) {
19701 			if (flags & TH_RST) {
19702 				goto done;
19703 			}
19704 			flags |=  TH_ACK_NEEDED;
19705 			seg_len = 0;
19706 			goto process_ack;
19707 		}
19708 	}
19709 	/*
19710 	 * Check whether we can update tcp_ts_recent.  This test is
19711 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
19712 	 * Extensions for High Performance: An Update", Internet Draft.
19713 	 */
19714 	if (tcp->tcp_snd_ts_ok &&
19715 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
19716 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
19717 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
19718 		tcp->tcp_last_rcv_lbolt = ddi_get_lbolt64();
19719 	}
19720 
19721 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
19722 		/* Always ack out of order packets */
19723 		flags |= TH_ACK_NEEDED;
19724 		seg_len = 0;
19725 	} else if (seg_len > 0) {
19726 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
19727 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
19728 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
19729 	}
19730 	if (flags & TH_RST) {
19731 		(void) tcp_clean_death(tcp, 0, 28);
19732 		goto done;
19733 	}
19734 	if (flags & TH_SYN) {
19735 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
19736 		    TH_RST|TH_ACK);
19737 		/*
19738 		 * Do not delete the TCP structure if it is in
19739 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
19740 		 */
19741 		goto done;
19742 	}
19743 process_ack:
19744 	if (flags & TH_ACK) {
19745 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
19746 		if (bytes_acked <= 0) {
19747 			if (bytes_acked == 0 && seg_len == 0 &&
19748 			    new_swnd == tcp->tcp_swnd)
19749 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
19750 		} else {
19751 			/* Acks something not sent */
19752 			flags |= TH_ACK_NEEDED;
19753 		}
19754 	}
19755 	if (flags & TH_ACK_NEEDED) {
19756 		/*
19757 		 * Time to send an ack for some reason.
19758 		 */
19759 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19760 		    tcp->tcp_rnxt, TH_ACK);
19761 	}
19762 done:
19763 	freemsg(mp);
19764 }
19765 
19766 /*
19767  * TCP Timers Implementation.
19768  */
19769 timeout_id_t
19770 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
19771 {
19772 	mblk_t *mp;
19773 	tcp_timer_t *tcpt;
19774 	tcp_t *tcp = connp->conn_tcp;
19775 
19776 	ASSERT(connp->conn_sqp != NULL);
19777 
19778 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
19779 
19780 	if (tcp->tcp_timercache == NULL) {
19781 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
19782 	} else {
19783 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
19784 		mp = tcp->tcp_timercache;
19785 		tcp->tcp_timercache = mp->b_next;
19786 		mp->b_next = NULL;
19787 		ASSERT(mp->b_wptr == NULL);
19788 	}
19789 
19790 	CONN_INC_REF(connp);
19791 	tcpt = (tcp_timer_t *)mp->b_rptr;
19792 	tcpt->connp = connp;
19793 	tcpt->tcpt_proc = f;
19794 	/*
19795 	 * TCP timers are normal timeouts. Plus, they do not require more than
19796 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
19797 	 * rounding up the expiration to the next resolution boundary, we can
19798 	 * batch timers in the callout subsystem to make TCP timers more
19799 	 * efficient. The roundup also protects short timers from expiring too
19800 	 * early before they have a chance to be cancelled.
19801 	 */
19802 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
19803 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
19804 
19805 	return ((timeout_id_t)mp);
19806 }
19807 
19808 static void
19809 tcp_timer_callback(void *arg)
19810 {
19811 	mblk_t *mp = (mblk_t *)arg;
19812 	tcp_timer_t *tcpt;
19813 	conn_t	*connp;
19814 
19815 	tcpt = (tcp_timer_t *)mp->b_rptr;
19816 	connp = tcpt->connp;
19817 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
19818 	    NULL, SQ_FILL, SQTAG_TCP_TIMER);
19819 }
19820 
19821 /* ARGSUSED */
19822 static void
19823 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
19824 {
19825 	tcp_timer_t *tcpt;
19826 	conn_t *connp = (conn_t *)arg;
19827 	tcp_t *tcp = connp->conn_tcp;
19828 
19829 	tcpt = (tcp_timer_t *)mp->b_rptr;
19830 	ASSERT(connp == tcpt->connp);
19831 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
19832 
19833 	/*
19834 	 * If the TCP has reached the closed state, don't proceed any
19835 	 * further. This TCP logically does not exist on the system.
19836 	 * tcpt_proc could for example access queues, that have already
19837 	 * been qprocoff'ed off.
19838 	 */
19839 	if (tcp->tcp_state != TCPS_CLOSED) {
19840 		(*tcpt->tcpt_proc)(connp);
19841 	} else {
19842 		tcp->tcp_timer_tid = 0;
19843 	}
19844 	tcp_timer_free(connp->conn_tcp, mp);
19845 }
19846 
19847 /*
19848  * There is potential race with untimeout and the handler firing at the same
19849  * time. The mblock may be freed by the handler while we are trying to use
19850  * it. But since both should execute on the same squeue, this race should not
19851  * occur.
19852  */
19853 clock_t
19854 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
19855 {
19856 	mblk_t	*mp = (mblk_t *)id;
19857 	tcp_timer_t *tcpt;
19858 	clock_t delta;
19859 
19860 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
19861 
19862 	if (mp == NULL)
19863 		return (-1);
19864 
19865 	tcpt = (tcp_timer_t *)mp->b_rptr;
19866 	ASSERT(tcpt->connp == connp);
19867 
19868 	delta = untimeout_default(tcpt->tcpt_tid, 0);
19869 
19870 	if (delta >= 0) {
19871 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
19872 		tcp_timer_free(connp->conn_tcp, mp);
19873 		CONN_DEC_REF(connp);
19874 	}
19875 
19876 	return (delta);
19877 }
19878 
19879 /*
19880  * Allocate space for the timer event. The allocation looks like mblk, but it is
19881  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
19882  *
19883  * Dealing with failures: If we can't allocate from the timer cache we try
19884  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
19885  * points to b_rptr.
19886  * If we can't allocate anything using allocb_tryhard(), we perform a last
19887  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
19888  * save the actual allocation size in b_datap.
19889  */
19890 mblk_t *
19891 tcp_timermp_alloc(int kmflags)
19892 {
19893 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
19894 	    kmflags & ~KM_PANIC);
19895 
19896 	if (mp != NULL) {
19897 		mp->b_next = mp->b_prev = NULL;
19898 		mp->b_rptr = (uchar_t *)(&mp[1]);
19899 		mp->b_wptr = NULL;
19900 		mp->b_datap = NULL;
19901 		mp->b_queue = NULL;
19902 		mp->b_cont = NULL;
19903 	} else if (kmflags & KM_PANIC) {
19904 		/*
19905 		 * Failed to allocate memory for the timer. Try allocating from
19906 		 * dblock caches.
19907 		 */
19908 		/* ipclassifier calls this from a constructor - hence no tcps */
19909 		TCP_G_STAT(tcp_timermp_allocfail);
19910 		mp = allocb_tryhard(sizeof (tcp_timer_t));
19911 		if (mp == NULL) {
19912 			size_t size = 0;
19913 			/*
19914 			 * Memory is really low. Try tryhard allocation.
19915 			 *
19916 			 * ipclassifier calls this from a constructor -
19917 			 * hence no tcps
19918 			 */
19919 			TCP_G_STAT(tcp_timermp_allocdblfail);
19920 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
19921 			    sizeof (tcp_timer_t), &size, kmflags);
19922 			mp->b_rptr = (uchar_t *)(&mp[1]);
19923 			mp->b_next = mp->b_prev = NULL;
19924 			mp->b_wptr = (uchar_t *)-1;
19925 			mp->b_datap = (dblk_t *)size;
19926 			mp->b_queue = NULL;
19927 			mp->b_cont = NULL;
19928 		}
19929 		ASSERT(mp->b_wptr != NULL);
19930 	}
19931 	/* ipclassifier calls this from a constructor - hence no tcps */
19932 	TCP_G_DBGSTAT(tcp_timermp_alloced);
19933 
19934 	return (mp);
19935 }
19936 
19937 /*
19938  * Free per-tcp timer cache.
19939  * It can only contain entries from tcp_timercache.
19940  */
19941 void
19942 tcp_timermp_free(tcp_t *tcp)
19943 {
19944 	mblk_t *mp;
19945 
19946 	while ((mp = tcp->tcp_timercache) != NULL) {
19947 		ASSERT(mp->b_wptr == NULL);
19948 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
19949 		kmem_cache_free(tcp_timercache, mp);
19950 	}
19951 }
19952 
19953 /*
19954  * Free timer event. Put it on the per-tcp timer cache if there is not too many
19955  * events there already (currently at most two events are cached).
19956  * If the event is not allocated from the timer cache, free it right away.
19957  */
19958 static void
19959 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
19960 {
19961 	mblk_t *mp1 = tcp->tcp_timercache;
19962 
19963 	if (mp->b_wptr != NULL) {
19964 		/*
19965 		 * This allocation is not from a timer cache, free it right
19966 		 * away.
19967 		 */
19968 		if (mp->b_wptr != (uchar_t *)-1)
19969 			freeb(mp);
19970 		else
19971 			kmem_free(mp, (size_t)mp->b_datap);
19972 	} else if (mp1 == NULL || mp1->b_next == NULL) {
19973 		/* Cache this timer block for future allocations */
19974 		mp->b_rptr = (uchar_t *)(&mp[1]);
19975 		mp->b_next = mp1;
19976 		tcp->tcp_timercache = mp;
19977 	} else {
19978 		kmem_cache_free(tcp_timercache, mp);
19979 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
19980 	}
19981 }
19982 
19983 /*
19984  * End of TCP Timers implementation.
19985  */
19986 
19987 /*
19988  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
19989  * on the specified backing STREAMS q. Note, the caller may make the
19990  * decision to call based on the tcp_t.tcp_flow_stopped value which
19991  * when check outside the q's lock is only an advisory check ...
19992  */
19993 void
19994 tcp_setqfull(tcp_t *tcp)
19995 {
19996 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19997 	conn_t	*connp = tcp->tcp_connp;
19998 
19999 	if (tcp->tcp_closed)
20000 		return;
20001 
20002 	conn_setqfull(connp, &tcp->tcp_flow_stopped);
20003 	if (tcp->tcp_flow_stopped)
20004 		TCP_STAT(tcps, tcp_flwctl_on);
20005 }
20006 
20007 void
20008 tcp_clrqfull(tcp_t *tcp)
20009 {
20010 	conn_t  *connp = tcp->tcp_connp;
20011 
20012 	if (tcp->tcp_closed)
20013 		return;
20014 	conn_clrqfull(connp, &tcp->tcp_flow_stopped);
20015 }
20016 
20017 /*
20018  * kstats related to squeues i.e. not per IP instance
20019  */
20020 static void *
20021 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
20022 {
20023 	kstat_t *ksp;
20024 
20025 	tcp_g_stat_t template = {
20026 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
20027 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
20028 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
20029 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
20030 	};
20031 
20032 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
20033 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
20034 	    KSTAT_FLAG_VIRTUAL);
20035 
20036 	if (ksp == NULL)
20037 		return (NULL);
20038 
20039 	bcopy(&template, tcp_g_statp, sizeof (template));
20040 	ksp->ks_data = (void *)tcp_g_statp;
20041 
20042 	kstat_install(ksp);
20043 	return (ksp);
20044 }
20045 
20046 static void
20047 tcp_g_kstat_fini(kstat_t *ksp)
20048 {
20049 	if (ksp != NULL) {
20050 		kstat_delete(ksp);
20051 	}
20052 }
20053 
20054 
20055 static void *
20056 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
20057 {
20058 	kstat_t *ksp;
20059 
20060 	tcp_stat_t template = {
20061 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
20062 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
20063 		{ "tcp_time_wait_syn_success",	KSTAT_DATA_UINT64 },
20064 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
20065 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
20066 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
20067 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
20068 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
20069 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
20070 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
20071 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
20072 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
20073 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
20074 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
20075 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
20076 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
20077 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
20078 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
20079 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
20080 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
20081 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
20082 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
20083 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
20084 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
20085 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
20086 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
20087 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
20088 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
20089 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
20090 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
20091 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
20092 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
20093 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
20094 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
20095 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
20096 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
20097 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
20098 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
20099 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
20100 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
20101 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
20102 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
20103 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
20104 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
20105 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
20106 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
20107 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
20108 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
20109 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
20110 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
20111 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
20112 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
20113 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
20114 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
20115 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
20116 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
20117 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
20118 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
20119 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
20120 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
20121 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
20122 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
20123 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
20124 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
20125 		{ "tcp_listen_cnt_drop",	KSTAT_DATA_UINT64 },
20126 		{ "tcp_listen_mem_drop",	KSTAT_DATA_UINT64 },
20127 		{ "tcp_zwin_ack_syn",		KSTAT_DATA_UINT64 },
20128 		{ "tcp_rst_unsent",		KSTAT_DATA_UINT64 }
20129 	};
20130 
20131 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
20132 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
20133 	    KSTAT_FLAG_VIRTUAL, stackid);
20134 
20135 	if (ksp == NULL)
20136 		return (NULL);
20137 
20138 	bcopy(&template, tcps_statisticsp, sizeof (template));
20139 	ksp->ks_data = (void *)tcps_statisticsp;
20140 	ksp->ks_private = (void *)(uintptr_t)stackid;
20141 
20142 	kstat_install(ksp);
20143 	return (ksp);
20144 }
20145 
20146 static void
20147 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
20148 {
20149 	if (ksp != NULL) {
20150 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
20151 		kstat_delete_netstack(ksp, stackid);
20152 	}
20153 }
20154 
20155 /*
20156  * TCP Kstats implementation
20157  */
20158 static void *
20159 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
20160 {
20161 	kstat_t	*ksp;
20162 
20163 	tcp_named_kstat_t template = {
20164 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
20165 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
20166 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
20167 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
20168 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
20169 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
20170 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
20171 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
20172 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
20173 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
20174 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
20175 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
20176 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
20177 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
20178 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
20179 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
20180 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
20181 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
20182 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
20183 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
20184 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
20185 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
20186 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
20187 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
20188 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
20189 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
20190 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
20191 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
20192 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
20193 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
20194 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
20195 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
20196 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
20197 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
20198 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
20199 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
20200 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
20201 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
20202 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
20203 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
20204 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
20205 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
20206 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
20207 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
20208 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
20209 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
20210 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
20211 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
20212 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
20213 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
20214 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
20215 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
20216 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
20217 	};
20218 
20219 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
20220 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
20221 
20222 	if (ksp == NULL)
20223 		return (NULL);
20224 
20225 	template.rtoAlgorithm.value.ui32 = 4;
20226 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
20227 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
20228 	template.maxConn.value.i32 = -1;
20229 
20230 	bcopy(&template, ksp->ks_data, sizeof (template));
20231 	ksp->ks_update = tcp_kstat_update;
20232 	ksp->ks_private = (void *)(uintptr_t)stackid;
20233 
20234 	kstat_install(ksp);
20235 	return (ksp);
20236 }
20237 
20238 static void
20239 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
20240 {
20241 	if (ksp != NULL) {
20242 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
20243 		kstat_delete_netstack(ksp, stackid);
20244 	}
20245 }
20246 
20247 static int
20248 tcp_kstat_update(kstat_t *kp, int rw)
20249 {
20250 	tcp_named_kstat_t *tcpkp;
20251 	tcp_t		*tcp;
20252 	connf_t		*connfp;
20253 	conn_t		*connp;
20254 	int 		i;
20255 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
20256 	netstack_t	*ns;
20257 	tcp_stack_t	*tcps;
20258 	ip_stack_t	*ipst;
20259 
20260 	if ((kp == NULL) || (kp->ks_data == NULL))
20261 		return (EIO);
20262 
20263 	if (rw == KSTAT_WRITE)
20264 		return (EACCES);
20265 
20266 	ns = netstack_find_by_stackid(stackid);
20267 	if (ns == NULL)
20268 		return (-1);
20269 	tcps = ns->netstack_tcp;
20270 	if (tcps == NULL) {
20271 		netstack_rele(ns);
20272 		return (-1);
20273 	}
20274 
20275 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
20276 
20277 	tcpkp->currEstab.value.ui32 = 0;
20278 
20279 	ipst = ns->netstack_ip;
20280 
20281 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
20282 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
20283 		connp = NULL;
20284 		while ((connp =
20285 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
20286 			tcp = connp->conn_tcp;
20287 			switch (tcp_snmp_state(tcp)) {
20288 			case MIB2_TCP_established:
20289 			case MIB2_TCP_closeWait:
20290 				tcpkp->currEstab.value.ui32++;
20291 				break;
20292 			}
20293 		}
20294 	}
20295 
20296 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
20297 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
20298 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
20299 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
20300 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
20301 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
20302 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
20303 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
20304 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
20305 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
20306 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
20307 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
20308 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
20309 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
20310 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
20311 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
20312 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
20313 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
20314 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
20315 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
20316 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
20317 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
20318 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
20319 	tcpkp->inDataInorderSegs.value.ui32 =
20320 	    tcps->tcps_mib.tcpInDataInorderSegs;
20321 	tcpkp->inDataInorderBytes.value.ui32 =
20322 	    tcps->tcps_mib.tcpInDataInorderBytes;
20323 	tcpkp->inDataUnorderSegs.value.ui32 =
20324 	    tcps->tcps_mib.tcpInDataUnorderSegs;
20325 	tcpkp->inDataUnorderBytes.value.ui32 =
20326 	    tcps->tcps_mib.tcpInDataUnorderBytes;
20327 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
20328 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
20329 	tcpkp->inDataPartDupSegs.value.ui32 =
20330 	    tcps->tcps_mib.tcpInDataPartDupSegs;
20331 	tcpkp->inDataPartDupBytes.value.ui32 =
20332 	    tcps->tcps_mib.tcpInDataPartDupBytes;
20333 	tcpkp->inDataPastWinSegs.value.ui32 =
20334 	    tcps->tcps_mib.tcpInDataPastWinSegs;
20335 	tcpkp->inDataPastWinBytes.value.ui32 =
20336 	    tcps->tcps_mib.tcpInDataPastWinBytes;
20337 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
20338 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
20339 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
20340 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
20341 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
20342 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
20343 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
20344 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
20345 	tcpkp->timKeepaliveProbe.value.ui32 =
20346 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
20347 	tcpkp->timKeepaliveDrop.value.ui32 =
20348 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
20349 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
20350 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
20351 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
20352 	tcpkp->outSackRetransSegs.value.ui32 =
20353 	    tcps->tcps_mib.tcpOutSackRetransSegs;
20354 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
20355 
20356 	netstack_rele(ns);
20357 	return (0);
20358 }
20359 
20360 static int
20361 tcp_squeue_switch(int val)
20362 {
20363 	int rval = SQ_FILL;
20364 
20365 	switch (val) {
20366 	case 1:
20367 		rval = SQ_NODRAIN;
20368 		break;
20369 	case 2:
20370 		rval = SQ_PROCESS;
20371 		break;
20372 	default:
20373 		break;
20374 	}
20375 	return (rval);
20376 }
20377 
20378 /*
20379  * This is called once for each squeue - globally for all stack
20380  * instances.
20381  */
20382 static void
20383 tcp_squeue_add(squeue_t *sqp)
20384 {
20385 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
20386 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
20387 
20388 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
20389 	tcp_time_wait->tcp_time_wait_tid =
20390 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
20391 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
20392 	    CALLOUT_FLAG_ROUNDUP);
20393 	if (tcp_free_list_max_cnt == 0) {
20394 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
20395 		    max_ncpus : boot_max_ncpus);
20396 
20397 		/*
20398 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
20399 		 */
20400 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
20401 		    (tcp_ncpus * sizeof (tcp_t) * 100);
20402 	}
20403 	tcp_time_wait->tcp_free_list_cnt = 0;
20404 }
20405 
20406 /*
20407  * On a labeled system we have some protocols above TCP, such as RPC, which
20408  * appear to assume that every mblk in a chain has a db_credp.
20409  */
20410 static void
20411 tcp_setcred_data(mblk_t *mp, ip_recv_attr_t *ira)
20412 {
20413 	ASSERT(is_system_labeled());
20414 	ASSERT(ira->ira_cred != NULL);
20415 
20416 	while (mp != NULL) {
20417 		mblk_setcred(mp, ira->ira_cred, NOPID);
20418 		mp = mp->b_cont;
20419 	}
20420 }
20421 
20422 static int
20423 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
20424     boolean_t bind_to_req_port_only, cred_t *cr)
20425 {
20426 	in_port_t	mlp_port;
20427 	mlp_type_t 	addrtype, mlptype;
20428 	boolean_t	user_specified;
20429 	in_port_t	allocated_port;
20430 	in_port_t	requested_port = *requested_port_ptr;
20431 	conn_t		*connp = tcp->tcp_connp;
20432 	zone_t		*zone;
20433 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20434 	in6_addr_t	v6addr = connp->conn_laddr_v6;
20435 
20436 	/*
20437 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
20438 	 */
20439 	ASSERT(cr != NULL);
20440 
20441 	/*
20442 	 * Get a valid port (within the anonymous range and should not
20443 	 * be a privileged one) to use if the user has not given a port.
20444 	 * If multiple threads are here, they may all start with
20445 	 * with the same initial port. But, it should be fine as long as
20446 	 * tcp_bindi will ensure that no two threads will be assigned
20447 	 * the same port.
20448 	 *
20449 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
20450 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
20451 	 * unless TCP_ANONPRIVBIND option is set.
20452 	 */
20453 	mlptype = mlptSingle;
20454 	mlp_port = requested_port;
20455 	if (requested_port == 0) {
20456 		requested_port = connp->conn_anon_priv_bind ?
20457 		    tcp_get_next_priv_port(tcp) :
20458 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
20459 		    tcp, B_TRUE);
20460 		if (requested_port == 0) {
20461 			return (-TNOADDR);
20462 		}
20463 		user_specified = B_FALSE;
20464 
20465 		/*
20466 		 * If the user went through one of the RPC interfaces to create
20467 		 * this socket and RPC is MLP in this zone, then give him an
20468 		 * anonymous MLP.
20469 		 */
20470 		if (connp->conn_anon_mlp && is_system_labeled()) {
20471 			zone = crgetzone(cr);
20472 			addrtype = tsol_mlp_addr_type(
20473 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
20474 			    IPV6_VERSION, &v6addr,
20475 			    tcps->tcps_netstack->netstack_ip);
20476 			if (addrtype == mlptSingle) {
20477 				return (-TNOADDR);
20478 			}
20479 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
20480 			    PMAPPORT, addrtype);
20481 			mlp_port = PMAPPORT;
20482 		}
20483 	} else {
20484 		int i;
20485 		boolean_t priv = B_FALSE;
20486 
20487 		/*
20488 		 * If the requested_port is in the well-known privileged range,
20489 		 * verify that the stream was opened by a privileged user.
20490 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
20491 		 * but instead the code relies on:
20492 		 * - the fact that the address of the array and its size never
20493 		 *   changes
20494 		 * - the atomic assignment of the elements of the array
20495 		 */
20496 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
20497 			priv = B_TRUE;
20498 		} else {
20499 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
20500 				if (requested_port ==
20501 				    tcps->tcps_g_epriv_ports[i]) {
20502 					priv = B_TRUE;
20503 					break;
20504 				}
20505 			}
20506 		}
20507 		if (priv) {
20508 			if (secpolicy_net_privaddr(cr, requested_port,
20509 			    IPPROTO_TCP) != 0) {
20510 				if (connp->conn_debug) {
20511 					(void) strlog(TCP_MOD_ID, 0, 1,
20512 					    SL_ERROR|SL_TRACE,
20513 					    "tcp_bind: no priv for port %d",
20514 					    requested_port);
20515 				}
20516 				return (-TACCES);
20517 			}
20518 		}
20519 		user_specified = B_TRUE;
20520 
20521 		connp = tcp->tcp_connp;
20522 		if (is_system_labeled()) {
20523 			zone = crgetzone(cr);
20524 			addrtype = tsol_mlp_addr_type(
20525 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
20526 			    IPV6_VERSION, &v6addr,
20527 			    tcps->tcps_netstack->netstack_ip);
20528 			if (addrtype == mlptSingle) {
20529 				return (-TNOADDR);
20530 			}
20531 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
20532 			    requested_port, addrtype);
20533 		}
20534 	}
20535 
20536 	if (mlptype != mlptSingle) {
20537 		if (secpolicy_net_bindmlp(cr) != 0) {
20538 			if (connp->conn_debug) {
20539 				(void) strlog(TCP_MOD_ID, 0, 1,
20540 				    SL_ERROR|SL_TRACE,
20541 				    "tcp_bind: no priv for multilevel port %d",
20542 				    requested_port);
20543 			}
20544 			return (-TACCES);
20545 		}
20546 
20547 		/*
20548 		 * If we're specifically binding a shared IP address and the
20549 		 * port is MLP on shared addresses, then check to see if this
20550 		 * zone actually owns the MLP.  Reject if not.
20551 		 */
20552 		if (mlptype == mlptShared && addrtype == mlptShared) {
20553 			/*
20554 			 * No need to handle exclusive-stack zones since
20555 			 * ALL_ZONES only applies to the shared stack.
20556 			 */
20557 			zoneid_t mlpzone;
20558 
20559 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
20560 			    htons(mlp_port));
20561 			if (connp->conn_zoneid != mlpzone) {
20562 				if (connp->conn_debug) {
20563 					(void) strlog(TCP_MOD_ID, 0, 1,
20564 					    SL_ERROR|SL_TRACE,
20565 					    "tcp_bind: attempt to bind port "
20566 					    "%d on shared addr in zone %d "
20567 					    "(should be %d)",
20568 					    mlp_port, connp->conn_zoneid,
20569 					    mlpzone);
20570 				}
20571 				return (-TACCES);
20572 			}
20573 		}
20574 
20575 		if (!user_specified) {
20576 			int err;
20577 			err = tsol_mlp_anon(zone, mlptype, connp->conn_proto,
20578 			    requested_port, B_TRUE);
20579 			if (err != 0) {
20580 				if (connp->conn_debug) {
20581 					(void) strlog(TCP_MOD_ID, 0, 1,
20582 					    SL_ERROR|SL_TRACE,
20583 					    "tcp_bind: cannot establish anon "
20584 					    "MLP for port %d",
20585 					    requested_port);
20586 				}
20587 				return (err);
20588 			}
20589 			connp->conn_anon_port = B_TRUE;
20590 		}
20591 		connp->conn_mlp_type = mlptype;
20592 	}
20593 
20594 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
20595 	    connp->conn_reuseaddr, B_FALSE, bind_to_req_port_only,
20596 	    user_specified);
20597 
20598 	if (allocated_port == 0) {
20599 		connp->conn_mlp_type = mlptSingle;
20600 		if (connp->conn_anon_port) {
20601 			connp->conn_anon_port = B_FALSE;
20602 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_proto,
20603 			    requested_port, B_FALSE);
20604 		}
20605 		if (bind_to_req_port_only) {
20606 			if (connp->conn_debug) {
20607 				(void) strlog(TCP_MOD_ID, 0, 1,
20608 				    SL_ERROR|SL_TRACE,
20609 				    "tcp_bind: requested addr busy");
20610 			}
20611 			return (-TADDRBUSY);
20612 		} else {
20613 			/* If we are out of ports, fail the bind. */
20614 			if (connp->conn_debug) {
20615 				(void) strlog(TCP_MOD_ID, 0, 1,
20616 				    SL_ERROR|SL_TRACE,
20617 				    "tcp_bind: out of ports?");
20618 			}
20619 			return (-TNOADDR);
20620 		}
20621 	}
20622 
20623 	/* Pass the allocated port back */
20624 	*requested_port_ptr = allocated_port;
20625 	return (0);
20626 }
20627 
20628 /*
20629  * Check the address and check/pick a local port number.
20630  */
20631 static int
20632 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
20633     boolean_t bind_to_req_port_only)
20634 {
20635 	tcp_t	*tcp = connp->conn_tcp;
20636 	sin_t	*sin;
20637 	sin6_t  *sin6;
20638 	in_port_t	requested_port;
20639 	ipaddr_t	v4addr;
20640 	in6_addr_t	v6addr;
20641 	ip_laddr_t	laddr_type = IPVL_UNICAST_UP;	/* INADDR_ANY */
20642 	zoneid_t	zoneid = IPCL_ZONEID(connp);
20643 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
20644 	uint_t		scopeid = 0;
20645 	int		error = 0;
20646 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
20647 
20648 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
20649 
20650 	if (tcp->tcp_state == TCPS_BOUND) {
20651 		return (0);
20652 	} else if (tcp->tcp_state > TCPS_BOUND) {
20653 		if (connp->conn_debug) {
20654 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20655 			    "tcp_bind: bad state, %d", tcp->tcp_state);
20656 		}
20657 		return (-TOUTSTATE);
20658 	}
20659 
20660 	ASSERT(sa != NULL && len != 0);
20661 
20662 	if (!OK_32PTR((char *)sa)) {
20663 		if (connp->conn_debug) {
20664 			(void) strlog(TCP_MOD_ID, 0, 1,
20665 			    SL_ERROR|SL_TRACE,
20666 			    "tcp_bind: bad address parameter, "
20667 			    "address %p, len %d",
20668 			    (void *)sa, len);
20669 		}
20670 		return (-TPROTO);
20671 	}
20672 
20673 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
20674 	if (error != 0) {
20675 		return (error);
20676 	}
20677 
20678 	switch (len) {
20679 	case sizeof (sin_t):	/* Complete IPv4 address */
20680 		sin = (sin_t *)sa;
20681 		requested_port = ntohs(sin->sin_port);
20682 		v4addr = sin->sin_addr.s_addr;
20683 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
20684 		if (v4addr != INADDR_ANY) {
20685 			laddr_type = ip_laddr_verify_v4(v4addr, zoneid, ipst,
20686 			    B_FALSE);
20687 		}
20688 		break;
20689 
20690 	case sizeof (sin6_t): /* Complete IPv6 address */
20691 		sin6 = (sin6_t *)sa;
20692 		v6addr = sin6->sin6_addr;
20693 		requested_port = ntohs(sin6->sin6_port);
20694 		if (IN6_IS_ADDR_V4MAPPED(&v6addr)) {
20695 			if (connp->conn_ipv6_v6only)
20696 				return (EADDRNOTAVAIL);
20697 
20698 			IN6_V4MAPPED_TO_IPADDR(&v6addr, v4addr);
20699 			if (v4addr != INADDR_ANY) {
20700 				laddr_type = ip_laddr_verify_v4(v4addr,
20701 				    zoneid, ipst, B_FALSE);
20702 			}
20703 		} else {
20704 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6addr)) {
20705 				if (IN6_IS_ADDR_LINKSCOPE(&v6addr))
20706 					scopeid = sin6->sin6_scope_id;
20707 				laddr_type = ip_laddr_verify_v6(&v6addr,
20708 				    zoneid, ipst, B_FALSE, scopeid);
20709 			}
20710 		}
20711 		break;
20712 
20713 	default:
20714 		if (connp->conn_debug) {
20715 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20716 			    "tcp_bind: bad address length, %d", len);
20717 		}
20718 		return (EAFNOSUPPORT);
20719 		/* return (-TBADADDR); */
20720 	}
20721 
20722 	/* Is the local address a valid unicast address? */
20723 	if (laddr_type == IPVL_BAD)
20724 		return (EADDRNOTAVAIL);
20725 
20726 	connp->conn_bound_addr_v6 = v6addr;
20727 	if (scopeid != 0) {
20728 		ixa->ixa_flags |= IXAF_SCOPEID_SET;
20729 		ixa->ixa_scopeid = scopeid;
20730 		connp->conn_incoming_ifindex = scopeid;
20731 	} else {
20732 		ixa->ixa_flags &= ~IXAF_SCOPEID_SET;
20733 		connp->conn_incoming_ifindex = connp->conn_bound_if;
20734 	}
20735 
20736 	connp->conn_laddr_v6 = v6addr;
20737 	connp->conn_saddr_v6 = v6addr;
20738 
20739 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
20740 
20741 	error = tcp_bind_select_lport(tcp, &requested_port,
20742 	    bind_to_req_port_only, cr);
20743 	if (error != 0) {
20744 		connp->conn_laddr_v6 = ipv6_all_zeros;
20745 		connp->conn_saddr_v6 = ipv6_all_zeros;
20746 		connp->conn_bound_addr_v6 = ipv6_all_zeros;
20747 	}
20748 	return (error);
20749 }
20750 
20751 /*
20752  * Return unix error is tli error is TSYSERR, otherwise return a negative
20753  * tli error.
20754  */
20755 int
20756 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
20757     boolean_t bind_to_req_port_only)
20758 {
20759 	int error;
20760 	tcp_t *tcp = connp->conn_tcp;
20761 
20762 	if (tcp->tcp_state >= TCPS_BOUND) {
20763 		if (connp->conn_debug) {
20764 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20765 			    "tcp_bind: bad state, %d", tcp->tcp_state);
20766 		}
20767 		return (-TOUTSTATE);
20768 	}
20769 
20770 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
20771 	if (error != 0)
20772 		return (error);
20773 
20774 	ASSERT(tcp->tcp_state == TCPS_BOUND);
20775 	tcp->tcp_conn_req_max = 0;
20776 	return (0);
20777 }
20778 
20779 int
20780 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
20781     socklen_t len, cred_t *cr)
20782 {
20783 	int 		error;
20784 	conn_t		*connp = (conn_t *)proto_handle;
20785 	squeue_t	*sqp = connp->conn_sqp;
20786 
20787 	/* All Solaris components should pass a cred for this operation. */
20788 	ASSERT(cr != NULL);
20789 
20790 	ASSERT(sqp != NULL);
20791 	ASSERT(connp->conn_upper_handle != NULL);
20792 
20793 	error = squeue_synch_enter(sqp, connp, NULL);
20794 	if (error != 0) {
20795 		/* failed to enter */
20796 		return (ENOSR);
20797 	}
20798 
20799 	/* binding to a NULL address really means unbind */
20800 	if (sa == NULL) {
20801 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
20802 			error = tcp_do_unbind(connp);
20803 		else
20804 			error = EINVAL;
20805 	} else {
20806 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
20807 	}
20808 
20809 	squeue_synch_exit(sqp, connp);
20810 
20811 	if (error < 0) {
20812 		if (error == -TOUTSTATE)
20813 			error = EINVAL;
20814 		else
20815 			error = proto_tlitosyserr(-error);
20816 	}
20817 
20818 	return (error);
20819 }
20820 
20821 /*
20822  * If the return value from this function is positive, it's a UNIX error.
20823  * Otherwise, if it's negative, then the absolute value is a TLI error.
20824  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
20825  */
20826 int
20827 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
20828     cred_t *cr, pid_t pid)
20829 {
20830 	tcp_t		*tcp = connp->conn_tcp;
20831 	sin_t		*sin = (sin_t *)sa;
20832 	sin6_t		*sin6 = (sin6_t *)sa;
20833 	ipaddr_t	*dstaddrp;
20834 	in_port_t	dstport;
20835 	uint_t		srcid;
20836 	int		error;
20837 	uint32_t	mss;
20838 	mblk_t		*syn_mp;
20839 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20840 	int32_t		oldstate;
20841 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
20842 
20843 	oldstate = tcp->tcp_state;
20844 
20845 	switch (len) {
20846 	default:
20847 		/*
20848 		 * Should never happen
20849 		 */
20850 		return (EINVAL);
20851 
20852 	case sizeof (sin_t):
20853 		sin = (sin_t *)sa;
20854 		if (sin->sin_port == 0) {
20855 			return (-TBADADDR);
20856 		}
20857 		if (connp->conn_ipv6_v6only) {
20858 			return (EAFNOSUPPORT);
20859 		}
20860 		break;
20861 
20862 	case sizeof (sin6_t):
20863 		sin6 = (sin6_t *)sa;
20864 		if (sin6->sin6_port == 0) {
20865 			return (-TBADADDR);
20866 		}
20867 		break;
20868 	}
20869 	/*
20870 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
20871 	 * make sure that the conn_ipversion is IPV4_VERSION.  We
20872 	 * need to this before we call tcp_bindi() so that the port lookup
20873 	 * code will look for ports in the correct port space (IPv4 and
20874 	 * IPv6 have separate port spaces).
20875 	 */
20876 	if (connp->conn_family == AF_INET6 &&
20877 	    connp->conn_ipversion == IPV6_VERSION &&
20878 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
20879 		if (connp->conn_ipv6_v6only)
20880 			return (EADDRNOTAVAIL);
20881 
20882 		connp->conn_ipversion = IPV4_VERSION;
20883 	}
20884 
20885 	switch (tcp->tcp_state) {
20886 	case TCPS_LISTEN:
20887 		/*
20888 		 * Listening sockets are not allowed to issue connect().
20889 		 */
20890 		if (IPCL_IS_NONSTR(connp))
20891 			return (EOPNOTSUPP);
20892 		/* FALLTHRU */
20893 	case TCPS_IDLE:
20894 		/*
20895 		 * We support quick connect, refer to comments in
20896 		 * tcp_connect_*()
20897 		 */
20898 		/* FALLTHRU */
20899 	case TCPS_BOUND:
20900 		break;
20901 	default:
20902 		return (-TOUTSTATE);
20903 	}
20904 
20905 	/*
20906 	 * We update our cred/cpid based on the caller of connect
20907 	 */
20908 	if (connp->conn_cred != cr) {
20909 		crhold(cr);
20910 		crfree(connp->conn_cred);
20911 		connp->conn_cred = cr;
20912 	}
20913 	connp->conn_cpid = pid;
20914 
20915 	/* Cache things in the ixa without any refhold */
20916 	ixa->ixa_cred = cr;
20917 	ixa->ixa_cpid = pid;
20918 	if (is_system_labeled()) {
20919 		/* We need to restart with a label based on the cred */
20920 		ip_xmit_attr_restore_tsl(ixa, ixa->ixa_cred);
20921 	}
20922 
20923 	if (connp->conn_family == AF_INET6) {
20924 		if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
20925 			error = tcp_connect_ipv6(tcp, &sin6->sin6_addr,
20926 			    sin6->sin6_port, sin6->sin6_flowinfo,
20927 			    sin6->__sin6_src_id, sin6->sin6_scope_id);
20928 		} else {
20929 			/*
20930 			 * Destination adress is mapped IPv6 address.
20931 			 * Source bound address should be unspecified or
20932 			 * IPv6 mapped address as well.
20933 			 */
20934 			if (!IN6_IS_ADDR_UNSPECIFIED(
20935 			    &connp->conn_bound_addr_v6) &&
20936 			    !IN6_IS_ADDR_V4MAPPED(&connp->conn_bound_addr_v6)) {
20937 				return (EADDRNOTAVAIL);
20938 			}
20939 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
20940 			dstport = sin6->sin6_port;
20941 			srcid = sin6->__sin6_src_id;
20942 			error = tcp_connect_ipv4(tcp, dstaddrp, dstport,
20943 			    srcid);
20944 		}
20945 	} else {
20946 		dstaddrp = &sin->sin_addr.s_addr;
20947 		dstport = sin->sin_port;
20948 		srcid = 0;
20949 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid);
20950 	}
20951 
20952 	if (error != 0)
20953 		goto connect_failed;
20954 
20955 	CL_INET_CONNECT(connp, B_TRUE, error);
20956 	if (error != 0)
20957 		goto connect_failed;
20958 
20959 	/* connect succeeded */
20960 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
20961 	tcp->tcp_active_open = 1;
20962 
20963 	/*
20964 	 * tcp_set_destination() does not adjust for TCP/IP header length.
20965 	 */
20966 	mss = tcp->tcp_mss - connp->conn_ht_iphc_len;
20967 
20968 	/*
20969 	 * Just make sure our rwnd is at least rcvbuf * MSS large, and round up
20970 	 * to the nearest MSS.
20971 	 *
20972 	 * We do the round up here because we need to get the interface MTU
20973 	 * first before we can do the round up.
20974 	 */
20975 	tcp->tcp_rwnd = connp->conn_rcvbuf;
20976 	tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
20977 	    tcps->tcps_recv_hiwat_minmss * mss);
20978 	connp->conn_rcvbuf = tcp->tcp_rwnd;
20979 	tcp_set_ws_value(tcp);
20980 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
20981 	if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
20982 		tcp->tcp_snd_ws_ok = B_TRUE;
20983 
20984 	/*
20985 	 * Set tcp_snd_ts_ok to true
20986 	 * so that tcp_xmit_mp will
20987 	 * include the timestamp
20988 	 * option in the SYN segment.
20989 	 */
20990 	if (tcps->tcps_tstamp_always ||
20991 	    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
20992 		tcp->tcp_snd_ts_ok = B_TRUE;
20993 	}
20994 
20995 	/*
20996 	 * tcp_snd_sack_ok can be set in
20997 	 * tcp_set_destination() if the sack metric
20998 	 * is set.  So check it here also.
20999 	 */
21000 	if (tcps->tcps_sack_permitted == 2 ||
21001 	    tcp->tcp_snd_sack_ok) {
21002 		if (tcp->tcp_sack_info == NULL) {
21003 			tcp->tcp_sack_info = kmem_cache_alloc(
21004 			    tcp_sack_info_cache, KM_SLEEP);
21005 		}
21006 		tcp->tcp_snd_sack_ok = B_TRUE;
21007 	}
21008 
21009 	/*
21010 	 * Should we use ECN?  Note that the current
21011 	 * default value (SunOS 5.9) of tcp_ecn_permitted
21012 	 * is 1.  The reason for doing this is that there
21013 	 * are equipments out there that will drop ECN
21014 	 * enabled IP packets.  Setting it to 1 avoids
21015 	 * compatibility problems.
21016 	 */
21017 	if (tcps->tcps_ecn_permitted == 2)
21018 		tcp->tcp_ecn_ok = B_TRUE;
21019 
21020 	TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21021 	syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21022 	    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
21023 	if (syn_mp != NULL) {
21024 		/*
21025 		 * We must bump the generation before sending the syn
21026 		 * to ensure that we use the right generation in case
21027 		 * this thread issues a "connected" up call.
21028 		 */
21029 		SOCK_CONNID_BUMP(tcp->tcp_connid);
21030 		tcp_send_data(tcp, syn_mp);
21031 	}
21032 
21033 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
21034 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
21035 	return (0);
21036 
21037 connect_failed:
21038 	connp->conn_faddr_v6 = ipv6_all_zeros;
21039 	connp->conn_fport = 0;
21040 	tcp->tcp_state = oldstate;
21041 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
21042 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
21043 	return (error);
21044 }
21045 
21046 int
21047 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
21048     socklen_t len, sock_connid_t *id, cred_t *cr)
21049 {
21050 	conn_t		*connp = (conn_t *)proto_handle;
21051 	squeue_t	*sqp = connp->conn_sqp;
21052 	int		error;
21053 
21054 	ASSERT(connp->conn_upper_handle != NULL);
21055 
21056 	/* All Solaris components should pass a cred for this operation. */
21057 	ASSERT(cr != NULL);
21058 
21059 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
21060 	if (error != 0) {
21061 		return (error);
21062 	}
21063 
21064 	error = squeue_synch_enter(sqp, connp, NULL);
21065 	if (error != 0) {
21066 		/* failed to enter */
21067 		return (ENOSR);
21068 	}
21069 
21070 	/*
21071 	 * TCP supports quick connect, so no need to do an implicit bind
21072 	 */
21073 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
21074 	if (error == 0) {
21075 		*id = connp->conn_tcp->tcp_connid;
21076 	} else if (error < 0) {
21077 		if (error == -TOUTSTATE) {
21078 			switch (connp->conn_tcp->tcp_state) {
21079 			case TCPS_SYN_SENT:
21080 				error = EALREADY;
21081 				break;
21082 			case TCPS_ESTABLISHED:
21083 				error = EISCONN;
21084 				break;
21085 			case TCPS_LISTEN:
21086 				error = EOPNOTSUPP;
21087 				break;
21088 			default:
21089 				error = EINVAL;
21090 				break;
21091 			}
21092 		} else {
21093 			error = proto_tlitosyserr(-error);
21094 		}
21095 	}
21096 
21097 	if (connp->conn_tcp->tcp_loopback) {
21098 		struct sock_proto_props sopp;
21099 
21100 		sopp.sopp_flags = SOCKOPT_LOOPBACK;
21101 		sopp.sopp_loopback = B_TRUE;
21102 
21103 		(*connp->conn_upcalls->su_set_proto_props)(
21104 		    connp->conn_upper_handle, &sopp);
21105 	}
21106 done:
21107 	squeue_synch_exit(sqp, connp);
21108 
21109 	return ((error == 0) ? EINPROGRESS : error);
21110 }
21111 
21112 /* ARGSUSED */
21113 sock_lower_handle_t
21114 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
21115     uint_t *smodep, int *errorp, int flags, cred_t *credp)
21116 {
21117 	conn_t		*connp;
21118 	boolean_t	isv6 = family == AF_INET6;
21119 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
21120 	    (proto != 0 && proto != IPPROTO_TCP)) {
21121 		*errorp = EPROTONOSUPPORT;
21122 		return (NULL);
21123 	}
21124 
21125 	connp = tcp_create_common(credp, isv6, B_TRUE, errorp);
21126 	if (connp == NULL) {
21127 		return (NULL);
21128 	}
21129 
21130 	/*
21131 	 * Put the ref for TCP. Ref for IP was already put
21132 	 * by ipcl_conn_create. Also Make the conn_t globally
21133 	 * visible to walkers
21134 	 */
21135 	mutex_enter(&connp->conn_lock);
21136 	CONN_INC_REF_LOCKED(connp);
21137 	ASSERT(connp->conn_ref == 2);
21138 	connp->conn_state_flags &= ~CONN_INCIPIENT;
21139 
21140 	connp->conn_flags |= IPCL_NONSTR;
21141 	mutex_exit(&connp->conn_lock);
21142 
21143 	ASSERT(errorp != NULL);
21144 	*errorp = 0;
21145 	*sock_downcalls = &sock_tcp_downcalls;
21146 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
21147 	    SM_SENDFILESUPP;
21148 
21149 	return ((sock_lower_handle_t)connp);
21150 }
21151 
21152 /* ARGSUSED */
21153 void
21154 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
21155     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
21156 {
21157 	conn_t *connp = (conn_t *)proto_handle;
21158 	struct sock_proto_props sopp;
21159 
21160 	ASSERT(connp->conn_upper_handle == NULL);
21161 
21162 	/* All Solaris components should pass a cred for this operation. */
21163 	ASSERT(cr != NULL);
21164 
21165 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
21166 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
21167 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
21168 
21169 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
21170 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
21171 	sopp.sopp_maxpsz = INFPSZ;
21172 	sopp.sopp_maxblk = INFPSZ;
21173 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
21174 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
21175 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
21176 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
21177 	    tcp_rinfo.mi_minpsz;
21178 
21179 	connp->conn_upcalls = sock_upcalls;
21180 	connp->conn_upper_handle = sock_handle;
21181 
21182 	ASSERT(connp->conn_rcvbuf != 0 &&
21183 	    connp->conn_rcvbuf == connp->conn_tcp->tcp_rwnd);
21184 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
21185 }
21186 
21187 /* ARGSUSED */
21188 int
21189 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
21190 {
21191 	conn_t *connp = (conn_t *)proto_handle;
21192 
21193 	ASSERT(connp->conn_upper_handle != NULL);
21194 
21195 	/* All Solaris components should pass a cred for this operation. */
21196 	ASSERT(cr != NULL);
21197 
21198 	tcp_close_common(connp, flags);
21199 
21200 	ip_free_helper_stream(connp);
21201 
21202 	/*
21203 	 * Drop IP's reference on the conn. This is the last reference
21204 	 * on the connp if the state was less than established. If the
21205 	 * connection has gone into timewait state, then we will have
21206 	 * one ref for the TCP and one more ref (total of two) for the
21207 	 * classifier connected hash list (a timewait connections stays
21208 	 * in connected hash till closed).
21209 	 *
21210 	 * We can't assert the references because there might be other
21211 	 * transient reference places because of some walkers or queued
21212 	 * packets in squeue for the timewait state.
21213 	 */
21214 	CONN_DEC_REF(connp);
21215 	return (0);
21216 }
21217 
21218 /* ARGSUSED */
21219 int
21220 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
21221     cred_t *cr)
21222 {
21223 	tcp_t		*tcp;
21224 	uint32_t	msize;
21225 	conn_t *connp = (conn_t *)proto_handle;
21226 	int32_t		tcpstate;
21227 
21228 	/* All Solaris components should pass a cred for this operation. */
21229 	ASSERT(cr != NULL);
21230 
21231 	ASSERT(connp->conn_ref >= 2);
21232 	ASSERT(connp->conn_upper_handle != NULL);
21233 
21234 	if (msg->msg_controllen != 0) {
21235 		freemsg(mp);
21236 		return (EOPNOTSUPP);
21237 	}
21238 
21239 	switch (DB_TYPE(mp)) {
21240 	case M_DATA:
21241 		tcp = connp->conn_tcp;
21242 		ASSERT(tcp != NULL);
21243 
21244 		tcpstate = tcp->tcp_state;
21245 		if (tcpstate < TCPS_ESTABLISHED) {
21246 			freemsg(mp);
21247 			/*
21248 			 * We return ENOTCONN if the endpoint is trying to
21249 			 * connect or has never been connected, and EPIPE if it
21250 			 * has been disconnected. The connection id helps us
21251 			 * distinguish between the last two cases.
21252 			 */
21253 			return ((tcpstate == TCPS_SYN_SENT) ? ENOTCONN :
21254 			    ((tcp->tcp_connid > 0) ? EPIPE : ENOTCONN));
21255 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
21256 			freemsg(mp);
21257 			return (EPIPE);
21258 		}
21259 
21260 		msize = msgdsize(mp);
21261 
21262 		mutex_enter(&tcp->tcp_non_sq_lock);
21263 		tcp->tcp_squeue_bytes += msize;
21264 		/*
21265 		 * Squeue Flow Control
21266 		 */
21267 		if (TCP_UNSENT_BYTES(tcp) > connp->conn_sndbuf) {
21268 			tcp_setqfull(tcp);
21269 		}
21270 		mutex_exit(&tcp->tcp_non_sq_lock);
21271 
21272 		/*
21273 		 * The application may pass in an address in the msghdr, but
21274 		 * we ignore the address on connection-oriented sockets.
21275 		 * Just like BSD this code does not generate an error for
21276 		 * TCP (a CONNREQUIRED socket) when sending to an address
21277 		 * passed in with sendto/sendmsg. Instead the data is
21278 		 * delivered on the connection as if no address had been
21279 		 * supplied.
21280 		 */
21281 		CONN_INC_REF(connp);
21282 
21283 		if (msg->msg_flags & MSG_OOB) {
21284 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output_urgent,
21285 			    connp, NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
21286 		} else {
21287 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
21288 			    connp, NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
21289 		}
21290 
21291 		return (0);
21292 
21293 	default:
21294 		ASSERT(0);
21295 	}
21296 
21297 	freemsg(mp);
21298 	return (0);
21299 }
21300 
21301 /* ARGSUSED2 */
21302 void
21303 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
21304 {
21305 	int len;
21306 	uint32_t msize;
21307 	conn_t *connp = (conn_t *)arg;
21308 	tcp_t *tcp = connp->conn_tcp;
21309 
21310 	msize = msgdsize(mp);
21311 
21312 	len = msize - 1;
21313 	if (len < 0) {
21314 		freemsg(mp);
21315 		return;
21316 	}
21317 
21318 	/*
21319 	 * Try to force urgent data out on the wire. Even if we have unsent
21320 	 * data this will at least send the urgent flag.
21321 	 * XXX does not handle more flag correctly.
21322 	 */
21323 	len += tcp->tcp_unsent;
21324 	len += tcp->tcp_snxt;
21325 	tcp->tcp_urg = len;
21326 	tcp->tcp_valid_bits |= TCP_URG_VALID;
21327 
21328 	/* Bypass tcp protocol for fused tcp loopback */
21329 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
21330 		return;
21331 
21332 	/* Strip off the T_EXDATA_REQ if the data is from TPI */
21333 	if (DB_TYPE(mp) != M_DATA) {
21334 		mblk_t *mp1 = mp;
21335 		ASSERT(!IPCL_IS_NONSTR(connp));
21336 		mp = mp->b_cont;
21337 		freeb(mp1);
21338 	}
21339 	tcp_wput_data(tcp, mp, B_TRUE);
21340 }
21341 
21342 /* ARGSUSED3 */
21343 int
21344 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
21345     socklen_t *addrlenp, cred_t *cr)
21346 {
21347 	conn_t	*connp = (conn_t *)proto_handle;
21348 	tcp_t	*tcp = connp->conn_tcp;
21349 
21350 	ASSERT(connp->conn_upper_handle != NULL);
21351 	/* All Solaris components should pass a cred for this operation. */
21352 	ASSERT(cr != NULL);
21353 
21354 	ASSERT(tcp != NULL);
21355 	if (tcp->tcp_state < TCPS_SYN_RCVD)
21356 		return (ENOTCONN);
21357 
21358 	return (conn_getpeername(connp, addr, addrlenp));
21359 }
21360 
21361 /* ARGSUSED3 */
21362 int
21363 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
21364     socklen_t *addrlenp, cred_t *cr)
21365 {
21366 	conn_t	*connp = (conn_t *)proto_handle;
21367 
21368 	/* All Solaris components should pass a cred for this operation. */
21369 	ASSERT(cr != NULL);
21370 
21371 	ASSERT(connp->conn_upper_handle != NULL);
21372 	return (conn_getsockname(connp, addr, addrlenp));
21373 }
21374 
21375 /*
21376  * tcp_fallback
21377  *
21378  * A direct socket is falling back to using STREAMS. The queue
21379  * that is being passed down was created using tcp_open() with
21380  * the SO_FALLBACK flag set. As a result, the queue is not
21381  * associated with a conn, and the q_ptrs instead contain the
21382  * dev and minor area that should be used.
21383  *
21384  * The 'issocket' flag indicates whether the FireEngine
21385  * optimizations should be used. The common case would be that
21386  * optimizations are enabled, and they might be subsequently
21387  * disabled using the _SIOCSOCKFALLBACK ioctl.
21388  */
21389 
21390 /*
21391  * An active connection is falling back to TPI. Gather all the information
21392  * required by the STREAM head and TPI sonode and send it up.
21393  */
21394 void
21395 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
21396     boolean_t issocket, so_proto_quiesced_cb_t quiesced_cb)
21397 {
21398 	conn_t			*connp = tcp->tcp_connp;
21399 	struct stroptions	*stropt;
21400 	struct T_capability_ack tca;
21401 	struct sockaddr_in6	laddr, faddr;
21402 	socklen_t 		laddrlen, faddrlen;
21403 	short			opts;
21404 	int			error;
21405 	mblk_t			*mp;
21406 
21407 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
21408 	connp->conn_minor_arena = WR(q)->q_ptr;
21409 
21410 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
21411 
21412 	connp->conn_rq = RD(q);
21413 	connp->conn_wq = WR(q);
21414 
21415 	WR(q)->q_qinfo = &tcp_sock_winit;
21416 
21417 	if (!issocket)
21418 		tcp_use_pure_tpi(tcp);
21419 
21420 	/*
21421 	 * free the helper stream
21422 	 */
21423 	ip_free_helper_stream(connp);
21424 
21425 	/*
21426 	 * Notify the STREAM head about options
21427 	 */
21428 	DB_TYPE(stropt_mp) = M_SETOPTS;
21429 	stropt = (struct stroptions *)stropt_mp->b_rptr;
21430 	stropt_mp->b_wptr += sizeof (struct stroptions);
21431 	stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
21432 
21433 	stropt->so_wroff = connp->conn_ht_iphc_len + (tcp->tcp_loopback ? 0 :
21434 	    tcp->tcp_tcps->tcps_wroff_xtra);
21435 	if (tcp->tcp_snd_sack_ok)
21436 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
21437 	stropt->so_hiwat = connp->conn_rcvbuf;
21438 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
21439 
21440 	putnext(RD(q), stropt_mp);
21441 
21442 	/*
21443 	 * Collect the information needed to sync with the sonode
21444 	 */
21445 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
21446 
21447 	laddrlen = faddrlen = sizeof (sin6_t);
21448 	(void) tcp_getsockname((sock_lower_handle_t)connp,
21449 	    (struct sockaddr *)&laddr, &laddrlen, CRED());
21450 	error = tcp_getpeername((sock_lower_handle_t)connp,
21451 	    (struct sockaddr *)&faddr, &faddrlen, CRED());
21452 	if (error != 0)
21453 		faddrlen = 0;
21454 
21455 	opts = 0;
21456 	if (connp->conn_oobinline)
21457 		opts |= SO_OOBINLINE;
21458 	if (connp->conn_ixa->ixa_flags & IXAF_DONTROUTE)
21459 		opts |= SO_DONTROUTE;
21460 
21461 	/*
21462 	 * Notify the socket that the protocol is now quiescent,
21463 	 * and it's therefore safe move data from the socket
21464 	 * to the stream head.
21465 	 */
21466 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
21467 	    (struct sockaddr *)&laddr, laddrlen,
21468 	    (struct sockaddr *)&faddr, faddrlen, opts);
21469 
21470 	while ((mp = tcp->tcp_rcv_list) != NULL) {
21471 		tcp->tcp_rcv_list = mp->b_next;
21472 		mp->b_next = NULL;
21473 		/* We never do fallback for kernel RPC */
21474 		putnext(q, mp);
21475 	}
21476 	tcp->tcp_rcv_last_head = NULL;
21477 	tcp->tcp_rcv_last_tail = NULL;
21478 	tcp->tcp_rcv_cnt = 0;
21479 }
21480 
21481 /*
21482  * An eager is falling back to TPI. All we have to do is send
21483  * up a T_CONN_IND.
21484  */
21485 void
21486 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
21487 {
21488 	tcp_t *listener = eager->tcp_listener;
21489 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
21490 
21491 	ASSERT(listener != NULL);
21492 	ASSERT(mp != NULL);
21493 
21494 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
21495 
21496 	/*
21497 	 * TLI/XTI applications will get confused by
21498 	 * sending eager as an option since it violates
21499 	 * the option semantics. So remove the eager as
21500 	 * option since TLI/XTI app doesn't need it anyway.
21501 	 */
21502 	if (!direct_sockfs) {
21503 		struct T_conn_ind *conn_ind;
21504 
21505 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
21506 		conn_ind->OPT_length = 0;
21507 		conn_ind->OPT_offset = 0;
21508 	}
21509 
21510 	/*
21511 	 * Sockfs guarantees that the listener will not be closed
21512 	 * during fallback. So we can safely use the listener's queue.
21513 	 */
21514 	putnext(listener->tcp_connp->conn_rq, mp);
21515 }
21516 
21517 int
21518 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
21519     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
21520 {
21521 	tcp_t			*tcp;
21522 	conn_t 			*connp = (conn_t *)proto_handle;
21523 	int			error;
21524 	mblk_t			*stropt_mp;
21525 	mblk_t			*ordrel_mp;
21526 
21527 	tcp = connp->conn_tcp;
21528 
21529 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
21530 	    NULL);
21531 
21532 	/* Pre-allocate the T_ordrel_ind mblk. */
21533 	ASSERT(tcp->tcp_ordrel_mp == NULL);
21534 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
21535 	    STR_NOSIG, NULL);
21536 	ordrel_mp->b_datap->db_type = M_PROTO;
21537 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
21538 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
21539 
21540 	/*
21541 	 * Enter the squeue so that no new packets can come in
21542 	 */
21543 	error = squeue_synch_enter(connp->conn_sqp, connp, NULL);
21544 	if (error != 0) {
21545 		/* failed to enter, free all the pre-allocated messages. */
21546 		freeb(stropt_mp);
21547 		freeb(ordrel_mp);
21548 		/*
21549 		 * We cannot process the eager, so at least send out a
21550 		 * RST so the peer can reconnect.
21551 		 */
21552 		if (tcp->tcp_listener != NULL) {
21553 			(void) tcp_eager_blowoff(tcp->tcp_listener,
21554 			    tcp->tcp_conn_req_seqnum);
21555 		}
21556 		return (ENOMEM);
21557 	}
21558 
21559 	/*
21560 	 * Both endpoints must be of the same type (either STREAMS or
21561 	 * non-STREAMS) for fusion to be enabled. So if we are fused,
21562 	 * we have to unfuse.
21563 	 */
21564 	if (tcp->tcp_fused)
21565 		tcp_unfuse(tcp);
21566 
21567 	/*
21568 	 * No longer a direct socket
21569 	 */
21570 	connp->conn_flags &= ~IPCL_NONSTR;
21571 	tcp->tcp_ordrel_mp = ordrel_mp;
21572 
21573 	if (tcp->tcp_listener != NULL) {
21574 		/* The eager will deal with opts when accept() is called */
21575 		freeb(stropt_mp);
21576 		tcp_fallback_eager(tcp, direct_sockfs);
21577 	} else {
21578 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
21579 		    quiesced_cb);
21580 	}
21581 
21582 	/*
21583 	 * There should be atleast two ref's (IP + TCP)
21584 	 */
21585 	ASSERT(connp->conn_ref >= 2);
21586 	squeue_synch_exit(connp->conn_sqp, connp);
21587 
21588 	return (0);
21589 }
21590 
21591 /* ARGSUSED */
21592 static void
21593 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
21594 {
21595 	conn_t 	*connp = (conn_t *)arg;
21596 	tcp_t	*tcp = connp->conn_tcp;
21597 
21598 	freemsg(mp);
21599 
21600 	if (tcp->tcp_fused)
21601 		tcp_unfuse(tcp);
21602 
21603 	if (tcp_xmit_end(tcp) != 0) {
21604 		/*
21605 		 * We were crossing FINs and got a reset from
21606 		 * the other side. Just ignore it.
21607 		 */
21608 		if (connp->conn_debug) {
21609 			(void) strlog(TCP_MOD_ID, 0, 1,
21610 			    SL_ERROR|SL_TRACE,
21611 			    "tcp_shutdown_output() out of state %s",
21612 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
21613 		}
21614 	}
21615 }
21616 
21617 /* ARGSUSED */
21618 int
21619 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
21620 {
21621 	conn_t  *connp = (conn_t *)proto_handle;
21622 	tcp_t   *tcp = connp->conn_tcp;
21623 
21624 	ASSERT(connp->conn_upper_handle != NULL);
21625 
21626 	/* All Solaris components should pass a cred for this operation. */
21627 	ASSERT(cr != NULL);
21628 
21629 	/*
21630 	 * X/Open requires that we check the connected state.
21631 	 */
21632 	if (tcp->tcp_state < TCPS_SYN_SENT)
21633 		return (ENOTCONN);
21634 
21635 	/* shutdown the send side */
21636 	if (how != SHUT_RD) {
21637 		mblk_t *bp;
21638 
21639 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
21640 		CONN_INC_REF(connp);
21641 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
21642 		    connp, NULL, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
21643 
21644 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21645 		    SOCK_OPCTL_SHUT_SEND, 0);
21646 	}
21647 
21648 	/* shutdown the recv side */
21649 	if (how != SHUT_WR)
21650 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21651 		    SOCK_OPCTL_SHUT_RECV, 0);
21652 
21653 	return (0);
21654 }
21655 
21656 /*
21657  * SOP_LISTEN() calls into tcp_listen().
21658  */
21659 /* ARGSUSED */
21660 int
21661 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
21662 {
21663 	conn_t	*connp = (conn_t *)proto_handle;
21664 	int 	error;
21665 	squeue_t *sqp = connp->conn_sqp;
21666 
21667 	ASSERT(connp->conn_upper_handle != NULL);
21668 
21669 	/* All Solaris components should pass a cred for this operation. */
21670 	ASSERT(cr != NULL);
21671 
21672 	error = squeue_synch_enter(sqp, connp, NULL);
21673 	if (error != 0) {
21674 		/* failed to enter */
21675 		return (ENOBUFS);
21676 	}
21677 
21678 	error = tcp_do_listen(connp, NULL, 0, backlog, cr, FALSE);
21679 	if (error == 0) {
21680 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21681 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
21682 	} else if (error < 0) {
21683 		if (error == -TOUTSTATE)
21684 			error = EINVAL;
21685 		else
21686 			error = proto_tlitosyserr(-error);
21687 	}
21688 	squeue_synch_exit(sqp, connp);
21689 	return (error);
21690 }
21691 
21692 static int
21693 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
21694     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
21695 {
21696 	tcp_t		*tcp = connp->conn_tcp;
21697 	int		error = 0;
21698 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21699 
21700 	/* All Solaris components should pass a cred for this operation. */
21701 	ASSERT(cr != NULL);
21702 
21703 	if (tcp->tcp_state >= TCPS_BOUND) {
21704 		if ((tcp->tcp_state == TCPS_BOUND ||
21705 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
21706 			/*
21707 			 * Handle listen() increasing backlog.
21708 			 * This is more "liberal" then what the TPI spec
21709 			 * requires but is needed to avoid a t_unbind
21710 			 * when handling listen() since the port number
21711 			 * might be "stolen" between the unbind and bind.
21712 			 */
21713 			goto do_listen;
21714 		}
21715 		if (connp->conn_debug) {
21716 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21717 			    "tcp_listen: bad state, %d", tcp->tcp_state);
21718 		}
21719 		return (-TOUTSTATE);
21720 	} else {
21721 		if (sa == NULL) {
21722 			sin6_t	addr;
21723 			sin_t *sin;
21724 			sin6_t *sin6;
21725 
21726 			ASSERT(IPCL_IS_NONSTR(connp));
21727 			/* Do an implicit bind: Request for a generic port. */
21728 			if (connp->conn_family == AF_INET) {
21729 				len = sizeof (sin_t);
21730 				sin = (sin_t *)&addr;
21731 				*sin = sin_null;
21732 				sin->sin_family = AF_INET;
21733 			} else {
21734 				ASSERT(connp->conn_family == AF_INET6);
21735 				len = sizeof (sin6_t);
21736 				sin6 = (sin6_t *)&addr;
21737 				*sin6 = sin6_null;
21738 				sin6->sin6_family = AF_INET6;
21739 			}
21740 			sa = (struct sockaddr *)&addr;
21741 		}
21742 
21743 		error = tcp_bind_check(connp, sa, len, cr,
21744 		    bind_to_req_port_only);
21745 		if (error)
21746 			return (error);
21747 		/* Fall through and do the fanout insertion */
21748 	}
21749 
21750 do_listen:
21751 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
21752 	tcp->tcp_conn_req_max = backlog;
21753 	if (tcp->tcp_conn_req_max) {
21754 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
21755 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
21756 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
21757 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
21758 		/*
21759 		 * If this is a listener, do not reset the eager list
21760 		 * and other stuffs.  Note that we don't check if the
21761 		 * existing eager list meets the new tcp_conn_req_max
21762 		 * requirement.
21763 		 */
21764 		if (tcp->tcp_state != TCPS_LISTEN) {
21765 			tcp->tcp_state = TCPS_LISTEN;
21766 			/* Initialize the chain. Don't need the eager_lock */
21767 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
21768 			tcp->tcp_eager_next_drop_q0 = tcp;
21769 			tcp->tcp_eager_prev_drop_q0 = tcp;
21770 			tcp->tcp_second_ctimer_threshold =
21771 			    tcps->tcps_ip_abort_linterval;
21772 		}
21773 	}
21774 
21775 	/*
21776 	 * We need to make sure that the conn_recv is set to a non-null
21777 	 * value before we insert the conn into the classifier table.
21778 	 * This is to avoid a race with an incoming packet which does an
21779 	 * ipcl_classify().
21780 	 * We initially set it to tcp_input_listener_unbound to try to
21781 	 * pick a good squeue for the listener when the first SYN arrives.
21782 	 * tcp_input_listener_unbound sets it to tcp_input_listener on that
21783 	 * first SYN.
21784 	 */
21785 	connp->conn_recv = tcp_input_listener_unbound;
21786 
21787 	/* Insert the listener in the classifier table */
21788 	error = ip_laddr_fanout_insert(connp);
21789 	if (error != 0) {
21790 		/* Undo the bind - release the port number */
21791 		tcp->tcp_state = TCPS_IDLE;
21792 		connp->conn_bound_addr_v6 = ipv6_all_zeros;
21793 
21794 		connp->conn_laddr_v6 = ipv6_all_zeros;
21795 		connp->conn_saddr_v6 = ipv6_all_zeros;
21796 		connp->conn_ports = 0;
21797 
21798 		if (connp->conn_anon_port) {
21799 			zone_t		*zone;
21800 
21801 			zone = crgetzone(cr);
21802 			connp->conn_anon_port = B_FALSE;
21803 			(void) tsol_mlp_anon(zone, connp->conn_mlp_type,
21804 			    connp->conn_proto, connp->conn_lport, B_FALSE);
21805 		}
21806 		connp->conn_mlp_type = mlptSingle;
21807 
21808 		tcp_bind_hash_remove(tcp);
21809 		return (error);
21810 	} else {
21811 		/*
21812 		 * If there is a connection limit, allocate and initialize
21813 		 * the counter struct.  Note that since listen can be called
21814 		 * multiple times, the struct may have been allready allocated.
21815 		 */
21816 		if (!list_is_empty(&tcps->tcps_listener_conf) &&
21817 		    tcp->tcp_listen_cnt == NULL) {
21818 			tcp_listen_cnt_t *tlc;
21819 			uint32_t ratio;
21820 
21821 			ratio = tcp_find_listener_conf(tcps,
21822 			    ntohs(connp->conn_lport));
21823 			if (ratio != 0) {
21824 				uint32_t mem_ratio, tot_buf;
21825 
21826 				tlc = kmem_alloc(sizeof (tcp_listen_cnt_t),
21827 				    KM_SLEEP);
21828 				/*
21829 				 * Calculate the connection limit based on
21830 				 * the configured ratio and maxusers.  Maxusers
21831 				 * are calculated based on memory size,
21832 				 * ~ 1 user per MB.  Note that the conn_rcvbuf
21833 				 * and conn_sndbuf may change after a
21834 				 * connection is accepted.  So what we have
21835 				 * is only an approximation.
21836 				 */
21837 				if ((tot_buf = connp->conn_rcvbuf +
21838 				    connp->conn_sndbuf) < MB) {
21839 					mem_ratio = MB / tot_buf;
21840 					tlc->tlc_max = maxusers / ratio *
21841 					    mem_ratio;
21842 				} else {
21843 					mem_ratio = tot_buf / MB;
21844 					tlc->tlc_max = maxusers / ratio /
21845 					    mem_ratio;
21846 				}
21847 				/* At least we should allow two connections! */
21848 				if (tlc->tlc_max <= tcp_min_conn_listener)
21849 					tlc->tlc_max = tcp_min_conn_listener;
21850 				tlc->tlc_cnt = 1;
21851 				tlc->tlc_drop = 0;
21852 				tcp->tcp_listen_cnt = tlc;
21853 			}
21854 		}
21855 	}
21856 	return (error);
21857 }
21858 
21859 void
21860 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
21861 {
21862 	conn_t  *connp = (conn_t *)proto_handle;
21863 	tcp_t	*tcp = connp->conn_tcp;
21864 	mblk_t *mp;
21865 	int error;
21866 
21867 	ASSERT(connp->conn_upper_handle != NULL);
21868 
21869 	/*
21870 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_clr_flowctrl()
21871 	 * is currently running.
21872 	 */
21873 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
21874 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
21875 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
21876 		return;
21877 	}
21878 	tcp->tcp_rsrv_mp = NULL;
21879 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
21880 
21881 	error = squeue_synch_enter(connp->conn_sqp, connp, mp);
21882 	ASSERT(error == 0);
21883 
21884 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
21885 	tcp->tcp_rsrv_mp = mp;
21886 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
21887 
21888 	if (tcp->tcp_fused) {
21889 		tcp_fuse_backenable(tcp);
21890 	} else {
21891 		tcp->tcp_rwnd = connp->conn_rcvbuf;
21892 		/*
21893 		 * Send back a window update immediately if TCP is above
21894 		 * ESTABLISHED state and the increase of the rcv window
21895 		 * that the other side knows is at least 1 MSS after flow
21896 		 * control is lifted.
21897 		 */
21898 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
21899 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
21900 			tcp_xmit_ctl(NULL, tcp,
21901 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
21902 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
21903 		}
21904 	}
21905 
21906 	squeue_synch_exit(connp->conn_sqp, connp);
21907 }
21908 
21909 /* ARGSUSED */
21910 int
21911 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
21912     int mode, int32_t *rvalp, cred_t *cr)
21913 {
21914 	conn_t  	*connp = (conn_t *)proto_handle;
21915 	int		error;
21916 
21917 	ASSERT(connp->conn_upper_handle != NULL);
21918 
21919 	/* All Solaris components should pass a cred for this operation. */
21920 	ASSERT(cr != NULL);
21921 
21922 	/*
21923 	 * If we don't have a helper stream then create one.
21924 	 * ip_create_helper_stream takes care of locking the conn_t,
21925 	 * so this check for NULL is just a performance optimization.
21926 	 */
21927 	if (connp->conn_helper_info == NULL) {
21928 		tcp_stack_t *tcps = connp->conn_tcp->tcp_tcps;
21929 
21930 		/*
21931 		 * Create a helper stream for non-STREAMS socket.
21932 		 */
21933 		error = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
21934 		if (error != 0) {
21935 			ip0dbg(("tcp_ioctl: create of IP helper stream "
21936 			    "failed %d\n", error));
21937 			return (error);
21938 		}
21939 	}
21940 
21941 	switch (cmd) {
21942 		case ND_SET:
21943 		case ND_GET:
21944 		case _SIOCSOCKFALLBACK:
21945 		case TCP_IOC_ABORT_CONN:
21946 		case TI_GETPEERNAME:
21947 		case TI_GETMYNAME:
21948 			ip1dbg(("tcp_ioctl: cmd 0x%x on non streams socket",
21949 			    cmd));
21950 			error = EINVAL;
21951 			break;
21952 		default:
21953 			/*
21954 			 * If the conn is not closing, pass on to IP using
21955 			 * helper stream. Bump the ioctlref to prevent tcp_close
21956 			 * from closing the rq/wq out from underneath the ioctl
21957 			 * if it ends up queued or aborted/interrupted.
21958 			 */
21959 			mutex_enter(&connp->conn_lock);
21960 			if (connp->conn_state_flags & (CONN_CLOSING)) {
21961 				mutex_exit(&connp->conn_lock);
21962 				error = EINVAL;
21963 				break;
21964 			}
21965 			CONN_INC_IOCTLREF_LOCKED(connp);
21966 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
21967 			    cmd, arg, mode, cr, rvalp);
21968 			CONN_DEC_IOCTLREF(connp);
21969 			break;
21970 	}
21971 	return (error);
21972 }
21973 
21974 sock_downcalls_t sock_tcp_downcalls = {
21975 	tcp_activate,
21976 	tcp_accept,
21977 	tcp_bind,
21978 	tcp_listen,
21979 	tcp_connect,
21980 	tcp_getpeername,
21981 	tcp_getsockname,
21982 	tcp_getsockopt,
21983 	tcp_setsockopt,
21984 	tcp_sendmsg,
21985 	NULL,
21986 	NULL,
21987 	NULL,
21988 	tcp_shutdown,
21989 	tcp_clr_flowctrl,
21990 	tcp_ioctl,
21991 	tcp_close,
21992 };
21993 
21994 /*
21995  * Timeout function to reset the TCP stack variable tcps_reclaim to false.
21996  */
21997 static void
21998 tcp_reclaim_timer(void *arg)
21999 {
22000 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
22001 
22002 	mutex_enter(&tcps->tcps_reclaim_lock);
22003 	tcps->tcps_reclaim = B_FALSE;
22004 	tcps->tcps_reclaim_tid = 0;
22005 	mutex_exit(&tcps->tcps_reclaim_lock);
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 	extern pgcnt_t lotsfree, needfree;
22025 
22026 	if (!tcp_do_reclaim)
22027 		return;
22028 
22029 	/*
22030 	 * The reclaim function may be called even when the system is not
22031 	 * really under memory pressure.
22032 	 */
22033 	if (freemem >= lotsfree + needfree)
22034 		return;
22035 
22036 	netstack_next_init(&nh);
22037 	while ((ns = netstack_next(&nh)) != NULL) {
22038 		tcps = ns->netstack_tcp;
22039 		mutex_enter(&tcps->tcps_reclaim_lock);
22040 		if (!tcps->tcps_reclaim) {
22041 			tcps->tcps_reclaim = B_TRUE;
22042 			tcps->tcps_reclaim_tid = timeout(tcp_reclaim_timer,
22043 			    tcps, MSEC_TO_TICK(tcps->tcps_reclaim_period));
22044 		}
22045 		mutex_exit(&tcps->tcps_reclaim_lock);
22046 		netstack_rele(ns);
22047 	}
22048 	netstack_next_fini(&nh);
22049 }
22050 
22051 /*
22052  * Given a tcp_stack_t and a port (in host byte order), find a listener
22053  * configuration for that port and return the ratio.
22054  */
22055 static uint32_t
22056 tcp_find_listener_conf(tcp_stack_t *tcps, in_port_t port)
22057 {
22058 	tcp_listener_t	*tl;
22059 	uint32_t ratio = 0;
22060 
22061 	mutex_enter(&tcps->tcps_listener_conf_lock);
22062 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22063 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22064 		if (tl->tl_port == port) {
22065 			ratio = tl->tl_ratio;
22066 			break;
22067 		}
22068 	}
22069 	mutex_exit(&tcps->tcps_listener_conf_lock);
22070 	return (ratio);
22071 }
22072 
22073 /*
22074  * Ndd param helper routine to return the current list of listener limit
22075  * configuration.
22076  */
22077 /* ARGSUSED */
22078 static int
22079 tcp_listener_conf_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22080 {
22081 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22082 	tcp_listener_t	*tl;
22083 
22084 	mutex_enter(&tcps->tcps_listener_conf_lock);
22085 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22086 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22087 		(void) mi_mpprintf(mp, "%d:%d ", tl->tl_port, tl->tl_ratio);
22088 	}
22089 	mutex_exit(&tcps->tcps_listener_conf_lock);
22090 	return (0);
22091 }
22092 
22093 /*
22094  * Ndd param helper routine to add a new listener limit configuration.
22095  */
22096 /* ARGSUSED */
22097 static int
22098 tcp_listener_conf_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22099     cred_t *cr)
22100 {
22101 	tcp_listener_t	*new_tl;
22102 	tcp_listener_t	*tl;
22103 	long		lport;
22104 	long		ratio;
22105 	char		*colon;
22106 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22107 
22108 	if (ddi_strtol(value, &colon, 10, &lport) != 0 || lport <= 0 ||
22109 	    lport > USHRT_MAX || *colon != ':') {
22110 		return (EINVAL);
22111 	}
22112 	if (ddi_strtol(colon + 1, NULL, 10, &ratio) != 0 || ratio <= 0)
22113 		return (EINVAL);
22114 
22115 	mutex_enter(&tcps->tcps_listener_conf_lock);
22116 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22117 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22118 		/* There is an existing entry, so update its ratio value. */
22119 		if (tl->tl_port == lport) {
22120 			tl->tl_ratio = ratio;
22121 			mutex_exit(&tcps->tcps_listener_conf_lock);
22122 			return (0);
22123 		}
22124 	}
22125 
22126 	if ((new_tl = kmem_alloc(sizeof (tcp_listener_t), KM_NOSLEEP)) ==
22127 	    NULL) {
22128 		mutex_exit(&tcps->tcps_listener_conf_lock);
22129 		return (ENOMEM);
22130 	}
22131 
22132 	new_tl->tl_port = lport;
22133 	new_tl->tl_ratio = ratio;
22134 	list_insert_tail(&tcps->tcps_listener_conf, new_tl);
22135 	mutex_exit(&tcps->tcps_listener_conf_lock);
22136 	return (0);
22137 }
22138 
22139 /*
22140  * Ndd param helper routine to remove a listener limit configuration.
22141  */
22142 /* ARGSUSED */
22143 static int
22144 tcp_listener_conf_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22145     cred_t *cr)
22146 {
22147 	tcp_listener_t	*tl;
22148 	long		lport;
22149 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22150 
22151 	if (ddi_strtol(value, NULL, 10, &lport) != 0 || lport <= 0 ||
22152 	    lport > USHRT_MAX) {
22153 		return (EINVAL);
22154 	}
22155 	mutex_enter(&tcps->tcps_listener_conf_lock);
22156 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22157 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22158 		if (tl->tl_port == lport) {
22159 			list_remove(&tcps->tcps_listener_conf, tl);
22160 			mutex_exit(&tcps->tcps_listener_conf_lock);
22161 			kmem_free(tl, sizeof (tcp_listener_t));
22162 			return (0);
22163 		}
22164 	}
22165 	mutex_exit(&tcps->tcps_listener_conf_lock);
22166 	return (ESRCH);
22167 }
22168 
22169 /*
22170  * To remove all listener limit configuration in a tcp_stack_t.
22171  */
22172 static void
22173 tcp_listener_conf_cleanup(tcp_stack_t *tcps)
22174 {
22175 	tcp_listener_t	*tl;
22176 
22177 	mutex_enter(&tcps->tcps_listener_conf_lock);
22178 	while ((tl = list_head(&tcps->tcps_listener_conf)) != NULL) {
22179 		list_remove(&tcps->tcps_listener_conf, tl);
22180 		kmem_free(tl, sizeof (tcp_listener_t));
22181 	}
22182 	mutex_destroy(&tcps->tcps_listener_conf_lock);
22183 	list_destroy(&tcps->tcps_listener_conf);
22184 }
22185